Class: VagrantPlugins::Cosmic::Action::RunInstance

Inherits:
Object
  • Object
show all
Includes:
Vagrant::Util::Retryable, Exceptions, Model, Service
Defined in:
lib/vagrant-cosmic/action/run_instance.rb

Overview

This runs the configured instance.

Instance Method Summary collapse

Constructor Details

#initialize(app, env) ⇒ RunInstance

Returns a new instance of RunInstance.



18
19
20
21
22
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 18

def initialize(app, env)
  @app              = app
  @logger           = Log4r::Logger.new('vagrant_cosmic::action::run_instance')
  @resource_service = CosmicResourceService.new(env[:cosmic_compute], env[:ui])
end

Instance Method Details

#apply_firewall_rule(acl_name, options, response_string, type_string) ⇒ Object



650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 650

def apply_firewall_rule(acl_name, options, response_string, type_string)
  firewall_rule = nil
  begin
    resp = @env[:cosmic_compute].request(options)
    job_id = resp[response_string]['jobid']

    if job_id.nil?
      @env[:ui].warn(" -- Failed to create firewall rule: #{resp[response_string]['errortext']}")
      return
    end

    while true
      response = @env[:cosmic_compute].query_async_job_result({:jobid => job_id})
      if response['queryasyncjobresultresponse']['jobstatus'] != 0
        firewall_rule = response['queryasyncjobresultresponse']['jobresult'][type_string]
        break
      else
        sleep 2
      end
    end
  rescue Fog::Cosmic::Compute::Error => e
    if e.message =~ /The range specified,.*conflicts with rule/
      @env[:ui].warn(" -- Failed to create firewall rule: #{e.message}")
    elsif e.message =~ /Default ACL cannot be modified/
      @env[:ui].warn(" -- Failed to create network acl: #{e.message}: #{acl_name}")
    else
      raise Fog::Cosmic::Compute::Error, :message => e.message
    end
  end
  firewall_rule
end

#apply_firewall_rulesObject



560
561
562
563
564
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 560

def apply_firewall_rules
  @domain_config.firewall_rules.each do |firewall_rule|
    create_firewall_rule(firewall_rule)
  end
end

#apply_port_forwarding_rule(rule) ⇒ Object



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
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 417

def apply_port_forwarding_rule(rule)
  port_forwarding_rule = nil
  @env[:ui].info(I18n.t('vagrant_cosmic.creating_port_forwarding_rule'))

  return unless (options = compose_port_forwarding_rule_creation_options(rule))

  begin
    resp = @env[:cosmic_compute].create_port_forwarding_rule(options)
    job_id = resp['createportforwardingruleresponse']['jobid']

    if job_id.nil?
      @env[:ui].warn(" -- Failed to create port forwarding rule: #{resp['createportforwardingruleresponse']['errortext']}")
      return
    end

    while true
      response = @env[:cosmic_compute].query_async_job_result({:jobid => job_id})
      if response['queryasyncjobresultresponse']['jobstatus'] != 0
        port_forwarding_rule = response['queryasyncjobresultresponse']['jobresult']['portforwardingrule']
        break
      else
        sleep 2
      end
    end
  rescue Fog::Cosmic::Compute::Error => e
    raise Fog::Cosmic::Compute::Error, :message => e.message
  end

  store_port_forwarding_rules(port_forwarding_rule)
end

#apply_port_forwarding_rulesObject



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 401

def apply_port_forwarding_rules
  return if @domain_config.port_forwarding_rules.empty?

  @domain_config.port_forwarding_rules.each do |port_forwarding_rule|
    # Sanatize/defaults pf rule before applying
    port_forwarding_rule[:ipaddressid] = @domain_config.pf_ip_address_id if port_forwarding_rule[:ipaddressid].nil?
    port_forwarding_rule[:ipaddress] = @domain_config.pf_ip_address if port_forwarding_rule[:ipaddress].nil?
    port_forwarding_rule[:protocol] = 'tcp' if port_forwarding_rule[:protocol].nil?
    port_forwarding_rule[:openfirewall] = @domain_config.pf_open_firewall if port_forwarding_rule[:openfirewall].nil?
    port_forwarding_rule[:publicport] = port_forwarding_rule[:privateport] if port_forwarding_rule[:publicport].nil?
    port_forwarding_rule[:privateport] = port_forwarding_rule[:publicport] if port_forwarding_rule[:privateport].nil?

    apply_port_forwarding_rule(port_forwarding_rule)
  end
