Flume之监控

Flume作为一个日志收集工具,在数据采集方面,展现出了非常强大的能力。它的SOURCE、SINK、CHANNEL三大组件这种模式,来完成数据的接收、缓存、发送这个过程,拥有非常完美的契合度。不过这里,我们要说的不是Flume有多好或者Flume有哪些优点,我们要谈的是Flume的监控。

1、为什么需要Flume监控?

Flume作为一个强大的数据收集工具,虽然功能非常强大实用,但是却无法看到flume收集数据的详细信息,所以我们需要一个能展示flume实时收集数据动态信息的界面,包括flume成功收集的日志数量、成功发送的日志数量、flume启动时间、停止时间、以及flume一些具体的配置信息,像通道容量等,于是顺利成章的监控能帮我们做到这些,有了这些数据,在遇到数据收集瓶颈或者数据丢失的时候,通过分析监控数据来分析、解决问题。

2、Flume有哪些监控方式?

(1)、Http监控

使用这种监控方式,只需要在启动flume的时候在启动参数上面加上监控配置,例如这样:

[java] view plain copy
  1. bin/flume-ng agent --conf conf --conf-file conf/flume_conf.properties --name collect -Dflume.monitoring.type=http -Dflume.monitoring.port=1234  
其中-Dflume.monitoring.type=http表示使用http方式来监控,后面的-Dflume.monitoring.port=1234表示我们需要启动的监控服务的端口号为1234,这个端口号可以自己随意配置。然后启动flume之后,通过http://ip:1234/metrics就可以得到flume的一个json格式的监控数据。

(2)、ganglia监控

这种监控方式需要先安装ganglia然后启动ganglia,然后再启动flume的时候加上监控配置,例如:

[java] view plain copy
  1. bin/flume-ng agent --conf conf --conf-file conf/producer.properties --name collect -Dflume.monitoring.type=ganglia -Dflume.monitoring.hosts=ip:port  
其中-Dflume.monitoring.type=ganglia表示使用ganglia的方式来监控,而-Dflume.monitoring.hosts=ip:port表示ganglia安装的ip和启动的端口号。

flume监控还可以使用zabbix,但是这种方式需要在flume源码中添加监控模块,相对比较麻烦,由于不是flume自带的监控方式,这里不讨论这种方式。

因此,flume自带的监控方式其实就是http、ganglia两种,http监控只能通过一个http地址访问得到一个json格式的监控数据,而ganglia监控是拿到这个数据后用界面的方式展示出来了,相对比较直观。

3、Flume监控哪些组件、能够得到组件的哪些信息?

(1)、SOURCE

SOURCE作为flume的数据源组件,所有收集日志的第一个到达的地方,它的监控信息非常重要。通过监控我们能够得到的监控数据有这些:

OpenConnectionCount(打开的连接数)、Type(组件类型)、AppendBatchAcceptedCount(追加到channel中的批数量)、AppendBatchReceivedCount(source端刚刚追加的批数量)、EventAcceptedCount(成功放入channel的event数量)、AppendReceivedCount(source追加目前收到的数量)、StartTime(组件开始时间)、StopTime(组件停止时间)、EventReceivedCount(source端成功收到的event数量)、AppendAcceptedCount(放入channel的event数量)等。当然这些只是flume监控源码中已经自带的监控元素,如果你需要其他的监控信息,例如ip、端口号等,有两种方法,第一个,修改监控源码,添加你需要的监控元素,这种方法只是在原有代码基础上,添加一些满足自己需求的监控元素,比较简单,但灵活性不足;第二个就是自定义监控组件,这种方法是在原有监控框架中,自己实现自己的监控组件,这样可以达到完全满足自己需求,且灵活性很高。至于这两种方法如何操作,在后面Flume监控如何实现有讨论到。

同理CHANNEL、SINK这两个组件的监控也可以使用这两种方法来添加自己想要的监控元素。

