找回密码
 立即注册
首页 业界区 业界 Sentinel源码—3.ProcessorSlot的执行过程

Sentinel源码—3.ProcessorSlot的执行过程

纪晴丽 2025-6-2 21:36:40
大纲
1.NodeSelectorSlot构建资源调用树
2.LogSlot和StatisticSlot采集资源的数据
3.Sentinel监听器模式的规则对象与规则管理
4.AuthoritySlot控制黑白名单权限
5.SystemSlot根据系统保护规则进行流控
 
1.NodeSelectorSlot构建资源调用树
(1)Entry的处理链的执行入口
(2)NodeSelectorSlot的源码
(3)Context对象中存储的资源调用树总结
 
(1)Entry的处理链的执行入口
每当一个线程处理包含某些资源的接口请求时,会调用SphU的entry()方法去创建并管控该接口中涉及的Entry资源访问对象。
 
在创建Entry资源访问对象的期间,会创建一个ResourceWrapper对象、一个Context对象、以及根据ResourceWrapper对象创建或获取一个ProcessorSlotChain对象,也就是把ProcessorSlotChain对象、Context对象与ResourceWrapper对象绑定到Entry对象中。
  1. public class SphU {
  2.     private static final Object[] OBJECTS0 = new Object[0];
  3.     ...
  4.     public static Entry entry(String name) throws BlockException {
  5.         //调用CtSph.entry()方法创建一个Entry资源访问对象,默认的请求类型为OUT
  6.         return Env.sph.entry(name, EntryType.OUT, 1, OBJECTS0);
  7.     }
  8. }
  9. public class Env {
  10.     //创建一个CtSph对象
  11.     public static final Sph sph = new CtSph();
  12.     static {
  13.         InitExecutor.doInit();
  14.     }
  15. }
  16. public class CtSph implements Sph {
  17.     //Same resource will share the same ProcessorSlotChain}, no matter in which Context.
  18.     //Same resource is that ResourceWrapper#equals(Object).
  19.     private static volatile Map<ResourceWrapper, ProcessorSlotChain> chainMap = new HashMap<ResourceWrapper, ProcessorSlotChain>();
  20.     ...
  21.     @Override
  22.     public Entry entry(String name, EntryType type, int count, Object... args) throws BlockException {
  23.         //StringResourceWrapper是ResourceWrapper的子类,且StringResourceWrapper的构造方法默认了资源类型为COMMON
  24.         StringResourceWrapper resource = new StringResourceWrapper(name, type);
  25.         return entry(resource, count, args);
  26.     }
  27.    
  28.     //Do all {@link Rule}s checking about the resource.
  29.     public Entry entry(ResourceWrapper resourceWrapper, int count, Object... args) throws BlockException {
  30.         //调用CtSph.entryWithPriority()方法,执行如下处理:
  31.         //初始化Context -> 将Context与线程绑定 -> 初始化Entry -> 将Context和ResourceWrapper放入Entry中
  32.         return entryWithPriority(resourceWrapper, count, false, args);
  33.     }
  34.    
  35.     private Entry entryWithPriority(ResourceWrapper resourceWrapper, int count, boolean prioritized, Object... args) throws BlockException {
  36.         //从当前线程中获取Context
  37.         Context context = ContextUtil.getContext();
  38.         if (context instanceof NullContext) {
  39.             return new CtEntry(resourceWrapper, null, context);
  40.         }
  41.         //如果没获取到Context
  42.         if (context == null) {
  43.             //Using default context.
  44.             //创建一个名为sentinel_default_context的Context,并且与当前线程绑定
  45.             context = InternalContextUtil.internalEnter(Constants.CONTEXT_DEFAULT_NAME);
  46.         }
  47.         //Global switch is close, no rule checking will do.
  48.         if (!Constants.ON) {
  49.             return new CtEntry(resourceWrapper, null, context);
  50.         }
  51.         //调用CtSph.lookProcessChain()方法初始化处理链(处理器插槽链条)
  52.         ProcessorSlot<Object> chain = lookProcessChain(resourceWrapper);
  53.         if (chain == null) {
  54.             return new CtEntry(resourceWrapper, null, context);
  55.         }
  56.         //创建出一个Entry对象,将处理链(处理器插槽链条)、Context与Entry绑定
  57.         //其中会将Entry的三个基础属性(封装在resourceWrapper里)以及当前Entry所属的Context作为参数传入CtEntry的构造方法
  58.         Entry e = new CtEntry(resourceWrapper, chain, context);
  59.         try {
  60.             //处理链(处理器插槽链条)入口,负责采集数据,规则验证
  61.             //调用DefaultProcessorSlotChain.entry()方法执行处理链每个节点的逻辑(数据采集+规则验证)
  62.             chain.entry(context, resourceWrapper, null, count, prioritized, args);
  63.         } catch (BlockException e1) {
  64.             //规则验证失败,比如:被流控、被熔断降级、触发黑白名单等
  65.             e.exit(count, args);
  66.             throw e1;
  67.         } catch (Throwable e1) {
  68.             RecordLog.info("Sentinel unexpected exception", e1);
  69.         }
  70.         return e;
  71.     }
  72.     ...
  73.    
  74.     private final static class InternalContextUtil extends ContextUtil {
  75.         static Context internalEnter(String name) {
  76.             //调用ContextUtil.trueEnter()方法创建一个Context对象
  77.             return trueEnter(name, "");
  78.         }
  79.         
  80.         static Context internalEnter(String name, String origin) {
  81.             return trueEnter(name, origin);
  82.         }
  83.     }
  84.    
  85.     //Get ProcessorSlotChain of the resource.
  86.     //new ProcessorSlotChain will be created if the resource doesn't relate one.
  87.     //Same resource will share the same ProcessorSlotChain globally, no matter in which Context.
  88.     //Same resource is that ResourceWrapper#equals(Object).
  89.     ProcessorSlot<Object> lookProcessChain(ResourceWrapper resourceWrapper) {
  90.         ProcessorSlotChain chain = chainMap.get(resourceWrapper);
  91.         if (chain == null) {
  92.             synchronized (LOCK) {
  93.                 chain = chainMap.get(resourceWrapper);
  94.                 if (chain == null) {
  95.                     //Entry size limit.
  96.                     if (chainMap.size() >= Constants.MAX_SLOT_CHAIN_SIZE) {
  97.                         return null;
  98.                     }
  99.                     //调用SlotChainProvider.newSlotChain()方法初始化处理链(处理器插槽链条)
  100.                     chain = SlotChainProvider.newSlotChain();
  101.                     //写时复制
  102.                     Map<ResourceWrapper, ProcessorSlotChain> newMap = new HashMap<ResourceWrapper, ProcessorSlotChain>(chainMap.size() + 1);
  103.                     newMap.putAll(chainMap);
  104.                     newMap.put(resourceWrapper, chain);
  105.                     chainMap = newMap;
  106.                 }
  107.             }
  108.         }
  109.         return chain;
  110.     }
  111. }
  112. public class StringResourceWrapper extends ResourceWrapper {
  113.     public StringResourceWrapper(String name, EntryType e) {
  114.         //调用父类构造方法,且默认资源类型为COMMON
  115.         super(name, e, ResourceTypeConstants.COMMON);
  116.     }
  117.     ...
  118. }
  119. //Utility class to get or create Context in current thread.
  120. //Each SphU.entry() should be in a Context.
  121. //If we don't invoke ContextUtil.enter() explicitly, DEFAULT context will be used.
  122. public class ContextUtil {
  123.     //Store the context in ThreadLocal for easy access.
  124.     //存放线程与Context的绑定关系
  125.     //每个请求对应一个线程,每个线程绑定一个Context,所以每个请求对应一个Context
  126.     private static ThreadLocal<Context> contextHolder = new ThreadLocal<>();
  127.     //Holds all EntranceNode. Each EntranceNode is associated with a distinct context name.
  128.     //以Context的name作为key,EntranceNode作为value缓存到HashMap中
  129.     private static volatile Map<String, DefaultNode> contextNameNodeMap = new HashMap<>();
  130.     private static final ReentrantLock LOCK = new ReentrantLock();
  131.     private static final Context NULL_CONTEXT = new NullContext();
  132.     ...
  133.    
  134.     //ContextUtil.trueEnter()方法会尝试从ThreadLocal获取一个Context对象
  135.     //如果获取不到,再创建一个Context对象然后放入ThreadLocal中
  136.     //入参name其实一般就是默认的Constants.CONTEXT_DEFAULT_NAME=sentinel_default_context
  137.     //由于当前线程可能会涉及创建多个Entry资源访问对象,所以trueEnter()方法需要注意并发问题
  138.     protected static Context trueEnter(String name, String origin) {
  139.         //从ThreadLocal中获取当前线程绑定的Context对象
  140.         Context context = contextHolder.get();
  141.         //如果当前线程还没绑定Context对象,则初始化Context对象并且与当前线程进行绑定
  142.         if (context == null) {
  143.             //首先要获取或创建Context对象所需要的EntranceNode对象,EntranceNode会负责统计名字相同的Context下的指标数据
  144.             //将全局缓存contextNameNodeMap赋值给一个临时变量localCacheNameMap
  145.             //因为后续会对contextNameNodeMap的内容进行修改,所以这里需要将原来的contextNameNodeMap复制一份出来
  146.             //从而避免后续对contextNameNodeMap的内容进行修改时,可能造成对接下来读取contextNameNodeMap内容的影响
  147.             Map<String, DefaultNode> localCacheNameMap = contextNameNodeMap;
  148.             //从缓存副本localCacheNameMap中获取EntranceNode
  149.             //这个name其实一般就是默认的sentinel_default_context
  150.             DefaultNode node = localCacheNameMap.get(name);
  151.             //如果获取的EntranceNode为空
  152.             if (node == null) {
  153.                 //为了防止缓存无限制地增长,导致内存占用过高,需要设置一个上限,只要超过上限,就直接返回NULL_CONTEXT
  154.                 if (localCacheNameMap.size() > Constants.MAX_CONTEXT_NAME_SIZE) {
  155.                     setNullContext();
  156.                     return NULL_CONTEXT;
  157.                 } else {
  158.                     //如果Context还没创建,缓存里也没有当前Context名称对应的EntranceNode,并且缓存数量尚未达到2000
  159.                     //那么就创建一个EntranceNode,创建EntranceNode时需要加锁,否则会有线程不安全问题
  160.                     //毕竟需要修改HashMap类型的contextNameNodeMap
  161.                     //通过加锁 + 缓存 + 写时复制更新缓存,避免并发情况下创建出多个EntranceNode对象
  162.                     //一个线程对应一个Context对象,多个线程对应多个Context对象
  163.                     //这些Context对象会使用ThreadLocal进行隔离,但它们的name默认都是sentinel_default_context
  164.                     //根据下面的代码逻辑:
  165.                     //多个线程(对应多个Context的name默认都是sentinel_default_context)会共用同一个EntranceNode
  166.                     //于是可知,多个Context对象会共用一个EntranceNode对象
  167.                     LOCK.lock();
  168.                     try {
  169.                         //从缓存中获取EntranceNode
  170.                         node = contextNameNodeMap.get(name);
  171.                         //对node进行Double Check
  172.                         //如果没获取到EntranceNode
  173.                         if (node == null) {
  174.                             if (contextNameNodeMap.size() > Constants.MAX_CONTEXT_NAME_SIZE) {
  175.                                 setNullContext();
  176.                                 return NULL_CONTEXT;
  177.                             } else {
  178.                                 //创建EntranceNode,缓存到contextNameNodeMap当中
  179.                                 node = new EntranceNode(new StringResourceWrapper(name, EntryType.IN), null);
  180.                                 //Add entrance node.
  181.                                 //将新创建的EntranceNode添加到ROOT中,ROOT就是每个Node的根结点
  182.                                 Constants.ROOT.addChild(node);
  183.                                 //写时复制,将新创建的EntranceNode添加到缓存中
  184.                                 Map<String, DefaultNode> newMap = new HashMap<>(contextNameNodeMap.size() + 1);
  185.                                 newMap.putAll(contextNameNodeMap);
  186.                                 newMap.put(name, node);
  187.                                 contextNameNodeMap = newMap;
  188.                             }
  189.                         }
  190.                     } finally {
  191.                         //解锁
  192.                         LOCK.unlock();
  193.                     }
  194.                 }
  195.             }
  196.             //此处可能会有多个线程同时执行到此处,并发创建多个Context对象
  197.             //但这是允许的,因为一个请求对应一个Context,一个请求对应一个线程,所以一个线程本来就需要创建一个Context对象
  198.             //初始化Context,将刚获取到或刚创建的EntranceNode放到Context的entranceNode属性中
  199.             context = new Context(node, name);
  200.             context.setOrigin(origin);
  201.             //将创建出来的Context对象放入ThreadLocal变量contextHolder中,实现Context对象与当前线程的绑定
  202.             contextHolder.set(context);
  203.         }
  204.         return context;
  205.     }
  206.     ...
  207. }
  208. public final class SlotChainProvider {
  209.     private static volatile SlotChainBuilder slotChainBuilder = null;
  210.     //The load and pick process is not thread-safe,
  211.     //but it's okay since the method should be only invoked via CtSph.lookProcessChain() under lock.
  212.     public static ProcessorSlotChain newSlotChain() {
  213.         //如果存在,则直接返回
  214.         if (slotChainBuilder != null) {
  215.             return slotChainBuilder.build();
  216.         }
  217.         //Resolve the slot chain builder SPI.
  218.         //通过SPI机制初始化SlotChainBuilder
  219.         slotChainBuilder = SpiLoader.of(SlotChainBuilder.class).loadFirstInstanceOrDefault();
  220.         if (slotChainBuilder == null) {
  221.             //Should not go through here.
  222.             RecordLog.warn("[SlotChainProvider] Wrong state when resolving slot chain builder, using default");
  223.             slotChainBuilder = new DefaultSlotChainBuilder();
  224.         } else {
  225.             RecordLog.info("[SlotChainProvider] Global slot chain builder resolved: {}", slotChainBuilder.getClass().getCanonicalName());
  226.         }
  227.         return slotChainBuilder.build();
  228.     }
  229.    
  230.     private SlotChainProvider() {
  231.    
  232.     }
  233. }
  234. @Spi(isDefault = true)
  235. public class DefaultSlotChainBuilder implements SlotChainBuilder {
  236.     @Override
  237.     public ProcessorSlotChain build() {
  238.         //创建一个DefaultProcessorSlotChain对象实例
  239.         ProcessorSlotChain chain = new DefaultProcessorSlotChain();
  240.         //通过SPI机制加载责任链的节点ProcessorSlot实现类
  241.         //然后按照@Spi注解的order属性进行排序并进行实例化
  242.         //最后将ProcessorSlot实例放到sortedSlotList中
  243.         List<ProcessorSlot> sortedSlotList = SpiLoader.of(ProcessorSlot.class).loadInstanceListSorted();
  244.         //遍历已排好序的ProcessorSlot集合
  245.         for (ProcessorSlot slot : sortedSlotList) {
  246.             //安全检查,防止业务系统也写了一个SPI文件,但没按规定继承AbstractLinkedProcessorSlot
  247.             if (!(slot instanceof AbstractLinkedProcessorSlot)) {
  248.                 RecordLog.warn("The ProcessorSlot(" + slot.getClass().getCanonicalName() + ") is not an instance of AbstractLinkedProcessorSlot, can't be added into ProcessorSlotChain");
  249.                 continue;
  250.             }
  251.             //调用DefaultProcessorSlotChain.addLast()方法构建单向链表
  252.             //将责任链的节点ProcessorSlot实例放入DefaultProcessorSlotChain中
  253.             chain.addLast((AbstractLinkedProcessorSlot<?>) slot);
  254.         }
  255.         //返回单向链表
  256.         return chain;
  257.     }
  258. }
