Class: Chef::Environment

Inherits:
Object show all
Includes:
IndexQueue::Indexable, Mixin::FromFile, Mixin::ParamsValidate
Defined in:
lib/chef/environment.rb

Constant Summary collapse

DEFAULT =
"default"
COMBINED_COOKBOOK_CONSTRAINT =
/(.+)(?:[\s]+)((?:#{Chef::VersionConstraint::OPS.join('|')})(?:[\s]+).+)$/.freeze
DESIGN_DOCUMENT =
{
  "version" => 1,
  "language" => "javascript",
  "views" => {
    "all" => {
      "map" => <<-EOJS
      function(doc) {
        if (doc.chef_type == "environment") {
          emit(doc.name, doc);
        }
      }
      EOJS
    },
    "all_id" => {
      "map" => <<-EOJS
      function(doc) {
        if (doc.chef_type == "environment") {
          emit(doc.name, doc.name);
        }
      }
      EOJS
    }
  }
}

Instance Attribute Summary collapse

Attributes included from IndexQueue::Indexable

#index_id

Class Method Summary collapse

Instance Method Summary collapse

Methods included from IndexQueue::Indexable

#add_to_index, #delete_from_index, included, #index_object_type, #with_indexer_metadata

Methods included from Mixin::FromFile

#class_from_file, #from_file

Methods included from Mixin::ParamsValidate

#set_or_return, #validate

Constructor Details

#initialize(couchdb = nil) ⇒ Environment

Returns a new instance of Environment


68
69
70
71
72
73
74
75
76
77
# File 'lib/chef/environment.rb', line 68

def initialize(couchdb=nil)
  @name = ''
  @description = ''
  @default_attributes = Mash.new
  @override_attributes = Mash.new
  @cookbook_versions = Hash.new
  @couchdb_rev = nil
  @couchdb_id = nil
  @couchdb = couchdb || Chef::CouchDB.new
end

Instance Attribute Details

#couchdbObject

Returns the value of attribute couchdb


40
41
42
# File 'lib/chef/environment.rb', line 40

def couchdb
  @couchdb
end

#couchdb_idObject

Returns the value of attribute couchdb_id


41
42
43
# File 'lib/chef/environment.rb', line 41

def couchdb_id
  @couchdb_id
end

#couchdb_revObject

Returns the value of attribute couchdb_rev


40
41
42
# File 'lib/chef/environment.rb', line 40

def couchdb_rev
  @couchdb_rev
end

Class Method Details

.cdb_list(inflate = false, couchdb = nil) ⇒ Object


260
261
262
263
264
# File 'lib/chef/environment.rb', line 260

def self.cdb_list(inflate=false, couchdb=nil)
  es = (couchdb || Chef::CouchDB.new).list("environments", inflate)
  lookup = (inflate ? "value" : "key")
  es["rows"].collect { |e| e[lookup] }
end

.cdb_load(name, couchdb = nil) ⇒ Object


275
276
277
# File 'lib/chef/environment.rb', line 275

def self.cdb_load(name, couchdb=nil)
  (couchdb || Chef::CouchDB.new).load("environment", name)
end

.cdb_load_filtered_cookbook_versions(name, couchdb = nil) ⇒ Object

Loads the set of Chef::CookbookVersion objects available to a given environment

Returns

Hash i.e.

"cookbook_name" => [ Chef::CookbookVersion ... ] ## the array of CookbookVersions is sorted highest to lowest

There will be a key for every cookbook. If no CookbookVersions are available for the specified environment the value will be an empty list.


335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/chef/environment.rb', line 335

def self.cdb_load_filtered_cookbook_versions(name, couchdb=nil)
  version_constraints = cdb_load(name, couchdb).cookbook_versions.inject({}) {|res, (k,v)| res[k] = Chef::VersionConstraint.new(v); res}

  # inject all cookbooks into the hash while filtering out restricted versions, then sort the individual arrays
  cookbook_list = Chef::CookbookVersion.cdb_list(true, couchdb)

  filtered_list = cookbook_list.inject({}) do |res, cookbook|
    # FIXME: should cookbook.version return a Chef::Version?
    version               = Chef::Version.new(cookbook.version)
    requirement_satisfied = version_constraints.has_key?(cookbook.name) ? version_constraints[cookbook.name].include?(version) : true
    # we want a key for every cookbook, even if no versions are available
    res[cookbook.name] ||= []
    res[cookbook.name] << cookbook if requirement_satisfied
    res
  end

  sorted_list = filtered_list.inject({}) do |res, (cookbook_name, versions)|
    res[cookbook_name] = versions.sort.reverse
    res
  end

  sorted_list
end

.cdb_load_filtered_recipe_list(name, couchdb = nil) ⇒ Object


400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/chef/environment.rb', line 400

def self.cdb_load_filtered_recipe_list(name, couchdb=nil)
  cdb_load_filtered_cookbook_versions(name, couchdb).map do |cb_name, cb|
    if cb.empty?            # no available versions
      []                    # empty list elided with flatten
    else
      latest_version = cb.first
      latest_version.recipe_filenames_by_name.keys.map do |recipe|
        case recipe
        when DEFAULT
          cb_name
        else
          "#{cb_name}::#{recipe}"
        end
      end
    end
  end.flatten
end

.cdb_minimal_filtered_versions(name, couchdb = nil) ⇒ Object

Like cdb_load_filtered_cookbook_versions, loads the set of cookbooks available in a given environment. The difference is that this method will load Chef::MinimalCookbookVersion objects that contain only the information necessary for solving a cookbook collection for a given run list. The user of this method must call Chef::MinimalCookbookVersion.load_full_versions_of() after solving the cookbook collection to get the full objects.

Returns

Hash i.e.

"cookbook_name" => [ Chef::CookbookVersion ... ] ## the array of CookbookVersions is sorted highest to lowest

There will be a key for every cookbook. If no CookbookVersions are available for the specified environment the value will be an empty list.


376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/chef/environment.rb', line 376

def self.cdb_minimal_filtered_versions(name, couchdb=nil)
  version_constraints = cdb_load(name, couchdb).cookbook_versions.inject({}) {|res, (k,v)| res[k] = Chef::VersionConstraint.new(v); res}

  # inject all cookbooks into the hash while filtering out restricted versions, then sort the individual arrays
  cookbook_list = Chef::MinimalCookbookVersion.load_all(couchdb)

  filtered_list = cookbook_list.inject({}) do |res, cookbook|
    # FIXME: should cookbook.version return a Chef::Version?
    version               = Chef::Version.new(cookbook.version)
    requirement_satisfied = version_constraints.has_key?(cookbook.name) ? version_constraints[cookbook.name].include?(version) : true
    # we want a key for every cookbook, even if no versions are available
    res[cookbook.name] ||= []
    res[cookbook.name] << cookbook if requirement_satisfied
    res
  end

  sorted_list = filtered_list.inject({}) do |res, (cookbook_name, versions)|
    res[cookbook_name] = versions.sort.reverse
    res
  end

  sorted_list
end

.chef_server_restObject


88
89
90
# File 'lib/chef/environment.rb', line 88

def self.chef_server_rest
  Chef::REST.new(Chef::Config[:chef_server_url])
end

.create_default_environment(couchdb = nil) ⇒ Object


443
444
445
446
447
448
449
450
451
452
453
# File 'lib/chef/environment.rb', line 443

def self.create_default_environment(couchdb=nil)
  couchdb = couchdb || Chef::CouchDB.new
  begin
    Chef::Environment.cdb_load('_default', couchdb)
  rescue Chef::Exceptions::CouchDBNotFound
    env = Chef::Environment.new(couchdb)
    env.name '_default'
    env.description 'The default Chef environment'
    env.cdb_save
  end
end

.create_design_document(couchdb = nil) ⇒ Object

Set up our CouchDB design document


319
320
321
# File 'lib/chef/environment.rb', line 319

def self.create_design_document(couchdb=nil)
  (couchdb || Chef::CouchDB.new).create_design_document("environments", DESIGN_DOCUMENT)
end

.exists?(name, couchdb) ⇒ Boolean

Returns:

  • (Boolean)

283
284
285
286
287
288
289
# File 'lib/chef/environment.rb', line 283

def self.exists?(name, couchdb)
  begin
    self.cdb_load(name, couchdb)
  rescue Chef::Exceptions::CouchDBNotFound
    nil
  end
end

.json_create(o) ⇒ Object


248
249
250
251
252
253
254
255
256
257
258
# File 'lib/chef/environment.rb', line 248

def self.json_create(o)
  environment = new
  environment.name(o["name"])
  environment.description(o["description"])
  environment.cookbook_versions(o["cookbook_versions"])
  environment.default_attributes(o["default_attributes"])
  environment.override_attributes(o["override_attributes"])
  environment.couchdb_rev = o["_rev"] if o.has_key?("_rev")
  environment.couchdb_id = o["_id"] if o.has_key?("_id")
  environment
end

.list(inflate = false) ⇒ Object


266
267
268
269
270
271
272
273
# File 'lib/chef/environment.rb', line 266

def self.list(inflate=false)
  if inflate
    # TODO: index the environments and use search to inflate - don't inflate for now :(
    chef_server_rest.get_rest("environments")
  else
    chef_server_rest.get_rest("environments")
  end
end

.load(name) ⇒ Object


279
280
281
# File 'lib/chef/environment.rb', line 279

def self.load(name)
  chef_server_rest.get_rest("environments/#{name}")
end

.load_filtered_recipe_list(environment) ⇒ Object


418
419
420
# File 'lib/chef/environment.rb', line 418

def self.load_filtered_recipe_list(environment)
  chef_server_rest.get_rest("environments/#{environment}/recipes")
end

.validate_cookbook_version(version) ⇒ Object


434
435
436
437
438
439
440
441
# File 'lib/chef/environment.rb', line 434

def self.validate_cookbook_version(version)
  begin
    Chef::VersionConstraint.new version
    true
  rescue ArgumentError
    false
  end
end

.validate_cookbook_versions(cv) ⇒ Object


426
427
428
429
430
431
432
# File 'lib/chef/environment.rb', line 426

def self.validate_cookbook_versions(cv)
  return false unless cv.kind_of?(Hash)
  cv.each do |cookbook, version|
    return false unless Chef::Environment.validate_cookbook_version(version)
  end
  true
end

Instance Method Details

#add_cookbook_constraint_error(index, cookbook_constraint_spec) ⇒ Object


229
230
231
232
# File 'lib/chef/environment.rb', line 229

def add_cookbook_constraint_error(index, cookbook_constraint_spec)
  invalid_fields[:cookbook_version] ||= {}
  invalid_fields[:cookbook_version][index] = "#{cookbook_constraint_spec} is not a valid cookbook constraint"
end

#cdb_destroyObject


291
292
293
# File 'lib/chef/environment.rb', line 291

def cdb_destroy
  couchdb.delete("environment", @name, couchdb_rev)
end

#cdb_saveObject


299
300
301
# File 'lib/chef/environment.rb', line 299

def cdb_save
  self.couchdb_rev = couchdb.store("environment", @name, self)["rev"]
end

#chef_server_restObject


84
85
86
# File 'lib/chef/environment.rb', line 84

def chef_server_rest
  Chef::REST.new(Chef::Config[:chef_server_url])
end

#cookbook(cookbook, version) ⇒ Object


137
138
139
140
141
142
143
144
145
146
# File 'lib/chef/environment.rb', line 137

def cookbook(cookbook, version)
  validate({
    :version => version
  },{
    :version => {
      :callbacks => { "should be a valid version requirement" => lambda { |v| Chef::Environment.validate_cookbook_version(v) } }
    }
  })
  @cookbook_versions[cookbook] = version
end

#cookbook_versions(arg = nil) ⇒ Object


124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/chef/environment.rb', line 124

def cookbook_versions(arg=nil)
  set_or_return(
    :cookbook_versions,
    arg,
    {
      :kind_of => Hash,
      :callbacks => {
        "should be a valid set of cookbook version requirements" => lambda { |cv| Chef::Environment.validate_cookbook_versions(cv) }
      }
    }
  )
end

#createObject


313
314
315
316
# File 'lib/chef/environment.rb', line 313

def create
  chef_server_rest.post_rest("environments", self)
  self
end

#default_attributes(arg = nil) ⇒ Object


108
109
110
111
112
113
114
# File 'lib/chef/environment.rb', line 108

def default_attributes(arg=nil)
  set_or_return(
    :default_attributes,
    arg,
    :kind_of => Hash
  )
end

#description(arg = nil) ⇒ Object


100
101
102
103
104
105
106
# File 'lib/chef/environment.rb', line 100

def description(arg=nil)
  set_or_return(
    :description,
    arg,
    :kind_of => String
  )
end

#destroyObject


295
296
297
# File 'lib/chef/environment.rb', line 295

def destroy
  chef_server_rest.delete_rest("environments/#{@name}")
end

#invalid_fieldsObject


234
235
236
# File 'lib/chef/environment.rb', line 234

def invalid_fields
  @invalid_fields ||= {}
end

#name(arg = nil) ⇒ Object


92
93
94
95
96
97
98
# File 'lib/chef/environment.rb', line 92

def name(arg=nil)
  set_or_return(
    :name,
    arg,
    { :regex => /^[\-[:alnum:]_]+$/, :kind_of => String }
  )
end

#override_attributes(arg = nil) ⇒ Object


116
117
118
119
120
121
122
# File 'lib/chef/environment.rb', line 116

def override_attributes(arg=nil)
  set_or_return(
    :override_attributes,
    arg,
    :kind_of => Hash
  )
end

#saveObject


303
304
305
306
307
308
309
310
311
# File 'lib/chef/environment.rb', line 303

def save
  begin
    chef_server_rest.put_rest("environments/#{@name}", self)
  rescue Net::HTTPServerException => e
    raise e unless e.response.code == "404"
    chef_server_rest.post_rest("environments", self)
  end
  self
end

#to_hashObject


148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/chef/environment.rb', line 148

def to_hash
  result = {
    "name" => @name,
    "description" => @description,
    "cookbook_versions" =>  @cookbook_versions,
    "json_class" => self.class.name,
    "chef_type" => "environment",
    "default_attributes" => @default_attributes,
    "override_attributes" => @override_attributes
  }
  result["_rev"] = couchdb_rev if couchdb_rev
  result
end

#to_json(*a) ⇒ Object


162
163
164
# File 'lib/chef/environment.rb', line 162

def to_json(*a)
  to_hash.to_json(*a)
end

#to_sObject


422
423
424
# File 'lib/chef/environment.rb', line 422

def to_s
  @name
end

#update_attributes_from_params(params) ⇒ Object


175
176
177
178
179
180
181
182
# File 'lib/chef/environment.rb', line 175

def update_attributes_from_params(params)
  unless params[:default_attributes].nil? || params[:default_attributes].size == 0
    default_attributes(Chef::JSONCompat.from_json(params[:default_attributes]))
  end
  unless params[:override_attributes].nil? || params[:override_attributes].size == 0
    override_attributes(Chef::JSONCompat.from_json(params[:override_attributes]))
  end
end

#update_cookbook_constraint_from_param(index, cookbook_constraint_spec) ⇒ Object


214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/chef/environment.rb', line 214

def update_cookbook_constraint_from_param(index, cookbook_constraint_spec)
  valid = true
  md = cookbook_constraint_spec.match(COMBINED_COOKBOOK_CONSTRAINT)
  if md.nil? || md[2].nil?
    valid = false
    add_cookbook_constraint_error(index, cookbook_constraint_spec)
  elsif self.class.validate_cookbook_version(md[2])
    cookbook_versions[md[1]] = md[2]
  else
    valid = false
    add_cookbook_constraint_error(index, cookbook_constraint_spec)
  end
  valid
end

#update_from!(o) ⇒ Object


166
167
168
169
170
171
172
# File 'lib/chef/environment.rb', line 166

def update_from!(o)
  description(o.description)
  cookbook_versions(o.cookbook_versions)
  default_attributes(o.default_attributes)
  override_attributes(o.override_attributes)
  self
end

#update_from_params(params) ⇒ Object


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
# File 'lib/chef/environment.rb', line 184

def update_from_params(params)
  # reset because everything we need will be in the params, this is necessary because certain constraints
  # may have been removed in the params and need to be removed from cookbook_versions as well.
  bkup_cb_versions = cookbook_versions
  cookbook_versions(Hash.new)
  valid = true

  begin
    name(params[:name])
  rescue Chef::Exceptions::ValidationFailed => e
    invalid_fields[:name] = e.message
    valid = false
  end
  description(params[:description])

  unless params[:cookbook_version].nil?
    params[:cookbook_version].each do |index, cookbook_constraint_spec|
      unless (cookbook_constraint_spec.nil? || cookbook_constraint_spec.size == 0)
        valid = valid && update_cookbook_constraint_from_param(index, cookbook_constraint_spec)
      end
    end
  end

  update_attributes_from_params(params)

  valid = validate_required_attrs_present && valid
  cookbook_versions(bkup_cb_versions) unless valid # restore the old cookbook_versions if valid is false
  valid
end

#validate_required_attrs_presentObject


238
239
240
241
242
243
244
245
# File 'lib/chef/environment.rb', line 238

def validate_required_attrs_present
  if name.nil? || name.size == 0
    invalid_fields[:name] ||= "name cannot be empty"
    false
  else
    true
  end
end