You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "guydriesen (via GitHub)" <gi...@apache.org> on 2024/05/07 15:15:31 UTC

[PR] Add args to docker service ContainerSpec [airflow]

guydriesen opened a new pull request, #39464:
URL: https://github.com/apache/airflow/pull/39464

   This PR adds the support for defining arguments to the DockerSwarmOperator.
   
   The currently available command option replaces the entrypoint on a docker service container, with the args you can give extra options to the entrypoint.
   
   <!--
    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.
    -->
   
   <!--
   Thank you for contributing! Please make sure that your code changes
   are covered with tests. And in case of new features or big changes
   remember to adjust the documentation.
   
   Feel free to ping committers for the review!
   
   In case of an existing issue, reference it using one of the following:
   
   closes: #ISSUE
   related: #ISSUE
   
   How to write a good git commit message:
   http://chris.beams.io/posts/git-commit/
   -->
   
   
   
   <!-- Please keep an empty line above the dashes. -->
   ---
   **^ Add meaningful description above**
   Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information.
   In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
   


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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add args to docker service ContainerSpec [airflow]

Posted by "Taragolis (via GitHub)" <gi...@apache.org>.
Taragolis commented on code in PR #39464:
URL: https://github.com/apache/airflow/pull/39464#discussion_r1592797003


##########
airflow/providers/docker/operators/docker_swarm.py:
##########
@@ -225,6 +231,24 @@ def stream_new_logs(last_line_logged, since=0):
             sleep(2)
             last_line_logged, last_timestamp = stream_new_logs(last_line_logged, since=last_timestamp)
 
+    @staticmethod
+    def format_args(args: list[str] | str | None) -> list[str] | None:
+        """Retrieve args.
+
+        The args string is parsed to a list. If it starts with ``[``,
+        the string is treated as a Python literal and parsed into a list.
+
+        :param args: args to the docker service
+
+        :return: the args as list
+        """
+        if isinstance(args, str):
+            if args.strip().startswith("["):
+                return ast.literal_eval(args)
+            else:
+                return shlex.split(args)
+        return args

Review Comment:
   Just wondering why it might required to parse it via `ast.literal_eval `, and not via `json.loads`. And why it is required to parse it? Maybe you could provide some real use cases?



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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add args to docker service ContainerSpec [airflow]

Posted by "Taragolis (via GitHub)" <gi...@apache.org>.
Taragolis merged PR #39464:
URL: https://github.com/apache/airflow/pull/39464


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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add args to docker service ContainerSpec [airflow]

Posted by "Taragolis (via GitHub)" <gi...@apache.org>.
Taragolis commented on code in PR #39464:
URL: https://github.com/apache/airflow/pull/39464#discussion_r1593491332


##########
airflow/providers/docker/operators/docker_swarm.py:
##########
@@ -225,6 +231,24 @@ def stream_new_logs(last_line_logged, since=0):
             sleep(2)
             last_line_logged, last_timestamp = stream_new_logs(last_line_logged, since=last_timestamp)
 
+    @staticmethod
+    def format_args(args: list[str] | str | None) -> list[str] | None:
+        """Retrieve args.
+
+        The args string is parsed to a list. If it starts with ``[``,
+        the string is treated as a Python literal and parsed into a list.
+
+        :param args: args to the docker service
+
+        :return: the args as list
+        """
+        if isinstance(args, str):
+            if args.strip().startswith("["):
+                return ast.literal_eval(args)
+            else:
+                return shlex.split(args)
+        return args

Review Comment:
   > I just got that from the docker command formatter
   
   It was exists because :
   - Field `DockerOperator.command` templated
   - For historical reason, it add this support before NativeEnvironment and/or JSON encoder
   
   But I can't see this case here
   



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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add args to docker service ContainerSpec [airflow]

Posted by "Taragolis (via GitHub)" <gi...@apache.org>.
Taragolis commented on code in PR #39464:
URL: https://github.com/apache/airflow/pull/39464#discussion_r1593883440


##########
airflow/providers/docker/operators/docker_swarm.py:
##########
@@ -225,6 +231,24 @@ def stream_new_logs(last_line_logged, since=0):
             sleep(2)
             last_line_logged, last_timestamp = stream_new_logs(last_line_logged, since=last_timestamp)
 
+    @staticmethod
+    def format_args(args: list[str] | str | None) -> list[str] | None:
+        """Retrieve args.
+
+        The args string is parsed to a list. If it starts with ``[``,
+        the string is treated as a Python literal and parsed into a list.
+
+        :param args: args to the docker service
+
+        :return: the args as list
+        """
+        if isinstance(args, str):
+            if args.strip().startswith("["):
+                return ast.literal_eval(args)
+            else:
+                return shlex.split(args)
+        return args

