Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import os 

2import re 

3import signal 

4import time 

5import psutil 

6from lockfile.pidlockfile import PIDLockFile 

7 

8from gutools.tools import wlikelyhood 

9# Process 

10 

11def send_signals(iterator, signals, tries=3, pause=1, done_callback=None): 

12 """iterator returns (name,pid) items""" 

13 def get_names(running): 

14 return set([name for name, _ in running]) 

15 

16 for sig in signals: 

17 running = [item for item in iterator()] 

18 if not running: 

19 break 

20 

21 # if sig in (signal.SIGKILL, ): 

22 # print(f"{RED}KILLING: {CYAN}{len(running)} {RED}processes {RESET}") 

23 # else: 

24 # print(f"{BLUE}Stopping: {CYAN}{len(running)} {BLUE}processes {RESET}") 

25 

26 for _ in range(tries): 

27 names = get_names(running) 

28 for name, pid in running: 

29 print(f' {name}\t<----\tsignal: {sig}') 

30 test_process(pid, sig=sig) 

31 

32 time.sleep(pause) 

33 running = [item for item in iterator()] 

34 names2 = get_names(running) 

35 

36 for name in names.difference(names2): 

37 done_callback and done_callback(name) 

38 # pidfile = self._get_filename('pid', name) 

39 # if os.path.exists(pidfile): 

40 # os.remove(pidfile) 

41 

42 names = names2 

43 if not running: 

44 break 

45 

46 

47def test_process(pid, sig=0): 

48 if not pid: 

49 return 

50 if isinstance(pid, str): 

51 try: 

52 pid = int(open(pid).read().strip()) 

53 except Exception as why: 

54 try: 

55 pid = int(pid) 

56 except ValueError: 

57 return 

58 try: 

59 os.kill(pid, sig) 

60 except OSError as why: # is finished? 

61 if why.errno == 3 or why.strerror.find("No such process"): 

62 return False 

63 return pid 

64 

65def test_alive(pid): 

66 if not pid: 

67 return 

68 if isinstance(pid, str): 

69 try: 

70 pid = int(open(pid).read().strip()) 

71 except Exception as why: 

72 try: 

73 pid = int(pid) 

74 except ValueError: 

75 return 

76 try: 

77 proc = psutil.Process(pid) 

78 proc.cwd() 

79 except Exception as why: # is finished? 

80 return None 

81 return proc 

82 

83 

84def get_fingerprint(proc: psutil.Process) -> dict: 

85 # BINDED/LISTEN sockets 

86 fp = { 

87 'files': [], 

88 'listen': [], 

89 'established': [], 

90 'udp': [], 

91 'cmdline': proc.cmdline(), 

92 } 

93 try: 

94 

95 for con in proc.connections(): 

96 key = con.status.lower().replace('none', 'udp') 

97 if key in ('listen', 'udp'): 

98 addr = con.laddr 

99 else: 

100 addr = con.raddr 

101 fp[key].append(f'{addr.ip}:{addr.port}') 

102 

103 # Open files 

104 files = fp['files'] 

105 for fd in proc.open_files(): 

106 info = f"{fd.path}" 

107 files.append(info) 

108 

109 except Exception: 

110 foo = 1 

111 

112 return fp 

113 

114def compare_fingerprint(fp0, fp): 

115 s = wlikelyhood(fp0, fp, listen=20, established=2, files=30, cmdline=50) 

116 return s 

117 

118def find_process(rexp): 

119 if isinstance(rexp, str): 

120 rexp = re.compile(rexp, re.DOTALL|re.I) 

121 for pid in psutil.pids(): 

122 process = psutil.Process(pid) 

123 cmdline = process.cmdline() 

124 m = cmdline and rexp.search(cmdline[0]) 

125 if m: 

126 yield process 

127 

128 

129 

130class SmartPIDLockFile(PIDLockFile): 

131 def __init__(self, path, threaded=False, timeout=None): 

132 if os.path.exists(path) and not test_process(path): 

133 os.remove(path) 

134 super().__init__(path, threaded, timeout)