Refactoring the sdc-BE-init python scripts
[sdc.git] / catalog-be / src / main / resources / scripts / sdcBePy / users / run.py
1 #!/usr/bin/env python3
2
3 import json
4 import os
5 import time
6 from argparse import ArgumentParser
7
8 from sdcBePy.common.bColors import BColors
9 from sdcBePy.common.healthCheck import check_backend, RETRY_ATTEMPTS
10 from sdcBePy.common.sdcBeProxy import SdcBeProxy
11
12 colors = BColors()
13
14
15 def load_users(conf_path):
16     with open(conf_path, 'r') as f:
17         return json.load(f)
18
19
20 def be_user_init(be_ip, be_port, protocol, conf_path):
21     sdc_be_proxy = SdcBeProxy(be_ip, be_port, protocol)
22     if check_backend(sdc_be_proxy, RETRY_ATTEMPTS):
23         users = load_users(conf_path)
24         for user in users:
25             if sdc_be_proxy.check_user(user['userId']) != 200:
26                 result = sdc_be_proxy.create_user(user['firstName'],
27                                                   user['lastName'],
28                                                   user['userId'],
29                                                   user['email'],
30                                                   user['role'])
31                 if result == 201:
32                     print('[INFO]: ' + user['userId'] +
33                           ' created, result: [' + str(result) + ']')
34                 else:
35                     print('[ERROR]: ' + colors.FAIL + user['userId'] + colors.END_C +
36                           ' error creating , result: [' + str(result) + ']')
37             else:
38                 print('[INFO]: ' + user['userId'] + ' already exists')
39     else:
40         print('[ERROR]: ' + time.strftime('%Y/%m/%d %H:%M:%S') + colors.FAIL
41               + 'Backend is DOWN :-(' + colors.END_C)
42         raise Exception("Cannot communicate with the backend!")
43
44
45 def get_args():
46     parser = ArgumentParser()
47
48     parser.add_argument('-i', '--ip', required=True)
49     parser.add_argument('-p', '--port', required=True)
50     parser.add_argument('--https', action='store_true')
51     path = os.path.dirname(__file__)
52     parser.add_argument('--conf', default=os.path.join(path, 'data', 'users.json'))
53
54     args = parser.parse_args()
55
56     return [args.ip, args.port, 'https' if args.https else 'http', args.conf]
57
58
59 def main():
60     be_user_init(*get_args())
61
62
63 if __name__ == "__main__":
64     main()