(2)、CHANNEL

CHANNEL是flume的一个通道组件,对数据有一个缓存的作用。能够得到的数据:

EventPutSuccessCount(成功放入channel的event数量)、ChannelFillPercentage(通道使用比例)、Type(组件类型)、EventPutAttemptCount(尝试放入将event放入channel的次数)、ChannelSize(目前在channel中的event数量)、StartTime(组件开始时间)、StopTime(组件停止时间)、EventTakeSuccessCount(从channel中成功取走的event数量)、ChannelCapacity(通道容量)、EventTakeAttemptCount(尝试从channel中取走event的次数)等。

(3)、SINK

SINK是数据即将离开flume的最后一个组件,它从channel中取走数据,然后发送到缓存系统或者持久化数据库。能得到数据:

BatchCompleteCount(完成的批数量)、ConnectionFailedCount(连接失败数)、EventDrainAttemptCount(尝试提交的event数量)、ConnectionCreatedCount(创建连接数)、Type(组件类型)、BatchEmptyCount(批量取空的数量)、ConnectionClosedCount(关闭连接数量)、EventDrainSuccessCount(成功发送event的数量)、StartTime(组件开始时间)、StopTime(组件停止时间)、BatchUnderflowCount(正处于批量处理的batch数)等。

4、Flume监控是如何实现的?

首先在flume-ng-node中org.apache.flume.node.Application的main方法中,有一个startAllComponents()方法:

[java] view plain copy
  1. private void startAllComponents(  
  2.             MaterializedConfiguration materializedConfiguration) {  
  3.         logger.info("Starting new configuration:{}", materializedConfiguration);  
  4.   
  5.         this.materializedConfiguration = materializedConfiguration;  
  6.   
  7.         for (Entry<String, Channel> entry : materializedConfiguration  
  8.                 .getChannels().entrySet()) {  
  9.             try {  
  10.                 logger.info("Starting Channel " + entry.getKey());  
  11.                 supervisor.supervise(entry.getValue(),  
  12.                         new SupervisorPolicy.AlwaysRestartPolicy(),  
  13.                         LifecycleState.START);  
  14.             } catch (Exception e) {  
  15.                 logger.error("Error while starting {}", entry.getValue(), e);  
  16.             }  
  17.         }  
  18.   
  19.         /* 
  20.          * Wait for all channels to start. 
  21.          */  
  22.         for (Channel ch : materializedConfiguration.getChannels().values()) {  
  23.             while (ch.getLifecycleState() != LifecycleState.START  
  24.                     && !supervisor.isComponentInErrorState(ch)) {  
  25.                 try {  
  26.                     logger.info("Waiting for channel: " + ch.getName()  
  27.                             + " to start. Sleeping for 500 ms");  
  28.                     Thread.sleep(500);  
  29.                 } catch (InterruptedException e) {  
  30.                     logger.error(  
  31.                             "Interrupted while waiting for channel to start.",  
  32.                             e);  
  33.                     Throwables.propagate(e);  
  34.                 }  
  35.             }  
  36.         }  
  37.   
  38.         for (Entry<String, SinkRunner> entry : materializedConfiguration  
  39.                 .getSinkRunners().entrySet()) {  
  40.             try {  
  41.                 logger.info("Starting Sink " + entry.getKey());  
  42.                 supervisor.supervise(entry.getValue(),  
  43.                         new SupervisorPolicy.AlwaysRestartPolicy(),  
  44.                         LifecycleState.START);  
  45.             } catch (Exception e) {  
  46.                 logger.error("Error while starting {}", entry.getValue(), e);  
  47.             }  
  48.         }  
  49.   
  50.         for (Entry<String, SourceRunner> entry : materializedConfiguration  
  51.                 .getSourceRunners().entrySet()) {  
  52.             try {  
  53.                 logger.info("Starting Source " + entry.getKey());  
  54.                 supervisor.supervise(entry.getValue(),  
  55.                         new SupervisorPolicy.AlwaysRestartPolicy(),  
  56.                         LifecycleState.START);  
  57.             } catch (Exception e) {  
  58.                 logger.error("Error while starting {}", entry.getValue(), e);  
  59.             }  
  60.         }  
  61.   
  62.         this.loadMonitoring();  
  63.     }  

