Class: Chef::Knife

Inherits:
Object show all
Extended by:
Mixin::ConvertToClassName, Forwardable
Includes:
Mixin::PathSanity, Mixlib::CLI
Defined in:
lib/chef/knife.rb,
lib/chef/knife/raw.rb,
lib/chef/knife/ssh.rb,
lib/chef/knife/deps.rb,
lib/chef/knife/diff.rb,
lib/chef/knife/edit.rb,
lib/chef/knife/help.rb,
lib/chef/knife/list.rb,
lib/chef/knife/show.rb,
lib/chef/knife/serve.rb,
lib/chef/knife/xargs.rb,
lib/chef/knife/delete.rb,
lib/chef/knife/search.rb,
lib/chef/knife/status.rb,
lib/chef/knife/upload.rb,
lib/chef/knife/core/ui.rb,
lib/chef/knife/download.rb,
lib/chef/knife/tag_list.rb,
lib/chef/knife/bootstrap.rb,
lib/chef/knife/configure.rb,
lib/chef/knife/node_edit.rb,
lib/chef/knife/node_list.rb,
lib/chef/knife/node_show.rb,
lib/chef/knife/role_edit.rb,
lib/chef/knife/role_list.rb,
lib/chef/knife/role_show.rb,
lib/chef/knife/ssl_check.rb,
lib/chef/knife/ssl_fetch.rb,
lib/chef/knife/user_edit.rb,
lib/chef/knife/user_list.rb,
lib/chef/knife/user_show.rb,
lib/chef/knife/tag_create.rb,
lib/chef/knife/tag_delete.rb,
lib/chef/knife/client_edit.rb,
lib/chef/knife/client_list.rb,
lib/chef/knife/client_show.rb,
lib/chef/knife/node_create.rb,
lib/chef/knife/node_delete.rb,
lib/chef/knife/role_create.rb,
lib/chef/knife/role_delete.rb,
lib/chef/knife/user_create.rb,
lib/chef/knife/user_delete.rb,
lib/chef/knife/client_create.rb,
lib/chef/knife/client_delete.rb,
lib/chef/knife/cookbook_list.rb,
lib/chef/knife/cookbook_show.rb,
lib/chef/knife/cookbook_test.rb,
lib/chef/knife/data_bag_edit.rb,
lib/chef/knife/data_bag_list.rb,
lib/chef/knife/data_bag_show.rb,
lib/chef/knife/index_rebuild.rb,
lib/chef/knife/node_from_file.rb,
lib/chef/knife/role_from_file.rb,
lib/chef/knife/cookbook_create.rb,
lib/chef/knife/cookbook_delete.rb,
lib/chef/knife/cookbook_upload.rb,
lib/chef/knife/data_bag_create.rb,
lib/chef/knife/data_bag_delete.rb,
lib/chef/knife/user_reregister.rb,
lib/chef/knife/configure_client.rb,
lib/chef/knife/core/node_editor.rb,
lib/chef/knife/environment_edit.rb,
lib/chef/knife/environment_list.rb,
lib/chef/knife/environment_show.rb,
lib/chef/knife/node_bulk_delete.rb,
lib/chef/knife/role_bulk_delete.rb,
lib/chef/knife/client_reregister.rb,
lib/chef/knife/cookbook_download.rb,
lib/chef/knife/cookbook_metadata.rb,
lib/chef/knife/node_run_list_add.rb,
lib/chef/knife/node_run_list_set.rb,
lib/chef/knife/client_bulk_delete.rb,
lib/chef/knife/cookbook_site_list.rb,
lib/chef/knife/cookbook_site_show.rb,
lib/chef/knife/core/object_loader.rb,
lib/chef/knife/data_bag_from_file.rb,
lib/chef/knife/environment_create.rb,
lib/chef/knife/environment_delete.rb,
lib/chef/knife/cookbook_site_share.rb,
lib/chef/knife/core/node_presenter.rb,
lib/chef/knife/core/text_formatter.rb,
lib/chef/knife/environment_compare.rb,
lib/chef/knife/cookbook_bulk_delete.rb,
lib/chef/knife/cookbook_site_search.rb,
lib/chef/knife/node_environment_set.rb,
lib/chef/knife/node_run_list_remove.rb,
lib/chef/knife/cookbook_site_install.rb,
lib/chef/knife/cookbook_site_unshare.rb,
lib/chef/knife/core/status_presenter.rb,
lib/chef/knife/environment_from_file.rb,
lib/chef/knife/cookbook_site_download.rb,
lib/chef/knife/core/bootstrap_context.rb,
lib/chef/knife/core/cookbook_scm_repo.rb,
lib/chef/knife/core/generic_presenter.rb,
lib/chef/knife/core/subcommand_loader.rb,
lib/chef/knife/data_bag_secret_options.rb,
lib/chef/knife/cookbook_metadata_from_file.rb

