remove included template

This commit is contained in:
Emmanuel Garette 2022-01-09 18:43:54 +01:00
parent cdfa065550
commit e8667848e9
2 changed files with 63 additions and 14 deletions

View file

@ -29,7 +29,7 @@ from shutil import copy
import logging import logging
from typing import Dict, Any from typing import Dict, Any
from subprocess import call 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 from os.path import dirname, join, isfile, isdir, abspath
@ -271,7 +271,7 @@ class RougailBaseTemplate:
type_: str, type_: str,
service_name: str, service_name: str,
service_type: str, service_type: str,
) -> None: ) -> str:
"""Run templatisation on one file """Run templatisation on one file
""" """
self.log.info(_("Instantiating file '{filename}'")) self.log.info(_("Instantiating file '{filename}'"))
@ -286,6 +286,7 @@ class RougailBaseTemplate:
variable = [variable] variable = [variable]
if not isdir(self.destinations_dir): if not isdir(self.destinations_dir):
raise TemplateError(_(f'cannot find destinations_dir {self.destinations_dir}')) raise TemplateError(_(f'cannot find destinations_dir {self.destinations_dir}'))
destfilenames = []
for idx, filename, in enumerate(filenames): for idx, filename, in enumerate(filenames):
if variable: if variable:
var = variable[idx] var = variable[idx]
@ -301,19 +302,28 @@ class RougailBaseTemplate:
) )
if data is None: if data is None:
continue continue
filename, source, destfile, var = data filename, source, true_destfilename, var = data
destfilename = join(self.destinations_dir, destfile[1:]) destfilename = join(self.destinations_dir, true_destfilename[1:])
makedirs(dirname(destfilename), exist_ok=True) makedirs(dirname(destfilename), exist_ok=True)
self.log.info(_(f"{filevar['engine']} processing: '{destfilename}'")) self.log.info(_(f"{filevar['engine']} processing: '{destfilename}'"))
self.engines[filevar['engine']].process(filename=filename, self.engines[filevar['engine']].process(filename=filename,
source=source, source=source,
true_destfilename=destfile, true_destfilename=true_destfilename,
destfilename=destfilename, destfilename=destfilename,
destdir=self.destinations_dir, destdir=self.destinations_dir,
variable=var, variable=var,
index=idx,
rougail_variables_dict=self.rougail_variables_dict, rougail_variables_dict=self.rougail_variables_dict,
eosfunc=self.eosfunc, 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: async def instance_files(self) -> None:
"""Run templatisation on all files """Run templatisation on all files
@ -339,6 +349,7 @@ class RougailBaseTemplate:
self.prepare_template(template, self.prepare_template(template,
templates_dir, templates_dir,
) )
files_to_delete = []
for included in (True, False): for included in (True, False):
for service_obj in await self.config.option('services').list('all'): for service_obj in await self.config.option('services').list('all'):
service_name = await service_obj.option.description() service_name = await service_obj.option.description()
@ -374,14 +385,24 @@ class RougailBaseTemplate:
elif included is True: elif included is True:
continue continue
if fill['activate']: if fill['activate']:
self.instance_file(fill, destfilenames = self.instance_file(fill,
type_, type_,
service_name, service_name,
service_type, service_type,
) )
if included and fill.get('included', 'no') == 'content':
files_to_delete.extend(destfilenames)
else: 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) 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() self.post_instance()
if ori_dir is not None: if ori_dir is not None:
chdir(ori_dir) chdir(ori_dir)
@ -415,6 +436,11 @@ class RougailBaseTemplate:
): # pragma: no cover ): # pragma: no cover
pass pass
def process(self,
*args,
): # pragma: no cover
raise NotImplementedError(_('cannot processed'))
def post_instance(self): # pragma: no cover def post_instance(self): # pragma: no cover
pass pass

View file

@ -21,13 +21,13 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" """
from typing import Dict, Any from typing import Dict, Any
from os import makedirs, symlink from os import makedirs, symlink, chmod
from os.path import dirname, isfile, join from os.path import dirname, isfile, join
from ipaddress import ip_network from ipaddress import ip_network
from .base import RougailBaseTemplate from .base import RougailBaseTemplate
from ..i18n import _ from ..i18n import _
from ..error import FileNotFound from ..error import FileNotFound, TemplateError
ROUGAIL_IP_TEMPLATE = """[Service] ROUGAIL_IP_TEMPLATE = """[Service]
@ -41,10 +41,14 @@ IPAddressDeny=any
ROUGAIL_DEST = '/usr/local/lib' ROUGAIL_DEST = '/usr/local/lib'
ROUGAIL_GLOBAL_SYSTEMD_FILE = '/usr/lib/systemd/system' ROUGAIL_GLOBAL_SYSTEMD_FILE = '/usr/lib/systemd/system'
ROUGAIL_DEST_FILE = '/tmpfiles.d/0rougail.conf' ROUGAIL_DEST_FILE = '/tmpfiles.d/0rougail.conf'
LOCAL_DIR = ('/etc/', '/var/', '/srv/')
ROUGAIL_TMPL_TEMPLATE = f"""%def display(%%file, %%filename) 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 C %%filename %%file.mode %%file.owner %%file.group - {ROUGAIL_DEST}%%filename
%end if %end if
%end def %end def
@ -180,11 +184,29 @@ class RougailSystemdTemplate(RougailBaseTemplate):
destfilename=destfilename, destfilename=destfilename,
destdir=self.destinations_dir, destdir=self.destinations_dir,
variable=self.ip_per_service, variable=self.ip_per_service,
index=None,
rougail_variables_dict=self.rougail_variables_dict, rougail_variables_dict=self.rougail_variables_dict,
eosfunc=self.eosfunc, eosfunc=self.eosfunc,
) )
self.ip_per_service = None 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): def post_instance(self):
destfilename = join(self.destinations_dir, ROUGAIL_DEST_FILE[1:]) destfilename = join(self.destinations_dir, ROUGAIL_DEST_FILE[1:])
makedirs(dirname(destfilename), exist_ok=True) makedirs(dirname(destfilename), exist_ok=True)
@ -195,6 +217,7 @@ class RougailSystemdTemplate(RougailBaseTemplate):
destfilename=destfilename, destfilename=destfilename,
destdir=self.destinations_dir, destdir=self.destinations_dir,
variable=None, variable=None,
index=None,
rougail_variables_dict=self.rougail_variables_dict, rougail_variables_dict=self.rougail_variables_dict,
eosfunc=self.eosfunc, eosfunc=self.eosfunc,
) )