其中有一个this.loadMonitoring();来启动监控方法loadMonitoring():

[java] view plain copy
  1. private void loadMonitoring() {  
  2.         Properties systemProps = System.getProperties();  
  3.         Set<String> keys = systemProps.stringPropertyNames();  
  4.         try {  
  5.             if (keys.contains(CONF_MONITOR_CLASS)) {  
  6.                 String monitorType = systemProps  
  7.                         .getProperty(CONF_MONITOR_CLASS);  
  8.                 Class<? extends MonitorService> klass;  
  9.                 try {  
  10.                     // Is it a known type?  
  11.                     klass = MonitoringType.valueOf(monitorType.toUpperCase())  
  12.                             .getMonitorClass();  
  13.                 } catch (Exception e) {  
  14.                     // Not a known type, use FQCN  
  15.                     klass = (Class<? extends MonitorService>) Class  
  16.                             .forName(monitorType);  
  17.                 }  
  18.                 this.monitorServer = klass.newInstance();  
  19.                 Context context = new Context();  
  20.                 for (String key : keys) {  
  21.                     if (key.startsWith(CONF_MONITOR_PREFIX)) {  
  22.                         context.put(  
  23.                                 key.substring(CONF_MONITOR_PREFIX.length()),  
  24.                                 systemProps.getProperty(key));  
  25.                     }  
  26.                 }  
  27.                 monitorServer.configure(context);  
  28.                 monitorServer.start();  
  29.             }  
  30.         } catch (Exception e) {  
  31.             logger.warn("Error starting monitoring. "  
  32.                     + "Monitoring might not be available.", e);  
  33.         }  
  34.   
  35.     }  

其中monitorServer.configure(context);来加载监控服务的配置信息,monitorServer.start();启动监控服务。

这里的monitorServer就会有两种:GangliaServer和HTTPMetricsServer,他们都实现了MonitorService这个接口。这里我们只追踪HTTPMetricsServer。

我们先看HTTPMetricsServer的源码:

