1- import logging
21from typing import Annotated
32
4- from aiodocker .networks import DockerNetwork
53from fastapi import APIRouter , Depends , FastAPI
64from fastapi import Path as PathParam
75from fastapi import Request , Response , status
86from models_library .services import ServiceOutput
97from pydantic .main import BaseModel
108
11- from ...core .docker_utils import docker_client
129from ...services import container_extensions
1310from ._dependencies import get_application
1411
15- _logger = logging .getLogger (__name__ )
16-
1712
1813class CreateDirsRequestItem (BaseModel ):
1914 outputs_labels : dict [str , ServiceOutput ]
@@ -91,33 +86,11 @@ async def attach_container_to_network(
9186 container_id : Annotated [str , PathParam (..., alias = "id" )],
9287) -> None :
9388 assert request # nosec
94-
95- async with docker_client () as docker :
96- container_instance = await docker .containers .get (container_id )
97- container_inspect = await container_instance .show ()
98-
99- attached_network_ids : set [str ] = {
100- x ["NetworkID" ]
101- for x in container_inspect ["NetworkSettings" ]["Networks" ].values ()
102- }
103-
104- if item .network_id in attached_network_ids :
105- _logger .debug (
106- "Container %s already attached to network %s" ,
107- container_id ,
108- item .network_id ,
109- )
110- return
111-
112- # NOTE: A docker network is only visible on a docker node when it is
113- # used by a container
114- network = DockerNetwork (docker = docker , id_ = item .network_id )
115- await network .connect (
116- {
117- "Container" : container_id ,
118- "EndpointConfig" : {"Aliases" : item .network_aliases },
119- }
120- )
89+ await container_extensions .attach_container_to_network (
90+ container_id = container_id ,
91+ network_id = item .network_id ,
92+ network_aliases = item .network_aliases ,
93+ )
12194
12295
12396@router .post (
@@ -130,23 +103,7 @@ async def detach_container_from_network(
130103 item : DetachContainerFromNetworkItem ,
131104 container_id : Annotated [str , PathParam (..., alias = "id" )],
132105) -> None :
133- async with docker_client () as docker :
134- container_instance = await docker .containers .get (container_id )
135- container_inspect = await container_instance .show ()
136-
137- attached_network_ids : set [str ] = set (
138- container_inspect ["NetworkSettings" ]["Networks" ].keys ()
139- )
140-
141- if item .network_id not in attached_network_ids :
142- _logger .debug (
143- "Container %s already detached from network %s" ,
144- container_id ,
145- item .network_id ,
146- )
147- return
148-
149- # NOTE: A docker network is only visible on a docker node when it is
150- # used by a container
151- network = DockerNetwork (docker = docker , id_ = item .network_id )
152- await network .disconnect ({"Container" : container_id , "Force" : True })
106+ await container_extensions .detach_container_from_network (
107+ container_id = container_id ,
108+ network_id = item .network_id ,
109+ )
0 commit comments