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