Class: Chef::Application::DeployApplication

Inherits:
Chef::Application
  • Object
show all
Defined in:
lib/chef-deploy-application/application.rb

Constant Summary collapse

SELF_PIPE =

Mimic self_pipe sleep from Unicorn to capture signals safely

[]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDeployApplication

Returns a new instance of DeployApplication.



102
103
104
105
106
107
108
# File 'lib/chef-deploy-application/application.rb', line 102

def initialize
  super

  @apps = []
  @chef_client = nil
  @chef_client_json = nil
end

Instance Attribute Details

#chef_client_jsonObject (readonly)

Returns the value of attribute chef_client_json.



100
101
102
# File 'lib/chef-deploy-application/application.rb', line 100

def chef_client_json
  @chef_client_json
end

Instance Method Details

#configure_chefObject



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/chef-deploy-application/application.rb', line 152

def configure_chef
  @apps = parse_options

  begin
    case config[:config_file]
    when /^(http|https):\/\//
      Chef::REST.new("", nil, nil).fetch(config[:config_file]) { |f| apply_config(f.path) }
    else
      ::File::open(config[:config_file]) { |f| apply_config(f.path) }
    end
  rescue SocketError => error
    Chef::Application.fatal!("Error getting config file #{Chef::Config[:config_file]}", 2)
  rescue Exception => error
    Chef::Log.warn("*****************************************")
    Chef::Log.warn("Can not find config file: #{config[:config_file]}, using defaults.")
    Chef::Log.warn("#{error.message}")
    Chef::Log.warn("*****************************************")

    Chef::Config.merge!(config)
  end

end

#configure_loggingObject



175
176
177
178
179
# File 'lib/chef-deploy-application/application.rb', line 175

def configure_logging
  super
  Mixlib::Authentication::Log.use_log_devices( Chef::Log )
  Ohai::Log.use_log_devices( Chef::Log )
end

#reconfigureObject

Reconfigure the chef client Re-open the JSON attributes and load them into the node



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
# File 'lib/chef-deploy-application/application.rb', line 112

def reconfigure
  super

  Chef::Config[:chef_server_url] = config[:chef_server_url] if config.has_key? :chef_server_url
  unless Chef::Config[:exception_handlers].any? {|h| Chef::Handler::ErrorReport === h}
    Chef::Config[:exception_handlers] << Chef::Handler::ErrorReport.new
  end

  # Run chef once and exit
  Chef::Config[:interval] = nil
  Chef::Config[:splay] = nil

  if Chef::Config[:json_attribs]
    begin
      json_io = case Chef::Config[:json_attribs]
                when /^(http|https):\/\//
                  @rest = Chef::REST.new(Chef::Config[:json_attribs], nil, nil)
                  @rest.get_rest(Chef::Config[:json_attribs], true).open
                else
                  open(Chef::Config[:json_attribs])
                end
    rescue SocketError => error
      Chef::Application.fatal!("I cannot connect to #{Chef::Config[:json_attribs]}", 2)
    rescue Errno::ENOENT => error
      Chef::Application.fatal!("I cannot find #{Chef::Config[:json_attribs]}", 2)
    rescue Errno::EACCES => error
      Chef::Application.fatal!("Permissions are incorrect on #{Chef::Config[:json_attribs]}. Please chmod a+r #{Chef::Config[:json_attribs]}", 2)
    rescue Exception => error
      Chef::Application.fatal!("Got an unexpected error reading #{Chef::Config[:json_attribs]}: #{error.message}", 2)
    end

    begin
      @chef_client_json = Chef::JSONCompat.from_json(json_io.read)
      json_io.close unless json_io.closed?
    rescue JSON::ParserError => error
      Chef::Application.fatal!("Could not parse the provided JSON file (#{Chef::Config[:json_attribs]})!: " + error.message, 2)
    end
  end
end

#run_applicationObject

Run the chef client, optionally daemonizing or looping at intervals.



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
# File 'lib/chef-deploy-application/application.rb', line 186

def run_application
  if no_app_name_given?
    puts "You must provide the name of an application to deploy."
    exit 1
  end

  begin
    Chef::Log.info("*** Chef #{Chef::VERSION} ***")

    # Make sure the client knows this is not chef solo
    Chef::Config[:solo] = false

    # Rebuild node
    client = Chef::Client.new
    client.run_ohai
    client.register
    client.build_node


    # Shorten node inspection
    node = client.node
    def node.inspect
      "<Chef::Node:0x#{self.object_id.to_s(16)} @name=\"#{self.name}\">"
    end

    # Rebuild context
    run_status = Chef::RunStatus.new(node)
    Chef::Cookbook::FileVendor.on_create { |manifest| Chef::Cookbook::RemoteFileVendor.new(manifest, Chef::REST.new(Chef::Config[:server_url])) }
    cookbook_hash = client.sync_cookbooks
    cookbooks = Chef::CookbookCollection.new(cookbook_hash)

    run_context = Chef::RunContext.new(node, cookbooks)
    run_context.load(Chef::RunList::RunListExpansionFromAPI.new(node.chef_environment, []))
    run_status.run_context = run_context

    # Merge json
    node.consume_attributes(@chef_client_json) if @chef_client_json

    # Setup the recipe
    app_name = application_name
    recipe = Chef::Recipe.new(nil, nil, run_context)
    recipe.instance_eval do
      # Run the applications cookbook
      node.run_state[:seen_recipes].delete(app_name)
      include_recipe app_name
      
      app = search(:apps, "id:#{app_name}").first
      raise "Cannot find an application named #{app_name}" unless app

      server_roles = (app["server_roles"] & node.run_list.roles)
      if server_roles.empty?
        Chef::Log.info("None of this server's roles match the app's server_roles. Double-check the server_roles configured in the app's data bag.")
      else
        server_roles.each do |app_role|
          app["type"][app_role].each do |thing|
            recipe_name = "application::#{thing}"
            node.run_state[:current_app] = app
            node.run_state[:seen_recipes].delete(recipe_name)
            include_recipe recipe_name
          end
        end
      end

      node.run_state.delete(:current_app)
    end


    # Run the recipe
    run_status.start_clock
    Chef::Runner.new(run_context).converge

    run_status.stop_clock
    Chef::Log.info("Chef Deploy complete in #{run_status.elapsed_time} seconds")

    Chef::Application.exit! "Exiting", 0
  rescue SystemExit => e
    raise
  rescue Exception => e
    Chef::Application.debug_stacktrace(e)
    Chef::Application.fatal!("#{e.class}: #{e.message}", 1)
  end
end

#setup_applicationObject



181
182
183
# File 'lib/chef-deploy-application/application.rb', line 181

def setup_application
  Chef::Daemon.change_privilege
end