dce309c33bfce3f50a8365f5902c3157a6c9fae1
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.dataprovider.data;
23
24 import java.io.File;
25 import java.io.IOException;
26 import java.lang.management.ClassLoadingMXBean;
27 import java.lang.management.GarbageCollectorMXBean;
28 import java.lang.management.ManagementFactory;
29 import java.lang.management.MemoryMXBean;
30 import java.lang.management.OperatingSystemMXBean;
31 import java.lang.management.RuntimeMXBean;
32 import java.lang.management.ThreadMXBean;
33 import java.lang.reflect.Method;
34 import java.nio.file.Files;
35 import java.nio.file.Path;
36 import java.text.DecimalFormat;
37 import java.text.DecimalFormatSymbols;
38 import java.text.NumberFormat;
39 import java.util.Iterator;
40 import java.util.Locale;
41 import java.util.concurrent.Callable;
42 import java.util.regex.Matcher;
43 import java.util.regex.Pattern;
44 import java.util.stream.Stream;
45
46 import org.osgi.framework.Bundle;
47 import org.osgi.framework.BundleContext;
48 import org.osgi.framework.FrameworkUtil;
49
50 public class SystemInfo {
51         private static NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH));
52         private static NumberFormat fmtDec = new DecimalFormat("###,###.##", new DecimalFormatSymbols(Locale.ENGLISH));
53         private static NumberFormat fmtD = new DecimalFormat("###,##0.000", new DecimalFormatSymbols(Locale.ENGLISH));
54         private static OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
55         protected static boolean showMemoryPools = false;
56
57         public static String getMdSalVersion(String def) {
58                 return getMdSalVersion("", def);
59         }       
60         public static String getYangToolsVersion(String def) {
61                 return getYangToolsVersion("", def);
62         }       
63         
64         public static String getMdSalVersion(String baseOdlDirectory,String def) {
65                 return getFeatureVersionByFolder(baseOdlDirectory,"system/org/opendaylight/mdsal/mdsal-binding-api/",def);
66         }
67         public static String getYangToolsVersion(String baseOdlDirectory,String def) {
68                 return getFeatureVersionByFolder(baseOdlDirectory,"system/org/opendaylight/yangtools/odl-yangtools-common/",def);
69         }
70         private static String getFeatureVersionByFolder(String baseOdlDirectory,String dir,String def) {
71                                 final String regex = "^[0-9]+\\.[0-9]+\\.[0-9]+(-SNAPSHOT)?$";
72                 Stream<Path> entries=null;
73                 try {
74                         if(baseOdlDirectory!=null && baseOdlDirectory.length()>0 && !baseOdlDirectory.endsWith("/")) {
75                                 baseOdlDirectory+="/";
76                         }
77                         entries = Files.list(new File(baseOdlDirectory+dir).toPath());
78                 } catch (IOException e) {
79                         
80                 }
81                 if(entries==null) {
82                         return def;
83                 }
84                 final Pattern pattern = Pattern.compile(regex);
85                 
86                 Iterator<Path> it = entries.iterator();
87                 Path p;File f;
88                 while(it.hasNext()) {
89                     p = it.next();
90                         f=p.toFile();
91                         if(f.isDirectory()) {
92                                 final Matcher matcher = pattern.matcher(f.getName().toString());
93                                 if(matcher.find()) {
94                                         def= matcher.group(0);
95                                         break;
96                                 }
97                         }
98                 }
99                 entries.close();
100                 return def;
101         }
102         public static String get() throws Exception {
103                 StringBuilder sb = new StringBuilder();
104                 int maxNameLen;
105
106                 RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
107                 ThreadMXBean threads = ManagementFactory.getThreadMXBean();
108                 MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
109                 ClassLoadingMXBean cl = ManagementFactory.getClassLoadingMXBean();
110
111                 //
112                 // print Karaf informations
113                 //
114                 maxNameLen = 25;
115                 sb.append("Karaf\n");
116                 printValue(sb, "Karaf version", maxNameLen, System.getProperty("karaf.version"));
117                 printValue(sb, "Karaf home", maxNameLen, System.getProperty("karaf.home"));
118                 printValue(sb, "Karaf base", maxNameLen, System.getProperty("karaf.base"));
119                 String osgi = getOsgiFramework();
120                 if (osgi != null) {
121                         printValue(sb, "OSGi Framework", maxNameLen, osgi);
122                 }
123
124                 sb.append("JVM\n");
125                 printValue(sb, "Java Virtual Machine", maxNameLen, runtime.getVmName() + " version " + runtime.getVmVersion());
126                 printValue(sb, "Version", maxNameLen, System.getProperty("java.version"));
127                 printValue(sb, "Vendor", maxNameLen, runtime.getVmVendor());
128                 printValue(sb, "Pid", maxNameLen, getPid());
129                 printValue(sb, "Uptime", maxNameLen, printDuration(runtime.getUptime()));
130                 try {
131                         Class<?> sunOS = Class.forName("com.sun.management.OperatingSystemMXBean");
132                         printValue(sb, "Process CPU time", maxNameLen,
133                                         printDuration(getValueAsLong(sunOS, "getProcessCpuTime") / 1000000.0));
134                         printValue(sb, "Process CPU load", maxNameLen, fmtDec.format(getValueAsDouble(sunOS, "getProcessCpuLoad")));
135                         printValue(sb, "System CPU load", maxNameLen, fmtDec.format(getValueAsDouble(sunOS, "getSystemCpuLoad")));
136                 } catch (Throwable t) {
137                 }
138                 try {
139                         Class<?> unixOS = Class.forName("com.sun.management.UnixOperatingSystemMXBean");
140                         printValue(sb, "Open file descriptors", maxNameLen,
141                                         printLong(getValueAsLong(unixOS, "getOpenFileDescriptorCount")));
142                         printValue(sb, "Max file descriptors", maxNameLen,
143                                         printLong(getValueAsLong(unixOS, "getMaxFileDescriptorCount")));
144                 } catch (Throwable t) {
145                 }
146                 printValue(sb, "Total compile time", maxNameLen,
147                                 printDuration(ManagementFactory.getCompilationMXBean().getTotalCompilationTime()));
148
149                 sb.append("Threads\n");
150                 printValue(sb, "Live threads", maxNameLen, Integer.toString(threads.getThreadCount()));
151                 printValue(sb, "Daemon threads", maxNameLen, Integer.toString(threads.getDaemonThreadCount()));
152                 printValue(sb, "Peak", maxNameLen, Integer.toString(threads.getPeakThreadCount()));
153                 printValue(sb, "Total started", maxNameLen, Long.toString(threads.getTotalStartedThreadCount()));
154
155                 sb.append("Memory\n");
156                 printValue(sb, "Current heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getUsed()));
157                 printValue(sb, "Maximum heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getMax()));
158                 printValue(sb, "Committed heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getCommitted()));
159                 printValue(sb, "Pending objects", maxNameLen, Integer.toString(mem.getObjectPendingFinalizationCount()));
160                 for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
161                         String val = "Name = '" + gc.getName() + "', Collections = " + gc.getCollectionCount() + ", Time = "
162                                         + printDuration(gc.getCollectionTime());
163                         printValue(sb, "Garbage collector", maxNameLen, val);
164                 }
165
166 //              if (showMemoryPools) {
167 //                      List<MemoryPoolMXBean> memoryPools = ManagementFactory.getMemoryPoolMXBeans();
168 //                      sb.append("Memory Pools\n");
169 //                      printValue(sb, "Total Memory Pools", maxNameLen, printLong(memoryPools.size()));
170 //                      String spaces4 = "   ";
171 //                      for (MemoryPoolMXBean pool : memoryPools) {
172 //                              String name = pool.getName();
173 //                              MemoryType type = pool.getType();
174 //                              printValue(sb, spaces4 + "Pool (" + type + ")", maxNameLen, name);
175 //
176 //                              // PeakUsage/CurrentUsage
177 //                              MemoryUsage peakUsage = pool.getPeakUsage();
178 //                              MemoryUsage usage = pool.getUsage();
179 //
180 //                              if (usage != null && peakUsage != null) {
181 //                                      long init = peakUsage.getInit();
182 //                                      long used = peakUsage.getUsed();
183 //                                      long committed = peakUsage.getCommitted();
184 //                                      long max = peakUsage.getMax();
185 //                                      sb.append(spaces4 + spaces4 + "Peak Usage\n");
186 //                                      printValue(sb, spaces4 + spaces4 + spaces4 + "init", maxNameLen, printLong(init));
187 //                                      printValue(sb, spaces4 + spaces4 + spaces4 + "used", maxNameLen, printLong(used));
188 //                                      printValue(sb, spaces4 + spaces4 + spaces4 + "committed", maxNameLen, printLong(committed));
189 //                                      printValue(sb, spaces4 + spaces4 + spaces4 + "max", maxNameLen, printLong(max));
190 //
191 //                                      init = usage.getInit();
192 //                                      used = usage.getUsed();
193 //                                      committed = usage.getCommitted();
194 //                                      max = usage.getMax();
195 //                                      sb.append(spaces4 + spaces4 + "Current Usage\n");
196 //                                      printValue(sb, spaces4 + spaces4 + spaces4 + "init", maxNameLen, printLong(init));
197 //                                      printValue(sb, spaces4 + spaces4 + spaces4 + "used", maxNameLen, printLong(used));
198 //                                      printValue(sb, spaces4 + spaces4 + spaces4 + "committed", maxNameLen, printLong(committed));
199 //                                      printValue(sb, spaces4 + spaces4 + spaces4 + "max", maxNameLen, printLong(max));
200 //                              }
201 //                      }
202 //              }
203
204                 sb.append("Classes\n");
205                 printValue(sb, "Current classes loaded", maxNameLen, printLong(cl.getLoadedClassCount()));
206                 printValue(sb, "Total classes loaded", maxNameLen, printLong(cl.getTotalLoadedClassCount()));
207                 printValue(sb, "Total classes unloaded", maxNameLen, printLong(cl.getUnloadedClassCount()));
208
209                 sb.append("Operating system\n");
210                 printValue(sb, "Name", maxNameLen, os.getName() + " version " + os.getVersion());
211                 printValue(sb, "Architecture", maxNameLen, os.getArch());
212                 printValue(sb, "Processors", maxNameLen, Integer.toString(os.getAvailableProcessors()));
213                 try {
214                         printValue(sb, "Total physical memory", maxNameLen,
215                                         printSizeInKb(getSunOsValueAsLong(os, "getTotalPhysicalMemorySize")));
216                         printValue(sb, "Free physical memory", maxNameLen,
217                                         printSizeInKb(getSunOsValueAsLong(os, "getFreePhysicalMemorySize")));
218                         printValue(sb, "Committed virtual memory", maxNameLen,
219                                         printSizeInKb(getSunOsValueAsLong(os, "getCommittedVirtualMemorySize")));
220                         printValue(sb, "Total swap space", maxNameLen,
221                                         printSizeInKb(getSunOsValueAsLong(os, "getTotalSwapSpaceSize")));
222                         printValue(sb, "Free swap space", maxNameLen,
223                                         printSizeInKb(getSunOsValueAsLong(os, "getFreeSwapSpaceSize")));
224                 } catch (Throwable t) {
225                 }
226                 return sb.toString();
227         }
228
229         private static String getPid() {
230                 // In Java 9 the new process API can be used:
231                 // long pid = ProcessHandle.current().getPid();
232                 String name = ManagementFactory.getRuntimeMXBean().getName();
233                 String[] parts = name.split("@");
234                 return parts[0];
235         }
236
237         private static long getSunOsValueAsLong(OperatingSystemMXBean os, String name) throws Exception {
238                 Method mth = os.getClass().getMethod(name);
239                 return (Long) mth.invoke(os);
240         }
241
242         private static long getValueAsLong(Class<?> osImpl, String name) throws Exception {
243                 if (osImpl.isInstance(os)) {
244                         Method mth = osImpl.getMethod(name);
245                         return (Long) mth.invoke(os);
246                 }
247                 return -1;
248         }
249
250         private static double getValueAsDouble(Class<?> osImpl, String name) throws Exception {
251                 if (osImpl.isInstance(os)) {
252                         Method mth = osImpl.getMethod(name);
253                         return (Double) mth.invoke(os);
254                 }
255                 return -1;
256         }
257
258         private static String printLong(long i) {
259                 return fmtI.format(i);
260         }
261
262         private static String printSizeInKb(double size) {
263                 return fmtI.format((long) (size / 1024)) + " kbytes";
264         }
265
266         protected static String printDuration(double uptime) {
267                 uptime /= 1000;
268                 if (uptime < 60) {
269                         return fmtD.format(uptime) + " seconds";
270                 }
271                 uptime /= 60;
272                 if (uptime < 60) {
273                         long minutes = (long) uptime;
274                         String s = fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
275                         return s;
276                 }
277                 uptime /= 60;
278                 if (uptime < 24) {
279                         long hours = (long) uptime;
280                         long minutes = (long) ((uptime - hours) * 60);
281                         String s = fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
282                         if (minutes != 0) {
283                                 s += " " + fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
284                         }
285                         return s;
286                 }
287                 uptime /= 24;
288                 long days = (long) uptime;
289                 long hours = (long) ((uptime - days) * 24);
290                 String s = fmtI.format(days) + (days > 1 ? " days" : " day");
291                 if (hours != 0) {
292                         s += " " + fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
293                 }
294                 return s;
295         }
296
297         static void printSysValue(StringBuilder sb, String prop, int pad) {
298                 printValue(sb, prop, pad, System.getProperty(prop));
299         }
300
301         static void printValue(StringBuilder sb, String name, int pad, String value) {
302                 sb.append("  " + // SimpleAnsi.INTENSITY_BOLD +
303                                 name + // SimpleAnsi.INTENSITY_NORMAL +
304                                 spaces(pad - name.length()) + "   " + value + "\n");
305         }
306
307         static String spaces(int nb) {
308                 StringBuilder sb = new StringBuilder();
309                 for (int i = 0; i < nb; i++) {
310                         sb.append(' ');
311                 }
312                 return sb.toString();
313         }
314
315         static String getOsgiFramework() {
316                 try {
317                         Callable<String> call = new Callable<String>() {
318                                 @Override
319                                 public String call() throws Exception {
320                                         BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext();
321                                         Bundle sysBundle = context.getBundle(0);
322                                         return sysBundle.getSymbolicName() + "-" + sysBundle.getVersion();
323                                 }
324                         };
325                         return call.call();
326                 } catch (Throwable t) {
327                         // We're not in OSGi, just safely return null
328                         return null;
329                 }
330         }
331 }