aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/resources/scripts/import/tosca/importUsersFromYaml.py
blob: 23e854bcb83706743ad683849a9b601332f36369 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
67
68
69
70
71
72
73
74
75
76
77
78
79
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import pycurl
import sys, getopt
from StringIO import StringIO
import json
import copy
import yaml

#########################################################################################################################################################################################
#																																				       									#
# Import all users from a given YAML file																											   									#
# 																																					   									#
# activation :																																		   									#
#       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> ]	#
#																																				  	   									#
# shortest activation (be host = localhost, be port = 8080): 																						   									#
#		python importUsersFromYaml.py [-f <input file> | --ifile=<input file> ]												 				           									#
#									    																											   									#
#   PyYAML module shall be added to python.																											   									#
#   pip install PyYAML>=3.1.0 --proxy=http://one.proxy.att.com:8080														                               									#
#########################################################################################################################################################################################


def importUsers(scheme, beHost, bePort, users, adminUser):
	
	result = []	

	for user in users:
			
		#print("Going to add user " + user['userId'])
	
		getRes = getUser(scheme, beHost, bePort, user)	
		userId = getRes[0]
		error = getRes[1]
		#print error
		if ( error != None and error == 404 ):
			res = createUser(scheme, beHost, bePort, user ,adminUser)			
			result.append(res)			
		else:
			if ( error == 200 ):
				curResult = (userId, 409)
				result.append(curResult)	
			else:
				result.append(getRes)

	return result				


def getUser(scheme, beHost, bePort, user):

	if (user.get('userId') == None):
                print "Ignoring record", user
                return ('NotExist', 200)
	userId = user['userId']
	try:
		buffer = StringIO()
		c = pycurl.Curl()

		#print type(userId)
		url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user/' + str(userId)
		c.setopt(c.URL, url)

		if scheme == 'https':
			c.setopt(c.SSL_VERIFYPEER, 0)

		#adminHeader = 'USER_ID: ' + adminUser
		c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json'])
		c.setopt(c.WRITEFUNCTION, lambda x: None)
		res = c.perform()
					
		#print("Before get response code")	
		httpRes = c.getinfo(c.RESPONSE_CODE)
		#print("After get response code")	
		responseCode = c.getinfo(c.RESPONSE_CODE)
		
		#print('Status: ' + str(responseCode))

		c.close()

		return (userId, httpRes)

	except Exception as inst:
		print(inst)
		return (userId, None)				

		

def createUser(scheme, beHost, bePort, user, adminUser):
	
	if (user.get('userId') == None):
		print "Ignoring record", user
		return ('NotExist', 200)
	
	userId = user['userId']
	try:
		buffer = StringIO()
		c = pycurl.Curl()

		url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user'
		c.setopt(c.URL, url)
		c.setopt(c.POST, 1)		

		adminHeader = 'USER_ID: ' + adminUser
		c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', adminHeader])

		data = json.dumps(user)
		c.setopt(c.POSTFIELDS, data)

		if scheme == 'https':
			c.setopt(c.SSL_VERIFYPEER, 0)

		c.setopt(c.WRITEFUNCTION, lambda x: None)
		#print("before perform")	
		res = c.perform()
        #print(res)
	
		#print("Before get response code")	
		httpRes = c.getinfo(c.RESPONSE_CODE)
		#print("After get response code")	
		responseCode = c.getinfo(c.RESPONSE_CODE)
		
		#print('Status: ' + str(responseCode))

		c.close()

		return (userId, httpRes)

	except Exception as inst:
		print(inst)
		return (userId, None)				


def error_and_exit(errorCode, errorDesc):
	if ( errorCode > 0 ):
		print("status=" + str(errorCode) + ". " + errorDesc) 
	else:
		print("status=" + str(errorCode))
	sys.exit(errorCode)
	
def usage():
	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> ]'

def main(argv):
	print 'Number of arguments:', len(sys.argv), 'arguments.'

	beHost = 'localhost' 
	bePort = '8080'
	inputfile = None 

	adminUser = 'jh0003'
	scheme ='http'

	try:
		opts, args = getopt.getopt(argv,"i:p:f:h:s:",["ip=","port=","ifile=","scheme="])
	except getopt.GetoptError:
		usage()
		error_and_exit(2, 'Invalid input')
		 
	for opt, arg in opts:
	#print opt, arg
		if opt == '-h':
			usage()                        
			sys.exit(3)
		elif opt in ("-i", "--ip"):
			beHost = arg
		elif opt in ("-p", "--port"):
			bePort = arg
		elif opt in ("-f", "--ifile"):
			inputfile = arg
		elif opt in ("-s", "--scheme"):
			scheme = arg

	print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', users file =',inputfile
	
	if ( inputfile == None ):
		usage()
		sys.exit(3)

	print 'Input file is ', inputfile

	
	usersAsYamlFile = open(inputfile, 'r')
    	usersDoc = yaml.load(usersAsYamlFile)	
	print usersDoc 

	cloneUsers = [] 
	for users in usersDoc.values():
		for x,y in users.items():		
			copiedUser = y
			copiedUser['userId'] = x
			#print copiedUser 
			cloneUsers.append(copiedUser)
	
	print cloneUsers

	usersAsYamlFile.close()

	#activeUsers = filter(lambda x: x.get('status') == None or x['status'] == 'ACTIVE', cloneUsers)

	resultTable = importUsers(scheme, beHost, bePort, cloneUsers, adminUser)

	g = lambda x: x[1] != 201 and x[1] != 409

	result = filter(g, resultTable)

	if ( len(result) > 0 ):
		#print("ERROR: Failed to load the users " + ', '.join(map(lambda x: x[0],result)))
		error_and_exit(3, "Failed to load the users " + ', '.join(map(lambda x: x[0],result)))	

	g = lambda x: x[1] == 409
	result = filter(g, resultTable)

	print("-------------------------------------------")
	print("Existing users: " + ', '.join(map(lambda x: x[0],result)))

	result = filter(lambda x: x[1] == 201, resultTable)
	if ( len(result) == 0 ):
		print("-------------------------------------------")
		print("No NEW user was loaded. All users are already exist")
		print("-------------------------------------------")
	else:
		print("-------------------------------------------")
		print("Loaded users: " + ', '.join(map(lambda x: x[0],result)))
		print("-------------------------------------------")

	error_and_exit(0, None)


if __name__ == "__main__":
        main(sys.argv[1:])