Exemplo n.º 1
0
    def post(self, plugin_id, **kwargs):
        """Force plugin installation on the given managers or agents.

        This method is for internal use only.
        """
        sm = get_storage_manager()
        action_dict = rest_utils.get_json_and_verify_params({
            'action': {
                'type': text_type
            },
        })
        plugin = sm.get(models.Plugin, plugin_id)
        if action_dict.get('action') == 'install':
            install_dict = rest_utils.get_json_and_verify_params({
                'managers': {
                    'type': list,
                    'optional': True
                },
                'agents': {
                    'type': list,
                    'optional': True
                },
            })
            get_resource_manager().install_plugin(
                plugin,
                manager_names=install_dict.get('managers'),
                agent_names=install_dict.get('agents'),
            )
            return get_resource_manager().install_plugin(plugin)
        else:
            raise manager_exceptions.ManagerException(
                400, 'Unknown action: {0}'.format(action_dict.get('action')))
 def put(self, deployment_id, **kwargs):
     """
     Create a deployment
     """
     rest_utils.validate_inputs({'deployment_id': deployment_id})
     request_schema = self.create_request_schema()
     request_dict = rest_utils.get_json_and_verify_params(request_schema)
     blueprint_id = request_dict['blueprint_id']
     bypass_maintenance = is_bypass_maintenance_mode()
     args = rest_utils.get_args_and_verify_arguments(
         [Argument('private_resource', type=boolean)]
     )
     visibility = rest_utils.get_visibility_parameter(
         optional=True,
         valid_values=VisibilityState.STATES
     )
     deployment = get_resource_manager().create_deployment(
         blueprint_id,
         deployment_id,
         inputs=request_dict.get('inputs', {}),
         bypass_maintenance=bypass_maintenance,
         private_resource=args.private_resource,
         visibility=visibility,
         skip_plugins_validation=self.get_skip_plugin_validation_flag(
             request_dict),
         site_name=_get_site_name(request_dict)
     )
     return deployment, 201
Exemplo n.º 3
0
    def post(self, **kwargs):
        """Execute a workflow"""
        request_dict = get_json_and_verify_params(
            {'deployment_id', 'workflow_id'})

        allow_custom_parameters = verify_and_convert_bool(
            'allow_custom_parameters',
            request_dict.get('allow_custom_parameters', 'false'))
        force = verify_and_convert_bool('force',
                                        request_dict.get('force', 'false'))
        dry_run = verify_and_convert_bool('dry_run',
                                          request_dict.get('dry_run', 'false'))
        queue = verify_and_convert_bool('queue',
                                        request_dict.get('queue', 'false'))

        deployment_id = request_dict['deployment_id']
        workflow_id = request_dict['workflow_id']
        parameters = request_dict.get('parameters', None)

        if parameters is not None and parameters.__class__ is not dict:
            raise manager_exceptions.BadParametersError(
                "request body's 'parameters' field must be a dict but"
                " is of type {0}".format(parameters.__class__.__name__))

        bypass_maintenance = is_bypass_maintenance_mode()
        execution = get_resource_manager().execute_workflow(
            deployment_id,
            workflow_id,
            parameters=parameters,
            allow_custom_parameters=allow_custom_parameters,
            force=force,
            dry_run=dry_run,
            bypass_maintenance=bypass_maintenance,
            queue=queue)
        return execution, 201
Exemplo n.º 4
0
 def post(self, snapshot_id):
     _verify_no_multi_node_cluster(action="restore snapshot")
     request_dict = rest_utils.get_json_and_verify_params(
         {'recreate_deployments_envs'})
     recreate_deployments_envs = rest_utils.verify_and_convert_bool(
         'recreate_deployments_envs',
         request_dict['recreate_deployments_envs'])
     bypass_maintenance = is_bypass_maintenance_mode()
     force = rest_utils.verify_and_convert_bool('force',
                                                request_dict['force'])
     restore_certificates = rest_utils.verify_and_convert_bool(
         'restore_certificates',
         request_dict.get('restore_certificates', 'false'))
     no_reboot = rest_utils.verify_and_convert_bool(
         'no_reboot', request_dict.get('no_reboot', 'false'))
     if no_reboot and not restore_certificates:
         raise manager_exceptions.BadParametersError(
             '`no_reboot` is only relevant when `restore_certificates` is '
             'activated')
     default_timeout_sec = 300
     request_timeout = request_dict.get('timeout', default_timeout_sec)
     timeout = rest_utils.convert_to_int(request_timeout)
     execution = get_resource_manager().restore_snapshot(
         snapshot_id, recreate_deployments_envs, force, bypass_maintenance,
         timeout, restore_certificates, no_reboot)
     return execution, 200
Exemplo n.º 5
0
    def patch(self, node_instance_id, **kwargs):
        """Update node instance by id."""
        request_dict = get_json_and_verify_params(
            {'version': {'type': int}}
        )

        if not isinstance(request.json, collections.Mapping):
            raise manager_exceptions.BadParametersError(
                'Request body is expected to be a map containing a "version" '
                'field and optionally "runtimeProperties" and/or "state" '
                'fields')

        # Added for backwards compatibility with older client versions that
        # had version=0 by default
        version = request_dict['version'] or 1

        instance = get_storage_manager().get(
            models.NodeInstance,
            node_instance_id,
            locking=True
        )
        if instance.version > version:
            raise manager_exceptions.ConflictError(
                'Node instance update conflict [current version={0}, '
                'update version={1}]'.format(instance.version, version)
            )
        # Only update if new values were included in the request
        instance.runtime_properties = request_dict.get(
            'runtime_properties',
            instance.runtime_properties
        )
        instance.state = request_dict.get('state', instance.state)
        return get_storage_manager().update(instance)
