Debian Codegraph @

src/lib389/cli/dsidm

raw
1 #!/usr/bin/python3
2
3 # --- BEGIN COPYRIGHT BLOCK ---
4 # Copyright (C) 2016, William Brown <william at blackhats.net.au>
5 # Copyright (C) 2024 Red Hat, Inc.
6 # All rights reserved.
7 #
8 # License: GPL (version 3 or any later version).
9 # See LICENSE for details.
10 # --- END COPYRIGHT BLOCK ---
11 #
12 # PYTHON_ARGCOMPLETE_OK
13
14 import json
15 import sys
16 import signal
17 import ldap
18 import argparse
19 import argcomplete
20 from lib389.utils import get_instance_list, instance_choices
21 from lib389._constants import DSRC_HOME
22 from lib389.cli_idm import _get_basedn_arg
23 from lib389.cli_idm import account as cli_account
24 from lib389.cli_idm import initialise as cli_init
25 from lib389.cli_idm import organizationalunit as cli_ou
26 from lib389.cli_idm import group as cli_group
27 from lib389.cli_idm import posixgroup as cli_posixgroup
28 from lib389.cli_idm import uniquegroup as cli_uniquegroup
29 from lib389.cli_idm import user as cli_user
30 from lib389.cli_idm import client_config as cli_client_config
31 from lib389.cli_idm import role as cli_role
32 from lib389.cli_idm import service as cli_service
33 from lib389.cli_base import connect_instance, disconnect_instance, setup_script_logger
34 from lib389.cli_base.dsrc import dsrc_to_ldap, dsrc_arg_concat
35 from lib389.cli_base import format_error_to_dict, format_pretty_error
36 from lib389.cli_base import parent_argparser
37
38 # Pre-pass to resolve --user-type before the main parser is built. This lets
39 # `dsidm inst user create` surface only the MUST-attribute flags relevant to
40 # the selected user type. The side parser knows ONLY --user-type, has no
41 # positionals, and uses parse_known_args so everything else passes through
42 # untouched to the real parser below.
43 _pre_user_type = argparse.ArgumentParser(add_help=False)
44 _pre_user_type.add_argument('--user-type', dest='user_type',
45 choices=sorted(cli_user.USER_TYPE_CHOICES),
46 default=cli_user.DEFAULT_USER_TYPE)
47 _pre_args, _ = _pre_user_type.parse_known_args(sys.argv[1:])
48
49 parser = argparse.ArgumentParser(allow_abbrev=True, parents=[parent_argparser])
50 # First, add the LDAP options
51 parser.add_argument('instance',
52 help="The name of the instance or its LDAP URL, such as ldap://server.example.com:389",
53 ).completer = instance_choices
54 parser.add_argument('-b', '--basedn',
55 help="Base DN (root naming context) of the instance to manage",
56 default=None
57 )
58 parser.add_argument('-D', '--binddn',
59 help="The account to bind as for executing operations",
60 default=None
61 )
62 parser.add_argument('-w', '--bindpw',
63 help="Password for the bind DN",
64 default=None
65 )
66 parser.add_argument('-W', '--prompt',
67 action='store_true', default=False,
68 help="Prompt for password of the bind DN"
69 )
70 parser.add_argument('-y', '--pwdfile',
71 help="Specifies a file containing the password of the bind DN",
72 default=None
73 )
74 parser.add_argument('-Z', '--starttls',
75 help="Connect with StartTLS",
76 default=False, action='store_true'
77 )
78 subparsers = parser.add_subparsers(help="resources to act upon")
79 # Call all the other cli modules to register their bits
80 cli_account.create_parser(subparsers)
81 cli_group.create_parser(subparsers)
82 cli_init.create_parser(subparsers)
83 cli_ou.create_parser(subparsers)
84 cli_posixgroup.create_parser(subparsers)
85 cli_user.create_parser(subparsers, user_type=_pre_args.user_type)
86 cli_client_config.create_parser(subparsers)
87 cli_role.create_parser(subparsers)
88 cli_service.create_parser(subparsers)
89 cli_uniquegroup.create_parser(subparsers)
90
91 argcomplete.autocomplete(parser)
92
93
94 # handle a control-c gracefully
95 def signal_handler(signal, frame):
96 print('\n\nExiting...')
97 sys.exit(0)
98
99
100 if __name__ == '__main__':
101
102 defbase = ldap.get_option(ldap.OPT_DEFBASE)
103 args = parser.parse_args()
104
105 log = setup_script_logger('dsidm', args.verbose)
106
107 log.debug("The 389 Directory Server Identity Manager")
108 # Leave this comment here: UofA let me take this code with me provided
109 # I gave attribution. -- wibrown
110 log.debug("Inspired by works of: ITS, The University of Adelaide")
111
112 # Now that we have our args, see how they relate with our instance.
113 dsrc_inst = dsrc_to_ldap(DSRC_HOME, args.instance, log.getChild('dsrc'))
114
115 # Now combine this with our arguments
116
117 dsrc_inst = dsrc_arg_concat(args, dsrc_inst)
118
119 log.debug("Called with: %s", args)
120 log.debug("Instance details: %s" % dsrc_inst)
121
122 # Assert we have a resources to work on.
123 if not hasattr(args, 'func'):
124 errmsg = "No action provided, here is some --help."
125 if args.json:
126 sys.stderr.write('{"desc": "%s"}\n' % errmsg)
127 else:
128 log.error(errmsg)
129 parser.print_help()
130 sys.exit(1)
131
132 if not args.verbose:
133 signal.signal(signal.SIGINT, signal_handler)
134
135 ldapurl = args.instance
136
137 # Connect
138 inst = None
139 result = False
140 try:
141 inst = connect_instance(dsrc_inst=dsrc_inst, verbose=args.verbose, args=args)
142 basedn = _get_basedn_arg(inst, args, dsrc_inst['basedn'], log, msg="Enter basedn")
143 if basedn is None:
144 errmsg = "Must provide a basedn!"
145 if args.json:
146 sys.stderr.write('{"desc": "%s"}\n' % errmsg)
147 else:
148 log.error(errmsg)
149 sys.exit(1)
150 result = args.func(inst, basedn, log, args)
151 if args.verbose:
152 log.info("Command successful.")
153 except Exception as e:
154 log.debug(e, exc_info=True)
155 msg = format_error_to_dict(e)
156 if args.json:
157 sys.stderr.write(f"{json.dumps(msg, indent=4)}\n")
158 else:
159 if not args.verbose:
160 msg = format_pretty_error(msg)
161 log.error("Error: %s" % " - ".join(str(val) for val in msg.values()))
162 result = False
163
164 disconnect_instance(inst)
165
166 if result is False:
167 sys.exit(1)