Review Comment:
   I mean, maybe it is even not required, since it not templated field, so user have an option to provide it as pure string command
   
   ```python
   DockerSwarmOperator(
       task_id="foo-bar",
       ...
       args="--foo bar --spam --egg",
   )
   ```
   
   Or command list
   
   ```python
   DockerSwarmOperator(
       task_id="foo-bar",
       ...
       args=["--foo", "bar", "--spam", "--egg"],
   )
   ```
   
   But I'm not sure if it handy to provide as json / string representation of python list at all
   
   ```python
   DockerSwarmOperator(
       task_id="foo-bar",
       ...
       args='["--foo", "bar", "--spam", "--egg"]',
   )
   ```



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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add args to docker service ContainerSpec [airflow]

Posted by "guydriesen (via GitHub)" <gi...@apache.org>.
guydriesen commented on code in PR #39464:
URL: https://github.com/apache/airflow/pull/39464#discussion_r1593856057


##########
airflow/providers/docker/operators/docker_swarm.py:
##########
@@ -225,6 +231,24 @@ def stream_new_logs(last_line_logged, since=0):
             sleep(2)
             last_line_logged, last_timestamp = stream_new_logs(last_line_logged, since=last_timestamp)
 
+    @staticmethod
+    def format_args(args: list[str] | str | None) -> list[str] | None:
+        """Retrieve args.
+
+        The args string is parsed to a list. If it starts with ``[``,
+        the string is treated as a Python literal and parsed into a list.
+
+        :param args: args to the docker service
+
+        :return: the args as list
+        """
+        if isinstance(args, str):
+            if args.strip().startswith("["):
+                return ast.literal_eval(args)
+            else:
+                return shlex.split(args)
+        return args

Review Comment:
   I've replaced it with `json.loads`.



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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add args to docker service ContainerSpec [airflow]

Posted by "guydriesen (via GitHub)" <gi...@apache.org>.
guydriesen commented on code in PR #39464:
URL: https://github.com/apache/airflow/pull/39464#discussion_r1593969669


##########
airflow/providers/docker/operators/docker_swarm.py:
##########
@@ -225,6 +231,24 @@ def stream_new_logs(last_line_logged, since=0):
             sleep(2)
             last_line_logged, last_timestamp = stream_new_logs(last_line_logged, since=last_timestamp)
 
+    @staticmethod
+    def format_args(args: list[str] | str | None) -> list[str] | None:
+        """Retrieve args.
+
+        The args string is parsed to a list. If it starts with ``[``,
+        the string is treated as a Python literal and parsed into a list.
+
+        :param args: args to the docker service
+
+        :return: the args as list
+        """
+        if isinstance(args, str):
+            if args.strip().startswith("["):
+                return ast.literal_eval(args)
+            else:
+                return shlex.split(args)
+        return args

Review Comment:
   I see, yes, it's probably even better to leave that out.
   Initially I thought to replicate the behavior of the docker command, as that is what the args are on the containerspec.
   Thanks, I'll remove it.



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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add args to docker service ContainerSpec [airflow]

Posted by "guydriesen (via GitHub)" <gi...@apache.org>.
guydriesen commented on code in PR #39464:
URL: https://github.com/apache/airflow/pull/39464#discussion_r1592822375


##########
airflow/providers/docker/operators/docker_swarm.py:
##########
@@ -225,6 +231,24 @@ def stream_new_logs(last_line_logged, since=0):
             sleep(2)
             last_line_logged, last_timestamp = stream_new_logs(last_line_logged, since=last_timestamp)
 
+    @staticmethod
+    def format_args(args: list[str] | str | None) -> list[str] | None:
+        """Retrieve args.
+
+        The args string is parsed to a list. If it starts with ``[``,
+        the string is treated as a Python literal and parsed into a list.
+
+        :param args: args to the docker service
+
+        :return: the args as list
+        """
+        if isinstance(args, str):
+            if args.strip().startswith("["):
+                return ast.literal_eval(args)
+            else:
+                return shlex.split(args)
+        return args

Review Comment:
   I just got that from the docker command formatter https://github.com/apache/airflow/blob/e299ac91e2fddc709487aaaa4bb24162f77ba615/airflow/providers/docker/operators/docker.py#L523 and thought it was a good idea to have this done the same way.



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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add args to docker service ContainerSpec [airflow]

Posted by "guydriesen (via GitHub)" <gi...@apache.org>.
guydriesen commented on code in PR #39464:
URL: https://github.com/apache/airflow/pull/39464#discussion_r1592822375


##########
airflow/providers/docker/operators/docker_swarm.py:
##########
@@ -225,6 +231,24 @@ def stream_new_logs(last_line_logged, since=0):
             sleep(2)
             last_line_logged, last_timestamp = stream_new_logs(last_line_logged, since=last_timestamp)
 
