blob: eaf783cf9ce1c7a5bb5ebfec28650991463a079c [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Allen Li51bb6122017-06-21 12:04:13 -07002# Copyright 2017 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Process metrics."""
7
8from __future__ import absolute_import
9from __future__ import print_function
10
Allen Li3992c662018-01-05 15:26:36 -080011from functools import partial
12
Mike Frysingercb56b642019-08-25 15:33:08 -040013import psutil # pylint: disable=import-error
Allen Li51bb6122017-06-21 12:04:13 -070014
15from chromite.lib import cros_logging as logging
Allen Lia9c6e802017-07-11 15:42:47 -070016from chromite.lib import metrics
Allen Li51bb6122017-06-21 12:04:13 -070017
18logger = logging.getLogger(__name__)
19
Allen Lia9c6e802017-07-11 15:42:47 -070020_count_metric = metrics.GaugeMetric(
Allen Li6bb74d52017-06-22 14:44:53 -070021 'proc/count',
Allen Li51bb6122017-06-21 12:04:13 -070022 description='Number of processes currently running.')
Allen Lia9c6e802017-07-11 15:42:47 -070023_cpu_percent_metric = metrics.GaugeMetric(
Allen Li6bb74d52017-06-22 14:44:53 -070024 'proc/cpu_percent',
25 description='CPU usage percent of processes.')
Allen Li51bb6122017-06-21 12:04:13 -070026
27
28def collect_proc_info():
Allen Li6bb74d52017-06-22 14:44:53 -070029 collector = _ProcessMetricsCollector()
30 collector.collect()
31
32
33class _ProcessMetricsCollector(object):
34 """Class for collecting process metrics."""
35
36 def __init__(self):
37 self._metrics = [
Allen Li3511a832018-06-27 14:41:01 -070038 _ProcessMetric('apache',
39 test_func=partial(_is_process_name, 'apache2')),
Allen Li22989bd2017-07-12 10:34:37 -070040 _ProcessMetric('autoserv',
41 test_func=_is_parent_autoserv),
Aviv Keshet98f33792019-10-29 11:05:53 -070042 _ProcessMetric('getty',
43 test_func=partial(_is_process_name, 'getty')),
Allen Li3511a832018-06-27 14:41:01 -070044 _ProcessMetric('gs_offloader',
45 test_func=_is_gs_offloader),
Allen Li3992c662018-01-05 15:26:36 -080046 _ProcessMetric('job_aborter',
47 test_func=partial(_is_python_module,
48 'lucifer.cmd.job_aborter')),
49 _ProcessMetric('job_reporter',
50 test_func=partial(_is_python_module,
51 'lucifer.cmd.job_reporter')),
Allen Liee3f5c42018-08-27 18:07:06 -070052 _ProcessMetric('lucifer',
53 test_func=partial(_is_process_name, 'lucifer')),
Prathmesh Prabhu5ed6f902018-05-07 14:13:02 -070054 _ProcessMetric('lxc-start',
55 test_func=partial(_is_process_name, 'lxc-start')),
56 _ProcessMetric('lxc-attach',
57 test_func=partial(_is_process_name, 'lxc-attach')),
Allen Li3511a832018-06-27 14:41:01 -070058 _ProcessMetric('sysmon',
59 test_func=partial(_is_python_module,
60 'chromite.scripts.sysmon')),
Allen Li6bb74d52017-06-22 14:44:53 -070061 ]
62 self._other_metric = _ProcessMetric('other')
63
64 def collect(self):
65 for proc in psutil.process_iter():
66 self._collect_proc(proc)
67 self._flush()
68
69 def _collect_proc(self, proc):
Allen Li6bb74d52017-06-22 14:44:53 -070070 for metric in self._metrics:
Allen Lif8397a82017-07-13 13:19:44 -070071 if metric.add(proc):
72 break
73 else:
Allen Li6bb74d52017-06-22 14:44:53 -070074 self._other_metric.add(proc)
75
76 def _flush(self):
77 for metric in self._metrics:
78 metric.flush()
79 self._other_metric.flush()
80
81
82class _ProcessMetric(object):
83 """Class for gathering process metrics."""
84
85 def __init__(self, process_name, test_func=lambda proc: True):
86 """Initialize instance.
87
88 process_name is used to identify the metric stream.
89
90 test_func is a function called
91 for each process. If it returns True, the process is counted. The
92 default test is to count every process.
93 """
94 self._fields = {
Allen Li22989bd2017-07-12 10:34:37 -070095 'process_name': process_name,
Allen Li6bb74d52017-06-22 14:44:53 -070096 }
97 self._test_func = test_func
98 self._count = 0
99 self._cpu_percent = 0
100
101 def add(self, proc):
102 """Do metric collection for the given process.
103
104 Returns True if the process was collected.
105 """
106 if not self._test_func(proc):
107 return False
108 self._count += 1
109 self._cpu_percent += proc.cpu_percent()
110 return True
111
112 def flush(self):
113 """Finish collection and send metrics."""
114 _count_metric.set(self._count, fields=self._fields)
115 self._count = 0
Aviv Keshet0b634e92017-07-14 14:29:48 -0700116 _cpu_percent_metric.set(int(round(self._cpu_percent)), fields=self._fields)
Allen Li6bb74d52017-06-22 14:44:53 -0700117 self._cpu_percent = 0
Allen Li51bb6122017-06-21 12:04:13 -0700118
119
120def _is_parent_autoserv(proc):
121 """Return whether proc is a parent (not forked) autoserv process."""
122 return _is_autoserv(proc) and not _is_autoserv(proc.parent())
123
124
125def _is_autoserv(proc):
126 """Return whether proc is an autoserv process."""
127 # This relies on the autoserv script being run directly. The script should
128 # be named autoserv exactly and start with a shebang that is /usr/bin/python,
129 # NOT /bin/env
Prathmesh Prabhu0b795f02018-05-07 13:12:37 -0700130 return _is_process_name('autoserv', proc)
Allen Li51bb6122017-06-21 12:04:13 -0700131
132
Allen Li3511a832018-06-27 14:41:01 -0700133def _is_gs_offloader(proc):
134 """Return whether proc is a gs_offloader process."""
135 cmdline = proc.cmdline()
136 return (len(cmdline) >= 2
137 and cmdline[0].endswith('python')
138 and cmdline[1].endswith('gs_offloader.py'))
139
140
Allen Li3992c662018-01-05 15:26:36 -0800141def _is_python_module(module, proc):
142 """Return whether proc is a process running a Python module."""
Aviv Keshet70a91c52017-07-17 16:09:09 -0700143 cmdline = proc.cmdline()
144 return (cmdline and
145 cmdline[0].endswith('python') and
Allen Li3992c662018-01-05 15:26:36 -0800146 cmdline[1:3] == ['-m', module])
147
148
Prathmesh Prabhu0b795f02018-05-07 13:12:37 -0700149def _is_process_name(name, proc):
150 """Return whether process proc is named name."""
151 return proc.name() == name