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

'''Bcfg2 Server'''
__revision__ = '$Revision'

from getopt import getopt, GetoptError
from socket import gethostbyaddr, herror
from syslog import openlog, syslog, LOG_INFO, LOG_ERR, LOG_LOCAL0
from sys import argv, exit as sysexit, exc_info
from time import time
from traceback import extract_tb
from ConfigParser import ConfigParser

from elementtree.ElementTree import Element

from Bcfg2.Server.Core import Core
from Bcfg2.Server.Metadata import MetadataStore

from sss.daemonize import daemonize
from sss.server import Server

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([xy+':' for xy in vopt.keys()])
    try:
        (o, a) = getopt(arglist, gstr)
    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
        sysexit(1)
    for (gopt, garg) in o:
        option = gopt[1:]
        if opt.has_key(option):
            ret[opt[option]] = True
        else:
            ret[vopt[option]] = garg
    return ret

class BcfgServer(Server):
    '''Bcfg2 Server Class'''
    __implementation__ = 'Bcfg2'
    __component__ = 'bcfg2'
    __dispatch__ = {'get-config':'BuildConfig', 'get-probes':'get_probes', 'probe-data':'put_probe_data', 'upload-statistics':'HandleStats'}
    __validate__ = 0
        
    def __setup__(self):
        self.setup = self.kwargs['setup']
        c = ConfigParser()
        c.read([self.kwargs.get('configfile', '/etc/bcfg2.conf')])
        repo = c.get('server','repository')
        generators = c.get('server','generators').split(',')
        structures = c.get('server', 'structures').split(',')
        mpath = c.get('server','metadata')
        self.core = Core(repo, structures, generators)
        self.metadata = MetadataStore("%s/metadata.xml"%(mpath), self.core.fam)
        self.__progress__()

    def __progress__(self):
        while self.core.fam.fm.pending():
            self.core.fam.HandleEvent()
        try:
            self.core.RunCronTasks()
        except:
            self.LogFailure("Cron")
        return 0

    def BuildConfig(self, xml, (peer, port)):
        '''Build Client Config'''
        if setup['client']:
            client = setup['client']
        else:
            try:
                client = gethostbyaddr(peer)[0].split('.')[0]
            except herror:
                return Element("error", type='host resolution error')
        t = time()
        config = Element("Configuration", version='2.0')
        # get metadata for host
        if xml.attrib.has_key("profile") and xml.attrib.has_key("image"):
            m = self.metadata.FetchMetadata(client, image=xml.attrib['image'], profile=xml.attrib['profile'])
        else:
            m = self.metadata.FetchMetadata(client)
            
        try:
            structures = self.core.GetStructures(m)
        except:
            self.LogFailure("GetStructures")
            return Element("error", type='structure error')
        for s in structures:
            try:
                self.core.BindStructure(s, m)
                config.append(s)
            except:
                self.LogFailure("BindStructure")
        syslog(LOG_INFO, "Generated config for %s in %s seconds"%(client, time()-t))
        return config

    def get_probes(self, xml, (peer, port)):
        '''Get Probes for Client'''
        r = Element('probes')
        try:
            client = gethostbyaddr(peer)[0].split('.')[0]
        except herror:
            return Element("error", type='host resolution error')
        m = self.metadata.FetchMetadata(client)
        for g in self.core.generators:
            for p in g.get_probes(m):
                r.append(p)
        return r

    def put_probe_data(self, xml, (peer, port)):
        '''Return Probe output to generators'''
        try:
            client = gethostbyaddr(peer)[0].split('.')[0]
        except herror:
            return Element("error", type='host resolution error')
        for data in xml.findall(".//probe-data"):
            try:
                [g] = [x for x in self.core.generators if x.__name__ == data.attrib['source']]
                g.accept_probe_data(client, data)
            except:
                self.LogFailure("put_probe_data")
        return Element("OK")

    def HandleStats(self, xml, (peer, port)):
        '''Act on statistics upload'''
        e = xml.find(".//Statistics")
        syslog(LOG_INFO, "Client %s reported state %s"%(peer, e.attrib['state']))
        return Element("ok")

    def LogFailure(self, failure):
        '''Log Failures in unexpected cases'''
        (t, v, tb)=exc_info()
        syslog(LOG_ERR, "Unexpected failure in %s"%(failure))
        for line in extract_tb(tb):
            syslog(LOG_ERR, '  File "%s", line %i, in %s\n    %s\n'%line)
        syslog(LOG_ERR, "%s: %s\n"%(t, v))
        del t, v, tb

if __name__ == '__main__':
    openlog("Bcfg2", 0, LOG_LOCAL0)
    options =  {'v':'verbose', 'd':'debug'}
    doptions = {'D':'daemon', 'C':'client'}
    setup = dgetopt(argv[1:], options, doptions)
    if setup['daemon']:
        daemonize(setup['daemon'])
    server = BcfgServer(setup=setup)
    for i in range(10):
        server.__progress__()
    server.ServeForever()