def restart_service(cls, client_object, service_name=None, strict=None):
        """
        Restarts the service with the given name.

        @type name: str
        @param name: Name of the service to be restarted.
        @type strict: bool
        @param strict: If set to 1/True, then exception will
            be raised incase of errors. If set to
            0/False, then exception will be discarded. default
            value is set to enabled.
        """
        current_state = cls.get_individual_service_status(
            client_object, service_name)
        if current_state == constants.Service.UNKNOWN:
            raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                  reason=current_state)
        command = constants.Service.SERVICE_CMD % (service_name,
                                                   constants.Service.RESTART)
        out = client_object.connection.\
            request(command).response_data
        pylogger.debug(out)
        current_state = cls.get_individual_service_status(
            client_object, service_name)
        if not current_state == constants.Service.STARTED:
            # Final State is started
            current_state = "% is in %s state, expected it to be in %s "\
                            % (service_name, current_state,
                               constants.Service.STARTED)
            raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                  reason=current_state)
        pylogger.info('%s is restarted' % service_name)
 def node_cleanup(cls, client_object):
     script_path = constants.ManagerScriptPath.NSXNODECLEANUPSCRIPTPATH
     endpoint = 'chmod 755 ' + script_path
     client_object.connection.login_to_st_en_terminal(expect=['#'])
     expect_prompt = ['>', '#']
     pylogger.debug("Command executed to change "
                    "the permission of file: [%s]" % endpoint)
     result = client_object.connection.request(endpoint, expect_prompt)
     response = result.response_data
     if 'No such file or directory' in response:
         raise errors.CLIError(status_code=common.status_codes.FAILURE,
                               reason=response)
     else:
         endpoint = script_path
         expect_prompt = ['>', '#']
         pylogger.debug("Command executed to run "
                        "the mp node cleanup script: [%s]" % endpoint)
         result = client_object.connection.request(endpoint, expect_prompt)
         response = result.response_data
         # Close the expect connection object
         client_object.connection.close()
         if response.find("Unable to stop") > 0:
             pylogger.error("Failed to run the cleanup script")
             raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                   reason=response)
         else:
             return common.status_codes.SUCCESS
    def set_log_level(cls, client_object, component=None, log_level=None):
        """
        Sets the log level of components.

        @type client_object: BaseClient
        @param client_object: Used to pass commands to the host.
        @type log_level: str
        @param log_level: Specifies whether the log level is being increased or
            decreased. Only supports increasing the log level now.
        """
        if component not in cls.NSX_COMPONENTS:
            response = ("Only %r components are allowed, got: %r" %
                        (cls.NSX_COMPONENTS, component))
            raise errors.CLIError(
                status_code=common.status_codes.INVALID_PARAM, reason=response)
        if not log_level.lower() in cls.ALLOWED_LOG_LEVELS:
            response = ("Only %r log levels are allowed, got: %r" %
                        (cls.ALLOWED_LOG_LEVELS, log_level))
            raise errors.CLIError(
                status_code=common.status_codes.INVALID_PARAM, reason=response)
        component_map = {
            constants.NSXPackages.OVS_L3D: cls._set_l3d_log_level,
            constants.NSXPackages.NSXA: cls._set_nsxa_log_level,
            constants.NSXPackages.NSX_MPA: cls._set_nsxmpa_log_level,
            constants.NSXPackages.NSX_AGENT: cls._set_nsxagent_log_level
        }
        component_map[component](client_object, log_level=log_level)
Exemple #4
0
    def register_nsx_edge_node(cls, client_object, manager_ip=None,
                               manager_username=None,
                               manager_password=None,
                               manager_thumbprint=None):
        try:
            # This method register edgenode with nsx manager
            cmd = 'join management-plane'
            command = ('%s %s thumbprint %s username %s password %s' %
                       (cmd, manager_ip, manager_thumbprint,
                        manager_username, manager_password))
            # XXX(dbadiani): Prompt we expect after exiting the configure
            # termninal mode on Edge VM.
            expect = ['bytes*', '>']
            pylogger.info("Executing NSX registration command: %s" % command)
            result = client_object.connection.request(
                command=command, expect=expect)
            client_object.connection.close()

            if result.status_code == 0:
                pylogger.info("Edge registration to NSX succeeded")
            else:
                pylogger.error("Edge registration to NSX failed")
                raise errors.CLIError(status_code=result.status_code,
                                      response_data=result.response_data,
                                      reason=result.error)
        except Exception, e:
            raise errors.CLIError(exc=e)
