Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessManager.py
More file actions
Latest commit
161 lines (139 loc) · 5.95 KB
/
Copy pathProcessManager.py
File metadata and controls
161 lines (139 loc) · 5.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
importthreading
fromdatetimeimportdatetime
fromtypingimportDict, List, Optional
importpsutil
classProcessManager:
"""Gestionnaire centralisé des processus avec monitoring."""
def__init__(self):
self.processes: Dict[str, Dict] = {} # {process_id: {process, metadata}}
self.lock=threading.Lock()
defregister(self, process, scanner_type: str, strategy: str, ip: str, thread_id: str):
"""Enregistre un nouveau processus avec metadata."""
withself.lock:
process_id=f"{scanner_type}_{thread_id}_{process.pid}"
self.processes[process_id] = {
"process": process,
"pid": process.pid,
"scanner_type": scanner_type,
"strategy": strategy,
"ip": ip,
"thread_id": thread_id,
"start_time": datetime.now(),
"status": "running"
}
returnprocess_id
defget_all(self) ->List[Dict]:
"""Retourne tous les processus avec leurs infos."""
withself.lock:
result= []
forproc_id, datainlist(self.processes.items()):
try:
proc=data["process"]
p=psutil.Process(proc.pid)
result.append({
"id": proc_id,
"pid": data["pid"],
"scanner": data["scanner_type"],
"strategy": data["strategy"],
"ip": data["ip"],
"thread_id": data["thread_id"],
"status": data["status"],
"start_time": data["start_time"].isoformat(),
"cpu_percent": p.cpu_percent(interval=0.1),
"memory_mb": p.memory_info().rss/1024/1024,
"uptime_seconds": (datetime.now() -data["start_time"]).total_seconds(),
"cmdline": " ".join(p.cmdline()[:3]) # Limiter taille
})
except (psutil.NoSuchProcess, psutil.AccessDenied):
# Processus terminé
data["status"] ="terminated"
returnresult
defget_by_id(self, process_id: str) ->Optional[Dict]:
"""Récupère info d'un processus spécifique."""
withself.lock:
data=self.processes.get(process_id)
ifnotdata:
returnNone
try:
proc=data["process"]
p=psutil.Process(proc.pid)
return {
"id": process_id,
"pid": data["pid"],
"scanner": data["scanner_type"],
"strategy": data["strategy"],
"ip": data["ip"],
"status": data["status"],
"cpu_percent": p.cpu_percent(interval=0.1),
"memory_mb": p.memory_info().rss/1024/1024,
"num_threads": p.num_threads(),
"open_files": len(p.open_files()),
"connections": len(p.net_connections()),
"cmdline": " ".join(p.cmdline())
}
except (psutil.NoSuchProcess, psutil.AccessDenied):
return {"id": process_id, "status": "terminated"}
defkill(self, process_id: str) ->bool:
"""Tue un processus spécifique."""
withself.lock:
data=self.processes.get(process_id)
ifnotdata:
returnFalse
# ÉTAPE 1: Trouver le processus
try:
proc=data["process"]
p=psutil.Process(proc.pid)
except (psutil.NoSuchProcess, psutil.AccessDenied):
# Le processus n'existe déjà plus ou on n'a pas les droits
data["status"] ="terminated"
returnFalse
# ÉTAPE 2: Tenter de le terminer poliment (terminate)
try:
p.terminate()
p.wait(timeout=3)
# S'il se termine à temps, 'p.wait()' ne lève pas d'exception
exceptpsutil.TimeoutExpired:
# Il n'a pas voulu s'arrêter, on force (kill)
try:
p.kill()
except (psutil.NoSuchProcess, psutil.AccessDenied, ProcessLookupError):
pass# Mort entre-temps, ou permissions
except (psutil.NoSuchProcess, psutil.AccessDenied, ProcessLookupError):
# Mort entre-temps, ou permissions
pass
data["status"] ="killed"
returnTrue
defkill_all(self):
"""Tue tous les processus enregistrés."""
withself.lock:
forproc_idinlist(self.processes.keys()):
self.kill(proc_id)
defcleanup_terminated(self):
"""Nettoie les processus terminés."""
withself.lock:
to_remove= []
forproc_id, datainself.processes.items():
# noinspection PyBroadException
try:
proc=data["process"]
ifproc.poll() isnotNone: # Terminé
to_remove.append(proc_id)
except:
to_remove.append(proc_id)
forproc_idinto_remove:
delself.processes[proc_id]
defget_stats(self) ->Dict:
"""Statistiques globales."""
self.cleanup_terminated()
withself.lock:
total=len(self.processes)
running=sum(1fordinself.processes.values() ifd["status"] =="running")
by_scanner= {}
fordatainself.processes.values():
scanner=data["scanner_type"]
by_scanner[scanner] =by_scanner.get(scanner, 0) +1
return {
"total": total,
"running": running,
"by_scanner": by_scanner
}