Test Failed
Push — master ( 21c149...b9e3b5 )
by Emmanuel
06:16
created

actions.StakkrActions._print_status_body()   A

Complexity

Conditions 3

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 10
nop 1
dl 0
loc 12
ccs 5
cts 5
cp 1
crap 3
rs 9.9
c 0
b 0
f 0
1
# coding: utf-8
2 1
"""Stakkr main controller. Used by the CLI to do all its actions."""
3
4 1
import os
5 1
from platform import system as os_name
6 1
import subprocess
7 1
import sys
8 1
import click
9 1
from clint.textui import colored, puts, columns
10 1
from stakkr import command, docker_actions as docker, package_utils
11 1
from stakkr.configreader import Config
12 1
from stakkr.proxy import Proxy
13
14
15 1
class StakkrActions:
16
    """Main class that does actions asked in the cli."""
17
18 1
    _services_to_display = {
19
        'adminer': {'name': 'Adminer', 'url': 'http://{}'},
20
        'apache': {'name': 'Web Server', 'url': 'http://{}'},
21
        'elasticsearch': {'name': 'ElasticSearch', 'url': 'http://{}'},
22
        'kibana': {'name': 'Kibana', 'url': 'http://{}'},
23
        'logstash': {'name': 'Logstash', 'url': 'http://{}'},
24
        'mailcatcher': {'name': 'Mailcatcher (fake SMTP)', 'url': 'http://{}', 'extra_port': 25},
25
        'maildev': {'name': 'Maildev (Fake SMTP)', 'url': 'http://{}', 'extra_port': 25},
26
        'nginx': {'name': 'Web Server', 'url': 'http://{}'},
27
        'phpmyadmin': {'name': 'PhpMyAdmin', 'url': 'http://{}'},
28
        'portainer': {'name': 'Portainer (Docker GUI)', 'url': 'http://{}'},
29
        'xhgui': {'name': 'XHGui (PHP Profiling)', 'url': 'http://{}'}
30
    }
31
32 1
    def __init__(self, base_dir: str, ctx: dict):
33
        """Set all require properties."""
34
        # Work with directories and move to the right place
35 1
        self.stakkr_base_dir = base_dir
36 1
        self.context = ctx
37 1
        self.cwd_abs = os.getcwd()
38 1
        self.cwd_relative = self._get_relative_dir()
39 1
        os.chdir(self.stakkr_base_dir)
40
41
        # Set some general variables
42 1
        self.config_file = ctx['CONFIG']
43 1
        self.compose_base_cmd = self._get_compose_base_cmd()
44 1
        self.cts = []
45 1
        self.running_cts = []
46
47
        # Get info from config
48 1
        self.config = self._get_config()
49 1
        self.main_config = self.config['main']
50 1
        self.project_name = self.main_config.get('project_name')
51
52 1
    def console(self, container: str, user: str, tty: bool):
53
        """Enter a container. Stakkr will try to guess the right shell."""
54 1
        docker.check_cts_are_running(self.project_name)
55
56 1
        tty = 't' if tty is True else ''
57 1
        ct_name = docker.get_ct_name(container)
58 1
        cmd = ['docker', 'exec', '-u', user, '-i' + tty]
59 1
        cmd += [docker.get_ct_name(container), docker.guess_shell(ct_name)]
60
        subprocess.call(cmd)
61
62
        command.verbose(self.context['VERBOSE'], 'Command : "' + ' '.join(cmd) + '"')
63
64 1
    def get_services_urls(self):
65
        """Once started, displays a message with a list of running containers."""
66 1
        cts = docker.get_running_containers(self.project_name)[1]
67
68 1
        text = ''
69 1
        for ct_id, ct_info in cts.items():
70 1
            if ct_info['compose_name'] not in self._services_to_display:
71 1
                continue
72
73 1
            options = self._services_to_display[ct_info['compose_name']]
74 1
            url = self.get_url(options['url'], ct_info['compose_name'])
75 1
            name = colored.yellow(options['name'])
76 1
            text += '  - For {}'.format(name).ljust(55, ' ') + ' : ' + url + '\n'
77
78 1
            if 'extra_port' in options:
79 1
                port = str(options['extra_port'])
