aboutsummaryrefslogtreecommitdiff
path: root/lib/mauve/alert.rb
blob: 7768f50d6e82a32bee680962c4460a6ba574f28a (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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
require 'mauve/proto'
require 'mauve/alert_changed'
require 'mauve/datamapper'
require 'sanitize'

module Mauve
  class AlertEarliestDate
 
    include DataMapper::Resource
    
    property :id, Serial
    property :alert_id, Integer
    property :earliest, DateTime
    belongs_to :alert, :model => "Alert"
    
    # 1) Shame we can't get this called automatically from DataMapper.auto_upgrade!
    #
    # 2) Can't use a neater per-connection TEMPORARY VIEW because the pooling 
    # function causes the connection to get dropped occasionally, and we can't
    # hook the reconnect function (that I know of).
    #
    # http://www.mail-archive.com/datamapper@googlegroups.com/msg02314.html
    #
    def self.create_view!
      the_distant_future = MauveTime.now + 86400000 # it is the year 2000 - the humans are dead
      ["BEGIN TRANSACTION",
       "DROP VIEW IF EXISTS mauve_alert_earliest_dates",
       "CREATE VIEW 
          mauve_alert_earliest_dates
        AS
        SELECT 
          id AS alert_id,
          NULLIF(
            MIN(
              IFNULL(will_clear_at, '#{the_distant_future}'),
              IFNULL(will_raise_at, '#{the_distant_future}'),
              IFNULL(will_unacknowledge_at,  '#{the_distant_future}')
            ),
            '#{the_distant_future}'
          ) AS earliest
        FROM mauve_alerts 
        WHERE
          will_clear_at IS NOT NULL OR
          will_raise_at IS NOT NULL OR
          will_unacknowledge_at IS NOT NULL
      ",
      "END TRANSACTION"].each do |statement|
        repository(:default).adapter.execute(statement.gsub(/\s+/, " "))
      end
    end

  end
  
  class Alert
    def bytesize; 99; end
    def size; 99; end
    
    include DataMapper::Resource
    
    property :id, Serial
    property :alert_id, String, :required => true, :unique_index => :alert_index, :length=>256
    property :source, String, :required => true, :unique_index => :alert_index, :length=>512
    property :subject, String, :length=>512, :length=>512
    property :summary, String, :length=>1024
    property :detail, Text, :length=>65535
    property :importance, Integer, :default => 50

    property :raised_at, DateTime
    property :cleared_at, DateTime
    property :updated_at, DateTime
    property :acknowledged_at, DateTime
    property :acknowledged_by, String
    property :update_type, String
    
    property :will_clear_at, DateTime
    property :will_raise_at, DateTime
    property :will_unacknowledge_at, DateTime
#    property :will_unacknowledge_after, Integer
    
    has n, :changes, :model => AlertChanged
    has 1, :alert_earliest_date

    validates_with_method :check_dates
    
    def to_s
      "#<Alert:#{id} #{alert_id} from #{source} update_type #{update_type}>"
    end
   
    def check_dates
      bad_dates = self.attributes.find_all do |key, value|
        value.is_a?(DateTime) and not (DateTime.new(2000,1,1,0,0,0)..DateTime.new(2020,1,1,0,0,0)).include?(value)
      end

      if bad_dates.empty?
        true
      else
        [ false, "The dates "+bad_dates.collect{|k,v| "#{v.to_s} (#{k})"}.join(", ")+" are invalid." ]
      end
    end

    default_scope(:default).update(:order => [:source, :importance])
   
    def logger
      Log4r::Logger.new(self.class.to_s)
    end

    def time_relative(secs)
      secs = secs.to_i.abs
      case secs
        when 0..59 then "just now"
        when 60..3599 then "#{secs/60}m ago"
        when 3600..86399 then "#{secs/3600}h ago"
        else
          days = secs/86400
          days == 1 ? "yesterday" : "#{secs/86400} days ago"
      end
    end

    #
    # AlertGroup.matches must always return a an array of groups.
    #
    def alert_group
      @alert_group ||= AlertGroup.matches(self).first
    end

    #
    #
    #
    def level
      @level ||= self.alert_group.level
    end
  
    def sort_tuple
      [AlertGroup::LEVELS.index(self.level), (self.raised_at || self.cleared_at || Time.now).to_time]
    end

    def <=>(other)
      other.sort_tuple <=> self.sort_tuple
    end
 
    def subject; attribute_get(:subject) || attribute_get(:source) || "not set" ; end
    def detail;  attribute_get(:detail)  || "_No detail set._" ; end
 
    def subject=(subject); set_changed_if_different( :subject, subject ); end
    def summary=(summary); set_changed_if_different( :summary, summary ); end

    # def source=(source);   attribute_set( :source, source ); end 
    # def detail=(detail);   attribute_set( :detail, detail ); end
    
    protected

    def set_changed_if_different(attribute, value)
      return if self.__send__(attribute) == value
      self.update_type ||= :changed
      attribute_set(attribute.to_sym, value)
    end
    
    public
    
    def acknowledge!(person, ack_until = Time.now+3600)
      raise ArgumentError unless person.is_a?(Person)
      raise ArgumentError unless ack_until.is_a?(Time)
  
      self.acknowledged_by = person.username
      self.acknowledged_at = MauveTime.now
      self.will_unacknowledge_at = ack_until
      self.update_type = :acknowledged

      logger.error("Couldn't save #{self}") unless save
      AlertGroup.notify([self]) if self.raised?
    end
    
    def unacknowledge!
      self.acknowledged_by = nil
      self.acknowledged_at = nil
      self.will_unacknowledge_at = nil
      self.update_type = (raised? ? :raised : :cleared)

      logger.error("Couldn't save #{self}") unless save
      AlertGroup.notify([self]) if self.raised?
    end
    
    def raise!
      already_raised = raised? && !acknowledged?
      self.acknowledged_by = nil
      self.acknowledged_at = nil
      self.will_unacknowledge_at = nil
      self.raised_at = MauveTime.now
      self.will_raise_at = nil
      self.cleared_at = nil
      # Don't clear will_clear_at
      self.update_type = :raised

      logger.error("Couldn't save #{self}") unless save
      AlertGroup.notify([self]) unless already_raised
    end
    
    def clear!(notify=true)
      already_cleared = cleared?
      self.acknowledged_by = nil
      self.acknowledged_at = nil
      self.will_unacknowledge_at = nil
      self.raised_at = nil
      # Don't clear will_raise_at
      self.cleared_at = MauveTime.now
      self.will_clear_at = nil
      self.update_type = :cleared

      logger.error("Couldn't save #{self}") unless save
      AlertGroup.notify([self]) unless !notify || already_cleared
    end
      
    # Returns the time at which a timer loop should call poll_event to either
    # raise, clear or unacknowldge this event.
    # 
    def due_at
      o = [will_clear_at, will_raise_at, will_unacknowledge_at].compact.sort[0]
      o ? o.to_time : nil
    end
    
    def poll
      raise! if (will_unacknowledge_at and will_unacknowledge_at.to_time <= MauveTime.now) or
        (will_raise_at and will_raise_at.to_time <= MauveTime.now)
      clear! if will_clear_at && will_clear_at.to_time <= MauveTime.now
    end
    
    def raised?
      !raised_at.nil? and (cleared_at.nil? or raised_at > cleared_at)
    end
    
    def acknowledged?
      !acknowledged_at.nil?
    end
    
    def cleared?
      !raised? 
    end
  
    class << self
    
      #
      # Utility methods to clean/remove html
      #
      def remove_html(txt)
        Sanitize.clean(
          txt.to_s,
          Sanitize::Config::DEFAULT
        )
      end

      def clean_html(txt)
        Sanitize.clean(
          txt.to_s,
         Sanitize::Config::RELAXED.merge({:remove_contents => true})
        )
      end
    
      #
      # Find stuff
      #
      #
      def all_raised
        all(:raised_at.not => nil, :cleared_at => nil) - all_acknowledged
      end

      def all_acknowledged
        all(:acknowledged_at.not => nil)
      end

      def all_cleared
        all(:cleared_at.not => nil) - all_acknowledged
      end

      # Returns a hash of all the :urgent, :normal and :low alerts.
      #
      # @return [Hash] A hash with the relevant alerts per level
      def get_all ()
        hash = Hash.new
        hash[:urgent] = Array.new
        hash[:normal] = Array.new
        hash[:low] = Array.new
        all().each do |iter|
          next if true == iter.cleared?
          hash[AlertGroup.matches(iter)[0].level] << iter
        end
        return hash
      end

      # 
      # Returns the next Alert that will have a timed action due on it, or nil
      # if none are pending.
      #
      def find_next_with_event
        earliest_alert = AlertEarliestDate.first(:order => [:earliest])
        earliest_alert ? earliest_alert.alert : nil
      end

      def all_overdue(at = MauveTime.now)
        AlertEarliestDate.all(:earliest.lt => at, :order => [:earliest]).collect do |earliest_alert|
          earliest_alert ? earliest_alert.alert : nil
        end
      end
     
      #
      # Receive an AlertUpdate buffer from the wire.
      #
      def receive_update(update, reception_time = MauveTime.now)

        update = Proto::AlertUpdate.parse_from_string(update) unless update.kind_of?(Proto::AlertUpdate)

        alerts_updated = []
        
        logger.debug("Alert update received from wire: #{update.inspect.split.join(", ")}")
        
        #
        # Transmission time helps us determine any time offset
        #
        if update.transmission_time and update.transmission_time > 0
          transmission_time = MauveTime.at(update.transmission_time) 
        else
          transmission_time = reception_time
        end

        time_offset = (reception_time - transmission_time).round

        logger.debug("Update received from a host #{time_offset}s behind") if time_offset.abs > 5

        #
        # Make sure there is no HTML in the update source.
        #
        update.source = Alert.remove_html(update.source)

        # Update each alert supplied
        #
        update.alert.each do |alert|
          # 
          # Infer some actions from our pure data structure (hmm, wonder if
          # this belongs in our protobuf-derived class?
          #
          clear_time = alert.clear_time == 0 ? nil : MauveTime.at(alert.clear_time + time_offset)
          raise_time = alert.raise_time == 0 ? nil : MauveTime.at(alert.raise_time + time_offset)

          if raise_time.nil? && clear_time.nil?
            #
            # Make sure that we raise if neither raise nor clear is set
            #
            logger.warn("No clear time or raise time set.  Assuming raised!")

            raise_time = reception_time 
          end

          #
          # Make sure there's no HTML in the ID... paranoia.  The rest of the
          # HTML removal is done elsewhere.
          #
          alert.id = Alert.remove_html(alert.id)
 
          alert_db = first(:alert_id => alert.id, :source => update.source) ||
            new(:alert_id => alert.id, :source => update.source)

          #
          # Work out what state the alert was in before receiving this update.
          #
          was_raised       = alert_db.raised?
          was_cleared      = alert_db.cleared?
          was_acknowledged = alert_db.acknowledged?
                    
          alert_db.update_type = nil
          
          ##
          #
          # Work out if we're raising now, or in the future.
          #
          # Allow a 5s offset in timings.
          #
          if raise_time
            if raise_time <= (reception_time + 5)
              #
              # Don't reset the raised_at time if the alert is already raised.
              # This prevents the raised time constantly changing on alerts
              # that are already raised.
              #
              alert_db.raised_at     = raise_time unless was_raised or alert_db.raised_at.nil?
              alert_db.will_raise_at = nil
            else
              alert_db.raised_at     = nil
              alert_db.will_raise_at = raise_time
            end
          end

          if clear_time
            if clear_time <= (reception_time + 5)
              #
              # Don't reset the cleared_at time (see above for raised_at timings).
              #
              alert_db.cleared_at    = clear_time unless was_cleared or alert_db.cleared_at.nil?
              alert_db.will_clear_at = nil
            else
              alert_db.cleared_at    = nil
              alert_db.will_clear_at = clear_time
            end
          end

          # 
          # Clear old cleared_at time, if the raised_at time is newer
          #
          if alert_db.cleared_at && alert_db.raised_at && alert_db.cleared_at < alert_db.raised_at
            alert_db.cleared_at = nil 
          end
         
          if alert_db.cleared?
            alert_db.update_type = :cleared
          else
            alert_db.update_type = :raised
          end
          
          #
          # If the alert is cleared ,or has just been raised unset the acknowledge dates. 
          #
          if alert_db.acknowledged? and (alert_db.cleared? or (alert_db.raised? and !was_raised))
            alert_db.acknowledged_at = nil 
          end

          #
          # Set the subject
          #
          if alert.subject and !alert.subject.empty?
            alert_db.subject = Alert.remove_html(alert.subject)
          else
            alert_db.subject = alert_db.source
          end

          alert_db.summary = Alert.remove_html(alert.summary) if alert.summary && !alert.summary.empty?

          #
          # The detail can be HTML -- scrub out unwanted parts.
          #
          alert_db.detail = Alert.clean_html(alert.detail)    if alert.detail  && !alert.detail.empty?

          alert_db.importance = alert.importance if alert.importance != 0 

          alert_db.update_type = :changed unless alert_db.update_type

          #
          # This decides if we notify.
          #
          should_notify = case alert_db.update_type.to_sym
            when :raised
              !was_raised
            when :acknowledged
              !was_acknowledged
            when :cleared
              !was_cleared
            else
              alert_db.raised?              
          end

          alerts_updated << alert_db if should_notify

          alert_db.updated_at = reception_time 

          logger.debug "Saving #{alert_db}"

          if !alert_db.save
            if alert_db.errors.respond_to?("full_messages")
              msg = alert_db.errors.full_messages
            else
              msg = alert_db.errors.inspect
            end
            logger.error "Couldn't save update #{alert} because of #{msg}" 
          end
        end
        
        # If this is a complete replacement update, find the other alerts
        # from this source and clear them.
        #
        if update.replace
          alert_ids_mentioned = update.alert.map { |alert| alert.id }
          logger.debug "Replacing all alerts from #{update.source} except "+alert_ids_mentioned.join(",")
          all(:source => update.source, 
              :alert_id.not => alert_ids_mentioned,
              :cleared_at => nil
              ).each do |alert_db|
            logger.debug "Replace: clearing #{alert_db.id}"
            alert_db.clear!(false)
            alerts_updated << alert_db
          end
        end
       
        logger.debug "Got #{alerts_updated.length} alerts to notify about" if alerts_updated.length > 0
 
        AlertGroup.notify(alerts_updated)
      end

      def logger
        Log4r::Logger.new("Mauve::Alert")
      end
    end
  end
end