<commit_before>#!/usr/bin/env python3
# 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.

import gc
import os
import statistics
import time

import click

MAX_DAG_RUNS_ALLOWED = 1


class ShortCircutExecutorMixin:
    def __init__(self, stop_when_these_completed):
        super().__init__()
        self.reset(stop_when_these_completed)

    def reset(self, stop_when_these_completed):
        self.stop_when_these_completed = {
            # We want to store the dag run here, but we don't have them until they are created.
            key: None for key in stop_when_these_completed
        }

    def change_state(self, key, state):
        from airflow.utils.state import State
        super().change_state(key, state)

        dag_id, task_id, execution_date, __ = key
        run_key = (dag_id, execution_date.timestamp())
        if run_key in self.stop_when_these_completed:

            if self.stop_when_these_completed[run_key] is None:
                import airflow.models

                # We are interested in this run, but don't yet have the record for it.
                run = airflow.models.DagRun.find(dag_id=dag_id, execution_date=execution_date)[0]
                self.stop_when_these_completed[run_key] = run
            else:
                run = self.stop_when_these_completed[run_key]

            if run and all(t.state == State.SUCCESS for t in run.get_task_instances()):
                self.stop_when_these_completed.pop(run_key)

                if not self.stop_when_these_completed:
                    self.log.warning("STOPPING SCHEDULER -- all runs complete")
                    self.scheduler_job.processor_agent._done = True
                else:
                    self.log.warning("WAITING ON %d RUNS", len(self.stop_when_these_completed))


def get_executor_under_test():
    try:
        # Run against master and 1.10.x releases
        from tests.test_utils.mock_executor import MockExecutor
    except ImportError:
        from tests.executors.test_executor import TestExecutor as MockExecutor

    # from airflow.executors.local_executor import LocalExecutor

    # Change this to try other executors
    Executor = MockExecutor

    class ShortCircutExecutor(ShortCircutExecutorMixin, Executor):
        pass

    return ShortCircutExecutor


def reset_dag(dag, session):
    import airflow.models

    DR = airflow.models.DagRun
    DM = airflow.models.DagModel
    TI = airflow.models.TaskInstance
    TF = airflow.models.TaskFail
    dag_id = dag.dag_id

    session.query(DM).filter(DM.dag_id == dag_id).update({'is_paused': False})
    session.query(DR).filter(DR.dag_id == dag_id).delete()
    session.query(TI).filter(TI.dag_id == dag_id).delete()
    session.query(TF).filter(TF.dag_id == dag_id).delete()


def pause_all_dags(session):
    from airflow.models.dag import DagModel
    session.query(DagModel).update({'is_paused': True})


def create_dag_runs(dag, num_runs, session):
    from airflow.models.dagrun import DagRun
    from airflow.utils import timezone
    from airflow.utils.state import State

    next_run_date = dag.normalize_schedule(dag.start_date or min(t.start_date for t in dag.tasks))

    for _ in range(num_runs):
        dag.create_dagrun(
            run_id=DagRun.ID_PREFIX + next_run_date.isoformat(),
            execution_date=next_run_date,
            start_date=timezone.utcnow(),
            state=State.RUNNING,
            external_trigger=False,
            session=session,
        )
        next_run_date = dag.following_schedule(next_run_date)


@click.command()
@click.option('--num-runs', default=1, help='number of DagRun, to run for each DAG')
@click.option('--repeat', default=3, help='number of times to run test, to reduce variance')
@click.option('--pre-create-dag-runs', is_flag=True, default=False, help='''Pre-create the dag runs and stop the scheduler creating more.

        Warning: this makes the scheduler do (slightly) less work so may skew your numbers. Use sparingly!
        ''')
