blob: e9453ffcb6fe808891585e61695fcbcfb6db0e83 [file] [log] [blame]
Allen Liec5beb32016-09-08 15:31:41 -07001# Copyright 2016 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5# Copyright (c) 2015 The Chromium Authors. All rights reserved.
6# Use of this source code is governed by a BSD-style license that can be
7# found in the LICENSE file.
8
9"""System metrics."""
10
11from __future__ import print_function
12
13import errno
14import os
Allen Liec5beb32016-09-08 15:31:41 -070015import time
16
17import psutil
18
19from chromite.lib import cros_logging as logging
20from infra_libs import ts_mon
21
Allen Li79317bb2016-12-16 18:25:07 -080022logger = logging.getLogger(__name__)
23
Allen Liec5beb32016-09-08 15:31:41 -070024
Allen Lia6b02252016-10-26 14:40:51 -070025_cpu_count_metric = ts_mon.GaugeMetric(
26 'dev/cpu/count',
27 description='Number of CPU cores.')
28_cpu_time_metric = ts_mon.FloatMetric(
29 'dev/cpu/time',
30 description='percentage of time spent by the CPU '
31 'in different states.')
Allen Liec5beb32016-09-08 15:31:41 -070032
Allen Lia6b02252016-10-26 14:40:51 -070033_disk_free_metric = ts_mon.GaugeMetric(
Allen Liec5beb32016-09-08 15:31:41 -070034 'dev/disk/free',
35 description='Available bytes on disk partition.',
36 units=ts_mon.MetricsDataUnits.BYTES)
Allen Lia6b02252016-10-26 14:40:51 -070037_disk_total_metric = ts_mon.GaugeMetric(
38 'dev/disk/total',
39 description='Total bytes on disk partition.',
40 units=ts_mon.MetricsDataUnits.BYTES)
Allen Liec5beb32016-09-08 15:31:41 -070041
Allen Lia6b02252016-10-26 14:40:51 -070042_inodes_free_metric = ts_mon.GaugeMetric(
43 'dev/inodes/free',
44 description='Number of available inodes on '
45 'disk partition (unix only).')
46_inodes_total_metric = ts_mon.GaugeMetric(
47 'dev/inodes/total',
48 description='Number of possible inodes on '
49 'disk partition (unix only)')
Allen Liec5beb32016-09-08 15:31:41 -070050
Allen Lia6b02252016-10-26 14:40:51 -070051_mem_free_metric = ts_mon.GaugeMetric(
52 'dev/mem/free',
53 description='Amount of memory available to a '
54 'process (in Bytes). Buffers are considered '
55 'free memory.',
56 units=ts_mon.MetricsDataUnits.BYTES)
Allen Liec5beb32016-09-08 15:31:41 -070057
Allen Lia6b02252016-10-26 14:40:51 -070058_mem_total_metric = ts_mon.GaugeMetric(
59 'dev/mem/total',
60 description='Total physical memory in Bytes.',
61 units=ts_mon.MetricsDataUnits.BYTES)
Allen Liec5beb32016-09-08 15:31:41 -070062
Allen Lia6b02252016-10-26 14:40:51 -070063BOOT_TIME = psutil.boot_time()
64_net_up_metric = ts_mon.CounterMetric(
65 'dev/net/bytes/up', start_time=BOOT_TIME,
66 description='Number of bytes sent on interface.',
67 units=ts_mon.MetricsDataUnits.BYTES)
68_net_down_metric = ts_mon.CounterMetric(
69 'dev/net/bytes/down', start_time=BOOT_TIME,
70 description='Number of Bytes received on '
71 'interface.',
72 units=ts_mon.MetricsDataUnits.BYTES)
73_net_err_up_metric = ts_mon.CounterMetric(
74 'dev/net/err/up', start_time=BOOT_TIME,
75 description='Total number of errors when '
76 'sending (per interface).')
77_net_err_down_metric = ts_mon.CounterMetric(
78 'dev/net/err/down', start_time=BOOT_TIME,
79 description='Total number of errors when '
80 'receiving (per interface).')
81_net_drop_up_metric = ts_mon.CounterMetric(
82 'dev/net/drop/up', start_time=BOOT_TIME,
83 description='Total number of outgoing '
84 'packets that have been dropped.')
85_net_drop_down_metric = ts_mon.CounterMetric(
86 'dev/net/drop/down', start_time=BOOT_TIME,
Allen Liec5beb32016-09-08 15:31:41 -070087 description='Total number of incoming '
88 'packets that have been dropped.')
89
Allen Lia6b02252016-10-26 14:40:51 -070090_disk_read_metric = ts_mon.CounterMetric(
91 'dev/disk/read', start_time=BOOT_TIME,
92 description='Number of Bytes read on disk.',
93 units=ts_mon.MetricsDataUnits.BYTES)
94_disk_write_metric = ts_mon.CounterMetric(
95 'dev/disk/write', start_time=BOOT_TIME,
96 description='Number of Bytes written on disk.',
97 units=ts_mon.MetricsDataUnits.BYTES)
Allen Liec5beb32016-09-08 15:31:41 -070098
Allen Lia6b02252016-10-26 14:40:51 -070099_uptime_metric = ts_mon.GaugeMetric(
100 'dev/uptime',
101 description='Machine uptime, in seconds.',
102 units=ts_mon.MetricsDataUnits.SECONDS)
Allen Liec5beb32016-09-08 15:31:41 -0700103
Allen Lia6b02252016-10-26 14:40:51 -0700104_proc_count_metric = ts_mon.GaugeMetric(
105 'dev/proc/count',
106 description='Number of processes currently running.')
Allen Liefe7adf2016-10-27 11:36:04 -0700107_autoserv_proc_count_metric = ts_mon.GaugeMetric(
108 'dev/proc/autoserv_count',
109 description='Number of autoserv processes currently running.')
Allen Li0937a522016-11-23 13:34:48 -0800110_sysmon_proc_count_metric = ts_mon.GaugeMetric(
111 'dev/proc/sysmon_count',
112 description='Number of sysmon processes currently running.')
Allen Lia6b02252016-10-26 14:40:51 -0700113_load_average_metric = ts_mon.FloatMetric(
114 'dev/proc/load_average',
115 description='Number of processes currently '
116 'in the system run queue.')
Allen Liec5beb32016-09-08 15:31:41 -0700117
Allen Lia6b02252016-10-26 14:40:51 -0700118# ts_mon pipeline uses backend clocks when assigning timestamps to metric
119# points. By comparing point timestamp to the point value (i.e. time by
120# machine's local clock), we can potentially detect some anomalies (clock
121# drift, unusually high metrics pipeline delay, completely wrong clocks, etc).
Allen Liec5beb32016-09-08 15:31:41 -0700122#
123# It is important to gather this metric right before the flush.
Allen Lia6b02252016-10-26 14:40:51 -0700124_unix_time_metric = ts_mon.GaugeMetric(
Allen Liec5beb32016-09-08 15:31:41 -0700125 'dev/unix_time',
Allen Lia6b02252016-10-26 14:40:51 -0700126 description='Number of milliseconds since epoch'
127 ' based on local machine clock.')
Allen Liec5beb32016-09-08 15:31:41 -0700128
Allen Lia6b02252016-10-26 14:40:51 -0700129_os_name_metric = ts_mon.StringMetric(
130 'proc/os/name',
131 description='OS name on the machine')
Allen Liec5beb32016-09-08 15:31:41 -0700132
Allen Lia6b02252016-10-26 14:40:51 -0700133_os_version_metric = ts_mon.StringMetric(
134 'proc/os/version',
135 description='OS version on the machine')
Allen Liec5beb32016-09-08 15:31:41 -0700136
Allen Lia6b02252016-10-26 14:40:51 -0700137_os_arch_metric = ts_mon.StringMetric(
138 'proc/os/arch',
139 description='OS architecture on this machine')
Allen Liec5beb32016-09-08 15:31:41 -0700140
Allen Lia6b02252016-10-26 14:40:51 -0700141_python_arch_metric = ts_mon.StringMetric(
142 'proc/python/arch',
143 description='python userland '
144 'architecture on this machine')
Allen Liec5beb32016-09-08 15:31:41 -0700145
146
Allen Li45ae8392017-03-02 14:19:35 -0800147def collect_uptime():
Allen Lia6b02252016-10-26 14:40:51 -0700148 _uptime_metric.set(int(time.time() - BOOT_TIME))
Allen Liec5beb32016-09-08 15:31:41 -0700149
150
Allen Li45ae8392017-03-02 14:19:35 -0800151def collect_cpu_info():
Allen Lia6b02252016-10-26 14:40:51 -0700152 _cpu_count_metric.set(psutil.cpu_count())
Allen Liec5beb32016-09-08 15:31:41 -0700153
154 times = psutil.cpu_times_percent()
155 for mode in ('user', 'system', 'idle'):
Allen Lia6b02252016-10-26 14:40:51 -0700156 _cpu_time_metric.set(getattr(times, mode), {'mode': mode})
Allen Liec5beb32016-09-08 15:31:41 -0700157
158
Allen Li45ae8392017-03-02 14:19:35 -0800159def collect_disk_info(mountpoints=None):
Allen Liec5beb32016-09-08 15:31:41 -0700160 if mountpoints is None:
161 mountpoints = [disk.mountpoint for disk in psutil.disk_partitions()]
Allen Liec5beb32016-09-08 15:31:41 -0700162 for mountpoint in mountpoints:
Allen Li45ae8392017-03-02 14:19:35 -0800163 _collect_disk_info_single(mountpoint)
164 _collect_fs_inode_info(mountpoint)
165 _collect_disk_io_info()
Allen Liec5beb32016-09-08 15:31:41 -0700166
Allen Liec5beb32016-09-08 15:31:41 -0700167
Allen Li45ae8392017-03-02 14:19:35 -0800168def _collect_disk_info_single(mountpoint):
Allen Lia6b02252016-10-26 14:40:51 -0700169 fields = {'path': mountpoint}
Allen Liec5beb32016-09-08 15:31:41 -0700170
171 try:
Allen Lia6b02252016-10-26 14:40:51 -0700172 usage = psutil.disk_usage(mountpoint)
173 except OSError as ex:
174 if ex.errno == errno.ENOENT:
175 # This happens on Windows when querying a removable drive that
176 # doesn't have any media inserted right now.
177 pass
178 else:
179 raise
180 else:
181 _disk_free_metric.set(usage.free, fields=fields)
182 _disk_total_metric.set(usage.total, fields=fields)
183
184 # inode counts are only available on Unix.
185 if os.name == 'posix':
Allen Li45ae8392017-03-02 14:19:35 -0800186 _collect_fs_inode_info(mountpoint)
Allen Lia6b02252016-10-26 14:40:51 -0700187
188
Allen Li45ae8392017-03-02 14:19:35 -0800189def _collect_fs_inode_info(mountpoint):
Allen Lia6b02252016-10-26 14:40:51 -0700190 fields = {'path': mountpoint}
191 stats = os.statvfs(mountpoint)
192 _inodes_free_metric.set(stats.f_favail, fields=fields)
193 _inodes_total_metric.set(stats.f_files, fields=fields)
194
195
Allen Li45ae8392017-03-02 14:19:35 -0800196def _collect_disk_io_info():
Allen Lia6b02252016-10-26 14:40:51 -0700197 try:
198 disk_counters = psutil.disk_io_counters(perdisk=True).iteritems()
Allen Liec5beb32016-09-08 15:31:41 -0700199 except RuntimeError as ex:
200 if "couldn't find any physical disk" in str(ex):
201 # Disk performance counters aren't enabled on Windows.
202 pass
203 else:
204 raise
Allen Lia6b02252016-10-26 14:40:51 -0700205 else:
206 for disk, counters in disk_counters:
207 fields = {'disk': disk}
208 _disk_read_metric.set(counters.read_bytes, fields=fields)
209 _disk_write_metric.set(counters.write_bytes, fields=fields)
Allen Liec5beb32016-09-08 15:31:41 -0700210
211
Allen Li45ae8392017-03-02 14:19:35 -0800212def collect_mem_info():
Allen Liec5beb32016-09-08 15:31:41 -0700213 # We don't report mem.used because (due to virtual memory) it is not
214 # useful.
215 mem = psutil.virtual_memory()
Allen Lia6b02252016-10-26 14:40:51 -0700216 _mem_free_metric.set(mem.available)
217 _mem_total_metric.set(mem.total)
Allen Liec5beb32016-09-08 15:31:41 -0700218
219
Allen Li45ae8392017-03-02 14:19:35 -0800220def collect_net_info():
Allen Liec5beb32016-09-08 15:31:41 -0700221 metric_counter_names = [
Allen Lia6b02252016-10-26 14:40:51 -0700222 (_net_up_metric, 'bytes_sent'),
223 (_net_down_metric, 'bytes_recv'),
224 (_net_err_up_metric, 'errout'),
225 (_net_err_down_metric, 'errin'),
226 (_net_drop_up_metric, 'dropout'),
227 (_net_drop_down_metric, 'dropin'),
Allen Liec5beb32016-09-08 15:31:41 -0700228 ]
229
230 nics = psutil.net_io_counters(pernic=True)
231 for nic, counters in nics.iteritems():
Allen Lic18ca9d2017-03-02 14:24:57 -0800232 if _is_virtual_netif(nic):
Allen Li10eb79a2016-10-19 11:11:53 -0700233 continue
Allen Liec5beb32016-09-08 15:31:41 -0700234 fields = {'interface': nic}
235 for metric, counter_name in metric_counter_names:
236 try:
237 metric.set(getattr(counters, counter_name), fields=fields)
238 except ts_mon.MonitoringDecreasingValueError as ex:
239 # This normally shouldn't happen, but might if the network
240 # driver module is reloaded, so log an error and continue
241 # instead of raising an exception.
Allen Li79317bb2016-12-16 18:25:07 -0800242 logger.warning(str(ex))
Allen Liec5beb32016-09-08 15:31:41 -0700243
244
Allen Lic18ca9d2017-03-02 14:24:57 -0800245def _is_virtual_netif(nic):
246 """Return whether the network interface is virtual."""
247 # TODO(ayatane): Use a different way of identifying virtual interfaces
248 return nic.startswith('veth')
249
250
Allen Li45ae8392017-03-02 14:19:35 -0800251def collect_proc_info():
Allen Liefe7adf2016-10-27 11:36:04 -0700252 autoserv_count = 0
Allen Li0937a522016-11-23 13:34:48 -0800253 sysmon_count = 0
Allen Liefe7adf2016-10-27 11:36:04 -0700254 total = 0
255 for proc in psutil.process_iter():
Allen Li80dae192016-11-01 11:58:10 -0700256 if _is_parent_autoserv(proc):
Allen Liefe7adf2016-10-27 11:36:04 -0700257 autoserv_count += 1
Allen Li0937a522016-11-23 13:34:48 -0800258 elif _is_sysmon(proc):
259 sysmon_count += 1
Allen Liefe7adf2016-10-27 11:36:04 -0700260 total += 1
Allen Li79317bb2016-12-16 18:25:07 -0800261 logger.debug('autoserv_count: %s', autoserv_count)
262 logger.debug('sysmon_count: %s', sysmon_count)
Allen Liefe7adf2016-10-27 11:36:04 -0700263 _autoserv_proc_count_metric.set(autoserv_count)
Allen Li0937a522016-11-23 13:34:48 -0800264 _sysmon_proc_count_metric.set(sysmon_count)
Allen Liefe7adf2016-10-27 11:36:04 -0700265 _proc_count_metric.set(total)
266
267
Allen Li80dae192016-11-01 11:58:10 -0700268def _is_parent_autoserv(proc):
269 """Return whether proc is a parent (not forked) autoserv process."""
270 return _is_autoserv(proc) and not _is_autoserv(proc.parent())
271
272
273def _is_autoserv(proc):
274 """Return whether proc is an autoserv process."""
275 # This relies on the autoserv script being run directly. The script should
276 # be named autoserv exactly and start with a shebang that is /usr/bin/python,
277 # NOT /bin/env
278 return proc.name() == 'autoserv'
Allen Liec5beb32016-09-08 15:31:41 -0700279
Allen Lia6b02252016-10-26 14:40:51 -0700280
Allen Li0937a522016-11-23 13:34:48 -0800281def _is_sysmon(proc):
282 """Return whether proc is a sysmon process."""
Allen Lidfdfbda2016-12-16 17:41:16 -0800283 return proc.cmdline()[:3] == ['python', '-m', 'chromite.scripts.sysmon']
Allen Li0937a522016-11-23 13:34:48 -0800284
285
Allen Li45ae8392017-03-02 14:19:35 -0800286def collect_load_avg():
Allen Lia6b02252016-10-26 14:40:51 -0700287 try:
288 avg1, avg5, avg15 = os.getloadavg()
289 except OSError:
290 pass
291 else:
292 _load_average_metric.set(avg1, fields={'minutes': 1})
293 _load_average_metric.set(avg5, fields={'minutes': 5})
294 _load_average_metric.set(avg15, fields={'minutes': 15})
Allen Liec5beb32016-09-08 15:31:41 -0700295
296
Allen Li45ae8392017-03-02 14:19:35 -0800297def collect_unix_time():
Allen Lia6b02252016-10-26 14:40:51 -0700298 _unix_time_metric.set(int(time.time() * 1000))