-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcore.py
594 lines (434 loc) · 20.7 KB
/
core.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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
##############################
# Crawling@Home Client #
# (c) Theo Coombes, 2021 #
# TheoCoombes/crawlingathome #
##############################
from requests import session, Response
from typing import Optional, Union
from time import sleep
import numpy as np
import logging
import tarfile
import shutil
import gzip
import os
from .errors import *
logging.basicConfig(format="[%(asctime)s crawling@home] %(message)s", datefmt="%H:%M", level=logging.INFO)
_builtin_print = print
def print(message) -> None:
logging.info(message)
def _safe_request(function, *args, **kwargs) -> Response:
try:
return function(*args, **kwargs)
except Exception as e:
print(f"retrying request after {e} error...")
sleep(60)
return _safe_request(function, *args, **kwargs)
def _handle_exceptions(status_code: int, text: str) -> Optional[Exception]:
if status_code == 200:
return None
elif status_code == 400:
return ValueError(f"[crawling@home] {text} (status {status_code})")
elif status_code == 403:
return ZeroJobError(f"[crawling@home] {text} (status {status_code})")
elif status_code == 404:
return WorkerTimedOutError(f"[crawling@home] {text} (status {status_code})")
else:
return ServerError(f"[crawling@home] {text} (status {status_code})")
# The main 'hybrid' client instance.
class HybridClient:
def __init__(self, url, nickname, _recycled=False) -> None:
if _recycled:
return
if url[-1] != "/":
url += "/"
self.s = session()
self.url = url
self.type = "HYBRID"
self.nickname = nickname
print("connecting to crawling@home server...")
payload = {"nickname": nickname, "type": "HYBRID"}
r = _safe_request(self.s.get, self.url + "api/new", params=payload)
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
print("connected to crawling@home server")
data = r.json()
self.token = data["token"]
self.display_name = data["display_name"]
self.upload_address = data["upload_address"]
print(f"worker name: {self.display_name}")
_builtin_print("\n\n")
print(f"You can view this worker's progress at {self.url + 'worker/hybrid/' + self.display_name}\n")
# Finds the amount of available jobs from the server, returning an integer.
def updateUploadServer(self) -> None:
r = _safe_request(self.s.get, self.url + "api/getUploadAddress", params={"type": "HYBRID"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
self.upload_address = r.text
print("updated upload server address")
# Updates the upload server.
def jobCount(self) -> int:
r = _safe_request(self.s.get, self.url + "api/jobCount", params={"type": "HYBRID"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
count = int(r.text)
print(f"jobs remaining: {count}")
return count
# Makes the node send a request to the server, asking for a new job.
def newJob(self) -> None:
print("looking for new job...")
r = _safe_request(self.s.post, self.url + "api/newJob", json={"token": self.token, "type": "HYBRID"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
else:
data = r.json()
self.shard = data["url"]
self.start_id = np.int64(data["start_id"])
self.end_id = np.int64(data["end_id"])
self.shard_piece = data["shard"]
print("recieved new job")
# Downloads the current job's shard to the current directory (./shard.wat)
def downloadShard(self, path="") -> None:
print("downloading shard...")
self.log("Downloading shard", noprint=True)
with self.s.get(self.shard, stream=True) as r:
r.raise_for_status()
with open(path + "temp.gz", 'w+b') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
with gzip.open(path + 'temp.gz', 'rb') as f_in:
with open(path + 'shard.wat', 'w+b') as f_out:
shutil.copyfileobj(f_in, f_out)
sleep(1) # Causes errors otherwise?
os.remove(path + "temp.gz")
self.log("Downloaded shard", noprint=True)
print("finished downloading shard")
# Marks a job as completed/done.
def completeJob(self, total_scraped : int) -> None:
r = _safe_request(self.s.post, self.url + "api/markAsDone", json={"token": self.token, "count": total_scraped, "type": "HYBRID"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
print("marked job as done")
# Wrapper for `completeJob` (for older workers)
def _markjobasdone(self, total_scraped : int) -> None:
print("WARNING: avoid using `_markjobasdone(...)` and instead use `completeJob(...)` to mark a job as done.")
self.completeJob(total_scraped)
# Logs the string progress into the server.
def log(self, progress : str, crashed=False, noprint=False) -> None:
data = {"token": self.token, "progress": progress, "type": "HYBRID"}
r = _safe_request(self.s.post, self.url + "api/updateProgress", json=data)
exc = _handle_exceptions(r.status_code, r.text)
if exc and not crashed:
self.log("Crashed", crashed=True)
raise exc
if not crashed and not noprint:
print(f"logged new progress data: {progress}")
# Client wrapper for `recycler.dump`.
def dump(self) -> dict:
from .recycler import dump as _dump
return _dump(self)
def recreate(self) -> None:
print("recreating client instance...")
new = HybridClient(self.url, self.nickname)
self.token = new.token
self.display_name = new.display_name
self.upload_address = new.upload_address
# Returns True if the worker is still alive, otherwise returns False.
def isAlive(self) -> bool:
r = _safe_request(self.s.post, self.url + "api/validateWorker", json={"token": self.token, "type": "HYBRID"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
else:
return ("True" in r.text)
# Removes the node instance from the server, ending all current jobs.
def bye(self) -> None:
_safe_request(self.s.post, self.url + "api/bye", json={"token": self.token, "type": "HYBRID"})
print("closed worker")
# The CPU client instance.
# Programatically similar to `HybridClient`, with different completion functions.
class CPUClient:
def __init__(self, url, nickname, _recycled=False) -> None:
if _recycled:
return
if url[-1] != "/":
url += "/"
self.s = session()
self.url = url
self.type = "CPU"
self.nickname = nickname
print("connecting to crawling@home server...")
payload = {"nickname": nickname, "type": "CPU"}
r = _safe_request(self.s.get, self.url + "api/new", params=payload)
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
print("connected to crawling@home server")
data = r.json()
self.token = data["token"]
self.display_name = data["display_name"]
self.upload_address = data["upload_address"]
print(f"worker name: {self.display_name}")
_builtin_print("\n\n")
print(f"You can view this worker's progress at {self.url + 'worker/cpu/' + self.display_name}\n")
# Finds the amount of available jobs from the server, returning an integer.
def updateUploadServer(self) -> None:
r = _safe_request(self.s.get, self.url + "api/getUploadAddress", params={"type": "CPU"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
self.upload_address = r.text
print("updated upload server address")
# Finds the amount of available jobs from the server, returning an integer.
def jobCount(self) -> int:
r = _safe_request(self.s.get, self.url + "api/jobCount", params={"type": "CPU"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
count = int(r.text)
print(f"jobs remaining: {count}")
return count
# Makes the node send a request to the server, asking for a new job.
def newJob(self) -> None:
print("looking for new job...")
r = _safe_request(self.s.post, self.url + "api/newJob", json={"token": self.token, "type": "CPU"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
else:
data = r.json()
self.shard = data["url"]
self.start_id = np.int64(data["start_id"])
self.end_id = np.int64(data["end_id"])
self.shard_piece = data["shard"]
print("recieved new job")
# Downloads the current job's shard to the current directory (./shard.wat)
def downloadShard(self, path="") -> None:
print("downloading shard...")
self.log("Downloading shard", noprint=True)
with self.s.get(self.shard, stream=True) as r:
r.raise_for_status()
with open(path + "temp.gz", 'w+b') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
with gzip.open(path + 'temp.gz', 'rb') as f_in:
with open(path + 'shard.wat', 'w+b') as f_out:
shutil.copyfileobj(f_in, f_out)
sleep(1) # Causes errors otherwise?
os.remove(path + "temp.gz")
self.log("Downloaded shard", noprint=True)
print("finished downloading shard")
# Uploads the image download URL for the GPU workers to use, marking the CPU job complete.
def completeJob(self, image_download_url : str) -> None:
r = _safe_request(self.s.post, self.url + "api/markAsDone", json={
"token": self.token,
"url": image_download_url,
"type": "CPU"
})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
print("marked job as done")
# Logs the string progress into the server.
def log(self, progress : str, crashed=False, noprint=False) -> None:
data = {"token": self.token, "progress": progress, "type": "CPU"}
r = _safe_request(self.s.post, self.url + "api/updateProgress", json=data)
exc = _handle_exceptions(r.status_code, r.text)
if exc and not crashed:
self.log("Crashed", crashed=True)
raise exc
if not crashed and not noprint:
print(f"logged new progress data: {progress}")
# Client wrapper for `recycler.dump`.
def dump(self) -> dict:
from .recycler import dump as _dump
return _dump(self)
# Recreates the client with the server, giving the client a new auth token, upload server and display name.
def recreate(self) -> None:
print("recreating client instance...")
new = CPUClient(self.url, self.nickname)
self.token = new.token
self.display_name = new.display_name
self.upload_address = new.upload_address
# Returns True if the worker is still alive, otherwise returns False.
def isAlive(self) -> bool:
r = _safe_request(self.s.post, self.url + "api/validateWorker", json={"token": self.token, "type": "CPU"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
else:
return ("True" in r.text)
# Removes the node instance from the server, ending all current jobs.
def bye(self) -> None:
_safe_request(self.s.post, self.url + "api/bye", json={"token": self.token, "type": "CPU"})
print("closed worker")
# The GPU client instance.
class GPUClient:
def __init__(self, url, nickname, _recycled=False) -> None:
if _recycled:
return
if url[-1] != "/":
url += "/"
self.s = session()
self.url = url
self.type = "GPU"
self.nickname = nickname
print("connecting to crawling@home server...")
payload = {"nickname": nickname, "type": "GPU"}
r = _safe_request(self.s.get, self.url + "api/new", params=payload)
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
print("connected to crawling@home server")
data = r.json()
self.token = data["token"]
self.display_name = data["display_name"]
self.upload_address = data["upload_address"]
print(f"worker name: {self.display_name}")
_builtin_print("\n\n")
print(f"You can view this worker's progress at {self.url + 'worker/gpu/' + self.display_name}\n")
# Finds the amount of available jobs from the server, returning an integer.
def updateUploadServer(self) -> None:
r = _safe_request(self.s.get, self.url + "api/getUploadAddress", params={"type": "GPU"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
self.upload_address = r.text
print("updated upload server address")
# Finds the amount of available jobs from the server, returning an integer.
def jobCount(self) -> int:
r = _safe_request(self.s.get, self.url + "api/jobCount", params={"type": "GPU"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
count = int(r.text)
print(f"GPU jobs remaining: {count}")
return count
# Makes the node send a request to the server, asking for a new job.
def newJob(self) -> None:
print("looking for new job...")
r = _safe_request(self.s.post, self.url + "api/newJob", json={"token": self.token, "type": "GPU"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
else:
data = r.json()
self.shard = data["url"]
self.start_id = np.int64(data["start_id"])
self.end_id = np.int64(data["end_id"])
self.shard_piece = data["shard"]
print("recieved new job")
# Flags a GPU job's URL as invalid to the server.
def invalidURL(self) -> None:
r = _safe_request(self.s.post, self.url + "api/gpuInvalidDownload", json={"token": self.token, "type": "GPU"})
if r.status_code != 200:
print("something went wrong when flagging a URL as invalid - not raising error.")
else:
print("successfully flagged url as invalid")
raise InvalidURLError('[crawling@home] Invalid URL')
# Downloads the CPU worker's processed images to the ./images/ (`path`) directory
def downloadShard(self, path="") -> None:
print("downloading shard...")
self.log("Downloading shard", noprint=True)
if self.shard.startswith('http'):
with self.s.get(self.shard, stream=True) as r:
r.raise_for_status()
with open(path + "temp.gz", 'w+b') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
with gzip.open(path + 'temp.gz', 'rb') as f_in:
with open(path + 'shard.wat', 'w+b') as f_out:
shutil.copyfileobj(f_in, f_out)
sleep(1) # Causes errors otherwise?
os.remove(path + "temp.gz")
elif self.shard.startswith('rsync'):
uid = self.shard.split('rsync', 1)[-1].strip()
resp = 1
for _ in range(5):
resp = os.system(f'rsync -av [email protected]::gpujobs/{uid}.tar.gz {uid}.tar.gz')
if resp == 5888:
print('[crawling@home] rsync job not found')
self.invalidURL()
if resp == 0:
with tarfile.open(f"{uid}.tar.gz", "r:gz") as tar:
tar.extractall()
break
else:
self.invalidURL()
self.log("Downloaded shard", noprint=True)
print("finished downloading shard")
# Uploads the image download URL for the GPU workers to use, marking the CPU job complete.
def completeJob(self, total_scraped : int) -> None:
r = _safe_request(self.s.post, self.url + "api/markAsDone", json={"token": self.token, "count": total_scraped, "type": "GPU"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
print("marked job as done")
# Logs the string progress into the server.
def log(self, progress : str, crashed=False, noprint=False) -> None:
data = {"token": self.token, "progress": progress, "type": "GPU"}
r = _safe_request(self.s.post, self.url + "api/updateProgress", json=data)
exc = _handle_exceptions(r.status_code, r.text)
if exc and not crashed:
self.log("Crashed", crashed=True)
raise exc
if not crashed and not noprint:
print(f"logged new progress data: {progress}")
# Client wrapper for `recycler.dump`.
def dump(self) -> dict:
from .recycler import dump as _dump
return _dump(self)
# Recreates the client with the server, giving the client a new auth token, upload server and display name.
def recreate(self) -> None:
print("recreating client instance...")
new = GPUClient(self.url, self.nickname)
self.token = new.token
self.display_name = new.display_name
self.upload_address = new.upload_address
# Returns True if the worker is still alive, otherwise returns False.
def isAlive(self) -> bool:
r = _safe_request(self.s.post, self.url + "api/validateWorker", json={"token": self.token, "type": "GPU"})
exc = _handle_exceptions(r.status_code, r.text)
if exc:
self.log("Crashed", crashed=True)
raise exc
else:
return ("True" in r.text)
# Removes the node instance from the server, ending all current jobs.
def bye(self) -> None:
_safe_request(self.s.post, self.url + "api/bye", json={"token": self.token, "type": "GPU"})
print("closed worker")
# Creates and returns a new client instance.
def init(url="http://crawlingathome.duckdns.org/", nickname="anonymous", type="Hybrid") -> Optional[Union[HybridClient, CPUClient, GPUClient]]:
if isinstance(type, str):
type = type.lower()[0]
if type == "h" or type == HybridClient:
return HybridClient(url, nickname)
elif type == "c" or type == CPUClient:
return CPUClient(url, nickname)
elif type == "g" or type == GPUClient:
return GPUClient(url, nickname)
else:
raise ValueError(f"[crawling@home] invalid worker `{type}`")