80 1
                text += ' '*4 + '(In your containers use the host '
81 1
                text += '"{}" and port {})\n'.format(ct_info['compose_name'], port)
82
83 1
        return text
84
85 1
    def exec_cmd(self, container: str, user: str, args: tuple, tty: bool):
86
        """Run a command from outside to any container. Wrapped into /bin/sh."""
87 1
        docker.check_cts_are_running(self.project_name)
88
89
        # Protect args to avoid strange behavior in exec
90 1
        args = ['"{}"'.format(arg) for arg in args]
91
92 1
        tty = 't' if tty is True else ''
93 1
        ct_name = docker.get_ct_name(container)
94 1
        cmd = ['docker', 'exec', '-u', user, '-i' + tty, ct_name, 'sh', '-c']
95 1
        cmd += ["""test -d "/var/{0}" && cd "/var/{0}" ; exec {1}""".format(self.cwd_relative, ' '.join(args))]
96 1
        command.verbose(self.context['VERBOSE'], 'Command : "' + ' '.join(cmd) + '"')
97 1
        subprocess.call(cmd, stdin=sys.stdin)
98
99 1
    def start(self, container: str, pull: bool, recreate: bool, proxy: bool):
100
        """If not started, start the containers defined in config."""
101 1
        verb = self.context['VERBOSE']
102 1
        debug = self.context['DEBUG']
103
104 1
        self._is_containers_running(container)
105
106 1
        if pull is True:
107
            command.launch_cmd_displays_output(self.compose_base_cmd + ['pull'], verb, debug, True)
108
109 1
        recreate_param = '--force-recreate' if recreate is True else '--no-recreate'
110 1
        cmd = self.compose_base_cmd + ['up', '-d', recreate_param, '--remove-orphans']
111 1
        cmd += _get_single_container_option(container)
112
113 1
        command.verbose(self.context['VERBOSE'], 'Command: ' + ' '.join(cmd))
114 1
        command.launch_cmd_displays_output(cmd, verb, debug, True)
115
116 1
        self.running_cts, self.cts = docker.get_running_containers(self.project_name)
117 1
        if self.running_cts is 0:
118
            raise SystemError("Couldn't start the containers, run the start with '-v' and '-d'")
119
120 1
        self._run_iptables_rules()
121 1
        self._run_services_post_scripts()
122 1
        if proxy is True:
123 1
            network_name = docker.get_network_name(self.project_name)
124 1
            Proxy(self.config['proxy'].get('port')).start(network_name)
125
126 1
    def status(self):
127
        """Return a nice table with the list of started containers."""
128 1
        try:
129 1
            docker.check_cts_are_running(self.project_name)
130 1
        except SystemError:
131 1
            puts(colored.yellow('[INFO]') + ' stakkr is currently stopped')
132 1
            sys.exit(0)
133
134 1
        self._print_status_headers()
135 1
        self._print_status_body()
136
137 1
    def stop(self, container: str, proxy: bool):
138
        """If started, stop the containers defined in config. Else throw an error."""
139 1
        verb = self.context['VERBOSE']
140 1
        debug = self.context['DEBUG']
141
142 1
        docker.check_cts_are_running(self.project_name)
143
144 1
        cmd = self.compose_base_cmd + ['stop'] + _get_single_container_option(container)
145 1
        command.launch_cmd_displays_output(cmd, verb, debug, True)
146
147 1
        self.running_cts, self.cts = docker.get_running_containers(self.project_name)
148 1
        if self.running_cts is not 0 and container is None:
149
            raise SystemError("Couldn't stop services ...")
150
151 1
        if proxy is True:
152 1
            Proxy(self.config['proxy'].get('port')).stop()
153 1
154
    def _call_service_post_script(self, service: str):
155 1
        service_script = package_utils.get_file('static', 'services/{}.sh'.format(service))
156 1
        if os.path.isfile(service_script) is True:
157 1
            cmd = ['bash', service_script, docker.get_ct_item(service, 'name')]
158
            subprocess.call(cmd)
159
            command.verbose(self.context['VERBOSE'], 'Service Script : ' + ' '.join(cmd))
160
161
    def _get_compose_base_cmd(self):
162 1
        if self.context['CONFIG'] is None:
163 1
            return ['stakkr-compose']
