summaryrefslogtreecommitdiff
path: root/lib/chef/handler.rb
blob: 97562ea31bd707e577a434584846744c47d94c8c (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
#--
# Author:: Adam Jacob (<adam@chef.io>)
# Copyright:: Copyright (c) Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require_relative "client"
require "forwardable" unless defined?(Forwardable)

class Chef
  # The base class for an Exception or Notification Handler. Create your own
  # handler by subclassing Chef::Handler. When a Chef run fails with an
  # uncaught Exception, Chef will set the +run_status+ on your handler and call
  # +report+
  #
  # @example
  #   require 'net/smtp'
  #
  #   module MyOrg
  #     class OhNoes < Chef::Handler
  #
  #       def report
  #         # Create the email message
  #         message  = "From: Your Name <your@mail.address>\n"
  #         message << "To: Destination Address <someone@example.com>\n"
  #         message << "Subject: Chef Run Failure\n"
  #         message << "Date: #{Time.now.rfc2822}\n\n"
  #
  #         # The Node is available as +node+
  #         message << "Chef run failed on #{node.name}\n"
  #         # +run_status+ is a value object with all of the run status data
  #         message << "#{run_status.formatted_exception}\n"
  #         # Join the backtrace lines. Coerce to an array just in case.
  #         message << Array(backtrace).join("\n")
  #
  #         # Send the email
  #         Net::SMTP.start('your.smtp.server', 25) do |smtp|
  #           smtp.send_message message, 'from@address', 'to@address'
  #         end
  #       end
  #
  #     end
  #   end
  #
  class Handler

    def self.handler_for(*args)
      if args.include?(:start)
        Chef::Config[:start_handlers] ||= []
        Chef::Config[:start_handlers] |= [self]
      end
      if args.include?(:report)
        Chef::Config[:report_handlers] ||= []
        Chef::Config[:report_handlers] |= [self]
      end
      if args.include?(:exception)
        Chef::Config[:exception_handlers] ||= []
        Chef::Config[:exception_handlers] |= [self]
      end
    end

    # The list of currently configured start handlers
    def self.start_handlers
      Array(Chef::Config[:start_handlers])
    end

    def self.resolve_handler_instance(handler)
      if handler.is_a?(Class)
        if handler.respond_to?(:instance)
          # support retrieving a Singleton reporting object
          handler.instance
        else
          # just a class with no way to insert data
          handler.new
        end
      else
        # the Chef::Config array contains an instance, not a class
        handler
      end
    end

    # Run the start handlers. This will usually be called by a notification
    # from Chef::Client
    def self.run_start_handlers(run_status)
      Chef::Log.info("Running start handlers")
      start_handlers.each do |handler|
        handler = resolve_handler_instance(handler)
        handler.run_report_safely(run_status)
      end
      Chef::Log.info("Start handlers complete.")
    end

    # Wire up a notification to run the start handlers when the chef run
    # starts.
    Chef::Client.when_run_starts do |run_status|
      run_start_handlers(run_status)
    end

    # The list of currently configured report handlers
    def self.report_handlers
      Array(Chef::Config[:report_handlers])
    end

    # Run the report handlers. This will usually be called by a notification
    # from Chef::Client
    def self.run_report_handlers(run_status)
      events = run_status.events
      events.handlers_start(report_handlers.size)
      Chef::Log.info("Running report handlers")
      report_handlers.each do |handler|
        handler = resolve_handler_instance(handler)
        handler.run_report_safely(run_status)
        events.handler_executed(handler)
      end
      events.handlers_completed
      Chef::Log.info("Report handlers complete")
    end

    # Wire up a notification to run the report handlers if the chef run
    # succeeds.
    Chef::Client.when_run_completes_successfully do |run_status|
      run_report_handlers(run_status)
    end

    # The list of currently configured exception handlers
    def self.exception_handlers
      Array(Chef::Config[:exception_handlers])
    end

    # Run the exception handlers. Usually will be called by a notification
    # from Chef::Client when the run fails.
    def self.run_exception_handlers(run_status)
      events = run_status.events
      events.handlers_start(exception_handlers.size)
      Chef::Log.error("Running exception handlers")
      exception_handlers.each do |handler|
        handler = resolve_handler_instance(handler)
        handler.run_report_safely(run_status)
        events.handler_executed(handler)
      end
      events.handlers_completed
      Chef::Log.error("Exception handlers complete")
    end

    # Wire up a notification to run the exception handlers if the chef run fails.
    Chef::Client.when_run_fails do |run_status|
      run_exception_handlers(run_status)
    end

    extend Forwardable

    # The Chef::RunStatus object containing data about the Chef run.
    attr_reader :run_status

    ##
    # :method: start_time
    #
    # The time the chef run started
    def_delegator :@run_status, :start_time

    ##
    # :method: end_time
    #
    # The time the chef run ended
    def_delegator :@run_status, :end_time

    ##
    # :method: elapsed_time
    #
    # The time elapsed between the start and finish of the chef run
    def_delegator :@run_status, :elapsed_time

    ##
    # :method: run_context
    #
    # The Chef::RunContext object used by the chef run
    def_delegator :@run_status, :run_context

    ##
    # :method: exception
    #
    # The uncaught Exception that terminated the chef run, or nil if the run
    # completed successfully
    def_delegator :@run_status, :exception

    ##
    # :method: backtrace
    #
    # The backtrace captured by the uncaught exception that terminated the chef
    # run, or nil if the run completed successfully
    def_delegator :@run_status, :backtrace

    ##
    # :method: node
    #
    # The Chef::Node for this client run
    def_delegator :@run_status, :node

    ##
    # :method: all_resources
    #
    # An Array containing all resources in the chef run's resource_collection
    def_delegator :@run_status, :all_resources

    ##
    # :method: updated_resources
    #
    # An Array containing all resources that were updated during the chef run
    def_delegator :@run_status, :updated_resources

    ##
    # :method: success?
    #
    # Was the chef run successful? True if the chef run did not raise an
    # uncaught exception
    def_delegator :@run_status, :success?

    ##
    # :method: failed?
    #
    # Did the chef run fail? True if the chef run raised an uncaught exception
    def_delegator :@run_status, :failed?

    # The main entry point for report handling. Subclasses should override this
    # method with their own report handling logic.
    def report; end

    # Runs the report handler, rescuing and logging any errors it may cause.
    # This ensures that all handlers get a chance to run even if one fails.
    # This method should not be overridden by subclasses unless you know what
    # you're doing.
    #
    # @api private
    def run_report_safely(run_status)
      run_report_unsafe(run_status)
    rescue Exception => e
      Chef::Log.error("Report handler #{self.class.name} raised #{e.inspect}")
      Array(e.backtrace).each { |line| Chef::Log.error(line) }
    ensure
      @run_status = nil
    end

    # Runs the report handler without any error handling. This method should
    # not be used directly except in testing.
    def run_report_unsafe(run_status)
      @run_status = run_status
      report
    end

    # Return the Hash representation of the run_status
    def data
      @run_status.to_h
    end

  end
end