Defined Under Namespace

Modules: Core, DataBagSecretOptions Classes: Bootstrap, ClientBulkDelete, ClientCreate, ClientDelete, ClientEdit, ClientList, ClientReregister, ClientShow, Configure, ConfigureClient, CookbookBulkDelete, CookbookCreate, CookbookDelete, CookbookDownload, CookbookList, CookbookMetadata, CookbookMetadataFromFile, CookbookSCMRepo, CookbookShow, CookbookSiteDownload, CookbookSiteInstall, CookbookSiteList, CookbookSiteSearch, CookbookSiteShare, CookbookSiteShow, CookbookSiteUnshare, CookbookSiteVendor, CookbookTest, CookbookUpload, DataBagCreate, DataBagDelete, DataBagEdit, DataBagFromFile, DataBagList, DataBagShow, Delete, Deps, Diff, Download, Edit, EnvironmentCompare, EnvironmentCreate, EnvironmentDelete, EnvironmentEdit, EnvironmentFromFile, EnvironmentList, EnvironmentShow, Exec, Help, IndexRebuild, List, NodeBulkDelete, NodeCreate, NodeDelete, NodeEdit, NodeEditor, NodeEnvironmentSet, NodeFromFile, NodeList, NodeRunListAdd, NodeRunListRemove, NodeRunListSet, NodeShow, Raw, RecipeList, RoleBulkDelete, RoleCreate, RoleDelete, RoleEdit, RoleFromFile, RoleList, RoleShow, Search, Serve, Show, Ssh, SslCheck, SslFetch, Status, SubcommandLoader, TagCreate, TagDelete, TagList, UI, Upload, UserCreate, UserDelete, UserEdit, UserList, UserReregister, UserShow, Xargs

Constant Summary collapse

@@chef_config_dir =

Shared with subclasses

nil

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Mixin::ConvertToClassName

constantize, convert_to_class_name, convert_to_snake_case, filename_to_qualified_string, snake_case_basename

Methods included from Mixin::PathSanity

#enforce_path_sanity

Constructor Details

#initialize(argv = []) ⇒ Knife

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



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

def initialize(argv=[])
  super() # having to call super in initialize is the most annoying anti-pattern :(
  @ui = Chef::Knife::UI.new(STDOUT, STDERR, STDIN, config)

  command_name_words = self.class.snake_case_name.split('_')

  # Mixlib::CLI ignores the embedded name_args
  @name_args = parse_options(argv)
  @name_args.delete(command_name_words.join('-'))
  @name_args.reject! { |name_arg| command_name_words.delete(name_arg) }

  # knife node run_list add requires that we have extra logic to handle
  # the case that command name words could be joined by an underscore :/
  command_name_words = command_name_words.join('_')
  @name_args.reject! { |name_arg| command_name_words == name_arg }

  if config[:help]
    msg opt_parser
    exit 1
  end

  # copy Mixlib::CLI over so that it cab be configured in knife.rb
  # config file
  Chef::Config[:verbosity] = config[:verbosity]
end

Instance Attribute Details

#name_argsObject

Returns the value of attribute name_args.



59
60
61
# File 'lib/chef/knife.rb', line 59

def name_args
  @name_args
end

#uiObject

Returns the value of attribute ui.



60
61
62
# File 'lib/chef/knife.rb', line 60

def ui
  @ui
end

Class Method Details

.category(new_category) ⇒ Object

Explicitly set the category for the current command to new_category The category is normally determined from the first word of the command name, but some commands make more sense using two or more words

Arguments

new_category:

A String to set the category to (see examples)

Examples:

