def run_next(self, next_job: KubernetesJobType) -> None:
        """
        The run_next command will check the task_queue for any un-run jobs.
        It will then create a unique job-id, launch that job in the cluster,
        and store relevant info in the current_jobs map so we can track the job's
        status
        """
        self.log.info('Kubernetes job is %s', str(next_job))
        key, command, kube_executor_config = next_job
        dag_id, task_id, execution_date, try_number = key

        if isinstance(command, str):
            command = [command]

        pod = PodGenerator.construct_pod(
            namespace=self.namespace,
            worker_uuid=self.worker_uuid,
            pod_id=self._create_pod_id(dag_id, task_id),
            dag_id=pod_generator.make_safe_label_value(dag_id),
            task_id=pod_generator.make_safe_label_value(task_id),
            try_number=try_number,
            date=self._datetime_to_label_safe_datestring(execution_date),
            command=command,
            kube_executor_config=kube_executor_config,
            worker_config=self.worker_configuration_pod)
        # Reconcile the pod generated by the Operator and the Pod
        # generated by the .cfg file
        self.log.debug("Kubernetes running for command %s", command)
        self.log.debug("Kubernetes launching image %s",
                       pod.spec.containers[0].image)

        # the watcher will monitor pods, so we do not block.
        self.launcher.run_pod_async(
            pod, **self.kube_config.kube_client_request_args)
        self.log.debug("Kubernetes Job created!")
    def clear_not_launched_queued_tasks(self, session=None) -> None:
        """
        Tasks can end up in a "Queued" state through either the executor being
        abruptly shut down (leaving a non-empty task_queue on this executor)
        or when a rescheduled/deferred operator comes back up for execution
        (with the same try_number) before the pod of its previous incarnation
        has been fully removed (we think).

        This method checks each of those tasks to see if the corresponding pod
        is around, and if not, and there's no matching entry in our own
        task_queue, marks it for re-execution.
        """
        self.log.debug("Clearing tasks that have not been launched")
        if not self.kube_client:
            raise AirflowException(NOT_STARTED_MESSAGE)
        queued_tasks = session.query(TaskInstance).filter(TaskInstance.state == State.QUEUED).all()
        self.log.info('Found %s queued task instances', len(queued_tasks))

        # Go through the "last seen" dictionary and clean out old entries
        allowed_age = self.kube_config.worker_pods_queued_check_interval * 3
        for key, timestamp in list(self.last_handled.items()):
            if time.time() - timestamp > allowed_age:
                del self.last_handled[key]

        for task in queued_tasks:

            self.log.debug("Checking task %s", task)

            # Check to see if we've handled it ourselves recently
            if task.key in self.last_handled:
                continue

            # Build the pod selector
            dict_string = "dag_id={},task_id={},airflow-worker={}".format(
                pod_generator.make_safe_label_value(task.dag_id),
                pod_generator.make_safe_label_value(task.task_id),
                pod_generator.make_safe_label_value(str(self.scheduler_job_id)),
            )
            kwargs = dict(label_selector=dict_string)
            if self.kube_config.kube_client_request_args:
                kwargs.update(**self.kube_config.kube_client_request_args)

            # Try run_id first
            kwargs['label_selector'] += ',run_id=' + pod_generator.make_safe_label_value(task.run_id)
            pod_list = self.kube_client.list_namespaced_pod(self.kube_config.kube_namespace, **kwargs)
            if pod_list.items:
                continue
            # Fallback to old style of using execution_date
            kwargs['label_selector'] = dict_string + ',exectuion_date={}'.format(
                pod_generator.datetime_to_label_safe_datestring(task.execution_date)
            )
            pod_list = self.kube_client.list_namespaced_pod(self.kube_config.kube_namespace, **kwargs)
            if pod_list.items:
                continue
            self.log.info('TaskInstance: %s found in queued state but was not launched, rescheduling', task)
            session.query(TaskInstance).filter(
                TaskInstance.dag_id == task.dag_id,
                TaskInstance.task_id == task.task_id,
                TaskInstance.run_id == task.run_id,
            ).update({TaskInstance.state: State.SCHEDULED})