Exemple #5
0
    def tunnel_process(cls, client_obj, endpoints=None, operation=None):
        """
        Kill/Check tunnel to other conntroller on controller

        @type endpoints: List
        @param endpoints: List of controller object, to get ip address
        @type operation: String
        @param operation: kill/check
        """
        connection = client_obj.connection
        status_code = common.status_codes.FAILURE
        command = None
        error_info = 'No such file'
        if operation == 'kill':
            pid_list = []
            for endpoint in endpoints:
                if endpoint.ip != client_obj.ip:
                    filepath = cls.TUNNEL_PREFIX + endpoint.ip + ":7777.pid"
                    command = "cat %s" % filepath
                    result = connection.request(command,
                                                expect=['bytes*', '#'])
                    response = result.response_data
                    if error_info in response:
                        pylogger.error("File %s doesn't exist" % filepath)
                        raise errors.CLIError(status_code=status_code,
                                              reason=response)
                    pid = response.split("\n")[0].strip()
                    pid_list.append(pid)
            pid_list = ' '.join(pid_list)
            pylogger.debug("The pid list should be killed is %s" % pid_list)
            command = "kill %s" % pid_list
            result = connection.request(command, expect=['bytes*', '#'])
            response = result.response_data
            if 'process' in response:
                raise errors.CLIError(status_code=status_code, reason=response)
        elif operation == 'check':
            for endpoint in endpoints:
                if endpoint.ip != client_obj.ip:
                    filepath = cls.TUNNEL_PREFIX + endpoint.ip
                    command = "cat %s:7777.pid" % filepath
                    result = connection.request(command,
                                                expect=['bytes*', '#'])
                    response = result.response_data
                    if error_info in response:
                        pylogger.error("File %s doesn't exist" % filepath)
                        raise errors.CLIError(status_code=status_code,
                                              reason=response)
                    pid = response
                    command = "ps ax|grep %s|awk '{print $1}'" % filepath
                    result = connection.request(command,
                                                expect=['bytes*', '#'])
                    response = result.response_data
                    if pid not in response:
                        raise errors.CLIError(status_code=status_code,
                                              reason=response)
        else:
            raise ValueError("Received unknown <%s> tunnel "
                             "partitioning operation" % operation)
        return constants.Result.SUCCESS.upper()
    def check_node_backup_file(cls, client_object, path, **kwargs):

        if path:
            endpoint = 'ls -l ' + path
        else:
            raise ValueError("Received empty path")

        pylogger.debug("Command executed to check file: [%s]" % endpoint)

        client_object.connection.login_to_st_en_terminal(expect=['#'])

        expect_prompt = ['>', '#']

        raw_payload = client_object.connection.request(
            endpoint, expect_prompt).response_data
        client_object.connection.close()

        lines = raw_payload.strip().split("\n")
        pydict = dict()

        if len(lines) > 0:
            pydict.update({'content': raw_payload})
            return pydict
        else:
            raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                  reason='Node backup file not found')
    def check_cluster_backup_file(cls, client_object, path, **kwargs):
        if path:
            endpoint = 'ls -l ' + path
        else:
            raise ValueError("Received empty path")

        pylogger.debug("Command executed to check file: [%s]" % endpoint)

        client_object.connection.login_to_st_en_terminal(expect=['#'])

        expect_prompt = ['>', '#']

        endpoint1 = 'cd ' + path + ' && ls -L | wc -l'
        result = client_object.connection.request(endpoint1, expect_prompt)
        response = result.response_data
        lines = response.strip().split("\n")

        if (len(lines) > 0) and (lines[0] == '1'):
            raw_payload = client_object.\
                connection.request(endpoint, expect_prompt).response_data
            client_object.connection.close()

            lines = raw_payload.strip().split("\n")
            pydict = dict()

            if (len(lines) > 0) and ("backup_" in lines[1]):
                pydict.update({'content': 'found'})
                return pydict

            pylogger.exception("backup file not found")
            pydict.update({'content': 'error'})
            return pydict
        else:
            raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                  reason='More than one backup file found')
    def configure_ip_route(cls, client_obj, **kwargs):

        client_obj.connection.request("configure terminal", ['bytes*', '#'])

        if kwargs['cidr'] and kwargs['manager_ip']:
            endpoint = \
                "ip route " + kwargs['cidr'] + " " + kwargs['manager_ip']
        else:
            raise ValueError("Received empty cidr/manager_ip")

        # Reset mode
        if 'reset' in kwargs and \
                (kwargs['reset'].lower() == 'yes' or
                 kwargs['reset'].lower() == 'true'):
            endpoint = "no " + endpoint

        expect_prompt = ["--More--", "#"]

        try:
            client_obj.connection.request(endpoint, expect_prompt)

            # Close the expect connection object
            client_obj.connection.close()
            return common.status_codes.SUCCESS

        except Exception:
            raise errors.CLIError(status_code=common.status_codes.FAILURE)
    def delete(cls, client_obj, manager_ip=None):

        # No join management cluster node
        endpoint = "no management-cluster node"
        expect_prompt = ['bytes *', '#']

        if manager_ip is None:
            raise ValueError("Received empty manager ip")

        endpoint = endpoint + " " + manager_ip

        pylogger.debug("CLI to remove node from mgmt-cluster:[%s]" % endpoint)
        client_obj.connection.request("configure terminal", expect_prompt)

        raw_payload = (client_obj.connection.request(
            endpoint, expect_prompt).response_data)

        result_dict = dict()
        lines = raw_payload.strip().splitlines()
        client_obj.connection.close()

        if ((len(lines) > 1) and ((lines[0].upper().find("ERROR") > 0) or
                                  (lines[1].upper().find("ERROR") > 0))):
            pylogger.exception("ERROR:Failure observed while running CLI: %s" %
                               raw_payload)
            raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                  reason='no join management-cluster command '
                                  'execution returned error')
        else:
            result_dict['response_data']['status_code'] = (
                common.status_codes.SUCCESS)
            return result_dict
