Repository: gabrieldemarmiesse/python-on-whales (language: python)

Issue:
Specialized DockerExceptions
Hello again!

while I'm working on the integration of python on whales into my applications, I found the error management mostly thought for a human use.

Currently all errors raise a DockerException that contains the exact error output produced by the CLI. That's great when using the package by a human and provides enough information to debug the problem. But when the package is used to automate processes this approach is not very helpful and to be able to properly react, a parser of the exception is needed.

Just a practical example:

```
docker.service.inspect("my_service")
```

This command can fail for a number of reasons, for example:

the swarm is not initialized:

```
python_on_whales.utils.DockerException: The docker command executed was `/usr/local/bin/docker service inspect myservice`.
It returned with code 1
The content of stdout is '[]
'
The content of stderr is 'Status: Error response from daemon: This node is not a swarm manager. Use "docker swarm init" or "docker swarm join" to connect this node to swarm and try again., Code: 1
'
```

or the service does not exist:

```
python_on_whales.utils.DockerException: The docker command executed was `/usr/local/bin/docker service inspect myservice`.
It returned with code 1
The content of stdout is '[]
'
The content of stderr is 'Status: Error: no such service: myservice, Code: 1
'
```

Probably there are much more possible reasons, but two are enough for the example


To implement specific reactions to the different problems a parser of the exception is needed:

```
try:
    docker.service.inspect("my_service")
except python_on_whales.utils.DockerException as e:
    if "This node is not a swarm manager" is str(e):
        initialized_my_node()
    elif "no such service" in str(e):
        log.error("This service does not exist")
    else:
        log.critical("Unexpected error")
```

I think that raise specific exceptions (that would extend the parent DockerException, of course) would be very very useful for the user experience:


```
try:
    docker.service.inspect("my_service")
except python_on_whales.utils.SwarmNotInitialized:
        initialized_my_node()
except python_on_whales.utis.NoSuchService:
        log.error("This service does not exist")
except Exception:
        log.critical("Unexpected error")
```

That means, in a practical way, move the parsing directly into the package to centralized that operation and make it transparent to the final user.

I understand that is a very boring issue but I'm pretty sure that would greatly improve the adoption... and of course I'm 100% available to ease this task as much as I can


Discussion / hints:
This is indeed an issue that I noticed and i'm not very happy about the only solution possible in the short term (parsing the error message). That might be something we have to do in the short term as it's necessary to build more complicated things.

I see two other solution, more mid to long term:
1) Make the CLI output different exit codes depending on the error. We would have to ask the Docker team for that. So a change to the CLI.
2) Call the Docker engine API directly like docker-py does. It may not be practical for more complicated functions that are not available in docker-py, like docker compose or buildx functions.
Just few comments, in reversed order:

> Call the Docker engine API directly like docker-py does. It may not be practical for more complicated functions that are not available in docker-py, like docker compose or buildx functions.

Based on my understanding this approach would be out of the scope of this package that is explicitly built around the docker-cli, or I'm wrong? Of course communicating with API should be the more consistent way to interact with the daemon but it seems to be a major drift the would complicate a lot the implementation, but i agree that it IS a solution

> Make the CLI output different exit codes depending on the error. We would have to ask the Docker team for that. So a change to the CLI

A very interesting approach, but probably the slower: convincing the docker team to consider that, wait for the implementation, then work on this integration... maybe that can be considered a very long term possibility, With a valid support from docker and a little patience I think that this would be the more stable solution :)

> i'm not very happy about the only solution possible in the short term (parsing the error message). That might be something we have to do in the short term as it's necessary to build more complicated things.

No, of course it is not a very exciting solution, but seems to be the only _quick_ solution, if you think that this issue can make sense.

From my side: if you think that you are interested in this issue (in a short term perspective) I will be grateful and very available to help you, if I can. Otherwise I will implement (at least temporarily) some kind of parser into my code to be able to distinguish the different cases

Thank you



My plan is 
1) raise different exceptions for different errors quickly, so by parsing the error message. Currently, with python-on-whales, it's impossible to answer the question "does that image/container/network/volume exists?", by calling the engine api, we can do that. So we need to fix it quicky. 
I would like a function `exists()`. So that we can do `docker.container.exists("my_container_name")` or `my_container.exists()`. This function would return a bool. We should also have an exception for different objects that don't exists.

2) Ask the docker team for different error codes from the CLI. It's not only useful for python-on-whales, it may be also useful for people doing bash scripting. From a bash script, knowing if an image exists or not is only possible by parsing stderr. So not great. The CLI has some progress to do there.

I'm going to do the first step, but if you want to help and contribute, I'd be happy to review any pull request I can get :) 
I started parsing stderr to raise specific exceptions, you can follow the work here: https://github.com/gabrieldemarmiesse/python-on-whales/pull/210

As soon as you think that this preliminary work is stable I will start some tests, so that I will be able to report or directly fix with PRs eventual problems
The version is unreleased yet, but you can try it with `pip install git+https://github.com/gabrieldemarmiesse/python-on-whales.git`.

We now have a custom exception `python_on_whales.exceptions.NoSuchImage`. You can trigger it with `docker.push`, `docker.image.inspect` and `docker.save` among other. I'll continue to add exceptions.

This change should be backward compatible. Please notify me if this change breaks any existing code.
Verified:

- [x] backward compatibily
- [x] new NoSuchImage exception
- [x] new image exists function

:+1: 
See https://github.com/docker/cli/issues/1683 for the RFC about the CLI exit codes. 

It's quite possible that the docker team doesn't have enough dev to push/implement this RFC. We'll likely need to do the PRs ourselves, time to learn Go 😆 
Let's... go! :smiley: 

In the meanwhile I integrated the NoSuchService exception :+1: 

