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(pycurl.SSL_VERIFYPEER, 0)
64 c.setopt(pycurl.SSL_VERIFYHOST, 0)
66 #adminHeader = 'USER_ID: ' + adminUser
67 c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json'])
68 c.setopt(c.WRITEFUNCTION, lambda x: None)
71 #print("Before get response code")
72 httpRes = c.getinfo(c.RESPONSE_CODE)
73 #print("After get response code")
74 responseCode = c.getinfo(c.RESPONSE_CODE)
76 #print('Status: ' + str(responseCode))
80 return (userId, httpRes)
82 except Exception as inst:
88 def createUser(scheme, beHost, bePort, user, adminUser):
90 if (user.get('userId') == None):
91 print "Ignoring record", user
92 return ('NotExist', 200)
94 userId = user['userId']
99 url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user'
103 adminHeader = 'USER_ID: ' + adminUser
104 c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', adminHeader])
106 data = json.dumps(user)
107 c.setopt(c.POSTFIELDS, data)
109 if scheme == 'https':
110 c.setopt(pycurl.SSL_VERIFYPEER, 0)
111 c.setopt(pycurl.SSL_VERIFYHOST, 0)
113 c.setopt(c.WRITEFUNCTION, lambda x: None)
114 #print("before perform")
118 #print("Before get response code")
119 httpRes = c.getinfo(c.RESPONSE_CODE)
120 #print("After get response code")
121 responseCode = c.getinfo(c.RESPONSE_CODE)
123 #print('Status: ' + str(responseCode))
127 return (userId, httpRes)
129 except Exception as inst:
131 return (userId, None)
134 def error_and_exit(errorCode, errorDesc):
135 if ( errorCode > 0 ):
136 print("status=" + str(errorCode) + ". " + errorDesc)
138 print("status=" + str(errorCode))
142 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 print 'Number of arguments:', len(sys.argv), 'arguments.'
155 opts, args = getopt.getopt(argv,"i:p:f:h:s:",["ip=","port=","ifile=","scheme="])
156 except getopt.GetoptError:
158 error_and_exit(2, 'Invalid input')
160 for opt, arg in opts:
165 elif opt in ("-i", "--ip"):
167 elif opt in ("-p", "--port"):
169 elif opt in ("-f", "--ifile"):
171 elif opt in ("-s", "--scheme"):
174 print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', users file =',inputfile
176 if ( inputfile == None ):
180 print 'Input file is ', inputfile
183 usersAsYamlFile = open(inputfile, 'r')
184 usersDoc = yaml.load(usersAsYamlFile)
188 for users in usersDoc.values():
189 for x,y in users.items():
191 copiedUser['userId'] = x
193 cloneUsers.append(copiedUser)
197 usersAsYamlFile.close()
199 #activeUsers = filter(lambda x: x.get('status') == None or x['status'] == 'ACTIVE', cloneUsers)
201 resultTable = importUsers(scheme, beHost, bePort, cloneUsers, adminUser)
203 g = lambda x: x[1] != 201 and x[1] != 409
205 result = filter(g, resultTable)
207 if ( len(result) > 0 ):
208 #print("ERROR: Failed to load the users " + ', '.join(map(lambda x: x[0],result)))
209 error_and_exit(3, "Failed to load the users " + ', '.join(map(lambda x: x[0],result)))
211 g = lambda x: x[1] == 409
212 result = filter(g, resultTable)
214 print("-------------------------------------------")
215 print("Existing users: " + ', '.join(map(lambda x: x[0],result)))
217 result = filter(lambda x: x[1] == 201, resultTable)
218 if ( len(result) == 0 ):
219 print("-------------------------------------------")
220 print("No NEW user was loaded. All users are already exist")
221 print("-------------------------------------------")
223 print("-------------------------------------------")
224 print("Loaded users: " + ', '.join(map(lambda x: x[0],result)))
225 print("-------------------------------------------")
227 error_and_exit(0, None)
230 if __name__ == "__main__":