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.

Fix patch:
diff --git a/python_on_whales/components/service/cli_wrapper.py b/python_on_whales/components/service/cli_wrapper.py
index cf02266d..3d2f7feb 100644
--- a/python_on_whales/components/service/cli_wrapper.py
+++ b/python_on_whales/components/service/cli_wrapper.py
@@ -17,6 +17,7 @@
     ServiceUpdateStatus,
     ServiceVersion,
 )
+from python_on_whales.exceptions import NoSuchService
 from python_on_whales.utils import ValidPath, format_dict_for_cli, run, to_list
 
 
@@ -126,7 +127,7 @@ def exists(self) -> bool:
         """Returns `True` if the service is still present in the swarm, `False`
         if the service has been removed.
         """
-        return self in ServiceCLI(self.client_config).list()
+        return ServiceCLI(self.client_config).exists(self.id)
 
 
 ValidService = Union[str, Service]
@@ -233,12 +234,33 @@ def inspect(self, x: List[str]) -> List[Service]:
         ...
 
     def inspect(self, x: Union[str, List[str]]) -> Union[Service, List[Service]]:
-        """Returns one or a list of `python_on_whales.Service` object(s)."""
+        """Returns one or a list of `python_on_whales.Service` object(s).
+
+        # Raises
+            `python_on_whales.exceptions.NoSuchService` if one of the services
+            doesn't exists.
+        """
         if isinstance(x, str):
             return Service(self.client_config, x)
         else:
             return [Service(self.client_config, a) for a in x]
 
+    def exists(self, x: str) -> bool:
+        """Verify that a service exists.
+
+         It's just calling `docker.service.inspect(...)` and verifies that it doesn't throw
+         a `python_on_whales.exceptions.NoSuchService`.
+
+        # Returns
+            A `bool`
+        """
+        try:
+            self.inspect(x)
+        except NoSuchService:
+            return False
+        else:
+            return True
+
     def logs(self):
         """Not yet implemented"""
         raise NotImplementedError
@@ -275,6 +297,10 @@ def ps(
 
         # Returns
             `List[python_on_whales.Task]`
+
+        # Raises
+            `python_on_whales.exceptions.NoSuchService` if one of the services
+            doesn't exists.
         """
         full_cmd = (
             self.docker_cmd + ["service", "ps", "--quiet", "--no-trunc"] + to_list(x)
@@ -292,6 +318,10 @@ def remove(self, services: Union[ValidService, List[ValidService]]) -> None:
 
         # Arguments
             services: One or a list of services to remove.
+
+        # Raises
+            `python_on_whales.exceptions.NoSuchService` if one of the services
+            doesn't exists.
         """
         full_cmd = self.docker_cmd + ["service", "remove"]
 
@@ -312,7 +342,14 @@ def scale(self, new_scales: Dict[ValidService, int], detach: bool = False) -> No
                 you can provide `new_scale={"service1": 4, "service2": 8}`
             detach: If True, does not wait for the services to converge and return
                 immediately.
+
+        # Raises
+            `python_on_whales.exceptions.NoSuchService` if one of the services
+            doesn't exists.
+
         """
+        # verify that the services exists
+        self.inspect(list(new_scales.keys()))
 
         full_cmd = self.docker_cmd + ["service", "scale"]
         full_cmd.add_flag("--detach", detach)
@@ -339,6 +376,9 @@ def update(
             image: Service image tag
             with_registry_authentication: Send registry authentication details
                 to swarm agents
+
+        # Raises
+            `python_on_whales.exceptions.NoSuchService` if the service doesn't exists.
         """
         full_cmd = self.docker_cmd + ["service", "update"]
         full_cmd.add_flag("--force", force)
diff --git a/python_on_whales/exceptions.py b/python_on_whales/exceptions.py
index 22ff9f58..6e1d9737 100644
--- a/python_on_whales/exceptions.py
+++ b/python_on_whales/exceptions.py
@@ -33,3 +33,7 @@ def __init__(
 
 class NoSuchImage(DockerException):
     pass
+
+
+class NoSuchService(DockerException):
+    pass
diff --git a/python_on_whales/utils.py b/python_on_whales/utils.py
index 1d77f9e2..a8096896 100644
--- a/python_on_whales/utils.py
+++ b/python_on_whales/utils.py
@@ -8,7 +8,7 @@
 
 import pydantic
 
-from python_on_whales.exceptions import DockerException, NoSuchImage
+from python_on_whales.exceptions import DockerException, NoSuchImage, NoSuchService
 
 PROJECT_ROOT = Path(__file__).parents[1]
 
@@ -95,13 +95,20 @@ def run(
 
     if completed_process.returncode != 0:
         if completed_process.stderr is not None:
-            if "No such image" in completed_process.stderr.decode():
+            if "no such image" in completed_process.stderr.decode().lower():
                 raise NoSuchImage(
                     args,
                     completed_process.returncode,
                     completed_process.stdout,
                     completed_process.stderr,
                 )
+            if "no such service" in completed_process.stderr.decode().lower():
+                raise NoSuchService(
+                    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 a5d68020..8bec2aaf 100644
--- a/tests/python_on_whales/components/test_service.py
+++ b/tests/python_on_whales/components/test_service.py
@@ -4,6 +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.test_utils import get_all_jsons
 
 
@@ -44,3 +45,19 @@ def test_context_manager():
             raise RuntimeError
 
     assert not my_service.exists()
+
+
+@pytest.mark.parametrize(
+    "docker_function",
+    [docker.service.inspect, docker.service.remove, docker.service.ps],
+)
+@pytest.mark.usefixtures("swarm_mode")
+def test_some_functions_no_such_service(docker_function):
+    with pytest.raises(NoSuchService):
+        docker_function("DOODODGOIHURHURI")
+
+
+@pytest.mark.usefixtures("swarm_mode")
+def test_scale_no_such_service():
+    with pytest.raises(NoSuchService):
+        docker.service.scale({"DOODODGOIHURHURI": 14})