def _task_utils_create_function(self, event, *args, **kwargs):
        """Function: A function which can be used to create a custom task using the REST API."""
        try:
            payload = ResultPayload("task_utils_create", **kwargs)
            # Get the function parameters:
            incident_id = get_function_input(kwargs, "incident_id")  # number
            task_name = get_function_input(kwargs, "task_name",
                                           optional=True)  # text
            task_utils_payload = self.get_textarea_param(
                kwargs.get("task_utils_payload"))  # textarea

            log = logging.getLogger(__name__)
            log.info("incident_id: %s", incident_id)
            log.info("task_name: %s", task_name)
            log.info("task_utils_payload: %s", task_utils_payload)

            try:
                task_utils_payload = json.loads(task_utils_payload)
            except Exception as json_exception:
                err_msg = "Could not load task_utils_payload as JSON. Error: {}", json_exception
                log.error(err_msg)
                raise TypeError(err_msg)
            else:
                log.debug(
                    "Successfully parsed task_utils_payload as valid JSON")

            resilient_client = self.rest_client()

            # Replace task_json["name"] if task_name is set and task_json["name"] is not set; otherwise use default name
            # If task_json["name"] is set, do nothing, use that
            task_utils_payload[
                "name"] = task_name if not task_utils_payload.get(
                    "name", False) and task_name else "Default Task Name"

            log.debug("New task will be saved with name %s",
                      task_utils_payload["name"])
            yield StatusMessage("Posting to API")
            try:
                task_response = resilient_client.post(
                    '/incidents/{}/tasks'.format(incident_id),
                    task_utils_payload)
            except Exception as add_note_exception:
                err_msg = "Encountered exception while trying to create task. Error: {}", add_note_exception
                raise ValueError(err_msg)

            log.info("Response from Resilient %s", task_response)

            yield StatusMessage("Created task with ID: {}".format(
                task_response.get('id', 'No task ID found')))

            results = payload.done(success=True,
                                   content={"task": task_response})
            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
