Allen Li | 51bb612 | 2017-06-21 12:04:13 -0700 | [diff] [blame] | 1 | # 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 | |
| 7 | from __future__ import absolute_import |
| 8 | from __future__ import print_function |
| 9 | |
| 10 | import psutil |
| 11 | |
| 12 | from chromite.lib import cros_logging as logging |
| 13 | from infra_libs import ts_mon |
| 14 | |
| 15 | logger = logging.getLogger(__name__) |
| 16 | |
| 17 | _proc_count_metric = ts_mon.GaugeMetric( |
| 18 | 'dev/proc/count', |
| 19 | description='Number of processes currently running.') |
| 20 | _autoserv_proc_count_metric = ts_mon.GaugeMetric( |
| 21 | 'dev/proc/autoserv_count', |
| 22 | description='Number of autoserv processes currently running.') |
| 23 | _sysmon_proc_count_metric = ts_mon.GaugeMetric( |
| 24 | 'dev/proc/sysmon_count', |
| 25 | description='Number of sysmon processes currently running.') |
| 26 | _apache_proc_count_metric = ts_mon.GaugeMetric( |
| 27 | 'dev/proc/apache_count', |
| 28 | description='Number of apache processes currently running.') |
| 29 | |
| 30 | |
| 31 | def collect_proc_info(): |
| 32 | autoserv_count = 0 |
| 33 | sysmon_count = 0 |
| 34 | apache_count = 0 |
| 35 | total = 0 |
| 36 | for proc in psutil.process_iter(): |
| 37 | if _is_parent_autoserv(proc): |
| 38 | autoserv_count += 1 |
| 39 | elif _is_sysmon(proc): |
| 40 | sysmon_count += 1 |
| 41 | elif _is_apache(proc): |
| 42 | apache_count += 1 |
| 43 | total += 1 |
| 44 | logger.debug(u'autoserv_count: %s', autoserv_count) |
| 45 | logger.debug(u'sysmon_count: %s', sysmon_count) |
| 46 | logger.debug(u'apache_count: %s', apache_count) |
| 47 | _autoserv_proc_count_metric.set(autoserv_count) |
| 48 | _sysmon_proc_count_metric.set(sysmon_count) |
| 49 | _apache_proc_count_metric.set(apache_count) |
| 50 | _proc_count_metric.set(total) |
| 51 | |
| 52 | |
| 53 | def _is_parent_autoserv(proc): |
| 54 | """Return whether proc is a parent (not forked) autoserv process.""" |
| 55 | return _is_autoserv(proc) and not _is_autoserv(proc.parent()) |
| 56 | |
| 57 | |
| 58 | def _is_autoserv(proc): |
| 59 | """Return whether proc is an autoserv process.""" |
| 60 | # This relies on the autoserv script being run directly. The script should |
| 61 | # be named autoserv exactly and start with a shebang that is /usr/bin/python, |
| 62 | # NOT /bin/env |
| 63 | return proc.name() == 'autoserv' |
| 64 | |
| 65 | |
| 66 | def _is_apache(proc): |
| 67 | """Return whether a proc is an apache2 process.""" |
| 68 | return proc.name() == 'apache2' |
| 69 | |
| 70 | |
| 71 | def _is_sysmon(proc): |
| 72 | """Return whether proc is a sysmon process.""" |
| 73 | return proc.cmdline()[:3] == ['python', '-m', 'chromite.scripts.sysmon'] |