复制代码
在DefaultSlotChainBuilder的build()方法中,从其初始化ProcessorSlotChain的逻辑可知,Entry的处理链的执行入口就是DefaultProcessorSlotChain的entry()方法。
 
当一个线程调用SphU的entry()方法创建完与接口相关的Entry对象后,就会调用DefaultProcessorSlotChain的entry()方法执行处理链节点的逻辑。因为NodeSelectorSlot是Entry的处理链ProcessorSlotChain的第一个节点,所以接着会调用NodeSelectorSlot的entry()方法。由于处理链中紧接着NodeSelectorSlot的下一个节点是ClusterBuilderSlot,所以执行完NodeSelectorSlot的entry()方法后,会接着执行ClusterBuilderSlot的entry()方法。
  1. public class DefaultProcessorSlotChain extends ProcessorSlotChain {
  2.     ...
  3.     @Override
  4.     public void entry(Context context, ResourceWrapper resourceWrapper, Object t, int count, boolean prioritized, Object... args) throws Throwable {
  5.         //默认情况下会调用处理链的第一个节点NodeSelectorSlot的transformEntry()方法
  6.         first.transformEntry(context, resourceWrapper, t, count, prioritized, args);
  7.     }
  8.     ...
  9. }
  10. public abstract class AbstractLinkedProcessorSlot<T> implements ProcessorSlot<T> {
  11.     ...
  12.     void transformEntry(Context context, ResourceWrapper resourceWrapper, Object o, int count, boolean prioritized, Object... args) throws Throwable {
  13.         T t = (T)o;
  14.         entry(context, resourceWrapper, t, count, prioritized, args);
  15.     }
  16.     ...
  17. }
复制代码
(2)NodeSelectorSlot的源码
NodeSelectorSlot和ClusterBuilderSlot会一起构建Context的资源调用树,资源调用树的作用其实就是用来统计资源的调用数据。
 
在一个Context对象实例的资源调用树上主要会有如下三类节点:DefaultNode、EntranceNode、ClusterNode,分别对应于:单机里的资源维度、接口维度、集群中的资源维度。
 
其中DefaultNode会统计名字相同的Context下的某个资源的调用数据,EntranceNode会统计名字相同的Context下的全部资源的调用数据,ClusterNode会统计某个资源在全部Context下的调用数据。
 
在执行NodeSelectorSlot的entry()方法时,首先会从缓存(NodeSelectorSlot.map属性)中获取一个DefaultNode对象。如果获取不到,再通过DCL机制创建一个DefaultNode对象并更新缓存。其中缓存的key是Context的name,value是DefaultNode对象。由于默认情况下多个线程对应的Context的name都相同,所以多个线程访问同一资源时使用的DefaultNode对象也一样。
 
在执行ClusterBuilderSlot的entry()方法时,首先会判断缓存是否为null,若是则创建一个ClusterNode对象,然后再将ClusterNode对象设置到DefaultNode对象的clusterNode属性中。
 
由DefaultNode、EntranceNode、ClusterNode构成的资源调用树:因为DefaultNode是和资源ResourceWrapper以及Context挂钩的,所以DefaultNode应该添加到EntranceNode中。因为ClusterNode和资源挂钩,而不和Context挂钩,所以ClusterNode应该添加到DefaultNode中。
 
具体的资源调用树构建源码如下:
  1. //This class will try to build the calling traces via:
  2. //adding a new DefaultNode if needed as the last child in the context.
  3. //the context's last node is the current node or the parent node of the context.
  4. //setting itself to the context current node.
  5. //It works as follow:
  6. //    ContextUtil.enter("entrance1", "appA");
  7. //    Entry nodeA = SphU.entry("nodeA");
  8. //    if (nodeA != null) {
  9. //        nodeA.exit();
  10. //    }
  11. //    ContextUtil.exit();
  12. //Above code will generate the following invocation structure in memory:
  13. //              machine-root
  14. //                  /
  15. //                 /
  16. //           EntranceNode1
  17. //               /
  18. //              /
  19. //        DefaultNode(nodeA)- - - - - -> ClusterNode(nodeA);
  20. //Here the EntranceNode represents "entrance1" given by ContextUtil.enter("entrance1", "appA").
  21. //Both DefaultNode(nodeA) and ClusterNode(nodeA) holds statistics of "nodeA", which is given by SphU.entry("nodeA").
  22. //The ClusterNode is uniquely identified by the ResourceId;
  23. //The DefaultNode is identified by both the resource id and {@link Context}.
  24. //In other words, one resource id will generate multiple DefaultNode for each distinct context,
  25. //but only one ClusterNode.
  26. //the following code shows one resource id in two different context:
  27. //    ContextUtil.enter("entrance1", "appA");
  28. //    Entry nodeA = SphU.entry("nodeA");
  29. //    if (nodeA != null) {
  30. //        nodeA.exit();
  31. //    }
  32. //    ContextUtil.exit();
  33. //    ContextUtil.enter("entrance2", "appA");
  34. //    nodeA = SphU.entry("nodeA");
  35. //    if (nodeA != null) {
  36. //        nodeA.exit();
  37. //    }
  38. //    ContextUtil.exit();
  39. //Above code will generate the following invocation structure in memory:
  40. //                  machine-root
  41. //                  /         \
  42. //                 /           \
  43. //         EntranceNode1   EntranceNode2
  44. //               /               \
  45. //              /                 \
  46. //      DefaultNode(nodeA)   DefaultNode(nodeA)
  47. //             |                    |
  48. //             +- - - - - - - - - - +- - - - - - -> ClusterNode(nodeA);
  49. //As we can see, two DefaultNode are created for "nodeA" in two context,
  50. //but only one ClusterNode is created.
  51. //We can also check this structure by calling: http://localhost:8719/tree?type=root
  52. @Spi(isSingleton = false, order = Constants.ORDER_NODE_SELECTOR_SLOT)
  53. public class NodeSelectorSlot extends AbstractLinkedProcessorSlot<Object> {
  54.     //DefaultNodes of the same resource in different context.
  55.     //缓存map以Context的name为key,DefaultNode为value
  56.     //由于默认情况下多个线程对应的Context的name都相同,所以多个线程访问资源时使用的DefaultNode也一样
  57.     private volatile Map<String, DefaultNode> map = new HashMap<String, DefaultNode>(10);
  58.    
  59.     @Override
  60.     public void entry(Context context, ResourceWrapper resourceWrapper, Object obj, int count, boolean prioritized, Object... args) throws Throwable {
  61.         //It's interesting that we use context name rather resource name as the map key.
  62.         //Remember that same resource will share the same ProcessorSlotChain globally, no matter in which context.
  63.         //Same resource is that ResourceWrapper#equals(Object).
  64.         //So if code goes into entry(Context, ResourceWrapper, DefaultNode, int, Object...),
  65.         //the resource name must be same but context name may not.
  66.       
  67.         //If we use SphU.entry(String resource)} to enter same resource in different context,
  68.         //using context name as map key can distinguish the same resource.
  69.         //In this case, multiple DefaultNodes will be created of the same resource name,
  70.         //for every distinct context (different context name) each.
  71.       
  72.         //Consider another question. One resource may have multiple DefaultNode,
  73.         //so what is the fastest way to get total statistics of the same resource?
  74.         //The answer is all DefaultNodes with same resource name share one ClusterNode.
  75.         //See ClusterBuilderSlot for detail.
  76.         //先从缓存中获取
  77.         DefaultNode node = map.get(context.getName());
  78.         if (node == null) {
  79.             //使用DCL机制,即Double Check + Lock机制
  80.             synchronized (this) {
  81.                 node = map.get(context.getName());
  82.                 if (node == null) {
  83.                     //每个线程访问Entry时,都会调用CtSph.entry()方法创建一个ResourceWrapper对象
  84.                     //下面根据ResourceWrapper创建一个DefaultNode对象
  85.                     node = new DefaultNode(resourceWrapper, null);
  86.                     //写时复制更新缓存map
  87.                     HashMap<String, DefaultNode> cacheMap = new HashMap<String, DefaultNode>(map.size());
  88.                     cacheMap.putAll(map);
  89.                     cacheMap.put(context.getName(), node);
  90.                     map = cacheMap;
  91.                     //Build invocation tree
  92.                     //首先会调用context.getLastNode()方法,获取到的是Context.entranceNode属性即一个EntranceNode对象
  93.                     //EntranceNode对象是在执行ContextUtil.trueEnter()方法创建Context对象实例时添加到Context对象中的
  94.                     //然后会将刚创建的DefaultNode对象添加到EntranceNode对象的childList列表中
  95.                     ((DefaultNode) context.getLastNode()).addChild(node);
  96.                 }
  97.             }
  98.         }
  99.         //设置Context的curNode属性为当前获取到或新创建的DefaultNode对象
  100.         context.setCurNode(node);
  101.         //触发执行下一个ProcessorSlot,即ClusterBuilderSlot
  102.         fireEntry(context, resourceWrapper, node, count, prioritized, args);
  103.     }
  104.    
  105.     @Override
  106.     public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
  107.         fireExit(context, resourceWrapper, count, args);
  108.     }
  109. }
  110. //This slot maintains resource running statistics (response time, qps, thread count, exception),
  111. //and a list of callers as well which is marked by ContextUtil.enter(String origin).
  112. //One resource has only one cluster node, while one resource can have multiple default nodes.
  113. @Spi(isSingleton = false, order = Constants.ORDER_CLUSTER_BUILDER_SLOT)
  114. public class ClusterBuilderSlot extends AbstractLinkedProcessorSlot<DefaultNode> {
  115.     //Remember that same resource will share the same ProcessorSlotChain globally, no matter in which context.
  116.     //Same resource is that ResourceWrapper#equals(Object).
  117.     //So if code goes into entry(Context, ResourceWrapper, DefaultNode, int, boolean, Object...),
  118.     //the resource name must be same but context name may not.
  119.    
  120.     //To get total statistics of the same resource in different context,
  121.     //same resource shares the same ClusterNode} globally.
  122.     //All ClusterNodes are cached in this map.
  123.     //The longer the application runs, the more stable this mapping will become.
  124.     //so we don't concurrent map but a lock.
  125.     //as this lock only happens at the very beginning while concurrent map will hold the lock all the time.
  126.     private static volatile Map<ResourceWrapper, ClusterNode> clusterNodeMap = new HashMap<>();
  127.     private static final Object lock = new Object();
  128.     private volatile ClusterNode clusterNode = null;
  129.     @Override
  130.     public void entry(Context context, ResourceWrapper resourceWrapper, DefaultNode node, int count, boolean prioritized, Object... args) throws Throwable {
  131.         if (clusterNode == null) {
  132.             //使用DCL机制,即Double Check + Lock机制
  133.             synchronized (lock) {
  134.                 if (clusterNode == null) {
  135.                     //Create the cluster node.
  136.                     //创建ClusterNode对象
  137.                     clusterNode = new ClusterNode(resourceWrapper.getName(), resourceWrapper.getResourceType());
  138.                     HashMap<ResourceWrapper, ClusterNode> newMap = new HashMap<>(Math.max(clusterNodeMap.size(), 16));
  139.                     newMap.putAll(clusterNodeMap);
  140.                     newMap.put(node.getId(), clusterNode);
  141.                     clusterNodeMap = newMap;
  142.                 }
  143.             }
  144.         }
  145.         
  146.         //设置DefaultNode的clusterNode属性为获取到的ClusterNode对象
  147.         node.setClusterNode(clusterNode);
  148.         //if context origin is set, we should get or create a new {@link Node} of the specific origin.
  149.         if (!"".equals(context.getOrigin())) {
  150.             Node originNode = node.getClusterNode().getOrCreateOriginNode(context.getOrigin());
  151.             context.getCurEntry().setOriginNode(originNode);
  152.         }
  153.         //执行下一个ProcessorSlot
  154.         fireEntry(context, resourceWrapper, node, count, prioritized, args);
  155.     }
  156.     @Override
  157.     public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
  158.         fireExit(context, resourceWrapper, count, args);
  159.     }
  160.     ...
  161. }
