Sentinel源码—6.熔断降级和数据统计的实现二

打印 上一主题 下一主题

主题 1617|帖子 1617|积分 4851

大纲
1.DegradeSlot实现熔断降级的原理与源码
2.Sentinel数据指标统计的滑动窗口算法

2.Sentinel数据指标统计的滑动窗口算法
(1)滑动窗口先容
(2)StatisticSlot利用滑动窗口算法进行数据统计

(1)滑动窗口先容
一.滑动窗口原理
滑动窗口不会指定固定的时间窗口出发点与尽头,而是将处置惩罚请求的时间点作为该请求对应时间窗口的尽头,出发点则是向前距离该尽头一个时间窗口长度的时间点。

二.滑动窗口的性能问题(样本窗口解决)
由于每到来一个请求,就会移动一下统计的时间窗口。如果先后到来的两个请求的相隔时间在一个时间窗口长度之内,那么分别在这个两个请求对应的时间窗口下统计请求数时就会出现重复计数的问题。如果在一个时间窗口长度内出现了大量的请求,则会进行大量重复计算从而浪费资源。

为了解决这个问题,就需要更细粒度的计算,比如引入样本窗口。样本窗口的长度会小于滑动窗口的长度,通常滑动窗口的长度是样本窗口的整数倍。每个样本窗口在到达尽头时间时,会统计其中的请求数并进行记录。这样统计请求对应的时间窗口的请求数时,就可复用样本窗口的数据了。

以是,通过多个样本窗口构成滑动窗口,可以解决滑动窗口的性能问题。

(2)StatisticSlot利用滑动窗口算法进行数据统计
一.StatisticNode为了实现统计数据而进行的计划
二.LeapArray实现滑动窗口算法的数据统计逻辑

一.StatisticNode为了实现统计数据而进行的计划
起首StatisticSlot的entry()方法会调用DefaultNode的addPassRequest()方法,接着DefaultNode的addPassRequest()方法又会调用StatisticNode的addPassRequest()方法,而StatisticNode的addPassRequest()方法便会通过利用滑动窗口算法来统计数据。

StatisticNode中会定义一个用来保存数据的ArrayMetric对象。创建该对象时默认就指定了样本窗口数量为2,时间窗口长度为1000ms。其中,ArrayMetric对象中的data属性会真正用来存储数据,而ArrayMetric对象中的data属性则是一个LeapArray对象。

在LeapArray对象中会详细记录:样本窗口长度、样本窗口数量、滑动窗口长度、样本窗口数组。LeapArray的array属性便是用来统计并保存数据的WindowWrap数组,WindowWrap数组也就是样本窗口数组。