end

#auto_complete_firewall_rulesObject



550
551
552
553
554
555
556
557
558
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 550

def auto_complete_firewall_rules
  @domain_config.firewall_rules.each do |firewall_rule|
    firewall_rule[:ipaddressid] = @domain_config.pf_ip_address_id if firewall_rule[:ipaddressid].nil?
    firewall_rule[:ipaddress] = @domain_config.pf_ip_address if firewall_rule[:ipaddress].nil?
    firewall_rule[:cidrlist] = @domain_config.pf_trusted_networks.join(',') if firewall_rule[:cidrlist].nil?
    firewall_rule[:protocol] = 'tcp' if firewall_rule[:protocol].nil?
    firewall_rule[:startport] = firewall_rule[:endport] if firewall_rule[:startport].nil?
  end
end

#call(env) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 24

def call(env)
  # Initialize metrics if they haven't been
  env[:metrics] ||= {}
  @env = env

  sanatize_creation_parameters

  show_creation_summary

  create_vm

  wait_for_instance_ready

  store_volumes

  store_password

  configure_networking

  unless @env[:interrupted]
    wait_for_communicator_ready
    @env[:ui].info(I18n.t('vagrant_cosmic.ready'))
  end

  # Terminate the instance if we were interrupted
  terminate if @env[:interrupted]

  @app.call(@env)
end

#compose_firewall_rule_creation_options_non_vpc(ip_address, rule) ⇒ Object



622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 622

def compose_firewall_rule_creation_options_non_vpc(ip_address, rule)
  command_string = 'createFirewallRule'
  response_string = 'createfirewallruleresponse'
  type_string = 'firewallrule'
  options = {
      :command => command_string,
      :ipaddressid => ip_address.id,
      :protocol => rule[:protocol],
      :cidrlist => rule[:cidrlist],
      :startport => rule[:startport],
      :endeport => rule[:endport],
      :icmpcode => rule[:icmpcode],
      :icmptype => rule[:icmptype]
  }
  return options, response_string, type_string
end

#compose_firewall_rule_creation_options_vpc(network, rule) ⇒ Object



603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 603

def compose_firewall_rule_creation_options_vpc(network, rule)
  command_string = 'createNetworkACL'
  response_string = 'createnetworkaclresponse'
  type_string = 'networkacl'
  options = {
      :command => command_string,
      :aclid => network.details['aclid'],
      :action => 'Allow',
      :protocol => rule[:protocol],
      :cidrlist => rule[:cidrlist],
      :startport => rule[:startport],
      :endport => rule[:endport],
      :icmpcode => rule[:icmpcode],
      :icmptype => rule[:icmptype],
      :traffictype => 'Ingress'
  }
  return options, response_string, type_string
end

#compose_port_forwarding_rule_creation_options(rule) ⇒ Object



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
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 448

def compose_port_forwarding_rule_creation_options(rule)
  begin
    ip_address = sync_ip_address(rule[:ipaddressid], rule[:ipaddress])
  rescue IpNotFoundException
    return
  end

  @env[:ui].info(" -- IP address    : #{ip_address.name} (#{ip_address.id})")
  @env[:ui].info(" -- Protocol      : #{rule[:protocol]}")
  @env[:ui].info(" -- Public port   : #{rule[:publicport]}")
  @env[:ui].info(" -- Private port  : #{rule[:privateport]}")
  @env[:ui].info(" -- Open Firewall : #{rule[:openfirewall]}")

  network = get_network_from_public_ip(ip_address)

  options = {
      :networkid => network.id,
      :ipaddressid => ip_address.id,
      :publicport => rule[:publicport],
      :privateport => rule[:privateport],
      :protocol => rule[:protocol],
      :openfirewall => rule[:openfirewall],
      :virtualmachineid => @env[:machine].id
  }

  options.delete(:openfirewall) if network.details.has_key?('vpcid')
  options
end

#compose_server_creation_optionsObject



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
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 216