Exemple #10
0
    def copy_tech_support(cls, client_object, logdir=None, collectorIP=None):
        """
        Copy CCP tech support file to given dir on collectorIP

        @logdir: String
        @collectorIP: IP address for collector,

        """
        filename = ('techsupportbundle-%s.tar.gz' %
                    time.strftime("%Y%m%d-%H%M%S"))
        cmd = "get support-bundle file " + filename
        client_object.connection.request(command=cmd,
                                         expect=['bytes*', '>'])
        cmd = ("copy file %s url scp://root@%s%s%s" %
               (filename, collectorIP, logdir, filename))
        try:
            client_object.connection.execute_command_with_hostkey_prompt(
                cmd, global_config.DEFAULT_PASSWORD,
                final_expect=['bytes*', '>'])
        except Exception, error:
            pylogger.error("Copy tech support bundle failed from %s "
                           "to %s with command: %s" %
                           (client_object.ip, collectorIP, cmd))
            pylogger.error("Failed reason: %s" % error)
            raise errors.CLIError(status_code=common.status_codes.FAILURE)
    def set_banner_motd(cls, client_obj, **kwargs):
        # ###
        # nsx-manager> configure terminal
        # nsx-manager(config)# banner motd
        # Enter TEXT message.  End with 'Ctrl-D'
        # Hello World!!
        # nsx-manager(config)#
        # ###

        if not kwargs['message']:
            raise ValueError("Received empty message")

        try:
            endpoint = "banner motd"
            ctrl_key = 'd'

            client_obj.connection.request("configure terminal",
                                          ['bytes*', '#'])
            client_obj.connection.request(endpoint, ["--More--", "\'Ctrl-D\'"])
            client_obj.connection.request(kwargs['message'],
                                          ["--More--", "\r\n", "#"], ctrl_key)

            # Close the expect connection object
            client_obj.connection.close()
            return common.status_codes.SUCCESS

        except Exception:
            raise errors.CLIError(status_code=common.status_codes.FAILURE)