复制代码
(3)Context对象中存储的资源调用树总结
其实Context对象的属性entranceNode就代表了一棵资源调用树。
 
首先,在调用ContextUtil的trueEnter()方法创建Context对象实例时,便会创建一个EntranceNode对象并赋值给Context的entranceNode属性,以及调用Constants.ROOT的addChild()方法,将这个EntranceNode对象放入Constants.ROOT的childList列表中。
 
然后,执行NodeSelectorSlot的entry()方法时,便会创建一个DefaultNode对象。该DefaultNode对象会被添加到Context.entranceNode的childList列表中,也就是前面创建的EntranceNode对象的childList列表中。
 
接着,执行ClusterBuilderSlot的entry()方法时,便会创建一个ClusterNode对象,该ClusterNode对象会赋值给前面DefaultNode对象中的clusterNode属性。
 
至此,便构建完Context下的资源调用树了。Constants.ROOT的childList里会存放多个EntranceNode对象,每个EntranceNode对象的childList里会存放多个DefaultNode对象,而每个DefaultNode对象会指向一个ClusterNode对象。
  1. //This class holds metadata of current invocation:
  2. //the EntranceNode: the root of the current invocation tree.
  3. //the current Entry: the current invocation point.
  4. //the current Node: the statistics related to the Entry.
  5. //the origin: The origin is useful when we want to control different invoker/consumer separately.
  6. //Usually the origin could be the Service Consumer's app name or origin IP.
  7. //Each SphU.entry() or SphO.entry() should be in a Context,
  8. //if we don't invoke ContextUtil.enter() explicitly, DEFAULT context will be used.
  9. //A invocation tree will be created if we invoke SphU.entry() multi times in the same context.
  10. //Same resource in different context will count separately, see NodeSelectorSlot.
  11. public class Context {
  12.     //Context name.
  13.     private final String name;
  14.     //The entrance node of current invocation tree.
  15.     private DefaultNode entranceNode;
  16.     //Current processing entry.
  17.     private Entry curEntry;
  18.     //The origin of this context (usually indicate different invokers, e.g. service consumer name or origin IP).
  19.     private String origin = "";
  20.     ...
  21.     public Context(DefaultNode entranceNode, String name) {
  22.         this(name, entranceNode, false);
  23.     }
  24.    
  25.     public Context(String name, DefaultNode entranceNode, boolean async) {
  26.         this.name = name;
  27.         this.entranceNode = entranceNode;
  28.         this.async = async;
  29.     }
  30.    
  31.     //Get the parent Node of the current.
  32.     public Node getLastNode() {
  33.         if (curEntry != null && curEntry.getLastNode() != null) {
  34.             return curEntry.getLastNode();
  35.         } else {
  36.             return entranceNode;
  37.         }
  38.     }
  39.     ...
  40. }
  41. public class ContextUtil {
  42.     //以Context的name作为key,EntranceNode作为value缓存所有的EntranceNode到HashMap中
  43.     private static volatile Map<String, DefaultNode> contextNameNodeMap = new HashMap<>();
  44.     ...
  45.     protected static Context trueEnter(String name, String origin) {
  46.         ...
  47.         //从缓存中获取EntranceNode
  48.         DefaultNode node = contextNameNodeMap.get(name);
  49.         ...
  50.         //创建EntranceNode,缓存到contextNameNodeMap当中
  51.         node = new EntranceNode(new StringResourceWrapper(name, EntryType.IN), null);
  52.         //将新创建的EntranceNode添加到ROOT中,ROOT就是每个Node的根结点
  53.         Constants.ROOT.addChild(node);
  54.         ...
  55.         //初始化Context,将刚获取到或刚创建的EntranceNode放到Context的entranceNode属性中
  56.         context = new Context(node, name);
  57.         ...
  58.     }
  59.     ...
  60. }
  61. public final class Constants {
  62.     ...
  63.     //Global ROOT statistic node that represents the universal parent node.
  64.     public final static DefaultNode ROOT = new EntranceNode(
  65.         new StringResourceWrapper(ROOT_ID, EntryType.IN),
  66.         new ClusterNode(ROOT_ID, ResourceTypeConstants.COMMON)
  67.     );
  68.     ...
  69. }
  70. //A Node used to hold statistics for specific resource name in the specific context.
  71. //Each distinct resource in each distinct Context will corresponding to a DefaultNode.
  72. //This class may have a list of sub DefaultNodes.
  73. //Child nodes will be created when calling SphU.entry() or SphO.entry() multiple times in the same Context.
  74. public class DefaultNode extends StatisticNode {
  75.     //The resource associated with the node.
  76.     private ResourceWrapper id;
  77.     //The list of all child nodes.
  78.     private volatile Set<Node> childList = new HashSet<>();
  79.     //Associated cluster node.
  80.     private ClusterNode clusterNode;
  81.     ...
  82.    
  83.     //Add child node to current node.
  84.     public void addChild(Node node) {
  85.         if (node == null) {
  86.             RecordLog.warn("Trying to add null child to node <{}>, ignored", id.getName());
  87.             return;
  88.         }
  89.         if (!childList.contains(node)) {
  90.             synchronized (this) {
  91.                 if (!childList.contains(node)) {
  92.                     Set<Node> newSet = new HashSet<>(childList.size() + 1);
  93.                     newSet.addAll(childList);
  94.                     newSet.add(node);
  95.                     childList = newSet;
  96.                 }
  97.             }
  98.             RecordLog.info("Add child <{}> to node <{}>", ((DefaultNode)node).id.getName(), id.getName());
  99.         }
  100.     }
  101.    
  102.     //Reset the child node list.
  103.     public void removeChildList() {
  104.         this.childList = new HashSet<>();
  105.     }
  106.     ...
  107. }
  108. @Spi(isSingleton = false, order = Constants.ORDER_NODE_SELECTOR_SLOT)
  109. public class NodeSelectorSlot extends AbstractLinkedProcessorSlot<Object> {
  110.     //DefaultNodes of the same resource in different context.
  111.     //缓存map以Context的name为key,DefaultNode为value
  112.     //由于默认情况下多个线程对应的Context的name都相同,所以多个线程访问资源时使用的DefaultNode也一样
  113.     private volatile Map<String, DefaultNode> map = new HashMap<String, DefaultNode>(10);
  114.     ...
  115.    
  116.     @Override
  117.     public void entry(Context context, ResourceWrapper resourceWrapper, Object obj, int count, boolean prioritized, Object... args) throws Throwable {
  118.         ...
  119.         //先从缓存中获取
  120.         DefaultNode node = map.get(context.getName());
  121.         ...
  122.         //下面根据ResourceWrapper创建一个DefaultNode对象
  123.         node = new DefaultNode(resourceWrapper, null);
  124.         ...
  125.         //Build invocation tree
  126.         //首先会调用context.getLastNode()方法,获取到的是Context.entranceNode属性即一个EntranceNode对象
  127.         //EntranceNode对象是在执行ContextUtil.trueEnter()方法创建Context对象实例时添加到Context对象中的
  128.         //然后会将刚创建的DefaultNode对象添加到EntranceNode对象的childList列表中
  129.         ((DefaultNode) context.getLastNode()).addChild(node);
  130.         ...
  131.         //执行下一个ProcessorSlot
  132.         fireEntry(context, resourceWrapper, node, count, prioritized, args);
  133.     }
  134.     ...
  135. }
  136. @Spi(isSingleton = false, order = Constants.ORDER_CLUSTER_BUILDER_SLOT)
  137. public class ClusterBuilderSlot extends AbstractLinkedProcessorSlot<DefaultNode> {
  138.     ...
  139.     private volatile ClusterNode clusterNode = null;
  140.    
  141.     @Override
  142.     public void entry(Context context, ResourceWrapper resourceWrapper, DefaultNode node, int count, boolean prioritized, Object... args) throws Throwable {
  143.         ...
  144.         //创建ClusterNode对象
  145.         clusterNode = new ClusterNode(resourceWrapper.getName(), resourceWrapper.getResourceType());  
  146.         ...
  147.         //设置DefaultNode的clusterNode属性为获取到的ClusterNode对象
  148.         node.setClusterNode(clusterNode);
  149.         ...
  150.         //执行下一个ProcessorSlot
  151.         fireEntry(context, resourceWrapper, node, count, prioritized, args);
  152.     }
  153.     ...
  154. }
  155. //资源调用树的示例如下所示:
  156. //                  machine-root
  157. //                  /         \
  158. //                 /           \
  159. //         EntranceNode1   EntranceNode2
  160. //               /               \
  161. //              /                 \
  162. //      DefaultNode(nodeA)   DefaultNode(nodeA)
  163. //             |                    |
  164. //             +- - - - - - - - - - +- - - - - - -> ClusterNode(nodeA);
  165. //其中,machine-root中的childList里会有很多个EntranceNode对象
  166. //EntranceNode对象中的childList里又会有很多个DefaultNode对象
  167. //每个DefaultNode对象下都会指向一个ClusterNode对象
复制代码
一些对应关系的梳理总结:
一个线程对应一个ResourceWrapper对象实例,一个线程对应一个Context对象实例。如果ResourceWrapper对象相同,则会共用一个ProcessorSlotChain实例。如果ResourceWrapper对象相同,则也会共用一个ClusterNode实例。如果Context对象的名字相同,则会共用一个EntranceNode对象实例。如果Context对象的名字相同,则也会共用一个DefaultNode对象实例。
  1. //每个请求对应一个线程,每个线程绑定一个Context,所以每个请求对应一个Context
  2. private static ThreadLocal<Context> contextHolder = new ThreadLocal<>();
  3. //以Context的name作为key,EntranceNode作为value缓存所有的EntranceNode到HashMap中
  4. private static volatile Map<String, EntranceNode> contextNameNodeMap = new HashMap<>();
  5. //Same resource will share the same ProcessorSlotChain}, no matter in which Context.
  6. //Same resource is that ResourceWrapper#equals(Object).
  7. private static volatile Map<ResourceWrapper, ProcessorSlotChain> chainMap = new HashMap<ResourceWrapper, ProcessorSlotChain>();
  8. //DefaultNodes of the same resource in different context.
  9. //以Context的name作为key,DefaultNode作为value
  10. //由于默认情况下多个线程对应的Context的name都相同,所以多个线程访问资源时使用的DefaultNode也一样
  11. private volatile Map<String, DefaultNode> map = new HashMap<String, DefaultNode>(10);
  12.    
  13. //To get total statistics of the same resource in different context,
  14. //same resource shares the same ClusterNode globally.
  15. //All ClusterNodes are cached in this map.
  16. private static volatile Map<ResourceWrapper, ClusterNode> clusterNodeMap = new HashMap<>();