Data bag commands would be in the ‘data’ category by default. To put them in the ‘data bag’ category:

category('data bag')


100
101
102
# File 'lib/chef/knife.rb', line 100

def self.category(new_category)
  @category = new_category
end

.chef_config_dirObject



186
187
188
# File 'lib/chef/knife.rb', line 186

def self.chef_config_dir
  @@chef_config_dir ||= config_loader.chef_config_dir
end

.common_nameObject



112
113
114
# File 'lib/chef/knife.rb', line 112

def self.common_name
  snake_case_name.split('_').join(' ')
end

.config_loaderObject



170
171
172
# File 'lib/chef/knife.rb', line 170

def self.config_loader
  @config_loader ||= WorkstationConfigLoader.new(nil, Chef::Log)
end

.dependency_loadersObject



244
245
246
# File 'lib/chef/knife.rb', line 244

def self.dependency_loaders
  @dependency_loaders ||= []
end

.deps(&block) ⇒ Object



248
249
250
# File 'lib/chef/knife.rb', line 248

def self.deps(&block)
  dependency_loaders << block
end

.guess_category(args) ⇒ Object



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

def self.guess_category(args)
  category_words = args.select {|arg| arg =~ /^(([[:alnum:]])[[:alnum:]\_\-]+)$/ }
  category_words.map! {|w| w.split('-')}.flatten!
  matching_category = nil
  while (!matching_category) && (!category_words.empty?)
    candidate_category = category_words.join(' ')
    matching_category = candidate_category if subcommands_by_category.key?(candidate_category)
    matching_category || category_words.pop
  end
  matching_category
end

.inherited(subclass) ⇒ Object



85
86
87
88
89
# File 'lib/chef/knife.rb', line 85

def self.inherited(subclass)
  unless subclass.unnamed?
    subcommands[subclass.snake_case_name] = subclass
  end
end

.list_commands(preferred_category = nil) ⇒ Object

Print the list of subcommands knife knows about. If preferred_category is given, only subcommands in that category are shown



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/chef/knife.rb', line 145

def self.list_commands(preferred_category=nil)
  load_commands

  category_desc = preferred_category ? preferred_category + " " : ''
  msg "Available #{category_desc}subcommands: (for details, knife SUB-COMMAND --help)\n\n"

  if preferred_category && subcommands_by_category.key?(preferred_category)
    commands_to_show = {preferred_category => subcommands_by_category[preferred_category]}
  else
    commands_to_show = subcommands_by_category
  end

  commands_to_show.sort.each do |category, commands|
    next if category =~ /deprecated/i
    msg "** #{category.upcase} COMMANDS **"
    commands.sort.each do |command|
      msg subcommands[command].banner if subcommands[command]
    end
    msg
  end
end

.load_commandsObject



125
126
127
# File 'lib/chef/knife.rb', line 125

def self.load_commands
  @commands_loaded ||= subcommand_loader.load_commands
end

.load_config(explicit_config_file) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
# File 'lib/chef/knife.rb', line 174

def self.load_config(explicit_config_file)
  config_loader.explicit_config_file = explicit_config_file
  config_loader.load

  ui.warn("No knife configuration file found") if config_loader.no_config_found?

  config_loader
rescue Exceptions::ConfigurationError => e
  ui.error(ui.color("CONFIGURATION ERROR:", :red) + e.message)
  exit 1
end

.load_depsObject



252
253
254
255
256
# File 'lib/chef/knife.rb', line 252

def self.load_deps
  dependency_loaders.each do |dep_loader|
    dep_loader.call
  end
end

.msg(msg = "") ⇒ Object



71
72
73
# File 'lib/chef/knife.rb', line 71

def self.msg(msg="")
  ui.msg(msg)
end

.reset_config_loader!Object



75
76
77
78
# File 'lib/chef/knife.rb', line 75

def self.reset_config_loader!
  @@chef_config_dir = nil
  @config_loader = nil
end

.reset_subcommands!Object



80
81
82
83
# File 'lib/chef/knife.rb', line 80

def self.reset_subcommands!
  @@subcommands = {}
  @subcommands_by_category = nil
end

.run(args, options = {}) ⇒ Object

Run knife for the given args (ARGV), adding options to the list of CLI options that the subcommand knows how to handle.