Exemple #12
0
 def map_sdk_exception(self, exc):
     if type(exc) in (AttributeError, RuntimeError, TypeError, ValueError):
         return errors.Error(status_code=common.status_codes.RUNTIME_ERROR,
                             exc=exc)
     else:
         # reuse same errors as cli
         return errors.CLIError(exc=exc)
    def get_motd(cls, client_obj, **kwargs):
        # ###
        # nsx-manager> st e
        # Password:
        # [root@nsx-manager ~]# cat /etc/motd.tail
        # Hello World!!
        # [root@nsx-manager ~]#
        # ###

        pydict = dict()
        client_obj.connection.login_to_st_en_terminal(expect=['#'])
        endpoint = "cat /etc/motd.tail"
        expect_prompt = ['bytes *', '#']

        try:
            raw_payload = client_obj.connection.request(
                endpoint, expect_prompt).response_data

            pydict.update({'message': raw_payload})
            # Close the expect connection object
            client_obj.connection.close()
            return pydict

        except Exception:
            raise errors.CLIError(status_code=common.status_codes.FAILURE)
    def remove_nsx_manager(cls,
                           client_object,
                           manager_ip=None,
                           manager_thumbprint=None,
                           username=None,
                           password=None):
        client_object.set_connection(
            connection_type=constants.ConnectionType.EXPECT)
        connection = client_object.connection
        connection.request(command='/opt/vmware/nsx-cli/bin/scripts/nsxcli',
                           expect=['bytes*', '.>'])
        connection.request(command='config terminal', expect=['bytes*', '#'])
        if username is None:
            username = constants.ManagerCredential.USERNAME
        if password is None:
            password = constants.ManagerCredential.PASSWORD
        deregister_command = "deregister-node %s %s %s %s" % (
            manager_ip, username, manager_thumbprint, password)

        result = connection.request(command=deregister_command,
                                    expect=['bytes*', '#'])
        pylogger.info("Deregister Host Node result: %s" % result.response_data)

        ret = result.response_data
        connection.request(command='exit', expect=['bytes*', '.>'])
        connection.request(command='exit', expect=['bytes*', '#', '$'])
        client_object.restore_connection()
        if NODE_DEREGISTRATION_SUCESSS not in ret:
            pylogger.error("Host Node Deregistration Failed!")
            message = [line for line in ret.splitlines() if "%" in line]
            if not message:
                message = [ret]
            raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                  reason=message[0][2:])
 def _stop_service(cls, client_object, key=None):
     current_state = cls._get_service_state(client_object,
                                            EXPECT_PROMPT,
                                            service_name=key)
     if current_state == NOTFOUND:
         raise errors.CLIError(status_code=-1, reason=current_state)
     if current_state == 'STOP':
         pylogger.info("%s is already stopped" % key)
     else:
         command = 'stop service %s' % key
         try:
             out = client_object.connection.\
                 request(command, EXPECT_PROMPT).response_data
         except Exception as e:
             pylogger.warning('%s stop failed due to exception: %s' %
                              (key, e))
             return common.status_codes.FAILURE
         pylogger.debug('Command: %s,output: %s' % (command, out))
         current_state = cls._get_service_state(client_object,
                                                EXPECT_PROMPT,
                                                service_name=key)
         if not current_state == STOP:
             pylogger.warning("%s is not stopped, its current state is %s" %
                              (key, current_state))
             return common.status_codes.FAILURE
     return common.status_codes.SUCCESS
    def read_hostname(cls, client_object, read_hostname=None):
        """
        Method to return hostname of esx host.

        @rtype: dict
        @return: dictionary having esx hostname
        """
        _ = read_hostname

        command = 'esxcli --debug --formatter=json system hostname get'

        try:
            raw_payload = client_object.connection.request(
                command, ['bytes*', '#']).response_data
        except Exception:
            error_msg = ("Command [%s] threw an exception during execution" %
                         command)
            pylogger.exception(error_msg)
            raise errors.CLIError(status_code=common.status_codes.FAILURE)
        finally:
            client_object.connection.close()

        ###
        # Command returns json format string e.g.
        #   {"DomainName": "eng.vmware.com",
        #    "FullyQualifiedDomainName": "colo-nimbus-dhcp.eng.vmware.com",
        #    "HostName": "colo-nimbus-dhcp"}
        # Converting this string to dictionary using json module
        ###
        pydict = json.loads(raw_payload)
        return {"hostname": pydict["FullyQualifiedDomainName"]}
 def _restart_service(cls, client_object, key=None):
     current_state = cls._get_service_state(client_object,
                                            EXPECT_PROMPT,
                                            service_name=key)
     if current_state == NOTFOUND:
         raise errors.CLIError(status_code=common.status_codes.FAILURE,
                               reason=current_state)
     command = 'restart service %s' % key
     try:
         out = client_object.connection.\
             request(command, EXPECT_PROMPT).response_data
     except Exception as e:
         pylogger.warning('%s restart failed due to exception: %s' %
                          (key, e))
         return common.status_codes.FAILURE
     pylogger.debug('Command: %s,output: %s' % (command, out))
     current_state = cls._get_service_state(client_object,
                                            EXPECT_PROMPT,
                                            service_name=key)
     if not current_state == START:
         pylogger.warning('%s is not restarted, its currect state is' %
                          (key, current_state))
         return common.status_codes.FAILURE
     pylogger.info('%s is restarted' % key)
     return common.status_codes.SUCCESS
 def method01(cls, client_object):
     pylogger.info("method01(%r) called" % client_object)
     out = client_object.connection.request('ls /tmp').response_data
     # Assuming the command returned a status_code with 255
     status_code = 255
     if status_code:  # non-zero for cli
         raise errors.CLIError(status_code=status_code, reason=out)
    def set_ntp_server(cls,
                       client_obj,
                       ip=None,
                       hostname=None,
                       reset=None,
                       **kwargs):

        client_obj.connection.request("configure terminal", ['bytes*', '#'])
        if (((ip is None and hostname is None)
             or (ip is not None and hostname is not None))):
            raise ValueError("Need to provide either ip or hostname, but "
                             "provided ip=%s, hostname=%s" % (ip, hostname))

        endpoint = "ntp server %s" % (ip or hostname)
        # NTP server reset mode
        if utilities.is_true(reset):
            endpoint = "no " + endpoint

        expect_prompt = ["--More--", "#"]
        try:
            client_obj.connection.request(endpoint, expect_prompt)
            client_obj.connection.close()
            return common.status_codes.SUCCESS
        except Exception, e:
            raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                  exc=e)
    def start_service(cls, client_object, service_name=None, strict=None):
        """
        Starts a service with the given name.

        @type name: str
        @param name: Name of the service to be started.
        @type strict: bool
        @param strict: If set to 1/True, then exception will
            be raised incase of errors. If set to
            0/False, then exception will be discarded. default
            value is set to enabled.
        @return: Any string from constants.Service.
        """
        if strict is None:
            strict = True
        current_state = cls.get_individual_service_status(
            client_object, service_name)
        if current_state == constants.Service.UNKNOWN:
            raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                  reason=current_state)
        if current_state == constants.Service.STARTED:
            pylogger.info("%s is already started" % service_name)
            error_reason = ("%s is found started before"
                            " starting the service." % service_name)
            if strict:
                raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                      reason=error_reason)
            else:
                return current_state
        else:
            command = constants.Service.SERVICE_CMD % (service_name,
                                                       constants.Service.START)
            out = client_object.connection.\
                request(command).response_data
            pylogger.debug(out)
            current_state = cls.get_individual_service_status(
                client_object, service_name)
            if not current_state == constants.Service.STARTED:
                # To ensure that process is started state
                pylogger.error('%s is not started' % service_name)
                current_state = "% is in %s state, expected it to be in %s " \
                                % (service_name, current_state,
                                   constants.Service.STARTED)
                raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                      reason=current_state)
 def wait_for_nsx_services_running(cls, client_object):
     pylogger.debug("Checking for nsx services to be running ...")
     kwargs = {'service_name': 'nsx-mpa'}
     if not timeouts.nsx_mpa_start_delay.wait_until(
             client_object.is_service_running,
             kwargs=kwargs,
             exc_handler=False,
             logger=pylogger):
         raise errors.CLIError(status_code=common.status_codes.FAILURE,
                               reason='nsx-mpa service is not running')
     kwargs = {'service_name': 'nsxa'}
     if not timeouts.nsxa_start_delay.wait_until(
             client_object.is_service_running,
             kwargs=kwargs,
             exc_handler=False,
             logger=pylogger):
         raise errors.CLIError(status_code=common.status_codes.FAILURE,
                               reason='nsxa service is not running')
 def _stop_service(cls, client_object, key=None):
     current_state = cls._get_service_state(client_object, EXPECT_PROMPT,
                                            service_name=key)
     if current_state == NOTFOUND:
         raise errors.CLIError(status_code=-1, reason=current_state)
     if current_state == 'STOP':
         pylogger.info("%s is already stopped" % key)
     else:
         command = '/etc/init.d/%s stop' % key
         out = client_object.connection.\
             request(command, EXPECT_PROMPT).response_data
         pylogger.debug('Command: %s,output: %s' % (command, out))
         current_state = cls._get_service_state(
             client_object, EXPECT_PROMPT, service_name=key)
         if not current_state == STOP:
             current_state = "%s :current State %s" % (key, current_state)
             raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                   reason=current_state)
     return common.status_codes.SUCCESS
    def set_nsx_manager(cls,
                        client_object,
                        manager_ip=None,
                        manager_thumbprint=None,
                        username=None,
                        password=None):
        client_object.set_connection(
            connection_type=constants.ConnectionType.EXPECT)
        connection = client_object.connection
        result = connection.request(
            command='/opt/vmware/nsx-cli/bin/scripts/nsxcli',
            expect=['bytes*', '.>'])
        result = connection.request(command='config terminal',
                                    expect=['bytes*', '.#'])
        if username is None:
            username = constants.ManagerCredential.USERNAME
        if password is None:
            password = constants.ManagerCredential.PASSWORD
        register_command = "register-node %s %s %s %s" % (
            manager_ip, username, manager_thumbprint, password)
        pylogger.info("Executing fabric host registration command: %s" %
                      register_command)
        result = connection.request(command=register_command,
                                    expect=['bytes*', '#'])
        pylogger.info("Register Host Node result: %s" % result.response_data)
        ret = result.response_data.splitlines()
        # Exit from the config terminal of the CLI.
        result = connection.request(command='exit', expect=['bytes*', '.>'])
        # Exit from the CLI itself.
        result = connection.request(command='exit', expect=['bytes*', '.#'])

        if not any(NODE_REGISTRATION_SUCESSS in line for line in ret):
            pylogger.error("Host Node Registration Failed!")
            message = [line for line in ret if "%" in line]
            if len(message) < 1:
                message[0] = ret
            raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                  reason=message[0][2:])
        else:
            pylogger.info("Verifiying that MPA is up ...")
            result = connection.request(command='/etc/init.d/nsx-mpa status',
                                        expect=['bytes*', '#'])
            if not re.search("is running", result.response_data):
                pylogger.error("NSX-MPA is not running!")
                raise RuntimeError("NSX-MPA is not running!")
            pylogger.info("Verifying nsxa status ...")
            # TODO(salmanm): Call helpers for verifying the service status.
            result = connection.request(command='/etc/init.d/nsxa status',
                                        expect=['bytes*', '#'])
            if not re.search("is running", result.response_data):
                pylogger.error("NSXA not started successfully")
                raise RuntimeError("NSXA is not running")
            client_object.restore_connection()
