Note: The default ITS GitLab runner is a shared resource and is subject to slowdowns during heavy usage.
You can run your own GitLab runner that is dedicated just to your group if you need to avoid processing delays.

create_group.py 8.71 KB
Newer Older
1
#!/usr/bin/env python3
2
3
4
5
6
7
import argparse
import re
import yaml
import logging
import logging.handlers

8
from .core import arg_prompt
9
10
11
12
13
14
15
16
17
from subprocess import check_output as cmd
from subprocess import CalledProcessError


class DiscussionGroup:

    def __init__(self, args, config):
        self.__dict__.update(args)
        self.config = config
Rob Carleski's avatar
Rob Carleski committed
18
        self.logger = logging.getLogger(__name__)
19
20

        # Create a sane email address automatically if one isn't specified.
Rob Carleski's avatar
Rob Carleski committed
21
        if not self.email:
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
            self.email = '{}@{}'.format(
                self.name.replace(' ', ''),
                self.config['discussions']['domain']
            )
        elif '@' not in self.email:
            self.email += '@{}'.format(self.config['discussions']['domain'])
        self.email = re.sub(r"[\s'\"]", '', self.email.strip())

    def create_group(self):
        # Create Group
        try:
            cmd([
                self.config['discussions']['gam_command'],
                'create',
                'group',
                self.email,
Rob Carleski's avatar
Rob Carleski committed
38
                'name',
39
                self.name,
Rob Carleski's avatar
Rob Carleski committed
40
                'description',
41
42
43
                self.description
            ])
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
44
            self.logger.error(e.output, extra={'entity': self.email})
Rob Carleski's avatar
Rob Carleski committed
45
            exit(2)
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

    def add_group_owners(self):
        if hasattr(self, 'owners'):
            for owner in self.owners:
                try:
                    cmd([
                        self.config['discussions']['gam_command'],
                        'update',
                        'group',
                        self.email,
                        'add',
                        'owner',
                        'user',
                        owner
                    ])
                except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
62
                    self.logger.error(
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
                        e.output,
                        extra={'entity': self.email}
                    )
                    continue
        elif hasattr(self, 'owners_file'):
            try:
                cmd([
                    self.config['discussions']['gam_command'],
                    'update',
                    'group',
                    self.email,
                    'add',
                    'owner',
                    'file',
                    self.owners_file
                ])
            except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
80
                self.logger.error(
81
82
83
84
                    e.output,
                    extra={'entity': self.email}
                )
        else:
Rob Carleski's avatar
Rob Carleski committed
85
            self.logger.error(
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
                'No owners assigned to group',
                extra={'entity': self.email}
            )

    def add_group_members(self):
        if hasattr(self, 'members'):
            for member in self.members:
                try:
                    cmd([
                        self.config['discussions']['gam_command'],
                        'update',
                        'group',
                        self.email,
                        'add',
                        'member',
                        'user',
                        member
                    ])
                except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
105
                    self.logger.warning(
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
                        e.output,
                        extra={'entity': self.email}
                    )
                    continue
        elif hasattr(self, 'members_file'):
            try:
                cmd([
                    self.config['discussions']['gam_command'],
                    'update',
                    'group',
                    self.email,
                    'add',
                    'member',
                    'file',
                    self.members_file
                ])
            except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
123
                self.logger.warning(
124
125
126
127
                    e.output,
                    extra={'entity': self.email}
                )
            except IOError as e:
Rob Carleski's avatar
Rob Carleski committed
128
                self.logger.error(
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
                    e,
                    extra={'entity': self.email}
                )

    def print_canned_text(self):
        print('================================================')
        print('''
Hello!

The new discussion group you requested with the name '{}' has been created
and is ready for use. The email address for this discussion group is '{}'.
Information on managing this group and its members can be found at the
following url:

http://documentation.its.umich.edu/node/578

If you have additional questions or concerns about using this group, please
contact 4HELP at 734.764.4357 or 4HELP@umich.edu.
'''.format(self.name, self.email.lower()))


