forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStatsCollector.java
More file actions
2207 lines (1993 loc) · 117 KB
/
StatsCollector.java
File metadata and controls
2207 lines (1993 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.server;
import static com.cloud.configuration.ConfigurationManagerImpl.DELETE_QUERY_BATCH_SIZE;
import static com.cloud.utils.NumbersUtil.toHumanReadableSize;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.RuntimeMXBean;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.inject.Inject;
import com.cloud.utils.DateUtil;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import org.apache.cloudstack.management.ManagementServerHost;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.utils.bytescale.ByteScaleUtils;
import org.apache.cloudstack.utils.graphite.GraphiteClient;
import org.apache.cloudstack.utils.graphite.GraphiteException;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import org.apache.cloudstack.utils.usage.UsageUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.Level;
import org.influxdb.BatchOptions;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.influxdb.dto.Pong;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.GetStorageStatsCommand;
import com.cloud.agent.api.HostStatsEntry;
import com.cloud.agent.api.VgpuTypesInfo;
import com.cloud.agent.api.VmDiskStatsEntry;
import com.cloud.agent.api.VmNetworkStatsEntry;
import com.cloud.agent.api.VmStatsEntry;
import com.cloud.agent.api.VmStatsEntryBase;
import com.cloud.agent.api.VolumeStatsEntry;
import com.cloud.api.ApiSessionListener;
import com.cloud.capacity.CapacityManager;
import com.cloud.cluster.ClusterManager;
import com.cloud.cluster.ClusterManagerListener;
import com.cloud.cluster.ClusterServicePdu;
import com.cloud.cluster.ManagementServerHostVO;
import com.cloud.cluster.ManagementServerStatusVO;
import com.cloud.cluster.dao.ManagementServerHostDao;
import com.cloud.cluster.dao.ManagementServerHostPeerDao;
import com.cloud.cluster.dao.ManagementServerStatusDao;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.VlanDao;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.gpu.dao.HostGpuGroupsDao;
import com.cloud.host.Host;
import com.cloud.host.HostStats;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.as.AutoScaleManager;
import com.cloud.org.Cluster;
import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceState;
import com.cloud.serializer.GsonHelper;
import com.cloud.storage.ImageStoreDetailsUtil;
import com.cloud.storage.ScopeType;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StorageManager;
import com.cloud.storage.StorageStats;
import com.cloud.storage.VolumeStats;
import com.cloud.storage.VolumeStatsVO;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.dao.VolumeStatsDao;
import com.cloud.user.UserStatisticsVO;
import com.cloud.user.VmDiskStatisticsVO;
import com.cloud.user.dao.UserStatisticsDao;
import com.cloud.user.dao.VmDiskStatisticsDao;
import com.cloud.utils.LogUtils;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentMethodInterceptable;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DbProperties;
import com.cloud.utils.db.DbUtil;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.MacAddress;
import com.cloud.utils.script.Script;
import com.cloud.vm.NicVO;
import com.cloud.vm.UserVmManager;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.VmDiskStats;
import com.cloud.vm.VmNetworkStats;
import com.cloud.vm.VmStats;
import com.cloud.vm.VmStatsVO;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.dao.VmStatsDao;
import com.codahale.metrics.JvmAttributeGaugeSet;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.MetricSet;
import com.codahale.metrics.jvm.BufferPoolMetricSet;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.codahale.metrics.jvm.ThreadStatesGaugeSet;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.sun.management.OperatingSystemMXBean;
/**
* Provides real time stats for various agent resources up to x seconds
*
* @startuml
*
* StatsCollector -> ClusterManager : register
* ClusterManager -> StatsCollector : onManagementNodeJoined
* StatsCollector -> list : add MS
* ClusterManager -> StatsCollector : onManagementNodeJoined
* StatsCollector -> list : add MS to send list
* StatsCollector -> collector : update own status
* StatsCollector -> list : get all ms ids
* StatsCollector -> ClusterManager : update status for my (ms id) to all ms_ids
* ClusterManager -> ClusterManager : update ms_ids on status on (ms id)
* ClusterManager -> StatsCollector : onManagementNodeLeft
* StatsCollector -> list : add MS
* ClusterManager -> StatsCollector : status data updated for (ms id)
* StatsCollector -> StatsCollector : update entry for (ms id)
* ClusterManager -> StatsCollector : onManagementNodeLeft
* StatsCollector -> list : add MS
* @enduml
*/
@Component
public class StatsCollector extends ManagerBase implements ComponentMethodInterceptable, Configurable, DbStatsCollection {
public static enum ExternalStatsProtocol {
NONE("none"), GRAPHITE("graphite"), INFLUXDB("influxdb");
String _type;
ExternalStatsProtocol(String type) {
_type = type;
}
@Override
public String toString() {
return _type;
}
}
private static final int UNDEFINED_PORT_VALUE = -1;
/**
* Default value for the Graphite connection port: {@value}
*/
private static final int GRAPHITE_DEFAULT_PORT = 2003;
/**
* Default value for the InfluxDB connection port: {@value}
*/
private static final int INFLUXDB_DEFAULT_PORT = 8086;
private static final String UUID_TAG = "uuid";
private static final String TOTAL_MEMORY_KBS_FIELD = "total_memory_kb";
private static final String FREE_MEMORY_KBS_FIELD = "free_memory_kb";
private static final String CPU_UTILIZATION_FIELD = "cpu_utilization";
private static final String CPUS_FIELD = "cpus";
private static final String CPU_SOCKETS_FIELD = "cpu_sockets";
private static final String NETWORK_READ_KBS_FIELD = "network_read_kbs";
private static final String NETWORK_WRITE_KBS_FIELD = "network_write_kbs";
private static final String MEMORY_TARGET_KBS_FIELD = "memory_target_kbs";
private static final String DISK_READ_IOPS_FIELD = "disk_read_iops";
private static final String DISK_READ_KBS_FIELD = "disk_read_kbs";
private static final String DISK_WRITE_IOPS_FIELD = "disk_write_iops";
private static final String DISK_WRITE_KBS_FIELD = "disk_write_kbs";
private static final int HOURLY_TIME = 60;
private static final int DAILY_TIME = HOURLY_TIME * 24;
private static final Long ONE_MINUTE_IN_MILLISCONDS = 60000L;
private static final String DEFAULT_DATABASE_NAME = "cloudstack";
private static final String INFLUXDB_HOST_MEASUREMENT = "host_stats";
private static final String INFLUXDB_VM_MEASUREMENT = "vm_stats";
public static final ConfigKey<Integer> MANAGEMENT_SERVER_STATUS_COLLECTION_INTERVAL = new ConfigKey<>("Advanced",
Integer.class, "management.server.stats.interval", "60",
"Time interval in seconds, for management servers stats collection. Set to <= 0 to disable management servers stats.", false);
private static final ConfigKey<Integer> DATABASE_SERVER_STATUS_COLLECTION_INTERVAL = new ConfigKey<>("Advanced",
Integer.class, "database.server.stats.interval", "60",
"Time interval in seconds, for database servers stats collection. Set to <= 0 to disable database servers stats.", false);
private static final ConfigKey<Integer> DATABASE_SERVER_LOAD_HISTORY_RETENTION_NUMBER = new ConfigKey<>("Advanced",
Integer.class, "database.server.stats.retention", "3",
"The number of queries/seconds values to retain in history. This will define for how many periods of 'database.server.stats.interval' seconds, the queries/seconds values will be kept in memory",
true);
private static final ConfigKey<Integer> vmDiskStatsInterval = new ConfigKey<>("Advanced", Integer.class, "vm.disk.stats.interval", "0",
"Interval (in seconds) to report vm disk statistics. Vm disk statistics will be disabled if this is set to 0 or less than 0.", false);
private static final ConfigKey<Integer> vmDiskStatsIntervalMin = new ConfigKey<>("Advanced", Integer.class, "vm.disk.stats.interval.min", "300",
"Minimal interval (in seconds) to report vm disk statistics. If vm.disk.stats.interval is smaller than this, use this to report vm disk statistics.", false);
private static final ConfigKey<Integer> vmNetworkStatsInterval = new ConfigKey<>("Advanced", Integer.class, "vm.network.stats.interval", "0",
"Interval (in seconds) to report vm network statistics (for Shared networks). Vm network statistics will be disabled if this is set to 0 or less than 0.", false);
private static final ConfigKey<Integer> vmNetworkStatsIntervalMin = new ConfigKey<>("Advanced", Integer.class, "vm.network.stats.interval.min", "300",
"Minimal Interval (in seconds) to report vm network statistics (for Shared networks). If vm.network.stats.interval is smaller than this, use this to report vm network statistics.",
false);
private static final ConfigKey<Integer> StatsTimeout = new ConfigKey<>("Advanced", Integer.class, "stats.timeout", "60000",
"The timeout for stats call in milli seconds.", true,
ConfigKey.Scope.Cluster);
private static final ConfigKey<String> statsOutputUri = new ConfigKey<>("Advanced", String.class, "stats.output.uri", "",
"URI to send StatsCollector statistics to. The collector is defined on the URI scheme. Example: graphite://graphite-hostaddress:port or influxdb://influxdb-hostaddress/dbname. Note that the port is optional, if not added the default port for the respective collector (graphite or influxdb) will be used. Additionally, the database name '/dbname' is also optional; default db name is 'cloudstack'. You must create and configure the database if using influxdb.",
true);
protected static ConfigKey<Boolean> vmStatsIncrementMetrics = new ConfigKey<>("Advanced", Boolean.class, "vm.stats.increment.metrics", "false",
"When set to 'true', VM metrics(NetworkReadKBs, NetworkWriteKBs, DiskWriteKBs, DiskReadKBs, DiskReadIOs and DiskWriteIOs) that are collected from the hypervisor are summed before being returned."
+ "On the other hand, when set to 'false', the VM metrics API will just display the latest metrics collected.", true);
protected static ConfigKey<Integer> vmStatsMaxRetentionTime = new ConfigKey<>("Advanced", Integer.class, "vm.stats.max.retention.time", "720",
"The maximum time (in minutes) for keeping VM stats records in the database. The VM stats cleanup process will be disabled if this is set to 0 or less than 0.", true);
protected static ConfigKey<Boolean> vmStatsCollectUserVMOnly = new ConfigKey<>("Advanced", Boolean.class, "vm.stats.user.vm.only", "false",
"When set to 'false' stats for system VMs will be collected otherwise stats collection will be done only for user VMs", true);
protected static ConfigKey<Boolean> vmDiskStatsRetentionEnabled = new ConfigKey<>("Advanced", Boolean.class, "vm.disk.stats.retention.enabled", "false",
"When set to 'true' stats for VM disks will be stored in the database otherwise disk stats will not be stored", true);
protected static ConfigKey<Integer> vmDiskStatsMaxRetentionTime = new ConfigKey<>("Advanced", Integer.class, "vm.disk.stats.max.retention.time", "720",
"The maximum time (in minutes) for keeping VM disks stats records in the database. The VM disks stats cleanup process will be disabled if this is set to 0 or less than 0.", true);
private static StatsCollector s_instance = null;
private static Gson gson = new Gson();
private static Gson msStatsGson = new GsonBuilder()
.setDateFormat(DateUtil.ZONED_DATETIME_FORMAT)
.create();
private ScheduledExecutorService _executor = null;
@Inject
private AgentManager _agentMgr;
@Inject
private UserVmManager _userVmMgr;
@Inject
private HostDao _hostDao;
@Inject
private ClusterDao _clusterDao;
@Inject
protected UserVmDao _userVmDao;
@Inject
protected VmStatsDao vmStatsDao;
@Inject
private VolumeDao _volsDao;
@Inject
protected VolumeStatsDao volumeStatsDao;
@Inject
private PrimaryDataStoreDao _storagePoolDao;
@Inject
private StorageManager _storageManager;
@Inject
private DataStoreManager _dataStoreMgr;
@Inject
private ResourceManager _resourceMgr;
@Inject
private ConfigurationDao _configDao;
@Inject
private EndPointSelector _epSelector;
@Inject
private VmDiskStatisticsDao _vmDiskStatsDao;
@Inject
private UserStatisticsDao _userStatsDao;
@Inject
private NicDao _nicDao;
@Inject
private VlanDao _vlanDao;
@Inject
private AutoScaleManager _asManager;
@Inject
private VMInstanceDao _vmInstance;
@Inject
private HostGpuGroupsDao _hostGpuGroupsDao;
@Inject
private ImageStoreDetailsUtil imageStoreDetailsUtil;
@Inject
private ManagementServerHostDao managementServerHostDao;
// stats collector is now a clustered agent
@Inject
private ClusterManager clusterManager;
@Inject
private ManagementServerStatusDao managementServerStatusDao;
@Inject
private ManagementServerHostPeerDao managementServerHostPeerDao;
@Inject
VirtualMachineManager virtualMachineManager;
private final ConcurrentHashMap<String, ManagementServerHostStats> managementServerHostStats = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Object> dbStats = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, HostStats> _hostStats = new ConcurrentHashMap<>();
protected ConcurrentHashMap<Long, VmStats> _VmStats = new ConcurrentHashMap<>();
private final Map<String, VolumeStats> _volumeStats = new ConcurrentHashMap<>();
private ConcurrentHashMap<Long, StorageStats> _storageStats = new ConcurrentHashMap<>();
private ConcurrentHashMap<Long, StorageStats> _storagePoolStats = new ConcurrentHashMap<>();
private static final long DEFAULT_INITIAL_DELAY = 15000L;
private long hostStatsInterval = -1L;
private long vmStatsInterval = -1L;
private long storageStatsInterval = -1L;
private long volumeStatsInterval = -1L;
private long autoScaleStatsInterval = -1L;
private String externalStatsPrefix = "";
String externalStatsHost = null;
int externalStatsPort = -1;
private String externalStatsScheme;
ExternalStatsProtocol externalStatsType = ExternalStatsProtocol.NONE;
private String databaseName = DEFAULT_DATABASE_NAME;
private ScheduledExecutorService _diskStatsUpdateExecutor;
private int _usageAggregationRange = 1440;
private String _usageTimeZone = "GMT";
private final long mgmtSrvrId = MacAddress.getMacAddress().toLong();
private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds
private boolean _dailyOrHourly = false;
protected long managementServerNodeId = ManagementServerNode.getManagementServerId();
protected long msId = managementServerNodeId;
final static MetricRegistry METRIC_REGISTRY = new MetricRegistry();
public static StatsCollector getInstance() {
return s_instance;
}
public static StatsCollector getInstance(Map<String, String> configs) {
s_instance.init(configs);
return s_instance;
}
public StatsCollector() {
s_instance = this;
}
@Override
public boolean start() {
init(_configDao.getConfiguration());
registerAll("gc", new GarbageCollectorMetricSet(), METRIC_REGISTRY);
registerAll("buffers", new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()), METRIC_REGISTRY);
registerAll("memory", new MemoryUsageGaugeSet(), METRIC_REGISTRY);
registerAll("threads", new ThreadStatesGaugeSet(), METRIC_REGISTRY);
registerAll("jvm", new JvmAttributeGaugeSet(), METRIC_REGISTRY);
return true;
}
@Override
public boolean stop() {
_executor.shutdown();
return true;
}
private void registerAll(String prefix, MetricSet metricSet, MetricRegistry registry) {
String registryTemplate = new String(prefix + "%s");
for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
String registryName = String.format(registryTemplate, entry.getKey());
if (entry.getValue() instanceof MetricSet) {
registerAll(registryName, (MetricSet) entry.getValue(), registry);
} else {
registry.register(registryName, entry.getValue());
}
}
}
protected void init(Map<String, String> configs) {
_executor = Executors.newScheduledThreadPool(6, new NamedThreadFactory("StatsCollector"));
hostStatsInterval = NumbersUtil.parseLong(configs.get("host.stats.interval"), ONE_MINUTE_IN_MILLISCONDS);
vmStatsInterval = NumbersUtil.parseLong(configs.get("vm.stats.interval"), ONE_MINUTE_IN_MILLISCONDS);
storageStatsInterval = NumbersUtil.parseLong(configs.get("storage.stats.interval"), ONE_MINUTE_IN_MILLISCONDS);
volumeStatsInterval = NumbersUtil.parseLong(configs.get("volume.stats.interval"), ONE_MINUTE_IN_MILLISCONDS);
autoScaleStatsInterval = AutoScaleManager.AutoScaleStatsInterval.value();
ManagementServerStatusAdministrator managementServerStatusAdministrator = new ManagementServerStatusAdministrator();
clusterManager.registerStatusAdministrator(managementServerStatusAdministrator);
clusterManager.registerListener(managementServerStatusAdministrator);
gson = GsonHelper.getGson();
String statsUri = statsOutputUri.value();
if (StringUtils.isNotBlank(statsUri)) {
try {
URI uri = new URI(statsUri);
externalStatsScheme = uri.getScheme();
try {
externalStatsType = ExternalStatsProtocol.valueOf(externalStatsScheme.toUpperCase());
} catch (IllegalArgumentException e) {
logger.error(externalStatsScheme + " is not a valid protocol for external statistics. No statistics will be send.");
}
if (StringUtils.isNotEmpty(uri.getHost())) {
externalStatsHost = uri.getHost();
}
externalStatsPort = retrieveExternalStatsPortFromUri(uri);
databaseName = configureDatabaseName(uri);
if (StringUtils.isNotEmpty(uri.getPath())) {
externalStatsPrefix = uri.getPath().substring(1);
}
/* Append a dot (.) to the prefix if it is set */
if (StringUtils.isNotEmpty(externalStatsPrefix)) {
externalStatsPrefix += ".";
} else {
externalStatsPrefix = "";
}
} catch (URISyntaxException e) {
logger.error("Failed to parse external statistics URI: ", e);
}
}
if (hostStatsInterval > 0) {
_executor.scheduleWithFixedDelay(new HostCollector(), DEFAULT_INITIAL_DELAY, hostStatsInterval, TimeUnit.MILLISECONDS);
}
if (vmStatsInterval > 0) {
_executor.scheduleWithFixedDelay(new VmStatsCollector(), DEFAULT_INITIAL_DELAY, vmStatsInterval, TimeUnit.MILLISECONDS);
} else {
logger.info("Skipping collect VM stats. The global parameter vm.stats.interval is set to 0 or less than 0.");
}
_executor.scheduleWithFixedDelay(new VmStatsCleaner(), DEFAULT_INITIAL_DELAY, 60000L, TimeUnit.MILLISECONDS);
_executor.scheduleWithFixedDelay(new VolumeStatsCleaner(), DEFAULT_INITIAL_DELAY, 60000L, TimeUnit.MILLISECONDS);
scheduleCollection(MANAGEMENT_SERVER_STATUS_COLLECTION_INTERVAL, new ManagementServerCollector(), 1L);
scheduleCollection(DATABASE_SERVER_STATUS_COLLECTION_INTERVAL, new DbCollector(), 0L);
if (storageStatsInterval > 0) {
_executor.scheduleWithFixedDelay(new StorageCollector(), DEFAULT_INITIAL_DELAY, storageStatsInterval, TimeUnit.MILLISECONDS);
}
if (autoScaleStatsInterval > 0) {
_executor.scheduleWithFixedDelay(new AutoScaleMonitor(), DEFAULT_INITIAL_DELAY, autoScaleStatsInterval * 1000L, TimeUnit.MILLISECONDS);
}
if (vmDiskStatsInterval.value() > 0) {
if (vmDiskStatsInterval.value() < vmDiskStatsIntervalMin.value()) {
logger.debug("vm.disk.stats.interval - " + vmDiskStatsInterval.value() + " is smaller than vm.disk.stats.interval.min - " + vmDiskStatsIntervalMin.value()
+ ", so use vm.disk.stats.interval.min");
_executor.scheduleAtFixedRate(new VmDiskStatsTask(), vmDiskStatsIntervalMin.value(), vmDiskStatsIntervalMin.value(), TimeUnit.SECONDS);
} else {
_executor.scheduleAtFixedRate(new VmDiskStatsTask(), vmDiskStatsInterval.value(), vmDiskStatsInterval.value(), TimeUnit.SECONDS);
}
} else {
logger.debug("vm.disk.stats.interval - " + vmDiskStatsInterval.value() + " is 0 or less than 0, so not scheduling the vm disk stats thread");
}
if (vmNetworkStatsInterval.value() > 0) {
if (vmNetworkStatsInterval.value() < vmNetworkStatsIntervalMin.value()) {
logger.debug("vm.network.stats.interval - " + vmNetworkStatsInterval.value() + " is smaller than vm.network.stats.interval.min - "
+ vmNetworkStatsIntervalMin.value() + ", so use vm.network.stats.interval.min");
_executor.scheduleAtFixedRate(new VmNetworkStatsTask(), vmNetworkStatsIntervalMin.value(), vmNetworkStatsIntervalMin.value(), TimeUnit.SECONDS);
} else {
_executor.scheduleAtFixedRate(new VmNetworkStatsTask(), vmNetworkStatsInterval.value(), vmNetworkStatsInterval.value(), TimeUnit.SECONDS);
}
} else {
logger.debug("vm.network.stats.interval - " + vmNetworkStatsInterval.value() + " is 0 or less than 0, so not scheduling the vm network stats thread");
}
if (volumeStatsInterval > 0) {
_executor.scheduleAtFixedRate(new VolumeStatsTask(), DEFAULT_INITIAL_DELAY, volumeStatsInterval, TimeUnit.MILLISECONDS);
}
//Schedule disk stats update task
_diskStatsUpdateExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DiskStatsUpdater"));
String aggregationRange = configs.get("usage.stats.job.aggregation.range");
_usageAggregationRange = NumbersUtil.parseInt(aggregationRange, 1440);
_usageTimeZone = configs.get("usage.aggregation.timezone");
if (_usageTimeZone == null) {
_usageTimeZone = "GMT";
}
TimeZone usageTimezone = TimeZone.getTimeZone(_usageTimeZone);
Calendar cal = Calendar.getInstance(usageTimezone);
cal.setTime(new Date());
long endDate = 0;
if (_usageAggregationRange == DAILY_TIME) {
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.roll(Calendar.DAY_OF_YEAR, true);
cal.add(Calendar.MILLISECOND, -1);
endDate = cal.getTime().getTime();
_dailyOrHourly = true;
} else if (_usageAggregationRange == HOURLY_TIME) {
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.roll(Calendar.HOUR_OF_DAY, true);
cal.add(Calendar.MILLISECOND, -1);
endDate = cal.getTime().getTime();
_dailyOrHourly = true;
} else {
endDate = cal.getTime().getTime();
_dailyOrHourly = false;
}
if (_usageAggregationRange < UsageUtils.USAGE_AGGREGATION_RANGE_MIN) {
logger.warn("Usage stats job aggregation range is to small, using the minimum value of " + UsageUtils.USAGE_AGGREGATION_RANGE_MIN);
_usageAggregationRange = UsageUtils.USAGE_AGGREGATION_RANGE_MIN;
}
long period = _usageAggregationRange * ONE_MINUTE_IN_MILLISCONDS;
_diskStatsUpdateExecutor.scheduleAtFixedRate(new VmDiskStatsUpdaterTask(), (endDate - System.currentTimeMillis()), period, TimeUnit.MILLISECONDS);
ManagementServerHostVO mgmtServerVo = managementServerHostDao.findByMsid(managementServerNodeId);
if (mgmtServerVo != null) {
msId = mgmtServerVo.getId();
} else {
logger.warn(String.format("Cannot find management server with msid [%s]. "
+ "Therefore, VM stats will be recorded with the management server MAC address converted as a long in the mgmt_server_id column.", managementServerNodeId));
}
}
private void scheduleCollection(ConfigKey<Integer> statusCollectionInterval, AbstractStatsCollector collector, long delay) {
if (statusCollectionInterval.value() > 0) {
_executor.scheduleAtFixedRate(collector,
delay,
statusCollectionInterval.value(),
TimeUnit.SECONDS);
} else {
logger.debug(String.format("%s - %d is 0 or less, so not scheduling the status collector thread",
statusCollectionInterval.key(), statusCollectionInterval.value()));
}
}
/**
* Configures the database name according to the URI path. For instance, if the URI is as influxdb://address:port/dbname, the database name will be 'dbname'.
*/
protected String configureDatabaseName(URI uri) {
String dbname = StringUtils.removeStart(uri.getPath(), "/");
if (StringUtils.isBlank(dbname)) {
return DEFAULT_DATABASE_NAME;
} else {
return dbname;
}
}
/**
* Configures the port to be used when connecting with the stats collector service.
* Default values are 8086 for influx DB and 2003 for GraphiteDB.
* Throws URISyntaxException in case of non configured port and external StatsType
*/
protected int retrieveExternalStatsPortFromUri(URI uri) throws URISyntaxException {
int port = uri.getPort();
if (externalStatsType != ExternalStatsProtocol.NONE) {
if (port != UNDEFINED_PORT_VALUE) {
return port;
}
if (externalStatsType == ExternalStatsProtocol.GRAPHITE) {
return GRAPHITE_DEFAULT_PORT;
}
if (externalStatsType == ExternalStatsProtocol.INFLUXDB) {
return INFLUXDB_DEFAULT_PORT;
}
}
throw new URISyntaxException(uri.toString(), String.format(
"Cannot define a port for the Stats Collector host %s://%s:%s or URI scheme is incorrect. The configured URI in stats.output.uri is not supported. Please configure as the following examples: graphite://graphite-hostaddress:port, or influxdb://influxdb-hostaddress:port. Note that the port is optional, if not added the default port for the respective collector (graphite or influxdb) will be used.",
externalStatsPrefix, externalStatsHost, externalStatsPort));
}
protected Pair<Map<Long, VMInstanceVO>, Map<String, Long>> getVmMapForStatsForHost(Host host) {
List<VMInstanceVO> vms = _vmInstance.listByHostAndState(host.getId(), VirtualMachine.State.Running);
boolean collectUserVMStatsOnly = Boolean.TRUE.equals(vmStatsCollectUserVMOnly.value());
if (collectUserVMStatsOnly) {
vms = vms.stream().filter(vm -> VirtualMachine.Type.User.equals(vm.getType())).collect(Collectors.toList());
}
Map<Long, VMInstanceVO> idInstanceMap = new HashMap<>();
Map<String, Long> instanceNameIdMap = new HashMap<>();
vms.forEach(vm -> {
if (!collectUserVMStatsOnly || VirtualMachine.Type.User.equals(vm.getType())) {
idInstanceMap.put(vm.getId(), vm);
instanceNameIdMap.put(vm.getInstanceName(), vm.getId());
}
});
return new Pair<>(idInstanceMap, instanceNameIdMap);
}
class HostCollector extends AbstractStatsCollector {
@Override
protected void runInContext() {
try {
SearchCriteria<HostVO> sc = createSearchCriteriaForHostTypeRoutingStateUpAndNotInMaintenance();
List<HostVO> hosts = _hostDao.search(sc, null);
logger.debug(String.format("HostStatsCollector is running to process %d UP hosts", hosts.size()));
Map<Object, Object> metrics = new HashMap<>();
for (HostVO host : hosts) {
HostStatsEntry hostStatsEntry = (HostStatsEntry) _resourceMgr.getHostStatistics(host);
if (hostStatsEntry != null) {
hostStatsEntry.setHostVo(host);
metrics.put(hostStatsEntry.getHostId(), hostStatsEntry);
_hostStats.put(host.getId(), hostStatsEntry);
} else {
logger.warn("The Host stats is null for host: {}", host);
}
}
if (externalStatsType == ExternalStatsProtocol.INFLUXDB) {
sendMetricsToInfluxdb(metrics);
}
updateGpuEnabledHostsDetails(hosts);
} catch (Throwable t) {
logger.error("Error trying to retrieve host stats", t);
}
}
/**
* Updates GPU details on hosts supporting GPU.
*/
private void updateGpuEnabledHostsDetails(List<HostVO> hosts) {
List<HostVO> gpuEnabledHosts = new ArrayList<HostVO>();
List<Long> hostIds = _hostGpuGroupsDao.listHostIds();
if (CollectionUtils.isEmpty(hostIds)) {
return;
}
for (HostVO host : hosts) {
if (hostIds.contains(host.getId())) {
gpuEnabledHosts.add(host);
}
}
for (HostVO host : gpuEnabledHosts) {
HashMap<String, HashMap<String, VgpuTypesInfo>> groupDetails = _resourceMgr.getGPUStatistics(host);
if (!MapUtils.isEmpty(groupDetails)) {
_resourceMgr.updateGPUDetails(host.getId(), groupDetails);
}
}
}
@Override
protected Point createInfluxDbPoint(Object metricsObject) {
return createInfluxDbPointForHostMetrics(metricsObject);
}
}
class DbCollector extends AbstractStatsCollector {
List<Double> loadHistory = new ArrayList<>();
DbCollector() {
dbStats.put(loadAvarages, loadHistory);
}
@Override
protected void runInContext() {
logger.debug(String.format("%s is running...", this.getClass().getSimpleName()));
try {
long lastUptime = (dbStats.containsKey(uptime) ? (Long) dbStats.get(uptime) : 0);
long lastQueries = (dbStats.containsKey(queries) ? (Long) dbStats.get(queries) : 0);
getDynamicDataFromDB();
long interval = (Long) dbStats.get(uptime) - lastUptime;
long activity = (Long) dbStats.get(queries) - lastQueries;
loadHistory.add(0, interval == 0 ? -1 : Double.valueOf(activity / interval));
int maxsize = DATABASE_SERVER_LOAD_HISTORY_RETENTION_NUMBER.value();
while (loadHistory.size() > maxsize) {
loadHistory.remove(maxsize);
}
} catch (Throwable e) {
// pokemon catch to make sure the thread stays running
logger.error("db statistics collection failed due to " + e.getLocalizedMessage());
if (logger.isDebugEnabled()) {
logger.debug("db statistics collection failed.", e);
}
}
}
private void getDynamicDataFromDB() {
Map<String, String> stats = DbUtil.getDbInfo("STATUS", queries, uptime);
dbStats.put(collectionTime, new Date());
dbStats.put(queries, (Long.valueOf(stats.get(queries))));
dbStats.put(uptime, (Long.valueOf(stats.get(uptime))));
}
@Override
protected Point createInfluxDbPoint(Object metricsObject) {
return null;
}
}
class ManagementServerCollector extends AbstractStatsCollector {
@Override
protected void runInContext() {
logger.debug(String.format("%s is running...", this.getClass().getSimpleName()));
long msid = ManagementServerNode.getManagementServerId();
ManagementServerHostVO mshost = null;
ManagementServerHostStatsEntry msHostStatsEntry = null;
try {
mshost = managementServerHostDao.findByMsid(msid);
// get local data
msHostStatsEntry = getDataFrom(mshost);
managementServerHostStats.put(mshost.getUuid(), msHostStatsEntry);
// send to other hosts
clusterManager.publishStatus(msStatsGson.toJson(msHostStatsEntry));
} catch (Throwable t) {
// pokemon catch to make sure the thread stays running
logger.error("Error trying to retrieve management server host statistics", t);
}
try {
// send to DB
storeStatus(msHostStatsEntry, mshost);
} catch (Throwable t) {
// pokemon catch to make sure the thread stays running
logger.error("Error trying to store management server host statistics", t);
}
}
private void storeStatus(ManagementServerHostStatsEntry hostStatsEntry, ManagementServerHostVO mshost) {
if (hostStatsEntry == null || mshost == null) {
return;
}
ManagementServerStatusVO msStats = managementServerStatusDao.findByMsId(hostStatsEntry.getManagementServerHostUuid());
if (msStats == null) {
logger.info(String.format("creating new status info record for host %s - %s",
mshost.getName(),
hostStatsEntry.getManagementServerHostUuid()));
msStats = new ManagementServerStatusVO();
msStats.setMsId(hostStatsEntry.getManagementServerHostUuid());
}
msStats.setOsDistribution(hostStatsEntry.getOsDistribution()); // for now just the bunch details come later
msStats.setJavaName(hostStatsEntry.getJvmVendor());
msStats.setJavaVersion(hostStatsEntry.getJvmVersion());
Date startTime = new Date(hostStatsEntry.getJvmStartTime());
if (logger.isTraceEnabled()) {
logger.trace(String.format("reporting starttime %s", startTime));
}
msStats.setLastJvmStart(startTime);
msStats.setLastSystemBoot(hostStatsEntry.getSystemBootTime());
msStats.setUpdated(new Date());
managementServerStatusDao.persist(msStats);
}
@NotNull
private ManagementServerHostStatsEntry getDataFrom(ManagementServerHostVO mshost) {
ManagementServerHostStatsEntry newEntry = new ManagementServerHostStatsEntry();
logger.trace("Metrics collection start...");
newEntry.setManagementServerHostId(mshost.getId());
newEntry.setManagementServerHostUuid(mshost.getUuid());
newEntry.setManagementServerRunId(mshost.getRunid());
newEntry.setDbLocal(isDbLocal());
newEntry.setUsageLocal(isUsageLocal());
retrieveSession(newEntry);
getJvmDimensions(newEntry);
logger.trace("Metrics collection extra...");
getRuntimeData(newEntry);
getMemoryData(newEntry);
// newEntry must now include a pid!
getProcFileSystemData(newEntry);
// proc memory data has precedence over mbean memory data
getCpuData(newEntry);
getFileSystemData(newEntry);
getDataBaseStatistics(newEntry, mshost.getMsid());
gatherAllMetrics(newEntry);
logger.trace("Metrics collection end!");
return newEntry;
}
private void retrieveSession(ManagementServerHostStatsEntry newEntry) {
long sessions = ApiSessionListener.getSessionCount();
newEntry.setSessions(sessions);
if (logger.isTraceEnabled()) {
logger.trace(String.format("Sessions found in Api %d vs context %d", sessions,ApiSessionListener.getNumberOfSessions()));
} else {
logger.debug("Sessions active: " + sessions);
}
}
private void getDataBaseStatistics(ManagementServerHostStatsEntry newEntry, long msid) {
List<String> lastAgents = _hostDao.listByLastMs(msid);
newEntry.setLastAgents(lastAgents);
List<String> agents = _hostDao.listByMs(msid);
newEntry.setAgents(agents);
newEntry.setAgentCount(agents.size());
}
private void getMemoryData(@NotNull ManagementServerHostStatsEntry newEntry) {
MemoryMXBean mxBean = ManagementFactory.getMemoryMXBean();
newEntry.setTotalInit(mxBean.getHeapMemoryUsage().getInit() + mxBean.getNonHeapMemoryUsage().getInit());
newEntry.setTotalUsed(mxBean.getHeapMemoryUsage().getUsed() + mxBean.getNonHeapMemoryUsage().getUsed());
newEntry.setMaxJvmMemoryBytes(mxBean.getHeapMemoryUsage().getMax() + mxBean.getNonHeapMemoryUsage().getMax());
newEntry.setTotalCommitted(mxBean.getHeapMemoryUsage().getCommitted() + mxBean.getNonHeapMemoryUsage().getCommitted());
}
private void getCpuData(@NotNull ManagementServerHostStatsEntry newEntry) {
java.lang.management.OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
newEntry.setAvailableProcessors(bean.getAvailableProcessors());
newEntry.setLoadAverage(bean.getSystemLoadAverage());
if (logger.isTraceEnabled()) {
logger.trace(String.format(
"Metrics processors - %d , loadavg - %f ",
newEntry.getAvailableProcessors(),
newEntry.getLoadAverage()));
}
if (bean instanceof OperatingSystemMXBean) {
OperatingSystemMXBean mxBean = (OperatingSystemMXBean) bean;
// if we got these from /proc, skip the bean
if (newEntry.getSystemMemoryTotal() == 0) {
newEntry.setSystemMemoryTotal(mxBean.getTotalPhysicalMemorySize());
}
if (newEntry.getSystemMemoryFree() == 0) {
newEntry.setSystemMemoryFree(mxBean.getFreePhysicalMemorySize());
}
if (newEntry.getSystemMemoryUsed() <= 0) {
newEntry.setSystemMemoryUsed(mxBean.getCommittedVirtualMemorySize());
}
if (logger.isTraceEnabled()) {
logger.trace(String.format("data from 'OperatingSystemMXBean': total mem: %d, free mem: %d, used mem: %d",
newEntry.getSystemMemoryTotal(),
newEntry.getSystemMemoryFree(),
newEntry.getSystemMemoryUsed()));
}
}
}
private void getRuntimeData(@NotNull ManagementServerHostStatsEntry newEntry) {
final RuntimeMXBean mxBean = ManagementFactory.getRuntimeMXBean();
newEntry.setJvmUptime(mxBean.getUptime());
newEntry.setJvmStartTime(mxBean.getStartTime());
newEntry.setProcessId(mxBean.getPid());
newEntry.setJvmName(mxBean.getName());
newEntry.setJvmVendor(mxBean.getVmVendor());
newEntry.setJvmVersion(mxBean.getVmVersion());
if (logger.isTraceEnabled()) {
logger.trace(String.format(
"Metrics uptime - %d , starttime - %d",
newEntry.getJvmUptime(),
newEntry.getJvmStartTime()));
}
}
private void getJvmDimensions(@NotNull ManagementServerHostStatsEntry newEntry) {
Runtime runtime = Runtime.getRuntime();
newEntry.setTotalJvmMemoryBytes(runtime.totalMemory());
newEntry.setFreeJvmMemoryBytes(runtime.freeMemory());
newEntry.setMaxJvmMemoryBytes(runtime.maxMemory());
//long maxMem = runtime.maxMemory();
if (logger.isTraceEnabled()) {
logger.trace(String.format(
"Metrics proc - %d , maxMem - %d , totalMemory - %d , freeMemory - %f ",
newEntry.getAvailableProcessors(),
newEntry.getMaxJvmMemoryBytes(),
newEntry.getTotalJvmMemoryBytes(),
newEntry.getFreeJvmMemoryBytes()));
}
}
/**
* As for data from outside the JVM, we only rely on /proc/ contained data.
*
* @param newEntry item to add the information to
*/
private void getProcFileSystemData(@NotNull ManagementServerHostStatsEntry newEntry) {
// this should be taken from ("cat /proc/version"), not sure how standard this /etc entry is
String OS = Script.runSimpleBashScript("cat /etc/os-release | grep PRETTY_NAME | cut -f2 -d '=' | tr -d '\"'");
newEntry.setOsDistribution(OS);
String kernel = Script.runSimpleBashScript("uname -r");
newEntry.setKernelVersion(kernel);
// if we got these from the bean, skip
if (newEntry.getSystemMemoryTotal() == 0) {
String mem = Script.runSimpleBashScript("cat /proc/meminfo | grep MemTotal | cut -f 2 -d ':' | tr -d 'a-zA-z '").trim();
newEntry.setSystemMemoryTotal(Long.parseLong(mem) * ByteScaleUtils.KiB);
logger.info(String.format("system memory from /proc: %d", newEntry.getSystemMemoryTotal()));
}
if (newEntry.getSystemMemoryFree() == 0) {
String free = Script.runSimpleBashScript("cat /proc/meminfo | grep MemFree | cut -f 2 -d ':' | tr -d 'a-zA-z '").trim();
newEntry.setSystemMemoryFree(Long.parseLong(free) * ByteScaleUtils.KiB);
logger.info(String.format("free memory from /proc: %d", newEntry.getSystemMemoryFree()));
}
if (newEntry.getSystemMemoryUsed() <= 0) {
String used = Script.runSimpleBashScript(String.format("ps -o rss= %d", newEntry.getPid()));
newEntry.setSystemMemoryUsed(Long.parseLong(used));
logger.info(String.format("used memory from /proc: %d", newEntry.getSystemMemoryUsed()));
}
try {
String bootTime = Script.runSimpleBashScript("date -d @$(grep btime /proc/stat | awk '{print $2}') '+%Y-%m-%d %H:%M:%S'");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
Date date = formatter.parse(bootTime);
newEntry.setSystemBootTime(date);
} catch (ParseException e) {
logger.error("can not retrieve system uptime", e);
}
String maxuse = Script.runSimpleBashScript(String.format("ps -o vsz= %d", newEntry.getPid()));
newEntry.setSystemMemoryVirtualSize(Long.parseLong(maxuse) * 1024);
newEntry.setSystemTotalCpuCycles(getSystemCpuCyclesTotal());
newEntry.setSystemLoadAverages(getCpuLoads());
newEntry.setSystemCyclesUsage(getSystemCpuUsage());
if (logger.isTraceEnabled()) {
logger.trace(
String.format("cpu\ncapacities: %f\n loads: %s ; %s ; %s\n stats: %d ; %d ; %d",
newEntry.getSystemTotalCpuCycles(),
newEntry.getSystemLoadAverages()[0], newEntry.getSystemLoadAverages()[1], newEntry.getSystemLoadAverages()[2],
newEntry.getSystemCyclesUsage()[0], newEntry.getSystemCyclesUsage()[1], newEntry.getSystemCyclesUsage()[2]
)
);
}
}
@NotNull
private double[] getCpuLoads() {
String[] cpuloadString = Script.runSimpleBashScript("cat /proc/loadavg").split(" ");
double[] cpuloads = {Double.parseDouble(cpuloadString[0]), Double.parseDouble(cpuloadString[1]), Double.parseDouble(cpuloadString[2])};
return cpuloads;
}
private long [] getSystemCpuUsage() {
String[] cpustats = Script.runSimpleBashScript("cat /proc/stat | grep \"cpu \" | tr -d \"cpu\"").trim().split(" ");
long [] cycleUsage = {Long.parseLong(cpustats[0]) + Long.parseLong(cpustats[1]), Long.parseLong(cpustats[2]), Long.parseLong(cpustats[3])};
return cycleUsage;
}
private double getSystemCpuCyclesTotal() {
String cpucaps = Script.runSimpleBashScript("cat /proc/cpuinfo | grep \"cpu MHz\" | grep \"cpu MHz\" | cut -f 2 -d : | tr -d ' '| tr '\\n' \" \"");
double totalcpucap = 0;
if (StringUtils.isEmpty(cpucaps)) {
String totalCpus = Script.runSimpleBashScript("nproc --all| tr '\\n' \" \"");
String maxCpuSpeed = Script.runSimpleBashScript("lscpu | grep -E 'CPU max MHz' | head -1 | cut -f 2 -d : | tr -d ' '| tr '\\n' \" \"");
if (StringUtils.isNotEmpty(totalCpus) && StringUtils.isNotEmpty(maxCpuSpeed)) {
totalcpucap = Double.parseDouble(totalCpus) * Double.parseDouble(maxCpuSpeed);
}
} else {
for (String cpucap : cpucaps.split(" ")) {
totalcpucap += Double.parseDouble(cpucap);
}
}
return totalcpucap;
}