Arguments

args:

usually ARGV

options:

A Mixlib::CLI option parser hash. These options are how

subcommands know about global knife CLI options



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/chef/knife.rb', line 196

def self.run(args, options={})
  # Fallback debug logging. Normally the logger isn't configured until we
  # read the config, but this means any logging that happens before the
  # config file is read may be lost. If the KNIFE_DEBUG variable is set, we
  # setup the logger for debug logging to stderr immediately to catch info
  # from early in the setup process.
  if ENV['KNIFE_DEBUG']
    Chef::Log.init($stderr)
    Chef::Log.level(:debug)
  end

  load_commands
  subcommand_class = subcommand_class_from(args)
  subcommand_class.options = options.merge!(subcommand_class.options)
  subcommand_class.load_deps
  instance = subcommand_class.new(args)
  instance.configure_chef
  instance.run_with_pretty_exceptions
end

.snake_case_nameObject



108
109
110
# File 'lib/chef/knife.rb', line 108

def self.snake_case_name
  convert_to_snake_case(name.split('::').last) unless unnamed?
end

.subcommand_categoryObject



104
105
106
# File 'lib/chef/knife.rb', line 104

def self.subcommand_category
  @category || snake_case_name.split('_').first unless unnamed?
end

.subcommand_class_from(args) ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/chef/knife.rb', line 228

def self.subcommand_class_from(args)
  command_words = args.select {|arg| arg =~ /^(([[:alnum:]])[[:alnum:]\_\-]+)$/ }

  subcommand_class = nil

  while ( !subcommand_class ) && ( !command_words.empty? )
    snake_case_class_name = command_words.join("_")
    unless subcommand_class = subcommands[snake_case_class_name]
      command_words.pop
    end
  end
  # see if we got the command as e.g., knife node-list
  subcommand_class ||= subcommands[args.first.gsub('-', '_')]
  subcommand_class || subcommand_not_found!(args)
end

.subcommand_loaderObject



121
122
123
# File 'lib/chef/knife.rb', line 121

def self.subcommand_loader
  @subcommand_loader ||= Knife::SubcommandLoader.new(chef_config_dir)
end

.subcommandsObject



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

def self.subcommands
  @@subcommands ||= {}
end

.subcommands_by_categoryObject



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

def self.subcommands_by_category
  unless @subcommands_by_category
    @subcommands_by_category = Hash.new { |hash, key| hash[key] = [] }
    subcommands.each do |snake_cased, klass|
      @subcommands_by_category[klass.subcommand_category] << snake_cased
    end
  end
  @subcommands_by_category
end

.uiObject



67
68
69
# File 'lib/chef/knife.rb', line 67

def self.ui
  @ui ||= Chef::Knife::UI.new(STDOUT, STDERR, STDIN, {})
end

.unnamed?Boolean

Does this class have a name? (Classes created via Class.new don’t)

Returns:

  • (Boolean)


117
118
119
# File 'lib/chef/knife.rb', line 117

def self.unnamed?
  name.nil? || name.empty?
end

.use_separate_defaults?Boolean

Configure mixlib-cli to always separate defaults from user-supplied CLI options

Returns:

  • (Boolean)


63
64
65
# File 'lib/chef/knife.rb', line 63

def self.use_separate_defaults?
  true
end

Instance Method Details

#api_keyObject



484
485
486
# File 'lib/chef/knife.rb', line 484

def api_key
  Chef::Config[:client_key]
end

#apply_computed_configObject

Catch-all method that does any massaging needed for various config components, such as expanding file paths and converting verbosity level into log level.



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

