python/provision: Reconcile code partitions-only provisioning and generic provisionin...
[kai/samba.git] / source / scripting / python / samba / __init__.py
1 #!/usr/bin/python
2
3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
5
6 # Based on the original in EJS:
7 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
8 #   
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #   
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #   
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22
23 import os
24
25 def _in_source_tree():
26     """Check whether the script is being run from the source dir. """
27     return os.path.exists("%s/../../../samba4-skip" % os.path.dirname(__file__))
28
29
30 # When running, in-tree, make sure bin/python is in the PYTHONPATH
31 if _in_source_tree():
32     import sys
33     srcdir = "%s/../../.." % os.path.dirname(__file__)
34     sys.path.append("%s/bin/python" % srcdir)
35     default_ldb_modules_dir = "%s/bin/modules/ldb" % srcdir
36
37
38 import ldb
39 import credentials
40 import misc
41
42 class Ldb(ldb.Ldb):
43     """Simple Samba-specific LDB subclass that takes care 
44     of setting up the modules dir, credentials pointers, etc.
45     
46     Please note that this is intended to be for all Samba LDB files, 
47     not necessarily the Sam database. For Sam-specific helper 
48     functions see samdb.py.
49     """
50     def __init__(self, url=None, session_info=None, credentials=None, 
51                  modules_dir=None, lp=None):
52         """Open a Samba Ldb file. 
53
54         :param url: Optional LDB URL to open
55         :param session_info: Optional session information
56         :param credentials: Optional credentials, defaults to anonymous.
57         :param modules_dir: Modules directory, if not the default.
58         :param lp: Loadparm object, optional.
59
60         This is different from a regular Ldb file in that the Samba-specific
61         modules-dir is used by default and that credentials and session_info 
62         can be passed through (required by some modules).
63         """
64         super(Ldb, self).__init__()
65
66         if modules_dir is not None:
67             self.set_modules_dir(modules_dir)
68         elif default_ldb_modules_dir is not None:
69             self.set_modules_dir(default_ldb_modules_dir)
70
71         if credentials is not None:
72             self.set_credentials(self, credentials)
73
74         if session_info is not None:
75             self.set_session_info(self, session_info)
76
77         assert misc.ldb_register_samba_handlers(self) == 0
78
79         if lp is not None:
80             self.set_loadparm(self, lp)
81
82         def msg(l,text):
83             print text
84         #self.set_debug(msg)
85
86         if url is not None:
87             self.connect(url)
88
89
90     set_credentials = misc.ldb_set_credentials
91     set_session_info = misc.ldb_set_session_info
92     set_loadparm = misc.ldb_set_loadparm
93
94     def searchone(self, basedn, attribute, expression=None, 
95                   scope=ldb.SCOPE_BASE):
96         """Search for one attribute as a string.
97         
98         :param basedn: BaseDN for the search.
99         :param attribute: Name of the attribute
100         :param expression: Optional search expression.
101         :param scope: Search scope (defaults to base).
102         :return: Value of attribute as a string or None if it wasn't found.
103         """
104         res = self.search(basedn, scope, expression, [attribute])
105         if len(res) != 1 or res[0][attribute] is None:
106             return None
107         values = set(res[0][attribute])
108         assert len(values) == 1
109         return values.pop()
110
111     def erase(self):
112         """Erase this ldb, removing all records."""
113         # delete the specials
114         for attr in ["@INDEXLIST", "@ATTRIBUTES", "@SUBCLASSES", "@MODULES", 
115                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
116             try:
117                 self.delete(attr)
118             except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
119                 # Ignore missing dn errors
120                 pass
121
122         basedn = ""
123         # and the rest
124         for msg in self.search(basedn, ldb.SCOPE_SUBTREE, 
125                 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", 
126                 ["distinguishedName"]):
127             try:
128                 self.delete(msg.dn)
129             except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
130                 # Ignor eno such object errors
131                 pass
132
133         res = self.search(basedn, ldb.SCOPE_SUBTREE, "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", ["distinguishedName"])
134         assert len(res) == 0
135
136     def erase_partitions(self):
137         """Erase an ldb, removing all records."""
138         res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)", 
139                          ["namingContexts"])
140         assert len(res) == 1
141         if not "namingContexts" in res[0]:
142             return
143         for basedn in res[0]["namingContexts"]:
144             previous_remaining = 1
145             current_remaining = 0
146
147             k = 0
148             while ++k < 10 and (previous_remaining != current_remaining):
149                 # and the rest
150                 res2 = self.search(basedn, ldb.SCOPE_SUBTREE, "(|(objectclass=*)(distinguishedName=*))", ["distinguishedName"])
151                 previous_remaining = current_remaining
152                 current_remaining = len(res2)
153                 for msg in res2:
154                     self.delete(msg.dn)
155
156     def load_ldif_file_add(self, ldif_path):
157         """Load a LDIF file.
158
159         :param ldif_path: Path to LDIF file.
160         """
161         self.add_ldif(open(ldif_path, 'r').read())
162
163     def add_ldif(self, ldif):
164         """Add data based on a LDIF string.
165
166         :param ldif: LDIF text.
167         """
168         for changetype, msg in self.parse_ldif(ldif):
169             assert changetype == ldb.CHANGETYPE_NONE
170             self.add(msg)
171
172     def modify_ldif(self, ldif):
173         """Modify database based on a LDIF string.
174
175         :param ldif: LDIF text.
176         """
177         for changetype, msg in self.parse_ldif(ldif):
178             self.modify(msg)
179
180
181 def substitute_var(text, values):
182     """substitute strings of the form ${NAME} in str, replacing
183     with substitutions from subobj.
184     
185     :param text: Text in which to subsitute.
186     :param values: Dictionary with keys and values.
187     """
188
189     for (name, value) in values.items():
190         assert isinstance(name, str), "%r is not a string" % name
191         assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
192         text = text.replace("${%s}" % name, value)
193
194     return text
195
196
197 def check_all_substituted(text):
198     """Make sure that all substitution variables in a string have been replaced.
199     If not, raise an exception.
200     
201     :param text: The text to search for substitution variables
202     """
203     if not "${" in text:
204         return
205     
206     var_start = text.find("${")
207     var_end = text.find("}", var_start)
208     
209     raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1])
210
211
212 def valid_netbios_name(name):
213     """Check whether a name is valid as a NetBIOS name. """
214     # FIXME: There are probably more constraints here. 
215     # crh has a paragraph on this in his book (1.4.1.1)
216     if len(name) > 13:
217         return False
218     return True
219
220 version = misc.version