Exemplo n.º 6
0
    def put(self, **kwargs):
        request_schema = self.create_request_schema()
        request_dict = get_json_and_verify_params(request_schema)

        logging.info('call grant PUT')
        if request_dict['vnfmid']:
            logging.info("vnfmid='{0}'".format(request_dict['vnfmid']))
        if request_dict['nfvoid']:
            logging.info("nfvoid='{0}'".format(request_dict['nfvoid']))
        if request_dict.get('vimid'):
            logging.info("vimid='{0}'".format(request_dict.get('vimid')))
        if request_dict['exvimidlist']:
            logging.info("exvimidlist:")
            for exvimid in request_dict['exvimidlist']:
                logging.info("    exvimid='{0}'".format(exvimid))
        if request_dict.get('tenant'):
            logging.info("tenant='{0}'".format(request_dict.get('tenant')))
        if request_dict['vnfistanceid']:
            logging.info("vnfistanceid='{0}'".format(request_dict['vnfistanceid']))
        if request_dict['operationright']:
            logging.info("operationright='{0}'".format(request_dict['operationright']))
        if request_dict['vmlist']:
            logging.info("vmlist:")
            for vm in request_dict['vmlist']:
                if vm.get('vmflavor'):
                    logging.info("    vm.vmflavor='{0}'".format(vm.get('vmflavor')))
                if vm.get('vmnumber'):
                    logging.info("    vm.vmnumber='{0}'".format(vm.get('vmnumber')))

        return {'vimid': '12345678', 'tenant':'tenant1'}
Exemplo n.º 7
0
 def post(self, snapshot_id):
     request_dict = rest_utils.get_json_and_verify_params(
         {'recreate_deployments_envs'})
     recreate_deployments_envs = rest_utils.verify_and_convert_bool(
         'recreate_deployments_envs',
         request_dict['recreate_deployments_envs'])
     force = rest_utils.verify_and_convert_bool('force',
                                                request_dict['force'])
     restore_certificates = rest_utils.verify_and_convert_bool(
         'restore_certificates',
         request_dict.get('restore_certificates', 'false'))
     no_reboot = rest_utils.verify_and_convert_bool(
         'no_reboot', request_dict.get('no_reboot', 'false'))
     ignore_plugin_failure = \
         rest_utils.verify_and_convert_bool(
             'ignore_plugin_failure',
             request_dict.get('ignore_plugin_failure', 'false')
         )
     if no_reboot and not restore_certificates:
         raise manager_exceptions.BadParametersError(
             '`no_reboot` is only relevant when `restore_certificates` is '
             'activated')
     default_timeout_sec = 300
     request_timeout = request_dict.get('timeout', default_timeout_sec)
     timeout = rest_utils.convert_to_int(request_timeout)
     execution = get_resource_manager().restore_snapshot(
         snapshot_id, recreate_deployments_envs, force, True, timeout,
         restore_certificates, no_reboot, ignore_plugin_failure)
     return execution, 200
Exemplo n.º 8
0
 def _get_request_dict():
     request_dict = get_json_and_verify_params({
         'reporting_freq': {'type': int},
         'report': {'type': dict},
         'timestamp': {'type': text_type}
     })
     return request_dict
Exemplo n.º 9
0
    def _get_secret_params(self, key):
        rest_utils.validate_inputs({'key': key})
        request_dict = rest_utils.get_json_and_verify_params({
            'value': {'type': unicode}
        })
        update_if_exists = rest_utils.verify_and_convert_bool(
            'update_if_exists',
            request_dict.get('update_if_exists', False),
        )
        is_hidden_value = rest_utils.verify_and_convert_bool(
            'is_hidden_value',
            request_dict.get('is_hidden_value', False),
        )
        visibility_param = rest_utils.get_visibility_parameter(
            optional=True,
            valid_values=VisibilityState.STATES,
        )
        visibility = get_resource_manager().get_resource_visibility(
            models.Secret,
            key,
            visibility_param
        )

        secret_params = {
            'value': request_dict['value'],
            'update_if_exists': update_if_exists,
            'visibility': visibility,
            'is_hidden_value': is_hidden_value
        }
        return secret_params
Exemplo n.º 10
0
    def put(self, name):
        """
        Create a new agent
        """
        request_dict = get_json_and_verify_params({
            'node_instance_id': {'type': unicode},
            'state': {'type': unicode},
            'create_rabbitmq_user': {'type': bool}
        })
        validate_inputs({'name': name})
        state = request_dict.get('state')
        self._validate_state(state)
        response = {}

        try:
            new_agent = self._create_agent(name, state, request_dict)
            response = new_agent
        except manager_exceptions.ConflictError:
            # Assuming the agent was already created in cases of reinstalling
            # or healing
            current_app.logger.info("Not creating agent {0} because it "
                                    "already exists".format(name))
            new_agent = get_storage_manager().get(models.Agent, name)

        if request_dict.get('create_rabbitmq_user'):
            # Create rabbitmq user
            self._get_amqp_manager().create_agent_user(new_agent)
        return response