Exemple #24
0
    def get_host_uuid(cls, client_object, get_host_uuid=None):
        """
        Method to execute 'show host uuid' cli on KVM host using nsxcli and
        return the fetched uuid.

        @rtype: dict
        @return: dictionary having host UUID
        """
        _ = get_host_uuid
        # Setting up the pexpect connection
        client_object.set_connection(
            connection_type=constants.ConnectionType.EXPECT)
        connection = client_object.connection

        # Invoking nsxcli prompt where the cli would run
        command = NSXCLI_SCRIPT_PATH_ON_HV
        expect_prompt = ['bytes*', '.>']

        try:
            connection.request(command, expect_prompt)

            endpoint = "show host uuid"
            raw_payload = connection.request(endpoint,
                                             expect_prompt).response_data
            connection.request(command='exit', expect=['bytes*', '#'])
        except Exception:
            error_msg = \
                "NSXCLI [%s] thrown exception during execution" % endpoint
            pylogger.exception(error_msg)
            raise errors.CLIError(status_code=common.status_codes.FAILURE)
        finally:
            client_object.restore_connection()

        if len(raw_payload.splitlines()) == 4:
            return {'host_uuid': raw_payload.splitlines()[1]}
        else:
            raise errors.CLIError(
                status_code=common.status_codes.FAILURE,
                reason='Unexpected CLI output returned, raw_payload: [%s]' %
                raw_payload)
