Class: Chef::Knife::AzureServerCreate

Inherits:
Chef::Knife show all
Includes:
AzureBase, Bootstrap::BootstrapOptions, Bootstrap::Bootstrapper, Knife::WinrmBase
Defined in:
lib/chef/knife/azure_server_create.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Bootstrap::Bootstrapper

#bootstrap_common_params, #bootstrap_exec, #bootstrap_for_node, #bootstrap_for_windows_node, #create_node_and_client_pem, #default_bootstrap_template, #default_hint_options, #get_chef_extension_name, #get_chef_extension_private_params, #get_chef_extension_public_params, #get_chef_extension_publisher, #get_chef_extension_version, #load_cloud_attributes_in_hints, #load_correct_secret, #load_winrm_deps, #ohai_hints, #tcp_test_ssh, #tcp_test_winrm

Methods included from Bootstrap::BootstrapOptions

included

Methods included from AzureBase

#fetch_chef_client_logs, #fetch_deployment, #fetch_extension, #fetch_role, #fetch_substatus, #find_file, #get_azure_profile_file_path, #get_default_subscription, included, #is_image_windows?, #locate_config_value, #msg_pair, #msg_server_summary, #parse_azure_profile, #parse_publish_settings_file, #pretty_key, #service, #validate!, #validate_asm_keys!, #validate_params!

Instance Attribute Details

#initial_sleep_delayObject

Returns the value of attribute initial_sleep_delay.



47
48
49
# File 'lib/chef/knife/azure_server_create.rb', line 47

def initial_sleep_delay
  @initial_sleep_delay
end

Instance Method Details

#create_server_defObject



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# File 'lib/chef/knife/azure_server_create.rb', line 412

