Repository navigation
Expand file tree
/
Copy pathsynchronizer.py
More file actions
669 lines (557 loc) · 22.9 KB
/
Copy pathsynchronizer.py
File metadata and controls
669 lines (557 loc) · 22.9 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
"""Synchronizer module."""
import abc
import logging
import threading
import time
from splitio.api import APIException
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
_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):
"""
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
@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
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 Synchronizer(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)
self._break_sync_all = False
@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_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
"""
self._break_sync_all = False
_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 True
except APIException as exc:
if exc._status_code is not None and exc._status_code == 414:
self._break_sync_all = True
_LOGGER.error('Failed syncing feature flags')
_LOGGER.debug('Error: ', exc_info=True)
return False
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:
if not self.synchronize_splits(None, False):
raise Exception("split 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 or self._break_sync_all:
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 _retry_block(self, max_retry_attempts, retry_attempts):
return 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 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."""
_LOGGER.debug('Stopping periodic fetching')
self._split_tasks.split_task.stop()
self._split_tasks.segment_task.stop()
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
"""
_LOGGER.debug('Stopping periodic data recording')
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 RedisSynchronizer(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)
self._periodic_data_recording_tasks = []
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
"""
_LOGGER.debug('Shutting down tasks.')
self.stop_periodic_data_recording(blocking)
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
"""
_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()
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 LocalhostSynchronizer(BaseSynchronizer):
"""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
"""
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
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 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."""
if self._split_tasks.split_task is not None:
_LOGGER.debug('Stopping periodic fetching')
self._split_tasks.split_task.stop()
if self._split_tasks.segment_task is not None:
self._split_tasks.segment_task.stop()
def kill_split(self, feature_flag_name, default_treatment, change_number):
"""Kill a feature flag locally."""
raise NotImplementedError()
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 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
"""
self.stop_periodic_fetching()
class PluggableSynchronizer(BaseSynchronizer):
"""Plugable Synchronizer."""
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):
"""
Synchronize all feature flags.
:param till: to fetch
:type till: int
"""
pass
def sync_all(self):
"""Synchronize all feature flag data."""
pass
def start_periodic_fetching(self):
"""Start fetchers for feature flags and segments."""
pass
def stop_periodic_fetching(self):
"""Stop fetchers for feature flags and segments."""
pass
def start_periodic_data_recording(self):
"""Start recorders."""
pass
def stop_periodic_data_recording(self, blocking):
"""Stop recorders."""
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
def shutdown(self, blocking):
"""
Stop tasks.
:param blocking:flag to wait until tasks are stopped
:type blocking: bool
"""
pass