[java] view plain copy
  1. public class HTTPMetricsServer implements MonitorService {  
  2.   
  3.   private Server jettyServer;  
  4.   private int port;  
  5.   private static Logger LOG = LoggerFactory.getLogger(HTTPMetricsServer.class);  
  6.   public static int DEFAULT_PORT = 41414;  
  7.   public static String CONFIG_PORT = "port";  
  8.   
  9.   @Override  
  10.   public void start() {  
  11.     jettyServer = new Server();  
  12.     //We can use Contexts etc if we have many urls to handle. For one url,  
  13.     //specifying a handler directly is the most efficient.  
  14.     SelectChannelConnector connector = new SelectChannelConnector();  
  15.     connector.setReuseAddress(true);  
  16.     connector.setPort(port);  
  17.     jettyServer.setConnectors(new Connector[] {connector});  
  18.     jettyServer.setHandler(new HTTPMetricsHandler());  
  19.     try {  
  20.       jettyServer.start();  
  21.       while (!jettyServer.isStarted()) {  
  22.         Thread.sleep(500);  
  23.       }  
  24.     } catch (Exception ex) {  
  25.       LOG.error("Error starting Jetty. JSON Metrics may not be available.", ex);  
  26.     }  
  27.   
  28.   }  
  29.   
  30.   @Override  
  31.   public void stop() {  
  32.     try {  
  33.       jettyServer.stop();  
  34.       jettyServer.join();  
  35.     } catch (Exception ex) {  
  36.       LOG.error("Error stopping Jetty. JSON Metrics may not be available.", ex);  
  37.     }  
  38.   
  39.   }  
  40.   
  41.   @Override  
  42.   public void configure(Context context) {  
  43.     port = context.getInteger(CONFIG_PORT, DEFAULT_PORT);  
  44.   }  
  45.   
  46.   private class HTTPMetricsHandler extends AbstractHandler {  
  47.   
  48.     Type mapType =  
  49.             new TypeToken<Map<String, Map<String, String>>>() {  
  50.             }.getType();  
  51.     Gson gson = new Gson();  
  52.   
  53.     @Override  
  54.     public void handle(String target,  
  55.             HttpServletRequest request,  
  56.             HttpServletResponse response,  
  57.             int dispatch) throws IOException, ServletException {  
  58.       // /metrics is the only place to pull metrics.  
  59.       //If we want to use any other url for something else, we should make sure  
  60.       //that for metrics only /metrics is used to prevent backward  
  61.       //compatibility issues.  
  62.       if(request.getMethod().equalsIgnoreCase("TRACE") || request.getMethod()  
  63.         .equalsIgnoreCase("OPTIONS")) {  
  64.         response.sendError(HttpServletResponse.SC_FORBIDDEN);  
  65.         response.flushBuffer();  
  66.         ((Request) request).setHandled(true);  
  67.         return;  
  68.       }  
  69.       if (target.equals("/")) {  
  70.         response.setContentType("text/html;charset=utf-8");  
  71.         response.setStatus(HttpServletResponse.SC_OK);  
  72.         response.getWriter().write("For Flume metrics please click"  
  73.                 + " <a href = \"./metrics\"> here</a>.");  
  74.         response.flushBuffer();  
  75.         ((Request) request).setHandled(true);  
  76.         return;  
  77.       } else if (target.equalsIgnoreCase("/metrics")) {  
  78.         response.setContentType("application/json;charset=utf-8");  
  79.         response.setStatus(HttpServletResponse.SC_OK);  
  80.         Map<String, Map<String, String>> metricsMap = JMXPollUtil.getAllMBeans();  
  81.         String json = gson.toJson(metricsMap, mapType);  
  82.         response.getWriter().write(json);  
  83.         response.flushBuffer();  
  84.         ((Request) request).setHandled(true);  
  85.         return;  
  86.       }  
  87.       response.sendError(HttpServletResponse.SC_NOT_FOUND);  
  88.       response.flushBuffer();  
  89.       //Not handling the request returns a Not found error page.  
  90.     }  
  91.   }  
  92. }  
其中会初始化一个jettyServer来提供监控数据的访问服务,里面的核心方法还是handle方法,定义了监控数据访问的url,这里的url就是获取监控json格式数据的http地址。那这些监控数据是如何得到的呢?

通过源码我们可以看到Map<String, Map<String, String>> metricsMap = JMXPollUtil.getAllMBeans();具体的数据都是从这条语句得来的,再仔细看可以得知,这些监控数据是同JMX的方式得到的。至于里面具体实现的细节,相对比较复杂,同时也不属于我们讨论的范畴,所以这里不讨论这块。

除了以上的源码,我们需要关注以外,我们还需要关注具体监控组件的源码,这些源码都是在flume-ng-core中的org.apache.flume.instrumentation包下面,所有的监控组件都会继承MonitoredCounterGroup实现xxxCounterMBean接口,MonitoredCounterGroup中定义了一些基本公有的监控属性,xxxCounterMBean定义了获取监控元素的方法接口,具体实现还是在监控组件中实现。我们看MonitoredCounterGroup的源码:

