summaryrefslogtreecommitdiffstats
path: root/src/lib/Server/Generators/Cfg.py
blob: c66596e7ee671acd8908d1285d4685b39fb453c9 (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
'''This module implements a config file repository'''
__revision__ = '$Revision$'

from binascii import b2a_base64
from os import stat
from re import compile as regcompile
from stat import S_ISDIR, ST_MODE
from syslog import syslog, LOG_INFO, LOG_ERR

from Bcfg2.Server.Generator import Generator, GeneratorError, FileBacked

class FileEntry(FileBacked):
    '''The File Entry class pertains to the config files contained in a particular directory.
    This includes :info, all base files and deltas'''
    
    def __init__(self, name, all, image, classes, bundles, attribs, hostname):
        FileBacked.__init__(self, name)
        self.all = all
        self.image = image
        self.bundles = bundles
        self.classes = classes
        self.attributes = attribs
        self.hostname = hostname

    def __cmp__(self, other):
        fields = ['all', 'image', 'classes', 'bundles', 'attributes', 'hostname']
        try:
            most1 = [index for index in range(len(fields)) if getattr(self, fields[index])][0]
        except IndexError:
            most1 = 0
        try:
            most2 = [index for index in range(len(fields)) if getattr(other, fields[index])][0]
        except IndexError:
            most2 = 0
        return most1 - most2

class ConfigFileEntry(object):
    '''ConfigFileEntry is a repository entry for a single file, containing
    all data for all clients.'''
    specific = regcompile('(.*/)(?P<filename>[\w.]+)\.((H_(?P<hostname>\S+))|(B(?P<bprio>\d+)_(?P<bundle>\S+))|(A(?P<aprio>\d+)_(?P<attr>\S+))|(I(?P<iprio>\d+)_(?P<image>\S+))|(C(?P<cprio>\d+)_(?P<class>\S+)))(\.(?P<op>cat|udiff))?$')
    info = regcompile('^owner:(\s)*(?P<owner>\w+)|group:(\s)*(?P<group>\w+)|perms:(\s)*(?P<perms>\w+)|encoding:(\s)*(?P<encoding>\w+)|(?P<paranoid>paranoid(\s)*)$')
    
    def __init__(self, path):
        object.__init__(self)
        self.path = path
        self.basefiles = []
        self.deltas = []
        self.encoding = 'ascii'
        self.owner = 'root'
        self.group = 'root'
        self.perms = '0644'
        self.paranoid = False

    def read_info(self, filename):
        '''read in :info metadata'''
        for line in open(filename).readlines():
            match = self.info.match(line)
            if not match:
                continue
            else:
                mgd = match.groupdict()
                if mgd['owner']:
                    self.owner = mgd['owner']
                elif mgd['group']:
                    self.group = mgd['group']
                elif mgd['encoding']:
                    self.encoding = mgd['encoding']
                elif mgd['perms']:
                    self.perms = mgd['perms']
                    if len(self.perms) == 3:
                        self.perms = "0%s" % (self.perms)
                elif mgd['paranoid']:
                    self.paranoid = True

    def AddEntry(self, name):
        '''add new file additions for a single cf file'''
        if name[-5:] == ':info':
            return self.read_info(name)

        if name.split('/')[-1] == self.path.split('/')[-1]:
            self.basefiles.append(FileEntry(name, True, None, [], [], [], None))
            return

        specmatch = self.specific.match(name)
        if specmatch == None:
            syslog(LOG_ERR, "Failed to match file %s" % (name))
            return

        data = {}
        for item, value in specmatch.groupdict().iteritems():
            if value != None:
                data[item] = value

        cfile = FileEntry(name, False, data.get('image', None), data.get('class', []),
                          data.get('bundle', []), data.get('attr', []), data.get('hostname', None))

        if specmatch.group("op") != None:
            self.deltas.append(cfile)
            self.deltas.sort()
        else:
            self.basefiles.append(cfile)
            self.basefiles.sort()

    def HandleEvent(self, event):
        '''Handle FAM updates'''
        action = event.code2str()
        if event.filename[-5:] == ':info':
            return self.read_info(event.filename)
        for entry in self.basefiles + self.deltas:
            if entry.name.split('/')[-1] == event.filename:
                if action == 'changed':
                    syslog(LOG_INFO, "File %s changed" % event.filename)
                    entry.HandleEvent(event)
                elif action == 'deleted':
                    [flist.remove(entry) for flist in [self.basefiles, self.deltas] if entry in flist]
                else:
                    syslog(LOG_ERR, "Cfg: Unhandled Action %s for file %s" % (action, event.filename))

    def GetConfigFile(self, entry, metadata):
        '''Fetch config file from repository'''
        name = entry.attrib['name']
        filedata = ""
        # first find basefile
        try:
            basefile = [bfile for bfile in self.basefiles if metadata.Applies(bfile)][-1]
        except IndexError:
            syslog(LOG_ERR, "Failed to locate basefile for %s" % name)
            raise GeneratorError, ('basefile', name)
        filedata += basefile.data

        # find applicable deltas
        #deltas = [x for x in self.deltas if x.Applies(metadata)]
        # filter for more specific
        #for delta in deltas:
        #    pass
        # apply diffs, etc
        entry.attrib.update({'owner':self.owner, 'group':self.group,
                             'perms':self.perms, 'encoding':self.encoding})
        if self.paranoid:
            entry.attrib['paranoid'] = 'true'
        if self.encoding == 'base64':
            entry.text = b2a_base64(filedata)
        else:
            entry.text = filedata

class Cfg(Generator):
    '''This generator in the configuration file repository for bcfg2'''
    __name__ = 'Cfg'
    __version__ = '$Id$'
    __author__ = 'bcfg-dev@mcs.anl.gov'

    def __init__(self, core, datastore):
        Generator.__init__(self, core, datastore)
        self.entries = {}
        self.__provides__ = {'ConfigFile':{}}
        self.famID = {}
        self.directories = []
        self.AddDirectoryMonitor(self.data)
        # eventually flush fam events here so that all entries built here
        # ready to go

    def AddDirectoryMonitor(self, name):
        '''Add new directory to FAM structures'''
        if name not in self.directories:
            try:
                stat(name)
            except OSError:
                self.LogError("Failed to open directory %s" % (name))
                return
            reqid = self.core.fam.AddMonitor(name, self)
            self.famID[reqid] = name
            self.directories.append(name)

    def AddEntry(self, name):
        '''Add new entry to FAM structures'''
        try:
            sdata = stat(name)[ST_MODE]
        except OSError:
            return

        if S_ISDIR(sdata):
            self.AddDirectoryMonitor(name)
        else:
            # file entries shouldn't contain path-to-repo
            shortname = '/'+ '/'.join(name[len(self.data)+1:].split('/')[:-1])
            if not self.entries.has_key(shortname):
                self.entries[shortname] = ConfigFileEntry(shortname)
                self.__provides__['ConfigFile'][shortname] = self.entries[shortname].GetConfigFile
            self.entries[shortname].AddEntry(name)
            #self.entries[shortname].HandleEvent()

    def HandleEvent(self, event):
        '''Handle FAM updates'''
        action = event.code2str()
        if event.filename[0] != '/':
            filename = "%s/%s" % (self.famID[event.requestID], event.filename)
        else:
            filename = event.filename
        configfile = filename[len(self.data):-(len(event.filename)+1)]

        if ((action in ['exists', 'created']) and (filename != self.data)):
            self.AddEntry(filename)
        elif action == 'changed':
            # pass the event down the chain to the ConfigFileEntry
            if event.filename == ':info':
                event.filename = filename
            if self.entries.has_key(configfile):
                self.entries[configfile].HandleEvent(event)
            else:
                if filename != self.data:
                    self.AddEntry(filename)
                else:
                    self.LogError("Ignoring event for %s"%(configfile))
        elif action == 'deleted':
            self.entries[configfile].HandleEvent(event)
        elif action in ['exists', 'endExist']:
            pass
        else:
            self.LogError("Got unknown event %s %s:%s" % (action, event.requestID, event.filename))