spoc/usr/lib/python3.8/spoc/repo_local.py

97 lines
2.3 KiB
Python

# -*- coding: utf-8 -*-
import fcntl
import json
import os
from . import config
from .exceptions import AppNotFoundError, ContainerNotFoundError, ImageNotFoundError
from .flock import locked
TYPE_APP = 'apps'
TYPE_CONTAINER = 'containers'
TYPE_IMAGE = 'images'
data = {TYPE_IMAGE: {}, TYPE_CONTAINER: {}, TYPE_APP: {}}
mtime = 0
def load():
global data
global mtime
try:
file_mtime = os.stat(config.REPO_FILE).st_mtime
if mtime != file_mtime:
with open(config.REPO_FILE) as f:
data = json.load(f)
mtime = file_mtime
except FileNotFoundError:
pass
def save():
global mtime
with open(config.REPO_FILE, 'w') as f:
json.dump(data, f, sort_keys=True, indent=4)
mtime = os.stat(config.REPO_FILE).st_mtime
@locked(config.REPO_LOCK_FILE)
def get_entries(entry_type):
load()
return data[entry_type]
def get_entry(entry_type, name, exception):
try:
return get_entries(entry_type)[name]
except KeyError as e:
raise exception(name) from e
@locked(config.REPO_LOCK_FILE)
def add_entry(entry_type, name, definition):
load()
data[entry_type][name] = definition
save()
@locked(config.REPO_LOCK_FILE)
def delete_entry(entry_type, name):
load()
try:
del data[entry_type][name]
save()
except KeyError:
pass
def get_images():
return get_entries(TYPE_IMAGE)
def get_image(image_name):
return get_entry(TYPE_IMAGE, image_name, ImageNotFoundError)
def register_image(image_name, definition):
add_entry(TYPE_IMAGE, image_name, definition)
def unregister_image(image_name):
delete_entry(TYPE_IMAGE, image_name)
def get_containers():
return get_entries(TYPE_CONTAINER)
def get_container(container_name):
return get_entry(TYPE_CONTAINER, container_name, ContainerNotFoundError)
def register_container(container_name, definition):
add_entry(TYPE_CONTAINER, container_name, definition)
def unregister_container(container_name):
delete_entry(TYPE_CONTAINER, container_name)
def get_apps():
return get_entries(TYPE_APP)
def get_app(app_name):
return get_entry(TYPE_APP, app_name, AppNotFoundError)
def register_app(app_name, definition):
add_entry(TYPE_APP, app_name, definition)
def unregister_app(app_name):
delete_entry(TYPE_APP, app_name)