Passed
Push — master ( 8abdc9...19dd16 )
by Emmanuel
05:55
created

stakkr.actions   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 267
Duplicated Lines 0 %

Test Coverage

Coverage 90.53%

Importance

Changes 0
Metric Value
eloc 179
dl 0
loc 267
ccs 153
cts 169
cp 0.9053
rs 8.72
c 0
b 0
f 0
wmc 46

16 Methods

Rating   Name   Duplication   Size   Complexity  
A StakkrActions.exec_cmd() 0 15 2
A StakkrActions.__init__() 0 15 1
A StakkrActions.console() 0 13 2
A StakkrActions.get_services_urls() 0 23 4
A StakkrActions._print_status_headers() 0 12 1
A StakkrActions._is_up() 0 15 4
A StakkrActions.get_url() 0 14 4
A StakkrActions._run_iptables_rules() 0 15 4
B StakkrActions.start() 0 27 5
A StakkrActions._get_compose_base_cmd() 0 5 2
A StakkrActions._get_relative_dir() 0 5 2
A StakkrActions.stop() 0 17 4
A StakkrActions.get_config() 0 9 2
A StakkrActions.status() 0 12 2
A StakkrActions.init_project() 0 15 2
A StakkrActions._print_status_body() 0 13 3

1 Function

Rating   Name   Duplication   Size   Complexity  
A _get_single_container_option() 0 5 2

How to fix   Complexity   

Complexity

Complex classes like stakkr.actions often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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
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
    def __init__(self, ctx: dict):
19
        """Set all require properties."""
20
        # Get info from config first to know the project name and project dir
21 1
        self.config_file = ctx['CONFIG']
22
23 1
        self.context = ctx
24
25
        # Set some general variables
26 1
        self.config = None
27 1
        self.project_name = None
28 1
        self.project_dir = None
29 1
        self.cwd_abs = os.getcwd()
30 1
        self.cwd_relative = None
31 1
        self.cts = []
32 1
        self.running_cts = []
33
34 1
    def console(self, container: str, user: str, tty: bool):
35
        """Enter a container. Stakkr will try to guess the right shell."""
36 1
        self.init_project()
37
38 1
        docker.check_cts_are_running(self.project_name)
39
40 1
        tty = 't' if tty is True else ''
41 1
        ct_name = docker.get_ct_name(container)
42 1
        cmd = ['docker', 'exec', '-u', user, '-i' + tty]
43 1
        cmd += [docker.get_ct_name(container), docker.guess_shell(ct_name)]
44
        subprocess.call(cmd)
45
46
        command.verbose(self.context['VERBOSE'], 'Command : "' + ' '.join(cmd) + '"')
47
48 1
    def get_services_urls(self):
49
        """Once started, displays a message with a list of running containers."""
50 1
        self.init_project()
51
52 1
        cts = docker.get_running_containers(self.project_name)[1]
53
54 1
        text = ''
55 1
        for _, ct_info in cts.items():
56 1
            service_config = self.config['services'][ct_info['compose_name']]
57 1
            if ({'service_name', 'service_url'} <= set(service_config)) is False:
58 1
                continue
59
60 1
            url = self.get_url(service_config['service_url'], ct_info['compose_name'])
61 1
            name = colored.yellow(service_config['service_name'])
62
63 1
            text += '  - For {}'.format(name).ljust(55, ' ') + ' : ' + url + '\n'
64
65 1
            if 'service_extra_ports' in service_config:
66 1
                ports = ', '.join(map(str, service_config['service_extra_ports']))
67 1
                text += ' '*4 + '(In your containers use the host '
68 1
                text += '"{}" and port(s) {})\n'.format(ct_info['compose_name'], ports)
69
70 1
        return text
71
72 1
    def exec_cmd(self, container: str, user: str, args: tuple, tty: bool):
73
        """Run a command from outside to any container. Wrapped into /bin/sh."""
74 1
        self.init_project()
75
76 1
        docker.check_cts_are_running(self.project_name)
