def ApplyConnectivityChanges(self, context, request):
        """
        Configures VLANs on multiple ports or port-channels
        :param ResourceCommandContext context: The context object for the command with resource and reservation info
        :param str request: A JSON object with the list of requested connectivity changes
        :return: a json object with the list of connectivity changes which were carried out by the switch
        :rtype: str
        """
        # res_id = context.reservation.reservation_id
        # api = CloudShellSessionContext(context).get_api()
        # api.WriteMessageToReservationOutput(res_id, "=== connectivity request ===")
        # api.WriteMessageToReservationOutput(res_id, request)
        # # response = apply_connectivity_changes(request=request,
        # #                                       add_vlan_action=lambda action: ConnectivitySuccessResponse(action, 'Success'),
        # #                                       remove_vlan_action=lambda action: ConnectivitySuccessResponse(action, 'Success'))
        # response = apply_connectivity_changes(request=request,
        #                                       add_vlan_action=my_add_vlan_action),
        #                                       remove_vlan_action=lambda action: ConnectivitySuccessResponse(action,
        #                                                                                                     'Success'))
        # api.WriteMessageToReservationOutput(res_id, "=== connectivity response ===")
        # # response.driverResponse.actionResults
        # api.WriteMessageToReservationOutput(res_id, response)
        # return response

        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()
            res_id = context.reservation.reservation_id
            api.WriteMessageToReservationOutput(
                res_id, "=== connectivity request ===")
            api.WriteMessageToReservationOutput(res_id, request)
            resource_config = NetworkingResourceConfig.from_context(
                self.SHELL_NAME,
                context,
                api,
                self.SUPPORTED_OS,
            )
            resource_config = NetworkingSwitchDemo.create_from_context(context)
            cli_configurator = JuniperCliConfigurator(self._cli,
                                                      resource_config, logger)
            connectivity_flow = MyConnectivityFlow(cli_configurator, logger)
            logger.info(
                'Start applying connectivity changes, request is: {0}'.format(
                    str(request)))
            result = connectivity_flow.apply_connectivity_changes(
                request=request)
            logger.info(
                'Finished applying connectivity changes, response is: {0}'.
                format(str(result)))
            logger.info('Apply Connectivity changes completed')
            return result
Beispiel #2
0
    def hello_world(self, context):
        """
        say hello to the world
        :param ResourceCommandContext context:
        :return:
        """
        api = CloudShellSessionContext(context).get_api()
        res_id = context.reservation.reservation_id
        api.WriteMessageToReservationOutput(res_id, "first session print")
        api.Logoff()
        api = CloudShellSessionContext(context).get_api()
        api.WriteMessageToReservationOutput(res_id, "second session print")

        name = context.resource.name
        model = context.resource.model
        address = context.resource.address
        return "Hello, I am {}, my model is {}, my ip is {}".format(
            name, model, address)
    def load_config(self, context, ixc_config):
        """ Load IxChariot configuration and select end points.

        :type context: cloudshell.shell.core.driver_context.ResourceRemoteCommandContext
        :param ixc_config: IxChariot configuration name.
        """

        session_id = self.handler.load_config(context, ixc_config)
        my_api = CloudShellSessionContext(context).get_api()
        my_api.WriteMessageToReservationOutput(
            context.reservation.reservation_id,
            ixc_config + ' loaded, endpoints reserved')
        return session_id
    def hello_world(self, context):
        """
        :param ResourceCommandContext context:
        :return:
        """
        api = CloudShellSessionContext(context).get_api()
        res_id = context.reservation.reservation_id

        name = context.resource.name
        ip = context.resource.address

        api.WriteMessageToReservationOutput(
            res_id, "resource name: {}, ip: {}".format(name, ip))

        pass
    def plan_terraform(self, context):
        """
        :param ResourceCommandContext context:
        :return:
        """
        api = CloudShellSessionContext(context).get_api()
        res_id = context.reservation.reservation_id

        api.WriteMessageToReservationOutput(res_id,
                                            "Generating terraform plan..")
        service_resource = TerraformService2G.create_from_context(context)
        tform_dir = service_resource.terraform_module_path
        tform_exe_dir = service_resource.terraform_executable
        tform_command = [
            f"{tform_exe_dir}\\terraform.exe", "plan", "-no-color"
        ]
        outp = check_output(tform_command, cwd=tform_dir).decode("utf-8")

        return outp
    def show_terraform_state(self, context):
        """
        :param ResourceCommandContext context:
        :return:
        """
        api = CloudShellSessionContext(context).get_api()
        res_id = context.reservation.reservation_id

        api.WriteMessageToReservationOutput(
            res_id, "Getting current Terraform Deployment state..")
        service_resource = TerraformService2G.create_from_context(context)
        tform_dir = service_resource.terraform_module_path
        try:
            state_file = open(f"{tform_dir}\\terraform.tfstate", mode="r")
            outp = state_file.read()

            state_file.close()
        except:
            outp = "Could not retrieve deployment state."
        return outp
