21 global_client_object = None
25 def global_client_object():
26 global global_client_object
27 if global_client_object == None:
28 global_client_object = KeepClient()
29 return global_client_object
32 def get(locator, **kwargs):
33 return Keep.global_client_object().get(locator, **kwargs)
36 def put(data, **kwargs):
37 return Keep.global_client_object().put(data, **kwargs)
39 class KeepClient(object):
41 class ThreadLimiter(object):
43 Limit the number of threads running at a given time to
44 {desired successes} minus {successes reported}. When successes
45 reported == desired, wake up the remaining threads and tell
48 Should be used in a "with" block.
50 def __init__(self, todo):
53 self._todo_lock = threading.Semaphore(todo)
54 self._done_lock = threading.Lock()
57 self._todo_lock.acquire()
60 def __exit__(self, type, value, traceback):
61 self._todo_lock.release()
63 def shall_i_proceed(self):
65 Return true if the current thread should do stuff. Return
66 false if the current thread should just stop.
69 return (self._done < self._todo)
71 def increment_done(self):
73 Report that the current thread was successful.
80 Return how many successes were reported.
85 class KeepWriterThread(threading.Thread):
87 Write a blob of data to the given Keep server. Call
88 increment_done() of the given ThreadLimiter if the write
91 def __init__(self, **kwargs):
92 super(KeepClient.KeepWriterThread, self).__init__()
97 with self.args['thread_limiter'] as limiter:
98 if not limiter.shall_i_proceed():
99 # My turn arrived, but the job has been done without
102 logging.debug("KeepWriterThread %s proceeding %s %s" %
103 (str(threading.current_thread()),
104 self.args['data_hash'],
105 self.args['service_root']))
107 url = self.args['service_root'] + self.args['data_hash']
108 api_token = config['ARVADOS_API_TOKEN']
109 headers = {'Authorization': "OAuth2 %s" % api_token}
111 resp, content = h.request(url.encode('utf-8'), 'PUT',
113 body=self.args['data'])
114 if (resp['status'] == '401' and
115 re.match(r'Timestamp verification failed', content)):
116 body = KeepClient.sign_for_old_server(
117 self.args['data_hash'],
120 resp, content = h.request(url.encode('utf-8'), 'PUT',
123 if re.match(r'^2\d\d$', resp['status']):
124 logging.debug("KeepWriterThread %s succeeded %s %s" %
125 (str(threading.current_thread()),
126 self.args['data_hash'],
127 self.args['service_root']))
128 return limiter.increment_done()
129 logging.warning("Request fail: PUT %s => %s %s" %
130 (url, resp['status'], content))
131 except (httplib2.HttpLib2Error, httplib.HTTPException) as e:
132 logging.warning("Request fail: PUT %s => %s: %s" %
133 (url, type(e), str(e)))
136 self.lock = threading.Lock()
137 self.service_roots = None
139 def shuffled_service_roots(self, hash):
140 if self.service_roots == None:
142 keep_disks = api().keep_disks().list().execute()['items']
143 roots = (("http%s://%s:%d/" %
144 ('s' if f['service_ssl_flag'] else '',
148 self.service_roots = sorted(set(roots))
149 logging.debug(str(self.service_roots))
152 pool = self.service_roots[:]
156 if len(pseq) < len(hash) / 4: # first time around
157 seed = hash[-4:] + hash
160 probe = int(seed[0:8], 16) % len(pool)
161 pseq += [pool[probe]]
162 pool = pool[:probe] + pool[probe+1:]
164 logging.debug(str(pseq))
167 def get(self, locator):
169 if re.search(r',', locator):
170 return ''.join(self.get(x) for x in locator.split(','))
171 if 'KEEP_LOCAL_STORE' in os.environ:
172 return KeepClient.local_store_get(locator)
173 expect_hash = re.sub(r'\+.*', '', locator)
174 for service_root in self.shuffled_service_roots(expect_hash):
176 url = service_root + expect_hash
177 api_token = config['ARVADOS_API_TOKEN']
178 headers = {'Authorization': "OAuth2 %s" % api_token,
179 'Accept': 'application/octet-stream'}
181 resp, content = h.request(url.encode('utf-8'), 'GET',
183 if re.match(r'^2\d\d$', resp['status']):
184 m = hashlib.new('md5')
187 if md5 == expect_hash:
189 logging.warning("Checksum fail: md5(%s) = %s" % (url, md5))
190 except (httplib2.HttpLib2Error, httplib.ResponseNotReady) as e:
191 logging.info("Request fail: GET %s => %s: %s" %
192 (url, type(e), str(e)))
193 raise errors.NotFoundError("Block not found: %s" % expect_hash)
195 def put(self, data, **kwargs):
196 if 'KEEP_LOCAL_STORE' in os.environ:
197 return KeepClient.local_store_put(data)
198 m = hashlib.new('md5')
200 data_hash = m.hexdigest()
202 want_copies = kwargs.get('copies', 2)
203 if not (want_copies > 0):
206 thread_limiter = KeepClient.ThreadLimiter(want_copies)
207 for service_root in self.shuffled_service_roots(data_hash):
208 t = KeepClient.KeepWriterThread(data=data,
210 service_root=service_root,
211 thread_limiter=thread_limiter)
216 have_copies = thread_limiter.done()
217 if have_copies == want_copies:
218 return (data_hash + '+' + str(len(data)))
219 raise errors.KeepWriteError(
220 "Write fail for %s: wanted %d but wrote %d" %
221 (data_hash, want_copies, have_copies))
224 def sign_for_old_server(data_hash, data):
225 return (("-----BEGIN PGP SIGNED MESSAGE-----\n\n\n%d %s\n-----BEGIN PGP SIGNATURE-----\n\n-----END PGP SIGNATURE-----\n" % (int(time.time()), data_hash)) + data)
229 def local_store_put(data):
230 m = hashlib.new('md5')
233 locator = '%s+%d' % (md5, len(data))
234 with open(os.path.join(os.environ['KEEP_LOCAL_STORE'], md5 + '.tmp'), 'w') as f:
236 os.rename(os.path.join(os.environ['KEEP_LOCAL_STORE'], md5 + '.tmp'),
237 os.path.join(os.environ['KEEP_LOCAL_STORE'], md5))
241 def local_store_get(locator):
242 r = re.search('^([0-9a-f]{32,})', locator)
244 raise errors.NotFoundError(
245 "Invalid data locator: '%s'" % locator)
246 if r.group(0) == EMPTY_BLOCK_LOCATOR.split('+')[0]:
248 with open(os.path.join(os.environ['KEEP_LOCAL_STORE'], r.group(0)), 'r') as f: