3 from StringIO import StringIO
6 from importCommon import *
8 ################################################################################################################################################
10 # Import all users from a given file #
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> ] #
18 ################################################################################################################################################
20 def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, updateversion):
23 log("in create normative type ", ELEMENT_NAME)
24 debug("userId", adminUser)
25 debug("fileDir", fileDir)
30 url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart'
31 if updateversion != None:
32 url += '?createNewVersion=' + updateversion
36 adminHeader = 'USER_ID: ' + adminUser
37 #c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', adminHeader])
38 c.setopt(pycurl.HTTPHEADER, [adminHeader])
41 path = fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".zip"
43 CURRENT_JSON_FILE=fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".json"
44 #sed -i 's/"userId": ".*",/"userId": "'${USER_ID}'",/' ${CURRENT_JSON_FILE}
46 jsonFile = open(CURRENT_JSON_FILE)
48 debug("before load json")
49 json_data = json.load(jsonFile, strict=False)
52 jsonAsStr = json.dumps(json_data)
54 send = [('resourceMetadata', jsonAsStr), ('resourceZip', (pycurl.FORM_FILE, path))]
56 c.setopt(pycurl.HTTPPOST, send)
58 #data = json.dumps(user)
59 #c.setopt(c.POSTFIELDS, data)
61 #c.setopt(c.WRITEFUNCTION, lambda x: None)
62 c.setopt(c.WRITEFUNCTION, buffer.write)
63 #print("before perform")
66 #print("Before get response code")
67 httpRes = c.getinfo(c.RESPONSE_CODE)
69 debug("http response=", httpRes)
70 #print('Status: ' + str(responseCode))
71 debug(buffer.getvalue())
74 return (ELEMENT_NAME, httpRes, buffer.getvalue())
76 except Exception as inst:
77 print("ERROR=" + str(inst))
78 return (ELEMENT_NAME, None, None)
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>]'
85 def importNormativeTypes(beHost, bePort, adminUser, fileDir, updateversion):
87 normativeTypes = [ "root", "compute", "softwareComponent", "webServer", "webApplication", "DBMS", "database", "objectStorage", "blockStorage", "containerRuntime", "containerApplication", "loadBalancer", "port", "network", "allottedResource"]
88 #normativeTypes = [ "root" ]
89 responseCodes = [200, 201]
91 if(updateversion == 'false'):
92 responseCodes = [200, 201, 409]
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])
104 print 'Number of arguments:', len(sys.argv), 'arguments.'
109 updateversion = 'true'
112 opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="])
113 except getopt.GetoptError:
115 errorAndExit(2, 'Invalid input')
117 for opt, arg in opts:
122 elif opt in ("-i", "--ip"):
124 elif opt in ("-p", "--port"):
126 elif opt in ("-u", "--user"):
128 elif opt in ("-v", "--updateversion"):
129 if (arg.lower() == "false" or arg.lower() == "no"):
130 updateversion = 'false'
132 print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', updateversion =', updateversion
134 if ( beHost == None ):
138 results = importNormativeTypes(beHost, bePort, adminUser, "../../../import/tosca/normative-types/", updateversion)
140 print "-----------------------------"
141 for result in results:
142 print "{0:20} | {1:6}".format(result[0], result[1])
143 print "-----------------------------"
145 responseCodes = [200, 201]
147 if(updateversion == 'false'):
148 responseCodes = [200, 201, 409]
150 failedNormatives = filter(lambda x: x[1] == None or x[1] not in responseCodes, results)
151 if (len(failedNormatives) > 0):
152 errorAndExit(1, None)
154 errorAndExit(0, None)
157 if __name__ == "__main__":