Python jsonrpclib.ProtocolError() Examples

The following are code examples for showing how to use jsonrpclib.ProtocolError(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: eapi_2_acl.py    MIT License 6 votes vote down vote up
def applyChanges(aclName, apiEndpoints, aclRules):
   """ Given the switch mapping and a list of the new ACL rules, apply
   the ACL to each switch """
   cmdList = ["enable",
              "configure",
              # Not the most efficient way to clear an ACL:
                 "no ip access-list %s" % aclName,
              # Now enter configuration mode for the ACL:
                 "ip access-list %s" % aclName]
   cmdList = cmdList + aclRules + ["exit"]
   
   for hostname, apiEndpoint in apiEndpoints.iteritems():
      print "Updating access list on switch", hostname, "....",
      try:
         apiEndpoint.runCmds(1, cmdList)
      except jsonrpclib.ProtocolError as e:
         print "[ERROR]"
         print "  ", e
         # jsonrpclib isn't very friendly at getting the error data as
         # specified by the spec. This is a shortcut for getting the
         # last error:
         errorResponse = jsonrpclib.loads(jsonrpclib.history.response)
         print "   Details:", errorResponse["error"]["data"][-1]["errors"]
      else:
         print "[SUCCESS]" 
Example 2
Project: trex-http-proxy   Author: alwye   File: trex_exceptions.py    MIT License 6 votes vote down vote up
def gen_exception (self, err):
        """
        Generates an exception based on a general ProtocolError exception object `err`. 

        When TRex is reserved, no other user can start new TRex runs.

                
        :parameters:
        
         err : exception
            a ProtocolError exception raised by :class:`trex_client.CTRexClient` class

        :return: 
         A TRex exception from the exception list defined in class creation.

         If such exception wasn't found, returns a TRexException exception

        """
        code, message, data = err
        try:
            exp = self.exceptions_dict[code]
            return exp(exp.code, message, data)
        except KeyError:
            # revert to TRexException when unknown error application raised
             return TRexException(err) 
Example 3
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 6 votes vote down vote up
def get_trex_files_path (self):
        """
        Fetches the local path in which files are stored when pushed to TRex server from client.

        :parameters:        
            None

        :return: 
            string representation of the desired path

            .. note::  The returned path represents a path on the TRex server **local machine**

        :raises:
            ProtocolError, in case of error in JSON-RPC protocol.

        """
        try:
            return (self.server.get_files_path() + '/')
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 4
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 6 votes vote down vote up
def is_reserved (self):
        """
        Checks if TRex is currently reserved to any user or not.

        :parameters:        
            None

        :return: 
            + **True** if TRex is reserved.
            + **False** otherwise.

        :raises:
            ProtocolError, in case of error in JSON-RPC protocol.

        """
        try:
            return self.server.is_reserved()
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 5
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 6 votes vote down vote up
def get_trex_daemon_log (self):
        """
        Get Trex daemon log.

        :return: 
            String representation of TRex daemon log

        :raises:
            + :exc:`trex_exceptions.TRexRequestDenied`, in case file could not be read.
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        try:
            res = binascii.a2b_base64(self.server.get_trex_daemon_log())
            if type(res) is bytes:
                return res.decode()
            return res
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 6
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 6 votes vote down vote up
def get_trex_log (self):
        """
        Get TRex CLI output log

        :return: 
            String representation of TRex log

        :raises:
            + :exc:`trex_exceptions.TRexRequestDenied`, in case file could not be fetched at server side.
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        try:
            res = binascii.a2b_base64(self.server.get_trex_log())
            if type(res) is bytes:
                return res.decode()
            return res
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 7
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 6 votes vote down vote up
def get_files_list (self, path):
        """
        Gets a list of dirs and files either from /tmp/trex_files or path relative to TRex server.

        :parameters:
            path : str
                a path to directory to read.

        :return: 
            Tuple: list of dirs and list of files in given path

        :raises:
            + :exc:`trex_exceptions.TRexRequestDenied`, in case TRex is reserved for another user than the one trying to cancel the reservation.
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        
        try:
            return self.server.get_files_list(path)
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 8
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 6 votes vote down vote up
def get_file(self, filepath):
        """
        Gets content of file as bytes string from /tmp/trex_files or TRex server directory.

        :parameters:
            filepath : str
                a path to a file at server.
                it can be either relative to TRex server or absolute path starting with /tmp/trex_files

        :return: 
            Content of the file

        :raises:
            + :exc:`trex_exceptions.TRexRequestDenied`, in case TRex is reserved for another user than the one trying to cancel the reservation.
            + ProtocolError, in case of error in JSON-RPC protocol.
        """

        try:
            return binascii.a2b_base64(self.server.get_file(filepath))
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 9
Project: Mastering-Python-Networking-Third-Edition   Author: PacktPublishing   File: eapi_2_acl.py    MIT License 6 votes vote down vote up
def applyChanges(aclName, apiEndpoints, aclRules):
   """ Given the switch mapping and a list of the new ACL rules, apply
   the ACL to each switch """
   cmdList = ["enable",
              "configure",
              # Not the most efficient way to clear an ACL:
                 "no ip access-list %s" % aclName,
              # Now enter configuration mode for the ACL:
                 "ip access-list %s" % aclName]
   cmdList = cmdList + aclRules + ["exit"]
   
   for hostname, apiEndpoint in apiEndpoints.iteritems():
      print "Updating access list on switch", hostname, "....",
      try:
         apiEndpoint.runCmds(1, cmdList)
      except jsonrpclib.ProtocolError as e:
         print "[ERROR]"
         print "  ", e
         # jsonrpclib isn't very friendly at getting the error data as
         # specified by the spec. This is a shortcut for getting the
         # last error:
         errorResponse = jsonrpclib.loads(jsonrpclib.history.response)
         print "   Details:", errorResponse["error"]["data"][-1]["errors"]
      else:
         print "[SUCCESS]" 
Example 10
Project: taf   Author: taf3   File: ui_onpss_jsonrpc.py    Apache License 2.0 6 votes vote down vote up
def request(self, method="", params=None):
        """Send and receive the JSON-RPC strings.

        Args:
            method(str):  name of the method to be invoked
            params(dict):  parameter values to be used during the invocation of the method

        Raises:
            UIException:  error in reply

        Returns:
            dict | list:  Result of method

        """
        result = None
        if params is None:
            params = {}
        try:
            result = self.jsonrpc._request(method, params)  # pylint: disable=protected-access
        except jsonrpclib.ProtocolError as err:
            message = "{0} command with parameters {1} returned error {2[0]}: {2[1]}".format(method, params, err.args[0])
            raise UIException(message)
        return result 
Example 11
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def add (self, x, y):
        try:
            return self.server.add(x,y)
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 12
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def stop_trex (self):
        """
        Request to stop a TRex run on server.

        The request is only valid if the stop initiator is the same client as the TRex run initiator.
                
        :parameters:        
            None

        :return: 
            + **True** on successful termination 
            + **False** if request issued but TRex wasn't running.

        :raises:
            + :exc:`trex_exceptions.TRexRequestDenied`, in case TRex ir running but started by another user.
            + :exc:`trex_exceptions.TRexIncompleteRunError`, in case one of failed TRex run (unexpected termination).
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        try:
            return self.server.stop_trex(self.seq)
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 13
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def force_kill (self, confirm = True):
        """
        Force killing of running TRex process (if exists) on the server.

        .. tip:: This method is a safety method and **overrides any running or reserved resources**, and as such isn't designed to be used on a regular basis. 
                 Always consider using :func:`trex_client.CTRexClient.stop_trex` instead.

        In the end of this method, TRex will return to IDLE state with no reservation.
        
        :parameters:        
            confirm : bool
                Prompt a user confirmation before continue terminating TRex session

        :return: 
            + **True** on successful termination 
            + **False** otherwise.

        :raises:
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        if confirm:
            prompt = "WARNING: This will terminate active TRex session indiscriminately.\nAre you sure? "
            sys.stdout.write('%s [y/n]\n' % prompt)
            while True:
                try:
                    if strtobool(user_input().lower()):
                        break
                    else:
                        return
                except ValueError:
                    sys.stdout.write('Please respond with \'y\' or \'n\'.\n')
        try:
            return self.server.force_trex_kill()
        except AppError as err:
            # Silence any kind of application errors- by design
            return False
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 14
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def is_running (self, dump_out = False):
        """
        Poll for TRex running status.

        If TRex is running, a history item will be added into result_obj and processed.

        .. tip:: This method is especially useful for iterating until TRex run is finished.

        :parameters:        
            dump_out : dict
                if passed, the pointer object is cleared and the latest dump stored in it.

        :return: 
            + **True** if TRex is running.
            + **False** if TRex is not running.

        :raises:
            + :exc:`trex_exceptions.TRexIncompleteRunError`, in case one of failed TRex run (unexpected termination).
            + :exc:`TypeError`, in case JSON stream decoding error.
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        try:
            res = self.get_running_info()
            if res == {}:
                return False
            if (dump_out != False) and (isinstance(dump_out, dict)):        # save received dump to given 'dump_out' pointer
                dump_out.clear()
                dump_out.update(res)
            return True
        except TRexWarning as err:
            if err.code == -12:      # TRex is either still at 'Starting' state or in Idle state, however NO error occured
                return False
        except TRexException:
            raise
        except ProtocolError as err:
            raise
        #is printed by self.get_running_info()
        #finally:
        #    self.prompt_verbose_data() 
Example 15
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def is_idle (self):
        """
        Poll for TRex running status, check if TRex is in Idle state.

        :parameters:
            None

        :return: 
            + **True** if TRex is idle.
            + **False** if TRex is starting or running.

        :raises:
            + :exc:`trex_exceptions.TRexIncompleteRunError`, in case one of failed TRex run (unexpected termination).
            + :exc:`TypeError`, in case JSON stream decoding error.
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        try:
            if self.get_running_status()['state'] == TRexStatus.Idle:
                return True
            return False
        except TRexException:
            raise
        except ProtocolError as err:
            raise
        finally:
            self.prompt_verbose_data() 
Example 16
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def get_running_status (self):
        """
        Fetches the current TRex status.

        If available, a verbose data will accompany the state itself.

        :parameters:        
            None

        :return: 
            dictionary with 'state' and 'verbose' keys.

        :raises:
            ProtocolError, in case of error in JSON-RPC protocol.

        """
        try:
            res = self.server.get_running_status()
            res['state'] = TRexStatus(res['state'])
            return res
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 17
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def get_running_info (self):
        """
        Performs single poll of TRex running data and process it into the result object (named `result_obj`).

        .. tip:: This method will throw an exception if TRex isn't running. Always consider using :func:`trex_client.CTRexClient.is_running` which handles a single poll operation in safer manner.

        :parameters:        
            None

        :return: 
            dictionary containing the most updated data dump from TRex.

        :raises:
            + :exc:`trex_exceptions.TRexIncompleteRunError`, in case one of failed TRex run (unexpected termination).
            + :exc:`TypeError`, in case JSON stream decoding error.
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        if not self.is_query_relevance():
            # if requested in timeframe smaller than the original sample rate, return the last known data without interacting with server
            return self.result_obj.get_latest_dump()
        else:
            try: 
                latest_dump = self.decoder.decode( self.server.get_running_info() ) # latest dump is not a dict, but json string. decode it.
                self.result_obj.update_result_data(latest_dump)
                return latest_dump
            except TypeError as inst:
                raise TypeError('JSON-RPC data decoding failed. Check out incoming JSON stream.')
            except AppError as err:
                self._handle_AppError_exception(err.args[0])
            except ProtocolError:
                raise
            finally:
                self.prompt_verbose_data() 
Example 18
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def sample_to_run_finish (self, time_between_samples = 5):
        """
        Automatically sets automatically sampling of TRex data with sampling rate described by time_between_samples until TRex run finished.

        :parameters:        
            time_between_samples : int
                determines the time between each sample of the server

                default value : **5**

        :return: 
            the latest result object (see :class:`CTRexResult` for further details) with sampled data.

        :raises:
            + :exc:`UserWarning`, in case the condition_func method condition hasn't been met
            + :exc:`trex_exceptions.TRexIncompleteRunError`, in case one of failed TRex run (unexpected termination).
            + :exc:`TypeError`, in case JSON stream decoding error.
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        self.wait_until_kickoff_finish()    
        
        try: 
            while self.is_running():
                time.sleep(time_between_samples)
        except TRexWarning:
            pass
        results = self.get_result_obj()
        return results 
Example 19
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def sample_x_seconds (self, sample_time, time_between_samples = 5):
        """
        Automatically sets ongoing sampling of TRex data for sample_time seconds, with sampling rate described by time_between_samples.
        Does not stop the TRex afterwards!

        .. tip:: Useful for changing the device (Router, ASA etc.) configuration after given time.

        :parameters:
            sample_time : int
                sample the TRex this number of seconds

            time_between_samples : int
                determines the time between each sample of the server

                default value : **5**

        :return:
            the first result object (see :class:`CTRexResult` for further details) of the TRex run after given sample_time.

        :raises:
            + :exc:`UserWarning`, in case the TRex run ended before sample_time duration
            + :exc:`trex_exceptions.TRexIncompleteRunError`, in case one of failed TRex run (unexpected termination).
            + :exc:`TypeError`, in case JSON stream decoding error.
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        # make sure TRex is running. raise exceptions here if any
        self.wait_until_kickoff_finish()
        elapsed_time = 0
        while self.is_running():
            if elapsed_time >= sample_time:
                return self.get_result_obj()
            time.sleep(time_between_samples)
            elapsed_time += time_between_samples
        raise UserWarning("TRex has stopped at %s seconds (before expected %s seconds)\nTry increasing test duration or decreasing sample_time" % (elapsed_time, sample_time)) 
Example 20
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def reserve_trex (self, user = None):
        """
        Reserves the usage of TRex to a certain user.

        When TRex is reserved, it can't be reserved.
                
        :parameters:        
            user : str
                a username of the desired owner of TRex

                default: current logged user

        :return: 
            **True** if reservation made successfully

        :raises:
            + :exc:`trex_exceptions.TRexRequestDenied`, in case TRex is reserved for another user than the one trying to make the reservation.
            + :exc:`trex_exceptions.TRexInUseError`, in case TRex is currently running.
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        username = user or self.__default_user
        try:
            return self.server.reserve_trex(user = username)
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 21
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def cancel_reservation (self, user = None):
        """
        Cancels a current reservation of TRex to a certain user.

        When TRex is reserved, no other user can start new TRex runs.

                
        :parameters:        
            user : str
                a username of the desired owner of TRex

                default: current logged user

        :return: 
            + **True** if reservation canceled successfully, 
            + **False** if there was no reservation at all.

        :raises:
            + :exc:`trex_exceptions.TRexRequestDenied`, in case TRex is reserved for another user than the one trying to cancel the reservation.
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        
        username = user or self.__default_user
        try:
            return self.server.cancel_reservation(user = username)
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data() 
Example 22
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 5 votes vote down vote up
def push_files (self, filepaths):
        """
        Pushes a file (or a list of files) to store locally on server. 
                
        :parameters:        
            filepaths : str or list
                a path to a file to be pushed to server.
                if a list of paths is passed, all of those will be pushed to server

        :return: 
            + **True** if file(s) copied successfully.
            + **False** otherwise.

        :raises:
            + :exc:`IOError`, in case specified file wasn't found or could not be accessed.
            + ProtocolError, in case of error in JSON-RPC protocol.

        """
        paths_list = None
        if isinstance(filepaths, str):
            paths_list = [filepaths]
        elif isinstance(filepaths, list):
            paths_list = filepaths
        else:
            raise TypeError("filepaths argument must be of type str or list")
        
        for filepath in paths_list:
            try:
                if not os.path.exists(filepath):
                    raise IOError(errno.ENOENT, "The requested `{fname}` file wasn't found. Operation aborted.".format(
                        fname = filepath) )
                else:
                    filename = os.path.basename(filepath)
                    with open(filepath, 'rb') as f:
                        file_content = f.read()
                        self.server.push_file(filename, binascii.b2a_base64(file_content).decode())
            finally:
                self.prompt_verbose_data()
        return True 
Example 23
Project: pyeos   Author: spotify   File: eos.py    Apache License 2.0 4 votes vote down vote up
def run_commands(self, commands, version=1, auto_format=False, format='json', timestamps=True):
        """
        This method will run as many commands as you want. The 'enable' command will be prepended automatically so you
        don't have to worry about that.

        :param commands: List of commands you want to run
        :param version: Version of the eAPI you want to connect to. By default is 1.
        :param auto_format: If set to True API calls not supporting returning JSON messages will be converted automatically to text. By default is False.
        :param format: Format you want to get; 'json' or 'text'. By default is json. This will trigger a CommandUnconverted exception if set to 'json' and auto_format is set to False. It will return text if set to 'json' but auto_format is set to True.
        :param timestamps: This will return some useful information like when was the command executed and how long it took.

        """

        if 'enable' is not commands[0]:
            commands.insert(0, 'enable')

        if auto_format:
            format = 'json'

        try:
            result = self.device.runCmds(
                version=version,
                cmds=commands,
                format=format,
                timestamps=timestamps,
            )
        except ProtocolError as e:
            code = e[0][0]
            error = e[0][1]

            if code == 1003:
                # code 1003 means the command is not yet converted to json
                if auto_format:
                    result = self.device.runCmds(
                        version=version,
                        cmds=commands,
                        format='text',
                        timestamps=timestamps
                    )
                else:
                    raise exceptions.CommandUnconverted(error)
            # code -32602 means "Unexpected parameter 'timestamps' for method 'runCmds' provided"
            elif code == -32602:
                result = self.device.runCmds(
                    version=version,
                    cmds=commands,
                    format=format
                )
            elif code == 1002:
                # code 1002 means the command was wrong
                raise exceptions.CommandError(error)
            elif code == 1000:
                # code 1000 means a command is wrong when doing a "config  replace"
                raise exceptions.ConfigReplaceError(e)
            else:
                raise exceptions.UnknownError((code, error))

        return result 
Example 24
Project: dom   Author: aristanetworks   File: dom.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get_interfaces(switch):
    """Get all of the interfaces on a switch.
    Get summary info on all of the interfaces in a switch and return a
        dictionary keyed on interface name.  NOTE: the interfaceIDs are
        missing the space between the interface type and the number.
    args:
        switch (object): A :class:`jsonrpclib` Server object
    returns:
        dict: Dictionary, keyed on interface name (without space), of interface
            summary information."
    Example:
        {u'Ethernet1': {u'autoNegotigateActive': False,
                        u'bandwidth': 10000000000,
                        u'description': u'',
                        u'duplex': u'duplexFull',
                        u'interfaceType': u'EbraTestPhyPort',
                        u'linkStatus': u'connected',
                        u'vlanInformation': {u'interfaceForwardingModel': u'bridged',
                                             u'interfaceMode': u'bridged',
                                             u'vlanId': 1}},
        u'Ethernet2': {u'autoNegotigateActive': False,
                       u'bandwidth': 10000000000,
                       u'description': u'',
                       u'duplex': u'duplexFull',
                       u'interfaceType': u'EbraTestPhyPort',
                       u'linkStatus': u'connected',
                       u'vlanInformation': {u'interfaceForwardingModel': u'bridged',
                                            u'interfaceMode': u'bridged',
                                            u'vlanId': 1}}
    """

    log("Entering {0}.".format(sys._getframe().f_code.co_name), level='DEBUG')
    conn_error = False
    commands = ["show interfaces status"]

    try:
        response = switch.runCmds(1, commands)
    except ProtocolError, err:
        (errno, msg) = err[0]
        # 1002: invalid command
        if errno == 1002:
            log("Invalid EOS interface name ({0})".format(commands), error=True)
        else:
            conn_error = True
            log("ProtocolError while retrieving {0} ([{1}] {2})".
                format(commands, errno, msg),
                error=True) 
Example 25
Project: trex-http-proxy   Author: alwye   File: trex_client.py    MIT License 4 votes vote down vote up
def start_stateless(self, block_to_success = True, timeout = 40, user = None, **trex_cmd_options):
        """
        Request to start a TRex run on server in stateless mode.
                
        :parameters:  
            block_to_success : bool
                determine if this method blocks until TRex changes state from 'Starting' to either 'Idle' or 'Running'

                default value : **True**
            timeout : int
                maximum time (in seconds) to wait in blocking state until TRex changes state from 'Starting' to either 'Idle' or 'Running'

                default value: **40**
            user : str
                the identity of the the run issuer.
            trex_cmd_options : key, val
                sets desired TRex options using key=val syntax, separated by comma.
                for keys with no value, state key=True

        :return: 
            **True** on success

        :raises:
            + :exc:`trex_exceptions.TRexError`, in case one of the trex_cmd_options raised an exception at server.
            + :exc:`trex_exceptions.TRexInUseError`, in case TRex is already taken.
            + :exc:`trex_exceptions.TRexRequestDenied`, in case TRex is reserved for another user than the one trying start TRex.
            + ProtocolError, in case of error in JSON-RPC protocol.
        
        """
        try:
            user = user or self.__default_user
            retval = self.server.start_trex(trex_cmd_options, user, block_to_success, timeout, True)
        except AppError as err:
            self._handle_AppError_exception(err.args[0])
        except ProtocolError:
            raise
        finally:
            self.prompt_verbose_data()

        if retval!=0:   
            self.seq = retval   # update seq num only on successful submission
            return True
        else:   # TRex is has been started by another user
            raise TRexInUseError('TRex is already being used by another user or process. Try again once TRex is back in IDLE state.') 
Example 26
Project: taf   Author: taf3   File: ui_onpss_jsonrpc.py    Apache License 2.0 4 votes vote down vote up
def multicall(self, calls_list):
        """Sends a list of commands.

        Args:
            calls_list(list(dict(("method",str),("params", list)))):  List of dictionaries for necessary JSON-RPC calls

        Raises:
            UIException:  incorrect key in call_list, error in reply

        Returns:
            list(int | boolean | list | dict):  List of responses

        Examples::

            env.switch[1].ui.multicall([{'method': 'getSwitchPortInfo', 'params': [{'component': '0', 'portIdentifier': 'sw0p1'},
                                                                                   {'component': '0', 'portIdentifier': 'sw0p2'}]}, ])

            env.switch[1].ui.multicall([{'method': 'getSwitchInfo', 'params': [{'component': '0'}],
                                        {'method': 'getSwitchPortInfo', 'params': [{'component': '0', 'portIdentifier': 'sw0p1'},
                                                                                   {'component': '0', 'portIdentifier': 'sw0p2'}]}, ])

        """
        multicall_list = []
        return_values = []
        batch = jsonrpclib.MultiCall(self.jsonrpc)
        # Generates a sequence of commands
        for row in calls_list:
            try:
                multicall_list.extend({"method": row["method"], "params": param}
                                      for param in row["params"])
            except KeyError as err:
                raise UIException("Incorrect key is transmitted in calls_list dictionary: {0}".format(err))
        for request in multicall_list:
            getattr(batch, request["method"])(**request["params"])

        # Executes a sequence of commands
        results = batch()

        # Verifies on error because result of execution is generator object
        # Iteration is necessary because multicall raises exceptions while iterating
        # and we need to collect the partial list in result_values in order to lookup the origin multicall method and params
        try:
            for res in results:
                return_values.append(res)
        except jsonrpclib.ProtocolError as err:
            method = multicall_list[len(return_values)]
            message = "{0[method]} command with parameters {0[params]} returned error {1[0]}: {1[1]}".format(method, err.args[0])
            raise UIException(message)

        assert len(return_values) == len(multicall_list), "Return values list has different length than multicall list"

        return return_values