Пример #1
0
    def __init__(
        self,
        *,
        job_name: str,
        job_definition: str,
        job_queue: str,
        overrides: dict,
        array_properties: Optional[dict] = None,
        parameters: Optional[dict] = None,
        job_id: Optional[str] = None,
        waiters: Optional[Any] = None,
        max_retries: Optional[int] = None,
        status_retries: Optional[int] = None,
        aws_conn_id: Optional[str] = None,
        region_name: Optional[str] = None,
        tags: Optional[dict] = None,
        **kwargs,
    ):

        BaseOperator.__init__(self, **kwargs)
        self.job_id = job_id
        self.job_name = job_name
        self.job_definition = job_definition
        self.job_queue = job_queue
        self.overrides = overrides or {}
        self.array_properties = array_properties or {}
        self.parameters = parameters or {}
        self.waiters = waiters
        self.tags = tags or {}
        self.hook = BatchClientHook(
            max_retries=max_retries,
            status_retries=status_retries,
            aws_conn_id=aws_conn_id,
            region_name=region_name,
        )
Пример #2
0
 def hook(self):
     """Create and return a BatchClientHook"""
     return BatchClientHook(
         max_retries=self.max_retries,
         status_retries=self.status_retries,
         aws_conn_id=self.aws_conn_id,
         region_name=self.region_name,
     )
Пример #3
0
    def get_hook(self) -> BatchClientHook:
        """Create and return a BatchClientHook"""
        if self.hook:
            return self.hook

        self.hook = BatchClientHook(
            aws_conn_id=self.aws_conn_id,
            region_name=self.region_name,
        )
        return self.hook
Пример #4
0
class BatchOperator(BaseOperator):
    """
    Execute a job on AWS Batch

    :param job_name: the name for the job that will run on AWS Batch (templated)

    :param job_definition: the job definition name on AWS Batch

    :param job_queue: the queue name on AWS Batch

    :param overrides: the `containerOverrides` parameter for boto3 (templated)

    :param array_properties: the `arrayProperties` parameter for boto3

    :param parameters: the `parameters` for boto3 (templated)

    :param job_id: the job ID, usually unknown (None) until the
        submit_job operation gets the jobId defined by AWS Batch

    :param waiters: an :py:class:`.BatchWaiters` object (see note below);
        if None, polling is used with max_retries and status_retries.

    :param max_retries: exponential back-off retries, 4200 = 48 hours;
        polling is only used when waiters is None

    :param status_retries: number of HTTP retries to get job status, 10;
        polling is only used when waiters is None

    :param aws_conn_id: connection id of AWS credentials / region name. If None,
        credential boto3 strategy will be used.

    :param region_name: region name to use in AWS Hook.
        Override the region_name in connection (if provided)

    :param tags: collection of tags to apply to the AWS Batch job submission
        if None, no tags are submitted

    .. note::
        Any custom waiters must return a waiter for these calls:
        .. code-block:: python

            waiter = waiters.get_waiter("JobExists")
            waiter = waiters.get_waiter("JobRunning")
            waiter = waiters.get_waiter("JobComplete")
    """

    ui_color = "#c3dae0"
    arn = None  # type: Optional[str]
    template_fields: Sequence[str] = (
        "job_name",
        "overrides",
        "parameters",
    )
    template_fields_renderers = {"overrides": "json", "parameters": "json"}

    def __init__(
        self,
        *,
        job_name: str,
        job_definition: str,
        job_queue: str,
        overrides: dict,
        array_properties: Optional[dict] = None,
        parameters: Optional[dict] = None,
        job_id: Optional[str] = None,
        waiters: Optional[Any] = None,
        max_retries: Optional[int] = None,
        status_retries: Optional[int] = None,
        aws_conn_id: Optional[str] = None,
        region_name: Optional[str] = None,
        tags: Optional[dict] = None,
        **kwargs,
    ):

        BaseOperator.__init__(self, **kwargs)
        self.job_id = job_id
        self.job_name = job_name
        self.job_definition = job_definition
        self.job_queue = job_queue
        self.overrides = overrides or {}
        self.array_properties = array_properties or {}
        self.parameters = parameters or {}
        self.waiters = waiters
        self.tags = tags or {}
        self.hook = BatchClientHook(
            max_retries=max_retries,
            status_retries=status_retries,
            aws_conn_id=aws_conn_id,
            region_name=region_name,
        )

    def execute(self, context: 'Context'):
        """
        Submit and monitor an AWS Batch job

        :raises: AirflowException
        """
        self.submit_job(context)
        self.monitor_job(context)

    def on_kill(self):
        response = self.hook.client.terminate_job(jobId=self.job_id, reason="Task killed by the user")
        self.log.info("AWS Batch job (%s) terminated: %s", self.job_id, response)

    def submit_job(self, context: 'Context'):
        """
        Submit an AWS Batch job

        :raises: AirflowException
        """
        self.log.info(
            "Running AWS Batch job - job definition: %s - on queue %s",
            self.job_definition,
            self.job_queue,
        )
        self.log.info("AWS Batch job - container overrides: %s", self.overrides)

        try:
            response = self.hook.client.submit_job(
                jobName=self.job_name,
                jobQueue=self.job_queue,
                jobDefinition=self.job_definition,
                arrayProperties=self.array_properties,
                parameters=self.parameters,
                containerOverrides=self.overrides,
                tags=self.tags,
            )
            self.job_id = response["jobId"]

            self.log.info("AWS Batch job (%s) started: %s", self.job_id, response)
        except Exception as e:
            self.log.error("AWS Batch job (%s) failed submission", self.job_id)
            raise AirflowException(e)

    def monitor_job(self, context: 'Context'):
        """
        Monitor an AWS Batch job
        monitor_job can raise an exception or an AirflowTaskTimeout can be raised if execution_timeout
        is given while creating the task. These exceptions should be handled in taskinstance.py
        instead of here like it was previously done

        :raises: AirflowException
        """
        if not self.job_id:
            raise AirflowException('AWS Batch job - job_id was not found')

        if self.waiters:
            self.waiters.wait_for_job(self.job_id)
        else:
            self.hook.wait_for_job(self.job_id)

        self.hook.check_job_success(self.job_id)
        self.log.info("AWS Batch job (%s) succeeded", self.job_id)
