-
Notifications
You must be signed in to change notification settings - Fork 5
/
basilico.py
executable file
·1602 lines (1379 loc) · 57.7 KB
/
basilico.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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import json
import subprocess
import stat
import os
import sys
import time
from collections import deque
from typing import Optional, Callable, Dict, Set, List
from pytarallo import Tarallo, Errors
from dotenv import load_dotenv
from io import StringIO
from pytarallo.Errors import ValidationError, NotAuthorizedError
from pytarallo.ItemToUpload import ItemToUpload
from twisted.internet import reactor, protocol
from twisted.protocols.basic import LineOnlyReceiver
import threading
import logging
from datetime import datetime
from read_smartctl import extract_smart_data, smart_health_status, parse_single_disk
NAME = "basilico"
# Use env vars, do not change the value here
TEST_MODE = False
class Disk:
def __init__(self, lsblk, tarallo: Optional[Tarallo.Tarallo]):
self._lsblk = lsblk
if "path" not in self._lsblk:
raise RuntimeError("lsblk did not provide path for this disk: " + self._lsblk)
self._path = str(self._lsblk["path"])
self._mountpoint_map = self._lsblk["mountpoint_map"]
del self._lsblk["mountpoint_map"]
self._composite_id = Disk.make_composite_id(self._lsblk)
self._code = None
self._item = None
self._update_lock = threading.Lock()
self._queue_lock = threading.Lock()
self._commands_queue = deque()
self._tarallo = tarallo
self._get_code(False)
self._get_item()
def update_mountpoints(self):
with self._update_lock:
# lsblk 2 is like Despacito 2
lsblk2 = get_disks(self._path)
for one_disk in lsblk2:
if one_disk.get("path") == self._path:
self._lsblk["mountpoint"] = one_disk.get("mountpoint", [])
self._mountpoint_map = one_disk.get("mountpoint_map", {})
# This is not copied over again
# if "mountpoint_map" in self._lsblk:
# del self._lsblk["mountpoint_map"]
break
def get_mountpoints_map(self) -> dict:
# Probably pointless lock
with self._update_lock:
return self._mountpoint_map
@staticmethod
def make_composite_id(lsblk: dict):
return lsblk.get("path"), lsblk.get("wwn"), lsblk.get("serial")
def compare_composite_id(self, lsblk_other: dict):
return self._composite_id == self.make_composite_id(lsblk_other)
def queue_is_empty(self):
with self._queue_lock:
return len(self._commands_queue) == 0
def enqueue(self, cmd_runner):
cmd_runner: CommandRunner
with self._queue_lock:
self._commands_queue.append(cmd_runner)
if len(self._commands_queue) == 1:
cmd_runner.start()
def dequeue(self, cmd_runner):
cmd_runner: CommandRunner
with self._queue_lock:
try:
self._commands_queue.remove(cmd_runner)
except ValueError:
# TODO: This could be a return
pass
if len(self._commands_queue) > 0:
next_in_line: CommandRunner = self._commands_queue[0]
if not next_in_line.is_alive():
next_in_line.start()
else:
if cmd_runner.get_cmd() != "queued_sleep":
cmd_runner._call_hdparm_for_sleep(self._path)
def get_path(self):
return self._path
def update_from_tarallo_if_needed(self) -> bool:
changes = False
if not self._code:
old_code = self._code
self._get_code(True)
changes = self._code == old_code
self._get_item()
return changes
def serialize_disk(self):
result = self._lsblk
result["code"] = self._code
critical = False
if not TEST_MODE:
for mountpoint in self._lsblk["mountpoint"]:
if mountpoint != "[SWAP]":
critical = True
break
result["has_critical_mounts"] = critical
return result
def update_status(self, status: str) -> bool:
if self._tarallo and self._code:
self._tarallo.update_item_features(self._code, {"smart-data": status})
return True
return False
def update_erase(self, erased: bool, all_blocks_ok: Optional[bool]) -> bool:
if self._tarallo and self._code:
data = {}
# Can be True, False or None
if all_blocks_ok is not None:
data["surface-scan"] = "pass" if all_blocks_ok else "fail"
if erased:
data["data-erased"] = "yes"
data["software"] = None
if len(data) > 0:
self._tarallo.update_item_features(self._code, data)
return True
return False
def update_software(self, software: str) -> bool:
if self._tarallo and self._code:
data = {"software": software}
self._tarallo.update_item_features(self._code, data)
return True
return False
def _get_code(self, stop_on_error: bool = True):
if not self._tarallo:
if TEST_MODE:
import binascii
num = binascii.crc32(self._path.encode("utf-8")) % 300
if num % 2:
self._code = "H" + str(num)
else:
self._code = None
else:
self._code = None
return
if "serial" not in self._lsblk:
self._code = None
if stop_on_error:
raise ErrorThatCanBeManuallyFixed(f"Disk {self._path} has no serial number")
sn = self._lsblk["serial"]
sn: str
if sn and sn.startswith("WD-"):
sn = sn[3:]
try:
codes = self._tarallo.get_codes_by_feature("sn", sn)
if len(codes) <= 0:
self._code = None
logging.debug(f"Disk {sn} not found in tarallo")
elif len(codes) == 1:
self._code = codes[0]
logging.debug(f"Disk {sn} found as {self._code}")
else:
self._code = None
if stop_on_error:
raise ErrorThatCanBeManuallyFixed(f"Duplicate codes for {self._path}: {' '.join(codes)}, S/N is {sn}")
except Errors.NoInternetConnectionError:
self._code = None
if stop_on_error:
raise ErrorThatCanBeManuallyFixed(f"Tarallo lookup for disk with S/N {sn} failed due to a connection error")
except Errors.ServerError:
self._code = None
if stop_on_error:
raise ErrorThatCanBeManuallyFixed(f"Tarallo lookup for disk with S/N {sn} failed due to server error, try again later")
except Errors.AuthenticationError:
self._code = None
if stop_on_error:
raise ErrorThatCanBeManuallyFixed(f"Tarallo lookup for disk with S/N {sn} failed due to authentication error, check the token")
except (Errors.ValidationError, RuntimeError) as e:
self._code = None
logging.warning(f"Tarallo lookup failed unexpectedly for disk with S/N {sn}", exc_info=e)
if stop_on_error:
raise ErrorThatCanBeManuallyFixed(f"Tarallo lookup for disk with S/N {sn} failed, more info has been logged on the server")
def _get_item(self):
if self._tarallo and self._code:
# Nothing to do, only the code is used at the moment. Add a try-except if you uncomment.
# self._item = self._tarallo.get_item(self._code, 0)
pass
else:
self._item = None
def create_on_tarallo(self, features: dict, loc: str = None) -> Optional[str]:
# TODO: does this need any lock?
# with self._update_lock:
if self._tarallo:
disk = ItemToUpload()
for f, v in features.items():
disk.features[f] = v
disk.set_parent(loc)
success = self._tarallo.add_item(disk)
if success and isinstance(disk.code, str) and disk.code != "":
return disk.code
# success = self._tarallo.bulk_add(disk.serializable())
return None
def set_code(self, code: str):
self._code = code
class SudoSessionKeeper(threading.Thread):
def run(self):
while True:
process = subprocess.run(["sudo", "-nv"])
threading.Event().wait(241)
class ErrorThatCanBeManuallyFixed(Exception):
pass
class CommandRunner(threading.Thread):
def __init__(self, cmd: str, args: str, the_id: int):
threading.Thread.__init__(self)
self._cmd = cmd
self._args = args
self._the_id = the_id
self._go = True
self._queued_command = None
self._function, disk_for_queue = self.dispatch_command(cmd, args)
if not self._function:
self.send_msg("error", {"message": "Unrecognized command", "command": cmd})
self._function = None
return
self._queued_command = None
if disk_for_queue is not None: # Empty string must enter this branch
# No need to lock, disks are never deleted, so if it is found then it is valid
disk = disks.get(disk_for_queue, None)
if not disk:
self.send_msg("error", {"message": f"{args} is not a disk"})
self._function = None
return
# Do not start yet, just prepare the data structure
self._queued_command = QueuedCommand(disk, self)
# And enqueue, which will start it when needed
with queued_commands_lock:
disk.enqueue(self)
else:
# Start immediately
self.start()
# noinspection PyUnresolvedReferences
def started(self) -> bool:
return self._started.is_set()
def get_cmd(self):
return self._cmd
def get_queued_command(self):
return self._queued_command
def run(self):
try:
# Stop immediately if nothing was dispatched
if not self._function:
self._queued_command.notify_error("Unknown command")
self._queued_command.delete_when_done()
return
# Also stop if program is terminating
if not self._go:
return
# Otherwise, lessss goooooo!
with running_commands_lock:
running_commands.add(self)
try:
self._function(self._cmd, self._args)
except Exception as e:
logging.error(f"[{self._the_id}] BIG ERROR in command thread", exc_info=e)
finally:
# The next thread on the disk can start, if there's a queue
if self._queued_command:
# Notify finish only if not already notified, as a catch all for errors
# that may prevent the actual function from notifying
self._queued_command.notify_finish_safe()
self._queued_command.disk.dequeue(self)
# Not running anymore (in a few nanoseconds, anyway)
with running_commands_lock:
try:
# If the thread was never started (not self._go and similar), it won't be there
running_commands.remove(self)
except KeyError:
pass
def stop_asap(self):
# This is completely pointless unless the command checks self._go
# (none of them does, for now)
self._go = False
def dispatch_command(self, cmd: str, args: str) -> (Optional[Callable[[str, str], None]], Optional[str]):
commands = {
"sudo_password": self.sudo_password,
"smartctl": self.get_smartctl,
"queued_smartctl": self.queued_get_smartctl,
"queued_badblocks": self.badblocks,
"queued_cannolo": self.cannolo,
"queued_sleep": self.sleep,
"queued_umount": self.umount,
"upload_to_tarallo": self.upload_to_tarallo,
"queued_upload_to_tarallo": self.queued_upload_to_tarallo,
"get_disks": self.get_disks,
"ping": self.ping,
"close_at_end": self.close_at_end,
"get_queue": self.get_queue,
"remove": self.remove_one_from_queue,
"remove_all": self.remove_all_from_queue,
"remove_completed": self.remove_all_from_queue,
"remove_queued": self.remove_all_from_queue,
"list_iso": self.list_iso,
"stop": self.stop_process,
}
logging.debug(f"[{self._the_id}] Received command {cmd}{' with args' if len(args) > 0 else ''}")
if cmd.startswith("queued_"):
disk_for_queue = self.dev_from_args(args)
else:
disk_for_queue = None
return commands.get(cmd.lower(), None), disk_for_queue
# noinspection PyUnusedLocal
def get_queue(self, cmd: str, args: str):
param = []
with queued_commands_lock:
for queued_command in queued_commands:
queued_command.lock_notifications()
param.append(queued_command.serialize_me())
self.send_msg(cmd, param)
for queued_command in queued_commands:
queued_command.unlock_notifications()
@staticmethod
def dev_from_args(args: str):
# This may be more complicated for some future commands
return args.split(" ", 1)[0]
def list_iso(self, cmd: str, iso_dir: str):
files = []
try:
for file in os.listdir(iso_dir):
if file.startswith("."):
continue
files.append(os.path.join(iso_dir, file))
except FileNotFoundError:
self.send_msg(
"error",
{"message": f"ISO directory {iso_dir} does not exist on server"},
)
return
except NotADirectoryError:
self.send_msg(
"error",
{"message": f"Cannot read {iso_dir} on server: is not a directory"},
)
return
except PermissionError:
self.send_msg(
"error",
{"message": f"Cannot read {iso_dir} on server: permission denied"},
)
return
except Exception as e:
self.send_msg(
"error",
{"message": f"Cannot list files in iso dir {iso_dir}: {str(e)}"},
)
return
self.send_msg(cmd, files)
# noinspection PyMethodMayBeStatic
def remove_all_from_queue(self, cmd: str, _unused: str):
remove_completed = False
remove_scheduled = False
if cmd == "remove_completed":
remove_completed = True
elif cmd == "remove_queued":
remove_scheduled = True
else:
remove_completed = True
remove_scheduled = True
logging.debug(f"remove_completed = {remove_completed}, remove_scheduled = {remove_scheduled}")
with queued_commands_lock:
with running_commands_lock:
commands_to_remove = []
for the_command in queued_commands:
if the_command.command_runner.started():
if not the_command.command_runner.is_alive():
if remove_completed:
commands_to_remove.append(the_command)
else:
if remove_scheduled:
commands_to_remove.append(the_command)
for the_command in commands_to_remove:
queued_commands.remove(the_command)
logging.debug(f"Removed {len(commands_to_remove)} items from tasks list")
return None
# noinspection PyMethodMayBeStatic
def remove_one_from_queue(self, _cmd: str, queue_id: str):
for the_cmd in queued_commands:
if the_cmd.id_is(queue_id):
the_cmd.delete_when_done()
break
return None
def badblocks(self, _cmd: str, dev: str):
go_ahead = self._unswap()
if not go_ahead:
return
self._queued_command.notify_start("Running badblocks")
if TEST_MODE:
final_message = ""
for progress in range(0, 100, 10):
if self._go:
self._queued_command.notify_percentage(progress, f"{progress/10} errors")
threading.Event().wait(2)
else:
final_message = "Process interrupted by user."
if progress == 100:
final_message = f"Finished with {progress/10} errors!"
completed = True
all_ok = False
else:
custom_env = os.environ.copy()
custom_env["LC_ALL"] = "C"
pipe = subprocess.Popen(
(
"sudo",
"-n",
"badblocks",
"-w",
"-s",
"-p",
"0",
"-t",
"0x00",
"-b",
"4096",
dev,
),
stderr=subprocess.PIPE,
env=custom_env,
) # , stdout=subprocess.PIPE)
percent = 0.0
reading_and_comparing = False
errors = -1
deleting = False
buffer = bytearray()
for char in iter(lambda: pipe.stderr.read(1), b""):
if not self._go:
pipe.kill()
pipe.wait()
print(f"Killed badblocks process {self.get_queued_command().id()}")
self._queued_command.notify_finish_with_error("Process terminated by user.")
return
if char == b"":
if pipe.poll() is not None:
break
elif char == b"\b":
if not deleting:
result = buffer.decode("utf-8")
errors_print = "?"
reading_and_comparing = reading_and_comparing or ("Reading and comparing" in result)
# If other messages are printed, ignore them
i = result.index("% done")
if i >= 0:
# /2 due to the 0x00 test + read & compare
percent = float(result[i - 6 : i]) / 2
if reading_and_comparing:
percent += 50
i = result.index("(", i)
if i >= 0:
# errors_str = result[i+1:].split(")", 1)[0]
errors_str = result[i + 1 :].split(" ", 1)[0]
# The errors are read, write and corruption
errors_str = errors_str.split("/")
errors = 0 # badblocks prints the 3 totals every time
for error in errors_str:
errors += int(error)
errors_print = str(errors)
self._queued_command.notify_percentage(percent, f"{errors_print} errors")
buffer.clear()
deleting = True
# elif char == b'\n':
# # Skip the first lines (total number of blocks)
# buffer.clear()
else:
if deleting:
deleting = False
buffer += char
# TODO: was this needed? Why were we doing it twice?
# pipe.wait()
exitcode = pipe.wait()
if errors <= -1:
all_ok = None
errors_print = "an unknown amount of"
elif errors == 0:
all_ok = True
errors_print = "no"
else:
all_ok = False
errors_print = str(errors)
final_message = f"Finished with {errors_print} errors"
if exitcode == 0:
# self._queued_command.notify_finish(final_message)
completed = True
else:
self._queued_command.notify_error()
final_message += f" and badblocks exited with status {exitcode}"
# self._queued_command.notify_finish(final_message)
completed = False
# print(pipe.stdout.readline().decode('utf-8'))
# print(pipe.stderr.readline().decode('utf-8'))
with disks_lock:
update_disks_if_needed(self)
disk_ref = disks[dev]
# noinspection PyBroadException
try:
disk_ref.update_erase(completed, all_ok)
except Exception as e:
final_message = f"Error during upload. {final_message}"
self._queued_command.notify_error(final_message)
logging.warning(
f"[{self._the_id}] Can't update badblocks results of {dev} on tarallo",
exc_info=e,
)
self._queued_command.notify_finish(final_message)
def ping(self, _cmd: str, _nothing: str):
self.send_msg("pong", None)
# noinspection PyMethodMayBeStatic
def close_at_end(self, _cmd: str, _nothing: str):
logging.info("Server will close at end")
with CLOSE_AT_END_LOCK:
global CLOSE_AT_END
# Do not start the timer twice
if CLOSE_AT_END:
return
CLOSE_AT_END = True
# noinspection PyUnresolvedReferences
reactor.callFromThread(reactor.callLater, CLOSE_AT_END_TIMER, try_stop_at_end)
@staticmethod
def _get_last_linux_partition_path_and_number(dev: str) -> tuple[str, str] | tuple[None, None]:
# Use PTTYPE to get MBR/GPT (dos/gpt are the possible values)
# PARTTYPENAME could be useful, too
exitcode, output = subprocess.getstatusoutput(f"lsblk -o PATH,PARTTYPE,PARTN -J {dev}")
if exitcode != 0:
exitcode, output = subprocess.getstatusoutput(f"lsblk -o PATH,PARTTYPE -J {dev}")
if exitcode != 0:
raise Exception(f"Error while running lsblk on {dev}")
jsonized = json.loads(output)
return CommandRunner._get_last_linux_partition_path_and_number_from_lsblk(jsonized)
@staticmethod
def _get_last_linux_partition_path_and_number_from_lsblk(lsblk_json: dict) -> tuple[str, str] | tuple[None, None]:
last_linux_entry = (None, None)
for i, entry in enumerate(lsblk_json["blockdevices"]):
if entry["path"]: # lsblk also returns the device itself, which has no partitions
# GPT or MBR Linux partition ID
if entry["parttype"] == "0fc63daf-8483-4772-8e79-3d69d8477de4" or entry["parttype"] == "0x83":
last_linux_entry = entry["path"], (entry["partn"] if "partn" in entry else i)
return last_linux_entry
def cannolo(self, _cmd: str, dev_and_iso: str):
parts: list[Optional[str]] = dev_and_iso.split(" ", 1)
while len(parts) < 2:
parts.append(None)
dev, iso = parts
if iso is None:
self._queued_command.notify_finish_with_error(f"No iso selected")
return
if not os.path.exists(iso):
self._queued_command.notify_finish_with_error(f"File {iso} does not exist")
return
if not os.path.isfile(iso):
self._queued_command.notify_finish_with_error(f"{iso} is not a file (is it a directory?)")
return
go_ahead = self._unswap()
if not go_ahead:
return
success = True
self._queued_command.notify_start("Cannoling")
if TEST_MODE:
self._queued_command.notify_percentage(10)
threading.Event().wait(2)
self._queued_command.notify_percentage(20)
threading.Event().wait(2)
self._queued_command.notify_percentage(30)
threading.Event().wait(2)
self._queued_command.notify_percentage(40)
threading.Event().wait(2)
self._queued_command.notify_percentage(50)
threading.Event().wait(2)
self._queued_command.notify_percentage(60)
threading.Event().wait(2)
self._queued_command.notify_percentage(70)
threading.Event().wait(2)
self._queued_command.notify_percentage(80)
threading.Event().wait(2)
self._queued_command.notify_percentage(90)
threading.Event().wait(2)
else:
success = self.dd(iso, dev)
if success:
logging.debug(f"{dev = }")
part_path, part_number = self._get_last_linux_partition_path_and_number(dev)
success = run_command_on_partition(dev, f"sudo growpart {dev} {part_number}")
if success:
success = run_command_on_partition(dev, f"sudo e2fsck -fy {part_path}")
if success:
success = run_command_on_partition(dev, f"sudo resize2fs {part_path}")
if success:
pass
else:
self._queued_command.notify_error(f"resize2fs failed")
else:
self._queued_command.notify_error(f"e2fsck failed")
else:
self._queued_command.notify_error(f"growpart failed")
else:
self._queued_command.notify_error(f"Disk imaging failed")
if success:
with disks_lock:
update_disks_if_needed(self)
disk_ref = disks[dev]
pretty_iso = self._pretty_print_iso(iso)
self._queued_command.notify_percentage(100.0, f"{pretty_iso} installed!")
final_message = f"{pretty_iso} installed, Tarallo updated"
# noinspection PyBroadException
try:
disk_ref.update_software(pretty_iso)
except Exception as e:
final_message = f"{pretty_iso} installed, failed to update Tarallo"
self._queued_command.notify_error(f"{pretty_iso} installed, failed to update Tarallo")
logging.warning(
f"[{self._the_id}] Can't update software of {dev} on tarallo",
exc_info=e,
)
self._queued_command.notify_finish(final_message)
else:
self._queued_command.notify_finish()
def umount(self, _cmd: str, dev: str):
self._queued_command.notify_start("Calling umount")
success = self._umount_internal(dev)
self._queued_command.disk.update_mountpoints()
if success:
self._queued_command.notify_finish(f"Disk {dev} umounted")
else:
self._queued_command.notify_finish_with_error(f"umount failed")
def _umount_internal(self, dev):
try:
result = subprocess.run(["lsblk", "-J", dev], capture_output=True, text=True)
if result.returncode != 0:
return False
lsblk_output = json.loads(result.stdout)
partitions_to_unmount = []
blockdevices = lsblk_output.get("blockdevices", [])
for device in blockdevices:
if "children" in device:
for partition in device["children"]:
if "mountpoints" in partition and len(partition["mountpoints"]) > 0:
partitions_to_unmount.append(f"/dev/{partition['name']}")
break
if not partitions_to_unmount:
return True
for partition in partitions_to_unmount:
rc = self._call_shell_command(("sudo", "umount", partition))
if rc != 0:
return False
except Exception as _:
return False
return True
def _unswap(self) -> bool:
if TEST_MODE:
return True
self._queued_command.disk.update_mountpoints()
mountpoints = self._queued_command.disk.get_mountpoints_map()
unswap_them = []
oh_no = None
for part in mountpoints:
if mountpoints[part] == "[SWAP]":
unswap_them.append(part)
else:
oh_no = part
break
if oh_no:
self._queued_command.notify_finish_with_error(f"Partition {oh_no} is mounted as {mountpoints[oh_no]}")
return False
if len(unswap_them) > 0:
self._queued_command.notify_start("Unswapping the disk")
for path in unswap_them:
sp = subprocess.Popen(("sudo", "swapoff", path))
exitcode = sp.wait()
if exitcode != 0:
self._queued_command.notify_finish_with_error(f"Failed to unswap {path}, exit code {str(exitcode)}")
return False
self._queued_command.disk.update_mountpoints()
return True
def sleep(self, _cmd: str, dev: str):
self._queued_command.notify_start("Calling hdparm")
exitcode = self._call_hdparm_for_sleep(dev)
if exitcode == 0:
self._queued_command.notify_finish("Good night!")
else:
self._queued_command.notify_finish_with_error(f"hdparm exited with status {str(exitcode)}")
def sudo_password(self, _cmd: str, password: str):
global needs_sudo
with clients_lock:
if not needs_sudo:
return
result = subprocess.run(
["sudo", "-vS"],
input=password + "\n",
encoding="utf-8",
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
# output, stderr = pipe.communicate(password.encode() + b"\n")
# exitcode = pipe.wait()
if result.returncode == 0:
needs_sudo = False
SudoSessionKeeper().start()
else:
self.send_msg("sudo_password")
def _call_hdparm_for_sleep(self, dev: str):
return self._call_shell_command(("sudo", "hdparm", "-Y", dev))
def get_smartctl(self, cmd: str, args: str):
params = self._get_smartctl(args, False)
if params:
self.send_msg(cmd, params)
def queued_get_smartctl(self, cmd: str, args: str):
self._get_smartctl(args, True)
# if params:
# self.send_msg(cmd, params)
def _get_smartctl(self, dev: str, queued: bool):
if queued:
self._queued_command.notify_start("Getting smarter")
pipe = subprocess.Popen(
("sudo", "-n", "smartctl", "-j", "-a", dev),
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
output = pipe.stdout.read().decode("utf-8")
stderr = pipe.stderr.read().decode("utf-8")
exitcode = pipe.wait()
if exitcode == 0:
smartctl_returned_valid = True
else:
exitcode_bytes = exitcode.to_bytes(8, "little")
if exitcode_bytes[0] == 1 or exitcode_bytes[1] == 1 or exitcode_bytes[2] == 1:
smartctl_returned_valid = False
else:
# TODO: parse remaining bits (https://github.com/WEEE-Open/pesto/issues/71)
smartctl_returned_valid = True
updated = False
status = None
if smartctl_returned_valid:
status = get_smartctl_status(output)
if queued:
if not status:
self._queued_command.notify_error("Error while parsing smartctl status")
return {
"disk": dev,
"status": status,
"updated": updated,
"exitcode": exitcode,
"output": output,
"stderr": stderr,
}
else:
if queued:
self._queued_command.notify_error("smartctl failed")
return {
"disk": dev,
"status": status,
"updated": updated,
"exitcode": exitcode,
"output": output,
"stderr": stderr,
}
if queued and status:
self._queued_command.notify_percentage(50.0, "Updating tarallo if needed")
with disks_lock:
update_disks_if_needed(self)
disk_ref = disks[dev]
# noinspection PyBroadException
try:
updated = disk_ref.update_status(status)
except Exception as e:
self._queued_command.notify_error("Error during upload")
logging.warning(
f"[{self._the_id}] Can't update status of {dev} on tarallo",
exc_info=e,
)
self._queued_command.notify_finish(f"Disk is {status}")
return {
"disk": dev,
"status": status,
"updated": updated,
"exitcode": exitcode,
"output": output,
"stderr": stderr,
}
# noinspection PyUnusedLocal
def queued_upload_to_tarallo(self, cmd: str, args: str):
self._upload_to_tarallo(args, True)
# noinspection PyUnusedLocal
def upload_to_tarallo(self, cmd: str, args: str):
self._upload_to_tarallo(args, False)
def _upload_to_tarallo(self, dev: str, queued: bool):
list_dev = dev.split(" ")
dev = list_dev[0]
loc = list_dev[1]
if TEST_MODE:
self._queued_command.notify_finish("This doesn't do anything when test mode is enabled")
return
if queued:
self._queued_command.notify_start("Preparing to upload")
# return {
# "disk": dev,
# "status": status,
# "updated": updated,
# "exitcode": exitcode,
# "output": output,
# "stderr": stderr,
# }
smartctl = self._get_smartctl(dev, False)
if queued:
self._queued_command.notify_percentage(50.0, "smartctl output obtained")
if queued and not smartctl.get("output"):
self._queued_command.notify_finish_with_error("Could not get smartctl output")
return
if queued and not smartctl.get("status"):
self._queued_command.notify_error("Could not determine disk status")
features = parse_single_disk(json.loads(smartctl.get("output", "")))
if queued:
self._queued_command.notify_percentage(75.0, "Parsing done")
with disks_lock:
# update_disks_if_needed(self)
disk_ref = disks[dev]
try:
code = disk_ref.create_on_tarallo(features, loc)
except ValidationError as e:
if queued:
self.send_msg(
"error_that_can_be_manually_fixed",
{"message": "Upload failed due to validation error: " + str(e), "disk": dev},
)
self._queued_command.notify_finish_with_error("Upload failed due to validation error: " + str(e))
return
except NotAuthorizedError as e:
if queued:
self.send_msg(
"error_that_can_be_manually_fixed",
{"message": "Upload failed due to authorization error: " + str(e), "disk": dev},
)
self._queued_command.notify_finish_with_error("Upload failed due to authorization error: " + str(e))
return
with disks_lock:
if code:
disk_ref.set_code(code)
try:
disk_ref.update_from_tarallo_if_needed()
except ErrorThatCanBeManuallyFixed as e:
if queued:
self.send_msg(
"error_that_can_be_manually_fixed",
{"message": str(e), "disk": dev},
)
self._queued_command.notify_finish_with_error("Upload succeeded, but an error was reported")
return
logging.info(f"[{self._the_id}] created {disk_ref.get_path()} on tarallo as {code if code else 'unknown code'}")
if queued:
self._queued_command.notify_finish("Upload done")
@staticmethod
def _encode_param(param):
return json.dumps(param, separators=(",", ":"), indent=None)
def send_msg(self, cmd: str, param=None, the_id: Optional[int] = None):
logging.debug(f"[{self._the_id}] Sending {cmd}{ ' with args' if param else ''} to client")
the_id = the_id or self._the_id
thread = clients.get(the_id)
if thread is None:
logging.info(f"[{the_id}] Connection already closed while trying to send {cmd}")
else:
thread: TurboProtocol
# noinspection PyBroadException
try:
if param is None:
response_string = cmd
else:
j_param = self._encode_param(param)
response_string = f"{cmd} {j_param}"