复制代码
 
2.LogSlot和StatisticSlot采集资源的数据
(1)LogSlot的源码
(2)StatisticSlot的源码
(3)记录资源在不同维度下的调用数据
 
(1)LogSlot的源码
LogSlot用于记录异常请求日志,以便于故障排查。也就是当出现BlockException异常时,调用EagleEyeLogUtil的log()方法将日志写到sentinel-block.log文件中。
  1. //A ProcessorSlot that is response for logging block exceptions to provide concrete logs for troubleshooting.
  2. @Spi(order = Constants.ORDER_LOG_SLOT)
  3. public class LogSlot extends AbstractLinkedProcessorSlot<DefaultNode> {
  4.     @Override
  5.     public void entry(Context context, ResourceWrapper resourceWrapper, DefaultNode obj, int count, boolean prioritized, Object... args) throws Throwable {
  6.         try {
  7.             //调用下一个ProcessorSlot
  8.             fireEntry(context, resourceWrapper, obj, count, prioritized, args);
  9.         } catch (BlockException e) {
  10.             //被流控或者熔断降级后打印log日志
  11.             EagleEyeLogUtil.log(resourceWrapper.getName(), e.getClass().getSimpleName(), e.getRuleLimitApp(), context.getOrigin(), e.getRule().getId(), count);
  12.             throw e;
  13.         } catch (Throwable e) {
  14.             RecordLog.warn("Unexpected entry exception", e);
  15.         }
  16.     }
  17.     @Override
  18.     public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
  19.         try {
  20.             //调用下一个ProcessorSlot
  21.             fireExit(context, resourceWrapper, count, args);
  22.         } catch (Throwable e) {
  23.             RecordLog.warn("Unexpected entry exit exception", e);
  24.         }
  25.     }
  26. }
  27. public class EagleEyeLogUtil {
  28.     public static final String FILE_NAME = "sentinel-block.log";
  29.     private static StatLogger statLogger;
  30.     static {
  31.         String path = LogBase.getLogBaseDir() + FILE_NAME;
  32.         statLogger = EagleEye.statLoggerBuilder("sentinel-block-log")
  33.             .intervalSeconds(1)
  34.             .entryDelimiter('|')
  35.             .keyDelimiter(',')
  36.             .valueDelimiter(',')
  37.             .maxEntryCount(6000)
  38.             .configLogFilePath(path)
  39.             .maxFileSizeMB(300)
  40.             .maxBackupIndex(3)
  41.             .buildSingleton();
  42.     }
  43.    
  44.     public static void log(String resource, String exceptionName, String ruleLimitApp, String origin, Long ruleId, int count) {
  45.         String ruleIdString = StringUtil.EMPTY;
  46.         if (ruleId != null) {
  47.             ruleIdString = String.valueOf(ruleId);
  48.         }
  49.         statLogger.stat(resource, exceptionName, ruleLimitApp, origin, ruleIdString).count(count);
  50.     }
  51. }
复制代码
(2)StatisticSlot的源码
StatisticSlot用于统计资源的调用数据,如请求成功数、请求失败数、响应时间等。
 
注意:开始对请求进行规则验证时,需要调用SphU的entry()方法。完成对请求的规则验证后,也需要调用Entry的exit()方法。
  1. //A processor slot that dedicates to real time statistics.
  2. //When entering this slot, we need to separately count the following information:
  3. //ClusterNode: total statistics of a cluster node of the resource ID.
  4. //Origin node: statistics of a cluster node from different callers/origins.
  5. //DefaultNode: statistics for specific resource name in the specific context.
  6. //Finally, the sum statistics of all entrances.
  7. @Spi(order = Constants.ORDER_STATISTIC_SLOT)
  8. public class StatisticSlot extends AbstractLinkedProcessorSlot<DefaultNode> {
  9.     @Override
  10.     public void entry(Context context, ResourceWrapper resourceWrapper, DefaultNode node, int count, boolean prioritized, Object... args) throws Throwable {
  11.         try {
  12.             //Do some checking.
  13.             //执行下一个ProcessorSlot,先进行规则验证等
  14.             fireEntry(context, resourceWrapper, node, count, prioritized, args);
  15.             //Request passed, add thread count and pass count.
  16.             //如果通过了后面ProcessorSlot的验证
  17.             //则将处理当前资源resourceWrapper的线程数 + 1 以及 将对当前资源resourceWrapper的成功请求数 + 1
  18.             node.increaseThreadNum();
  19.             node.addPassRequest(count);
  20.             if (context.getCurEntry().getOriginNode() != null) {
  21.                 //Add count for origin node.
  22.                 context.getCurEntry().getOriginNode().increaseThreadNum();
  23.                 context.getCurEntry().getOriginNode().addPassRequest(count);
  24.             }
  25.             if (resourceWrapper.getEntryType() == EntryType.IN) {
  26.                 //Add count for global inbound entry node for global statistics.
  27.                 Constants.ENTRY_NODE.increaseThreadNum();
  28.                 Constants.ENTRY_NODE.addPassRequest(count);
  29.             }
  30.             //Handle pass event with registered entry callback handlers.
  31.             for (ProcessorSlotEntryCallback<DefaultNode> handler : StatisticSlotCallbackRegistry.getEntryCallbacks()) {
  32.                 handler.onPass(context, resourceWrapper, node, count, args);
  33.             }
  34.         } catch (PriorityWaitException ex) {
  35.             node.increaseThreadNum();
  36.             if (context.getCurEntry().getOriginNode() != null) {
  37.                 //Add count for origin node.
  38.                 context.getCurEntry().getOriginNode().increaseThreadNum();
  39.             }
  40.             if (resourceWrapper.getEntryType() == EntryType.IN) {
  41.                 //Add count for global inbound entry node for global statistics.
  42.                 Constants.ENTRY_NODE.increaseThreadNum();
  43.             }
  44.            
  45.             //Handle pass event with registered entry callback handlers.
  46.             for (ProcessorSlotEntryCallback<DefaultNode> handler : StatisticSlotCallbackRegistry.getEntryCallbacks()) {
  47.                 handler.onPass(context, resourceWrapper, node, count, args);
  48.             }
  49.         } catch (BlockException e) {//捕获BlockException
  50.             //Blocked, set block exception to current entry.
  51.             context.getCurEntry().setBlockError(e);
  52.             //Add block count.
  53.             //如果规则验证失败,则将BlockQps+1
  54.             node.increaseBlockQps(count);
  55.             if (context.getCurEntry().getOriginNode() != null) {
  56.                 context.getCurEntry().getOriginNode().increaseBlockQps(count);
  57.             }
  58.             if (resourceWrapper.getEntryType() == EntryType.IN) {
  59.                 //Add count for global inbound entry node for global statistics.
  60.                 Constants.ENTRY_NODE.increaseBlockQps(count);
  61.             }
  62.             //Handle block event with registered entry callback handlers.
  63.             for (ProcessorSlotEntryCallback<DefaultNode> handler : StatisticSlotCallbackRegistry.getEntryCallbacks()) {
  64.                 handler.onBlocked(e, context, resourceWrapper, node, count, args);
  65.             }
  66.             throw e;
  67.         } catch (Throwable e) {
  68.             //Unexpected internal error, set error to current entry.
  69.             context.getCurEntry().setError(e);
  70.             throw e;
  71.         }
  72.     }
  73.    
  74.     //开始对请求进行规则验证时,需要调用SphU.entry()方法
  75.     //完成对请求的规则验证后,也需要调用Entry.exit()方法
  76.     @Override
  77.     public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
  78.         Node node = context.getCurNode();
  79.         if (context.getCurEntry().getBlockError() == null) {
  80.             //Calculate response time (use completeStatTime as the time of completion).
  81.             //获取系统当前时间
  82.             long completeStatTime = TimeUtil.currentTimeMillis();
  83.             context.getCurEntry().setCompleteTimestamp(completeStatTime);
  84.             //计算响应时间 = 系统当前事件 - 根据资源resourceWrapper创建Entry资源访问对象时的时间
  85.             long rt = completeStatTime - context.getCurEntry().getCreateTimestamp();
  86.             Throwable error = context.getCurEntry().getError();
  87.             //Record response time and success count.
  88.             //记录响应时间等信息
  89.             recordCompleteFor(node, count, rt, error);
  90.             recordCompleteFor(context.getCurEntry().getOriginNode(), count, rt, error);
  91.             if (resourceWrapper.getEntryType() == EntryType.IN) {
  92.                 recordCompleteFor(Constants.ENTRY_NODE, count, rt, error);
  93.             }
  94.         }
  95.         //Handle exit event with registered exit callback handlers.
  96.         Collection<ProcessorSlotExitCallback> exitCallbacks = StatisticSlotCallbackRegistry.getExitCallbacks();
  97.         for (ProcessorSlotExitCallback handler : exitCallbacks) {
  98.             handler.onExit(context, resourceWrapper, count, args);
  99.         }
  100.       
  101.         fireExit(context, resourceWrapper, count, args);
  102.     }
  103.     private void recordCompleteFor(Node node, int batchCount, long rt, Throwable error) {
  104.         if (node == null) {
  105.             return;
  106.         }
  107.         node.addRtAndSuccess(rt, batchCount);
  108.         node.decreaseThreadNum();
  109.         if (error != null && !(error instanceof BlockException)) {
  110.             node.increaseExceptionQps(batchCount);
  111.         }
  112.     }
  113. }
复制代码
(3)记录资源在不同维度下的调用数据
一.如何统计单机里某个资源的调用数据
二.如何统计所有资源的调用数据即接口调用数据
三.如何统计集群中某个资源的调用数据
 
一.如何统计单机里某个资源的调用数据
由于DefaultNode会统计名字相同的Context下的某个资源的调用数据,它是按照单机里的资源维度进行调用数据统计的,所以在StatisticSlot的entry()方法中,会调用DefaultNode的方法来进行统计。
  1. //A Node used to hold statistics for specific resource name in the specific context.
  2. //Each distinct resource in each distinct Context will corresponding to a DefaultNode.
  3. //This class may have a list of sub DefaultNodes.
  4. //Child nodes will be created when calling SphU.entry() or SphO.entry() multiple times in the same Context.
  5. public class DefaultNode extends StatisticNode {
  6.     //The resource associated with the node.
  7.     private ResourceWrapper id;
  8.     //Associated cluster node.
  9.     private ClusterNode clusterNode;
  10.     ...
  11.    
  12.     @Override
  13.     public void increaseThreadNum() {
  14.         super.increaseThreadNum();
  15.         this.clusterNode.increaseThreadNum();
  16.     }
  17.    
  18.     @Override
  19.     public void addPassRequest(int count) {
  20.         super.addPassRequest(count);
  21.         this.clusterNode.addPassRequest(count);
  22.     }
  23.    
  24.     @Override
  25.     public void increaseBlockQps(int count) {
  26.         super.increaseBlockQps(count);
  27.         this.clusterNode.increaseBlockQps(count);
  28.     }
  29.    
  30.     @Override
  31.     public void addRtAndSuccess(long rt, int successCount) {
  32.         super.addRtAndSuccess(rt, successCount);
  33.         this.clusterNode.addRtAndSuccess(rt, successCount);
  34.     }
  35.    
  36.     @Override
  37.     public void decreaseThreadNum() {
  38.         super.decreaseThreadNum();
  39.         this.clusterNode.decreaseThreadNum();
  40.     }
  41.     ...
  42. }
  43. public class StatisticNode implements Node {
  44.     //The counter for thread count.
  45.     private LongAdder curThreadNum = new LongAdder();
  46.     //Holds statistics of the recent INTERVAL milliseconds.
  47.     //The INTERVAL is divided into time spans by given sampleCount.
  48.     private transient volatile Metric rollingCounterInSecond = new ArrayMetric(SampleCountProperty.SAMPLE_COUNT, IntervalProperty.INTERVAL);
  49.     //Holds statistics of the recent 60 seconds.
  50.     //The windowLengthInMs is deliberately set to 1000 milliseconds,
  51.     //meaning each bucket per second, in this way we can get accurate statistics of each second.
  52.     private transient Metric rollingCounterInMinute = new ArrayMetric(60, 60 * 1000, false);
  53.     ...
  54.    
  55.     @Override
  56.     public void increaseThreadNum() {
  57.         curThreadNum.increment();
  58.     }
  59.    
  60.     @Override
  61.     public void addPassRequest(int count) {
  62.         rollingCounterInSecond.addPass(count);
  63.         rollingCounterInMinute.addPass(count);
  64.     }
  65.    
  66.     @Override
  67.     public void increaseBlockQps(int count) {
  68.         rollingCounterInSecond.addBlock(count);
  69.         rollingCounterInMinute.addBlock(count);
  70.     }
  71.    
  72.     @Override
  73.     public void addRtAndSuccess(long rt, int successCount) {
  74.         rollingCounterInSecond.addSuccess(successCount);
  75.         rollingCounterInSecond.addRT(rt);
  76.         rollingCounterInMinute.addSuccess(successCount);
  77.         rollingCounterInMinute.addRT(rt);
  78.     }
  79.    
  80.     @Override
  81.     public void decreaseThreadNum() {
  82.         curThreadNum.decrement();
  83.     }
  84.     ...
  85. }
