dbcheck: skip reverse member link checks when cli option specified
[samba.git] / python / samba / netcmd / dbcheck.py
1 # Samba4 AD database checker
2 #
3 # Copyright (C) Andrew Tridgell 2011
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18
19 import ldb
20 import sys
21 import samba.getopt as options
22 from samba.auth import system_session
23 from samba.samdb import SamDB
24 from samba.netcmd import (
25     Command,
26     CommandError,
27     Option
28 )
29 from samba.dbchecker import dbcheck
30
31
32 class cmd_dbcheck(Command):
33     """Check local AD database for errors."""
34     synopsis = "%prog [<DN>] [options]"
35
36     takes_optiongroups = {
37         "sambaopts": options.SambaOptions,
38         "versionopts": options.VersionOptions,
39         "credopts": options.CredentialsOptionsDouble,
40     }
41
42     def process_yes(option, opt, value, parser):
43         assert value is None
44         rargs = parser.rargs
45         if rargs:
46             arg = rargs[0]
47             if ((arg[:2] == "--" and len(arg) > 2) or
48                 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
49                 setattr(parser.values, "yes", True)
50             else:
51                 setattr(parser.values, "yes_rules", arg.split())
52                 del rargs[0]
53         else:
54             setattr(parser.values, "yes", True)
55
56     takes_args = ["DN?"]
57
58     takes_options = [
59         Option("--scope", dest="scope", default="SUB",
60                help="Pass search scope that builds DN list. Options: SUB, ONE, BASE"),
61         Option("--fix", dest="fix", default=False, action='store_true',
62                help='Fix any errors found'),
63         Option("--yes", action='callback', callback=process_yes,
64                help="don't confirm changes individually. Applies all as a single transaction (will not succeed if any errors are found)"),
65         Option("--cross-ncs", dest="cross_ncs", default=False, action='store_true',
66                help="cross naming context boundaries"),
67         Option("-v", "--verbose", dest="verbose", action="store_true", default=False,
68                help="Print more details of checking"),
69         Option("-q", "--quiet", action="store_true", default=False,
70                help="don't print details of checking"),
71         Option("--attrs", dest="attrs", default=None, help="list of attributes to check (space separated)"),
72         Option("--reindex", dest="reindex", default=False, action="store_true", help="force database re-index"),
73         Option("--force-modules", dest="force_modules", default=False, action="store_true", help="force loading of Samba modules and ignore the @MODULES record (for very old databases)"),
74         Option("--reset-well-known-acls", dest="reset_well_known_acls", default=False, action="store_true", help="reset ACLs on objects with well known default ACL values to the default"),
75         Option("--quick-membership-checks", dest="quick_membership_checks",
76                help=("Skips missing/orphaned memberOf backlinks checks, "
77                      "but speeds up dbcheck dramatically for domains with "
78                      "large groups"),
79                default=False, action="store_true"),
80         Option("-H", "--URL", help="LDB URL for database or target server (defaults to local SAM database)",
81                type=str, metavar="URL", dest="H"),
82     ]
83
84     def run(self, DN=None, H=None, verbose=False, fix=False, yes=False,
85             cross_ncs=False, quiet=False,
86             scope="SUB", credopts=None, sambaopts=None, versionopts=None,
87             attrs=None, reindex=False, force_modules=False,
88             quick_membership_checks=False,
89             reset_well_known_acls=False, yes_rules=[]):
90
91         lp = sambaopts.get_loadparm()
92
93         over_ldap = H is not None and H.startswith('ldap')
94
95         if over_ldap:
96             creds = credopts.get_credentials(lp, fallback_machine=True)
97         else:
98             creds = None
99
100         if force_modules:
101             samdb = SamDB(session_info=system_session(), url=H,
102                           credentials=creds, lp=lp, options=["modules=samba_dsdb"])
103         else:
104             try:
105                 samdb = SamDB(session_info=system_session(), url=H,
106                               credentials=creds, lp=lp)
107             except:
108                 raise CommandError("Failed to connect to DB at %s.  If this is a really old sam.ldb (before alpha9), then try again with --force-modules" % H)
109
110         if H is None or not over_ldap:
111             samdb_schema = samdb
112         else:
113             samdb_schema = SamDB(session_info=system_session(), url=None,
114                                  credentials=creds, lp=lp)
115
116         scope_map = {"SUB": ldb.SCOPE_SUBTREE, "BASE": ldb.SCOPE_BASE, "ONE": ldb.SCOPE_ONELEVEL}
117         scope = scope.upper()
118         if scope not in scope_map:
119             raise CommandError("Unknown scope %s" % scope)
120         search_scope = scope_map[scope]
121
122         controls = ['show_deleted:1']
123         if over_ldap:
124             controls.append('paged_results:1:1000')
125         if cross_ncs:
126             controls.append("search_options:1:2")
127
128         if not attrs:
129             attrs = ['*']
130         else:
131             attrs = attrs.split()
132
133         started_transaction = False
134         if yes and fix:
135             samdb.transaction_start()
136             started_transaction = True
137         try:
138             chk = dbcheck(samdb, samdb_schema=samdb_schema, verbose=verbose,
139                           fix=fix, yes=yes, quiet=quiet,
140                           in_transaction=started_transaction,
141                           quick_membership_checks=quick_membership_checks,
142                           reset_well_known_acls=reset_well_known_acls)
143
144             for option in yes_rules:
145                 if hasattr(chk, option):
146                     setattr(chk, option, 'ALL')
147                 else:
148                     raise CommandError("Invalid fix rule %s" % option)
149
150             if reindex:
151                 self.outf.write("Re-indexing...\n")
152                 error_count = 0
153                 if chk.reindex_database():
154                     self.outf.write("completed re-index OK\n")
155
156             elif force_modules:
157                 self.outf.write("Resetting @MODULES...\n")
158                 error_count = 0
159                 if chk.reset_modules():
160                     self.outf.write("completed @MODULES reset OK\n")
161
162             else:
163                 error_count = chk.check_database(DN=DN, scope=search_scope,
164                                                  controls=controls, attrs=attrs)
165         except:
166             if started_transaction:
167                 samdb.transaction_cancel()
168             raise
169
170         if started_transaction:
171             samdb.transaction_commit()
172
173         if error_count != 0:
174             sys.exit(1)