Class: CycleChefHandler

Inherits:
Chef::Handler
  • Object
show all
Defined in:
lib/cycle_chef_handler.rb

Constant Summary collapse

VERSION =
'1.2.2'

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ CycleChefHandler

Returns a new instance of CycleChefHandler.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/cycle_chef_handler.rb', line 32

def initialize(params)
  defaults = {:exchange    => 'chef',
              :exchange_type => :direct,
              :exchange_durable => false,
              :exchange_autodelete => false,
              :bind_queue => false,
              :queue => nil,
              :queue_durable => false,
              :queue_autodelete => true,
              :routing_key => 'chef',
              :max_retries => 5,
              :retry_delay => 5}

  @amqp_config = defaults.merge(params[:amqp_config])
  check_amqp_config

  @extras = params[:extras] || {}
  @converge_index_file = params[:converge_index_file] || '/var/run/chef/converge_index'
  @failed_converge_file = params[:failed_converge_count_file] || '/var/run/chef/failed_converge_count'
end

Instance Method Details

#check_amqp_configObject



53
54
55
56
57
58
59
# File 'lib/cycle_chef_handler.rb', line 53

def check_amqp_config
  [:host, :exchange].each do |i|
    if not @amqp_config[i]
      raise ArgumentError, ":amqp_config missing value for #{i}"
    end
  end
end

#clear_count_file(count_file) ⇒ Object



200
201
202
203
204
# File 'lib/cycle_chef_handler.rb', line 200

def clear_count_file(count_file)
  if File.exist? count_file
    FileUtils.rm count_file
  end
end

#create_adObject



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
# File 'lib/cycle_chef_handler.rb', line 131

def create_ad
  ad = ClassAd.new
  ad['AdType']              = 'Chef.Host'
  ad['ChefNode']            = Chef::Config[:node_name]
  ad['ConvergeStartTime']   = start_time
  ad['ConvergeEndTime']     = end_time
  ad['ConvergeElapsedTime'] = RelativeTime.new(elapsed_time)

  updated = []
  if not updated_resources.nil?
    updated = updated_resources.map {|x| x.to_s}
  end

  ad['UpdatedResources']      = updated
  ad['UpdatedResourcesCount'] = updated.size
  ad['ConvergeIndex']         = increment_count_file(@converge_index_file)
  ad['ChefServerUrl']         = Chef::Config[:chef_server_url]
  ad['ChefServerHostName']    = URI.parse(Chef::Config[:chef_server_url]).host
  ad['ChefClientVersion']     = Chef::VERSION
  ad['CycleChefHandlerVersion'] = CycleChefHandler::VERSION
  ad['Success']               = success?

  exception = nil
  backtrace = nil
  if failed?
    exception = run_status.formatted_exception
    backtrace = run_status.backtrace
    ad['FailedConvergeCount'] = increment_count_file(@failed_converge_file)
  else
    clear_count_file(@failed_converge_file)
    ad['FailedConvergeCount'] = 0
  end

  ad['Exception']             = exception
  ad['Backtrace']             = backtrace

  @extras.each do |k,v|
    ad[k] = v
  end

  ad
end

#increment_count_file(count_file) ⇒ Object



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
# File 'lib/cycle_chef_handler.rb', line 174

def increment_count_file(count_file)
  file_dir = File.dirname(count_file)
  if not File.directory? file_dir
    FileUtils.mkdir_p file_dir
  end
 
  count = nil
  if File.exists? count_file
    File.open(count_file) do |file|
      count = file.readline.chomp.to_i
    end
  end

  if count.nil?
    count = 1
  else
    count += 1
  end

  File.open(count_file, "w") do |file|
    file.puts(count)
  end
    
  count
end

#reportObject



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
# File 'lib/cycle_chef_handler.rb', line 62

def report

  ## Create and Post a classad
  ad = create_ad
  payload = "<classads>" + ad.to_xml + "</classads>"
  
  for attempt in 1..@amqp_config[:max_retries] do
    begin

      b = Bunny.new(@amqp_config)

      b.start
      e = b.exchange(@amqp_config[:exchange], 
                    :type        => @amqp_config[:exchange_type],
                    :durable     => @amqp_config[:exchange_durable], 
                    :auto_delete => @amqp_config[:exchange_autodelete])

      # in some cases, the user may want to declare and bind a queue
      # to the exchange so consumers get all messages, even ones that 
      # enter the exchange before the consumer exists.
      if @amqp_config[:bind_queue]
        q = b.queue(@amqp_config[:queue], 
                   :durable     => @amqp_config[:queue_durable],
                   :auto_delete => @amqp_config[:queue_autodelete])

        if not @amqp_config[:routing_key].nil?

          q.bind(@amqp_config[:exchange], :key => @amqp_config[:routing_key])

        else

          q.bind(@amqp_config[:exchange])

        end

      end

      if not @amqp_config[:routing_key].nil?

        e.publish(payload, :key => @amqp_config[:routing_key])

      else
        
        e.publish(payload)
      
      end

      Chef::Log.info("Posted converge history report")
      return

    rescue Exception => e
      if attempt < @amqp_config[:max_retries]
        delay = attempt * @amqp_config[:retry_delay]
        Chef::Log.error("Failed to post converge history report, retrying in #{delay} seconds...")
        sleep(delay)  # Sleep for a while if it's a transient communcation error then try again
      else
        trace = e.backtrace.join("\n")
        Chef::Log.error("Failed to post converge history report: #{e.message} #{trace}")
        return
      end

    ensure

      b.stop

    end
  end
end