# Copyright (C) 2017 Lars Wirzenius # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . import glob import os import yaml class ControllerState: def __init__(self): self._statedir = None def get_state_directory(self): return self._statedir def set_state_directory(self, dirname): self._statedir = dirname if not os.path.exists(self._statedir): os.makedirs(self._statedir) def get_resource_directory(self, type_name): return os.path.join(self.get_state_directory(), type_name) def get_resource_filename(self, type_name, project_name): return os.path.join( self.get_resource_directory(type_name), project_name + '.yaml') def load_resources(self, type_name): assert self._statedir is not None resources = [] dirname = self.get_resource_directory(type_name) for filename in glob.glob(dirname + '/*.yaml'): obj = self.load_resource(filename) resources.append(obj) return resources def load_resource(self, filename): with open(filename, 'r') as f: return yaml.safe_load(f) def get_resources(self, type_name): return self.load_resources(type_name) def get_resource(self, type_name, resource_name): filename = self.get_resource_filename(type_name, resource_name) if os.path.exists(filename): return self.load_resource(filename) raise NotFound() def add_resource(self, type_name, resource_name, resource): filename = self.get_resource_filename(type_name, resource_name) dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.makedirs(dirname) with open(filename, 'w') as f: yaml.safe_dump(resource, stream=f) return resource def update_resource(self, type_name, resource_name, body): filename = self.get_resource_filename(type_name, resource_name) with open(filename, 'w') as f: yaml.safe_dump(body, stream=f) return body def remove_resource(self, type_name, resource_name): filename = self.get_resource_filename(type_name, resource_name) if not os.path.exists(filename): raise NotFound() os.remove(filename) class NotFound(Exception): def __init__(self): super().__init__('Resource not found') class WrongPipelineStatus(Exception): # pragma: no cover def __init__(self, new_state): super().__init__('Cannot set pipeline state to {}'.format(new_state))