def compose_server_creation_options
  options = {
      :display_name => @domain_config.display_name,
      :group => @domain_config.group,
      :zone_id => @zone.id,
      :flavor_id => @service_offering.id,
      :image_id => @template.id
  }

  unless @affinity_groups.empty?
    ags = @affinity_groups.map(&:id).compact.join(",")
    options['affinity_group_ids'] = ags unless ags.empty?
  end
  unless @networks.empty?
    nets = @networks.map(&:id).compact.join(",")
    options['network_ids'] = nets unless nets.empty?
  end
  options['project_id'] = @domain_config.project_id unless @domain_config.project_id.nil?
  options['key_name'] = @domain_config.keypair unless @domain_config.keypair.nil?
  options['name'] = @domain_config.name unless @domain_config.name.nil?
  options['ip_address'] = @domain_config.private_ip_address unless @domain_config.private_ip_address.nil?
  options['disk_offering_id'] = @disk_offering.id unless @disk_offering.id.nil?

  if @domain_config.user_data != nil
    options['user_data'] = Base64.urlsafe_encode64(@domain_config.user_data)
    if options['user_data'].length > 2048
      raise Errors::UserdataError,
            :userdataLength => options['user_data'].length
    end
  end
  options
end

#configure_firewallObject



487
488
489
490
491
492
493
494
495
496
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 487

def configure_firewall
  if @domain_config.pf_trusted_networks
    generate_firewall_rules_for_communicators unless @pf_ip_address.is_undefined?
    generate_firewall_rules_for_portforwarding_rules
  end

  return if @domain_config.firewall_rules.empty?
  auto_complete_firewall_rules
  apply_firewall_rules
end

#configure_networkingObject



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 249

def configure_networking
  begin
    enable_static_nat_rules

    configure_port_forwarding

    # First create_port_forwardings,
    # as it may generate 'pf_public_port' or 'pf_public_rdp_port',
    # which after this may need a firewall rule
    configure_firewall

  rescue CosmicResourceNotFound => e
    @env[:ui].error(e.message)
    terminate
    exit(false)
  end
end

#configure_port_forwardingObject



311
312
313
314
315
316
317
318
319
320
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 311

def configure_port_forwarding

  unless @pf_ip_address.is_undefined?
    evaluate_pf_private_port
    evaluate_pf_private_rdp_port
    generate_and_apply_port_forwarding_rules_for_communicators
  end

  apply_port_forwarding_rules
end

#create_firewall_rule(rule) ⇒ Object



566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 566

def create_firewall_rule(rule)
  acl_name = ''
  firewall_rule = nil
  @env[:ui].info(I18n.t('vagrant_cosmic.creating_firewall_rule'))

  ip_address = CosmicResource.new(rule[:ipaddressid], rule[:ipaddress], 'public_ip_address')
  @resource_service.sync_resource(ip_address)

  @env[:ui].info(" -- IP address : #{ip_address.name} (#{ip_address.id})")
  @env[:ui].info(" -- Protocol   : #{rule[:protocol]}")
  @env[:ui].info(" -- CIDR list  : #{rule[:cidrlist]}")
  @env[:ui].info(" -- Start port : #{rule[:startport]}")
  @env[:ui].info(" -- End port   : #{rule[:endport]}")
  @env[:ui].info(" -- ICMP code  : #{rule[:icmpcode]}")
  @env[:ui].info(" -- ICMP type  : #{rule[:icmptype]}")

  if ip_address.details.has_key?('vpcid')
    network = @networks.find{ |f| f.id == ip_address.details['associatednetworkid']}
    acl_id = network.details['aclid']

    raise CosmicResourceNotFound.new("No ACL found associated with VPC tier #{network.details['name']} (id: #{network.details['id']})") unless acl_id

    resp = @env[:cosmic_compute].list_network_acl_lists(
        id:  network.details[acl_id]
    )
    acl_name = resp['listnetworkacllistsresponse']['networkacllist'][0]['name']

    options, response_string, type_string = compose_firewall_rule_creation_options_vpc(network, rule)
  else
    options, response_string, type_string = compose_firewall_rule_creation_options_non_vpc(ip_address, rule)
  end

  firewall_rule = apply_firewall_rule(acl_name, options, response_string, type_string)

  store_firewall_rule(firewall_rule, type_string) if firewall_rule
end

#create_randomport_forwarding_rule(rule, randomrange, filename) ⇒ Object



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
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 375

