b01884
From 67875c3b75ad1af493ff5930f9c5fd5e9797b775 Mon Sep 17 00:00:00 2001
b01884
From: Thomas Woerner <twoerner@redhat.com>
b01884
Date: Oct 12 2018 07:50:29 +0000
b01884
Subject: Find orphan automember rules
b01884
b01884
b01884
If groups or hostgroups have been removed after automember rules have been
b01884
created using them, then automember-rebuild, automember-add, host-add and
b01884
more commands could fail.
b01884
b01884
A new command has been added to the ipa tool:
b01884
b01884
  ipa automember-find-orphans --type={hostgroup,group} [--remove]
b01884
b01884
This command retuns the list of orphan automember rules in the same way as
b01884
automember-find. With the --remove option the orphan rules are also removed.
b01884
b01884
The IPA API version has been increased and a test case has been added.
b01884
b01884
Using ideas from a patch by: Rob Crittenden <rcritten@redhat.com>
b01884
b01884
See: https://pagure.io/freeipa/issue/6476
b01884
Signed-off-by: Thomas Woerner <twoerner@redhat.com>
b01884
Reviewed-By: Christian Heimes <cheimes@redhat.com>
b01884
Reviewed-By: Florence Blanc-Renaud <flo@redhat.com>
b01884
Reviewed-By: Florence Blanc-Renaud <flo@redhat.com>
b01884
b01884
---
b01884
b01884
diff --git a/API.txt b/API.txt
b01884
index 49216cb..93e1a38 100644
b01884
--- a/API.txt
b01884
+++ b/API.txt
b01884
@@ -186,6 +186,20 @@ output: Output('count', type=[<type 'int'>])
b01884
 output: ListOfEntries('result')
b01884
 output: Output('summary', type=[<type 'unicode'>, <type 'NoneType'>])
b01884
 output: Output('truncated', type=[<type 'bool'>])
b01884
+command: automember_find_orphans/1
b01884
+args: 1,7,4
b01884
+arg: Str('criteria?')
b01884
+option: Flag('all', autofill=True, cli_name='all', default=False)
b01884
+option: Str('description?', autofill=False, cli_name='desc')
b01884
+option: Flag('pkey_only?', autofill=True, default=False)
b01884
+option: Flag('raw', autofill=True, cli_name='raw', default=False)
b01884
+option: Flag('remove?', autofill=True, default=False)
b01884
+option: StrEnum('type', values=[u'group', u'hostgroup'])
b01884
+option: Str('version?')
b01884
+output: Output('count', type=[<type 'int'>])
b01884
+output: ListOfEntries('result')
b01884
+output: Output('summary', type=[<type 'unicode'>, <type 'NoneType'>])
b01884
+output: Output('truncated', type=[<type 'bool'>])
b01884
 command: automember_mod/1
b01884
 args: 1,9,3
b01884
 arg: Str('cn', cli_name='automember_rule')
b01884
@@ -6503,6 +6517,7 @@ default: automember_default_group_set/1
b01884
 default: automember_default_group_show/1
b01884
 default: automember_del/1
b01884
 default: automember_find/1
b01884
+default: automember_find_orphans/1
b01884
 default: automember_mod/1
b01884
 default: automember_rebuild/1
b01884
 default: automember_remove_condition/1
b01884
diff --git a/VERSION.m4 b/VERSION.m4
b01884
index f437ef0..9d5532c 100644
b01884
--- a/VERSION.m4
b01884
+++ b/VERSION.m4
b01884
@@ -83,8 +83,8 @@ define(IPA_DATA_VERSION, 20100614120000)
b01884
 #                                                      #
b01884
 ########################################################
b01884
 define(IPA_API_VERSION_MAJOR, 2)
b01884
-define(IPA_API_VERSION_MINOR, 229)
b01884
-# Last change: Added the Certificate parameter
b01884
+define(IPA_API_VERSION_MINOR, 230)
b01884
+# Last change: Added `automember-find-orphans' command
b01884
 
b01884
 
b01884
 ########################################################
b01884
diff --git a/ipaserver/plugins/automember.py b/ipaserver/plugins/automember.py
b01884
index a502aea..a7f468d 100644
b01884
--- a/ipaserver/plugins/automember.py
b01884
+++ b/ipaserver/plugins/automember.py
b01884
@@ -117,6 +117,11 @@ EXAMPLES:
b01884
  Find all of the automember rules:
b01884
     ipa automember-find
b01884
 """) + _("""
b01884
+ Find all of the orphan automember rules:
b01884
+    ipa automember-find-orphans --type=hostgroup
b01884
+ Find all of the orphan automember rules and remove them:
b01884
+    ipa automember-find-orphans --type=hostgroup --remove
b01884
+""") + _("""
b01884
  Display a automember rule:
b01884
     ipa automember-show --type=hostgroup webservers
b01884
     ipa automember-show --type=group devel
b01884
@@ -817,3 +822,58 @@ class automember_rebuild(Method):
b01884
             result=result,
b01884
             summary=unicode(summary),
b01884
             value=pkey_to_value(None, options))