WindowWrap有一个奇妙的计划:就是利用LongAdder数组而不是用LongAdder来存储统计数据。由于统计的数据是多维度的,且MetricEvent枚举类定义了这些维度类型,因此将MetricEvent维度类型枚举值对应的序号映射成数组索引,可以奇妙地将多维度的数据存储到LongAdder数组中。
  1. @Spi(order = Constants.ORDER_STATISTIC_SLOT)
  2. public class StatisticSlot extends AbstractLinkedProcessorSlot<DefaultNode> {
  3.     @Override
  4.     public void entry(Context context, ResourceWrapper resourceWrapper, DefaultNode node, int count, boolean prioritized, Object... args) throws Throwable {
  5.         ...
  6.         //执行下一个ProcessorSlot,先进行规则验证等
  7.         fireEntry(context, resourceWrapper, node, count, prioritized, args);
  8.         //如果通过了后面ProcessorSlot的验证
  9.         //则将处理当前资源resourceWrapper的线程数+1 以及 将对当前资源resourceWrapper的成功请求数+1
  10.         node.increaseThreadNum();
  11.         node.addPassRequest(count);
  12.         ...
  13.     }
  14. }
  15. //A Node used to hold statistics for specific resource name in the specific context.
  16. //Each distinct resource in each distinct Context will corresponding to a DefaultNode.
  17. //This class may have a list of sub DefaultNodes.
  18. //Child nodes will be created when calling SphU.entry() or SphO.entry() multiple times in the same Context.
  19. public class DefaultNode extends StatisticNode {
  20.     //Associated cluster node.
  21.     private ClusterNode clusterNode;
  22.     ...
  23.    
  24.     //DefaultNode会统计名字相同的Context下的某个资源的调用数据,按照单机里的资源维度进行调用数据统计
  25.     //EntranceNode会统计名字相同的Context下的全部资源的调用数据,按接口维度来统计调用数据,即统计接口下所有资源的调用情况
  26.     //ClusterNode会统计某个资源在全部Context下的调用数据,按照集群中的资源维度进行调用数据统计
  27.     @Override
  28.     public void addPassRequest(int count) {
  29.         //增加当前资源对应的DefaultNode中的数据
  30.         super.addPassRequest(count);
  31.         //增加当前资源对应的ClusterNode中的全局统计数据
  32.         this.clusterNode.addPassRequest(count);
  33.     }
  34.     ...
  35. }
  36. //The statistic node keep three kinds of real-time statistics metrics:
  37. //1.metrics in second level rollingCounterInSecond
  38. //2.metrics in minute level rollingCounterInMinute
  39. //3.thread count
  40. //Sentinel use sliding window to record and count the resource statistics in real-time.
  41. //The sliding window infrastructure behind the ArrayMetric is LeapArray.
  42. //case 1: When the first request comes in,
  43. //Sentinel will create a new window bucket of a specified time-span to store running statics,
  44. //such as total response time(rt), incoming request(QPS), block request(bq), etc.
  45. //And the time-span is defined by sample count.
  46. //     0      100ms
  47. //  +-------+--→ Sliding Windows
  48. //         ^
  49. //         |
  50. //       request
  51. //Sentinel use the statics of the valid buckets to decide whether this request can be passed.
  52. //For example, if a rule defines that only 100 requests can be passed,
  53. //it will sum all qps in valid buckets, and compare it to the threshold defined in rule.
  54. //case 2: continuous requests
  55. //  0    100ms    200ms    300ms
  56. //  +-------+-------+-------+-----→ Sliding Windows
  57. //                      ^
  58. //                      |
  59. //                   request
  60. //case 3: requests keeps coming, and previous buckets become invalid
  61. //  0    100ms    200ms      800ms       900ms  1000ms    1300ms
  62. //  +-------+-------+ ...... +-------+-------+ ...... +-------+-----→ Sliding Windows
  63. //                                                      ^
  64. //                                                      |
  65. //                                                    request
  66. //The sliding window should become:
  67. // 300ms     800ms  900ms  1000ms  1300ms
  68. //  + ...... +-------+ ...... +-------+-----→ Sliding Windows
  69. //                                                      ^
  70. //                                                      |
  71. //                                                    request
  72. public class StatisticNode implements Node {
  73.     //Holds statistics of the recent INTERVAL milliseconds.
  74.     //The INTERVAL is divided into time spans by given sampleCount.
  75.     //定义一个保存数据的ArrayMetric,指定了样本窗口数量默认为2(SAMPLE_COUNT),指定了时间窗口长度默认为1000ms(INTERVAL)
  76.     private transient volatile Metric rollingCounterInSecond = new ArrayMetric(SampleCountProperty.SAMPLE_COUNT, IntervalProperty.INTERVAL);
  77.    
  78.     //Holds statistics of the recent 60 seconds.
  79.     //The windowLengthInMs is deliberately set to 1000 milliseconds,
  80.     //meaning each bucket per second, in this way we can get accurate statistics of each second.
  81.     private transient Metric rollingCounterInMinute = new ArrayMetric(60, 60 * 1000, false);
  82.     ...
  83.     @Override
  84.     public void addPassRequest(int count) {
  85.         //调用ArrayMetric.addPass()方法,根据当前请求增加计数
  86.         rollingCounterInSecond.addPass(count);
  87.         rollingCounterInMinute.addPass(count);
  88.     }
  89.     ...
  90. }
  91. //The basic metric class in Sentinel using a BucketLeapArray internal.
  92. public class ArrayMetric implements Metric {
  93.     //用于存储统计数据
  94.     private final LeapArray<MetricBucket> data;
  95.     ...
  96.    
  97.     @Override
  98.     public void addPass(int count) {
  99.         //1.通过LeapArray.currentWindow()方法获取当前时间所在的样本窗口
  100.         WindowWrap<MetricBucket> wrap = data.currentWindow();
  101.         //2.调用MetricBucket.addPass()方法将当前请求的计数量添加到样本窗口的统计数据中
  102.         wrap.value().addPass(count);
  103.     }
  104.     ...
  105. }
  106. //Basic data structure for statistic metrics in Sentinel.
  107. //Leap array use sliding window algorithm to count data.
  108. //Each bucket cover windowLengthInMs time span, and the total time span is intervalInMs,
  109. //so the total bucket amount is: sampleCount = intervalInMs / windowLengthInMs.
  110. public abstract class LeapArray<T> {
  111.     //样本窗口的长度
  112.     protected int windowLengthInMs;
  113.     //一个滑动窗口包含的样本窗口数量,公式 intervalInMs / windowLengthInMs,也就是滑动窗口长度 / 样本窗口长度
  114.     protected int sampleCount;
  115.     //滑动窗口长度
  116.     protected int intervalInMs;
  117.     //也是滑动窗口长度,只是单位为s
  118.     private double intervalInSecond;
  119.     //WindowWrap是样本窗口类,它是一个数组,泛型T实际类型为MetricBucket
  120.     //LeapArray类似于一个样本窗口管理类,而真正的样本窗口类是WindowWrap<T>
  121.     protected final AtomicReferenceArray<WindowWrap<T>> array;
  122.     //The total bucket count is: sampleCount = intervalInMs / windowLengthInMs.
  123.     //@param sampleCount  bucket count of the sliding window
  124.     //@param intervalInMs the total time interval of this LeapArray in milliseconds
  125.     public LeapArray(int sampleCount, int intervalInMs) {
  126.         ...
  127.         this.windowLengthInMs = intervalInMs / sampleCount;//默认为500ms
  128.         this.intervalInMs = intervalInMs;//默认为1000ms
  129.         this.intervalInSecond = intervalInMs / 1000.0;//默认为1
  130.         this.sampleCount = sampleCount;//默认为2
  131.         this.array = new AtomicReferenceArray<>(sampleCount);
  132.     }
  133.     //Get the bucket at current timestamp.
  134.     //获取当前时间点所在的样本窗口
  135.     public WindowWrap<T> currentWindow() {
  136.         return currentWindow(TimeUtil.currentTimeMillis());
  137.     }
  138.     ...
  139. }
  140. //Wrapper entity class for a period of time window.
  141. //样本窗口类,泛型T比如是MetricBucket
  142. public class WindowWrap<T> {
  143.     //Time length of a single window bucket in milliseconds.
  144.     //单个样本窗口的长度
  145.     private final long windowLengthInMs;
  146.     //Start timestamp of the window in milliseconds.
  147.     //样本窗口的起始时间戳
  148.     private long windowStart;
  149.     //Statistic data.
  150.     //当前样本窗口的统计数据,类型为MetricBucket
  151.     private T value;
  152.     ...
  153.     //返回比如MetricBucket对象
  154.     public T value() {
  155.         return value;
  156.     }
  157. }
  158. //Represents metrics data in a period of time span.
  159. //统计数据的封装类
  160. public class MetricBucket {
  161.     //统计的数据会存放在LongAdder数组里
  162.     //使用数组而不直接使用"LongAdder+1"是因为:
  163.     //由于统计的数据是多维度的,并且MetricEvent枚举类定义了这些维度类型
  164.     //因此将MetricEvent维度类型枚举值对应的序号映射成数组索引,巧妙地将多维度的数据定义在LongAdder数组中
  165.     private final LongAdder[] counters;
  166.     private volatile long minRt;
  167.    
  168.     public MetricBucket() {
  169.         MetricEvent[] events = MetricEvent.values();
  170.         this.counters = new LongAdder[events.length];
  171.         for (MetricEvent event : events) {
  172.             counters[event.ordinal()] = new LongAdder();
  173.         }
  174.         initMinRt();
  175.     }
  176.    
  177.     private void initMinRt() {
  178.         this.minRt = SentinelConfig.statisticMaxRt();
  179.     }
  180.    
  181.     public void addPass(int n) {
  182.         add(MetricEvent.PASS, n);
  183.     }
  184.    
  185.     public MetricBucket add(MetricEvent event, long n) {
  186.         //统计数据并存储到counters中
  187.         counters[event.ordinal()].add(n);
  188.         return this;
  189.     }
  190.     ...
  191. }
  192. public enum MetricEvent {
  193.     PASS,
  194.     BLOCK,
  195.     EXCEPTION,
  196.     SUCCESS,
  197.     RT,
  198.     OCCUPIED_PASS
  199. }
