d47c0b80736d565dcd93c0f9a4ec779d5b7cd4b8
[sdc.git] / catalog-be / src / main / resources / scripts / import / tosca / importNormativeTypes.py
1 import pycurl
2 import sys, getopt
3 from StringIO import StringIO
4 import json
5 import copy
6 from importCommon import *
7 import importCommon
8 ################################################################################################################################################
9 #                                                                                                                                                                                                                                                                                      #        
10 # Import all users from a given file                                                                                                                                                                                                               #
11 #                                                                                                                                                                                                                                                                                          #            
12 # activation :                                                                                                                                                                                                                                                             #
13 #       python importUsers.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ]     #
14 #                                                         [-v <true|false> | --updateversion=<true|false>]                                                                                                                                                                                                                                 #                    
15 # shortest activation (be host = localhost, be port = 8080):                                                                                                                                                               #                                                                                                                                   #
16 #               python importUsers.py [-f <input file> | --ifile=<input file> ]                                                                                                                                    #
17 #                                                                                                                                                                                                                                                                                      #        
18 ################################################################################################################################################
19
20 def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, updateversion):
21         
22         try:
23                 log("in create normative type ", ELEMENT_NAME)
24                 debug("userId", adminUser)
25                 debug("fileDir", fileDir)
26                 
27                 buffer = StringIO()
28                 c = pycurl.Curl()
29
30                 url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart'
31                 if updateversion != None:
32                         url += '?createNewVersion=' + updateversion
33                 c.setopt(c.URL, url)
34                 c.setopt(c.POST, 1)             
35
36                 adminHeader = 'USER_ID: ' + adminUser
37                 #c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', adminHeader])
38                 c.setopt(pycurl.HTTPHEADER, [adminHeader])
39
40
41                 path = fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".zip"
42                 debug(path)
43                 CURRENT_JSON_FILE=fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".json"
44                 #sed -i 's/"userId": ".*",/"userId": "'${USER_ID}'",/' ${CURRENT_JSON_FILE}
45
46                 jsonFile = open(CURRENT_JSON_FILE)
47                 
48                 debug("before load json")
49                 json_data = json.load(jsonFile, strict=False)
50                 debug(json_data)
51         
52                 jsonAsStr = json.dumps(json_data)
53
54                 send = [('resourceMetadata', jsonAsStr), ('resourceZip', (pycurl.FORM_FILE, path))]
55                 debug(send)
56                 c.setopt(pycurl.HTTPPOST, send)         
57
58                 #data = json.dumps(user)
59                 #c.setopt(c.POSTFIELDS, data)   
60
61                 #c.setopt(c.WRITEFUNCTION, lambda x: None)
62                 c.setopt(c.WRITEFUNCTION, buffer.write)
63                 #print("before perform")        
64                 res = c.perform()
65         
66                 #print("Before get response code")      
67                 httpRes = c.getinfo(c.RESPONSE_CODE)
68                 if (httpRes != None):
69                         debug("http response=", httpRes)
70                 #print('Status: ' + str(responseCode))
71                 debug(buffer.getvalue())
72                 c.close()
73
74                 return (ELEMENT_NAME, httpRes, buffer.getvalue())
75
76         except Exception as inst:
77                 print("ERROR=" + str(inst))
78                 return (ELEMENT_NAME, None, None)                               
79
80
81 def usage():
82         print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-v <true|false> | --updateversion=<true|false>]'
83
84
85 def importNormativeTypes(beHost, bePort, adminUser, fileDir, updateversion):
86         
87         normativeTypes = [ "root", "compute", "softwareComponent", "webServer", "webApplication", "DBMS", "database", "objectStorage", "blockStorage", "containerRuntime", "containerApplication", "loadBalancer", "port", "network"]
88         #normativeTypes = [ "root" ]
89         responseCodes = [200, 201]
90         
91         if(updateversion == 'false'):
92                 responseCodes = [200, 201, 409]
93         
94         results = []
95         for normativeType in normativeTypes:
96                 result = createNormativeType(beHost, bePort, adminUser, fileDir, normativeType, updateversion)
97                 results.append(result)
98                 if ( result[1] == None or result[1] not in responseCodes ):
99                         print "Failed creating normative type " + normativeType + ". " + str(result[1])                                 
100         return results
101
102
103 def main(argv):
104         print 'Number of arguments:', len(sys.argv), 'arguments.'
105
106         beHost = 'localhost' 
107         bePort = '8080'
108         adminUser = 'jh0003'
109         updateversion = 'true'
110
111         try:
112                 opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="])
113         except getopt.GetoptError:
114                 usage()
115                 errorAndExit(2, 'Invalid input')
116                  
117         for opt, arg in opts:
118         #print opt, arg
119                 if opt == '-h':
120                         usage()                        
121                         sys.exit(3)
122                 elif opt in ("-i", "--ip"):
123                         beHost = arg
124                 elif opt in ("-p", "--port"):
125                         bePort = arg
126                 elif opt in ("-u", "--user"):
127                         adminUser = arg
128                 elif opt in ("-v", "--updateversion"):
129                         if (arg.lower() == "false" or arg.lower() == "no"):
130                                 updateversion = 'false'
131
132         print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', updateversion =', updateversion
133         
134         if ( beHost == None ):
135                 usage()
136                 sys.exit(3)
137
138         results = importNormativeTypes(beHost, bePort, adminUser, "../../../import/tosca/normative-types/", updateversion)
139
140         print "-----------------------------"
141         for result in results:
142                 print "{0:20} | {1:6}".format(result[0], result[1])
143         print "-----------------------------"
144         
145         responseCodes = [200, 201]
146         
147         if(updateversion == 'false'):
148                 responseCodes = [200, 201, 409]
149         
150         failedNormatives = filter(lambda x: x[1] == None or x[1] not in responseCodes, results)
151         if (len(failedNormatives) > 0):
152                 errorAndExit(1, None)
153         else:
154                 errorAndExit(0, None)
155
156
157 if __name__ == "__main__":
158         main(sys.argv[1:])
159