复制代码
二.如何统计所有资源的调用数据即接口调用数据
由于EntranceNode会统计名字相同的Context下的全部资源的调用数据,它是按接口维度来统计调用数据的,即统计接口下所有资源的调用情况,所以可以通过遍历EntranceNode的childList来统计接口的调用数据。
  1. //A Node represents the entrance of the invocation tree.
  2. //One Context will related to a EntranceNode,
  3. //which represents the entrance of the invocation tree.
  4. //New EntranceNode will be created if current context does't have one.
  5. //Note that same context name will share same EntranceNode globally.
  6. public class EntranceNode extends DefaultNode {
  7.     public EntranceNode(ResourceWrapper id, ClusterNode clusterNode) {
  8.         super(id, clusterNode);
  9.     }
  10.    
  11.     @Override
  12.     public double avgRt() {
  13.         double total = 0;
  14.         double totalQps = 0;
  15.         for (Node node : getChildList()) {
  16.             total += node.avgRt() * node.passQps();
  17.             totalQps += node.passQps();
  18.         }
  19.         return total / (totalQps == 0 ? 1 : totalQps);
  20.     }
  21.    
  22.     @Override
  23.     public double blockQps() {
  24.         double blockQps = 0;
  25.         for (Node node : getChildList()) {
  26.             blockQps += node.blockQps();
  27.         }
  28.         return blockQps;
  29.     }
  30.    
  31.     @Override
  32.     public long blockRequest() {
  33.         long r = 0;
  34.         for (Node node : getChildList()) {
  35.             r += node.blockRequest();
  36.         }
  37.         return r;
  38.     }
  39.    
  40.     @Override
  41.     public int curThreadNum() {
  42.         int r = 0;
  43.         for (Node node : getChildList()) {
  44.             r += node.curThreadNum();
  45.         }
  46.         return r;
  47.     }
  48.    
  49.     @Override
  50.     public double totalQps() {
  51.         double r = 0;
  52.         for (Node node : getChildList()) {
  53.             r += node.totalQps();
  54.         }
  55.         return r;
  56.     }
  57.    
  58.     @Override
  59.     public double successQps() {
  60.         double r = 0;
  61.         for (Node node : getChildList()) {
  62.             r += node.successQps();
  63.         }
  64.         return r;
  65.     }
  66.    
  67.     @Override
  68.     public double passQps() {
  69.         double r = 0;
  70.         for (Node node : getChildList()) {
  71.             r += node.passQps();
  72.         }
  73.         return r;
  74.     }
  75.    
  76.     @Override
  77.     public long totalRequest() {
  78.         long r = 0;
  79.         for (Node node : getChildList()) {
  80.             r += node.totalRequest();
  81.         }
  82.         return r;
  83.     }
  84.    
  85.     @Override
  86.     public long totalPass() {
  87.         long r = 0;
  88.         for (Node node : getChildList()) {
  89.             r += node.totalPass();
  90.         }
  91.         return r;
  92.     }
  93. }
复制代码
三.如何统计集群中某个资源的调用数据
由于ClusterNode会统计某个资源在全部Context下的调用数据,它是按照集群中的资源维度进行调用数据统计的,而StatisticSlot的entry()调用DefaultNode的方法统计单机下的资源时,会顺便调用ClusterNode的方法来统计集群下的资源调用,所以通过ClusterNode就可以获取集群中某个资源的调用数据。
  1. //A Node used to hold statistics for specific resource name in the specific context.
  2. //Each distinct resource in each distinct Context will corresponding to a DefaultNode.
  3. //This class may have a list of sub DefaultNodes.
  4. //Child nodes will be created when calling SphU.entry() or SphO.entry() multiple times in the same Context.
  5. public class DefaultNode extends StatisticNode {
  6.     //The resource associated with the node.
  7.     private ResourceWrapper id;
  8.     //Associated cluster node.
  9.     private ClusterNode clusterNode;
  10.     ...
  11.    
  12.     @Override
  13.     public void increaseThreadNum() {
  14.         super.increaseThreadNum();
  15.         this.clusterNode.increaseThreadNum();
  16.     }
  17.    
  18.     @Override
  19.     public void addPassRequest(int count) {
  20.         super.addPassRequest(count);
  21.         this.clusterNode.addPassRequest(count);
  22.     }
  23.    
  24.     @Override
  25.     public void increaseBlockQps(int count) {
  26.         super.increaseBlockQps(count);
  27.         this.clusterNode.increaseBlockQps(count);
  28.     }
  29.    
  30.     @Override
  31.     public void addRtAndSuccess(long rt, int successCount) {
  32.         super.addRtAndSuccess(rt, successCount);
  33.         this.clusterNode.addRtAndSuccess(rt, successCount);
  34.     }
  35.    
  36.     @Override
  37.     public void decreaseThreadNum() {
  38.         super.decreaseThreadNum();
  39.         this.clusterNode.decreaseThreadNum();
  40.     }
  41.     ...
  42. }
复制代码
 
3.Sentinel监听器模式的规则对象与规则管理
(1)Sentinel的规则对象
(2)Sentinel的规则管理
 
(1)Sentinel的规则对象
一.Sentinel中的规则其实就是配置
二.规则接口Rule和抽象父类AbstractRule及其具体实现类
 
一.Sentinel中的规则其实就是配置
黑白名单控制规则:例如需要设置一份配置,确定哪些请求属于黑名单、哪些请求属于白名单,那么这份配置就是黑白名单控制规则。
 
系统负载自适应规则:例如需要设置当CPU使用率达到90%时,系统就不再接受新请求以防止系统崩溃,那么这个90%的CPU使用率阈值就是系统负载自适应规则。
 
流量控制规则:例如需要设置单机QPS最高为100,那么这个单机限流100QPS便是流量控制规则。
 
熔断降级规则:例如需要设置当错误比例在1秒内超过10次时,系统自动触发熔断降级,那么这个1秒内超过10次的错误比例就是熔断降级规则。
 
二.规则接口Rule和抽象父类AbstractRule及其具体实现类
首先规则与资源是紧密关联的,规则会对资源起作用,因此规则接口Rule需要一个获取资源的方法getResource()。
 
然后每一条具体的规则都应继承抽象父类AbstractRule并具备三个字段:规则id、资源name以及针对来源limitApp。其中针对来源指的是诸如黑名单值、白名单值等,默认是default。
  1. //Base interface of all rules.
  2. public interface Rule {
  3.     //Get target resource of this rule.
  4.     //获取当前规则起作用的目标资源
  5.     String getResource();
  6. }
  7. //Abstract rule entity. AbstractRule是实现了规则接口Rule的抽象规则类
  8. public abstract class AbstractRule implements Rule {
  9.     //rule id. 规则id
  10.     private Long id;
  11.     //Resource name. 资源名称
  12.     private String resource;
  13.     //针对来源,默认是default
  14.     //多个来源使用逗号隔开,比如黑名单规则,限制userId是1和3的访问,那么就设置limitApp为"1,3"
  15.     //Application name that will be limited by origin.
  16.     //The default limitApp is default, which means allowing all origin apps.
  17.     //For authority rules, multiple origin name can be separated with comma (',').
  18.     private String limitApp;
  19.    
  20.     public Long getId() {
  21.         return id;
  22.     }
  23.    
  24.     public AbstractRule setId(Long id) {
  25.         this.id = id;
  26.         return this;
  27.     }
  28.    
  29.     @Override
  30.     public String getResource() {
  31.         return resource;
  32.     }
  33.    
  34.     public AbstractRule setResource(String resource) {
  35.         this.resource = resource;
  36.         return this;
  37.     }
  38.    
  39.     public String getLimitApp() {
  40.         return limitApp;
  41.     }
  42.    
  43.     public AbstractRule setLimitApp(String limitApp) {
  44.         this.limitApp = limitApp;
  45.         return this;
  46.     }
  47.     ...
  48. }
  49. //Authority rule is designed for limiting by request origins.
  50. public class AuthorityRule extends AbstractRule {
  51.     ...
  52. }
  53. public class SystemRule extends AbstractRule {
  54.     ...
  55. }
  56. public class FlowRule extends AbstractRule {
  57.     ...
  58. }
  59. public class DegradeRule extends AbstractRule {
  60.     ...
  61. }
复制代码
1.png
(2)Sentinel的规则管理
一.PropertyListener监听器接口及其实现类
二.SentinelProperty监听器接口管理所有PropertyListener子类
三.DynamicSentinelProperty会触发监听器PropertyListener的回调
 
一.PropertyListener监听器接口及其实现类
为了感知规则Rule的变化,需要一个负责监听规则变化的类,也就是需要一个监听器来监听规则Rule的变化,这个监听器就是PropertyListener。
 
PropertyListener是一个接口,它定义了两个方法:方法一是首次加载规则时触发的回调方法configLoad(),方法二是规则变更时触发的回调方法configUpdate()。
 
PropertyListener接口使用了泛型T而不是规则接口Rule来定义,是因为除了规则的变化需要监听器监听外,还有其他场景也需要监听。
 
PropertyListener接口的具体实现类有:
  1. AuthorityRuleManager.RulePropertyListener
  2. FlowRuleManager.FlowPropertyListener
  3. DegradeRuleManager.RulePropertyListener
  4. SystemRuleManager.SystemPropertyListener
复制代码
  1. //This class holds callback method when SentinelProperty.updateValue(Object) need inform the listener.
  2. public interface PropertyListener<T> {
  3.     //Callback method when {@link SentinelProperty#updateValue(Object)} need inform the listener.
  4.     //规则变更时触发的回调方法
  5.     void configUpdate(T value);
  6.     //The first time of the {@code value}'s load.
  7.     //首次加载规则时触发的回调方法
  8.     void configLoad(T value);
  9. }
  10. //Manager for authority rules.
  11. public final class AuthorityRuleManager {
  12.     //key是资源名称,value是资源对应的规则
  13.     private static volatile Map<String, Set> authorityRules = new ConcurrentHashMap<>();
  14.     //饿汉式单例模式实例化黑白名单权限控制规则的监听器对象
  15.     private static final RulePropertyListener LISTENER = new RulePropertyListener();
  16.     //监听器对象的管理器
  17.     private static SentinelProperty<List> currentProperty = new DynamicSentinelProperty<>();
  18.    
  19.     static {
  20.         //将黑白名单权限控制规则的监听器对象添加到DynamicSentinelProperty中
  21.         currentProperty.addListener(LISTENER);
  22.     }
  23.     ...
  24.    
  25.     private static class RulePropertyListener implements PropertyListener<List> {
  26.         @Override
  27.         public synchronized void configLoad(List value) {
  28.             authorityRules = loadAuthorityConf(value);
  29.             RecordLog.info("[AuthorityRuleManager] Authority rules loaded: {}", authorityRules);
  30.         }
  31.         
  32.         @Override
  33.         public synchronized void configUpdate(List conf) {
  34.             authorityRules = loadAuthorityConf(conf);
  35.             RecordLog.info("[AuthorityRuleManager] Authority rules received: {}", authorityRules);
  36.         }
  37.         
  38.         private Map<String, Set> loadAuthorityConf(List list) {
  39.             Map<String, Set> newRuleMap = new ConcurrentHashMap<>();
  40.             if (list == null || list.isEmpty()) {
  41.                 return newRuleMap;
  42.             }
  43.             for (AuthorityRule rule : list) {
  44.                 if (!isValidRule(rule)) {
  45.                     RecordLog.warn("[AuthorityRuleManager] Ignoring invalid authority rule when loading new rules: {}", rule);
  46.                     continue;
  47.                 }
  48.                 if (StringUtil.isBlank(rule.getLimitApp())) {
  49.                     rule.setLimitApp(RuleConstant.LIMIT_APP_DEFAULT);
  50.                 }
  51.                 String identity = rule.getResource();
  52.                 Set ruleSet = newRuleMap.get(identity);
  53.                 //putIfAbsent
  54.                 if (ruleSet == null) {
  55.                     ruleSet = new HashSet<>();
  56.                     ruleSet.add(rule);
  57.                     newRuleMap.put(identity, ruleSet);
  58.                 } else {
  59.                     //One resource should only have at most one authority rule, so just ignore redundant rules.
  60.                     RecordLog.warn("[AuthorityRuleManager] Ignoring redundant rule: {}", rule.toString());
  61.                 }
  62.             }
  63.             return newRuleMap;
  64.         }
  65.     }
  66.     ...
  67. }
  68. public class FlowRuleManager {
  69.     private static volatile Map<String, List<FlowRule>> flowRules = new HashMap<>();
  70.     private static final FlowPropertyListener LISTENER = new FlowPropertyListener();
  71.     private static SentinelProperty<List<FlowRule>> currentProperty = new DynamicSentinelProperty<List<FlowRule>>();
  72.    
  73.     static {
  74.         currentProperty.addListener(LISTENER);
  75.         startMetricTimerListener();
  76.     }
  77.     ...
  78.    
  79.     private static final class FlowPropertyListener implements PropertyListener<List<FlowRule>> {
  80.         @Override
  81.         public synchronized void configUpdate(List<FlowRule> value) {
  82.             Map<String, List<FlowRule>> rules = FlowRuleUtil.buildFlowRuleMap(value);
  83.             if (rules != null) {
  84.                 flowRules = rules;
  85.             }
  86.             RecordLog.info("[FlowRuleManager] Flow rules received: {}", rules);
  87.         }
  88.         
  89.         @Override
  90.         public synchronized void configLoad(List<FlowRule> conf) {
  91.             Map<String, List<FlowRule>> rules = FlowRuleUtil.buildFlowRuleMap(conf);
  92.             if (rules != null) {
  93.                 flowRules = rules;
  94.             }
  95.             RecordLog.info("[FlowRuleManager] Flow rules loaded: {}", rules);
  96.         }
  97.     }
  98.     ...
  99. }
  100. public final class DegradeRuleManager {
  101.     private static final RulePropertyListener LISTENER = new RulePropertyListener();
  102.     private static SentinelProperty<List<DegradeRule>> currentProperty = new DynamicSentinelProperty<>();
  103.    
  104.     static {
  105.         currentProperty.addListener(LISTENER);
  106.     }
  107.     ...
  108.    
  109.     private static class RulePropertyListener implements PropertyListener<List<DegradeRule>> {
  110.         ...
  111.         @Override
  112.         public void configUpdate(List<DegradeRule> conf) {
  113.             reloadFrom(conf);
  114.             RecordLog.info("[DegradeRuleManager] Degrade rules has been updated to: {}", ruleMap);
  115.         }
  116.         
  117.         @Override
  118.         public void configLoad(List<DegradeRule> conf) {
  119.             reloadFrom(conf);
  120.             RecordLog.info("[DegradeRuleManager] Degrade rules loaded: {}", ruleMap);
  121.         }
  122.         ...
  123.     }
  124.     ...
  125. }
