View Javadoc
1   /*
2    * Copyright 2012-2019 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.timer;
17  
18  import java.io.ByteArrayOutputStream;
19  import java.io.OutputStream;
20  import java.util.Arrays;
21  import java.util.List;
22  import java.util.function.Supplier;
23  import java.util.stream.Collectors;
24  
25  import org.apache.commons.text.StringEscapeUtils;
26  import org.codelibs.core.timer.TimeoutTarget;
27  import org.codelibs.fess.Constants;
28  import org.codelibs.fess.es.client.FessEsClient;
29  import org.codelibs.fess.util.ComponentUtil;
30  import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
31  import org.elasticsearch.common.xcontent.ToXContent;
32  import org.elasticsearch.common.xcontent.XContentBuilder;
33  import org.elasticsearch.common.xcontent.XContentFactory;
34  import org.elasticsearch.monitor.jvm.JvmStats;
35  import org.elasticsearch.monitor.jvm.JvmStats.BufferPool;
36  import org.elasticsearch.monitor.jvm.JvmStats.Classes;
37  import org.elasticsearch.monitor.jvm.JvmStats.GarbageCollectors;
38  import org.elasticsearch.monitor.jvm.JvmStats.Mem;
39  import org.elasticsearch.monitor.jvm.JvmStats.Threads;
40  import org.elasticsearch.monitor.os.OsProbe;
41  import org.elasticsearch.monitor.os.OsStats;
42  import org.elasticsearch.monitor.process.ProcessProbe;
43  import org.slf4j.Logger;
44  import org.slf4j.LoggerFactory;
45  
46  public class SystemMonitorTarget implements TimeoutTarget {
47      private static final Logger logger = LoggerFactory.getLogger(SystemMonitorTarget.class);
48  
49      protected StringBuilder append(final StringBuilder buf, final String key, final Supplier<Object> supplier) {
50          buf.append('"').append(key).append("\":");
51          try {
52              final Object value = supplier.get();
53              if (value == null) {
54                  buf.append("null");
55              } else if (value instanceof Integer) {
56                  buf.append(((Integer) value).intValue());
57              } else if (value instanceof Long) {
58                  buf.append(((Long) value).longValue());
59              } else if (value instanceof Short) {
60                  buf.append(((Short) value).shortValue());
61              } else if (value instanceof double[]) {
62                  buf.append(Arrays.toString((double[]) value));
63              } else {
64                  buf.append('"').append(StringEscapeUtils.escapeJson(value.toString())).append('"');
65              }
66          } catch (final Exception e) {
67              buf.append("null");
68          }
69          return buf;
70      }
71  
72      @Override
73      public void expired() {
74          final StringBuilder buf = new StringBuilder(1000);
75  
76          buf.append("[SYSTEM MONITOR] ");
77          buf.append('{');
78  
79          appendOsStats(buf);
80          appendProcessStats(buf);
81          appendJvmStats(buf);
82          appendElasticsearchStats(buf);
83  
84          append(buf, "timestamp", () -> System.currentTimeMillis());
85          buf.append('}');
86  
87          logger.info(buf.toString());
88      }
89  
90      private void appendJvmStats(final StringBuilder buf) {
91          buf.append("\"jvm\":{");
92          final JvmStats jvmStats = JvmStats.jvmStats();
93          final Mem mem = jvmStats.getMem();
94          buf.append("\"memory\":{");
95          buf.append("\"heap\":{");
96          append(buf, "used", () -> mem.getHeapUsed().getBytes()).append(',');
97          append(buf, "committed", () -> mem.getHeapCommitted().getBytes()).append(',');
98          append(buf, "max", () -> mem.getHeapMax().getBytes()).append(',');
99          append(buf, "percent", () -> mem.getHeapUsedPercent());
100         buf.append("},");
101         buf.append("\"non_heap\":{");
102         append(buf, "used", () -> mem.getNonHeapUsed().getBytes()).append(',');
103         append(buf, "committed", () -> mem.getNonHeapCommitted().getBytes());
104         buf.append('}');
105         buf.append("},");
106         final List<BufferPool> bufferPools = jvmStats.getBufferPools();
107         buf.append("\"pools\":{");
108         buf.append(bufferPools.stream().map(p -> {
109             final StringBuilder b = new StringBuilder();
110             b.append('"').append(StringEscapeUtils.escapeJson(p.getName())).append("\":{");
111             append(b, "count", () -> p.getCount()).append(',');
112             append(b, "used", () -> p.getUsed().getBytes()).append(',');
113             append(b, "capacity", () -> p.getTotalCapacity().getBytes()).append('}');
114             return b.toString();
115         }).collect(Collectors.joining(",")));
116         buf.append("},");
117         final GarbageCollectors gc = jvmStats.getGc();
118         buf.append("\"gc\":{");
119         buf.append(Arrays.stream(gc.getCollectors()).map(c -> {
120             final StringBuilder b = new StringBuilder();
121             b.append('"').append(StringEscapeUtils.escapeJson(c.getName())).append("\":{");
122             append(b, "count", () -> c.getCollectionCount()).append(',');
123             append(b, "time", () -> c.getCollectionTime().getMillis()).append('}');
124             return b.toString();
125         }).collect(Collectors.joining(",")));
126         buf.append("},");
127         final Threads threads = jvmStats.getThreads();
128         buf.append("\"threads\":{");
129         append(buf, "count", () -> threads.getCount()).append(',');
130         append(buf, "peak", () -> threads.getPeakCount());
131         buf.append("},");
132         final Classes classes = jvmStats.getClasses();
133         buf.append("\"classes\":{");
134         append(buf, "loaded", () -> classes.getLoadedClassCount()).append(',');
135         append(buf, "total_loaded", () -> classes.getTotalLoadedClassCount()).append(',');
136         append(buf, "unloaded", () -> classes.getUnloadedClassCount());
137         buf.append("},");
138         append(buf, "uptime", () -> jvmStats.getUptime().getMillis());
139         buf.append("},");
140     }
141 
142     private void appendProcessStats(final StringBuilder buf) {
143         buf.append("\"process\":{");
144         final ProcessProbe processProbe = ProcessProbe.getInstance();
145         buf.append("\"file_descriptor\":{");
146         append(buf, "open", () -> processProbe.getOpenFileDescriptorCount()).append(',');
147         append(buf, "max", () -> processProbe.getMaxFileDescriptorCount());
148         buf.append("},");
149         buf.append("\"cpu\":{");
150         append(buf, "percent", () -> processProbe.getProcessCpuPercent()).append(',');
151         append(buf, "total", () -> processProbe.getProcessCpuTotalTime());
152         buf.append("},");
153         buf.append("\"virtual_memory\":{");
154         append(buf, "total", () -> processProbe.getTotalVirtualMemorySize());
155         buf.append('}');
156         buf.append("},");
157     }
158 
159     private void appendOsStats(final StringBuilder buf) {
160         buf.append("\"os\":{");
161         final OsProbe osProbe = OsProbe.getInstance();
162         buf.append("\"memory\":{");
163         buf.append("\"physical\":{");
164         append(buf, "free", () -> osProbe.getFreePhysicalMemorySize()).append(',');
165         append(buf, "total", () -> osProbe.getTotalPhysicalMemorySize());
166         buf.append("},");
167         buf.append("\"swap_space\":{");
168         append(buf, "free", () -> osProbe.getFreeSwapSpaceSize()).append(',');
169         append(buf, "total", () -> osProbe.getTotalSwapSpaceSize());
170         buf.append('}');
171         buf.append("},");
172         buf.append("\"cpu\":{");
173         append(buf, "percent", () -> osProbe.getSystemCpuPercent());
174         final OsStats osStats = osProbe.osStats();
175         buf.append("},");
176         append(buf, "load_averages", () -> osStats.getCpu().getLoadAverage());
177         buf.append("},");
178     }
179 
180     private void appendElasticsearchStats(final StringBuilder buf) {
181         String stats = null;
182         try {
183             final FessEsClient esClient = ComponentUtil.getFessEsClient();
184             final NodesStatsResponse response =
185                     esClient.admin().cluster().prepareNodesStats().setIngest(false).setBreaker(false).setDiscovery(false).setFs(true)
186                             .setHttp(true).setIndices(true).setJvm(true).setOs(true).setProcess(true).setScript(false).setThreadPool(true)
187                             .setTransport(true).execute().actionGet(10000L);
188             final XContentBuilder builder = XContentFactory.jsonBuilder();
189             builder.startObject();
190             response.toXContent(builder, ToXContent.EMPTY_PARAMS);
191             builder.endObject();
192             builder.flush();
193             try (OutputStream out = builder.getOutputStream()) {
194                 stats = ((ByteArrayOutputStream) out).toString(Constants.UTF_8);
195             }
196         } catch (final Exception e) {
197             logger.debug("Failed to access Elasticsearch stats.", e);
198         }
199         buf.append("\"elasticsearch\":").append(stats).append(',');
200     }
201 }