ashb commented on a change in pull request #8991:
URL: https://github.com/apache/airflow/pull/8991#discussion_r429920356



##########
File path: backport_packages/import_all_provider_classes.py
##########
@@ -0,0 +1,97 @@
+#!/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 importlib
+import os
+import sys
+import traceback
+from inspect import isclass
+from typing import List
+
+
+def import_all_provider_classes(source_path: str,
+                                provider_ids: List[str] = None,
+                                print_imports: bool = False) -> List[str]:
+    """
+    Imports all classes in providers packages. This method loads and imports
+    all the classes found in providers, so that we can find all the subclasses
+    of operators/sensors etc.
+
+    :param provider_ids - provider ids that should be loaded.
+    :param print_imports - if imported class should also be printed in output
+    :param source_path: path to look for sources - might be None to look for 
all packages in all source paths
+    :return: list of all imported classes
+    """
+    if provider_ids:
+        prefixed_provider_paths = [source_path + "/airflow/providers/" + 
provider_id.replace(".", "/")
+                                   for provider_id in provider_ids]
+    else:
+        prefixed_provider_paths = [source_path + "/airflow/providers/"]
+
+    imported_classes = []
+    tracebacks = []
+    for root, dirs, files in os.walk(source_path):
+        if all([not root.startswith(prefix_provider_path)
+                for prefix_provider_path in prefixed_provider_paths]) or 
root.endswith("__pycache__"):
+            # Skip loading module if it is not in the list of providers that 
we are looking for
+            continue
+        package_name = root[len(source_path) + 1:].replace("/", ".")
+        for file in files:
+            if file.endswith(".py"):
+                module_name = package_name + "." + file[:-3] if file != 
"__init__.py" else package_name
+                if print_imports:
+                    print(f"Importing module: {module_name}")
+                # noinspection PyBroadException
+                try:
+                    _module = importlib.import_module(module_name)
+                    for attribute_name in dir(_module):
+                        class_name = module_name + "." + attribute_name
+                        attribute = getattr(_module, attribute_name)
+                        if isclass(attribute):
+                            if print_imports:
+                                print(f"Imported {class_name}")
+                            imported_classes.append(class_name)
+                except Exception:
+                    exception_str = traceback.format_exc()
+                    tracebacks.append(exception_str)
+    if tracebacks:
+        print()
+        print("ERROR: There were some import errors")
+        print()
+        for trace in tracebacks:
+            print("----------------------------------------")
+            print(trace)
+            print("----------------------------------------")
+        sys.exit(1)

Review comment:
       All these prints should be to sys.stdout really.