[java] view plain copy
  1. public abstract class MonitoredCounterGroup {  
  2.   
  3.   private static final Logger logger =  
  4.       LoggerFactory.getLogger(MonitoredCounterGroup.class);  
  5.   
  6.   // Key for component's start time in MonitoredCounterGroup.counterMap  
  7.   private static final String COUNTER_GROUP_START_TIME = "start.time";  
  8.   
  9.   // key for component's stop time in MonitoredCounterGroup.counterMap  
  10.   private static final String COUNTER_GROUP_STOP_TIME = "stop.time";  
  11.   
  12.   private final Type type;  
  13.   private final String name;  
  14.   private final Map<String, AtomicLong> counterMap;  
  15.   
  16.   private AtomicLong startTime;  
  17.   private AtomicLong stopTime;  
  18.   private volatile boolean registered = false;  
  19.   
  20.   
  21.   protected MonitoredCounterGroup(Type type, String name, String... attrs) {  
  22.     this.type = type;  
  23.     this.name = name;  
  24.   
  25.     Map<String, AtomicLong> counterInitMap = new HashMap<String, AtomicLong>();  
  26.   
  27.     // Initialize the counters  
  28.     for (String attribute : attrs) {  
  29.       counterInitMap.put(attribute, new AtomicLong(0L));  
  30.     }  
  31.   
  32.     counterMap = Collections.unmodifiableMap(counterInitMap);  
  33.   
  34.     startTime = new AtomicLong(0L);  
  35.     stopTime = new AtomicLong(0L);  
  36.   
  37.   }  
  38.   
  39.   /** 
  40.    * Starts the component 
  41.    * 
  42.    * Initializes the values for the stop time as well as all the keys in the 
  43.    * internal map to zero and sets the start time to the current time in 
  44.    * milliseconds since midnight January 1, 1970 UTC 
  45.    */  
  46.   public void start() {  
  47.   
  48.     register();  
  49.     stopTime.set(0L);  
  50.     for (String counter : counterMap.keySet()) {  
  51.       counterMap.get(counter).set(0L);  
  52.     }  
  53.     startTime.set(System.currentTimeMillis());  
  54.     logger.info("Component type: " + type + ", name: " + name + " started");  
  55.   }  
  56.   
  57.   /** 
  58.    * Registers the counter. 
  59.    * This method is exposed only for testing, and there should be no need for 
  60.    * any implementations to call this method directly. 
  61.    */  
  62.   @VisibleForTesting  
  63.   void register() {  
  64.     if (!registered) {  
  65.       try {  
  66.         ObjectName objName = new ObjectName("org.apache.flume."  
  67.                 + type.name().toLowerCase() + ":type=" + this.name);  
  68.   
  69.         if (ManagementFactory.getPlatformMBeanServer().isRegistered(objName)) {  
  70.           logger.debug("Monitored counter group for type: " + type + ", name: "  
  71.               + name + ": Another MBean is already registered with this name. "  
  72.               + "Unregistering that pre-existing MBean now...");  
  73.           ManagementFactory.getPlatformMBeanServer().unregisterMBean(objName);  
  74.           logger.debug("Monitored counter group for type: " + type + ", name: "  
  75.               + name + ": Successfully unregistered pre-existing MBean.");  
  76.         }  
  77.         ManagementFactory.getPlatformMBeanServer().registerMBean(this, objName);  
  78.         logger.info("Monitored counter group for type: " + type + ", name: "  
  79.             + name + ": Successfully registered new MBean.");  
  80.         registered = true;  
  81.       } catch (Exception ex) {  
  82.         logger.error("Failed to register monitored counter group for type: "  
  83.                 + type + ", name: " + name, ex);  
  84.       }  
  85.     }  
  86.   }  
  87.   
  88.   /** 
  89.    * Shuts Down the Component 
  90.    * 
  91.    * Used to indicate that the component is shutting down. 
  92.    * 
  93.    * Sets the stop time and then prints out the metrics from 
  94.    * the internal map of keys to values for the following components: 
  95.    * 
  96.    * - ChannelCounter 
  97.    * - ChannelProcessorCounter 
  98.    * - SinkCounter 
  99.    * - SinkProcessorCounter 
  100.    * - SourceCounter 
  101.    */  
  102.   public void stop() {  
  103.   
  104.     // Sets the stopTime for the component as the current time in milliseconds  
  105.     stopTime.set(System.currentTimeMillis());  
  106.   
  107.     // Prints out a message indicating that this component has been stopped  
  108.     logger.info("Component type: " + type + ", name: " + name + " stopped");  
  109.   
  110.     // Retrieve the type for this counter group  
  111.     final String typePrefix = type.name().toLowerCase();  
  112.   
  113.     // Print out the startTime for this component  
  114.     logger.info("Shutdown Metric for type: " + type + ", "  
  115.       + "name: " + name + ". "  
  116.       + typePrefix + "." + COUNTER_GROUP_START_TIME  
  117.       + " == " + startTime);  
  118.   
  119.     // Print out the stopTime for this component  
  120.     logger.info("Shutdown Metric for type: " + type + ", "  
  121.       + "name: " + name + ". "  
  122.       + typePrefix + "." + COUNTER_GROUP_STOP_TIME  
  123.       + " == " + stopTime);  
  124.   
  125.     // Retrieve and sort counter group map keys  
  126.     final List<String> mapKeys = new ArrayList<String>(counterMap.keySet());  
  127.   
  128.     Collections.sort(mapKeys);  
  129.   
  130.     // Cycle through and print out all the key value pairs in counterMap  
  131.     for (final String counterMapKey : mapKeys) {  
  132.   
  133.       // Retrieves the value from the original counterMap.  
  134.       final long counterMapValue = get(counterMapKey);  
  135.   
  136.       logger.info("Shutdown Metric for type: " + type + ", "  
  137.         + "name: " + name + ". "  
  138.         + counterMapKey + " == " + counterMapValue);  
  139.     }  
  140.   }  
  141.   
  142.   /** 
  143.    * Returns when this component was first started 
  144.    * 
  145.    * @return 
  146.    */  
  147.   public long getStartTime() {  
  148.     return startTime.get();  
  149.   }  
  150.   
  151.   /** 
  152.    * Returns when this component was stopped 
  153.    * 
  154.    * @return 
  155.    */  
  156.   public long getStopTime() {  
  157.     return stopTime.get();  
  158.   }  
  159.   
  160.   @Override  
  161.   public final String toString() {  
  162.     StringBuilder sb = new StringBuilder(type.name()).append(":");  
  163.     sb.append(name).append("{");  
  164.     boolean first = true;  
  165.     Iterator<String> counterIterator = counterMap.keySet().iterator();  
  166.     while (counterIterator.hasNext()) {  
  167.       if (first) {  
  168.         first = false;  
  169.       } else {  
  170.         sb.append(", ");  
  171.       }  
  172.       String counterName = counterIterator.next();  
  173.       sb.append(counterName).append("=").append(get(counterName));  
  174.     }  
  175.     sb.append("}");  
  176.   
  177.     return sb.toString();  
  178.   }  
  179.   
  180.   
  181.   /** 
  182.    * Retrieves the current value for this key 
  183.    * 
  184.    * @param counter The key for this metric 
  185.    * @return The current value for this key 
  186.    */  
  187.   protected long get(String counter) {  
  188.     return counterMap.get(counter).get();  
  189.   }  
  190.   
  191.   /** 
  192.    * Sets the value for this key to the given value 
  193.    * 
  194.    * @param counter The key for this metric 
  195.    * @param value The new value for this key 
  196.    */  
  197.   protected void set(String counter, long value) {  
  198.     counterMap.get(counter).set(value);  
  199.   }  
  200.   
  201.   /** 
  202.    * Atomically adds the delta to the current value for this key 
  203.    * 
  204.    * @param counter The key for this metric 
  205.    * @param delta 
  206.    * @return The updated value for this key 
  207.    */  
  208.   protected long addAndGet(String counter, long delta) {  
  209.     return counterMap.get(counter).addAndGet(delta);  
  210.   }  
  211.   
  212.   /** 
  213.    * Atomically increments the current value for this key by one 
  214.    * 
  215.    * @param counter The key for this metric 
  216.    * @return The updated value for this key 
  217.    */  
  218.   protected long increment(String counter) {  
  219.     return counterMap.get(counter).incrementAndGet();  
  220.   }  
  221.   
  222.   /** 
  223.    * Component Enum Constants 
  224.    * 
  225.    * Used by each component's constructor to distinguish which type the 
  226.    * component is. 
  227.    */  
  228.   public static enum Type {  
  229.     SOURCE,  
  230.     CHANNEL_PROCESSOR,  
  231.     CHANNEL,  
  232.     SINK_PROCESSOR,  
  233.     SINK,  
  234.     INTERCEPTOR,  
  235.     SERIALIZER,  
  236.     OTHER  
  237.   };  
  238.   
  239.   public String getType(){  
  240.     return type.name();  
  241.   }  
  242. }  
