-
Notifications
You must be signed in to change notification settings - Fork 0
/
rps-manage.py
executable file
·193 lines (158 loc) · 4.97 KB
/
rps-manage.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/bin/env python
# -*- coding: utf-8 -*-
# Set default encoding to UTF-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import sqlite3
import json
import random
import time
from urllib2 import urlopen
import subprocess
from datetime import datetime
import os
import shutil
testplayer = ('rockpaperscissors/testclient4', 'rockpaperscissors/testclient5',
'rockpaperscissors/testclient6')
def get_next():
with sqlite3.connect('data.db') as con:
cur = con.cursor()
cur.execute('''select user_id, name, docker_image
from user where not played limit 0,1''')
return cur.fetchone()
def get_highscore_player():
with sqlite3.connect('data.db') as con:
cur = con.cursor()
cur.execute('''select user_id, docker_image
from user where highscore order by highscore desc''')
return cur.fetchall()
def play(p1, p2):
error = False
print('### Starting Docker Container')
id1 = str(random.randint(1000000000,9999999999))
id2 = str(random.randint(1000000000,9999999999))
p = subprocess.Popen( ['docker', 'run', '-d', '--name', 'rps-server',
'-p', '4441:4441', 'rockpaperscissors/server', '/rps/start.sh', id1, id2])
p.communicate()
if p.returncode:
print('Failed to start rps-server docker container')
# Something is wrong on our side. Exit immediately.
exit()
# Wait for server to start up
result = None
n = 0
while not result:
try:
result = urlopen('http://localhost:4441').read()
except:
time.sleep(0.1)
n += 1
if n > 10000:
print('Failed to connect to rps-server')
error = True
if not error:
# Start Player 1
p = subprocess.Popen( ['docker', 'run', '-d', '--name', 'rps-player-one',
'--link', 'rps-server:rps-server ', p1, '/rps/start.sh', id1])
p.communicate()
if p.returncode:
print('Failed to start player-one docker container')
error = True
if not error:
# Start Player 1
p = subprocess.Popen( ['docker', 'run', '-d', '--name', 'rps-player-two',
'--link', 'rps-server:rps-server ', p2, '/rps/start.sh', id2])
p.communicate()
if p.returncode:
print('Failed to start player-two docker container')
error = True
print('### Wait for Server to Finish')
# Wait for server to finish
result = 'playing'
if not error:
while result == 'playing':
try:
result = urlopen('http://localhost:4441').read()
time.sleep(0.1)
except:
print('Failed to get result from rps-server')
error = True
break
if not error:
print(result)
try:
result = json.loads(result)
except:
error = True
print('### Store Logs')
# Keep logs
logname = ''.join([ c for c in str(datetime.now())[0:-7] if c in '0123456789' ])
os.system('mkdir -p logs')
os.system('docker logs rps-server &> logs/%s.serv.log' % logname)
os.system('docker logs rps-player-one &> logs/%s.p1.log' % logname)
os.system('docker logs rps-player-two &> logs/%s.p2.log' % logname)
print('### Drop Containers')
# Drop docker container
subprocess.Popen( ['docker', 'rm', '-f', 'rps-server', 'rps-player-one',
'rps-player-two']).communicate()
if error:
return None
return result[id1], result[id2]
def save_game(p1, p2, r1, r2):
with sqlite3.connect('data.db') as con:
cur = con.cursor()
cur.execute('''insert into game ( user_id_1, user_id_2, win_player_1,
win_player_2, rock_player_1, paper_player_1, scissors_player_1,
rock_player_2, paper_player_2, scissors_player_2 )
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
( p1, p2, r1['won'], r2['won'],
r1['rock'], r1['paper'], r1['scissors'],
r2['rock'], r2['paper'], r2['scissors'] ))
con.commit()
def mark_played(pid):
with sqlite3.connect('data.db') as con:
cur = con.cursor()
cur.execute('update user set played=1 where user_id = ?', (pid,))
con.commit()
def player_highscore(pid, n):
with sqlite3.connect('data.db') as con:
cur = con.cursor()
cur.execute('update user set highscore=? where user_id = ?', (n,pid))
con.commit()
if __name__ == "__main__":
pid, pname, pdocker = get_next() or exit('No upcoming player.\nExiting...')
print('### Backing up database')
backupname = ''.join([ c for c in str(datetime.now())[0:-7] if c in '0123456789' ])
shutil.copy2('data.db', 'backup/data.db.' + backupname)
print('### Now playing: ' + pname)
# Play against testplayer
for tdocker in testplayer:
result = play(pdocker, tdocker)
# Mark this player in any case
mark_played(pid)
if not result:
exit()
save_game(pid, 0, result[0], result[1])
# Player lost -> The end
if int(result[0]['won']) < int(result[1]['won']):
print('### Player has lost against test')
exit()
print('### Player has won against test')
# Play against highscore
highscore = get_highscore_player()
n = len(highscore)
if n <= 10:
player_highscore(pid, n+1)
for oid, odocker in highscore:
result = play(pdocker, odocker)
if not result:
exit()
save_game(pid, oid, result[0], result[1])
# Player lost -> The end
if int(result[0]['won']) <= int(result[1]['won']):
exit()
else:
player_highscore(pid, n)
player_highscore(oid, n+1 if n < 10 else None)
n -= 1