Exemplo n.º 11
0
 def put(self, operation_id, **kwargs):
     params = get_json_and_verify_params({
         'name': {
             'type': unicode,
             'required': True
         },
         'graph_id': {
             'type': unicode,
             'required': True
         },
         'dependencies': {
             'type': list,
             'required': True
         },
         'parameters': {
             'type': dict
         },
         'type': {
             'type': unicode
         }
     })
     operation = get_resource_manager().create_operation(
         operation_id,
         name=params['name'],
         graph_id=params['graph_id'],
         dependencies=params['dependencies'],
         type=params['type'],
         parameters=params['parameters'])
     return operation, 201
Exemplo n.º 12
0
 def put(self, deployment_id, **kwargs):
     """
     Create a deployment
     """
     rest_utils.validate_inputs({'deployment_id': deployment_id})
     request_schema = self.create_request_schema()
     request_dict = rest_utils.get_json_and_verify_params(request_schema)
     blueprint_id = request_dict['blueprint_id']
     bypass_maintenance = is_bypass_maintenance_mode()
     args = rest_utils.get_args_and_verify_arguments(
         [Argument('private_resource', type=boolean)]
     )
     visibility = rest_utils.get_visibility_parameter(
         optional=True,
         valid_values=VisibilityState.STATES
     )
     deployment = get_resource_manager().create_deployment(
         blueprint_id,
         deployment_id,
         inputs=request_dict.get('inputs', {}),
         bypass_maintenance=bypass_maintenance,
         private_resource=args.private_resource,
         visibility=visibility,
         skip_plugins_validation=self.get_skip_plugin_validation_flag(
             request_dict),
         site_name=_get_site_name(request_dict),
         runtime_only_evaluation=request_dict.get(
             'runtime_only_evaluation', False)
     )
     return deployment, 201
Exemplo n.º 13
0
    def put(self, name):
        """
        Create a new agent
        """
        request_dict = get_json_and_verify_params({
            'node_instance_id': {
                'type': unicode
            },
            'state': {
                'type': unicode
            },
            'create_rabbitmq_user': {
                'type': bool
            }
        })
        validate_inputs({'name': name})
        state = request_dict.get('state')
        self._validate_state(state)
        response = {}

        try:
            new_agent = self._create_agent(name, state, request_dict)
            response = new_agent
        except manager_exceptions.ConflictError:
            # Assuming the agent was already created in cases of reinstalling
            # or healing
            current_app.logger.info("Not creating agent {0} because it "
                                    "already exists".format(name))
            new_agent = get_storage_manager().get(models.Agent, name)

        if request_dict.get('create_rabbitmq_user'):
            # Create rabbitmq user
            self._get_amqp_manager().create_agent_user(new_agent)
        return response
Exemplo n.º 14
0
    def put(self, snapshot_id):
        rest_utils.validate_inputs({'snapshot_id': snapshot_id})
        request_dict = rest_utils.get_json_and_verify_params()
        include_metrics = rest_utils.verify_and_convert_bool(
            'include_metrics',
            request_dict.get('include_metrics', 'false')
        )
        include_credentials = rest_utils.verify_and_convert_bool(
            'include_credentials',
            request_dict.get('include_credentials', 'true')
        )
        include_logs = rest_utils.verify_and_convert_bool(
            'include_logs',
            request_dict.get('include_logs', 'true')
        )
        include_events = rest_utils.verify_and_convert_bool(
            'include_events',
            request_dict.get('include_events', 'true')
        )
        queue = rest_utils.verify_and_convert_bool(
            'queue',
            request_dict.get('queue', 'false')
        )
        execution = get_resource_manager().create_snapshot(
            snapshot_id,
            include_metrics,
            include_credentials,
            include_logs,
            include_events,
            True,
            queue
        )

        return execution, 201
Exemplo n.º 15
0
    def patch(self, node_instance_id, **kwargs):
        """Update node instance by id."""
        request_dict = get_json_and_verify_params({'version': {'type': int}})

        if not isinstance(request.json, collections.Mapping):
            raise manager_exceptions.BadParametersError(
                'Request body is expected to be a map containing a "version" '
                'field and optionally "runtimeProperties" and/or "state" '
                'fields')

        # Added for backwards compatibility with older client versions that
        # had version=0 by default
        version = request_dict['version'] or 1

        instance = get_storage_manager().get(models.NodeInstance,
                                             node_instance_id,
                                             locking=True)
        if instance.version > version:
            raise manager_exceptions.ConflictError(
                'Node instance update conflict [current version={0}, '
                'update version={1}]'.format(instance.version, version))
        # Only update if new values were included in the request
        instance.runtime_properties = request_dict.get(
            'runtime_properties', instance.runtime_properties)
        instance.state = request_dict.get('state', instance.state)
        return get_storage_manager().update(instance)
