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



##########
File path: airflow/utils/parse.py
##########
@@ -0,0 +1,168 @@
+#
+# 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.
+#
+
+"""Parse data from a file if it uses a valid format."""
+import json
+import logging
+import os
+from collections import defaultdict
+from json import JSONDecodeError
+from typing import Any, Dict, List, Tuple
+
+import airflow.utils.yaml as yaml
+from airflow.exceptions import AirflowException, AirflowFileParseException, 
FileSyntaxError
+from airflow.utils.file import COMMENT_PATTERN
+
+log = logging.getLogger(__name__)
+
+
+def _parse_env_file(file_path: str) -> Tuple[Dict[str, List[str]], 
List[FileSyntaxError]]:
+    """
+    Parse a file in the ``.env`` format.
+
+    .. code-block:: text
+
+        
MY_CONN_ID=my-conn-type://my-login:my-pa%2Fssword@my-host:5432/my-schema?param1=val1&param2=val2
+
+    :param file_path: The location of the file that will be processed.
+    :type file_path: str
+    :return: Tuple with mapping of key and list of values and list of syntax 
errors
+    """
+    with open(file_path) as f:
+        content = f.read()
+
+    contents_dict: Dict[str, List[str]] = defaultdict(list)
+    errors: List[FileSyntaxError] = []
+    for line_no, line in enumerate(content.splitlines(), 1):
+        if not line:
+            # Ignore empty line
+            continue
+
+        if COMMENT_PATTERN.match(line):
+            # Ignore comments
+            continue
+
+        var_parts: List[str] = line.split("=", 2)
+        if len(var_parts) != 2:
+            errors.append(
+                FileSyntaxError(
+                    line_no=line_no,
+                    message='Invalid line format. The line should contain at 
least one equal sign ("=").',
+                )
+            )
+            continue
+
+        key, value = var_parts
+        if not key:
+            errors.append(
+                FileSyntaxError(
+                    line_no=line_no,
+                    message="Invalid line format. Key is empty.",
+                )
+            )
+        contents_dict[key].append(value)
+    return contents_dict, errors
+
+
+def _parse_yaml_file(file_path: str) -> Tuple[Dict[str, List[str]], 
List[FileSyntaxError]]:
+    """
+    Parse a file in the YAML format.
+
+    :param file_path: The location of the file that will be processed.
+    :type file_path: str
+    :return: Tuple with mapping of key and list of values and list of syntax 
errors
+    """
+    with open(file_path) as f:
+        content = f.read()
+
+    if not content:
+        return {}, [FileSyntaxError(line_no=1, message="The file is empty.")]
+    try:
+        contents_dict = yaml.safe_load(content)
+
+    except yaml.MarkedYAMLError as e:
+        return {}, [FileSyntaxError(line_no=e.problem_mark.line, 
message=str(e))]
+    if not isinstance(contents_dict, dict):
+        return {}, [FileSyntaxError(line_no=1, message="The file should 
contain the object.")]
+
+    return contents_dict, []
+
+
+def _parse_json_file(file_path: str) -> Tuple[Dict[str, Any], 
List[FileSyntaxError]]:
+    """
+    Parse a file in the JSON format.
+
+    :param file_path: The location of the file that will be processed.
+    :type file_path: str
+    :return: Tuple with mapping of key and list of values and list of syntax 
errors
+    """
+    with open(file_path) as f:
+        content = f.read()
+
+    if not content:
+        return {}, [FileSyntaxError(line_no=1, message="The file is empty.")]
+    try:
+        contents_dict = json.loads(content)
+    except JSONDecodeError as e:
+        return {}, [FileSyntaxError(line_no=int(e.lineno), message=e.msg)]
+    if not isinstance(contents_dict, dict):
+        return {}, [FileSyntaxError(line_no=1, message="The file should 
contain the object.")]
+
+    return contents_dict, []
+
+
+FILE_PARSERS = {
+    "env": _parse_env_file,
+    "json": _parse_json_file,
+    "yaml": _parse_yaml_file,
+}
+
+
+def _parse_file(file_path: str) -> Dict[str, Any]:
+    """
+    Based on the file extension format, selects a parser, and parses the file.
+
+    :param file_path: The location of the file that will be processed.
+    :type file_path: str
+    :return: Map of key (e.g. connection ID) and value.
+    """
+    if not os.path.exists(file_path):
+        raise AirflowException(f"File {file_path} was not found.")
+
+    log.debug("Parsing file: %s", file_path)
+
+    ext = file_path.rsplit(".", 2)[-1].lower()
+
+    if ext not in FILE_PARSERS:
+        raise AirflowException(
+            "Unsupported file format. The file must have the extension .env or 
.json or .yaml"
+        )
+
+    contents_dict, parse_errors = FILE_PARSERS[ext](file_path)
+
+    log.debug(
+        "Parsed file: len(parse_errors)=%d, len(contents_dict)=%d", 
len(parse_errors), len(contents_dict)
+    )
+
+    if parse_errors:
+        raise AirflowFileParseException(
+            "Failed to load the file.", file_path=file_path, 
parse_errors=parse_errors
+        )

Review comment:
       Just make the format specific parsers throw the errors directly?

##########
File path: airflow/utils/parse.py
##########
@@ -0,0 +1,168 @@
+#
+# 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.
+#
+
+"""Parse data from a file if it uses a valid format."""
+import json
+import logging
+import os
+from collections import defaultdict
+from json import JSONDecodeError
+from typing import Any, Dict, List, Tuple
+
+import airflow.utils.yaml as yaml
+from airflow.exceptions import AirflowException, AirflowFileParseException, 
FileSyntaxError
+from airflow.utils.file import COMMENT_PATTERN
+
+log = logging.getLogger(__name__)
+
+
+def _parse_env_file(file_path: str) -> Tuple[Dict[str, List[str]], 
List[FileSyntaxError]]:
+    """
+    Parse a file in the ``.env`` format.
+
+    .. code-block:: text
+
+        
MY_CONN_ID=my-conn-type://my-login:my-pa%2Fssword@my-host:5432/my-schema?param1=val1&param2=val2
+
+    :param file_path: The location of the file that will be processed.
+    :type file_path: str
+    :return: Tuple with mapping of key and list of values and list of syntax 
errors
+    """
+    with open(file_path) as f:
+        content = f.read()
+
+    contents_dict: Dict[str, List[str]] = defaultdict(list)
+    errors: List[FileSyntaxError] = []
+    for line_no, line in enumerate(content.splitlines(), 1):
+        if not line:
+            # Ignore empty line
+            continue

Review comment:
       This loads the whole file in to memory, which is slightly wasteful. 
Instead we should do something like this:
   
   ```python
       with open(file_path) as f:
           for line_no, line in enumerate(f, 1):
               if not line.strip():
                  continue
   ```

##########
File path: airflow/utils/parse.py
##########
@@ -0,0 +1,168 @@
+#
+# 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.
+#
+
+"""Parse data from a file if it uses a valid format."""
+import json
+import logging
+import os
+from collections import defaultdict
+from json import JSONDecodeError
+from typing import Any, Dict, List, Tuple
+
+import airflow.utils.yaml as yaml
+from airflow.exceptions import AirflowException, AirflowFileParseException, 
FileSyntaxError
+from airflow.utils.file import COMMENT_PATTERN
+
+log = logging.getLogger(__name__)
+
+
+def _parse_env_file(file_path: str) -> Tuple[Dict[str, List[str]], 
List[FileSyntaxError]]:
+    """
+    Parse a file in the ``.env`` format.
+
+    .. code-block:: text
+
+        
MY_CONN_ID=my-conn-type://my-login:my-pa%2Fssword@my-host:5432/my-schema?param1=val1&param2=val2
+
+    :param file_path: The location of the file that will be processed.
+    :type file_path: str
+    :return: Tuple with mapping of key and list of values and list of syntax 
errors
+    """
+    with open(file_path) as f:
+        content = f.read()
+
+    contents_dict: Dict[str, List[str]] = defaultdict(list)
+    errors: List[FileSyntaxError] = []
+    for line_no, line in enumerate(content.splitlines(), 1):
+        if not line:
+            # Ignore empty line
+            continue
+
+        if COMMENT_PATTERN.match(line):
+            # Ignore comments
+            continue
+
+        var_parts: List[str] = line.split("=", 2)
+        if len(var_parts) != 2:
+            errors.append(
+                FileSyntaxError(
+                    line_no=line_no,
+                    message='Invalid line format. The line should contain at 
least one equal sign ("=").',
+                )
+            )
+            continue
+
+        key, value = var_parts
+        if not key:
+            errors.append(
+                FileSyntaxError(
+                    line_no=line_no,
+                    message="Invalid line format. Key is empty.",
+                )
+            )
+        contents_dict[key].append(value)
+    return contents_dict, errors
+
+
+def _parse_yaml_file(file_path: str) -> Tuple[Dict[str, List[str]], 
List[FileSyntaxError]]:
+    """
+    Parse a file in the YAML format.
+
+    :param file_path: The location of the file that will be processed.
+    :type file_path: str
+    :return: Tuple with mapping of key and list of values and list of syntax 
errors
+    """
+    with open(file_path) as f:
+        content = f.read()
+
+    if not content:
+        return {}, [FileSyntaxError(line_no=1, message="The file is empty.")]
+    try:
+        contents_dict = yaml.safe_load(content)
+
+    except yaml.MarkedYAMLError as e:
+        return {}, [FileSyntaxError(line_no=e.problem_mark.line, 
message=str(e))]
+    if not isinstance(contents_dict, dict):
+        return {}, [FileSyntaxError(line_no=1, message="The file should 
contain the object.")]
+
+    return contents_dict, []
+
+
+def _parse_json_file(file_path: str) -> Tuple[Dict[str, Any], 
List[FileSyntaxError]]:
+    """
+    Parse a file in the JSON format.
+
+    :param file_path: The location of the file that will be processed.
+    :type file_path: str
+    :return: Tuple with mapping of key and list of values and list of syntax 
errors
+    """
+    with open(file_path) as f:
+        content = f.read()
+
+    if not content:
+        return {}, [FileSyntaxError(line_no=1, message="The file is empty.")]
+    try:
+        contents_dict = json.loads(content)
+    except JSONDecodeError as e:
+        return {}, [FileSyntaxError(line_no=int(e.lineno), message=e.msg)]
+    if not isinstance(contents_dict, dict):
+        return {}, [FileSyntaxError(line_no=1, message="The file should 
contain the object.")]

Review comment:
       ```suggestion
           return {}, [FileSyntaxError(line_no=1, message="The file should 
contain an object.")]
   ```

##########
File path: airflow/utils/parse.py
##########
@@ -0,0 +1,168 @@
+#
+# 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.
+#
+
+"""Parse data from a file if it uses a valid format."""
+import json
+import logging
+import os
+from collections import defaultdict
+from json import JSONDecodeError
+from typing import Any, Dict, List, Tuple
+
+import airflow.utils.yaml as yaml
+from airflow.exceptions import AirflowException, AirflowFileParseException, 
FileSyntaxError
+from airflow.utils.file import COMMENT_PATTERN
+
+log = logging.getLogger(__name__)
+
+
+def _parse_env_file(file_path: str) -> Tuple[Dict[str, List[str]], 
List[FileSyntaxError]]:
+    """
+    Parse a file in the ``.env`` format.
+
+    .. code-block:: text
+
+        
MY_CONN_ID=my-conn-type://my-login:my-pa%2Fssword@my-host:5432/my-schema?param1=val1&param2=val2
+
+    :param file_path: The location of the file that will be processed.
+    :type file_path: str
+    :return: Tuple with mapping of key and list of values and list of syntax 
errors
+    """
+    with open(file_path) as f:
+        content = f.read()
+
+    contents_dict: Dict[str, List[str]] = defaultdict(list)
+    errors: List[FileSyntaxError] = []
+    for line_no, line in enumerate(content.splitlines(), 1):
+        if not line:
+            # Ignore empty line
+            continue
+
+        if COMMENT_PATTERN.match(line):
+            # Ignore comments
+            continue
+
+        var_parts: List[str] = line.split("=", 2)
+        if len(var_parts) != 2:
+            errors.append(
+                FileSyntaxError(
+                    line_no=line_no,
+                    message='Invalid line format. The line should contain at 
least one equal sign ("=").',
+                )
+            )
+            continue
+
+        key, value = var_parts
+        if not key:
+            errors.append(
+                FileSyntaxError(
+                    line_no=line_no,
+                    message="Invalid line format. Key is empty.",
+                )
+            )
+        contents_dict[key].append(value)
+    return contents_dict, errors
+
+
+def _parse_yaml_file(file_path: str) -> Tuple[Dict[str, List[str]], 
List[FileSyntaxError]]:
+    """
+    Parse a file in the YAML format.
+
+    :param file_path: The location of the file that will be processed.
+    :type file_path: str
+    :return: Tuple with mapping of key and list of values and list of syntax 
errors
+    """
+    with open(file_path) as f:
+        content = f.read()
+
+    if not content:
+        return {}, [FileSyntaxError(line_no=1, message="The file is empty.")]
+    try:
+        contents_dict = yaml.safe_load(content)
+
+    except yaml.MarkedYAMLError as e:
+        return {}, [FileSyntaxError(line_no=e.problem_mark.line, 
message=str(e))]
+    if not isinstance(contents_dict, dict):
+        return {}, [FileSyntaxError(line_no=1, message="The file should 
contain the object.")]
+
+    return contents_dict, []
+
+
+def _parse_json_file(file_path: str) -> Tuple[Dict[str, Any], 
List[FileSyntaxError]]:
+    """
+    Parse a file in the JSON format.
+
+    :param file_path: The location of the file that will be processed.
+    :type file_path: str
+    :return: Tuple with mapping of key and list of values and list of syntax 
errors
+    """
+    with open(file_path) as f:
+        content = f.read()
+
+    if not content:
+        return {}, [FileSyntaxError(line_no=1, message="The file is empty.")]
+    try:
+        contents_dict = json.loads(content)
+    except JSONDecodeError as e:
+        return {}, [FileSyntaxError(line_no=int(e.lineno), message=e.msg)]
+    if not isinstance(contents_dict, dict):
+        return {}, [FileSyntaxError(line_no=1, message="The file should 
contain the object.")]
+
+    return contents_dict, []
+
+
+FILE_PARSERS = {
+    "env": _parse_env_file,
+    "json": _parse_json_file,
+    "yaml": _parse_yaml_file,
+}
+
+
+def _parse_file(file_path: str) -> Dict[str, Any]:

Review comment:
       Since this is used outside of this module it should be "non-private"
   
   ```suggestion
   def parse_file(file_path: str) -> Dict[str, Any]:
   ```

##########
File path: airflow/secrets/local_filesystem.py
##########
@@ -263,19 +71,32 @@ def load_connections_dict(file_path: str) -> Dict[str, 
Any]:
     :return: A dictionary where the key contains a connection ID and the value 
contains the connection.
     :rtype: Dict[str, airflow.models.connection.Connection]
     """
+    from airflow.models.connection import Connection
+
     log.debug("Loading connection")
 
-    secrets: Dict[str, Any] = _parse_secret_file(file_path)
+    secrets: Dict[str, Any] = _parse_file(file_path)
     connection_by_conn_id = {}
     for key, secret_values in list(secrets.items()):
         if isinstance(secret_values, list):
-            if len(secret_values) > 1:
+            # secret_values is either length 0, 1 or 2+ -- only length 1 is 
valid
+            if not secret_values:
+                log.debug("No secret values for %s", key)
+                continue
+
+            if len(secret_values) >= 2:
                 raise ConnectionNotUnique(f"Found multiple values for {key} in 
{file_path}.")
 
-            for secret_value in secret_values:
-                connection_by_conn_id[key] = _create_connection(key, 
secret_value)
+            # secret_values must be of length one, so unpack it
+            elif secret_values:
+                secret_values = secret_values[0]
+
+        if isinstance(secret_values, dict):
+            connection_by_conn_id[key] = Connection.from_dict(key, 
secret_values)
+        elif isinstance(secret_values, str):
+            connection_by_conn_id[key] = Connection(uri=secret_values)
         else:
-            connection_by_conn_id[key] = _create_connection(key, secret_values)
+            raise AirflowException(f"Unexpected value type: 
{type(secret_values)}.")

Review comment:
       ```suggestion
               raise AirflowException(f"Unexpected value type: 
{type(secret_values).__name__}.")
   ```

##########
File path: airflow/secrets/local_filesystem.py
##########
@@ -263,19 +71,32 @@ def load_connections_dict(file_path: str) -> Dict[str, 
Any]:
     :return: A dictionary where the key contains a connection ID and the value 
contains the connection.
     :rtype: Dict[str, airflow.models.connection.Connection]
     """
+    from airflow.models.connection import Connection
+
     log.debug("Loading connection")
 
-    secrets: Dict[str, Any] = _parse_secret_file(file_path)
+    secrets: Dict[str, Any] = _parse_file(file_path)
     connection_by_conn_id = {}
     for key, secret_values in list(secrets.items()):
         if isinstance(secret_values, list):
-            if len(secret_values) > 1:
+            # secret_values is either length 0, 1 or 2+ -- only length 1 is 
valid
+            if not secret_values:
+                log.debug("No secret values for %s", key)
+                continue
+
+            if len(secret_values) >= 2:
                 raise ConnectionNotUnique(f"Found multiple values for {key} in 
{file_path}.")
 
-            for secret_value in secret_values:
-                connection_by_conn_id[key] = _create_connection(key, 
secret_value)
+            # secret_values must be of length one, so unpack it
+            elif secret_values:
+                secret_values = secret_values[0]
+
+        if isinstance(secret_values, dict):
+            connection_by_conn_id[key] = Connection.from_dict(key, 
secret_values)

Review comment:
       Do we need a method for this? Isn't it the same as
   
   ```suggestion
               connection_by_conn_id[key] = Connection(key, **secret_values)
   ```




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