You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by GitBox <gi...@apache.org> on 2019/01/13 02:28:53 UTC

[GitHub] kaxil closed pull request #4496: [AIRFLOW-722] Add celery queue sensor

kaxil closed pull request #4496: [AIRFLOW-722] Add celery queue sensor
URL: https://github.com/apache/airflow/pull/4496
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/airflow/contrib/sensors/celery_queue_sensor.py b/airflow/contrib/sensors/celery_queue_sensor.py
new file mode 100644
index 0000000000..52258a9404
--- /dev/null
+++ b/airflow/contrib/sensors/celery_queue_sensor.py
@@ -0,0 +1,90 @@
+# -*- 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 __future__ import absolute_import
+
+from airflow.sensors.base_sensor_operator import BaseSensorOperator
+from airflow.utils.decorators import apply_defaults
+
+from celery.app import control
+
+
+class CeleryQueueSensor(BaseSensorOperator):
+    """
+    Waits for a Celery queue to be empty. By default, in order to be considered
+    empty, the queue must not have any tasks in the ``reserved``, ``scheduled``
+    or ``active`` states.
+
+    :param celery_queue: The name of the Celery queue to wait for.
+    :type celery_queue: str
+    :param target_task_id: Task id for checking
+    :type target_task_id: str
+    """
+    @apply_defaults
+    def __init__(
+            self,
+            celery_queue,
+            target_task_id=None,
+            *args,
+            **kwargs):
+
+        super(CeleryQueueSensor, self).__init__(*args, **kwargs)
+        self.celery_queue = celery_queue
+        self.target_task_id = target_task_id
+
+    def _check_task_id(self, context):
+        """
+        Gets the returned Celery result from the Airflow task
+        ID provided to the sensor, and returns True if the
+        celery result has been finished execution.
+
+        :param context: Airflow's execution context
+        :type context: dict
+        :return: True if task has been executed, otherwise False
+        :rtype: bool
+        """
+        ti = context['ti']
+        celery_result = ti.xcom_pull(task_ids=self.target_task_id)
+        return celery_result.ready()
+
+    def poke(self, context):
+
+        if self.target_task_id:
+            return self._check_task_id(context)
+
+        inspect_result = control.Inspect()
+        reserved = inspect_result.reserved()
+        scheduled = inspect_result.scheduled()
+        active = inspect_result.active()
+
+        try:
+            reserved = len(reserved[self.celery_queue])
+            scheduled = len(scheduled[self.celery_queue])
+            active = len(active[self.celery_queue])
+
+            self.log.info(
+                'Checking if celery queue %s is empty.', self.celery_queue
+            )
+
+            return reserved == 0 and scheduled == 0 and active == 0
+        except KeyError:
+            raise KeyError(
+                'Could not locate Celery queue {0}'.format(
+                    self.celery_queue
+                )
+            )
diff --git a/docs/code.rst b/docs/code.rst
index c5a7bb4fcc..7f5ae0efd4 100644
--- a/docs/code.rst
+++ b/docs/code.rst
@@ -242,6 +242,7 @@ Sensors
 .. autoclass:: airflow.contrib.sensors.bigquery_sensor.BigQueryTableSensor
 .. autoclass:: airflow.contrib.sensors.cassandra_record_sensor.CassandraRecordSensor
 .. autoclass:: airflow.contrib.sensors.cassandra_table_sensor.CassandraTableSensor
+.. autoclass:: airflow.contrib.sensors.celery_queue_sensor.CeleryQueueSensor
 .. autoclass:: airflow.contrib.sensors.datadog_sensor.DatadogSensor
 .. autoclass:: airflow.contrib.sensors.emr_base_sensor.EmrBaseSensor
 .. autoclass:: airflow.contrib.sensors.emr_job_flow_sensor.EmrJobFlowSensor
diff --git a/tests/contrib/sensors/test_celery_queue_sensor.py b/tests/contrib/sensors/test_celery_queue_sensor.py
new file mode 100644
index 0000000000..abf91317cb
--- /dev/null
+++ b/tests/contrib/sensors/test_celery_queue_sensor.py
@@ -0,0 +1,80 @@
+# -*- 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 __future__ import absolute_import
+
+import unittest
+from mock import patch
+
+from airflow.contrib.sensors.celery_queue_sensor import CeleryQueueSensor
+
+
+class TestCeleryQueueSensor(unittest.TestCase):
+
+    def setUp(self):
+        class TestCeleryqueueSensor(CeleryQueueSensor):
+
+            def _check_task_id(self, context):
+                return True
+
+        self.sensor = TestCeleryqueueSensor
+
+    @patch('celery.app.control.Inspect')
+    def test_poke_success(self, mock_inspect):
+        mock_inspect_result = mock_inspect.return_value
+        # test success
+        mock_inspect_result.reserved.return_value = {
+            'test_queue': []
+        }
+
+        mock_inspect_result.scheduled.return_value = {
+            'test_queue': []
+        }
+
+        mock_inspect_result.active.return_value = {
+            'test_queue': []
+        }
+        test_sensor = self.sensor(celery_queue='test_queue',
+                                  task_id='test-task')
+        self.assertTrue(test_sensor.poke(None))
+
+    @patch('celery.app.control.Inspect')
+    def test_poke_fail(self, mock_inspect):
+        mock_inspect_result = mock_inspect.return_value
+        # test success
+        mock_inspect_result.reserved.return_value = {
+            'test_queue': []
+        }
+
+        mock_inspect_result.scheduled.return_value = {
+            'test_queue': []
+        }
+
+        mock_inspect_result.active.return_value = {
+            'test_queue': ['task']
+        }
+        test_sensor = self.sensor(celery_queue='test_queue',
+                                  task_id='test-task')
+        self.assertFalse(test_sensor.poke(None))
+
+    @patch('celery.app.control.Inspect')
+    def test_poke_success_with_taskid(self, mock_inspect):
+        test_sensor = self.sensor(celery_queue='test_queue',
+                                  task_id='test-task',
+                                  af_task_id='target-task')
+        self.assertTrue(test_sensor.poke(None))


 

----------------------------------------------------------------
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