Exemple #1
0
def apply_connectivity_changes(request, add_vlan_action, remove_vlan_action, logger=None):
    """
    Standard implementation for the apply_connectivity_changes operation
    This function will accept as an input the actions to perform for add/remove vlan. It implements
    the basic flow of decoding the JSON connectivity changes requests, and combining the results
    of the add/remove vlan functions into a result object.

    :param str request: json string sent from the CloudShell server describing the connectivity changes to perform
    :param Function -> ConnectivityActionResult remove_vlan_action: This action will be called for VLAN remove operations
    :param Function -> ConnectivityActionResult add_vlan_action: This action will be called for VLAN add operations
    :param logger: logger to use for the operation, if you don't provide a logger, a default Python logger will be used
    :return Returns a driver action result object, this can be returned to CloudShell server by the command result
    :rtype: DriverResponseRoot
    """

    if not logger:
        logger = logging.getLogger("apply_connectivity_changes")

    if request is None or request == '':
        raise Exception('ConnectivityOperations', 'request is None or empty')

    holder = connectivity_request_from_json(request)

    driver_response = DriverResponse()
    results = []
    driver_response_root = DriverResponseRoot()

    for action in holder.actions:
        logger.info('Action: ', action.__dict__)
        if action.type == ConnectivityActionRequest.SET_VLAN:
            action_result = add_vlan_action(action)

        elif action.type == ConnectivityActionRequest.REMOVE_VLAN:
            action_result = remove_vlan_action(action)

        else:
            continue
        results.append(action_result)

    driver_response.actionResults = results
    driver_response_root.driverResponse = driver_response
    return driver_response_root
