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