Spaces:
Running
Running
File size: 2,398 Bytes
b72ab63 |
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 |
from collections import deque
class Transaction:
"""Filesystem transaction write context
Gathers files for deferred commit or discard, so that several write
operations can be finalized semi-atomically. This works by having this
instance as the ``.transaction`` attribute of the given filesystem
"""
def __init__(self, fs, **kwargs):
"""
Parameters
----------
fs: FileSystem instance
"""
self.fs = fs
self.files = deque()
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""End transaction and commit, if exit is not due to exception"""
# only commit if there was no exception
self.complete(commit=exc_type is None)
if self.fs:
self.fs._intrans = False
self.fs._transaction = None
self.fs = None
def start(self):
"""Start a transaction on this FileSystem"""
self.files = deque() # clean up after previous failed completions
self.fs._intrans = True
def complete(self, commit=True):
"""Finish transaction: commit or discard all deferred files"""
while self.files:
f = self.files.popleft()
if commit:
f.commit()
else:
f.discard()
self.fs._intrans = False
self.fs._transaction = None
self.fs = None
class FileActor:
def __init__(self):
self.files = []
def commit(self):
for f in self.files:
f.commit()
self.files.clear()
def discard(self):
for f in self.files:
f.discard()
self.files.clear()
def append(self, f):
self.files.append(f)
class DaskTransaction(Transaction):
def __init__(self, fs):
"""
Parameters
----------
fs: FileSystem instance
"""
import distributed
super().__init__(fs)
client = distributed.default_client()
self.files = client.submit(FileActor, actor=True).result()
def complete(self, commit=True):
"""Finish transaction: commit or discard all deferred files"""
if commit:
self.files.commit().result()
else:
self.files.discard().result()
self.fs._intrans = False
self.fs = None
|