Debian Codegraph @

src/lib389/cli/dscontainer

raw
1 #!/usr/bin/python3
2
3 # --- BEGIN COPYRIGHT BLOCK ---
4 # Copyright (C) 2019 William Brown <[email protected]>
5 # All rights reserved.
6 #
7 # License: GPL (version 3 or any later version).
8 # See LICENSE for details.
9 # --- END COPYRIGHT BLOCK ---
10
11 # Why does this exist, and what does it do?
12 ###########################################
13 #
14 # This entry point exists because it's hard to make 389 really "stateless"
15 # in the way a container environment expects, and especially with systems
16 # like kubernetes with volume setup etc.
17 #
18 # This script will detect if an instance exists in the volume locations
19 # and if one does not (new, or ephemeral) we create a container-optimised
20 # instance of 389-ds.
21 #
22 # If an instance *does* exist, we will start it up, and let it run. Simple
23 # as that!
24 #
25
26 import grp
27 import pwd
28 import atexit
29 import os
30 import time
31 import signal
32 import sys
33 import subprocess
34 import argparse, argcomplete
35 from argparse import RawTextHelpFormatter
36
37 from lib389 import DirSrv, pid_exists, pid_from_file
38 from lib389.cli_base import setup_script_logger
39 from lib389.instance.setup import SetupDs
40 from lib389.instance.options import General2Base, Slapd2Base
41 from lib389.passwd import password_generate
42 from lib389.nss_ssl import NssSsl, CERT_NAME
43 from lib389.paths import Paths
44 from lib389.config import LDBMConfig
45 from lib389.utils import get_default_db_lib
46 from lib389._constants import (
47 DSRC_CONTAINER,
48 CONTAINER_TLS_SERVER_KEY,
49 CONTAINER_TLS_SERVER_CERT,
50 CONTAINER_TLS_SERVER_CADIR,
51 CONTAINER_TLS_PWDFILE
52 )
53
54 from lib389.idm.directorymanager import DirectoryManager
55
56 # We setup the logger in verbose mode to make sure debug info
57 # is always available!
58 log = setup_script_logger("container-init", True)
59
60 # PID FILE
61 PID_FILE = "/data/run/slapd-localhost.pid"
62
63
64 # Handle any dead child process signals we receive. Wait for them to terminate, or
65 # if they are not found, move on.
66 #
67 # We take *args and **kwargs here to handle the fact that this signal gets args, but
68 # we don't need or care about them.
69 def _sigchild_handler(*args, **kwargs):
70 # log.debug("Received SIGCHLD ...")
71 os.waitpid(-1, os.WNOHANG)
72
73
74 # Start the exit process.
75 def _sigterm_handler(*args, **kwargs):
76 exit()
77
78
79 def _gen_instance():
80 inst = DirSrv(verbose=True)
81 inst.local_simple_allocate("localhost")
82 inst.setup_ldapi()
83 return inst
84
85
86 def _begin_environment_config():
87 inst = _gen_instance()
88 inst.open()
89 # TODO: Should we reset cn=Directory Manager from env?
90 dm_pass = os.getenv("DS_DM_PASSWORD", None)
91 if dm_pass is not None:
92 log.debug("Setting Directory Manager Password ...")
93 dm = DirectoryManager(inst)
94 dm.change_password(dm_pass)
95 # TODO: Should we set replica id from env?
96 # TODO: Should we set replication agreements from env?
97 autotune_pct = os.getenv("DS_MEMORY_PERCENTAGE", None)
98 if autotune_pct is not None:
99 if get_default_db_lib() == "mdb":
100 log.warning("DS_MEMORY_PERCENTAGE is present, but setting entry cache is not supported for MDB")
101 else:
102 try:
103 autotune_pct = int(autotune_pct)
104 except:
105 log.warning("Invalid DS_MEMORY_PERCENTAGE - resetting to system default value")
106 autotune_pct = 0
107 log.debug("Setting LDBM Autotune Percentage to: %s", autotune_pct)
108 ldbmconfig = LDBMConfig(inst)
109 ldbmconfig.set("nsslapd-cache-autosize", str(autotune_pct))
110
111 # If the user imported TLS certs, ensure that the TLS listener is enabled.
112 if os.path.exists(CONTAINER_TLS_SERVER_KEY):
113 inst.config.set('nsslapd-security', 'on')
114
115 inst.close()
116
117
118 def _begin_setup_pem_tls():
119 # If we have the needed files, we can use them.
120 #
121 # We need at least:
122 # * 1 ca in the ca's folder
123 # * the server.key
124 # * the server.crt
125 #
126 # Optional future idea: we have many ca's in ca folder
127 log.info("Checking for PEM TLS files ...")
128 have_atleast_ca = False
129 have_server_key = os.path.exists(CONTAINER_TLS_SERVER_KEY)
130 have_server_cert = os.path.exists(CONTAINER_TLS_SERVER_CERT)
131 have_pwdfile = os.path.exists(CONTAINER_TLS_PWDFILE)
132 if os.path.exists(CONTAINER_TLS_SERVER_CADIR) and os.path.isdir(CONTAINER_TLS_SERVER_CADIR):
133 cas = [ca for ca in os.listdir(CONTAINER_TLS_SERVER_CADIR) if ca.endswith('.crt')]
134 log.info("Found -> %s" % cas)
135 have_atleast_ca = len(cas) > 0
136 log.info("Have %s -> %s" % (CONTAINER_TLS_SERVER_KEY, have_server_key))
137 log.info("Have %s -> %s" % (CONTAINER_TLS_SERVER_CERT, have_server_cert))
138 log.info("Have %s -> %s" % (CONTAINER_TLS_SERVER_CADIR, have_atleast_ca))
139 log.info("Have %s -> %s" % (CONTAINER_TLS_PWDFILE, have_pwdfile))
140
141 if not (have_atleast_ca and have_server_key and have_server_cert and have_pwdfile):
142 log.info("Unable to configure TLS from PEM, missing a required file.")
143 return
144 log.info("TLS PEM requirements met - configuring NSSDB ...")
145 inst = _gen_instance()
146 tls = NssSsl(dirsrv=inst)
147 # First, remove the existing server-cert.
148 tls.del_cert(CERT_NAME)
149 # Import the ca's
150 for ca_path in [os.path.join(CONTAINER_TLS_SERVER_CADIR, ca) for ca in cas]:
151 log.info("Enrolling -> %s" % ca_path)
152 tls.add_cert(nickname=ca_path, input_file=ca_path, ca=True)
153 tls.edit_cert_trust(ca_path, "C,,")
154 # Import the new server-cert
155 tls.add_server_key_and_cert(CONTAINER_TLS_SERVER_KEY, CONTAINER_TLS_SERVER_CERT)
156 # Done!
157 log.info("TLS PEM configuration complete.")
158
159
160 def _begin_check_reindex():
161 if os.getenv('DS_REINDEX', None) is not None:
162 log.info("Reindexing database. This may take a while ...")
163 inst = _gen_instance()
164 inst.db2index()
165
166
167 def begin_magic():
168 log.info("The 389 Directory Server Container Bootstrap")
169 # Leave this comment here: UofA let me take this code with me provided
170 # I gave attribution. -- wibrown
171 log.info("Inspired by works of: ITS, The University of Adelaide")
172
173 # Setup our ds_paths ...
174 # Notice we pre-populate the instance id, which allows the start up to work correctly
175 # to find the correct configuration path?
176 #
177 # We wouldn't need this *except* for testing containers that build to /opt/dirsrv
178 paths = Paths(serverid='localhost')
179 log.info("389 Directory Server Version: %s" % paths.version)
180
181 # Make sure that /data/config, /data/ssca and /data/config exist, because
182 # k8s may not template them out.
183 #
184 # Big note for those at home: This means you need your dockerfile to run
185 # something like:
186 # EXPOSE 3389 3636
187 # RUN mkdir -p /data/config && \
188 # mkdir -p /data/ssca && \
189 # ln -s /data/config /etc/dirsrv/slapd-localhost && \
190 # ln -s /data/ssca /etc/dirsrv/ssca && \
191 # # Temporal volumes for each instance
192 # VOLUME /data
193 #
194 # When I said this was a container tool, I really really meant it!
195 #
196 # Q: "William, why do you symlink in these locations?"
197 # A: Docker lets you mount in volumes. The *simpler* we can make this for a user
198 # the absolute beter. This means any downstream container can simply use:
199 # docker run -v 389_data:/data ... 389-ds:latest
200 # If we were to use the "normal paths", we would require MORE volume mounts, with
201 # cryptic paths and complexity. Not friendly at all.
202 #
203 # Q: "William, why not change the paths in the config?"
204 # A: Despite the fact that ds alleges support for moving content and paths, this
205 # is not possible for the /etc/dirsrv content unless at COMPILE time. Additionally
206 # some parts of the code base make assumptions. Instead of fighting legacy, we want
207 # results now! So we mask our limitations with symlinks.
208 #
209 for d in [
210 '/data/config',
211 '/data/ssca',
212 '/data/db',
213 '/data/bak',
214 '/data/ldif',
215 '/data/run',
216 '/data/run/lock',
217 '/data/run/dbhome',
218 '/data/logs'
219 ]:
220 if not os.path.exists(d):
221 # Yolo, container security is from ns isolation, not unix perms. When we drop
222 # privs we'll need this to support future writes.
223 os.makedirs(d, mode=0o777)
224
225 basedn = '# basedn = dc=example,dc=com'
226 suffix = os.getenv("SUFFIX_NAME")
227 if suffix is not None:
228 log.warning("SUFFIX_NAME is deprecated, please use DS_SUFFIX_NAME instead")
229 else:
230 suffix = os.getenv("DS_SUFFIX_NAME")
231 if suffix is not None:
232 basedn = f'basedn = {suffix}'
233
234 have_server_key = os.path.exists(CONTAINER_TLS_SERVER_KEY)
235
236 # Do we have correct permissions to our volumes? With the power of thoughts and
237 # prayers, we continue blindy and ... well hope.
238
239 # Do we have an instance? We can only tell by the DSRC_CONTAINER marker file
240 if not os.path.exists(DSRC_CONTAINER):
241 # Nope? Make one ...
242 log.info("Initialising 389-ds-container due to empty volume ...")
243 rpw = password_generate()
244
245 g2b = General2Base(log)
246 s2b = Slapd2Base(log)
247 # Fill in container defaults?
248
249 g2b.set('strict_host_checking', False)
250 g2b.set('selinux', False)
251 g2b.set('systemd', False)
252 g2b.set('start', False)
253
254 s2b.set('instance_name', 'localhost')
255
256 # We use our user/group from the current user, begause in envs like kubernetes
257 # it WILL NOT be dirsrv
258 user_name = pwd.getpwuid(os.getuid())[0]
259 group_name = grp.getgrgid(os.getgid())[0]
260
261 s2b.set('user', user_name)
262 s2b.set('group', group_name)
263 s2b.set('root_password', rpw)
264 s2b.set('port', 3389)
265 s2b.set('secure_port', 3636)
266
267 s2b.set('local_state_dir', '/data')
268 s2b.set('inst_dir', '/data')
269 s2b.set('db_dir', '/data/db')
270 # 51008, ds changed dbhome for bdb to /dev/shm, however in docker this
271 # defaults to 64M and DS requires at least 130M. It may not be possible to
272 # Ask people to change this in their deployments, and in the interest of
273 # simplicity, we just put this into a /data/run directory instead to make
274 # containers as painless as possible. If people want it to be a ram disk
275 # they can easily use something like:
276 # docker run --tmpfs /data/run/dbhome:rw
277 s2b.set('db_home_dir', '/data/run/dbhome')
278 # Why is this bak? Some dsctl commands use INST_DIR/bak, not "backup_dir"
279 # due to some legacy handling of paths in lib389's population of instances.
280 s2b.set('backup_dir', '/data/bak')
281 s2b.set('ldif_dir', '/data/ldif')
282 s2b.set('run_dir', '/data/run')
283 s2b.set('lock_dir', '/data/run/lock')
284 s2b.set('ldapi', '/data/run/slapd-localhost.socket')
285
286 s2b.set('log_dir', '/data/logs')
287 s2b.set('access_log', '/data/logs/access')
288 s2b.set('error_log', '/data/logs/error')
289 s2b.set('audit_log', '/data/logs/audit')
290
291 # User intends to import a TLS KEY/Cert, don't setup self-signed.
292 if have_server_key:
293 s2b.set('self_sign_cert', False)
294
295 backends = []
296 if suffix is not None:
297 backends = [
298 {
299 'name': 'userroot',
300 'suffix': suffix,
301 'create_suffix_entry': True,
302 }
303 ]
304
305 # Now collect and submit for creation.
306 sds = SetupDs(verbose=True, dryrun=False, log=log, containerised=True)
307
308 if not sds.create_from_args(g2b.collect(), s2b.collect(), backends):
309 log.error("Failed to create instance")
310 sys.exit(1)
311
312 log.info("IMPORTANT: Set cn=Directory Manager password to \"%s\"" % rpw)
313
314 # Create the marker to say we exist. This is also a good writable permissions
315 # test for the volume.
316 config_file = """
317 [localhost]
318 # Note that '/' is replaced to '%%2f' for ldapi url format.
319 # So this is pointing to /data/run/slapd-localhost.socket
320 uri = ldapi://%%2fdata%%2frun%%2fslapd-localhost.socket
321 binddn = cn=Directory Manager
322 # Set your basedn here
323 {0}
324 """.format(basedn)
325 with open(DSRC_CONTAINER, 'w') as f:
326 f.write(config_file)
327 os.chmod(DSRC_CONTAINER, 0o755)
328
329 # Setup TLS from PEM files as required.
330 _begin_setup_pem_tls()
331
332 # If we have been requested to re-index, do so now ...
333 _begin_check_reindex()
334
335 loglevel = os.getenv("ERRORLOG_LEVEL")
336 if loglevel is not None:
337 log.warning("ERRORLOG_LEVEL is deprecated, please use DS_ERRORLOG_LEVEL instead")
338 else:
339 loglevel = os.getenv("DS_ERRORLOG_LEVEL")
340 if loglevel is not None:
341 try:
342 n_loglevel = str(int(loglevel) | 266354688)
343 log.info(f"Set log level to {loglevel} | DEFAULT")
344 loglevel = n_loglevel
345 except:
346 log.error("Invalid ERRORLOG_LEVEL value, setting default ...")
347 loglevel = "266354688"
348 else:
349 # See /ldap/servers/slapd/slap.h SLAPD_DEFAULT_ERRORLOG_LEVEL
350 loglevel = "266354688"
351
352 # Yep! Run it ...
353 # Now unlike a normal lib389 start, we use subprocess and don't fork!
354 # TODO: Should we pass in a loglevel from env?
355 log.info("Starting 389-ds-container ...")
356
357 # We can't use the instance "start" because we need the pid handler so we can do
358 # a wait/block on it. That's why we do the Popen here direct.
359 global ds_proc
360 ds_proc = subprocess.Popen([
361 "%s/ns-slapd" % paths.sbin_dir,
362 "-D", paths.config_dir,
363 "-i", PID_FILE,
364 "-d", loglevel,
365 ], stdout=None, stderr=None, env=os.environ.copy())
366
367 # Setup the process and shutdown handler in an init-esque fashion.
368 def kill_ds():
369 if ds_proc is None:
370 pass
371 else:
372 try:
373 ds_proc.terminate()
374 log.info("STOPPING: Sent SIGTERM to ns-slapd ...")
375 except:
376 # It's already gone ...
377 pass
378 log.info("STOPPING: Shutting down 389-ds-container ...")
379 # To make sure we really do shutdown, we actually re-block on the proc
380 # again here to be sure it's done.
381 ds_proc.wait()
382 log.info("STOPPED: Shut down 389-ds-container")
383
384 atexit.register(kill_ds)
385
386 # Wait on the health check to show we are ready for ldapi.
387 healthy = False
388 startup_timeout = os.getenv("DS_STARTUP_TIMEOUT", 60)
389 max_failure_count = int(int(startup_timeout) / 3)
390 for i in range(0, max_failure_count):
391 if ds_proc is None:
392 log.warning("ns-slapd pid has disappeared ...")
393 break
394 # Is this the final check before we reach the timeout?
395 # If yes, then we'll log the exception too
396 final_check = True if i == max_failure_count - 1 else False
397 (check_again, healthy) = begin_healthcheck(ds_proc, final_check)
398 if check_again is False:
399 break
400 time.sleep(3)
401 # Check again then ....
402 if not healthy:
403 log.error(f"Timeout of {startup_timeout} seconds was reached")
404 log.error("Couldn't connect via LDAPI socket")
405 log.error("389-ds-container failed to start")
406 sys.exit(1)
407
408 # Now via ldapi, set some values.
409 log.info("Applying environment configuration (if present) ...")
410 _begin_environment_config()
411
412 log.info("389-ds-container started.")
413
414 # Now block until we get shutdown! If we are signaled to exit, this
415 # will trigger the atexit handler from above.
416 try:
417 ds_proc.wait()
418 except KeyboardInterrupt:
419 pass
420 # THE LETTER OF THE DAY IS C AND THE NUMBER IS 10
421
422
423 def begin_healthcheck(ds_proc, log_exception):
424 # We skip the pid check if ds_proc is none because that means it's coming from the
425 # container healthcheck.
426 if ds_proc is not None and ds_proc.poll() is not None:
427 # Ruh-Roh
428 log.warning("ns-slapd pid has completed, you should check the error log ...")
429 return (False, False)
430 # Now do an ldapi check, make sure we are dm.
431 try:
432 inst = _gen_instance()
433 inst.open()
434 if "dn: cn=Directory Manager" == inst.whoami_s():
435 return (False, True)
436 else:
437 log.error("The instance may be misconfigured, unable to cn=Directory Manager autobind.")
438 return (False, False)
439 except:
440 err_msg = "Instance LDAPI not functional (yet?)"
441 if log_exception:
442 log.exception(err_msg)
443 else:
444 log.debug(err_msg)
445 pass
446 return (True, False)
447
448
449 def stop():
450 stop_timeout = os.getenv("DS_STOP_TIMEOUT", 60)
451 count = int(stop_timeout)
452 pid = pid_from_file(PID_FILE)
453 os.kill(pid, signal.SIGTERM)
454 while pid_exists(pid) and count > 0:
455 time.sleep(1)
456 count -= 1
457 if pid_exists(pid):
458 os.kill(pid, signal.SIGKILL)
459
460
461 if __name__ == '__main__':
462 # Before all else, we are INIT so setup sigchild
463 signal.signal(signal.SIGCHLD, _sigchild_handler)
464 # Setup catching for term and int
465 signal.signal(signal.SIGTERM, _sigterm_handler)
466 signal.signal(signal.SIGINT, _sigterm_handler)
467 signal.signal(signal.SIGHUP, _sigterm_handler)
468
469 parser = argparse.ArgumentParser(allow_abbrev=True, description="""
470 dscontainer - this is a container entry point that will run a stateless
471 instance of 389-ds. You should not use this unless you are developing or
472 building a container image of some nature. As a result, this tool is
473 *extremely* opinionated, and you will need your container build file to
474 have certain settings to work correctly.
475
476 \tEXPOSE 3389 3636
477 \tRUN mkdir -p /data/config && \\
478 \t mkdir -p /data/ssca && \\
479 \t ln -s /data/config /etc/dirsrv/slapd-localhost && \\
480 \t ln -s /data/ssca /etc/dirsrv/ssca && \\
481 \tVOLUME /data
482
483 This is an example of the minimal required configuration. The 389
484 instance will be created with ports 3389 and 3636. *All* of the data will
485 be installed under /data. This means that to "reset" an instance you only
486 need to remove the content of /data. In the case there is no instance
487 one will be created.
488
489 No backends or suffixes are created by default, as we can not assume your
490 domain component. The cn=Directory Manager password is randomised on
491 install, and can be viewed in the setup log, or can be accessed via ldapi
492 - the ldapi socket is placed into /data so you can access it from the
493 container host.
494 """, formatter_class=RawTextHelpFormatter)
495 parser.add_argument('-r', '--runit',
496 help="Actually run the instance! You understand what that means ...",
497 action='store_true', default=False, dest='runit')
498 parser.add_argument('-s', '--stop',
499 help="Stop the instance",
500 action='store_true', default=False, dest='stop')
501 parser.add_argument('-H', '--healthcheck',
502 help="Start a healthcheck inside of the container for an instance. You should understand what this means ...",
503 action='store_true', default=False, dest='healthcheck')
504
505 argcomplete.autocomplete(parser)
506
507 args = parser.parse_args()
508
509 if args.runit:
510 begin_magic()
511 elif args.stop:
512 stop()
513 elif args.healthcheck:
514 if begin_healthcheck(None, False) == (False, True):
515 sys.exit(0)
516 else:
517 sys.exit(1)
518
519