Exemplo n.º 16
0
    def put(self, name):
        """Update a config value.

        Settings which have is_editable set to False, can only be edited
        when passing the force flag.
        If a schema is specified for the given setting, the new value
        must validate.
        """
        sm = get_storage_manager()
        data = rest_utils.get_json_and_verify_params({
            'value': {},
            'force': {
                'type': bool,
                'optional': True
            }
        })
        value = data['value']
        force = data.get('force', False)

        inst = sm.get(models.Config, None, filters={'name': name})
        if not inst.is_editable and not force:
            raise ConflictError('{0} is not editable'.format(name))
        if inst.schema:
            try:
                jsonschema.validate(value, inst.schema)
            except jsonschema.ValidationError as e:
                raise ConflictError(e.args[0])
        inst.value = value
        inst.updated_at = datetime.now()
        inst.updated_by = current_user
        sm.update(inst)
        return inst
Exemplo n.º 17
0
 def put(self, deployment_id, **kwargs):
     """
     Create a deployment
     """
     validate_inputs({'deployment_id': deployment_id})
     request_schema = self.create_request_schema()
     request_dict = get_json_and_verify_params(request_schema)
     blueprint_id = request_dict['blueprint_id']
     bypass_maintenance = is_bypass_maintenance_mode()
     args = get_args_and_verify_arguments(
         [Argument('private_resource', type=boolean,
                   default=False)]
     )
     skip_plugins_validation = self.get_skip_plugin_validation_flag(
         request_dict)
     rm = get_resource_manager()
     sm = get_storage_manager()
     blueprint = sm.get(models.Blueprint, blueprint_id)
     rm.cleanup_failed_deployment(deployment_id)
     if not skip_plugins_validation:
         rm.check_blueprint_plugins_installed(blueprint.plan)
     deployment = rm.create_deployment(
         blueprint,
         deployment_id,
         private_resource=args.private_resource,
         visibility=None,
     )
     try:
         rm.execute_workflow(deployment.make_create_environment_execution(
             inputs=request_dict.get('inputs', {}),
         ), bypass_maintenance=bypass_maintenance)
     except manager_exceptions.ExistingRunningExecutionError:
         rm.delete_deployment(deployment)
         raise
     return deployment, 201
Exemplo n.º 18
0
    def _get_secret_params(self, key):
        rest_utils.validate_inputs({'key': key})
        request_dict = rest_utils.get_json_and_verify_params(
            {'value': {
                'type': unicode
            }})
        update_if_exists = rest_utils.verify_and_convert_bool(
            'update_if_exists',
            request_dict.get('update_if_exists', False),
        )
        is_hidden_value = rest_utils.verify_and_convert_bool(
            'is_hidden_value',
            request_dict.get('is_hidden_value', False),
        )
        visibility_param = rest_utils.get_visibility_parameter(
            optional=True,
            valid_values=VisibilityState.STATES,
        )
        visibility = get_resource_manager().get_resource_visibility(
            models.Secret, key, visibility_param)

        secret_params = {
            'value': request_dict['value'],
            'update_if_exists': update_if_exists,
            'visibility': visibility,
            'is_hidden_value': is_hidden_value
        }
        return secret_params
Exemplo n.º 19
0
    def post(self, execution_id, **kwargs):
        """
        Apply execution action (cancel, force-cancel) by id
        """
        request_dict = get_json_and_verify_params({'action'})
        action = request_dict['action']

        valid_actions = ['cancel', 'force-cancel']

        if action not in valid_actions:
            raise manager_exceptions.BadParametersError(
                'Invalid action: {0}, Valid action values are: {1}'.format(
                    action, valid_actions))

        if action in ('cancel', 'force-cancel'):
            service = self.model.execution.get(execution_id)
            executor = process.ProcessExecutor(self.plugin_manager)

            compiler = execution_preparer.ExecutionPreparer(
                self.model,
                self.resource,
                self.plugin_manager,
                service,
                request_dict['workflow_name']
            )
            workflow_ctx = compiler.prepare(execution_id=execution_id)
            engine_ = engine.Engine(executor)
            engine_.cancel_execution(workflow_ctx)
Exemplo n.º 20
0
    def post(self, **kwargs):
        """
        Start an execution
        """
        request_dict = rest_utils.get_json_and_verify_params(
            dict(
                service_id={'type': int},
                workflow_name={'type': basestring},
            )
        )

        service = self.model.service.get(request_dict['service_id'])
        executor = process.ProcessExecutor(plugin_manager=self.plugin_manager)

        compiler = execution_preparer.ExecutionPreparer(
            self.model,
            self.resource,
            self.plugin_manager,
            service,
            request_dict['workflow_name']
        )
        workflow_ctx = compiler.prepare(executor=executor)
        engine_ = engine.Engine(executor)
        engine_.execute(workflow_ctx)

        return workflow_ctx.execution.to_dict(
            workflow_ctx.execution.fields() -
            {'created_at', 'started_at', 'ended_at'}), \
            201
