Revert "samba-tool: moved takes_optiongroups definition to Command base class"
[samba.git] / source4 / scripting / python / samba / netcmd / dbcheck.py
1 #!/usr/bin/env python
2 #
3 # Samba4 AD database checker
4 #
5 # Copyright (C) Andrew Tridgell 2011
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20
21 import ldb, sys
22 import samba.getopt as options
23 from samba.auth import system_session
24 from samba.samdb import SamDB
25 from samba.netcmd import (
26     Command,
27     CommandError,
28     Option
29     )
30 from samba.dbchecker import dbcheck
31
32
33 class cmd_dbcheck(Command):
34     """check local AD database for errors"""
35     synopsis = "%prog [<DN>] [options]"
36
37     takes_optiongroups = {
38         "sambaopts": options.SambaOptions,
39         "versionopts": options.VersionOptions,
40         "credopts": options.CredentialsOptionsDouble,
41     }
42
43     takes_args = ["DN?"]
44
45     takes_options = [
46         Option("--scope", dest="scope", default="SUB",
47             help="Pass search scope that builds DN list. Options: SUB, ONE, BASE"),
48         Option("--fix", dest="fix", default=False, action='store_true',
49                help='Fix any errors found'),
50         Option("--yes", dest="yes", default=False, action='store_true',
51                help="don't confirm changes, just do them all as a single transaction"),
52         Option("--cross-ncs", dest="cross_ncs", default=False, action='store_true',
53                help="cross naming context boundaries"),
54         Option("-v", "--verbose", dest="verbose", action="store_true", default=False,
55             help="Print more details of checking"),
56         Option("--quiet", dest="quiet", action="store_true", default=False,
57             help="don't print details of checking"),
58         Option("--attrs", dest="attrs", default=None, help="list of attributes to check (space separated)"),
59         Option("--reindex", dest="reindex", default=False, action="store_true", help="force database re-index"),
60         Option("-H", "--URL", help="LDB URL for database or target server (defaults to local SAM database)",
61                type=str, metavar="URL", dest="H"),
62         ]
63
64     def run(self, DN=None, H=None, verbose=False, fix=False, yes=False,
65             cross_ncs=False, quiet=False,
66             scope="SUB", credopts=None, sambaopts=None, versionopts=None,
67             attrs=None, reindex=False):
68
69         lp = sambaopts.get_loadparm()
70
71         over_ldap = H is not None and H.startswith('ldap')
72
73         if over_ldap:
74             creds = credopts.get_credentials(lp, fallback_machine=True)
75         else:
76             creds = None
77
78         samdb = SamDB(session_info=system_session(), url=H,
79                       credentials=creds, lp=lp)
80
81         if H is None or not over_ldap:
82             samdb_schema = samdb
83         else:
84             samdb_schema = SamDB(session_info=system_session(), url=None,
85                                  credentials=creds, lp=lp)
86
87         scope_map = { "SUB": ldb.SCOPE_SUBTREE, "BASE": ldb.SCOPE_BASE, "ONE":ldb.SCOPE_ONELEVEL }
88         scope = scope.upper()
89         if not scope in scope_map:
90             raise CommandError("Unknown scope %s" % scope)
91         search_scope = scope_map[scope]
92
93         controls = ['show_deleted:1']
94         if over_ldap:
95             controls.append('paged_results:1:1000')
96         if cross_ncs:
97             controls.append("search_options:1:2")
98
99         if not attrs:
100             attrs = ['*']
101         else:
102             attrs = attrs.split()
103
104         started_transaction = False
105         if yes and fix:
106             samdb.transaction_start()
107             started_transaction = True
108         try:
109             chk = dbcheck(samdb, samdb_schema=samdb_schema, verbose=verbose,
110                     fix=fix, yes=yes, quiet=quiet, in_transaction=started_transaction)
111
112             if reindex:
113                 self.outf.write("Re-indexing...\n")
114                 error_count = 0
115                 if chk.reindex_database():
116                     self.outf.write("completed re-index OK\n")
117             else:
118                 error_count = chk.check_database(DN=DN, scope=search_scope,
119                         controls=controls, attrs=attrs)
120         except Exception:
121             if started_transaction:
122                 samdb.transaction_cancel()
123             raise
124
125         if started_transaction:
126             samdb.transaction_commit()
127
128         if error_count != 0:
129             sys.exit(1)