4 from StringIO import StringIO
7 from importCommon import *
9 #########################################################################################################################################################################################
11 # Import all users from a given file #
14 # 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> ] #
15 # [-v <true|false> | --updateversion=<true|false>] #
16 # shortest activation (be host = localhost, be port = 8080): #
17 # python importNormativeTypes.py [-f <input file> | --ifile=<input file> ] #
19 #########################################################################################################################################################################################
21 def createNormativeType(scheme, beHost, bePort, adminUser, fileDir, ELEMENT_NAME, updateversion):
24 log("in create normative type ", ELEMENT_NAME)
25 debug("userId", adminUser)
26 debug("fileDir", fileDir)
31 url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart'
32 if updateversion != None:
33 url += '?createNewVersion=' + updateversion
37 adminHeader = 'USER_ID: ' + adminUser
38 #c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', adminHeader])
39 c.setopt(pycurl.HTTPHEADER, [adminHeader])
41 yml_path = fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".yml"
42 path = fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".zip"
44 zf = zipfile.ZipFile(path, "w")
45 zf.write(yml_path, ELEMENT_NAME + '.yml')
49 CURRENT_JSON_FILE=fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".json"
50 #sed -i 's/"userId": ".*",/"userId": "'${USER_ID}'",/' ${CURRENT_JSON_FILE}
52 jsonFile = open(CURRENT_JSON_FILE)
54 debug("before load json")
55 json_data = json.load(jsonFile, strict=False)
58 jsonAsStr = json.dumps(json_data)
60 send = [('resourceMetadata', jsonAsStr), ('resourceZip', (pycurl.FORM_FILE, path))]
62 c.setopt(pycurl.HTTPPOST, send)
64 #data = json.dumps(user)
65 #c.setopt(c.POSTFIELDS, data)
68 c.setopt(pycurl.SSL_VERIFYPEER, 0)
69 c.setopt(pycurl.SSL_VERIFYHOST, 0)
71 #c.setopt(c.WRITEFUNCTION, lambda x: None)
72 c.setopt(c.WRITEFUNCTION, buffer.write)
73 #print("before perform")
76 #print("Before get response code")
77 httpRes = c.getinfo(c.RESPONSE_CODE)
79 debug("http response=", httpRes)
80 #print('Status: ' + str(responseCode))
81 debug(buffer.getvalue())
84 return (ELEMENT_NAME, httpRes, buffer.getvalue())
86 except Exception as inst:
87 print("ERROR=" + str(inst))
88 return (ELEMENT_NAME, None, None)
92 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>]'
95 def importNormativeTypes(scheme, beHost, bePort, adminUser, fileDir, updateversion):
97 normativeTypes = [ "root", "compute", "softwareComponent", "webServer", "webApplication", "DBMS", "database", "objectStorage", "blockStorage", "containerRuntime", "containerApplication", "loadBalancer", "port", "network"]
98 #normativeTypes = [ "root" ]
99 responseCodes = [200, 201]
101 if(updateversion == 'false'):
102 responseCodes = [200, 201, 409]
105 for normativeType in normativeTypes:
106 result = createNormativeType(scheme, beHost, bePort, adminUser, fileDir, normativeType, updateversion)
107 results.append(result)
108 if ( result[1] == None or result[1] not in responseCodes ):
109 print "Failed creating normative type " + normativeType + ". " + str(result[1])
114 print 'Number of arguments:', len(sys.argv), 'arguments.'
119 updateversion = 'true'
123 opts, args = getopt.getopt(argv,"i:p:u:v:h:s:",["ip=","port=","user=","updateversion=","scheme="])
124 except getopt.GetoptError:
126 error_and_exit(2, 'Invalid input')
128 for opt, arg in opts:
133 elif opt in ("-i", "--ip"):
135 elif opt in ("-p", "--port"):
137 elif opt in ("-u", "--user"):
139 elif opt in ("-s", "--scheme"):
141 elif opt in ("-v", "--updateversion"):
142 if (arg.lower() == "false" or arg.lower() == "no"):
143 updateversion = 'false'
145 print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', updateversion =', updateversion
147 if ( beHost == None ):
151 results = importNormativeTypes(scheme, beHost, bePort, adminUser, "../../../import/tosca/normative-types/", updateversion)
153 print "-----------------------------"
154 for result in results:
155 print "{0:20} | {1:6}".format(result[0], result[1])
156 print "-----------------------------"
158 responseCodes = [200, 201]
160 if(updateversion == 'false'):
161 responseCodes = [200, 201, 409]
163 failedNormatives = filter(lambda x: x[1] == None or x[1] not in responseCodes, results)
164 if (len(failedNormatives) > 0):
165 error_and_exit(1, None)
167 error_and_exit(0, None)
170 if __name__ == "__main__":