Exemplo n.º 21
0
    def _query_events(self):
        """Query events using a SQL backend.

        :returns:
            Results using a format that resembles the one used by elasticsearch
            (more information about the format in :meth:`.._map_event_to_dict`)
        :rtype: dict(str)

        """
        request_dict = get_json_and_verify_params()

        es_query = request_dict['query']['bool']

        _include = None
        # This is a trick based on the elasticsearch query pattern
        # - when only a filter is used it's in a 'must' section
        # - when multiple filters are used they're in a 'should' section
        if 'should' in es_query:
            filters = {'type': ['cloudify_event', 'cloudify_log']}
        else:
            filters = {'type': ['cloudify_event']}
        filters['execution_id'] = [
            es_query['must'][0]['match']['context.execution_id'],
        ]
        pagination = {
            'size': request_dict.get('size', self.DEFAULT_SEARCH_SIZE),
            'offset': request_dict['from'],
        }
        sort = {
            field: value['order']
            for es_sort in request_dict['sort']
            for field, value in es_sort.items()
        }
        # TBD: Support range filters in API v1 if needed
        range_filters = {}

        params = {
            'limit': pagination['size'],
            'offset': pagination['offset'],
        }

        select_query, total = self._build_select_query(filters, sort,
                                                       range_filters,
                                                       self.current_tenant.id)

        events = [
            self._map_event_to_dict(_include, event)
            for event in select_query.params(**params).all()
        ]

        results = {
            'hits': {
                'hits': [{
                    '_source': event
                } for event in events],
                'total': total,
            },
        }

        return results
Exemplo n.º 22
0
    def post(self):
        request_dict = get_json_and_verify_params({
            'deployment_group_id': {'type': str},
            'workflow_id': {'type': str},
            'default_parameters': {'optional': True},
            'parameters': {'optional': True},
            'force': {'optional': True},
            'concurrency': {'optional': True},
        })
        default_parameters = request_dict.get('default_parameters') or {}
        parameters = request_dict.get('parameters') or {}
        workflow_id = request_dict['workflow_id']
        force = request_dict.get('force') or False
        concurrency = request_dict.get('concurrency', 5)

        sm = get_storage_manager()
        dep_group = sm.get(models.DeploymentGroup,
                           request_dict['deployment_group_id'])
        group = models.ExecutionGroup(
            id=str(uuid.uuid4()),
            deployment_group=dep_group,
            workflow_id=workflow_id,
            visibility=dep_group.visibility,
            concurrency=concurrency,
        )
        sm.put(group)
        rm = get_resource_manager()
        executions = []
        with sm.transaction():
            for dep in dep_group.deployments:
                params = default_parameters.copy()
                params.update(parameters.get(dep.id) or {})
                try:
                    execution = models.Execution(
                        workflow_id=workflow_id,
                        deployment=dep,
                        parameters=params,
                        status=ExecutionState.PENDING,
                    )
                except NonexistentWorkflowError as ex:
                    log = models.Log(
                        reported_timestamp=datetime.utcnow(),
                        message=str(ex),
                        logger='cloudify-restservice',
                        level='info',
                        execution_group=group
                    )
                    sm.put(log)
                else:
                    sm.put(execution)
                    executions.append(execution)
                    group.executions.append(execution)

        amqp_client = get_amqp_client()
        handler = workflow_sendhandler()
        amqp_client.add_handler(handler)
        with amqp_client:
            group.start_executions(sm, rm, handler, force=force)
        return group
Exemplo n.º 23
0
 def _validate_import_secrets_params():
     request_dict = rest_utils.get_json_and_verify_params({
         'secrets_list': {'type': list, 'optional': False},
         'tenant_map': {'type': dict, 'optional': True},
         'passphrase': {'type': unicode, 'optional': True},
         'override_collisions': {'type': bool, 'optional': False}
     })
     return request_dict
Exemplo n.º 24
0
 def patch(self, operation_id, **kwargs):
     request_dict = get_json_and_verify_params(
         {'state': {'type': unicode}}
     )
     sm = get_storage_manager()
     instance = sm.get(models.Operation, operation_id, locking=True)
     instance.state = request_dict.get('state', instance.state)
     return sm.update(instance)
Exemplo n.º 25
0
 def patch(self, operation_id, **kwargs):
     request_dict = get_json_and_verify_params(
         {'state': {'type': text_type}}
     )
     sm = get_storage_manager()
     instance = sm.get(models.Operation, operation_id, locking=True)
     instance.state = request_dict.get('state', instance.state)
     return sm.update(instance)
Exemplo n.º 26
0
    def patch(self, snapshot_id):
        """Update snapshot status by id
        """
        request_dict = rest_utils.get_json_and_verify_params({'status'})
        snapshot = get_storage_manager().get(models.Snapshot, snapshot_id)

        snapshot.status = request_dict['status']
        snapshot.error = request_dict.get('error', '')
        get_storage_manager().update(snapshot)
Exemplo n.º 27
0
    def patch(self, snapshot_id):
        """Update snapshot status by id
        """
        request_dict = rest_utils.get_json_and_verify_params({'status'})
        snapshot = get_storage_manager().get(models.Snapshot, snapshot_id)

        snapshot.status = request_dict['status']
        snapshot.error = request_dict.get('error', '')
        get_storage_manager().update(snapshot)