其中主要包括:

初始化构造方法protected MonitoredCounterGroup(Type type, String name, String... attrs):初始化组件类型,和一些监控元素;

启动方法start():启动监控组件;

停止方法stop():停止监控组件;

监控组件的注册方法register():监控组件必须在监控服务MBeanServer中注册以后才能正常监控。

然后我们看获取监控元素信息的方法接口,我们以SourceCounterMBean为例子:

[java] view plain copy
  1. public interface SourceCounterMBean {  
  2.   
  3.   long getEventReceivedCount();  
  4.   
  5.   long getEventAcceptedCount();  
  6.   
  7.   long getAppendReceivedCount();  
  8.   
  9.   long getAppendAcceptedCount();  
  10.   
  11.   long getAppendBatchReceivedCount();  
  12.   
  13.   long getAppendBatchAcceptedCount();  
  14.   
  15.   long getStartTime();  
  16.   
  17.   long getStopTime();  
  18.   
  19.   String getType();  
  20.   
  21.   long getOpenConnectionCount();  
  22.     
  23.   String getIp();  
  24.     
  25.   String getPort();  
  26. }  
如果我们要自定义监控元素,除了在监控组件(xxxCounter)中定义监控属性以外,在这里(xxxCounterMBean)也必须要定义一个获取值得方法。