复制代码
二.SentinelProperty监听器接口管理所有PropertyListener子类
为了在创建规则时回调configLoad()方法初始化规则配置,以及在规则变更时回调configUpdate()方法通知到所有监听者,需要一个类来管理所有监听器,比如将所有监听器添加到集合中。当配置发生变化时,就可以遍历监听器集合然后调用回调方法进行处理。
 
其实就是使用监听器模式或观察者模式,创建一个实现了SentinelProperty接口的类,专门负责管理所有实现了PropertyListener接口的监听器。
 
其中SentinelProperty接口如下所示:
  1. //This class holds current value of the config,
  2. //and is responsible for informing all PropertyListeners added on this when the config is updated.
  3. //Note that not every updateValue(Object newValue) invocation should inform the listeners,
  4. //only when newValue is not Equals to the old value, informing is needed.
  5. public interface SentinelProperty<T> {
  6.     //添加监听者
  7.     //Add a PropertyListener to this SentinelProperty.
  8.     //After the listener is added, updateValue(Object) will inform the listener if needed.
  9.     //This method can invoke multi times to add more than one listeners.
  10.     void addListener(PropertyListener<T> listener);
  11.     //移除监听者
  12.     //Remove the PropertyListener on this.
  13.     //After removing, updateValue(Object) will not inform the listener.
  14.     void removeListener(PropertyListener<T> listener);
  15.     //当监听值有变化时,调用此方法进行通知
  16.     //Update the newValue as the current value of this property and inform all
  17.     //PropertyListeners added on this only when new value is not Equals to the old value.
  18.     boolean updateValue(T newValue);
  19. }
复制代码
三.DynamicSentinelProperty会触发监听器PropertyListener的回调
DynamicSentinelProperty会使用写时复制集合CopyOnWriteArraySet来存储监听器,当DynamicSentinelProperty添加监听器或者更新新值时,便会触发执行PropertyListener接口的两个回调方法。
 
具体就是:当执行DynamicSentinelProperty的addListener()方法添加监听器时,会将监听器保存到DynamicSentinelProperty的写时复制集合CopyOnWriteArraySet中,并且回调监听器的configLoad()方法来初始化规则配置。由于监听器监听的是规则,而规则又是和资源绑定的,所以初始化就是将资源和规则绑定到一个Map中:即形如Map这样的Map。
 
当执行DynamicSentinelProperty的updateValue()方法更新规则配置时,则会遍历所有监听器并调用每个监听器的configUpdate()方法进行更新,也就是更新Map这种Map里的value。
  1. public class DynamicSentinelProperty<T> implements SentinelProperty<T> {
  2.     protected Set<PropertyListener<T>> listeners = new CopyOnWriteArraySet<>();
  3.     private T value = null;
  4.    
  5.     public DynamicSentinelProperty() {
  6.    
  7.     }
  8.    
  9.     public DynamicSentinelProperty(T value) {
  10.         super();
  11.         this.value = value;
  12.     }
  13.    
  14.     //添加监听器到集合
  15.     @Override
  16.     public void addListener(PropertyListener<T> listener) {
  17.         listeners.add(listener);
  18.         //回调监听器的configLoad()方法初始化规则配置
  19.         listener.configLoad(value);
  20.     }
  21.    
  22.     //移除监听器
  23.     @Override
  24.     public void removeListener(PropertyListener<T> listener) {
  25.         listeners.remove(listener);
  26.     }
  27.    
  28.     //更新值
  29.     @Override
  30.     public boolean updateValue(T newValue) {
  31.         //如果值没变化,直接返回
  32.         if (isEqual(value, newValue)) {
  33.             return false;
  34.         }
  35.         RecordLog.info("[DynamicSentinelProperty] Config will be updated to: {}", newValue);
  36.         value = newValue;
  37.         //如果值发生了变化,则遍历监听器,回调监听器的configUpdate()方法更新对应的值
  38.         for (PropertyListener<T> listener : listeners) {
  39.             listener.configUpdate(newValue);
  40.         }
  41.         return true;
  42.     }
  43.     ...
  44. }
复制代码
(3)总结
一.PropertyListener
PropertyListener是一个泛型接口,用于监听配置变更。它包含两个方法:configUpdate()方法和configLoad()方法。
 
PropertyListener的configUpdate()方法在配置发生变化时触发,PropertyListener的configLoad()方法在首次加载配置时触发。通过实现PropertyListener接口,可以实现不同类型的监听器,例如FlowPropertyListener等。
 
二.SentinelProperty
SentinelProperty是一个用于管理PropertyListener监听器的接口,它提供了添加、移除和更新监听器的方法。
 
添加监听器可调用SentinelProperty实现类的addListener()方法实现添加,配置变更可调用SentinelProperty实现类的updateValue()方法通知监听器。Sentinel提供了默认的SentinelProperty实现:DynamicSentinelProperty。
 
4.AuthoritySlot控制黑白名单权限
(1)黑白名单权限控制规则的配置Demo
(2)AuthoritySlot验证黑白名单权限控制规则
 
(1)黑白名单权限控制规则的配置Demo
一.配置黑白名单权限控制规则的过程
二.AuthorityRuleManager初始化和加载黑白名单权限控制规则详情
 
一.配置黑白名单权限控制规则的过程
首先创建一个AuthorityRule规则对象,然后设置三个关键要素:通过setStrategy()方法设置规则是黑名单还是白名单、通过setResource()方法设置规则绑定到哪个资源、通过setLimitApp()方法设置限制哪些来源,最后调用AuthorityRuleManager的loadRules()方法加载此规则。所以黑白名单权限规则是通过AuthorityRuleManager类来进行管理的。
  1. //Authority rule is designed for limiting by request origins.
  2. //In blacklist mode, requests will be blocked when blacklist contains current origin, otherwise will pass.
  3. //In whitelist mode, only requests from whitelist origin can pass.
  4. public class AuthorityDemo {
  5.     private static final String RESOURCE_NAME = "testABC";
  6.    
  7.     public static void main(String[] args) {
  8.         System.out.println("========Testing for black list========");
  9.         initBlackRules();
  10.         testFor(RESOURCE_NAME, "appA");
  11.         testFor(RESOURCE_NAME, "appB");
  12.         testFor(RESOURCE_NAME, "appC");
  13.         testFor(RESOURCE_NAME, "appE");
  14.         System.out.println("========Testing for white list========");
  15.         initWhiteRules();
  16.         testFor(RESOURCE_NAME, "appA");
  17.         testFor(RESOURCE_NAME, "appB");
  18.         testFor(RESOURCE_NAME, "appC");
  19.         testFor(RESOURCE_NAME, "appE");
  20.     }
  21.    
  22.     private static void testFor(String resource, String origin) {
  23.         ContextUtil.enter(resource, origin);
  24.         Entry entry = null;
  25.         try {
  26.             entry = SphU.entry(resource);
  27.             System.out.println(String.format("Passed for resource %s, origin is %s", resource, origin));
  28.         } catch (BlockException ex) {
  29.             System.err.println(String.format("Blocked for resource %s, origin is %s", resource, origin));
  30.         } finally {
  31.             if (entry != null) {
  32.                 entry.exit();
  33.             }
  34.             ContextUtil.exit();
  35.         }
  36.     }
  37.    
  38.     private static void initWhiteRules() {
  39.         AuthorityRule rule = new AuthorityRule();
  40.         rule.setResource(RESOURCE_NAME);
  41.         rule.setStrategy(RuleConstant.AUTHORITY_WHITE);
  42.         rule.setLimitApp("appA,appE");
  43.         AuthorityRuleManager.loadRules(Collections.singletonList(rule));
  44.     }
  45.    
  46.     private static void initBlackRules() {
  47.         AuthorityRule rule = new AuthorityRule();
  48.         rule.setResource(RESOURCE_NAME);
  49.         rule.setStrategy(RuleConstant.AUTHORITY_BLACK);
  50.         rule.setLimitApp("appA,appB");
  51.         AuthorityRuleManager.loadRules(Collections.singletonList(rule));
  52.     }
  53. }
复制代码
二.AuthorityRuleManager初始化和加载黑白名单权限控制规则详情
AuthorityRuleManager类中有一个静态变量LISTENER,该变量指向由饿汉式单例模式实例化的黑白名单权限控制规则监听器对象。
 
AuthorityRuleManager类有一个静态代码块,在该代码块中,会调用DynamicSentinelProperty的addListener(LISTENER)方法,将黑白名单权限控制规则的监听器对象添加到DynamicSentinelProperty。
 
在DynamicSentinelProperty的addListener()方法中,又会回调LISTENER的configLoad()方法初始化黑白名单权限规则。
 
