From e8667848e9f1ddd58e826c7f33cc62c7607f2615 Mon Sep 17 00:00:00 2001 From: Emmanuel Garette Date: Sun, 9 Jan 2022 18:43:54 +0100 Subject: [PATCH] remove included template --- src/rougail/template/base.py | 48 +++++++++++++++++++++++++-------- src/rougail/template/systemd.py | 29 +++++++++++++++++--- 2 files changed, 63 insertions(+), 14 deletions(-) diff --git a/src/rougail/template/base.py b/src/rougail/template/base.py index 2f167743..aaef46df 100644 --- a/src/rougail/template/base.py +++ b/src/rougail/template/base.py @@ -29,7 +29,7 @@ from shutil import copy import logging from typing import Dict, Any from subprocess import call -from os import listdir, makedirs, getcwd, chdir +from os import listdir, makedirs, getcwd, chdir, unlink, rmdir from os.path import dirname, join, isfile, isdir, abspath @@ -271,7 +271,7 @@ class RougailBaseTemplate: type_: str, service_name: str, service_type: str, - ) -> None: + ) -> str: """Run templatisation on one file """ self.log.info(_("Instantiating file '{filename}'")) @@ -286,6 +286,7 @@ class RougailBaseTemplate: variable = [variable] if not isdir(self.destinations_dir): raise TemplateError(_(f'cannot find destinations_dir {self.destinations_dir}')) + destfilenames = [] for idx, filename, in enumerate(filenames): if variable: var = variable[idx] @@ -301,19 +302,28 @@ class RougailBaseTemplate: ) if data is None: continue - filename, source, destfile, var = data - destfilename = join(self.destinations_dir, destfile[1:]) + filename, source, true_destfilename, var = data + destfilename = join(self.destinations_dir, true_destfilename[1:]) makedirs(dirname(destfilename), exist_ok=True) self.log.info(_(f"{filevar['engine']} processing: '{destfilename}'")) self.engines[filevar['engine']].process(filename=filename, source=source, - true_destfilename=destfile, + true_destfilename=true_destfilename, destfilename=destfilename, destdir=self.destinations_dir, variable=var, + index=idx, rougail_variables_dict=self.rougail_variables_dict, eosfunc=self.eosfunc, ) + self.process(true_destfilename, + destfilename, + filevar.get('mode'), + filevar.get('owner'), + filevar.get('group'), + ) + destfilenames.append(destfilename) + return destfilenames async def instance_files(self) -> None: """Run templatisation on all files @@ -339,6 +349,7 @@ class RougailBaseTemplate: self.prepare_template(template, templates_dir, ) + files_to_delete = [] for included in (True, False): for service_obj in await self.config.option('services').list('all'): service_name = await service_obj.option.description() @@ -374,14 +385,24 @@ class RougailBaseTemplate: elif included is True: continue if fill['activate']: - self.instance_file(fill, - type_, - service_name, - service_type, - ) + destfilenames = self.instance_file(fill, + type_, + service_name, + service_type, + ) + if included and fill.get('included', 'no') == 'content': + files_to_delete.extend(destfilenames) else: - self.log.debug(_("Instantiation of file '{filename}' disabled")) + self.log.debug(_(f"Instantiation of file '{fill['name']}' disabled")) self.post_instance_service(service_name, service_type) + for filename in files_to_delete: + unlink(filename) + parent = filename + while True: + parent = dirname(parent) + if listdir(parent): + break + rmdir(parent) self.post_instance() if ori_dir is not None: chdir(ori_dir) @@ -415,6 +436,11 @@ class RougailBaseTemplate: ): # pragma: no cover pass + def process(self, + *args, + ): # pragma: no cover + raise NotImplementedError(_('cannot processed')) + def post_instance(self): # pragma: no cover pass diff --git a/src/rougail/template/systemd.py b/src/rougail/template/systemd.py index 61c6ce20..4370bcbe 100644 --- a/src/rougail/template/systemd.py +++ b/src/rougail/template/systemd.py @@ -21,13 +21,13 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from typing import Dict, Any -from os import makedirs, symlink +from os import makedirs, symlink, chmod from os.path import dirname, isfile, join from ipaddress import ip_network from .base import RougailBaseTemplate from ..i18n import _ -from ..error import FileNotFound +from ..error import FileNotFound, TemplateError ROUGAIL_IP_TEMPLATE = """[Service] @@ -41,10 +41,14 @@ IPAddressDeny=any ROUGAIL_DEST = '/usr/local/lib' ROUGAIL_GLOBAL_SYSTEMD_FILE = '/usr/lib/systemd/system' ROUGAIL_DEST_FILE = '/tmpfiles.d/0rougail.conf' +LOCAL_DIR = ('/etc/', '/var/', '/srv/') ROUGAIL_TMPL_TEMPLATE = f"""%def display(%%file, %%filename) -%if %%filename.startswith('/etc/') or %%filename.startswith('/var/') or %%filename.startswith('/srv/') +""" +TMP_LOCAL_DIR = (f"%%filename.startswith('{local_dir}')" for local_dir in LOCAL_DIR) +ROUGAIL_TMPL_TEMPLATE += '%if ' + ' or '.join(TMP_LOCAL_DIR) +ROUGAIL_TMPL_TEMPLATE += f""" C %%filename %%file.mode %%file.owner %%file.group - {ROUGAIL_DEST}%%filename %end if %end def @@ -180,11 +184,29 @@ class RougailSystemdTemplate(RougailBaseTemplate): destfilename=destfilename, destdir=self.destinations_dir, variable=self.ip_per_service, + index=None, rougail_variables_dict=self.rougail_variables_dict, eosfunc=self.eosfunc, ) self.ip_per_service = None + def process(self, + filename: str, + destfilename: str, + mode: str, + owner: str, + group: str, + ) -> None: + for local_dir in LOCAL_DIR: + if filename.startswith(local_dir): + return + if owner not in [None, self.rougailconfig['default_files_owner']]: + raise TemplateError(_(f'cannot change owner of file {destfilename}')) + if group not in [None, self.rougailconfig['default_files_group']]: + raise TemplateError(_(f'cannot change group of file {destfilename}')) + if mode not in [None, self.rougailconfig['default_files_mode']]: + chmod(destfilename, eval(f'0o{mode}')) + def post_instance(self): destfilename = join(self.destinations_dir, ROUGAIL_DEST_FILE[1:]) makedirs(dirname(destfilename), exist_ok=True) @@ -195,6 +217,7 @@ class RougailSystemdTemplate(RougailBaseTemplate): destfilename=destfilename, destdir=self.destinations_dir, variable=None, + index=None, rougail_variables_dict=self.rougail_variables_dict, eosfunc=self.eosfunc, )