Exemple #25
0
    def _get_query_object(cls, endpoints, switch_vni):
        """
        Helper method to return the right object to be queried for data.

        This method determines which host should be queried for getting MAC/ARP
        table. If endpoints length is greater than 1, then method
        assumes that all passed in objects are controller objects and then
        determines the master controller for that vni, otherwise it returns the
        one and only element in the verification objects list.
        @param endpoints: List of objects on which the query needs
            to be made. If multiple entries are found in the list then logic to
            figure out master controller is triggered.
        @type verification_onjects: list
        @param switch_vni: VNI of the logical switch.
        @type switch_vni: int
        """
        queried_obj = None
        if len(endpoints) > 1:
            # Check that all objects are of type controller.
            all_controllers = [
                True for host_elem in endpoints if isinstance(
                    host_elem, controller_cli_client.ControllerCLIClient)
            ]
            if not all(all_controllers):
                raise TypeError("Since the list contains more than 1 element, "
                                "all elements were expected to be of "
                                "controller cli clients, got %r" % endpoints)
            # Controller verification invloves determing which controller is
            # the master controller.
            master_controllers = []
            for controller in endpoints:
                if controller.is_master_for_vni(switch_vni=switch_vni):
                    master_controllers.append(controller)
            if not master_controllers:
                reason = ('No controller is identified as the '
                          'master controller for vni %r. Expected '
                          'at least one master controller.' % switch_vni)
                raise errors.CLIError(
                    status_code=common.status_codes.NOT_FOUND, reason=reason)
            if len(master_controllers) > 1:
                raise AssertionError(
                    'More than one controllers [%r] have '
                    'been identified as master controllers '
                    'for vni %r. Expected only one '
                    'controller to be the master controller' %
                    ([mc.ip for mc in master_controllers], switch_vni))
            queried_obj = master_controllers[0]
            pylogger.debug("Master controller(s) for LS %r: %r" %
                           (switch_vni, queried_obj.ip))
        else:
            queried_obj = endpoints[0]
        return queried_obj