Beispiel #7
0
    def Deploy(self, context, request=None, cancellation_context=None):
        """

        :param ResourceCommandContext context:
        :param str request: json string to be parsed
        :param cancellation_context:
        :return:
        """

        RESOURCE_POOL_ATTR = "App Pool Name"
        CP_RESTRICTED_ATTR = "Restricted App Model Pools"

        api = CloudShellSessionContext(context).get_api()
        res_id = context.reservation.reservation_id

        # VALIDATE THAT CLOUD PROVIDER RESOURCE HAS POOL LIST Attribute
        cp_attrs = context.resource.attributes
        try:
            cp_pool_list_val = cp_attrs[CP_RESTRICTED_ATTR]
        except KeyError:
            pass
        else:
            api.WriteMessageToReservationOutput(res_id,
                                                "=== full request json ===")
            api.WriteMessageToReservationOutput(res_id, request)
            request_obj = json.loads(request)
            request_action_params = request_obj["driverRequest"]["actions"][0][
                "actionParams"]
            app_name = request_action_params["appName"]
            deployment = request_action_params["deployment"]
            app_resource = request_action_params["appResource"]
            app_resource_attrs = app_resource["attributes"]

            pool_attr_search = [
                attr for attr in app_resource_attrs
                if attr["attributeName"] == RESOURCE_POOL_ATTR
            ]
            if pool_attr_search:
                app_pool_attr_val = pool_attr_search[0]["attributeValue"]
                restricted_attrs_dict = get_cp_restricted_attrs_dict(
                    cp_pool_list_val)
                try:
                    app_pool_limit = restricted_attrs_dict[app_pool_attr_val]
                except KeyError:
                    not_found_msg = "{} pool name key not in cp restricted list {}".format(
                        app_pool_attr_val, restricted_attrs_dict)
                    api.WriteMessageToReservationOutput(res_id, not_found_msg)
                else:
                    # count deployed apps
                    all_generic_app_resources = api.FindResources(
                        resourceFamily="Generic App Family").Resources

                    # collect matching apps
                    matching_apps = []
                    for resource in all_generic_app_resources:
                        attrs = api.GetResourceDetails(
                            resource.Name).ResourceAttributes
                        attr_search = [
                            attr for attr in attrs
                            if attr.Name == RESOURCE_POOL_ATTR
                        ]
                        if attr_search:
                            attr_val = attr_search[0].Value
                            if attr_val == app_pool_attr_val:
                                matching_apps.append(resource)

                    # PERFORM VALIDATION
                    if len(matching_apps) >= int(app_pool_limit):
                        matching_app_names = [r.Name for r in matching_apps]
                        exc_msg = "Can not deploy '{}'. The pool '{}' has reached it's limit of {}. Current Apps in Pool: {}".format(
                            app_name, app_pool_attr_val, app_pool_limit,
                            matching_app_names)
                        api.WriteMessageToReservationOutput(
                            res_id, '<span style="color:red">{}</span>'.format(
                                exc_msg))
                        raise AppLimitDeploymentError(exc_msg)

        actions = self.request_parser.convert_driver_request_to_actions(
            request)
        deploy_action = single(actions, lambda x: isinstance(x, DeployApp))
        deployment_name = deploy_action.actionParams.deployment.deploymentPath

        if deployment_name in self.deployments.keys():
            deploy_method = self.deployments[deployment_name]
            deploy_result = deploy_method(context, deploy_action,
                                          cancellation_context)
            return DriverResponse([deploy_result]).to_driver_response_json()
        else:
            raise Exception('Could not find the deployment')