summaryrefslogtreecommitdiffstats
path: root/src/sbin/StatReports
blob: 91321919d0684bea0f0ec4568f781adf346e1f92 (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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/usr/bin/env python

#Jun 7 2005
#StatReports - Joey Hagedorn - hagedorn@mcs.anl.gov

'''StatReports Generates & distributes reports of statistic information
for bcfg2'''
__revision__ = '$Revision$'

from ConfigParser import ConfigParser, NoSectionError, NoOptionError
from elementtree.ElementTree import *
from xml.parsers.expat import ExpatError
from xml.sax.saxutils import escape
from time import asctime, strftime, strptime, gmtime, time
from socket import getfqdn
from sys import exit, argv
from getopt import getopt, GetoptError
import re, os, string, libxml2, libxslt
from tempfile import mktemp
from copy import deepcopy

def generatereport(rs, nr):
    '''generatereport creates and returns an ElementTree representation
     of a report adhering to the XML spec for intermediate reports'''
    reportspec = deepcopy(rs)
    nodereprt = deepcopy(nr)

    reportgood = reportspec.get("good", default = 'Y')
    reportmodified = reportspec.get("modified", default = 'Y')

    current_date = asctime()[:10]

    '''build regex of all the nodes we are reporting about'''
    regex = string.join([x.get("name") for x in \
                         reportspec.findall('Machine')], '|')
    pattern = re.compile(regex)


    for node in nodereprt.findall('Node'):

        if node.findall('HostInfo') == [] or \
        not pattern.match(node.get("name")) or \
        node.findall('Statistics') == [] or \
        node.find("HostInfo").get("fqdn") == "":#maybe issue a warning instead?
            nodereprt.remove(node)
            continue

        #reduce to most recent Statistics entry
        statisticslist = node.findall('Statistics')
        #this line actually sorts from most recent to oldest
        statisticslist.sort(lambda y, x: cmp(strptime(x.get("time")), \
                                             strptime(y.get("time"))))
        
        stats = statisticslist[0]

        [node.remove(x) for x in node.findall('Statistics')]
        

        #add a good tag if node is good and we wnat to report such
        if reportgood == 'Y' and stats.get('state') == 'clean':
            SubElement(stats,"Good")

        for x in stats.findall('Modified'):
            if reportmodified == 'N' or x.getchildren() == None:
                stats.remove(x)

        for x in stats.findall('Bad'):
            if x.getchildren() == None:
                stats.remove(x)
                
        #test for staleness -if stale add Stale tag
        if stats.get("time").find(current_date) == -1:
            SubElement(stats,"Stale")
            
        node.append(stats)
        
    return nodereprt



def mail(mailbody, confi):
    '''mail mails a previously generated report'''

    try:
        mailer = confi.get('statistics', 'sendmailpath')
    except NoSectionError, NoOptionError:
        mailer = "/usr/sbin/sendmail"
    # open a pipe to the mail program and
    # write the data to the pipe
    pipe = os.popen("%s -t" % mailer, 'w')
    pipe.write(mailbody)
    exitcode = pipe.close()
    if exitcode:
        print "Exit code: %s" % exitcode

def rss(reportxml, delivery, report):
    '''rss appends a new report to the specified rss file
     keeping the last 9 articles'''
    #check and see if rss file exists
    for destination in delivery.findall('Destination'):
        try:
            fil = open(destination.attrib['address'], 'r')
            olddoc = XML(fil.read())

            #defines the number of recent articles to keep
            items = olddoc.find("channel").findall("item")[0:9]
            fil.close()
            fil = open(destination.attrib['address'], 'w')
        except (IOError, ExpatError):
            fil = open(destination.attrib['address'], 'w')
            items = []

        rssdata = Element("rss")
        channel = SubElement(rssdata, "channel")
        rssdata.set("version", "2.0")
        chantitle = SubElement(channel, "title")
        chantitle.text = report.attrib['name']
        chanlink = SubElement(channel, "link")
        
        #this can later link to WWW report if one gets published simultaneously?
        chanlink.text = "http://www.mcs.anl.gov/cobalt/bcfg2"
        chandesc = SubElement(channel, "description")
        chandesc.text = "Information regarding the 10 most recent bcfg2 runs."

        channel.append(XML(reportxml))

        if items != []:
            for item in items:
                channel.append(item)

        tree = "<?xml version=\"1.0\"?>" + tostring(rssdata)
        fil.write(tree)
        fil.close()

def www(reportxml, delivery):
    '''www outputs report to'''

    #this can later link to WWW report if one gets published simultaneously?    
    for destination in delivery.findall('Destination'):
        fil = open(destination.attrib['address'], 'w')

        fil.write(reportxml)
        fil.close()

def pretty_print(element, level=0):
    '''Produce a pretty-printed text representation of element'''
    if element.text:
        fmt = "%s<%%s %%s>%%s</%%s>" % (level*" ")
        data = (element.tag, (" ".join(["%s='%s'" % keyval for keyval in element.attrib.iteritems()])),
                element.text, element.tag)
    if element._children:
        fmt = "%s<%%s %%s>\n" % (level*" ",) + (len(element._children) * "%s") + "%s</%%s>\n" % (level*" ")
        data = (element.tag, ) + (" ".join(["%s='%s'" % keyval for keyval in element.attrib.iteritems()]),)
        data += tuple([pretty_print(entry, level+2) for entry in element._children]) + (element.tag, )
    else:
        fmt = "%s<%%s %%s/>\n" % (level * " ")
        data = (element.tag, " ".join(["%s='%s'" % keyval for keyval in element.attrib.iteritems()]))
    return fmt % data


if __name__ == '__main__':
    c = ConfigParser()
    c.read(['/etc/bcfg2.conf'])
    configpath = "%s/report-configuration.xml" % c.get('server', 'metadata')
    statpath = "%s/statistics.xml" % c.get('server', 'metadata')
    hostinfopath = "%s/hostinfo.xml" % c.get('server', 'metadata')
    metadatapath = "%s/metadata.xml" % c.get('server', 'metadata')
    transformpath = "/usr/share/bcfg2/xsl-transforms/"
    #websrcspath = "/usr/share/bcfg2/web-rprt-srcs/"

    try:
        opts, args = getopt(argv[1:], "hc:s:", ["help", "config=", "stats="])
    except GetoptError, mesg:
        # print help information and exit:
        print "%s\nUsage:\nStatReports.py [-h] [-c <configuration-file>] [-s <statistics-file>]" % (mesg) 
        exit(2)
    for o, a in opts:
        if o in ("-h", "--help"):
            print "Usage:\nStatReports.py [-h] [-c <configuration-file>] [-s <statistics-file>]"
            exit()
        if o in ("-c", "--config"):
            configpath = a
        if o in ("-s", "--stats"):
            statpath = a


    #See if hostinfo.xml exists, and is less than 23.5 hours old
    try:
        hostinstat = os.stat(hostinfopath)
        if (time() - hostinstat[9])/(60*60) > 23.5:
            os.system('GenerateHostInfo')#Generate HostInfo needs to be in path
    except OSError:
        os.system('GenerateHostInfo')#Generate HostInfo needs to be in path


    '''Reads Data & Config files'''
    try:
        statsdata = XML(open(statpath).read())
    except (IOError, ExpatError):
        print("StatReports: Failed to parse %s"%(statpath))
        exit(1)
    try:
        configdata = XML(open(configpath).read())
    except (IOError, ExpatError):
        print("StatReports: Failed to parse %s"%(configpath))
        exit(1)
    try:
        metadata = XML(open(metadatapath).read())
    except (IOError, ExpatError):
        print("StatReports: Failed to parse %s"%(metadatapath))
        exit(1)
    try:
        hostinfodata = XML(open(hostinfopath).read())
    except (IOError, ExpatError):
        print("StatReports: Failed to parse %s. Is GenerateHostInfo in your path?"%(hostinfopath))
        exit(1)


    #Merge data from three sources
    nodereport = Element("Report", attrib={"time" : asctime()})

    #should all of the other info in Metadata be appended?
    #What about all of the package stuff for other types of reports?
    
    for client in metadata.findall("Client"):
        nodel = Element("Node", attrib={"name" : client.get("name")})
        nodel.append(client)
        for hostinfo in hostinfodata.findall("HostInfo"):
            if hostinfo.get("name") == client.get("name"):
                nodel.append(hostinfo)

        for nod in statsdata.findall("Node"):
            if nod.get("name") == client.get("name"):
                for statel in nod.findall("Statistics"):
                    nodel.append(statel)
        nodereport.append(nodel)


    for reprt in configdata.findall('Report'):
        nodereport.set("name", reprt.get("name", default="BCFG Report"))

        procnodereport = generatereport(reprt, nodereport)

        for deliv in reprt.findall('Delivery'):
            #is a deepcopy of procnodereport necessary?
            
            delivtype = deliv.get('type', default='nodes-digest')
            deliverymechanism = deliv.get('mechanism', default='invalid')

            #apply XSLT, different ones based on report type, and options
            transform = ''
            if deliverymechanism == 'mail':
                if delivtype == 'nodes-individual':
                    transform = 'nodes-individual-email.xsl'                    
                elif delivtype == 'overview-stats':
                    transform = 'overview-stats-email.xsl'
                else:
                    transform = 'nodes-digest-email.xsl'
            elif deliverymechanism == 'rss':
                if delivtype == 'overview-stats':
                    transform = 'overview-stats-rss.xsl'
                else:
                    transform = 'nodes-digest-rss.xsl'
            elif deliverymechanism == 'www':
                if delivtype == 'overview-stats':
                    transform = 'overview-stats-html.xsl'
                else:
                    transform = 'nodes-digest-html.xsl'
            else:
                print("StatReports: Invalid delivery mechanism in report-config")
                exit(1)


            #IMPORTANT to add some error checking here-parseerrors
            #this might be sufficient
            try:
                styledoc = libxml2.parseFile(transformpath+transform)
                style = libxslt.parseStylesheetDoc(styledoc)
            except:
                print("StatReports: invalid XSLT transform file.")
                exit(1)
                
            if deliverymechanism == 'mail':
                if delivtype == 'nodes-individual':
                    p2noderep = deepcopy(procnodereport)
                    for noden in procnodereport.findall("Node"):
                        [p2noderep.remove(y) for y in p2noderep.findall("Node")]
                        p2noderep.append(noden)
                        tempfilename = mktemp()
                        tempr = open(tempfilename, "w+")
                        tempr.write(tostring(p2noderep))
                        tempr.seek(0)
                        doc = libxml2.parseFile(tempfilename)
                        result = style.applyStylesheet(doc, None)
                        tempr.close()
                        del tempr
                        try:
                            tempfilename = mktemp()
                            tempr = open(tempfilename, "w+")
                            style.saveResultToFile(tempr, result)
                            tempr.seek(0)
                            outputstring = tempr.read()
                        except:
                            outputstring = None#this is a nasty hack. When the xslt transform breaks-- just blank it out
                            #this is done due to a bug in libxslt
                            #This needs to be fixed in future releases

                        tempr.close()
                        del tempr
                        
                        if not outputstring == None:
                            toastring = ''
                            for desti in deliv.findall("Destination"):
                                toastring = "%s%s " % \
                                            (toastring, desti.get('address'))
                            #prepend To: and From:
                            outputstring = "To: %s\nFrom: root@%s\n%s"% \
                                           (toastring, getfqdn(), outputstring)
                            mail(outputstring, c) #call function to send
                        doc.freeDoc()
                        result.freeDoc()
                    style.freeStylesheet()
                else:
                    tempfilename = mktemp()
                    tempr = open(tempfilename, "w+")
                    tempr.write(tostring(procnodereport))
                    tempr.seek(0)
                    doc = libxml2.parseFile(tempfilename)
                    result = style.applyStylesheet(doc, None)
                    tempr.close()
                    del tempr
                    tempfilename = mktemp()
                    tempr = open(tempfilename, "w+")
                    style.saveResultToFile(tempr, result)
                    tempr.seek(0)
                    outputstring = tempr.read()
                    tempr.close()
                    del tempr

                    if not outputstring == None:
                        toastring = ''
                        for desti in deliv.findall("Destination"):
                            toastring = "%s%s " % \
                                        (toastring, desti.get('address'))
                        #prepend To: and From:
                        outputstring = "To: %s\nFrom: root@%s\n%s"% \
                                       (toastring, getfqdn(), outputstring)
                        mail(outputstring, c) #call function to send
                    style.freeStylesheet()
                    doc.freeDoc()
                    result.freeDoc()
            else:
                tempfilename = mktemp()
                tempr = open(tempfilename, "w+")
                tempr.write(tostring(procnodereport))
                tempr.seek(0)
                doc = libxml2.parseFile(tempfilename)
                result = style.applyStylesheet(doc, None)
                tempr.close()
                del tempr
                tempfilename = mktemp()
                tempr = open(tempfilename, "w+")
                style.saveResultToFile(tempr, result)
                tempr.seek(0)
                outputstring = tempr.read()
                tempr.close()
                del tempr

                if deliverymechanism == 'rss':
                    rss(outputstring, deliv, reprt)
                else: # must be deliverymechanism == 'www':
                    www(outputstring, deliv)
                style.freeStylesheet()
                doc.freeDoc()
                result.freeDoc()