def apply_computed_config
  Chef::Config[:color] = config[:color]

  case Chef::Config[:verbosity]
  when 0, nil
    Chef::Config[:log_level] = :error
  when 1
    Chef::Config[:log_level] = :info
  else
    Chef::Config[:log_level] = :debug
  end

  Chef::Config[:log_level] = :debug if ENV['KNIFE_DEBUG']

  Chef::Config[:node_name]         = config[:node_name]       if config[:node_name]
  Chef::Config[:client_key]        = config[:client_key]      if config[:client_key]
  Chef::Config[:chef_server_url]   = config[:chef_server_url] if config[:chef_server_url]
  Chef::Config[:environment]       = config[:environment]     if config[:environment]

  Chef::Config.local_mode = config[:local_mode] if config.has_key?(:local_mode)
  if Chef::Config.local_mode && !Chef::Config.has_key?(:cookbook_path) && !Chef::Config.has_key?(:chef_repo_path)
    Chef::Config.chef_repo_path = Chef::Config.find_chef_repo_path(Dir.pwd)
  end
  Chef::Config.chef_zero.host = config[:chef_zero_host] if config[:chef_zero_host]
  Chef::Config.chef_zero.port = config[:chef_zero_port] if config[:chef_zero_port]

  # Expand a relative path from the config directory. Config from command
  # line should already be expanded, and absolute paths will be unchanged.
  if Chef::Config[:client_key] && config[:config_file]
    Chef::Config[:client_key] = File.expand_path(Chef::Config[:client_key], File.dirname(config[:config_file]))
  end

  Mixlib::Log::Formatter.show_time = false
  Chef::Log.init(Chef::Config[:log_location])
  Chef::Log.level(Chef::Config[:log_level] || :error)

  if Chef::Config[:node_name] && Chef::Config[:node_name].bytesize > 90
    # node names > 90 bytes only work with authentication protocol >= 1.1
    # see discussion in config.rb.
    Chef::Config[:authentication_protocol_version] = "1.1"
  end
end

#config_file_settingsObject

Returns a subset of the Chef::Config Hash that is relevant to the currently executing knife command. This is used by #configure_chef to apply settings from knife.rb to the config hash.



327
328
329
330
331
332
333
# File 'lib/chef/knife.rb', line 327

def config_file_settings
  config_file_settings = {}
  self.class.options.keys.each do |key|
    config_file_settings[key] = Chef::Config[:knife][key] if Chef::Config[:knife].has_key?(key)
  end
  config_file_settings
end

#configure_chefObject



397
398
399
400
401
402
403
404
405
# File 'lib/chef/knife.rb', line 397

def configure_chef
  config_loader = self.class.load_config(config[:config_file])
  config[:config_file] = config_loader.config_location

  merge_configs
  apply_computed_config
  # This has to be after apply_computed_config so that Mixlib::Log is configured
  Chef::Log.info("Using configuration from #{config[:config_file]}") if config[:config_file]
end

#create_object(object, pretty_name = nil, &block) ⇒ Object



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/chef/knife.rb', line 498

def create_object(object, pretty_name=nil, &block)
  output = edit_data(object)

  if Kernel.block_given?
    output = block.call(output)
  else
    output.save
  end

  pretty_name ||= output

  self.msg("Created #{pretty_name}")

  output(output) if config[:print_after]
end

#delete_object(klass, name, delete_name = nil, &block) ⇒ Object



514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'lib/chef/knife.rb', line 514

def delete_object(klass, name, delete_name=nil, &block)
  confirm("Do you really want to delete #{name}")

  if Kernel.block_given?
    object = block.call
  else
    object = klass.load(name)
    object.destroy
  end

  output(format_for_display(object)) if config[:print_after]

  obj_name = delete_name ? "#{delete_name}[#{name}]" : object
  self.msg("Deleted #{obj_name}")
end

#format_rest_error(response) ⇒ Object

Parses JSON from the error response sent by Chef Server and returns the error message – TODO: this code belongs in Chef::REST



492
493
494
495
496
# File 'lib/chef/knife.rb', line 492

def format_rest_error(response)
  Array(Chef::JSONCompat.from_json(response.body)["error"]).join('; ')
rescue Exception
  response.body
end

#humanize_exception(e) ⇒ Object



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/chef/knife.rb', line 425