def create_randomport_forwarding_rule(rule, randomrange, filename)
  pf_public_port = rule[:publicport]
  retryable(:on => DuplicatePFRule, :tries => 10) do
    begin
      # Only if public port is missing, will generate a random one
      rule[:publicport] = Kernel.rand(randomrange) if pf_public_port.nil?

      apply_port_forwarding_rule(rule)

      if pf_public_port.nil?
        pf_port_file = @env[:machine].data_dir.join(filename)
        pf_port_file.open('a+') do |f|
          f.write("#{rule[:publicport]}")
        end
      end
    rescue Fog::Cosmic::Compute::Error => e
      if pf_public_port.nil? && !(e.message =~ /The range specified,.*conflicts with rule.*which has/).nil?
        raise DuplicatePFRule, :message => e.message
      else
        raise Fog::Cosmic::Compute::Error, :message => e.message
      end
    end
  end
  pf_public_port.nil? ? (rule[:publicport]) : (pf_public_port)
end

#create_vmObject



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 192

def create_vm
  @server = nil
  begin
    options = compose_server_creation_options

    @server = @env[:cosmic_compute].servers.create(options)
    @server_job_id = @server.job_id
  rescue Fog::Cosmic::Compute::NotFound => e
    # Invalid subnet doesn't have its own error so we catch and
    # check the error message here.
    # XXX FIXME vpc?
    if e.message =~ /subnet ID/
      raise Fog::Cosmic::Compute::Error,
            :message => "Subnet ID not found: #{@networks.map(&:id).compact.join(",")}"
    end

    raise
  rescue Fog::Cosmic::Compute::Error => e
    raise Fog::Cosmic::Compute::Error, :message => e.message
  end

  @env[:machine].id = @server.id
end

#enable_static_nat(rule) ⇒ Object



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
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 275

def enable_static_nat(rule)
  @env[:ui].info(I18n.t('vagrant_cosmic.enabling_static_nat'))

  begin
    ip_address = sync_ip_address(rule[:ipaddressid], rule[:ipaddress])
  rescue IpNotFoundException
    return
  end

  @env[:ui].info(" -- IP address : #{ip_address.name} (#{ip_address.id})")

  options = {
      :command          => 'enableStaticNat',
      :ipaddressid      => ip_address_id,
      :virtualmachineid => @env[:machine].id
  }

  begin
    resp = @env[:cosmic_compute].request(options)
    is_success = resp['enablestaticnatresponse']['success']

    if is_success != 'true'
      @env[:ui].warn(" -- Failed to enable static nat: #{resp['enablestaticnatresponse']['errortext']}")
      return
    end
  rescue Fog::Cosmic::Compute::Error => e
    raise Fog::Cosmic::Compute::Error, :message => e.message
  end

  # Save ipaddress id to the data dir so it can be disabled when the instance is destroyed
  static_nat_file = @env[:machine].data_dir.join('static_nat')
  static_nat_file.open('a+') do |f|
    f.write("#{ip_address.id}\n")
  end
end

#enable_static_nat_rulesObject



267
268
269
270
271
272
273
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 267

def enable_static_nat_rules
  unless @domain_config.static_nat.empty?
    @domain_config.static_nat.each do |rule|
      enable_static_nat(rule)
    end
  end
end

#evaluate_pf_private_portObject



330
331
332
333
334
335
336
337
338
339
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 330

def evaluate_pf_private_port
  return unless @domain_config.pf_private_port.nil?

  communicator_short_name = get_communicator_short_name(@env[:machine].communicate)
  communicator_config = @env[:machine].config.send(communicator_short_name)

  @domain_config.pf_private_port = communicator_config.port if communicator_config.respond_to?('port')
  @domain_config.pf_private_port = communicator_config.guest_port if communicator_config.respond_to?('guest_port')
  @domain_config.pf_private_port = communicator_config.default.port if (communicator_config.respond_to?('default') && communicator_config.default.respond_to?('port'))
end

#evaluate_pf_private_rdp_portObject



341
342
343
344
345
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 341

def evaluate_pf_private_rdp_port
  @domain_config.pf_private_rdp_port = @env[:machine].config.vm.rdp.port if
                                          @env[:machine].config.vm.respond_to?(:rdp) &&
                                          @env[:machine].config.vm.rdp.respond_to?(:port)
end

#generate_and_apply_port_forwarding_rules_for_communicatorsObject



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
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 347