77
78
        # Protect args to avoid strange behavior in exec
79 1
        args = ['"{}"'.format(arg) for arg in args]
80
81 1
        tty = 't' if tty is True else ''
82 1
        ct_name = docker.get_ct_name(container)
83 1
        cmd = ['docker', 'exec', '-u', user, '-i' + tty, ct_name, 'sh', '-c']
84 1
        cmd += ["""test -d "/var/{0}" && cd "/var/{0}" ; exec {1}""".format(self.cwd_relative, ' '.join(args))]
85 1
        command.verbose(self.context['VERBOSE'], 'Command : "' + ' '.join(cmd) + '"')
86 1
        subprocess.call(cmd, stdin=sys.stdin)
87
88 1
    def get_config(self):
89
        """Read and validate config from config file"""
90 1
        config = Config(self.config_file)
91 1
        main_config = config.read()
92 1
        if main_config is False:
93 1
            config.display_errors()
94 1
            sys.exit(1)
95
96 1
        return main_config
97
98 1
    def init_project(self):
99
        """
100
        Initializing the project by reading config and
101
        setting some properties of the object
102
        """
103 1
        if self.config is not None:
104 1
            return
105
106 1
        self.config = self.get_config()
107 1
        self.project_name = self.config['project_name']
108 1
        self.project_dir = self.config['project_dir']
109 1
        sys.path.append(self.project_dir)
110
111 1
        self.cwd_relative = self._get_relative_dir()
112 1
        os.chdir(self.project_dir)
113
114 1
    def start(self, container: str, pull: bool, recreate: bool, proxy: bool):
115
        """If not started, start the containers defined in config."""
116 1
        self.init_project()
117 1
        verb = self.context['VERBOSE']
118 1
        debug = self.context['DEBUG']
119
120 1
        self._is_up(container)
121
122 1
        if pull is True:
123
            command.launch_cmd_displays_output(self._get_compose_base_cmd() + ['pull'], verb, debug, True)
124
125 1
        recreate_param = '--force-recreate' if recreate is True else '--no-recreate'
126 1
        cmd = self._get_compose_base_cmd() + ['up', '-d', recreate_param, '--remove-orphans']
127 1
        cmd += _get_single_container_option(container)
128
129 1
        command.verbose(self.context['VERBOSE'], 'Command: ' + ' '.join(cmd))
130 1
        command.launch_cmd_displays_output(cmd, verb, debug, True)
131
132 1
        self.running_cts, self.cts = docker.get_running_containers(self.project_name)
133 1
        if not self.running_cts:
134
            raise SystemError("Couldn't start the containers, run the start with '-v' and '-d'")
135
136 1
        self._run_iptables_rules()
137 1
        if proxy is True:
138 1
            network_name = docker.get_network_name(self.project_name)
139 1
            conf = self.config['proxy']
140 1
            Proxy(conf.get('http_port'), conf.get('https_port')).start(network_name)
141
142 1
    def status(self):
143
        """Return a nice table with the list of started containers."""
144 1
        self.init_project()
145
146 1
        try:
147 1
            docker.check_cts_are_running(self.project_name)
148 1
        except SystemError:
149 1
            puts(colored.yellow('[INFO]') + ' stakkr is currently stopped')
150 1
            sys.exit(0)
151
152 1
        self._print_status_headers()
153 1
        self._print_status_body()
154
155 1
    def stop(self, container: str, proxy: bool):
156
        """If started, stop the containers defined in config. Else throw an error."""
157 1
        self.init_project()
158 1
        verb = self.context['VERBOSE']
159 1
        debug = self.context['DEBUG']
160
161 1
        docker.check_cts_are_running(self.project_name)
162
163 1
        cmd = self._get_compose_base_cmd() + ['stop'] + _get_single_container_option(container)
164 1
        command.launch_cmd_displays_output(cmd, verb, debug, True)
165
166 1
        self.running_cts, self.cts = docker.get_running_containers(self.project_name)
167 1
        if self.running_cts and container is None:
168
            raise SystemError("Couldn't stop services ...")
