blob: 947164675f07cb07288f89fa1415e17f4b740168 [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
martin f. krafft9a9b0ac2013-06-21 21:24:18 +020025def get_data(storage_type, nodes_uri, classes_uri, applications_postfix, node):
martin f. krafftf37f0682013-06-14 16:36:20 +020026 storage_class = StorageBackendLoader(storage_type).load()
27 storage = storage_class(os.path.abspath(os.path.expanduser(nodes_uri)),
martin f. krafft9a9b0ac2013-06-21 21:24:18 +020028 os.path.abspath(os.path.expanduser(classes_uri)),
29 applications_postfix
30 )
martin f. krafftf37f0682013-06-14 16:36:20 +020031 if node is False:
32 ret = storage.inventory()
33 else:
34 ret = storage.nodeinfo(node)
35 ret['RECLASS']['timestamp'] = time.strftime('%c')
36
37 return ret
38
39def output(data, fmt, pretty_print=False):
40 output_class = OutputLoader(fmt).load()
41 outputter = output_class()
42 return outputter.dump(data, pretty_print=pretty_print)
43
martin f. krafft3434b6b2013-06-14 20:40:52 +020044def _error(msg, rc):
45 print >>sys.stderr, msg
46 sys.exit(rc)
47
martin f. krafftf37f0682013-06-14 16:36:20 +020048if __name__ == '__main__':
49 __name__ = __prog__
50 config_file = None
51 for d in (os.getcwd(), os.path.dirname(sys.argv[0])):
52 f = os.path.join(d, __name__ + '-config.yml')
53 if os.access(f, os.R_OK):
54 config_file = f
55 break
martin f. krafft3434b6b2013-06-14 20:40:52 +020056 try:
57 options = get_options(config_file)
58 data = get_data(options.storage_type, options.nodes_uri,
martin f. krafft9a9b0ac2013-06-21 21:24:18 +020059 options.classes_uri, options.applications_postfix,
60 options.node)
martin f. krafft3434b6b2013-06-14 20:40:52 +020061 print output(data, options.output, options.pretty_print)
62 sys.exit(posix.EX_OK)
63
64 except errors.ReclassException, e:
65 _error(e.message, e.rc)