|
1
|
|
|
""" |
|
2
|
|
|
Manage public proxy to expose containers |
|
3
|
|
|
""" |
|
4
|
|
|
|
|
5
|
1 |
|
import os |
|
6
|
1 |
|
import click |
|
7
|
1 |
|
from docker.errors import DockerException |
|
8
|
1 |
|
from stakkr import docker_actions |
|
9
|
1 |
|
from stakkr.configreader import Config |
|
10
|
|
|
|
|
11
|
|
|
|
|
12
|
1 |
|
class Proxy(): |
|
13
|
|
|
"""Main class that does actions asked in the cli""" |
|
14
|
|
|
|
|
15
|
1 |
|
def __init__(self, port: int = 80, proxy_name: str = 'proxy_stakkr'): |
|
16
|
|
|
"""Set the right values to start the proxy""" |
|
17
|
|
|
|
|
18
|
1 |
|
self.port = port |
|
19
|
1 |
|
self.proxy_name = proxy_name |
|
20
|
1 |
|
self.docker_client = docker_actions.get_client() |
|
21
|
|
|
|
|
22
|
1 |
|
def start(self, stakkr_network: str = None): |
|
23
|
|
|
"""Start stakkr proxy if stopped""" |
|
24
|
|
|
|
|
25
|
1 |
|
if docker_actions.container_running(self.proxy_name) is False: |
|
26
|
1 |
|
print(click.style('[STARTING]', fg='green') + ' traefik') |
|
27
|
1 |
|
self._start_container() |
|
28
|
|
|
|
|
29
|
|
|
# Connect it to network if asked |
|
30
|
1 |
|
if stakkr_network is not None: |
|
31
|
|
|
docker_actions.add_container_to_network(self.proxy_name, stakkr_network) |
|
32
|
|
|
|
|
33
|
|
|
|
|
34
|
1 |
|
def stop(self): |
|
35
|
|
|
"""Stop stakkr proxy""" |
|
36
|
|
|
|
|
37
|
1 |
|
if docker_actions.container_running(self.proxy_name) is False: |
|
38
|
1 |
|
return |
|
39
|
|
|
|
|
40
|
1 |
|
print(click.style('[STOPPING]', fg='green') + ' traefik') |
|
41
|
1 |
|
proxy_ct = self.docker_client.containers.get(self.proxy_name) |
|
42
|
1 |
|
proxy_ct.stop() |
|
43
|
|
|
|
|
44
|
|
|
|
|
45
|
1 |
|
def _start_container(self): |
|
46
|
|
|
"""Start The container""" |
|
47
|
1 |
|
try: |
|
48
|
1 |
|
self.docker_client.images.pull('traefik:latest') |
|
49
|
1 |
|
self.docker_client.containers.run( |
|
50
|
|
|
'traefik:latest', remove=True, detach=True, |
|
51
|
|
|
hostname=self.proxy_name, name=self.proxy_name, |
|
52
|
|
|
volumes=['/var/run/docker.sock:/var/run/docker.sock'], |
|
53
|
|
|
ports={80: self.port, 8080: 8080}, command='--api --docker') |
|
54
|
|
|
except DockerException as error: |
|
55
|
|
|
raise RuntimeError("Can't start proxy ...({})".format(error)) |
|
56
|
|
|
|