diff options
Diffstat (limited to 'openecomp-be/tools')
3 files changed, 138 insertions, 127 deletions
diff --git a/openecomp-be/tools/build/scripts/action_library_client/action_library_client.py b/openecomp-be/tools/build/scripts/action_library_client/action_library_client.py index 7f513afe86..0537128665 100644 --- a/openecomp-be/tools/build/scripts/action_library_client/action_library_client.py +++ b/openecomp-be/tools/build/scripts/action_library_client/action_library_client.py @@ -147,6 +147,7 @@ class FinalizeStatus(object): class ArgsDict(dict): """A dict which makes attributes accessible as properties.""" + def __getattr__(self, attr): return self[attr] @@ -221,33 +222,33 @@ class ArgumentParser(object): def usage(): """Print usage message.""" print("" + - "Usage: action_library_client.py [--help] [--url <url>] [--in <filename>]\n" + - " [--out <filename>] [--config <filename>]\n" + - " [--log <filename>] [--uuid <uuid>]\n" + - " [--curl] [--dryrun] [--verbose] [--version]\n" + - " [--list | --create | --update= | --delete |\n" + - " --checkout | --undocheckout | --checkin | --submit]\n" + - "\n" + - "Optional arguments:\n" + - " --help Show this help message and exit\n" + - " --url <url> REST endpoint URL\n" + - " --in <filename> Path to JSON input file (else STDIN)\n" + - " --out <filename> Path to JSON output file (else STDOUT or logfile)\n" + - " --config <filename> Path to configuration file\n" + - " --log <filename> Path to logfile (else STDOUT)\n" + - " --uuid <uuid> Action UUID, (=='actionInvariantUUID')\n" + - " --curl Use curl transport impl\n" + - " --dryrun Describe what will happen, execute nothing\n" + - " --verbose Verbose diagnostic output\n" + - " --version Print script version and exit\n" + - " --list List actions\n" + - " --create Create new action (requires --in)\n" + - " --update Update existing action (requires --uuid, --in)\n" + - " --delete Delete existing action (requires --uuid)\n" + - " --checkout Create minor version candidate (requires --uuid)\n" + - " --undocheckout Discard minor version candidate (requires --uuid)\n" + - " --checkin Create minor version from candidate (requires --uuid)\n" + - " --submit Create next major version (requires --uuid)") + "Usage: action_library_client.py [--help] [--url <url>] [--in <filename>]\n" + + " [--out <filename>] [--config <filename>]\n" + + " [--log <filename>] [--uuid <uuid>]\n" + + " [--curl] [--dryrun] [--verbose] [--version]\n" + + " [--list | --create | --update= | --delete |\n" + + " --checkout | --undocheckout | --checkin | --submit]\n" + + "\n" + + "Optional arguments:\n" + + " --help Show this help message and exit\n" + + " --url <url> REST endpoint URL\n" + + " --in <filename> Path to JSON input file (else STDIN)\n" + + " --out <filename> Path to JSON output file (else STDOUT or logfile)\n" + + " --config <filename> Path to configuration file\n" + + " --log <filename> Path to logfile (else STDOUT)\n" + + " --uuid <uuid> Action UUID, (=='actionInvariantUUID')\n" + + " --curl Use curl transport impl\n" + + " --dryrun Describe what will happen, execute nothing\n" + + " --verbose Verbose diagnostic output\n" + + " --version Print script version and exit\n" + + " --list List actions\n" + + " --create Create new action (requires --in)\n" + + " --update Update existing action (requires --uuid, --in)\n" + + " --delete Delete existing action (requires --uuid)\n" + + " --checkout Create minor version candidate (requires --uuid)\n" + + " --undocheckout Discard minor version candidate (requires --uuid)\n" + + " --checkin Create minor version from candidate (requires --uuid)\n" + + " --submit Create next major version (requires --uuid)") ############################################################################### @@ -533,7 +534,7 @@ class CURLRESTClient(IRESTClient): """Debug curl command, for diags and dryrun.""" buf = "" for token in cmd: - if token is "curl" or token.startswith("-"): + if token == "curl" or token.startswith("-"): buf = "{0}{1} ".format(buf, token) else: buf = "{0}\"{1}\" ".format(buf, token) @@ -556,7 +557,7 @@ class CURLRESTClient(IRESTClient): try: separator = output.index("\r\n\r\n{") self.logger.debug("HTTP preamble:\n{0}".format(output[:separator])) - json_body = json.loads(output[(separator+4):]) + json_body = json.loads(output[(separator + 4):]) self.log_json_response(method, json_body) return json_body except ValueError: diff --git a/openecomp-be/tools/build/scripts/parse-json.py b/openecomp-be/tools/build/scripts/parse-json.py index 46537ceac5..83c70aac01 100644 --- a/openecomp-be/tools/build/scripts/parse-json.py +++ b/openecomp-be/tools/build/scripts/parse-json.py @@ -41,17 +41,19 @@ from collections import OrderedDict def readJsonFile(file, type): - with open(file, 'r') as f: - data = json.load(f, object_pairs_hook=OrderedDict) - return data[type] + with open(file, 'r') as f: + data = json.load(f, object_pairs_hook=OrderedDict) + return data[type] + def printJsonTypeEntries(jsonData): - for i in jsonData.keys(): - print jsonData[i] + ';' + for i in jsonData.keys(): + print(jsonData[i] + ';') def usage(): - print 'parseJsonFile.py [-f <json-file> & -t <cql-type: drop|create|insert|update|select]' + print('parseJsonFile.py [-f <json-file> & -t <cql-type: drop|create|insert|update|select]') + def main(argv): action = '' diff --git a/openecomp-be/tools/migration/1607_to_1610.py b/openecomp-be/tools/migration/1607_to_1610.py index f46cb3a4b8..e817e3b1e6 100644 --- a/openecomp-be/tools/migration/1607_to_1610.py +++ b/openecomp-be/tools/migration/1607_to_1610.py @@ -1,6 +1,6 @@ #!/usr/bin/python import os -import sys,json,datetime,time,types,httplib,re +import sys, json, datetime, time, types, httplib, re import mimetypes DEFAULT_HOST = "127.0.0.1" @@ -13,49 +13,50 @@ DEFAULT_PASSWORD = "cs0008" ONBOARD_BASE_PATH = "/onboarding-api/v1.0" VSP_LIST_PATH = "{0}/vendor-software-products".format(ONBOARD_BASE_PATH) -VSP_ACTIONS_PATH = "{0}/vendor-software-products/{{vspId}}/actions".format(ONBOARD_BASE_PATH) +VSP_ACTIONS_PATH = "{0}/vendor-software-products/{{vspId}}/actions".format(ONBOARD_BASE_PATH) VSP_UPLOAD_PATH = "{0}/vendor-software-products/{{vspId}}/upload".format(ONBOARD_BASE_PATH) VSP_DOWNLOAD_PATH = "{0}/vendor-software-products/{{vspId}}/downloadHeat".format(ONBOARD_BASE_PATH) VSP_GET_URL = "{0}/vendor-software-products/{{vspId}}".format(ONBOARD_BASE_PATH) + def main(argv): - username=DEFAULT_USERNAME - password=DEFAULT_PASSWORD - host=DEFAULT_HOST + username = DEFAULT_USERNAME + password = DEFAULT_PASSWORD + host = DEFAULT_HOST if not argv: - print "Going to use default values" + print("Going to use default values") else: - if argv[0].lower() == 'h' or argv[0].lower() == '-h': - printHelp() - return - - if argv[0] == '-ip': - host=argv[1] - else: - if argv[0].lower() == '-a' and '/' not in argv[1]: - print '\n>>> Error: Credentials required (username/password)\n' - printHelp() - return - - else: - creds = argv[1].split('/') - username = creds[0] - password = creds[1] # not used - - try: - cmdIp=argv[2] - host=argv[3] - except IndexError: - host=DEFAULT_HOST - print "Going to use user defined values" + if argv[0].lower() == 'h' or argv[0].lower() == '-h': + printHelp() + return + + if argv[0] == '-ip': + host = argv[1] + else: + if argv[0].lower() == '-a' and '/' not in argv[1]: + print('\n>>> Error: Credentials required (username/password)\n') + printHelp() + return + + else: + creds = argv[1].split('/') + username = creds[0] + password = creds[1] # not used + + try: + cmdIp = argv[2] + host = argv[3] + except IndexError: + host = DEFAULT_HOST + print("Going to use user defined values") Service.server(host) - webHandler=WebHandler(host=host, port=DEFAULT_PORT) + webHandler = WebHandler(host=host, port=DEFAULT_PORT) response, headers = webHandler.rest(url=VSP_LIST_PATH, method='GET', data=None, userId=username) jResult = json.loads(response) jSrvices = jResult["results"] - reportFileName = 'upgradereport.csv' #datetime.now() + reportFileName = 'upgradereport.csv' # datetime.now() reportFile = open(reportFileName, 'w') reportFile.write(Service.header()) @@ -69,85 +70,91 @@ def main(argv): else: lockingUser = jService["lockingUser"] - service = Service(serviceName=serviceName, vspId=vspId, vendorName=vendorName, lockingUser=lockingUser ) - print service - # Will try to GET the service + service = Service(serviceName=serviceName, vspId=vspId, vendorName=vendorName, lockingUser=lockingUser) + print(service) + # Will try to GET the service res = service.Get() if res == 500: - serviceMigration(service, status, username) + serviceMigration(service, status, username) else: - print "Service {0} was tested and does not need a migration".format(serviceName) + print("Service {0} was tested and does not need a migration".format(serviceName)) reportFile.write(service.line()) reportFile.close() def serviceMigration(service, serviceStatus, username): - print "Service {0} was tested and it needs a migration".format(service.serviceName) - print "Service {0} - Migration start" - if serviceStatus == "Locked": - print "Service {0} is locked - forcing checkin".format(service.serviceName) - service.Checkin() - print "Doing new checkout" - service.Checkout(username) - - zipName = service.DownloadHeat() - if not zipName: - print "no heat found" - service.uploadStatus = "no heat found" - else: - uploadResponse = service.UploadHeat(zipName) - uploadResults = json.loads(uploadResponse) - if uploadResults['status'] == 'Success' and uploadResults['errors'].__len__() == 0: - service.uploadStatus = "Heat uploaded successfully" - else: - service.uploadStatus = "Heat uploaded with errors" - print "Doing new checkin" + print("Service {0} was tested and it needs a migration".format(service.serviceName)) + print("Service {0} - Migration start") + if serviceStatus == "Locked": + print("Service {0} is locked - forcing checkin".format(service.serviceName)) service.Checkin() + print("Doing new checkout") + service.Checkout(username) + + zipName = service.DownloadHeat() + if not zipName: + print("no heat found") + service.uploadStatus = "no heat found" + else: + uploadResponse = service.UploadHeat(zipName) + uploadResults = json.loads(uploadResponse) + if uploadResults['status'] == 'Success' and uploadResults['errors'].__len__() == 0: + service.uploadStatus = "Heat uploaded successfully" + else: + service.uploadStatus = "Heat uploaded with errors" + print("Doing new checkin") + service.Checkin() - print "Service {0} - Migration end" + print("Service {0} - Migration end") -def printHelp(): +def printHelp(): print("Upgrade script Help:") print("==================================") print("1607_to_1610 -h --> get help") print("1607_to_1610 -a <username>/<password> [-ip {ip}]") print("Example: 1607_to_1610 -a root/secret") + class Service(object): - def __init__(self, serviceName, vspId ,vendorName, lockingUser): + def __init__(self, serviceName, vspId, vendorName, lockingUser): self.serviceName = serviceName self.vspId = vspId self.vendorName = vendorName self.lockingUser = lockingUser - self.webHandler = WebHandler(host=Service.serveraddress, port=DEFAULT_PORT) # Schema? + self.webHandler = WebHandler(host=Service.serveraddress, port=DEFAULT_PORT) # Schema? self.uploadStatus = "not started" def __repr__(self): - return 'Name: {0}, Id: {1}, Vendor: {2}, locked by: {3}, status {4}'.format(self.serviceName, self.vspId ,self.vendorName, self.lockingUser, self.uploadStatus) + return 'Name: {0}, Id: {1}, Vendor: {2}, locked by: {3}, status {4}'.format(self.serviceName, self.vspId, + self.vendorName, self.lockingUser, + self.uploadStatus) + @classmethod def header(cls): return 'Name,Id,Vendor,locked-by,status\n' @classmethod def server(cls, address): - cls.serveraddress=address + cls.serveraddress = address def line(self): - return '{0},{1},{2},{3},{4}\n'.format(self.serviceName, self.vspId ,self.vendorName, self.lockingUser, self.uploadStatus) + return '{0},{1},{2},{3},{4}\n'.format(self.serviceName, self.vspId, self.vendorName, self.lockingUser, + self.uploadStatus) def Checkout(self, userId): # /v1.0/vendor-software-products/{vspId}/actions - urlpath=VSP_ACTIONS_PATH.format(vspId=self.vspId) - response, headers = self.webHandler.rest( url=urlpath, method='PUT', data={"action": "Checkout"}, userId=userId) - self.lockingUser=userId #we will later use this user to checkin + urlpath = VSP_ACTIONS_PATH.format(vspId=self.vspId) + response, headers = self.webHandler.rest(url=urlpath, method='PUT', data={"action": "Checkout"}, userId=userId) + self.lockingUser = userId # we will later use this user to checkin return response def Checkin(self): # /v1.0/vendor-software-products/{vspId}/actions urlpath = VSP_ACTIONS_PATH.format(vspId=self.vspId) - response, headers = self.webHandler.rest(url=urlpath, method='PUT', data={"action": "Checkin"}, userId=self.lockingUser) + response, headers = self.webHandler.rest(url=urlpath, method='PUT', data={"action": "Checkin"}, + userId=self.lockingUser) return response def Get(self): @@ -156,38 +163,39 @@ class Service(object): try: response, headers = self.webHandler.rest(url=urlpath, method='GET', data=None, userId=self.lockingUser) except HttpError as e: - print e.message + print(e.message) response = e.status return response def UploadHeat(self, zipName): - #/v1.0/vendor-software-products/{vspId}/upload - urlpath = VSP_UPLOAD_PATH.format(vspId=self.vspId) - try: - fields = [] - with open(zipName, 'rb') as fin: - buffer = fin.read() - fin.close() - files = [('upload', 'heatfile.zip', buffer)] - response = self.webHandler.post_multipart('HTTP', urlpath, fields, files, self.lockingUser) - - return response - finally: - print "done upload" + # /v1.0/vendor-software-products/{vspId}/upload + urlpath = VSP_UPLOAD_PATH.format(vspId=self.vspId) + try: + fields = [] + with open(zipName, 'rb') as fin: + buffer = fin.read() + fin.close() + files = [('upload', 'heatfile.zip', buffer)] + response = self.webHandler.post_multipart('HTTP', urlpath, fields, files, self.lockingUser) + + return response + finally: + print("done upload") def DownloadHeat(self): - urlpath=VSP_DOWNLOAD_PATH.format(vspId=self.vspId) + urlpath = VSP_DOWNLOAD_PATH.format(vspId=self.vspId) try: - response, headers = self.webHandler.rest(url=urlpath, method='Get', data=None, userId=self.lockingUser, accept='application/octet-stream') + response, headers = self.webHandler.rest(url=urlpath, method='Get', data=None, userId=self.lockingUser, + accept='application/octet-stream') except HttpError as e: if e.status == 404: return "" for (key, value) in headers: if key.lower() == "content-disposition": - file_name = value[value.index('=')+1:] + file_name = value[value.index('=') + 1:] break - heatsDir= os.path.join(os.path.dirname(__file__), 'heats') + heatsDir = os.path.join(os.path.dirname(__file__), 'heats') if not os.path.exists(heatsDir): os.makedirs(heatsDir) file_name = os.path.join(heatsDir, file_name) @@ -198,7 +206,6 @@ class Service(object): return file_name - class WebHandler(object): def __init__(self, host, port): self.host = host @@ -208,13 +215,13 @@ class WebHandler(object): connection = httplib.HTTPConnection(host=self.host, port=self.port) try: - headers = {'Content-Type':content_type ,'Accept':accept} + headers = {'Content-Type': content_type, 'Accept': accept} headers['USER_ID'] = userId connection.request(method=method, headers=headers, body=json.dumps(data), url=url) response = connection.getresponse() if response.status not in range(200, 300): - raise HttpError(status= response.status, message=response.reason) + raise HttpError(status=response.status, message=response.reason) return response.read(), response.getheaders() finally: @@ -241,7 +248,7 @@ class WebHandler(object): h.endheaders() h.send(body) errcode, errmsg, headers = h.getreply() - print errcode, errmsg, headers + print(errcode, errmsg, headers) return h.file.read() def encode_multipart_form_data(self, fields, files): @@ -268,14 +275,15 @@ class WebHandler(object): def get_content_type(self, filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream' + class HttpError(Exception): def __init__(self, status, message): self.status = status - self.message=message + self.message = message + def __str__(self): return repr(self.value, self.message) + if __name__ == "__main__": main(sys.argv[1:]) - - |