summaryrefslogtreecommitdiffstats
path: root/src/sbin/Bcfg2Server
blob: 76e4e7dac53dff80891c789b54457988229c8dad (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
#!/usr/bin/env python

'''The XML-RPC Bcfg2 Server'''
__revision__ = '$Revision:$'

from getopt import getopt, GetoptError
from sys import argv, exc_info
from syslog import openlog, LOG_LOCAL0, syslog, LOG_INFO, LOG_ERR
from Bcfg2.Server.Core import Core, CoreInitError
from Bcfg2.Server.Metadata import MetadataConsistencyError
from Bcfg2.Server.Component import Component
from threading import Lock
from select import select, error as selecterror
from signal import signal, SIGINT, SIGTERM
from xmlrpclib import Fault
from socket import gethostbyaddr, herror
from lxml.etree import XML, Element, tostring
from M2Crypto.SSL import SSLError

def dgetopt(arglist, opt, vopt):
    '''parse options into a dictionary'''
    ret = {}
    for optname in opt.values() + vopt.values():
        ret[optname] = False
    gstr = "".join(opt.keys()) + "".join([field+':' for field in vopt.keys()])
    try:
        opts = getopt(arglist, gstr)[0]
    except GetoptError, gerr:
        print gerr
        print "bcfg2 Usage:"
        for arg in opt.iteritems():
            print " -%s %s" % arg
        for arg in  vopt.iteritems():
            print " -%s <%s>" % arg
        raise SystemExit, 1
    for (gopt, garg) in opts:
        option = gopt[1:]
        if opt.has_key(option):
            ret[opt[option]] = True
        else:
            ret[vopt[option]] = garg
    return ret

class Bcfg2(Component):
    """The Bcfg2 Server component providing XML-RPC access to Bcfg methods"""
    __name__ = 'bcfg2'
    __implementation__ = 'bcfg2'

    request_queue_size = 15

    def __init__(self, setup):
        Component.__init__(self, setup)
        self.shut = False
        # set shutdown handlers for sigint and sigterm
        signal(SIGINT, self.start_shutdown)
        signal(SIGTERM, self.start_shutdown)
        try:
            self.Core = Core(setup, setup['configfile'])
            self.CoreLock = Lock()
        except CoreInitError, msg:
            print msg
            raise SystemExit, 1
        self.funcs.update({"GetConfig":self.Bcfg2GetConfig, "GetProbes":self.Bcfg2GetProbes,
                           "RecvProbeData":self.Bcfg2RecvProbeData, "RecvStats":self.Bcfg2RecvStats})
        for plugin in self.Core.plugins.values():
            for method in plugin.__rmi__:
                self.register_function(getattr(self.Core.plugins[plugin.__name__], method),
                                       "%s.%s" % (plugin.__name__, method))

    def get_request(self):
        '''We need to do work between requests, so select with timeout instead of blocking in accept'''
        rsockinfo = []
        famfd = self.Core.fam.fileno()
        while self.socket not in rsockinfo:
            if self.shut:
                raise SSLError
            try:
                rsockinfo = select([self.socket, famfd], [], [], 15)[0]
            except selecterror:
                raise SSLError
            if famfd in rsockinfo:
                self.Core.fam.Service()
            if self.socket in rsockinfo:
                # workaround for m2crypto 0.15 bug
                self.socket.postConnectionCheck = None
                return self.socket.accept()

    def serve_forever(self):
        """Handle one request at a time until doomsday."""
        while not self.shut:
            self.handle_request()

    def start_shutdown(self, signum, frame):
        '''Shutdown on unexpected signals'''
        self.shut = True

    def handle_error(self):
        '''Catch error path for clean exit'''
        return False
        
    def Bcfg2GetProbes(self, address):
        '''Fetch probes for a particular client'''
        peer = address[0]
        resp = Element('probes')
        try:
            client = gethostbyaddr(peer)[0]
        except herror:
            raise Fault, "host resolution error"
        try:
            meta = self.Core.metadata.FetchMetadata(client)
        except MetadataConsistencyError:
            raise Fault, 'metadata resolution error'
        for generator in self.Core.generators:
            for probe in generator.GetProbes(meta):
                resp.append(probe)
        return tostring(resp)

    def Bcfg2RecvProbeData(self, address, probedata):
        '''Receive probe data from clients'''
        peer = address[0]
        try:
            client = gethostbyaddr(peer)[0]
        except herror:
            raise Fault, "host resolution error"
        for data in probedata:
            try:
                [generator] = [gen for gen in self.Core.generators if gen.__name__ == data.get('source')]
                generator.ReceiveData(client, data)
            except IndexError:
                syslog(LOG_ERR, "Failed to locate plugin %s" % (data.get('source')))
            except:
                syslog(LOG_ERR, "Unexpected failure in probe data receipt")
        return True

    def Bcfg2GetConfig(self, address, image=False, profile=False):
        '''Build config for a client'''
        peer = address[0]
        try:
            client = gethostbyaddr(peer)[0]
        except herror:
            raise Fault, "host resolution error"
        if image and profile:
            try:
                # if metadata is provided, call FetchMetadata with settings
                # it is screwey. i know.
                self.Core.metadata.FetchMetadata(client, image=image, profile=profile)
            except MetadataConsistencyError:
                syslog(LOG_ERR, "Metadata consistency error for client %s" % client)
                return Fault, 'metadata error'
        return tostring(self.Core.BuildConfiguration(client))

    def Bcfg2RecvStats(self, address, stats):
        '''Act on statistics upload'''
        sdata = XML(stats)
        state = sdata.find(".//Statistics")
        # Versioned stats to prevent tied client/server upgrade
        if state.get('version') >= '2.0':
            try:
                client = gethostbyaddr(address[0])[0]
            except herror:
                return Fault, 'host resolution error'

            # Update statistics
            self.Core.stats.updateStats(sdata, client)

        syslog(LOG_INFO, "Client %s reported state %s"%(client, state.attrib['state']))
        return "<ok/>"

if __name__ == '__main__':
    openlog("Bcfg2", 0, LOG_LOCAL0)
    options =  {'v':'verbose', 'd':'debug'}
    doptions = {'D':'daemon', 'c':'configfile', 'C':'client'}
    ssetup = dgetopt(argv[1:], options, doptions)
    if not ssetup['configfile']:
        ssetup['configfile'] = '/etc/bcfg2.conf'
    s = Bcfg2(ssetup)
    while not s.shut:
        try:
            s.serve_forever()
        except:
            syslog(LOG_ERR, "Unexpected serve loop failure")
            (trace, val, trb)=exc_info()
            for line in extract_tb(trb):
                syslog(LOG_ERR, '  File "%s", line %i, in %s\n    %s\n'%line)
            syslog(LOG_ERR, "%s: %s\n"%(trace, val))
            del trace, val, trb
    syslog(LOG_INFO, "Shutting down")