Exemplo n.º 28
0
        def wrapper(*args, **kwargs):

            # getting the tenant name
            if get_tenant_from == 'header':
                tenant_name = tenant_for_auth or request.headers.get(
                    CLOUDIFY_TENANT_HEADER)
            elif get_tenant_from == 'param':
                tenant_name = tenant_for_auth or kwargs['tenant_name']
            elif get_tenant_from == 'data':
                tenant_name = tenant_for_auth or get_json_and_verify_params({
                    'tenant_name': {
                        'type': unicode
                    }
                }).get('tenant_name')
            else:
                tenant_name = tenant_for_auth

            # finding tenant to add to the app config
            if tenant_name:
                try:
                    tenant = get_storage_manager().get(
                        Tenant, tenant_name, filters={'name': tenant_name})
                    utils.set_current_tenant(tenant)
                except NotFoundError:
                    raise ForbiddenError(
                        'Authorization failed: Tried to authenticate with '
                        'invalid tenant name: {0}'.format(tenant_name))

            # when running unittests, there is no authorization
            if config.instance.test_mode:
                return func(*args, **kwargs)

            # extracting tenant roles for user in the tenant
            tenant_roles = []
            for t in current_user.all_tenants:
                if (allow_all_tenants and request_use_all_tenants()) \
                        or t.name == tenant_name:
                    tenant_roles += current_user.all_tenants[t]

            # joining user's system role with his tenant roles
            user_roles = [role.name for role in tenant_roles] \
                + current_user.system_roles

            # getting the roles allowed to perform requested action
            action_roles = config.instance.authorization_permissions[action]

            # checking if any of the user's roles is allowed to perform action
            for user_role in user_roles:
                if user_role in action_roles:
                    return func(*args, **kwargs)

            # none of the user's role is allowed to perform the action
            error_message = 'User `{0}` is not permitted to perform the ' \
                            'action {1}'.format(current_user.username, action)
            if tenant_name:
                error_message += ' in the tenant `{0}`'.format(tenant_name)
            raise ForbiddenError(error_message)
Exemplo n.º 29
0
 def patch(self, name):
     """
     Update an existing agent
     """
     request_dict = get_json_and_verify_params({'state': {'type': unicode}})
     validate_inputs({'name': name})
     state = request_dict['state']
     self._validate_state(state)
     return self._update_agent(name, state)
Exemplo n.º 30
0
    def patch(self, execution_id, **kwargs):
        """
        Update execution status by id
        """
        request_dict = get_json_and_verify_params({'status'})

        return get_resource_manager().update_execution_status(
            execution_id, request_dict['status'],
            request_dict.get('error', ''))
Exemplo n.º 31
0
 def _get_request_data():
     return rest_utils.get_json_and_verify_params({
         'deployment_id': {
             'type': text_type
         },
         'update_service_composition': {
             'type': bool
         },
     })
Exemplo n.º 32
0
    def patch(self, filters_model, filter_id, filtered_resource):
        """Update a filter by its ID

        This function updates the filter rules and visibility
        """
        rest_utils.validate_inputs({'filter_id': filter_id})
        if not request.json:
            raise manager_exceptions.IllegalActionError(
                'Update a filter request must include at least one parameter '
                'to update')

        request_dict = rest_utils.get_json_and_verify_params(
            {'filter_rules': {
                'type': list,
                'optional': True
            }})

        filter_rules = request_dict.get('filter_rules')
        visibility = rest_utils.get_visibility_parameter(
            optional=True, valid_values=VisibilityState.STATES)

        storage_manager = get_storage_manager()
        filter_elem = storage_manager.get(filters_model, filter_id)
        _verify_not_a_system_filter(filter_elem, 'update')
        if visibility:
            get_resource_manager().validate_visibility_value(
                filters_model, filter_elem, visibility)
            filter_elem.visibility = visibility
        if filter_rules:
            new_filter_rules = create_filter_rules_list(
                filter_rules, filtered_resource)
            new_attrs_filter_rules = _get_filter_rules_by_type(
                new_filter_rules, 'attribute')
            new_labels_filter_rules = _get_filter_rules_by_type(
                new_filter_rules, 'label')
            if new_attrs_filter_rules:
                if new_labels_filter_rules:  # Both need to be updated
                    filter_elem.value = new_filter_rules
                else:  # Only labels filter rules should be saved
                    filter_elem.value = (filter_elem.labels_filter_rules +
                                         new_filter_rules)

            elif new_labels_filter_rules:
                # Only attributes filter rules should be saved
                filter_elem.value = (filter_elem.attrs_filter_rules +
                                     new_filter_rules)

            else:  # Should not get here
                raise manager_exceptions.BadParametersError(
                    'Unknown filter rules type')

        filter_elem.updated_at = get_formatted_timestamp()

        return storage_manager.update(filter_elem)
Exemplo n.º 33
0
 def patch(self, name):
     """
     Update an existing agent
     """
     request_dict = get_json_and_verify_params({
         'state': {'type': unicode}
     })
     validate_inputs({'name': name})
     state = request_dict['state']
     self._validate_state(state)
     return self._update_agent(name, state)
Exemplo n.º 34
0
    def patch(self, execution_id, **kwargs):
        """
        Update execution status by id
        """
        request_dict = get_json_and_verify_params({'status'})

        return get_resource_manager().update_execution_status(
            execution_id,
            request_dict['status'],
            request_dict.get('error', '')
        )
Exemplo n.º 35
0
 def post(self, **kwargs):
     params = get_json_and_verify_params({
         'name': {'type': text_type, 'required': True},
         'execution_id': {'type': text_type, 'required': True},
         'operations': {'required': False}
     })
     tasks_graph = get_resource_manager().create_tasks_graph(
         name=params['name'],
         execution_id=params['execution_id'],
         operations=params.get('operations', [])
     )
     return tasks_graph, 201