我们以flume中AvroSource的监控为例子,监控对象是AvroSource,与监控有关的类有SourceCounter、SourceCounterMBean、MonitoredCounterGroup这三个,其中SourceCounter是我们的监控组件,它继承MonitoredCounterGroup并且实现SourceCounterMBean接口,具体要监控的元素是在SourceCounter、MonitoredCounterGroup这两个类中定义的,获取监控元素的方法是在SourceCounterMBean接口中定义的,然后我们会在AvroSource类中初始化一个我们的监控组件SourceCounter,所有的监控元素的值都是在监控对象AvroSource中设值,然后获取值是通过SourceCounterMBean的接口方法来获取。

具体的监控数据流向图:

Flume之监控

熟悉了以上的流程,我们也可以开发自己想要的监控组件,得到完全满足自己需求的所有监控元素。

这里如果只是在原有基础之上添加一些组件的监控元素,比较简单,只需要在监控组件(xxxCounter)中添加你需要的监控元素属性,然后在(xxxCounterMBean)中添加get方法(只有这里添加get方法,JMX监控服务才能顺利获取到值),然后在相应的组件(source、channel、sink)中set值。

如果是自定义监控组件,你只需要添加xxxCounter、xxxCounterMBean,以及你自定义的xxx(source、channel、sink),这里需要注意一点,就是命名规范的问题,需要严格按照上面的命令规范JMX才能正常识别。例如,这里如果你把获取值得接口类xxxCounterMBean命名为xxxCounterMbean,这样就出问题。

flume监控数据截图:

Flume之监控


flume监控web页面:

Flume之监控


Flume之监控