def humanize_exception(e)
  case e
  when SystemExit
    raise # make sure exit passes through.
  when Net::HTTPServerException, Net::HTTPFatalError
    humanize_http_exception(e)
  when Errno::ECONNREFUSED, Timeout::Error, Errno::ETIMEDOUT, SocketError
    ui.error "Network Error: #{e.message}"
    ui.info "Check your knife configuration and network settings"
  when NameError, NoMethodError
    ui.error "knife encountered an unexpected error"
    ui.info  "This may be a bug in the '#{self.class.common_name}' knife command or plugin"
    ui.info  "Please collect the output of this command with the `-VV` option before filing a bug report."
    ui.info  "Exception: #{e.class.name}: #{e.message}"
  when Chef::Exceptions::PrivateKeyMissing
    ui.error "Your private key could not be loaded from #{api_key}"
    ui.info  "Check your configuration file and ensure that your private key is readable"
  when Chef::Exceptions::InvalidRedirect
    ui.error "Invalid Redirect: #{e.message}"
    ui.info  "Change your server location in knife.rb to the server's FQDN to avoid unwanted redirections."
  else
    ui.error "#{e.class.name}: #{e.message}"
  end
end

#humanize_http_exception(e) ⇒ Object



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/chef/knife.rb', line 450

def humanize_http_exception(e)
  response = e.response
  case response
  when Net::HTTPUnauthorized
    ui.error "Failed to authenticate to #{server_url} as #{username} with key #{api_key}"
    ui.info "Response:  #{format_rest_error(response)}"
  when Net::HTTPForbidden
    ui.error "You authenticated successfully to #{server_url} as #{username} but you are not authorized for this action"
    ui.info "Response:  #{format_rest_error(response)}"
  when Net::HTTPBadRequest
    ui.error "The data in your request was invalid"
    ui.info "Response: #{format_rest_error(response)}"
  when Net::HTTPNotFound
    ui.error "The object you are looking for could not be found"
    ui.info "Response: #{format_rest_error(response)}"
  when Net::HTTPInternalServerError
    ui.error "internal server error"
    ui.info "Response: #{format_rest_error(response)}"
  when Net::HTTPBadGateway
    ui.error "bad gateway"
    ui.info "Response: #{format_rest_error(response)}"
  when Net::HTTPServiceUnavailable
    ui.error "Service temporarily unavailable"
    ui.info "Response: #{format_rest_error(response)}"
  else
    ui.error response.message
    ui.info "Response: #{format_rest_error(response)}"
  end
end

#merge_configsObject

Apply Config in this order: defaults from mixlib-cli settings from config file, via Chef::Config config from command line



339
340
341
342
343
344
345
346
347
348
349
# File 'lib/chef/knife.rb', line 339

def merge_configs
  # Apply config file settings on top of mixlib-cli defaults
  combined_config = default_config.merge(config_file_settings)
  # Apply user-supplied options on top of the above combination
  combined_config = combined_config.merge(config)
  # replace the config hash from mixlib-cli with our own.
  # Need to use the mutate-in-place #replace method instead of assigning to
  # the instance variable because other code may have a reference to the
  # original config hash object.
  config.replace(combined_config)
end

#noauth_restObject



537
538
539
540
541
542
# File 'lib/chef/knife.rb', line 537

def noauth_rest
  @rest ||= begin
    require 'chef/rest'
    Chef::REST.new(Chef::Config[:chef_server_url], false, false)
  end
end

#parse_options(args) ⇒ Object



316
317
318
319
320
321
322
# File 'lib/chef/knife.rb', line 316

def parse_options(args)
  super
rescue OptionParser::InvalidOption => e
  puts "Error: " + e.to_s
  show_usage
  exit(1)
end

#restObject



530
531
532
533
534
535
# File 'lib/chef/knife.rb', line 530

def rest
  @rest ||= begin
    require 'chef/rest'
    Chef::REST.new(Chef::Config[:chef_server_url])
  end
end

#run_with_pretty_exceptions(raise_exception = false) ⇒ Object



411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/chef/knife.rb', line 411

def run_with_pretty_exceptions(raise_exception = false)
  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
  Chef::LocalMode.with_server_connectivity do
    run
  end
rescue Exception => e
  raise if raise_exception || Chef::Config[:verbosity] == 2
  humanize_exception(e)
  exit 100
end

#server_urlObject



544
545
546
# File 'lib/chef/knife.rb', line 544

def server_url
  Chef::Config[:chef_server_url]
end

#show_usageObject



407
408
409
# File 'lib/chef/knife.rb', line 407

def show_usage
  stdout.puts("USAGE: " + self.opt_parser.to_s)
end

#usernameObject



480
481
482
# File 'lib/chef/knife.rb', line 480

def username
  Chef::Config[:node_name]
end