Example #1
0
    def getResponse(self,cmd,operation,classname,instance,keyValues, secureRequest = False ):
        if secureRequest:
            instance.set_protocol_type('https')            
        
        setFuncs=self.getSetFuncs(classname)
        if len(setFuncs)>0:
            for func in setFuncs:
                key=func.split('set_',1)[1]
                if len(key)>0 and key in keyValues:
                    arg=keyValues[key]
                    if arg is not None and len(arg)>0:
                        param=arg[0]
                        getattr(instance,func)(param)
        userKey=self.getUserKey()
        userSecret=self.getUserSecret()
        regionId=self.getRegionId(keyValues)
        userAgent=self.getUserAgent()
        port = self.getPort()
        module='aliyunsdkcore'
        try:
            from aliyunsdkcore import client
            from aliyunsdkcore.acs_exception.exceptions import ClientException  , ServerException
            Client=client.AcsClient(userKey,userSecret,regionId,True,3,userAgent,port)
            instance.set_accept_format('json')
            
            if hasattr(Client ,"do_action_with_exception"):
                result = Client.do_action_with_exception(instance)
            else:    
                result=Client.do_action(instance)
            jsonobj = json.loads(result)
            return jsonobj
        
        except ImportError as e:
            print module, 'is not exist!'
            sys.exit(1)            

        except ServerException as e:
            error = cliError.error()
            error.printInFormat(e.get_error_code(), e.get_error_msg())
            print "Detail of Server Exception:\n"
            print str(e)
            sys.exit(1)
        
        except ClientException as e:            
            # print e.get_error_msg()
            error = cliError.error()
            error.printInFormat(e.get_error_code(), e.get_error_msg())
            print "Detail of Client Exception:\n"
            print str(e)
            sys.exit(1)
Example #2
0
 def exportInstance(self,cmd,operation,version):
     if cmd.lower() == 'ecs' and operation.lower() =='exportinstance':
         operations = ['DescribeInstanceAttribute']
     else :
         return None
     _keyValues = self.parser.getCliKeyValues()
     # filename = self.getFileName(_keyValues)
     filename, errorMsg = self.getFileName(_keyValues)
     if filename is None:
         import cliError
         errorClass = cliError.error()
         errorClass.printInFormat(errorClass.CliException, errorMsg)
         return
     for item in operations:
         if self.apiHandler.isAvailableOperation(cmd, item, version):
             cmdInstance, mclassname = self.apiHandler.getInstanceByCmdOperation(cmd, item, version)
             if not cmdInstance is None:
                 newkeyValues = self.parser.getOpenApiKeyValues(_keyValues)
                 if self.apiHandler.needSetDefaultRegion(cmdInstance, newkeyValues):
                     newkeyValues["RegionId"] = [self.extensionHandler.getUserRegion()]
                 self.apiHandler.setAttr(cmdInstance, newkeyValues) # set all key values in instance
                 self.apiHandler.changeEndPoint(cmdInstance, newkeyValues)
                 try:
                     #result = cmdInstance.getResponse()
                     result = self.apiHandler.getResponse(cmd,operation, mclassname, cmdInstance, newkeyValues)
                     result = self._optimizeResult(result)
                     if("Code" in result):
                         response.display_response("error", result, "json")
                     else:
                         if not filename == None:
                             self.exportInstanceToFile(result,filename)
                         else:
                             print 'Filename is needed'
                 except Exception,e:
                     print(e)
Example #3
0
 def getResponse(self,cmd,operation,classname,instance,keyValues):
     setFuncs=self.getSetFuncs(classname)
     if len(setFuncs)>0:
         for func in setFuncs:
             key=func.split('set_',1)[1]
             if len(key)>0 and key in keyValues:
                 arg=keyValues[key]
                 if arg is not None and len(arg)>0:
                     param=arg[0]
                     getattr(instance,func)(param)
     userKey=self.getUserKey()
     userSecret=self.getUserSecret()
     regionId=self.getRegionId(keyValues)
     userAgent=self.getUserAgent()
     module='aliyunsdkcore'
     try:
         from aliyunsdkcore import client
         from aliyunsdkcore.acs_exception.exceptions import ClientException as exs
         Client=client.AcsClient(userKey,userSecret,regionId,True,3,userAgent)
         instance.set_accept_format('json')
         result=Client.do_action(instance)
         jsonobj = json.loads(result)
         return jsonobj
     except ImportError as e:
         print module, 'is not exist!'
         return
     except exs as e:
         # print e.get_error_msg()
         error = cliError.error()
         error.printInFormat(e.get_error_code(), e.get_error_msg())
         return
