summaryrefslogtreecommitdiffstats
path: root/lib/puppet/metric.rb
blob: fb72c305bd2e81269b6fd3ff5438ddc963110946 (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
# included so we can test object types
require 'puppet'

module Puppet
    # A class for handling metrics.  This is currently ridiculously hackish.
	class Metric
        def Metric.init
            @@typemetrics = Hash.new { |typehash,typename|
                typehash[typename] = Hash.new(0)
            }

            @@eventmetrics = Hash.new(0)

            @@metrics = {}
        end

        def Metric.clear
            Metric.init
        end

        def Metric.gather
            Metric.init

            # first gather stats about all of the types
            Puppet::Type.eachtype { |type|
                type.each { |instance|
                    hash = @@typemetrics[type]
                    hash[:total] += 1
                    if instance.managed?
                        hash[:managed] += 1
                    end
                }
            }

            # the rest of the metrics are injected directly by type.rb
        end

        def Metric.add(type,instance,metric,count)
            return unless defined? @@typemetrics
            case metric
            when :outofsync:
                @@typemetrics[type][metric] += count
            when :changes:
                @@typemetrics[type][:changed] += 1
                @@typemetrics[type][:totalchanges] += count
            else
                raise Puppet::DevError, "Unknown metric %s" % metric
            end
        end

        # we're currently throwing away the type and instance information
        def Metric.addevents(type,instance,events)
            return unless defined? @@eventmetrics
            events.each { |event|
                @@eventmetrics[event] += 1
            }
        end

        # Iterate across all of the metrics
        def Metric.each
            @@metrics.each { |name,metric|
                yield metric
            }
        end

        # I'm nearly positive this method is used only for testing
        def Metric.load(ary)
            @@typemetrics = ary[0]
            @@eventmetrics = ary[1]
        end

        def Metric.graph(range = nil)
            @@metrics.each { |name,metric|
                metric.graph(range)
            }
        end

        def Metric.store(time = nil)
            require 'RRD'
            unless time
                time = Time.now.to_i
            end
            @@metrics.each { |name,metric|
                metric.store(time)
            }
        end

        def Metric.tally
            type = Metric.new("typecount","Types")
            type.newvalue("Number",@@typemetrics.length)

            metrics = {
                :total => "Instances",
                :managed => "Managed Instances",
                :outofsync => "Out of Sync Instances",
                :changed => "Changed Instances",
                :totalchanges => "Total Number of Changes",
            }
            total = Hash.new(0)
            @@typemetrics.each { |type,instancehash|
                name = type.name.to_s
                instmet = Metric.new("type-" + name,name.capitalize)
                metrics.each { |symbol,label|
                    instmet.newvalue(symbol.to_s,instancehash[symbol],label)
                    total[symbol] += instancehash[symbol]
                }
            }

            totalmet = Metric.new("typetotals","Type Totals")
            metrics.each { |symbol,label|
                totalmet.newvalue(symbol.to_s,total[symbol],label)
            }

            eventmet = Metric.new("events")
            total = 0
            @@eventmetrics.each { |event,count|
                event = event.to_s
                # add the specific event as a value, with the label being a
                # capitalized version with s/_/ /g
                eventmet.newvalue(
                    event,
                    count,
                    event.capitalize.gsub(/_/,' ')
                )

                total += count
            }
            eventmet.newvalue("total",total,"Event Total")
        end

        attr_accessor :type, :name, :value, :label


        def create
            Puppet.config.use(:metrics)

            path = self.path
            args = [
                path,
                "--start", Time.now.to_i - 5,
                "--step", "300", # XXX Defaulting to every five minutes, but prob bad
            ]

            @values.each { |value|
                args.push "DS:%s:GAUGE:600:U:U" % value[0]
            }
            args.push "RRA:AVERAGE:0.5:1:300"

            begin
                RRD.create(*args)
            rescue => detail
                raise "Could not create RRD file %s: %s" % [path,detail]
            end
        end

        def initialize(name,label = nil)
            @name = name
            if label
                @label = label
            else
                @label = name.capitalize
            end

            @values = []
            if @@metrics.include?(self.name)
                raise "Somehow created two metrics with name %s" % self.name
            else
                @@metrics[self.name] = self
            end
        end

        def newvalue(name,value,label = nil)
            unless label
                label = name.capitalize
            end
            @values.push [name,label,value]
        end

        def path
            return File.join(Puppet[:rrddir],@name + ".rrd")
        end

        def graph(range = nil)
            args = [self.path.sub(/rrd$/,"png")]
            args.push("--title",self.label)
            args.push("--imgformat","PNG")
            args.push("--interlace")
            colorstack = %w{#ff0000 #00ff00 #0000ff #099000 #000990 #f00990}
            i = 0
            defs = []
            lines = []
            @values.zip(colorstack).each { |value,color|
                next if value.nil?
                # this actually uses the data label
                defs.push("DEF:%s=%s:%s:AVERAGE" % [value[0],self.path,value[0]])
                lines.push("LINE3:%s%s:%s" % [value[0],color,value[1]])
            }
            args << defs
            args << lines
            args.flatten!
            if range 
                args.push("--start",range[0],"--end",range[1])
            end

            begin
                RRD.graph(*args)
            rescue => detail
                Puppet.err "Failed to graph %s: %s" % [self.name,detail]
            end
        end

        def store(time)
            unless FileTest.exists?(File.join(Puppet[:rrddir],@name + ".rrd"))
                self.create
            end

            # XXX this is not terribly error-resistant
            args = [time]
            @values.each { |value|
                args.push value[2]
            }
            arg = args.join(":")
            begin
                RRD.update(self.path,args.join(":"))
            rescue => detail
                raise Puppet::Error, "Failed to update %s: %s" % [self.name,detail]
            end
        end
    end
end

# $Id$