3 from StringIO import StringIO
8 #########################################################################################################################################################################################
10 # Import all users from a given YAML file #
13 # python importUsersFromYaml.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
15 # shortest activation (be host = localhost, be port = 8080): #
16 # python importUsersFromYaml.py [-f <input file> | --ifile=<input file> ] #
18 # PyYAML module shall be added to python. #
19 # pip install PyYAML>=3.1.0 --proxy=http://one.proxy.att.com:8080 #
20 #########################################################################################################################################################################################
23 def importUsers(scheme, beHost, bePort, users, adminUser):
29 #print("Going to add user " + user['userId'])
31 getRes = getUser(scheme, beHost, bePort, user)
35 if ( error != None and error == 404 ):
36 res = createUser(scheme, beHost, bePort, user ,adminUser)
40 curResult = (userId, 409)
41 result.append(curResult)
48 def getUser(scheme, beHost, bePort, user):
50 if (user.get('userId') == None):
51 print "Ignoring record", user
52 return ('NotExist', 200)
53 userId = user['userId']
59 url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user/' + str(userId)
63 c.setopt(c.SSL_VERIFYPEER, 0)
65 #adminHeader = 'USER_ID: ' + adminUser
66 c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json'])
67 c.setopt(c.WRITEFUNCTION, lambda x: None)
70 #print("Before get response code")
71 httpRes = c.getinfo(c.RESPONSE_CODE)
72 #print("After get response code")
73 responseCode = c.getinfo(c.RESPONSE_CODE)
75 #print('Status: ' + str(responseCode))
79 return (userId, httpRes)
81 except Exception as inst:
87 def createUser(scheme, beHost, bePort, user, adminUser):
89 if (user.get('userId') == None):
90 print "Ignoring record", user
91 return ('NotExist', 200)
93 userId = user['userId']
98 url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user'
102 adminHeader = 'USER_ID: ' + adminUser
103 c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', adminHeader])
105 data = json.dumps(user)
106 c.setopt(c.POSTFIELDS, data)
108 if scheme == 'https':
109 c.setopt(c.SSL_VERIFYPEER, 0)
111 c.setopt(c.WRITEFUNCTION, lambda x: None)
112 #print("before perform")
116 #print("Before get response code")
117 httpRes = c.getinfo(c.RESPONSE_CODE)
118 #print("After get response code")
119 responseCode = c.getinfo(c.RESPONSE_CODE)
121 #print('Status: ' + str(responseCode))
125 return (userId, httpRes)
127 except Exception as inst:
129 return (userId, None)
132 def errorAndExit(errorCode, errorDesc):
133 if ( errorCode > 0 ):
134 print("status=" + str(errorCode) + ". " + errorDesc)
136 print("status=" + str(errorCode))
140 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> ]'
143 print 'Number of arguments:', len(sys.argv), 'arguments.'
153 opts, args = getopt.getopt(argv,"i:p:f:h:s:",["ip=","port=","ifile=","scheme="])
154 except getopt.GetoptError:
156 errorAndExit(2, 'Invalid input')
158 for opt, arg in opts:
163 elif opt in ("-i", "--ip"):
165 elif opt in ("-p", "--port"):
167 elif opt in ("-f", "--ifile"):
169 elif opt in ("-s", "--scheme"):
172 print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', users file =',inputfile
174 if ( inputfile == None ):
178 print 'Input file is ', inputfile
181 usersAsYamlFile = open(inputfile, 'r')
182 usersDoc = yaml.load(usersAsYamlFile)
186 for users in usersDoc.values():
187 for x,y in users.items():
189 copiedUser['userId'] = x
191 cloneUsers.append(copiedUser)
195 usersAsYamlFile.close()
197 #activeUsers = filter(lambda x: x.get('status') == None or x['status'] == 'ACTIVE', cloneUsers)
199 resultTable = importUsers(scheme, beHost, bePort, cloneUsers, adminUser)
201 g = lambda x: x[1] != 201 and x[1] != 409
203 result = filter(g, resultTable)
205 if ( len(result) > 0 ):
206 #print("ERROR: Failed to load the users " + ', '.join(map(lambda x: x[0],result)))
207 errorAndExit(3, "Failed to load the users " + ', '.join(map(lambda x: x[0],result)))
209 g = lambda x: x[1] == 409
210 result = filter(g, resultTable)
212 print("-------------------------------------------")
213 print("Existing users: " + ', '.join(map(lambda x: x[0],result)))
215 result = filter(lambda x: x[1] == 201, resultTable)
216 if ( len(result) == 0 ):
217 print("-------------------------------------------")
218 print("No NEW user was loaded. All users are already exist")
219 print("-------------------------------------------")
221 print("-------------------------------------------")
222 print("Loaded users: " + ', '.join(map(lambda x: x[0],result)))
223 print("-------------------------------------------")
225 errorAndExit(0, None)
228 if __name__ == "__main__":