ctdb-scripts: Improve update and listing code
[samba4-gss.git] / python / samba / netcmd / domain / level.py
blobf4d257ac3244ca720998814f7c306ccf3a5198d3
1 # domain management - domain level
3 # Copyright Matthias Dieter Wallnoefer 2009
4 # Copyright Andrew Kroeger 2009
5 # Copyright Jelmer Vernooij 2007-2012
6 # Copyright Giampaolo Lauria 2011
7 # Copyright Matthieu Patou <mat@matws.net> 2011
8 # Copyright Andrew Bartlett 2008-2015
9 # Copyright Stefan Metzmacher 2012
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.
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.
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/>.
25 import ldb
26 import samba.getopt as options
27 from samba.auth import system_session
28 from samba.dsdb import check_and_update_fl, DS_DOMAIN_FUNCTION_2000
29 from samba.netcmd import Command, CommandError, Option
30 from samba.samdb import SamDB
32 from samba import functional_level
35 class cmd_domain_level(Command):
36 """Raise domain and forest function levels."""
38 synopsis = "%prog (show|raise <options>) [options]"
40 takes_optiongroups = {
41 "sambaopts": options.SambaOptions,
42 "credopts": options.CredentialsOptions,
43 "versionopts": options.VersionOptions,
46 takes_options = [
47 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
48 metavar="URL", dest="H"),
49 Option("-q", "--quiet", help="Be quiet", action="store_true"), # unused
50 Option("--forest-level", type="choice", choices=["2003", "2008", "2008_R2", "2012", "2012_R2", "2016"],
51 help="The forest function level (2003 | 2008 | 2008_R2 | 2012 | 2012_R2 | 2016)"),
52 Option("--domain-level", type="choice", choices=["2003", "2008", "2008_R2", "2012", "2012_R2", "2016"],
53 help="The domain function level (2003 | 2008 | 2008_R2 | 2012 | 2012_R2 | 2016)")
56 takes_args = ["subcommand"]
58 def run(self, subcommand, H=None, forest_level=None, domain_level=None,
59 quiet=False, credopts=None, sambaopts=None, versionopts=None):
60 if subcommand not in ["show", "raise"]:
61 raise CommandError("invalid argument: '%s' (choose from 'show', 'raise')" % subcommand)
63 lp = sambaopts.get_loadparm()
64 creds = credopts.get_credentials(lp, fallback_machine=True)
66 samdb = SamDB(url=H, session_info=system_session(),
67 credentials=creds, lp=lp)
69 domain_dn = samdb.domain_dn()
71 in_transaction = False
72 if subcommand == "raise" and (H is None or not H.startswith("ldap")):
73 samdb.transaction_start()
74 in_transaction = True
75 try:
76 check_and_update_fl(samdb, lp)
77 except Exception as e:
78 samdb.transaction_cancel()
79 raise e
81 try:
82 res_forest = samdb.search("CN=Partitions,%s" % samdb.get_config_basedn(),
83 scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
84 if len(res_forest) != 1:
85 raise CommandError("Forest not found")
87 res_domain = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
88 attrs=["msDS-Behavior-Version", "nTMixedDomain"])
89 if len(res_domain) != 1:
90 raise CommandError("domain not found")
92 res_domain_cross = samdb.search("CN=Partitions,%s" % samdb.get_config_basedn(),
93 scope=ldb.SCOPE_SUBTREE,
94 expression="(&(objectClass=crossRef)(nCName=%s))" % domain_dn,
95 attrs=["msDS-Behavior-Version"])
96 if len(res_domain_cross) != 1:
97 raise CommandError("no crossRef objects found")
99 res_dc_s = samdb.search("CN=Sites,%s" % samdb.get_config_basedn(),
100 scope=ldb.SCOPE_SUBTREE, expression="(objectClass=nTDSDSA)",
101 attrs=["msDS-Behavior-Version"])
102 if len(res_dc_s) == 0:
103 raise CommandError("no nTDSDSA objects found")
105 # default values, since "msDS-Behavior-Version" does not exist on Windows 2000 AD
106 level_forest = DS_DOMAIN_FUNCTION_2000
107 level_domain = DS_DOMAIN_FUNCTION_2000
109 if "msDS-Behavior-Version" in res_forest[0]:
110 level_forest = int(res_forest[0]["msDS-Behavior-Version"][0])
111 if "msDS-Behavior-Version" in res_domain[0]:
112 level_domain = int(res_domain[0]["msDS-Behavior-Version"][0])
113 level_domain_mixed = int(res_domain[0]["nTMixedDomain"][0])
115 min_level_dc = None
116 for msg in res_dc_s:
117 if "msDS-Behavior-Version" in msg:
118 if min_level_dc is None or int(msg["msDS-Behavior-Version"][0]) < min_level_dc:
119 min_level_dc = int(msg["msDS-Behavior-Version"][0])
120 else:
121 min_level_dc = DS_DOMAIN_FUNCTION_2000
122 # well, this is the least
123 break
125 if level_forest < DS_DOMAIN_FUNCTION_2000 or level_domain < DS_DOMAIN_FUNCTION_2000:
126 raise CommandError("Domain and/or forest function level(s) is/are invalid. Correct them or reprovision!")
127 if min_level_dc < DS_DOMAIN_FUNCTION_2000:
128 raise CommandError("Lowest function level of a DC is invalid. Correct this or reprovision!")
129 if level_forest > level_domain:
130 raise CommandError("Forest function level is higher than the domain level(s). Correct this or reprovision!")
131 if level_domain > min_level_dc:
132 raise CommandError("Domain function level is higher than the lowest function level of a DC. Correct this or reprovision!")
133 except Exception as e:
134 if in_transaction:
135 samdb.transaction_cancel()
136 raise e
138 def do_show():
139 self.message("Domain and forest function level for domain '%s'" % domain_dn)
140 if level_forest == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
141 self.message("\nATTENTION: You run SAMBA 4 on a forest function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
142 if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
143 self.message("\nATTENTION: You run SAMBA 4 on a domain function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
144 if min_level_dc == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
145 self.message("\nATTENTION: You run SAMBA 4 on a lowest function level of a DC lower than Windows 2003. This isn't supported! Please step-up or upgrade the concerning DC(s)!")
147 self.message("")
149 outstr = functional_level.level_to_string(level_forest)
150 self.message("Forest function level: (Windows) " + outstr)
152 if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed:
153 outstr = "2000 mixed (NT4 DC support)"
154 else:
155 outstr = functional_level.level_to_string(level_domain)
156 self.message("Domain function level: (Windows) " + outstr)
158 outstr = functional_level.level_to_string(min_level_dc)
159 self.message("Lowest function level of a DC: (Windows) " + outstr)
161 def do_raise():
162 msgs = []
164 current_level_domain = level_domain
166 if domain_level is not None:
167 try:
168 new_level_domain = functional_level.string_to_level(domain_level)
169 except KeyError:
170 raise CommandError(f"New functional level '{domain_level}' is not known to Samba as an AD functional level")
172 if new_level_domain <= level_domain and level_domain_mixed == 0:
173 raise CommandError("Domain function level can't be smaller than or equal to the actual one!")
174 if new_level_domain > min_level_dc:
175 raise CommandError("Domain function level can't be higher than the lowest function level of a DC!")
177 # Deactivate mixed/interim domain support
178 if level_domain_mixed != 0:
179 # Directly on the base DN
180 m = ldb.Message()
181 m.dn = ldb.Dn(samdb, domain_dn)
182 m["nTMixedDomain"] = ldb.MessageElement("0",
183 ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
184 samdb.modify(m)
185 # Under partitions
186 m = ldb.Message()
187 m.dn = res_domain_cross[0].dn
188 m["nTMixedDomain"] = ldb.MessageElement("0",
189 ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
190 try:
191 samdb.modify(m)
192 except ldb.LdbError as e:
193 (enum, emsg) = e.args
194 if enum != ldb.ERR_UNWILLING_TO_PERFORM:
195 raise
197 # Directly on the base DN
198 m = ldb.Message()
199 m.dn = ldb.Dn(samdb, domain_dn)
200 m["msDS-Behavior-Version"] = ldb.MessageElement(
201 str(new_level_domain), ldb.FLAG_MOD_REPLACE,
202 "msDS-Behavior-Version")
203 samdb.modify(m)
204 # Under partitions
205 m = ldb.Message()
206 m.dn = res_domain_cross[0].dn
207 m["msDS-Behavior-Version"] = ldb.MessageElement(
208 str(new_level_domain), ldb.FLAG_MOD_REPLACE,
209 "msDS-Behavior-Version")
210 try:
211 samdb.modify(m)
212 except ldb.LdbError as e2:
213 (enum, emsg) = e2.args
214 if enum != ldb.ERR_UNWILLING_TO_PERFORM:
215 raise
217 current_level_domain = new_level_domain
218 msgs.append("Domain function level changed!")
220 if forest_level is not None:
221 new_level_forest = functional_level.string_to_level(forest_level)
223 if new_level_forest <= level_forest:
224 raise CommandError("Forest function level can't be smaller than or equal to the actual one!")
225 if new_level_forest > current_level_domain:
226 raise CommandError("Forest function level can't be higher than the domain function level(s). Please raise it/them first!")
228 m = ldb.Message()
229 m.dn = ldb.Dn(samdb, "CN=Partitions,%s" % samdb.get_config_basedn())
230 m["msDS-Behavior-Version"] = ldb.MessageElement(
231 str(new_level_forest), ldb.FLAG_MOD_REPLACE,
232 "msDS-Behavior-Version")
233 samdb.modify(m)
234 msgs.append("Forest function level changed!")
235 msgs.append("All changes applied successfully!")
236 self.message("\n".join(msgs))
237 return
239 if subcommand == "show":
240 assert not in_transaction
241 do_show()
242 return
243 elif subcommand == "raise":
244 try:
245 do_raise()
246 except Exception as e:
247 if in_transaction:
248 samdb.transaction_cancel()
249 raise e
250 if in_transaction:
251 samdb.transaction_commit()
252 return
254 raise AssertionError("Internal Error subcommand[%s] not handled" % subcommand)