Exemple #26
0
 def delete_backend_file(cls, client_object, path, file_name):
     endpoint = 'rm -rf ' + ' ' + path + '/' + file_name
     expect_prompt = ['>', '#']
     pylogger.debug("Command executed to delete file: [%s]" % endpoint)
     result = client_object.connection.request(endpoint, expect_prompt)
     response = result.response_data
     if 'No such file or directory' in response:
         pylogger.debug("%s file_name does not exist, skipping delete")
         return common.status_codes.SUCCESS
     if 'cannot remove' in response:
         raise errors.CLIError(status_code=common.status_codes.FAILURE,
                               reason=response)
     else:
         return common.status_codes.SUCCESS
Exemple #27
0
 def clear_controller(cls, client_obj):
     """Clear the left process in ccp"""
     connection = client_obj.connection
     command = 'docker ps -q | xargs docker kill | xargs docker rm'
     result = connection.request(command, expect=['bytes*', '#'])
     response = result.response_data
     if 'docker' in response:
         raise errors.CLIError(status_code=common.status_codes.FAILURE,
                               reason=response)
     command = "ps ax|grep openvpn-moot|awk '{print $1}'|xargs kill -9"
     result = connection.request(command, expect=['bytes*', '#'])
     command = 'openvpn-moot --rmtun --dev tun0'
     result = connection.request(command, expect=['bytes*', '#'])
     return constants.Result.SUCCESS.upper()
 def kill_service(cls, client_object, service_name=None, strict=None):
     if strict is None:
         strict = True
     current_state = cls.get_individual_service_status(
         client_object, service_name)
     if current_state == constants.Service.UNKNOWN:
         current_state = "%s :current State %s"\
                         % (service_name, current_state)
         raise errors.CLIError(status_code=common.status_codes.FAILURE,
                               reason=current_state)
     if current_state == constants.Service.STOPPED:
         # assuming kill will be only used for
         # abrupt stop
         error_reason = "%s :current State %s"\
                        % (service_name, current_state)
         if strict:
             raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                   reason=error_reason)
         else:
             return current_state
     else:
         pid_before = client_object.connection.\
             request("pgrep %s" % service_name)
         command = 'pkill %s' % service_name
         out = client_object.connection.\
             request(command).response_data
         pylogger.debug(out)
         pid_after = client_object.connection.\
             request("pgrep %s" % service_name)
         # verifying whether process id is changed because
         # watchdog restarts the process for NSX services
         # post abrupt stop
         if pid_before == pid_after:
             raise errors.\
                 CLIError(status_code=common.status_codes.FAILURE,
                          reason=current_state)
         pylogger.info('%s is killed' % service_name)
    def configure_auth_type(cls, client_obj, **kwargs):

        client_obj.connection.request("configure terminal", ['bytes*', '#'])

        if kwargs['auth_type']:
            endpoint = "tacacs-server-authentication  " + kwargs['auth_type']
        else:
            raise ValueError("Received empty type field")

        expect_prompt = ["--More--", "#"]

        try:
            client_obj.connection.request(endpoint, expect_prompt)

            # Close the expect connection object
            client_obj.connection.close()
            return common.status_codes.SUCCESS

        except Exception:
            raise errors.CLIError(status_code=common.status_codes.FAILURE)
    def create(cls, client_obj, schema=None, **kwargs):

        if (schema['username'] is None or schema['manager_ip'] is None
                or schema['password'] is None
                or schema['manager_thumbprint'] is None):
            raise ValueError("Required parameters not provided.")

        manager_ip = schema['manager_ip']
        username = schema['username']
        password = schema['password']
        thumbprint = schema['manager_thumbprint']

        mgr_obj = manager_client.NSXManagerFacade(ip=manager_ip,
                                                  username=username,
                                                  password=password)
        id_ = mgr_obj.get_node_id()

        # Construct the command arguments
        endpoint = ("join management-cluster " + manager_ip + " " + username +
                    " " + thumbprint + " " + password)
        expect_prompt = ['bytes*', '#']
        pylogger.debug("CLI for join node to mgmt-cluster:[%s]" % endpoint)
        client_obj.connection.request("configure terminal", expect_prompt)

        raw_payload = (client_obj.connection.request(
            endpoint, expect_prompt).response_data)

        result_dict = dict()
        lines = raw_payload.strip().splitlines()
        client_obj.connection.close()

        if ((len(lines) > 1) and ((lines[0].upper().find("ERROR") > 0) or
                                  (lines[1].upper().find("ERROR") > 0))):
            pylogger.exception("ERROR:Failure observed while running CLI "
                               ": %s" % raw_payload)
            raise errors.CLIError(status_code=common.status_codes.FAILURE,
                                  reason='join management-cluster command '
                                  'execution returned error')
        else:
            result_dict['id_'] = id_
            return result_dict