Skip to content

Commit

Permalink
fix: prevent accessing config files concurrently
Browse files Browse the repository at this point in the history
  • Loading branch information
Crissium committed Apr 15, 2024
1 parent 55e620e commit 0882ccc
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions server/app/settings.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import atexit
import copy
import os
import sys
Expand Down Expand Up @@ -39,6 +40,21 @@ class Settings:
'DSL (.dsl/.dsl.dz)': ['.dsl', '.dz']
}

LOCK_FILE = os.path.join(APP_RESOURCES_ROOT, 'lock')

@classmethod
def _acquire_lock(cls) -> None:
if os.path.isfile(cls.LOCK_FILE):
logger.error('Another instance of the application is running.')
sys.exit(1)

with open(cls.LOCK_FILE, 'w') as f:
f.write('locked')

@classmethod
def _release_lock(cls) -> None:
os.remove(cls.LOCK_FILE)

PREFERENCES_FILE = os.path.join(APP_RESOURCES_ROOT, 'preferences.yaml')
# a dict with three fields: listening_address, suggestions_mode, running_mode

Expand Down Expand Up @@ -167,10 +183,10 @@ def parse_path_with_env_variables(path: str) -> str:
"""
return os.path.expanduser(os.path.expandvars(path))

@staticmethod
def _save_settings_to_file(settings: list | dict, filename: str) -> None:
with open(filename, 'w') as settings_file:
yaml.dump(settings, settings_file, Dumper=Dumper)
def _save_settings_to_file(self, settings: list | dict, filename: str) -> None:
with self._config_files_lock:
with open(filename, 'w') as settings_file:
yaml.dump(settings, settings_file, Dumper=Dumper)

@staticmethod
def _read_settings_from_file(filename: str) -> list | dict:
Expand Down Expand Up @@ -218,6 +234,12 @@ def change_suggestions_mode_from_right_side_to_both_sides(self) -> None:
preferences_file.write(preferences)

def __init__(self) -> None:
self._acquire_lock()
atexit.register(self._release_lock)

self._config_files_lock = threading.Lock()
self._scan_lock = threading.Lock()

if not os.path.isfile(self.PREFERENCES_FILE):
with open(self.PREFERENCES_FILE, 'w') as preferences_file:
preferences_file.write('''listening_address: 127.0.0.1
Expand Down Expand Up @@ -319,8 +341,6 @@ def __init__(self) -> None:
}
self._save_misc_configs()

self._scan_lock = threading.Lock()

def dictionary_info_valid(self, dictionary_info: dict) -> bool:
filename = dictionary_info['dictionary_filename']
filename = self.parse_path_with_env_variables(filename)
Expand Down

0 comments on commit 0882ccc

Please sign in to comment.