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