def main():

    helptext = '''examples:
    discussions-create-group -n collabchat -o jpage@umich.edu bdenver@gmail.com
    discussions-create-group --name collabchat --owners_file /tmp/owners.txt
    '''

    parser = argparse.ArgumentParser(
        description='Creates a new Google discussions group.',
        epilog=helptext,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        '--name',
        '-n',
        help='The name to use for the discussion group.',
    )
    parser.add_argument(
        '--email',
        '-e',
        help='The email address to use for the discussion group.',
    )
172
    owners = parser.add_mutually_exclusive_group()
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
    owners.add_argument(
        '--owners',
        '-o',
        help='The full email address(es) of group owners.',
        nargs='+'
    )
    owners.add_argument(
        '--owners_file',
        '-O',
        help='The location of a file containing a list of group owners.'
    )
    members = parser.add_mutually_exclusive_group()
    members.add_argument(
        '--members',
        '-m',
        help='The full email address(es) of group members.',
        nargs='+',
        default=[]
    )
    members.add_argument(
        '--members_file',
        '-M',
        help='The location of a file containing a list of group members.'
    )
    parser.add_argument(
        '--description',
        '-d',
        help='A description of the group.',
        default=''
    )
    parser.add_argument(
        '--config',
        '-c',
        help='The CAK config file to use.',
        default='/etc/collab-admin-kit.yml'
    )
    args = parser.parse_args()

211
212
213
214
215
216
217
218
219
220
    # Argument prompt fallback
    if not args.name:
        args.name = arg_prompt(
            'Group display name'
        )
        args.email = arg_prompt(
            '(optional) Local part to be used for the group email address',
            default=''
        )
        args.owners = arg_prompt(
Rob Carleski's avatar
Rob Carleski committed
221
            '(option 1) Full email addresses of owners, separated by commas',
222
            default=''
Rob Carleski's avatar
Rob Carleski committed
223
224
225
226
227
228
        ).split(',')
        print(args.owners)
        if not args.owners[0]:
            args.owners_file = arg_prompt(
                '(option 2) Full file path to a list of owners'
            )
229
        args.members = arg_prompt(
Rob Carleski's avatar
Rob Carleski committed
230
            '(option 1) Full email addresses of members, separated by commas',
231
            default=''
Rob Carleski's avatar
Rob Carleski committed
232
233
234
235
236
        ).split(',')
        if not args.members[0]:
            args.members_file = arg_prompt(
                '(option 2) The full file path to a list of members'
            )
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
        args.description = arg_prompt(
            '(optional) Description to assign to the group',
            default=''
        )

    # Argument sanity check
    _required = [
        'name',
        ('owners', 'owners_file'),
        ('members', 'members_file')
    ]
    for r in _required:
        try:
            if isinstance(r, str):
                assert getattr(args, r)
            if isinstance(r, tuple):
                assert getattr(args, r[0]) or getattr(args, r[1])
        except AssertionError:
            print('Missing required argument {}'.format(r))

257
258
259
260
261
    # Open the CAK Config
    with open(args.config) as stream:
        config = yaml.load(stream, Loader=yaml.BaseLoader)

    # Get the root logger and set the debug level
Rob Carleski's avatar
Rob Carleski committed
262
    logger = logging.getLogger(__name__)
263
264
265
266
267
268
269
270
271
272
273
274
275
    logger.setLevel(logging.DEBUG)

    # Create a syslog handler, set format, and associate.
    sh = logging.handlers.SysLogHandler(
        address='/dev/log',
        facility=config['general']['log_facility']
    )
    formatter = logging.Formatter(config['general']['log_format'])
    sh.setFormatter(formatter)
    logger.addHandler(sh)

    # Create a console handler, set format, and associate.
    ch = logging.StreamHandler()
276
277
278
279
    formatter = logging.Formatter(
        config['general']['console_format'],
        config['general']['date_format']
    )
280
281
282
    ch.setFormatter(formatter)
    logger.addHandler(ch)

283
    group = DiscussionGroup(vars(args), config)
284
285
286
287
288
289
290
291
    group.create_group()
    group.add_group_owners()
    group.add_group_members()
    group.print_canned_text()


if __name__ == '__main__':
    main()