b01884
+
b01884
+
b01884
+@register()
b01884
+class automember_find_orphans(LDAPSearch):
b01884
+    __doc__ = _("""
b01884
+    Search for orphan automember rules. The command might need to be run as
b01884
+    a privileged user user to get all orphan rules.
b01884
+    """)
b01884
+    takes_options = group_type + (
b01884
+        Flag(
b01884
+            'remove?',
b01884
+            doc=_("Remove orphan automember rules"),
b01884
+        ),
b01884
+    )
b01884
+
b01884
+    msg_summary = ngettext(
b01884
+        '%(count)d rules matched', '%(count)d rules matched', 0
b01884
+    )
b01884
+
b01884
+    def execute(self, *keys, **options):
b01884
+        results = super(automember_find_orphans, self).execute(*keys,
b01884
+                                                               **options)
b01884
+
b01884
+        remove_option = options.get('remove')
b01884
+        pkey_only = options.get('pkey_only', False)
b01884
+        ldap = self.obj.backend
b01884
+        orphans = []
b01884
+        for entry in results["result"]:
b01884
+            am_dn_entry = entry['automembertargetgroup'][0]
b01884
+            # Make DN for --raw option
b01884
+            if not isinstance(am_dn_entry, DN):
b01884
+                am_dn_entry = DN(am_dn_entry)
b01884
+            try:
b01884
+                ldap.get_entry(am_dn_entry)
b01884
+            except errors.NotFound:
b01884
+                if pkey_only:
b01884
+                    # For pkey_only remove automembertargetgroup
b01884
+                    del(entry['automembertargetgroup'])
b01884
+                orphans.append(entry)
b01884
+                if remove_option:
b01884
+                    ldap.delete_entry(entry['dn'])
b01884
+
b01884
+        results["result"][:] = orphans
b01884
+        results["count"] = len(orphans)
b01884
+        return results
b01884
+
b01884
+    def pre_callback(self, ldap, filters, attrs_list, base_dn, scope, *args,
b01884
+                     **options):
b01884
+        assert isinstance(base_dn, DN)
b01884
+        scope = ldap.SCOPE_SUBTREE
b01884
+        ndn = DN(('cn', options['type']), base_dn)
b01884
+        if options.get('pkey_only', False):
b01884
+            # For pkey_only add automembertargetgroup
b01884
+            attrs_list.append('automembertargetgroup')
b01884
+        return filters, ndn, scope
b01884
diff --git a/ipatests/test_xmlrpc/test_automember_plugin.py b/ipatests/test_xmlrpc/test_automember_plugin.py
b01884
index ffbc911..c83e11a 100644
b01884
--- a/ipatests/test_xmlrpc/test_automember_plugin.py
b01884
+++ b/ipatests/test_xmlrpc/test_automember_plugin.py
b01884
@@ -715,3 +715,51 @@ class TestMultipleAutomemberConditions(XMLRPC_test):
b01884
 
b01884
         defaultgroup1.ensure_missing()
b01884
         defaulthostgroup1.ensure_missing()
b01884
+
b01884
+
b01884
+@pytest.mark.tier1
b01884
+class TestAutomemberFindOrphans(XMLRPC_test):
b01884
+    def test_create_deps_for_find_orphans(self, hostgroup1, host1,
b01884
+                                          automember_hostgroup):
b01884
+        """ Create host, hostgroup, and automember tracker for this class
b01884
+        of tests. """
b01884
+
b01884
+        # Create hostgroup1 and automember rule with condition
b01884
+        hostgroup1.ensure_exists()
b01884
+        host1.ensure_exists()
b01884
+
b01884
+        # Manually create automember rule and condition, racker will try to
b01884
+        # remove the automember rule in the end, which is failing as the rule
b01884
+        # is already removed
b01884
+        api.Command['automember_add'](hostgroup1.cn, type=u'hostgroup')
b01884
+        api.Command['automember_add_condition'](
b01884
+            hostgroup1.cn,
b01884
+            key=u'fqdn', type=u'hostgroup',
b01884
+            automemberinclusiveregex=[hostgroup_include_regex]
b01884
+        )
b01884
+
b01884
+        hostgroup1.retrieve()
b01884
+
b01884
+    def test_find_orphan_automember_rules(self, hostgroup1):
b01884
+        """ Remove hostgroup1, find and remove obsolete automember rules. """
b01884
+        # Remove hostgroup1
b01884
+
b01884
+        hostgroup1.ensure_missing()
b01884
+
b01884
+        # Find obsolete automember rules
b01884
+        result = api.Command['automember_find_orphans'](type=u'hostgroup')
b01884
+        assert result['count'] == 1
b01884
+
b01884
+        # Find and remove obsolete automember rules
b01884
+        result = api.Command['automember_find_orphans'](type=u'hostgroup',
b01884
+                                                        remove=True)
b01884
+        assert result['count'] == 1
b01884
+
b01884
+        # Find obsolete automember rules
b01884
+        result = api.Command['automember_find_orphans'](type=u'hostgroup')
b01884
+        assert result['count'] == 0
b01884
+
b01884
+        # Final cleanup of automember rule if it still exists
b01884
+        with raises_exact(errors.NotFound(
b01884
+                reason=u'%s: Automember rule not found' % hostgroup1.cn)):
b01884
+            api.Command['automember_del'](hostgroup1.cn, type=u'hostgroup')
b01884