Пример #2
0
    def _task_utils_add_note_function(self, event, *args, **kwargs):
        """Function: A function which takes in the ID of an existing Task and then adds either a plain or richtext note to the Task."""
        try:
            payload = ResultPayload("task_utils_add_note", **kwargs)
            # Get the function parameters:
            incident_id = get_function_input(kwargs, "incident_id")  # number
            task_id = get_function_input(kwargs, "task_id",
                                         optional=True)  # number
            task_name = get_function_input(kwargs, "task_name",
                                           optional=True)  # text
            task_utils_note_type = self.get_select_param(
                kwargs.get(
                    "task_utils_note_type"))  # select, values: "text", "html"
            task_utils_note_body = get_function_input(kwargs,
                                                      "task_utils_note_body",
                                                      optional=True)  # text

            log = logging.getLogger(__name__)
            log.info("incident_id: %s", incident_id)
            log.info("task_id: %s", task_id)
            log.info("task_name: %s", task_name)
            log.info("task_utils_note_type: %s", task_utils_note_type)
            log.info("task_utils_note_body: %s", task_utils_note_body)

            if not task_name and not task_id:
                raise ValueError(
                    "Either a Task ID or a Task Name to search for must be provided."
                )

            task_note_json = {
                "text": {
                    "format": task_utils_note_type,
                    "content": task_utils_note_body
                }
            }

            res_client = self.rest_client()

            if task_name:
                yield StatusMessage(
                    "task_name was provided; Searching incident {} for first matching task with name '{}'"
                    .format(incident_id, task_name))

                task_id = find_task_by_name(res_client, incident_id, task_name)

                if not task_id:
                    raise ValueError(
                        u"Could not find task with name {}".format(task_name))

            yield StatusMessage("Posting note to API")
            try:
                task_response = res_client.post(
                    '/tasks/{}/comments'.format(task_id), task_note_json)
            except Exception as add_note_exception:
                err_msg = "Encountered exception while trying to add note to task. Error: %s", add_note_exception
                raise ValueError(err_msg)

            yield StatusMessage("Completed API call")

            results = payload.done(success=True,
                                   content={"task_note": task_response})

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
    def _task_utils_close_task_function(self, event, *args, **kwargs):
        """Function: A function which will attempt to close either a System or Custom task using the REST API."""
        def close_task_status(task):
            """
            A inner function which is used as a lambda
            Get_put from the res_client gets our data and this lambda decides what to do with the data
            The return value of this lambda is then sent to Resilient as a PUT.
            :param task:
            :return task:
            """
            task["status"] = "C"
            log.debug("Changed status to closed for task with name %s" %
                      task["name"])
            return task

        try:
            payload = ResultPayload("task_utils_close_task", **kwargs)
            # Get the function parameters:
            incident_id = get_function_input(kwargs, "incident_id")  # number
            task_id = get_function_input(kwargs, "task_id",
                                         optional=True)  # number
            task_name = get_function_input(kwargs, "task_name",
                                           optional=True)  # text

            log = logging.getLogger(__name__)
            log.info("incident_id: %s", incident_id)
            log.info("task_id: %s", task_id)
            log.info("task_name: %s", task_name)

            res_client = self.rest_client()

            if not task_name and not task_id:
                raise ValueError(
                    "Either a Task ID or a Task Name to search for must be provided."
                )

            if task_id:
                log.debug(
                    "Task ID was provided, using this to contact REST API")

            else:
                if task_name:
                    yield StatusMessage(
                        u"task_name was provided; Searching incident {} for first matching task with name '{}'"
                        .format(incident_id, task_name))

                    task_id = find_task_by_name(res_client, incident_id,
                                                task_name)

                    if not task_id:
                        raise ValueError(
                            u"Could not find task with name {}".format(
                                task_name))

            task_url = "/tasks/{}".format(task_id)
            try:
                res_client.get_put(task_url,
                                   lambda task: close_task_status(task))
            except Exception as close_exception:
                err_msg = "Encountered exception while trying to close task. Error: {}", close_exception
                raise ValueError(err_msg)
            yield StatusMessage("Task {} has been closed".format(task_id))

            results = payload.done(success=True,
                                   content={
                                       "task_id": task_id,
                                       "task_name": task_name
                                   })
            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()
    def _task_utils_update_task_function(self, event, *args, **kwargs):
        """Function: A function which takes in the ID of an existing Task and a task_utils_payload which is a JSON String of the task details to update."""
        def update_task(task):
            """
            A inner function which is used as a lambda
            The return value of this lambda is then sent to Resilient as a PUT.

            In this case we also update an outer scope variable called updated_task
             with the value of the newly modified task object before returning it
            :param task:
            :return:
            """
            task.update(json.loads(task_utils_payload))
            updated_task.update(task)
            return task

        try:
            payload = ResultPayload("task_utils_update_task", **kwargs)

            # Get the function parameters:
            incident_id = get_function_input(kwargs, "incident_id")  # number
            task_id = get_function_input(kwargs, "task_id",
                                         optional=True)  # number
            task_name = get_function_input(kwargs, "task_name",
                                           optional=True)  # text
            task_utils_payload = self.get_textarea_param(
                kwargs.get("task_utils_payload"))  # textarea

            if not task_name and not task_id:
                raise ValueError(
                    "Either a Task ID or a Task Name to search for must be provided."
                )

            log = logging.getLogger(__name__)
            log.info(kwargs.get("task_utils_payload"))

            log.info("incident_id: %s", incident_id)
            log.info("task_id: %s", task_id)
            log.info("task_name: %s", task_name)
            log.info("task_utils_payload: %s", task_utils_payload)

            try:
                json.loads(task_utils_payload)
            except Exception as json_exception:
                err_msg = "Could not load task_utils_payload as JSON. Error: {}", json_exception
                log.error(err_msg)
                raise TypeError(err_msg)

            res_client = self.rest_client()

            # If task name was provided try to find its ID
            if task_name:
                yield StatusMessage(
                    u"task_name was provided; Searching incident {} for first matching task with name '{}'"
                    .format(incident_id, task_name))
                task_id = find_task_by_name(res_client, incident_id, task_name)

                if not task_id:
                    raise ValueError("task_name not found: %s", task_name)

            log.info("Sending new task info to res")
            updated_task = {}

            task_url = "/tasks/{}".format(task_id)
            try:
                res_client.get_put(task_url, lambda task: update_task(task))
            except Exception as update_exception:
                err_msg = "Encountered exception while trying to update task. Error: {}", update_exception
                raise ValueError(err_msg)

            yield StatusMessage("Task {} has been updated".format(task_id))

            results = payload.done(success=True,
                                   content={
                                       "task_id": task_id,
                                       "task": updated_task
                                   })
            log.info("Complete")

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()