]> Frank Brehm's Git Trees - pixelpark/pp-admin-tools.git/commitdiff
Completing reading statis virtual aliases
authorFrank Brehm <frank.brehm@pixelpark.com>
Wed, 24 May 2023 10:18:36 +0000 (12:18 +0200)
committerFrank Brehm <frank.brehm@pixelpark.com>
Wed, 24 May 2023 10:18:36 +0000 (12:18 +0200)
lib/pp_admintools/app/barracuda_sync.py

index c9a2dd7e8a2927b3670f0a5c0dea01b933ddc8d9..6850e3c9d0ab63333cbc3f6bc8194f463cf2369d 100644 (file)
@@ -17,7 +17,7 @@ from pathlib import Path
 
 # Third party modules
 from fb_tools.argparse_actions import DirectoryOptionAction
-from fb_tools.common import pp
+from fb_tools.common import pp
 from fb_tools.handler import BaseHandler
 from fb_tools.multi_config import DEFAULT_ENCODING
 # from fb_tools.xlate import format_list
@@ -26,7 +26,7 @@ from fb_tools.multi_config import DEFAULT_ENCODING
 from .ldap import BaseLdapApplication
 from ..xlate import XLATOR
 
-__version__ = '0.7.6'
+__version__ = '0.7.7'
 LOG = logging.getLogger(__name__)
 
 _ = XLATOR.gettext
@@ -66,6 +66,7 @@ class BarracudaSyncApp(BaseLdapApplication):
     re_pf_config = re.compile(r'^(?P<key>\S+)\s*=\s*(?P<value>\S.*)?')
     re_pf_fieldsep = re.compile(r'\s*[,;]\s*')
     re_pf_valsep = re.compile(r'\s+')
+    re_pf_mapping = re.compile(r'^(?P<key>\S+)\s+(?P<value>\S.*)?')
     re_empty_line = re.compile(r'^\s*(?:#.*|$)')
     re_pf_lookup_map = re.compile(r'^(?P<table_type>[^:]+):(?P<path>\S.*)')
 
@@ -101,8 +102,10 @@ class BarracudaSyncApp(BaseLdapApplication):
         self.postconf_command = Path('/sbin') / self.default_postconf_command
         self.postmap_command = Path('/sbin') / self.default_postmap_command
 
+        self.postfix_origin = self.default_origin
+
         self.lookup_table_types = []
-        self.existing_aliases = []
+        self.existing_aliases = {}
         self.ldap_aliases = []
         self.aliases_to_create = []
         self.aliases_to_remove = []
@@ -132,22 +135,6 @@ class BarracudaSyncApp(BaseLdapApplication):
                 'It has to be exists. Default: {!r}.').format(str(self.postfix_maps_dir)),
         )
 
