|
1 | 1 | import logging
|
2 |
| -from typing import TYPE_CHECKING |
| 2 | +from typing import TYPE_CHECKING, List, Optional |
3 | 3 |
|
4 | 4 |
|
5 | 5 | from gefyra.configuration import ClientConfiguration
|
|
12 | 12 | logger = logging.getLogger(__name__)
|
13 | 13 |
|
14 | 14 |
|
15 |
| -def get_or_create_gefyra_network(config: ClientConfiguration) -> "Network": |
16 |
| - gefyra_network = handle_create_network(config) |
| 15 | +def get_or_create_gefyra_network( |
| 16 | + config: ClientConfiguration, occupied_networks: Optional[List[str]] = None |
| 17 | +) -> "Network": |
| 18 | + if not occupied_networks: |
| 19 | + occupied_networks = [] |
| 20 | + gefyra_network = handle_create_network(config, occupied_networks) |
17 | 21 | logger.debug(f"Network {gefyra_network.attrs}")
|
18 | 22 | return gefyra_network
|
19 | 23 |
|
20 | 24 |
|
21 |
| -def handle_create_network(config: ClientConfiguration) -> "Network": |
| 25 | +def _get_subnet( |
| 26 | + config: ClientConfiguration, network_name: str, occupied_networks: List[str] |
| 27 | +) -> str: |
| 28 | + tries = 255 |
| 29 | + networks: List[Network] = [] |
| 30 | + subnet = "" |
| 31 | + # this is a workaround to select a free subnet (instead of finding it with python code) |
| 32 | + for i in range(tries): |
| 33 | + temp_network = config.DOCKER.networks.create( |
| 34 | + f"{network_name}-{i}", driver="bridge" |
| 35 | + ) |
| 36 | + networks.append(temp_network) |
| 37 | + subnet = temp_network.attrs["IPAM"]["Config"][0]["Subnet"] |
| 38 | + if subnet not in occupied_networks: |
| 39 | + break |
| 40 | + for network in networks: |
| 41 | + network.remove() |
| 42 | + if not subnet: |
| 43 | + raise RuntimeError("Could not find a free subnet") |
| 44 | + return subnet |
| 45 | + |
| 46 | + |
| 47 | +def handle_create_network( |
| 48 | + config: ClientConfiguration, occupied_networks: List[str] |
| 49 | +) -> "Network": |
22 | 50 | from docker.errors import NotFound
|
23 | 51 | from docker.types import IPAMConfig, IPAMPool
|
24 | 52 |
|
@@ -56,10 +84,10 @@ def handle_create_network(config: ClientConfiguration) -> "Network":
|
56 | 84 | except NotFound:
|
57 | 85 | pass
|
58 | 86 |
|
59 |
| - # this is a workaround to select a free subnet (instead of finding it with python code) |
60 |
| - temp_network = config.DOCKER.networks.create(network_name, driver="bridge") |
61 |
| - subnet = temp_network.attrs["IPAM"]["Config"][0]["Subnet"] |
62 |
| - temp_network.remove() # remove the temp network again |
| 87 | + subnet = _get_subnet( |
| 88 | + config=config, network_name=network_name, occupied_networks=occupied_networks |
| 89 | + ) |
| 90 | + logger.debug(f"Using subnet: {subnet}") |
63 | 91 |
|
64 | 92 | ipam_pool = IPAMPool(subnet=f"{subnet}", aux_addresses={})
|
65 | 93 | ipam_config = IPAMConfig(pool_configs=[ipam_pool])
|
|
0 commit comments