def generate_and_apply_port_forwarding_rules_for_communicators
  communicators_port_names = [Hash[:public_port => 'pf_public_port', :private_port => 'pf_private_port']]
  communicators_port_names << Hash[:public_port => 'pf_public_rdp_port', :private_port => 'pf_private_rdp_port'] if is_windows_guest

  communicators_port_names.each do |communicator_port_names|
    public_port_name = communicator_port_names[:public_port]
    private_port_name = communicator_port_names[:private_port]

    next unless @domain_config.send(public_port_name) || @domain_config.pf_public_port_randomrange

    port_forwarding_rule = {
        :ipaddressid => @domain_config.pf_ip_address_id,
        :ipaddress => @domain_config.pf_ip_address,
        :protocol => 'tcp',
        :publicport => @domain_config.send(public_port_name),
        :privateport => @domain_config.send(private_port_name),
        :openfirewall => @domain_config.pf_open_firewall
    }

    public_port = create_randomport_forwarding_rule(
        port_forwarding_rule,
        @domain_config.pf_public_port_randomrange[:start]...@domain_config.pf_public_port_randomrange[:end],
        public_port_name
    )
    @domain_config.send("#{public_port_name}=", public_port)
  end
end

#generate_display_nameObject



163
164
165
166
167
168
169
170
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 163

def generate_display_name
  local_user = ENV['USER'] ? ENV['USER'].dup : 'VACS'
  local_user.gsub!(/[^-a-z0-9_]/i, '')
  prefix = @env[:root_path].basename.to_s
  prefix.gsub!(/[^-a-z0-9_]/i, '')

  local_user + '_' + prefix + "_#{Time.now.to_i}"
end

#generate_firewall_rules_for_communicatorsObject



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
526
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 498

def generate_firewall_rules_for_communicators

  return if @pf_ip_address.is_undefined? ||
      !@domain_config.pf_trusted_networks ||
      @domain_config.pf_open_firewall

  ports = [Hash[publicport: 'pf_public_port', privateport: 'pf_private_port']]
  ports << Hash[publicport: 'pf_public_rdp_port', privateport: 'pf_private_rdp_port'] if is_windows_guest

  ports.each do |port_set|
    forward_portname = @pf_ip_address.details.key?('vpcid') ? port_set[:privateport] : port_set[:publicport]
    check_portname = port_set[:publicport]

    next unless @domain_config.send(check_portname)

    # Allow access to public port from trusted networks only
    fw_rule_trusted_networks = {
        ipaddressid: @pf_ip_address.id,
        ipaddress: @pf_ip_address.name,
        protocol: 'tcp',
        startport: @domain_config.send(forward_portname),
        endport: @domain_config.send(forward_portname),
        cidrlist: @domain_config.pf_trusted_networks.join(',')
    }
    @domain_config.firewall_rules = [] unless @domain_config.firewall_rules
    @domain_config.firewall_rules << fw_rule_trusted_networks

  end
end

#generate_firewall_rules_for_portforwarding_rulesObject



528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 528

def generate_firewall_rules_for_portforwarding_rules
  @pf_ip_address.details.has_key?('vpcid') ? port_name = :privateport : port_name = :publicport

  unless @domain_config.port_forwarding_rules.empty?
    @domain_config.port_forwarding_rules.each do |port_forwarding_rule|
      if port_forwarding_rule[:generate_firewall] && @domain_config.pf_trusted_networks && !port_forwarding_rule[:openfirewall]
        # Allow access to public port from trusted networks only
        fw_rule_trusted_networks = {
            :ipaddressid => port_forwarding_rule[:ipaddressid],
            :ipaddress => port_forwarding_rule[:ipaddress],
            :protocol => port_forwarding_rule[:protocol],
            :startport => port_forwarding_rule[port_name],
            :endport => port_forwarding_rule[port_name],
            :cidrlist => @domain_config.pf_trusted_networks.join(',')
        }
        @domain_config.firewall_rules = [] unless @domain_config.firewall_rules
        @domain_config.firewall_rules << fw_rule_trusted_networks
      end
    end
  end
end

#generate_ssh_keypair(keyname, account = nil, domainid = nil, projectid = nil) ⇒ Object



686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 686

