/
dsadmin.py
1840 lines (1676 loc) · 75 KB
/
dsadmin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
import os.path
import popen2
import base64
import urllib
import urllib2
import socket
import ldif
import re
import ldap
import cStringIO
import time
import operator
import tempfile
import pprint
import shutil
from ldap.ldapobject import SimpleLDAPObject
REPLBINDDN = ''
REPLBINDCN = ''
REPLBINDPW = ''
REPLICAID = 1 # the initial replica ID
(MASTER_TYPE,
HUB_TYPE,
LEAF_TYPE) = range(3)
class Error(Exception): pass
class InvalidArgumentError(Error):
def __init__(self,message): self.message = message
def __repr__(self): return message
class NoSuchEntryError(Error):
def __init__(self,message): self.message = message
def __repr__(self): return message
class Entry:
"""This class represents an LDAP Entry object. An LDAP entry consists of a DN
and a list of attributes. Each attribute consists of a name and a list of
values. In python-ldap, entries are returned as a list of 2-tuples.
Instance variables:
dn - string - the string DN of the entry
data - cidict - case insensitive dict of the attributes and values"""
def __init__(self,entrydata):
"""data is the raw data returned from the python-ldap result method, which is
a search result entry or a reference or None.
If creating a new empty entry, data is the string DN."""
if entrydata:
if isinstance(entrydata,tuple):
self.dn = entrydata[0]
self.data = ldap.cidict.cidict(entrydata[1])
elif isinstance(entrydata,basestring):
self.dn = entrydata
self.data = ldap.cidict.cidict()
else:
self.dn = ''
self.data = ldap.cidict.cidict()
def __nonzero__(self):
"""This allows us to do tests like if entry: returns false if there is no data,
true otherwise"""
return self.data != None and len(self.data) > 0
def hasAttr(self,name):
"""Return True if this entry has an attribute named name, False otherwise"""
return self.data and self.data.has_key(name)
def __getattr__(self,name):
"""If name is the name of an LDAP attribute, return the first value for that
attribute - equivalent to getValue - this allows the use of
entry.cn
instead of
entry.getValue('cn')
This also allows us to return None if an attribute is not found rather than
throwing an exception"""
return self.getValue(name)
def getValues(self,name):
"""Get the list (array) of values for the attribute named name"""
return self.data.get(name)
def getValue(self,name):
"""Get the first value for the attribute named name"""
return self.data.get(name,[None])[0]
def hasValue(self,name,val):
"""True if the given attribute is present and has the given value"""
if not self.hasAttr(name): return False
return val in self.data.get(name)
def hasValueCase(self,name,val):
"""True if the given attribute is present and has the given value - case insensitive value match"""
if not self.hasAttr(name): return False
return val.lower() in [x.lower() for x in self.data.get(name)]
def setValue(self,name,*value):
"""Value passed in may be a single value, several values, or a single sequence.
For example:
ent.setValue('name', 'value')
ent.setValue('name', 'value1', 'value2', ..., 'valueN')
ent.setValue('name', ['value1', 'value2', ..., 'valueN'])
ent.setValue('name', ('value1', 'value2', ..., 'valueN'))
Since *value is a tuple, we may have to extract a list or tuple from that
tuple as in the last two examples above"""
if isinstance(value[0],list) or isinstance(value[0],tuple):
self.data[name] = value[0]
else:
self.data[name] = value
setValues = setValue
def toTupleList(self):
"""Convert the attrs and values to a list of 2-tuples. The first element
of the tuple is the attribute name. The second element is either a
single value or a list of values."""
return self.data.items()
def __str__(self):
"""Convert the Entry to its LDIF representation"""
return self.__repr__()
# the ldif class base64 encodes some attrs which I would rather see in raw form - to
# encode specific attrs as base64, add them to the list below
ldif.safe_string_re = re.compile('^$')
base64_attrs = ['nsstate']
def __repr__(self):
"""Convert the Entry to its LDIF representation"""
sio = cStringIO.StringIO()
# what's all this then? the unparse method will currently only accept
# a list or a dict, not a class derived from them. self.data is a
# cidict, so unparse barfs on it. I've filed a bug against python-ldap,
# but in the meantime, we have to convert to a plain old dict for printing
# I also don't want to see wrapping, so set the line width really high (1000)
newdata = {}
newdata.update(self.data)
ldif.LDIFWriter(sio,Entry.base64_attrs,1000).unparse(self.dn,newdata)
return sio.getvalue()
def wrapper(f,name):
"""This is the method that wraps all of the methods of the superclass. This seems
to need to be an unbound method, that's why it's outside of DSAdmin. Perhaps there
is some way to do this with the new classmethod or staticmethod of 2.4.
Basically, we replace every call to a method in SimpleLDAPObject (the superclass
of DSAdmin) with a call to inner. The f argument to wrapper is the bound method
of DSAdmin (which is inherited from the superclass). Bound means that it will implicitly
be called with the self argument, it is not in the args list. name is the name of
the method to call. If name is a method that returns entry objects (e.g. result),
we wrap the data returned by an Entry class. If name is a method that takes an entry
argument, we extract the raw data from the entry object to pass in."""
def inner(*args, **kargs):
if name == 'result':
objtype, data = f(*args, **kargs)
# data is either a 2-tuple or a list of 2-tuples
# print data
if data:
if isinstance(data,tuple):
return objtype, Entry(data)
elif isinstance(data,list):
# AD sends back these search references
if objtype == ldap.RES_SEARCH_RESULT and \
isinstance(data[-1],tuple) and \
not data[-1][0]:
print "Received search reference: "
pprint.pprint(data[-1][1])
data.pop() # remove the last non-entry element
return objtype, [Entry(x) for x in data]
else:
raise TypeError, "unknown data type %s returned by result" % type(data)
else:
return objtype, data
elif name.startswith('add'):
# the first arg is self
# the second and third arg are the dn and the data to send
# We need to convert the Entry into the format used by
# python-ldap
ent = args[0]
if isinstance(ent,Entry):
return f(ent.dn, ent.toTupleList(), *args[2:])
else:
return f(*args, **kargs)
else:
return f(*args, **kargs)
return inner
class LDIFConn(ldif.LDIFParser):
def __init__(
self,
input_file,
ignored_attr_types=None,max_entries=0,process_url_schemes=None
):
"""
See LDIFParser.__init__()
Additional Parameters:
all_records
List instance for storing parsed records
"""
self.dndict = {} # maps dn to Entry
self.dnlist = [] # contains entries in order read
myfile = input_file
if isinstance(input_file,basestring):
myfile = open(input_file, "r")
ldif.LDIFParser.__init__(self,myfile,ignored_attr_types,max_entries,process_url_schemes)
self.parse()
if isinstance(input_file,basestring):
myfile.close()
def handle(self,dn,entry):
"""
Append single record to dictionary of all records.
"""
if not dn:
dn = ''
newentry = Entry((dn, entry))
self.dndict[DSAdmin.normalizeDN(dn)] = newentry
self.dnlist.append(newentry)
def get(self,dn):
ndn = DSAdmin.normalizeDN(dn)
return self.dndict.get(ndn, Entry(None))
class DSAdmin(SimpleLDAPObject):
CFGSUFFIX = "o=NetscapeRoot"
DEFAULT_USER_ID = "nobody"
def getDseAttr(self,attrname):
conffile = self.confdir + '/dse.ldif'
try:
dseldif = LDIFConn(conffile)
cnconfig = dseldif.get("cn=config")
if cnconfig:
return cnconfig.getValue(attrname)
except IOError, err:
print "could not read dse config file", err
return None
def __initPart2(self):
if self.binddn and len(self.binddn) and not hasattr(self,'sroot'):
try:
ent = self.getEntry('cn=config', ldap.SCOPE_BASE, '(objectclass=*)',
[ 'nsslapd-instancedir', 'nsslapd-errorlog',
'nsslapd-certdir', 'nsslapd-schemadir' ])
self.errlog = ent.getValue('nsslapd-errorlog')
self.confdir = ent.getValue('nsslapd-certdir')
if self.isLocal:
if not self.confdir or not os.access(self.confdir + '/dse.ldif', os.R_OK):
self.confdir = ent.getValue('nsslapd-schemadir')
if self.confdir:
self.confdir = os.path.dirname(self.confdir)
instdir = ent.getValue('nsslapd-instancedir')
if not instdir and self.isLocal:
# get instance name from errorlog
self.inst = re.match(r'(.*)[\/]slapd-([^/]+)/errors', self.errlog).group(2)
if self.isLocal and self.confdir:
instdir = self.getDseAttr('nsslapd-instancedir')
else:
instdir = re.match(r'(.*/slapd-.*)/logs/errors', self.errlog).group(1)
if not instdir:
instdir = self.confdir
print "instdir=", instdir
print ent
self.sroot, self.inst = re.match(r'(.*)[\/]slapd-([^/]+)$', instdir).groups()
ent = self.getEntry('cn=config,cn=ldbm database,cn=plugins,cn=config',
ldap.SCOPE_BASE, '(objectclass=*)',
[ 'nsslapd-directory' ])
self.dbdir = os.path.dirname(ent.getValue('nsslapd-directory'))
except (ldap.INSUFFICIENT_ACCESS, ldap.CONNECT_ERROR, NoSuchEntryError):
pass # usually means
# print "ignored exception"
except ldap.OPERATIONS_ERROR, e:
print "caught exception ", e
print "Probably Active Directory, pass"
pass # usually means this is Active Directory
except ldap.LDAPError, e:
print "caught exception ", e
raise
def __localinit__(self):
SimpleLDAPObject.__init__(self,'ldap://%s:%d' % (self.host,self.port))
# see if binddn is a dn or a uid that we need to lookup
if self.binddn and not DSAdmin.is_a_dn(self.binddn):
self.simple_bind_s("","") # anon
ent = self.getEntry(DSAdmin.CFGSUFFIX, ldap.SCOPE_SUBTREE,
"(uid=%s)" % self.binddn,
['uid'])
if ent:
self.binddn = ent.dn
else:
print "Error: could not find %s under %s" % (self.binddn, DSAdmin.CFGSUFFIX)
self.simple_bind_s(self.binddn,self.bindpw)
self.__initPart2()
def __init__(self,host,port,binddn='',bindpw=''): # default to anon bind
"""We just set our instance variables and wrap the methods - the real work is
done in __localinit__ and __initPart2 - these are separated out this way so
that we can call them from places other than instance creation e.g. when
using the start command, we just need to reconnect, not create a new instance"""
self.__wrapmethods()
self.port = port or 389
self.sslport = 0
self.host = host
self.binddn = binddn
self.bindpw = bindpw
self.isLocal = DSAdmin.isLocalHost(host)
self.suffixes = {}
self.__localinit__()
def __str__(self):
return self.host + ":" + str(self.port)
def toLDAPURL(self):
return "ldap://%s:%d/" % (self.host,self.port)
def getEntry(self,*args):
"""This wraps the search function. It is common to just get one entry"""
res = self.search(*args)
type, obj = self.result(res)
if not obj:
raise NoSuchEntryError("no such entry for " + str(args) + "\n")
elif isinstance(obj,Entry):
return obj
else: # assume list/tuple
return obj[0]
def __wrapmethods(self):
"""This wraps all methods of SimpleLDAPObject, so that we can intercept
the methods that deal with entries. Instead of using a raw list of tuples
of lists of hashes of arrays as the entry object, we want to wrap entries
in an Entry class that provides some useful methods"""
for name in dir(self.__class__.__bases__[0]):
attr = getattr(self, name)
if callable(attr):
setattr(self, name, wrapper(attr, name))
def serverCmd(self,cmd,verbose,timeout):
instanceDir = self.sroot + "/slapd-" + self.inst
errLog = instanceDir + '/logs/errors'
if hasattr(self, 'errlog'):
errLog = self.errlog
done = False
started = True
code = 0
lastLine = ""
cmd = cmd.lower()
fullCmd = instanceDir + "/" + cmd + "-slapd"
if cmd == 'start':
cmdPat = 'slapd started.'
else:
cmdPat = 'slapd stopped.'
timeout = timeout or 120 # default is 120 seconds
timeout = int(time.time()) + timeout
if cmd == 'stop':
self.unbind()
logfp = open(errLog, 'r')
logfp.seek(0, 2) # seek to end
pos = logfp.tell() # get current position
logfp.seek(pos, 0) # reset the EOF flag
rc = os.system(fullCmd)
while not done and int(time.time()) < timeout:
line = logfp.readline().strip()
while not done and line:
lastLine = line
if verbose: print line
if line.find(cmdPat) >= 0:
started += 1
if started == 2: done = True
elif line.find("Initialization Failed") >= 0:
# sometimes the server fails to start - try again
rc = os.system(fullCmd)
elif line.find("exiting.") >= 0:
# possible transient condition - try again
rc = os.system(fullCmd)
pos = logfp.tell()
line = logfp.readline().strip()
if line.find("PR_Bind") >= 0:
# server port conflicts with another one, just report and punt
print lastLine
print "This server cannot be started until the other server on this"
print "port is shutdown"
done = True
if not done:
time.sleep(2)
logfp.seek(pos, 0)
logfp.close()
if started < 2:
now = int(time.time())
if now > timeout:
print "Probable timeout: timeout=%d now=%d" % (timeout, now)
if verbose:
print "Error: could not %s server %s %s: %d" % (cmd, self.sroot, self.inst, rc)
return 1
else:
if verbose:
print "%s was successful for %s %s" % (cmd, self.sroot, self.inst)
if cmd == 'start':
self.__localinit__()
return 0
def stop(self,verbose=False,timeout=0):
if not self.isLocal and hasattr(self, 'asport'):
if verbose:
print "stopping remote server ", self
self.unbind()
if verbose:
print "closed remote server ", self
cgiargs = {}
rc = DSAdmin.cgiPost(self.host, self.asport, self.cfgdsuser,
self.cfgdspwd,
"/slapd-%s/Tasks/Operation/stop" % self.inst,
verbose, cgiargs)
if verbose:
print "stopped remote server %s rc = %d" % (self, rc)
return rc
else:
return self.serverCmd('stop', verbose, timeout)
def start(self,verbose=False,timeout=0):
if not self.isLocal and hasattr(self, 'asport'):
if verbose:
print "starting remote server ", self
cgiargs = {}
rc = DSAdmin.cgiPost(self.host, self.asport, self.cfgdsuser,
self.cfgdspwd,
"/slapd-%s/Tasks/Operation/start" % self.inst,
verbose, cgiargs)
if verbose:
print "connecting remote server", self
if not rc:
self.__localinit__()
if verbose:
print "started remote server %s rc = %d" % (self, rc)
return rc
else:
return self.serverCmd('start', verbose, timeout)
def startTaskAndWait(self,entry,verbose=False):
# start the task
dn = entry.dn
self.add_s(entry)
entry = self.getEntry(dn, ldap.SCOPE_BASE)
if not entry:
if verbose:
print "Entry %s was added successfully, but I cannot search it" % dn
return -1
elif verbose:
print entry
# wait for task completion - task is complete when the nsTaskExitCode attr is set
attrlist = ['nsTaskLog', 'nsTaskStatus', 'nsTaskExitCode', 'nsTaskCurrentItem', 'nsTaskTotalItems']
done = False
exitCode = 0
while not done:
time.sleep(1)
entry = self.getEntry(dn, ldap.SCOPE_BASE, "(objectclass=*)", attrlist)
if verbose:
print entry
if entry.nsTaskExitCode:
exitCode = int(entry.nsTaskExitCode)
done = True
return exitCode
def importLDIF(self,file,suffix,be=None,verbose=False):
cn = "import" + str(int(time.time()));
dn = "cn=%s, cn=import, cn=tasks, cn=config" % cn
entry = Entry(dn)
entry.setValues('objectclass', 'top', 'extensibleObject')
entry.setValues('cn', cn)
entry.setValues('nsFilename', file)
if be:
entry.setValues('nsInstance', be)
else:
entry.setValues('nsIncludeSuffix', suffix)
rc = self.startTaskAndWait(entry, verbose)
if rc:
if verbose:
print "Error: import task %s for file %s exited with %d" % (cn,file,rc)
else:
if verbose:
print "Import task %s for file %s completed successfully" % (cn,file)
return rc
def exportLDIF(self, file, suffix, forrepl=False, verbose=False):
cn = "export" + str(int(time.time()))
dn = "cn=%s, cn=export, cn=tasks, cn=config" % cn
entry = Entry(dn)
entry.setValues('objectclass', 'top', 'extensibleObject')
entry.setValues('cn', cn)
entry.setValues('nsFilename', file)
entry.setValues('nsIncludeSuffix', suffix)
if forrepl:
entry.setValues('nsExportReplica', 'true')
rc = self.startTaskAndWait(entry, verbose)
if rc:
if verbose:
print "Error: export task %s for file %s exited with %d" % (cn,file,rc)
else:
if verbose:
print "Export task %s for file %s completed successfully" % (cn,file)
return rc
def setupBackend(self,suffix,binddn=None,bindpw=None,urls=[],attrvals={}):
ldbmdn = "cn=ldbm database, cn=plugins, cn=config"
chaindn = "cn=chaining database, cn=plugins, cn=config"
dnbase = ""
benamebase = ""
# figure out what type of be based on args
if binddn and bindpw and urls: # its a chaining be
benamebase = "chaindb"
dnbase = chaindn
else: # its a ldbm be
benamebase = "localdb"
dnbase = ldbmdn
nsuffix = DSAdmin.normalizeDN(suffix)
benum = 1
done = False
while not done:
try:
cn = benamebase + str(benum) # e.g. localdb1
dn = "cn=" + cn + ", " + dnbase
entry = Entry(dn)
entry.setValues('objectclass', 'top', 'extensibleObject', 'nsBackendInstance')
entry.setValues('cn', cn)
entry.setValues('nsslapd-suffix', nsuffix)
if binddn and bindpw and urls: # its a chaining be
entry.setValues('nsfarmserverurl', urls)
entry.setValues('nsmultiplexorbinddn', binddn)
entry.setValues('nsmultiplexorcredentials', bindpw)
else: # set ldbm parameters, if any
pass
# $entry->add('nsslapd-cachesize' => '-1');
# $entry->add('nsslapd-cachememsize' => '2097152');
if attrvals:
for attr,val in attrvals.items():
print "adding %s = %s to entry %s" % (attr,val,dn)
entry.setValues(attr, val)
print entry
self.add_s(entry)
done = True
except ldap.ALREADY_EXISTS:
benum += 1
except ldap.LDAPError, e:
print "Could not add backend entry " + dn, e
raise
entry = self.getEntry(dn, ldap.SCOPE_BASE)
if not entry:
print "Backend entry added, but could not be searched"
else:
print entry
return cn
return ""
def setupSuffix(self,suffix,bename,parent=""):
rc = 0
nsuffix = DSAdmin.normalizeDN(suffix)
nparent = ""
if parent: nparent = DSAdmin.normalizeDN(parent)
dn = "cn=\"%s\", cn=mapping tree, cn=config" % nsuffix
try:
entry = self.getEntry("cn=mapping tree, cn=config", ldap.SCOPE_SUBTREE,
"(|(cn=\"%s\")(cn=\"%s\"))" % (suffix,nsuffix))
except NoSuchEntryError: entry = None
if not entry:
dn = "cn=\"%s\", cn=mapping tree, cn=config" % nsuffix
entry = Entry(dn)
entry.setValues('objectclass', 'top', 'extensibleObject', 'nsMappingTree')
entry.setValues('cn', "\"%s\"" % nsuffix)
entry.setValues('nsslapd-state', 'backend')
entry.setValues('nsslapd-backend', bename)
if parent: entry.setValues('nsslapd-parent-suffix', "\"%s\"" % nparent)
try:
self.add_s(entry)
entry = self.getEntry(dn, ldap.SCOPE_BASE)
if not entry:
print "Entry %s was added successfully, but I cannot search it" % dn
rc = -1
else:
print entry
except LDAPError, e:
print "Error adding suffix entry " + dn, e
raise
else:
print "Suffix entry already exists:"
print entry
return rc
def getMTEntry(self, suffix, attrs=[]):
"""Given a suffix, return the mapping tree entry for it. If attrs is
given, only fetch those attributes, otherwise, get all attributes."""
nsuffix = DSAdmin.normalizeDN(suffix)
try:
entry = self.getEntry("cn=mapping tree,cn=config", ldap.SCOPE_ONELEVEL,
"(|(cn=\"%s\")(cn=\"%s\"))" % (suffix,nsuffix),
attrs)
except NoSuchEntryError: pass
return entry
def getBackendsForSuffix(self,suffix, attrs=[]):
nsuffix = DSAdmin.normalizeDN(suffix)
try:
entries = self.search_s("cn=plugins,cn=config", ldap.SCOPE_SUBTREE,
"(&(objectclass=nsBackendInstance)(|(nsslapd-suffix=%s)(nsslapd-suffix=%s)))" % (suffix,nsuffix),
attrs)
except NoSuchEntryError: pass
return entries
# given a backend name, return the mapping tree entry for it
def getSuffixForBackend(self, bename, attrs=[]):
try:
entry = self.getEntry("cn=plugins,cn=config", ldap.SCOPE_SUBTREE,
"(&(objectclass=nsBackendInstance)(cn=%s))" % bename,
['nsslapd-suffix'])
except NoSuchEntryError:
print "Could not find and entry for backend", bename
if entry:
suffix = entry.getValue('nsslapd-suffix')
return self.getMTEntry(suffix, attrs)
return None
# see if the given suffix has a parent suffix
def findParentSuffix(self, suffix):
rdns = ldap.explode_dn(suffix)
nsuffix = DSAdmin.normalizeDN(suffix)
nrdns = ldap.explode_dn(nsuffix)
del rdns[0]
del nrdns[0]
if len(rdns) == 0:
return ""
while len(rdns) > 0:
suffix = ','.join(rdns)
nsuffix = ','.join(nrdns)
mapent = None
try:
mapent = self.getEntry('cn=mapping tree, cn=config', ldap.SCOPE_SUBTREE,
"(|(cn=\"%s\")(cn=\"%s\"))" % (suffix,nsuffix),
['cn'])
except NoSuchEntryError: pass
if mapent:
return suffix
else:
del rdns[0]
del nrdns[0]
return ""
def addSuffix(self, suffix, binddn=None, bindpw=None, urls=[]):
beents = self.getBackendsForSuffix(suffix, ['cn'])
bename = ""
benames = []
# no backends for this suffix yet - create one
if not beents:
bename = self.setupBackend(suffix,binddn,bindpw,urls)
if not bename:
print "Couldn't create backend for", suffix
return -1 # ldap error code handled already
else: # use existing backend(s)
benames = [entry.cn for entry in beents]
bename = benames.pop(0)
parent = self.findParentSuffix(suffix)
if self.setupSuffix(suffix, bename, parent):
print "Couldn't create suffix for %s %s" % (bename, suffix)
return -1
return 0
def waitForEntry(self, dn, timeout=7200, attr='', quiet=False):
scope = ldap.SCOPE_BASE
filter = "(objectclass=*)"
attrlist = []
if attr:
filter = "(%s=*)" % attr
attrlist.append(attr)
timeout += int(time.time())
if isinstance(dn,Entry):
dn = dn.dn
# wait for entry and/or attr to show up
if not quiet:
sys.stdout.write("Waiting for %s %s:%s " % (self,dn,attr))
sys.stdout.flush()
entry = None
while not entry and int(time.time()) < timeout:
try:
entry = self.getEntry(dn, scope, filter, attrlist)
except NoSuchEntryError: pass # found entry, but no attr
except ldap.NO_SUCH_OBJECT: pass # no entry yet
except ldap.LDAPError, e: # badness
print "\nError reading entry", dn, e
break
if not entry:
if not quiet:
sys.stdout.write(".")
sys.stdout.flush()
time.sleep(1)
if not entry and int(time.time()) > timeout:
print "\nwaitForEntry timeout for %s for %s" % (self,dn)
elif entry and not quiet:
print "\nThe waited for entry is:", entry
else:
print "\nError: could not read entry %s from %s" % (dn,self)
return entry
# specify the suffix (should contain 1 local database backend),
# the name of the attribute to index, and the types of indexes
# to create e.g. "pres", "eq", "sub"
def addIndex(self, suffix, attr, indexTypes, *matchingRules):
beents = self.getBackendsForSuffix(suffix, ['cn'])
# assume 1 local backend
dn = "cn=%s,cn=index,%s" % (attr, beents[0].dn)
entry = Entry(dn)
entry.setValues('objectclass', 'top', 'nsIndex')
entry.setValues('cn', attr)
entry.setValues('nsSystemIndex', "false")
entry.setValues('nsIndexType', indexTypes)
if matchingRules:
entry.setValues('nsMatchingRule', matchingRules)
try:
self.add_s(entry)
except ldap.ALREADY_EXISTS:
print "Index for attr %s for backend %s already exists" % (attr, dn)
def requireIndex(self, suffix):
beents = self.getBackendsForSuffix(suffix, ['cn'])
# assume 1 local backend
dn = beents[0].dn
replace = [(ldap.MOD_REPLACE, 'nsslapd-require-index', 'on')]
self.modify_s(dn, replace)
def addSchema(self, attr, val):
dn = "cn=schema"
self.modify_s(dn, [(ldap.MOD_ADD, attr, val)])
def addAttr(self, *args):
return self.addSchema('attributeTypes', args)
def addObjClass(self, *args):
return self.addSchema('objectClasses', args)
def enableReplLogging(self):
return self.setLogLevel(8192)
def disableReplLogging(self):
return self.setLogLevel(0)
def setLogLevel(self, *vals):
val = reduce(operator.add, vals)
self.modify_s('cn=config', [(ldap.MOD_REPLACE, 'nsslapd-errorlog-level', str(val))])
def setAccessLogLevel(self, *vals):
val = reduce(operator.add, vals)
self.modify_s('cn=config', [(ldap.MOD_REPLACE, 'nsslapd-accesslog-level', str(val))])
def setupChainingIntermediate(self):
confdn = "cn=config,cn=chaining database,cn=plugins,cn=config"
try:
self.modify_s(confdn, [(ldap.MOD_ADD, 'nsTransmittedControl',
[ '2.16.840.1.113730.3.4.12', '1.3.6.1.4.1.1466.29539.12' ])])
except ldap.TYPE_OR_VALUE_EXISTS:
print "chaining backend config already has the required controls"
def setupChainingMux(self, suffix, isIntermediate, binddn, bindpw, urls):
self.addSuffix(suffix, binddn, bindpw, urls)
if isIntermediate:
self.setupChainingIntermediate()
def setupChainingFarm(self, suffix, binddn, bindcn, bindpw):
# step 1 - create the bind dn to use as the proxy
self.setupBindDN(binddn, bindcn, bindpw)
self.addSuffix(suffix) # step 2 - create the suffix
# step 3 - add the proxy ACI to the suffix
try:
self.modify_s(suffix, [(ldap.MOD_ADD, 'aci',
[ "(targetattr = \"*\")(version 3.0; acl \"Proxied authorization for database links\"; allow (proxy) userdn = \"ldap:///%s\";)" % binddn ])])
except ldap.TYPE_OR_VALUE_EXISTS:
print "proxy aci already exists in suffix %s for %s" % (suffix, binddn)
# setup chaining from self to to - self is the mux, to is the farm
# if isIntermediate is set, this server will chain requests from another server to to
def setupChaining(self, to, suffix, isIntermediate):
bindcn = "chaining user"
binddn = "cn=%s,cn=config" % bindcn
bindpw = "chaining"
to.setupChainingFarm(suffix, binddn, bindcn, bindpw)
self.setupChainingMux(suffix, isIntermediate, binddn, bindpw, to.toLDAPURL());
def setupChangelog(self, dirpath=''):
dn = "cn=changelog5, cn=config"
dirpath = dirpath or self.dbdir + "/cldb"
entry = Entry(dn)
entry.setValues('objectclass', "top", "extensibleobject")
entry.setValues('cn', "changelog5")
entry.setValues('nsslapd-changelogdir', dirpath)
try:
self.add_s(entry)
except ldap.ALREADY_EXISTS:
print "entry %s already exists" % dn
return 0
entry = self.getEntry(dn, ldap.SCOPE_BASE)
if not entry:
print "Entry %s was added successfully, but I cannot search it" % dn
return -1
else:
print entry
return 0
def enableChainOnUpdate(self, suffix, bename):
# first, get the mapping tree entry to modify
mtent = self.getMTEntry(suffix, ['cn'])
dn = mtent.dn
# next, get the path of the replication plugin
plgent = self.getEntry("cn=Multimaster Replication Plugin,cn=plugins,cn=config",
ldap.SCOPE_BASE, "(objectclass=*)", ['nsslapd-pluginPath'])
path = plgent.getValue('nsslapd-pluginPath')
mod = [(ldap.MOD_REPLACE, 'nsslapd-state', 'backend'),
(ldap.MOD_ADD, 'nsslapd-backend', bename),
(ldap.MOD_ADD, 'nsslapd-distribution-plugin', path),
(ldap.MOD_ADD, 'nsslapd-distribution-funct', 'repl_chain_on_update')]
try:
self.modify_s(dn, mod)
except ldap.TYPE_OR_VALUE_EXISTS:
print "chainOnUpdate already enabled for %s" % suffix
def setupConsumerChainOnUpdate(self, suffix, isIntermediate, binddn, bindpw, urls):
# suffix should already exist
# we need to create a chaining backend
chainbe = self.setupBackend(suffix, binddn, bindpw, urls,
{'nsCheckLocalACI': 'on'}) # enable local db aci eval.
# do the stuff for intermediate chains
if isIntermediate:
self.setupChainingIntermediate()
# enable the chain on update
return self.enableChainOnUpdate(suffix, chainbe)
# arguments to set up a replica:
# suffix - dn of suffix
# binddn - the replication bind dn for this replica
# type - master, hub, leaf (see above for values) - if type is omitted, default is master
# legacy - true or false - for legacy consumer
# id - replica id
# if replica ID is not given, an internal sequence number will be assigned
# call like this:
# conn.setupReplica({
# 'suffix': "dc=mcom, dc=com",
# 'type' : dsadmin.MASTER_TYPE,
# 'binddn': "cn=replication manager, cn=config"
# })
# binddn can also be a list:
# 'binddn': [ "cn=repl1, cn=config", "cn=repl2, cn=config" ]
def setupReplica(self, args):
global REPLICAID # declared here because we may assign to it
suffix = args['suffix']
type = args.get('type', MASTER_TYPE)
legacy = args.get('legacy', False)
binddn = args['binddn']
id = args.get('id', None)
nsuffix = DSAdmin.normalizeDN(suffix)
dn = "cn=replica, cn=\"%s\", cn=mapping tree, cn=config" % nsuffix
try:
entry = self.getEntry(dn, ldap.SCOPE_BASE)
except ldap.NO_SUCH_OBJECT: entry = None
if entry:
print "Already setup replica for suffix", suffix
self.suffixes[nsuffix] = {}
self.suffixes[nsuffix]['dn'] = dn
self.suffixes[nsuffix]['type'] = type
return 0
binddnlist = []
if binddn:
if isinstance(binddn, basestring):
binddnlist.append(binddn)
else:
binddnlist = binddn
else:
binddnlist.append(REPLBINDDN)
if not id and type == MASTER_TYPE:
id = REPLICAID
REPLICAID += 1
elif not id:
id = 0
else:
REPLICAID = id # use given id for internal counter
if type == MASTER_TYPE:
replicatype = "3"
else:
replicatype = "2"
if legacy:
legacyval = "on"
else:
legacyval = "off"
entry = Entry(dn)
entry.setValues('objectclass', "top", "nsds5replica", "extensibleobject")
entry.setValues('cn', "replica")
entry.setValues('nsds5replicaroot', nsuffix)
entry.setValues('nsds5replicaid', str(id))
entry.setValues('nsds5replicatype', replicatype)
if type != LEAF_TYPE:
entry.setValues('nsds5flags', "1")
entry.setValues('nsds5replicabinddn', binddnlist)
entry.setValues('nsds5replicalegacyconsumer', legacyval)
if args.has_key('tpi'):
entry.setValues('nsds5replicatombstonepurgeinterval', args['tpi'])
if args.has_key('pd'):
entry.setValues('nsds5ReplicaPurgeDelay', args['pd'])
if args.has_key('referrals'):
entry.setValues('nsds5ReplicaReferral', args['referrals'])
if args.has_key('fractional'):
entry.setValues('nsDS5ReplicatedAttributeList', args['fractional'])
self.add_s(entry)
entry = self.getEntry(dn, ldap.SCOPE_BASE)
if not entry:
print "Entry %s was added successfully, but I cannot search it" % dn
return -1
else:
print entry
self.suffixes[nsuffix] = {}
self.suffixes[nsuffix]['dn'] = dn
self.suffixes[nsuffix]['type'] = type
return 0
# dn can be an entry
def setupBindDN(self, dn, cn, pwd):
if dn and isinstance(dn,Entry):
dn = dn.dn
elif not dn:
dn = REPLBINDDN
cn = cn or REPLBINDCN
pwd = pwd or REPLBINDPW
ent = Entry(dn)
ent.setValues('objectclass', "top", "person")
ent.setValues('cn', cn)
ent.setValues('userpassword', pwd)
ent.setValues('sn', "bind dn pseudo user")
try:
self.add_s(ent)
except ldap.ALREADY_EXISTS:
print "Entry %s already exists" % dn
ent = self.getEntry(dn, ldap.SCOPE_BASE)
if not ent:
print "Entry %s was added successfully, but I cannot search it" % dn
return -1
else:
print ent
return 0
def setupReplBindDN(self, dn, cn, pwd):
return self.setupBindDN(dn, cn, pwd)
def setupWinSyncAgmt(self, repoth, args, entry):
if not args.has_key('winsync'):
return
suffix = args['suffix']
entry.setValues("objectclass", "nsDSWindowsReplicationAgreement")
entry.setValues("nsds7WindowsReplicaSubtree",
args.get("win_subtree",
"cn=users," + suffix))
entry.setValues("nsds7DirectoryReplicaSubtree",
args.get("ds_subtree",
"ou=People," + suffix))
entry.setValues("nsds7NewWinUserSyncEnabled", args.get('newwinusers', 'true'))
entry.setValues("nsds7NewWinGroupSyncEnabled", args.get('newwingroups', 'true'))
windomain = ''
if args.has_key('windomain'):
windomain = args['windomain']
else:
windomain = '.'.join(ldap.explode_dn(suffix, 1))
entry.setValues("nsds7WindowsDomain", windomain)
if args.has_key('interval'):
entry.setValues("winSyncInterval", args['interval'])
# args - DSAdmin consumer (repoth), suffix, binddn, bindpw, timeout
# also need an auto_init argument