Beispiel #3
0
    def clear_not_launched_queued_tasks(self, session=None) -> None:
        """
        If the airflow scheduler restarts with pending "Queued" tasks, the tasks may or
        may not
        have been launched. Thus on starting up the scheduler let's check every
        "Queued" task to
        see if it has been launched (ie: if there is a corresponding pod on kubernetes)

        If it has been launched then do nothing, otherwise reset the state to "None" so
        the task
        will be rescheduled

        This will not be necessary in a future version of airflow in which there is
        proper support
        for State.LAUNCHED
        """
        self.log.debug("Clearing tasks that have not been launched")
        if not self.kube_client:
            raise AirflowException(NOT_STARTED_MESSAGE)
        queued_tasks = session \
            .query(TaskInstance) \
            .filter(TaskInstance.state == State.QUEUED).all()
        self.log.info(
            'When executor started up, found %s queued task instances',
            len(queued_tasks)
        )

        for task in queued_tasks:
            # pylint: disable=protected-access
            self.log.debug("Checking task %s", task)
            dict_string = (
                "dag_id={},task_id={},execution_date={},airflow-worker={}".format(
                    pod_generator.make_safe_label_value(task.dag_id),
                    pod_generator.make_safe_label_value(task.task_id),
                    pod_generator.datetime_to_label_safe_datestring(
                        task.execution_date
                    ),
                    self.scheduler_job_id
                )
            )
            # pylint: enable=protected-access
            kwargs = dict(label_selector=dict_string)
            if self.kube_config.kube_client_request_args:
                for key, value in self.kube_config.kube_client_request_args.items():
                    kwargs[key] = value
            pod_list = self.kube_client.list_namespaced_pod(
                self.kube_config.kube_namespace, **kwargs)
            if not pod_list.items:
                self.log.info(
                    'TaskInstance: %s found in queued state but was not launched, '
                    'rescheduling', task
                )
                session.query(TaskInstance).filter(
                    TaskInstance.dag_id == task.dag_id,
                    TaskInstance.task_id == task.task_id,
                    TaskInstance.execution_date == task.execution_date
                ).update({TaskInstance.state: State.NONE})
Beispiel #4
0
 def test_make_safe_label_value(self):
     for dag_id, task_id in self._cases():
         safe_dag_id = pod_generator.make_safe_label_value(dag_id)
         assert self._is_safe_label_value(safe_dag_id)
         safe_task_id = pod_generator.make_safe_label_value(task_id)
         assert self._is_safe_label_value(safe_task_id)
         dag_id = "my_dag_id"
         assert dag_id == pod_generator.make_safe_label_value(dag_id)
         dag_id = "my_dag_id_" + "a" * 64
         assert "my_dag_id_" + "a" * 43 + "-0ce114c45" == pod_generator.make_safe_label_value(dag_id)
    def _labels_to_key(
            self, labels: Dict[str, str]) -> Optional[TaskInstanceKeyType]:
        try_num = 1
        try:
            try_num = int(labels.get('try_number', '1'))
        except ValueError:
            self.log.warning("could not get try_number as an int: %s",
                             labels.get('try_number', '1'))

        try:
            dag_id = labels['dag_id']
            task_id = labels['task_id']
            ex_time = self._label_safe_datestring_to_datetime(
                labels['execution_date'])
        except Exception as e:  # pylint: disable=broad-except
            self.log.warning(
                'Error while retrieving labels; labels: %s; exception: %s',
                labels, e)
            return None

        with create_session() as session:
            task = (session.query(TaskInstance).filter_by(
                task_id=task_id, dag_id=dag_id,
                execution_date=ex_time).one_or_none())
            if task:
                self.log.info(
                    'Found matching task %s-%s (%s) with current state of %s',
                    task.dag_id, task.task_id, task.execution_date, task.state)
                return (dag_id, task_id, ex_time, try_num)
            else:
                self.log.warning(
                    'task_id/dag_id are not safe to use as Kubernetes labels. This can cause '
                    'severe performance regressions. Please see '
                    '<https://kubernetes.io/docs/concepts/overview/working-with-objects'
                    '/labels/#syntax-and-character-set>. '
                    'Given dag_id: %s, task_id: %s', task_id, dag_id)

            tasks = (session.query(TaskInstance).filter_by(
                execution_date=ex_time).all())
            self.log.info('Checking %s task instances.', len(tasks))
            for task in tasks:
                if (pod_generator.make_safe_label_value(task.dag_id) == dag_id
                        and pod_generator.make_safe_label_value(task.task_id)
                        == task_id and task.execution_date == ex_time):
                    self.log.info(
                        'Found matching task %s-%s (%s) with current state of %s',
                        task.dag_id, task.task_id, task.execution_date,
                        task.state)
                    dag_id = task.dag_id
                    task_id = task.task_id
                    return dag_id, task_id, ex_time, try_num
        self.log.warning(
            'Failed to find and match task details to a pod; labels: %s',
            labels)
        return None
 def test_make_safe_label_value(self):
     for dag_id, task_id in self._cases():
         safe_dag_id = pod_generator.make_safe_label_value(dag_id)
         self.assertTrue(self._is_safe_label_value(safe_dag_id))
         safe_task_id = pod_generator.make_safe_label_value(task_id)
         self.assertTrue(self._is_safe_label_value(safe_task_id))
         dag_id = "my_dag_id"
         self.assertEqual(dag_id,
                          pod_generator.make_safe_label_value(dag_id))
         dag_id = "my_dag_id_" + "a" * 64
         self.assertEqual("my_dag_id_" + "a" * 43 + "-0ce114c45",
                          pod_generator.make_safe_label_value(dag_id))
