This repository was archived by the owner on Oct 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurd.py
executable file
·408 lines (361 loc) · 11.1 KB
/
urd.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
#!/usr/bin/env python2.7
############################################################################
# #
# Copyright (c) 2017 eBay Inc. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
############################################################################
from __future__ import unicode_literals
from glob import glob
from collections import defaultdict
from bottle import route, request, auth_basic, abort
import bottle
from threading import Lock
import json
import re
from datetime import datetime
import operator
LOGFILEVERSION = '2'
lock = Lock()
def locked(func):
def inner(*a, **kw):
with lock:
return func(*a, **kw)
return inner
class DotDict(dict):
"""Like a dict, but with d.foo as well as d['foo'].
d.foo returns '' for unset values.
The normal dict.f (get, items, ...) still return the functions.
"""
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def __getattr__(self, name):
if name[0] == "_":
raise AttributeError(name)
return self[name]
def joblistlike(jl):
assert isinstance(jl, list)
for v in jl:
assert isinstance(v, (list, tuple)), v
assert len(v) == 2, v
for s in v:
assert isinstance(s, unicode), s
return True
class DB:
def __init__(self, path):
self._initialised = False
self.path = path
self.db = defaultdict(dict)
self.ghost_db = defaultdict(lambda: defaultdict(list))
if os.path.isdir(path):
files = glob(os.path.join(path, '*/*.urd'))
print 'init: ', files
self._parsed = {}
for fn in files:
with open(fn) as fh:
for line in fh:
self._parse(line)
self._playback_parsed()
else:
print "Creating directory \"%s\"." % (path,)
os.makedirs(path)
self._lasttime = None
self._initialised = True
def _parse(self, line):
line = line.rstrip('\n').split('|')
logfileversion, writets = line[:2]
assert logfileversion == '2'
assert writets not in self._parsed
self._parsed[writets] = line[2:]
def _playback_parsed(self):
for _writets, line in sorted(self._parsed.iteritems()):
action = line.pop(0)
assert action in ('add', 'truncate',)
if action == 'add':
self._parse_add(line)
elif action == 'truncate':
self._parse_truncate(line)
else:
assert "can't happen"
def _parse_add(self, line):
key = line[1]
user, automata = key.split('/')
flags = line[4].split(',') if line[4] else []
data = DotDict(timestamp=line[0],
user=user,
automata=automata,
deps=json.loads(line[2]),
joblist=json.loads(line[3]),
flags=flags,
caption=line[5],
)
self.add(data)
def _parse_truncate(self, line):
timestamp, key = line
self.truncate(key, timestamp)
def _validate_timestamp(self, timestamp):
assert re.match(r"\d{8}( \d\d(\d\d(\d\d)?)?)?", timestamp), timestamp
def _validate_data(self, data, with_deps=True):
if with_deps:
assert set(data) == {'timestamp', 'joblist', 'caption', 'user', 'automata', 'deps', 'flags',}
assert isinstance(data.user, unicode)
assert isinstance(data.automata, unicode)
assert isinstance(data.deps, dict)
for v in data.deps.itervalues():
assert isinstance(v, dict)
self._validate_data(DotDict(v), False)
else:
assert set(data) == {'timestamp', 'joblist', 'caption',}
assert joblistlike(data.joblist), data.joblist
assert data.joblist
assert isinstance(data.caption, unicode)
self._validate_timestamp(data.timestamp)
def _serialise(self, action, data):
if action == 'add':
self._validate_data(data)
json_deps = json.dumps(data.deps)
json_joblist = json.dumps(data.joblist)
key = '%s/%s' % (data.user, data.automata,)
flags = ','.join(data.flags)
for s in json_deps, json_joblist, data.caption, data.user, data.automata, data.timestamp, flags:
assert '|' not in s, s
logdata = [json_deps, json_joblist, flags, data.caption,]
elif action == 'truncate':
key = data.key
logdata = []
else:
assert "can't happen"
while True: # paranoia
now = datetime.utcnow().strftime("%Y%m%d %H%M%S.%f")
if now != self._lasttime: break
self._lasttime = now
s = '|'.join([LOGFILEVERSION, now, action, data.timestamp, key,] + logdata)
print 'serialise', s
return s
def _is_ghost(self, data):
for key, data in data.deps.iteritems():
db = self.db[key]
ts = data['timestamp']
if ts not in db:
return True
for k, v in data.iteritems():
if db[ts].get(k) != v:
return True
return False
@locked
def add(self, data):
key = '%s/%s' % (data.user, data.automata)
new = False
changed = False
ghosted = 0
is_ghost = self._is_ghost(data)
if is_ghost:
db = self.ghost_db[key]
if data.timestamp in db:
new = False
changed = (data not in db[data.timestamp])
else:
new = True
else:
db = self.db[key]
if data.timestamp in db:
new = False
changed = (db[data.timestamp] != data)
else:
new = True
flags = data.get('flags', [])
assert flags in ([], ['update']), 'Unknown flags: %r' % (flags,)
if changed and 'update' not in flags:
assert self._initialised, 'Log updates without update flag: %r' % (data,)
bottle.response.status = 409
return {'error': 'would update'}
if new or changed:
data.flags = flags
self.log('add', data) # validates, too
del data.flags
if is_ghost:
db[data.timestamp].append(data)
else:
if changed:
ghost_data = db[data.timestamp]
self.ghost_db[key][data.timestamp].append(ghost_data)
db[data.timestamp] = data
if changed:
ghosted = self._update_ghosts()
res = dict(new=new, changed=changed, is_ghost=is_ghost)
if changed:
res['deps'] = ghosted
return res
def _update_ghosts(self):
def inner():
count = 0
for key, db in self.db.iteritems():
for ts, data in sorted(db.items()):
if self._is_ghost(data):
count += 1
del db[ts]
self.ghost_db[key][ts].append(data)
return count
res = 0
while True:
count = inner()
if not count:
break
res += count
return res
@locked
def truncate(self, key, timestamp):
old = self.db[key]
new = {}
ghost = {}
for ts, data in old.iteritems():
if ts < timestamp:
new[ts] = data
else:
ghost[ts] = data
self.log('truncate', DotDict(key=key, timestamp=timestamp))
self.db[key] = new
ghost_db = self.ghost_db[key]
for ts, data in ghost.iteritems():
ghost_db[ts].append(data)
if ghost:
deps = self._update_ghosts()
else:
deps = 0
return {'count': len(ghost), 'deps': deps}
def log(self, action, data):
if self._initialised:
if action == 'truncate':
user, automata = data.key.split('/')
else:
user, automata = data.user, data.automata
assert '/' not in user
assert '/' not in automata
path = os.path.join(self.path, user)
if not os.path.isdir(path):
os.makedirs(path)
with open(os.path.join(path, automata + '.urd'), 'a') as fh:
fh.write(self._serialise(action, data) + '\n')
@locked
def get(self, key, timestamp):
db = self.db[key]
return db.get(timestamp)
@locked
def since(self, key, timestamp):
return sorted(k for k in self.db[key] if k > timestamp)
@locked
def limited_endpoint(self, key, timestamp, cmpfunc, minmaxfunc):
db = self.db[key]
try:
k = minmaxfunc(k for k in db if cmpfunc(k, timestamp))
except ValueError: # empty sequence
return None
return db[k]
@locked
def latest(self, key):
db = self.db[key]
if db:
return db[max(db)]
@locked
def first(self, key):
db = self.db[key]
if db:
return db[min(db)]
def keys(self):
return filter(self.db.get, self.db)
def auth(user, passphrase):
return authdict.get(user) == passphrase
@route('/<user>/<automata>/since/<timestamp>')
def since(user, automata, timestamp):
return db.since(user + '/' + automata, timestamp)
@route('/<user>/<automata>/latest')
def latest(user, automata):
return db.latest(user + '/' + automata)
@route('/<user>/<automata>/first')
def first(user, automata):
return db.first(user + '/' + automata)
@route('/<user>/<automata>/<timestamp>')
def single(user, automata, timestamp):
key = user + '/' + automata
if len(timestamp) > 1 and timestamp[0] in '<>':
if timestamp[0] == '<':
minmaxfunc = max
if timestamp[1] == '=':
# we want 20140410 <= 201404 to be True
def cmpfunc(k, ts):
return k <= ts or k.startswith(ts)
timestamp = timestamp[2:]
else:
cmpfunc = operator.lt
timestamp = timestamp[1:]
else:
minmaxfunc = min
if timestamp[1] == '=':
cmpfunc = operator.ge
timestamp = timestamp[2:]
else:
cmpfunc = operator.gt
timestamp = timestamp[1:]
return db.limited_endpoint(key, timestamp, cmpfunc, minmaxfunc)
else:
return db.get(key, timestamp)
@route('/add', method='POST')
@auth_basic(auth)
def add():
data = DotDict(request.json or {})
if data.user != request.auth[0]:
abort(401, "Error: user does not match authentication!")
result = db.add(data)
return result
@route('/truncate/<user>/<automata>/<timestamp>', method='POST')
@auth_basic(auth)
def truncate(user, automata, timestamp):
if user != request.auth[0]:
abort(401, "Error: user does not match authentication!")
return db.truncate(user + '/' + automata, timestamp)
#(setq indent-tabs-mode t)
@route('/list')
def slash_list():
return sorted(db.keys())
def readauth(filename):
d = {}
with open(filename) as fh:
for line in fh:
line = line.strip()
if not line or line.startswith('#'): continue
line = line.split(':')
assert len(line) == 2, "Parse error in \"" + filename + "\" " + ':'.join(line)
d[line[0]] = line[1]
return d
def jsonify(callback):
def func(*a, **kw):
res = callback(*a, **kw)
if isinstance(res, (bottle.BaseResponse, bottle.BottleException)):
return res
return json.dumps(res)
return func
if __name__ == "__main__":
from argparse import ArgumentParser
import os.path
parser = ArgumentParser(description='pelle')
parser.add_argument('--port', type=int, default=8080, help='server port')
parser.add_argument('--path', type=str, default='./', help='database directory')
args = parser.parse_args()
print '-'*79
print args
print
authdict = readauth(os.path.join(args.path, 'passwd'))
db = DB(os.path.join(args.path, 'database'))
bottle.install(jsonify)
bottle.run(host='localhost', port=args.port, debug=False, reloader=False, quiet=False)