169
170 1
        if proxy is True:
171 1
            Proxy().stop()
172
173 1
    def _get_compose_base_cmd(self):
174 1
        if self.context['CONFIG'] is None:
175
            return ['stakkr-compose']
176
177 1
        return ['stakkr-compose', '-c', self.context['CONFIG']]
178
179 1
    def _get_relative_dir(self):
180 1
        if self.cwd_abs.startswith(self.project_dir):
181
            return self.cwd_abs[len(self.project_dir):].lstrip('/')
182
183 1
        return ''
184
185 1
    def _is_up(self, container: str):
186 1
        try:
187 1
            docker.check_cts_are_running(self.project_name)
188 1
        except SystemError:
189 1
            return
190
191 1
        if container is None:
192 1
            puts(colored.yellow('[INFO]') + ' stakkr is already started ...')
193 1
            sys.exit(0)
194
195
        # If single container : check if that specific one is running
196 1
        ct_name = docker.get_ct_item(container, 'name')
197 1
        if docker.container_running(ct_name):
198 1
            puts(colored.yellow('[INFO]') + ' service {} is already started ...'.format(container))
199 1
            sys.exit(0)
200
201 1
    def _print_status_headers(self):
202
        """Display messages for stakkr status (header)"""
203 1
        puts(columns(
204
            [(colored.green('Container')), 16], [colored.green('IP'), 15],
205
            [(colored.green('Url')), 32], [(colored.green('Image')), 32],
206
            [(colored.green('Docker ID')), 15], [(colored.green('Docker Name')), 25]
207
            ))
208
209 1
        puts(columns(
210
            ['-'*16, 16], ['-'*15, 15],
211
            ['-'*32, 32], ['-'*32, 32],
212
            ['-'*15, 15], ['-'*25, 25]
213
            ))
214
215 1
    def _print_status_body(self):
216
        """Display messages for stakkr status (body)"""
217 1
        self.running_cts, self.cts = docker.get_running_containers(self.project_name)
218
219 1
        for container in sorted(self.cts.keys()):
220 1
            ct_data = self.cts[container]
221 1
            if ct_data['ip'] == '':
222
                continue
223
224 1
            puts(columns(
225
                [ct_data['compose_name'], 16], [ct_data['ip'], 15],
226
                [ct_data['traefik_host'], 32], [ct_data['image'], 32],
227
                [ct_data['id'][:12], 15], [ct_data['name'], 25]
228
                ))
229
230 1
    def _run_iptables_rules(self):
231
        """For some containers we need to add iptables rules added from the config."""
232 1
        for _, ct_info in self.cts.items():
233 1
            container = ct_info['compose_name']
234 1
            ct_config = self.config['services'][container]
235 1
            if 'blocked_ports' not in ct_config:
236 1
                continue
237
238
            blocked_ports = ct_config['blocked_ports']
239
            error, msg = docker.block_ct_ports(container, blocked_ports, self.project_name)
240
            if error is True:
241
                click.secho(msg, fg='red')
242
                continue
243
244
            command.verbose(self.context['VERBOSE'], msg)
245
246 1
    def get_url(self, service_url: str, service: str):
247
        """Build URL to be displayed."""
248 1
        proxy_conf = self.config['proxy']
249
        # By default our URL is the IP
250 1
        url = docker.get_ct_item(service, 'ip')
251
        # If proxy enabled, display nice urls
252 1
        if bool(proxy_conf['enabled']):
253 1
            http_port = int(proxy_conf['http_port'])
254 1
            url = docker.get_ct_item(service, 'traefik_host')
255 1
            url += '' if http_port == 80 else ':{}'.format(http_port)
256
        elif os_name() in ['Windows', 'Darwin']:
257
            puts(colored.yellow('[WARNING]') + ' Under Win and Mac, you need the proxy enabled')
258
259 1
        return service_url.format(url)
260
261
262 1
def _get_single_container_option(container: str):
263 1
    if container is None:
264 1
        return []
265
266
    return [container]
267