Exemplo n.º 36
0
 def post(self, **kwargs):
     request_dict = get_json_and_verify_params({
         'deployment_id': {},
         'context': {'optional': True, 'type': dict},
         'nodes': {'optional': True, 'type': dict}
     })
     deployment_id = request_dict['deployment_id']
     context = request_dict.get('context', {})
     nodes = request_dict.get('nodes', {})
     modification = get_resource_manager(). \
         start_deployment_modification(deployment_id, nodes, context)
     return modification, 201
Exemplo n.º 37
0
 def post(self, **kwargs):
     params = get_json_and_verify_params({
         'name': {'type': unicode, 'required': True},
         'execution_id': {'type': unicode, 'required': True},
         'operations': {'required': False}
     })
     tasks_graph = get_resource_manager().create_tasks_graph(
         name=params['name'],
         execution_id=params['execution_id'],
         operations=params.get('operations', [])
     )
     return tasks_graph, 201
Exemplo n.º 38
0
 def post(self, **kwargs):
     request_dict = get_json_and_verify_params({
         'deployment_id': {},
         'context': {'optional': True, 'type': dict},
         'nodes': {'optional': True, 'type': dict}
     })
     deployment_id = request_dict['deployment_id']
     context = request_dict.get('context', {})
     nodes = request_dict.get('nodes', {})
     modification = get_resource_manager(). \
         start_deployment_modification(deployment_id, nodes, context)
     return modification, 201
Exemplo n.º 39
0
 def post(self):
     """
     Enable/Disable SSL
     """
     request_dict = rest_utils.get_json_and_verify_params({'state'})
     state = rest_utils.verify_and_convert_bool('state',
                                                request_dict.get('state'))
     status = 'enabled' if state else 'disabled'
     if state == SSLConfig._is_enabled():
         return 'SSL is already {0} on the manager'.format(status)
     else:
         self._set_ssl_state(state)
     return 'SSL is now {0} on the manager'.format(status)
Exemplo n.º 40
0
 def _validate_site_params(self, name):
     validate_inputs({'name': name})
     visibility = get_visibility_parameter(
         optional=True,
         valid_values=VisibilityState.STATES,
     )
     request_dict = get_json_and_verify_params({
         'location': {'type': text_type, 'optional': True},
         'new_name': {'type': text_type, 'optional': True}
     })
     request_dict['visibility'] = visibility
     self._validate_location(request_dict)
     return request_dict
Exemplo n.º 41
0
 def _validate_site_params(self, name):
     validate_inputs({'name': name})
     visibility = get_visibility_parameter(
         optional=True,
         valid_values=VisibilityState.STATES,
     )
     request_dict = get_json_and_verify_params({
         'location': {'type': unicode, 'optional': True},
         'new_name': {'type': unicode, 'optional': True}
     })
     request_dict['visibility'] = visibility
     self._validate_location(request_dict)
     return request_dict
        def wrapper(*args, **kwargs):

            # getting the tenant name
            if get_tenant_from == 'header':
                tenant_name = tenant_for_auth or request.headers.get(
                    CLOUDIFY_TENANT_HEADER)
            elif get_tenant_from == 'param':
                tenant_name = tenant_for_auth or kwargs['tenant_name']
            elif get_tenant_from == 'data':
                tenant_name = tenant_for_auth or get_json_and_verify_params(
                    {'tenant_name': {'type': unicode}}).get('tenant_name')
            else:
                tenant_name = tenant_for_auth

            # finding tenant to add to the app config
            if tenant_name:
                try:
                    tenant = get_storage_manager().get(
                        Tenant,
                        tenant_name,
                        filters={'name': tenant_name}
                    )
                    utils.set_current_tenant(tenant)
                except NotFoundError:
                    raise ForbiddenError(
                        'Authorization failed: Tried to authenticate with '
                        'invalid tenant name: {0}'.format(tenant_name)
                    )

            if not current_user.active:
                raise ForbiddenError(
                    'Authorization failed: '
                    'User `{0}` is deactivated'.format(current_user.username)
                )

            # when running unittests, there is no authorization
            if config.instance.test_mode:
                return func(*args, **kwargs)

            # checking if any of the user's roles is allowed to perform action
            if is_user_action_allowed(action, tenant_name, allow_all_tenants):
                return func(*args, **kwargs)

            # none of the user's role is allowed to perform the action
            error_message = 'User `{0}` is not permitted to perform the ' \
                            'action {1}'.format(current_user.username, action)
            if tenant_name:
                error_message += ' in the tenant `{0}`'.format(tenant_name)
            raise ForbiddenError(error_message)
Exemplo n.º 43
0
 def put(self, operation_id, **kwargs):
     params = get_json_and_verify_params({
         'name': {'type': unicode, 'required': True},
         'graph_id': {'type': unicode, 'required': True},
         'dependencies': {'type': list, 'required': True},
         'parameters': {'type': dict},
         'type': {'type': unicode}
     })
     operation = get_resource_manager().create_operation(
         operation_id,
         name=params['name'],
         graph_id=params['graph_id'],
         dependencies=params['dependencies'],
         type=params['type'],
         parameters=params['parameters']
     )
     return operation, 201
    def put(self, name):
        """Update a config value.

        Settings which have is_editable set to False, can only be edited
        when passing the force flag.
        If a schema is specified for the given setting, the new value
        must validate.
        Names can be prefixed with scope, using the same semantics as GET.
        """
        data = rest_utils.get_json_and_verify_params({
            'value': {},
            'force': {'type': bool, 'optional': True}
        })
        value = data['value']
        force = data.get('force', False)
        config.instance.update_db({name: value}, force)

        return self._get_config(name)