Example #4
0
def _getParamFromUrl(prefix, value, mode):

    req = urllib2.Request(value)
    try:
        response = urllib2.urlopen(req)
        if response.getcode() == 200:
            return response.read()
        else:
            errorClass = cliError.error()
            errorMsg = 'Get the wrong content'
            errorClass.printInFormat(response.getcode(), errorMsg)
    except Exception as e:
        print e
Example #5
0
def _getParamFromUrl(prefix,value,mode):

    req = urllib2.Request(value)
    try:
        response=urllib2.urlopen(req)
        if response.getcode() == 200:
            return response.read()
        else:
            errorClass = cliError.error()
            errorMsg='Get the wrong content'
            errorClass.printInFormat(response.getcode(), errorMsg)
    except Exception as e:
        print e
Example #6
0
def _getParamFromFile(prefix, value, mode):
    path = value[len(prefix):]
    path = os.path.expanduser(path)
    path = os.path.os.path.expandvars(path)
    if not os.path.isfile(path):
        errorClass = cliError.error()
        errorMsg = 'file is not exist'
        errorClass.printInFormat(errorClass.CliException, errorMsg)
    try:
        with open(path, mode) as f:
            data = f.read()
            return data
    except (OSError, IOError) as e:
        print e
Example #7
0
 def importInstance(self,cmd,operation,version,secureRequest = False):
     _keyValues = self.parser.getCliKeyValues()
     operations = self.getSubOperations(cmd,operation)
     _instanceCount, countMsg = self.getInstanceCount(_keyValues)
     filename, errorMsg = self.getFileName(_keyValues)
     if filename is None:
         import cliError
         errorClass = cliError.error()
         errorClass.printInFormat(errorClass.CliException, errorMsg)
         return
     keyValues = self.getKVFromJson(filename)
     keyValues['PayType'] = ["Postpaid"]
     for i in range(1,_instanceCount+1):
         self._handSubOperation(cmd,operations,keyValues,version,secureRequest)
Example #8
0
 def importInstance(self,cmd,operation,version):
     _keyValues = self.parser.getCliKeyValues()
     operations = self.getSubOperations(cmd,operation)
     _instanceCount, countMsg = self.getInstanceCount(_keyValues)
     filename, errorMsg = self.getFileName(_keyValues)
     if filename is None:
         import cliError
         errorClass = cliError.error()
         errorClass.printInFormat(errorClass.CliException, errorMsg)
         return
     keyValues = self.getKVFromJson(filename)
     keyValues['PayType'] = ["Postpaid"]
     for i in range(1,_instanceCount+1):
         self._handSubOperation(cmd,operations,keyValues,version)
Example #9
0
def _getParamFromFile(prefix,value,mode):
    path=value[len(prefix):]
    path = os.path.expanduser(path)
    path = os.path.os.path.expandvars(path)
    if not os.path.isfile(path):
        errorClass = cliError.error()
        errorMsg='file is not exist'
        errorClass.printInFormat(errorClass.CliException, errorMsg)
    try:
        with open(path, mode) as f:
            data = f.read()
            return data
    except (OSError, IOError) as e:
        print e
