| 1 |
#!/usr/bin/python3 |
| 2 |
|
| 3 |
# Copyright (C) 2001 Matt Zimmerman <[email protected]> |
| 4 |
# Copyright (C) 2007-2020 Javier Fernandez-Sanguino <[email protected]> |
| 5 |
# - included patch from Justin Pryzby <justinpryzby_AT_users.sourceforge.net> |
| 6 |
# to work with the latest Lsof |
| 7 |
# - modify to reduce false positives by not |
| 8 |
# complaining about deleted inodes/files under /tmp/, /var/log/, |
| 9 |
# /var/run or named /SYSV. |
| 10 |
# - introduced a verbose option |
| 11 |
# - included code from 'psdel' contributed by Sam Morris <sam_AT_robots.org.uk> to |
| 12 |
# make the program work even if lsof is not installed |
| 13 |
# (available at https://robots.org.uk/src/psdel) |
| 14 |
# Copyright (C) 2013-2020 Axel Beckert |
| 15 |
# Copyright (C) 2022 Richard Lewis |
| 16 |
# |
| 17 |
# This program is free software; you can redistribute it and/or modify |
| 18 |
# it under the terms of the GNU General Public License as published by |
| 19 |
# the Free Software Foundation; either version 2, or (at your option) |
| 20 |
# any later version. |
| 21 |
|
| 22 |
# This program is distributed in the hope that it will be useful, |
| 23 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 24 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 25 |
# GNU General Public License for more details. |
| 26 |
|
| 27 |
# You should have received a copy of the GNU General Public License |
| 28 |
# along with this program; if not, write to the Free Software |
| 29 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, |
| 30 |
# MA 02110-1301 USA |
| 31 |
# |
| 32 |
# On Debian systems, a copy of the GNU General Public License may be |
| 33 |
# found in /usr/share/common-licenses/GPL. |
| 34 |
|
| 35 |
import sys |
| 36 |
import os, errno |
| 37 |
import re |
| 38 |
import sys |
| 39 |
import subprocess |
| 40 |
import getopt |
| 41 |
import shutil |
| 42 |
import collections |
| 43 |
|
| 44 |
def checkroot(): |
| 45 |
if os.getuid() != 0: |
| 46 |
sys.stderr.write('WARNING: This program should be run as root: information will be incomplete\n') |
| 47 |
|
| 48 |
def init_is_systemd(): |
| 49 |
"""Is systemd being used""" |
| 50 |
return os.path.exists('/run/systemd/system') |
| 51 |
|
| 52 |
def cgroups2(): |
| 53 |
"""Are cgroups(7) v2 in use""" |
| 54 |
if init_is_systemd(): |
| 55 |
return subprocess.run(["stat", "-fc", "%T", "/sys/fs/cgroup"], |
| 56 |
capture_output=True, |
| 57 |
encoding="utf-8", |
| 58 |
errors="ignore").stdout.strip() == "cgroup2fs" |
| 59 |
else: |
| 60 |
return False |
| 61 |
|
| 62 |
|
| 63 |
def usage(code): |
| 64 |
msg="""Usage: checkrestart [OPTIONS] |
| 65 |
Shows processes using deleted files. |
| 66 |
Options: |
| 67 |
-h, --help Show this message and exit |
| 68 |
-f, --show-files Show the deleted files |
| 69 |
-v, --verbose Show more information |
| 70 |
-d, --debug Show extensive information (for debugging) |
| 71 |
-t, --terse Show only the number of processes needing |
| 72 |
a restart |
| 73 |
-m, --machine Produce machine-readable output |
| 74 |
|
| 75 |
-p, --packages Only look for files from a package |
| 76 |
-a, --all Report all deleted files, regardless of |
| 77 |
location. Cancels all uses of -x |
| 78 |
|
| 79 |
-n, --no-lsof Do not use lsof to find deleted files |
| 80 |
-b, --blocklistfile FILE Ignore files matching patterns in FILE |
| 81 |
-x, --exclude TYPE:REGEXP Ignore MATCH (a python regexp). |
| 82 |
The argument can be: |
| 83 |
|
| 84 |
package:xxx ~ ignore processes from package xxx |
| 85 |
program:/path/to/program ~ ignore program |
| 86 |
pid:N ~ ignore process with PID N |
| 87 |
file:/path/to/file ~ ignore anything using file |
| 88 |
unit:s.service ~ ignore all processes started by s.service |
| 89 |
|
| 90 |
dangerous-unit:s.service ~ Advise caution before restarting s.service |
| 91 |
(processes are still reported, but the |
| 92 |
command is shown as commented out) |
| 93 |
|
| 94 |
suggested-unit:s.service ~ do not guess that s can restart anything |
| 95 |
(only applies to programmes not started |
| 96 |
by any unit) |
| 97 |
|
| 98 |
dangerous-initscript:x ~ advise caution before restarting the |
| 99 |
initscript x (processes are still |
| 100 |
reported but the command is shown as |
| 101 |
commented out) |
| 102 |
|
| 103 |
suggested-initscript:x ~ do not suggest /etc/init.d/x can restart |
| 104 |
anything |
| 105 |
|
| 106 |
Everything after the ':' is a python regexp. 'file:' can be omitted |
| 107 |
The last two only affect what commands are shown, not what is reported |
| 108 |
|
| 109 |
-i, --exclude-package PACKAGE Same as -x package:PACKAGE |
| 110 |
--exclude-program PATH Same as -x program:PATH |
| 111 |
-e, --exclude-pid PID Same as -x pid:PID |
| 112 |
--exclude-file PATH Same as -x file:PATH |
| 113 |
--exclude-unit UNIT Same as -x unit:UNIT |
| 114 |
--dangerous-unit UNIT Same as -x dangerous-unit:UNIT |
| 115 |
--dont-suggest-unit U Same as -x suggested-unit:U |
| 116 |
--dangerous-initscript X Same as -x dangerous-initscript X |
| 117 |
--dont-suggest-initscript X Same as -x suggested-initscript:X |
| 118 |
""" |
| 119 |
if code==0: |
| 120 |
print(msg) |
| 121 |
else: |
| 122 |
sys.stderr.write(msg+'\n') |
| 123 |
sys.exit(code) |
| 124 |
|
| 125 |
def _parse_excludes(a,exclude,suggestions): |
| 126 |
"""Add a to exclude or suggestions, choosing the key based on the prefix in a. |
| 127 |
If no prefix, assume 'file:'""" |
| 128 |
for prefix in ["package:", "program:","pid:", |
| 129 |
"file:", |
| 130 |
"unit:", |
| 131 |
]: |
| 132 |
if _add_exclude(prefix,a,exclude): |
| 133 |
return None |
| 134 |
for prefix in ["suggested-unit:","dangerous-unit:", |
| 135 |
"suggested-initscript:","dangerous-initscript:", |
| 136 |
]: |
| 137 |
if _add_exclude(prefix,a,suggestions): |
| 138 |
return None |
| 139 |
_add_exclude("file:",f"file:{a}",exclude) |
| 140 |
|
| 141 |
|
| 142 |
def _add_exclude(prefix,s,exclude): |
| 143 |
"""If s starts with prefix, remove it and add remainder to exclude[prefix]. |
| 144 |
Returns True iff something was added to exclude.""" |
| 145 |
if s.startswith(prefix): |
| 146 |
a=s.removeprefix(prefix) |
| 147 |
if DEBUG: print(f"Adding exclusion: {prefix} {a}") |
| 148 |
try: |
| 149 |
exclude[prefix].append(re.compile(a)) |
| 150 |
except re.error as e: |
| 151 |
sys.stderr.write(f"ERROR: syntax error in '{prefix}' regexp {repr(a)}: {e}\n") |
| 152 |
sys.exit(3) |
| 153 |
return True |
| 154 |
else: |
| 155 |
return False |
| 156 |
|
| 157 |
def main(): |
| 158 |
"""Parse options, find processes using deleted files, filter, group, and output how to restart""" |
| 159 |
# lc_all_c_env is used by calls to dpkg-query (it does not really need to be a global variable) |
| 160 |
global lc_all_c_env |
| 161 |
lc_all_c_env = os.environ |
| 162 |
lc_all_c_env['LC_ALL'] = 'C' |
| 163 |
|
| 164 |
useLsof = True |
| 165 |
|
| 166 |
using_systemd=init_is_systemd() |
| 167 |
using_cgroups2=cgroups2() |
| 168 |
|
| 169 |
# exclude is a dict of prefix=>[Regexp] prefix corresponds to the |
| 170 |
# start of an argument to -x (see man page or usage). For example, |
| 171 |
# exclude["pid"] will exclude by pid. |
| 172 |
exclude=collections.defaultdict(list) |
| 173 |
|
| 174 |
# like exclude but suggested and dangerous - ie things not reset by -a |
| 175 |
suggestions=collections.defaultdict(list) |
| 176 |
# added as prefix for commands that are suggested to be dangerous |
| 177 |
caution="# CAUTION: " |
| 178 |
|
| 179 |
# Only report deleted files that were installed by a .deb package |
| 180 |
onlyPackageFiles = False |
| 181 |
|
| 182 |
# cache of exclusions: dict of prefix=>dict(what=>Bool) |
| 183 |
# used to cache whether a package, unit, etc is ignored or not-to-be-suggested or dangerous |
| 184 |
cache=collections.defaultdict(dict) |
| 185 |
|
| 186 |
# files from which to read extra entries for ignored* |
| 187 |
ignorelistFiles = [] |
| 188 |
|
| 189 |
# default settings (files in /etc/checkrestart) |
| 190 |
default_exclude=["local-exclude.conf","exclude.conf"] |
| 191 |
default_suggestions=["local-suggestions.conf","suggestions.conf"] |
| 192 |
|
| 193 |
# Parse options |
| 194 |
try: |
| 195 |
opts, args = getopt.getopt(sys.argv[1:], |
| 196 |
"hfvdtmpanb:x:e:i:", |
| 197 |
["help", |
| 198 |
"show-files", |
| 199 |
"verbose", "debug", "terse","machine", |
| 200 |
"no-lsof","nolsof", |
| 201 |
"packages", "all", |
| 202 |
"blocklistfile=","blacklist=", |
| 203 |
"exclude=", |
| 204 |
"exclude-package=","ignore=", |
| 205 |
"exclude-unit=", "exclude-program=", |
| 206 |
"exclude-pid=","excludepid=","exclude-file=", |
| 207 |
"dangerous-unit=", |
| 208 |
"dont-suggest-unit=", |
| 209 |
"dangerous-initscript=", |
| 210 |
"dont-suggest-initscript=", |
| 211 |
"no-systemd","no-cgroups2", |
| 212 |
]) |
| 213 |
except getopt.GetoptError as err: |
| 214 |
# eg: "option -y not recognized" |
| 215 |
sys.stderr.write(f"{err}\n") |
| 216 |
usage(3) |
| 217 |
|
| 218 |
## output |
| 219 |
# DEBUG is used in many functions so is left global (-d option), |
| 220 |
# although it would be better to |
| 221 |
global DEBUG |
| 222 |
DEBUG=False |
| 223 |
|
| 224 |
# verbose output (-v option) explains why things are ignored. |
| 225 |
verbose = False |
| 226 |
# Generate terse (one-line) output, disabled by default (-t option) |
| 227 |
terseOutput = False |
| 228 |
# Generate machine parsable output, disabled by default (-m option) |
| 229 |
machineOutput = False |
| 230 |
|
| 231 |
# Whether to list the (non-ignored) deleted files (-f option) |
| 232 |
showfiles=False |
| 233 |
|
| 234 |
for o, a in opts: |
| 235 |
if DEBUG: print(f"Option {o}; arg: {a}") |
| 236 |
if o in ("-h", "--help"): |
| 237 |
usage(0) |
| 238 |
elif o in ("-f","--show-files"): |
| 239 |
showfiles=True |
| 240 |
elif o in ("-v", "--verbose"): |
| 241 |
verbose = True |
| 242 |
showfiles=True |
| 243 |
elif o in ("-d", "--debug"): |
| 244 |
DEBUG=True |
| 245 |
verbose=True |
| 246 |
showfiles=True |
| 247 |
elif o in ("-t", "--terse"): |
| 248 |
terseOutput = True |
| 249 |
elif o in ("-m", "--machine"): |
| 250 |
machineOutput = True |
| 251 |
elif o in ("-p", "--packages"): |
| 252 |
onlyPackageFiles = True |
| 253 |
elif o in ("-a", "--all"): |
| 254 |
exclude=collections.defaultdict(list) |
| 255 |
ignorelistFiles=[] |
| 256 |
default_exclude=[] |
| 257 |
elif o in ("-n", "--no-lsof","--nolsof"): |
| 258 |
useLsof = False |
| 259 |
elif o in ("-b", "--blocklistfile","--blacklist"): |
| 260 |
ignorelistFiles.append(a) |
| 261 |
elif o in ("-x","--exclude"): |
| 262 |
_parse_excludes(a,exclude,suggestions) |
| 263 |
elif o in ("-i", "--exclude-package","--ignore"): |
| 264 |
_add_exclude("package:",f"package:{a}",exclude) |
| 265 |
elif o in ("--exclude-program",): |
| 266 |
_add_exclude("program:",f"program:{a}",exclude) |
| 267 |
elif o in ("-e", "--exclude-pid"): |
| 268 |
_add_exclude("pid:",f"pid:{a}",exclude) |
| 269 |
elif o in ("--exclude-file",): |
| 270 |
_add_exclude("file:",f"file:{a}",exclude) |
| 271 |
elif o in ("--exclude-unit",): |
| 272 |
_add_exclude("unit:",f"unit:{a}",exclude) |
| 273 |
elif o in ("--dangerous-unit",): |
| 274 |
_add_exclude("dangerous-unit:",f"dangerous-unit:{a}",suggestions) |
| 275 |
elif o in ("--dont-suggest-unit",): |
| 276 |
_add_exclude("suggested-unit:",f"suggested-unit:{a}",suggestions) |
| 277 |
elif o in ("--dangerous-initscript",): |
| 278 |
_add_exclude("dangerous-initscript:",f"dangerous-initscript:{a}",suggestions) |
| 279 |
elif o in ("--dont-suggest-initscript",): |
| 280 |
_add_exclude("suggested-initscript:",f"suggested-initscript:{a}",suggestions) |
| 281 |
elif o in ("--no-systemd",): |
| 282 |
# undocumented: debug only |
| 283 |
using_systemd=False |
| 284 |
using_cgroups2=False |
| 285 |
elif o in ("--no-cgroups2",): |
| 286 |
# undocumented: debug only |
| 287 |
using_cgroups2=False |
| 288 |
else: |
| 289 |
sys.stderr.write(f"INTERNAL ERROR: Unhandled option: {o}\n") |
| 290 |
usage(3) |
| 291 |
|
| 292 |
checkroot() |
| 293 |
|
| 294 |
|
| 295 |
load_default=default_exclude+default_suggestions |
| 296 |
if DEBUG: print(f"Default blocklist: {load_default}") |
| 297 |
for f in load_default: |
| 298 |
f=f"/etc/checkrestart/{f}" |
| 299 |
if os.path.exists(f): |
| 300 |
if DEBUG: print(f"Using default blocklist: {f}") |
| 301 |
ignorelistFiles.append(f) |
| 302 |
|
| 303 |
for f in ignorelistFiles: |
| 304 |
if DEBUG: print(f"Reading blocklist file: {f}") |
| 305 |
try: |
| 306 |
with open(f, 'r') as ignorelistFile: |
| 307 |
for line in ignorelistFile.readlines(): |
| 308 |
a=line.rstrip() |
| 309 |
if a.startswith("#") or a=="": |
| 310 |
continue |
| 311 |
_parse_excludes(a,exclude,suggestions) |
| 312 |
except OSError as e: |
| 313 |
sys.stderr.write(f"ERROR: Could not read file: {f}: {e}\n") |
| 314 |
sys.exit(3) |
| 315 |
|
| 316 |
|
| 317 |
if DEBUG: |
| 318 |
print(f"Exclusions: {exclude}") |
| 319 |
print(f"Excluded from suggestions: {suggestions}") |
| 320 |
|
| 321 |
if DEBUG: |
| 322 |
print(f"Systemd: {using_systemd}") |
| 323 |
print(f"cgroups v2: {using_cgroups2}") |
| 324 |
|
| 325 |
# Check if we have lsof, if not, use an alternative mechanism |
| 326 |
if not shutil.which('lsof'): |
| 327 |
useLsof=None |
| 328 |
if verbose: |
| 329 |
sys.stderr.write("WARNING: lsof is not available. Using alternative mechanism to find processes using deleted files.\n") |
| 330 |
if not useLsof: |
| 331 |
using_deleted = procfilescheck(exclude["pid:"],using_cgroups2) |
| 332 |
else: |
| 333 |
using_deleted = lsoffilescheck(using_cgroups2) |
| 334 |
|
| 335 |
if verbose: |
| 336 |
if machineOutput: |
| 337 |
print(f"PROCESSES_ALL: {len(using_deleted)}") |
| 338 |
else: |
| 339 |
print(f"(Found {len(using_deleted)} process(es) using deleted files)") |
| 340 |
|
| 341 |
# 1. filter out ignored programs, pids, units, and files |
| 342 |
# 2. Group processes by program (name of executable) or unit |
| 343 |
n=0 # number of non-ignored processes |
| 344 |
programs=collections.defaultdict(list) # program_name => [processes] |
| 345 |
units_that_need_restart={} # unit_name => [processes] |
| 346 |
|
| 347 |
for process in using_deleted: |
| 348 |
if is_ignored(process.program,exclude,"program:",onlyPackageFiles,cache): |
| 349 |
show_ignore(f"program {process.program}", |
| 350 |
"program", process, verbose, machineOutput) |
| 351 |
elif is_ignored(str(process.pid),exclude,"pid:",False,cache): |
| 352 |
show_ignore(f"PID {process.pid}", |
| 353 |
"pid", process, verbose, machineOutput) |
| 354 |
elif process.systemd_unit and is_ignored(process.systemd_unit,exclude,"unit:",False,cache): |
| 355 |
# 4th arg to is_ignore must be False, as some units, eg: apache2, are generated from initscripts |
| 356 |
show_ignore(f"process started by unit {process.systemd_unit}", |
| 357 |
f"unit\t{process.systemd_unit}", |
| 358 |
process, verbose, machineOutput) |
| 359 |
else: |
| 360 |
interesting_files=[] |
| 361 |
for f in process.files: |
| 362 |
if is_ignored(f, exclude,"file:",onlyPackageFiles,cache): |
| 363 |
show_ignore(f"deleted file {f}", |
| 364 |
f"file\t{f}", |
| 365 |
process, verbose, machineOutput) |
| 366 |
else: |
| 367 |
interesting_files.append(f) |
| 368 |
|
| 369 |
if len(interesting_files)>0: |
| 370 |
n=n+1 |
| 371 |
process.files=sorted(interesting_files) |
| 372 |
|
| 373 |
unit=process.systemd_unit |
| 374 |
if unit: |
| 375 |
if verbose: |
| 376 |
if machineOutput: |
| 377 |
print(f"from_unit\t{process}\t{unit}") |
| 378 |
else: |
| 379 |
print(f"{process} was started by systemd unit: {unit}") |
| 380 |
if units_that_need_restart.get(unit): |
| 381 |
units_that_need_restart[unit].processes.append(process) |
| 382 |
else: |
| 383 |
u=SystemdUnit(unit) |
| 384 |
if u.restart_command: |
| 385 |
units_that_need_restart[unit]=u |
| 386 |
units_that_need_restart[unit].processes.append(process) |
| 387 |
else: |
| 388 |
if DEBUG: print(f"{process} was started by systemd. but we do not know how to restart it)") |
| 389 |
programs[process.program].append(process) |
| 390 |
else: |
| 391 |
programs[process.program].append(process) |
| 392 |
else: |
| 393 |
# all files have been excluded, so hide the process |
| 394 |
show_ignore("all files from","all_files",process,verbose,machineOutput) |
| 395 |
|
| 396 |
# list of SystemdUnit |
| 397 |
systemdUnits=sorted(units_that_need_restart.values(),key=lambda p:p.cgroup_path) |
| 398 |
|
| 399 |
|
| 400 |
# Group programs by package. programs is modified so that anything |
| 401 |
# packaged is deleted - anything remaining in programs is |
| 402 |
# unpackaged. |
| 403 |
packages = group_by_package(programs) |
| 404 |
|
| 405 |
if verbose: |
| 406 |
for packagename,package in packages.items(): |
| 407 |
for process in package.processes: |
| 408 |
if machineOutput: |
| 409 |
print(f"from_package\t{process}\t{packagename}") |
| 410 |
else: |
| 411 |
print(f"{process} is part of package: {packagename}") |
| 412 |
|
| 413 |
for program_name,processes in programs.items(): |
| 414 |
if verbose: |
| 415 |
if machineOutput: |
| 416 |
print(f"unpackaged\t{process}") |
| 417 |
else: |
| 418 |
print(f"{process} is not part of any package or systemd unit") |
| 419 |
name=f"Unpackaged: {os.path.basename(program_name)}" # todo - this does conflate /bin/sh and /local/bin/sh |
| 420 |
packages.setdefault(name,Package(name,is_fake=True)) |
| 421 |
packages[name].processes.extend(processes) |
| 422 |
|
| 423 |
sys.stdout.flush() |
| 424 |
|
| 425 |
# Remove ignored packages - modify n accordingly |
| 426 |
interesting_packages=[] |
| 427 |
for p in packages: |
| 428 |
if is_ignored(p,exclude,"package:",False,cache): |
| 429 |
num_ignored=len(packages[p].processes) |
| 430 |
n=n-num_ignored |
| 431 |
show_ignore(f"all ({num_ignored}) programs from package", f"package\t{num_ignored}", p, |
| 432 |
verbose,machineOutput) |
| 433 |
else: |
| 434 |
interesting_packages.append(packages[p]) |
| 435 |
|
| 436 |
packages=sorted(interesting_packages,key=lambda p:p.name) |
| 437 |
|
| 438 |
# check if reboot needed |
| 439 |
flag="/run/reboot-required" |
| 440 |
pkgs=f"{flag}.pkgs" |
| 441 |
if os.path.exists(pkgs): |
| 442 |
reboot_needed=True |
| 443 |
if machineOutput: |
| 444 |
msg=["REBOOT_NEEDED: Yes"] |
| 445 |
else: |
| 446 |
msg=["The system needs rebooting"] |
| 447 |
|
| 448 |
if not terseOutput: |
| 449 |
try: |
| 450 |
with open(pkgs,"r") as f: |
| 451 |
if machineOutput: |
| 452 |
msg.extend([f"REQUESTED_REBOOT: {package.strip()}" for package in f.readlines()]) |
| 453 |
else: |
| 454 |
msg[0]+=". The following packages have indicated that a reboot is required:" |
| 455 |
msg.extend([f"\t{package.strip()}" for package in f.readlines()]) |
| 456 |
msg.append("") |
| 457 |
except OSError as e: |
| 458 |
sys.stderr.write(f"ERROR: File exists but is unreadable: {pkgs}: {e}\n") |
| 459 |
sys.exit(3) |
| 460 |
elif os.path.exists(flag): |
| 461 |
reboot_needed=True |
| 462 |
if machineOutput: |
| 463 |
msg=[f"REBOOT_NEEDED: Yes; MISSING: {pkgs}"] |
| 464 |
else: |
| 465 |
msg=[f"The system needs rebooting: ({flag} exists but there is no {pkgs}, so we do not know why)"] |
| 466 |
else: |
| 467 |
reboot_needed=False |
| 468 |
msg=[] |
| 469 |
|
| 470 |
if machineOutput: |
| 471 |
msg.append(f"RESTART_NEEDED: {n}") |
| 472 |
else: |
| 473 |
msg.append(f"{n} non-ignored program(s) or unit(s) need restarting (see checkrestart(8))") |
| 474 |
sys.stdout.flush() |
| 475 |
|
| 476 |
|
| 477 |
if terseOutput: |
| 478 |
print('; '.join(msg)) |
| 479 |
else: |
| 480 |
print('\n'.join(msg)) |
| 481 |
|
| 482 |
if n==0 and not reboot_needed: |
| 483 |
sys.exit(0) |
| 484 |
|
| 485 |
if terseOutput: |
| 486 |
# use Nagios exit codes: 0 OK, 1 warning, (2 critical, 3 unknown) |
| 487 |
sys.exit(1) |
| 488 |
|
| 489 |
# else, we are not in terse mode (no -t) and so have more output to produce |
| 490 |
systemdCommands=[] # [String] - commands to do the restart of units |
| 491 |
for s in systemdUnits: |
| 492 |
if is_ignored(s.name,suggestions,"dangerous-unit:",False,cache): |
| 493 |
prefix=caution |
| 494 |
else: |
| 495 |
prefix="" |
| 496 |
systemdCommands.append(f"{prefix}{s.restart_command}") |
| 497 |
|
| 498 |
if not using_cgroups2: |
| 499 |
search_packages_for_suggestions(packages,using_systemd) |
| 500 |
|
| 501 |
restartWithSystemd=[] # [Package] - suggested units to restart |
| 502 |
restartWithInitscript=[] # [Package] - suggested initscripts to restart |
| 503 |
initCommands=[] # [String] - suggested initscript commands |
| 504 |
|
| 505 |
restartOther=[] # [Package] - no unit/initscript |
| 506 |
|
| 507 |
for package in packages: |
| 508 |
done=False |
| 509 |
if len(package.systemdservice)>0: |
| 510 |
if DEBUG: print(f"Maybe suggesting restart via systemd for package {package.name}") |
| 511 |
for s in sorted(package.systemdservice): |
| 512 |
if is_ignored(s,suggestions,"suggested-unit:",False,cache): |
| 513 |
if verbose: |
| 514 |
if machineOutput: |
| 515 |
print(f"not_suggesting_unit\t{s}\t{package.name}") |
| 516 |
else: |
| 517 |
print(f"Not suggesting unit {s} (from package: {package.name})") |
| 518 |
else: |
| 519 |
if not done: |
| 520 |
restartWithSystemd.append(package) |
| 521 |
done=True |
| 522 |
|
| 523 |
if is_ignored(s,suggestions,"dangerous-unit:",False,cache): |
| 524 |
prefix=caution |
| 525 |
else: |
| 526 |
prefix="" |
| 527 |
systemdCommands.append(f"{prefix}systemctl try-restart {s} # suggested - from package:{package.name}") |
| 528 |
|
| 529 |
if not done: |
| 530 |
if verbose and not machineOutput: |
| 531 |
print(f"All units that might restart programs in package {package.name} have been excluded") |
| 532 |
if (not done) and len(package.initscripts) > 0: |
| 533 |
if DEBUG: print(f"Maybe suggesting restart via initscript for package {package.name}") |
| 534 |
for s in sorted(package.initscripts): |
| 535 |
if is_ignored(s,suggestions,"suggested-initscript:",False,cache): |
| 536 |
if verbose: |
| 537 |
if machineOutput: |
| 538 |
print(f"not_suggesting_initscript\t{s}\t{package.name}") |
| 539 |
else: |
| 540 |
print(f"Not suggesting initscript {s} (from package: {package.name})") |
| 541 |
if not done: |
| 542 |
restartWithInitscript.append(package) |
| 543 |
done=True |
| 544 |
|
| 545 |
if is_ignored(s,suggestions,"dangerous-initscript:",False,cache): |
| 546 |
prefix=caution |
| 547 |
else: |
| 548 |
prefix="" |
| 549 |
initCommands.append(f"{prefix}service {s} restart # suggested - from package:{package.name}") |
| 550 |
if not done: |
| 551 |
if verbose and not machineOutput: |
| 552 |
print(f"All initscripts that might restart programs in package {package.name} have been excluded") |
| 553 |
|
| 554 |
if not done: |
| 555 |
restartOther.append(package) |
| 556 |
|
| 557 |
|
| 558 |
|
| 559 |
if not machineOutput: |
| 560 |
show_processes("The following systemd units started programmes that are using deleted files:",systemdUnits,showfiles) |
| 561 |
show_processes("The following packages provided processes that are using deleted files and might be restartable via systemd:", |
| 562 |
restartWithSystemd,showfiles) |
| 563 |
show_processes("The following packages provided processes that are using deleted files and might be restarted by an initscript:", |
| 564 |
restartWithInitscript,showfiles) |
| 565 |
show_processes("The following are using deleted files but there is no suggested way to restart them:", |
| 566 |
restartOther,showfiles) |
| 567 |
|
| 568 |
if len(systemdCommands)>0: |
| 569 |
print("\n\nSystemd commands:") |
| 570 |
print('\n'.join(systemdCommands)) |
| 571 |
print() |
| 572 |
|
| 573 |
if len(initCommands)>0: |
| 574 |
print("\n\nInit script commands:") |
| 575 |
print('\n'.join(initCommands)) |
| 576 |
print() |
| 577 |
else: |
| 578 |
show_processes_Machine("SYSTEMD", |
| 579 |
systemdUnits,showfiles) |
| 580 |
|
| 581 |
show_processes_Machine("PACKAGE_SYSTEMD", |
| 582 |
restartWithSystemd,showfiles) |
| 583 |
show_processes_Machine("SERVICE", |
| 584 |
restartWithInitscript,showfiles) |
| 585 |
show_processes_Machine("OTHER",restartOther,showfiles) |
| 586 |
for c in systemdCommands: |
| 587 |
print(f"SYSTEMD_COMMAND\t{c}") |
| 588 |
for c in initCommands: |
| 589 |
print(f"SERVICE_COMMAND\t{c}") |
| 590 |
|
| 591 |
# use Nagios exit codes: 0 OK, 1 warning, (2 critical, 3 unknown) |
| 592 |
sys.exit(1) |
| 593 |
# end of main() |
| 594 |
|
| 595 |
def show_processes(text,packages,showfiles): |
| 596 |
if len(packages)>0: |
| 597 |
print() |
| 598 |
print(text) |
| 599 |
for package in packages: |
| 600 |
print(f"{package.name}:") |
| 601 |
for process in sorted(package.processes,key=lambda p:[p.program,p.pid]): |
| 602 |
if showfiles: |
| 603 |
print(f"\t{process} is using the following deleted files:") |
| 604 |
for f in process.files: |
| 605 |
print(f"\t\t{f}") |
| 606 |
print() |
| 607 |
else: |
| 608 |
print(f"\t{process}") |
| 609 |
print() |
| 610 |
|
| 611 |
def show_processes_Machine(what,packages,showfiles): |
| 612 |
for package in packages: |
| 613 |
for process in sorted(package.processes,key=lambda p:[p.program,p.pid]): |
| 614 |
print(f"{what}\t{package.name}\t{repr(process)}") |
| 615 |
if showfiles: |
| 616 |
for f in process.files: |
| 617 |
print(f"file\t{f}\t{repr(process)}") |
| 618 |
|
| 619 |
def dpkg_query(what,args,clean): |
| 620 |
"""run dpkg-query what args |
| 621 |
if clean: Working around lack of support for usrmerge |
| 622 |
print stderr and yield each line to caller |
| 623 |
""" |
| 624 |
dpkgQuery = ["dpkg-query", what] |
| 625 |
if clean: |
| 626 |
dpkgQuery.extend(cleanPathsForDpkgSearch(args)) |
| 627 |
else: |
| 628 |
dpkgQuery.extend(args) |
| 629 |
if DEBUG: |
| 630 |
print(f"Running: {repr(dpkgQuery)}") |
| 631 |
dpkgProc = subprocess.run(dpkgQuery, |
| 632 |
capture_output=True, |
| 633 |
encoding="utf-8", |
| 634 |
errors="ignore", |
| 635 |
env = lc_all_c_env) |
| 636 |
if DEBUG: |
| 637 |
for line in dpkgProc.stderr.splitlines(): |
| 638 |
print(f"dpkg-query: stderr: {repr(line)}") |
| 639 |
|
| 640 |
for line in dpkgProc.stdout.splitlines(): |
| 641 |
if DEBUG: print(f"dpkg-query: {repr(line)}") |
| 642 |
yield(line) |
| 643 |
|
| 644 |
def group_by_package(programs): |
| 645 |
"""Group programs by debian package |
| 646 |
|
| 647 |
This function returns a dict of name=>Package where the package |
| 648 |
ships the programe. Each Package's .processes is set to the |
| 649 |
processes that were in programs. Programs is modified to delete |
| 650 |
anything found - so any unpackaged programs will be left in programs |
| 651 |
""" |
| 652 |
packages={} # program.name=>Package |
| 653 |
diverted = None |
| 654 |
|
| 655 |
if len(programs)==0: |
| 656 |
return packages |
| 657 |
|
| 658 |
if DEBUG: |
| 659 |
print(f"Looking for packages providing: {repr(programs.keys())}") |
| 660 |
for line in dpkg_query("--search",programs.keys(),clean=True): |
| 661 |
if line.startswith('local diversion'): |
| 662 |
continue |
| 663 |
if not ':' in line: |
| 664 |
continue |
| 665 |
|
| 666 |
m = re.search(r"^diversion by (\S+) (from|to): (.*)$", line) |
| 667 |
if m: |
| 668 |
if m.group(2) == 'from': |
| 669 |
diverted = m.group(3) |
| 670 |
continue |
| 671 |
if not diverted: |
| 672 |
raise Exception(f"checkrestart: Internal error while handling diversion in line {repr(line)}") |
| 673 |
packagename, program = m.group(1), diverted |
| 674 |
else: |
| 675 |
packagename, program = line.split(': ') |
| 676 |
if program == diverted: |
| 677 |
# dpkg-query (sometimes) prints a summary line after the |
| 678 |
# two "diversion by" lines naming both |
| 679 |
# packages involved in the diversion, eg |
| 680 |
# "mutt-patched, mutt: /usr/bin/mutt" |
| 681 |
# (another example is help.txt from vim-tiny and vim-runtime) |
| 682 |
continue |
| 683 |
|
| 684 |
if not programs.get(program): |
| 685 |
# Some complications due to usrmerge: |
| 686 |
# eg: bash ships '/bin/bash' but scripts may run as '/usr/bin/bash' |
| 687 |
# eg: python3 ships '/usr/bin/python3' but scripts may run as '/bin/python3' |
| 688 |
added_links=add_usrmerge_symlinks(program) |
| 689 |
if programs.get(added_links): |
| 690 |
# /usr/bin/prog packaged but /bin/prog running |
| 691 |
if DEBUG: print(f"program found after symlinks added: packaged: {program} -> running: {added_links}") |
| 692 |
program=added_links |
| 693 |
else: |
| 694 |
removed_links=remove_usrmerge_symlinks(program) |
| 695 |
if programs.get(removed_links): |
| 696 |
# /bin/prog packaged but /use/bin/prog running |
| 697 |
if DEBUG: print(f"program found after symlinks removed: packaged: {program} -> running: {removed_links}") |
| 698 |
program=removed_links |
| 699 |
|
| 700 |
# The next 'if' is needed in rare circumstances: Suppose a |
| 701 |
# container shares its /proc with its host system and that |
| 702 |
# the host is usrmerged and the container is not: a |
| 703 |
# checkrestart in the container could detect /usr/bin/prog |
| 704 |
# running outside, But the key in programs could be |
| 705 |
# /bin/prog if that is what is packaged (The best outcome |
| 706 |
# is to consider such a process as unpackaged, hence the |
| 707 |
# 'if' below) |
| 708 |
if programs.get(program): |
| 709 |
if DEBUG: print(f"program {program} found in package: {packagename}") |
| 710 |
packages.setdefault(packagename,Package(packagename)) |
| 711 |
packages[packagename].processes.extend(programs[program]) |
| 712 |
del programs[program] |
| 713 |
|
| 714 |
return packages |
| 715 |
|
| 716 |
|
| 717 |
def search_packages_for_suggestions(packages,using_systemd): |
| 718 |
""" Look for systemd unit and initscript in packages. Only used if not using cgroups v2""" |
| 719 |
for package in packages: |
| 720 |
if package.is_fake: |
| 721 |
continue |
| 722 |
|
| 723 |
for path in dpkg_query("--listfiles",[package.name], |
| 724 |
clean=False): |
| 725 |
# If running on a systemd system, extract the systemd's service files from the package |
| 726 |
if using_systemd and (path.startswith('/lib/systemd/system/') or path.startswith('/usr/lib/systemd/system/')) and path.endswith('.service') and path.find('.wants') == -1: |
| 727 |
if path.endswith('@.service'): |
| 728 |
continue |
| 729 |
unit_name=os.path.basename(path) |
| 730 |
# Previous versions ignored 'oneshot' units, but you can restart a oneshot |
| 731 |
# unit_type=subprocess.run(["systemctl","show",unit_name,"-P","Type"]).stdout.strip() |
| 732 |
#if unit_type != "oneshot": package.systemdservice.add(unit_name) |
| 733 |
if DEBUG: print(f"Found suggested systemd unit {path} for {package.name}") |
| 734 |
package.systemdservice.add(unit_name) |
| 735 |
|
| 736 |
# find initscripts |
| 737 |
elif path.startswith('/etc/init.d/'): |
| 738 |
if DEBUG: print(f"Found suggested init script {path} for {package.name}") |
| 739 |
package.initscripts.add(path[12:]) |
| 740 |
|
| 741 |
# Alternatively, find init.d scripts that match the process name |
| 742 |
if len(package.initscripts) == 0 and len(package.systemdservice) == 0: |
| 743 |
for process in package.processes: |
| 744 |
path = os.path.basename(process.program) |
| 745 |
if os.path.exists(f"/etc/init.d/{path}"): |
| 746 |
if DEBUG: print(f"Found suggested init script {path} for {package.name} using name of process {process.program}") |
| 747 |
package.initscripts.add(path) |
| 748 |
|
| 749 |
|
| 750 |
def lsoffilescheck(using_cgroups2): |
| 751 |
"""Use lsof(1) to find processes using deleted files |
| 752 |
returns: [Process] where each entry is using a deleted file.""" |
| 753 |
processes = {} |
| 754 |
|
| 755 |
# not sure if this is needed on modern kernels? |
| 756 |
path_inode_regexp=re.compile(r"\(path inode=[0-9]+\)$") |
| 757 |
|
| 758 |
# -X ~ exclude network files |
| 759 |
# -L ~ include all link counts |
| 760 |
# -F pfkn0 ~ show fields n (filename), f(descriptor), p(pid), k(no. links), 0~NUL-separated |
| 761 |
# -w ~ hide warnings (fix #99150) |
| 762 |
for line in subprocess.run(['lsof', '+XL', '-F', 'pfkn0', '-w'], |
| 763 |
capture_output=True, |
| 764 |
encoding="utf-8", |
| 765 |
errors="ignore", |
| 766 |
env = lc_all_c_env).stdout.splitlines(): |
| 767 |
line=line[:-1] # strip trailing NUL |
| 768 |
fieldset=line[0] |
| 769 |
if fieldset=="p": |
| 770 |
# Info about process: p<PID> |
| 771 |
pid=int(line[1:]) |
| 772 |
process=processes.get(pid) # Process or None |
| 773 |
if not process: |
| 774 |
if DEBUG: print(f"Creating Process object for PID {pid}") |
| 775 |
process=Process(pid,using_cgroups2) |
| 776 |
processes[pid]=process |
| 777 |
else: |
| 778 |
# lsof can produce multiple fieldsets for the same pid |
| 779 |
# - possibly one per task (thread) (The '-K i' option |
| 780 |
# to lsof may prevent this, but unclear what that |
| 781 |
# hides) |
| 782 |
if DEBUG: print(f"lsof produced duplicate data for PID {pid} - merging") |
| 783 |
elif fieldset=="f": |
| 784 |
# Info about a file used by process: f<fd><NUL>k<links><NUL>n<PATH><NUL> |
| 785 |
fd="" |
| 786 |
filename="" |
| 787 |
links=-1 |
| 788 |
for f in line.split('\0'): |
| 789 |
if f.startswith("f"): |
| 790 |
fd=f[1:] |
| 791 |
elif f.startswith("k"): |
| 792 |
try: |
| 793 |
links=int(f[1:]) |
| 794 |
except ValueError: |
| 795 |
links=-1 |
| 796 |
elif f.startswith('n'): |
| 797 |
# n/path/to/file or n[signalfd] etc |
| 798 |
filename=f[1:] |
| 799 |
# If the name starts with (deleted) put it in the end of the |
| 800 |
# file name, this is used to workaround different behaviour in |
| 801 |
# OpenVZ systems, see |
| 802 |
# https://bugzilla.openvz.org/show_bug.cgi?id=2932 |
| 803 |
if filename.startswith('(deleted)'): |
| 804 |
filename = filename[9:] + ' (deleted)' |
| 805 |
elif filename.startswith(' (deleted)'): |
| 806 |
filename = name[10:] + ' (deleted)' |
| 807 |
else: |
| 808 |
print(f"Unknown field {f} from lsof in pid {process.pid}: {repr(line)}") |
| 809 |
if filename.startswith('/'): |
| 810 |
if filename.endswith(" (deleted)"): |
| 811 |
filename=filename[:-10] |
| 812 |
if DEBUG: print(f"lsof reported that PID {process.pid} is using deleted file {filename}; lsof data was: {repr(line)}") |
| 813 |
process.files.add(filename) |
| 814 |
elif path_inode_regexp.search(filename): |
| 815 |
if DEBUG: print(f"lsof reported that PID {process.pid} is using 'path inode' file {filename}; lsof data was: {repr(line)}") |
| 816 |
filename=path_inode_regexp.sub("",filename) |
| 817 |
process.files.add(filename) |
| 818 |
elif links==0 or fd=="DEL": |
| 819 |
if DEBUG: print(f"lsof reported that PID {process.pid} is using deleted file {filename} (detected via fd={fd},links={links}); lsof data was: {repr(line)}") |
| 820 |
process.files.add(filename) |
| 821 |
else: |
| 822 |
print(f"Unknown fieldset from lsof: {repr(line)}") |
| 823 |
|
| 824 |
return [process for process in processes.values() if len(process.files)>0] |
| 825 |
|
| 826 |
def procfilescheck(ignoredpids,using_cgroups2): |
| 827 |
"""Use the /proc file system to determine processes that are using deleted files. |
| 828 |
Any pid is ignoredpids (list of int) is silently ignored |
| 829 |
(This sometimes finds fewer deleted files than lsoffilescheck)""" |
| 830 |
processes = [] |
| 831 |
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()] |
| 832 |
|
| 833 |
for pid in pids: |
| 834 |
if pid in ignoredpids: |
| 835 |
continue |
| 836 |
|
| 837 |
# Get the list of open files for this process from /proc We |
| 838 |
# ignore failures because links may disappear while we run |
| 839 |
foundfiles = set() |
| 840 |
try: |
| 841 |
for fd in os.listdir('/proc/' + pid + '/fd'): |
| 842 |
if os.path.islink('/proc/' + pid + '/fd/' + fd): |
| 843 |
fname = os.readlink('/proc/' + pid + '/fd/' + fd) |
| 844 |
if re.compile(r"\s\(deleted\)$").search(fname): |
| 845 |
if DEBUG: print(f"/proc/pid/fd shows PID {pid} using deleted file {f}") |
| 846 |
foundfiles.add(fname[:-10]) |
| 847 |
except OSError: |
| 848 |
continue |
| 849 |
|
| 850 |
# Get the list of memory mapped files using pmap |
| 851 |
for output in subprocess.run(['pmap', '--show-path', pid], |
| 852 |
capture_output=True, |
| 853 |
encoding="utf-8", |
| 854 |
errors="ignore", |
| 855 |
env = lc_all_c_env).stdout.splitlines(): |
| 856 |
data = re.split(r"\s+", output, 3) |
| 857 |
if len(data) == 4: |
| 858 |
f = data[3] |
| 859 |
if re.compile(r"\s\(deleted\)$").search(f): |
| 860 |
if DEBUG: print(f"pmap reported PID {pid} using deleted file {repr(f)}") |
| 861 |
foundfiles.add(f[:-10]) |
| 862 |
|
| 863 |
if len(foundfiles)>0: |
| 864 |
process=Process(int(pid),using_cgroups2) |
| 865 |
process.files = foundfiles |
| 866 |
processes.append(process) |
| 867 |
|
| 868 |
return processes |
| 869 |
|
| 870 |
|
| 871 |
def ispackagedFile(f): |
| 872 |
"""Check if file f (path) is part of a debian package |
| 873 |
# Returns: |
| 874 |
# - False - file does not exist or is not part of a debian package (according to dpkg-query --search) |
| 875 |
# - True - file is found in an operating system package |
| 876 |
""" |
| 877 |
file_in_package = False |
| 878 |
file_regexp = False |
| 879 |
soname_regexp=re.compile(r"\.so[\d.]+$") |
| 880 |
if DEBUG: print(f"Checking if file {f} belongs to any package") |
| 881 |
# First check if the file exists |
| 882 |
if not os.path.exists(f): |
| 883 |
if f.startswith('/lib/') or f.startswith('/usr/lib/'): |
| 884 |
# A library that does not exist may have been upgraded to a new soname |
| 885 |
if DEBUG: print(f"{f} is a deleted library") |
| 886 |
f = soname_regexp.sub(".so.*", f) |
| 887 |
file_regexp = True |
| 888 |
else: |
| 889 |
if DEBUG: |
| 890 |
print(f"File {f} is deleted but is not a library: assuming it is not part of a package") |
| 891 |
return False |
| 892 |
|
| 893 |
# If it exists, run dpkg-query |
| 894 |
file_in_package = False |
| 895 |
for line in dpkg_query("--search", [f],clean=True): |
| 896 |
if line.endswith(f": {f}") or (file_regexp and re.search(f": {f}$", line)): |
| 897 |
package = line.split(":")[0] |
| 898 |
file_in_package = True |
| 899 |
break |
| 900 |
|
| 901 |
if DEBUG: |
| 902 |
if file_in_package: |
| 903 |
print(f"File {f} belongs to package: {package}") |
| 904 |
else: |
| 905 |
print(f"File {f} does not belong to any package") |
| 906 |
|
| 907 |
return file_in_package |
| 908 |
|
| 909 |
def is_ignored(f, ignorelist,key,onlyPackageFiles,cached): |
| 910 |
"""Decide if a f should be reported (ie not matched by anything in ignorelist.) |
| 911 |
if '-p' then only report deleted files from packages |
| 912 |
Returns: |
| 913 |
- True if f is in ignorelist (result is cached in the last argument) |
| 914 |
- False otherwise.""" |
| 915 |
cache_hit=cached[key].get(f) |
| 916 |
if cache_hit is not None: |
| 917 |
if DEBUG: print(f"Cache hit: {key} {f}: ignored={cache_hit}") |
| 918 |
return cache_hit |
| 919 |
|
| 920 |
for regexp in ignorelist[key]: |
| 921 |
if regexp.search(f): |
| 922 |
if DEBUG: print(f"Exclusion found for {key} {f} using: {regexp}") |
| 923 |
cached[key][f]=True |
| 924 |
return True |
| 925 |
|
| 926 |
if onlyPackageFiles: |
| 927 |
cached[key][f]=not ispackagedFile(f) |
| 928 |
else: |
| 929 |
cached[key][f]=False |
| 930 |
return cached[key][f] |
| 931 |
|
| 932 |
def cleanPathsForDpkgSearch(paths): |
| 933 |
"""Work around for usrmerged systems: dpkg-query --search /usr/bin/bash |
| 934 |
does not work, because the bash package only installed /bin/bash (if |
| 935 |
dpkg-query is ever fixed then this can be deleted""" |
| 936 |
result=set(paths) |
| 937 |
for p in paths: |
| 938 |
result.add(remove_usrmerge_symlinks(p)) |
| 939 |
result.add(add_usrmerge_symlinks(p)) |
| 940 |
return result |
| 941 |
|
| 942 |
def remove_usrmerge_symlinks(path): |
| 943 |
"""/usr/bin --> /bin and /usr/lib -> /lib etc |
| 944 |
- needed on usrmerged systems where |
| 945 |
dpkg-query does not find the path if it does not match the exact |
| 946 |
name shipped in the package (ie all of Debian) |
| 947 |
- see /usr/lib/usrmerge/convert-usrmerge for the list of |
| 948 |
directories involved""" |
| 949 |
bin_regexp=re.compile(r"^/usr/(s)?bin/") |
| 950 |
lib_regexp=re.compile(r"^/usr/lib(64|32|o32|x32)?/") |
| 951 |
return bin_regexp.sub(r'/\1bin/', lib_regexp.sub(r'/lib\1/',path)) |
| 952 |
|
| 953 |
def add_usrmerge_symlinks(path): |
| 954 |
"""Reverses remove_usrmerge_symlinks""" |
| 955 |
bin_regexp=re.compile(r"^/(s)?bin/") |
| 956 |
lib_regexp=re.compile(r"^/lib(64|32|o32|x32)?/") |
| 957 |
return bin_regexp.sub(r"/usr/\1bin/", lib_regexp.sub(r"/usr/lib\1/",path)) |
| 958 |
|
| 959 |
|
| 960 |
def show_ignore(description,what,process,verbose,machineOutput): |
| 961 |
if verbose: |
| 962 |
if machineOutput: |
| 963 |
print(f"ignored_{what}\t{repr(process)}") |
| 964 |
else: |
| 965 |
print(f"Ignoring {description}: {process}") |
| 966 |
|
| 967 |
class Process: |
| 968 |
"""A Process represents a running process""" |
| 969 |
|
| 970 |
|
| 971 |
# if /usr is a symlink (eg: /usr -> /srv/usr), then we want to replace '/srv/usr/bin/python3' |
| 972 |
# with /bin/python3 so that we can find which package it is in. |
| 973 |
usrsymlinkd = os.path.islink('/usr') |
| 974 |
if usrsymlinkd: |
| 975 |
usr_target = os.path.realpath('/usr') |
| 976 |
|
| 977 |
def __init__(self, pid,using_cgroups2): |
| 978 |
""" |
| 979 |
Process |
| 980 |
# If using_cgroups2 then we use |
| 981 |
# cgroups to identify which unit to restart |
| 982 |
""" |
| 983 |
|
| 984 |
self.pid = pid |
| 985 |
self.files = set() |
| 986 |
self._exe = None # /proc/pid/exe |
| 987 |
self.prefix="" # "" or Deleted |
| 988 |
self.what="Program" # Can be changed to "Script", depending on self.cmdline |
| 989 |
self._program = None # cleaned version of self._exe |
| 990 |
self._cmdline=None # /proc/pid/cmdline |
| 991 |
|
| 992 |
self._systemd_unit=None # name of unit that started the process (or False) |
| 993 |
self._using_cgroups2=using_cgroups2 |
| 994 |
|
| 995 |
@property |
| 996 |
def program(self): |
| 997 |
"""If the program name (_program) has not been set, infer it from /proc/pid/exe. |
| 998 |
If the program is a script, use the first executable non-option argument in /proc/pid/cmdline instead""" |
| 999 |
if self._program is None: |
| 1000 |
try: |
| 1001 |
self._program = os.readlink(f"/proc/{self.pid}/exe") |
| 1002 |
except OSError as e: |
| 1003 |
if e.errno != errno.ENOENT: |
| 1004 |
# eg, main thread exited (see proc(5)) |
| 1005 |
sys.stderr.write(f"WARNING: Failed to read /proc/{self.pid}/exe\n") |
| 1006 |
self._program=f"<unknown: PID: {self.pid}>" |
| 1007 |
else: |
| 1008 |
# some other error, possibly indicating it closed |
| 1009 |
self._program=f"<Deleted: PID: {self.pid}>" |
| 1010 |
|
| 1011 |
# /proc/pid/exe has all kinds of junk in it sometimes |
| 1012 |
null = self._program.find('\0') |
| 1013 |
if null != -1: |
| 1014 |
self._program = self._program[:null] |
| 1015 |
self._exe=self.program |
| 1016 |
|
| 1017 |
# clean self._program |
| 1018 |
if Process.usrsymlinkd and self._program.startswith(Process.usr_target): |
| 1019 |
# if /usr -> /srv/usr we want to report '/usr/bin/python3' not '/srv/usr/bin/python3') |
| 1020 |
if DEBUG: print(f"Rewriting path for {self._program} due to symlink /usr -> {Process.usr_target}") |
| 1021 |
self._program = re.sub(Process.usr_target,'^/usr',self._program) |
| 1022 |
|
| 1023 |
self._program,program_deleted=re.subn(r"( \(deleted\)|.dpkg-new)\s*$",'',self._program) |
| 1024 |
if program_deleted==1: |
| 1025 |
if DEBUG: print(f"Program is deleted: {self._program}") |
| 1026 |
# self._program should already be in self.files |
| 1027 |
self.prefix="Deleted" |
| 1028 |
else: |
| 1029 |
self.prefix="" |
| 1030 |
|
| 1031 |
if re.search(r"^(/usr)?/bin/(perl|python|ruby|tclsh|bash|dash)", self._program): |
| 1032 |
if DEBUG: print(f"program {self._program} (PID {self.pid}) is a script") |
| 1033 |
|
| 1034 |
# we are a script run by an interpreter such as |
| 1035 |
# perl/python/ruby/tclsh, we want to use the script's name |
| 1036 |
|
| 1037 |
# Spamd adds a blank to $0, see |
| 1038 |
# https://bugzilla.redhat.com/show_bug.cgi?id=755644 |
| 1039 |
#(...which seems to be closed so is this even needed any more?) |
| 1040 |
m = re.search(r"^/usr/sbin/spamd |^spamd ", self.cmdline[0]) |
| 1041 |
if m: |
| 1042 |
self._program = "/usr/sbin/spamd" |
| 1043 |
else: |
| 1044 |
# Skip first entry (the interpreter) |
| 1045 |
for arg in self.cmdline[1:]: |
| 1046 |
# Ignore any options following the interpreter, e.g. python's -O (see #715000) |
| 1047 |
if DEBUG: print(f"Found option {repr(arg)} to {self._program}") |
| 1048 |
if not arg.startswith("-"): |
| 1049 |
arg=shutil.which(arg) |
| 1050 |
if arg is not None: |
| 1051 |
# arg is the name of an executable script (BUG: does not detect deleted scripts) |
| 1052 |
if DEBUG: print(f"PID {self.pid} (a {self._program} script) treated as if named: {arg}") |
| 1053 |
self._program = arg |
| 1054 |
self.what="Script" |
| 1055 |
break |
| 1056 |
else: |
| 1057 |
self.what="Program" |
| 1058 |
return self._program |
| 1059 |
|
| 1060 |
@property |
| 1061 |
def cmdline(self): |
| 1062 |
"""Return an array containing the program and any arguments. Uses |
| 1063 |
/prpc/pid/cmdline so we are trusting the process to set this correctly. see proc(5). Never |
| 1064 |
call self.program in this method or you could get an infinite loop.""" |
| 1065 |
if self._cmdline is None: |
| 1066 |
try: |
| 1067 |
with open(f"/proc/{self.pid}/cmdline", 'r') as cmdline: |
| 1068 |
# cmdline is NULL-separated, with a trailing NULL per proc(5) |
| 1069 |
data=cmdline.read().split('\0') |
| 1070 |
if not data[-1]: data.pop() |
| 1071 |
except OSError: |
| 1072 |
data=[] |
| 1073 |
if len(data)==0: |
| 1074 |
data=[f"Unknown (PID {self.pid})"] |
| 1075 |
self._cmdline=data |
| 1076 |
if DEBUG: print(f"Set cmdline to: {self._cmdline} for PID:{self.pid}") |
| 1077 |
return self._cmdline |
| 1078 |
|
| 1079 |
def __str__(self): |
| 1080 |
"""Human-readable representation |
| 1081 |
Shows: |
| 1082 |
[Deleted] {Program|Script} PATH (PID, [exe], [command line]) |
| 1083 |
|
| 1084 |
exe is hidden if it matches path |
| 1085 |
command line is hidden if it is the same as PATH |
| 1086 |
""" |
| 1087 |
# nb: calling self.programe sets self._exe |
| 1088 |
if self.program != self._exe: |
| 1089 |
exe=f", EXE: '{self._exe}'" |
| 1090 |
else: |
| 1091 |
exe="" |
| 1092 |
if len(self.cmdline)!=1 or self.program!=self.cmdline[0]: |
| 1093 |
args=f", CMDLINE: '{' '.join(self.cmdline)}'" |
| 1094 |
else: |
| 1095 |
args="" |
| 1096 |
if self.prefix!="": # "Deleted" or "" |
| 1097 |
sep=" " |
| 1098 |
else: sep="" |
| 1099 |
return f"{self.prefix}{sep}{self.what} {self.program} (PID: {self.pid}{exe}{args})" |
| 1100 |
|
| 1101 |
def __repr__(self): |
| 1102 |
"""Machine-readable representation. |
| 1103 |
Tab-separated version of __str__ - but always shows all fields""" |
| 1104 |
return f"{self.pid}\t{self.program}\t{self._exe}\t{self.cmdline}\t{self.prefix}\t{self.what}" |
| 1105 |
|
| 1106 |
@property |
| 1107 |
def systemd_unit(self): |
| 1108 |
"""Use cgroup v2 to find systemd service that started self. |
| 1109 |
Sets self.systemd_unit, self.systemd_type and self.systemd-command""" |
| 1110 |
if self._systemd_unit is None and self._using_cgroups2: |
| 1111 |
if DEBUG: print(f"Finding unit for {self.program} (PID={self.pid})") |
| 1112 |
cgroup_file=f"/proc/{self.pid}/cgroup" |
| 1113 |
if os.path.exists(cgroup_file): |
| 1114 |
try: |
| 1115 |
# /proc/pid/cgroup contains line: hierarchy_id:controller_list:cgroup_path |
| 1116 |
# in cgroups2, there is only one hierachy_id, so the file has one line like: |
| 1117 |
# 0::/system.slice/dbus.service\n |
| 1118 |
# 0::/user.slice/user-1000.slice/[email protected]/app.slice/dbus.service\n |
| 1119 |
# 0::/user.slice/user-1001.slice/[email protected]/init.scope\n |
| 1120 |
# 0::/machine.slice/machine-unstable\x2damd64.scope/payload/system.slice/console-getty.service |
| 1121 |
# |
| 1122 |
# (in cgroups v1, there are multiple hierachies, |
| 1123 |
# we would want the one called 'name=systemd' |
| 1124 |
# and then the cgroup_path should be as above: |
| 1125 |
# supporting cgroups v1 is therefore possible, |
| 1126 |
# however, this is not implemented.) |
| 1127 |
# |
| 1128 |
# HOWEVER: If you run a container with |
| 1129 |
# systemd-nspawn, |
| 1130 |
# - by default the container uses cgroups v1 (at least when the host is bullseye) |
| 1131 |
# - processes on the host now have 2 lines in their cgroup_file |
| 1132 |
# + one starting 0 as above |
| 1133 |
# + one which is just 1:name=systemd:/ |
| 1134 |
# + (this persists even after the container is shutdown) |
| 1135 |
# - processes in the container have |
| 1136 |
# + line startung 0 - points to machine.slice/machine-<name>.scope/payload/... |
| 1137 |
# + line starting 1 - gives a path to |
| 1138 |
# the container's unit |
| 1139 |
# (and if checkrestart is started in such a container: we would detect cgroups v1 |
| 1140 |
# host processes are of course not visible inside the container) |
| 1141 |
# untested: host running cgroups1 with containers running v2 |
| 1142 |
with open(cgroup_file, 'r') as f: |
| 1143 |
for line in f.readlines(): |
| 1144 |
if line.startswith("0::"): |
| 1145 |
self._systemd_unit=line.strip() |
| 1146 |
break |
| 1147 |
except OSError as e: |
| 1148 |
# should never happen |
| 1149 |
sys.stderr.write(f"WARNING: unable to read cgroup file: {cgroup_file}: {e}\n") |
| 1150 |
self._systemd_unit=None |
| 1151 |
if DEBUG: print(f"program {self.program} (PID {self.pid}) is part of systemd unit: {self._systemd_unit}") |
| 1152 |
return self._systemd_unit |
| 1153 |
|
| 1154 |
class Package: |
| 1155 |
"""Package represents either: |
| 1156 |
- a .deb package, |
| 1157 |
- an unpackaged program |
| 1158 |
|
| 1159 |
The latter has is_fake set to True""" |
| 1160 |
def __init__(self, name, is_fake=False): |
| 1161 |
self.name = name |
| 1162 |
self.is_fake=is_fake |
| 1163 |
self.initscripts = set() |
| 1164 |
self.systemdservice = set() |
| 1165 |
self.processes = [] |
| 1166 |
|
| 1167 |
|
| 1168 |
class SystemdUnit: |
| 1169 |
"""Represents a systemd unit (eg: apache2.service) and the processes it started""" |
| 1170 |
def __init__(self, cgroup): |
| 1171 |
"""cgroup is a string such as '0::/system.slice/x.service""" |
| 1172 |
self.cgroup_path=cgroup.split("/") |
| 1173 |
self.unit_slice=self.cgroup_path[1] |
| 1174 |
self.unit_name=self.cgroup_path[-1] |
| 1175 |
|
| 1176 |
if self.unit_slice=="system.slice": |
| 1177 |
# ['0::','system.slice','x.service'] |
| 1178 |
self._machine=".host" |
| 1179 |
elif self.unit_slice=="user.slice": |
| 1180 |
# eg ['0::','user.slice', 'user-N.slice' 'session-Y.scope','x.service'] |
| 1181 |
self.user_slice=self.cgroup_path[2] |
| 1182 |
self._machine=".host" |
| 1183 |
elif self.unit_slice=="machine.slice": |
| 1184 |
self.machine_scope=self.cgroup_path[2] |
| 1185 |
self._machine=None # machine name is set on demand |
| 1186 |
self.unit_slice=self.cgroup_path[4] |
| 1187 |
if self.unit_slice=="system.slice": |
| 1188 |
# ['0::', 'machine.slice', 'machine-NAME.scope', 'payload', 'system.slice', 'x.service'] |
| 1189 |
self.user_slice=None |
| 1190 |
elif self.unit_slice=="user.slice": |
| 1191 |
# ['0::', 'machine.slice', 'machine-NAME.scope', 'payload', 'user.slice', 'user-N.slice', 'x.service'] |
| 1192 |
self.user_slice=self.cgroup_path[5] |
| 1193 |
self._machine=None # set on demand for units started by containers |
| 1194 |
elif self.unit_slice=="init.scope": |
| 1195 |
# 0::/init.scope contains init (PID 1) |
| 1196 |
self._machine=".host" |
| 1197 |
else: |
| 1198 |
if DEBUG: print(f"unexpected cgroup format: {self.cgroup_path}") |
| 1199 |
self._machine=".host" |
| 1200 |
|
| 1201 |
# properties set on demand |
| 1202 |
self._user=None # set on demand for units in user.slice (ie started by user session managers) |
| 1203 |
self._name=None # set on demand |
| 1204 |
self._restart_command=None # set on demand |
| 1205 |
|
| 1206 |
self.processes=[] |
| 1207 |
|
| 1208 |
def __repr__(self): |
| 1209 |
"""human readable name of unit""" |
| 1210 |
self.name |
| 1211 |
|
| 1212 |
@property |
| 1213 |
def name(self): |
| 1214 |
"""human readable name of unit""" |
| 1215 |
if self._name is None: |
| 1216 |
if self.machine==".host": |
| 1217 |
in_machine="" |
| 1218 |
else: |
| 1219 |
in_machine=f" in container: {self.machine}" |
| 1220 |
|
| 1221 |
if self.unit_slice=="system.slice": |
| 1222 |
suffix=in_machine |
| 1223 |
elif self.unit_slice=="user.slice": |
| 1224 |
suffix=f" (started by user {self.user}{in_machine})" |
| 1225 |
else: |
| 1226 |
suffix=f" (in {self.unit_slice}{machine})" |
| 1227 |
self._name=f"{self.unit_name}{suffix}" |
| 1228 |
|
| 1229 |
return self._name |
| 1230 |
|
| 1231 |
@property |
| 1232 |
def user(self): |
| 1233 |
if self._user is None: |
| 1234 |
try: |
| 1235 |
# user-XXX.slice -> XXX |
| 1236 |
self._user=self.user_slice[5:-6] |
| 1237 |
except IndexError: |
| 1238 |
# should not happen |
| 1239 |
if DEBUG: print(f"unexpected user slice in cgroup: {self.cgroup_path}") |
| 1240 |
self._restart_command=False |
| 1241 |
self._user="UNKNOWN" |
| 1242 |
return self._user |
| 1243 |
|
| 1244 |
@property |
| 1245 |
def machine(self): |
| 1246 |
"""Set name of machine from self.machine_scope""" |
| 1247 |
if self._machine is None: |
| 1248 |
try: |
| 1249 |
# machine-unstable\\x2damd64\\x2dsbuild.scope -> unstable-amd64-sbuild |
| 1250 |
self._machine=subprocess.run(['systemd-escape', '--unescape',self.machine_scope[8:-6]], |
| 1251 |
capture_output=True, |
| 1252 |
encoding="utf-8", |
| 1253 |
errors="ignore").stdout.strip() |
| 1254 |
except IndexError: |
| 1255 |
# should not happen |
| 1256 |
if DEBUG: print(f"unexpected machine name in cgroup: {self.cgroup_path}") |
| 1257 |
self._restart_command=False |
| 1258 |
self._machine="UNKNOWN" # could use .host here perhaps |
| 1259 |
return self._machine |
| 1260 |
|
| 1261 |
@property |
| 1262 |
def restart_command(self): |
| 1263 |
"""Command to restart the unit. |
| 1264 |
|
| 1265 |
If we dont know how to restart the unit, this will be False, else a string which |
| 1266 |
is a command to cause a restart (e.g., 'systemctl restart foo.service'). |
| 1267 |
""" |
| 1268 |
if self._restart_command is None: |
| 1269 |
if self.unit_name.endswith(".service"): |
| 1270 |
if self.unit_slice=="system.slice": |
| 1271 |
if self.machine==".host": |
| 1272 |
self._restart_command=f"systemctl try-restart {self.unit_name}" |
| 1273 |
else: |
| 1274 |
# service inside systemd-nspawn container |
| 1275 |
self._restart_command=f"systemctl --machine={self.machine} try-restart {self.unit_name}" |
| 1276 |
elif self.unit_slice=="user.slice": |
| 1277 |
# user unit (the use of --machine <user>@.host requires systemd v248) |
| 1278 |
self._restart_command=f"# systemctl --user --machine={self.user}@{self.machine} try-restart {self.unit_name}" |
| 1279 |
else: |
| 1280 |
if DEBUG: print(f"service in neither system nor user slice: {self.unit_slice} ({self.cgroup_path})") |
| 1281 |
self._restart_command=False |
| 1282 |
else: |
| 1283 |
# eg, PID 1 is inside init.scope, (a scope can contain |
| 1284 |
# processes and slices not started via .service) |
| 1285 |
if DEBUG: print(f"unit is not a service: {self.unit_name} ({self.cgroup_path})") |
| 1286 |
self._restart_command=False |
| 1287 |
return self._restart_command |
| 1288 |
|
| 1289 |
|
| 1290 |
if __name__ == '__main__': |
| 1291 |
try: |
| 1292 |
main() |
| 1293 |
except (BrokenPipeError, KeyboardInterrupt): |
| 1294 |
sys.exit(3) |