airflow-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From GitBox <...@apache.org>
Subject [GitHub] ashb commented on a change in pull request #4111: [AIRFLOW-3266] Add AWS Athena Operator and hook
Date Mon, 29 Oct 2018 13:52:45 GMT
ashb commented on a change in pull request #4111: [AIRFLOW-3266] Add AWS Athena Operator and
hook
URL: https://github.com/apache/incubator-airflow/pull/4111#discussion_r228930497
 
 

 ##########
 File path: airflow/contrib/hooks/aws_athena_hook.py
 ##########
 @@ -0,0 +1,147 @@
+# -*- coding: utf-8 -*-
+#
+# 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 time import sleep
+from airflow.contrib.hooks.aws_hook import AwsHook
+from uuid import uuid4
+
+INTERMEDIATE_STATES = ('QUEUED', 'RUNNING',)
+FINAL_STATES = ('SUCCEEDED', 'FAILED', 'CANCELLED',)
+
+
+class AWSAthenaHook(AwsHook):
+
+    def __init__(self, query, database, region_name, output_location, aws_conn_id=None, *args,
**kwargs):
+        self.query = query
+        self.database = database
+        self.region_name = region_name
+        self.outputLocation = output_location
+        self.aws_conn_id = aws_conn_id
+        if 'client_request_token' in kwargs:  # This ensures idempotency of query execution
+            self.client_request_token = kwargs['client_request_token']
+        else:
+            self.client_request_token = str(uuid4())
+        if 'query_execution_context' in kwargs:
+            self.query_execution_context = kwargs['query_execution_context']
+        else:
+            self.query_execution_context = {}
+        if 'result_configuration' in kwargs:
+            self.result_configuration = kwargs['result_configuration']
+        else:
+            self.result_configuration = {}
+        if 'sleep_time' in kwargs:
+            self.sleep_time = kwargs['sleep_time']
+        else:
+            self.sleep_time = 5  # Use this to poll query status in athena
+        self.query_execution_context['Database'] = self.database
+        self.result_configuration['OutputLocation'] = self.outputLocation
+        super(AWSAthenaHook, self).__init__(self.aws_conn_id, verify=None)
+        self.conn = self.get_conn()
+
+    def _check_query_status(self):
+        if self._queryExecutionId is None:
+            return None
+        return self.conn.get_query_execution(QueryExecutionId=self._queryExecutionId)
+
+    def _get_query_results(self):
+        if self._queryExecutionId is None:
+            return None
+        state = self.check_query_status()
+        if state is None or state in INTERMEDIATE_STATES:
+            self.log.error("Invalid Query state")
+            return None
+        elif state in INTERMEDIATE_STATES or state == 'CANCELLED':
+            self.log.info("Query is in {state} state. Cannot fetch results".format(state=state))
+            return None
+        return self.conn.get_query_results(QueryExecutionId=self._queryExecutionId)
+
+    def _stop_query(self):
+        if self._queryExecutionId is None:
+            return None
+        return self.conn.stop_query_execution(QueryExecutionId=self._queryExecutionId)
+
+    def _poll_query_status(self, sleep_time=None, max_tries=None):
+        try_number = 1
+        if sleep_time is None:
+            sleep_time = self.sleep_time
+        if max_tries is None:  # Retries forever until query reaches final state
+            retry_condition = True
+        else:
+            retry_condition = try_number <= max_tries
+        while retry_condition:
+            response = self._check_query_status()
+            state = None
+            try:
+                state = response['QueryExecution']['Status']['State']
+            except Exception as ex:
+                self.log.error("{try_number}. Error occurred while fetching query state".format(
+                    try_number=try_number), ex)
+            finally:
+                if state is None:
+                    self.log.error("Trial {try_number}: Invalid query state. Retrying again".format(
+                        try_number=try_number))
+                elif state in INTERMEDIATE_STATES:
+                    self.log.info("Trial {try_number}: Query is still in an intermediate
state - {state}"
+                                  .format(try_number=try_number, state=state))
+                else:
+                    self.log.info("Trial {try_number}: Query execution completed. Final state
is {state}"
+                                  .format(try_number=try_number, state=state))
+                    break
+                try_number += 1
+                if max_tries:
+                    retry_condition = try_number <= max_tries
+                sleep(sleep_time)
+
+    def get_conn(self):
+        self.conn = self.get_client_type('athena', self.region_name)
+        return self.conn
+
+    def run_query(self):
+        response = self.conn.start_query_execution(QueryString=self.query,
+                                                   ClientRequestToken=self.client_request_token,
+                                                   QueryExecutionContext=self.query_execution_context,
+                                                   ResultConfiguration=self.result_configuration)
+        self._queryExecutionId = response['QueryExecutionId']
+        return response
+
+    def check_query_status(self):
+        response = self._check_query_status()
+        state = None
+        try:
+            state = response['QueryExecution']['Status']['State']
+        finally:
+            return state
+
+    def poll_query_status(self, sleep_time=None, max_tries=None):
+        self._poll_query_status(sleep_time=None, max_tries=max_tries)
+
+    def on_kill(self):
+        self.log.info("Received a kill Signal.")
+        self.log.info("Stopping Query with executionId - {queryId}".format(queryId=self._queryExecutionId))
+        response = self._stop_query()
+        HTTPStatusCode = None
 
 Review comment:
   Python style point:  call this`http_status_code`

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

Mime
View raw message