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.

fitbit.py 4.61 KB
Newer Older
1
#!/usr/bin/env python3
2
3
4
5
6
import argparse
import yaml
import logging
import logging.handlers

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


class Account():

    def __init__(self, args, config):
        self.__dict__.update(args)
        self.config = config
Rob Carleski's avatar
Rob Carleski committed
17
        self.logger = logging.getLogger(__name__)
18
19
20
21
22
23
24
25
26
27
28
29
30
        self.localpart = self.account.split('@')[0]

        # Create a formatted list, starting at 001.
        self.count = ("{0:03}".format(i) for i in range(1, self.total+1))

        # Verify that the subject user exists.
        try:
            cmd([
                config['google']['gam_command'],
                'whatis',
                self.account
            ])
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
31
            self.logger.error(e.output, extra={'entity': self.account})
32
33
34
            exit(2)

    def create_labels_and_filters(self):
Rob Carleski's avatar
Rob Carleski committed
35
36
37
        for i in self.count:
            if self.prefix:
                label = '{}-{}'.format(self.prefix, i)
38
            else:
Rob Carleski's avatar
Rob Carleski committed
39
                label = i
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

            # Generate the full alias (e.x. studymailbox+prefix-001)
            alias = '{}+{}@{}'.format(
                self.localpart,
                label,
                self.config['google']['domain']
            )

            try:
                cmd([
                    self.config['google']['gam_command'],
                    'user',
                    self.account,
                    'label',
                    label
                ])
                cmd([
                    self.config['google']['gam_command'],
                    'user',
                    self.account,
                    'filter',
                    'to',
                    alias,
                    'label',
                    label
                ])
            except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
67
                self.logger.error(e.output, extra={'entity': self.account})
68
69
70
71
72
73
74
75
76
77
78


def main():

    helptext = '''examples:
    google-build-fitbitstudy -a awesomestudy -t 20 -p study1
    google-build-fitbitstudy --account awesomestudy --toal 20 --prefix study1
    '''

    # Kick up an argument parser and assign values into the env object.
    parser = argparse.ArgumentParser(
Rob Carleski's avatar
Rob Carleski committed
79
        description='Creates labels and filters in a given Google account',
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
        epilog=helptext,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        '--account',
        '-a',
        help='The target account.',
    )
    parser.add_argument(
        '--total',
        '-t',
        help='The total number of aliases to create.',
        default=50,
        type=int
    )
    parser.add_argument(
        '--prefix',
        '-p',
        help='A prefix to append to aliases.'
    )
    parser.add_argument(
        '--config',
        '-c',
        help='The CAK config to use',
        default='/etc/collab-admin-kit.yml'
    )
    args = parser.parse_args()

108
109
110
111
112
113
114
115
116
    # Argument prompt fallback
    if not args.account:
        args.account = arg_prompt(
            'Target existing shared account'
        )
        args.total = arg_prompt(
            'Number of alias labels to create. [50]',
            default=50
        )
Rob Carleski's avatar
Rob Carleski committed
117
        args.total = int(args.total)
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
        args.prefix = arg_prompt(
            '(optional) Prefix to assign to labels',
            default=None
        )

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

134
135
136
137
138
    # 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
139
    logger = logging.getLogger(__name__)
140
141
142
143
144
145
146
147
148
149
150
151
152
    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()
153
154
155
156
    formatter = logging.Formatter(
        config['general']['console_format'],
        config['general']['date_format']
    )
157
158
159
    ch.setFormatter(formatter)
    logger.addHandler(ch)

160
    fba = Account(vars(args), config)
161
162
163
164
165
    fba.create_labels_and_filters()


if __name__ == "__main__":
    main()