summaryrefslogtreecommitdiffstats
path: root/hostinfo/printer.py
blob: 430b1f6277838e37e94746e6b4bb95dc1088f379 (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
# -*- coding: utf-8 -*-

from __future__ import print_function

class Prefix:
    def __init__(self, prefix, output, oneline):
        self.prefix = prefix
        self.output = output
        self.empty = oneline

    def pprint(self, data):
        self.output("%s%s" % (self.prefix, data))
        if not self.empty:
            self.prefix = ' ' * len(self.prefix)
            self.empty = True

class Printer:
    labels = {
        'hostname': 'Hostname',
        'arch': 'Architecture',
        'os': 'Operating System',
        'addresses': 'IPs',
        'ports': 'Ports',
        'vserver': 'VServer'
    }

    ignore = ['vserver-host']

    def __init__(self, data, oneline):
        self.data = data
        self.oneline = oneline

    def _sort_with_list(self, list, sort):
        def helper(value):
            if value in sort:
                return sort.index(value)
            return len(sort)

        return sorted(list, key=helper)

    def print_addresses(self, p, value, filter_key):
        interfaces = sorted(set([ip['interface'] for ip in value]))
        maxlength = max(map(len, interfaces))
        for interface in interfaces:
            if filter_key is None:
                iface_name = ("%s: " % interface).ljust(maxlength+2)
                p_new = Prefix(iface_name, p.pprint, self.oneline)
            else:
                p_new = p

            if filter_key is None or filter_key == interface:
                for ip in value:
                    if 'vserver' in ip:
                        continue

                    if interface == ip['interface']:
                        p_new.pprint('%s/%s' %
                                     (ip['address'], ip['netmask']))

    def print_vserver(self, p, value, filter_key):
        if value == 'guest':
            p.pprint('guest running on %s' % self.data['vserver-host'])
        else:
            p.pprint(value)

    def print_ports(self, p, value, filter_key):
        processes = set([port['process'] for port in value if 'process' in port])
        processes = self._sort_with_list(processes,
                                        ['sshd', 'nrpe', 'munin-node'])
        if len([port for port in value if 'process' not in port]) > 0:
            processes.append('UNKNOWN')

        maxlength = max(map(len, processes))
        for process in processes:
            if filter_key is None:
                process_name = ("%s: " % process).ljust(maxlength+2)
                p_new = Prefix(process_name, p.pprint, self.oneline)
            else:
                p_new = p

            if filter_key is None or filter_key == process:
                for port in value:
                    if 'process' in port and process == port['process'] or \
                       'process' not in port and process == 'UNKNOWN':
                        if port['proto'] in ['tcp6', 'udp6']:
                            p_new.pprint('(%s) [%s]:%s' %
                                         (port['proto'].replace('6', ''),
                                          port['ip'], port['port']))
                        else:
                            p_new.pprint('(%s) %s:%s' %
                                         (port['proto'], port['ip'], port['port']))

    def print_default(self, key, value, filter_key=None):
        label = ''
        if self.length > 0:
            label = '%s: ' % self.get_label(key)
            label = label.rjust(self.length)
        p = Prefix(label, print, self.oneline)

        try:
            method = getattr(self, 'print_%s' % key)
            method(p, value, filter_key)
        except AttributeError:
            try:
                value = value.strip().splitlines()
            except:
                pass

            if isinstance(value, list):
                for v in value:
                    p.pprint(v)
            else:
                p.pprint(value)

    def get_label(self, key):
        if key in self.labels:
            return self.labels[key]
        return key

    def info(self, key):
        # find max lenght for labels
        labels = map(self.get_label, self.data.keys())
        self.length = max(map(len, labels)) + 3

        if key is not None:
            key_extra = None
            if '.' in key:
                [key, key_extra] = key.split('.', 1)

            self.length = 0
            if key in self.data:
                self.print_default(key, self.data[key], key_extra)
        else:
            keys = self._sort_with_list(self.data.keys(),
                                       ['hostname', 'arch', 'os',
                                        'addresses', 'ports'])
            for key in keys:
                if key not in self.ignore:
                    self.print_default(key, self.data[key])