samba-tool: let 'domain level raise' call check_and_update_fl() in a transaction
[Samba.git] / python / samba / netcmd / domain / level.py
blobc4361eed342ecc72dc8f4be085905fcfb76882db
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 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 assert len(res_forest) == 1
86 res_domain = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
87 attrs=["msDS-Behavior-Version", "nTMixedDomain"])
88 assert len(res_domain) == 1
90 res_domain_cross = samdb.search("CN=Partitions,%s" % samdb.get_config_basedn(),
91 scope=ldb.SCOPE_SUBTREE,
92 expression="(&(objectClass=crossRef)(nCName=%s))" % domain_dn,
93 attrs=["msDS-Behavior-Version"])
94 assert len(res_domain_cross) == 1
96 res_dc_s = samdb.search("CN=Sites,%s" % samdb.get_config_basedn(),
97 scope=ldb.SCOPE_SUBTREE, expression="(objectClass=nTDSDSA)",
98 attrs=["msDS-Behavior-Version"])
99 assert len(res_dc_s) >= 1
101 # default values, since "msDS-Behavior-Version" does not exist on Windows 2000 AD
102 level_forest = DS_DOMAIN_FUNCTION_2000
103 level_domain = DS_DOMAIN_FUNCTION_2000
105 if "msDS-Behavior-Version" in res_forest[0]:
106 level_forest = int(res_forest[0]["msDS-Behavior-Version"][0])
107 if "msDS-Behavior-Version" in res_domain[0]:
108 level_domain = int(res_domain[0]["msDS-Behavior-Version"][0])
109 level_domain_mixed = int(res_domain[0]["nTMixedDomain"][0])
111 min_level_dc = None
112 for msg in res_dc_s:
113 if "msDS-Behavior-Version" in msg:
114 if min_level_dc is None or int(msg["msDS-Behavior-Version"][0]) < min_level_dc:
115 min_level_dc = int(msg["msDS-Behavior-Version"][0])
116 else:
117 min_level_dc = DS_DOMAIN_FUNCTION_2000
118 # well, this is the least
119 break
121 if level_forest < DS_DOMAIN_FUNCTION_2000 or level_domain < DS_DOMAIN_FUNCTION_2000:
122 raise CommandError("Domain and/or forest function level(s) is/are invalid. Correct them or reprovision!")
123 if min_level_dc < DS_DOMAIN_FUNCTION_2000:
124 raise CommandError("Lowest function level of a DC is invalid. Correct this or reprovision!")
125 if level_forest > level_domain:
126 raise CommandError("Forest function level is higher than the domain level(s). Correct this or reprovision!")
127 if level_domain > min_level_dc:
128 raise CommandError("Domain function level is higher than the lowest function level of a DC. Correct this or reprovision!")
129 except Exception as e:
130 if in_transaction:
131 samdb.transaction_cancel()
132 raise e
134 def do_show():
135 self.message("Domain and forest function level for domain '%s'" % domain_dn)
136 if level_forest == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
137 self.message("\nATTENTION: You run SAMBA 4 on a forest function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
138 if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
139 self.message("\nATTENTION: You run SAMBA 4 on a domain function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
140 if min_level_dc == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
141 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)!")
143 self.message("")
145 outstr = functional_level.level_to_string(level_forest)
146 self.message("Forest function level: (Windows) " + outstr)
148 if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed:
149 outstr = "2000 mixed (NT4 DC support)"
150 else:
151 outstr = functional_level.level_to_string(level_domain)
152 self.message("Domain function level: (Windows) " + outstr)
154 outstr = functional_level.level_to_string(min_level_dc)
155 self.message("Lowest function level of a DC: (Windows) " + outstr)
156 return
158 def do_raise():
159 msgs = []
161 current_level_domain = level_domain
163 if domain_level is not None:
164 try:
165 new_level_domain = functional_level.string_to_level(domain_level)
166 except KeyError:
167 raise CommandError(f"New functional level '{domain_level}' is not known to Samba as an AD functional level")
169 if new_level_domain <= level_domain and level_domain_mixed == 0:
170 raise CommandError("Domain function level can't be smaller than or equal to the actual one!")
171 if new_level_domain > min_level_dc:
172 raise CommandError("Domain function level can't be higher than the lowest function level of a DC!")
174 # Deactivate mixed/interim domain support
175 if level_domain_mixed != 0:
176 # Directly on the base DN
177 m = ldb.Message()
178 m.dn = ldb.Dn(samdb, domain_dn)
179 m["nTMixedDomain"] = ldb.MessageElement("0",
180 ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
181 samdb.modify(m)
182 # Under partitions
183 m = ldb.Message()
184 m.dn = res_domain_cross[0].dn
185 m["nTMixedDomain"] = ldb.MessageElement("0",
186 ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
187 try:
188 samdb.modify(m)
189 except ldb.LdbError as e:
190 (enum, emsg) = e.args
191 if enum != ldb.ERR_UNWILLING_TO_PERFORM:
192 raise
194 # Directly on the base DN
195 m = ldb.Message()
196 m.dn = ldb.Dn(samdb, domain_dn)
197 m["msDS-Behavior-Version"] = ldb.MessageElement(
198 str(new_level_domain), ldb.FLAG_MOD_REPLACE,
199 "msDS-Behavior-Version")
200 samdb.modify(m)
201 # Under partitions
202 m = ldb.Message()
203 m.dn = res_domain_cross[0].dn
204 m["msDS-Behavior-Version"] = ldb.MessageElement(
205 str(new_level_domain), ldb.FLAG_MOD_REPLACE,
206 "msDS-Behavior-Version")
207 try:
208 samdb.modify(m)
209 except ldb.LdbError as e2:
210 (enum, emsg) = e2.args
211 if enum != ldb.ERR_UNWILLING_TO_PERFORM:
212 raise
214 current_level_domain = new_level_domain
215 msgs.append("Domain function level changed!")
217 if forest_level is not None:
218 new_level_forest = functional_level.string_to_level(forest_level)
220 if new_level_forest <= level_forest:
221 raise CommandError("Forest function level can't be smaller than or equal to the actual one!")
222 if new_level_forest > current_level_domain:
223 raise CommandError("Forest function level can't be higher than the domain function level(s). Please raise it/them first!")
225 m = ldb.Message()
226 m.dn = ldb.Dn(samdb, "CN=Partitions,%s" % samdb.get_config_basedn())
227 m["msDS-Behavior-Version"] = ldb.MessageElement(
228 str(new_level_forest), ldb.FLAG_MOD_REPLACE,
229 "msDS-Behavior-Version")
230 samdb.modify(m)
231 msgs.append("Forest function level changed!")
232 msgs.append("All changes applied successfully!")
233 self.message("\n".join(msgs))
234 return
236 if subcommand == "show":
237 assert not in_transaction
238 do_show()
239 return
240 elif subcommand == "raise":
241 try:
242 do_raise()
243 except Exception as e:
244 if in_transaction:
245 samdb.transaction_cancel()
246 raise e
247 if in_transaction:
248 samdb.transaction_commit()
249 return
251 raise AssertionError("Internal Error subcommand[%s] not handled" % subcommand)