-#        sync_group.add_argument(
-#            '-B', '--basename', '--virtalias-basename', nargs='*', dest='basename',
-#            metavar=_('NAME'),
-#            help=_(
-#                'All possible basenames of the virtual aliases file below the latter '
-#                'directory. All of these basenames are used as source of the virtual aliases. '
-#                'Default: {!r}.').format(self.default_virtaliases_basename),
-#        )
-
-#        sync_group.add_argument(
-#            '--type', dest='hashtype', metavar=_('TYPE'),
-#            help=_(
-#                'The used lookup table type of all virtual aliases table. '
-#                'Default: {!r}.').format(self.default_postfix_db_hashtype),
-#        )
-
         sync_group.add_argument(
             '--base-dn', dest='baase_dn', metavar='DN',
             help=_(
@@ -170,7 +157,8 @@ class BarracudaSyncApp(BaseLdapApplication):
         self._check_postfix_commands()
         self._check_postfix_table_types()
         self._get_postfix_default_db_type()
-        self._init_virtaliases_files()
+        self._get_postfix_origin()
+        self._get_virtual_alias_mappings()
         self._check_virtalias_mappings()
 
     # -------------------------------------------------------------------------
@@ -229,15 +217,16 @@ class BarracudaSyncApp(BaseLdapApplication):
             self.exit(6)
 
     # -------------------------------------------------------------------------
-    def _get_postfix_default_db_type(self):
-        """Evaluate default postfix lookup table type."""
-        LOG.debug(_('Evaluating default postfix lookup table type ...'))
+    def get_postfix_config_value(self, key):
+        """Evaluate the given Postfix configuration value."""
+        if self.verbose > 1:
+            LOG.debug(_('Evaluating postfix configuration value {!r}.').format(key))
 
         handler = BaseHandler(appname=self.appname, verbose=self.verbose)
-        pdata = handler.call([str(self.postconf_command), 'default_database_type'], quiet=True)
+        pdata = handler.call([str(self.postconf_command), key], quiet=True)
         if pdata.returncode > 0:
-            msg = _('Error {} on evaluating default postfix lookup table type').format(
-                pdata.returncode)
+            msg = _('Error {rc} on evaluating Postfix config {k!r}').format(
+                rc=pdata.returncode, k=key)
             if pdata.stderr:
                 msg += ': ' + pdata.stderr
             else:
@@ -245,62 +234,73 @@ class BarracudaSyncApp(BaseLdapApplication):
             LOG.err(msg)
             self.exit(6)
 
+        value = None
+
         for line in pdata.stdout.splitlines():
             if self.re_empty_line.match(line):
                 continue
             m = self.re_pf_config.match(line)
-            if m and m.group('key') == 'default_database_type':
-                table_type = m.group('value')
-                if table_type:
-                    table_type = table_type.strip()
-                if table_type:
-                    self.postfix_db_hashtype = table_type
-                    LOG.debug(_('Found postfix default database type: {!r}.').format(table_type))
+            if m and m.group('key') == key:
+                value = m.group('value')
+                if value:
+                    value = value.strip()
+                break
+
+        return value
 
     # -------------------------------------------------------------------------
-    def _init_virtaliases_files(self):
-        """Collect all files used as database for virtual aliases."""
-        LOG.debug(_('Collecting all available virtual aliases table files ...'))
+    def _get_postfix_default_db_type(self):
+        """Evaluate default postfix lookup table type."""
+        LOG.debug(_('Evaluating default postfix lookup table type ...'))
 
-        handler = BaseHandler(appname=self.appname, verbose=self.verbose)
-        pdata = handler.call([str(self.postconf_command), 'virtual_alias_maps'], quiet=True)
-        if pdata.returncode > 0:
-            msg = _('Error {} on evaluating postfix virtual alias maps').format(
-                pdata.returncode)
-            if pdata.stderr:
-                msg += ': ' + pdata.stderr
-            else:
-                msg += '.'
-            LOG.err(msg)
-            self.exit(6)
+        table_type = self.get_postfix_config_value('default_database_type')
+
+        if table_type:
+            self.postfix_db_hashtype = table_type
+            LOG.debug(_('Found postfix default database type: {!r}.').format(table_type))
+
+    # -------------------------------------------------------------------------
+    def _get_postfix_origin(self):
+        """Evaluate postfix myorigin."""
+        LOG.debug(_('Evaluating postfix myorigin ...'))
+
+        origin = self.get_postfix_config_value('myorigin')
+        if origin:
+            self.postfix_origin = origin
+            LOG.debug(_('Found postfix myorigin: {!r}.').format(origin))
+
+    # -------------------------------------------------------------------------
+    def _get_virtual_alias_mappings(self):
+        """Collect all .vailable virtual alias mappings."""
+        LOG.debug(_('Collecting all available virtual alias mappings ...'))
+
+        virtual_alias_maps = self.get_postfix_config_value('virtual_alias_maps')
+        if not virtual_alias_maps:
+            msg = _('Did not found a configured value for {!r}.').format('virtual_alias_maps')
+            LOG.warn(msg)
+            return
 
         valias_maps = []
 
-        for line in pdata.stdout.splitlines():
-            if self.re_empty_line.match(line):
-                continue
-            m = self.re_pf_config.match(line)
-            if m and m.group('key') == 'virtual_alias_maps':
-                values = m.group('value')
-                for mapping in self.re_pf_valsep.split(values):
-                    if self.verbose > 1:
-                        LOG.debug(_('Evaluating mapping {!r}.').format(mapping))
-                    m = self.re_pf_lookup_map.match(mapping.strip())
-                    if m:
-                        table_type = m.group('table_type')
-                        path = m.group('path')
-                        if table_type.lower() == '${default_database_type}':
-                            table_type = self.postfix_db_hashtype
-                        va_mappping = table_type + ':' + path
-                        if table_type in self.usable_postfix_hashtypes:
-                            LOG.debug(_('Using virtual alias map {!r}.').format(va_mappping))
-                            valias_maps.append(va_mappping)
-                        else:
-                            msg = _(
-                                'Cannot use virtual alias mapping {va!r}: table type {ty!r} '
-                                'cannot be searched for all database elements.').format(
-                                va=path, ty=table_type)
-                            LOG.debug(msg)
+        for mapping in self.re_pf_valsep.split(virtual_alias_maps):
+            if self.verbose > 1:
+                LOG.debug(_('Evaluating mapping {!r}.').format(mapping))
+            m = self.re_pf_lookup_map.match(mapping.strip())
+            if m:
+                table_type = m.group('table_type')
+                path = m.group('path')
+                if table_type.lower() == '${default_database_type}':
+                    table_type = self.postfix_db_hashtype
+                va_mappping = table_type + ':' + path
+                if table_type in self.usable_postfix_hashtypes:
+                    LOG.debug(_('Using virtual alias map {!r}.').format(va_mappping))
+                    valias_maps.append(va_mappping)
+                else:
+                    msg = _(
+                        'Cannot use virtual alias mapping {va!r}: table type {ty!r} '
+                        'cannot be searched for all database elements.').format(
+                        va=path, ty=table_type)
+                    LOG.debug(msg)
 
         if not len(valias_maps):
             msg = _(
@@ -366,26 +366,31 @@ class BarracudaSyncApp(BaseLdapApplication):
                 'okay.').format(db=str(db_file), va=str(va_file)))
 
     # -------------------------------------------------------------------------
-    def read_local_virtual_aliases(self):
-        """Read virtual alias files."""
-        LOG.info(_('Reading in virtual alias files ...'))
+    def read_virtual_alias_mappings(self):
+        """Read all virtual alias mappings."""
+        LOG.info(_('Reading in all virtual alias mappings ...'))
 
-        self.existing_aliases = []
+        self.existing_aliases = {}
 
-        for va_file in self.virtaliases_files:
-            self.read_virtual_alias_file(va_file)
+        for mapping in self.virtalias_mappings:
+            self.read_virtual_alias_mapping(mapping)
+
+        if self.verbose > 1:
+            msg = _('Evaluated static virtual aliases:')
+            msg += '\n' + pp(self.existing_aliases)
+            LOG.debug(msg)
 
     # -------------------------------------------------------------------------
-    def read_virtual_alias_file(self, va_file):
-        """Read virtual aliases from given file."""
-        LOG.info(_('Reading in from virtual alias file {!r} ...').format(str(va_file)))
+    def read_virtual_alias_mapping(self, mapping):
+        """Read virtual aliases from mappping."""
+        LOG.info(_('Reading in from virtual alias mapping {!r} ...').format(str(mapping)))
 
         handler = BaseHandler(appname=self.appname, verbose=self.verbose)
-        pdata = handler.call([str(self.postmap_command), '-s', str(va_file)], quiet=True)
+        pdata = handler.call([str(self.postmap_command), '-s', mapping], quiet=True)
 
         if pdata.returncode > 0:
             msg = _('Error {rc} on getting virtual aliases from {va!r}').format(
-                rc=pdata.returncode, va=str(va_file))
+                rc=pdata.returncode, va=mapping)
             if pdata.stderr:
                 msg += ': ' + pdata.stderr
             else:
@@ -396,11 +401,30 @@ class BarracudaSyncApp(BaseLdapApplication):
         if self.verbose > 2:
             LOG.debug(_('Result:') + '\n' + str(pdata))
 
+        for line in pdata.stdout.splitlines():
+            if self.re_empty_line.match(line):
+                continue
+            m = self.re_pf_mapping.match(line)
+            if m:
+                alias = m.group('key')
+                if '@' not in alias:
+                    alias += '@' + self.postfix_origin
+                if alias not in self.existing_aliases:
+                    self.existing_aliases[alias] = []
+
+                val = m.group('value').strip()
+                targets = self.re_pf_fieldsep.split(val)
+                for target in targets:
+                    target = target.strip()
+                    if '@' not in target:
+                        target += '@' + self.postfix_origin
+                    if target not in self.existing_aliases[alias]:
+                        self.existing_aliases[alias].append(target)
+
     # -------------------------------------------------------------------------
     def _run(self):
 
-        pass
-        # self.read_local_virtual_aliases()
+        self.read_virtual_alias_mappings()
 
 
 # =============================================================================