def generate_ssh_keypair(keyname,  = nil, domainid = nil, projectid = nil)
  response = @env[:cosmic_compute].create_ssh_key_pair(keyname, , domainid, projectid)
  sshkeypair = response['createsshkeypairresponse']['keypair']

  # Save private key to file
  sshkeyfile_file = @env[:machine].data_dir.join('sshkeyfile')
  sshkeyfile_file.open('w') do |f|
    f.write("#{sshkeypair['privatekey']}")
  end
  @domain_config.ssh_key = sshkeyfile_file.to_s

  sshkeyname_file = @env[:machine].data_dir.join('sshkeyname')
  sshkeyname_file.open('w') do |f|
    f.write("#{sshkeypair['name']}")
  end

  @domain_config.keypair =  sshkeypair['name']
end

#get_communicator_short_name(communicator) ⇒ Object



322
323
324
325
326
327
328
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 322

def get_communicator_short_name(communicator)
  communicator_short_names = {
    'VagrantPlugins::CommunicatorSSH::Communicator' => 'ssh',
    'VagrantPlugins::CommunicatorWinRM::Communicator' => 'winrm'
  }
  communicator_short_names[communicator.class.name]
end

#get_network_from_public_ip(ip_address) ⇒ Object



477
478
479
480
481
482
483
484
485
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 477

def get_network_from_public_ip(ip_address)
  if ip_address.details.has_key?('associatednetworkid')
    network = @networks.find {|f| f.id == ip_address.details['associatednetworkid']}
  elsif ip_address.details.has_key?('vpcid')
    # In case of VPC and ip has not yet been used, a network MUST be specified
    network = @networks.find {|f| f.details['vpcid'] == ip_address.details['vpcid']}
  end
  network
end

#get_next_free_acl_entry(network) ⇒ Object



639
640
641
642
643
644
645
646
647
648
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 639

def get_next_free_acl_entry(network)
  resp = @env[:cosmic_compute].list_network_acls(
      aclid: network.details['aclid']
  )
  number = 0
  if resp["listnetworkaclsresponse"].key?("networkacl")
    resp["listnetworkaclsresponse"]["networkacl"].each {|ace| number = [number, ace["number"]].max}
  end
  number = number+1
end

#initialize_parametersObject



118
119
120
121
122
123
124
125
126
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 118

def initialize_parameters
  @affinity_groups = CosmicResource.create_list(@domain_config.affinity_group_id, @domain_config.affinity_group_name, 'affinity_group')
  @zone = CosmicResource.new(@domain_config.zone_id, @domain_config.zone_name, 'zone')
  @networks = CosmicResource.create_list(@domain_config.network_id, @domain_config.network_name, 'network')
  @service_offering = CosmicResource.new(@domain_config.service_offering_id, @domain_config.service_offering_name, 'service_offering')
  @disk_offering = CosmicResource.new(@domain_config.disk_offering_id, @domain_config.disk_offering_name, 'disk_offering')
  @template = CosmicResource.new(@domain_config.template_id, @domain_config.template_name || @env[:machine].config.vm.box, 'template')
  @pf_ip_address = CosmicResource.new(@domain_config.pf_ip_address_id, @domain_config.pf_ip_address, 'public_ip_address')
end

#is_windows_guestObject



682
683
684
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 682

def is_windows_guest
  false || @env[:machine].config.vm.guest == :windows || get_communicator_short_name(@env[:machine].communicate) == 'winrm'
end

#recover(env) ⇒ Object



809
810
811
812
813
814
815
816
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 809

def recover(env)
  return if env['vagrant.error'].is_a?(Vagrant::Errors::VagrantError)

  if env[:machine].provider.state.id != :not_created
    # Undo the import
    terminate
  end
end

#resolve_network(cs_zone) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 144

def resolve_network(cs_zone)
  if cs_zone.network_type.downcase == 'basic'
    # No network specification in basic zone
    @env[:ui].warn(I18n.t('vagrant_cosmic.basic_network', :zone_name => @zone.name)) if !@networks.empty? && (@networks[0].id || @networks[0].name)
    @networks = [CosmicResource.new(nil, nil, 'network')]

    # No portforwarding in basic zone, so none of the below
    @domain_config.pf_ip_address = nil
    @domain_config.pf_ip_address_id = nil
    @domain_config.pf_public_port = nil
    @domain_config.pf_public_rdp_port = nil
    @domain_config.pf_public_port_randomrange = nil
  else
    @networks.each do |network|
      @resource_service.sync_resource(network)
    end
  end
end

