From f675996e609c63e06cb04bc4fbcb609f55bc1244 Mon Sep 17 00:00:00 2001 From: Disassembler Date: Sun, 28 Oct 2018 18:19:45 +0100 Subject: [PATCH] Add config file locking --- basic/srv/vm/mgr/config.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/basic/srv/vm/mgr/config.py b/basic/srv/vm/mgr/config.py index 8206b1c..4579e97 100644 --- a/basic/srv/vm/mgr/config.py +++ b/basic/srv/vm/mgr/config.py @@ -1,20 +1,27 @@ # -*- coding: utf-8 -*- +import fcntl import json CONF_FILE = '/srv/vm/config.json' +# Locking is needed in order to prevent race conditions in WSGI threads +LOCK_FILE = '/srv/vm/config.lock' class Config: def __init__(self): self.load() def load(self): - with open(CONF_FILE, 'r') as f: - self.data = json.load(f) + with open(LOCK_FILE, 'w') as l: + fcntl.flock(l, fcntl.LOCK_EX) + with open(CONF_FILE, 'r') as f: + self.data = json.load(f) def save(self): - with open(CONF_FILE, 'w') as f: - json.dump(self.data, f, sort_keys=True, indent=4) + with open(LOCK_FILE, 'w') as l: + fcntl.flock(l, fcntl.LOCK_EX) + with open(CONF_FILE, 'w') as f: + json.dump(self.data, f, sort_keys=True, indent=4) def __getitem__(self, attr): return self.data[attr]