def create_server_def
  server_def = {
    :azure_storage_account => locate_config_value(:azure_storage_account),
    :azure_api_host_name => locate_config_value(:azure_api_host_name),
    :azure_dns_name => locate_config_value(:azure_dns_name),
    :azure_vm_name => locate_config_value(:azure_vm_name),
    :azure_service_location => locate_config_value(:azure_service_location),
    :azure_os_disk_name => locate_config_value(:azure_os_disk_name),
    :azure_source_image => locate_config_value(:azure_source_image),
    :azure_vm_size => locate_config_value(:azure_vm_size),
    :tcp_endpoints => locate_config_value(:tcp_endpoints),
    :udp_endpoints => locate_config_value(:udp_endpoints),
    :bootstrap_proto => locate_config_value(:bootstrap_protocol),
    :azure_connect_to_existing_dns => locate_config_value(:azure_connect_to_existing_dns),
    :winrm_user => locate_config_value(:winrm_user),
    :azure_availability_set => locate_config_value(:azure_availability_set),
    :azure_affinity_group => locate_config_value(:azure_affinity_group),
    :azure_network_name => locate_config_value(:azure_network_name),
    :azure_subnet_name => locate_config_value(:azure_subnet_name),
    :ssl_cert_fingerprint => locate_config_value(:thumbprint),
    :cert_path => locate_config_value(:cert_path),
    :cert_password => locate_config_value(:cert_passphrase),
    :winrm_transport => locate_config_value(:winrm_transport),
    :winrm_max_timeout => locate_config_value(:winrm_max_timeout).to_i * 60 * 1000, #converting minutes to milliseconds
    :winrm_max_memoryPerShell => locate_config_value(:winrm_max_memory_per_shell)
  }

  if locate_config_value(:bootstrap_protocol) == 'cloud-api'
    server_def[:chef_extension] = get_chef_extension_name
    server_def[:chef_extension_publisher] = get_chef_extension_publisher
    server_def[:chef_extension_version] = get_chef_extension_version
    server_def[:chef_extension_public_param] = get_chef_extension_public_params
    server_def[:chef_extension_private_param] = get_chef_extension_private_params
  else
    if is_image_windows?
      if not locate_config_value(:winrm_password) or not locate_config_value(:bootstrap_protocol)
        ui.error("WinRM Password and Bootstrapping Protocol are compulsory parameters")
        exit 1
      end
      # We can specify the AdminUsername after API version 2013-03-01. However, in this API version,
      # the AdminUsername is a required parameter.
      # Also, the user name cannot be Administrator, Admin, Admin1 etc, for enhanced security (provided by Azure)
      if locate_config_value(:winrm_user).nil? || locate_config_value(:winrm_user).downcase =~ /admin*/
        ui.error("WinRM User is compulsory parameter and it cannot be named 'admin*'")
        exit 1
      end
      # take cares of when user name contains domain
      # azure add role api doesn't support '\\' in user name
      if locate_config_value(:winrm_user) && locate_config_value(:winrm_user).split("\\").length.eql?(2)
        server_def[:winrm_user] = locate_config_value(:winrm_user).split("\\")[1]
      end
    else
      if not locate_config_value(:ssh_user)
        ui.error("SSH User is compulsory parameter")
        exit 1
      end
      unless locate_config_value(:ssh_password) or locate_config_value(:identity_file)
        ui.error("Specify either SSH Key or SSH Password")
        exit 1
      end
    end
  end

  if is_image_windows?
    server_def[:os_type] = 'Windows'
    server_def[:admin_password] = locate_config_value(:winrm_password)
    server_def[:bootstrap_proto] = locate_config_value(:bootstrap_protocol)
  else
    server_def[:os_type] = 'Linux'
    server_def[:bootstrap_proto] = (locate_config_value(:bootstrap_protocol) == 'winrm') ? 'ssh' : locate_config_value(:bootstrap_protocol)
    server_def[:ssh_user] = locate_config_value(:ssh_user)
    server_def[:ssh_password] = locate_config_value(:ssh_password)
    server_def[:identity_file] = locate_config_value(:identity_file)
    server_def[:identity_file_passphrase] = locate_config_value(:identity_file_passphrase)
  end

  azure_connect_to_existing_dns = locate_config_value(:azure_connect_to_existing_dns)
  if is_image_windows? && server_def[:bootstrap_proto] == 'winrm'
    port = locate_config_value(:winrm_port) || '5985'
    port = locate_config_value(:winrm_port) || Random.rand(64000) + 1000 if azure_connect_to_existing_dns
  elsif server_def[:bootstrap_proto] == 'ssh'
    port = locate_config_value(:ssh_port) || '22'
    port = locate_config_value(:ssh_port) || Random.rand(64000) + 1000 if azure_connect_to_existing_dns
  end

  server_def[:port] = port

  server_def[:is_vm_image] = service.vm_image?(locate_config_value(:azure_source_image))
  server_def[:azure_domain_name] = locate_config_value(:azure_domain_name) if locate_config_value(:azure_domain_name)

  if locate_config_value(:azure_domain_user)
    # extract domain name since it should be part of username
    case locate_config_value(:azure_domain_user)
    when /(\S+)\\(.+)/  # format - fully-qualified-DNS-domain\username
      server_def[:azure_domain_name] = $1 if locate_config_value(:azure_domain_name).nil?
      server_def[:azure_user_domain_name] = $1
      server_def[:azure_domain_user] = $2
    when /(.+)@(\S+)/  # format - user@fully-qualified-DNS-domain
      server_def[:azure_domain_name] = $2 if locate_config_value(:azure_domain_name).nil?
      server_def[:azure_user_domain_name] = $2
      server_def[:azure_domain_user] = $1
    else
      if locate_config_value(:azure_domain_name).nil?
        ui.error('--azure-domain-name should be specified if --azure-domain-user is not in one of the following formats: fully-qualified-DNS-domain\username, user@fully-qualified-DNS-domain')
        exit 1
      end
      server_def[:azure_domain_user] = locate_config_value(:azure_domain_user)
    end
  end
  server_def[:azure_domain_passwd] = locate_config_value(:azure_domain_passwd)
  server_def[:azure_domain_ou_dn] = locate_config_value(:azure_domain_ou_dn)

  server_def
end

#get_extension_statusObject



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