#resolve_parametersObject



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 128

def resolve_parameters
  begin
    @resource_service.sync_resource(@zone, {available: true, name: @zone.name})
    @resource_service.sync_resource(@service_offering, {listall: true, name: @service_offering.name})
    @resource_service.sync_resource(@disk_offering, {listall: true, name: @disk_offering.name})
    @resource_service.sync_resource(@template, {zoneid: @zone.id, templatefilter: 'executable', listall: true, name: @template.name})
    @resource_service.sync_resource(@pf_ip_address)
    @affinity_groups.each do |affinity_group|
      @resource_service.sync_resource(affinity_group)
    end
  rescue CosmicResourceNotFound => e
    @env[:ui].error(e.message)
    exit(false)
  end
end

#sanatize_creation_parametersObject



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 54

def sanatize_creation_parameters
  # Get the domain we're going to booting up in
  @domain = @env[:machine].provider_config.domain_id
  # Get the configs
  @domain_config = @env[:machine].provider_config.get_domain_config(@domain)

  sanitize_domain_config

  initialize_parameters

  if @zone.is_undefined?
    @env[:ui].error("No Zone specified!")
    exit(false)
  end

  resolve_parameters

  cs_zone = @env[:cosmic_compute].zones.find {|f| f.id == @zone.id}
  resolve_network(cs_zone)

  @domain_config.display_name = generate_display_name if @domain_config.display_name.nil?

  if @domain_config.keypair.nil? && @domain_config.ssh_key.nil?
    @env[:ui].warn(I18n.t('vagrant_cosmic.launch_no_keypair_no_sshkey'))
    generate_ssh_keypair("vagacs_#{@domain_config.display_name}_#{sprintf('%04d', rand(9999))}",
                         nil, @domain, @domain_config.project_id)
  end
end

#sanitize_domain_configObject



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 83

def sanitize_domain_config
  # Accept a single entry as input, convert it to array
  @domain_config.pf_trusted_networks = Array(@domain_config.pf_trusted_networks) if @domain_config.pf_trusted_networks

  if @domain_config.affinity_group_id.nil?
    # Use names if ids are not present
    @domain_config.affinity_group_id = []

    if @domain_config.affinity_group_name.nil?
      @domain_config.affinity_group_name = []
    else
      @domain_config.affinity_group_name = Array(@domain_config.affinity_group_name)
    end
  else
    # Use ids if present
    @domain_config.affinity_group_id = Array(@domain_config.affinity_group_id)
    @domain_config.affinity_group_name = []
  end

  if @domain_config.network_id.nil?
    # Use names if ids are not present
    @domain_config.network_id = []

    if @domain_config.network_name.nil?
      @domain_config.network_name = []
    else
      @domain_config.network_name = Array(@domain_config.network_name)
    end
  else
    # Use ids if present
    @domain_config.network_id = Array(@domain_config.network_id)
    @domain_config.network_name = []
  end
end

#show_creation_summaryObject



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 172

def show_creation_summary
  # Launch!
  @env[:ui].info(I18n.t('vagrant_cosmic.launching_instance'))
  @env[:ui].info(" -- Display Name: #{@domain_config.display_name}")
  @affinity_groups.each do |affinity_group|
    @env[:ui].info(" -- Affinity group: #{affinity_group.name} (#{affinity_group.id})")
  end
  @env[:ui].info(" -- Group: #{@domain_config.group}") if @domain_config.group
  @env[:ui].info(" -- Service offering: #{@service_offering.name} (#{@service_offering.id})")
  @env[:ui].info(" -- Disk offering: #{@disk_offering.name} (#{@disk_offering.id})") unless @disk_offering.id.nil?
  @env[:ui].info(" -- Template: #{@template.name} (#{@template.id})")
  @env[:ui].info(" -- Project UUID: #{@domain_config.project_id}") unless @domain_config.project_id.nil?
  @env[:ui].info(" -- Zone: #{@zone.name} (#{@zone.id})")
  @networks.each do |network|
    @env[:ui].info(" -- Network: #{network.name} (#{network.id})")
  end
  @env[:ui].info(" -- Keypair: #{@domain_config.keypair}") if @domain_config.keypair
  @env[:ui].info(' -- User Data: Yes') if @domain_config.user_data
end

#store_firewall_rule(firewall_rule, type_string) ⇒ Object