Example #10
0
 def getSdkVersion(self,cmd,keyValues):
     tempVersion=self.getTempVersion(keyValues)
     versions=self.getAllVersionsByCmdName(cmd)
     if tempVersion is not None and len(tempVersion)>0:
         if tempVersion[0] in versions:
             return tempVersion[0]
         else:
             # show error
             error = cliError.error()
             error.printInFormat("Wrong version", "The version input is not exit.")
             return None
     configVersion=self.getVersionFromFile(cmd)
     if configVersion is not None:
         return configVersion
     defaultVersion=self.getLatestVersion(versions)
     if defaultVersion is not None:
         return defaultVersion
 def exportDBInstance(self, cmd, operation, version):
     rdsConfigure = commandConfigure.rds()
     if cmd.lower() == rdsConfigure.cmdName.lower() and operation.lower(
     ) == rdsConfigure.exportDBInstance.lower():
         pass
     else:
         return None
     _keyValues = self.parser.getCliKeyValues()
     filename, errorMsg = self.getFileName(_keyValues)
     if filename is None:
         import cliError
         errorClass = cliError.error()
         errorClass.printInFormat(errorClass.CliException, errorMsg)
         return
     operation = self.operations[0]
     if self.apiHandler.isAvailableOperation(cmd, operation, version):
         cmdInstance, mclassname = self.apiHandler.getInstanceByCmdOperation(
             cmd, operation, version)
         if not cmdInstance is None:
             newkeyValues = self.parser.getOpenApiKeyValues(_keyValues)
             if self.apiHandler.needSetDefaultRegion(
                     cmdInstance, newkeyValues):
                 newkeyValues["RegionId"] = [
                     self.extensionHandler.getUserRegion()
                 ]
             self.apiHandler.setAttr(
                 cmdInstance,
                 newkeyValues)  # set all key values in instance
             self.apiHandler.changeEndPoint(cmdInstance, newkeyValues)
             try:
                 result = self.apiHandler.getResponse(
                     cmd, operation, mclassname, cmdInstance, newkeyValues)
                 self.apiHandler.responseOptimize(result, cmd, operation)
                 # result = cmdInstance.getResponse()
                 # result = self._optimizeResult(result)
                 if ("Code" in result):
                     response.display_response("error", result, "json")
                 else:
                     if not filename == None:
                         self.exportInstanceToFile(result, filename)
                     else:
                         print 'Filename is needed'
             except Exception, e:
                 print(e)
Example #12
0
 def exportInstance(self, cmd, operation, version):
     if cmd.lower() == 'ecs' and operation.lower() == 'exportinstance':
         operations = ['DescribeInstanceAttribute']
     else:
         return None
     _keyValues = self.parser.getCliKeyValues()
     # filename = self.getFileName(_keyValues)
     filename, errorMsg = self.getFileName(_keyValues)
     if filename is None:
         import cliError
         errorClass = cliError.error()
         errorClass.printInFormat(errorClass.CliException, errorMsg)
         return
     for item in operations:
         if self.apiHandler.isAvailableOperation(cmd, item, version):
             cmdInstance, mclassname = self.apiHandler.getInstanceByCmdOperation(
                 cmd, item, version)
             if not cmdInstance is None:
                 newkeyValues = self.parser.getOpenApiKeyValues(_keyValues)
                 if self.apiHandler.needSetDefaultRegion(
                         cmdInstance, newkeyValues):
                     newkeyValues["RegionId"] = [
                         self.extensionHandler.getUserRegion()
                     ]
                 self.apiHandler.setAttr(
                     cmdInstance,
                     newkeyValues)  # set all key values in instance
                 self.apiHandler.changeEndPoint(cmdInstance, newkeyValues)
                 try:
                     #result = cmdInstance.getResponse()
                     result = self.apiHandler.getResponse(
                         cmd, operation, mclassname, cmdInstance,
                         newkeyValues)
                     result = self._optimizeResult(result)
                     if ("Code" in result):
                         response.display_response("error", result, "json")
                     else:
                         if not filename == None:
                             self.exportInstanceToFile(result, filename)
                         else:
                             print 'Filename is needed'
                 except Exception, e:
                     print(e)
Example #13
0
 def showOperationError(self, cmd, operation):
     keyValues=self.openApiDataHandler.parser._getKeyValues()
     version = self.openApiDataHandler.getSdkVersion(cmd,keyValues)
     versions=self.openApiDataHandler.getAllVersionsByCmdName(cmd)
     if version not in versions:
             error = cliError.error()
             error.printInFormat("Wrong version", "The sdk version is not exit.")
             return None
     self.showUsage()
     print "["+cmd+"]","valid operations as follows:\n"
     operations = self.openApiDataHandler.getApiOperations(cmd, version)
     extensions = self.openApiDataHandler.getExtensionOperationsFromCmd(cmd)
     operations.update(extensions)
     import commandConfigure
     if cmd.lower() == 'rds':
         rdsConfigure = commandConfigure.rds()
         operations.add(rdsConfigure.exportDBInstance)
         operations.add(rdsConfigure.importDBInstance)
     self.printAsFormat(operations)
Example #14
0
 def showOperationError(self, cmd, operation):
     keyValues = self.openApiDataHandler.parser._getKeyValues()
     version = self.openApiDataHandler.getSdkVersion(cmd, keyValues)
     versions = self.openApiDataHandler.getAllVersionsByCmdName(cmd)
     if version not in versions:
         error = cliError.error()
         error.printInFormat("Wrong version",
                             "The sdk version is not exit.")
         return None
     self.showUsage()
     print "[" + cmd + "]", "valid operations as follows:\n"
     operations = self.openApiDataHandler.getApiOperations(cmd, version)
     extensions = self.openApiDataHandler.getExtensionOperationsFromCmd(cmd)
     operations.update(extensions)
     import commandConfigure
     if cmd.lower() == 'rds':
         rdsConfigure = commandConfigure.rds()
         operations.add(rdsConfigure.exportDBInstance)
         operations.add(rdsConfigure.importDBInstance)
     self.printAsFormat(operations)