From my side the next important exception is probably that:

```
It returned with code 1
The content of stdout is ''
The content of stderr is 'Error response from daemon: This node is not a swarm manager. Use "docker swarm init" or "docker swarm join" to connect this node to swarm and try again.
'
```

raised when the swarm is not initialized

In case I will try to work on a PR next week


Fix patch:
diff --git a/python_on_whales/components/stack/cli_wrapper.py b/python_on_whales/components/stack/cli_wrapper.py
index 79edc076..64db3c96 100644
--- a/python_on_whales/components/stack/cli_wrapper.py
+++ b/python_on_whales/components/stack/cli_wrapper.py
@@ -83,7 +83,7 @@ def deploy(
         env = read_env_files([Path(x) for x in env_files])
         env.update(variables)
 
-        run(full_cmd, capture_stdout=False, capture_stderr=False, env=env)
+        run(full_cmd, capture_stdout=False, env=env)
         return Stack(self.client_config, name)
 
     def list(self) -> List[Stack]:
diff --git a/python_on_whales/exceptions.py b/python_on_whales/exceptions.py
index 7cd2d9aa..c5311c38 100644
--- a/python_on_whales/exceptions.py
+++ b/python_on_whales/exceptions.py
@@ -41,3 +41,7 @@ class NoSuchImage(DockerException):
 
 class NoSuchService(DockerException):
     pass
+
+
+class NotASwarmManager(DockerException):
+    pass
diff --git a/python_on_whales/utils.py b/python_on_whales/utils.py
index 9b65b818..ac1ce96b 100644
--- a/python_on_whales/utils.py
+++ b/python_on_whales/utils.py
@@ -13,6 +13,7 @@
     NoSuchContainer,
     NoSuchImage,
     NoSuchService,
+    NotASwarmManager,
 )
 
 PROJECT_ROOT = Path(__file__).parents[1]
@@ -121,6 +122,16 @@ def run(
                     completed_process.stdout,
                     completed_process.stderr,
                 )
+            if (
+                "this node is not a swarm manager"
+                in completed_process.stderr.decode().lower()
+            ):
+                raise NotASwarmManager(
+                    args,
+                    completed_process.returncode,
+                    completed_process.stdout,
+                    completed_process.stderr,
+                )
 
         raise DockerException(
             args,


Test patch:
diff --git a/tests/python_on_whales/components/test_service.py b/tests/python_on_whales/components/test_service.py
index 8bec2aaf..c9612835 100644
--- a/tests/python_on_whales/components/test_service.py
+++ b/tests/python_on_whales/components/test_service.py
@@ -4,7 +4,7 @@
 
 from python_on_whales import docker
 from python_on_whales.components.service.models import ServiceInspectResult
-from python_on_whales.exceptions import NoSuchService
+from python_on_whales.exceptions import NoSuchService, NotASwarmManager
 from python_on_whales.test_utils import get_all_jsons
 
 
@@ -61,3 +61,59 @@ def test_some_functions_no_such_service(docker_function):
 def test_scale_no_such_service():
     with pytest.raises(NoSuchService):
         docker.service.scale({"DOODODGOIHURHURI": 14})
+
+
+def test_create_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.service.create("busybox", ["sleep", "infinity"])
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_inspect_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.service.inspect("dodo")
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_exists_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.service.exists("dodo")
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_list_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.service.list()
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_ps_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.service.ps("dodo")
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_remove_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.service.remove("dodo")
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_scale_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.service.scale({"dodo": 8})
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_update_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.service.update("dodo", image="busybox")
+
+    assert "not a swarm manager" in str(e.value).lower()
diff --git a/tests/python_on_whales/components/test_stack.py b/tests/python_on_whales/components/test_stack.py
index 1c966a46..c109888c 100644
--- a/tests/python_on_whales/components/test_stack.py
+++ b/tests/python_on_whales/components/test_stack.py
@@ -4,6 +4,7 @@
 import pytest
 
 from python_on_whales import docker
+from python_on_whales.exceptions import NotASwarmManager
 from python_on_whales.utils import PROJECT_ROOT
 
 
@@ -77,3 +78,41 @@ def test_stack_env_files(tmp_path: Path):
     time.sleep(1)
     docker.stack.remove(third_stack)
     time.sleep(1)
+
+
+def test_deploy_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.stack.deploy(
+            "some_stack",
+            [PROJECT_ROOT / "tests/python_on_whales/components/test-stack-file.yml"],
+        )
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_ps_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.stack.ps("dodo")
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_list_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.stack.list()
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_remove_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.stack.remove("dodo")
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_services_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.stack.services("dodo")
+
+    assert "not a swarm manager" in str(e.value).lower()
diff --git a/tests/python_on_whales/components/test_swarm.py b/tests/python_on_whales/components/test_swarm.py
index 33effb53..e9e96e44 100644
--- a/tests/python_on_whales/components/test_swarm.py
+++ b/tests/python_on_whales/components/test_swarm.py
@@ -3,6 +3,7 @@
 import pytest
 
 from python_on_whales import docker
+from python_on_whales.exceptions import NotASwarmManager
 
 
 @pytest.mark.usefixtures("swarm_mode")
@@ -43,3 +44,24 @@ def test_swarm_unlock_key():
 
     # make sure it changes:
     assert first_key != docker.swarm.unlock_key(rotate=True)
+
+
+def test_swarm_join_token_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.swarm.join_token("manager")
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_update_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.swarm.update(autolock=True)
+
+    assert "not a swarm manager" in str(e.value).lower()
+
+
+def test_unlock_key_not_swarm_manager():
+    with pytest.raises(NotASwarmManager) as e:
+        docker.swarm.unlock_key()
+
+    assert "not a swarm manager" in str(e.value).lower()