diff --git a/main b/main index 5cbd703..c856ad0 100755 --- a/main +++ b/main @@ -20,5 +20,5 @@ if __name__ == '__main__': init.load_configuration() sherpa() except Exception: - logging.critical("unhandled exception", exc_info=True) + logging.critical('unhandled exception', exc_info=True) raise diff --git a/src/acl.py b/src/acl.py index c470417..ae397b0 100644 --- a/src/acl.py +++ b/src/acl.py @@ -6,11 +6,15 @@ import re from jinja2 import Template +CONST_CONFIG_FILENAME_SIZE = 6 + class ACL: - def __init__(self, mode): - self._config = json.loads(open('/opt/sherpa/config.json', 'r').read()) + def __init__(self, mode): + with open('/opt/sherpa/config.json', 'r') as conf, open('/opt/sherpa/templates/nginx-acl.tmpl.conf', 'r') as template: + self._config = json.loads(conf.read()) + self._template = Template(template.read()) + self._allow = True if mode is 'allow' else False - self._template = Template(open('/opt/sherpa/templates/nginx-acl.tmpl.conf', 'r').read()) self._default_allowed_methods = ['OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE'] self._parse_mode() self._generate_paths() @@ -19,23 +23,22 @@ def __init__(self, mode): def _parse_mode(self): default_config = self._template.render(allow=self._allow, path='/', allowed_methods=self._default_allowed_methods, compare='all') # create the default config - f = open('/etc/nginx/conf.d/default.conf', 'w+') - f.write(default_config) + with open('/etc/nginx/conf.d/default.conf', 'w+') as f: + f.write(default_config) def _generate_paths(self): for acl in self._config: access = True if acl['Access'] == 'allow' else False path = re.sub(r'\*', r'.*', acl['Path']) - compare = 'regex' if '*' in path else 'exact' methods = self._default_allowed_methods if 'Methods' not in acl else acl['Methods'] - random_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6)) + random_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(CONST_CONFIG_FILENAME_SIZE)) - config = self._template.render(allow=access, path=path, allowed_methods=methods, exact=True, compare=compare) + config = self._template.render(allow=access, path=path, allowed_methods=methods, exact=True, compare=('regex' if '*' in path else 'exact')) # create configs - f = open('/etc/nginx/conf.d/{}.conf'.format(random_name), 'w+') - f.write(config) + with open('/etc/nginx/conf.d/{}.conf'.format(random_name), 'w+') as f: + f.write(config) diff --git a/src/nginx.py b/src/nginx.py index b1b7893..9973be5 100644 --- a/src/nginx.py +++ b/src/nginx.py @@ -7,7 +7,7 @@ def __init__(self): def _parse_output(self, process): for line in iter(process.stdout.readline, b''): - log = line.decode("utf-8"); + log = line.decode('utf-8') print(log) def _start_nginx(self):