Beispiel #7
0
    def _adopt_completed_pods(self, kube_client: client.CoreV1Api) -> None:
        """

        Patch completed pod so that the KubernetesJobWatcher can delete it.

        :param kube_client: kubernetes client for speaking to kube API
        """
        kwargs = {
            'field_selector': "status.phase=Succeeded",
            'label_selector': 'kubernetes_executor=True',
        }
        pod_list = kube_client.list_namespaced_pod(
            namespace=self.kube_config.kube_namespace, **kwargs)
        for pod in pod_list.items:
            self.log.info("Attempting to adopt pod %s", pod.metadata.name)
            pod.metadata.labels[
                'airflow-worker'] = pod_generator.make_safe_label_value(
                    str(self.scheduler_job_id))
            try:
                kube_client.patch_namespaced_pod(
                    name=pod.metadata.name,
                    namespace=pod.metadata.namespace,
                    body=PodGenerator.serialize_pod(pod),
                )
            except ApiException as e:
                self.log.info("Failed to adopt pod %s. Reason: %s",
                              pod.metadata.name, e)
Beispiel #8
0
    def adopt_launched_task(self, kube_client: client.CoreV1Api,
                            pod: k8s.V1Pod, pod_ids: Dict[TaskInstanceKey,
                                                          k8s.V1Pod]) -> None:
        """
        Patch existing pod so that the current KubernetesJobWatcher can monitor it via label selectors

        :param kube_client: kubernetes client for speaking to kube API
        :param pod: V1Pod spec that we will patch with new label
        :param pod_ids: pod_ids we expect to patch.
        """
        self.log.info("attempting to adopt pod %s", pod.metadata.name)
        pod.metadata.labels[
            'airflow-worker'] = pod_generator.make_safe_label_value(
                str(self.scheduler_job_id))
        pod_id = annotations_to_key(pod.metadata.annotations)
        if pod_id not in pod_ids:
            self.log.error(
                "attempting to adopt taskinstance which was not specified by database: %s",
                pod_id)
            return

        try:
            kube_client.patch_namespaced_pod(
                name=pod.metadata.name,
                namespace=pod.metadata.namespace,
                body=PodGenerator.serialize_pod(pod),
            )
            pod_ids.pop(pod_id)
            self.running.add(pod_id)
        except ApiException as e:
            self.log.info("Failed to adopt pod %s. Reason: %s",
                          pod.metadata.name, e)
Beispiel #9
0
    def _get_ti_pod_labels(context: Optional[dict] = None,
                           include_try_number: bool = True) -> dict:
        """
        Generate labels for the pod to track the pod in case of Operator crash

        :param context: task context provided by airflow DAG
        :return: dict
        """
        if not context:
            return {}

        labels = {
            'dag_id': context['dag'].dag_id,
            'task_id': context['task'].task_id,
            'execution_date': context['ts'],
        }
        if include_try_number:
            labels.update(try_number=context['ti'].try_number)
        # In the case of sub dags this is just useful
        if context['dag'].is_subdag:
            labels['parent_dag_id'] = context['dag'].parent_dag.dag_id
        # Ensure that label is valid for Kube,
        # and if not truncate/remove invalid chars and replace with short hash.
        for label_id, label in labels.items():
            safe_label = pod_generator.make_safe_label_value(str(label))
            labels[label_id] = safe_label
        return labels
Beispiel #10
0
    def adopt_launched_task(self, kube_client, pod, pod_ids: dict):
        """
        Patch existing pod so that the current KubernetesJobWatcher can monitor it via label selectors

        :param kube_client: kubernetes client for speaking to kube API
        :param pod: V1Pod spec that we will patch with new label
        :param pod_ids: pod_ids we expect to patch.
        """
        self.log.info("attempting to adopt pod %s", pod.metadata.name)
        pod.metadata.labels[
            'airflow-worker'] = pod_generator.make_safe_label_value(
                str(self.scheduler_job_id))
        dag_id = pod.metadata.labels['dag_id']
        task_id = pod.metadata.labels['task_id']
        pod_id = create_pod_id(dag_id=dag_id, task_id=task_id)
        if pod_id not in pod_ids:
            self.log.error(
                "attempting to adopt task %s in dag %s which was not specified by database",
                task_id,
                dag_id,
            )
        else:
            try:
                kube_client.patch_namespaced_pod(
                    name=pod.metadata.name,
                    namespace=pod.metadata.namespace,
                    body=PodGenerator.serialize_pod(pod),
                )
                pod_ids.pop(pod_id)
            except ApiException as e:
                self.log.info("Failed to adopt pod %s. Reason: %s",
                              pod.metadata.name, e)
