This repository was archived by the owner on Aug 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 604
Expand file tree
/
Copy pathassassin.py
More file actions
171 lines (118 loc) · 3.73 KB
/
assassin.py
File metadata and controls
171 lines (118 loc) · 3.73 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
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/env python
import os
import sys
import time
import json
import socket
import commands
try:
import psutil
import pycurl
except ImportError:
print "Install required packages first: pip install psutil pycurl"
sys.exit(1)
THRESHOLD = 1.0 # percentage
KILL_THRESHOLD = 3.0 # average percentage before deciding to kill
REPEAT_EVERY = 1 # seconds
MAX_OCCURRENCE = 5 # times
MAX_REPEAT = 10 # times ~ 0 to infinite
KILL_ENABLED = False
SLACK_ENABLED = False
WHITE_LIST = [
"kloud",
"koding-webserver",
"koding-authworker",
"koding-socialworker",
]
(status, hostaddr) = commands.getstatusoutput(
"/opt/aws/bin/ec2-metadata --public-hostname"
)
hostname = socket.gethostname()
if status == 0:
hostaddr = "ssh://ec2-user@%s" % hostaddr.split(':')[-1].strip()
hostname = "<%s|%s>" % (hostaddr, hostname)
else:
hostname = "*%s*" % hostname
my_pid = os.getpid()
bad_guys = {}
PAYLOAD = {
"channel" : "#_devops",
"username" : "py_assassin",
"icon_emoji" : ":snake:"
}
slack = pycurl.Curl()
slack.setopt(pycurl.URL, "")
slack.setopt(pycurl.POST, 1)
def slack_it(message):
print message
if not SLACK_ENABLED:
return
PAYLOAD['text'] = "[%s] %s" % (hostname, message)
slack.setopt(pycurl.POSTFIELDS, "payload=%s" % json.dumps(PAYLOAD))
slack.perform()
def get_top_processes():
procs = []
for p in psutil.process_iter():
if p.pid == my_pid:
continue
try:
p.dict = p.as_dict(['cpu_percent', 'name', 'status'])
except:
pass
else:
if p.dict['cpu_percent'] > THRESHOLD:
procs.append(p)
# return processes sorted by CPU percent usage
return sorted(procs, key=lambda p: p.dict['cpu_percent'], reverse = True)
def kill(proc, usage):
usage = usage / MAX_OCCURRENCE # get average CPU usage
if usage > KILL_THRESHOLD:
if KILL_ENABLED and proc.name() in WHITE_LIST:
slack_it("Killing: *%s* (*PID %s*) usage was: %s" %
(proc.name(), proc.pid, usage))
proc.kill()
else:
print("If I was able to, I would like to kill: *%s* (*PID %s*) "
"since it's using %s cpu on average..." %
(proc.name(), proc.pid, usage))
else:
print("Giving another chance to *%s* since "
"its usage average (*%s*) below kill "
"threshold: *%s* " % (proc.name(), usage, KILL_THRESHOLD))
del bad_guys[proc.pid]
def checks():
global bad_guys
top_process = get_top_processes()
if len(top_process) == 0:
bad_guys = {}
return
for proc in top_process[0:5]:
if proc.pid in bad_guys:
bad_guys[proc.pid]['counter'] += 1
bad_guys[proc.pid]['cpu'] += proc.dict['cpu_percent']
if bad_guys[proc.pid]['counter'] >= MAX_OCCURRENCE:
kill(proc, bad_guys[proc.pid]['cpu'])
else:
bad_guys[proc.pid] = dict( proc = proc, counter = 0, cpu = 0 )
PROCESS_OUT = "Process '%s' (PID %s) is using more than %s " \
"CPU (%s) in last %d seconds for the %d times."
for pid, p in bad_guys.iteritems():
[p, counter] = [p['proc'].dict, p['counter']]
print(PROCESS_OUT % (
p['name'], pid, THRESHOLD, p['cpu_percent'], REPEAT_EVERY, counter
))
def main():
counter = 0
while True:
checks()
counter += 1
if counter == MAX_REPEAT:
print("Done.")
sys.exit()
time.sleep(REPEAT_EVERY)
if __name__ == '__main__':
print "Assassin started..."
try:
main()
except (KeyboardInterrupt, SystemExit):
pass