This repository was archived by the owner on Jun 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathabfile.py
More file actions
291 lines (238 loc) · 8.43 KB
/
abfile.py
File metadata and controls
291 lines (238 loc) · 8.43 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
import logging
import os
import time
from typing import Optional
from cryptojwt.utils import importer
from filelock import FileLock
from oidcmsg.storage import DictType
from oidcmsg.util import PassThru
from oidcmsg.util import QPKey
logger = logging.getLogger(__name__)
class AbstractFileSystem(DictType):
"""
FileSystem implements a simple file based database.
It has a dictionary like interface.
Each key maps one-to-one to a file on disc, where the content of the
file is the value.
ONLY goes one level deep.
Not directories in directories.
"""
def __init__(self,
fdir: Optional[str] = '',
key_conv: Optional[str] = '',
value_conv: Optional[str] = ''):
"""
items = FileSystem(
{
'fdir': fdir,
'key_conv':{'to': quote_plus, 'from': unquote_plus},
'value_conv':{'to': keyjar_to_jwks, 'from': jwks_to_keyjar}
})
:param fdir: The root of the directory
:param key_conv: Converts to/from the key displayed by this class to
users of it to something that can be used as a file name.
The value of key_conv is a class that has the methods 'serialize'/'deserialize'.
:param value_conv: As with key_conv you can convert/translate
the value bound to a key in the database to something that can easily
be stored in a file. Like with key_conv the value of this parameter
is a class that has the methods 'serialize'/'deserialize'.
"""
super(AbstractFileSystem, self).__init__(fdir=fdir, key_conv=key_conv, value_conv=value_conv)
self.fdir = fdir
self.fmtime = {}
self.storage = {}
if key_conv:
self.key_conv = importer(key_conv)()
else:
self.key_conv = QPKey()
if value_conv:
self.value_conv = importer(value_conv)()
else:
self.value_conv = PassThru()
if not os.path.isdir(self.fdir):
os.makedirs(self.fdir)
self.synch()
def get(self, item, default=None):
try:
return self[item]
except KeyError:
return default
def __getitem__(self, item):
"""
Return the value bound to an identifier.
:param item: The identifier.
:return:
"""
item = self.key_conv.serialize(item)
if self.is_changed(item):
logger.info("File content change in {}".format(item))
fname = os.path.join(self.fdir, item)
self.storage[item] = self._read_info(fname)
logger.debug('Read from "%s"', item)
return self.storage[item]
def __setitem__(self, key, value):
"""
Binds a value to a specific key. If the file that the key maps to
does not exist it will be created. The content of the file will be
set to the value given.
:param key: Identifier
:param value: Value that should be bound to the identifier.
:return:
"""
if not os.path.isdir(self.fdir):
os.makedirs(self.fdir, exist_ok=True)
try:
_key = self.key_conv.serialize(key)
except KeyError:
_key = key
fname = os.path.join(self.fdir, _key)
lock = FileLock('{}.lock'.format(fname))
with lock:
with open(fname, 'w') as fp:
fp.write(self.value_conv.serialize(value))
self.storage[_key] = value
logger.debug('Wrote to "%s"', key)
self.fmtime[_key] = self.get_mtime(fname)
def __delitem__(self, key):
fname = os.path.join(self.fdir, key)
if os.path.isfile(fname):
lock = FileLock('{}.lock'.format(fname))
with lock:
os.unlink(fname)
try:
del self.storage[key]
except KeyError:
pass
def keys(self):
"""
Implements the dict.keys() method
"""
self.synch()
for k in self.storage.keys():
yield self.key_conv.deserialize(k)
@staticmethod
def get_mtime(fname):
"""
Find the time this file was last modified.
:param fname: File name
:return: The last time the file was modified.
"""
try:
mtime = os.stat(fname).st_mtime_ns
except OSError:
# The file might be right in the middle of being written
# so sleep
time.sleep(1)
mtime = os.stat(fname).st_mtime_ns
return mtime
def is_changed(self, item):
"""
Find out if this item has been modified since last
:param item: A key
:return: True/False
"""
fname = os.path.join(self.fdir, item)
if os.path.isfile(fname):
mtime = self.get_mtime(fname)
try:
_ftime = self.fmtime[item]
except KeyError: # Never been seen before
self.fmtime[item] = mtime
return True
if mtime > _ftime: # has changed
self.fmtime[item] = mtime
return True
else:
return False
else:
logger.error('Could not access {}'.format(fname))
raise KeyError(item)
def _read_info(self, fname):
if os.path.isfile(fname):
try:
lock = FileLock('{}.lock'.format(fname))
with lock:
info = open(fname, 'r').read().strip()
return self.value_conv.deserialize(info)
except Exception as err:
logger.error(err)
raise
else:
logger.error('No such file: {}'.format(fname))
return None
def synch(self):
"""
Goes through the directory and builds a local cache based on
the content of the directory.
"""
if not os.path.isdir(self.fdir):
os.makedirs(self.fdir)
# raise ValueError('No such directory: {}'.format(self.fdir))
for f in os.listdir(self.fdir):
fname = os.path.join(self.fdir, f)
if not os.path.isfile(fname):
continue
if fname.endswith('.lock'):
continue
if f in self.fmtime:
if self.is_changed(f):
self.storage[f] = self._read_info(fname)
else:
mtime = self.get_mtime(fname)
try:
self.storage[f] = self._read_info(fname)
except Exception as err:
logger.warning('Bad content in {} ({})'.format(fname, err))
else:
self.fmtime[f] = mtime
def items(self):
"""
Implements the dict.items() method
"""
self.synch()
for k, v in self.storage.items():
yield self.key_conv.deserialize(k), v
def clear(self):
"""
Completely resets the database. This means that all information in
the local cache and on disc will be erased.
"""
if not os.path.isdir(self.fdir):
os.makedirs(self.fdir, exist_ok=True)
return
for f in os.listdir(self.fdir):
del self[f]
def update(self, ava):
"""
Replaces what's in the database with a set of key, value pairs.
Only data bound to keys that appear in ava will be affected.
Implements the dict.update() method
:param ava: Dictionary
"""
for key, val in ava.items():
self[key] = val
def __contains__(self, item):
return self.key_conv.serialize(item) in self.storage
def __iter__(self):
return self.items()
def __call__(self, *args, **kwargs):
return [self.key_conv.deserialize(k) for k in self.storage.keys()]
def __len__(self):
if not os.path.isdir(self.fdir):
return 0
n = 0
for f in os.listdir(self.fdir):
fname = os.path.join(self.fdir, f)
if not os.path.isfile(fname):
continue
if fname.endswith('.lock'):
continue
n += 1
return n
def __str__(self):
return '{config:' + str(self.config) + ', info:' + str(self.storage) + '}'
def dump(self):
return {k: v for k, v in self.items()}
def load(self, info):
for k, v in info.items():
self[k] = v