-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathdsadmin.py
More file actions
2826 lines (2542 loc) · 109 KB
/
dsadmin.py
File metadata and controls
2826 lines (2542 loc) · 109 KB
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
"""The dsadmin module.
IMPORTANT: Ternary operator syntax is unsupported on RHEL5
x if cond else y #don't!
"""
try:
from subprocess import Popen, PIPE, STDOUT
HASPOPEN = True
except ImportError:
import popen2
HASPOPEN = False
import sys
import os
import os.path
import base64
import urllib
import urllib2
import socket
import ldif
import re
import ldap
import cStringIO
import time
import operator
import shutil
import datetime
import select
from ldap.ldapobject import SimpleLDAPObject
from ldapurl import LDAPUrl
from ldap.cidict import cidict
from dsadmin_utils import *
# replicatype @see https://access.redhat.com/knowledge/docs/en-US/Red_Hat_Directory_Server/8.1/html/Administration_Guide/Managing_Replication-Configuring-Replication-cmd.html
# 2 for consumers and hubs (read-only replicas)
# 3 for both single and multi-master suppliers (read-write replicas)
# TODO: let's find a way to be consistent - eg. using bitwise operator
(MASTER_TYPE,
HUB_TYPE,
LEAF_TYPE) = range(3)
REPLICA_RDONLY_TYPE = 2 # CONSUMER and HUB
REPLICA_WRONLY_TYPE = 1 # SINGLE and MULTI MASTER
REPLICA_RDWR_TYPE = REPLICA_RDONLY_TYPE | REPLICA_WRONLY_TYPE
DBMONATTRRE = re.compile(r'^([a-zA-Z]+)-([1-9][0-9]*)$')
DBMONATTRRESUN = re.compile(r'^([a-zA-Z]+)-([a-zA-Z]+)$')
# Some DN constants
DN_CONFIG = "cn=config"
DN_LDBM = "cn=ldbm database,cn=plugins,cn=config"
DN_MAPPING_TREE = "cn=mapping tree,cn=config"
DN_CHAIN = "cn=chaining database,cn=plugins,cn=config"
class Error(Exception):
pass
class InvalidArgumentError(Error):
pass
class NoSuchEntryError(Error):
pass
class MissingEntryError(NoSuchEntryError):
"""When just added entries are missing."""
pass
class Entry(object):
"""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.
String values will be rendered badly!
ex. {
'uid': ['user01'],
'cn': ['User'],
'objectlass': [ 'person', 'inetorgperson' ]
}
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
"""
# 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 __init__(self, entrydata):
"""entrydata is the raw data returned from the python-ldap
result method, which is:
* a search result entry -> (dn, {dict...} )
* or a reference -> (None, reference)
* or None.
If creating a new empty entry, data is the string DN.
"""
self.ref = None
if entrydata:
if isinstance(entrydata, tuple):
if entrydata[0] is None:
self.ref = entrydata[1] # continuation reference
else:
self.dn = entrydata[0]
self.data = cidict(entrydata[1])
elif isinstance(entrydata, basestring):
self.dn = entrydata
self.data = cidict()
else:
#
self.dn = ''
self.data = 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 is not 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 name in self.data
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"""
if name == 'dn' or name == 'data':
return self.__dict__.get(name, None)
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=None):
"""True if the given attribute is present and has the given value"""
if not self.hasAttr(name):
return False
if not val:
return True
if isinstance(val, list):
return val == self.data.get(name)
if isinstance(val, tuple):
return list(val) == self.data.get(name)
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
def getAttrs(self):
if not self.data:
return []
return self.data.keys()
def iterAttrs(self, attrsOnly=False):
if attrsOnly:
return self.data.iterkeys()
else:
return self.data.iteritems()
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 getref(self):
return self.ref
def __str__(self):
"""Convert the Entry to its LDIF representation"""
return self.__repr__()
def update(self, dct):
"""Update passthru to the data attribute."""
print "update with %s" % dct
for k, v in dct.items():
if hasattr(v, '__iter__'):
self.data[k] = v
else:
self.data[k] = [v]
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()
class CSN(object):
"""CSN is Change Sequence Number
csn.ts is the timestamp (time_t - seconds)
csn.seq is the sequence number (max 65535)
csn.rid is the replica ID of the originating master
csn.subseq is not currently used"""
csnpat = r'(.{8})(.{4})(.{4})(.{4})'
csnre = re.compile(csnpat)
def __init__(self, csnstr):
match = CSN.csnre.match(csnstr)
self.ts = 0
self.seq = 0
self.rid = 0
self.subseq = 0
if match:
self.ts = int(match.group(1), 16)
self.seq = int(match.group(2), 16)
self.rid = int(match.group(3), 16)
self.subseq = int(match.group(4), 16)
elif csnstr:
self.ts = 0
self.seq = 0
self.rid = 0
self.subseq = 0
print csnstr, "is not a valid CSN"
def csndiff(self, oth):
return (oth.ts - self.ts, oth.seq - self.seq, oth.rid - self.rid, oth.subseq - self.subseq)
def __cmp__(self, oth):
if self is oth:
return 0
(tsdiff, seqdiff, riddiff, subseqdiff) = self.csndiff(oth)
diff = tsdiff or seqdiff or riddiff or subseqdiff
ret = 0
if diff > 0:
ret = 1
elif diff < 0:
ret = -1
return ret
def __eq__(self, oth):
return cmp(self, oth) == 0
def diff2str(self, oth):
retstr = ''
diff = oth.ts - self.ts
if diff > 0:
td = datetime.timedelta(seconds=diff)
retstr = "is behind by %s" % td
elif diff < 0:
td = datetime.timedelta(seconds=-diff)
retstr = "is ahead by %s" % td
else:
diff = oth.seq - self.seq
if diff:
retstr = "seq differs by %d" % diff
elif self.rid != oth.rid:
retstr = "rid %d not equal to rid %d" % (self.rid, oth.rid)
else:
retstr = "equal"
return retstr
def __repr__(self):
return time.strftime("%x %X", time.localtime(self.ts)) + " seq: " + str(self.seq) + " rid: " + str(self.rid)
def __str__(self):
return self.__repr__()
class RUV(object):
"""RUV is Replica Update Vector
ruv.gen is the generation CSN
ruv.rid[1] through ruv.rid[N] are dicts - the number (1-N) is the replica ID
ruv.rid[N][url] is the purl
ruv.rid[N][min] is the min csn
ruv.rid[N][max] is the max csn
ruv.rid[N][lastmod] is the last modified timestamp
example ruv attr:
nsds50ruv: {replicageneration} 3b0ebc7f000000010000
nsds50ruv: {replica 1 ldap://myhost:51010} 3b0ebc9f000000010000 3b0ebef7000000010000
nsruvReplicaLastModified: {replica 1 ldap://myhost:51010} 292398402093
if the tryrepl flag is true, if getting the ruv from the suffix fails, try getting
the ruv from the cn=replica entry
"""
genpat = r'\{replicageneration\}\s+(\w+)'
genre = re.compile(genpat)
ruvpat = r'\{replica\s+(\d+)\s+(.+?)\}\s*(\w*)\s*(\w*)'
ruvre = re.compile(ruvpat)
def __init__(self, ent):
# rid is a dict
# key is replica ID - val is dict of url, min csn, max csn
self.rid = {}
for item in ent.getValues('nsds50ruv'):
matchgen = RUV.genre.match(item)
matchruv = RUV.ruvre.match(item)
if matchgen:
self.gen = CSN(matchgen.group(1))
elif matchruv:
rid = int(matchruv.group(1))
self.rid[rid] = {'url': matchruv.group(2),
'min': CSN(matchruv.group(3)),
'max': CSN(matchruv.group(4))}
else:
print "unknown RUV element", item
for item in ent.getValues('nsruvReplicaLastModified'):
matchruv = RUV.ruvre.match(item)
if matchruv:
rid = int(matchruv.group(1))
self.rid[rid]['lastmod'] = int(matchruv.group(3), 16)
else:
print "unknown nsruvReplicaLastModified item", item
def __cmp__(self, oth):
if self is oth:
return 0
if not self:
return -1 # None is less than something
if not oth:
return 1 # something is greater than None
diff = cmp(self.gen, oth.gen)
if diff:
return diff
for rid in self.rid.keys():
for item in ('max', 'min'):
csn = self.rid[rid][item]
csnoth = oth.rid[rid][item]
diff = cmp(csn, csnoth)
if diff:
return diff
return 0
def __eq__(self, oth):
return cmp(self, oth) == 0
def getdiffs(self, oth):
"""Compare two ruvs and return the differences
returns a tuple - the first element is the
result of cmp() - the second element is a string"""
if self is oth:
return (0, "\tRUVs are the same")
if not self:
return (-1, "\tfirst RUV is empty")
if not oth:
return (1, "\tsecond RUV is empty")
diff = cmp(self.gen, oth.gen)
if diff:
return (diff, "\tgeneration [" + str(self.gen) + "] not equal to [" + str(oth.gen) + "]: likely not yet initialized")
retstr = ''
for rid in self.rid.keys():
for item in ('max', 'min'):
csn = self.rid[rid][item]
csnoth = oth.rid[rid][item]
csndiff = cmp(csn, csnoth)
if csndiff:
if len(retstr):
retstr += "\n"
retstr += "\trid %d %scsn %s\n\t[%s] vs [%s]" % (rid, item, csn.diff2str(csnoth),
csn, csnoth)
if not diff:
diff = csndiff
if not diff:
retstr = "\tup-to-date - RUVs are equal"
return (diff, retstr)
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[normalizeDN(dn)] = newentry
self.dnlist.append(newentry)
def get(self, dn):
ndn = 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(DN_CONFIG)
if cnconfig:
return cnconfig.getValue(attrname)
except IOError, err:
print "could not read dse config file", err
return None
def __initPart2(self):
"""Initialize the DSAdmin structure filling various fields, like:
- dbdir
- errlog
- confdir
"""
if self.binddn and len(self.binddn) and not hasattr(self, 'sroot'):
try:
ent = self.getEntry(
DN_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
if self.verbose:
print "instdir=", instdir
print ent
match = re.match(r'(.*)[\/]slapd-([^/]+)$', instdir)
if match:
self.sroot, self.inst = match.groups()
else:
self.sroot = self.inst = ''
ent = self.getEntry(
'cn=config,' + DN_LDBM,
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"
except ldap.LDAPError, e:
print "caught exception ", e
raise
def __localinit__(self):
uri = self.toLDAPURL()
SimpleLDAPObject.__init__(self, uri)
# see if binddn is a dn or a uid that we need to lookup
if self.binddn and not 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)
if not self.nobind:
needtls = False
while True:
try:
if needtls:
self.start_tls_s()
self.simple_bind_s(self.binddn, self.bindpw)
break
except ldap.CONFIDENTIALITY_REQUIRED:
needtls = True
self.__initPart2()
def __init__(self, host, port=389, binddn='', bindpw='', nobind=False, sslport=0, verbose=False): # default to anon bind
"""We just set our instance variables and wrap the methods.
The real work is done in the following methods, reused during
instance creation & co.
* __localinit__
* __initPart2
e.g. when using the start command, we just need to reconnect,
not create a new instance"""
self.__wrapmethods()
self.verbose = verbose
self.port = port
self.sslport = sslport
self.host = host
self.binddn = binddn
self.bindpw = bindpw
self.nobind = nobind
self.isLocal = isLocalHost(host)
#
# dict caching DS structure
#
self.suffixes = {}
self.agmt = {}
# the real init
self.__localinit__()
def __str__(self):
"""XXX and in SSL case?"""
return self.host + ":" + str(self.port)
def toLDAPURL(self):
"""Return the uri ldap[s]://host:[ssl]port."""
if self.sslport:
return "ldaps://%s:%d/" % (self.host, self.sslport)
else:
return "ldap://%s:%d/" % (self.host, self.port)
def getEntry(self, *args):
"""Wrapper around SimpleLDAPObject.search. It is common to just get one entry.
eg. getEntry(dn, scope, filter, attributes)
XXX This cannot return None
"""
res = self.search(*args)
restype, obj = self.result(res)
# TODO: why not test restype?
if not obj:
raise NoSuchEntryError("no such entry for %r" % [args])
elif isinstance(obj, Entry):
return obj
else: # assume list/tuple
assert obj[0] is not None, "None entry!" # TEST CODE
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=120):
instanceDir = self.sroot + "/slapd-" + self.inst
errLog = instanceDir + '/logs/errors'
if hasattr(self, 'errlog'):
errLog = self.errlog
done = False
started = True
lastLine = ""
cmd = cmd.lower()
fullCmd = instanceDir + "/" + cmd + "-slapd"
if cmd == 'start':
cmdPat = 'slapd started.'
else:
cmdPat = 'slapd stopped.'
if "USE_GDB" in os.environ or "USE_VALGRIND" in os.environ:
timeout = timeout * 3
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()
while not done and line:
lastLine = line
if verbose:
print line.strip()
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()
if line.find("PR_Bind") >= 0:
# server port conflicts with another one, just report and punt
print lastLine.strip()
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 startTask(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 False
elif verbose:
print entry
return True
def checkTask(self, entry, dowait=False, verbose=False):
'''check task status - task is complete when the nsTaskExitCode attr is set
return a 2 tuple (true/false,code) first is false if task is running, true if
done - if true, second is the exit code - if dowait is True, this function
will block until the task is complete'''
attrlist = ['nsTaskLog', 'nsTaskStatus', 'nsTaskExitCode',
'nsTaskCurrentItem', 'nsTaskTotalItems']
done = False
exitCode = 0
dn = entry.dn
while not done:
entry = self.getEntry(
dn, ldap.SCOPE_BASE, "(objectclass=*)", attrlist)
if verbose:
print entry
if entry.nsTaskExitCode:
exitCode = int(entry.nsTaskExitCode)
done = True
if dowait:
time.sleep(1)
else:
break
return (done, exitCode)
def startTaskAndWait(self, entry, verbose=False):
self.startTask(entry, verbose)
(done, exitCode) = self.checkTask(entry, True, verbose)
return exitCode
def importLDIF(self, ldiffile, 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', ldiffile)
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, ldiffile, rc)
else:
if verbose:
print "Import task %s for file %s completed successfully" % (
cn, ldiffile)
return rc
def exportLDIF(self, ldiffile, suffix, be=None, 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', ldiffile)
if be:
entry.setValues('nsInstance', be)
else:
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, ldiffile, rc)
else:
if verbose:
print "Export task %s for file %s completed successfully" % (
cn, ldiffile)
return rc
def createIndex(self, suffix, attr, verbose=False):
entries_backend = self.getBackendsForSuffix(suffix, ['cn'])
cn = "index%d" % time.time()
dn = "cn=%s,cn=index,cn=tasks,cn=config" % cn
entry = Entry(dn)
entry.update({
'objectclass': ['top', 'extensibleObject'],
'cn': cn,
'nsIndexAttribute': attr,
'nsInstance': entries_backend[0].cn
})
# assume 1 local backend
rc = self.startTaskAndWait(entry, verbose)
if rc:
if verbose:
print "Error: index task %s for file %s exited with %d" % (
cn, ldiffile, rc)
else:
if verbose:
print "Index task %s for file %s completed successfully" % (
cn, ldiffile)
return rc
def fixupMemberOf(self, suffix, filt=None, verbose=False):
cn = "fixupmemberof" + str(int(time.time()))
dn = "cn=%s,cn=memberOf task,cn=tasks,cn=config" % cn
entry = Entry(dn)
entry.setValues('objectclass', 'top', 'extensibleObject')
entry.setValues('cn', cn)
entry.setValues('basedn', suffix)
if filt:
entry.setValues('filter', filt)
rc = self.startTaskAndWait(entry, verbose)
if rc:
if verbose:
print "Error: fixupMemberOf task %s for basedn %s exited with %d" % (cn, suffix, rc)
else:
if verbose:
print "fixupMemberOf task %s for basedn %s completed successfully" % (cn, suffix)
return rc
def addLDIF(self, input_file, cont=False):
class LDIFAdder(ldif.LDIFParser):
def __init__(self, input_file, conn, cont=False,
ignored_attr_types=None, max_entries=0, process_url_schemes=None
):
myfile = input_file
if isinstance(input_file, basestring):
myfile = open(input_file, "r")
self.conn = conn
self.cont = cont
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):
if not dn:
dn = ''
newentry = Entry((dn, entry))
try:
self.conn.add_s(newentry)
except ldap.LDAPError, e:
if not self.cont:
raise e
print "Error: could not add entry %s: error %s" % (
dn, str(e))
adder = LDIFAdder(input_file, self, cont)
def getSuffixes(self):
ents = self.search_s(DN_MAPPING_TREE, ldap.SCOPE_ONELEVEL)
sufs = []
for ent in ents:
unquoted = None
quoted = None
for val in ent.getValues('cn'):
if val.find('"') < 0: # prefer the one that is not quoted
unquoted = val
else:
quoted = val
if unquoted: # preferred
sufs.append(unquoted)
elif quoted: # strip
sufs.append(quoted.strip('"'))
else:
raise Exception(
"Error: mapping tree entry " + ent.dn + " has no suffix")
return sufs
def setupBackend(self, suffix, binddn=None, bindpw=None, urls=None, attrvals=None, benamebase=None, verbose=False):
"""Setup a backend and return its dn. Blank on error
FIXME: avoid duplicate backends
"""
attrvals = attrvals or {}
dnbase = ""
# if benamebase is set, try creating without appending
if benamebase:
benum = 0
else:
benum = 1
# figure out what type of be based on args
if binddn and bindpw and urls: # its a chaining be
benamebase = benamebase or "chaindb"
dnbase = DN_CHAIN
else: # its a ldbm be
benamebase = benamebase or "localdb"
dnbase = DN_LDBM
print "benamebase: " + benamebase
nsuffix = normalizeDN(suffix)
done = False
while not done:
try:
# if benamebase is set, benum starts at 0
# and the first attempt tries to create the
# simple benamebase. On failure benum is
# incremented and the suffix is appended
# to the cn
if benum:
cn = benamebase + str(benum) # e.g. localdb1
else:
cn = benamebase
print "create backend with cn: %s" % cn
dn = "cn=" + cn + "," + dnbase
entry = Entry(dn)
entry.update({
'objectclass': ['top', 'extensibleObject', 'nsBackendInstance'],
'cn': cn,
'nsslapd-suffix': nsuffix
})
if binddn and bindpw and urls: # its a chaining be
entry.update({
'nsfarmserverurl': urls,
'nsmultiplexorbinddn': binddn,
'nsmultiplexorcredentials': bindpw
})
else: # set ldbm parameters, if any
pass
# $entry->add('nsslapd-cachesize' => '-1');