Beispiel #11
0
    def _get_ti_pod_labels(context: Optional[dict] = None,
                           include_try_number: bool = True) -> dict:
        """
        Generate labels for the pod to track the pod in case of Operator crash

        :param context: task context provided by airflow DAG
        :return: dict
        """
        if not context:
            return {}

        ti = context['ti']
        run_id = context['run_id']

        labels = {'dag_id': ti.dag_id, 'task_id': ti.task_id, 'run_id': run_id}

        # If running on Airflow 2.3+:
        map_index = getattr(ti, 'map_index', -1)
        if map_index >= 0:
            labels['map_index'] = map_index

        if include_try_number:
            labels.update(try_number=ti.try_number)
        # In the case of sub dags this is just useful
        if context['dag'].is_subdag:
            labels['parent_dag_id'] = context['dag'].parent_dag.dag_id
        # Ensure that label is valid for Kube,
        # and if not truncate/remove invalid chars and replace with short hash.
        for label_id, label in labels.items():
            safe_label = pod_generator.make_safe_label_value(str(label))
            labels[label_id] = safe_label
        return labels
Beispiel #12
0
    def run_next(self, next_job):
        """
        The run_next command will check the task_queue for any un-run jobs.
        It will then create a unique job-id, launch that job in the cluster,
        and store relevant info in the current_jobs map so we can track the job's
        status
        """
        self.log.info('Kubernetes job is %s', str(next_job))
        key, command, kube_executor_config = next_job
        dag_id, task_id, execution_date, try_number = key

        if command[0:2] != ["airflow", "run"]:
            raise ValueError('The command must start with ["airflow", "run"].')

        pod = PodGenerator.construct_pod(
            namespace=self.namespace,
            worker_uuid=self.worker_uuid,
            pod_id=self._create_pod_id(dag_id, task_id),
            dag_id=pod_generator.make_safe_label_value(dag_id),
            task_id=pod_generator.make_safe_label_value(task_id),
            try_number=try_number,
            kube_image=self.kube_config.kube_image,
            date=execution_date,
            command=command,
            pod_override_object=kube_executor_config,
            base_worker_pod=self.worker_configuration_pod)

        sanitized_pod = self.launcher._client.api_client.sanitize_for_serialization(
            pod)
        json_pod = json.dumps(sanitized_pod, indent=2)

        self.log.debug('Pod Creation Request before mutation: \n%s', json_pod)

        # Reconcile the pod generated by the Operator and the Pod
        # generated by the .cfg file
        self.log.debug("Kubernetes running for command %s", command)
        self.log.debug("Kubernetes launching image %s",
                       pod.spec.containers[0].image)

        # the watcher will monitor pods, so we do not block.
        self.launcher.run_pod_async(
            pod, **self.kube_config.kube_client_request_args)
        self.log.debug("Kubernetes Job created!")
Beispiel #13
0
 def try_adopt_task_instances(self, tis: List[TaskInstance]) -> List[TaskInstance]:
     tis_to_flush = [ti for ti in tis if not ti.external_executor_id]
     scheduler_job_ids = [ti.external_executor_id for ti in tis]
     pod_ids = {
         create_pod_id(
             dag_id=pod_generator.make_safe_label_value(ti.dag_id),
             task_id=pod_generator.make_safe_label_value(ti.task_id),
         ): ti
         for ti in tis
         if ti.external_executor_id
     }
     kube_client: client.CoreV1Api = self.kube_client
     for scheduler_job_id in scheduler_job_ids:
         scheduler_job_id = pod_generator.make_safe_label_value(str(scheduler_job_id))
         kwargs = {'label_selector': f'airflow-worker={scheduler_job_id}'}
         pod_list = kube_client.list_namespaced_pod(namespace=self.kube_config.kube_namespace, **kwargs)
         for pod in pod_list.items:
             self.adopt_launched_task(kube_client, pod, pod_ids)
     self._adopt_completed_pods(kube_client)
     tis_to_flush.extend(pod_ids.values())
     return tis_to_flush
Beispiel #14
0
    def create_labels_for_pod(context) -> dict:
        """
        Generate labels for the pod to track the pod in case of Operator crash

        :param context: task context provided by airflow DAG
        :return: dict
        """
        labels = {
            'dag_id': context['dag'].dag_id,
            'task_id': context['task'].task_id,
            'execution_date': context['ts'],
            'try_number': context['ti'].try_number,
        }
        # In the case of sub dags this is just useful
        if context['dag'].is_subdag:
            labels['parent_dag_id'] = context['dag'].parent_dag.dag_id
        # Ensure that label is valid for Kube,
        # and if not truncate/remove invalid chars and replace with short hash.
        for label_id, label in labels.items():
            safe_label = pod_generator.make_safe_label_value(str(label))
            labels[label_id] = safe_label
        return labels