Module: Chef::Knife::ChopBase

Includes:
ChopLogging, ChopErrors
Included in:
ChopTranslate, ChopUpload
Defined in:
lib/chef/knife/chop_base.rb

Instance Attribute Summary

Attributes included from ChopLogging

#TODO, #args, #logger, #step

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ChopLogging

#getLogger, #logStep, #logTodo, #setLogger

Class Method Details

.included(includer) ⇒ Object




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
# File 'lib/chef/knife/chop_base.rb', line 178

def self.included(includer)
  includer.class_eval do

    deps do
      require 'readline'
      require 'colorize'
      require 'inifile'
      require 'chef/knife/chop/chef_knife'
      require 'chef/environment'
      require 'chef/knife/core/object_loader'
      require 'chef/cookbook_loader'
      require 'chef/cookbook_uploader'
      require 'chef/knife/chop/cookbook_upload'
      require 'chef/knife/chop/data_bag_from_file'
      require 'chef/knife/chop/role_from_file'
      require 'chef/knife/chop/environment_from_file'
      require 'chef/knife/chop/chef_part'
      require 'chef/knife/chop/chef_environment'
      require 'chef/knife/chop/chef_role'
      #require 'chef/knife/chop/chef_data_bag_item'
      require 'chef/json_compat'
      require 'chef/knife/bootstrap'
      require 'chef/knife/chop/ui'
      Chef::Knife::Bootstrap.load_deps
    end

    attr_reader   :argv

    # This will print an args summary.
    option  :help,
            :short        => "-h",
            :long         => "--help",
            :description  => "Show this message",
            :show_options => true,
            :exit         => 1
    # print the version.
    option  :version,
            :short        => '-V',
            :long         => "--version",
            :description  => "Show version",
            :proc         => Proc.new{ puts ::Knife::Chop::VERSION },
            :exit         => 2
    option  :verbosity,
            :short        => "-v",
            :long         => "--[no-]verbose [LEVEL]",
            :description  => "Run verbosely",
            :proc         => lambda{|s|
              if s.nil? or (s == '')
                $CHOP.verbosity += 1
              else
                $CHOP.verbosity = v.gsub(%r/['"]*/, '').to_i
              end
            }
    option  :log_path,
            :long         => '--log-path PATH',
            :description  => "Log destination path"
    option  :log_file,
            :long         => '--log-file PATH',
            :description  => "Log destination file"
    option  :log_level,
            :short        => '-l',
            :long         => ['--log_level LEVEL','--log-level LEVEL'],
            :description  => "Log level (#{::Chef::Knife.loglevels.to_s})",
            :proc         => lambda{|v|
              if ::Chef::Knife.loglevels.include? v.to_sym
                v.to_sym
              else
                level = ::Chef::Knife.loglevels.select{|l| l.to_s.match(%r(^#{v}))}
                unless level.size > 0
                  raise OptionParser::InvalidOption.new("Invalid log level: #{v}. Valid levels are #{::Chef::Knife.loglevels.ai}")
                end
                level[0].to_sym
              end
            },
            :default      => :step
    option  :inifile,
            :short        => "-f",
            :long         => "--inifile FILE",
            :description  => "INI file with settings"
    option  :parts,
            :short        => "-R",
            :long         => "--resources PARTS",
            :description  => "Parts to upload #{[ :all, ::Chef::Knife.allparts].flatten }. Default: all",
            :default      => ::Chef::Knife.allparts,
            :proc         => lambda{|v|
              parts = $CHOP.parseOptionString(v,',','parsePartSymbol')
              parts.each{ |part|
                raise ::OptionParser::InvalidOption.new("Invalid part: #{part.to_s}. Valid parts are: #{[::Chef::Knife.allparts, :all].to_s}") unless [::Chef::Knife.allparts, :all].flatten.include?(part.to_sym)
              }
              parts
            }
    option  :depends,
            :short        => "-I",
            :long         => "--[no-]include-dependencies [yes|no|true|false|0|1|enable|disable]",
            :description  => "Include Cookbook dependencies?, Default --include-dependencies or -I [1|yes|enable|true]",
            :default      => true
    option  :dry_run,
            :short        => "-n",
            :long         => "--[no-]dry-run",
            :description  => "Do a dry run, Default --no-dry-run",
            :default      => false
    option  :cookbook_path,
            :short        => "-P",
            :long         => "--cookbook-path PATH",
            :description  => "Cookbook search path, Default chef/cookbooks/:chef/vendor-cookbooks",
            :default      => ["cookbooks","vendor-cookbooks"],
            :proc         => lambda{|v|
              $CHOP.parseOptionString(v,'[:,]','parsePath')
            }
    option  :repo_path,
            :long         => "--repo-path PATH",
            :description  => "Chef repo path, Default ./chef",
            :default      => ".",
            #:required     => true,
            :proc         => lambda{|v|
              File.expand_path(v)
            }
    option  :cookbooks,
            :short        => "-c",
            :long         => "--cookbooks COOKBOOKS",
            :description  => "Cookbooks to upload (List separated by commas or --all. Default: role",
            :default      => ['role'],
            :proc         => lambda{|v|
              $CHOP.parseOptionString(v)
            }
    option  :envs,
            :short        => ["-e", "-E",],
            :long         => "--environments REGEXLIST",
            :description  => "Environments regex",
            :proc         => lambda{|v|
              $CHOP.parseOptionString(v)
            },
            :default      => ['.*']
    option  :databags,
            :short        => "-b",
            :long         => "--databags BAGS",
            :description  => "Data bags to upload",
            :default      => ['.*:.*'],
            :proc         => lambda{|v|
              $CHOP.parseOptionString(v)
            }
    option  :roles,
            :short        => "-r",
            :long         => "--roles ROLES",
            :description  => "Roles to upload",
            :default      => [".*"],
            :proc         => lambda{|v|
              $CHOP.parseOptionString(v)
            }

    option :all,
           :short => "-a",
           :long  => "--all",
           :description => "Upload all items for resource group(s)"

    option :trace,
           :short => "-t",
           :long  => "--trace",
           :boolean => true,
           :default => false,
           :description => "Trace logging locations (file::line)"

    # ------------------------------------------------------------------------------------------------------------
    # Cookbooks
    # ------------------------------------------------------------------------------------------------------------
    option :freeze,
           :long => '--freeze',
           :description => 'Freeze this version of the cookbook so that it cannot be overwritten',
           :boolean => true

    #option :all,
    #       :short => "-a",
    #       :long => "--all",
    #       :description => "Upload all cookbooks, rather than just a single cookbook"

    option :force,
           :long => '--force',
           :boolean => true,
           :description => "Update cookbook versions even if they have been frozen"

    # ------------------------------------------------------------------------------------------------------------
    # Data bags
    # ------------------------------------------------------------------------------------------------------------
    option :secret,
           :short => "-s SECRET",
           :long  => "--secret ",
           :description => "The secret key to use to encrypt data bag item values"

    option :secret_file,
           :long => "--secret-file SECRET_FILE",
           :description => "A file containing the secret key to use to encrypt data bag item values"


    # ------------------------------------------------------------------------------------------------------------
    option  :precedence,
            :long         => "--precedence PREC",
            :description  => "Precedence order of parts extensions. Default: json:1,rb:2 or json,rb == [json rb] == { json => 1, rb => 2 } == .rb files will be used when there is both a .json and .rb",
            :default      => %w(json rb),
            :proc         => lambda{|v|
              prec = $CHOP.parseOptionString(v,',', 'parsePrecedence')
              prec.sort{|x,y| x.values.shift <=> y.values.shift }.map{|e| e.keys.shift }
            }
    option  :actions,
            :short        => '-a',
            :long         => "--action ACTION",
            :description  => "Actions to be performed #{[ :all, ::Chef::Knife.allactions].flatten }. Default: upload",
            #:default      => [:upload],
            :proc         => lambda{|v|
              actions = $CHOP.parseOptionString(v,',','parseActionSymbol')
              actions.each{ |act|
                raise ::OptionParser::InvalidOption.new("Invalid action: #{act.to_s}. Valid actions are: #{[ :all, ::Chef::Knife.allactions].flatten.to_s}") unless [ :all, ::Chef::Knife.allactions].flatten.include?(act.to_sym)
              }
              actions
            }
    option  :translate,
            :long         => "--translate PREC",
            :description  => "Translate parts. Default: json,rb == { :from => 'json', :to => 'rb' } == .json files will be read and .rb equivalents will be saved",
            :default      => %w(json rb),
            :proc         => lambda{|v|
              $CHOP.parseOptionString(v)
            }
  end
end

Instance Method Details

#build_option_arguments(opt_setting) ⇒ Object




421
422
423
424
# File 'lib/chef/knife/chop_base.rb', line 421

def build_option_arguments(opt_setting)
  arguments = super
  arguments.flatten
end

#configure_chefObject




470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/chef/knife/chop_base.rb', line 470

def configure_chef
  super
  @config[:log_opts] = lambda{|mlll| {
      :pattern      => "%#{mlll}l: %m %C\n",
      :date_pattern => '%Y-%m-%d %H:%M:%S',
    }
  }

  @logger = getLogger(@config)
  @ui = Chef::Knife::ChopUI.new(@logger,@config)
  Chef::Log.logger = @logger
end

#initialize(argv = []) ⇒ Object


Create a new instance of the current class configured for the given arguments and options



405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/chef/knife/chop_base.rb', line 405

def initialize(argv=[])
  @argv       = argv
  $CHOP       = self
  @verbosity  = 0
  @inis       = []
  @use_knife_api = true

  @stop = false
  @prec_max = 0
  @TODO = {}
  @actors = {}

  super
end

#parse_options(args, source = nil) ⇒ Object




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
# File 'lib/chef/knife/chop_base.rb', line 427

def parse_options(args,source=nil)
  argv = super(args)

  @config = parse_and_validate_options(@config,source ? source : "ARGV - #{__LINE__}")
  v = @config[:depends]
  m = (v.is_a?(String) && v.downcase.match(%r/^(no|false|disable|0)/) )
  @config[:depends] = (v === true) || (m.nil? ? true : false)

  unless @config[:actions]
    @config[:actions] = [ argv[1].to_sym ] # self.class.name.gsub(%r(Chef::Knife::Chop), '').downcase
  end
  @actors[argv[1].to_sym] = self
  others = @config[:actions].select{|a|
    a != argv[1].to_sym
  }
  index   = args.index '--action'
  others.each{|a|
    args[1] = a.to_s
    unless index.nil?
      args[index+1] = a.to_s
    end
    subcommand_class = ::Chef::Knife.subcommand_class_from(args)
    subcommand_class.load_deps
    instance = subcommand_class.new(args)
    instance.configure_chef
    @actors[a] = instance
  }
  argv
end

#parseActionSymbol(v) ⇒ Object




106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/chef/knife/chop_base.rb', line 106

def parseActionSymbol(v)
  if v.to_sym == :all
    ::Chef::Knife.allactions
  else
    s = v.to_sym
    allactions = [::Chef::Knife.allactions, :all].flatten
    unless allactions.include?(s)
      allactions.each{ |p|
        s = p if p.match(%r/^#{s}/)
      }
    end
    s = ::Chef::Knife.allactions if s == :all
    s
  end
end

#parseList(v, s = ',', method = 'parseString') ⇒ Object




133
134
135
136
137
138
139
140
# File 'lib/chef/knife/chop_base.rb', line 133

def parseList(v,s=',',method='parseString')
  parts = []
  a = v.split(%r/#{s}/)
  a.each{ |t|
    parts << send(method,t)
  }
  parts
end

#parseOptionString(v, s = ',', method = 'parseString') ⇒ Object




143
144
145
146
147
148
149
150
151
# File 'lib/chef/knife/chop_base.rb', line 143

def parseOptionString(v,s=',',method='parseString')
  bags = []
  if v.match(%r'#{s}')
    bags << parseList(v,s,method)
  else
    bags << send(method,v)
  end
  bags.flatten
end

#parsePartSymbol(v) ⇒ Object




89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/chef/knife/chop_base.rb', line 89

def parsePartSymbol(v)
  if v.to_sym == :all
    ::Chef::Knife.allparts
  else
    s = v.to_sym
    allparts = [::Chef::Knife.allparts, :all].flatten
    unless allparts.include?(s)
      allparts.each{ |p|
        s = p if p.match(%r/^#{s}/)
      }
    end
    s = ::Chef::Knife.allparts if s == :all
    s
  end
end

#parsePath(v) ⇒ Object




128
129
130
# File 'lib/chef/knife/chop_base.rb', line 128

def parsePath(v)
  File.expand_path(parseString(v))
end

#parsePrecedence(v) ⇒ Object




154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/chef/knife/chop_base.rb', line 154

def parsePrecedence(v)
  @prec_max += 1
  match = v.match(%r/^(json|rb|yaml)$/i)
  unless match
    m = "ERROR: Invalid precedence argument: #{v}. Accept only from this set: [json,rb,yaml]"
    puts m
    raise Exception.new(m)
  end
  s = { v => @prec_max }
  match = v.match(%r/^(\S+):(\d+)$/)
  if match
    begin
      a = match[1]
      i = match[2].to_i
      s = { a => i }
    rescue => e
      puts "ERROR: Unable to match precedence #{v}"
      raise e
    end
  end
  s
end

#parseString(v) ⇒ Object




123
124
125
# File 'lib/chef/knife/chop_base.rb', line 123

def parseString(v)
  v
end

#run_with_pretty_exceptionsObject



483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'lib/chef/knife/chop_base.rb', line 483

def run_with_pretty_exceptions
  unless self.respond_to?(:run)
    ui.error "You need to add a #run method to your knife command before you can use it"
  end
  enforce_path_sanity

  raise ChopOptionError.new("The --repo-path '#{@config[:repo_path]}' is invalid!") unless File.directory?(@config[:repo_path])

  run
rescue ChopOptionError => e
  raise if Chef::Config[:verbosity] == 2
  humanize_exception(e)
  exit 100
rescue ChopError => e
  humanize_exception(e)
  exit 101
end