upgradeprovision: Use logging infrastructure.
[samba.git] / source4 / scripting / python / samba / upgradehelpers.py
1 #!/usr/bin/python
2 #
3 # Helpers for provision stuff
4 # Copyright (C) Matthieu Patou <mat@matws.net> 2009-2010
5 #
6 # Based on provision a Samba4 server by
7 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
8 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008
9 #
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
25 import os
26 import string
27 import re
28 import shutil
29
30 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE
31 import ldb
32
33 from samba import Ldb
34 from samba.dcerpc import misc, security
35 from samba.dsdb import DS_DOMAIN_FUNCTION_2000
36 from samba.provision import (ProvisionNames, provision_paths_from_lp,
37     FILL_FULL, provision, ProvisioningError)
38 from samba.ndr import ndr_unpack
39
40
41 def get_paths(param, targetdir=None, smbconf=None):
42     """Get paths to important provision objects (smb.conf, ldb files, ...)
43
44     :param param: Param object
45     :param targetdir: Directory where the provision is (or will be) stored
46     :param smbconf: Path to the smb.conf file
47     :return: A list with the path of important provision objects"""
48     if targetdir is not None:
49         etcdir = os.path.join(targetdir, "etc")
50         if not os.path.exists(etcdir):
51             os.makedirs(etcdir)
52         smbconf = os.path.join(etcdir, "smb.conf")
53     if smbconf is None:
54         smbconf = param.default_path()
55
56     if not os.path.exists(smbconf):
57         raise ProvisioningError("Unable to find smb.conf")
58
59     lp = param.LoadParm()
60     lp.load(smbconf)
61     paths = provision_paths_from_lp(lp, lp.get("realm"))
62     return paths
63
64
65 def find_provision_key_parameters(param, credentials, session_info, paths,
66         smbconf):
67     """Get key provision parameters (realm, domain, ...) from a given provision
68
69     :param param: Param object
70     :param credentials: Credentials for the authentification
71     :param session_info: Session object
72     :param paths: A list of path to provision object
73     :param smbconf: Path to the smb.conf file
74     :return: A list of key provision parameters
75     """
76
77     lp = param.LoadParm()
78     lp.load(paths.smbconf)
79     names = ProvisionNames()
80     names.adminpass = None
81     # NT domain, kerberos realm, root dn, domain dn, domain dns name
82     names.domain = string.upper(lp.get("workgroup"))
83     names.realm = lp.get("realm")
84     basedn = "DC=" + names.realm.replace(".", ",DC=")
85     names.dnsdomain = names.realm
86     names.realm = string.upper(names.realm)
87     # netbiosname
88     secrets_ldb = Ldb(paths.secrets, session_info=session_info,
89         credentials=credentials,lp=lp, options=["modules:samba_secrets"])
90     # Get the netbiosname first (could be obtained from smb.conf in theory)
91     res = secrets_ldb.search(expression="(flatname=%s)" % names.domain,
92             base="CN=Primary Domains", scope=SCOPE_SUBTREE, attrs=["sAMAccountName"])
93     names.netbiosname = str(res[0]["sAMAccountName"]).replace("$","")
94
95     names.smbconf = smbconf
96     # It's important here to let ldb load with the old module or it's quite
97     # certain that the LDB won't load ...
98     samdb = Ldb(paths.samdb, session_info=session_info,
99             credentials=credentials, lp=lp, options=["modules:samba_dsdb"])
100
101     # That's a bit simplistic but it's ok as long as we have only 3
102     # partitions
103     current = samdb.search(expression="(objectClass=*)", 
104         base="", scope=SCOPE_BASE,
105         attrs=["defaultNamingContext", "schemaNamingContext",
106                "configurationNamingContext","rootDomainNamingContext"])
107
108     names.configdn = current[0]["configurationNamingContext"]
109     configdn = str(names.configdn)
110     names.schemadn = current[0]["schemaNamingContext"]
111     if ldb.Dn(samdb, basedn) != ldb.Dn(samdb, current[0]["defaultNamingContext"][0]):
112         raise ProvisioningError("basedn in %s (%s) and from %s (%s) is not the same ..." % (paths.samdb, str(current[0]["defaultNamingContext"][0]), paths.smbconf, basedn))
113
114     names.domaindn=current[0]["defaultNamingContext"]
115     names.rootdn=current[0]["rootDomainNamingContext"]
116     # default site name
117     res3 = samdb.search(expression="(objectClass=*)", 
118         base="CN=Sites,"+configdn, scope=SCOPE_ONELEVEL, attrs=["cn"])
119     names.sitename = str(res3[0]["cn"])
120
121     # dns hostname and server dn
122     res4 = samdb.search(expression="(CN=%s)" % names.netbiosname,
123         base="OU=Domain Controllers,"+basedn, scope=SCOPE_ONELEVEL, attrs=["dNSHostName"])
124     names.hostname = str(res4[0]["dNSHostName"]).replace("."+names.dnsdomain,"")
125
126     server_res = samdb.search(expression="serverReference=%s" % res4[0].dn,
127             attrs=[], base=configdn)
128     names.serverdn = server_res[0].dn
129
130     # invocation id/objectguid
131     res5 = samdb.search(expression="(objectClass=*)",
132             base="CN=NTDS Settings,%s" % str(names.serverdn), scope=SCOPE_BASE,
133             attrs=["invocationID", "objectGUID"])
134     names.invocation = str(ndr_unpack(misc.GUID, res5[0]["invocationId"][0]))
135     names.ntdsguid = str(ndr_unpack(misc.GUID, res5[0]["objectGUID"][0]))
136
137     # domain guid/sid
138     res6 = samdb.search(expression="(objectClass=*)",base=basedn,
139             scope=SCOPE_BASE, attrs=["objectGUID",
140                 "objectSid","msDS-Behavior-Version" ])
141     names.domainguid = str(ndr_unpack( misc.GUID,res6[0]["objectGUID"][0]))
142     names.domainsid = ndr_unpack( security.dom_sid,res6[0]["objectSid"][0])
143     if (res6[0].get("msDS-Behavior-Version") is None or
144         int(res6[0]["msDS-Behavior-Version"][0]) < DS_DOMAIN_FUNCTION_2000):
145         names.domainlevel = DS_DOMAIN_FUNCTION_2000
146     else:
147         names.domainlevel = int(res6[0]["msDS-Behavior-Version"][0])
148
149     # policy guid
150     res7 = samdb.search(expression="(displayName=Default Domain Policy)",
151             base="CN=Policies,CN=System,"+basedn, scope=SCOPE_ONELEVEL,
152             attrs=["cn","displayName"])
153     names.policyid = str(res7[0]["cn"]).replace("{","").replace("}","")
154     # dc policy guid
155     res8 = samdb.search(expression="(displayName=Default Domain Controllers Policy)",
156             base="CN=Policies,CN=System,"+basedn, scope=SCOPE_ONELEVEL,
157             attrs=["cn","displayName"])
158     if len(res8) == 1:
159         names.policyid_dc = str(res8[0]["cn"]).replace("{","").replace("}","")
160     else:
161         names.policyid_dc = None
162
163     return names
164
165
166 def newprovision(names, setup_dir, creds, session, smbconf, provdir, logger):
167     """Create a new provision.
168
169     This provision will be the reference for knowing what has changed in the
170     since the latest upgrade in the current provision
171
172     :param names: List of provision parameters
173     :param setup_dis: Directory where the setup files are stored
174     :param creds: Credentials for the authentification
175     :param session: Session object
176     :param smbconf: Path to the smb.conf file
177     :param provdir: Directory where the provision will be stored
178     :param logger: A `Logger`
179     """
180     if os.path.isdir(provdir):
181         shutil.rmtree(provdir)
182     os.chdir(os.path.join(setup_dir,".."))
183     os.mkdir(provdir)
184     logger.info("Provision stored in %s", provdir)
185     provision(setup_dir, logger, session, creds, smbconf=smbconf,
186             targetdir=provdir, samdb_fill=FILL_FULL, realm=names.realm,
187             domain=names.domain, domainguid=names.domainguid,
188             domainsid=str(names.domainsid), ntdsguid=names.ntdsguid,
189             policyguid=names.policyid, policyguid_dc=names.policyid_dc,
190             hostname=names.netbiosname, hostip=None, hostip6=None,
191             invocationid=names.invocation, adminpass=names.adminpass,
192             krbtgtpass=None, machinepass=None, dnspass=None, root=None,
193             nobody=None, wheel=None, users=None,
194             serverrole="domain controller", ldap_backend_extra_port=None,
195             backend_type=None, ldapadminpass=None, ol_mmr_urls=None,
196             slapd_path=None, setup_ds_path=None, nosync=None,
197             dom_for_fun_level=names.domainlevel,
198             ldap_dryrun_mode=None, useeadb=True)
199
200
201 def dn_sort(x, y):
202     """Sorts two DNs in the lexicographical order it and put higher level DN
203     before.
204
205     So given the dns cn=bar,cn=foo and cn=foo the later will be return as
206     smaller
207
208     :param x: First object to compare
209     :param y: Second object to compare
210     """
211     p = re.compile(r'(?<!\\),')
212     tab1 = p.split(str(x))
213     tab2 = p.split(str(y))
214     minimum = min(len(tab1), len(tab2))
215     len1 = len(tab1)-1
216     len2 = len(tab2)-1
217     # Note: python range go up to upper limit but do not include it
218     for i in range(0, minimum):
219         ret = cmp(tab1[len1-i], tab2[len2-i])
220         if ret != 0:
221             return ret
222         else:
223             if i == minimum-1:
224                 assert len1 != len2, "PB PB PB"+" ".join(tab1)+" / "+" ".join(tab2)
225                 if len1 > len2:
226                     return 1
227                 else:
228                     return -1
229     return ret