-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.py
2044 lines (1651 loc) · 105 KB
/
worker.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
from datetime import datetime
import logging
import sys
import asyncio
from asyncio import Event, exceptions
from time import time
from weakref import WeakSet, WeakKeyDictionary
from typing import final, Final, NoReturn, Optional
from config import GLOBAL_RING_TOPOLOGY, Config, PING_TIMEOOUT, PING_DURATION, USERNAME, PASSWORD, TEST_FILES_PATH, DOWNLOAD_PATH, H1, H2, H3, H4, H5, H6, H7, H8, H9, H10
from nodes import Node
from packets import Packet, PacketType
from protocol import AwesomeProtocol
from membershipList import MemberShipList
from leader import Leader
from globalClass import Global
from election import Election
from file_service import FileService
from os import path
import copy
from typing import List
import random
import os
from ast import literal_eval
from models import perform_inference, NpEncoder, Merge, dump_to_file, perform_inference_without_async, ModelParameters
import json
import fnmatch
import statistics
class Worker:
"""Main worker class to handle all the failure detection and sends PINGs and ACKs to other nodes"""
def __init__(self, io: AwesomeProtocol) -> None:
self.io: Final = io
self._waiting: WeakKeyDictionary[Node, WeakSet[Event]] = WeakKeyDictionary()
self.config: Config = None
self.membership_list: Optional[MemberShipList] = None
self.is_current_node_active = True
self.waiting_for_introduction = True
self.total_pings_send = 0
self.total_ack_missed = 0
self.missed_acks_count = {}
self.file_service = FileService()
self.file_status = {}
self._waiting_for_leader_event: Optional[Event] = None
self._waiting_for_second_leader_event: Optional[Event] = None
self.get_file_sdfsfilename = None
self.get_file_machineids_with_file_versions = None
self.job_count = 30
self.current_job_id = 0
self.job_reqester_dict = {}
self.job_task = None
self.worker_nodes = [H3.unique_name, H4.unique_name, H5.unique_name, H6.unique_name, H7.unique_name, H8.unique_name, H9.unique_name, H10.unique_name]
self.workers_tasks_dict = {
}
self.model_dict = {
"InceptionV3": {
'hyperparams' : {
'batch_size' : 10,
'time': ModelParameters(download_time=1, model_load_time=5.6, first_image_predict_time=2, each_image_predict_time=0.325, batch_size=10).execution_time_per_vm()
},
'queue': [],
'inprogress_queue': [],
'measurements' : {
'query_count': 0,
'query_rate_list' : [],
'query_rate_array': []
}
},
"ResNet50": {
'hyperparams' : {
'batch_size' : 10,
'time': ModelParameters(download_time=1, model_load_time=3.5, first_image_predict_time=1, each_image_predict_time=0.250, batch_size=10).execution_time_per_vm()
},
'queue': [],
'inprogress_queue': [],
'measurements' : {
'query_count': 0,
'query_rate_list' : [],
'query_rate_array': []
}
}
}
def load_model_parameters(self, batch_size):
self.batch_size = batch_size
self.inceptionV3_model_params = ModelParameters(download_time=1, model_load_time=5.6, first_image_predict_time=2, each_image_predict_time=0.325, batch_size=self.batch_size)
self.resNet50_model_params = ModelParameters(download_time=1, model_load_time=3.5, first_image_predict_time=1, each_image_predict_time=0.250, batch_size=self.batch_size)
def initialize(self, config: Config, globalObj: Global) -> None:
"""Function to initialize all the required class for Worker"""
self.config = config
globalObj.set_worker(self)
self.globalObj = globalObj
self.globalObj.set_election(Election(globalObj))
# self.waiting_for_introduction = False if self.config.introducerFlag else True
self.leaderFlag = False
self.leaderObj: Leader = None
self.leaderNode: Node= None
self.fetchingIntroducerFlag = True
self.temporary_file_dict = {}
# if self.config.introducerFlag:
# self.leaderObj = Leader(self.config.node)
# self.leaderFlag = True
# self.leaderNode = self.config.node.unique_name
self.membership_list = MemberShipList(
self.config.node, self.config.ping_nodes, globalObj)
self.io.testing = config.testing
async def replica_file(self, req_node: Node, replicas: List[dict]):
"""Function to replicate files from other nodes. This function initiates a scp command to transfer the files and is run when leader sends the REPLICATE packet"""
status = False
filename = ""
for replica in replicas:
host = replica["hostname"]
username = USERNAME
password = PASSWORD
file_locations = replica["file_paths"]
filename = replica["filename"]
status = await self.file_service.replicate_file(host=host, username=username, password=password, file_locations=file_locations, filename=filename)
if status:
logging.info(f'successfully replicated file {filename} from {host} requested by {req_node.unique_name}')
response = {"filename": filename, "all_files": self.file_service.current_files}
await self.io.send(req_node.host, req_node.port, Packet(self.config.node.unique_name, PacketType.REPLICATE_FILE_SUCCESS, response).pack())
break
else:
logging.error(f'failed to replicate file {filename} from {host} requested by {req_node.unique_name}')
if not status:
response = {"filename": filename, "all_files": self.file_service.current_files}
await self.io.send(req_node.host, req_node.port, Packet(self.config.node.unique_name, PacketType.REPLICATE_FILE_FAIL, response).pack())
async def put_file(self, req_node: Node, host, username, password, file_location, filename):
"""Function to download file from the client node. This function initiates a scp command to transfer the files and is run when leader sends the DOWNLOAD packet"""
status = await self.file_service.download_file(host=host, username=username, password=password, file_location=file_location, filename=filename)
if status:
logging.info(f'successfully downloaded file {file_location} from {host} requested by {req_node.unique_name}')
# download success sending sucess back to requester
response = {"filename": filename, "all_files": self.file_service.current_files}
await self.io.send(req_node.host, req_node.port, Packet(self.config.node.unique_name, PacketType.DOWNLOAD_FILE_SUCCESS, response).pack())
else:
logging.error(f'failed to download file {file_location} from {host} requested by {req_node.unique_name}')
# download failed sending failure message back to requester
response = {"filename": filename, "all_files": self.file_service.current_files}
await self.io.send(req_node.host, req_node.port, Packet(self.config.node.unique_name, PacketType.DOWNLOAD_FILE_FAIL, response).pack())
async def delete_file(self, req_node, filename):
"""Function to delete file on the node. Itis run when leader sends the DELETE packet"""
logging.debug(f"request from {req_node.host}:{req_node.port} to delete file {filename}")
status = self.file_service.delete_file(filename)
if status:
logging.info(f"successfully deleted file {filename}")
response = {"filename": filename, "all_files": self.file_service.current_files}
await self.io.send(req_node.host, req_node.port, Packet(self.config.node.unique_name, PacketType.DELETE_FILE_ACK, response).pack())
else:
logging.error(f"failed to delete file {filename}")
response = {"filename": filename, "all_files": self.file_service.current_files}
await self.io.send(req_node.host, req_node.port, Packet(self.config.node.unique_name, PacketType.DELETE_FILE_NAK, response).pack())
async def get_file(self, req_node, filename):
"""Function to get files from other nodes. This function initiates a scp command to transfer the files and is run on the client once the leader sends it info of the replicas"""
logging.debug(f"request from {req_node.host}:{req_node.port} to get file {filename}")
response = self.file_service.get_file_details(filename)
if "latest_file" in response:
logging.error(f"Failed to find the file {filename}")
await self.io.send(req_node.host, req_node.port, Packet(self.config.node.unique_name, PacketType.GET_FILE_NAK, response).pack())
else:
logging.info(f"Found file {filename} locally")
await self.io.send(req_node.host, req_node.port, Packet(self.config.node.unique_name, PacketType.GET_FILE_ACK, response).pack())
async def handle_job_request(self, req_node, model, number_of_images, job_id):
if self.leaderFlag:
sdfs_images = await self.ls_all_cli("*.jpeg")
else:
sdfs_images = self.ls_all_temp_dict("*.jpeg")
sdfs_images.sort()
self.preprocess_job_request(req_node, model, number_of_images, job_id, sdfs_images)
if self.leaderFlag:
await self.schedule_job()
def preprocess_job_request(self, req_node, model, number_of_images, job_id, sdfs_images):
logging.info(f"JOB#{job_id} request from {req_node.host}:{req_node.port} for {model} to run inference on {number_of_images} files")
if len(sdfs_images) == 0:
return
# images = random.sample(sdfs_images, number_of_images)
images = []
index = 0
while len(images) < number_of_images:
if index >= len(sdfs_images):
index = 0
images.append(sdfs_images[index])
index += 1
# batch images
batch_size = self.model_dict[model]["hyperparams"]["batch_size"]
all_batches = []
batch = []
# batch_id = 1
for image in images:
if len(batch) < batch_size:
batch.append(image)
else:
batch.append(image)
batch_dict = {
"job_id": job_id,
"batch_id": len(all_batches) + 1,
"images": batch
}
all_batches.append(batch_dict)
# batch_id += 1
batch = []
if len(batch):
# batch_id += 1
batch_dict = {
"job_id": job_id,
"batch_id": len(all_batches) + 1,
"images": batch
}
all_batches.append(batch_dict)
batch = []
for all_batch in all_batches:
self.model_dict[model]["queue"].append(all_batch)
self.job_reqester_dict[job_id] = {
"request_node": req_node,
"num_of_batches_pending": len(all_batches)
}
def get_running_nodes(self, model):
result = []
for worker in self.workers_tasks_dict:
if(self.workers_tasks_dict[worker]['model'] == model):
result.append(worker)
return result
async def schedule_job(self):
if (len(self.model_dict["InceptionV3"]["queue"]) != 0 and len(self.model_dict["ResNet50"]["queue"]) == 0) or (len(self.model_dict["InceptionV3"]["queue"]) == 0 and len(self.model_dict["ResNet50"]["queue"]) != 0):
model = "InceptionV3"
if len(self.model_dict["InceptionV3"]["queue"]) == 0 and len(self.model_dict["ResNet50"]["queue"]) != 0:
model = "ResNet50"
free_workers = list(set(list(self.membership_list.memberShipListDict.keys())).intersection(set(self.worker_nodes)) - set(list(self.workers_tasks_dict.keys())))
if len(free_workers) == 0:
logging.info(f"All the workers are busy will schedule if any worker becomes available")
return
count = 0
for worker in free_workers:
if len(self.model_dict[model]["queue"]) == 0:
break
single_batch_dict = self.model_dict[model]["queue"][0]
single_batch_jobid = single_batch_dict["job_id"]
single_batch_id = single_batch_dict["batch_id"]
images = single_batch_dict["images"]
self.workers_tasks_dict[worker] = {
'model': model,
'job_id': single_batch_jobid,
'batch_id': single_batch_id
}
self.model_dict[model]["inprogress_queue"].append(single_batch_dict)
self.model_dict[model]["queue"].pop(0)
result_dict = {}
for image in images:
machineids_with_filenames = self.leaderObj.get_machineids_with_filenames(image)
result_dict[image] = machineids_with_filenames
# forward the request to VMs
workernode = Config.get_node_from_unique_name(worker)
await self.io.send(workernode.host, workernode.port, Packet(self.config.node.unique_name, PacketType.WORKER_TASK_REQUEST, {"jobid": single_batch_jobid, "batchid": single_batch_id, "model": model, "images": result_dict}).pack())
count += 1
logging.info(f"scheduling {count} tasks for {model}")
elif len(self.model_dict["InceptionV3"]["queue"]) != 0 and len(self.model_dict["ResNet50"]["queue"]) != 0:
online_worker_node_count = len(set(list(self.membership_list.memberShipListDict.keys())) - {H1.unique_name, H2.unique_name})
temp = 1
split_job_array = []
while(online_worker_node_count > 1):
split_job_array.append([online_worker_node_count - 1, temp])
online_worker_node_count-=1
temp+=1
differences = []
for split in split_job_array:
inception_vmcount, resnet_vmcount = split
inception_query_rate = (inception_vmcount * self.model_dict['InceptionV3']['hyperparams']['batch_size']) / self.model_dict['InceptionV3']['hyperparams']['time']
resnet50_query_rate = (resnet_vmcount * self.model_dict['ResNet50']['hyperparams']['batch_size']) / self.model_dict['ResNet50']['hyperparams']['time']
difference = (abs(inception_query_rate - resnet50_query_rate) / max(inception_query_rate, resnet50_query_rate)) * 100
differences.append(difference)
min_index = differences.index(min(differences))
inception_vmcount_predicted, resnet_vmcount_predicted = split_job_array[min_index]
logging.info(f"predicted query_differences: {differences}, final split: {split_job_array[min_index]}")
inceptionV3_running_jobs = self.get_running_nodes('InceptionV3')
resnet50_running_jobs = self.get_running_nodes('ResNet50')
free_workers = list(set(list(self.membership_list.memberShipListDict.keys())).intersection(set(self.worker_nodes)) - set(list(self.workers_tasks_dict.keys())))
new_nodes_for_inceptionV3 = []
if len(inceptionV3_running_jobs) < inception_vmcount_predicted:
while len(free_workers) > 0:
free_worker = free_workers[-1]
if len(new_nodes_for_inceptionV3) + len(inceptionV3_running_jobs) < inception_vmcount_predicted:
new_nodes_for_inceptionV3.append(free_worker)
else:
break
free_workers.pop()
if len(new_nodes_for_inceptionV3) + len(inceptionV3_running_jobs) < inception_vmcount_predicted:
# assign that from resNet VMs
while len(resnet50_running_jobs) > 0:
free_worker = resnet50_running_jobs[-1]
if len(new_nodes_for_inceptionV3) + len(inceptionV3_running_jobs) < inception_vmcount_predicted:
new_nodes_for_inceptionV3.append(free_worker)
else:
break
resnet50_running_jobs.pop()
new_nodes_for_resnet50 = []
if len(resnet50_running_jobs) < resnet_vmcount_predicted:
while len(free_workers) > 0:
free_worker = free_workers[-1]
if len(new_nodes_for_resnet50) + len(resnet50_running_jobs) < resnet_vmcount_predicted:
new_nodes_for_resnet50.append(free_worker)
else:
break
free_workers.pop()
if len(new_nodes_for_resnet50) + len(resnet50_running_jobs) < resnet_vmcount_predicted:
# assign that from inceptionV3 VMs
while len(inceptionV3_running_jobs) > 0:
free_worker = inceptionV3_running_jobs[-1]
if len(new_nodes_for_resnet50) + len(resnet50_running_jobs) < resnet_vmcount_predicted:
new_nodes_for_resnet50.append(free_worker)
else:
break
inceptionV3_running_jobs.pop()
logging.info(f"New nodes for resNet50={new_nodes_for_resnet50 + resnet50_running_jobs}, New nodes for inceptionV3={new_nodes_for_inceptionV3 + inceptionV3_running_jobs}")
nodes_for_resnet50 = new_nodes_for_resnet50
nodes_for_inceptionv3 = new_nodes_for_inceptionV3
model = 'ResNet50'
for worker in nodes_for_resnet50:
if len(self.model_dict[model]["queue"]) == 0:
break
single_batch_dict = self.model_dict[model]["queue"][0]
single_batch_jobid = single_batch_dict["job_id"]
single_batch_id = single_batch_dict["batch_id"]
images = single_batch_dict["images"]
if worker in self.workers_tasks_dict:
# add the batch_dict to infront of the queue
batch_dict = self.workers_tasks_dict[worker]
batch_jobid = batch_dict['job_id']
batch_id = batch_dict['batch_id']
batch_dict_model = batch_dict["model"]
i = 0
for item in self.model_dict[batch_dict_model]['inprogress_queue']:
item_jobid = item["job_id"]
item_batchid = item["batch_id"]
if item_jobid == batch_jobid and item_batchid == batch_id:
break
i+= 1
logging.info(f'preempting job {batch_jobid} of {batch_dict_model} from {worker}')
preempted_batch = self.model_dict[batch_dict_model]['inprogress_queue'].pop(i)
self.model_dict[batch_dict_model]["queue"].insert(0, preempted_batch)
self.workers_tasks_dict[worker] = {
'model': model,
'job_id': single_batch_jobid,
'batch_id': single_batch_id
}
self.model_dict[model]["inprogress_queue"].append(single_batch_dict)
self.model_dict[model]["queue"].pop(0)
result_dict = {}
for image in images:
machineids_with_filenames = self.leaderObj.get_machineids_with_filenames(image)
result_dict[image] = machineids_with_filenames
# forward the request to VMs
workernode = Config.get_node_from_unique_name(worker)
logging.info(f'Assigning a new job {model} to {workernode.unique_name}')
await self.io.send(workernode.host, workernode.port, Packet(self.config.node.unique_name, PacketType.WORKER_TASK_REQUEST, {"jobid": single_batch_jobid, "batchid": single_batch_id, "model": model, "images": result_dict}).pack())
model = 'InceptionV3'
for worker in nodes_for_inceptionv3:
if len(self.model_dict[model]["queue"]) == 0:
break
single_batch_dict = self.model_dict[model]["queue"][0]
single_batch_jobid = single_batch_dict["job_id"]
single_batch_id = single_batch_dict["batch_id"]
images = single_batch_dict["images"]
if worker in self.workers_tasks_dict:
# add the batch_dict to infront of the queue
batch_dict = self.workers_tasks_dict[worker]
batch_jobid = batch_dict['job_id']
batch_id = batch_dict['batch_id']
batch_dict_model = batch_dict["model"]
i = 0
for item in self.model_dict[batch_dict_model]['inprogress_queue']:
item_jobid = item["job_id"]
item_batchid = item["batch_id"]
if item_jobid == batch_jobid and item_batchid == batch_id:
break
i+= 1
logging.info(f'preempting job {batch_jobid} of {batch_dict_model} from {worker}')
preempted_batch = self.model_dict[batch_dict_model]['inprogress_queue'].pop(i)
self.model_dict[batch_dict_model]["queue"].insert(0, preempted_batch)
self.workers_tasks_dict[worker] = {
'model': model,
'job_id': single_batch_jobid,
'batch_id': single_batch_id
}
self.model_dict[model]["inprogress_queue"].append(single_batch_dict)
self.model_dict[model]["queue"].pop(0)
result_dict = {}
for image in images:
machineids_with_filenames = self.leaderObj.get_machineids_with_filenames(image)
result_dict[image] = machineids_with_filenames
# forward the request to VMs
workernode = Config.get_node_from_unique_name(worker)
logging.info(f'Assigning a new job {model} to {workernode.unique_name}')
await self.io.send(workernode.host, workernode.port, Packet(self.config.node.unique_name, PacketType.WORKER_TASK_REQUEST, {"jobid": single_batch_jobid, "batchid": single_batch_id, "model": model, "images": result_dict}).pack())
else:
return
model = 'ResNet50'
model_running_list = self.get_running_nodes(model)
if len(model_running_list):
query_rate = len(model_running_list) * self.model_dict[model]["hyperparams"]["batch_size"]
self.model_dict[model]["measurements"]["query_rate_array"].append((time(), query_rate))
model = 'InceptionV3'
model_running_list = self.get_running_nodes(model)
if len(model_running_list):
query_rate = len(model_running_list) * self.model_dict[model]["hyperparams"]["batch_size"]
self.model_dict[model]["measurements"]["query_rate_array"].append((time(), query_rate))
def display_machineids_for_file(self, sdfsfilename, machineids):
"""Function to pretty print replica info for the LS command"""
output = f"File {sdfsfilename} found in {len(machineids)} machines:\n"
for recv_machineid in machineids:
output += f"{recv_machineid}\n"
print(output)
def _add_waiting(self, node: Node, event: Event) -> None:
"""Function to keep track of all the unresponsive PINGs"""
waiting = self._waiting.get(node)
if waiting is None:
self._waiting[node] = waiting = WeakSet()
waiting.add(event)
def _notify_waiting(self, node) -> None:
"""Notify the PINGs which are waiting for ACKs"""
waiting = self._waiting.get(node)
if waiting is not None:
for event in waiting:
event.set()
async def handle_worker_task_request(self, curr_node, model, req_images, jobid, batchid, start_time):
try:
logging.info(f"received a Task from cordinator: JobId={jobid}, model={model}, images_count={len(req_images)}")
# perform prediction
filename = await self.predict_locally_cli(model, req_images, jobid, batchid)
# upload it to SDFS
logging.info(f"JOB#{jobid}: uploading result file:{filename} to SDFS")
await self.io.send(self.leaderNode.host, self.leaderNode.port, Packet(self.config.node.unique_name, PacketType.PUT_REQUEST, {'file_path': DOWNLOAD_PATH + filename, 'filename': filename}).pack())
await asyncio.sleep(0)
# send response to cordinator
logging.info(f"ACK for JOB#{jobid} to {curr_node.unique_name}")
await self.io.send(curr_node.host, curr_node.port, Packet(self.config.node.unique_name, PacketType.WORKER_TASK_REQUEST_ACK, {'jobid': jobid, "batchid": batchid, "model": model, 'image_count': len(req_images), 'start_time': start_time}).pack())
# del self.job_task_dict[jobid]
self.job_task = None
except asyncio.CancelledError as e:
logging.info(f"Stopping the JOB#{jobid}")
finally:
logging.info(f"Task JOB#{jobid} cancelled")
async def _run_handler(self) -> NoReturn:
"""RUN the main loop which handles all the communication to external nodes"""
while True:
packedPacket, host, port = await self.io.recv()
packet: Packet = Packet.unpack(packedPacket)
if (not packet) or (not self.is_current_node_active):
continue
logging.debug(f'got data: {packet.data} from {host}:{port}')
if packet.type == PacketType.ACK or packet.type == PacketType.INTRODUCE_ACK:
"""Instructions to execute when the node receives failure detector ACKs or ACKs from the introducer"""
# print('I GOT AN ACK FROM ', packet.sender)
curr_node: Node = Config.get_node_from_unique_name(
packet.sender)
logging.debug(f'got ack from {curr_node.unique_name}')
if curr_node:
if packet.type == PacketType.ACK:
self.membership_list.update(packet.data)
else:
self.membership_list.update(packet.data['membership_list'])
leader = packet.data['leader']
self.leaderNode = Config.get_node_from_unique_name(leader)
self.waiting_for_introduction = False
# self.membership_list.update(packet.data)
self.missed_acks_count[curr_node] = 0
self._notify_waiting(curr_node)
elif packet.type == PacketType.FETCH_INTRODUCER_ACK:
"""Instructions to execute once the node receives the introducer information from the Introducer DNS process"""
logging.debug(f'got fetch introducer ack from {self.config.introducerDNSNode.unique_name}')
introducer = packet.data['introducer']
print(introducer)
if introducer == self.config.node.unique_name:
self.leaderObj = Leader(self.config.node, self.globalObj)
self.globalObj.set_leader(self.leaderObj)
self.leaderFlag = True
self.leaderNode = self.config.node
self.waiting_for_introduction = False
self.leaderObj.global_file_dict = copy.deepcopy(self.temporary_file_dict)
self.leaderObj.global_file_dict[self.config.node.unique_name] = self.file_service.current_files
self.temporary_file_dict = {}
logging.info(f"I BECAME THE LEADER {self.leaderNode.unique_name}")
if H2.unique_name == self.config.node.unique_name:
await self.schedule_job()
else:
self.leaderNode = Config.get_node_from_unique_name(introducer)
logging.info(f"MY NEW LEADER IS {self.leaderNode.unique_name}")
response = {'all_files': self.file_service.current_files}
await self.io.send(self.leaderNode.host, self.leaderNode.port, Packet(self.config.node.unique_name, PacketType.ALL_LOCAL_FILES, response).pack())
self.fetchingIntroducerFlag = False
self._notify_waiting(self.config.introducerDNSNode)
elif packet.type == PacketType.ALL_LOCAL_FILES:
files_in_node = packet.data['all_files']
if isinstance(self.leaderObj, Leader):
self.leaderObj.merge_files_in_global_dict(files_in_node, packet.sender)
if H1.unique_name == self.leaderNode.unique_name:
await self.io.send(H2.host, H2.port, Packet(self.config.node.unique_name, PacketType.ALL_LOCAL_FILES_RELAY, {"all_files": files_in_node, 'node': packet.sender, 'leader_files': self.file_service.current_files}).pack())
elif packet.type == PacketType.ALL_LOCAL_FILES_RELAY:
files_in_node = packet.data['all_files']
sender_node = packet.data['node']
leader_files = packet.data['leader_files']
self.temporary_file_dict[sender_node] = files_in_node
self.temporary_file_dict[H1.unique_name] = leader_files
elif packet.type == PacketType.PING or packet.type == PacketType.INTRODUCE:
# print(f'{datetime.now()}: received ping from {host}:{port}')
self.membership_list.update(packet.data)
await self.io.send(host, port, Packet(self.config.node.unique_name, PacketType.ACK, self.membership_list.get()).pack())
elif packet.type == PacketType.ELECTION:
"""Instructions to execute when node receives the election packet. If it has not started its own election then its starts it. If election is already going on, it checks if it itself is the leader using the full membership list. If new leader, then send the coordinate message"""
logging.info(f'{self.config.node.unique_name} GOT AN ELECTION PACKET')
if not self.globalObj.election.electionPhase:
self.globalObj.election.initiate_election()
else:
if self.globalObj.election.check_if_leader():
await self.send_coordinator_message()
elif packet.type == PacketType.COORDINATE:
"""Instructions to execute when a node receives the COORDINATE message from the new leader"""
self.globalObj.election.electionPhase = False
self.leaderNode = Config.get_node_from_unique_name(packet.sender)
logging.info(f'{self.config.node.unique_name} NEW LEADER IS f{packet.sender}')
response = {'all_files': self.file_service.current_files}
await self.io.send(host, port, Packet(self.config.node.unique_name, PacketType.COORDINATE_ACK, response).pack())
elif packet.type == PacketType.COORDINATE_ACK:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
files_in_node = packet.data['all_files']
self.globalObj.election.coordinate_ack += 1
self.temporary_file_dict[packet.sender] = files_in_node
# self.leaderObj.merge_files_in_global_dict(files_in_node, host, port)
print(f"Got COORDINATE_ACK from {curr_node.unique_name} and my members: {list(self.membership_list.memberShipListDict.keys())}")
# if self.globalObj.election.coordinate_ack == len(self.membership_list.memberShipListDict.keys()) - 1:
logging.info(f'{self.config.node.unique_name} IS THE NEW LEADER NOW')
await self.update_introducer()
elif packet.type == PacketType.REPLICATE_FILE:
"""Handle REPLICATE request from the leader"""
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
data: dict = packet.data
replicas = data["replicas"]
logging.debug(f"request from {curr_node.host}:{curr_node.port} to replicate files")
asyncio.create_task(self.replica_file(req_node=curr_node, replicas=replicas))
elif packet.type == PacketType.REPLICATE_FILE_SUCCESS:
"""Handle the Replicate success messages from the replicas. This request is only handled by the leader"""
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
data: dict = packet.data
sdfsFileName = data['filename']
all_files = data['all_files']
# update status dict
self.leaderObj.merge_files_in_global_dict(all_files, packet.sender)
self.leaderObj.update_replica_status(sdfsFileName, curr_node, 'Success')
print(f'{packet.sender} REPLICATED {sdfsFileName}')
if self.leaderObj.check_if_request_completed(sdfsFileName):
self.leaderObj.delete_status_for_file(sdfsFileName)
print(f'REPLICATED {sdfsFileName} at all nodes: in {time() - self.replicate_start_time} seconds')
elif packet.type == PacketType.REPLICATE_FILE_FAIL:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
data: dict = packet.data
sdfsFileName = data['filename']
all_files = data['all_files']
# update status dict
self.leaderObj.merge_files_in_global_dict(all_files, packet.sender)
self.leaderObj.update_replica_status(sdfsFileName, curr_node, 'Failed')
print(f'{packet.sender} NOT REPLICATED {sdfsFileName}')
# self.leaderObj.delete_status_for_file(sdfsFileName)
elif packet.type == PacketType.DOWNLOAD_FILE:
# parse packet and get all the required fields to download a file
"""Handle Download request from the leader"""
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
data: dict = packet.data
machine_hostname = data["hostname"]
machine_username = USERNAME
machine_password = PASSWORD
machine_file_location = data["file_path"]
machine_filename = data["filename"]
logging.debug(f"request from {curr_node.host}:{curr_node.port} to download file from {machine_username}@{machine_hostname}:{machine_file_location}")
asyncio.create_task(self.put_file(curr_node, machine_hostname, machine_username, machine_password, machine_file_location, machine_filename))
elif packet.type == PacketType.DOWNLOAD_FILE_SUCCESS:
"""INstructions for the leader to handle the download file success messages. The leader updates the status of the file in and notifies the client that the file has been uploaded successfully if Success is received from all 4 replicas"""
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
data: dict = packet.data
sdfsFileName = data['filename']
all_files = data['all_files']
# update status dict
self.leaderObj.merge_files_in_global_dict(all_files, packet.sender)
self.leaderObj.update_replica_status(sdfsFileName, curr_node, 'Success')
if self.leaderObj.check_if_request_completed(sdfsFileName):
original_requesting_node = self.leaderObj.status_dict[sdfsFileName]['request_node']
await self.io.send(original_requesting_node.host, original_requesting_node.port, Packet(self.config.node.unique_name, PacketType.PUT_REQUEST_SUCCESS, {'filename': sdfsFileName}).pack())
self.leaderObj.delete_status_for_file(sdfsFileName)
elif packet.type == PacketType.DOWNLOAD_FILE_FAIL:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
data: dict = packet.data
sdfsFileName = data['filename']
all_files = data['all_files']
# update status dict
self.leaderObj.merge_files_in_global_dict(all_files, packet.sender)
self.leaderObj.update_replica_status(sdfsFileName, curr_node, 'Failed')
if self.leaderObj.check_if_request_falied(sdfsFileName):
original_requesting_node = self.leaderObj.status_dict[sdfsFileName]['request_node']
await self.io.send(original_requesting_node.host, original_requesting_node.port, Packet(self.config.node.unique_name, PacketType.PUT_REQUEST_FAIL, {'filename': sdfsFileName}).pack())
del self.leaderObj.status_dict[sdfsFileName]
elif packet.type == PacketType.DELETE_FILE:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
data: dict = packet.data
machine_filename = data["filename"]
await self.delete_file(curr_node, machine_filename)
elif packet.type == PacketType.DELETE_FILE_ACK or packet.type == PacketType.DELETE_FILE_NAK:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
data: dict = packet.data
sdfsFileName = data['filename']
all_files = data['all_files']
# update status dict
self.leaderObj.merge_files_in_global_dict(all_files, packet.sender)
self.leaderObj.update_replica_status(sdfsFileName, curr_node, 'Success')
if self.leaderObj.check_if_request_completed(sdfsFileName):
original_requesting_node = self.leaderObj.status_dict[sdfsFileName]['request_node']
await self.io.send(original_requesting_node.host, original_requesting_node.port, Packet(self.config.node.unique_name, PacketType.DELETE_FILE_REQUEST_SUCCESS, {'filename': sdfsFileName}).pack())
self.leaderObj.delete_status_for_file(sdfsFileName)
elif packet.type == PacketType.GET_FILE:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
data: dict = packet.data
machine_filename = data["filename"]
self.get_file(curr_node, machine_filename)
elif packet.type == PacketType.PUT_REQUEST:
"""Instructions to handle the PUT request from the client. This request is handled by the leader. It finds 4 random replicas for the file, sends download command to them and tracks their status"""
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
sdfsFileName = packet.data['filename']
if self.leaderObj.is_file_upload_inprogress(sdfsFileName):
await self.io.send(curr_node.host, curr_node.port, Packet(self.config.node.unique_name, PacketType.PUT_REQUEST_FAIL, {'filename': sdfsFileName, 'error': 'File upload already inprogress...'}).pack())
else:
download_nodes = self.leaderObj.find_nodes_to_put_file(sdfsFileName)
self.leaderObj.create_new_status_for_file(sdfsFileName, packet.data['file_path'], curr_node, 'PUT')
for node in download_nodes:
await self.io.send(node.host, node.port, Packet(self.config.node.unique_name, PacketType.DOWNLOAD_FILE, {'hostname': host, 'file_path': packet.data['file_path'], 'filename': sdfsFileName}).pack())
self.leaderObj.add_replica_to_file(sdfsFileName, node)
await self.io.send(curr_node.host, curr_node.port, Packet(self.config.node.unique_name, PacketType.PUT_REQUEST_ACK, {'filename': sdfsFileName}).pack())
elif packet.type == PacketType.DELETE_FILE_REQUEST:
"""Instructions for the leader to handle the delete request from the client. It finds the replicas for that file and sends the delete command to them It also tracks their status"""
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
sdfsFileName = packet.data['filename']
if self.leaderObj.is_file_upload_inprogress(sdfsFileName):
await self.io.send(curr_node.host, curr_node.port, Packet(self.config.node.unique_name, PacketType.DELETE_FILE_REQUEST_FAIL, {'error': "File upload inprogress"}).pack())
else:
file_nodes = self.leaderObj.find_nodes_to_delete_file(sdfsFileName)
if len(file_nodes) == 0:
await self.io.send(curr_node.host, curr_node.port, Packet(self.config.node.unique_name, PacketType.DELETE_FILE_REQUEST_SUCCESS, {'filename': sdfsFileName}).pack())
else:
self.leaderObj.create_new_status_for_file(sdfsFileName, '', curr_node, 'DELETE')
for node in file_nodes:
await self.io.send(node.host, node.port, Packet(self.config.node.unique_name, PacketType.DELETE_FILE, {'filename': sdfsFileName}).pack())
self.leaderObj.add_replica_to_file(sdfsFileName, node)
await self.io.send(curr_node.host, curr_node.port, Packet(self.config.node.unique_name, PacketType.DELETE_FILE_REQUEST_ACK, {'filename': sdfsFileName}).pack())
elif packet.type == PacketType.DELETE_FILE_REQUEST_ACK:
filename = packet.data['filename']
print(f'Leader successfully received DELETE request for file {filename}. waiting for nodes to delete the file...')
if self._waiting_for_leader_event is not None:
self._waiting_for_leader_event.set()
elif packet.type == PacketType.DELETE_FILE_REQUEST_FAIL:
filename = packet.data['filename']
error = packet.data['error']
print(f'Failed to delete file {filename}: {error}')
if self._waiting_for_leader_event is not None:
self._waiting_for_leader_event.set()
if self._waiting_for_second_leader_event is not None:
self._waiting_for_second_leader_event.set()
elif packet.type == PacketType.DELETE_FILE_REQUEST_SUCCESS:
filename = packet.data['filename']
print(f'FILE {filename} SUCCESSFULLY DELETED')
if self._waiting_for_leader_event is not None:
self._waiting_for_leader_event.set()
if self._waiting_for_second_leader_event is not None:
self._waiting_for_second_leader_event.set()
elif packet.type == PacketType.PUT_REQUEST_ACK:
filename = packet.data['filename']
print(f'Leader successfully received PUT request for file {filename}. waiting for nodes to download the file...')
if self._waiting_for_leader_event is not None:
self._waiting_for_leader_event.set()
elif packet.type == PacketType.PUT_REQUEST_SUCCESS:
filename = packet.data['filename']
print(f'FILE {filename} SUCCESSFULLY STORED')
if self._waiting_for_leader_event is not None:
self._waiting_for_leader_event.set()
if self._waiting_for_second_leader_event is not None:
self._waiting_for_second_leader_event.set()
elif packet.type == PacketType.PUT_REQUEST_FAIL:
filename = packet.data['filename']
error = packet.data['error']
print(f'Failed to PUT file {filename}: {error}')
if self._waiting_for_leader_event is not None:
self._waiting_for_leader_event.set()
if self._waiting_for_second_leader_event is not None:
self._waiting_for_second_leader_event.set()
elif packet.type == PacketType.LIST_FILE_REQUEST:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
sdfsFileName = packet.data['filename']
machines = self.leaderObj.get_machineids_for_file(sdfsFileName)
await self.io.send(curr_node.host, curr_node.port, Packet(self.config.node.unique_name, PacketType.LIST_FILE_REQUEST_ACK, {'filename': sdfsFileName, 'machines': machines}).pack())
elif packet.type == PacketType.LIST_FILE_REQUEST_ACK:
recv_sdfsfilename = packet.data['filename']
recv_machineids: list[str] = packet.data["machines"]
self.display_machineids_for_file(recv_sdfsfilename, recv_machineids)
if self._waiting_for_leader_event is not None:
self._waiting_for_leader_event.set()
elif packet.type == PacketType.GET_FILE_REQUEST:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
sdfsFileName = packet.data['filename']
machineids_with_filenames = self.leaderObj.get_machineids_with_filenames(sdfsFileName)
await self.io.send(curr_node.host, curr_node.port, Packet(self.config.node.unique_name, PacketType.GET_FILE_REQUEST_ACK, {'filename': sdfsFileName, 'machineids_with_file_versions': machineids_with_filenames}).pack())
elif packet.type == PacketType.GET_FILE_REQUEST_ACK:
self.get_file_sdfsfilename = packet.data['filename']
self.get_file_machineids_with_file_versions = packet.data["machineids_with_file_versions"]
if self._waiting_for_leader_event is not None:
self._waiting_for_leader_event.set()
elif packet.type == PacketType.GET_FILE_NAMES_REQUEST:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
file_pattern = packet.data['filepattern']
all_filenames = self.leaderObj.get_all_matching_files(file_pattern)
await self.io.send(curr_node.host, curr_node.port, Packet(self.config.node.unique_name, PacketType.GET_FILE_NAMES_REQUEST_ACK, {'filepattern': file_pattern, 'files': all_filenames}).pack())
elif packet.type == PacketType.GET_FILE_NAMES_REQUEST_ACK:
self.get_file_sdfsfilename = packet.data['filepattern']
self.get_file_machineids_with_file_versions = packet.data["files"]
if self._waiting_for_leader_event is not None:
self._waiting_for_leader_event.set()
elif packet.type == PacketType.SUBMIT_JOB_RELAY:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
model = packet.data['model']
images_count = packet.data['images_count']
request_node = packet.data['request_node']
self.job_count += 1
# await self.io.send(curr_node.host, curr_node.port, Packet(self.config.node.unique_name, PacketType.SUBMIT_JOB_REQUEST_ACK, {'jobid': self.job_count}).pack())
await self.handle_job_request(Config.get_node_from_unique_name(request_node), model=model, number_of_images=images_count, job_id=self.job_count)
elif packet.type == PacketType.SUBMIT_JOB_REQUEST:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
model = packet.data['model']
images_count = packet.data['images_count']
self.job_count += 1
await self.io.send(curr_node.host, curr_node.port, Packet(self.config.node.unique_name, PacketType.SUBMIT_JOB_REQUEST_ACK, {'jobid': self.job_count}).pack())
if H1.unique_name == self.leaderNode.unique_name:
await self.io.send(H2.host, H2.port, Packet(self.config.node.unique_name, PacketType.SUBMIT_JOB_RELAY, {'model': model, 'images_count': images_count, 'request_node': curr_node.unique_name}).pack())
await self.handle_job_request(curr_node, model=model, number_of_images=images_count, job_id=self.job_count)
elif packet.type == PacketType.SUBMIT_JOB_REQUEST_ACK:
self.current_job_id = packet.data['jobid']
print(f"Leader node ACK for Job#{self.current_job_id}")
if self._waiting_for_leader_event is not None:
self._waiting_for_leader_event.set()
elif packet.type == PacketType.SUBMIT_JOB_REQUEST_SUCCESS:
jobid = packet.data['jobid']
print(f'Job#{jobid} SUCCESSFULLY Completed')
# await self.get_output_cli(jobid)
if self._waiting_for_leader_event is not None:
self._waiting_for_leader_event.set()
if self._waiting_for_second_leader_event is not None:
self._waiting_for_second_leader_event.set()
elif packet.type == PacketType.WORKER_TASK_REQUEST:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
if self.job_task is not None:
# cancel the task
self.job_task.cancel()
# Wait for the cancellation of task to be complete
try:
await self.job_task
except asyncio.CancelledError:
print("cancelled now")
self.job_task = None
jobid = packet.data['jobid']
batchid = packet.data['batchid']
model = packet.data['model']
req_images = packet.data['images']
start_time = time()
task = asyncio.create_task(self.handle_worker_task_request(curr_node, model, req_images, jobid, batchid, start_time))
self.job_task = task
elif packet.type == PacketType.WORKER_TASK_ACK_RELAY:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
jobid = packet.data['jobid']
batchid = packet.data['batchid']
model = packet.data['model']
image_count = packet.data['image_counts']
if jobid in self.job_reqester_dict:
index = -1
i = 0
for batch_dict in self.model_dict[model]["queue"]:
if batch_dict["job_id"] == jobid and batch_dict["batch_id"] == batchid:
index = i
break
i += 1
if index != -1:
self.model_dict[model]["queue"].pop(index)
self.job_reqester_dict[jobid]["num_of_batches_pending"] -= 1
self.model_dict[model]['measurements']['query_count'] += image_count
elif packet.type == PacketType.WORKER_TASK_REQUEST_ACK:
curr_node: Node = Config.get_node_from_unique_name(packet.sender)
if curr_node:
jobid = packet.data['jobid']
batchid = packet.data['batchid']
model = packet.data['model']
image_count= packet.data['image_count']
start_time = packet.data['start_time']
if jobid in self.job_reqester_dict:
self.model_dict[model]['measurements']['query_count'] += image_count