def get_extension_status()
  deployment_name = service.deployment_name(locate_config_value(:azure_dns_name))
  deployment = service.deployment("hostedservices/#{locate_config_value(:azure_dns_name)}/deployments/#{deployment_name}")
  extension_status = Hash.new

  if deployment.at_css('Deployment Name') != nil
    role_list_xml =  deployment.css('RoleInstanceList RoleInstance')
    role_list_xml.each do |role|
      if role.at_css("RoleName").text == locate_config_value(:azure_vm_name)
        lnx_waagent_fail_msg = "Failed to deserialize the status reported by the Guest Agent"
        waagent_status_msg = role.at_css("GuestAgentStatus FormattedMessage Message").text
        if role.at_css("GuestAgentStatus Status").text == "Ready"
          extn_status = role.at_css("ResourceExtensionStatusList Status").text
          Chef::Log.debug("Resource extension status is #{extn_status}")
          if extn_status == "Installing"
            extension_status[:status] = :extension_installing
            extension_status[:message] = role.at_css("ResourceExtensionStatusList FormattedMessage Message").text
          elsif extn_status == "NotReady"
            extension_status[:status] = :extension_provisioning
            extension_status[:message] = role.at_css("ResourceExtensionStatusList FormattedMessage Message").text
          elsif extn_status == "Ready"
            extension_status[:status] = :extension_ready
            extension_status[:message] = role.at_css("ResourceExtensionStatusList FormattedMessage Message").text
          else
            extension_status[:status] = :extension_status_not_detected
          end
        # This fix is for linux waagent issue: api unable to deserialize the waagent status.
        elsif (role.at_css('GuestAgentStatus Status').text == 'NotReady') && (waagent_status_msg == lnx_waagent_fail_msg)
          extension_status[:status] = :extension_ready
        else
          extension_status[:status] = :wagent_provisioning
          extension_status[:message] = role.at_css("GuestAgentStatus Message").text
        end
      else
        extension_status[:status] = :extension_status_not_detected
      end
    end
  else
    extension_status[:status] = :extension_status_not_detected
  end
  return extension_status
end

#get_virtual_machine_statusObject



331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/chef/knife/azure_server_create.rb', line 331

def get_virtual_machine_status()
  role = service.get_role_server(locate_config_value(:azure_dns_name), locate_config_value(:azure_vm_name))
  unless role.nil?
    Chef::Log.debug("Role status is #{role.status.to_s}")
    if  "ReadyRole".eql? role.status.to_s
      return :vm_status_ready
    elsif "Provisioning".eql? role.status.to_s
      return :vm_status_provisioning
    else
      return :vm_status_not_detected
    end
  end
  return :vm_status_not_detected
end

#runObject



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/chef/knife/azure_server_create.rb', line 389

def run
  $stdout.sync = true
  storage = nil
  Chef::Log.info("validating...")
  validate_asm_keys!(:azure_source_image)
  validate_params!
  ssh_override_winrm if !is_image_windows?
  Chef::Log.info("creating...")
  config[:azure_dns_name] = get_dns_name(locate_config_value(:azure_dns_name))
  config[:azure_vm_name] = locate_config_value(:azure_dns_name) unless locate_config_value(:azure_vm_name)
  config[:chef_node_name] = locate_config_value(:azure_vm_name) unless locate_config_value(:chef_node_name)
  service.create_server(create_server_def)
  wait_until_virtual_machine_ready()
  if locate_config_value(:bootstrap_protocol) == 'cloud-api' && locate_config_value(:extended_logs)
    print "\n\nWaiting for the first chef-client run"
    fetch_chef_client_logs(Time.now, 30)
  end
  server = service.get_role_server(locate_config_value(:azure_dns_name), locate_config_value(:azure_vm_name))
  msg_server_summary(server)

  bootstrap_exec(server) unless locate_config_value(:bootstrap_protocol) == 'cloud-api'
end

#wait_for_resource_extension_state(extension_status_goal, total_wait_time_in_minutes, retry_interval_in_seconds) ⇒ Object



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

def wait_for_resource_extension_state(extension_status_goal, total_wait_time_in_minutes, retry_interval_in_seconds)

  extension_status_ordering = {:extension_status_not_detected => 0, :wagent_provisioning => 1, :extension_installing => 2, :extension_provisioning => 3, :extension_ready => 4}

  status_description = {:extension_status_not_detected => 'any', :wagent_provisioning => 'wagent provisioning', :extension_installing => "installing", :extension_provisioning => "provisioning", :extension_ready => "ready" }

  print ui.color("Waiting for Resource Extension to reach status '#{status_description[extension_status_goal]}'", :magenta)

  max_polling_attempts = (total_wait_time_in_minutes * 60) / retry_interval_in_seconds
  polling_attempts = 0

  wait_start_time = Time.now

  begin
    extension_status = get_extension_status()
    extension_ready = extension_status_ordering[extension_status[:status]] >= extension_status_ordering[extension_status_goal]
    print '.'
    sleep retry_interval_in_seconds if !extension_ready
    polling_attempts += 1
  end until extension_ready || polling_attempts >= max_polling_attempts

  if ! extension_ready
    raise Chef::Exceptions::CommandTimeout, "Resource extension state '#{status_description[extension_status_goal]}' not reached after #{total_wait_time_in_minutes} minutes. #{extension_status[:message]}"
  end

  elapsed_time_in_minutes = ((Time.now - wait_start_time) / 60).round(2)
  print ui.color("Resource extension state '#{status_description[extension_status_goal]}' reached after #{elapsed_time_in_minutes} minutes.\n", :cyan)

  extension_status[:status]
