- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbufferpool.py
More file actions
Latest commit
424 lines (339 loc) · 12.3 KB
/
Copy pathbufferpool.py
File metadata and controls
424 lines (339 loc) · 12.3 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
########################################
# bufferpool.py
#
# an implementation of a buffer pool in Python 3.
# python version: 3.10
#
# (C) AGPL3 Paul Nathan 2022
importjson
importos
importrandom
fromcollections.abcimportCallable
fromtypingimportAny
classUniqueStack(object):
# A space-inefficient means of having a unique priority queue. A
# set maintains the unique facility and rapid tests for existence.
# A vector maintains the ordering.
#
# Space: 2*n
#
# Time: n on push (linear vector delete).
#
# The alternative here is, likely, working out a Heap or variant
# thereof. That would be find - O(n) + delete - O(lg n) + insert -
# O(lg n), where we are at O(n). If we could implement insert with
# only optionally deleting/inserting "if we find", then that
# should be done. But, too, heaps require a "key", whereas we
# maintain here the order by simple indexing and the location of
# the data in the linear data structure.
def__init__(self):
self._d=set()
self._o= []
defpush(self, e):
ifeinself._d:
r= []
foriinrange(0, len(self._o)):
ifself._o[i] ==e:
# splice them together without e
r=self._o[:i] +self._o[i+1:]
r.append(e)
self._o=r
else:
self._d.add(e)
self._o.append(e)
# just whack it.
defdelete(self, e):
self._d.remove(e)
r=self._o
foriinrange(0, len(self._o)):
ifself._o[i] ==e:
# splice them together without e
r=self._o[:i] +self._o[i+1:]
self._o=r
defpop(self):
r=self._o[len(self._o) -1]
self._d.remove(r)
self._o.pop()
returnr
deftop(self):
returnself._o[len(self._o) -1]
defbottom(self):
returnself._o[0]
def__getitem__(self, i):
returnself._o[i]
def__len__(self):
returnlen(self._d)
def__repr__(self):
return"< "+", ".join(map(str, self._o)) +" > "
defelems(self):
returnself._o
classFramePool(object):
defassess_size(self) ->int:
raiseNotImplemented
defsize(self) ->int:
raiseNotImplemented
defread_frame(self, id: int):
raiseNotImplemented
defwrite_frame(self, id: int, data: Any):
raiseNotImplemented
deffalloc(self, count: int):
raiseNotImplemented
classDiskPool(FramePool):
def__init__(self, limit, dirname):
self._dirname=dirname
self._size=0
self.falloc(limit)
defassess_size(self):
flist= []
# this essentially requires a flock on the directory.
withos.scandir(path=self._dirname) asit:
forentryinit:
ifentry.is_file():
flist.append(entry.name)
counter=0
forfinflist:
iff.startswith("page_"):
counter+=1
self._size=counter
returncounter
defsize(self):
returnself._size
defread_frame(self, pageid):
withopen(os.path.join(self._dirname, f"page_{pageid}"), 'r') asf:
returnPageFrame(json.loads(f.read()))
deffalloc(self, count):
prior_size=self._size
# increase bound
self._size+=count
foriinrange(0, count):
pageid=prior_size+i
filename=os.path.join(self._dirname, f"page_{pageid}")
ifnotos.path.isfile(filename):
withopen(filename, 'w') asf:
f.write(json.dumps({}))
defwrite_frame(self, pageid, data):
assertisinstance(data, PageFrame)
withopen(os.path.join(self._dirname, f"page_{pageid}"), 'w') asf:
f.write(json.dumps(data.data()))
classMockPool(FramePool):
def__init__(self, limit):
self._frames= {}
self._size=0
self.falloc(limit)
defsize(self):
returnself._size
defassess_size(self):
returnlen(self._frames)
defread_frame(self, pageid):
returnPageFrame(self._frames[pageid])
deffalloc(self, count):
prior_size=self._size
foriinrange(0, count):
pageid=prior_size+i
self.write_frame(pageid, PageFrame(None))
self._size+=count
defwrite_frame(self, pageid, data):
assertisinstance(data, PageFrame)
self._frames[pageid] =data.data()
classPageFrame(object):
# a Page is created, associated with some specific data frame.
def__init__(self, data: Any):
self._frame=data
# one pin per thread using the page.
self._pins=0
# should the frame know it's dirty? or should the FramePool
# track whether its dirty or not?
self._dirty=False
def__repr__(self):
returnf"<pf p: {self._pins}, d: {self._dirty}, {self._frame} >"
defdata(self) ->Any:
returnself._frame
defset_data(self, data: Any):
self._dirty=True
self._frame=data
defcount_pins(self)->int:
returnself._pins
definc_pin(self):
self._pins=self._pins+1
returnself._pins
defdec_pin(self):
self._pins=self._pins-1
returnself._pins
defis_dirty(self):
returnself._dirty
defmake_dirty(self):
self._dirty=True
defundirty(self):
self._dirty=False
def__enter__(self):
self.inc_pin()
returnself.data()
def__exit__(self, x, y, z):
self.dec_pin()
# interface: an evictor takes a list of pages and a unique Stack and return the index of
# the one to evict.
defrandom_evictor(pages: list[PageFrame|None], frame2buf: dict[int, int], _ : UniqueStack)->int:
# TODO: properly handle pins
#potential = random.randint(0, len(pages) - 1)
#while pages[potential].count_pins() != 0:
potential=random.randint(0, len(pages) -1)
returnframe2buf[potential]
defbottom_evictor(pages: list[PageFrame|None], frame2buf: dict[int, int], lru: UniqueStack)-> (int, int):
#sys.stderr.write(f"length of pages {len(pages)}\n")
#sys.stderr.write(f"lru {lru.elems()}\n")
foreinlru.elems():
# sys.stderr.write(f"element: {e}\n")
pageid=frame2buf[e]
ifpages[pageid] isnotNone:
# TODO: properly handle pins
# if pages[e].count_pins == 0:
returnpageid, e
raiseEvictionError()
classEvictionError(Exception):
pass
classBufferPool(object):
_buf2frame: dict[int, int]
_evictor: Callable[[list[PageFrame|None], dict[int, int], UniqueStack], int]
_frame2buf: dict[int, int]
_pages: list[PageFrame|None]
_pool: FramePool
_stack: UniqueStack
__slots__= [
'_size',
# fixed number of pages
'_pages',
# pageid -> index
'_frame2buf',
# index -> pageid
'_buf2frame',
# lru
'_stack',
# backing store
'_pool',
# victim selector
'_evictor',
# unused, it seemed like a good idea at the time
# page OIDs run from [0, _total_page_count) over integers.
'_total_page_count',
]
def__init__(self, size: int, pool: FramePool, evictor: Callable[[list[PageFrame|None], dict[int, int], UniqueStack], int]):
# This size is the size of the buffer pool
self._size=size
self._pages= [Noneforxinrange(0, size)]
# map of pageid to index in self._pages
self._frame2buf= {}
# map of index to pageid.
self._buf2frame= {}
self._pool=pool
self._evictor=evictor
self._stack=UniqueStack()
defrelease_page(self, idx: int):
"""
Page is released for later eviction
"""
ifidx>self._pool.size() -1:
raiseIndexError(f"buffer pool index out of range{idx}")
ifidxnotinself._frame2buf:
# this is not a valid page for writing: something has
# evicted it from under our feet.
raiseEvictionError()
self._pages[self._frame2buf[idx]].dec_pin()
defacquire_page(self, idx: int) ->PageFrame:
"""
Page is acquired from its data source, if need be
"""
p=self.get_page(idx)
p.inc_pin()
returnp
def__getitem__(self, idx):
returnself.get_page(idx)
def__setitem__(self, idx, value):
"""
Writes value to page, then syncs it.
"""
item=self.acquire_page(idx)
item.set_data(value)
self.fsync_item(idx)
defensure_allocation(self, idx):
to_be_allocated=idx- (self._pool.size() -1)
ifto_be_allocated>0:
self._pool.falloc(to_be_allocated)
deffalloc(self):
self._pool.falloc(1)
deffsync_item(self, idx):
page=self._pages[self._frame2buf[idx]]
ifpage.is_dirty():
self._pool.write_frame(idx, page)
page.undirty()
deffsync(self):
forkeyinself._frame2buf:
self.fsync_item(key)
defsize(self):
returnself._pool.size()
defget_page(self, frame_index: int) ->PageFrame:
"""
:param frame_index: index of the frame, _as understood by the overlay_, not the id of the buffer
:return: frame or exception
"""
ifframe_index>self._pool.size() -1:
raiseIndexError(f"mempool index out of range {frame_index}")
# if we don't have the data already
ifframe_indexnotinself._frame2buf:
# precondition: we don't have the page loaded
iflen(self._frame2buf) ==self._size:
# precondition: we are full
# victim index is the index in the array for the
# (limited) list of pages. Evictors must check pin status.
victim_buf_idx, victim_frame_idx=self._evictor(self._pages, self._frame2buf, self._stack)
# victim pageid is the page victim_index points to
victim_page=self._pages[victim_buf_idx]
ifvictim_page.is_dirty():
self._pool.write_frame(victim_buf_idx, victim_page)
# drop the page out of memory
self._pages[victim_buf_idx] =None
# drop the idx out of use
self._stack.delete(self._buf2frame[victim_buf_idx])
# drop the two way map
delself._frame2buf[victim_frame_idx]
delself._buf2frame[victim_buf_idx]
# postcondition of this little block: we have one empty slot
# precondition: we have at least one slot, which is
# signified by a None element in the self._pages array
target_index=None
foriinrange(0, self._size):
ifself._pages[i] isNone:
target_index=i
break
frame=self._pool.read_frame(frame_index)
self._pages[target_index] =frame
self._frame2buf[frame_index] =target_index
self._buf2frame[target_index] =frame_index
# postcondition: the frame is loaded into memory and wired into the map
# push idx onto the lru
self._stack.push(frame_index)
returnself._pages[self._frame2buf[frame_index]]
# the SlabMapper maps an array of Objects onto the bufferpool.
# crucially, it _must_ be a 0 indexed sequence. Notably, the
# Bufferpool is a 0 indexed sequence, but does not presume any
# structure on the data.
classSlabMapper(object):
def__init__(self, bp, stride):
"""
bp - bufferpool
stride - number of elements to map into a given frame.
"""
self._bp=bp
self._stride=stride
defflush(self, seq):
required_allocation=int(len(seq) /self._stride)
self._bp.ensure_allocation(required_allocation-1)
foriinrange(0, required_allocation):
bottom=i*self._stride
top= (i+1) *self._stride
self._bp[i] =seq[bottom:top]
defload(self):
result= []
foriinrange(0, self._bp.size()):
sublist=self._bp.get_page(i)
result.extend(sublist.data())
returnresult