Source code for airflow.providers.amazon.aws.operators.kinesis_analytics
# Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The ASF licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.from__future__importannotationsfromtypingimportTYPE_CHECKING,Any,Sequencefrombotocore.exceptionsimportClientErrorfromairflow.configurationimportconffromairflow.exceptionsimportAirflowExceptionfromairflow.providers.amazon.aws.hooks.kinesis_analyticsimportKinesisAnalyticsV2Hookfromairflow.providers.amazon.aws.operators.base_awsimportAwsBaseOperatorfromairflow.providers.amazon.aws.triggers.kinesis_analyticsimport(KinesisAnalyticsV2ApplicationOperationCompleteTrigger,)fromairflow.providers.amazon.aws.utilsimportvalidate_execute_complete_eventfromairflow.providers.amazon.aws.utils.mixinsimportaws_template_fieldsifTYPE_CHECKING:fromairflow.utils.contextimportContext
[docs]classKinesisAnalyticsV2CreateApplicationOperator(AwsBaseOperator[KinesisAnalyticsV2Hook]):""" Creates an AWS Managed Service for Apache Flink application. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:KinesisAnalyticsV2CreateApplicationOperator` :param application_name: The name of application. (templated) :param runtime_environment: The runtime environment for the application. (templated) :param service_execution_role: The IAM role used by the application to access services. (templated) :param create_application_kwargs: Create application extra properties. (templated) :param application_description: A summary description of the application. (templated) :param aws_conn_id: The Airflow connection used for AWS credentials. If this is ``None`` or empty then the default boto3 behaviour is used. If running Airflow in a distributed manner and aws_conn_id is None or empty, then default boto3 configuration would be used (and must be maintained on each worker node). :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used. :param verify: Whether to verify SSL certificates. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html :param botocore_config: Configuration dictionary (key-values) for botocore client. See: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html """
def__init__(self,application_name:str,runtime_environment:str,service_execution_role:str,create_application_kwargs:dict[str,Any]|None=None,application_description:str="Managed Service for Apache Flink application created from Airflow",**kwargs,):super().__init__(**kwargs)self.application_name=application_nameself.runtime_environment=runtime_environmentself.service_execution_role=service_execution_roleself.create_application_kwargs=create_application_kwargsor{}self.application_description=application_description
[docs]defexecute(self,context:Context)->dict[str,str]:self.log.info("Creating AWS Managed Service for Apache Flink application %s.",self.application_name)try:response=self.hook.conn.create_application(ApplicationName=self.application_name,ApplicationDescription=self.application_description,RuntimeEnvironment=self.runtime_environment,ServiceExecutionRole=self.service_execution_role,**self.create_application_kwargs,)exceptClientErroraserror:raiseAirflowException(f"AWS Managed Service for Apache Flink application creation failed: {error.response['Error']['Message']}")self.log.info("AWS Managed Service for Apache Flink application created successfully %s.",self.application_name,)return{"ApplicationARN":response["ApplicationDetail"]["ApplicationARN"]}
[docs]classKinesisAnalyticsV2StartApplicationOperator(AwsBaseOperator[KinesisAnalyticsV2Hook]):""" Starts an AWS Managed Service for Apache Flink application. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:KinesisAnalyticsV2StartApplicationOperator` :param application_name: The name of application. (templated) :param run_configuration: Application properties to start Apache Flink Job. (templated) :param wait_for_completion: Whether to wait for job to stop. (default: True) :param waiter_delay: Time in seconds to wait between status checks. (default: 60) :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 20) :param deferrable: If True, the operator will wait asynchronously for the job to stop. This implies waiting for completion. This mode requires aiobotocore module to be installed. (default: False) :param aws_conn_id: The Airflow connection used for AWS credentials. If this is ``None`` or empty then the default boto3 behaviour is used. If running Airflow in a distributed manner and aws_conn_id is None or empty, then default boto3 configuration would be used (and must be maintained on each worker node). :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used. :param verify: Whether to verify SSL certificates. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html :param botocore_config: Configuration dictionary (key-values) for botocore client. See: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html """
[docs]defexecute(self,context:Context)->dict[str,Any]:msg="AWS Managed Service for Apache Flink application"try:self.log.info("Starting %s%s.",msg,self.application_name)self.hook.conn.start_application(ApplicationName=self.application_name,RunConfiguration=self.run_configuration)exceptClientErroraserror:raiseAirflowException(f"Failed to start {msg}{self.application_name}: {error.response['Error']['Message']}")describe_response=self.hook.conn.describe_application(ApplicationName=self.application_name)ifself.deferrable:self.log.info("Deferring for %s to start: %s.",msg,self.application_name)self.defer(trigger=KinesisAnalyticsV2ApplicationOperationCompleteTrigger(application_name=self.application_name,waiter_name="application_start_complete",aws_conn_id=self.aws_conn_id,waiter_delay=self.waiter_delay,waiter_max_attempts=self.waiter_max_attempts,region_name=self.region_name,verify=self.verify,botocore_config=self.botocore_config,),method_name="execute_complete",)ifself.wait_for_completion:self.log.info("Waiting for %s to start: %s.",msg,self.application_name)self.hook.get_waiter("application_start_complete").wait(ApplicationName=self.application_name,WaiterConfig={"Delay":self.waiter_delay,"MaxAttempts":self.waiter_max_attempts},)self.log.info("%s started successfully %s.",msg,self.application_name)return{"ApplicationARN":describe_response["ApplicationDetail"]["ApplicationARN"]}
[docs]defexecute_complete(self,context:Context,event:dict[str,Any]|None=None)->dict[str,Any]:event=validate_execute_complete_event(event)ifevent["status"]!="success":raiseAirflowException("Error while starting AWS Managed Service for Apache Flink application: %s",event)response=self.hook.conn.describe_application(ApplicationName=event["application_name"],)self.log.info("AWS Managed Service for Apache Flink application %s started successfully.",event["application_name"],)return{"ApplicationARN":response["ApplicationDetail"]["ApplicationARN"]}
[docs]classKinesisAnalyticsV2StopApplicationOperator(AwsBaseOperator[KinesisAnalyticsV2Hook]):""" Stop an AWS Managed Service for Apache Flink application. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:KinesisAnalyticsV2StopApplicationOperator` :param application_name: The name of your application. (templated) :param force: Set to true to force the application to stop. If you set Force to true, Managed Service for Apache Flink stops the application without taking a snapshot. (templated) :param wait_for_completion: Whether to wait for job to stop. (default: True) :param waiter_delay: Time in seconds to wait between status checks. (default: 60) :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 20) :param deferrable: If True, the operator will wait asynchronously for the job to stop. This implies waiting for completion. This mode requires aiobotocore module to be installed. (default: False) :param aws_conn_id: The Airflow connection used for AWS credentials. If this is ``None`` or empty then the default boto3 behaviour is used. If running Airflow in a distributed manner and aws_conn_id is None or empty, then default boto3 configuration would be used (and must be maintained on each worker node). :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used. :param verify: Whether to verify SSL certificates. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html :param botocore_config: Configuration dictionary (key-values) for botocore client. See: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html """
[docs]defexecute(self,context:Context)->dict[str,Any]:msg="AWS Managed Service for Apache Flink application"try:self.log.info("Stopping %s%s.",msg,self.application_name)self.hook.conn.stop_application(ApplicationName=self.application_name,Force=self.force)exceptClientErroraserror:raiseAirflowException(f"Failed to stop {msg}{self.application_name}: {error.response['Error']['Message']}")describe_response=self.hook.conn.describe_application(ApplicationName=self.application_name)ifself.deferrable:self.log.info("Deferring for %s to stop: %s.",msg,self.application_name)self.defer(trigger=KinesisAnalyticsV2ApplicationOperationCompleteTrigger(application_name=self.application_name,waiter_name="application_stop_complete",aws_conn_id=self.aws_conn_id,waiter_delay=self.waiter_delay,waiter_max_attempts=self.waiter_max_attempts,region_name=self.region_name,verify=self.verify,botocore_config=self.botocore_config,),method_name="execute_complete",)ifself.wait_for_completion:self.log.info("Waiting for %s to stop: %s.",msg,self.application_name)self.hook.get_waiter("application_stop_complete").wait(ApplicationName=self.application_name,WaiterConfig={"Delay":self.waiter_delay,"MaxAttempts":self.waiter_max_attempts},)self.log.info("%s stopped successfully %s.",msg,self.application_name)return{"ApplicationARN":describe_response["ApplicationDetail"]["ApplicationARN"]}
[docs]defexecute_complete(self,context:Context,event:dict[str,Any]|None=None)->dict[str,Any]:event=validate_execute_complete_event(event)ifevent["status"]!="success":raiseAirflowException("Error while stopping AWS Managed Service for Apache Flink application")response=self.hook.conn.describe_application(ApplicationName=event["application_name"],)self.log.info("AWS Managed Service for Apache Flink application %s stopped successfully.",event["application_name"],)return{"ApplicationARN":response["ApplicationDetail"]["ApplicationARN"]}