KCC: whitespace for pep8
[samba.git] / source4 / scripting / bin / samba_kcc
1 #!/usr/bin/env python
2 #
3 # Compute our KCC topology
4 #
5 # Copyright (C) Dave Craft 2011
6 # Copyright (C) Andrew Bartlett 2015
7 #
8 # Andrew Bartlett's alleged work performed by his underlings Douglas
9 # Bagnall and Garming Sam.
10 #
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
23
24 import os
25 import sys
26 import random
27
28 # ensure we get messages out immediately, so they get in the samba logs,
29 # and don't get swallowed by a timeout
30 os.environ['PYTHONUNBUFFERED'] = '1'
31
32 # forcing GMT avoids a problem in some timezones with kerberos. Both MIT
33 # heimdal can get mutual authentication errors due to the 24 second difference
34 # between UTC and GMT when using some zone files (eg. the PDT zone from
35 # the US)
36 os.environ["TZ"] = "GMT"
37
38 # Find right directory when running from source tree
39 sys.path.insert(0, "bin/python")
40
41 import optparse
42 import time
43
44 from samba import getopt as options
45
46 from samba.kcc.graph_utils import verify_and_dot, list_verify_tests
47 from samba.kcc.graph_utils import GraphError
48
49 import logging
50 from samba.kcc.debug import logger, DEBUG, DEBUG_FN
51 from samba.kcc import KCC
52
53 # If DEFAULT_RNG_SEED is None, /dev/urandom or system time is used.
54 DEFAULT_RNG_SEED = None
55
56 def test_all_reps_from(kcc, lp, creds, unix_now, rng_seed=None):
57     """Run the KCC from all DSAs in read-only mode
58
59     The behaviour depends on the global opts variable which contains
60     command line variables. Usually you will want to run it with
61     opt.dot_file_dir set (via --dot-file-dir) to see the graphs that
62     would be created from each DC.
63
64     :param lp: a loadparm object.
65     :param creds: a Credentials object.
66     :param unix_now: the unix epoch time as an integer
67     :param rng_seed: a seed for the random number generator
68     :return None:
69     """
70     # This implies readonly and attempt_live_connections
71     dsas = kcc.list_dsas()
72     samdb = kcc.samdb
73     needed_parts = {}
74     current_parts = {}
75
76     guid_to_dnstr = {}
77     for site in kcc.site_table.values():
78         guid_to_dnstr.update((str(dsa.dsa_guid), dnstr)
79                              for dnstr, dsa in site.dsa_table.items())
80
81     dot_edges = []
82     dot_vertices = []
83     colours = []
84     vertex_colours = []
85
86     for dsa_dn in dsas:
87         if rng_seed is not None:
88             random.seed(rng_seed)
89         kcc = KCC(unix_now, readonly=True,
90                   verify=opts.verify, debug=opts.debug,
91                   dot_file_dir=opts.dot_file_dir)
92         kcc.samdb = samdb
93         kcc.run(opts.dburl, lp, creds, forced_local_dsa=dsa_dn,
94                 forget_local_links=opts.forget_local_links,
95                 forget_intersite_links=opts.forget_intersite_links,
96                 attempt_live_connections=opts.attempt_live_connections)
97
98         current, needed = kcc.my_dsa.get_rep_tables()
99
100         for dsa in kcc.my_site.dsa_table.values():
101             if dsa is kcc.my_dsa:
102                 continue
103             kcc.translate_ntdsconn(dsa)
104             c, n = dsa.get_rep_tables()
105             current.update(c)
106             needed.update(n)
107
108         for name, rep_table, rep_parts in (
109                 ('needed', needed, needed_parts),
110                 ('current', current, current_parts)):
111             for part, nc_rep in rep_table.items():
112                 edges = rep_parts.setdefault(part, [])
113                 for reps_from in nc_rep.rep_repsFrom:
114                     source = guid_to_dnstr[str(reps_from.source_dsa_obj_guid)]
115                     dest = guid_to_dnstr[str(nc_rep.rep_dsa_guid)]
116                     edges.append((source, dest))
117
118         for site in kcc.site_table.values():
119             for dsa in site.dsa_table.values():
120                 if dsa.is_ro():
121                     vertex_colours.append('#cc0000')
122                 else:
123                     vertex_colours.append('#0000cc')
124                 dot_vertices.append(dsa.dsa_dnstr)
125                 if dsa.connect_table:
126                     DEBUG_FN("DSA %s %s connections:\n%s" %
127                              (dsa.dsa_dnstr, len(dsa.connect_table),
128                               [x.from_dnstr for x in
129                                dsa.connect_table.values()]))
130                 for con in dsa.connect_table.values():
131                     if con.is_rodc_topology():
132                         colours.append('red')
133                     else:
134                         colours.append('blue')
135                     dot_edges.append((con.from_dnstr, dsa.dsa_dnstr))
136
137     verify_and_dot('all-dsa-connections', dot_edges, vertices=dot_vertices,
138                    label="all dsa NTDSConnections", properties=(),
139                    debug=DEBUG, verify=opts.verify,
140                    dot_file_dir=opts.dot_file_dir,
141                    directed=True, edge_colors=colours,
142                    vertex_colors=vertex_colours)
143
144     for name, rep_parts in (('needed', needed_parts),
145                             ('current', current_parts)):
146         for part, edges in rep_parts.items():
147             verify_and_dot('all-repsFrom_%s__%s' % (name, part), edges,
148                            directed=True, label=part,
149                            properties=(), debug=DEBUG, verify=opts.verify,
150                            dot_file_dir=opts.dot_file_dir)
151
152 ##################################################
153 # samba_kcc entry point
154 ##################################################
155
156
157 parser = optparse.OptionParser("samba_kcc [options]")
158 sambaopts = options.SambaOptions(parser)
159 credopts = options.CredentialsOptions(parser)
160
161 parser.add_option_group(sambaopts)
162 parser.add_option_group(credopts)
163 parser.add_option_group(options.VersionOptions(parser))
164
165 parser.add_option("--readonly", default=False,
166                   help="compute topology but do not update database",
167                   action="store_true")
168
169 parser.add_option("--debug",
170                   help="debug output",
171                   action="store_true")
172
173 parser.add_option("--verify",
174                   help="verify that assorted invariants are kept",
175                   action="store_true")
176
177 parser.add_option("--list-verify-tests",
178                   help=("list what verification actions are available "
179                         "and do nothing else"),
180                   action="store_true")
181
182 parser.add_option("--dot-file-dir", default=None,
183                   help="Write Graphviz .dot files to this directory")
184
185 parser.add_option("--seed",
186                   help="random number seed",
187                   type=int, default=DEFAULT_RNG_SEED)
188
189 parser.add_option("--importldif",
190                   help="import topology ldif file",
191                   type=str, metavar="<file>")
192
193 parser.add_option("--exportldif",
194                   help="export topology ldif file",
195                   type=str, metavar="<file>")
196
197 parser.add_option("-H", "--URL",
198                   help="LDB URL for database or target server",
199                   type=str, metavar="<URL>", dest="dburl")
200
201 parser.add_option("--tmpdb",
202                   help="schemaless database file to create for ldif import",
203                   type=str, metavar="<file>")
204
205 parser.add_option("--now",
206                   help=("assume current time is this ('YYYYmmddHHMMSS[tz]',"
207                         " default: system time)"),
208                   type=str, metavar="<date>")
209
210 parser.add_option("--forced-local-dsa",
211                   help="run calculations assuming the DSA is this DN",
212                   type=str, metavar="<DSA>")
213
214 parser.add_option("--attempt-live-connections", default=False,
215                   help="Attempt to connect to other DSAs to test links",
216                   action="store_true")
217
218 parser.add_option("--list-valid-dsas", default=False,
219                   help=("Print a list of DSA dnstrs that could be"
220                         " used in --forced-local-dsa"),
221                   action="store_true")
222
223 parser.add_option("--test-all-reps-from", default=False,
224                   help="Create and verify a graph of reps-from for every DSA",
225                   action="store_true")
226
227 parser.add_option("--forget-local-links", default=False,
228                   help="pretend not to know the existing local topology",
229                   action="store_true")
230
231 parser.add_option("--forget-intersite-links", default=False,
232                   help="pretend not to know the existing intersite topology",
233                   action="store_true")
234
235
236 opts, args = parser.parse_args()
237
238
239 if opts.list_verify_tests:
240     list_verify_tests()
241     sys.exit(0)
242
243 if opts.test_all_reps_from:
244     opts.readonly = True
245
246 if opts.debug:
247     logger.setLevel(logging.DEBUG)
248 elif opts.readonly:
249     logger.setLevel(logging.INFO)
250 else:
251     logger.setLevel(logging.WARNING)
252
253 random.seed(opts.seed)
254
255 if opts.now:
256     for timeformat in ("%Y%m%d%H%M%S%Z", "%Y%m%d%H%M%S"):
257         try:
258             now_tuple = time.strptime(opts.now, timeformat)
259             break
260         except ValueError:
261             pass
262     else:
263         # else happens if break doesn't --> no match
264         print >> sys.stderr, "could not parse time '%s'" % opts.now
265         sys.exit(1)
266     unix_now = int(time.mktime(now_tuple))
267 else:
268     unix_now = int(time.time())
269
270 lp = sambaopts.get_loadparm()
271 creds = credopts.get_credentials(lp, fallback_machine=True)
272
273 if opts.dburl is None:
274     opts.dburl = lp.samdb_url()
275
276 # Instantiate Knowledge Consistency Checker and perform run
277 kcc = KCC(unix_now, readonly=opts.readonly, verify=opts.verify,
278           debug=opts.debug, dot_file_dir=opts.dot_file_dir)
279
280 if opts.exportldif:
281     rc = kcc.export_ldif(opts.dburl, lp, creds, opts.exportldif)
282     sys.exit(rc)
283
284 if opts.importldif:
285     if opts.tmpdb is None or opts.tmpdb.startswith('ldap'):
286         logger.error("Specify a target temp database file with --tmpdb option")
287         sys.exit(1)
288
289     rc = kcc.import_ldif(opts.tmpdb, lp, creds, opts.importldif,
290                          forced_local_dsa=opts.forced_local_dsa)
291     if rc != 0:
292         sys.exit(rc)
293
294
295 kcc.load_samdb(opts.dburl, lp, creds, force=False)
296
297 if opts.test_all_reps_from:
298     test_all_reps_from(kcc, lp, creds, unix_now, rng_seed=opts.seed)
299     sys.exit()
300
301 if opts.list_valid_dsas:
302     print '\n'.join(kcc.list_dsas())
303     sys.exit()
304
305 try:
306     rc = kcc.run(opts.dburl, lp, creds, opts.forced_local_dsa,
307                  opts.forget_local_links, opts.forget_intersite_links,
308                  attempt_live_connections=opts.attempt_live_connections)
309     sys.exit(rc)
310
311 except GraphError, e:
312     print e
313     sys.exit(1)