blob: 4caf6da4b068f99daa294b046cd541798c76d336 [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
Allen Lia6b02252016-10-26 14:40:51 -070013import collections
Allen Liec5beb32016-09-08 15:31:41 -070014import errno
15import os
16import platform
17import sys
18import time
19
20import psutil
21
22from chromite.lib import cros_logging as logging
23from infra_libs import ts_mon
24
25
Allen Lia6b02252016-10-26 14:40:51 -070026_cpu_count_metric = ts_mon.GaugeMetric(
27 'dev/cpu/count',
28 description='Number of CPU cores.')
29_cpu_time_metric = ts_mon.FloatMetric(
30 'dev/cpu/time',
31 description='percentage of time spent by the CPU '
32 'in different states.')
Allen Liec5beb32016-09-08 15:31:41 -070033
Allen Lia6b02252016-10-26 14:40:51 -070034_disk_free_metric = ts_mon.GaugeMetric(
Allen Liec5beb32016-09-08 15:31:41 -070035 'dev/disk/free',
36 description='Available bytes on disk partition.',
37 units=ts_mon.MetricsDataUnits.BYTES)
Allen Lia6b02252016-10-26 14:40:51 -070038_disk_total_metric = ts_mon.GaugeMetric(
39 'dev/disk/total',
40 description='Total bytes on disk partition.',
41 units=ts_mon.MetricsDataUnits.BYTES)
Allen Liec5beb32016-09-08 15:31:41 -070042
Allen Lia6b02252016-10-26 14:40:51 -070043_inodes_free_metric = ts_mon.GaugeMetric(
44 'dev/inodes/free',
45 description='Number of available inodes on '
46 'disk partition (unix only).')
47_inodes_total_metric = ts_mon.GaugeMetric(
48 'dev/inodes/total',
49 description='Number of possible inodes on '
50 'disk partition (unix only)')
Allen Liec5beb32016-09-08 15:31:41 -070051
Allen Lia6b02252016-10-26 14:40:51 -070052_mem_free_metric = ts_mon.GaugeMetric(
53 'dev/mem/free',
54 description='Amount of memory available to a '
55 'process (in Bytes). Buffers are considered '
56 'free memory.',
57 units=ts_mon.MetricsDataUnits.BYTES)
Allen Liec5beb32016-09-08 15:31:41 -070058
Allen Lia6b02252016-10-26 14:40:51 -070059_mem_total_metric = ts_mon.GaugeMetric(
60 'dev/mem/total',
61 description='Total physical memory in Bytes.',
62 units=ts_mon.MetricsDataUnits.BYTES)
Allen Liec5beb32016-09-08 15:31:41 -070063
Allen Lia6b02252016-10-26 14:40:51 -070064BOOT_TIME = psutil.boot_time()
65_net_up_metric = ts_mon.CounterMetric(
66 'dev/net/bytes/up', start_time=BOOT_TIME,
67 description='Number of bytes sent on interface.',
68 units=ts_mon.MetricsDataUnits.BYTES)
69_net_down_metric = ts_mon.CounterMetric(
70 'dev/net/bytes/down', start_time=BOOT_TIME,
71 description='Number of Bytes received on '
72 'interface.',
73 units=ts_mon.MetricsDataUnits.BYTES)
74_net_err_up_metric = ts_mon.CounterMetric(
75 'dev/net/err/up', start_time=BOOT_TIME,
76 description='Total number of errors when '
77 'sending (per interface).')
78_net_err_down_metric = ts_mon.CounterMetric(
79 'dev/net/err/down', start_time=BOOT_TIME,
80 description='Total number of errors when '
81 'receiving (per interface).')
82_net_drop_up_metric = ts_mon.CounterMetric(
83 'dev/net/drop/up', start_time=BOOT_TIME,
84 description='Total number of outgoing '
85 'packets that have been dropped.')
86_net_drop_down_metric = ts_mon.CounterMetric(
87 'dev/net/drop/down', start_time=BOOT_TIME,
Allen Liec5beb32016-09-08 15:31:41 -070088 description='Total number of incoming '
89 'packets that have been dropped.')
90
Allen Lia6b02252016-10-26 14:40:51 -070091_disk_read_metric = ts_mon.CounterMetric(
92 'dev/disk/read', start_time=BOOT_TIME,
93 description='Number of Bytes read on disk.',
94 units=ts_mon.MetricsDataUnits.BYTES)
95_disk_write_metric = ts_mon.CounterMetric(
96 'dev/disk/write', start_time=BOOT_TIME,
97 description='Number of Bytes written on disk.',
98 units=ts_mon.MetricsDataUnits.BYTES)
Allen Liec5beb32016-09-08 15:31:41 -070099
Allen Lia6b02252016-10-26 14:40:51 -0700100_uptime_metric = ts_mon.GaugeMetric(
101 'dev/uptime',
102 description='Machine uptime, in seconds.',
103 units=ts_mon.MetricsDataUnits.SECONDS)
Allen Liec5beb32016-09-08 15:31:41 -0700104
Allen Lia6b02252016-10-26 14:40:51 -0700105_proc_count_metric = ts_mon.GaugeMetric(
106 'dev/proc/count',
107 description='Number of processes currently running.')
Allen Liefe7adf2016-10-27 11:36:04 -0700108_autoserv_proc_count_metric = ts_mon.GaugeMetric(
109 'dev/proc/autoserv_count',
110 description='Number of autoserv processes currently running.')
Allen Lia6b02252016-10-26 14:40:51 -0700111_load_average_metric = ts_mon.FloatMetric(
112 'dev/proc/load_average',
113 description='Number of processes currently '
114 'in the system run queue.')
Allen Liec5beb32016-09-08 15:31:41 -0700115
Allen Lia6b02252016-10-26 14:40:51 -0700116# ts_mon pipeline uses backend clocks when assigning timestamps to metric
117# points. By comparing point timestamp to the point value (i.e. time by
118# machine's local clock), we can potentially detect some anomalies (clock
119# drift, unusually high metrics pipeline delay, completely wrong clocks, etc).
Allen Liec5beb32016-09-08 15:31:41 -0700120#
121# It is important to gather this metric right before the flush.
Allen Lia6b02252016-10-26 14:40:51 -0700122_unix_time_metric = ts_mon.GaugeMetric(
Allen Liec5beb32016-09-08 15:31:41 -0700123 'dev/unix_time',
Allen Lia6b02252016-10-26 14:40:51 -0700124 description='Number of milliseconds since epoch'
125 ' based on local machine clock.')
Allen Liec5beb32016-09-08 15:31:41 -0700126
Allen Lia6b02252016-10-26 14:40:51 -0700127_os_name_metric = ts_mon.StringMetric(
128 'proc/os/name',
129 description='OS name on the machine')
Allen Liec5beb32016-09-08 15:31:41 -0700130
Allen Lia6b02252016-10-26 14:40:51 -0700131_os_version_metric = ts_mon.StringMetric(
132 'proc/os/version',
133 description='OS version on the machine')
Allen Liec5beb32016-09-08 15:31:41 -0700134
Allen Lia6b02252016-10-26 14:40:51 -0700135_os_arch_metric = ts_mon.StringMetric(
136 'proc/os/arch',
137 description='OS architecture on this machine')
Allen Liec5beb32016-09-08 15:31:41 -0700138
Allen Lia6b02252016-10-26 14:40:51 -0700139_python_arch_metric = ts_mon.StringMetric(
140 'proc/python/arch',
141 description='python userland '
142 'architecture on this machine')
Allen Liec5beb32016-09-08 15:31:41 -0700143
144
145def get_uptime():
Allen Lia6b02252016-10-26 14:40:51 -0700146 _uptime_metric.set(int(time.time() - BOOT_TIME))
Allen Liec5beb32016-09-08 15:31:41 -0700147
148
149def get_cpu_info():
Allen Lia6b02252016-10-26 14:40:51 -0700150 _cpu_count_metric.set(psutil.cpu_count())
Allen Liec5beb32016-09-08 15:31:41 -0700151
152 times = psutil.cpu_times_percent()
153 for mode in ('user', 'system', 'idle'):
Allen Lia6b02252016-10-26 14:40:51 -0700154 _cpu_time_metric.set(getattr(times, mode), {'mode': mode})
Allen Liec5beb32016-09-08 15:31:41 -0700155
156
157def get_disk_info(mountpoints=None):
158 if mountpoints is None:
159 mountpoints = [disk.mountpoint for disk in psutil.disk_partitions()]
Allen Liec5beb32016-09-08 15:31:41 -0700160 for mountpoint in mountpoints:
Allen Lia6b02252016-10-26 14:40:51 -0700161 _get_disk_info_single(mountpoint)
162 _get_fs_inode_info(mountpoint)
163 _get_disk_io_info()
Allen Liec5beb32016-09-08 15:31:41 -0700164
Allen Liec5beb32016-09-08 15:31:41 -0700165
Allen Lia6b02252016-10-26 14:40:51 -0700166def _get_disk_info_single(mountpoint):
167 fields = {'path': mountpoint}
Allen Liec5beb32016-09-08 15:31:41 -0700168
169 try:
Allen Lia6b02252016-10-26 14:40:51 -0700170 usage = psutil.disk_usage(mountpoint)
171 except OSError as ex:
172 if ex.errno == errno.ENOENT:
173 # This happens on Windows when querying a removable drive that
174 # doesn't have any media inserted right now.
175 pass
176 else:
177 raise
178 else:
179 _disk_free_metric.set(usage.free, fields=fields)
180 _disk_total_metric.set(usage.total, fields=fields)
181
182 # inode counts are only available on Unix.
183 if os.name == 'posix':
184 _get_fs_inode_info(mountpoint)
185
186
187def _get_fs_inode_info(mountpoint):
188 fields = {'path': mountpoint}
189 stats = os.statvfs(mountpoint)
190 _inodes_free_metric.set(stats.f_favail, fields=fields)
191 _inodes_total_metric.set(stats.f_files, fields=fields)
192
193
194def _get_disk_io_info():
195 try:
196 disk_counters = psutil.disk_io_counters(perdisk=True).iteritems()
Allen Liec5beb32016-09-08 15:31:41 -0700197 except RuntimeError as ex:
198 if "couldn't find any physical disk" in str(ex):
199 # Disk performance counters aren't enabled on Windows.
200 pass
201 else:
202 raise
Allen Lia6b02252016-10-26 14:40:51 -0700203 else:
204 for disk, counters in disk_counters:
205 fields = {'disk': disk}
206 _disk_read_metric.set(counters.read_bytes, fields=fields)
207 _disk_write_metric.set(counters.write_bytes, fields=fields)
Allen Liec5beb32016-09-08 15:31:41 -0700208
209
210def get_mem_info():
211 # We don't report mem.used because (due to virtual memory) it is not
212 # useful.
213 mem = psutil.virtual_memory()
Allen Lia6b02252016-10-26 14:40:51 -0700214 _mem_free_metric.set(mem.available)
215 _mem_total_metric.set(mem.total)
Allen Liec5beb32016-09-08 15:31:41 -0700216
217
218def get_net_info():
219 metric_counter_names = [
Allen Lia6b02252016-10-26 14:40:51 -0700220 (_net_up_metric, 'bytes_sent'),
221 (_net_down_metric, 'bytes_recv'),
222 (_net_err_up_metric, 'errout'),
223 (_net_err_down_metric, 'errin'),
224 (_net_drop_up_metric, 'dropout'),
225 (_net_drop_down_metric, 'dropin'),
Allen Liec5beb32016-09-08 15:31:41 -0700226 ]
227
228 nics = psutil.net_io_counters(pernic=True)
229 for nic, counters in nics.iteritems():
Allen Li10eb79a2016-10-19 11:11:53 -0700230 # TODO(ayatane): Use a different way of identifying virtual interfaces
231 if nic.startswith('veth'):
232 # Skip virtual interfaces
233 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 Lia6b02252016-10-26 14:40:51 -0700242 logging.warning(str(ex))
Allen Liec5beb32016-09-08 15:31:41 -0700243
244
245def get_os_info():
Allen Lia6b02252016-10-26 14:40:51 -0700246 os_info = _get_os_info()
247 _os_name_metric.set(os_info.name)
248 _os_version_metric.set(os_info.version)
249 _os_arch_metric.set(platform.machine())
250 _python_arch_metric.set(_get_python_arch())
Allen Liec5beb32016-09-08 15:31:41 -0700251
Allen Liec5beb32016-09-08 15:31:41 -0700252
Allen Lia6b02252016-10-26 14:40:51 -0700253OSInfo = collections.namedtuple('OSInfo', 'name,version')
254
255
256def _get_os_info():
257 """Get OS name and version.
258
259 Returns:
260 OSInfo instance
261 """
262 os_name = platform.system().lower()
263 os_version = ''
264 if 'windows' in os_name:
265 os_name = 'windows'
266 # release will be something like '7', 'vista', or 'xp'
267 os_version = platform.release()
268 elif 'linux' in os_name:
Allen Liec5beb32016-09-08 15:31:41 -0700269 # will return something like ('Ubuntu', '14.04', 'trusty')
Allen Lia6b02252016-10-26 14:40:51 -0700270 os_name, os_version, _ = platform.dist()
Allen Liec5beb32016-09-08 15:31:41 -0700271 else:
Allen Lia6b02252016-10-26 14:40:51 -0700272 # On mac platform.system() reports 'darwin'.
273 os_version = _get_mac_version()
274 if os_version:
275 # We found a valid mac.
276 os_name = 'mac'
Allen Liec5beb32016-09-08 15:31:41 -0700277 else:
278 # not a mac, unable to find platform information, reset
Allen Lia6b02252016-10-26 14:40:51 -0700279 os_name = ''
280 os_version = ''
Allen Liec5beb32016-09-08 15:31:41 -0700281
Allen Lia6b02252016-10-26 14:40:51 -0700282 os_name = os_name.lower()
283 os_version = os_version.lower()
284 return OSInfo(name=os_name, version=os_version)
Allen Liec5beb32016-09-08 15:31:41 -0700285
Allen Lia6b02252016-10-26 14:40:51 -0700286def _get_mac_version():
287 """Get Mac system version.
288
289 Returns:
290 Version string, which is empty if not a valid Mac system.
291 """
292 # This tuple is only populated on mac systems.
293 mac_ver = platform.mac_ver()
294 # Will be '10.11.5' or similar on a valid mac or will be '' on a non-mac.
295 os_version = mac_ver[0]
296 return os_version
297
298
299def _get_python_arch():
Allen Liec5beb32016-09-08 15:31:41 -0700300 if sys.maxsize > 2**32:
Allen Lia6b02252016-10-26 14:40:51 -0700301 return '64'
302 else:
303 return '32'
Allen Liec5beb32016-09-08 15:31:41 -0700304
305
306def get_proc_info():
Allen Liefe7adf2016-10-27 11:36:04 -0700307 autoserv_count = 0
308 total = 0
309 for proc in psutil.process_iter():
310 if _is_autoserv_proc(proc):
311 autoserv_count += 1
312 total += 1
313 _autoserv_proc_count_metric.set(autoserv_count)
314 _proc_count_metric.set(total)
315
316
317def _is_autoserv_proc(proc):
318 return (
319 proc.name == 'python'
320 and '/usr/local/autotest/server/autoserv' in proc.cmdline)
Allen Liec5beb32016-09-08 15:31:41 -0700321
Allen Lia6b02252016-10-26 14:40:51 -0700322
323def get_load_avg():
324 try:
325 avg1, avg5, avg15 = os.getloadavg()
326 except OSError:
327 pass
328 else:
329 _load_average_metric.set(avg1, fields={'minutes': 1})
330 _load_average_metric.set(avg5, fields={'minutes': 5})
331 _load_average_metric.set(avg15, fields={'minutes': 15})
Allen Liec5beb32016-09-08 15:31:41 -0700332
333
334def get_unix_time():
Allen Lia6b02252016-10-26 14:40:51 -0700335 _unix_time_metric.set(int(time.time() * 1000))