blob: b56c1714e3b494038b0e3d9028fcbbb4b1012f97 [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.')
108_load_average_metric = ts_mon.FloatMetric(
109 'dev/proc/load_average',
110 description='Number of processes currently '
111 'in the system run queue.')
Allen Liec5beb32016-09-08 15:31:41 -0700112
Allen Lia6b02252016-10-26 14:40:51 -0700113# ts_mon pipeline uses backend clocks when assigning timestamps to metric
114# points. By comparing point timestamp to the point value (i.e. time by
115# machine's local clock), we can potentially detect some anomalies (clock
116# drift, unusually high metrics pipeline delay, completely wrong clocks, etc).
Allen Liec5beb32016-09-08 15:31:41 -0700117#
118# It is important to gather this metric right before the flush.
Allen Lia6b02252016-10-26 14:40:51 -0700119_unix_time_metric = ts_mon.GaugeMetric(
Allen Liec5beb32016-09-08 15:31:41 -0700120 'dev/unix_time',
Allen Lia6b02252016-10-26 14:40:51 -0700121 description='Number of milliseconds since epoch'
122 ' based on local machine clock.')
Allen Liec5beb32016-09-08 15:31:41 -0700123
Allen Lia6b02252016-10-26 14:40:51 -0700124_os_name_metric = ts_mon.StringMetric(
125 'proc/os/name',
126 description='OS name on the machine')
Allen Liec5beb32016-09-08 15:31:41 -0700127
Allen Lia6b02252016-10-26 14:40:51 -0700128_os_version_metric = ts_mon.StringMetric(
129 'proc/os/version',
130 description='OS version on the machine')
Allen Liec5beb32016-09-08 15:31:41 -0700131
Allen Lia6b02252016-10-26 14:40:51 -0700132_os_arch_metric = ts_mon.StringMetric(
133 'proc/os/arch',
134 description='OS architecture on this machine')
Allen Liec5beb32016-09-08 15:31:41 -0700135
Allen Lia6b02252016-10-26 14:40:51 -0700136_python_arch_metric = ts_mon.StringMetric(
137 'proc/python/arch',
138 description='python userland '
139 'architecture on this machine')
Allen Liec5beb32016-09-08 15:31:41 -0700140
141
142def get_uptime():
Allen Lia6b02252016-10-26 14:40:51 -0700143 _uptime_metric.set(int(time.time() - BOOT_TIME))
Allen Liec5beb32016-09-08 15:31:41 -0700144
145
146def get_cpu_info():
Allen Lia6b02252016-10-26 14:40:51 -0700147 _cpu_count_metric.set(psutil.cpu_count())
Allen Liec5beb32016-09-08 15:31:41 -0700148
149 times = psutil.cpu_times_percent()
150 for mode in ('user', 'system', 'idle'):
Allen Lia6b02252016-10-26 14:40:51 -0700151 _cpu_time_metric.set(getattr(times, mode), {'mode': mode})
Allen Liec5beb32016-09-08 15:31:41 -0700152
153
154def get_disk_info(mountpoints=None):
155 if mountpoints is None:
156 mountpoints = [disk.mountpoint for disk in psutil.disk_partitions()]
Allen Liec5beb32016-09-08 15:31:41 -0700157 for mountpoint in mountpoints:
Allen Lia6b02252016-10-26 14:40:51 -0700158 _get_disk_info_single(mountpoint)
159 _get_fs_inode_info(mountpoint)
160 _get_disk_io_info()
Allen Liec5beb32016-09-08 15:31:41 -0700161
Allen Liec5beb32016-09-08 15:31:41 -0700162
Allen Lia6b02252016-10-26 14:40:51 -0700163def _get_disk_info_single(mountpoint):
164 fields = {'path': mountpoint}
Allen Liec5beb32016-09-08 15:31:41 -0700165
166 try:
Allen Lia6b02252016-10-26 14:40:51 -0700167 usage = psutil.disk_usage(mountpoint)
168 except OSError as ex:
169 if ex.errno == errno.ENOENT:
170 # This happens on Windows when querying a removable drive that
171 # doesn't have any media inserted right now.
172 pass
173 else:
174 raise
175 else:
176 _disk_free_metric.set(usage.free, fields=fields)
177 _disk_total_metric.set(usage.total, fields=fields)
178
179 # inode counts are only available on Unix.
180 if os.name == 'posix':
181 _get_fs_inode_info(mountpoint)
182
183
184def _get_fs_inode_info(mountpoint):
185 fields = {'path': mountpoint}
186 stats = os.statvfs(mountpoint)
187 _inodes_free_metric.set(stats.f_favail, fields=fields)
188 _inodes_total_metric.set(stats.f_files, fields=fields)
189
190
191def _get_disk_io_info():
192 try:
193 disk_counters = psutil.disk_io_counters(perdisk=True).iteritems()
Allen Liec5beb32016-09-08 15:31:41 -0700194 except RuntimeError as ex:
195 if "couldn't find any physical disk" in str(ex):
196 # Disk performance counters aren't enabled on Windows.
197 pass
198 else:
199 raise
Allen Lia6b02252016-10-26 14:40:51 -0700200 else:
201 for disk, counters in disk_counters:
202 fields = {'disk': disk}
203 _disk_read_metric.set(counters.read_bytes, fields=fields)
204 _disk_write_metric.set(counters.write_bytes, fields=fields)
Allen Liec5beb32016-09-08 15:31:41 -0700205
206
207def get_mem_info():
208 # We don't report mem.used because (due to virtual memory) it is not
209 # useful.
210 mem = psutil.virtual_memory()
Allen Lia6b02252016-10-26 14:40:51 -0700211 _mem_free_metric.set(mem.available)
212 _mem_total_metric.set(mem.total)
Allen Liec5beb32016-09-08 15:31:41 -0700213
214
215def get_net_info():
216 metric_counter_names = [
Allen Lia6b02252016-10-26 14:40:51 -0700217 (_net_up_metric, 'bytes_sent'),
218 (_net_down_metric, 'bytes_recv'),
219 (_net_err_up_metric, 'errout'),
220 (_net_err_down_metric, 'errin'),
221 (_net_drop_up_metric, 'dropout'),
222 (_net_drop_down_metric, 'dropin'),
Allen Liec5beb32016-09-08 15:31:41 -0700223 ]
224
225 nics = psutil.net_io_counters(pernic=True)
226 for nic, counters in nics.iteritems():
Allen Li10eb79a2016-10-19 11:11:53 -0700227 # TODO(ayatane): Use a different way of identifying virtual interfaces
228 if nic.startswith('veth'):
229 # Skip virtual interfaces
230 continue
Allen Liec5beb32016-09-08 15:31:41 -0700231 fields = {'interface': nic}
232 for metric, counter_name in metric_counter_names:
233 try:
234 metric.set(getattr(counters, counter_name), fields=fields)
235 except ts_mon.MonitoringDecreasingValueError as ex:
236 # This normally shouldn't happen, but might if the network
237 # driver module is reloaded, so log an error and continue
238 # instead of raising an exception.
Allen Lia6b02252016-10-26 14:40:51 -0700239 logging.warning(str(ex))
Allen Liec5beb32016-09-08 15:31:41 -0700240
241
242def get_os_info():
Allen Lia6b02252016-10-26 14:40:51 -0700243 os_info = _get_os_info()
244 _os_name_metric.set(os_info.name)
245 _os_version_metric.set(os_info.version)
246 _os_arch_metric.set(platform.machine())
247 _python_arch_metric.set(_get_python_arch())
Allen Liec5beb32016-09-08 15:31:41 -0700248
Allen Liec5beb32016-09-08 15:31:41 -0700249
Allen Lia6b02252016-10-26 14:40:51 -0700250OSInfo = collections.namedtuple('OSInfo', 'name,version')
251
252
253def _get_os_info():
254 """Get OS name and version.
255
256 Returns:
257 OSInfo instance
258 """
259 os_name = platform.system().lower()
260 os_version = ''
261 if 'windows' in os_name:
262 os_name = 'windows'
263 # release will be something like '7', 'vista', or 'xp'
264 os_version = platform.release()
265 elif 'linux' in os_name:
Allen Liec5beb32016-09-08 15:31:41 -0700266 # will return something like ('Ubuntu', '14.04', 'trusty')
Allen Lia6b02252016-10-26 14:40:51 -0700267 os_name, os_version, _ = platform.dist()
Allen Liec5beb32016-09-08 15:31:41 -0700268 else:
Allen Lia6b02252016-10-26 14:40:51 -0700269 # On mac platform.system() reports 'darwin'.
270 os_version = _get_mac_version()
271 if os_version:
272 # We found a valid mac.
273 os_name = 'mac'
Allen Liec5beb32016-09-08 15:31:41 -0700274 else:
275 # not a mac, unable to find platform information, reset
Allen Lia6b02252016-10-26 14:40:51 -0700276 os_name = ''
277 os_version = ''
Allen Liec5beb32016-09-08 15:31:41 -0700278
Allen Lia6b02252016-10-26 14:40:51 -0700279 os_name = os_name.lower()
280 os_version = os_version.lower()
281 return OSInfo(name=os_name, version=os_version)
Allen Liec5beb32016-09-08 15:31:41 -0700282
Allen Lia6b02252016-10-26 14:40:51 -0700283def _get_mac_version():
284 """Get Mac system version.
285
286 Returns:
287 Version string, which is empty if not a valid Mac system.
288 """
289 # This tuple is only populated on mac systems.
290 mac_ver = platform.mac_ver()
291 # Will be '10.11.5' or similar on a valid mac or will be '' on a non-mac.
292 os_version = mac_ver[0]
293 return os_version
294
295
296def _get_python_arch():
Allen Liec5beb32016-09-08 15:31:41 -0700297 if sys.maxsize > 2**32:
Allen Lia6b02252016-10-26 14:40:51 -0700298 return '64'
299 else:
300 return '32'
Allen Liec5beb32016-09-08 15:31:41 -0700301
302
303def get_proc_info():
304 procs = psutil.pids()
Allen Lia6b02252016-10-26 14:40:51 -0700305 _proc_count_metric.set(len(procs))
Allen Liec5beb32016-09-08 15:31:41 -0700306
Allen Lia6b02252016-10-26 14:40:51 -0700307
308def get_load_avg():
309 try:
310 avg1, avg5, avg15 = os.getloadavg()
311 except OSError:
312 pass
313 else:
314 _load_average_metric.set(avg1, fields={'minutes': 1})
315 _load_average_metric.set(avg5, fields={'minutes': 5})
316 _load_average_metric.set(avg15, fields={'minutes': 15})
Allen Liec5beb32016-09-08 15:31:41 -0700317
318
319def get_unix_time():
Allen Lia6b02252016-10-26 14:40:51 -0700320 _unix_time_metric.set(int(time.time() * 1000))