当AuthorityDemo调用AuthorityRuleManager的loadRules()方法加载规则时,便会执行DynamicSentinelProperty的updateValue()方法,也就是会触发执行LISTENER的configUpdate()方法加载权限规则到一个map中,即执行RulePropertyListener的loadAuthorityConf()方法加载规则,从而完成黑白名单权限控制规则的加载和初始化。其中map是AuthorityRuleManager的Map。
  1. //Manager for authority rules.
  2. public final class AuthorityRuleManager {
  3.     //key是资源名称,value是资源对应的规则
  4.     private static volatile Map<String, Set> authorityRules = new ConcurrentHashMap<>();
  5.     //饿汉式单例模式实例化黑白名单权限控制规则的监听器对象
  6.     private static final RulePropertyListener LISTENER = new RulePropertyListener();
  7.     //监听器对象的管理器
  8.     private static SentinelProperty<List> currentProperty = new DynamicSentinelProperty<>();
  9.    
  10.     static {
  11.         //将黑白名单权限控制规则的监听器对象添加到DynamicSentinelProperty中
  12.         currentProperty.addListener(LISTENER);
  13.     }
  14.    
  15.     //Load the authority rules to memory.
  16.     public static void loadRules(List rules) {
  17.         currentProperty.updateValue(rules);
  18.     }
  19.     ...
  20.    
  21.     //静态内部类的方式实现黑白名单权限控制规则监听器
  22.     private static class RulePropertyListener implements PropertyListener<List> {
  23.         //黑名单权限控制规则初始化
  24.         @Override
  25.         public synchronized void configLoad(List value) {
  26.             authorityRules = loadAuthorityConf(value);
  27.             RecordLog.info("[AuthorityRuleManager] Authority rules loaded: {}", authorityRules);
  28.         }
  29.         
  30.         //黑名单权限控制规则变更
  31.         @Override
  32.         public synchronized void configUpdate(List conf) {
  33.             authorityRules = loadAuthorityConf(conf);
  34.             RecordLog.info("[AuthorityRuleManager] Authority rules received: {}", authorityRules);
  35.         }
  36.         
  37.         //加载黑白名单权限控制规则
  38.         private Map<String, Set> loadAuthorityConf(List list) {
  39.             Map<String, Set> newRuleMap = new ConcurrentHashMap<>();
  40.             if (list == null || list.isEmpty()) {
  41.                 return newRuleMap;
  42.             }
  43.             //遍历每个黑白名单权限控制规则
  44.             for (AuthorityRule rule : list) {
  45.                 if (!isValidRule(rule)) {
  46.                     RecordLog.warn("[AuthorityRuleManager] Ignoring invalid authority rule when loading new rules: {}", rule);
  47.                     continue;
  48.                 }
  49.                 if (StringUtil.isBlank(rule.getLimitApp())) {
  50.                     rule.setLimitApp(RuleConstant.LIMIT_APP_DEFAULT);
  51.                 }
  52.                 //获取黑白名单权限控制规则对应的资源名称
  53.                 String identity = rule.getResource();
  54.                 Set ruleSet = newRuleMap.get(identity);
  55.                 //putIfAbsent
  56.                 //将黑白名单权限控制规则放到newRuleMap中
  57.                 if (ruleSet == null) {
  58.                     ruleSet = new HashSet<>();
  59.                     ruleSet.add(rule);
  60.                     newRuleMap.put(identity, ruleSet);
  61.                 } else {
  62.                     //One resource should only have at most one authority rule, so just ignore redundant rules.
  63.                     RecordLog.warn("[AuthorityRuleManager] Ignoring redundant rule: {}", rule.toString());
  64.                 }
  65.             }
  66.             return newRuleMap;
  67.         }
  68.     }
  69.     ...
  70. }
  71. public class DynamicSentinelProperty<T> implements SentinelProperty<T> {
  72.     protected Set<PropertyListener<T>> listeners = new CopyOnWriteArraySet<>();
  73.     private T value = null;
  74.    
  75.     public DynamicSentinelProperty() {
  76.    
  77.     }
  78.    
  79.     public DynamicSentinelProperty(T value) {
  80.         super();
  81.         this.value = value;
  82.     }
  83.    
  84.     //添加监听器到集合
  85.     @Override
  86.     public void addListener(PropertyListener<T> listener) {
  87.         listeners.add(listener);
  88.         //回调监听器的configLoad()方法初始化规则配置
  89.         listener.configLoad(value);
  90.     }
  91.    
  92.     //移除监听器
  93.     @Override
  94.     public void removeListener(PropertyListener<T> listener) {
  95.         listeners.remove(listener);
  96.     }
  97.    
  98.     //更新值
  99.     @Override
  100.     public boolean updateValue(T newValue) {
  101.         //如果值没变化,直接返回
  102.         if (isEqual(value, newValue)) {
  103.             return false;
  104.         }
  105.         RecordLog.info("[DynamicSentinelProperty] Config will be updated to: {}", newValue);
  106.         //如果值发生了变化,则遍历监听器,回调监听器的configUpdate()方法更新对应的值
  107.         value = newValue;
  108.         for (PropertyListener<T> listener : listeners) {
  109.             listener.configUpdate(newValue);
  110.         }
  111.         return true;
  112.     }
  113.    
  114.     private boolean isEqual(T oldValue, T newValue) {
  115.         if (oldValue == null && newValue == null) {
  116.             return true;
  117.         }
  118.         if (oldValue == null) {
  119.             return false;
  120.         }
  121.         return oldValue.equals(newValue);
  122.     }
  123.    
  124.     public void close() {
  125.         listeners.clear();
  126.     }
  127. }
复制代码
(2)AuthoritySlot验证黑白名单权限控制规则
在AuthoritySlot的checkBlackWhiteAuthority()方法中,首先会调用AuthorityRuleManager的getAuthorityRules()方法,从AuthorityRuleManager中获取全部黑白名单权限控制规则,然后再调用AuthorityRuleChecker的passCheck()方法根据规则验证权限。
 
在AuthorityRuleChecker的passCheck()方法中,首先会从当前上下文Context中获取调用源的名称,然后判断调用源不空且配置了黑白名单规则,才执行黑白名单验证逻辑。接着先通过indexOf()方法进行一次黑白名单的简单匹配,再通过split()方法分割黑白名单数组以实现精确匹配。如果调用源在名单中,再根据黑白名单策略来决定是否拒绝请求。
 
注意,实现黑白名单权限控制的前提条件是:每个客户端在发起请求时已将自己服务的唯一标志放到Context的origin属性里。
  1. @Spi(order = Constants.ORDER_AUTHORITY_SLOT)
  2. public class AuthoritySlot 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.         checkBlackWhiteAuthority(resourceWrapper, context);
  7.         fireEntry(context, resourceWrapper, node, count, prioritized, args);
  8.     }
  9.    
  10.     @Override
  11.     public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
  12.         fireExit(context, resourceWrapper, count, args);
  13.     }
  14.    
  15.     void checkBlackWhiteAuthority(ResourceWrapper resource, Context context) throws AuthorityException {
  16.         //先从AuthorityRuleManager中获取存放全部的黑白名单权限控制规则的Map
  17.         Map<String, Set> authorityRules = AuthorityRuleManager.getAuthorityRules();
  18.         if (authorityRules == null) {
  19.             return;
  20.         }
  21.         //获取当前资源对应的黑白名单权限控制规则集合
  22.         Set rules = authorityRules.get(resource.getName());
  23.         if (rules == null) {
  24.             return;
  25.         }
  26.         for (AuthorityRule rule : rules) {
  27.             //验证规则
  28.             if (!AuthorityRuleChecker.passCheck(rule, context)) {
  29.                 throw new AuthorityException(context.getOrigin(), rule);
  30.             }
  31.         }
  32.     }
  33. }
  34. //Rule checker for white/black list authority.
  35. final class AuthorityRuleChecker {
  36.     static boolean passCheck(AuthorityRule rule, Context context) {
  37.         String requester = context.getOrigin();
  38.         //Empty origin or empty limitApp will pass.
  39.         //如果没设置来源,或者没限制app,那么就直接放行,不进行规则限制
  40.         if (StringUtil.isEmpty(requester) || StringUtil.isEmpty(rule.getLimitApp())) {
  41.             return true;
  42.         }
  43.         //Do exact match with origin name.
  44.         //判断此次请求的来源是不是在limitApp里,注意这里用的是近似精确匹配,但不是绝对精确
  45.         //比如limitApp写的是a,b,而资源名称是",b",那么就匹配不到,因为limitApp是按逗号隔开的,但资源却包含了逗号
  46.         int pos = rule.getLimitApp().indexOf(requester);
  47.         boolean contain = pos > -1;
  48.         //如果近似精确匹配成功,则再进行精确匹配
  49.         if (contain) {
  50.             boolean exactlyMatch = false;
  51.             String[] appArray = rule.getLimitApp().split(",");
  52.             for (String app : appArray) {
  53.                 if (requester.equals(app)) {
  54.                     exactlyMatch = true;
  55.                     break;
  56.                 }
  57.             }
  58.             contain = exactlyMatch;
  59.         }
  60.         //获取策略
  61.         int strategy = rule.getStrategy();
  62.         //如果是黑名单,并且此次请求的来源在limitApp里,则需返回false,禁止请求
  63.         if (strategy == RuleConstant.AUTHORITY_BLACK && contain) {
  64.             return false;
  65.         }
  66.         //如果是白名单,并且此次请求的来源不在limitApp里,则也需返回false,禁止请求
  67.         if (strategy == RuleConstant.AUTHORITY_WHITE && !contain) {
  68.             return false;
  69.         }
  70.         return true;
  71.     }
  72.    
  73.     private AuthorityRuleChecker() {
  74.    
  75.     }
  76. }
复制代码
(3)总结
一.黑白名单权限验证规则涉及的核心类
二.黑白名单权限验证的处理逻辑
三.Sentinel监听器模式的处理逻辑
 
一.黑白名单权限验证规则涉及的核心类
首先是黑白名单管理器AuthorityRuleManager,调用方直接调用该类的loadRules()方法来通知监听器规则的变更。
 
然后是黑白名单监听器RulePropertyListener,它实现了PropertyListener接口,负责监听和管理黑白名单的规则变化。
 
二.黑白名单权限验证的处理逻辑
首先通过AuthorityRuleManager获取全部黑白名单权限控制规则,然后循环遍历这些权限控制规则逐一验证是否匹配。
 
这里需要注意:来源是从Context里获取的,也就是Context的getOrigin()方法。因此在进行黑白名单权限规则控制时,需要先定义好一个origin。这个origin可以是userId,也可以是IP地址,还可以是项目名称等。
 
此外,规则里的limitApp字段是字符串,多个时需要使用逗号隔开,然后在验证环节先通过indexOf()方法近似匹配,匹配上之后再通过split()方法转成数组进行精确匹配。
 
三.Sentinel监听器模式的处理逻辑
Sentinel监听器模式会包含三大角色:
角色一:监听器PropertyListener
角色二:监听器管理器SentinelProperty
角色三:规则管理器RuleManager
 
首先,规则管理器RuleManager在初始化时:会调用监听器管理器SentinelProperty的addListener()方法将监听器PropertyListener注册到监听器管理器SentinelProperty中。
 
然后,使用方使用具体的规则时:可以通过调用规则管理器RuleManager的loadRules()方法加载规则。加载规则时会调用监听器管理器SentinelProperty的的updateValue()方法通知每一个监听器,即通过监听器PropertyListener的configUpdate()方法把规则加载到规则管理器RuleManager的本地中。
 
5.SystemSlot根据系统保护规则进行流控
(1)系统保护规则SystemRule的配置Demo
(2)SystemRuleManager加载规则和获取系统信息
(3)SystemSlot根据系统保护规则进行流控
 
(1)系统保护规则SystemRule的配置Demo
系统规则类SystemRule包含了以下几个指标:highestSystemLoad、highestCpuUsage、QPS、avgRt、maxThread。
 