Exemplo n.º 45
0
 def post(self, snapshot_id):
     request_dict = rest_utils.get_json_and_verify_params(
         {'recreate_deployments_envs'}
     )
     recreate_deployments_envs = rest_utils.verify_and_convert_bool(
         'recreate_deployments_envs',
         request_dict['recreate_deployments_envs']
     )
     force = rest_utils.verify_and_convert_bool(
         'force',
         request_dict['force']
     )
     restore_certificates = rest_utils.verify_and_convert_bool(
         'restore_certificates',
         request_dict.get('restore_certificates', 'false')
     )
     no_reboot = rest_utils.verify_and_convert_bool(
         'no_reboot',
         request_dict.get('no_reboot', 'false')
     )
     ignore_plugin_failure = \
         rest_utils.verify_and_convert_bool(
             'ignore_plugin_failure',
             request_dict.get('ignore_plugin_failure', 'false')
         )
     if no_reboot and not restore_certificates:
         raise manager_exceptions.BadParametersError(
             '`no_reboot` is only relevant when `restore_certificates` is '
             'activated')
     default_timeout_sec = 300
     request_timeout = request_dict.get('timeout', default_timeout_sec)
     timeout = rest_utils.convert_to_int(request_timeout)
     execution = get_resource_manager().restore_snapshot(
         snapshot_id,
         recreate_deployments_envs,
         force,
         True,
         timeout,
         restore_certificates,
         no_reboot,
         ignore_plugin_failure
     )
     return execution, 200
Exemplo n.º 46
0
    def post(self, execution_id, **kwargs):
        """
        Apply execution action (cancel, force-cancel) by id
        """
        request_dict = get_json_and_verify_params({'action'})
        action = request_dict['action']

        valid_actions = ['cancel', 'force-cancel', 'kill', 'resume',
                         'force-resume']

        if action not in valid_actions:
            raise manager_exceptions.BadParametersError(
                'Invalid action: {0}, Valid action values are: {1}'.format(
                    action, valid_actions))

        if action in ('resume', 'force-resume'):
            return get_resource_manager().resume_execution(
                execution_id, force=action == 'force-resume')
        return get_resource_manager().cancel_execution(
            execution_id, action == 'force-cancel', action == 'kill')
Exemplo n.º 47
0
    def post(self, **kwargs):
        """Execute a workflow"""
        request_dict = get_json_and_verify_params({'deployment_id',
                                                   'workflow_id'})

        allow_custom_parameters = verify_and_convert_bool(
            'allow_custom_parameters',
            request_dict.get('allow_custom_parameters', 'false'))
        force = verify_and_convert_bool(
            'force',
            request_dict.get('force', 'false'))
        dry_run = verify_and_convert_bool(
            'dry_run',
            request_dict.get('dry_run', 'false'))
        queue = verify_and_convert_bool(
            'queue',
            request_dict.get('queue', 'false'))

        deployment_id = request_dict['deployment_id']
        workflow_id = request_dict['workflow_id']
        parameters = request_dict.get('parameters', None)
        wait_after_fail = request_dict.get('wait_after_fail', 600)
        scheduled_time = request_dict.get('scheduled_time', None)

        if scheduled_time:
            scheduled_time = parse_datetime(scheduled_time)

        if parameters is not None and parameters.__class__ is not dict:
            raise manager_exceptions.BadParametersError(
                "request body's 'parameters' field must be a dict but"
                " is of type {0}".format(parameters.__class__.__name__))

        bypass_maintenance = is_bypass_maintenance_mode()
        execution = get_resource_manager().execute_workflow(
            deployment_id, workflow_id, parameters=parameters,
            allow_custom_parameters=allow_custom_parameters, force=force,
            dry_run=dry_run, bypass_maintenance=bypass_maintenance,
            queue=queue, wait_after_fail=wait_after_fail,
            scheduled_time=scheduled_time)
        return execution, 201
Exemplo n.º 48
0
 def put(self, deployment_id, **kwargs):
     """
     Create a deployment
     """
     validate_inputs({'deployment_id': deployment_id})
     request_schema = self.create_request_schema()
     request_dict = get_json_and_verify_params(request_schema)
     blueprint_id = request_dict['blueprint_id']
     bypass_maintenance = is_bypass_maintenance_mode()
     args = get_args_and_verify_arguments(
         [Argument('private_resource', type=boolean,
                   default=False)]
     )
     deployment = get_resource_manager().create_deployment(
         blueprint_id,
         deployment_id,
         private_resource=args.private_resource,
         visibility=None,
         inputs=request_dict.get('inputs', {}),
         bypass_maintenance=bypass_maintenance,
         skip_plugins_validation=self.get_skip_plugin_validation_flag(
             request_dict)
     )
     return deployment, 201