airflow-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From GitBox <...@apache.org>
Subject [GitHub] [airflow] feluelle commented on a change in pull request #6090: [AIRFLOW-5470] Add Apache Livy REST operator
Date Sat, 21 Sep 2019 19:52:15 GMT
feluelle commented on a change in pull request #6090: [AIRFLOW-5470] Add Apache Livy REST operator
URL: https://github.com/apache/airflow/pull/6090#discussion_r326870689
 
 

 ##########
 File path: airflow/contrib/hooks/livy_hook.py
 ##########
 @@ -0,0 +1,297 @@
+# -*- 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.
+
+"""
+This module contains the Apache Livy hook.
+"""
+
+import re
+from enum import Enum
+import json
+import requests
+
+from airflow.exceptions import AirflowException
+from airflow.hooks.base_hook import BaseHook
+from airflow.utils.log.logging_mixin import LoggingMixin
+
+
+class BatchState(Enum):
+    """
+    Batch session states
+    """
+    NOT_STARTED = 'not_started'
+    STARTING = 'starting'
+    RUNNING = 'running'
+    IDLE = 'idle'
+    BUSY = 'busy'
+    SHUTTING_DOWN = 'shutting_down'
+    ERROR = 'error'
+    DEAD = 'dead'
+    KILLED = 'killed'
+    SUCCESS = 'success'
+
+
+TERMINAL_STATES = {
+    BatchState.SUCCESS,
+    BatchState.DEAD,
+    BatchState.KILLED,
+    BatchState.ERROR,
+}
+
+
+class LivyHook(BaseHook, LoggingMixin):
+    """
+    Hook for Apache Livy through the REST API.
+
+    For more information about the API refer to
+    https://livy.apache.org/docs/latest/rest-api.html
+
+    :param livy_conn_id: reference to a pre-defined Livy Connection.
+    :type livy_conn_id: str
+    """
+    def __init__(self, livy_conn_id='livy_default'):
+        super(LivyHook, self).__init__(livy_conn_id)
+        self._livy_conn_id = livy_conn_id
+        self._build_base_url()
+
+    def _build_base_url(self):
+        """
+        Build connection URL
+        """
+        params = self.get_connection(self._livy_conn_id)
+
+        base_url = params.host
+
+        if not base_url:
+            raise AirflowException("Missing Livy endpoint hostname")
+
+        if '://' not in base_url:
+            base_url = '{}://{}'.format('http', base_url)
+        if not re.search(r':\d+$', base_url):
+            base_url = '{}:{}'.format(base_url, str(params.port or 8998))
+
+        self._base_url = base_url
+
+    def get_conn(self):
+        pass
+
+    def post_batch(self, *args, **kwargs):
+        """
+        Perform request to submit batch
+        """
+
+        batch_submit_body = json.dumps(LivyHook.build_post_batch_body(*args, **kwargs))
+        headers = {'Content-Type': 'application/json'}
+
+        self.log.info("Submitting job {} to {}".format(batch_submit_body, self._base_url))
+        response = requests.post(self._base_url + '/batches', data=batch_submit_body, headers=headers)
+        self.log.debug("Got response: {}".format(response.text))
+
+        if response.status_code != 201:
+            raise AirflowException("Could not submit batch. Status code: {}".format(response.status_code))
+
+        batch_id = LivyHook._parse_post_response(response.json())
+        if batch_id is None:
+            raise AirflowException("Unable to parse a batch session id")
+        self.log.info("Batch submitted with session id: {}".format(batch_id))
+
+        return batch_id
+
+    def get_batch(self, session_id):
+        """
+        Fetch info about the specified batch
+        :param session_id: identifier of the batch sessions
+        :type session_id: int
+        """
+        LivyHook._validate_session_id(session_id)
+
+        self.log.debug("Fetching info for batch session {}".format(session_id))
+        response = requests.get('{}/batches/{}'.format(self._base_url, session_id))
+
+        if response.status_code != 200:
+            self.log.warning("Got status code {} for session {}".format(response.status_code,
session_id))
+            raise AirflowException("Unable to fetch batch with id: {}".format(session_id))
+
+        return response.json()
+
+    def get_batch_state(self, session_id):
+        """
+        Fetch the state of the specified batch
+        :param session_id: identifier of the batch sessions
+        :type session_id: int
+        """
+        LivyHook._validate_session_id(session_id)
+
+        self.log.debug("Fetching info for batch session {}".format(session_id))
+        response = requests.get('{}/batches/{}/state'.format(self._base_url, session_id))
+
+        if response.status_code != 200:
+            self.log.warning("Got status code {} for session {}".format(response.status_code,
session_id))
+            raise AirflowException("Unable to fetch state for batch id: {}".format(session_id))
+
+        jresp = response.json()
+        if 'state' not in jresp:
+            raise AirflowException("Unable to get state for batch with id: {}".format(session_id))
+        return BatchState(jresp['state'])
+
+    def delete_batch(self, session_id):
+        """
+        Delete the specified batch
+        :param session_id: identifier of the batch sessions
+        :type session_id: int
+        """
+        LivyHook._validate_session_id(session_id)
+
+        self.log.info("Deleting batch session {}".format(session_id))
+        response = requests.delete('{}/batches/{}'.format(self._base_url, session_id))
+
+        if response.status_code != 200:
+            self.log.warning("Got status code {} for session {}".format(response.status_code,
session_id))
+            raise AirflowException("Could not kill the batch with session id: {}".format(session_id))
+
+        return response.json()
+
+    @staticmethod
+    def _validate_session_id(session_id):
+        try:
+            int(session_id)
+        except (TypeError, ValueError):
+            raise AirflowException("'session_id' must represent an integer")
+
+    @staticmethod
+    def _parse_post_response(response):
+        """Parse batch response for batch id"""
+        return response['id'] if 'id' in response else None
+
+    @staticmethod
+    def build_post_batch_body(
+        file,
+        args=None,
+        conf=None,
+        **kwargs
+    ):
+        """
+        Build the post batch request body.
+        For more information about the format refer to
+        See https://livy.apache.org/docs/latest/rest-api.html
 
 Review comment:
   ```suggestion
           
           .. seealso:: https://livy.apache.org/docs/latest/rest-api.html
   ```

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to 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