复制代码
二.LeapArray实现滑动窗口算法的数据统计逻辑
调用ArrayMetric的addPass()进行数据统计的逻辑如下:起首通过LeapArray的currentWindow()方法获取当前时间所在的样本窗口,然后调用MetricBucket的addPass()方法统计并存储数据到样本窗口中。

LeapArray的currentWindow()方法获取当前时间所在的样本窗口的逻辑为:

情况一:如果当前时间所在的样本窗口如果还没创建,则需要初始化。

情况二:如果当前样本窗口的起始时间与计算出的样本窗口起始时间相同,则说明这两个是同一个样本窗口,直接获取就行。

情况三:如果当前样本窗口的起始时间大于计算出的样本窗口起始时间,则说明计算出的样本窗口已过时,要将原来的样本窗口替换为新样本窗口。留意LeapArray.array数组是一个环形数组。

情况四:如果当前样本窗口的起始时间小于计算出的样本窗口起始时间,一样寻常不出现,因为时间不会倒流,除非人为修改系统时间导致时钟回拨。

  1. public abstract class LeapArray<T> {
  2.     //样本窗口的长度
  3.     protected int windowLengthInMs;
  4.     //一个滑动窗口包含的样本窗口数量,公式 intervalInMs / windowLengthInMs,也就是滑动窗口长度 / 样本窗口长度
  5.     protected int sampleCount;
  6.     //滑动窗口长度
  7.     protected int intervalInMs;
  8.     //也是滑动窗口长度,只是单位为s
  9.     private double intervalInSecond;
  10.     //WindowWrap是样本窗口类,它是一个数组,泛型T实际类型为MetricBucket
  11.     //LeapArray类似于一个样本窗口管理类,而真正的样本窗口类是WindowWrap<T>
  12.     protected final AtomicReferenceArray<WindowWrap<T>> array;
  13.     ...
  14.     //假设timeMillis = 1600,windowLengthInMs = 500,array.length = 2,那么timeId = 3,返回1
  15.     private int calculateTimeIdx(/*@Valid*/ long timeMillis) {
  16.         long timeId = timeMillis / windowLengthInMs;
  17.         //Calculate current index so we can map the timestamp to the leap array.
  18.         return (int)(timeId % array.length());
  19.     }
  20.     //假设timeMillis = 1600,windowLengthInMs = 500,那么返回1500
  21.     protected long calculateWindowStart(/*@Valid*/ long timeMillis) {
  22.         return timeMillis - timeMillis % windowLengthInMs;
  23.     }
  24.     //Get bucket item at provided timestamp.
  25.     public WindowWrap<T> currentWindow(long timeMillis) {
  26.         if (timeMillis < 0) {
  27.             return null;
  28.         }
  29.         //计算当前时间所在的样本窗口id,也就是样本窗口的下标,即计算在数组LeapArray中的下标
  30.         int idx = calculateTimeIdx(timeMillis);
  31.         //Calculate current bucket start time.
  32.         //计算当前样本窗口的开始时间点
  33.         long windowStart = calculateWindowStart(timeMillis);
  34.         //Get bucket item at given time from the array.
  35.         //(1) Bucket is absent, then just create a new bucket and CAS update to circular array.
  36.         //(2) Bucket is up-to-date, then just return the bucket.
  37.         //(3) Bucket is deprecated, then reset current bucket.
  38.         while (true) {
  39.             //获取当前时间所在的样本窗口
  40.             WindowWrap<T> old = array.get(idx);
  41.             //如果当前时间所在的样本窗口为null,则需要创建
  42.             if (old == null) {
  43.                 //创建一个时间窗口
  44.                 //     B0       B1      B2    NULL      B4
  45.                 // ||_______|_______|_______|_______|_______||___
  46.                 // 200     400     600     800     1000    1200  timestamp
  47.                 //                             ^
  48.                 //                          time=888
  49.                 //            bucket is empty, so create new and update
  50.                 //If the old bucket is absent, then we create a new bucket at windowStart,
  51.                 //then try to update circular array via a CAS operation.
  52.                 //Only one thread can succeed to update, while other threads yield its time slice.
  53.                 WindowWrap<T> window = new WindowWrap<T>(windowLengthInMs, windowStart, newEmptyBucket(timeMillis));
  54.                 //通过CAS将新创建的窗口放入到LeapArray中
  55.                 if (array.compareAndSet(idx, null, window)) {
  56.                     //Successfully updated, return the created bucket.
  57.                     return window;
  58.                 } else {
  59.                     //Contention failed, the thread will yield its time slice to wait for bucket available.
  60.                     Thread.yield();
  61.                 }
  62.             }
  63.             //如果当前样本窗口的起始时间与计算出的样本窗口起始时间相同,则说明这两个是同一个样本窗口,直接获取就行
  64.             else if (windowStart == old.windowStart()) {
  65.                 //     B0       B1      B2     B3      B4
  66.                 // ||_______|_______|_______|_______|_______||___
  67.                 // 200     400     600     800     1000    1200  timestamp
  68.                 //                             ^
  69.                 //                          time=888
  70.                 //            startTime of Bucket 3: 800, so it's up-to-date
  71.                 //If current windowStart is equal to the start timestamp of old bucket,
  72.                 //that means the time is within the bucket, so directly return the bucket.
  73.                 return old;
  74.             }
  75.             //如果当前样本窗口的起始时间大于计算出的样本窗口起始时间,则说明计算出来的样本窗口已经过时了,需要将原来的样本窗口替换为新的样本窗口
  76.             //数组的环形数组,不是无限长的,比如存1s,1000个样本窗口,那么下1s的1000个时间窗口会覆盖上一秒的
  77.             else if (windowStart > old.windowStart()) {
  78.                 //   (old)
  79.                 //             B0       B1      B2    NULL      B4
  80.                 // |_______||_______|_______|_______|_______|_______||___
  81.                 // ...    1200     1400    1600    1800    2000    2200  timestamp
  82.                 //                              ^
  83.                 //                           time=1676
  84.                 //          startTime of Bucket 2: 400, deprecated, should be reset
  85.                 //If the start timestamp of old bucket is behind provided time, that means the bucket is deprecated.
  86.                 //We have to reset the bucket to current windowStart.
  87.                 //Note that the reset and clean-up operations are hard to be atomic,
  88.                 //so we need a update lock to guarantee the correctness of bucket update.
  89.                 //The update lock is conditional (tiny scope) and will take effect only when bucket is deprecated,
  90.                 //so in most cases it won't lead to performance loss.
  91.                 if (updateLock.tryLock()) {
  92.                     try {
  93.                         //Successfully get the update lock, now we reset the bucket.
  94.                         //替换老的样本窗口
  95.                         return resetWindowTo(old, windowStart);
  96.                     } finally {
  97.                         updateLock.unlock();
  98.                     }
  99.                 } else {
  100.                     //Contention failed, the thread will yield its time slice to wait for bucket available.
  101.                     Thread.yield();
  102.                 }
  103.             }
  104.             //如果当前样本窗口的起始时间小于计算出的样本窗口起始时间
  105.             //这种情况一般不会出现,因为时间不会倒流,除非人为修改系统时间导致时钟回拨
  106.             else if (windowStart < old.windowStart()) {
  107.                 //Should not go through here, as the provided time is already behind.
  108.                 return new WindowWrap<T>(windowLengthInMs, windowStart, newEmptyBucket(timeMillis));
  109.             }
  110.         }
  111.     }
  112.     ...
  113. }
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

反转基因福娃

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表