Skip to content

Commit

Permalink
WIP - conext cleanup
Browse files Browse the repository at this point in the history
no contextlib.chdir on older OSes.
  • Loading branch information
mvollmer committed Aug 28, 2024
1 parent 17e7b7a commit cbb0aae
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions pkg/storaged/btrfs/btrfs-tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,10 @@
def debug(msg):
subprocess.check_call(["logger", msg])

def ensure_tmp_mp_dir():
os.makedirs(TMP_MP_DIR, mode=0o700, exist_ok=True)

@contextlib.contextmanager
def atomic_file(path):
def mount_database():
path = TMP_MP_DIR + "/db"
os.makedirs(TMP_MP_DIR, mode=0o700, exist_ok=True)
fd = os.open(path, os.O_RDWR | os.O_CREAT)
fcntl.flock(fd, fcntl.LOCK_EX)
data = os.read(fd, 100000)
Expand All @@ -48,6 +47,15 @@ def atomic_file(path):
finally:
os.close(fd)

@contextlib.contextmanager
def context_chdir(path):
old_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(old_cwd)

def list_filesystems():
output = json.loads(subprocess.check_output(["lsblk", "-Jplno", "NAME,FSTYPE,UUID,MOUNTPOINTS"]))
filesystems = {}
Expand Down Expand Up @@ -102,8 +110,7 @@ def remove_tmp_mountpoint(db, uuid):
db[uuid] -= 1

def remove_all_tmp_mountpoints():
ensure_tmp_mp_dir()
with atomic_file(TMP_MP_DIR + "/db") as db:
with mount_database() as db:
for mp in set(tmp_mountpoints):
remove_tmp_mountpoint(db, mp)

Expand Down Expand Up @@ -156,8 +163,7 @@ def get_usages(uuid):

def poll(opt_mount, opt_repair):
debug(f"POLL mount {opt_mount} repair {opt_repair}")
ensure_tmp_mp_dir()
with atomic_file(TMP_MP_DIR + "/db") as db:
with mount_database() as db:
filesystems = list_filesystems()
info = { }
for fs in filesystems.values():
Expand Down Expand Up @@ -193,13 +199,12 @@ def cmd_poll(opt_mount):

def cmd_do(uuid, cmd):
debug(f"DO {uuid} {cmd}")
ensure_tmp_mp_dir()
with atomic_file(TMP_MP_DIR + "/db") as db:
with mount_database() as db:
filesystems = list_filesystems()
for fs in filesystems.values():
if fs['uuid'] == uuid:
mp = force_mount_point(db, fs, True)
with contextlib.chdir(mp):
with context_chdir(mp):
subprocess.check_call(cmd)

def cmd(args):
Expand Down

0 comments on commit cbb0aae

Please sign in to comment.