+    @staticmethod
+    def format_args(args: list[str] | str | None) -> list[str] | None:
+        """Retrieve args.
+
+        The args string is parsed to a list. If it starts with ``[``,
+        the string is treated as a Python literal and parsed into a list.
+
+        :param args: args to the docker service
+
+        :return: the args as list
+        """
+        if isinstance(args, str):
+            if args.strip().startswith("["):
+                return ast.literal_eval(args)
+            else:
+                return shlex.split(args)
+        return args

Review Comment:
   I just got that from the docker command formatter (https://github.com/apache/airflow/blob/e299ac91e2fddc709487aaaa4bb24162f77ba615/airflow/providers/docker/operators/docker.py#L512), and thought it was a good idea to have this done the same way.



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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add args to docker service ContainerSpec [airflow]

Posted by "guydriesen (via GitHub)" <gi...@apache.org>.
guydriesen commented on code in PR #39464:
URL: https://github.com/apache/airflow/pull/39464#discussion_r1593454225


##########
tests/providers/docker/operators/test_docker_swarm.py:
##########
@@ -254,3 +255,41 @@ def test_container_resources(self, types_mock, docker_api_client_patcher):
             placement=None,
         )
         types_mock.Resources.assert_not_called()
+
+    @mock.patch("airflow.providers.docker.operators.docker_swarm.types")
+    def test_service_args(self, types_mock, docker_api_client_patcher):
+        mock_obj = mock.Mock()
+
+        client_mock = mock.Mock(spec=APIClient)
+        client_mock.create_service.return_value = {"ID": "some_id"}
+        client_mock.images.return_value = []
+        client_mock.pull.return_value = [b'{"status":"pull log"}']
+        client_mock.tasks.return_value = [{"Status": {"State": "complete"}}]
+        types_mock.TaskTemplate.return_value = mock_obj
+        types_mock.ContainerSpec.return_value = mock_obj
+        types_mock.RestartPolicy.return_value = mock_obj
+        types_mock.Resources.return_value = mock_obj
+
+        docker_api_client_patcher.return_value = client_mock
+
+        operator = DockerSwarmOperator(
+            image="ubuntu:latest",
+            command="env",
+            args="--show",

Review Comment:
   Sure



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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add args to docker service ContainerSpec [airflow]

Posted by "guydriesen (via GitHub)" <gi...@apache.org>.
guydriesen commented on code in PR #39464:
URL: https://github.com/apache/airflow/pull/39464#discussion_r1592835583


##########
airflow/providers/docker/operators/docker_swarm.py:
##########
@@ -225,6 +231,24 @@ def stream_new_logs(last_line_logged, since=0):
             sleep(2)
             last_line_logged, last_timestamp = stream_new_logs(last_line_logged, since=last_timestamp)
 
+    @staticmethod
+    def format_args(args: list[str] | str | None) -> list[str] | None:
+        """Retrieve args.
+
+        The args string is parsed to a list. If it starts with ``[``,
+        the string is treated as a Python literal and parsed into a list.
+
+        :param args: args to the docker service
+
+        :return: the args as list
+        """
+        if isinstance(args, str):
+            if args.strip().startswith("["):
+                return ast.literal_eval(args)
+            else:
+                return shlex.split(args)
+        return args

Review Comment:
   The parsing is necessary because docker-py expects the args as a list (https://docker-py.readthedocs.io/en/stable/api.html#docker.types.ContainerSpec). I added the string variants as a convenient option, that was not strictly needed.



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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add args to docker service ContainerSpec [airflow]

Posted by "dirrao (via GitHub)" <gi...@apache.org>.
dirrao commented on code in PR #39464:
URL: https://github.com/apache/airflow/pull/39464#discussion_r1593293779


##########
tests/providers/docker/operators/test_docker_swarm.py:
##########
@@ -254,3 +255,41 @@ def test_container_resources(self, types_mock, docker_api_client_patcher):
             placement=None,
         )
         types_mock.Resources.assert_not_called()
+
+    @mock.patch("airflow.providers.docker.operators.docker_swarm.types")
+    def test_service_args(self, types_mock, docker_api_client_patcher):
+        mock_obj = mock.Mock()
+
+        client_mock = mock.Mock(spec=APIClient)
+        client_mock.create_service.return_value = {"ID": "some_id"}
+        client_mock.images.return_value = []
+        client_mock.pull.return_value = [b'{"status":"pull log"}']
+        client_mock.tasks.return_value = [{"Status": {"State": "complete"}}]
+        types_mock.TaskTemplate.return_value = mock_obj
+        types_mock.ContainerSpec.return_value = mock_obj
+        types_mock.RestartPolicy.return_value = mock_obj
+        types_mock.Resources.return_value = mock_obj
+
+        docker_api_client_patcher.return_value = client_mock
+
+        operator = DockerSwarmOperator(
+            image="ubuntu:latest",
+            command="env",
+            args="--show",

Review Comment:
   Can you add the test case with list as well? 



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

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org