-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis_aggregator.py
190 lines (161 loc) · 6.93 KB
/
redis_aggregator.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
# The MIT License (MIT)
#
# Copyright (c) 2016 Sean Bell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Based on https://github.com/seanbell/descriptor-store
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Balazs Kovacs (modified the original implementation)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import signal
import time
import traceback
import redis
from cnntools import packer
from cnntools.common_utils import progress_bar_widgets
from django.conf import settings
from progressbar import ProgressBar
INTERRUPTED = False
def patch_interrupt_signal():
def signal_handler(signal, frame):
global INTERRUPTED
print('\nInterrupted -- will exit on next loop iteration.')
INTERRUPTED = True
signal.signal(signal.SIGINT, signal_handler)
def detach_patch_interrupt_signal():
signal.signal(signal.SIGINT, signal.SIG_DFL)
def batch_ready(task_id, batch_id, value):
client = redis.StrictRedis(**settings.REDIS_AGGRO_LOCAL_CONFIG)
client.set(batch_id, value)
client.sadd(task_id, batch_id)
class RedisAggregator(object):
def __init__(self, verbose=True):
self.verbose = verbose
def scan(self, task_id, completed_ids, num_ids, aggr_batchsize=1024, flush_interval=60):
self.task_id = task_id
self.num_ids = num_ids
self.aggr_batchsize = aggr_batchsize
self.completed_ids = set(completed_ids)
if self.verbose:
print "RedisAggregator.scan(task_id: %s, completed_ids: %s, num_ids: %s)" % (
self.task_id, len(self.completed_ids), self.num_ids)
self.client = redis.StrictRedis(**settings.REDIS_AGGRO_LOCAL_CONFIG)
if self.verbose:
print "initial dbsize: %s" % self.client.dbsize()
self.visited_keys = set()
self.keys_to_delete = set()
self.keys_to_get = []
self.last_flush = time.time()
num_remaining = self.num_ids - len(self.completed_ids)
if self.verbose:
self.pbar = ProgressBar(
widgets=progress_bar_widgets(),
maxval=num_remaining,
)
self.pbar.start()
self.pbar_count = 0
while self.pbar_count < num_remaining and not INTERRUPTED:
try:
self.scan_for_keys()
if time.time() > self.last_flush + flush_interval:
self.flush()
self.last_flush = time.time()
except Exception:
traceback.print_exc()
time.sleep(10)
# if we finished, delete set which holds the completed keys
if not INTERRUPTED:
self.client.delete(self.task_id)
if self.verbose:
self.pbar.finish()
def aggregate_item(self, value):
""" Return the added ids if successful, empty list if unsuccessful """
raise NotImplementedError()
def flush(self):
""" Override this if you want flush behavior """
pass
def scan_for_keys(self):
""" Scan for available keys on redis """
finished_keys = self.client.smembers(self.task_id)
for key in finished_keys:
if key not in self.visited_keys:
self.visited_keys.add(key)
self.keys_to_get.append(key)
if len(self.keys_to_get) >= self.aggr_batchsize:
self.batch_get()
if len(self.keys_to_delete) >= self.aggr_batchsize:
self.batch_delete()
if INTERRUPTED:
return
made_progress = (self.keys_to_get or self.keys_to_delete)
self.batch_get()
self.batch_delete()
if not made_progress:
time.sleep(4)
def unpack_task_value(self, value):
value = packer.unpackb_version(value, settings.API_VERSION)
#if value['api_version'] == settings.API_VERSION:
#return value['data']
#return None
return value
def batch_get(self):
""" Process a batch of keys """
if self.keys_to_get:
values = self.client.mget(self.keys_to_get)
for i, key in enumerate(self.keys_to_get):
try:
data = self.unpack_task_value(values[i])
added_ids = self.aggregate_item(data)
if len(added_ids) > 0:
self.pbar_count += len(added_ids)
self.completed_ids.update(added_ids)
if self.verbose:
self.pbar.update(self.pbar_count)
except Exception:
traceback.print_exc()
if INTERRUPTED:
return
self.keys_to_delete.update(self.keys_to_get)
self.keys_to_get = []
def batch_delete(self):
""" Delete a batch of keys """
if self.keys_to_delete:
self.client.srem(self.task_id, *self.keys_to_delete)
self.client.delete(*self.keys_to_delete)
self.keys_to_delete = set()