当需要限制系统的这些指标时,可以创建一个SystemRule对象并设置对应的阈值,然后通过调用SystemRuleManager的loadRules()方法,加载系统保护规则设置的阈值到SystemRuleManager。
  1. //Sentinel System Rule makes the inbound traffic and capacity meet.
  2. //It takes average RT, QPS and thread count of requests into account.
  3. //And it also provides a measurement of system's load, but only available on Linux.
  4. //We recommend to coordinate highestSystemLoad, qps, avgRt and maxThread to make sure your system run in safety level.
  5. //To set the threshold appropriately, performance test may be needed.
  6. public class SystemRule extends AbstractRule {
  7.     //对应Dashboard上阈值类型为LOAD的值,代表系统最高负载值,默认为-1,只有大于等于0才生效
  8.     private double highestSystemLoad = -1;
  9.     //对应Dashboard上阈值类型为CPU使用率的值,代表系统最高CPU使用率,取值是[0,1]之间,默认为-1,只有大于等于0才生效
  10.     private double highestCpuUsage = -1;
  11.     //对应Dashboard上阈值类型为为入口QPS的值,代表限流的阈值,默认为-1,只有大于0才生效
  12.     private double qps = -1;
  13.     //对应Dashboard上阈值类型为为RT的值,代表系统的平均响应时间,默认为-1,只有大于0才生效
  14.     private long avgRt = -1;
  15.     //对应Dashboard上阈值类型为线程数的值,代表系统允许的最大线程数,默认为-1,只有大于0才生效
  16.     private long maxThread = -1;
  17.     ...
  18. }
  19. public class SystemGuardDemo {
  20.     private static AtomicInteger pass = new AtomicInteger();
  21.     private static AtomicInteger block = new AtomicInteger();
  22.     private static AtomicInteger total = new AtomicInteger();
  23.     private static volatile boolean stop = false;
  24.     private static final int threadCount = 100;
  25.     private static int seconds = 60 + 40;
  26.    
  27.     public static void main(String[] args) throws Exception {
  28.         //启动线程定时输出信息
  29.         tick();
  30.         //初始化系统保护规则
  31.         initSystemRule();
  32.         //模拟有100个线程在访问系统
  33.         for (int i = 0; i < threadCount; i++) {
  34.             Thread entryThread = new Thread(new Runnable() {
  35.                 @Override
  36.                 public void run() {
  37.                     while (true) {
  38.                         Entry entry = null;
  39.                         try {
  40.                             entry = SphU.entry("methodA", EntryType.IN);
  41.                             pass.incrementAndGet();
  42.                             try {
  43.                                 TimeUnit.MILLISECONDS.sleep(20);
  44.                             } catch (InterruptedException e) {
  45.                                 // ignore
  46.                             }
  47.                         } catch (BlockException e1) {
  48.                             block.incrementAndGet();
  49.                             try {
  50.                                 TimeUnit.MILLISECONDS.sleep(20);
  51.                             } catch (InterruptedException e) {
  52.                                 // ignore
  53.                             }
  54.                         } catch (Exception e2) {
  55.                             // biz exception
  56.                         } finally {
  57.                             total.incrementAndGet();
  58.                             if (entry != null) {
  59.                                 entry.exit();
  60.                             }
  61.                         }
  62.                     }
  63.                 }
  64.             });
  65.             entryThread.setName("working-thread");
  66.             entryThread.start();
  67.         }
  68.     }
  69.    
  70.     private static void initSystemRule() {
  71.         List<SystemRule> rules = new ArrayList<SystemRule>();
  72.         SystemRule rule = new SystemRule();
  73.         //最大负载是3
  74.         rule.setHighestSystemLoad(3.0);
  75.         //最大CPU使用率是60%
  76.         rule.setHighestCpuUsage(0.6);
  77.         //请求的平均响应时间最大是10ms
  78.         rule.setAvgRt(10);
  79.         //最大的QPS是20
  80.         rule.setQps(20);
  81.         //最大的工作线程数是10
  82.         rule.setMaxThread(10);
  83.         rules.add(rule);
  84.         //加载系统保护规则设置的阈值到SystemRuleManager中
  85.         SystemRuleManager.loadRules(Collections.singletonList(rule));
  86.     }
  87.    
  88.     private static void tick() {
  89.         Thread timer = new Thread(new TimerTask());
  90.         timer.setName("sentinel-timer-task");
  91.         timer.start();
  92.     }
  93.    
  94.     static class TimerTask implements Runnable {
  95.         @Override
  96.         public void run() {
  97.             System.out.println("begin to statistic!!!");
  98.             long oldTotal = 0;
  99.             long oldPass = 0;
  100.             long oldBlock = 0;
  101.             
  102.             while (!stop) {
  103.                 try {
  104.                     TimeUnit.SECONDS.sleep(1);
  105.                 } catch (InterruptedException e) {
  106.                
  107.                 }
  108.                 long globalTotal = total.get();
  109.                 long oneSecondTotal = globalTotal - oldTotal;
  110.                 oldTotal = globalTotal;
  111.                 long globalPass = pass.get();
  112.                 long oneSecondPass = globalPass - oldPass;
  113.                 oldPass = globalPass;
  114.                 long globalBlock = block.get();
  115.                 long oneSecondBlock = globalBlock - oldBlock;
  116.                 oldBlock = globalBlock;
  117.                 System.out.println(seconds + ", " + TimeUtil.currentTimeMillis() + ", total:"
  118.                     + oneSecondTotal + ", pass:"
  119.                     + oneSecondPass + ", block:" + oneSecondBlock);
  120.                 if (seconds-- <= 0) {
  121.                     stop = true;
  122.                 }
  123.             }
  124.             System.exit(0);
  125.         }
  126.     }
  127. }
复制代码
(3)SystemSlot根据系统保护规则进行流控
SystemSlot会根据当前系统的实际情况,判断是否需要对请求进行限流,也就是通过调用SystemRuleManager的checkSystem()方法来进行检查。
 
在SystemRuleManager的checkSystem()方法中:
 
一.首先通过checkSystemStatus.get()判断系统保护功能是否开启
开启的入口就是:
  1. public final class SystemRuleManager {
  2.     //系统保护规则中的5个阈值:Load、CPU使用率、QPS、最大RT、最大线程数
  3.     private static volatile double highestSystemLoad = Double.MAX_VALUE;
  4.     private static volatile double highestCpuUsage = Double.MAX_VALUE;
  5.     private static volatile double qps = Double.MAX_VALUE;
  6.     private static volatile long maxRt = Long.MAX_VALUE;
  7.     private static volatile long maxThread = Long.MAX_VALUE;
  8.     ...
  9.     //标记系统流控功能是否开启
  10.     private static AtomicBoolean checkSystemStatus = new AtomicBoolean(false);
  11.     //定时获取系统状态信息(负载和CPU使用率)的线程
  12.     private static SystemStatusListener statusListener = null;
  13.     //饿汉式单例模式实例化系统保护规则的监听器对象
  14.     private final static SystemPropertyListener listener = new SystemPropertyListener();
  15.     //监听器对象的管理器
  16.     private static SentinelProperty<List<SystemRule>> currentProperty = new DynamicSentinelProperty<List<SystemRule>>();
  17.     private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, new NamedThreadFactory("sentinel-system-status-record-task", true));
  18.    
  19.     static {
  20.         checkSystemStatus.set(false);
  21.         //启动定时任务获取系统的Load、CPU负载等信息
  22.         statusListener = new SystemStatusListener();
  23.         scheduler.scheduleAtFixedRate(statusListener, 0, 1, TimeUnit.SECONDS);
  24.         //添加监听器
  25.         currentProperty.addListener(listener);
  26.     }
  27.    
  28.     //Load SystemRules, former rules will be replaced.
  29.     public static void loadRules(List<SystemRule> rules) {
  30.         currentProperty.updateValue(rules);
  31.     }
  32.    
  33.     static class SystemPropertyListener extends SimplePropertyListener<List<SystemRule>> {
  34.         @Override
  35.         public synchronized void configUpdate(List<SystemRule> rules) {
  36.             restoreSetting();
  37.             if (rules != null && rules.size() >= 1) {
  38.                 for (SystemRule rule : rules) {
  39.                     //加载系统保护规则的阈值到本地
  40.                     loadSystemConf(rule);
  41.                 }
  42.             } else {
  43.                 checkSystemStatus.set(false);
  44.             }
  45.             ...
  46.         }
  47.     }
  48.    
  49.     //加载系统保护规则的阈值到本地
  50.     public static void loadSystemConf(SystemRule rule) {
  51.         boolean checkStatus = false;
  52.         if (rule.getHighestSystemLoad() >= 0) {
  53.             highestSystemLoad = Math.min(highestSystemLoad, rule.getHighestSystemLoad());
  54.             highestSystemLoadIsSet = true;
  55.             checkStatus = true;
  56.         }
  57.         if (rule.getHighestCpuUsage() >= 0) {
  58.             if (rule.getHighestCpuUsage() > 1) {
  59.                 RecordLog.warn(String.format("[SystemRuleManager] Ignoring invalid SystemRule: " + "highestCpuUsage %.3f > 1", rule.getHighestCpuUsage()));
  60.             } else {
  61.                 highestCpuUsage = Math.min(highestCpuUsage, rule.getHighestCpuUsage());
  62.                 highestCpuUsageIsSet = true;
  63.                 checkStatus = true;
  64.             }
  65.         }
  66.         if (rule.getAvgRt() >= 0) {
  67.             maxRt = Math.min(maxRt, rule.getAvgRt());
  68.             maxRtIsSet = true;
  69.             checkStatus = true;
  70.         }
  71.         if (rule.getMaxThread() >= 0) {
  72.             maxThread = Math.min(maxThread, rule.getMaxThread());
  73.             maxThreadIsSet = true;
  74.             checkStatus = true;
  75.         }
  76.         if (rule.getQps() >= 0) {
  77.             qps = Math.min(qps, rule.getQps());
  78.             qpsIsSet = true;
  79.             checkStatus = true;
  80.         }
  81.         checkSystemStatus.set(checkStatus);
  82.     }
  83.     ...
  84. }
  85. public class DynamicSentinelProperty<T> implements SentinelProperty<T> {
  86.     protected Set<PropertyListener<T>> listeners = new CopyOnWriteArraySet<>();
  87.     private T value = null;
  88.     ...
  89.     //添加监听器到集合
  90.     @Override
  91.     public void addListener(PropertyListener<T> listener) {
  92.         listeners.add(listener);
  93.         //回调监听器的configLoad()方法初始化规则配置
  94.         listener.configLoad(value);
  95.     }
  96.    
  97.     //更新值
  98.     @Override
  99.     public boolean updateValue(T newValue) {
  100.         //如果值没变化,直接返回
  101.         if (isEqual(value, newValue)) {
  102.             return false;
  103.         }
  104.         RecordLog.info("[DynamicSentinelProperty] Config will be updated to: {}", newValue);
  105.         //如果值发生了变化,则遍历监听器,回调监听器的configUpdate()方法更新对应的值
  106.         value = newValue;
  107.         for (PropertyListener<T> listener : listeners) {
  108.             listener.configUpdate(newValue);
  109.         }
  110.         return true;
  111.     }
  112.     ...
  113. }
  114. public class SystemStatusListener implements Runnable {
  115.     volatile double currentLoad = -1;
  116.     volatile double currentCpuUsage = -1;
  117.     volatile long processCpuTime = 0;
  118.     volatile long processUpTime = 0;
  119.     ...
  120.     @Override
  121.     public void run() {
  122.         try {
  123.             OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
  124.             currentLoad = osBean.getSystemLoadAverage();
  125.             double systemCpuUsage = osBean.getSystemCpuLoad();
  126.             //calculate process cpu usage to support application running in container environment
  127.             RuntimeMXBean runtimeBean = ManagementFactory.getPlatformMXBean(RuntimeMXBean.class);
  128.             long newProcessCpuTime = osBean.getProcessCpuTime();
  129.             long newProcessUpTime = runtimeBean.getUptime();
  130.             int cpuCores = osBean.getAvailableProcessors();
  131.             long processCpuTimeDiffInMs = TimeUnit.NANOSECONDS.toMillis(newProcessCpuTime - processCpuTime);
  132.             long processUpTimeDiffInMs = newProcessUpTime - processUpTime;
  133.             double processCpuUsage = (double) processCpuTimeDiffInMs / processUpTimeDiffInMs / cpuCores;
  134.             processCpuTime = newProcessCpuTime;
  135.             processUpTime = newProcessUpTime;
  136.             currentCpuUsage = Math.max(processCpuUsage, systemCpuUsage);
  137.             if (currentLoad > SystemRuleManager.getSystemLoadThreshold()) {
  138.                 writeSystemStatusLog();
  139.             }
  140.         } catch (Throwable e) {
  141.             RecordLog.warn("[SystemStatusListener] Failed to get system metrics from JMX", e);
  142.         }
  143.     }
  144.    
  145.     public double getSystemAverageLoad() {
  146.         return currentLoad;
  147.     }
  148.    
  149.     public double getCpuUsage() {
  150.         return currentCpuUsage;
  151.     }
  152.     ...
  153. }
复制代码
二.接着通过Constants.ENTRY_NODE获取如QPS、threadNum等数据
Constants.ENTRY_NODE其实就是ClusterNode。在StatisticSlot的entry()方法中,会对Constants.ENTRY_NODE进行统计,所以可以通过Constants.ENTRY_NODE获取QPS、threadNum等数据。
 
三.然后采取BBR算法来检查系统负载是否超过系统保护规则的阈值
BBR是Google开发的一种拥塞控制算法,主要用来解决网络拥塞问题。SystemRuleManager的checkBbr()方法的目的是在系统负载较高的情况下,通过限制并行线程数来防止系统过载。
 
简单来说就是:检查当前线程数是否大于(每秒最大成功请求数 * 最小响应时间 / 1000)。如果大于这个值,说明系统可能出现拥塞,要返回false,否则返回true。
 
四.最后判断CPU使用率是否超系统保护规则的阈值
系统负载和CPU使用率是通过SystemStatusListener获取的。
  1. ->SystemRuleManager.loadRules()方法
  2. ->DynamicSentinelProperty.updateValue()方法
  3. ->SystemPropertyListener.configUpdate()方法
  4. ->SystemRuleManager.loadSystemConf()方法
复制代码
(4)总结
一.SystemSlot的使用和处理流程
二.Sentinel监听器模式的处理逻辑
 
一.SystemSlot的使用和处理流程
在使用SystemSlot前,需要先定义系统保护规则,设置相应的阈值,然后通过SystemRuleManager加载系统保护规则SystemRule。当请求进入SystemSlot时,会检查系统性能数据是否满足规则中的阈值。如果满足,则请求可以继续执行。如果不满足,则请求将被限流,也就是抛出SystemBlockException异常。
 
二.Sentinel监听器模式的处理逻辑
Sentinel监听器模式会包含三大角色:
角色一:监听器PropertyListener
角色二:监听器管理器SentinelProperty
角色三:规则管理器RuleManager
首先,规则管理器RuleManager在初始化时:会调用监听器管理器SentinelProperty的addListener()方法将监听器PropertyListener注册到监听器管理器SentinelProperty中。
 
然后,使用方使用具体的规则时:可以通过调用规则管理器RuleManager的loadRules()方法加载规则。加载规则时会调用监听器管理器SentinelProperty的的updateValue()方法通知每一个监听器,即通过监听器PropertyListener的configUpdate()方法把规则加载到规则管理器RuleManager的本地中。
 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

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