##########
File path: backport_packages/refactor_backport_packages.py
##########
@@ -0,0 +1,750 @@
+#!/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 os
+import sys
+from os.path import dirname
+from shutil import copyfile, copytree, rmtree
+from typing import List
+
+from backport_packages.setup_backport_packages import (
+    get_source_airflow_folder, get_source_providers_folder, 
get_target_providers_folder,
+    get_target_providers_package_folder, is_bigquery_non_dts_module,
+)
+from bowler import LN, TOKEN, Capture, Filename, Query
+from fissix.fixer_util import Comma, KeywordArg, Name
+from fissix.pytree import Leaf
+
+CLASS_TYPES = ["hooks", "operators", "sensors", "secrets", "protocols"]
+
+
+def copy_provider_sources() -> None:
+    """
+    Copies provider sources to directory where they will be refactored.
+    """
+    def rm_build_dir() -> None:
+        """
+        Removes build directory.
+        """
+        build_dir = os.path.join(dirname(__file__), "build")
+        if os.path.isdir(build_dir):
+            rmtree(build_dir)
+
+    def ignore_bigquery_files(src: str, names: List[str]) -> List[str]:
+        """
+        Ignore files with bigquery
+        :param src: source file
+        :param names: Name of the file
+        :return:
+        """
+        ignored_names = []
+        if any([src.endswith(os.path.sep + class_type) for class_type in 
CLASS_TYPES]):
+            ignored_names = [name for name in names
+                             if is_bigquery_non_dts_module(module_name=name)]
+        if src.endswith(os.path.sep + "example_dags"):
+            for file_name in names:
+                file_path = src + os.path.sep + file_name
+                with open(file_path, "rt") as file:
+                    text = file.read()
+                if 
any([f"airflow.providers.google.cloud.{class_type}.bigquery" in text
+                        for class_type in CLASS_TYPES]) or "_to_bigquery" in 
text:
+                    print(f"Ignoring {file_path}")
+                    ignored_names.append(file_name)
+        return ignored_names
+
+    def ignore_kubernetes_files(src: str, names: List[str]) -> List[str]:
+        ignored_names = []
+        if src.endswith(os.path.sep + "example_dags"):
+            for file_name in names:
+                if "example_kubernetes" in file_name:
+                    ignored_names.append(file_name)
+        return ignored_names
+
+    def ignore_some_files(src: str, names: List[str]) -> List[str]:
+        ignored_list = ignore_bigquery_files(src=src, names=names)
+        ignored_list.extend(ignore_kubernetes_files(src=src, names=names))
+        return ignored_list
+
+    rm_build_dir()
+    package_providers_dir = get_target_providers_folder()
+    if os.path.isdir(package_providers_dir):
+        rmtree(package_providers_dir)
+    copytree(get_source_providers_folder(), get_target_providers_folder(), 
ignore=ignore_some_files)
+
+
+def copy_helper_py_file(target_file_path: str) -> None:
+    """
+    Copies. airflow/utils/helper.py to a new location within provider package
+
+    The helper has two methods (chain, cross_downstream) that are moved from 
the original helper to
+    'airflow.models.baseoperator'. so in 1.10 they should reimport the 
original 'airflow.utils.helper'
+    methods. Those deprecated methods use importe with 
import_string("<IMPORT>") so it is easier to
+    replace them as strings rather than with Bowler
+
+    :param target_file_path: target path name for the helpers.py
+    """
+
+    source_helper_file_path = os.path.join(get_source_airflow_folder(), 
"airflow", "utils", "helpers.py")
+
+    with open(source_helper_file_path, "rt") as in_file:
+        with open(target_file_path, "wt") as out_file:
+            for line in in_file:
+                out_file.write(line.replace('airflow.models.baseoperator', 
'airflow.utils.helpers'))
+
+
+class RefactorBackportPackages:
+    """
+    Refactors the code of providers, so that it works in 1.10.
+
+    """
+
+    def __init__(self):
+        self.qry = Query()
+
+    def remove_class(self, class_name) -> None:
+        """
+        Removes class altogether. Example diff generated:
+
+
+        .. code-block:: diff
+
+            --- ./airflow/providers/google/cloud/operators/kubernetes_engine.py
+            +++ ./airflow/providers/google/cloud/operators/kubernetes_engine.py
+            @@ -179,86 +179,3 @@
+            -
+            -class GKEStartPodOperator(KubernetesPodOperator):
+            -
+            - ...
+
+        :param class_name: name to remove
+        """
+        # noinspection PyUnusedLocal
+        def _remover(node: LN, capture: Capture, filename: Filename) -> None:
+            if node.type not in (300, 311):  # remove only definition
+                node.remove()
+
+        self.qry.select_class(class_name).modify(_remover)
+
+    def rename_deprecated_modules(self) -> None:
+        """
+        Renames back to deprecated modules imported. Example diff generated:
+
+        .. code-block:: diff
+
+            --- ./airflow/providers/dingding/operators/dingding.py
+            +++ ./airflow/providers/dingding/operators/dingding.py
+            @@ -16,7 +16,7 @@
+             # specific language governing permissions and limitations
+             # under the License.
+
+            -from airflow.operators.bash import BaseOperator
+            +from airflow.operators.bash_operator import BaseOperator
+             from airflow.providers.dingding.hooks.dingding import DingdingHook
+             from airflow.utils.decorators import apply_defaults
+
+        """
+        changes = [
+            ("airflow.operators.bash", "airflow.operators.bash_operator"),
+            ("airflow.operators.python", "airflow.operators.python_operator"),
+            ("airflow.utils.session", "airflow.utils.db"),
+            (
+                "airflow.providers.cncf.kubernetes.operators.kubernetes_pod",
+                "airflow.contrib.operators.kubernetes_pod_operator"
+            ),
+        ]
+        for new, old in changes:
+            self.qry.select_module(new).rename(old)
+
+    def add_provide_context_to_python_operators(self) -> None:
+        """
+
+        Adds provide context to usages of Python/BranchPython Operators in 
example dags.
+        Note that those changes  apply to example DAGs not to the 
operators/hooks erc.
+        We package the example DAGs together with the provider classes and 
they should serve as
+        examples independently on the version of Airflow it will be installed 
in.
+        Provide_context feature in Python operators was feature added 2.0.0 
and we are still
+        using the "Core" operators from the Airflow version that the backport 
packages are installed
+        in - the "Core" operators do not have (for now) their own provider 
package.
+
+        The core operators are:
+
+            * Python
+            * BranchPython
+            * Bash
+            * Branch
+            * Dummy
+            * LatestOnly
+            * ShortCircuit
+            * PythonVirtualEnv
+
+
+        Example diff generated:
+
+        .. code-block:: diff
+
+            --- 
./airflow/providers/amazon/aws/example_dags/example_google_api_to_s3_transfer_advanced.py
+            +++ 
./airflow/providers/amazon/aws/example_dags/example_google_api_to_s3_transfer_advanced.py
+            @@ -105,7 +105,8 @@
+                         task_video_ids_to_s3.google_api_response_via_xcom,
+                         task_video_ids_to_s3.task_id
+                     ],
+            -        task_id='check_and_transform_video_ids'
+            +        task_id='check_and_transform_video_ids',
+            +        provide_context=True
+                 )
+
+        """
+        # noinspection PyUnusedLocal
+        def add_provide_context_to_python_operator(node: LN, capture: Capture, 
filename: Filename) -> None:
+            fn_args = capture['function_arguments'][0]
+            fn_args.append_child(Comma())
+
+            provide_context_arg = KeywordArg(Name('provide_context'), 
Name('True'))
+            provide_context_arg.prefix = fn_args.children[0].prefix
+            fn_args.append_child(provide_context_arg)
+
+        (
+            self.qry.
+            select_function("PythonOperator").
+            is_call().
+            is_filename(include=r"mlengine_operator_utils.py$").
+            modify(add_provide_context_to_python_operator)
+        )
+        (
+            self.qry.
+            select_function("BranchPythonOperator").
+            is_call().
+            
is_filename(include=r"example_google_api_to_s3_transfer_advanced.py$").
+            modify(add_provide_context_to_python_operator)
+        )
+
+    def remove_super_init_call(self):
+        """
+        Removes super().__init__() call from Hooks. Example diff generated:
+
+        .. code-block:: diff
+
+            --- ./airflow/providers/apache/druid/hooks/druid.py
+            +++ ./airflow/providers/apache/druid/hooks/druid.py
+            @@ -49,7 +49,7 @@
+                         timeout=1,
+                         max_ingestion_time=None):
+
+            -        super().__init__()
+            +

Review comment:
       Why do we want to do this? Druid inherits basehook, surely we want to 
keep that still?

##########
File path: airflow/config_templates/config.yml
##########
@@ -672,7 +672,7 @@
       version_added: ~
       type: string
       example: ~
-      default: "Airflow HiveOperator task for 
{{hostname}}.{{dag_id}}.{{task_id}}.{{execution_date}}"

Review comment:
       Okay, wow, so this config option was introduced in #3534 from 2018, but 
was never included in any release.
   
   So I actually think the change as you have it is right, otherwise this 
operator wouldn't work without adding a new config option. 

##########
File path: airflow/providers/apache/hive/operators/hive.py
##########
@@ -95,8 +95,11 @@ def __init__(
         self.mapred_queue = mapred_queue
         self.mapred_queue_priority = mapred_queue_priority
         self.mapred_job_name = mapred_job_name
-        self.mapred_job_name_template = conf.get('hive',
-                                                 'mapred_job_name_template')
+        self.mapred_job_name_template = conf.get(
+            'hive', 'mapred_job_name_template', fallback='')
+        if self.mapred_job_name_template == '':
+            self.mapred_job_name_template = "Airflow HiveOperator task for " \
+                                            
"{hostname}.{dag_id}.{task_id}.{execution_date}"

Review comment:
       ```suggestion
           self.mapred_job_name_template = conf.get(
               'hive', 'mapred_job_name_template', fallback="Airflow 
HiveOperator task for " \
                                               
"{hostname}.{dag_id}.{task_id}.{execution_date}")
   ```
   
   (I've messed up the formatting, but I think you get the idea)




----------------------------------------------------------------
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:
[email protected]


Reply via email to