blob: f03adcebb6f10d859607e10d67b30985c88232b8 [file] [log] [blame]
Allen Li51bb6122017-06-21 12:04:13 -07001# Copyright 2017 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"""Process metrics."""
6
7from __future__ import absolute_import
Allen Li51bb6122017-06-21 12:04:13 -07008
Allen Li3992c662018-01-05 15:26:36 -08009from functools import partial
Chris McDonald59650c32021-07-20 15:29:28 -060010import logging
Allen Li3992c662018-01-05 15:26:36 -080011
Mike Frysingercb56b642019-08-25 15:33:08 -040012import psutil # pylint: disable=import-error
Allen Li51bb6122017-06-21 12:04:13 -070013
Allen Lia9c6e802017-07-11 15:42:47 -070014from chromite.lib import metrics
Allen Li51bb6122017-06-21 12:04:13 -070015
Chris McDonald59650c32021-07-20 15:29:28 -060016
Allen Li51bb6122017-06-21 12:04:13 -070017logger = logging.getLogger(__name__)
18
Allen Lia9c6e802017-07-11 15:42:47 -070019_count_metric = metrics.GaugeMetric(
Alex Klein1699fab2022-09-08 08:46:06 -060020 "proc/count", description="Number of processes currently running."
21)
Allen Lia9c6e802017-07-11 15:42:47 -070022_cpu_percent_metric = metrics.GaugeMetric(
Alex Klein1699fab2022-09-08 08:46:06 -060023 "proc/cpu_percent", description="CPU usage percent of processes."
24)
Allen Li51bb6122017-06-21 12:04:13 -070025
26
27def collect_proc_info():
Alex Klein1699fab2022-09-08 08:46:06 -060028 collector = _ProcessMetricsCollector()
29 collector.collect()
Allen Li6bb74d52017-06-22 14:44:53 -070030
31
32class _ProcessMetricsCollector(object):
Alex Klein1699fab2022-09-08 08:46:06 -060033 """Class for collecting process metrics."""
Allen Li6bb74d52017-06-22 14:44:53 -070034
Alex Klein1699fab2022-09-08 08:46:06 -060035 def __init__(self):
36 self._metrics = [
37 _ProcessMetric("autoserv", test_func=_is_parent_autoserv),
38 _ProcessMetric("curl", test_func=partial(_is_process_name, "curl")),
39 _ProcessMetric(
40 "getty", test_func=partial(_is_process_name, "getty")
41 ),
42 _ProcessMetric(
43 "gs_archive_server",
44 test_func=partial(_is_python_module, "gs_archive_server"),
45 ),
46 _ProcessMetric(
47 "gs_offloader",
48 test_func=partial(_is_process_name, "gs_offloader.py"),
49 ),
50 _ProcessMetric("gsutil", test_func=_is_gsutil),
51 _ProcessMetric("java", test_func=partial(_is_process_name, "java")),
52 _ProcessMetric(
53 "lxc-attach", test_func=partial(_is_process_name, "lxc-attach")
54 ),
55 _ProcessMetric(
56 "lxc-start", test_func=partial(_is_process_name, "lxc-start")
57 ),
58 _ProcessMetric("sshd", test_func=partial(_is_process_name, "sshd")),
59 _ProcessMetric("swarming_bot", test_func=_is_swarming_bot),
60 _ProcessMetric(
61 "sysmon",
62 test_func=partial(_is_python_module, "chromite.scripts.sysmon"),
63 ),
64 ]
65 self._other_metric = _ProcessMetric("other")
Allen Li6bb74d52017-06-22 14:44:53 -070066
Alex Klein1699fab2022-09-08 08:46:06 -060067 def collect(self):
68 for proc in psutil.process_iter():
69 self._collect_proc(proc)
70 self._flush()
Allen Li6bb74d52017-06-22 14:44:53 -070071
Alex Klein1699fab2022-09-08 08:46:06 -060072 def _collect_proc(self, proc):
73 for metric in self._metrics:
74 if metric.add(proc):
75 break
76 else:
77 self._other_metric.add(proc)
Allen Li6bb74d52017-06-22 14:44:53 -070078
Alex Klein1699fab2022-09-08 08:46:06 -060079 def _flush(self):
80 for metric in self._metrics:
81 metric.flush()
82 self._other_metric.flush()
Allen Li6bb74d52017-06-22 14:44:53 -070083
84
85class _ProcessMetric(object):
Alex Klein1699fab2022-09-08 08:46:06 -060086 """Class for gathering process metrics."""
Allen Li6bb74d52017-06-22 14:44:53 -070087
Alex Klein1699fab2022-09-08 08:46:06 -060088 def __init__(self, process_name, test_func=lambda proc: True):
89 """Initialize instance.
Allen Li6bb74d52017-06-22 14:44:53 -070090
Alex Klein1699fab2022-09-08 08:46:06 -060091 process_name is used to identify the metric stream.
Allen Li6bb74d52017-06-22 14:44:53 -070092
Alex Klein1699fab2022-09-08 08:46:06 -060093 test_func is a function called
94 for each process. If it returns True, the process is counted. The
95 default test is to count every process.
96 """
97 self._fields = {
98 "process_name": process_name,
99 }
100 self._test_func = test_func
101 self._count = 0
102 self._cpu_percent = 0
Allen Li6bb74d52017-06-22 14:44:53 -0700103
Alex Klein1699fab2022-09-08 08:46:06 -0600104 def add(self, proc):
105 """Do metric collection for the given process.
Allen Li6bb74d52017-06-22 14:44:53 -0700106
Alex Klein1699fab2022-09-08 08:46:06 -0600107 Returns True if the process was collected.
108 """
109 if not self._test_func(proc):
110 return False
111 self._count += 1
112 self._cpu_percent += proc.cpu_percent()
113 return True
Allen Li6bb74d52017-06-22 14:44:53 -0700114
Alex Klein1699fab2022-09-08 08:46:06 -0600115 def flush(self):
116 """Finish collection and send metrics."""
117 _count_metric.set(self._count, fields=self._fields)
118 self._count = 0
119 _cpu_percent_metric.set(
120 int(round(self._cpu_percent)), fields=self._fields
121 )
122 self._cpu_percent = 0
Allen Li51bb6122017-06-21 12:04:13 -0700123
124
125def _is_parent_autoserv(proc):
Alex Klein1699fab2022-09-08 08:46:06 -0600126 """Return whether proc is a parent (not forked) autoserv process."""
127 return _is_autoserv(proc) and not _is_autoserv(proc.parent())
Allen Li51bb6122017-06-21 12:04:13 -0700128
129
130def _is_autoserv(proc):
Alex Klein1699fab2022-09-08 08:46:06 -0600131 """Return whether proc is an autoserv process."""
132 # This relies on the autoserv script being run directly. The script should
133 # be named autoserv exactly and start with a shebang that is /usr/bin/python,
134 # NOT /bin/env
135 return _is_process_name("autoserv", proc)
Allen Li51bb6122017-06-21 12:04:13 -0700136
137
Allen Li3992c662018-01-05 15:26:36 -0800138def _is_python_module(module, proc):
Alex Klein1699fab2022-09-08 08:46:06 -0600139 """Return whether proc is a process running a Python module."""
140 cmdline = proc.cmdline()
141 return (
142 cmdline
143 and cmdline[0].endswith("python")
144 and cmdline[1:3] == ["-m", module]
145 )
Allen Li3992c662018-01-05 15:26:36 -0800146
147
Prathmesh Prabhu0b795f02018-05-07 13:12:37 -0700148def _is_process_name(name, proc):
Alex Klein1699fab2022-09-08 08:46:06 -0600149 """Return whether process proc is named name."""
150 return proc.name() == name
Congbin Guo17542e02022-06-29 13:48:15 -0700151
152
153def _is_swarming_bot(proc):
Alex Klein1699fab2022-09-08 08:46:06 -0600154 """Return whether proc is a Swarming bot.
Congbin Guo17542e02022-06-29 13:48:15 -0700155
Alex Klein1699fab2022-09-08 08:46:06 -0600156 A swarming bot process is like '/usr/bin/python3.8 <bot-zip-path> start_bot'.
157 """
158 cmdline = proc.cmdline()
159 return (
160 len(cmdline) == 3
161 and cmdline[0].split("/")[-1].startswith("python")
162 and cmdline[2] == "start_bot"
163 )
Congbin Guo17542e02022-06-29 13:48:15 -0700164
165
166def _is_gsutil(proc):
Alex Klein1699fab2022-09-08 08:46:06 -0600167 """Return whether proc is gsutil."""
168 cmdline = proc.cmdline()
169 return (
170 len(cmdline) >= 2
171 and cmdline[0] == "python"
172 and cmdline[1].endswith("gsutil")
173 )