Debian Codegraph @

tests/killdaemons.py

raw
1 #!/usr/bin/env python3
2
3 import os
4 import signal
5 import sys
6 import time
7
8 if os.name == 'nt':
9 import ctypes
10
11 _BOOL = ctypes.c_long
12 _DWORD = ctypes.c_ulong
13 _UINT = ctypes.c_uint
14 _HANDLE = ctypes.c_void_p
15
16 ctypes.windll.kernel32.CloseHandle.argtypes = [_HANDLE]
17 ctypes.windll.kernel32.CloseHandle.restype = _BOOL
18
19 ctypes.windll.kernel32.GetLastError.argtypes = []
20 ctypes.windll.kernel32.GetLastError.restype = _DWORD
21
22 ctypes.windll.kernel32.OpenProcess.argtypes = [_DWORD, _BOOL, _DWORD]
23 ctypes.windll.kernel32.OpenProcess.restype = _HANDLE
24
25 ctypes.windll.kernel32.TerminateProcess.argtypes = [_HANDLE, _UINT]
26 ctypes.windll.kernel32.TerminateProcess.restype = _BOOL
27
28 ctypes.windll.kernel32.WaitForSingleObject.argtypes = [_HANDLE, _DWORD]
29 ctypes.windll.kernel32.WaitForSingleObject.restype = _DWORD
30
31 def _check(ret, expectederr=None):
32 if ret == 0:
33 winerrno = ctypes.GetLastError()
34 if winerrno == expectederr:
35 return True
36 raise ctypes.WinError(winerrno)
37
38 def kill(pid, logfn, tryhard=True):
39 logfn('# Killing daemon process %d' % pid)
40 PROCESS_TERMINATE = 1
41 PROCESS_QUERY_INFORMATION = 0x400
42 SYNCHRONIZE = 0x00100000
43 WAIT_OBJECT_0 = 0
44 WAIT_TIMEOUT = 258
45 WAIT_FAILED = _DWORD(0xFFFFFFFF).value
46 handle = ctypes.windll.kernel32.OpenProcess(
47 PROCESS_TERMINATE | SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
48 False,
49 pid,
50 )
51 if handle is None:
52 _check(0, 87) # err 87 when process not found
53 return # process not found, already finished
54 try:
55 r = ctypes.windll.kernel32.WaitForSingleObject(handle, 100)
56 if r == WAIT_OBJECT_0:
57 pass # terminated, but process handle still available
58 elif r == WAIT_TIMEOUT:
59 # Allow the caller to optionally specify the exit code, to
60 # simulate killing with a signal.
61 exit_code = int(os.environ.get("DAEMON_EXITCODE", -1))
62 _check(
63 ctypes.windll.kernel32.TerminateProcess(handle, exit_code)
64 )
65 elif r == WAIT_FAILED:
66 _check(0) # err stored in GetLastError()
67
68 # TODO?: forcefully kill when timeout
69 # and ?shorter waiting time? when tryhard==True
70 r = ctypes.windll.kernel32.WaitForSingleObject(handle, 100)
71 # timeout = 100 ms
72 if r == WAIT_OBJECT_0:
73 pass # process is terminated
74 elif r == WAIT_TIMEOUT:
75 logfn('# Daemon process %d is stuck')
76 elif r == WAIT_FAILED:
77 _check(0) # err stored in GetLastError()
78 except: # re-raises
79 ctypes.windll.kernel32.CloseHandle(handle) # no _check, keep error
80 raise
81 _check(ctypes.windll.kernel32.CloseHandle(handle))
82
83 else:
84
85 def kill(pid, logfn, tryhard=True):
86 try:
87 os.kill(pid, 0)
88 logfn('# Killing daemon process %d' % pid)
89 os.kill(pid, signal.SIGTERM)
90 if tryhard:
91 for i in range(10):
92 time.sleep(0.05)
93 os.kill(pid, 0)
94 else:
95 time.sleep(0.1)
96 os.kill(pid, 0)
97 logfn('# Daemon process %d is stuck - really killing it' % pid)
98 os.kill(pid, signal.SIGKILL)
99 except ProcessLookupError:
100 pass
101
102
103 def killdaemons(pidfile, tryhard=True, remove=False, logfn=None):
104 if not logfn:
105 logfn = lambda s: s
106 # Kill off any leftover daemon processes
107 try:
108 pids = []
109 if pidfile == '-':
110 fp = sys.stdin
111 else:
112 fp = open(pidfile)
113
114 with fp:
115 for line in fp:
116 try:
117 pid = int(line)
118 if pid <= 0:
119 raise ValueError
120 except ValueError:
121 logfn(
122 '# Not killing daemon process %s - invalid pid'
123 % line.rstrip()
124 )
125 continue
126 pids.append(pid)
127 for pid in pids:
128 kill(pid, logfn, tryhard)
129 if remove:
130 os.unlink(pidfile)
131 except OSError:
132 pass
133
134
135 if __name__ == '__main__':
136 if len(sys.argv) > 1:
137 (path,) = sys.argv[1:]
138 else:
139 path = os.environ["DAEMON_PIDS"]
140
141 killdaemons(path, remove=True)