aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py
blob: 511e8417e4b710b90f34b07f516992aead70578a (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
import pycurl
import sys, getopt
import zipfile
from StringIO import StringIO
import json
import copy
from importCommon import *
import importCommon
#########################################################################################################################################################################################
#																																		       											#
# Import all users from a given file																										   											#
# 																																			   											#
# activation :																																   											#
#       python importNormativeTypes.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ]	#
#							  [-v <true|false> | --updateversion=<true|false>]																											#
# shortest activation (be host = localhost, be port = 8080): 																				   											#
#		python importNormativeTypes.py [-f <input file> | --ifile=<input file> ]												 				           								#
#																																		       											#	
#########################################################################################################################################################################################

def createNormativeType(scheme, beHost, bePort, adminUser, fileDir, ELEMENT_NAME, updateversion):
	
	try:
		log("in create normative type ", ELEMENT_NAME)
		debug("userId", adminUser)
		debug("fileDir", fileDir)
		
		buffer = StringIO()
		c = pycurl.Curl()

		url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart'
		if updateversion != None:
			url += '?createNewVersion=' + updateversion
		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])
		c.setopt(pycurl.HTTPHEADER, [adminHeader])

		yml_path = fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".yml"
		path = fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".zip"

		zf = zipfile.ZipFile(path, "w")
		zf.write(yml_path, ELEMENT_NAME + '.yml')
		zf.close()

		debug(path)
        	CURRENT_JSON_FILE=fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".json"
        	#sed -i 's/"userId": ".*",/"userId": "'${USER_ID}'",/' ${CURRENT_JSON_FILE}

		jsonFile = open(CURRENT_JSON_FILE)
		
		debug("before load json")
		json_data = json.load(jsonFile, strict=False)
		debug(json_data)
	
		jsonAsStr = json.dumps(json_data)

		send = [('resourceMetadata', jsonAsStr), ('resourceZip', (pycurl.FORM_FILE, path))]
		debug(send)
		c.setopt(pycurl.HTTPPOST, send)		

		#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)
		c.setopt(c.WRITEFUNCTION, buffer.write)
		#print("before perform")	
		res = c.perform()
	
		#print("Before get response code")	
		httpRes = c.getinfo(c.RESPONSE_CODE)
		if (httpRes != None):
			debug("http response=", httpRes)
		#print('Status: ' + str(responseCode))
		debug(buffer.getvalue())
		c.close()

		return (ELEMENT_NAME, httpRes, buffer.getvalue())

	except Exception as inst:
		print("ERROR=" + str(inst))
		return (ELEMENT_NAME, None, None)				


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> ] [-u <user userId> | --user=<user userId> ] [-v <true|false> | --updateversion=<true|false>]'


def importNormativeTypes(scheme, beHost, bePort, adminUser, fileDir, updateversion):
	
	normativeTypes = [ "root", "compute", "softwareComponent", "webServer", "webApplication", "DBMS", "database", "objectStorage", "blockStorage", "containerRuntime", "containerApplication", "loadBalancer", "port", "network"]
	#normativeTypes = [ "root" ]
	responseCodes = [200, 201]
	
	if(updateversion == 'false'):
		responseCodes = [200, 201, 409]
	
        results = []
        for normativeType in normativeTypes:
                result = createNormativeType(scheme, beHost, bePort, adminUser, fileDir, normativeType, updateversion)
                results.append(result)
                if ( result[1] == None or result[1] not in responseCodes ):
			print "Failed creating normative type " + normativeType + ". " + str(result[1]) 				
	return results


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

	beHost = 'localhost' 
	bePort = '8080'
	adminUser = 'jh0003'
	updateversion = 'true'
	scheme = 'http'

	try:
		opts, args = getopt.getopt(argv,"i:p:u:v:h:s:",["ip=","port=","user=","updateversion=","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 ("-u", "--user"):
			adminUser = arg
		elif opt in ("-s", "--scheme"):
			scheme = arg
		elif opt in ("-v", "--updateversion"):
			if (arg.lower() == "false" or arg.lower() == "no"):
				updateversion = 'false'

	print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', updateversion =', updateversion
	
	if ( beHost == None ):
		usage()
		sys.exit(3)

	results = importNormativeTypes(scheme, beHost, bePort, adminUser, "../../../import/tosca/normative-types/", updateversion)

	print "-----------------------------"
	for result in results:
		print "{0:20} | {1:6}".format(result[0], result[1])
	print "-----------------------------"
	
	responseCodes = [200, 201]
	
	if(updateversion == 'false'):
		responseCodes = [200, 201, 409]
	
	failedNormatives = filter(lambda x: x[1] == None or x[1] not in responseCodes, results)
	if (len(failedNormatives) > 0):
		error_and_exit(1, None)
	else:
		error_and_exit(0, None)


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