749
750
751
752
753
754
755
756
757
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 749

def store_firewall_rule(firewall_rule, type_string)
  unless firewall_rule.nil?
    # Save firewall rule id to the data dir so it can be released when the instance is destroyed
    firewall_file = @env[:machine].data_dir.join('firewall')
    firewall_file.open('a+') do |f|
      f.write("#{firewall_rule['id']},#{type_string}\n")
    end
  end
end

#store_passwordObject



705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 705

def store_password
  password = nil
  if @server.password_enabled and @server.respond_to?('job_id')
    server_job_result = @env[:cosmic_compute].query_async_job_result({:jobid => @server_job_id})
    if server_job_result.nil?
      @env[:ui].warn(' -- Failed to retrieve job_result for retrieving the password')
      return
    end

    while true
      server_job_result = @env[:cosmic_compute].query_async_job_result({:jobid => @server_job_id})
      if server_job_result['queryasyncjobresultresponse']['jobstatus'] != 0
        password = server_job_result['queryasyncjobresultresponse']['jobresult']['virtualmachine']['password']
        break
      else
        sleep 2
      end
    end

    @env[:ui].info("Password of virtualmachine: #{password}")
    # Set the password on the current communicator
    @domain_config.vm_password = password

    # Save password to file
    vmcredentials_file = @env[:machine].data_dir.join('vmcredentials')
    vmcredentials_file.open('w') do |f|
      f.write("#{password}")
    end
  end
end

#store_port_forwarding_rules(port_forwarding_rule) ⇒ Object



759
760
761
762
763
764
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 759

def store_port_forwarding_rules(port_forwarding_rule)
  port_forwarding_file = @env[:machine].data_dir.join('port_forwarding')
  port_forwarding_file.open('a+') do |f|
    f.write("#{port_forwarding_rule['id']}\n")
  end
end

#store_volumesObject



736
737
738
739
740
741
742
743
744
745
746
747
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 736

def store_volumes
  volumes = @env[:cosmic_compute].volumes.find_all { |f| f.server_id == @server.id }
  # volumes refuses to be iterated directly, do it by index
  (0...volumes.length).each do |idx|
    unless volumes[idx].type == 'ROOT'
      volumes_file = @env[:machine].data_dir.join('volumes')
      volumes_file.open('a+') do |f|
        f.write("#{volumes[idx].id}\n")
      end
    end
  end
end

#terminateObject



818
819
820
821
822
823
824
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 818

def terminate
  destroy_env = @env.dup
  destroy_env.delete(:interrupted)
  destroy_env[:config_validate]       = false
  destroy_env[:force_confirm_destroy] = true
  @env[:action_runner].run(Action.action_destroy, destroy_env)
end

#wait_for_communicator_readyObject



766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 766

def wait_for_communicator_ready
  @env[:metrics]['instance_ssh_time'] = Util::Timer.time do
    # Wait for communicator to be ready.
    communicator_short_name = get_communicator_short_name(@env[:machine].communicate)
    @env[:ui].info(
      I18n.t('vagrant_cosmic.waiting_for_communicator',
             communicator: communicator_short_name.to_s.upcase)
    )
    while true
      # If we're interrupted then just back out
      break if @env[:interrupted]
      break if @env[:machine].communicate.ready?
      sleep 2
    end
  end
  @logger.info("Time for SSH ready: #{@env[:metrics]['instance_ssh_time']}")
end

#wait_for_instance_readyObject



784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
# File 'lib/vagrant-cosmic/action/run_instance.rb', line 784

def wait_for_instance_ready
  @env[:metrics]['instance_ready_time'] = Util::Timer.time do
    tries = @domain_config.instance_ready_timeout / 2

    @env[:ui].info(I18n.t('vagrant_cosmic.waiting_for_ready'))
    begin
      retryable(:on => Fog::Errors::TimeoutError, :tries => tries) do
        # If we're interrupted don't worry about waiting
        next if @env[:interrupted]

        # Wait for the server to be ready
        @server.wait_for(2) { ready? }
      end
    rescue Fog::Errors::TimeoutError
      # Delete the instance
      terminate

      # Notify the user
      raise Errors::InstanceReadyTimeout,
            :timeout => @domain_config.instance_ready_timeout
    end
  end
  @logger.info("Time to instance ready: #{@env[:metrics]['instance_ready_time']}")
end