Skip to content

Commit ffbcfb7

Browse files
phlogistonjohnmergify[bot]
authored andcommitted
sambacc: add ClusterMetaJSONFile class
The ClusterMetaJSONFile and ClusterMetaJSONHandle wrap the functions provided by jfile that allow us to use a locked json file to store state about a managed ctdb cluster. These classes will be used in future changes to abstract handling this cluster metadata. Signed-off-by: John Mulligan <[email protected]>
1 parent e6cc8ca commit ffbcfb7

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

sambacc/jfile.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
import os
2424
import typing
2525

26+
from sambacc.typelets import ExcType, ExcValue, ExcTraceback, Self
27+
2628
OPEN_RO = os.O_RDONLY
2729
OPEN_RW = os.O_CREAT | os.O_RDWR
2830

@@ -61,3 +63,47 @@ def dump(data: typing.Any, fh: typing.IO) -> None:
6163
def flock(fh: typing.IO) -> None:
6264
"""A simple wrapper around flock."""
6365
fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
66+
67+
68+
class ClusterMetaJSONHandle:
69+
def __init__(self, fh: typing.IO) -> None:
70+
self._fh = fh
71+
72+
def load(self) -> typing.Any:
73+
return load(self._fh, {})
74+
75+
def dump(self, data: typing.Any) -> None:
76+
dump(data, self._fh)
77+
self._fh.flush()
78+
os.fsync(self._fh)
79+
80+
def __enter__(self) -> Self:
81+
return self
82+
83+
def __exit__(
84+
self, exc_type: ExcType, exc_val: ExcValue, exc_tb: ExcTraceback
85+
) -> None:
86+
self._fh.close()
87+
88+
89+
class ClusterMetaJSONFile:
90+
def __init__(self, path: str) -> None:
91+
self.path = path
92+
93+
def open(
94+
self, *, read: bool = True, write: bool = False, locked: bool = False
95+
) -> ClusterMetaJSONHandle:
96+
if read and write:
97+
flags = OPEN_RW
98+
elif read:
99+
flags = OPEN_RO
100+
else:
101+
raise ValueError("write-only not supported")
102+
fh = open(self.path, flags)
103+
try:
104+
if locked:
105+
flock(fh)
106+
except Exception:
107+
fh.close()
108+
raise
109+
return ClusterMetaJSONHandle(fh)

0 commit comments

Comments
 (0)