Use file-locking also for config.

This commit is contained in:
Disassembler 2018-11-02 19:54:20 +01:00
parent fa23e4828f
commit ace50a79e7
No known key found for this signature in database
GPG Key ID: 524BD33A0EE29499
2 changed files with 11 additions and 5 deletions

View File

@ -1,22 +1,25 @@
# -*- coding: utf-8 -*-
import fcntl
import json
from threading import Lock
CONF_FILE = '/etc/vmmgr/config.json'
class Config:
def __init__(self):
self.lock = Lock()
self.load()
def load(self):
with self.lock:
# Load configuration from file. Uses file lock as interprocess mutex
with open('/var/lock/vmmgr-hosts.lock', 'w') as lock:
fcntl.lockf(lock, fcntl.LOCK_EX)
with open(CONF_FILE, 'r') as f:
self.data = json.load(f)
def save(self):
with self.lock:
# Save configuration to a file. Uses file lock as interprocess mutex
with open('/var/lock/vmmgr-hosts.lock', 'w') as lock:
fcntl.lockf(lock, fcntl.LOCK_EX)
with open(CONF_FILE, 'w') as f:
json.dump(self.data, f, sort_keys=True, indent=4)

View File

@ -113,8 +113,9 @@ def reboot_vm():
def update_hosts_lease(app, is_request):
# This is a poor man's DHCP server which uses /etc/hosts as lease database
# Leases the first unused IP from range 172.17.0.0/16
# Uses file lock as interprocess mutex
ip = None
with open('/var/lock/hosts.lock', 'w') as lock:
with open('/var/lock/vmmgr-hosts.lock', 'w') as lock:
fcntl.lockf(lock, fcntl.LOCK_EX)
with open('/etc/hosts', 'r') as f:
leases = [l.strip().split(' ', 1) for l in f]
@ -138,6 +139,8 @@ def set_container_ip(pid, ip):
subprocess.run(['nsenter', '-a', '-t', pid, '--', '/bin/sh', '-c', cmd])
def clean_ephemeral_layer(app):
# Cleans containers ephemeral layer.
# This is done early in the container start process, so the inode of the delta0 directory must remain unchanged
layer = os.path.join('/var/lib/lxc', app, 'delta0')
if os.path.exists(layer):
for item in os.scandir(layer):