create_resource.py 7.16 KB
Newer Older
1
2
3
4
5
6
7
8
#!/usr/bin/env python
import argparse
import logging
import logging.handlers
import re
import string
import yaml

9
from .core import arg_prompt
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
from subprocess import check_output as cmd
from subprocess import CalledProcessError
from time import sleep


class Resource:

    def __init__(self, args, config):
        self.__dict__.update(args)
        self.config = config
        self.logger = logging.getLogger(__name__)
        self.resource_id = ''
        _allowed = string.ascii_letters + string.digits
        for char in self.name:
            if char in _allowed:
                self.resource_id += char.lower()

    def create_resource(self):
        try:
            cmd([
                self.config['google']['gam_command'],
                'create',
                'resource',
                self.resource_id,
                self.name,
                'description',
                self.description,
                'type',
                self.resource_type
            ])
        except CalledProcessError:
            self.logger.error(
                'Failed to create resource.',
                extra={'entity': self.name}
            )
            exit(2)

47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
        for n in range(5):
            try:
                resource_info = cmd([
                    self.config['google']['gam_command'],
                    'info',
                    'resource',
                    self.resource_id
                ])
                self.email = re.findall(b'Email: (.+)', resource_info)[0]
                break
            except CalledProcessError:
                self.logger.error(
                    'Unable to fetch resource. Retrying.',
                    extra={'entity': self.name}
                )
                sleep(5)
        else:
64
            self.logger.error(
65
                'Permenant failure fetching resource. Exiting.',
66
67
68
69
70
71
72
73
74
75
                extra={'entity': self.name}
            )
            exit(2)

    def add_resource_owners(self):
        for owner in self.owners:
            try:
                cmd([
                    self.config['google']['gam_command'],
                    'calendar',
Rob Carleski's avatar
Rob Carleski committed
76
                    self.email.decode('utf-8'),
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
                    'add',
                    'owner',
                    owner
                ])
            except CalledProcessError:
                self.logger.warning(
                    'Failed to add {} as calendar owner'.format(owner),
                    extra={'entity': self.name}
                )
                continue

    def strip_global_access(self):
        try:
            cmd([
                self.config['google']['gam_command'],
                'calendar',
Rob Carleski's avatar
Rob Carleski committed
93
                self.email.decode('utf-8'),
94
95
96
97
98
99
100
                'delete',
                'user',
                'domain'
            ])
            cmd([
                self.config['google']['gam_command'],
                'calendar',
Rob Carleski's avatar
Rob Carleski committed
101
                self.email.decode('utf-8'),
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
                'delete',
                'user',
                'default'
            ])
        except CalledProcessError as e:
            self.logger.warning(
                'Unable to remove domain-wide access to resource: {}'.format(
                    e.output
                ),
                extra={'entity': self.name}
            )

    def generate_canned_text(self):
        canned_text = '''
Hello,

Your requested resource calendar has been created. As the requester of
the resource, you and your fellow owners should now see it listed in
your own Google calendar.

Information about this new resource is as follows:

Calendar Name: {}
Calendar Type: {}
Calendar Description: {}
Calendar Owners: {}
Calendar ID: {}

If you have any questions about how to utilize this calendar, please
consult the documentation found at the following link:

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

If any of the above information is incorrect, please feel free to reply
to this message and your incident will be automatically reopened.'''.format(
            self.name,
            self.resource_type,
            self.description,
            ','.join(self.owners),
Rob Carleski's avatar
Rob Carleski committed
141
            self.email.decode('utf-8')
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
            )

        print(
            '============================================',
            canned_text
        )


def main():

    helptext = '''examples:
    google-create-resource -n AL1-B1-2510 -o kmoss aaliyah
    google-create-resource --name AL1-B1-2510 --owners kmoss aaliyah
        --type 'Private Office'
    '''

    parser = argparse.ArgumentParser(
        description='Creates a new resource in GSuite',
        epilog=helptext,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        '--name',
        '-n',
        help='The name to assign to the resource.',
    )
    parser.add_argument(
        '--owners',
        '-o',
        help='Users to give management access to.',
        nargs='+',
    )
    parser.add_argument(
        '--resource_type',
        '-t',
177
178
        help='The resource type.',
        default=''
179
180
181
182
    )
    parser.add_argument(
        '--description',
        '-d',
183
184
        help='A description of the resource.',
        default=''
185
186
187
188
189
190
191
192
193
    )
    parser.add_argument(
        '--config',
        '-c',
        help='The CAK config to use.',
        default='/etc/collab-admin-kit.yml'
    )
    args = parser.parse_args()

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
    # Argument prompt fallback
    if not args.name:
        args.name = arg_prompt(
            'Name to assign to the resource'
        )
        args.owners = arg_prompt(
            '(optional) Resource owner uniqnames, separated by spaces',
            default=''
        ).split(' ')
        args.resource_type = arg_prompt(
            '(optional) Resource type',
            default=''
        )
        args.description = arg_prompt(
            '(optional) Resource description',
            default=''
        )

    # Argument sanity check
    _required = ['name']
    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))

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    # 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
    logger = logging.getLogger(__name__)
    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()
242
243
244
245
    formatter = logging.Formatter(
        config['general']['console_format'],
        config['general']['date_format']
    )
246
247
248
    ch.setFormatter(formatter)
    logger.addHandler(ch)

249
    resource = Resource(vars(args), config)
250
251
252
253
254
255
256
257
    resource.create_resource()
    resource.add_resource_owners()
    resource.strip_global_access()
    resource.generate_canned_text()


if __name__ == '__main__':
    main()