-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtestserver.py
119 lines (103 loc) · 3.42 KB
/
testserver.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
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading
import sys, tty, termios, time, random, string, json
from datetime import tzinfo, timedelta, datetime
class TZ(tzinfo):
def utcoffset(self, dt): return timedelta(minutes=60)
class Handler(BaseHTTPRequestHandler):
def log_request(self, *args):
pass
def do_GET(self):
global QUEUE
self.send_response(200)
self.end_headers()
now = time.time()
foundevents = False
while 1:
if QUEUE:
self.wfile.write(json.dumps(QUEUE))
QUEUE = []
foundevents = True
break
elif time.time() - now > 10:
break
else:
time.sleep(1)
if not foundevents:
self.wfile.write(json.dumps([make_action(ACTIONS[0], -1)]))
self.wfile.write('\n')
return
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
timeout = 6
def printtime():
while 1:
if not TYPING:
print time.asctime(), TYPING, "\r",
def randomLetters():
return "".join([random.choice(string.uppercase) for x in range(10)])
CREATED = {}
def create(thing):
if thing not in CREATED: CREATED[thing] = []
val = randomLetters()
CREATED[thing].append(val)
return val
def use(thing):
if thing not in CREATED: return randomLetters()
if not CREATED[thing]: return randomLetters()
return CREATED[thing].pop()
ACTIONS = [
{"type": "TIMEOUT", "params": lambda: {}},
{"type": "NODE_CONNECTED", "params": lambda: {"node": create("node")}},
{"type": "NODE_DISCONNECTED", "params": lambda: {"node": use("node")}},
{"type": "PULL_START", "params": lambda: {
"repo": 'reponame', "file": create("file") + ".txt",
"size": random.randint(1,10000), "modified": time.time(), "flags": ""}},
{"type": "PULL_COMPLETE", "params": lambda: {
"repo": 'reponame', "file": use("file") + ".txt"}},
{"type": "PULL_ERROR", "params": lambda: {
"repo": 'reponame', "file": use("file") + ".txt", "error": "MESSAGE"}}
]
QUEUE = []
def menu():
for i in range(len(ACTIONS)):
print "%s: %s" % (i, ACTIONS[i]["type"])
print "q. quit"
def make_action(action_template, action_id):
ts = datetime.now()
ts = ts.replace(tzinfo=TZ())
action = {
"type": action_template["type"],
"params": action_template["params"](),
"id": action_id,
"timestamp": ts.isoformat()
}
return action
if __name__ == '__main__':
server = ThreadedHTTPServer(('localhost', 5115), Handler)
print 'Starting server, use <Ctrl-C> to stop'
server = threading.Thread(target=server.serve_forever)
server.daemon = True
server.start()
fd = sys.stdin.fileno()
menu()
acount = 1
while 1:
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
if ch == "q": break
try:
action_template = ACTIONS[int(ch)]
except:
continue
action = make_action(action_template, acount)
print action
QUEUE.append(action)
acount += 1
if acount % 20 == 0:
menu()