Пример #5
0
class BatchOperator(BaseOperator):
    """
    Execute a job on AWS Batch

    .. seealso::
        For more information on how to use this operator, take a look at the guide:
        :ref:`howto/operator:BatchOperator`

    :param job_name: the name for the job that will run on AWS Batch (templated)

    :param job_definition: the job definition name on AWS Batch

    :param job_queue: the queue name on AWS Batch

    :param overrides: the `containerOverrides` parameter for boto3 (templated)

    :param array_properties: the `arrayProperties` parameter for boto3

    :param parameters: the `parameters` for boto3 (templated)

    :param job_id: the job ID, usually unknown (None) until the
        submit_job operation gets the jobId defined by AWS Batch

    :param waiters: an :py:class:`.BatchWaiters` object (see note below);
        if None, polling is used with max_retries and status_retries.

    :param max_retries: exponential back-off retries, 4200 = 48 hours;
        polling is only used when waiters is None

    :param status_retries: number of HTTP retries to get job status, 10;
        polling is only used when waiters is None

    :param aws_conn_id: connection id of AWS credentials / region name. If None,
        credential boto3 strategy will be used.

    :param region_name: region name to use in AWS Hook.
        Override the region_name in connection (if provided)

    :param tags: collection of tags to apply to the AWS Batch job submission
        if None, no tags are submitted

    .. note::
        Any custom waiters must return a waiter for these calls:
        .. code-block:: python

            waiter = waiters.get_waiter("JobExists")
            waiter = waiters.get_waiter("JobRunning")
            waiter = waiters.get_waiter("JobComplete")
    """

    ui_color = "#c3dae0"
    arn = None  # type: Optional[str]
    template_fields: Sequence[str] = (
        "job_name",
        "job_queue",
        "job_definition",
        "overrides",
        "parameters",
    )
    template_fields_renderers = {"overrides": "json", "parameters": "json"}

    @property
    def operator_extra_links(self):
        op_extra_links = [BatchJobDetailsLink()]
        if self.wait_for_completion:
            op_extra_links.extend(
                [BatchJobDefinitionLink(),
                 BatchJobQueueLink()])
        if not self.array_properties:
            # There is no CloudWatch Link to the parent Batch Job available.
            op_extra_links.append(CloudWatchEventsLink())

        return tuple(op_extra_links)

    def __init__(
        self,
        *,
        job_name: str,
        job_definition: str,
        job_queue: str,
        overrides: dict,
        array_properties: Optional[dict] = None,
        parameters: Optional[dict] = None,
        job_id: Optional[str] = None,
        waiters: Optional[Any] = None,
        max_retries: Optional[int] = None,
        status_retries: Optional[int] = None,
        aws_conn_id: Optional[str] = None,
        region_name: Optional[str] = None,
        tags: Optional[dict] = None,
        wait_for_completion: bool = True,
        **kwargs,
    ):

        BaseOperator.__init__(self, **kwargs)
        self.job_id = job_id
        self.job_name = job_name
        self.job_definition = job_definition
        self.job_queue = job_queue
        self.overrides = overrides or {}
        self.array_properties = array_properties or {}
        self.parameters = parameters or {}
        self.waiters = waiters
        self.tags = tags or {}
        self.wait_for_completion = wait_for_completion
        self.hook = BatchClientHook(
            max_retries=max_retries,
            status_retries=status_retries,
            aws_conn_id=aws_conn_id,
            region_name=region_name,
        )

    def execute(self, context: 'Context'):
        """
        Submit and monitor an AWS Batch job

        :raises: AirflowException
        """
        self.submit_job(context)

        if self.wait_for_completion:
            self.monitor_job(context)

        return self.job_id

    def on_kill(self):
        response = self.hook.client.terminate_job(
            jobId=self.job_id, reason="Task killed by the user")
        self.log.info("AWS Batch job (%s) terminated: %s", self.job_id,
                      response)

    def submit_job(self, context: 'Context'):
        """
        Submit an AWS Batch job

        :raises: AirflowException
        """
        self.log.info(
            "Running AWS Batch job - job definition: %s - on queue %s",
            self.job_definition,
            self.job_queue,
        )
        self.log.info("AWS Batch job - container overrides: %s",
                      self.overrides)

        try:
            response = self.hook.client.submit_job(
                jobName=self.job_name,
                jobQueue=self.job_queue,
                jobDefinition=self.job_definition,
                arrayProperties=self.array_properties,
                parameters=self.parameters,
                containerOverrides=self.overrides,
                tags=self.tags,
            )
        except Exception as e:
            self.log.error(
                "AWS Batch job failed submission - job definition: %s - on queue %s",
                self.job_definition,
                self.job_queue,
            )
            raise AirflowException(e)

        self.job_id = response["jobId"]
        self.log.info("AWS Batch job (%s) started: %s", self.job_id, response)
        BatchJobDetailsLink.persist(
            context=context,
            operator=self,
            region_name=self.hook.conn_region_name,
            aws_partition=self.hook.conn_partition,
            job_id=self.job_id,
        )

    def monitor_job(self, context: 'Context'):
        """
        Monitor an AWS Batch job
        monitor_job can raise an exception or an AirflowTaskTimeout can be raised if execution_timeout
        is given while creating the task. These exceptions should be handled in taskinstance.py
        instead of here like it was previously done

        :raises: AirflowException
        """
        if not self.job_id:
            raise AirflowException('AWS Batch job - job_id was not found')

        try:
            job_desc = self.hook.get_job_description(self.job_id)
            job_definition_arn = job_desc["jobDefinition"]
            job_queue_arn = job_desc["jobQueue"]
            self.log.info(
                "AWS Batch job (%s) Job Definition ARN: %r, Job Queue ARN: %r",
                self.job_id,
                job_definition_arn,
                job_queue_arn,
            )
        except KeyError:
            self.log.warning(
                "AWS Batch job (%s) can't get Job Definition ARN and Job Queue ARN",
                self.job_id)
        else:
            BatchJobDefinitionLink.persist(
                context=context,
                operator=self,
                region_name=self.hook.conn_region_name,
                aws_partition=self.hook.conn_partition,
                job_definition_arn=job_definition_arn,
            )
            BatchJobQueueLink.persist(
                context=context,
                operator=self,
                region_name=self.hook.conn_region_name,
                aws_partition=self.hook.conn_partition,
                job_queue_arn=job_queue_arn,
            )

        if self.waiters:
            self.waiters.wait_for_job(self.job_id)
        else:
            self.hook.wait_for_job(self.job_id)

        awslogs = self.hook.get_job_awslogs_info(self.job_id)
        if awslogs:
            self.log.info(
                "AWS Batch job (%s) CloudWatch Events details found: %s",
                self.job_id, awslogs)
            CloudWatchEventsLink.persist(
                context=context,
                operator=self,
                region_name=self.hook.conn_region_name,
                aws_partition=self.hook.conn_partition,
                **awslogs,
            )

        self.hook.check_job_success(self.job_id)
        self.log.info("AWS Batch job (%s) succeeded", self.job_id)
Пример #6
0
 def hook(self) -> BatchClientHook:
     """Create and return a BatchClientHook"""
     return BatchClientHook(
         aws_conn_id=self.aws_conn_id,
         region_name=self.region_name,
     )