summaryrefslogtreecommitdiff
path: root/src/leap/bitmask/cli/command.py
blob: 77d2bdfcb4a317cfa06595161f5668d8a41a2cec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# -*- coding: utf-8 -*-
# sender
# Copyright (C) 2016 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Bitmask Command Line interface: zmq sender.
"""
import argparse
import json
import sys

from colorama import init as color_init
from colorama import Fore
from twisted.internet import defer
from txzmq import ZmqEndpoint, ZmqEndpointType
from txzmq import ZmqFactory, ZmqREQConnection
from txzmq import ZmqRequestTimeoutError

from leap.bitmask.core import ENDPOINT


appname = 'bitmaskctl'


def _print_result(result):
    print Fore.GREEN + '%s' % result + Fore.RESET


def default_dict_printer(result):
    if not result:
        return
    for key, value in result.items():
        if value is not str:
            value = str(value)
        if value in ('OFF', 'OFFLINE', 'ABORTED', 'False'):
            color = Fore.RED
        else:
            color = Fore.GREEN
        print(Fore.RESET + key.ljust(10) + color + value + Fore.RESET)


def print_status(status, depth=0):

    if status.get('vpn') == 'disabled':
        print('vpn       ' + Fore.RED + 'disabled' + Fore.RESET)
        return

    for name, v in [('status', status)] + status['childrenStatus'].items():
        line = Fore.RESET + name.ljust(12)
        if v['status'] in ('on', 'starting'):
            line += Fore.GREEN
        elif v['status'] == 'failure':
            line += Fore.RED
        line += v['status']
        if v['error']:
            line += Fore.RED + " (%s)" % v['error']
        line += Fore.RESET
        print(line)

    for k, v in status.items():
        if k in ('status', 'childrenStatus', 'error'):
            continue
        if k == 'up':
            k = '↑↑↑         '
        elif k == 'down':
            k = '↓↓↓         '
        print(Fore.RESET + k.ljust(12) + Fore.CYAN + str(v) + Fore.RESET)


class Command(object):
    """A generic command dispatcher.
    Any command in the class attribute `commands` will be dispached and
    represented with a generic printer."""
    service = ''
    usage = '''{name} <subcommand>'''.format(name=appname)
    epilog = ("Use bitmaskctl <subcommand> --help' to learn more "
              "about each command.")
    commands = []

    def __init__(self, cfg, print_json=False):
        self.cfg = cfg

        color_init()
        zf = ZmqFactory()
        e = ZmqEndpoint(ZmqEndpointType.connect, ENDPOINT)
        self._conn = ZmqREQConnection(zf, e)

        self.data = []
        if self.service:
            self.data = [self.service]
        self.print_json = print_json

    def execute(self, raw_args):
        self.parser = argparse.ArgumentParser(usage=self.usage,
                                              epilog=self.epilog)
        self.parser.add_argument('command', help='Subcommand to run')
        try:
            args = self.parser.parse_args(raw_args[0:1])
        except SystemExit:
            return defer.succeed(None)

        # if command is in the default list, send the bare command
        # and use the default printer
        if args.command in self.commands:
            self.data += [args.command] + raw_args[1:]
            return self._send(printer=default_dict_printer)

        elif (args.command == 'execute' or
                args.command.startswith('_') or
                not hasattr(self, args.command)):
            print 'Unrecognized command'
            return self.help([])

        try:
            # use dispatch pattern to invoke method with same name
            return getattr(self, args.command)(raw_args[1:])
        except SystemExit:
            return defer.succeed(None)

    def help(self, raw_args):
        self.parser.print_help()
        return defer.succeed(None)

    def _send(self, printer=_print_result, timeout=60, errb=None):
        d = self._conn.sendMsg(*self.data, timeout=timeout)
        d.addCallback(self._check_err, printer)
        d.addErrback(self._timeout_handler, errb)
        return d

    def _error(self, msg):
        print Fore.RED + "[!] %s" % msg + Fore.RESET
        sys.exit(1)

    def _check_err(self, stuff, printer):
        obj = json.loads(stuff[0])
        if self.print_json:
            print(json.dumps(obj, indent=2))
        elif not obj['error']:
            if not obj['result']:
                print (Fore.RED + 'ERROR: malformed response, expected'
                       ' obj["result"]' + Fore.RESET)
            else:
                return printer(obj['result'])
        else:
            print Fore.RED + 'ERROR: ' + '%s' % obj['error'] + Fore.RESET

    def _timeout_handler(self, failure, errb):
        if failure.trap(ZmqRequestTimeoutError) == ZmqRequestTimeoutError:
            if callable(errb):
                errb()
            else:
                print (Fore.RED + "[ERROR] Timeout contacting the bitmask "
                       "daemon. Is it running?" + Fore.RESET)