164 1
165
        return ['stakkr-compose', '-c', self.context['CONFIG']]
166 1
167
    def _get_config(self):
168 1
        config = Config(self.config_file)
169 1
        main_config = config.read()
170 1
        if main_config is False:
171 1
            config.display_errors()
172 1
            sys.exit(1)
173 1
174
        return main_config
175 1
176
    def _get_relative_dir(self):
177 1
        if self.cwd_abs.startswith(self.stakkr_base_dir):
178 1
            return self.cwd_abs[len(self.stakkr_base_dir):].lstrip('/')
179 1
180
        return ''
181 1
182
    def _is_containers_running(self, container: str):
183 1
184 1
        try:
185 1
            docker.check_cts_are_running(self.project_name)
186
        except SystemError:
187
            return
188
189 1
        if container is None:
190
            puts(colored.yellow('[INFO]') + ' stakkr is already started ...')
191 1
            sys.exit(0)
192 1
193 1
        # If single container : check if that specific one is running
194 1
        ct_name = docker.get_ct_item(container, 'name')
195
        if docker.container_running(ct_name):
196 1
            puts(colored.yellow('[INFO]') + ' service {} is already started ...'.format(container))
197 1
            sys.exit(0)
198 1
199
    def _print_status_headers(self):
200
        puts(columns(
201 1
            [(colored.green('Container')), 16], [colored.green('IP'), 15],
202 1
            [(colored.green('Url')), 32], [(colored.green('Image')), 32],
203 1
            [(colored.green('Docker ID')), 15], [(colored.green('Docker Name')), 25]
204 1
            ))
205
206 1
        puts(columns(
207 1
            ['-'*16, 16], ['-'*15, 15],
208
            ['-'*32, 32], ['-'*32, 32],
209
            ['-'*15, 15], ['-'*25, 25]
210
            ))
211
212
    def _print_status_body(self):
213 1
        self.running_cts, self.cts = docker.get_running_containers(self.project_name)
214
215
        for container in sorted(self.cts.keys()):
216
            ct_data = self.cts[container]
217
            if ct_data['ip'] == '':
218
                continue
219 1
220 1
            puts(columns(
221
                [ct_data['compose_name'], 16], [ct_data['ip'], 15],
222 1
                [ct_data['traefik_host'], 32], [ct_data['image'], 32],
223 1
                [ct_data['id'][:12], 15], [ct_data['name'], 25]
224 1
                ))
225
226
    def _run_iptables_rules(self):
227 1
        """For some containers we need to add iptables rules added from the config."""
228
        block_config = self.config['network-block']
229
        for service, ports in block_config.items():
230
            error, msg = docker.block_ct_ports(service, ports, self.project_name)
231
            if error is True:
232
                click.secho(msg, fg='red')
233 1
                continue
234
235 1
            command.verbose(self.context['VERBOSE'], msg)
236 1
237 1
    def _run_services_post_scripts(self):
238 1
        """
239
        Run services post scripts.
240
241
        A service can have a .sh file that will be executed once it's started.
242 1
        Useful to override some actions of the classical /run.sh.
243
        """
244 1
        if os.name == 'nt':
245
            click.secho('Could not run service post scripts under Windows', fg='red')
246
            return
247
248
        for service in self.main_config.get('services'):
249
            self._call_service_post_script(service)
250
251 1
    def get_url(self, service_url: str, service: str):
252
        """Build URL to be displayed."""
253
        proxy_conf = self.config['proxy']
254
        # By default our URL is the IP
255 1
        url = docker.get_ct_item(service, 'ip')
256 1
        # If proxy enabled, display nice urls
257
        if int(proxy_conf['enabled']) is 1:
258 1
            url = docker.get_ct_item(service, 'traefik_host')
259
            url += '' if int(proxy_conf['port']) is 80 else ':{}'.format(proxy_conf['port'])
260 1
        elif os_name() in ['Windows', 'Darwin']:
261
            puts(colored.yellow('[WARNING]') + ' Under Win and Mac, you need the proxy enabled')
262 1
263
        return service_url.format(url)
264 1
265 1
266 1
def _get_single_container_option(container: str):
267
    if container is None:
268
        return []
269
270
    return [container]
271