-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_control.py
More file actions
290 lines (264 loc) · 13.4 KB
/
server_control.py
File metadata and controls
290 lines (264 loc) · 13.4 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import zmq, time, subprocess, sys, socket, minestat, logging.handlers, os, secrets, ast
from interruptingcow import timeout
start_dir = os.path.dirname(os.path.realpath(__file__))
if not os.path.exists(os.path.join(start_dir, "logs")):
os.mkdir(os.path.join(start_dir, "logs"))
logger = logging.getLogger()
file_handler = logging.handlers.RotatingFileHandler(os.path.join(start_dir, "logs", "server-control.log"), maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s [line %(lineno)d]"))
file_handler.setLevel(logging.INFO)
logger.addHandler(file_handler)
logger.setLevel(logging.INFO)
def system_start():
logger.info("Starting the server, please wait...")
zmq_context = zmq.Context()
zmq_socket = zmq_context.socket(zmq.REQ)
zmq_socket.setsockopt(zmq.LINGER, 0) # The default value is -1, which means wait until all messages have been sent before allowing termination. Set to 0 to discard unsent messages immediately, and any positive integer will be the number of milliseconds to keep trying to send before discard.
subprocess.run(["/usr/bin/sudo", "/usr/sbin/etherwake", "-i", "eth0", secrets.MAC_ADDRESS])
logger.info("Sent Wake on LAN packet. Waiting 10 seconds for the server to switch on...")
time.sleep(10)
try:
with timeout(5, exception=RuntimeError):
logger.info("Attempting to connect to the control server...")
zmq_socket.connect("tcp://" + secrets.LOCAL_IP + ":5555")
logger.info("Connected. Server successfully switched on.")
pass
return {"result": "done"}
except RuntimeError:
logger.info("No response...")
logger.info("The server could not be switched on")
return {"result": "failed"}
zmq_socket.close()
zmq_context.term()
def vanilla_start():
logger.info("Starting the server, please wait...")
zmq_context = zmq.Context()
zmq_socket = zmq_context.socket(zmq.REQ)
zmq_socket.setsockopt(zmq.LINGER, 0) # The default value is -1, which means wait until all messages have been sent before allowing termination. Set to 0 to discard unsent messages immediately, and any positive integer will be the number of milliseconds to keep trying to send before discard.
subprocess.run(["/usr/bin/sudo ", "/usr/sbin/etherwake", "-i", "eth0", secrets.MAC_ADDRESS])
logger.info("Sent Wake on LAN packet. Waiting 10 seconds for the server to switch on...")
time.sleep(10)
try:
with timeout(5, exception=RuntimeError):
logger.info("Attempting to connect to the control server...")
zmq_socket.connect("tcp://" + secrets.LOCAL_IP + ":5555")
logger.info("Connected. Sending \"start\" command...")
zmq_socket.send_string("start")
pass
with timeout(5, exception=RuntimeError):
logger.info("Done. Waiting for response...")
response = zmq_socket.recv_string()
pass
if response == "done":
logger.info("The server has been switched on ✅")
zmq_socket.close()
zmq_context.term()
return {"result": "done"}
else:
logger.info("Received response: " + response)
logger.info("The server was switched on but the Minecraft Server was not switched on")
zmq_socket.close()
zmq_context.term()
return {"result": "failed"}
except RuntimeError:
logger.info("No response...")
logger.info("The server could not be switched on")
zmq_socket.close()
zmq_context.term()
return {"result": "failed"}
zmq_socket.close()
zmq_context.term()
def system_stop():
logger.info("Stopping the server, please wait...")
zmq_context = zmq.Context()
zmq_socket = zmq_context.socket(zmq.REQ)
zmq_socket.setsockopt(zmq.LINGER, 0) # The default value is -1, which means wait until all messages have been sent before allowing termination. Set to 0 to discard unsent messages immediately, and any positive integer will be the number of milliseconds to keep trying to send before discard.
# use os.path thingy to add danny bot's install folder to these path checks:
# if os.path.exists("disable_stop.txt"):
# await message.channel.send("Not turning the server off because tech189 has requested that it stays on")
# else:
# if os.path.exists("last_start.txt"):
# os.remove("last_start.txt")
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
with timeout(1, exception=RuntimeError):
logger.info("Pinging the server to check if it's online...")
s.connect((secrets.LOCAL_IP, 5555))
logger.info("Ping successful.")
pass
with timeout(5, exception=RuntimeError):
logger.info("Attempting to connect to the control server...")
zmq_socket.connect("tcp://" + secrets.LOCAL_IP + ":5555")
logger.info("Connected. Sending \"stop\" command...")
zmq_socket.send_string("stop")
pass
logger.info("Done. Waiting for response...")
response = zmq_socket.recv_string()
if response == "done":
logger.info("Received response. Waiting 20 seconds for server to shut down...")
time.sleep(20)
s_2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
with timeout(1, exception=RuntimeError):
logger.info("Pinging the server to check if it's online...")
s_2.connect((secrets.LOCAL_IP, 5555))
logger.info("Ping successful. The server could not be shut down")
zmq_socket.close()
zmq_context.term()
return {"result": "failed"}
except RuntimeError:
logger.info("No response within 1 second. Therefore server is off")
logger.info("The server has been shut down 😴")
zmq_socket.close()
zmq_context.term()
return {"result": "done"}
s_2.close()
else:
logger.info("Received response: " + response)
logger.info("The server could not be shut down")
zmq_socket.close()
zmq_context.term()
return {"result": "failed"}
except RuntimeError:
logger.info("The server seems to be off already, you can turn it on with `!server start`")
zmq_socket.close()
zmq_context.term()
return {"result": "done"}
s.close()
except RuntimeError:
logger.info("The server could not be shut down")
zmq_socket.close()
zmq_context.term()
return {"result": "failed"}
zmq_socket.close()
zmq_context.term()
def system_sleep():
logger.info("Sleeping the server, please wait...")
zmq_context = zmq.Context()
zmq_socket = zmq_context.socket(zmq.REQ)
zmq_socket.setsockopt(zmq.LINGER, 0) # The default value is -1, which means wait until all messages have been sent before allowing termination. Set to 0 to discard unsent messages immediately, and any positive integer will be the number of milliseconds to keep trying to send before discard.
# use os.path thingy to add danny bot's install folder to these path checks:
# if os.path.exists("disable_stop.txt"):
# await message.channel.send("Not turning the server off because tech189 has requested that it stays on")
# else:
# if os.path.exists("last_start.txt"):
# os.remove("last_start.txt")
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
with timeout(1, exception=RuntimeError):
logger.info("Pinging the server to check if it's online...")
s.connect((secrets.LOCAL_IP, 5555))
logger.info("Ping successful.")
pass
with timeout(5, exception=RuntimeError):
logger.info("Attempting to connect to the control server...")
zmq_socket.connect("tcp://" + secrets.LOCAL_IP + ":5555")
logger.info("Connected. Sending \"sleep\" command...")
zmq_socket.send_string("sleep")
pass
logger.info("Done. Waiting for response...")
response = zmq_socket.recv_string()
if response == "done":
logger.info("Received response. Waiting 20 seconds for server to sleep...")
time.sleep(20)
s_2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
with timeout(1, exception=RuntimeError):
logger.info("Pinging the server to check if it's online...")
s_2.connect((secrets.LOCAL_IP, 5555))
logger.info("Ping successful. The server could not be put to sleep")
zmq_socket.close()
zmq_context.term()
return {"result": "failed"}
except RuntimeError:
logger.info("No response within 1 second. Therefore server is off")
logger.info("The server is asleep 😴")
zmq_socket.close()
zmq_context.term()
return {"result": "done"}
s_2.close()
else:
logger.info("Received response: " + response)
logger.info("The server could not be put to sleep")
zmq_socket.close()
zmq_context.term()
return {"result": "failed"}
except RuntimeError:
logger.info("The server seems to be off already, you can turn it on with `!server start`")
zmq_socket.close()
zmq_context.term()
return {"result": "done"}
s.close()
except RuntimeError:
logger.info("The server could not be put to sleep")
zmq_socket.close()
zmq_context.term()
return {"result": "failed"}
zmq_socket.close()
zmq_context.term()
def status():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
with timeout(1, exception=RuntimeError):
logger.info("Pinging the server to check if it's online...")
sock.connect((secrets.LOCAL_IP, 5555))
logger.info("Ping successful. The server is on.")
pass
sock.close()
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
with timeout(1, exception=RuntimeError):
logger.info("Pinging the server to check if it's online...")
sock.connect((secrets.LOCAL_IP, 25565))
logger.info("Ping successful. The server is on.")
pass
ms = minestat.MineStat('tech189.duckdns.org', 25565)
ms1 = 'Online ✅\nVersion %s - %s out of %s players\nLatency: %sms\nPort: 25565' % (ms.version, ms.current_players, ms.max_players, ms.latency)
except RuntimeError:
ms1 = 'Offline'
sock.close()
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
with timeout(1, exception=RuntimeError):
logger.info("Pinging the server to check if it's online...")
sock.connect((secrets.LOCAL_IP, 25566))
logger.info("Ping successful. The server is on.")
pass
sock.close()
ms = minestat.MineStat('tech189.duckdns.org', 25566)
ms2 = 'Online ✅\nVersion %s - %s out of %s players\nLatency: %sms\nModpack: %s\nPort: 25566' % (ms.version, ms.current_players, ms.max_players, ms.latency, ms.motd.decode("utf-8"))
except RuntimeError:
ms2 = 'Offline'
zmq_context = zmq.Context()
zmq_socket = zmq_context.socket(zmq.REQ)
zmq_socket.setsockopt(zmq.LINGER, 0) # The default value is -1, which means wait until all messages have been sent before allowing termination. Set to 0 to discard unsent messages immediately, and any positive integer will be the number of milliseconds to keep trying to send before discard.
try:
with timeout(5, exception=RuntimeError):
logger.info("Attempting to connect to the control server...")
zmq_socket.connect("tcp://" + secrets.LOCAL_IP + ":5555")
logger.info("Connected. Sending \"stats\" command...")
zmq_socket.send_string("stats")
pass
logger.info("Done. Waiting for response...")
stats = ast.literal_eval(zmq_socket.recv_string())
except RuntimeError:
stats = {'cpu_temp': '???'}
return {"result": "Online ✅", "ms1": ms1, "ms2": ms2, "stats": stats}
except RuntimeError:
logger.info("No response within 1 second. Therefore server is off")
return {"result": "Offline", "ms1": 'Offline', "ms2": 'Offline', "stats": {'cpu_temp': '???'}}
sock.close()
if "--system_start" in sys.argv:
logger.info("COMMAND: system_start")
print(system_start())
elif "--system_sleep" in sys.argv:
logger.info("COMMAND: system_sleep")
print(system_sleep())
elif "--system_stop" in sys.argv:
logger.info("COMMAND: system_stop")
print(system_stop())
elif "--status" in sys.argv:
logger.info("COMMAND: status")
print(status())