-
Notifications
You must be signed in to change notification settings - Fork 80
/
__init__.py
3471 lines (2986 loc) · 131 KB
/
__init__.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
# --- BEGIN COPYRIGHT BLOCK ---
# Copyright (C) 2019 Red Hat, Inc.
# Copyright (C) 2019 William Brown <william@blackhats.net.au>
# All rights reserved.
#
# License: GPL (version 3 or any later version).
# See LICENSE for details.
# --- END COPYRIGHT BLOCK ---
"""The lib389 module.
IMPORTANT: Ternary operator syntax is unsupported on RHEL5
x if cond else y #don't!
The lib389 functionalities are split in various classes
defined in brookers.py
TODO: reorganize method parameters according to SimpleLDAPObject
naming: filterstr, attrlist
"""
import sys
import os
import stat
import pwd
import grp
import os.path
import socket
import ldif
import re
import ldap
import ldapurl
import time
import shutil
from datetime import datetime
import logging
import glob
import tarfile
import subprocess
from collections.abc import Callable
import signal
import errno
import uuid
import json
from shutil import copy2
import six
# Deprecation
import warnings
import inspect
from ldap.ldapobject import SimpleLDAPObject
# file in this package
from lib389._constants import *
from lib389.properties import *
from lib389._entry import Entry
from lib389._ldifconn import LDIFConn
from lib389.tools import DirSrvTools
from lib389.utils import (
ds_is_older,
isLocalHost,
normalizeDN,
escapeDNValue,
formatInfData,
ensure_bytes,
ensure_str,
ensure_list_str,
format_cmd_list,
selinux_present,
selinux_label_port)
from lib389.paths import Paths
from lib389.nss_ssl import NssSsl
from lib389.tasks import BackupTask, RestoreTask
from lib389.dseldif import DSEldif
# mixin
# from lib389.tools import DirSrvTools
from lib389.exceptions import *
MAJOR, MINOR, _, _, _ = sys.version_info
if MAJOR >= 3 or (MAJOR == 2 and MINOR >= 7):
from ldap.controls.simple import GetEffectiveRightsControl
from lib389._controls import DereferenceControl
RE_DBMONATTR = re.compile(r'^([a-zA-Z]+)-([1-9][0-9]*)$')
RE_DBMONATTRSUN = re.compile(r'^([a-zA-Z]+)-([a-zA-Z]+)$')
# This controls pyldap debug levels
TRACE_LEVEL = 0
DEBUGGING = os.getenv('DEBUGGING', default=False)
# My logger
logger = logging.getLogger(__name__)
# Initiate the paths object here. Should this be part of the DirSrv class
# for submodules?
def wrapper(f, name):
"""
Wrapper of all superclass methods using lib389.Entry.
@param f - DirSrv method inherited from SimpleLDAPObject
@param name - method to call
This seems to need to be an unbound method, that's why it's outside of
DirSrv. Perhaps there is some way to do this with the new classmethod
or staticmethod of 2.4.
We replace every call to a method in SimpleLDAPObject (the superclass
of DirSrv) with a call to inner. The f argument to wrapper is the bound
method of DirSrv (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, **kwargs):
if name in [
'add_s',
'bind_s',
'delete_s',
'modify_s',
'modrdn_s',
'rename_s',
'sasl_interactive_bind_s',
'search_s',
'search_ext_s',
'simple_bind_s',
'unbind_s',
'getEntry',
] and not ('escapehatch' in kwargs and kwargs['escapehatch'] == 'i am sure'):
c_stack = inspect.stack()
frame = c_stack[1]
warnings.warn(DeprecationWarning("Use of raw ldap function %s. This will be removed in a future release. "
"Found in: %s:%s" % (name, frame.filename, frame.lineno)))
# Later, we will add a sleep here to make it even more painful.
# Finally, it will raise an exception.
elif 'escapehatch' in kwargs:
kwargs.pop('escapehatch')
if name == 'result':
objtype, data = f(*args, **kwargs)
# 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, **kwargs)
else:
return f(*args, **kwargs)
return inner
def pid_exists(pid):
if pid <= 0:
return False
try:
os.kill(pid, 0)
except OSError as err:
if err.errno == errno.ESRCH:
return False
elif err.errno == errno.EPERM:
return True
else:
raise
# Tell the OS to reap this please ...
try:
os.waitpid(pid, os.WNOHANG)
except ChildProcessError:
pass
return True
def pid_from_file(pidfile):
pid = None
try:
with open(pidfile, 'rb') as f:
for line in f.readlines():
try:
pid = int(line.strip())
break
except ValueError:
continue
except IOError:
pass
return pid
def _ds_shutil_copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,
ignore_dangling_symlinks=False):
"""Recursively copy a directory tree.
This is taken from /usr/lib64/python3.5/shutil.py, but removes the
copystat function at the end. Why? Because in a container without
privileges, we don't have access to set xattr. But copystat attempts to
set the xattr when we are root, which causes the copy to fail. Remove it!
"""
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if os.path.islink(srcname):
linkto = os.readlink(srcname)
if symlinks:
# We can't just leave it to `copy_function` because legacy
# code with a custom `copy_function` may rely on copytree
# doing the right thing.
os.symlink(linkto, dstname)
copystat(srcname, dstname, follow_symlinks=not symlinks)
else:
# ignore dangling symlink if the flag is on
if not os.path.exists(linkto) and ignore_dangling_symlinks:
continue
# otherwise let the copy occurs. copy2 will raise an error
if os.path.isdir(srcname):
_ds_shutil_copytree(srcname, dstname, symlinks, ignore,
copy_function)
else:
copy_function(srcname, dstname)
elif os.path.isdir(srcname):
_ds_shutil_copytree(srcname, dstname, symlinks, ignore, copy_function)
else:
# Will raise a SpecialFileError for unsupported file types
copy_function(srcname, dstname)
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error as err:
errors.extend(err.args[0])
except OSError as why:
errors.append((srcname, dstname, str(why)))
return dst
class DirSrv(SimpleLDAPObject, object):
def __initPart2(self):
"""Initialize the DirSrv structure filling various fields, like:
self.errlog -> nsslapd-errorlog
self.accesslog -> nsslapd-accesslog
self.auditlog -> nsslapd-auditlog
self.confdir -> nsslapd-certdir
self.inst -> equivalent to self.serverid
self.sroot/self.inst -> nsslapd-instancedir
self.dbdir -> dirname(nsslapd-directory)
self.bakdir -> nsslapd-bakdir
self.ldifdir -> nsslapd-ldifdir
@param - self
@return - None
@raise ldap.LDAPError - if failure during initialization
"""
self.errlog = self.ds_paths.error_log
self.accesslog = self.ds_paths.access_log
self.auditlog = self.ds_paths.audit_log
self.confdir = self.ds_paths.config_dir
self.schemadir = self.ds_paths.schema_dir
self.bakdir = self.ds_paths.backup_dir
self.ldifdir = self.ds_paths.ldif_dir
self.instdir = self.ds_paths.inst_dir
self.dbdir = self.ds_paths.db_dir
self.changelogdir = os.path.join(os.path.dirname(self.dbdir), DEFAULT_CHANGELOG_DB)
def rebind(self):
"""Reconnect to the DS
@raise ldap.CONFIDENTIALITY_REQUIRED - missing TLS:
"""
if hasattr(ldap, 'PYLDAP_VERSION') and MAJOR >= 3:
super(DirSrv, self).__init__(uri, bytes_mode=False, trace_level=TRACE_LEVEL)
else:
super(DirSrv, self).__init__(uri, trace_level=TRACE_LEVEL)
# self.start_tls_s()
self.simple_bind_s(ensure_str(self.binddn), self.bindpw, escapehatch='i am sure')
def __add_brookers__(self):
from lib389.config import Config
from lib389.aci import Aci
from lib389.config import RSA
from lib389.config import Encryption
from lib389.dirsrv_log import DirsrvAccessLog, DirsrvErrorLog
from lib389.ldclt import Ldclt
from lib389.mappingTree import MappingTrees
from lib389.mappingTree import MappingTreeLegacy as MappingTree
from lib389.backend import Backends
from lib389.backend import BackendLegacy as Backend
from lib389.suffix import Suffix
from lib389.replica import ReplicaLegacy as Replica
from lib389.replica import Replicas
from lib389.agreement import AgreementLegacy as Agreement
from lib389.schema import SchemaLegacy as Schema
from lib389.plugins import Plugins
from lib389.tasks import Tasks
from lib389.index import IndexLegacy as Index
from lib389.monitor import Monitor, MonitorLDBM
from lib389.rootdse import RootDSE
from lib389.saslmap import SaslMapping, SaslMappings
from lib389.pwpolicy import PwPolicyManager
# Need updating
self.agreement = Agreement(self)
self.replica = Replica(self)
self.backend = Backend(self)
self.config = Config(self)
self.index = Index(self)
self.mappingtree = MappingTree(self)
self.suffix = Suffix(self)
self.schema = Schema(self)
self.plugins = Plugins(self)
self.tasks = Tasks(self)
self.saslmap = SaslMapping(self)
self.pwpolicy = PwPolicyManager(self)
# Do we have a certdb path?
# if MAJOR < 3:
self.monitor = Monitor(self)
self.monitorldbm = MonitorLDBM(self)
self.rootdse = RootDSE(self)
self.backends = Backends(self)
self.mappingtrees = MappingTrees(self)
self.replicas = Replicas(self)
self.aci = Aci(self)
self.rsa = RSA(self)
self.encryption = Encryption(self)
self.ds_access_log = DirsrvAccessLog(self)
self.ds_error_log = DirsrvErrorLog(self)
self.ldclt = Ldclt(self)
self.saslmaps = SaslMappings(self)
def __init__(self, verbose=False, external_log=None):
"""
This method does various initialization of DirSrv object:
parameters:
- 'state' to DIRSRV_STATE_INIT
- 'verbose' flag for debug purpose
- 'log' so that the use the module defined logger
wrap the methods.
- from SimpleLDAPObject
- from agreement, backends, suffix...
It just create a DirSrv object. To use it the user will likely do
the following additional steps:
- allocate
- create
- open
"""
self.state = DIRSRV_STATE_INIT
self.uuid = str(uuid.uuid4())
self.verbose = verbose
self.serverid = None
# If we have an external logger, use it!
self.log = logger
if external_log is None:
if self.verbose:
self.log.setLevel(logging.DEBUG)
else:
self.log.setLevel(logging.INFO)
else:
self.log = external_log
self.confdir = None
self.ds_paths = Paths(instance=self)
# Set the default systemd status. This MAY be overidden in the setup utils
# as required.
self.systemd = self.ds_paths.with_systemd
# Reset the args (py.test reuses the args_instance for each test case)
# We allocate a "default" prefix here which allows an un-allocate or
# un-instantiated DirSrv
# instance to be able to do an an instance discovery. For example:
# ds = lib389.DirSrv()
# ds.list(all=True)
# self.ds_paths.prefix = args_instance[SER_DEPLOYED_DIR]
self.__wrapmethods()
self.__add_brookers__()
def __str__(self):
"""XXX and in SSL case?"""
return self.host + ":" + str(self.port)
def local_simple_allocate(self, serverid, ldapuri=None, binddn='cn=Directory Manager', password=None):
"""Allocate an instance and perform a simple bind. This is a local instance, so
you can perform tasks like db2ldif etc. Note that you can use password=None and
skip .open(), and still perform local tasks.
:param serverid: The instance name to manipulate
:type serverid: str
:param ldapuri: The instance uri to connect to.
:type ldapuri: str
:param binddn: The dn to bind as.
:type binddn: str
:param password: The password for the dn to bind as.
:type password: str
"""
if self.state != DIRSRV_STATE_INIT and self.state != DIRSRV_STATE_ALLOCATED:
raise ValueError("invalid state for calling allocate: %s" % self.state)
# The lack of this value basically rules it out in most cases
self.isLocal = True
self.ds_paths = Paths(serverid, instance=self)
self.serverid = serverid
# Do we have ldapi settings?
self.ldapi_enabled = None
self.ldapi_socket = None
self.ldapuri = ldapuri
# We must also alloc host and ports for some manipulation tasks
self.host = socket.gethostname()
dse_ldif = DSEldif(self)
port = dse_ldif.get(DN_CONFIG, "nsslapd-port", single=True)
sslport = dse_ldif.get(DN_CONFIG, "nsslapd-secureport", single=True)
self.port = int(port) if port is not None else None
self.sslport = int(sslport) if sslport is not None else None
self.binddn = binddn
self.bindpw = password
self.state = DIRSRV_STATE_ALLOCATED
self.log.debug("Allocate local instance %s with %s", self.__class__, self.ldapuri)
def setup_ldapi(self):
self.ldapi_enabled = "on"
self.ldapi_socket = self.ds_paths.ldapi
self.ldapi_autobind = "on"
def remote_simple_allocate(self, ldapuri, binddn='cn=Directory Manager', password=None):
"""Allocate an instance, and perform a simple bind. This instance is remote, so
local tasks will not operate.
:param ldapuri: The instance uri to connect to.
:type ldapuri: str
:param binddn: The dn to bind as.
:type binddn: str
:param password: The password for the dn to bind as.
:type password: str
"""
if self.state != DIRSRV_STATE_INIT and self.state != DIRSRV_STATE_ALLOCATED:
raise ValueError("invalid state for calling allocate: %s" % self.state)
self.log.debug('SER_SERVERID_PROP not provided, assuming non-local instance')
# The lack of this value basically rules it out in most cases
self.isLocal = False
self.ds_paths = Paths(instance=self)
# Do we have ldapi settings?
# Do we really need .strip() on this?
self.ldapi_enabled = None
self.ldapi_socket = None
self.ldapuri = ldapuri
self.binddn = binddn
self.bindpw = password
self.state = DIRSRV_STATE_ALLOCATED
self.log.debug("Allocate %s with %s", self.__class__, self.ldapuri)
# Should there be an extra boolean to this function to determine to use
# ldapi or not? Or does the settings presence indicate intent?
def allocate(self, args):
'''
Initialize a DirSrv object according to the provided args.
The final state -> DIRSRV_STATE_ALLOCATED
@param args - dictionary that contains the DirSrv properties
properties are
SER_SERVERID_PROP: used for offline op
(create/delete/backup/start/stop..) -> slapd-<serverid>
SER_HOST: hostname [LOCALHOST]
SER_PORT: normal ldap port [DEFAULT_PORT]
SER_SECURE_PORT: secure ldap port
SER_ROOT_DN: root DN [DN_DM]
SER_ROOT_PW: password of root DN [PW_DM]
SER_USER_ID: user id of the create instance [DEFAULT_USER]
SER_GROUP_ID: group id of the create instance [SER_USER_ID]
SER_DEPLOYED_DIR: directory where 389-ds is deployed
SER_BACKUP_INST_DIR: directory where instances will be
backed up
@return None
@raise ValueError - if missing mandatory properties or invalid
state of DirSrv
'''
if self.state != DIRSRV_STATE_INIT and \
self.state != DIRSRV_STATE_ALLOCATED:
raise ValueError("invalid state for calling allocate: %s" %
self.state)
self.isLocal = False
if SER_SERVERID_PROP not in args:
self.log.debug('SER_SERVERID_PROP not provided, assuming non-local instance')
# The lack of this value basically rules it out in most cases
self.ds_paths = Paths(instance=self)
else:
self.ds_paths = Paths(serverid=args[SER_SERVERID_PROP], instance=self)
# Settings from args of server attributes
self.serverid = args.get(SER_SERVERID_PROP, None)
# Probably local?
self.isLocal = True
# Do we have ldapi settings?
# Do we really need .strip() on this?
self.ldapi_enabled = args.get(SER_LDAPI_ENABLED, 'off')
self.ldapi_socket = args.get(SER_LDAPI_SOCKET, None)
self.ldapuri = args.get(SER_LDAP_URL, None)
self.log.debug("Allocate %s with %s", self.__class__, self.ldapuri)
# Still needed in setup, even if ldapuri over writes.
self.host = args.get(SER_HOST, socket.gethostname())
self.port = args.get(SER_PORT, DEFAULT_PORT)
self.sslport = args.get(SER_SECURE_PORT)
self.inst_scripts = args.get(SER_INST_SCRIPTS_ENABLED, None)
# Or do we have tcp / ip settings?
if self.ldapi_enabled == 'on' and self.ldapi_socket is not None:
self.ldapi_autobind = args.get(SER_LDAPI_AUTOBIND, 'off')
self.isLocal = True
self.log.debug("Allocate %s with %s", self.__class__, self.ldapi_socket)
# Settings from args of server attributes
self.strict_hostname = args.get(SER_STRICT_HOSTNAME_CHECKING, False)
if self.strict_hostname is True:
if self.host == LOCALHOST:
DirSrvTools.testLocalhost()
else:
# Make sure our name is in hosts
DirSrvTools.searchHostsFile(self.host, None)
self.isLocal = isLocalHost(self.host)
self.log.debug("Allocate %s with %s:%s", self.__class__, self.host, (self.sslport or self.port))
self.binddn = args.get(SER_ROOT_DN, DN_DM)
self.bindpw = args.get(SER_ROOT_PW, PW_DM)
self.creation_suffix = args.get(SER_CREATION_SUFFIX, None)
# These settings are only needed on a local connection.
if self.isLocal:
self.userid = args.get(SER_USER_ID)
if not self.userid:
if os.getuid() == 0:
# as root run as default user
self.userid = DEFAULT_USER
else:
self.userid = pwd.getpwuid(os.getuid())[0]
self.groupid = args.get(SER_GROUP_ID, self.userid)
self.backupdir = args.get(SER_BACKUP_INST_DIR, DEFAULT_BACKUPDIR)
# This will be externally populated in topologies.
self.realm = None
# additional settings
self.suffixes = {}
self.agmt = {}
self.state = DIRSRV_STATE_ALLOCATED
self.log.debug("Allocate %s with %s:%s",
self.__class__,
self.host,
(self.sslport or self.port))
def clone(self, args_instance={}):
"""
Open a new connection to our LDAP server
*IMPORTANT*
This is different to re-opening on the same dirsrv, as quirks in pyldap
mean that ldap.set_option doesn't take effect! You need to use this
to allow all of the start TLS options to work!
"""
server = DirSrv(verbose=self.verbose)
args_instance[SER_LDAP_URL] = self.ldapuri
args_instance[SER_HOST] = self.host
args_instance[SER_PORT] = self.port
args_instance[SER_LDAP_URL] = self.ldapuri
args_instance[SER_SECURE_PORT] = self.sslport
args_instance[SER_SERVERID_PROP] = self.serverid
args_standalone = args_instance.copy()
server.allocate(args_standalone)
return server
def list(self, all=False, serverid=None):
"""
Returns a list dictionary. For a created instance that is on the
local file system (e.g. <prefix>/etc/dirsrv/slapd-*/dse.ldif).
A dictionary is created with the following properties:
CONF_SERVER_DIR
CONF_SERVERBIN_DIR
CONF_CONFIG_DIR
CONF_INST_DIR
CONF_RUN_DIR
CONF_DS_ROOT
CONF_PRODUCT_NAME
If all=True it builds a list of dictionaries for all created
instances. Else (default), the list will only contain the
dictionary of the calling instance
@param all - True or False . default is [False]
@param instance - The name of the instance to retrieve or None for
the current instance
@return - list of dictionaries, each of them containing instance
properities
@raise IOError - if the file containing the properties is not
foundable or readable
"""
### This inner function WILL BE REMOVED soon.
def _parse_configfile(filename=None, serverid=None):
'''
This method read 'filename' and build a dictionary with
CONF_* properties
'''
if not filename:
raise IOError('filename is mandatory')
if not os.path.isfile(filename) or \
not os.access(filename, os.R_OK):
raise IOError('invalid file name or rights: %s' % filename)
prop = {}
prop[CONF_SERVER_ID] = serverid
prop[SER_SERVERID_PROP] = serverid
inst_paths = Paths(serverid)
# WARNING: This is not correct, but is a stop gap until: https://pagure.io/389-ds-base/issue/50207
# Once that's done, this will "just work". Saying this, the whole prop dictionary
# concept is fundamentally broken, and we should be using ds_paths anyway.
prop[CONF_SERVER_DIR] = inst_paths.lib_dir
prop[CONF_SERVERBIN_DIR] = inst_paths.sbin_dir
prop[CONF_CONFIG_DIR] = inst_paths.config_dir
prop[CONF_INST_DIR] = inst_paths.inst_dir
prop[CONF_RUN_DIR] = inst_paths.run_dir
prop[CONF_DS_ROOT] = ''
prop[CONF_PRODUCT_NAME] = 'slapd'
ldifconn = LDIFConn(filename)
configentry = ldifconn.get(DN_CONFIG)
for key in args_dse_keys:
prop[key] = configentry.getValue(args_dse_keys[key])
# SER_HOST (host) nsslapd-localhost
# SER_PORT (port) nsslapd-port
# SER_SECURE_PORT (sslport) nsslapd-secureport
# SER_ROOT_DN (binddn) nsslapd-rootdn
# SER_ROOT_PW (bindpw) We can't do this
# SER_CREATION_SUFFIX (creation_suffix)
# nsslapd-defaultnamingcontext
# SER_USER_ID (userid) nsslapd-localuser
# SER_SERVERID_PROP (serverid) Already have this
# SER_GROUP_ID (groupid)
# SER_DEPLOYED_DIR (prefix) Already provided to for
# discovery
# SER_BACKUP_INST_DIR (backupdir) nsslapd-bakdir
# We need to convert these two to int
# because other routines get confused if we don't
for intkey in [SER_PORT, SER_SECURE_PORT]:
if intkey in prop and prop[intkey] is not None:
prop[intkey] = int(prop[intkey])
return prop
### end _parse_configfile
# Retrieves all instances under '<prefix>/etc/dirsrv'
# Don't need a default value now since it's set in init.
if serverid is None and hasattr(self, 'serverid'):
serverid = self.serverid
elif serverid is not None:
serverid = serverid.replace('slapd-', '', 1)
if self.serverid is None:
# Need to set the Paths in case it does exist
self.ds_paths = Paths(serverid)
# list of the found instances
instances = []
# now prepare the list of instances properties
if not all:
# Don't use self.ds_paths here, because it has no server id : this
# causes the config_dir to have a formatting issue.
#
# As dse.ldif is one of the only fixed locations in the server, this is
# okay to use this without parsing of dse.ldif to add the other paths
# required: yet.
inst_paths = Paths(serverid)
dse_ldif = os.path.join(inst_paths.config_dir, 'dse.ldif')
# easy case we just look for the current instance
if os.path.exists(dse_ldif):
# It's real
# Now just populate that instance dict (soon to be changed ...)
instances.append(_parse_configfile(dse_ldif, serverid))
else:
# it's not=
self.log.debug("list instance not found in {}: {}\n".format(dse_ldif, serverid))
else:
# For each dir that starts with slapd-*
inst_path = self.ds_paths.sysconf_dir + "/dirsrv"
potential_inst = [
os.path.join(inst_path, f)
for f in os.listdir(inst_path)
if f.startswith('slapd-')
]
# check it has dse.ldif
for pi in potential_inst:
pi_dse_ldif = os.path.join(pi, 'dse.ldif')
# Takes /etc/dirsrv/slapd-instance -> slapd-instance -> instance
pi_name = pi.split('/')[-1].split('slapd-')[-1]
# parse + append
if os.path.exists(pi_dse_ldif):
instances.append(_parse_configfile(pi_dse_ldif, pi_name))
return instances
def _createDirsrv(self):
"""Create a new instance of directory server
@param self - containing the set properties
SER_HOST (host)
SER_PORT (port)
SER_SECURE_PORT (sslport)
SER_ROOT_DN (binddn)
SER_ROOT_PW (bindpw)
SER_CREATION_SUFFIX (creation_suffix)
SER_USER_ID (userid)
SER_SERVERID_PROP (serverid)
SER_GROUP_ID (groupid)
SER_DEPLOYED_DIR (prefix)
SER_BACKUP_INST_DIR (backupdir)
@return None
@raise None
}
"""
DirSrvTools.lib389User(user=DEFAULT_USER)
prog = os.path.join(self.ds_paths.sbin_dir, CMD_PATH_SETUP_DS)
if not os.path.isfile(prog):
self.log.error("Can't find file: %r, removing extension", prog)
prog = prog[:-3]
# Create and extract a service keytab
args = {SER_HOST: self.host,
SER_PORT: self.port,
SER_SECURE_PORT: self.sslport,
SER_ROOT_DN: self.binddn,
SER_ROOT_PW: self.bindpw,
SER_CREATION_SUFFIX: self.creation_suffix,
SER_USER_ID: self.userid,
SER_SERVERID_PROP: self.serverid,
SER_GROUP_ID: self.groupid,
SER_BACKUP_INST_DIR: self.backupdir,
SER_STRICT_HOSTNAME_CHECKING: self.strict_hostname}
if self.inst_scripts is not None:
args[SER_INST_SCRIPTS_ENABLED] = self.inst_scripts
content = formatInfData(args)
result = DirSrvTools.runInfProg(prog, content, self.verbose, prefix=self.ds_paths.prefix)
if result != 0:
raise Exception('Failed to run setup-ds.pl')
def _createPythonDirsrv(self, version):
"""
Create a new dirsrv instance based on the new python installer, rather
than setup-ds.pl
version represents the config default and sample entry version to use.
"""
from lib389.instance.setup import SetupDs
from lib389.instance.options import General2Base, Slapd2Base
# Import the new setup ds library.
sds = SetupDs(verbose=self.verbose, dryrun=False, log=self.log)
# Configure the options.
general_options = General2Base(self.log)
general_options.set('strict_host_checking', False)
general_options.verify()
general = general_options.collect()
slapd_options = Slapd2Base(self.log)
slapd_options.set('instance_name', self.serverid)
slapd_options.set('port', self.port)
slapd_options.set('secure_port', self.sslport)
slapd_options.set('root_password', self.bindpw)
slapd_options.set('root_dn', self.binddn)
#We disable TLS during setup, we use a function in tests to enable instead.
slapd_options.set('self_sign_cert', False)
slapd_options.set('defaults', version)
slapd_options.verify()
slapd = slapd_options.collect()
# In order to work by "default" for tests, we need to create a backend.
backends = []
if self.creation_suffix is not None:
userroot = {
'cn': 'userRoot',
'nsslapd-suffix': self.creation_suffix,
BACKEND_SAMPLE_ENTRIES: version,
}
backends = [userroot,]
# Go!
self.log.debug("DEBUG: creating with parameters:")
self.log.debug(general)
self.log.debug(slapd)
self.log.debug(backends)
sds.create_from_args(general, slapd, backends, None)
def create(self, pyinstall=False, version=INSTALL_LATEST_CONFIG):
"""
Creates an instance with the parameters sets in dirsrv
The state change from DIRSRV_STATE_ALLOCATED ->
DIRSRV_STATE_OFFLINE
@param - self
@return - None
@raise ValueError - if 'serverid' is missing or if it exist an
instance with the same 'serverid'
"""
# check that DirSrv was in DIRSRV_STATE_ALLOCATED state
self.log.debug("Server is in state %s", self.state)
if self.state != DIRSRV_STATE_ALLOCATED:
raise ValueError("invalid state for calling create: %s" %
self.state)
if self.exists():
raise ValueError("Error it already exists the instance (%s)" %
self.list()[0][CONF_INST_DIR])
if not self.serverid:
raise ValueError("SER_SERVERID_PROP is missing, " +
"it is required to create an instance")
# Time to create the instance and retrieve the effective sroot
if (not self.ds_paths.perl_enabled or pyinstall):
self._createPythonDirsrv(version)
else:
self._createDirsrv()
# Because of how this works, we force ldap:// only for now.
# A real install will have ldaps, and won't go via this path.
self.use_ldap_uri()
# Retrieve sroot from the sys/priv config file
assert(self.exists())
self.sroot = self.list()[0][CONF_SERVER_DIR]
# Now the instance is created but DirSrv is not yet connected to it
self.state = DIRSRV_STATE_OFFLINE
def _deleteDirsrv(self):
'''
Deletes the instance with the parameters sets in dirsrv
The state changes -> DIRSRV_STATE_ALLOCATED
@param self
@return None
@raise None
'''
# Grab all the instances now, before we potentially remove the last one
insts = self.list(all=True)
if self.state == DIRSRV_STATE_ONLINE:
self.close()
if not self.exists():
raise ValueError("Error can not find instance %s[%s:%d]" %
(self.serverid, self.host, self.port))
# Now time to remove the instance
prog = os.path.join(self.ds_paths.sbin_dir, CMD_PATH_REMOVE_DS)
if (not self.ds_paths.prefix or self.ds_paths.prefix == '/') and os.geteuid() != 0:
raise ValueError("Error: without prefix deployment it is required to be root user")
cmd = "%s -i %s%s" % (prog, DEFAULT_INST_HEAD, self.serverid)
self.log.debug("running: %s ", cmd)
try:
os.system(cmd)
except:
self.log.exception("error executing %r", cmd)
# If this was the last instance being deleted, remove the DEFAULT_USER
# if lib389 created the default user
if os.getuid() == 0:
# Only the root user could of added the entry
if len(insts) == 1:
# No more instances (this was the last one)
if pwd.getpwnam(DEFAULT_USER).pw_gecos == DEFAULT_USER_COMMENT:
# We created this user, so we will delete it
cmd = ['/usr/sbin/userdel', DEFAULT_USER]
try:
subprocess.call(cmd)
except subprocess.CalledProcessError as e:
self.log.exception(
'Failed to delete default user ',
'(%s): error %s' % (DEFAULT_USER,
e.output))
self.state = DIRSRV_STATE_ALLOCATED
def delete(self, pyinstall=False):
# Time to create the instance and retrieve the effective sroot
if (not self.ds_paths.perl_enabled or pyinstall):
from lib389.instance.remove import remove_ds_instance
remove_ds_instance(self)
else:
self._deleteDirsrv()
# Now, we are still an allocated ds object so we can be re-installed
self.state = DIRSRV_STATE_ALLOCATED
def open(self, uri=None, saslmethod=None, sasltoken=None, certdir=None, starttls=False, connOnly=False, reqcert=ldap.OPT_X_TLS_HARD,
usercert=None, userkey=None):
'''
It opens a ldap bound connection to dirsrv so that online
administrative tasks are possible. It binds with the binddn
property, then it initializes various fields from DirSrv
(via __initPart2)
The state changes -> DIRSRV_STATE_ONLINE
@param self
@param saslmethod - None, or GSSAPI
@param sasltoken - The ldap.sasl token type to bind with.
@param certdir - Certificate directory for TLS
@return None
@raise LDAPError
'''
# Force our state offline to prevent paths from trying to search
# cn=config while we startup.
self.state = DIRSRV_STATE_OFFLINE
if not uri:
uri = self.toLDAPURL()
self.log.debug('open(): Connecting to uri %s', uri)
if hasattr(ldap, 'PYLDAP_VERSION') and MAJOR >= 3:
super(DirSrv, self).__init__(uri, bytes_mode=False, trace_level=TRACE_LEVEL)
else:
super(DirSrv, self).__init__(uri, trace_level=TRACE_LEVEL)
if certdir is None and self.isLocal:
certdir = self.get_cert_dir()
self.log.debug("Using dirsrv ca certificate %s", certdir)