-
Notifications
You must be signed in to change notification settings - Fork 105
/
speedcomplainer.py
executable file
·172 lines (135 loc) · 6.26 KB
/
speedcomplainer.py
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
172
import os
import sys
import time
from datetime import datetime
import daemon
import signal
import threading
import twitter
import json
import random
from logger import Logger
shutdownFlag = False
def main(filename, argv):
print "======================================"
print " Starting Speed Complainer! "
print " Lets get noisy! "
print "======================================"
global shutdownFlag
signal.signal(signal.SIGINT, shutdownHandler)
monitor = Monitor()
while not shutdownFlag:
try:
monitor.run()
for i in range(0, 5):
if shutdownFlag:
break
time.sleep(1)
except Exception as e:
print 'Error: %s' % e
sys.exit(1)
sys.exit()
def shutdownHandler(signo, stack_frame):
global shutdownFlag
print 'Got shutdown signal (%s: %s).' % (signo, stack_frame)
shutdownFlag = True
class Monitor():
def __init__(self):
self.lastPingCheck = None
self.lastSpeedTest = None
def run(self):
if not self.lastPingCheck or (datetime.now() - self.lastPingCheck).total_seconds() >= 60:
self.runPingTest()
self.lastPingCheck = datetime.now()
if not self.lastSpeedTest or (datetime.now() - self.lastSpeedTest).total_seconds() >= 3600:
self.runSpeedTest()
self.lastSpeedTest = datetime.now()
def runPingTest(self):
pingThread = PingTest()
pingThread.start()
def runSpeedTest(self):
speedThread = SpeedTest()
speedThread.start()
class PingTest(threading.Thread):
def __init__(self, numPings=3, pingTimeout=2, maxWaitTime=6):
super(PingTest, self).__init__()
self.numPings = numPings
self.pingTimeout = pingTimeout
self.maxWaitTime = maxWaitTime
self.config = json.load(open('./config.json'))
self.logger = Logger(self.config['log']['type'], { 'filename': self.config['log']['files']['ping'] })
def run(self):
pingResults = self.doPingTest()
self.logPingResults(pingResults)
def doPingTest(self):
response = os.system("ping -c %s -W %s -w %s 8.8.8.8 > /dev/null 2>&1" % (self.numPings, (self.pingTimeout * 1000), self.maxWaitTime))
success = 0
if response == 0:
success = 1
return { 'date': datetime.now(), 'success': success }
def logPingResults(self, pingResults):
self.logger.log([ pingResults['date'].strftime('%Y-%m-%d %H:%M:%S'), str(pingResults['success'])])
class SpeedTest(threading.Thread):
def __init__(self):
super(SpeedTest, self).__init__()
self.config = json.load(open('./config.json'))
self.logger = Logger(self.config['log']['type'], { 'filename': self.config['log']['files']['speed'] })
def run(self):
speedTestResults = self.doSpeedTest()
self.logSpeedTestResults(speedTestResults)
self.tweetResults(speedTestResults)
def doSpeedTest(self):
# run a speed test
result = os.popen("/usr/local/bin/speedtest-cli --simple").read()
if 'Cannot' in result:
return { 'date': datetime.now(), 'uploadResult': 0, 'downloadResult': 0, 'ping': 0 }
# Result:
# Ping: 529.084 ms
# Download: 0.52 Mbit/s
# Upload: 1.79 Mbit/s
resultSet = result.split('\n')
pingResult = resultSet[0]
downloadResult = resultSet[1]
uploadResult = resultSet[2]
pingResult = float(pingResult.replace('Ping: ', '').replace(' ms', ''))
downloadResult = float(downloadResult.replace('Download: ', '').replace(' Mbit/s', ''))
uploadResult = float(uploadResult.replace('Upload: ', '').replace(' Mbit/s', ''))
return { 'date': datetime.now(), 'uploadResult': uploadResult, 'downloadResult': downloadResult, 'ping': pingResult }
def logSpeedTestResults(self, speedTestResults):
self.logger.log([ speedTestResults['date'].strftime('%Y-%m-%d %H:%M:%S'), str(speedTestResults['uploadResult']), str(speedTestResults['downloadResult']), str(speedTestResults['ping']) ])
def tweetResults(self, speedTestResults):
thresholdMessages = self.config['tweetThresholds']
message = None
for (threshold, messages) in thresholdMessages.items():
threshold = float(threshold)
if speedTestResults['downloadResult'] < threshold:
message = messages[random.randint(0, len(messages) - 1)].replace('{tweetTo}', self.config['tweetTo']).replace('{internetSpeed}', self.config['internetSpeed']).replace('{downloadResult}', str(speedTestResults['downloadResult']))
if message:
api = twitter.Api(consumer_key=self.config['twitter']['twitterConsumerKey'],
consumer_secret=self.config['twitter']['twitterConsumerSecret'],
access_token_key=self.config['twitter']['twitterToken'],
access_token_secret=self.config['twitter']['twitterTokenSecret'])
if api:
status = api.PostUpdate(message)
class DaemonApp():
def __init__(self, pidFilePath, stdout_path='/dev/null', stderr_path='/dev/null'):
self.stdin_path = '/dev/null'
self.stdout_path = stdout_path
self.stderr_path = stderr_path
self.pidfile_path = pidFilePath
self.pidfile_timeout = 1
def run(self):
main(__file__, sys.argv[1:])
if __name__ == '__main__':
main(__file__, sys.argv[1:])
workingDirectory = os.path.basename(os.path.realpath(__file__))
stdout_path = '/dev/null'
stderr_path = '/dev/null'
fileName, fileExt = os.path.split(os.path.realpath(__file__))
pidFilePath = os.path.join(workingDirectory, os.path.basename(fileName) + '.pid')
from daemon import runner
dRunner = runner.DaemonRunner(DaemonApp(pidFilePath, stdout_path, stderr_path))
dRunner.daemon_context.working_directory = workingDirectory
dRunner.daemon_context.umask = 0o002
dRunner.daemon_context.signal_map = { signal.SIGTERM: 'terminate', signal.SIGUP: 'terminate' }
dRunner.do_action()