def apply_connectivity_changes(request, add_vlan_action, remove_vlan_action, logger=None):
    """
    Standard implementation for the apply_connectivity_changes operation
    This function will accept as an input the actions to perform for add/remove vlan. It implements
    the basic flow of decoding the JSON connectivity changes requests, and combining the results
    of the add/remove vlan functions into a result object.

    :param str request: json string sent from the CloudShell server describing the connectivity changes to perform
    :param (ConnectivityActionRequest) -> ConnectivityActionResult remove_vlan_action: This action will be called for VLAN remove operations
    :param (ConnectivityActionRequest) -> ConnectivityActionResult add_vlan_action: This action will be called for VLAN_add_operations
    :param logger: logger to use for the operation, if you don't provide a logger, a default Python logger will be used
    :return Returns a driver action result object, this can be returned to CloudShell server by the command result
    :rtype: DriverResponseRoot
    """

    if not logger:
        logger = logging.getLogger("apply_connectivity_changes")

    if request is None or request == '':
        raise Exception('ConnectivityOperations', 'request is None or empty')

    holder = connectivity_request_from_json(request)

    driver_response = DriverResponse()
    results = []
    driver_response_root = DriverResponseRoot()

    for action in holder.actions:
        logger.info('Action: ', action.__dict__)
        if action.type == ConnectivityActionRequest.SET_VLAN:
            action_result = add_vlan_action(action)

        elif action.type == ConnectivityActionRequest.REMOVE_VLAN:
            action_result = remove_vlan_action(action)

        else:
            continue
        results.append(action_result)

    driver_response.actionResults = results
    driver_response_root.driverResponse = driver_response
    return driver_response_root
    def apply_connectivity_changes(self, request):
        """ Handle apply connectivity changes request json, trigger add or remove vlan methods,
        get responce from them and create json response

        :param request: json with all required action to configure or remove vlans from certain port
        :return Serialized DriverResponseRoot to json
        :rtype json
        """

        if request is None or request == "":
            raise Exception(self.__class__.__name__,
                            "request is None or empty")

        holder = JsonRequestDeserializer(jsonpickle.decode(request))

        if not holder or not hasattr(holder, "driverRequest"):
            raise Exception(self.__class__.__name__,
                            "Deserialized request is None or empty")

        driver_response = DriverResponse()
        add_vlan_thread_list = []
        remove_vlan_thread_list = []
        driver_response_root = DriverResponseRoot()

        for action in holder.driverRequest.actions:
            self._logger.info("Action: ", action.__dict__)
            self._validate_request_action(action)

            action_id = action.actionId
            full_name = action.actionTarget.fullName
            port_mode = action.connectionParams.mode.lower()

            if action.type == "setVlan":
                qnq = False
                ctag = ""
                for attribute in action.connectionParams.vlanServiceAttributes:
                    if attribute.attributeName.lower(
                    ) == "qnq" and attribute.attributeValue.lower() == "true":
                        qnq = True
                    if attribute.attributeName.lower() == "ctag":
                        ctag = attribute.attributeValue

                for vlan_id in self._get_vlan_list(
                        action.connectionParams.vlanId):
                    add_vlan_thread = Thread(target=self.add_vlan,
                                             name=action_id,
                                             args=(vlan_id, full_name,
                                                   port_mode, qnq, ctag))
                    add_vlan_thread_list.append(add_vlan_thread)
            elif action.type == "removeVlan":
                for vlan_id in self._get_vlan_list(
                        action.connectionParams.vlanId):
                    remove_vlan_thread = Thread(target=self.remove_vlan,
                                                name=action_id,
                                                args=(
                                                    vlan_id,
                                                    full_name,
                                                    port_mode,
                                                ))
                    remove_vlan_thread_list.append(remove_vlan_thread)
            else:
                self._logger.warning(
                    "Undefined action type determined '{}': {}".format(
                        action.type, action.__dict__))
                continue

        # Start all created remove_vlan_threads
        for thread in remove_vlan_thread_list:
            thread.start()

        # Join all remove_vlan_threads. Main thread will wait completion of all remove_vlan_thread
        for thread in remove_vlan_thread_list:
            thread.join()

        # Start all created add_vlan_threads
        for thread in add_vlan_thread_list:
            thread.start()

        # Join all add_vlan_threads. Main thread will wait completion of all add_vlan_thread
        for thread in add_vlan_thread_list:
            thread.join()

        request_result = []
        for action in holder.driverRequest.actions:
            result_statuses, message = zip(*self.result.get(action.actionId))
            if all(result_statuses):
                action_result = ConnectivitySuccessResponse(
                    action,
                    "Add Vlan {vlan} configuration successfully completed".
                    format(vlan=action.connectionParams.vlanId))
            else:
                message_details = "\n\t".join(message)
                action_result = ConnectivityErrorResponse(
                    action, "Add Vlan {vlan} configuration failed."
                    "\nAdd Vlan configuration details:\n{message_details}".
                    format(vlan=action.connectionParams.vlanId,
                           message_details=message_details))
            request_result.append(action_result)

        driver_response.actionResults = request_result
        driver_response_root.driverResponse = driver_response
        return serialize_to_json(
            driver_response_root)  # .replace("[true]", "true")
    def apply_connectivity_changes(self, request):
        """Handle apply connectivity changes request json, trigger add or remove vlan methods,
        get responce from them and create json response

        :param request: json with all required action to configure or remove vlans from certain port
        :return Serialized DriverResponseRoot to json
        :rtype json
        """

        if request is None or request == '':
            raise Exception('ConnectivityOperations', 'request is None or empty')

        holder = JsonRequestDeserializer(jsonpickle.decode(request))

        if not holder or not hasattr(holder, 'driverRequest'):
            raise Exception('ConnectivityOperations', 'Deserialized request is None or empty')

        driver_response = DriverResponse()
        results = []
        driver_response_root = DriverResponseRoot()

        for action in holder.driverRequest.actions:
            self.logger.info('Action: ', action.__dict__)
            self._validate_request_action(action)
            action_result = ActionResult()
            action_result.type = action.type
            action_result.actionId = action.actionId
            action_result.errorMessage = None
            action_result.infoMessage = None
            action_result.updatedInterface = action.actionTarget.fullName
            if action.type == 'setVlan':
                qnq = False
                ctag = ''
                for attribute in action.connectionParams.vlanServiceAttributes:
                    if attribute.attributeName.lower() == 'qnq':
                        request_qnq = attribute.attributeValue
                        if request_qnq.lower() == 'true':
                            qnq = True
                    elif attribute.attributeName.lower() == 'ctag':
                        ctag = attribute.attributeValue
                try:
                    action_result.infoMessage = self.add_vlan(action.connectionParams.vlanId,
                                                              action.actionTarget.fullAddress,
                                                              action.connectionParams.mode.lower(),
                                                              qnq,
                                                              ctag)
                except Exception as e:
                    self.logger.error('Add vlan failed: {0}'.format(traceback.format_exc()))
                    action_result.errorMessage = ', '.join(map(str, e.args))
                    action_result.success = False
            elif action.type == 'removeVlan':
                try:
                    action_result.infoMessage = self.remove_vlan(action.connectionParams.vlanId,
                                                                 action.actionTarget.fullAddress,
                                                                 action.connectionParams.mode.lower())
                except Exception as e:
                    self.logger.error('Remove vlan failed: {0}'.format(traceback.format_exc()))
                    action_result.errorMessage = ', '.join(map(str, e.args))
                    action_result.success = False
            else:
                continue
            results.append(action_result)

        driver_response.actionResults = results
        driver_response_root.driverResponse = driver_response
        return self.set_command_result(driver_response_root).replace('[true]', 'true')