-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathsynchronizer.py
More file actions
1203 lines (986 loc) · 41.3 KB
/
Copy pathsynchronizer.py
File metadata and controls
1203 lines (986 loc) · 41.3 KB
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
"""Synchronizer module."""
import abc
import logging
import threading
import time
from collections import namedtuple
from splitio.optional.loaders import asyncio
from splitio.api import APIException, APIUriException
from splitio.util.backoff import Backoff
from splitio.sync.split import _ON_DEMAND_FETCH_BACKOFF_BASE, _ON_DEMAND_FETCH_BACKOFF_MAX_RETRIES, _ON_DEMAND_FETCH_BACKOFF_MAX_WAIT, LocalhostMode
SplitSyncResult = namedtuple('SplitSyncResult', ['success', 'error_code'])
_LOGGER = logging.getLogger(__name__)
_SYNC_ALL_NO_RETRIES = -1
class SplitSynchronizers(object):
"""SplitSynchronizers."""
def __init__(self, feature_flag_sync, segment_sync, impressions_sync, events_sync, # pylint:disable=too-many-arguments
impressions_count_sync, telemetry_sync=None, unique_keys_sync = None, clear_filter_sync = None):
"""
Class constructor.
:param feature_flag_sync: sync for feature flags
:type feature_flag_sync: splitio.sync.split.SplitSynchronizer
:param segment_sync: sync for segments
:type segment_sync: splitio.sync.segment.SegmentSynchronizer
:param impressions_sync: sync for impressions
:type impressions_sync: splitio.sync.impression.ImpressionSynchronizer
:param events_sync: sync for events
:type events_sync: splitio.sync.event.EventSynchronizer
:param impressions_count_sync: sync for impression_counts
:type impressions_count_sync: splitio.sync.impression.ImpressionsCountSynchronizer
"""
self._feature_flag_sync = feature_flag_sync
self._segment_sync = segment_sync
self._impressions_sync = impressions_sync
self._events_sync = events_sync
self._impressions_count_sync = impressions_count_sync
self._unique_keys_sync = unique_keys_sync
self._clear_filter_sync = clear_filter_sync
self._telemetry_sync = telemetry_sync
@property
def split_sync(self):
"""Return split synchonizer."""
return self._feature_flag_sync
@property
def segment_sync(self):
"""Return segment synchonizer."""
return self._segment_sync
@property
def impressions_sync(self):
"""Return impressions synchonizer."""
return self._impressions_sync
@property
def events_sync(self):
"""Return events synchonizer."""
return self._events_sync
@property
def impressions_count_sync(self):
"""Return impressions count synchonizer."""
return self._impressions_count_sync
@property
def unique_keys_sync(self):
"""Return unique keys synchonizer."""
return self._unique_keys_sync
@property
def clear_filter_sync(self):
"""Return clear filter synchonizer."""
return self._clear_filter_sync
@property
def telemetry_sync(self):
"""Return clear filter synchonizer."""
return self._telemetry_sync
class SplitTasks(object):
"""SplitTasks."""
def __init__(self, feature_flag_task, segment_task, impressions_task, events_task, # pylint:disable=too-many-arguments
impressions_count_task, telemetry_task=None, unique_keys_task = None, clear_filter_task = None, internal_events_task=None):
"""
Class constructor.
:param feature_flag_task: sync for feature_flags
:type feature_flag_task: splitio.tasks.split_sync.SplitSynchronizationTask
:param segment_task: sync for segments
:type segment_task: splitio.tasks.segment_sync.SegmentSynchronizationTask
:param impressions_task: sync for impressions
:type impressions_task: splitio.tasks.impressions_sync.ImpressionsSyncTask
:param events_task: sync for events
:type events_task: splitio.tasks.events_sync.EventsSyncTask
:param impressions_count_task: sync for impression_counts
:type impressions_count_task: splitio.tasks.impressions_sync.ImpressionsCountSyncTask
"""
self._feature_flag_task = feature_flag_task
self._segment_task = segment_task
self._impressions_task = impressions_task
self._events_task = events_task
self._impressions_count_task = impressions_count_task
self._unique_keys_task = unique_keys_task
self._clear_filter_task = clear_filter_task
self._telemetry_task = telemetry_task
self._internal_events_task = internal_events_task
@property
def split_task(self):
"""Return feature_flag sync task."""
return self._feature_flag_task
@property
def segment_task(self):
"""Return segment sync task."""
return self._segment_task
@property
def impressions_task(self):
"""Return impressions sync task."""
return self._impressions_task
@property
def events_task(self):
"""Return events sync task."""
return self._events_task
@property
def impressions_count_task(self):
"""Return impressions count sync task."""
return self._impressions_count_task
@property
def unique_keys_task(self):
"""Return unique keys sync task."""
return self._unique_keys_task
@property
def clear_filter_task(self):
"""Return clear filter sync task."""
return self._clear_filter_task
@property
def telemetry_task(self):
"""Return clear filter sync task."""
return self._telemetry_task
@property
def internal_events_task(self):
"""Return internal events task."""
return self._internal_events_task
class BaseSynchronizer(object, metaclass=abc.ABCMeta):
"""Synchronizer interface."""
@abc.abstractmethod
def synchronize_segment(self, segment_name, till):
"""
Synchronize particular segment.
:param segment_name: segment associated
:type segment_name: str
:param till: to fetch
:type till: int
"""
pass
@abc.abstractmethod
def synchronize_splits(self, till):
"""
Synchronize all feature flags.
:param till: to fetch
:type till: int
"""
pass
@abc.abstractmethod
def sync_all(self):
"""Synchronize all feature flag data."""
pass
@abc.abstractmethod
def start_periodic_fetching(self):
"""Start fetchers for feature flags and segments."""
pass
@abc.abstractmethod
def stop_periodic_fetching(self):
"""Stop fetchers for feature flags and segments."""
pass
@abc.abstractmethod
def start_periodic_data_recording(self):
"""Start recorders."""
pass
@abc.abstractmethod
def stop_periodic_data_recording(self, blocking):
"""Stop recorders."""
pass
@abc.abstractmethod
def kill_split(self, feature_flag_name, default_treatment, change_number):
"""
Kill a feature flag locally.
:param feature_flag_name: name of the feature flag to perform kill
:type feature_flag_name: str
:param default_treatment: name of the default treatment to return
:type default_treatment: str
:param change_number: change_number
:type change_number: int
"""
pass
@abc.abstractmethod
def shutdown(self, blocking):
"""
Stop tasks.
:param blocking:flag to wait until tasks are stopped
:type blocking: bool
"""
pass
class SynchronizerInMemoryBase(BaseSynchronizer):
"""Synchronizer."""
def __init__(self, split_synchronizers, split_tasks):
"""
Class constructor.
:param split_synchronizers: syncs for performing synchronization of segments and feature flags
:type split_synchronizers: splitio.sync.synchronizer.SplitSynchronizers
:param split_tasks: tasks for starting/stopping tasks
:type split_tasks: splitio.sync.synchronizer.SplitTasks
"""
self._backoff = Backoff(
_ON_DEMAND_FETCH_BACKOFF_BASE,
_ON_DEMAND_FETCH_BACKOFF_MAX_WAIT)
self._split_synchronizers = split_synchronizers
self._split_tasks = split_tasks
self._periodic_data_recording_tasks = [
self._split_tasks.impressions_task,
self._split_tasks.events_task,
self._split_tasks.telemetry_task
]
if self._split_tasks.impressions_count_task:
self._periodic_data_recording_tasks.append(self._split_tasks.impressions_count_task)
if self._split_tasks.unique_keys_task:
self._periodic_data_recording_tasks.append(self._split_tasks.unique_keys_task)
if self._split_tasks.clear_filter_task:
self._periodic_data_recording_tasks.append(self._split_tasks.clear_filter_task)
@property
def split_sync(self):
return self._split_synchronizers.split_sync
@property
def segment_storage(self):
return self._split_synchronizers.segment_sync._segment_storage
def synchronize_segment(self, segment_name, till):
"""
Synchronize particular segment.
:param segment_name: segment associated
:type segment_name: str
:param till: to fetch
:type till: int
"""
pass
def synchronize_splits(self, till, sync_segments=True):
"""
Synchronize all feature flags.
:param till: to fetch
:type till: int
:returns: whether the synchronization was successful or not.
:rtype: bool
"""
pass
def sync_all(self, max_retry_attempts=_SYNC_ALL_NO_RETRIES):
"""
Synchronize all feature flags.
:param max_retry_attempts: apply max attempts if it set to absilute integer.
:type max_retry_attempts: int
"""
pass
def shutdown(self, blocking):
"""
Stop tasks.
:param blocking:flag to wait until tasks are stopped
:type blocking: bool
"""
pass
def start_periodic_fetching(self):
"""Start fetchers for feature flags and segments."""
_LOGGER.debug('Starting periodic data fetching')
self._split_tasks.split_task.start()
self._split_tasks.segment_task.start()
def stop_periodic_fetching(self):
"""Stop fetchers for feature flags and segments."""
pass
def start_periodic_data_recording(self):
"""Start recorders."""
_LOGGER.debug('Starting periodic data recording')
for task in self._periodic_data_recording_tasks:
task.start()
def stop_periodic_data_recording(self, blocking):
"""
Stop recorders.
:param blocking: flag to wait until tasks are stopped
:type blocking: bool
"""
pass
def kill_split(self, feature_flag_name, default_treatment, change_number):
"""
Kill a feature flag locally.
:param feature_flag_name: name of the feature flag to perform kill
:type feature_flag_name: str
:param default_treatment: name of the default treatment to return
:type default_treatment: str
:param change_number: change_number
:type change_number: int
"""
pass
class Synchronizer(SynchronizerInMemoryBase):
"""Synchronizer."""
def __init__(self, split_synchronizers, split_tasks):
"""
Class constructor.
:param split_synchronizers: syncs for performing synchronization of segments and feature flags
:type split_synchronizers: splitio.sync.synchronizer.SplitSynchronizers
:param split_tasks: tasks for starting/stopping tasks
:type split_tasks: splitio.sync.synchronizer.SplitTasks
"""
SynchronizerInMemoryBase.__init__(self, split_synchronizers, split_tasks)
def _synchronize_segments(self):
_LOGGER.debug('Starting segments synchronization')
return self._split_synchronizers.segment_sync.synchronize_segments()
def synchronize_segment(self, segment_name, till):
"""
Synchronize particular segment.
:param segment_name: segment associated
:type segment_name: str
:param till: to fetch
:type till: int
"""
_LOGGER.debug('Synchronizing segment %s', segment_name)
success = self._split_synchronizers.segment_sync.synchronize_segment(segment_name, till)
if not success:
_LOGGER.error('Failed to sync some segments.')
return success
def synchronize_splits(self, till, sync_segments=True):
"""
Synchronize all feature flags.
:param till: to fetch
:type till: int
:returns: whether the synchronization was successful or not.
:rtype: bool
"""
_LOGGER.debug('Starting feature flags synchronization')
try:
new_segments = []
for segment in self._split_synchronizers.split_sync.synchronize_splits(till):
if not self._split_synchronizers.segment_sync.segment_exist_in_storage(segment):
new_segments.append(segment)
if sync_segments and len(new_segments) != 0:
_LOGGER.debug('Synching Segments: %s', ','.join(new_segments))
success = self._split_synchronizers.segment_sync.synchronize_segments(new_segments, True)
if not success:
_LOGGER.error('Failed to schedule sync one or all segment(s) below.')
_LOGGER.error(','.join(new_segments))
else:
_LOGGER.debug('Segment sync scheduled.')
return SplitSyncResult(True, 0)
except APIUriException as exc:
_LOGGER.error('Failed syncing feature flags due to long URI')
_LOGGER.debug('Error: ', exc_info=True)
return SplitSyncResult(False, exc._status_code)
except APIException as exc:
_LOGGER.error('Failed syncing feature flags')
_LOGGER.debug('Error: ', exc_info=True)
return SplitSyncResult(False, exc._status_code)
def sync_all(self, max_retry_attempts=_SYNC_ALL_NO_RETRIES):
"""
Synchronize all feature flags.
:param max_retry_attempts: apply max attempts if it set to absilute integer.
:type max_retry_attempts: int
"""
retry_attempts = 0
while True:
try:
sync_result = self.synchronize_splits(None, False)
if not sync_result.success and sync_result.error_code is not None and sync_result.error_code == 414:
_LOGGER.error("URI too long exception caught, aborting retries")
break
if not sync_result.success:
raise Exception("feature flags sync failed")
# Only retrying feature flags, since segments may trigger too many calls.
if not self._synchronize_segments():
_LOGGER.warning('Segments failed to synchronize.')
# All is good
return
except Exception as exc: # pylint:disable=broad-except
_LOGGER.error("Exception caught when trying to sync all data: %s", str(exc))
_LOGGER.debug('Error: ', exc_info=True)
if max_retry_attempts != _SYNC_ALL_NO_RETRIES:
retry_attempts += 1
if retry_attempts > max_retry_attempts:
break
how_long = self._backoff.get()
time.sleep(how_long)
_LOGGER.error("Could not correctly synchronize feature flags and segments after %d attempts.", retry_attempts)
def shutdown(self, blocking):
"""
Stop tasks.
:param blocking:flag to wait until tasks are stopped
:type blocking: bool
"""
_LOGGER.debug('Shutting down tasks.')
self._split_synchronizers.segment_sync.shutdown()
self.stop_periodic_fetching()
self.stop_periodic_data_recording(blocking)
def stop_periodic_fetching(self):
"""Stop fetchers for feature flags and segments."""
_LOGGER.debug('Stopping periodic fetching')
self._split_tasks.split_task.stop()
self._split_tasks.segment_task.stop()
def stop_periodic_data_recording(self, blocking):
"""
Stop recorders.
:param blocking: flag to wait until tasks are stopped
:type blocking: bool
"""
_LOGGER.debug('Stopping periodic data recording')
if self._split_tasks.internal_events_task:
self._split_tasks.internal_events_task.stop()
if blocking:
events = []
for task in self._periodic_data_recording_tasks:
if task != self._split_tasks.telemetry_task:
stop_event = threading.Event()
task.stop(stop_event)
events.append(stop_event)
all(event.wait() for event in events)
telemetry_event = threading.Event()
self._split_tasks.telemetry_task.stop(telemetry_event)
if telemetry_event.wait():
_LOGGER.debug('all tasks finished successfully.')
else:
for task in self._periodic_data_recording_tasks:
task.stop()
def kill_split(self, feature_flag_name, default_treatment, change_number):
"""
Kill a feature flag locally.
:param feature_flag_name: name of the feature flag to perform kill
:type feature_flag_name: str
:param default_treatment: name of the default treatment to return
:type default_treatment: str
:param change_number: change_number
:type change_number: int
"""
self._split_synchronizers.split_sync.kill_split(feature_flag_name, default_treatment,
change_number)
class SynchronizerAsync(SynchronizerInMemoryBase):
"""Synchronizer async."""
def __init__(self, split_synchronizers, split_tasks):
"""
Class constructor.
:param split_synchronizers: syncs for performing synchronization of segments and feature flags
:type split_synchronizers: splitio.sync.synchronizer.SplitSynchronizers
:param split_tasks: tasks for starting/stopping tasks
:type split_tasks: splitio.sync.synchronizer.SplitTasks
"""
SynchronizerInMemoryBase.__init__(self, split_synchronizers, split_tasks)
self._shutdown = False
async def _synchronize_segments(self):
_LOGGER.debug('Starting segments synchronization')
return await self._split_synchronizers.segment_sync.synchronize_segments()
async def synchronize_segment(self, segment_name, till):
"""
Synchronize particular segment.
:param segment_name: segment associated
:type segment_name: str
:param till: to fetch
:type till: int
"""
_LOGGER.debug('Synchronizing segment %s', segment_name)
success = await self._split_synchronizers.segment_sync.synchronize_segment(segment_name, till)
if not success:
_LOGGER.error('Failed to sync some segments.')
return success
async def synchronize_splits(self, till, sync_segments=True):
"""
Synchronize all feature flags.
:param till: to fetch
:type till: int
:returns: whether the synchronization was successful or not.
:rtype: bool
"""
if self._shutdown:
return
_LOGGER.debug('Starting feature flags synchronization')
try:
new_segments = []
for segment in await self._split_synchronizers.split_sync.synchronize_splits(till):
if not await self._split_synchronizers.segment_sync.segment_exist_in_storage(segment):
new_segments.append(segment)
if sync_segments and len(new_segments) != 0:
_LOGGER.debug('Synching Segments: %s', ','.join(new_segments))
success = await self._split_synchronizers.segment_sync.synchronize_segments(new_segments, True)
if not success:
_LOGGER.error('Failed to schedule sync one or all segment(s) below.')
_LOGGER.error(','.join(new_segments))
else:
_LOGGER.debug('Segment sync scheduled.')
return SplitSyncResult(True, 0)
except APIUriException as exc:
_LOGGER.error('Failed syncing feature flags due to long URI')
_LOGGER.debug('Error: ', exc_info=True)
return SplitSyncResult(False, exc._status_code)
except APIException as exc:
_LOGGER.error('Failed syncing feature flags')
_LOGGER.debug('Error: ', exc_info=True)
return SplitSyncResult(False, exc._status_code)
async def sync_all(self, max_retry_attempts=_SYNC_ALL_NO_RETRIES):
"""
Synchronize all feature flags.
:param max_retry_attempts: apply max attempts if it set to absilute integer.
:type max_retry_attempts: int
"""
self._shutdown = False
retry_attempts = 0
while not self._shutdown:
try:
sync_result = await self.synchronize_splits(None, False)
if not sync_result.success and sync_result.error_code is not None and sync_result.error_code == 414:
_LOGGER.error("URI too long exception caught, aborting retries")
break
if not sync_result.success:
raise Exception("feature flags sync failed")
# Only retrying feature flags, since segments may trigger too many calls.
if not await self._synchronize_segments():
_LOGGER.warning('Segments failed to synchronize.')
# All is good
return
except Exception as exc: # pylint:disable=broad-except
_LOGGER.error("Exception caught when trying to sync all data: %s", str(exc))
_LOGGER.debug('Error: ', exc_info=True)
if max_retry_attempts != _SYNC_ALL_NO_RETRIES:
retry_attempts += 1
if retry_attempts > max_retry_attempts:
break
how_long = self._backoff.get()
if not self._shutdown:
await asyncio.sleep(how_long)
_LOGGER.error("Could not correctly synchronize feature flags and segments after %d attempts.", retry_attempts)
async def shutdown(self, blocking):
"""
Stop tasks.
:param blocking:flag to wait until tasks are stopped
:type blocking: bool
"""
_LOGGER.debug('Shutting down tasks.')
self._shutdown = True
await self._split_synchronizers.segment_sync.shutdown()
await self.stop_periodic_fetching()
await self.stop_periodic_data_recording(blocking)
async def stop_periodic_fetching(self):
"""Stop fetchers for feature flags and segments."""
_LOGGER.debug('Stopping periodic fetching')
await self._split_tasks.split_task.stop()
await self._split_tasks.segment_task.stop()
async def stop_periodic_data_recording(self, blocking):
"""
Stop recorders.
:param blocking: flag to wait until tasks are stopped
:type blocking: bool
"""
_LOGGER.debug('Stopping periodic data recording')
if self._split_tasks.internal_events_task:
await self._split_tasks.internal_events_task.stop()
if blocking:
await self._stop_periodic_data_recording()
_LOGGER.debug('all tasks finished successfully.')
else:
asyncio.get_running_loop().create_task(self._stop_periodic_data_recording())
async def _stop_periodic_data_recording(self):
"""
Stop recorders.
:param blocking: flag to wait until tasks are stopped
:type blocking: bool
"""
for task in self._periodic_data_recording_tasks:
await task.stop()
async def kill_split(self, feature_flag_name, default_treatment, change_number):
"""
Kill a feature flag locally.
:param feature_flag_name: name of the feature flag to perform kill
:type feature_flag_name: str
:param default_treatment: name of the default treatment to return
:type default_treatment: str
:param change_number: change_number
:type change_number: int
"""
await self._split_synchronizers.split_sync.kill_split(feature_flag_name, default_treatment,
change_number)
class RedisSynchronizerBase(BaseSynchronizer):
"""Redis Synchronizer."""
def __init__(self, split_synchronizers, split_tasks):
"""
Class constructor.
:param split_synchronizers: syncs for performing synchronization of segments and feature flags
:type split_synchronizers: splitio.sync.synchronizer.SplitSynchronizers
:param split_tasks: tasks for starting/stopping tasks
:type split_tasks: splitio.sync.synchronizer.SplitTasks
"""
self._split_synchronizers = split_synchronizers
self._tasks = []
if split_tasks.impressions_count_task is not None:
self._tasks.append(split_tasks.impressions_count_task)
if split_tasks.unique_keys_task is not None:
self._tasks.append(split_tasks.unique_keys_task)
if split_tasks.clear_filter_task is not None:
self._tasks.append(split_tasks.clear_filter_task)
def sync_all(self):
"""
Not implemented
"""
pass
def shutdown(self, blocking):
"""
Stop tasks.
:param blocking:flag to wait until tasks are stopped
:type blocking: bool
"""
pass
def start_periodic_data_recording(self):
"""Start recorders."""
_LOGGER.debug('Starting periodic data recording')
for task in self._tasks:
task.start()
def stop_periodic_data_recording(self, blocking):
"""
Stop recorders.
:param blocking: flag to wait until tasks are stopped
:type blocking: bool
"""
pass
def kill_split(self, feature_flag_name, default_treatment, change_number):
"""Kill a feature flag locally."""
raise NotImplementedError()
def synchronize_splits(self, till):
"""Synchronize all feature flags."""
raise NotImplementedError()
def synchronize_segment(self, segment_name, till):
"""Synchronize particular segment."""
raise NotImplementedError()
def start_periodic_fetching(self):
"""Start fetchers for feature flags and segments."""
raise NotImplementedError()
def stop_periodic_fetching(self):
"""Stop fetchers for feature flags and segments."""
raise NotImplementedError()
class RedisSynchronizer(RedisSynchronizerBase):
"""Redis Synchronizer."""
def __init__(self, split_synchronizers, split_tasks):
"""
Class constructor.
:param split_synchronizers: syncs for performing synchronization of segments and feature flags
:type split_synchronizers: splitio.sync.synchronizer.SplitSynchronizers
:param split_tasks: tasks for starting/stopping tasks
:type split_tasks: splitio.sync.synchronizer.SplitTasks
"""
RedisSynchronizerBase.__init__(self, split_synchronizers, split_tasks)
def shutdown(self, blocking):
"""
Stop tasks.
:param blocking:flag to wait until tasks are stopped
:type blocking: bool
"""
_LOGGER.debug('Shutting down tasks.')
self.stop_periodic_data_recording(blocking)
def stop_periodic_data_recording(self, blocking):
"""
Stop recorders.
:param blocking: flag to wait until tasks are stopped
:type blocking: bool
"""
_LOGGER.debug('Stopping periodic data recording')
if blocking:
events = []
for task in self._tasks:
stop_event = threading.Event()
task.stop(stop_event)
events.append(stop_event)
if all(event.wait() for event in events):
_LOGGER.debug('all tasks finished successfully.')
else:
for task in self._tasks:
task.stop()
class RedisSynchronizerAsync(RedisSynchronizerBase):
"""Redis Synchronizer."""
def __init__(self, split_synchronizers, split_tasks):
"""
Class constructor.
:param split_synchronizers: syncs for performing synchronization of segments and feature flags
:type split_synchronizers: splitio.sync.synchronizer.SplitSynchronizers
:param split_tasks: tasks for starting/stopping tasks
:type split_tasks: splitio.sync.synchronizer.SplitTasks
"""
RedisSynchronizerBase.__init__(self, split_synchronizers, split_tasks)
async def shutdown(self, blocking):
"""
Stop tasks.
:param blocking:flag to wait until tasks are stopped
:type blocking: bool
"""
_LOGGER.debug('Shutting down tasks.')
await self.stop_periodic_data_recording(blocking)
async def _stop_periodic_data_recording(self):
"""
Stop recorders.
"""
for task in self._tasks:
await task.stop()
async def stop_periodic_data_recording(self, blocking):
"""
Stop recorders.
:param blocking: flag to wait until tasks are stopped
:type blocking: bool
"""
_LOGGER.debug('Stopping periodic data recording')
if blocking:
await self._stop_periodic_data_recording()
_LOGGER.debug('all tasks finished successfully.')
else:
asyncio.get_running_loop().create_task(self._stop_periodic_data_recording)
class LocalhostSynchronizerBase(BaseSynchronizer):
"""LocalhostSynchronizer base."""
def __init__(self, split_synchronizers, split_tasks, localhost_mode):
"""
Class constructor.
:param split_synchronizers: syncs for performing synchronization of segments and feature flags
:type split_synchronizers: splitio.sync.synchronizer.SplitSynchronizers
:param split_tasks: tasks for starting/stopping tasks
:type split_tasks: splitio.sync.synchronizer.SplitTasks
"""
self._split_synchronizers = split_synchronizers
self._split_tasks = split_tasks
self._localhost_mode = localhost_mode
self._backoff = Backoff(
_ON_DEMAND_FETCH_BACKOFF_BASE,
_ON_DEMAND_FETCH_BACKOFF_MAX_WAIT)
def sync_all(self, till=None):
"""
Synchronize all feature flags.
"""
# TODO: to be removed when legacy and yaml use BUR
pass
def start_periodic_fetching(self):
"""Start fetchers for feature flags and segments."""
if self._split_tasks.split_task is not None:
_LOGGER.debug('Starting periodic data fetching')
self._split_tasks.split_task.start()
if self._split_tasks.segment_task is not None:
self._split_tasks.segment_task.start()
def stop_periodic_fetching(self):
"""Stop fetchers for feature flags and segments."""
pass
def kill_split(self, split_name, default_treatment, change_number):
"""Kill a feature flag locally."""
raise NotImplementedError()
def synchronize_splits(self):
"""Synchronize all feature flags."""
pass
def synchronize_segment(self, segment_name, till):
"""Synchronize particular segment."""
pass
def start_periodic_data_recording(self):
"""Start recorders."""
pass
def stop_periodic_data_recording(self, blocking):
"""Stop recorders."""
pass
def shutdown(self, blocking):
"""
Stop tasks.
:param blocking:flag to wait until tasks are stopped
:type blocking: bool
"""
pass
class LocalhostSynchronizer(LocalhostSynchronizerBase):
"""LocalhostSynchronizer."""
def __init__(self, split_synchronizers, split_tasks, localhost_mode):
"""
Class constructor.
:param split_synchronizers: syncs for performing synchronization of segments and feature flags
:type split_synchronizers: splitio.sync.synchronizer.SplitSynchronizers
:param split_tasks: tasks for starting/stopping tasks
:type split_tasks: splitio.sync.synchronizer.SplitTasks
"""
LocalhostSynchronizerBase.__init__(self, split_synchronizers, split_tasks, localhost_mode)
def sync_all(self, till=None):
"""
Synchronize all feature flags.
"""
# TODO: to be removed when legacy and yaml use BUR
if self._localhost_mode != LocalhostMode.JSON:
return self.synchronize_splits()
self._backoff.reset()
remaining_attempts = _ON_DEMAND_FETCH_BACKOFF_MAX_RETRIES
while remaining_attempts > 0:
remaining_attempts -= 1
try:
return self.synchronize_splits()
except APIException as exc:
_LOGGER.error('Failed syncing all')
_LOGGER.error(str(exc))
how_long = self._backoff.get()
time.sleep(how_long)
def stop_periodic_fetching(self):
"""Stop fetchers for feature flags and segments."""
_LOGGER.debug('Stopping periodic fetching')
if self._split_tasks.split_task is not None:
self._split_tasks.split_task.stop()
if self._split_tasks.segment_task is not None:
self._split_tasks.segment_task.stop()
if self._split_tasks.internal_events_task:
_LOGGER.debug('Stopping internal events notification')
self._split_tasks.internal_events_task.stop()
def synchronize_splits(self):
"""Synchronize all feature flags."""
try:
new_segments = []
for segment in self._split_synchronizers.split_sync.synchronize_splits():
if not self._split_synchronizers.segment_sync.segment_exist_in_storage(segment):
new_segments.append(segment)
if len(new_segments) > 0:
_LOGGER.debug('Synching Segments: %s', ','.join(new_segments))
success = self._split_synchronizers.segment_sync.synchronize_segments(new_segments)
if not success:
_LOGGER.error('Failed to schedule sync one or all segment(s) below.')
_LOGGER.error(','.join(new_segments))
else:
_LOGGER.debug('Segment sync scheduled.')
return True
except APIException as exc:
_LOGGER.error('Failed syncing feature flags')
raise APIException('Failed to sync feature flags') from exc
def shutdown(self, blocking):
"""
Stop tasks.
:param blocking:flag to wait until tasks are stopped
:type blocking: bool
"""
self.stop_periodic_fetching()
class LocalhostSynchronizerAsync(LocalhostSynchronizerBase):
"""LocalhostSynchronizer Async."""