Example #15
0
 def exportDBInstance(self, cmd, operation, version):
     rdsConfigure = commandConfigure.rds()
     if cmd.lower() == rdsConfigure.cmdName.lower() and operation.lower() ==rdsConfigure.exportDBInstance.lower():
         pass
     else :
         return None
     _keyValues = self.parser.getCliKeyValues()
     filename, errorMsg = self.getFileName(_keyValues)
     if filename is None:
         import cliError
         errorClass = cliError.error()
         errorClass.printInFormat(errorClass.CliException, errorMsg)
         return
     operation = self.operations[0]
     if self.apiHandler.isAvailableOperation(cmd, operation, version):
         cmdInstance, mclassname = self.apiHandler.getInstanceByCmdOperation(cmd, operation, version)
         if not cmdInstance is None:
             newkeyValues = self.parser.getOpenApiKeyValues(_keyValues)
             if self.apiHandler.needSetDefaultRegion(cmdInstance, newkeyValues):
                 newkeyValues["RegionId"] = [self.extensionHandler.getUserRegion()]
             self.apiHandler.setAttr(cmdInstance, newkeyValues) # set all key values in instance
             self.apiHandler.changeEndPoint(cmdInstance, newkeyValues)
             try:
                 result = self.apiHandler.getResponse(cmd,operation, mclassname, cmdInstance, newkeyValues)
                 self.apiHandler.responseOptimize(result,cmd,operation)
                 # result = cmdInstance.getResponse()
                 # result = self._optimizeResult(result)
                 if("Code" in result):
                     response.display_response("error", result, "json")
                 else:
                     if not filename == None:
                         self.exportInstanceToFile(result,filename)
                     else:
                         print 'Filename is needed'
             except Exception,e:
                 print(e)
    def getResponse(self,
                    cmd,
                    operation,
                    classname,
                    instance,
                    keyValues,
                    secureRequest=False):
        if secureRequest:
            instance.set_protocol_type('https')

        setFuncs = self.getSetFuncs(classname)
        if len(setFuncs) > 0:
            for func in setFuncs:
                key = func.split('set_', 1)[1]
                if len(key) > 0 and key in keyValues:
                    arg = keyValues[key]
                    if arg is not None and len(arg) > 0:
                        param = arg[0]
                        try:
                            getattr(instance, func)(param)
                        except AttributeError as e:
                            # When the param is a json string, and it's handled as a 'repeat list',
                            # set it in the string format will raise AttributeError
                            # in this case, handle it in the json format
                            # FIXME
                            if str(e) == "'str' object has no attribute 'get'":
                                try:
                                    param_in_obj = json.loads(param)
                                except ValueError:
                                    raise Exception(
                                        "Can not handle param %s: not a valid json string"
                                        % key)
                                getattr(instance, func)(param_in_obj)
                            else:
                                raise e
        userKey = self.getUserKey()
        userSecret = self.getUserSecret()
        regionId = self.getRegionId(keyValues)
        userAgent = self.getUserAgent()
        port = self.getPort()
        module = 'aliyunsdkcore'
        try:
            from aliyunsdkcore import client
            from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException
            Client = client.AcsClient(userKey, userSecret, regionId, True, 3,
                                      userAgent, port)
            instance.set_accept_format('json')

            if hasattr(Client, "do_action_with_exception"):
                result = Client.do_action_with_exception(instance)
            else:
                result = Client.do_action(instance)
            jsonobj = json.loads(result)
            return jsonobj

        except ImportError as e:
            print module, 'is not exist!'
            sys.exit(1)

        except ServerException as e:
            error = cliError.error()
            error.printInFormat(e.get_error_code(), e.get_error_msg())
            print "Detail of Server Exception:\n"
            print str(e)
            sys.exit(1)

        except ClientException as e:
            # print e.get_error_msg()
            error = cliError.error()
            error.printInFormat(e.get_error_code(), e.get_error_msg())
            print "Detail of Client Exception:\n"
            print str(e)
            sys.exit(1)