blob: cd44652fb52309cac49b6fb741d46dd5b6c18e11 [file] [log] [blame]
martin f. krafftf37f0682013-06-14 16:36:20 +02001#!/usr/bin/python
2# -*- coding: utf-8 -*-
3#
4# reclass — recursive external node classifier
5#
6# Copyright © 2007–13 martin f. krafft <madduck@madduck.net>
7# Released under the terms of the Artistic Licence 2.0
8#
9__prog__ = 'reclass'
10__description__ = 'classify nodes based on an external data source'
11__version__ = '1.0'
12__author__ = 'martin f. krafft <madduck@madduck.net>'
13__copyright__ = 'Copyright © 2007–13 ' + __author__
14__licence__ = 'Artistic Licence 2.0'
15
16import sys, os, posix, time
17import config
18from output import OutputLoader
19from storage import StorageBackendLoader
martin f. krafft3434b6b2013-06-14 20:40:52 +020020import errors
martin f. krafftf37f0682013-06-14 16:36:20 +020021
22def get_options(config_file=None):
23 return config.get_options(__name__, __version__, __description__, config_file)
24
25def get_data(storage_type, nodes_uri, classes_uri, node):
26 storage_class = StorageBackendLoader(storage_type).load()
27 storage = storage_class(os.path.abspath(os.path.expanduser(nodes_uri)),
28 os.path.abspath(os.path.expanduser(classes_uri)))
29 if node is False:
30 ret = storage.inventory()
31 else:
32 ret = storage.nodeinfo(node)
33 ret['RECLASS']['timestamp'] = time.strftime('%c')
34
35 return ret
36
37def output(data, fmt, pretty_print=False):
38 output_class = OutputLoader(fmt).load()
39 outputter = output_class()
40 return outputter.dump(data, pretty_print=pretty_print)
41
martin f. krafft3434b6b2013-06-14 20:40:52 +020042def _error(msg, rc):
43 print >>sys.stderr, msg
44 sys.exit(rc)
45
martin f. krafftf37f0682013-06-14 16:36:20 +020046if __name__ == '__main__':
47 __name__ = __prog__
48 config_file = None
49 for d in (os.getcwd(), os.path.dirname(sys.argv[0])):
50 f = os.path.join(d, __name__ + '-config.yml')
51 if os.access(f, os.R_OK):
52 config_file = f
53 break
martin f. krafft3434b6b2013-06-14 20:40:52 +020054 try:
55 options = get_options(config_file)
56 data = get_data(options.storage_type, options.nodes_uri,
57 options.classes_uri, options.node)
58 print output(data, options.output, options.pretty_print)
59 sys.exit(posix.EX_OK)
60
61 except errors.ReclassException, e:
62 _error(e.message, e.rc)