summaryrefslogtreecommitdiffstats
path: root/bin/hostinfo
blob: 4a48e2b9b60018a0ea0c6d198751c1af2927f23b (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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import argparse
import yaml
import os
from dns import resolver, reversename

OWN_DIRECTORY = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
LIB = os.path.join(OWN_DIRECTORY, '..')
if os.path.exists(os.path.join(LIB, 'hostinfo')):
    sys.path = [LIB] + sys.path

from hostinfo import printer
from hostinfo import utils

def _get_data(path):
    stream = file(path, 'r')
    return yaml.load(stream)

def match_key(data, keys):
    if data is None:
        return None

    if len(keys) == 0:
        return data

    key = keys[0]
    rest = keys[1:]

    if key == 'addresses' and 'addresses' in data:
        return match_key(utils.group_by(data['addresses'], 'interface'), rest)

    if key == 'ports' and 'ports' in data:
        return match_key(utils.group_by(data['ports'], 'process', 'UNKNOWN'), rest)

    if isinstance(data, dict):
        if key in data:
            return match_key(data[key], rest)
        return None

    if isinstance(data, list):
        for elem in data:
            result = match_key(elem, keys)
            if result is not None:
                return result
        return None

    if data == key:
        return data

    return None

def match(host, search):
    if search[0] != '?':
        sys.stderr.write("Invalid search string.")
        sys.exit(1)
    search = search[1:]

    negate = False
    if search[0] == '~':
        search = search[1:]
        negate = True

    key_elem = search.split('.')
    data = host

    result = match_key(data, key_elem)
    if negate:
        if result is not None:
            return (search, None)
        return (None, True)
    return (search, result)

def print_search(basepath, flags, search, filter_key=None):
    def _get_label(host):
        if flags.short:
            return host.replace('.spline.inf.fu-berlin.de','')
        return host

    metadata = os.path.join(basepath, 'metadata', 'hosts')
    if not os.path.exists(metadata):
        sys.stderr.write("Invalid hostinfo data. "
                         "'metadata/hosts' not found!\n")
        sys.exit(1)

    hosts = _get_data(metadata)
    length = [len(_get_label(host)) for host in hosts['hosts']]
    for host in hosts['hosts']:
        data = _get_data(os.path.join(basepath, host))
        key, result = match(data, search)
        if result is not None:
            if flags.only_names:
                print(_get_label(host))
                continue

            p = printer.Printer(data, flags)
            if filter_key is not None or flags.details:
                p.info(filter_key, label=_get_label(host), maxlength=max(length))
            else:
                if key is None:
                    print(_get_label(host))
                else:
                    p.info(key, label=_get_label(host), maxlength=max(length))

def print_info(path, flags, key=None):
    data = _get_data(path)
    p = printer.Printer(data, flags)
    p.info(key)

def print_keys(path):
    def _print_keys(data, prefix = ''):
        if isinstance(data, str):
            return

        for key in data.keys():
            print "%s%s" % (prefix, key)

            if key == 'addresses':
                for k in utils.group_by(data[key], 'interface').keys():
                    print "%s%s.%s" % (prefix, key, k)
            elif key == 'ports':
                for k in utils.group_by(data[key], 'process', 'UNKNOWN').keys():
                    print "%s%s.%s" % (prefix, key, k)
            elif isinstance(data[key], dict):
                _print_keys(data[key], "%s%s." % (prefix, key))
            elif isinstance(data[key], list):
                for value in data[key]:
                    _print_keys(value, "%s%s." % (prefix, key))

    data = _get_data(path)
    _print_keys(data)

def print_hosts(path, short):
    metadata = os.path.join(path, 'metadata', 'hosts')
    if os.path.exists(metadata):
        hosts = yaml.load(file(metadata, 'r'))
        if 'hosts' in hosts:
            for host in hosts['hosts']:
                if short:
                    print(host.replace('.spline.inf.fu-berlin.de',''))
                else:
                    print(host)
            return True

    sys.stderr.write("'%s' not found!\n" % metadata)
    return False

def find_host(basepath, host):
    path = os.path.join(basepath, host)
    if os.path.exists(path):
        return path

    # try to build the fqdn
    path = os.path.join(basepath, "%s.spline.inf.fu-berlin.de" %
                        host.replace('.spline.de', ''))
    if os.path.exists(path):
        return path

    try:
        # try to use reverse dns
        addr = reversename.from_address(host)
        hostname = str(resolver.query(addr,"PTR")[0])
        path = os.path.join(basepath, hostname[0:-1])
    except:
        pass

    if os.path.exists(path):
        return path

    return None

def main():
    basepath = '/usr/local/share/hostinfo'
    if 'HOSTINFO_PATH' in os.environ and os.environ['HOSTINFO_PATH'] != '':
        basepath = os.environ['HOSTINFO_PATH']

    parser = argparse.ArgumentParser()
    parser.add_argument("name", nargs="?")
    parser.add_argument("filter", nargs="?")
    parser.add_argument("-o", "--oneline", action="store_true",
                        help="each line is a complete record")
    parser.add_argument("-f", "--file", action="store_true",
                        help="print the path of the file the "
                             "information is read from")
    parser.add_argument("-k", "--keys", action="store_true",
                        help="print only the available keys "
                             "(used for bash completion)")
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="increase output verbosity")
    parser.add_argument("-n", "--nospaces", action="store_true",
                        help="remove unnecessary spaces from output")
    parser.add_argument("-p", "--path", default=basepath,
                        help="set the basepath to the hostinfo data")
    parser.add_argument("-l", "--hosts", action="store_true",
                        help="lists all available hosts")
    parser.add_argument("-s", "--short", action="store_true",
                        help="remove the domain from the output")
    parser.add_argument("--only-names", action="store_true",
                        help="only print the hostname of the matching entries")
    parser.add_argument("-d", "--details", action="store_true",
                        help="print details about matching hosts")
    args = parser.parse_args()

    if args.path:
        basepath = args.path

    if args.hosts:
        if not print_hosts(basepath, args.short):
            sys.exit(1)
        sys.exit(0)

    if args.name is None:
        parser.print_help()
        sys.exit(1)

    if args.name.startswith('?'):
        # search
        print_search(basepath, search=args.name, filter_key=args.filter, flags=args)
    else:
        # info
        path = find_host(basepath, args.name)
        if path is None:
            sys.stderr.write("Host '%s' could not be found!\n" % args.name)
            sys.exit(1)

        if args.file:
            print(path)
        elif args.keys:
            print_keys(path)
        else:
            print_info(path, key=args.filter, flags=args)

    sys.exit(0)

if __name__ == '__main__':
    main()