-
Notifications
You must be signed in to change notification settings - Fork 2
/
roadblock.py
1710 lines (1385 loc) · 69.2 KB
/
roadblock.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
'''Roadblock is a synchronization and message passing utility which relies on redis for communication'''
import datetime
import time
import calendar
import signal
import hashlib
import json
import uuid
import threading
import logging
import sys
import re
import subprocess
import select
import copy
import base64
import lzma
import redis
import jsonschema
class roadblock:
'''roadblock object class'''
# log formatting variables
log_debug_format = '[CODE][%(module)s %(funcName)s:%(lineno)d]\n[%(asctime)s][%(levelname) 8s] %(message)s'
log_normal_format = '[%(asctime)s][%(levelname) 8s] %(message)s'
# return code variables
RC_SUCCESS=0
RC_ERROR=1
RC_INVALID_INPUT=2
RC_TIMEOUT=3
RC_ABORT=4
RC_HEARTBEAT_TIMEOUT=5
RC_ABORT_WAITING=6
def __init__(self, logger, debug):
'''roadblock object initiator function'''
# object variables
self.logger = None
self.debug = False
# return code status
self.rc = 0
# parameters
self.roadblock_role = None
self.my_id = None
self.roadblock_uuid = None
self.message_validation = "all"
self.connection_watchdog_state = "disabled"
self.roadblock_followers = None
self.abort = None
self.roadblock_leader_id = None
self.wait_for_cmd = None
self.wait_for = None
self.wait_for_log = None
self.simulate_heartbeat_timeout = None
self.roadblock_follower_id = None
self.roadblock_timeout = 30
self.roadblock_redis_server = "localhost"
self.roadblock_redis_password = None
# runtime variables
self.alarm_active = False
self.con_pool = None
self.con_pool_state = False
self.con_watchdog_exit = None
self.con_watchdog = None
self.wait_for_cmd = None
self.wait_for_io_handler_exited = None
self.wait_for_launcher_thread = None
self.wait_for_process = None
self.wait_for_monitor_thread = None
self.wait_for_monitor_exit = None
self.wait_for_monitor_start = None
self.wait_for_waiting = False
self.redcon = None
self.initiator = False
self.schema = None
self.user_schema = None
self.my_id = None
self.watch_bus = True
self.leader_abort = False
self.leader_abort_waiting = False
self.roadblock_waiting = False
self.follower_abort = False
self.initiator_type = None
self.initiator_id = None
self.followers = { "online": {},
"ready": {},
"gone": {},
"waiting": {},
"waiting_backup": {},
"busy_waiting": {} }
self.processed_messages = {}
self.messages = { "sent": [],
"received": [] }
self.message_log = None
self.user_messages = []
self.log = None
self.heartbeat_timeout = 30
self.waiting_failed = False
self.sigint_counter = 0
if not debug:
self.debug = True
if not logger is None:
self.logger = logger
else:
if self.debug:
logging.basicConfig(level = logging.DEBUG, format = self.log_debug_format, stream = sys.stdout)
else:
logging.basicConfig(level = logging.INFO, format = self.log_normal_format, stream = sys.stdout)
self.logger = logging.getLogger(__file__)
def get_rc(self):
'''get the roadblock return code'''
return self.rc
def get_logger(self):
'''return the logging object'''
return self.logger
def set_role(self, role):
'''set the participant's role'''
self.roadblock_role = role
return 0
def set_follower_id(self, follower_id):
'''set the follower's id'''
self.roadblock_follower_id = follower_id
return 0
def set_leader_id(self, leader_id):
'''set the leader's id'''
self.roadblock_leader_id = leader_id
return 0
def set_uuid(self, rb_uuid):
'''set the roadblock's uuid'''
self.roadblock_uuid = rb_uuid
return 0
def set_timeout(self, timeout):
'''set the roadblock's timeout'''
self.roadblock_timeout = timeout
return 0
def set_redis_server(self, server):
'''set the redis server'''
self.roadblock_redis_server = server
return 0
def set_redis_password(self, password):
'''set the redis password'''
self.roadblock_redis_password = password
return 0
def set_followers(self, followers):
'''set the roadblock followers'''
self.roadblock_followers = copy.deepcopy(followers)
return 0
def set_abort(self, abort):
'''set the abort status'''
self.abort = abort
return 0
def set_message_log(self, msg_log):
'''set the message log'''
self.message_log = msg_log
return 0
def set_user_messages(self, usr_msgs):
'''set the user messages'''
self.user_messages = usr_msgs
return 0
def set_message_validation(self, msg_val):
'''set the message validation level'''
self.message_validation = msg_val
return 0
def set_connection_watchdog(self, con_watchdog_state):
'''Enable/disable the connection watchdog'''
self.connection_watchdog_state = con_watchdog_state
return 0
def set_wait_for_cmd(self, wait_for_cmd):
'''set the wait-for program'''
self.wait_for_cmd = wait_for_cmd
self.wait_for = self.wait_for_cmd
return 0
def set_wait_for_log(self, wait_for_log):
'''set the wait-for log'''
self.wait_for_log = wait_for_log
return 0
def set_simulate_heartbeat_timeout(self, value):
'''set the simulate heartbeat timeout value'''
self.simulate_heartbeat_timeout = value
return 0
def set_alarm(self, seconds):
'''Set a SIGALRM to fire in `seconds` seconds'''
signal.alarm(seconds)
self.alarm_active = True
return self.RC_SUCCESS
def disable_alarm(self):
'''Disable an existing SIGALRM'''
signal.alarm(0)
self.alarm_active = True
return self.RC_SUCCESS
def message_to_str(self, message):
'''Converts a message into a JSON string'''
return json.dumps(message, separators=(",", ":"))
def message_from_str(self, message):
'''Convert a JSON string into a message'''
return json.loads(message)
def message_build(self, recipient_type, recipient_id, command, value=None):
'''Create a generic message using the ID and role of the sender'''
return self.message_build_custom(self.roadblock_role, self.my_id, recipient_type, recipient_id, command, value)
def message_build_custom(self, sender_type, sender_id, recipient_type, recipient_id, command, value=None):
'''Create a custom message with any user specified values'''
message = {
"payload": {
"uuid": str(uuid.uuid4()),
"roadblock": self.roadblock_uuid,
"sender": {
"timestamp": calendar.timegm(time.gmtime()),
"type": sender_type,
"id": sender_id,
},
"recipient": {
"type": recipient_type
},
"message": {
"command": command
}
},
"tx_checksum": None
}
if recipient_type != "all":
message["payload"]["recipient"]["id"] = recipient_id
if value is not None:
if command == "user-string":
message["payload"]["message"]["user-string"] = value
elif command == "user-object":
message["payload"]["message"]["user-object"] = value
else:
message["payload"]["message"]["value"] = str(value)
message["tx_checksum"] = hashlib.sha256(str(self.message_to_str(message["payload"])).encode("utf-8")).hexdigest()
return message
def message_validate(self, message):
'''Validate that a received message matches the message schema and that it is not corrupted'''
if self.message_validation == "none":
return True
if self.message_validation in [ "checksum", "all" ]:
# the checksum comparison appears to be fairly light weight so do
# that first -- no reason to continue with schema validation if
# this fails
if not bool(message["tx_checksum"] == message["rx_checksum"]):
self.logger.error("message failed checksum validation [%s]", self.message_to_str(message))
return False
else:
self.logger.debug("message passed checksum validation [%s]", self.message_to_str(message))
if self.message_validation in [ "schema", "all" ]:
try:
jsonschema.validate(instance=message, schema=self.schema)
self.logger.debug("message passed schema validation [%s]", self.message_to_str(message))
except jsonschema.exceptions.SchemaError:
self.logger.error("message failed schema validation [%s]", self.message_to_str(message))
return False
return True
def message_for_me(self, message):
'''Determine if a received message was intended for me'''
# grab the rx_timestamp ASAP after beginning to process the message
rx_timestamp = calendar.timegm(time.gmtime())
incomplete_message = False
if not "payload" in message:
incomplete_message = True
elif not "recipient" in message["payload"]:
incomplete_message = True
elif not "sender" in message["payload"]:
incomplete_message = True
elif not "id" in message["payload"]["sender"]:
incomplete_message = True
elif not "recipient" in message["payload"]:
incomplete_message = True
elif not "type" in message["payload"]["recipient"]:
incomplete_message = True
if incomplete_message:
self.logger.error("incomplete message received [%s]", self.message_to_str(message))
return False
if message["payload"]["sender"]["id"] == self.my_id and message["payload"]["sender"]["type"] == self.roadblock_role:
# I'm the sender so ignore it
return False
elif message["payload"]["recipient"]["type"] == "all":
pass
elif message["payload"]["recipient"]["type"] == self.roadblock_role and message["payload"]["recipient"]["id"] == self.my_id:
pass
else:
return False
if self.message_validation in [ "checksum", "all" ]:
# get the rx_checksum before we modify the message by adding the rx_timestamp to it
message["rx_checksum"] = hashlib.sha256(str(self.message_to_str(message["payload"])).encode("utf-8")).hexdigest()
# embed the rx_timestamp into the message
message["payload"]["recipient"]["timestamp"] = rx_timestamp
return True
def message_get_command(self, message):
'''Extract the command from a message'''
return message["payload"]["message"]["command"]
def message_get_value(self, message):
'''Extract a value from the a message'''
return message["payload"]["message"]["value"]
def message_get_sender(self, message):
'''Extract the sender ID from a message'''
return message["payload"]["sender"]["id"]
def message_get_sender_type(self, message):
'''Extract the sender type from a message'''
return message["payload"]["sender"]["type"]
def message_get_uuid(self, message):
'''Extract a message's UUID'''
return message["payload"]["uuid"]
def define_usr_msg_schema(self):
'''Define the schema used to validate user messages'''
self.user_schema = {
"type": "array",
"minItems": 1,
"uniqueItems": True,
"items": {
"oneOf": [
{
"type": "object",
"properties": {
"recipient": {
"$ref": "#/definitions/recipient"
},
"user-string": {
"type": "string",
"minLength": 1
}
},
"required": [
"recipient",
"user-string"
],
"additionalProperties": False
},
{
"type": "object",
"properties": {
"recipient": {
"$ref": "#/definitions/recipient"
},
"user-object": {
"type": "object"
}
},
"required": [
"recipient",
"user-object"
],
"additionalProperties": False
}
]
},
"definitions": {
"recipient": {
"type": "object",
"properties": {
"timestamp": {
"type": "integer"
},
"type": {
"type": "string",
"enum": [
"leader",
"follower",
"all"
]
},
"id": {
"type": "string",
"minLength": 1
}
},
"required": [
"type",
"id"
],
"additionalProperties": False
}
}
}
return 0
def define_msg_schema(self):
'''Define the schema used to validate roadblock protocol messages'''
self.schema = {
"type": "object",
"properties": {
"payload": {
"type": "object",
"properties": {
"uuid": {
"type": "string",
"minLength": 36,
"maxLength": 36
},
"roadblock": {
"type": "string",
"enum": [
self.roadblock_uuid
]
},
"sender": {
"type": "object",
"properties": {
"timestamp": {
"type": "integer"
},
"type": {
"type": "string",
"enum": [
"leader",
"follower"
]
},
"id": {
"type": "string",
"minLength": 1
}
},
"required": [
"timestamp",
"type",
"id"
],
"additionalProperties": False
},
"recipient": {
"type": "object",
"properties": {
"timestamp": {
"type": "integer"
},
"type": {
"type": "string",
"enum": [
"leader",
"follower",
"all"
]
},
"id": {
"type": "string",
"minLength": 1
}
},
"required": [
"type"
],
"additionalProperties": False,
"if": {
"properties": {
"type": {
"enum": [
"leader",
"follower"
]
}
}
},
"then": {
"required": [
"id"
]
}
},
"message": {
"type": "object",
"properties": {
"command": {
"type": "string",
"enum": [
"global-bus-created",
"leader-bus-created",
"followers-bus-created",
"personal-bus-created",
"timeout-ts",
"initialized",
"switch-buses",
"leader-online",
"follower-online",
"all-online",
"initiator-info",
"follower-ready",
"follower-ready-abort",
"follower-ready-waiting",
"leader-heartbeat",
"follower-heartbeat",
"follower-waiting-complete",
"follower-waiting-complete-failed",
"heartbeat-timeout",
"all-ready",
"all-go",
"all-abort",
"all-wait",
"follower-gone",
"all-gone",
"user-string",
"user-object"
]
},
"value": {
"type": "string",
"minLength": 1
},
"user-string": {
"type": "string",
"minLength": 1
},
"user-object": {}
},
"required": [
"command"
],
"additionalProperties": False,
"allOf": [
{
"if": {
"properties": {
"command": {
"enum": [
"timeout-ts"
]
}
}
},
"then": {
"required": [
"value"
]
}
},
{
"if": {
"properties": {
"command": {
"enum": [
"user-string"
]
}
}
},
"then": {
"required": [
"user-string"
]
}
},
{
"if": {
"properties": {
"command": {
"enum": [
"user-object"
]
}
}
},
"then": {
"required": [
"user-object"
]
}
}
]
}
},
"required": [
"uuid",
"roadblock",
"sender",
"recipient",
"message"
],
"additionalProperties": False
},
"tx_checksum": {
"type": "string",
"minLength": 64,
"maxLength": 64
},
"rx_checksum": {
"type": "string",
"minLength": 64,
"maxLength": 64
}
},
"required": [
"payload",
"tx_checksum"
],
"additionalProperties": False
}
return 0
def send_user_messages(self):
'''Send user defined messages'''
if self.user_messages is not None:
self.logger.info("Sending user requested messages")
user_msg_counter = 1
for user_msg in self.user_messages:
bus_name = "global"
if user_msg["recipient"]["id"] != "all":
bus_name = user_msg["recipient"]["id"]
if "user-string" in user_msg:
self.logger.info("Sending user message %d: 'user-string'", user_msg_counter)
self.message_publish(bus_name, self.message_build(user_msg["recipient"]["type"], user_msg["recipient"]["id"], "user-string", user_msg["user-string"]))
elif "user-object" in user_msg:
self.logger.info("Sending user message %d: 'user-object'", user_msg_counter)
self.message_publish(bus_name, self.message_build(user_msg["recipient"]["type"], user_msg["recipient"]["id"], "user-object", user_msg["user-object"]))
user_msg_counter += 1
return 0
def message_handle (self, message):
'''Roadblock protocol message handler'''
msg_uuid = self.message_get_uuid(message)
if msg_uuid in self.processed_messages:
self.logger.debug("I have already processed this message! [%s]", msg_uuid)
return self.RC_SUCCESS
else:
self.logger.debug("adding uuid='%s' to the processed messages list", msg_uuid)
self.processed_messages[msg_uuid] = True
if self.message_log is not None:
# if the message log is open then append messages to the queue
# for later dumping
self.messages["received"].append(message)
msg_command = self.message_get_command(message)
if msg_command in ("global-bus-created", "leader-bus-created", "followers-bus-created", "personal-bus-created"):
self.logger.info("Received '%s' message", msg_command)
elif msg_command == "timeout-ts":
self.logger.info("Received 'timeout-ts' message")
cluster_timeout = int(self.message_get_value(message))
mytime = calendar.timegm(time.gmtime())
timeout = mytime - cluster_timeout
if timeout < 0:
self.set_alarm(abs(timeout))
self.logger.info("The new timeout value is in %d seconds", abs(timeout))
self.logger.info("Timeout: %s", datetime.datetime.utcfromtimestamp(cluster_timeout).strftime("%Y-%m-%d at %H:%M:%S UTC"))
else:
self.disable_alarm()
self.logger.critical("The timeout has already occurred")
return self.RC_TIMEOUT
elif msg_command == "leader-online":
if self.roadblock_role == "follower":
self.logger.debug("I see that the leader is online")
elif msg_command == "follower-online":
if self.roadblock_role == "leader":
msg_sender = self.message_get_sender(message)
if msg_sender in self.followers["online"]:
self.logger.info("Received 'follower-online' message from '%s'", msg_sender)
del self.followers["online"][msg_sender]
elif msg_sender in self.roadblock_followers:
self.logger.warning("Did I already process this 'follower-online' message from follower '%s'?", msg_sender)
else:
self.logger.info("Received 'follower-online' message from unknown follower '%s'", msg_sender)
if len(self.followers["online"]) == 0:
self.logger.info("Sending 'all-online' message")
self.message_publish("followers", self.message_build("all", "all", "all-online"))
if self.initiator:
self.send_user_messages()
elif msg_command == "all-online":
if self.initiator:
self.logger.info("Initiator received 'all-online' message")
else:
self.logger.info("Received 'all-online' message")
self.send_user_messages()
if self.roadblock_role == "follower":
if self.abort:
self.logger.info("Sending 'follower-ready-abort' message")
self.message_publish("leader", self.message_build("leader", self.roadblock_leader_id, "follower-ready-abort"))
else:
if self.wait_for is not None and self.wait_for_process is not None and self.wait_for_process.poll() is None:
self.wait_for_waiting = True
self.logger.info("Sending 'follower-ready-waiting' message")
self.message_publish("leader", self.message_build("leader", self.roadblock_leader_id, "follower-ready-waiting"))
else:
self.logger.info("Sending 'follower-ready' message")
self.message_publish("leader", self.message_build("leader", self.roadblock_leader_id, "follower-ready"))
elif msg_command in ("follower-ready", "follower-ready-abort", "follower-ready-waiting"):
if self.roadblock_role == "leader":
self.logger.debug("leader got a '%s' message", msg_command)
msg_sender = self.message_get_sender(message)
if msg_command == "follower-ready-abort":
self.leader_abort = True
elif msg_command == "follower-ready-waiting":
self.roadblock_waiting = True
self.logger.info("Adding follower '%s' to the waiting list", msg_sender)
self.followers["busy_waiting"][msg_sender] = True
if msg_sender in self.followers["ready"]:
self.logger.info("Received '%s' message from '%s'", msg_command, msg_sender)
del self.followers["ready"][msg_sender]
elif msg_sender in self.roadblock_followers:
self.logger.warning("Received a redundant '%s' message from follower '%s'?", msg_command, msg_sender)
else:
self.logger.info("Received '%s' message from unknown follower '%s'", msg_command, msg_sender)
if len(self.followers["ready"]) == 0:
self.logger.info("Sending 'all-ready' message")
self.message_publish("followers", self.message_build("all", "all", "all-ready"))
if self.leader_abort:
self.logger.info("Sending 'all-abort' command")
self.message_publish("followers", self.message_build("all", "all", "all-abort"))
elif self.roadblock_waiting:
self.logger.info("Sending 'all-wait' command")
self.message_publish("followers", self.message_build("all", "all", "all-wait"))
self.logger.info("Disabling original timeout")
self.disable_alarm()
self.logger.info("Disabling original timeout signal handler")
self.logger.info("Enabling heartbeat timeout signal handler")
signal.signal(signal.SIGALRM, self.heartbeat_signal_handler)
self.logger.info("Sending 'leader-heartbeat' message")
self.message_publish("followers", self.message_build("all", "all", "leader-heartbeat"))
self.logger.info("Starting heartbeat monitoring period")
self.set_alarm(self.heartbeat_timeout)
else:
self.logger.info("Sending 'all-go' command")
self.message_publish("followers", self.message_build("all", "all", "all-go"))
elif msg_command == "all-wait":
if self.roadblock_role == "follower":
self.logger.info("Received 'all-wait' message")
self.logger.info("Disabling original timeout")
self.disable_alarm()
elif msg_command == "leader-heartbeat":
if self.roadblock_role == "follower":
self.logger.info("Received 'leader-heartbeat' message")
if self.simulate_heartbeat_timeout:
self.logger.critical("Not sending 'follower-heartbeat' because of heartbeat timeout simulation request")
else:
self.logger.info("Sending 'follower-heartbeat' message")
self.message_publish("leader", self.message_build("leader", self.roadblock_leader_id, "follower-heartbeat"))
elif msg_command == "follower-heartbeat":
if self.roadblock_role == "leader":
self.logger.info("Received '%s' message", msg_command)
msg_sender = self.message_get_sender(message)
if msg_sender in self.followers["waiting"]:
self.logger.info("Received heartbeat from follower '%s'", msg_sender)
del self.followers["waiting"][msg_sender]
elif msg_sender in self.roadblock_followers:
self.logger.warning("Received a redundant heartbeat message from follower '%s'?", msg_sender)
else:
self.logger.warning("Received a heartbeat message from an unknown follower '%s'", msg_sender)
if len(self.followers["busy_waiting"]) == 0 and len(self.followers["waiting"]) == 0:
self.logger.info("Disabling heartbeat timeout")
self.disable_alarm()
if self.waiting_failed:
self.leader_abort = True
self.logger.info("Sending 'all-abort' command")
self.message_publish("followers", self.message_build("all", "all", "all-abort"))
else:
self.logger.info("Sending 'all-go' command")
self.message_publish("followers", self.message_build("all", "all", "all-go"))
elif msg_command in ("follower-waiting-complete", "follower-waiting-complete-failed"):
if self.roadblock_role == "leader":
self.logger.info("Received '%s' message", msg_command)
msg_sender = self.message_get_sender(message)
if msg_sender in self.followers["busy_waiting"]:
self.logger.info("Follower '%s' is no longer busy waiting", msg_sender)
del self.followers["busy_waiting"][msg_sender]
if msg_command == "follower-waiting-complete-failed":
self.waiting_failed = True
elif msg_sender in self.roadblock_followers:
self.logger.warning("Received '%s' from a follower '%s' that is not busy waiting?", msg_command, msg_sender)
else:
self.logger.info("Received '%s' message from an unknown follower '%s'", msg_command, msg_sender)
if len(self.followers["busy_waiting"]) == 0 or self.waiting_failed:
self.logger.info("Disabling heartbeat timeout")
self.disable_alarm()
if self.waiting_failed:
self.leader_abort_waiting = True
self.logger.info("Sending 'all-abort' command")
self.message_publish("followers", self.message_build("all", "all", "all-abort"))
else:
self.logger.info("Sending 'all-go' command")
self.message_publish("followers", self.message_build("all", "all", "all-go"))
elif msg_command == "heartbeat-timeout":
if self.roadblock_role == "follower":
self.logger.info("Received '%s' message", msg_command)
self.logger.critical("Roadblock failed due to a heartbeat timeout")
self.timeout_internals()
# signal myself to exit
self.watch_bus = False
self.rc = self.RC_HEARTBEAT_TIMEOUT
return self.rc
elif msg_command == "all-ready":
self.logger.info("Received 'all-ready' message")
elif msg_command in ("all-go", "all-abort"):
if self.roadblock_role == "follower":
if msg_command == "all-go":
self.logger.info("Received 'all-go' from leader")
else:
self.logger.info("Received 'all-abort' from leader")
self.follower_abort = True
if self.wait_for is not None and self.wait_for_process is not None:
self.logger.critical("Killing wait_for process due to 'all-abort' from leader")
self.wait_for_process.kill()
# tell the leader that I'm gone
self.logger.info("Sending 'follower-gone' message")
self.message_publish("leader", self.message_build("leader", self.roadblock_leader_id, "follower-gone"))
# signal myself to exit
self.watch_bus = False
elif msg_command == "follower-gone":
if self.roadblock_role == "leader":
self.logger.debug("leader got a 'follower-gone' message")
msg_sender = self.message_get_sender(message)
if msg_sender in self.followers["gone"]:
self.logger.info("Received 'follower-gone' message from '%s'", msg_sender)
del self.followers["gone"][msg_sender]
elif msg_sender in self.roadblock_followers:
self.logger.warning("Received a redundant 'follower-gone' message from follower '%s'?", msg_sender)
else:
self.logger.info("Received 'follower-gone' message from unknown follower '%s'", msg_sender)
if len(self.followers["gone"]) == 0:
# send a message that will probably not be observed by
# anyone...but just in case...
self.logger.info("Sending 'all-gone' message")
self.message_publish("followers", self.message_build("all", "all", "all-gone"))
# signal myself to exit
self.watch_bus = False
elif msg_command == "initiator-info":
self.initiator_type = self.message_get_sender_type(message)
self.initiator_id = self.message_get_sender(message)
self.logger.debug("Received an 'initiator-info' message with type='%s' and id='%s'", self.initiator_type, self.initiator_id)
return self.RC_SUCCESS
def message_publish(self, message_bus, message):
'''Publish messages for subscribers to receive'''
ret_val = 0
counter = 0
self.logger.debug("Attempting to publish message '%s' on bus '%s'", message, message_bus)
while ret_val == 0:
if self.rc != 0:
self.logger.debug("self.rc != 0 --> breaking")
break
counter += 1
try:
ret_val = self.redcon.xadd(self.roadblock_uuid + "__bus__" + message_bus, { 'msg': self.message_to_str(message) })
except redis.exceptions.ConnectionError as con_error:
self.logger.error("%s", con_error)
self.logger.error("Bus add to '%s' failed due to connection error!", message_bus)
except redis.exceptions.TimeoutError as con_error:
self.logger.error("%s", con_error)
self.logger.error("Bus add to '%s' failed due to a timeout error!", message_bus)
if ret_val is None:
self.logger.warning("Failed attempt %d to publish message '%s' to bus '%s'", counter, message, message_bus)