end

#wait_for_virtual_machine_state(vm_status_goal, total_wait_time_in_minutes, retry_interval_in_seconds) ⇒ Object



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

def wait_for_virtual_machine_state(vm_status_goal, total_wait_time_in_minutes, retry_interval_in_seconds)
  vm_status_ordering = {:vm_status_not_detected => 0, :vm_status_provisioning => 1, :vm_status_ready => 2}
  vm_status_description = {:vm_status_not_detected => 'any', :vm_status_provisioning => 'provisioning', :vm_status_ready => 'ready'}

  print ui.color("Waiting for virtual machine to reach status '#{vm_status_description[vm_status_goal]}'", :magenta)

  total_wait_time_in_seconds = total_wait_time_in_minutes * 60
  max_polling_attempts = total_wait_time_in_seconds / retry_interval_in_seconds
  polling_attempts = 0

  wait_start_time = Time.now

  begin
    vm_status = get_virtual_machine_status()
    vm_ready = vm_status_ordering[vm_status] >= vm_status_ordering[vm_status_goal]
    print '.'
    sleep retry_interval_in_seconds if !vm_ready
    polling_attempts += 1
  end until vm_ready || polling_attempts >= max_polling_attempts

  if ! vm_ready
    raise Chef::Exceptions::CommandTimeout, "Virtual machine state '#{vm_status_description[vm_status_goal]}' not reached after #{total_wait_time_in_minutes} minutes."
  end

  elapsed_time_in_minutes = ((Time.now - wait_start_time) / 60).round(2)
  print ui.color("vm state '#{vm_status_description[vm_status_goal]}' reached after #{elapsed_time_in_minutes} minutes.\n", :cyan)
  vm_status
end

#wait_until_virtual_machine_ready(retry_interval_in_seconds = 30) ⇒ Object



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

def wait_until_virtual_machine_ready(retry_interval_in_seconds = 30)
  vm_status = nil
  begin
    azure_vm_startup_timeout = locate_config_value(:azure_vm_startup_timeout).to_i
    azure_vm_ready_timeout = locate_config_value(:azure_vm_ready_timeout).to_i
    vm_status = wait_for_virtual_machine_state(:vm_status_provisioning, azure_vm_startup_timeout, retry_interval_in_seconds)
    if vm_status != :vm_status_ready
      begin
        wait_for_virtual_machine_state(:vm_status_ready, azure_vm_ready_timeout, retry_interval_in_seconds)
      rescue Chef::Exceptions::CommandTimeout => e
        ui.warn("\n#{e.message}")
        ui.warn("Ignoring failure to reach 'ready' with bootstrap.")
      end
    end

    msg_server_summary(service.get_role_server(locate_config_value(:azure_dns_name), locate_config_value(:azure_vm_name)))

    if locate_config_value(:bootstrap_protocol) == "cloud-api"
      extension_status = wait_for_resource_extension_state(:wagent_provisioning, 5, retry_interval_in_seconds)

      if extension_status != :extension_installing
        extension_status = wait_for_resource_extension_state(:extension_installing, 5, retry_interval_in_seconds)
      end

      if extension_status != :extension_provisioning
        extension_status = wait_for_resource_extension_state(:extension_provisioning, 10, retry_interval_in_seconds)
      end

      if extension_status != :extension_ready
        wait_for_resource_extension_state(:extension_ready, 5, retry_interval_in_seconds)
      end
    end
  rescue Exception => e
    Chef::Log.error("#{e.to_s}")
    raise 'Verify connectivity to Azure and subscription resource limit compliance (e.g. maximum CPU core limits) and try again.'
  end
end