rules_sampler.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. // Unless explicitly stated otherwise all files in this repository are licensed
  2. // under the Apache License Version 2.0.
  3. // This product includes software developed at Datadog (https://www.datadoghq.com/).
  4. // Copyright 2016 Datadog, Inc.
  5. package tracer
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "math"
  10. "os"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "golang.org/x/time/rate"
  17. "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
  18. "gopkg.in/DataDog/dd-trace-go.v1/internal/log"
  19. "gopkg.in/DataDog/dd-trace-go.v1/internal/samplernames"
  20. )
  21. // rulesSampler holds instances of trace sampler and single span sampler, that are configured with the given set of rules.
  22. type rulesSampler struct {
  23. // traceRulesSampler samples trace spans based on a user-defined set of rules and might impact sampling decision of the trace.
  24. traces *traceRulesSampler
  25. // singleSpanRulesSampler samples individual spans based on a separate user-defined set of rules and
  26. // cannot impact the trace sampling decision.
  27. spans *singleSpanRulesSampler
  28. }
  29. // newRulesSampler configures a *rulesSampler instance using the given set of rules.
  30. // Rules are split between trace and single span sampling rules according to their type.
  31. // Such rules are user-defined through environment variable or WithSamplingRules option.
  32. // Invalid rules or environment variable values are tolerated, by logging warnings and then ignoring them.
  33. func newRulesSampler(traceRules, spanRules []SamplingRule) *rulesSampler {
  34. return &rulesSampler{
  35. traces: newTraceRulesSampler(traceRules),
  36. spans: newSingleSpanRulesSampler(spanRules),
  37. }
  38. }
  39. func (r *rulesSampler) SampleTrace(s *span) bool { return r.traces.apply(s) }
  40. func (r *rulesSampler) SampleSpan(s *span) bool { return r.spans.apply(s) }
  41. func (r *rulesSampler) HasSpanRules() bool { return r.spans.enabled() }
  42. func (r *rulesSampler) TraceRateLimit() (float64, bool) { return r.traces.limit() }
  43. // SamplingRule is used for applying sampling rates to spans that match
  44. // the service name, operation name or both.
  45. // For basic usage, consider using the helper functions ServiceRule, NameRule, etc.
  46. type SamplingRule struct {
  47. // Service specifies the regex pattern that a span service name must match.
  48. Service *regexp.Regexp
  49. // Name specifies the regex pattern that a span operation name must match.
  50. Name *regexp.Regexp
  51. // Rate specifies the sampling rate that should be applied to spans that match
  52. // service and/or name of the rule.
  53. Rate float64
  54. // MaxPerSecond specifies max number of spans per second that can be sampled per the rule.
  55. // If not specified, the default is no limit.
  56. MaxPerSecond float64
  57. ruleType SamplingRuleType
  58. exactService string
  59. exactName string
  60. limiter *rateLimiter
  61. }
  62. // match returns true when the span's details match all the expected values in the rule.
  63. func (sr *SamplingRule) match(s *span) bool {
  64. if sr.Service != nil && !sr.Service.MatchString(s.Service) {
  65. return false
  66. } else if sr.exactService != "" && sr.exactService != s.Service {
  67. return false
  68. }
  69. if sr.Name != nil && !sr.Name.MatchString(s.Name) {
  70. return false
  71. } else if sr.exactName != "" && sr.exactName != s.Name {
  72. return false
  73. }
  74. return true
  75. }
  76. // SamplingRuleType represents a type of sampling rule spans are matched against.
  77. type SamplingRuleType int
  78. const (
  79. // SamplingRuleTrace specifies a sampling rule that applies to the entire trace if any spans satisfy the criteria.
  80. // If a sampling rule is of type SamplingRuleTrace, such rule determines the sampling rate to apply
  81. // to trace spans. If a span matches that rule, it will impact the trace sampling decision.
  82. SamplingRuleTrace = iota
  83. // SamplingRuleSpan specifies a sampling rule that applies to a single span without affecting the entire trace.
  84. // If a sampling rule is of type SamplingRuleSingleSpan, such rule determines the sampling rate to apply
  85. // to individual spans. If a span matches a rule, it will NOT impact the trace sampling decision.
  86. // In the case that a trace is dropped and thus not sent to the Agent, spans kept on account
  87. // of matching SamplingRuleSingleSpan rules must be conveyed separately.
  88. SamplingRuleSpan
  89. )
  90. func (sr SamplingRuleType) String() string {
  91. switch sr {
  92. case SamplingRuleTrace:
  93. return "trace"
  94. case SamplingRuleSpan:
  95. return "span"
  96. default:
  97. return ""
  98. }
  99. }
  100. // ServiceRule returns a SamplingRule that applies the provided sampling rate
  101. // to spans that match the service name provided.
  102. func ServiceRule(service string, rate float64) SamplingRule {
  103. return SamplingRule{
  104. exactService: service,
  105. Rate: rate,
  106. }
  107. }
  108. // NameRule returns a SamplingRule that applies the provided sampling rate
  109. // to spans that match the operation name provided.
  110. func NameRule(name string, rate float64) SamplingRule {
  111. return SamplingRule{
  112. exactName: name,
  113. Rate: rate,
  114. }
  115. }
  116. // NameServiceRule returns a SamplingRule that applies the provided sampling rate
  117. // to spans matching both the operation and service names provided.
  118. func NameServiceRule(name string, service string, rate float64) SamplingRule {
  119. return SamplingRule{
  120. exactService: service,
  121. exactName: name,
  122. Rate: rate,
  123. }
  124. }
  125. // RateRule returns a SamplingRule that applies the provided sampling rate to all spans.
  126. func RateRule(rate float64) SamplingRule {
  127. return SamplingRule{
  128. Rate: rate,
  129. }
  130. }
  131. // SpanNameServiceRule returns a SamplingRule of type SamplingRuleSpan that applies
  132. // the provided sampling rate to all spans matching the operation and service name glob patterns provided.
  133. // Operation and service fields must be valid glob patterns.
  134. func SpanNameServiceRule(name, service string, rate float64) SamplingRule {
  135. return SamplingRule{
  136. Service: globMatch(service),
  137. Name: globMatch(name),
  138. Rate: rate,
  139. ruleType: SamplingRuleSpan,
  140. exactName: name,
  141. limiter: newSingleSpanRateLimiter(0),
  142. }
  143. }
  144. // SpanNameServiceMPSRule returns a SamplingRule of type SamplingRuleSpan that applies
  145. // the provided sampling rate to all spans matching the operation and service name glob patterns
  146. // up to the max number of spans per second that can be sampled.
  147. // Operation and service fields must be valid glob patterns.
  148. func SpanNameServiceMPSRule(name, service string, rate, limit float64) SamplingRule {
  149. return SamplingRule{
  150. Service: globMatch(service),
  151. Name: globMatch(name),
  152. MaxPerSecond: limit,
  153. Rate: rate,
  154. ruleType: SamplingRuleSpan,
  155. exactName: name,
  156. limiter: newSingleSpanRateLimiter(limit),
  157. }
  158. }
  159. // traceRulesSampler allows a user-defined list of rules to apply to traces.
  160. // These rules can match based on the span's Service, Name or both.
  161. // When making a sampling decision, the rules are checked in order until
  162. // a match is found.
  163. // If a match is found, the rate from that rule is used.
  164. // If no match is found, and the DD_TRACE_SAMPLE_RATE environment variable
  165. // was set to a valid rate, that value is used.
  166. // Otherwise, the rules sampler didn't apply to the span, and the decision
  167. // is passed to the priority sampler.
  168. //
  169. // The rate is used to determine if the span should be sampled, but an upper
  170. // limit can be defined using the DD_TRACE_RATE_LIMIT environment variable.
  171. // Its value is the number of spans to sample per second.
  172. // Spans that matched the rules but exceeded the rate limit are not sampled.
  173. type traceRulesSampler struct {
  174. rules []SamplingRule // the rules to match spans with
  175. globalRate float64 // a rate to apply when no rules match a span
  176. limiter *rateLimiter // used to limit the volume of spans sampled
  177. }
  178. // newTraceRulesSampler configures a *traceRulesSampler instance using the given set of rules.
  179. // Invalid rules or environment variable values are tolerated, by logging warnings and then ignoring them.
  180. func newTraceRulesSampler(rules []SamplingRule) *traceRulesSampler {
  181. return &traceRulesSampler{
  182. rules: rules,
  183. globalRate: globalSampleRate(),
  184. limiter: newRateLimiter(),
  185. }
  186. }
  187. // globalSampleRate returns the sampling rate found in the DD_TRACE_SAMPLE_RATE environment variable.
  188. // If it is invalid or not within the 0-1 range, NaN is returned.
  189. func globalSampleRate() float64 {
  190. defaultRate := math.NaN()
  191. v := os.Getenv("DD_TRACE_SAMPLE_RATE")
  192. if v == "" {
  193. return defaultRate
  194. }
  195. r, err := strconv.ParseFloat(v, 64)
  196. if err != nil {
  197. log.Warn("ignoring DD_TRACE_SAMPLE_RATE: error: %v", err)
  198. return defaultRate
  199. }
  200. if r >= 0.0 && r <= 1.0 {
  201. return r
  202. }
  203. log.Warn("ignoring DD_TRACE_SAMPLE_RATE: out of range %f", r)
  204. return defaultRate
  205. }
  206. func (rs *traceRulesSampler) enabled() bool {
  207. return len(rs.rules) > 0 || !math.IsNaN(rs.globalRate)
  208. }
  209. // apply uses the sampling rules to determine the sampling rate for the
  210. // provided span. If the rules don't match, and a default rate hasn't been
  211. // set using DD_TRACE_SAMPLE_RATE, then it returns false and the span is not
  212. // modified.
  213. func (rs *traceRulesSampler) apply(span *span) bool {
  214. if !rs.enabled() {
  215. // short path when disabled
  216. return false
  217. }
  218. var matched bool
  219. rate := rs.globalRate
  220. for _, rule := range rs.rules {
  221. if rule.match(span) {
  222. matched = true
  223. rate = rule.Rate
  224. break
  225. }
  226. }
  227. if !matched && math.IsNaN(rate) {
  228. // no matching rule or global rate, so we want to fall back
  229. // to priority sampling
  230. return false
  231. }
  232. rs.applyRule(span, rate, time.Now())
  233. return true
  234. }
  235. func (rs *traceRulesSampler) applyRule(span *span, rate float64, now time.Time) {
  236. span.SetTag(keyRulesSamplerAppliedRate, rate)
  237. if !sampledByRate(span.TraceID, rate) {
  238. span.setSamplingPriority(ext.PriorityUserReject, samplernames.RuleRate)
  239. return
  240. }
  241. sampled, rate := rs.limiter.allowOne(now)
  242. if sampled {
  243. span.setSamplingPriority(ext.PriorityUserKeep, samplernames.RuleRate)
  244. } else {
  245. span.setSamplingPriority(ext.PriorityUserReject, samplernames.RuleRate)
  246. }
  247. span.SetTag(keyRulesSamplerLimiterRate, rate)
  248. }
  249. // limit returns the rate limit set in the rules sampler, controlled by DD_TRACE_RATE_LIMIT, and
  250. // true if rules sampling is enabled. If not present it returns math.NaN() and false.
  251. func (rs *traceRulesSampler) limit() (float64, bool) {
  252. if rs.enabled() {
  253. return float64(rs.limiter.limiter.Limit()), true
  254. }
  255. return math.NaN(), false
  256. }
  257. // defaultRateLimit specifies the default trace rate limit used when DD_TRACE_RATE_LIMIT is not set.
  258. const defaultRateLimit = 100.0
  259. // newRateLimiter returns a rate limiter which restricts the number of traces sampled per second.
  260. // The limit is DD_TRACE_RATE_LIMIT if set, `defaultRateLimit` otherwise.
  261. func newRateLimiter() *rateLimiter {
  262. limit := defaultRateLimit
  263. v := os.Getenv("DD_TRACE_RATE_LIMIT")
  264. if v != "" {
  265. l, err := strconv.ParseFloat(v, 64)
  266. if err != nil {
  267. log.Warn("DD_TRACE_RATE_LIMIT invalid, using default value %f: %v", limit, err)
  268. } else if l < 0.0 {
  269. log.Warn("DD_TRACE_RATE_LIMIT negative, using default value %f", limit)
  270. } else {
  271. // override the default limit
  272. limit = l
  273. }
  274. }
  275. return &rateLimiter{
  276. limiter: rate.NewLimiter(rate.Limit(limit), int(math.Ceil(limit))),
  277. prevTime: time.Now(),
  278. }
  279. }
  280. // singleSpanRulesSampler allows a user-defined list of rules to apply to spans
  281. // to sample single spans.
  282. // These rules match based on the span's Service and Name. If empty value is supplied
  283. // to either Service or Name field, it will default to "*", allow all.
  284. // When making a sampling decision, the rules are checked in order until
  285. // a match is found.
  286. // If a match is found, the rate from that rule is used.
  287. // If no match is found, no changes or further sampling is applied to the spans.
  288. // The rate is used to determine if the span should be sampled, but an upper
  289. // limit can be defined using the max_per_second field when supplying the rule.
  290. // If max_per_second is absent in the rule, the default is allow all.
  291. // Its value is the max number of spans to sample per second.
  292. // Spans that matched the rules but exceeded the rate limit are not sampled.
  293. type singleSpanRulesSampler struct {
  294. rules []SamplingRule // the rules to match spans with
  295. }
  296. // newSingleSpanRulesSampler configures a *singleSpanRulesSampler instance using the given set of rules.
  297. // Invalid rules or environment variable values are tolerated, by logging warnings and then ignoring them.
  298. func newSingleSpanRulesSampler(rules []SamplingRule) *singleSpanRulesSampler {
  299. return &singleSpanRulesSampler{
  300. rules: rules,
  301. }
  302. }
  303. func (rs *singleSpanRulesSampler) enabled() bool {
  304. return len(rs.rules) > 0
  305. }
  306. // apply uses the sampling rules to determine the sampling rate for the
  307. // provided span. If the rules don't match, then it returns false and the span is not
  308. // modified.
  309. func (rs *singleSpanRulesSampler) apply(span *span) bool {
  310. for _, rule := range rs.rules {
  311. if rule.match(span) {
  312. rate := rule.Rate
  313. span.setMetric(keyRulesSamplerAppliedRate, rate)
  314. if !sampledByRate(span.SpanID, rate) {
  315. return false
  316. }
  317. var sampled bool
  318. if rule.limiter != nil {
  319. sampled, rate = rule.limiter.allowOne(nowTime())
  320. if !sampled {
  321. return false
  322. }
  323. }
  324. span.setMetric(keySpanSamplingMechanism, samplingMechanismSingleSpan)
  325. span.setMetric(keySingleSpanSamplingRuleRate, rate)
  326. if rule.MaxPerSecond != 0 {
  327. span.setMetric(keySingleSpanSamplingMPS, rule.MaxPerSecond)
  328. }
  329. return true
  330. }
  331. }
  332. return false
  333. }
  334. // rateLimiter is a wrapper on top of golang.org/x/time/rate which implements a rate limiter but also
  335. // returns the effective rate of allowance.
  336. type rateLimiter struct {
  337. limiter *rate.Limiter
  338. mu sync.Mutex // guards below fields
  339. prevTime time.Time // time at which prevAllowed and prevSeen were set
  340. allowed float64 // number of spans allowed in the current period
  341. seen float64 // number of spans seen in the current period
  342. prevAllowed float64 // number of spans allowed in the previous period
  343. prevSeen float64 // number of spans seen in the previous period
  344. }
  345. // allowOne returns the rate limiter's decision to allow the span to be sampled, and the
  346. // effective rate at the time it is called. The effective rate is computed by averaging the rate
  347. // for the previous second with the current rate
  348. func (r *rateLimiter) allowOne(now time.Time) (bool, float64) {
  349. r.mu.Lock()
  350. defer r.mu.Unlock()
  351. if d := now.Sub(r.prevTime); d >= time.Second {
  352. // enough time has passed to reset the counters
  353. if d.Truncate(time.Second) == time.Second && r.seen > 0 {
  354. // exactly one second, so update prev
  355. r.prevAllowed = r.allowed
  356. r.prevSeen = r.seen
  357. } else {
  358. // more than one second, so reset previous rate
  359. r.prevAllowed = 0
  360. r.prevSeen = 0
  361. }
  362. r.prevTime = now
  363. r.allowed = 0
  364. r.seen = 0
  365. }
  366. r.seen++
  367. var sampled bool
  368. if r.limiter.AllowN(now, 1) {
  369. r.allowed++
  370. sampled = true
  371. }
  372. er := (r.prevAllowed + r.allowed) / (r.prevSeen + r.seen)
  373. return sampled, er
  374. }
  375. // newSingleSpanRateLimiter returns a rate limiter which restricts the number of single spans sampled per second.
  376. // This defaults to infinite, allow all behaviour. The MaxPerSecond value of the rule may override the default.
  377. func newSingleSpanRateLimiter(mps float64) *rateLimiter {
  378. limit := math.MaxFloat64
  379. if mps > 0 {
  380. limit = mps
  381. }
  382. return &rateLimiter{
  383. limiter: rate.NewLimiter(rate.Limit(limit), int(math.Ceil(limit))),
  384. prevTime: time.Now(),
  385. }
  386. }
  387. // globMatch compiles pattern string into glob format, i.e. regular expressions with only '?'
  388. // and '*' treated as regex metacharacters.
  389. func globMatch(pattern string) *regexp.Regexp {
  390. if pattern == "" {
  391. return regexp.MustCompile("^.*$")
  392. }
  393. // escaping regex characters
  394. pattern = regexp.QuoteMeta(pattern)
  395. // replacing '?' and '*' with regex characters
  396. pattern = strings.Replace(pattern, "\\?", ".", -1)
  397. pattern = strings.Replace(pattern, "\\*", ".*", -1)
  398. // pattern must match an entire string
  399. return regexp.MustCompile(fmt.Sprintf("^%s$", pattern))
  400. }
  401. // samplingRulesFromEnv parses sampling rules from the DD_TRACE_SAMPLING_RULES,
  402. // DD_SPAN_SAMPLING_RULES and DD_SPAN_SAMPLING_RULES_FILE environment variables.
  403. func samplingRulesFromEnv() (trace, span []SamplingRule, err error) {
  404. var errs []string
  405. defer func() {
  406. if len(errs) != 0 {
  407. err = fmt.Errorf("\n\t%s", strings.Join(errs, "\n\t"))
  408. }
  409. }()
  410. rulesFromEnv := os.Getenv("DD_TRACE_SAMPLING_RULES")
  411. if rulesFromEnv != "" {
  412. trace, err = unmarshalSamplingRules([]byte(rulesFromEnv), SamplingRuleTrace)
  413. if err != nil {
  414. errs = append(errs, err.Error())
  415. }
  416. }
  417. span, err = unmarshalSamplingRules([]byte(os.Getenv("DD_SPAN_SAMPLING_RULES")), SamplingRuleSpan)
  418. if err != nil {
  419. errs = append(errs, err.Error())
  420. }
  421. rulesFile := os.Getenv("DD_SPAN_SAMPLING_RULES_FILE")
  422. if len(span) != 0 {
  423. if rulesFile != "" {
  424. log.Warn("DIAGNOSTICS Error(s): DD_SPAN_SAMPLING_RULES is available and will take precedence over DD_SPAN_SAMPLING_RULES_FILE")
  425. }
  426. return trace, span, err
  427. }
  428. if rulesFile != "" {
  429. rulesFromEnvFile, err := os.ReadFile(rulesFile)
  430. if err != nil {
  431. errs = append(errs, fmt.Sprintf("Couldn't read file from DD_SPAN_SAMPLING_RULES_FILE: %v", err))
  432. }
  433. span, err = unmarshalSamplingRules(rulesFromEnvFile, SamplingRuleSpan)
  434. if err != nil {
  435. errs = append(errs, err.Error())
  436. }
  437. }
  438. return trace, span, err
  439. }
  440. // unmarshalSamplingRules unmarshals JSON from b and returns the sampling rules found, attributing
  441. // the type t to them. If any errors are occurred, they are returned.
  442. func unmarshalSamplingRules(b []byte, spanType SamplingRuleType) ([]SamplingRule, error) {
  443. if len(b) == 0 {
  444. return nil, nil
  445. }
  446. var jsonRules []struct {
  447. Service string `json:"service"`
  448. Name string `json:"name"`
  449. Rate json.Number `json:"sample_rate"`
  450. MaxPerSecond float64 `json:"max_per_second"`
  451. }
  452. err := json.Unmarshal(b, &jsonRules)
  453. if err != nil {
  454. return nil, fmt.Errorf("error unmarshalling JSON: %v", err)
  455. }
  456. rules := make([]SamplingRule, 0, len(jsonRules))
  457. var errs []string
  458. for i, v := range jsonRules {
  459. if v.Rate == "" {
  460. if spanType == SamplingRuleSpan {
  461. v.Rate = "1"
  462. } else {
  463. errs = append(errs, fmt.Sprintf("at index %d: rate not provided", i))
  464. continue
  465. }
  466. }
  467. rate, err := v.Rate.Float64()
  468. if err != nil {
  469. errs = append(errs, fmt.Sprintf("at index %d: %v", i, err))
  470. continue
  471. }
  472. if rate < 0.0 || rate > 1.0 {
  473. errs = append(errs, fmt.Sprintf("at index %d: ignoring rule %+v: rate is out of [0.0, 1.0] range", i, v))
  474. continue
  475. }
  476. switch spanType {
  477. case SamplingRuleSpan:
  478. rules = append(rules, SamplingRule{
  479. Service: globMatch(v.Service),
  480. Name: globMatch(v.Name),
  481. Rate: rate,
  482. MaxPerSecond: v.MaxPerSecond,
  483. limiter: newSingleSpanRateLimiter(v.MaxPerSecond),
  484. ruleType: SamplingRuleSpan,
  485. })
  486. case SamplingRuleTrace:
  487. if v.Rate == "" {
  488. errs = append(errs, fmt.Sprintf("at index %d: rate not provided", i))
  489. continue
  490. }
  491. rate, err := v.Rate.Float64()
  492. if err != nil {
  493. errs = append(errs, fmt.Sprintf("at index %d: %v", i, err))
  494. continue
  495. }
  496. if rate < 0.0 || rate > 1.0 {
  497. errs = append(errs, fmt.Sprintf("at index %d: ignoring rule %+v: rate is out of [0.0, 1.0] range", i, v))
  498. continue
  499. }
  500. switch {
  501. case v.Service != "" && v.Name != "":
  502. rules = append(rules, NameServiceRule(v.Name, v.Service, rate))
  503. case v.Service != "":
  504. rules = append(rules, ServiceRule(v.Service, rate))
  505. case v.Name != "":
  506. rules = append(rules, NameRule(v.Name, rate))
  507. }
  508. }
  509. }
  510. if len(errs) != 0 {
  511. return rules, fmt.Errorf("%s", strings.Join(errs, "\n\t"))
  512. }
  513. return rules, nil
  514. }
  515. // MarshalJSON implements the json.Marshaler interface.
  516. func (sr *SamplingRule) MarshalJSON() ([]byte, error) {
  517. s := struct {
  518. Service string `json:"service"`
  519. Name string `json:"name"`
  520. Rate float64 `json:"sample_rate"`
  521. Type string `json:"type"`
  522. MaxPerSecond *float64 `json:"max_per_second,omitempty"`
  523. }{}
  524. if sr.exactService != "" {
  525. s.Service = sr.exactService
  526. } else if sr.Service != nil {
  527. s.Service = fmt.Sprintf("%s", sr.Service)
  528. }
  529. if sr.exactName != "" {
  530. s.Name = sr.exactName
  531. } else if sr.Name != nil {
  532. s.Name = fmt.Sprintf("%s", sr.Name)
  533. }
  534. s.Rate = sr.Rate
  535. s.Type = fmt.Sprintf("%v(%d)", sr.ruleType.String(), sr.ruleType)
  536. if sr.MaxPerSecond != 0 {
  537. s.MaxPerSecond = &sr.MaxPerSecond
  538. }
  539. return json.Marshal(&s)
  540. }