forked from picoCTF/picoCTF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatus.py
263 lines (213 loc) · 8.21 KB
/
status.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
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
import json
import logging
import os
import shutil
import socket
from os.path import join
from hacksport.operations import execute
from shell_manager.util import (
BUNDLE_ROOT,
DEPLOYED_ROOT,
get_problem,
get_problem_root,
SHARED_ROOT,
PROBLEM_ROOT,
STAGING_ROOT,
get_pid_hash,
sanitize_name,
get_bundle,
get_bundle_root,
release_lock,
)
logger = logging.getLogger(__name__)
def get_all_problems():
""" Returns a dictionary of name-hash:object mappings """
problems = {}
if os.path.isdir(PROBLEM_ROOT):
for name in os.listdir(PROBLEM_ROOT):
try:
problem = get_problem(get_problem_root(name, absolute=True))
problems[name] = problem
except FileNotFoundError as e:
pass
return problems
def get_all_bundles():
""" Returns a dictionary of name:object mappings """
bundles = {}
if os.path.isdir(BUNDLE_ROOT):
for name in os.listdir(BUNDLE_ROOT):
try:
bundle = get_bundle(get_bundle_root(name, absolute=True))
bundles[name] = bundle
except FileNotFoundError as e:
pass
return bundles
def get_all_problem_instances(problem_name):
"""
Returns a list of instances for a given problem
Args:
problem_name: Sanitized problem name with hash.
"""
instances = []
instances_dir = join(DEPLOYED_ROOT, problem_name)
if os.path.isdir(instances_dir):
for name in os.listdir(instances_dir):
if name.endswith(".json"):
try:
instance = json.loads(open(join(instances_dir, name)).read())
except Exception as e:
continue
instances.append(instance)
return instances
def publish(args):
""" Main entrypoint for publish """
problems = get_all_problems()
bundles = get_all_bundles()
output = {"problems": [], "bundles": []}
for name_with_hash, problem in problems.items():
logger.debug("Finding instances of %s", name_with_hash)
problem["instances"] = get_all_problem_instances(name_with_hash)
problem["sanitized_name"] = sanitize_name(problem["name"])
problem["unique_name"] = name_with_hash
output["problems"].append(problem)
for _, bundle in bundles.items():
output["bundles"].append(bundle)
print(json.dumps(output, indent=2))
def clean(args):
""" Main entrypoint for clean """
# remove staging directories
if os.path.isdir(STAGING_ROOT):
logger.info("Removing the staging directories")
shutil.rmtree(STAGING_ROOT)
# remove lock file
release_lock()
def status(args):
""" Main entrypoint for status """
bundles = get_all_bundles()
problems = get_all_problems()
def get_instance_status(instance):
status = {
"instance_number": instance["instance_number"],
"port": instance["port"] if "port" in instance else None,
"flag": instance["flag"],
}
status["connection"] = False
if "port" in instance:
port = instance["port"]
try:
# XXX: assumes that the challenge is hosted locally
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", port))
s.close()
status["connection"] = True
except ConnectionRefusedError as e:
logger.debug(f"instance: {instance['instance_number']} has port: {port} but can't connect")
pass
if instance["service"]:
result = execute(
["systemctl", "is-failed", instance["service"]], allow_error=True
)
else:
result = execute(["systemctl", "is-failed"], allow_error=True)
status["service"] = result.return_code == 1
if status["port"] is not None and not status["connection"]:
status["service"] = False
return status
def get_problem_status(name_with_hash, problem):
problem_status = {
"name": problem["name"],
"unique_name": problem["unique_name"],
}
instances = get_all_problem_instances(name_with_hash)
instance_statuses = []
for instance in instances:
instance_statuses.append(get_instance_status(instance))
problem_status["instances"] = instance_statuses
return problem_status
def print_problem_status(problem, prefix=""):
def pprint(string):
print("{}{}".format(prefix, string))
pprint(
"* [{}] {} ({})".format(
len(problem["instances"]), problem["name"], problem["unique_name"]
)
)
if args.all:
for instance in problem["instances"]:
pprint(" - Instance {}".format(instance["instance_number"]))
pprint(" flag: {}".format(instance["flag"]))
pprint(" port: {}".format(instance["port"]))
pprint(
" service: {}".format(
"active" if instance["service"] else "failed"
)
)
pprint(
" connection: {}".format(
"online" if instance["connection"] else "offline"
)
)
def print_bundle(bundle, path, prefix=""):
def pprint(string):
print("{}{}".format(prefix, string))
pprint("* {} ({})".format(bundle["name"], path))
def get_bundle_status(bundle):
problem_statuses = []
for name_with_hash in bundle["problems"]:
problem = problems.get(name_with_hash)
problem_statuses.append(get_problem_status(name_with_hash, problem))
bundle["problems"] = problem_statuses
return bundle
if args.problem is not None:
problem = problems.get(args.problem, None)
if problem is None:
print('Could not find problem "{}"'.format(args.problem))
return
problem_status = get_problem_status(args.problem, problem)
if args.json:
print(json.dumps(problem_status, indent=4))
else:
print_problem_status(problem_status, prefix="")
elif args.bundle is not None:
bundle = bundles.get(args.bundle, None)
if bundle is None:
print('Could not find bundle "{}"'.format(args.bundle))
return
if args.json:
print(json.dumps(get_bundle_status(bundle), indent=4))
else:
print_bundle(bundle, args.bundle, prefix="")
else:
return_code = 0
if args.json:
result = {
"bundles": bundles,
"problems": list(
map(lambda tup: get_problem_status(*tup), problems.items())
),
}
print(json.dumps(result, indent=4))
elif args.errors_only:
for path, problem in problems.items():
problem_status = get_problem_status(path, problem)
# Determine if any problem instance is offline
for instance_status in problem_status["instances"]:
if not instance_status["service"]:
print_problem_status(problem_status, prefix=" ")
return_code = 1
else:
print("** Installed Bundles [{}] **".format(len(bundles)))
shown_problems = []
for path, bundle in bundles.items():
print_bundle(bundle, path, prefix=" ")
print("** Installed Problems [{}] **".format(len(problems)))
for path, problem in problems.items():
problem_status = get_problem_status(path, problem)
# Determine if any problem instance is offline
for instance_status in problem_status["instances"]:
if not instance_status["service"]:
return_code = 1
print_problem_status(problem_status, prefix=" ")
if return_code != 0:
print("WARNING: Some instances offline. Run with -e to see failing instances")
exit(return_code)