@click.argument('dag_ids', required=True, nargs=-1)
def main(num_runs, repeat, pre_create_dag_runs, dag_ids):
    """
    This script can be used to measure the total "scheduler overhead" of Airflow.
<commit_msg>[AIRFLOW-XXXX] Wrap line under 90 characters (#7701)<commit_after>#!/usr/bin/env python3
# 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.

import gc
import os
import statistics
import time

import click

MAX_DAG_RUNS_ALLOWED = 1


class ShortCircutExecutorMixin:
    def __init__(self, stop_when_these_completed):
        super().__init__()
        self.reset(stop_when_these_completed)

    def reset(self, stop_when_these_completed):
        self.stop_when_these_completed = {
            # We want to store the dag run here, but we don't have them until they are created.
            key: None for key in stop_when_these_completed
        }

    def change_state(self, key, state):
        from airflow.utils.state import State
        super().change_state(key, state)

        dag_id, task_id, execution_date, __ = key
        run_key = (dag_id, execution_date.timestamp())
        if run_key in self.stop_when_these_completed:

            if self.stop_when_these_completed[run_key] is None:
                import airflow.models

                # We are interested in this run, but don't yet have the record for it.
                run = airflow.models.DagRun.find(dag_id=dag_id, execution_date=execution_date)[0]
                self.stop_when_these_completed[run_key] = run
            else:
                run = self.stop_when_these_completed[run_key]

            if run and all(t.state == State.SUCCESS for t in run.get_task_instances()):
                self.stop_when_these_completed.pop(run_key)

                if not self.stop_when_these_completed:
                    self.log.warning("STOPPING SCHEDULER -- all runs complete")
                    self.scheduler_job.processor_agent._done = True
                else:
                    self.log.warning("WAITING ON %d RUNS", len(self.stop_when_these_completed))


def get_executor_under_test():
    try:
        # Run against master and 1.10.x releases
        from tests.test_utils.mock_executor import MockExecutor
    except ImportError:
        from tests.executors.test_executor import TestExecutor as MockExecutor

    # from airflow.executors.local_executor import LocalExecutor

    # Change this to try other executors
    Executor = MockExecutor

    class ShortCircutExecutor(ShortCircutExecutorMixin, Executor):
        pass

    return ShortCircutExecutor


def reset_dag(dag, session):
    import airflow.models

    DR = airflow.models.DagRun
    DM = airflow.models.DagModel
    TI = airflow.models.TaskInstance
    TF = airflow.models.TaskFail
    dag_id = dag.dag_id

    session.query(DM).filter(DM.dag_id == dag_id).update({'is_paused': False})
    session.query(DR).filter(DR.dag_id == dag_id).delete()
    session.query(TI).filter(TI.dag_id == dag_id).delete()
    session.query(TF).filter(TF.dag_id == dag_id).delete()


def pause_all_dags(session):
    from airflow.models.dag import DagModel
    session.query(DagModel).update({'is_paused': True})


def create_dag_runs(dag, num_runs, session):
    from airflow.models.dagrun import DagRun
    from airflow.utils import timezone
    from airflow.utils.state import State

    next_run_date = dag.normalize_schedule(dag.start_date or min(t.start_date for t in dag.tasks))

    for _ in range(num_runs):
        dag.create_dagrun(
            run_id=DagRun.ID_PREFIX + next_run_date.isoformat(),
            execution_date=next_run_date,
            start_date=timezone.utcnow(),
            state=State.RUNNING,
            external_trigger=False,
            session=session,
        )
        next_run_date = dag.following_schedule(next_run_date)


@click.command()
@click.option('--num-runs', default=1, help='number of DagRun, to run for each DAG')
@click.option('--repeat', default=3, help='number of times to run test, to reduce variance')
@click.option('--pre-create-dag-runs', is_flag=True, default=False,
              help='''Pre-create the dag runs and stop the scheduler creating more.

        Warning: this makes the scheduler do (slightly) less work so may skew your numbers. Use sparingly!
        ''')
@click.argument('dag_ids', required=True, nargs=-1)
def main(num_runs, repeat, pre_create_dag_runs, dag_ids):
    """
    This script can be used to measure the total "scheduler overhead" of Airflow.

{'fraction_non_alphanumeric': 0.08523469695446778, 'fraction_numerical': 0.0032164036586591616, 'mean_word_length': 3.0879211175020544, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3392470', 'n_tokens_mistral': 3049, 'n_tokens_neox': 2887, 'n_words': 836}