Sync Integ to Master
[sdc.git] / asdctool / src / main / resources / scripts / python / user / importUsers.py
1 import pycurl
2 import sys, getopt
3 from StringIO import StringIO
4 import json
5 import copy
6
7 #####################################################################################################################################################################################
8 #                                                                                                                                                                                                                                                                                                                                                               #
9 # Import all users from a given file                                                                                                                                                                                                                                                                                            #
10 #                                                                                                                                                                                                                                                                                                                                                                       #
11 # activation :                                                                                                                                                                                                                                                                                                                                          #
12 #       python importUsers.py  [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ]          #
13 #                                                                                                                                                                                                                                                                                                                                                                       #
14 # shortest activation (be host = localhost, be port = 8080):                                                                                                                                                                                                                                            #
15 #               python importUsers.py [-f <input file> | --ifile=<input file> ]                                                                                                                                                                                                                 #
16 #                                                                                                                                                                                                                                                                                                                                                               #
17 #####################################################################################################################################################################################
18
19
20 def importUsers(scheme, beHost, bePort, users, adminUser):
21         
22         result = []     
23
24         for user in users:
25                         
26                 #print("Going to add user " + user['userId'])
27         
28                 getRes = getUser(scheme, beHost, bePort, user)  
29                 userId = getRes[0]
30                 error = getRes[1]
31                 #print error
32                 if ( error != None and error == 404 ):
33                         res = createUser(scheme, beHost, bePort, user ,adminUser)                       
34                         result.append(res)                      
35                 else:
36                         if ( error == 200 ):
37                                 curResult = (userId, 409)
38                                 result.append(curResult)        
39                         else:
40                                 result.append(getRes)
41
42         return result                           
43
44
45 def convertUsersToCreationObject(users):
46
47         cloneUsers  = copy.deepcopy(users)
48         for user in cloneUsers:
49                 #print user     
50                 if (user.get('fullName') != None):
51                         del user['fullName']
52                 #user['userId'] = user['userId'] + '1'
53                 #print user
54
55         return cloneUsers
56
57 def getUser(scheme, beHost, bePort, user):
58
59         userId = user['userId']
60         try:
61                 buffer = StringIO()
62                 c = pycurl.Curl()
63
64                 #print type(userId)
65                 url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user/' + str(userId)
66                 c.setopt(c.URL, url)
67
68                 #adminHeader = 'USER_ID: ' + adminUser
69                 c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json'])
70                 c.setopt(c.WRITEFUNCTION, lambda x: None)
71
72                 if scheme == 'https':
73                         c.setopt(c.SSL_VERIFYPEER, 0)
74
75                 res = c.perform()
76                                         
77                 #print("Before get response code")      
78                 httpRes = c.getinfo(c.RESPONSE_CODE)
79                 #print("After get response code")       
80                 responseCode = c.getinfo(c.RESPONSE_CODE)
81                 
82                 #print('Status: ' + str(responseCode))
83
84                 c.close()
85
86                 return (userId, httpRes)
87
88         except Exception as inst:
89                 print(inst)
90                 return (userId, None)                           
91
92                 
93
94 def createUser(scheme, beHost, bePort, user, adminUser):
95
96         userId = user['userId']
97         try:
98                 buffer = StringIO()
99                 c = pycurl.Curl()
100
101                 url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user'
102                 c.setopt(c.URL, url)
103                 c.setopt(c.POST, 1)             
104
105                 adminHeader = 'USER_ID: ' + adminUser
106                 c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', adminHeader])
107
108                 data = json.dumps(user)
109                 c.setopt(c.POSTFIELDS, data)    
110
111                 c.setopt(c.WRITEFUNCTION, lambda x: None)
112
113                 if scheme == 'https':
114                         c.setopt(c.SSL_VERIFYPEER, 0)
115
116                 #print("before perform")        
117                 res = c.perform()
118         #print(res)
119         
120                 #print("Before get response code")      
121                 httpRes = c.getinfo(c.RESPONSE_CODE)
122                 #print("After get response code")       
123                 responseCode = c.getinfo(c.RESPONSE_CODE)
124                 
125                 #print('Status: ' + str(responseCode))
126
127                 c.close()
128
129                 return (userId, httpRes)
130
131         except Exception as inst:
132                 print(inst)
133                 return (userId, None)                           
134
135
136 def errorAndExit(errorCode, errorDesc):
137         if ( errorCode > 0 ):
138                 print("status=" + str(errorCode) + ". " + errorDesc) 
139         else:
140                 print("status=" + str(errorCode))
141         sys.exit(errorCode)
142         
143 def usage():
144         print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ]'
145
146 def main(argv):
147         print 'Number of arguments:', len(sys.argv), 'arguments.'
148
149         beHost = 'localhost' 
150         bePort = '8080'
151         inputfile = None 
152         scheme = 'http'
153         adminUser = 'jh0003'
154
155         try:
156                 opts, args = getopt.getopt(argv,"i:p:f:h:s:",["ip=","port=","ifile=","scheme="])
157         except getopt.GetoptError:
158                 usage()
159                 errorAndExit(2, 'Invalid input')
160                  
161         for opt, arg in opts:
162         #print opt, arg
163                 if opt == '-h':
164                         usage()                        
165                         sys.exit(3)
166                 elif opt in ("-i", "--ip"):
167                         beHost = arg
168                 elif opt in ("-p", "--port"):
169                         bePort = arg
170                 elif opt in ("-f", "--ifile"):
171                         inputfile = arg
172                 elif opt in ("-s", "--scheme"):
173                         scheme = arg
174
175         print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', users file =',inputfile
176         
177         if ( inputfile == None ):
178                 usage()
179                 sys.exit(3)
180
181         print 'Input file is ', inputfile
182
183         usersFile = open(inputfile)
184
185         json_data = json.load(usersFile)
186
187         #print json_data
188
189         cloneUsers = convertUsersToCreationObject(json_data)
190
191         activeUsers = filter(lambda x: x['status'] == 'ACTIVE', cloneUsers)
192
193         #print activeUsers
194
195         resultTable = importUsers(scheme, beHost, bePort, activeUsers, adminUser)
196
197         g = lambda x: x[1] != 201 and x[1] != 409
198
199         result = filter(g, resultTable)
200
201         if ( len(result) > 0 ):
202                 #print("ERROR: Failed to load the users " + ', '.join(map(lambda x: x[0],result)))
203                 errorAndExit(3, "Failed to load the users " + ', '.join(map(lambda x: x[0],result)))    
204
205         g = lambda x: x[1] == 409
206         result = filter(g, resultTable)
207
208         print("-------------------------------------------")
209         print("Existing users: " + ', '.join(map(lambda x: x[0],result)))
210
211         result = filter(lambda x: x[1] == 201, resultTable)
212         if ( len(result) == 0 ):
213                 print("-------------------------------------------")
214                 print("No NEW user was loaded. All users are already exist")
215                 print("-------------------------------------------")
216         else:
217                 print("-------------------------------------------")
218                 print("Loaded users: " + ', '.join(map(lambda x: x[0],result)))
219                 print("-------------------------------------------")
220
221         errorAndExit(0, None)
222
223
224 if __name__ == "__main__":
225         main(sys.argv[1:])