Class: VagrantPlugins::VCloud::Driver::Version_5_1

Inherits:
Base
  • Object
show all
Defined in:
lib/vagrant-vcloud/driver/version_5_1.rb

Overview

Main class to access vCloud rest APIs

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hostname, username, password, org_name) ⇒ Version_5_1

Init the driver with the Vagrantfile information



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 32

def initialize(hostname, username, password, org_name)
  @logger = Log4r::Logger.new('vagrant::provider::vcloud::driver_5_1')
  uri = URI(hostname)
  @api_url = "#{uri.scheme}://#{uri.host}:#{uri.port}/api"
  @host_url = "#{uri.scheme}://#{uri.host}:#{uri.port}"
  @username = username
  @password = password
  @org_name = org_name
  @api_version = '5.5'
  @id = nil

  @cached_vapp_edge_public_ips = {}
end

Instance Attribute Details

#auth_keyObject (readonly)

Returns the value of attribute auth_key.



28
29
30
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 28

def auth_key
  @auth_key
end

#idObject (readonly)

Returns the value of attribute id.



28
29
30
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 28

def id
  @id
end

Instance Method Details

#add_edge_gateway_rules(edge_gateway_name, vdc_id, edge_gateway_ip, vapp_id, ports) ⇒ Object

Add Org Edge port forwarding and firewall rules

  • vapp_id: id of the vapp to be modified

  • network_name: name of the vapp network to be modified

  • ports: array with port numbers to forward 1:1 to vApp.



1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1458

def add_edge_gateway_rules(edge_gateway_name, vdc_id, edge_gateway_ip, vapp_id, ports)
  edge_vapp_ip = get_vapp_edge_public_ip(vapp_id)
  edge_network_id = find_edge_gateway_network(
    edge_gateway_name,
    vdc_id,
    edge_gateway_ip
  )
  edge_gateway_id = find_edge_gateway_id(edge_gateway_name, vdc_id)

  ### FIXME: tsugliani
  # We need to check the previous variables, especially (edge_*)
  # which can fail in some *weird* situations.
  params = {
     'method'   => :get,
     'command'  => "/admin/edgeGateway/#{edge_gateway_id}"
   }

  response, _headers = send_request(params)

  interesting = response.css(
    'EdgeGateway Configuration EdgeGatewayServiceConfiguration'
  )

  add_snat_rule = true
  interesting.css('NatService NatRule').each do |node|
    if node.css('RuleType').text == 'DNAT' &&
       node.css('GatewayNatRule/OriginalIp').text == edge_gateway_ip &&
       node.css('GatewayNatRule/TranslatedIp').text == edge_vapp_ip &&
       node.css('GatewayNatRule/OriginalPort').text == 'any'
       # remove old DNAT rule any -> any from older vagrant-vcloud versions
      node.remove
    end
    if node.css('RuleType').text == 'SNAT' &&
       node.css('GatewayNatRule/OriginalIp').text == edge_vapp_ip &&
       node.css('GatewayNatRule/TranslatedIp').text == edge_gateway_ip
      add_snat_rule = false
    end
  end

  add_firewall_rule = true
  interesting.css('FirewallService FirewallRule').each do |node|
    if node.css('Port').text == '-1' &&
       node.css('DestinationIp').text == edge_gateway_ip &&
       node.css('DestinationPortRange').text == 'Any'
      add_firewall_rule = false
    end
  end

  builder = Nokogiri::XML::Builder.new
  builder << interesting

  set_edge_rules = Nokogiri::XML(builder.to_xml) do |config|
    config.default_xml.noblanks
  end

  nat_rules = set_edge_rules.at_css('NatService')

  # Add all DNAT port rules edge -> vApp for the given list
  ports.each do |port|
    nat_rule = Nokogiri::XML::Builder.new do |xml|
        xml.NatRule {
          xml.RuleType 'DNAT'
          xml.IsEnabled 'true'
          xml.GatewayNatRule {
            xml.Interface('href' => edge_network_id )
            xml.OriginalIp edge_gateway_ip
            xml.OriginalPort port
            xml.TranslatedIp edge_vapp_ip
            xml.TranslatedPort port
            xml.Protocol 'tcpudp'
          }
        }
    end
    nat_rules << nat_rule.doc.root.to_xml
  end

  if (add_snat_rule)
    snat_rule = Nokogiri::XML::Builder.new do |xml|
        xml.NatRule {
          xml.RuleType 'SNAT'
          xml.IsEnabled 'true'
          xml.GatewayNatRule {
            xml.Interface('href' => edge_network_id )
            xml.OriginalIp edge_vapp_ip
            xml.TranslatedIp edge_gateway_ip
            xml.Protocol 'any'
          }
        }
    end
    nat_rules << snat_rule.doc.root.to_xml
  end


  if (add_firewall_rule)
  firewall_rule_1 = Nokogiri::XML::Builder.new do |xml|
      xml.FirewallRule {
        xml.IsEnabled 'true'
        xml.Description 'Allow Vagrant Communications'
        xml.Policy 'allow'
        xml.Protocols {
          xml.Any 'true'
        }
        xml.DestinationPortRange 'Any'
        xml.DestinationIp edge_gateway_ip
        xml.SourcePortRange 'Any'
        xml.SourceIp 'Any'
        xml.EnableLogging 'false'
      }
  end
  fw_rules = set_edge_rules.at_css('FirewallService')
    fw_rules << firewall_rule_1.doc.root.to_xml
  end

  xml = set_edge_rules.at_css 'EdgeGatewayServiceConfiguration'
  xml['xmlns'] = 'http://www.vmware.com/vcloud/v1.5'

  params = {
    'method'  => :post,
    'command' => "/admin/edgeGateway/#{edge_gateway_id}/action/" +
                 'configureServices'
  }

  _response, headers = send_request(
    params,
    set_edge_rules.to_xml,
    'application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml'
  )

  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#add_vapp_port_forwarding_rules(vapp_id, network_name, edge_network_name, config = {}) ⇒ Object

Add vApp port forwarding rules

  • vapp_id: id of the vapp to be modified

  • network_name: name of the vapp network to be modified

  • config: hash with network configuration specifications, must contain an array inside :nat_rules with the nat rules to add. nat_rules <<

    :nat_external_port    => j.to_s,
    :nat_internal_port    => "22",
    :nat_protocol         => "TCP",
    :vm_scoped_local_id   => value[:vapp_scoped_local_id]
    



1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1118

def add_vapp_port_forwarding_rules(vapp_id, network_name, edge_network_name, config = {})
  params = {
    'method'  => :get,
    'command' => "/vApp/vapp-#{vapp_id}/networkConfigSection"
  }
  response, _headers = send_request(params)

  nat_svc = response.css("/NetworkConfigSection/NetworkConfig[networkName='#{network_name}']/Configuration/Features/NatService").first

  config[:nat_rules].each do |nr|
    nat_svc << (
      "<NatRule>" +
        "<VmRule>" +
          "<ExternalPort>#{nr[:nat_external_port]}</ExternalPort>" +
          "<VAppScopedVmId>#{nr[:vapp_scoped_local_id]}</VAppScopedVmId>" +
          "<VmNicId>#{nr[:nat_vmnic_id]}</VmNicId>" +
          "<InternalPort>#{nr[:nat_internal_port]}</InternalPort>" +
          "<Protocol>#{nr[:nat_protocol]}</Protocol>" +
        "</VmRule>" +
      "</NatRule>"
    )
  end

  params = {
    'method'  => :put,
    'command' => "/vApp/vapp-#{vapp_id}/networkConfigSection"
  }

  _response, headers = send_request(
    params,
    response.to_xml,
    'application/vnd.vmware.vcloud.networkConfigSection+xml'
  )

  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#compose_vapp_from_vm(vdc, vapp_name, vapp_description, vm_list = {}, network_config = [], _cfg) ⇒ Object

Compose a vapp using existing virtual machines

Params:

  • vdc: the associated VDC

  • vapp_name: name of the target vapp

  • vapp_description: description of the target vapp

  • vm_list: hash with IDs of the VMs used in the composing process

  • network_config: hash of the network configuration for the vapp



776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 776

def compose_vapp_from_vm(vdc, vapp_name, vapp_description, vm_list = {}, network_config = [], _cfg)
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.ComposeVAppParams('xmlns' => 'http://www.vmware.com/vcloud/v1.5',
                          'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1',
                          'deploy' => 'false',
                          'powerOn' => 'false',
                          'name' => vapp_name) {
      xml.Description vapp_description
      xml.InstantiationParams {
        xml.NetworkConfigSection {
          xml['ovf'].Info 'Configuration parameters for logical networks'
          network_config.each do |network|
            xml.NetworkConfig('networkName' => network[:name]) {
              xml.Configuration {
                if network[:fence_mode] != 'bridged'
                  xml.IpScopes {
                  xml.IpScope {
                    xml.IsInherited(network[:is_inherited] || 'false')
                    xml.Gateway network[:gateway]
                    xml.Netmask network[:netmask]
                    xml.Dns1 network[:dns1] if network[:dns1]
                    xml.Dns2 network[:dns2] if network[:dns2]
                    xml.DnsSuffix network[:dns_suffix] if network[:dns_suffix]
                    xml.IpRanges {
                      xml.IpRange {
                        xml.StartAddress network[:start_address]
                        xml.EndAddress network[:end_address]
                        }
                      }
                    }
                  }
                end
                xml.ParentNetwork("href" => "#{@api_url}/network/#{network[:parent_network]}") if network[:parent_network]
                xml.FenceMode network[:fence_mode]
                if network[:fence_mode] != 'bridged'
                  xml.Features {
                    if network[:dhcp_enabled] == 'true'
                      xml.DhcpService {
                        xml.IsEnabled "true"
                        xml.DefaultLeaseTime "3600"
                        xml.MaxLeaseTime "7200"
                        xml.IpRange {
                          xml.StartAddress network[:dhcp_start]
                          xml.EndAddress network[:dhcp_end]
                        }
                      }
                    end
                    xml.FirewallService {
                      xml.IsEnabled(network[:enable_firewall] || "false")
                    }
                    xml.NatService {
                      xml.IsEnabled "true"
                      xml.NatType "portForwarding"
                      xml.Policy(network[:nat_policy_type] || "allowTraffic")
                    }
                  }
                end
              }
            }
          end #networks
        }
      }
      vm_list.each do |vm_name, vm_id|
        xml.SourcedItem {
          xml.Source('href' => "#{@api_url}/vAppTemplate/vm-#{vm_id}", 'name' => vm_name)
          xml.InstantiationParams {
            if _cfg.enable_guest_customization.nil? || _cfg.enable_guest_customization
              xml.GuestCustomizationSection(
                'xmlns' => 'http://www.vmware.com/vcloud/v1.5',
                'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1') {
                  xml['ovf'].Info 'VM Guest Customization configuration'
                  xml.Enabled true
                  if _cfg.guest_customization_change_sid == true
                    xml.ChangeSid true
                    if _cfg.guest_customization_join_domain == true
                      xml.JoinDomainEnabled true
                      xml.DomainName _cfg.guest_customization_domain_name
                      xml.DomainUserName _cfg.guest_customization_domain_user_name
                      xml.DomainUserPassword _cfg.guest_customization_domain_user_password
                      xml.MachineObjectOU _cfg.guest_customization_domain_ou if !_cfg.guest_customization_domain_ou.nil?
                    end
                  end
                  if _cfg.guest_customization_admin_password_enabled
                    xml.AdminPasswordEnabled true
                    xml.AdminPasswordAuto true if _cfg.guest_customization_admin_password_auto
                    xml.AdminPassword _cfg.guest_customization_admin_password if !_cfg.guest_customization_admin_password.nil?
                    if _cfg. == true
                      xml.AdminAutoLogonEnabled true
                      xml.AdminAutoLogonCount _cfg.
                    end
                  else
                    xml.AdminPasswordEnabled false
                  end
                  xml.ResetPasswordRequired _cfg.guest_customization_admin_password_reset if !_cfg.guest_customization_admin_password_reset.nil?
                  xml.CustomizationScript{ xml.cdata(_cfg.guest_customization_script) } if !_cfg.guest_customization_script.nil?
                  xml.ComputerName vm_name
              }
            end
            if _cfg.nics.nil? && network_config.length == 1
              xml.NetworkConnectionSection(
                'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1',
                'type' => 'application/vnd.vmware.vcloud.networkConnectionSection+xml',
                'href' => "#{@api_url}/vAppTemplate/vm-#{vm_id}/networkConnectionSection/") {
                  xml['ovf'].Info 'Network config for sourced item'
                  xml.PrimaryNetworkConnectionIndex '0'
                  xml.NetworkConnection('network' => network_config[0][:name]) {
                    xml.NetworkConnectionIndex '0'
                    xml.IsConnected 'true'
                    xml.IpAddressAllocationMode(network_config[0][:ip_allocation_mode] || 'POOL')
                }
              }
            end
          }
          xml.NetworkAssignment('containerNetwork' => network_config[0][:name], 'innerNetwork' => network_config[0][:name]) if _cfg.nics.nil? && network_config.length == 1
        }
      end
      xml.AllEULAsAccepted 'true'
    }
  end

  params = {
    'method'  => :post,
    'command' => "/vdc/#{vdc}/action/composeVApp"
  }

  response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.composeVAppParams+xml'
  )

  vapp_id = URI(headers['Location']).path.gsub("/api/vApp/vapp-", '')

  task = response.css("VApp Task[operationName='vdcComposeVapp']").first
  task_id = URI(task['href']).path.gsub('/api/task/', '')

  { :vapp_id => vapp_id, :task_id => task_id }
end

#create_catalog(org_id, catalog_name, catalog_description) ⇒ Object

Create a catalog in an organization



692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 692

def create_catalog(org_id, catalog_name, catalog_description)
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.AdminCatalog(
      'xmlns' => 'http://www.vmware.com/vcloud/v1.5',
      'name' => catalog_name
    ) { xml.Description catalog_description }

  end

  params = {
    'method'  => :post,
    'command' => "/admin/org/#{org_id}/catalogs"
  }

  response, _headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.admin.catalog+xml'
  )
  task_id = URI(response.css(
      "AdminCatalog Tasks Task[operationName='catalogCreateCatalog']"
    ).first[:href]).path.gsub('/api/task/', '')

  catalog_id = URI(response.css(
      "AdminCatalog Link[type='application/vnd.vmware.vcloud.catalog+xml']"
    ).first[:href]).path.gsub('/api/catalog/', '')

  { :task_id => task_id, :catalog_id => catalog_id }
end

#create_vapp_from_template(vdc, vapp_name, vapp_description, vapp_template_id, poweron = false) ⇒ Object

Create a vapp starting from a template

Params:

  • vdc: the associated VDC

  • vapp_name: name of the target vapp

  • vapp_description: description of the target vapp

  • vapp_templateid: ID of the vapp template



730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 730

def create_vapp_from_template(vdc, vapp_name, vapp_description, vapp_template_id, poweron = false)
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.InstantiateVAppTemplateParams(
      'xmlns'     => 'http://www.vmware.com/vcloud/v1.5',
      'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
      'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1',
      'name'      => vapp_name,
      'deploy'    => 'true',
      'powerOn'   => poweron
    ) { xml.Description vapp_description xml.Source(
        'href' => "#{@api_url}/vAppTemplate/#{vapp_template_id}"
      )
    }
  end

  params = {
    'method'  => :post,
    'command' => "/vdc/#{vdc}/action/instantiateVAppTemplate"
  }

  response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml'
  )

  vapp_id = URI(headers['Location']).path.gsub('/api/vApp/vapp-', '')

  task = response.css(
    "VApp Task[operationName='vdcInstantiateVapp']"
  ).first

  task_id = URI(task['href']).path.gsub('/api/task/', '')

  { :vapp_id => vapp_id, :task_id => task_id }
end

#delete_vapp(vapp_id) ⇒ Object

Delete a given vapp NOTE: It doesn’t verify that the vapp is shutdown



467
468
469
470
471
472
473
474
475
476
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 467

def delete_vapp(vapp_id)
  params = {
    'method'  => :delete,
    'command' => "/vApp/vapp-#{vapp_id}"
  }

  _response, headers = send_request(params)
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#delete_vm(vm_id) ⇒ Object

VM operations ####

Delete a given vm NOTE: It doesn’t verify that the vm is shutdown



562
563
564
565
566
567
568
569
570
571
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 562

def delete_vm(vm_id)
  params = {
    'method'  => :delete,
    'command' => "/vApp/vm-#{vm_id}"
  }

  _response, headers = send_request(params)
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#find_edge_gateway_id(edge_gateway_name, vdc_id) ⇒ Object

Find an edge gateway id from the edge name and vdc_id

  • edge_gateway_name: Name of the vSE

  • vdc_id: virtual datacenter id



1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1221

def find_edge_gateway_id(edge_gateway_name, vdc_id)
  params = {
    'method'  => :get,
    'command' => '/query?type=edgeGateway&' \
                 'format=records&' \
                 "filter=vdc==#{@api_url}/vdc/#{vdc_id}&" +
                 "filter=name==#{edge_gateway_name}"
  }

  response, _headers = send_request(params)

  edge_gateway = response.css('EdgeGatewayRecord').first

  if edge_gateway
    return URI(edge_gateway['href']).path.gsub(
      '/api/admin/edgeGateway/', ''
    )
  else
    return nil
  end
end

#find_edge_gateway_network(edge_gateway_name, vdc_id, edge_gateway_ip) ⇒ Object

Find an edge gateway network from the edge name and vdc_id, and ip

  • edge_gateway_name: Name of the vSE

  • vdc_id: virtual datacenter id

  • edge_gateway_ip: public ip associated to that vSE



1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1267

def find_edge_gateway_network(edge_gateway_name, vdc_id, edge_gateway_ip)
  params = {
    'method'  => :get,
    'command' => '/query?type=edgeGateway&' \
                 'format=records&' \
                 "filter=vdc==#{@api_url}/vdc/#{vdc_id}&" +
                 "filter=name==#{edge_gateway_name}"
  }

  response, _headers = send_request(params)

  edge_gateway = response.css('EdgeGatewayRecord').first

  if edge_gateway
    edge_gateway_id = URI(edge_gateway['href']).path.gsub(
      '/api/admin/edgeGateway/', ''
    )
  end

  params = {
    'method'  => :get,
    'command' => "/admin/edgeGateway/#{edge_gateway_id}"
  }

  response, _headers = send_request(params)
  response.css(
    'EdgeGateway Configuration GatewayInterfaces GatewayInterface'
  ).each do |gw|
    # Only check uplinks, avoid another check
    if gw.css('InterfaceType').text == 'uplink'

      # Loop on all sub-allocation pools
      gw.css('SubnetParticipation IpRanges IpRange').each do |cur_range|

        low_ip = cur_range.css('StartAddress').first.text
        high_ip = cur_range.css('EndAddress').first.text

        range_ip_low = NetAddr.ip_to_i(low_ip)
        range_ip_high = NetAddr.ip_to_i(high_ip)
        test_ip = NetAddr.ip_to_i(edge_gateway_ip)

        # FIXME: replace "===" (tsugliani)
        if (range_ip_low..range_ip_high) === test_ip
          return gw.css('Network').first[:href]
        end
      end
    end
  end
end

#get_catalog(catalog_id) ⇒ Object

Fetch details about a given catalog



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 188

def get_catalog(catalog_id)
  params = {
    'method'  => :get,
    'command' => "/catalog/#{catalog_id}"
  }

  response, _headers = send_request(params)
  description = response.css('Description').first
  description = description.text unless description.nil?

  items = {}
  response.css(
    "CatalogItem[type='application/vnd.vmware.vcloud.catalogItem+xml']"
  ).each do |item|
    items[item['name']] = URI(item['href']).path.gsub(
      '/api/catalogItem/', ''
    )
  end
  { :description => description, :items => items }
end

#get_catalog_by_name(organization, catalog_name) ⇒ Object

Friendly helper method to fetch an catalog by name

  • organization hash (from get_organization/get_organization_by_name)

  • catalog name



257
258
259
260
261
262
263
264
265
266
267
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 257

def get_catalog_by_name(organization, catalog_name)
  result = nil

  organization[:catalogs].each do |catalog|
    if catalog[0].downcase == catalog_name.downcase
      result = get_catalog(catalog[1])
    end
  end

  result
end

#get_catalog_id_by_name(organization, catalog_name) ⇒ Object

Friendly helper method to fetch an catalog id by name

  • organization hash (from get_organization/get_organization_by_name)

  • catalog name



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
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 213

def get_catalog_id_by_name(organization, catalog_name)
  result = nil

  organization[:catalogs].each do |catalog|
    if catalog[0].downcase == catalog_name.downcase
      result = catalog[1]
    end
  end

  if result.nil?
    # catalog not found, search in global catalogs as well
    # that are not listed in organization directly
    params = {
      'method'  => :get,
      'command' => '/catalogs/query/',
      'cacheable' => true
    }

    response, _headers = send_request(params)

    catalogs = {}
    response.css(
      'CatalogRecord'
    ).each do |item|
      catalogs[item['name']] = URI(item['href']).path.gsub(
        '/api/catalog/', ''
      )
    end

    catalogs.each do |catalog|
      if catalog[0].downcase == catalog_name.downcase
        result = catalog[1]
      end
    end

  end

  result
end

#get_catalog_item(catalog_item_id) ⇒ Object

Fetch details about a given catalog item:

  • description

  • vApp templates



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 342

def get_catalog_item(catalog_item_id)
  params = {
    'method'  => :get,
    'command' => "/catalogItem/#{catalog_item_id}"
  }

  response, _headers = send_request(params)
  description = response.css('Description').first
  description = description.text unless description.nil?

  items = {}
  response.css(
    "Entity[type='application/vnd.vmware.vcloud.vAppTemplate+xml']"
  ).each do |item|
    items[item['name']] = URI(item['href']).path.gsub(
      '/api/vAppTemplate/vappTemplate-', ''
    )
  end
  { :description => description, :items => items }
end

#get_catalog_item_by_name(catalog_id, catalog_item_name) ⇒ Object

friendly helper method to fetch an catalogItem by name

  • catalogId (use get_catalog_name(org, name))

  • catalagItemName



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
401
402
403
404
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 367

def get_catalog_item_by_name(catalog_id, catalog_item_name)
  result = nil
  catalog_elems = get_catalog(catalog_id)

  catalog_elems[:items].each do |catalog_elem|

    catalog_item = get_catalog_item(catalog_elem[1])
    if catalog_item[:items][catalog_item_name]
      # This is a vApp Catalog Item

      # fetch CatalogItemId
      catalog_item_id = catalog_item[:items][catalog_item_name]

      # Fetch the catalogItemId information
      params = {
        'method'  => :get,
        'command' => "/vAppTemplate/vappTemplate-#{catalog_item_id}"
      }
      response, _headers = send_request(params)

      # VMs Hash for all the vApp VM entities
      vms_hash = {}
      response.css('/VAppTemplate/Children/Vm').each do |vm_elem|
        vm_name = vm_elem['name']
        vm_id = URI(vm_elem['href']).path.gsub(
          '/api/vAppTemplate/vm-', ''
        )

        # Add the VM name/id to the VMs Hash
        vms_hash[vm_name] = { :id => vm_id }
      end
      result = {
        catalog_item_name => catalog_item_id, :vms_hash => vms_hash
      }
    end
  end
  result
end

#get_edge_gateway_rules(edge_gateway_name, vdc_id) ⇒ Object

Get Org Edge port forwarding and firewall rules

  • vapp_id: id of the vapp to be modified

  • network_name: name of the vapp network to be modified

  • config: hash with network configuration specifications,

    must contain an array inside :nat_rules with the nat rules
    to be applied.
    


1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1325

def get_edge_gateway_rules(edge_gateway_name, vdc_id)
  edge_gateway_id = find_edge_gateway_id(edge_gateway_name, vdc_id)

  params = {
    'method'  => :get,
    'command' => "/admin/edgeGateway/#{edge_gateway_id}"
  }

  response, _headers = send_request(params)

  nat_fw_rules = []

  interesting = response.css(
    'EdgeGateway Configuration EdgeGatewayServiceConfiguration'
  )
  interesting.css('NatService NatRule').each do |node|
    if node.css('RuleType').text == 'DNAT'
      gw_node = node.css('GatewayNatRule')
      nat_fw_rules << {
        :rule_type        => 'DNAT',
        :original_ip      => gw_node.css('OriginalIp').text,
        :original_port    => gw_node.css('OriginalPort').text,
        :translated_ip    => gw_node.css('TranslatedIp').text,
        :translated_port  => gw_node.css('TranslatedPort').text,
        :protocol         => gw_node.css('Protocol').text,
        :is_enabled       => node.css('IsEnabled').text
      }

    end
    if node.css('RuleType').text == 'SNAT'
      gw_node = node.css('GatewayNatRule')
      nat_fw_rules << {
        :rule_type      => 'SNAT',
        :interface_name => gw_node.css('Interface').first['name'],
        :original_ip    => gw_node.css('OriginalIp').text,
        :translated_ip  => gw_node.css('TranslatedIp').text,
        :is_enabled     => node.css('IsEnabled').text
      }
    end
  end

  interesting.css('FirewallService FirewallRule').each do |node|
    if node.css('Port').text == '-1'
      nat_fw_rules << {
        :rule_type             => 'Firewall',
        :id                    => node.css('Id').text,
        :policy                => node.css('Policy').text,
        :description           => node.css('Description').text,
        :destination_ip        => node.css('DestinationIp').text,
        :destination_portrange => node.css('DestinationPortRange').text,
        :source_ip             => node.css('SourceIp').text,
        :source_portrange      => node.css('SourcePortRange').text,
        :is_enabled            => node.css('IsEnabled').text
      }
    end
  end

  nat_fw_rules
end

#get_organization(org_id) ⇒ Object

Fetch details about an organization:

  • catalogs

  • vdcs

  • networks



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 134

def get_organization(org_id)
  params = {
    'method'  => :get,
    'command' => "/org/#{org_id}"
  }

  response, _headers = send_request(params)

  catalogs = {}
  response.css(
    "Link[type='application/vnd.vmware.vcloud.catalog+xml']"
  ).each do |item|
    catalogs[item['name']] = URI(item['href']).path.gsub(
      '/api/catalog/', ''
    )
  end

  vdcs = {}
  response.css(
    "Link[type='application/vnd.vmware.vcloud.vdc+xml']"
  ).each do |item|
    vdcs[item['name']] = URI(item['href']).path.gsub(
      '/api/vdc/', ''
    )
  end

  networks = {}
  response.css(
    "Link[type='application/vnd.vmware.vcloud.orgNetwork+xml']"
  ).each do |item|
    networks[item['name']] = URI(item['href']).path.gsub(
      '/api/network/', ''
    )
  end

  tasklists = {}
  response.css(
    "Link[type='application/vnd.vmware.vcloud.tasksList+xml']"
  ).each do |item|
    tasklists[item['name']] = URI(item['href']).path.gsub(
      '/api/tasksList/', ''
    )
  end

  {
    :catalogs   => catalogs,
    :vdcs       => vdcs,
    :networks   => networks,
    :tasklists  => tasklists
  }
end

#get_organization_by_name(name) ⇒ Object

friendly helper method to fetch an Organization by name

  • name (this isn’t case sensitive)



115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 115

def get_organization_by_name(name)
  result = nil

  # Fetch all organizations
  organizations = get_organizations

  organizations.each do |organization|
    if organization[0].downcase == name.downcase
      result = get_organization(organization[1])
    end
  end
  result
end

#get_organization_id_by_name(name) ⇒ Object

friendly helper method to fetch an Organization Id by name

  • name (this isn’t case sensitive)



98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 98

def get_organization_id_by_name(name)
  result = nil

  # Fetch all organizations
  organizations = get_organizations

  organizations.each do |organization|
    if organization[0].downcase == name.downcase
      result = organization[1]
    end
  end
  result
end

#get_organizationsObject

Fetch existing organizations and their IDs



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 79

def get_organizations
  params = {
    'method'  => :get,
    'command' => '/org'
  }

  response, _headers = send_request(params)
  orgs = response.css('OrgList Org')

  results = {}
  orgs.each do |org|
    results[org['name']] = URI(org['href']).path.gsub('/api/org/', '')
  end
  results
end

#get_task(task_id) ⇒ Object

Fetch information for a given task



1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1833

def get_task(task_id)
  params = {
    'method'  => :get,
    'command' => "/task/#{task_id}"
  }

  response, _headers = send_request(params)

  task = response.css('Task').first
  status = task['status']
  start_time = task['startTime']
  end_time = task['endTime']

  {
    :status     => status,
    :start_time => start_time,
    :end_time   => end_time,
    :response   => response
  }
end

#get_vapp(vapp_id) ⇒ Object

Fetch details about a given vapp:

  • name

  • description

  • status

  • IP

  • Children VMs: – IP addresses – status – ID



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
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 416

def get_vapp(vapp_id)
  params = {
    'method'  => :get,
    'command' => "/vApp/vapp-#{vapp_id}"
  }

  response, _headers = send_request(params)

  vapp_node = response.css('VApp').first
  if vapp_node
    name = vapp_node['name']
    status = convert_vapp_status(vapp_node['status'])
  end

  description = response.css('Description').first
  description = description.text unless description.nil?

  ip = response.css('IpAddress').first
  ip = ip.text unless ip.nil?

  vms = response.css('Children Vm')
  vms_hash = {}

  # ipAddress could be namespaced or not:
  # see https://github.com/astratto/vcloud-rest/issues/3
  vms.each do |vm|
    vapp_local_id = vm.css('VAppScopedLocalId')
    addresses = vm.css('rasd|Connection').collect {
      |n| n['vcloud:ipAddress'] || n['ipAddress']
    }
    vms_hash[vm['name'].to_sym] = {
      :addresses            => addresses,
      :status               => convert_vapp_status(vm['status']),
      :id                   => URI(vm['href']).path.gsub('/api/vApp/vm-', ''),
      :vapp_scoped_local_id => vapp_local_id.text
    }
  end

  # TODO: EXPAND INFO FROM RESPONSE
  {
    :name         => name,
    :description  => description,
    :status       => status,
    :ip           => ip,
    :vms_hash     => vms_hash
  }
end

#get_vapp_edge_public_ip(vapp_id, network_name = nil) ⇒ Object

get vApp edge public IP from the vApp ID Only works when:

  • vApp needs to be poweredOn

  • FenceMode is set to “natRouted”

  • NatType“ is set to ”portForwarding

This will be required to know how to connect to VMs behind the Edge device.



1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1599

def get_vapp_edge_public_ip(vapp_id, network_name=nil)
  return @cached_vapp_edge_public_ips["#{vapp_id}#{network_name}"] unless @cached_vapp_edge_public_ips["#{vapp_id}#{network_name}"].nil?

  # Check the network configuration section
  params = {
    'method' => :get,
    'command' => "/vApp/vapp-#{vapp_id}/networkConfigSection"
  }

  response, _headers = send_request(params)

  # FIXME: this will return nil if the vApp uses multiple vApp Networks
  # with Edge devices in natRouted/portForwarding mode.
  nconfig = response.css(
    'NetworkConfigSection/NetworkConfig'
  )
  config = nil
  if nconfig.size > 1
    nconfig.each {|c|
      pn = c.css('/Configuration/ParentNetwork')
      next if pn.size == 0
      if pn.first['name'] == network_name
        config = c.css('/Configuration')
        break
      end
    }
  else
    config = nconfig.css('/Configuration')
  end

  fence_mode = config.css('/FenceMode').text
  nat_type = config.css('/Features/NatService/NatType').text

  unless fence_mode == 'natRouted'
    raise InvalidStateError,
          'Invalid request because FenceMode must be natRouted.'
  end

  unless nat_type == 'portForwarding'
    raise InvalidStateError,
          'Invalid request because NatType must be portForwarding.'
  end

  # Check the routerInfo configuration where the global external IP
  # is defined
  edge_ip = config.css('/RouterInfo/ExternalIp').text
  if edge_ip == ''
    return nil
  else
    @cached_vapp_edge_public_ips["#{vapp_id}#{network_name}"] = edge_ip
    return edge_ip
  end
end

#get_vapp_port_forwarding_rules(vapp_id, network_name = nil) ⇒ Object

Get vApp port forwarding rules

  • vapp_id: id of the vApp



1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1159

def get_vapp_port_forwarding_rules(vapp_id, network_name=nil)
  params = {
    'method'  => :get,
    'command' => "/vApp/vapp-#{vapp_id}/networkConfigSection"
  }

  response, _headers = send_request(params)

  # FIXME: this will return nil if the vApp uses multiple vApp Networks
  # with Edge devices in natRouted/portForwarding mode.
  nconfig = response.css(
    'NetworkConfigSection/NetworkConfig'
  )
  config = nil
  if nconfig.size > 1
    nconfig.each {|c|
      pn = c.css('/Configuration/ParentNetwork')
      next if pn.size == 0
      if pn.first['name'] == network_name
        config = c.css('/Configuration')
        break
      end
    }
  else
    config = nconfig.css('/Configuration')
  end
  fence_mode = config.css('/FenceMode').text
  nat_type = config.css('/Features/NatService/NatType').text

  unless fence_mode == 'natRouted'
    raise InvalidStateError,
          'Invalid request because FenceMode must be natRouted.'
  end

  unless nat_type == 'portForwarding'
    raise InvalidStateError,
          'Invalid request because NatType must be portForwarding.'
  end

  nat_rules = []
  config.css('/Features/NatService/NatRule').each do |rule|
    # portforwarding rules information
    vm_rule = rule.css('VmRule')

    nat_rules << {
      :nat_external_ip      => vm_rule.css('ExternalIpAddress').text,
      :nat_external_port    => vm_rule.css('ExternalPort').text,
      :vapp_scoped_local_id => vm_rule.css('VAppScopedVmId').text,
      :vm_nic_id            => vm_rule.css('VmNicId').text,
      :nat_internal_port    => vm_rule.css('InternalPort').text,
      :nat_protocol         => vm_rule.css('Protocol').text
    }
  end
  nat_rules
end

#get_vapp_template(vapp_id) ⇒ Object

Fetch details about a given vapp template:

  • name

  • description

  • Children VMs: – ID



1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1016

def get_vapp_template(vapp_id)
  params = {
    'method'  => :get,
    'command' => "/vAppTemplate/vappTemplate-#{vapp_id}"
  }

  response, _headers = send_request(params)

  vapp_node = response.css('VAppTemplate').first
  if vapp_node
    name = vapp_node['name']
    convert_vapp_status(vapp_node['status'])
  end

  description = response.css('Description').first
  description = description.text unless description.nil?

  # FIXME: What are those 2 lines for ? disabling for now (tsugliani)
  # ip = response.css('IpAddress').first
  # ip = ip.text unless ip.nil?

  vms = response.css('Children Vm')
  vms_hash = {}

  vms.each do |vm|
    vms_hash[vm['name']] = {
      :id => URI(vm['href']).path.gsub('/api/vAppTemplate/vm-', '')
    }
  end

  # TODO: EXPAND INFO FROM RESPONSE
  { :name => name, :description => description, :vms_hash => vms_hash }
end

#get_vdc(vdc_id) ⇒ Object

Fetch details about a given vdc:

  • description

  • vapps

  • networks



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
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 274

def get_vdc(vdc_id)
  params = {
    'method'  => :get,
    'command' => "/vdc/#{vdc_id}"
  }

  response, _headers = send_request(params)
  description = response.css('Description').first
  description = description.text unless description.nil?

  vapps = {}
  response.css(
    "ResourceEntity[type='application/vnd.vmware.vcloud.vApp+xml']"
  ).each do |item|
    vapps[item['name']] = URI(item['href']).path.gsub(
      '/api/vApp/vapp-', ''
    )
  end

  networks = {}
  response.css(
    "Network[type='application/vnd.vmware.vcloud.network+xml']"
  ).each do |item|
    networks[item['name']] = URI(item['href']).path.gsub(
      '/api/network/', ''
    )
  end
  {
    :description => description, :vapps => vapps, :networks => networks
  }
end

#get_vdc_by_name(organization, vdc_name) ⇒ Object

Friendly helper method to fetch a Organization VDC by name

  • Organization object

  • Organization VDC Name



326
327
328
329
330
331
332
333
334
335
336
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 326

def get_vdc_by_name(organization, vdc_name)
  result = nil

  organization[:vdcs].each do |vdc|
    if vdc[0].downcase == vdc_name.downcase
      result = get_vdc(vdc[1])
    end
  end

  result
end

#get_vdc_id_by_name(organization, vdc_name) ⇒ Object

Friendly helper method to fetch a Organization VDC Id by name

  • Organization object

  • Organization VDC Name



310
311
312
313
314
315
316
317
318
319
320
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 310

def get_vdc_id_by_name(organization, vdc_name)
  result = nil

  organization[:vdcs].each do |vdc|
    if vdc[0].downcase == vdc_name.downcase
      result = vdc[1]
    end
  end

  result
end

#get_vm(vm_id) ⇒ Object

Fetch details about a given VM



2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 2320

def get_vm(vm_id)
  params = {
    'method'  => :get,
    'command' => "/vApp/vm-#{vm_id}"
  }

  response, _headers = send_request(params)

  hypervisor_enabled = response[:nestedHypervisorEnabled]
  os_desc = response.css('ovf|OperatingSystemSection ovf|Description').first.text

  networks = {}
  primary_network = response.css('PrimaryNetworkConnectionIndex').first.text.to_i
  response.css('NetworkConnection').each do |network|
    ip = network.css('IpAddress').first
    ip = ip.text if ip
    primary = false
    primary = true if network.css('NetworkConnectionIndex').first.text.to_i == primary_network

    networks[network['network']] = {
      :primary            => primary,
      :index              => network.css('NetworkConnectionIndex').first.text,
      :ip                 => ip,
      :is_connected       => network.css('IsConnected').first.text,
      :mac_address        => network.css('MACAddress').first.text,
      :ip_allocation_mode => network.css('IpAddressAllocationMode').first.text
    }
  end

  admin_password = response.css('GuestCustomizationSection AdminPassword').first
  admin_password = admin_password.text if admin_password

  # make the lines shorter by adjusting the nokogiri css namespace
  guest_css = response.css('GuestCustomizationSection')
  guest_customizations = {
    :enabled                => guest_css.css('Enabled').first.text,
    :admin_passwd_enabled   => guest_css.css('AdminPasswordEnabled').first.text,
    :admin_passwd_auto      => guest_css.css('AdminPasswordAuto').first.text,
    :admin_passwd           => admin_password,
    :reset_passwd_required  => guest_css.css('ResetPasswordRequired').first.text,
    :computer_name          => guest_css.css('ComputerName').first.text
  }

  {
    :os_desc              => os_desc,
    :networks             => networks,
    :guest_customizations => guest_customizations,
    :hypervisor_enabled   => hypervisor_enabled
  }
end

#loginObject

Authenticate against the specified server



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 48

def 
  params = {
    'method'  => :post,
    'command' => '/sessions'
  }

  _response, headers = send_request(params)

  if !headers.key?('x-vcloud-authorization')
    raise 'Failed to authenticate: ' \
          'missing x-vcloud-authorization header'
  end

  @auth_key = headers['x-vcloud-authorization']
end

#logoutObject

Destroy the current session



66
67
68
69
70
71
72
73
74
75
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 66

def logout
  params = {
    'method'  => :delete,
    'command' => '/session'
  }

  _response, _headers = send_request(params)
  # reset auth key to nil
  @auth_key = nil
end

#poweroff_vapp(vapp_id) ⇒ Object

Shutdown a given vapp



480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 480

def poweroff_vapp(vapp_id)
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.UndeployVAppParams(
      'xmlns' => 'http://www.vmware.com/vcloud/v1.5'
    ) { xml.UndeployPowerAction 'powerOff' }
  end

  params = {
    'method'  => :post,
    'command' => "/vApp/vapp-#{vapp_id}/action/undeploy"
  }

  _response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.undeployVAppParams+xml'
  )
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#poweroff_vm(vm_id) ⇒ Object

Poweroff a given VM Using undeploy as a REAL powerOff Only poweroff will put the VM into a partially powered off state.



577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 577

def poweroff_vm(vm_id)
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.UndeployVAppParams(
    'xmlns' => 'http://www.vmware.com/vcloud/v1.5'
  ) { xml.UndeployPowerAction 'powerOff' }
  end

  params = {
    'method'  => :post,
    'command' => "/vApp/vm-#{vm_id}/action/undeploy"
  }

  _response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.undeployVAppParams+xml'
  )
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#poweron_vapp(vapp_id) ⇒ Object

Boot a given vapp



547
548
549
550
551
552
553
554
555
556
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 547

def poweron_vapp(vapp_id)
  params = {
    'method'  => :post,
    'command' => "/vApp/vapp-#{vapp_id}/power/action/powerOn"
  }

  _response, headers = send_request(params)
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#poweron_vm(vm_id) ⇒ Object

Boot a given VM



679
680
681
682
683
684
685
686
687
688
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 679

def poweron_vm(vm_id)
  params = {
    'method'  => :post,
    'command' => "/vApp/vm-#{vm_id}/power/action/powerOn"
  }

  _response, headers = send_request(params)
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#reboot_vapp(vapp_id) ⇒ Object

reboot a given vapp This will basically initial a guest OS reboot, and will only work if VMware-tools are installed on the underlying VMs. vShield Edge devices are not affected



519
520
521
522
523
524
525
526
527
528
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 519

def reboot_vapp(vapp_id)
  params = {
    'method'  => :post,
    'command' => "/vApp/vapp-#{vapp_id}/power/action/reboot"
  }

  _response, headers = send_request(params)
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#reboot_vm(vm_id) ⇒ Object

reboot a given VM This will basically initial a guest OS reboot, and will only work if VMware-tools are installed on the underlying VMs. vShield Edge devices are not affected



651
652
653
654
655
656
657
658
659
660
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 651

def reboot_vm(vm_id)
  params = {
    'method'  => :post,
    'command' => "/vApp/vm-#{vm_id}/power/action/reboot"
  }

  _response, headers = send_request(params)
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#recompose_vapp_from_vm(vapp_id, vm_list = {}, network_config = [], _cfg) ⇒ Object

Recompose an existing vapp using existing virtual machines

Params:

  • vdc: the associated VDC

  • vapp_name: name of the target vapp

  • vapp_description: description of the target vapp

  • vm_list: hash with IDs of the VMs to be used in the composing process

  • network_config: hash of the network configuration for the vapp



925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 925

def recompose_vapp_from_vm(vapp_id, vm_list = {}, network_config = [], _cfg)
  original_vapp = get_vapp(vapp_id)

  builder = Nokogiri::XML::Builder.new do |xml|
  xml.RecomposeVAppParams(
    'xmlns' => 'http://www.vmware.com/vcloud/v1.5',
    'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1',
    'name' => original_vapp[:name]) {
    xml.Description original_vapp[:description]
    xml.InstantiationParams {}
    vm_list.each do |vm_name, vm_id|
        xml.SourcedItem {
          xml.Source('href' => "#{@api_url}/vAppTemplate/vm-#{vm_id}", 'name' => vm_name)
          xml.InstantiationParams {
            if _cfg.enable_guest_customization.nil? || _cfg.enable_guest_customization
              xml.GuestCustomizationSection(
                'xmlns' => 'http://www.vmware.com/vcloud/v1.5',
                'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1') {
                  xml['ovf'].Info 'VM Guest Customization configuration'
                  xml.Enabled true
                  if _cfg.guest_customization_change_sid == true
                    xml.ChangeSid true
                    if _cfg.guest_customization_join_domain == true
                      xml.JoinDomainEnabled true
                      xml.DomainName _cfg.guest_customization_domain_name
                      xml.DomainUserName _cfg.guest_customization_domain_user_name
                      xml.DomainUserPassword _cfg.guest_customization_domain_user_password
                      xml.MachineObjectOU _cfg.guest_customization_domain_ou if !_cfg.guest_customization_domain_ou.nil?
                    end
                  end
                  if _cfg.guest_customization_admin_password_enabled
                    xml.AdminPasswordEnabled true
                    xml.AdminPasswordAuto true if _cfg.guest_customization_admin_password_auto
                    xml.AdminPassword _cfg.guest_customization_admin_password if !_cfg.guest_customization_admin_password.nil?
                    if _cfg. == true
                      xml.AdminAutoLogonEnabled true
                      xml.AdminAutoLogonCount _cfg.
                    end
                  else
                    xml.AdminPasswordEnabled false
                  end
                  xml.ResetPasswordRequired _cfg.guest_customization_admin_password_reset if !_cfg.guest_customization_admin_password_reset.nil?
                  xml.CustomizationScript{ xml.cdata(_cfg.guest_customization_script) } if !_cfg.guest_customization_script.nil?
                  xml.ComputerName vm_name
              }
            end
            if _cfg.nics.nil? && network_config.length == 1
              xml.NetworkConnectionSection(
                'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1',
                'type' => 'application/vnd.vmware.vcloud.networkConnectionSection+xml',
                'href' => "#{@api_url}/vAppTemplate/vm-#{vm_id}/networkConnectionSection/") {
                  xml['ovf'].Info 'Network config for sourced item'
                  xml.PrimaryNetworkConnectionIndex '0'
                  xml.NetworkConnection('network' => network_config[0][:name]) {
                    xml.NetworkConnectionIndex '0'
                    xml.IsConnected 'true'
                    xml.IpAddressAllocationMode(network_config[0][:ip_allocation_mode] || 'POOL')
                }
              }
            end
          }
          xml.NetworkAssignment('containerNetwork' => network_config[0][:name], 'innerNetwork' => network_config[0][:name]) if _cfg.nics.nil? && network_config.length == 1
      }
    end
    xml.AllEULAsAccepted 'true'
  }
  end

  params = {
    'method'  => :post,
    'command' => "/vApp/vapp-#{vapp_id}/action/recomposeVApp"
  }

  response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.recomposeVAppParams+xml'
  )

  vapp_id = URI(headers['Location']).path.gsub('/api/vApp/vapp-', '')
  task = response.css("Task[operationName='vdcRecomposeVapp']").first
  task_id = URI(task['href']).path.gsub('/api/task/', '')

  { :vapp_id => vapp_id, :task_id => task_id }
end

#redeploy_edge_gateway(edge_gateway_id) ⇒ Object

Redeploy the vShield Edge Gateway VM, due to some knowns issues where the current rules are not “applied” and the EdgeGW is in an unmanageable state.



1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1248

def redeploy_edge_gateway(edge_gateway_id)
  params = {
    'method'  => :post,
    'command' => "/admin/edgeGateway/#{edge_gateway_id}/action/redeploy"
  }

  _response, headers = send_request(params)
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#remove_edge_gateway_rules(edge_gateway_name, vdc_id, edge_gateway_ip, vapp_id) ⇒ Object

Remove NAT/FW rules from a edge gateway device

  • edge_gateway_name: Name of the vSE

  • vdc_id: virtual datacenter id

  • edge_gateway_ip: public ip associated the vSE

  • vapp_id: vApp identifier to correlate with the vApp Edge



1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1393

def remove_edge_gateway_rules(edge_gateway_name, vdc_id, edge_gateway_ip, vapp_id)
  edge_vapp_ip = get_vapp_edge_public_ip(vapp_id)
  edge_gateway_id = find_edge_gateway_id(edge_gateway_name, vdc_id)

  params = {
   'method'  => :get,
   'command' => "/admin/edgeGateway/#{edge_gateway_id}"
  }

  response, _headers = send_request(params)

  interesting = response.css(
    'EdgeGateway Configuration EdgeGatewayServiceConfiguration'
  )
  interesting.css('NatService NatRule').each do |node|
    if node.css('RuleType').text == 'DNAT' &&
       node.css('GatewayNatRule/OriginalIp').text == edge_gateway_ip &&
       node.css('GatewayNatRule/TranslatedIp').text == edge_vapp_ip
      node.remove
    end
    if node.css('RuleType').text == 'SNAT' &&
       node.css('GatewayNatRule/OriginalIp').text == edge_vapp_ip &&
       node.css('GatewayNatRule/TranslatedIp').text == edge_gateway_ip
      node.remove
    end
  end

  interesting.css('FirewallService FirewallRule').each do |node|
    if node.css('Port').text == '-1' &&
       node.css('DestinationIp').text == edge_gateway_ip &&
       node.css('DestinationPortRange').text == 'Any'
      node.remove
    end
  end

  builder = Nokogiri::XML::Builder.new
  builder << interesting

  remove_edge_rules = Nokogiri::XML(builder.to_xml)

  xml = remove_edge_rules.at_css 'EdgeGatewayServiceConfiguration'
  xml['xmlns'] = 'http://www.vmware.com/vcloud/v1.5'

  params = {
    'method'  => :post,
    'command' => "/admin/edgeGateway/#{edge_gateway_id}/action/" +
                 'configureServices'
  }

  _response, headers = send_request(
    params,
    remove_edge_rules.to_xml,
    'application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml'
  )

  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#reset_vapp(vapp_id) ⇒ Object

reset a given vapp This will basically reset the VMs within the vApp vShield Edge devices are not affected.



534
535
536
537
538
539
540
541
542
543
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 534

def reset_vapp(vapp_id)
  params = {
    'method'  => :post,
    'command' => "/vApp/vapp-#{vapp_id}/power/action/reset"
  }

  _response, headers = send_request(params)
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#reset_vm(vm_id) ⇒ Object

reset a given VM This will basically reset the VMs within the vApp vShield Edge devices are not affected.



666
667
668
669
670
671
672
673
674
675
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 666

def reset_vm(vm_id)
  params = {
    'method'  => :post,
    'command' => "/vApp/vm-#{vm_id}/power/action/reset"
  }

  _response, headers = send_request(params)
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#set_metadata(link, data) ⇒ Object

Add metadata



2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 2242

def (link, data)
  params = {
    'method'  => :post,
    'command' => "/#{link}/metadata"
  }

  md = Nokogiri::XML::Builder.new do |xml|
    xml.Metadata('xmlns' => 'http://www.vmware.com/vcloud/v1.5',
                 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
                 'type' => 'application/vnd.vmware.vcloud.metadata+xml') do
      data.each do |d|
        xml.MetadataEntry('type' => 'application/vnd.vmware.vcloud.metadata.value+xml') {
          xml.Key(d[0])
          if d[1].kind_of?(Integer)
            typ = 'MetadataNumberValue'
          elsif !!d[1] == d[1] # boolean
            typ = 'MetadataBooleanValue'
          else
            typ = 'MetadataStringValue'
          end
          xml.TypedValue('xsi:type' => typ) {
            xml.Value(d[1])
          }
        }
      end
    end
  end

  _response, headers = send_request(
    params,
    md.to_xml,
    'application/vnd.vmware.vcloud.metadata+xml'
  )

  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id

end

#set_ovf_properties(vm_id, properties) ⇒ Object

Set OVF data



2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 2283

def set_ovf_properties(vm_id, properties)
  params = {
    'method'  => :get,
    'command' => "/vApp/vm-#{vm_id}/productSections"
  }
  response, _headers = send_request(params)

  changed = false
  response.css('ovf|Property').each do |prop|
    next if prop['ovf:userConfigurable'] == 'false'
    key = prop['ovf:key']
    next if !properties[ key ]
    if properties[ key ] != prop['ovf:value']
      changed = true
      prop['ovf:value'] = properties[ key ]
    end
  end

  if changed
    params = {
      'method'  => :put,
      'command' => "/vApp/vm-#{vm_id}/productSections"
    }
    _response, headers = send_request(
      params,
      response.to_xml,
      'application/vnd.vmware.vcloud.productSections+xml'
    )

    task_id = URI(headers['Location']).path.gsub('/api/task/', '')
    return task_id
  end
  return nil
end

#set_vapp_metadata(id, data) ⇒ Object

Add metadata



2226
2227
2228
2229
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 2226

def (id, data)
  task_id =  "vApp/vapp-#{id}", data
  task_id
end

#set_vapp_network_config(vapp_id, network_name, config = {}) ⇒ Object

Set vApp Network Config



1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1888

def set_vapp_network_config(vapp_id, network_name, config = {})
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.NetworkConfigSection(
      'xmlns' => 'http://www.vmware.com/vcloud/v1.5',
      'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1'
    ) {
      xml['ovf'].Info 'Network configuration'
      xml.NetworkConfig('networkName' => network_name) {
        xml.Configuration {
          xml.FenceMode(config[:fence_mode] || 'isolated')
          xml.RetainNetInfoAcrossDeployments(config[:retain_net] || false)
          xml.ParentNetwork('href' => config[:parent_network])
        }
      }
    }
  end

  params = {
    'method'  => :put,
    'command' => "/vApp/vapp-#{vapp_id}/networkConfigSection"
  }

  _response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.networkConfigSection+xml'
  )

  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#set_vapp_port_forwarding_rules(vapp_id, network_name, config = {}) ⇒ Object

Set vApp port forwarding rules

  • vapp_id: id of the vapp to be modified

  • network_name: name of the vapp network to be modified

  • config: hash with network configuration specifications, must contain an array inside :nat_rules with the nat rules to be applied.



1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1056

def set_vapp_port_forwarding_rules(vapp_id, network_name, config = {})
  builder = Nokogiri::XML::Builder.new do |xml|
  xml.NetworkConfigSection(
    'xmlns' => 'http://www.vmware.com/vcloud/v1.5',
    'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1') {
    xml['ovf'].Info 'Network configuration'
    xml.NetworkConfig('networkName' => network_name) {
      xml.Configuration {
        xml.ParentNetwork('href' => "#{@api_url}/network/#{config[:parent_network]}")
        xml.FenceMode(config[:fence_mode] || 'isolated')
        xml.Features {
          xml.NatService {
            xml.IsEnabled 'true'
            xml.NatType 'portForwarding'
            xml.Policy(config[:nat_policy_type] || 'allowTraffic')
            config[:nat_rules].each do |nat_rule|
              xml.NatRule {
                xml.VmRule {
                  xml.ExternalPort nat_rule[:nat_external_port]
                  xml.VAppScopedVmId nat_rule[:vapp_scoped_local_id]
                  xml.VmNicId(nat_rule[:nat_vmnic_id] || '0')
                  xml.InternalPort nat_rule[:nat_internal_port]
                  xml.Protocol(nat_rule[:nat_protocol] || 'TCP')
                }
              }
            end
          }
        }
      }
    }
  }
  end

  params = {
    'method'  => :put,
    'command' => "/vApp/vapp-#{vapp_id}/networkConfigSection"
  }

  _response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.networkConfigSection+xml'
  )

  task_id = URI(headers['Location']).path.gsub("/api/task/", '')
  task_id
end

#set_vm_guest_customization(vm_id, computer_name, config = {}) ⇒ Object

Set VM Guest Customization Config



1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1993

def set_vm_guest_customization(vm_id, computer_name, config = {})
  builder = Nokogiri::XML::Builder.new do |xml|
  xml.GuestCustomizationSection(
    'xmlns' => 'http://www.vmware.com/vcloud/v1.5',
    'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1') {
      xml['ovf'].Info 'VM Guest Customization configuration'
      xml.Enabled config[:enabled] if config[:enabled]
      xml.AdminPasswordEnabled config[:admin_passwd_enabled] if config[:admin_passwd_enabled]
      xml.AdminPassword config[:admin_passwd] if config[:admin_passwd]
      xml.ComputerName computer_name
  }
  end

  params = {
    'method'  => :put,
    'command' => "/vApp/vm-#{vm_id}/guestCustomizationSection"
  }

  _response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.guestCustomizationSection+xml'
  )
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#set_vm_hardware(vm_id, cfg) ⇒ Object

Set memory and number of cpus in virtualHardwareSection of a given vm returns task_id or nil if there is no task to wait for



2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 2043

def set_vm_hardware(vm_id, cfg)
  params = {
    'method'  => :get,
    'command' => "/vApp/vm-#{vm_id}/virtualHardwareSection"
  }

  changed = false
  instance_id = -1
  hdd_address_on_parent = -1
  hdd_parent_id = nil
  hdd_bus_type = nil
  hdd_bus_sub_type = nil
  hdd_count = 0
  nic_count = 0
  nic_address_on_parent = -1
  response, _headers = send_request(params)

  response.css('ovf|Item').each do |item|
    type = item.css('rasd|ResourceType').first
    instance_id = [ instance_id, item.css('rasd|InstanceID').first.text.to_i ].max
    if type.content == '3'
      # cpus
      if cfg.cpus
        if item.at_css('rasd|VirtualQuantity').content != cfg.cpus.to_s
          item.at_css('rasd|VirtualQuantity').content = cfg.cpus
          item.at_css('rasd|ElementName').content = "#{cfg.cpus} virtual CPU(s)"
          changed = true
        end
      end
    elsif type.content == '4'
      # memory
      if cfg.memory
        if item.at_css('rasd|VirtualQuantity').content != cfg.memory.to_s
          item.at_css('rasd|VirtualQuantity').content = cfg.memory
          item.at_css('rasd|ElementName').content = "#{cfg.memory} MB of memory"
          changed = true
        end
      end
    elsif type.content == '10'
      # network card
      nic_address_on_parent = nic_address_on_parent + 1
      # nic_address_on_parent = [ nic_address_on_parent, item.css('rasd|AddressOnParent').first.text.to_i ].max
      next if !cfg.nics || nic_count == cfg.nics.length
      nic = cfg.nics[nic_count]

      orig_mac = item.css('rasd|Address').first.text
      orig_ip = item.css('rasd|Connection').first['vcloud:ipAddress']
      orig_address_mode = item.css('rasd|Connection').first['vcloud:ipAddressingMode']
      orig_primary = item.css('rasd|Connection').first['vcloud:primaryNetworkConnection']
      orig_network = item.css('rasd|Connection').first.text
      orig_parent = item.css('rasd|AddressOnParent').first.text
      # resourceSubType cannot be changed for an existing network card

      if !nic[:mac].nil?
        changed = true if nic[:mac].upcase != orig_mac.upcase
      end
      if !nic[:ip].nil?
        changed = true if orig_ip.nil? || nic[:ip].upcase != orig_ip.upcase
      end
      changed = true if nic[:ip_mode].upcase != orig_address_mode.upcase
      changed = true if nic[:primary] != orig_primary
      changed = true if nic[:network].upcase != orig_network.upcase
      changed = true if nic_address_on_parent != orig_parent

      if changed
        item.css('rasd|Address').first.content = nic[:mac] if !nic[:mac].nil?
        item.css('rasd|AddressOnParent').first.content = nic_address_on_parent if nic_address_on_parent != orig_parent
        conn = item.css('rasd|Connection').first
        conn.content = nic[:network]
        if nic[:ip_mode].upcase == 'DHCP'
          conn['vcloud:ipAddressingMode'] = 'DHCP'
        elsif nic[:ip_mode].upcase == 'STATIC'
          conn['vcloud:ipAddressingMode'] = 'MANUAL'
          conn['vcloud:ipAddress'] = nic[:ip]
        elsif nic[:ip_mode].upcase == 'POOL'
          conn['vcloud:ipAddressingMode'] = 'POOL'
          conn['vcloud:ipAddress'] = nic[:ip] if !nic[:ip].nil?
        end
        conn['vcloud:primaryNetworkConnection'] = nic[:primary]
      end
      nic_count = nic_count + 1
    elsif type.content == '17'
      # hard disk
      hdd_count = hdd_count + 1
      if hdd_parent_id.nil?
        hdd_parent_id = item.css('rasd|Parent').first.text
        hdd_bus_type = item.css('rasd|HostResource').first[:busType]
        hdd_bus_sub_type = item.css('rasd|HostResource').first[:busSubType]
      end
      if hdd_parent_id == item.css('rasd|Parent').first.text
        hdd_address_on_parent = [ hdd_address_on_parent,  item.css('rasd|AddressOnParent').first.text.to_i ].max
      end
    end
  end

  if cfg.add_hdds
    changed = true
    cfg.add_hdds.each do |hdd_size|
      hdd_address_on_parent = hdd_address_on_parent + 1
      instance_id = instance_id + 1
      newhdd = Nokogiri::XML::Builder.new do |xml|
        xml.root('xmlns:rasd' => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData',
                 'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1') do
          xml['ovf'].Item {
            xml['rasd'].AddressOnParent(hdd_address_on_parent)
            xml['rasd'].Description("Hard disk")
            xml['rasd'].ElementName("Hard disk #{hdd_address_on_parent+1}")
            xml['rasd'].HostResource()
            xml['rasd'].InstanceID(instance_id)
            xml['rasd'].Parent(hdd_parent_id)
            xml['rasd'].ResourceType(17)
          }
        end
      end
      hr = newhdd.doc.css('rasd|HostResource').first
      hr['xmlns:vcloud'] = 'http://www.vmware.com/vcloud/v1.5'
      hr['vcloud:busSubType'] = hdd_bus_sub_type
      hr['vcloud:busType'] = hdd_bus_type
      hr['vcloud:capacity'] = hdd_size
      response.css('ovf|Item').last.add_next_sibling(newhdd.doc.css('ovf|Item'))
    end
  end

  if cfg.nics
    cfg.nics.each_with_index do |nic, i|
      next if i < nic_count
      changed = true
      nic_address_on_parent = nic_address_on_parent + 1
      instance_id = instance_id + 1
      newnic = Nokogiri::XML::Builder.new do |xml|
        xml.root('xmlns:rasd' => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData',
                 'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1') do
          xml['ovf'].Item {
            xml['rasd'].Address(nic[:mac]) if !nic[:mac].nil?
            xml['rasd'].AddressOnParent(nic_address_on_parent)
            xml['rasd'].AutomaticAllocation(true)
            xml['rasd'].Connection(nic[:network])
            xml['rasd'].Description("#{nic[:type] || :vmxnet3} ethernet adapter")
            xml['rasd'].ElementName("Network adapter #{nic_count}")
            xml['rasd'].InstanceID(instance_id)
            xml['rasd'].ResourceSubType(nic[:type] || :vmxnet3)
            xml['rasd'].ResourceType(10)
          }
        end
      end
      conn = newnic.doc.css('rasd|Connection').first
      conn['xmlns:vcloud'] = 'http://www.vmware.com/vcloud/v1.5'
      if nic[:ip_mode].upcase == 'DHCP'
        conn['vcloud:ipAddressingMode'] = 'DHCP'
      elsif nic[:ip_mode].upcase == 'STATIC'
        conn['vcloud:ipAddressingMode'] = 'MANUAL'
        conn['vcloud:ipAddress'] = nic[:ip]
      elsif nic[:ip_mode].upcase == 'POOL'
        conn['vcloud:ipAddressingMode'] = 'POOL'
        conn['vcloud:ipAddress'] = nic[:ip] if !nic[:ip].nil?
      end
      conn['vcloud:primaryNetworkConnection'] = nic[:primary]
      response.css('ovf|Item').last.add_next_sibling(newnic.doc.css('ovf|Item'))
    end
  end

  if changed
    params = {
      'method'  => :put,
      'command' => "/vApp/vm-#{vm_id}/virtualHardwareSection"
    }

    _response, headers = send_request(
      params,
      response.to_xml,
      'application/vnd.vmware.vcloud.virtualhardwaresection+xml'
    )

    task_id = URI(headers['Location']).path.gsub('/api/task/', '')
    task_id
  else
    return nil
  end
end

#set_vm_metadata(id, data) ⇒ Object

Add metadata



2234
2235
2236
2237
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 2234

def (id, data)
  task_id =  "vApp/vm-#{id}", data
  task_id
end

#set_vm_nested_hypervisor(vm_id, enable) ⇒ Object

Enable VM Nested Hardware-Assisted Virtualization



2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 2021

def set_vm_nested_hypervisor(vm_id, enable)
  vm = get_vm(vm_id)
  if enable && vm[:hypervisor_enabled] == 'true'
    return nil
  elsif !enable && vm[:hypervisor_enabled] == 'false'
    return nil
  end

  action = enable ? "enable" : "disable"
  params = {
    'method'  => :post,
    'command' => "/vApp/vm-#{vm_id}/action/#{action}NestedHypervisor"
  }

  _response, headers = send_request(params)
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#set_vm_network_config(vm_id, network_name, config = {}) ⇒ Object

Set VM Network Config



1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1922

def set_vm_network_config(vm_id, network_name, config = {})
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.NetworkConnectionSection(
      'xmlns' => 'http://www.vmware.com/vcloud/v1.5',
      'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1') {
      xml['ovf'].Info 'VM Network configuration'
      xml.PrimaryNetworkConnectionIndex(config[:primary_index] || 0)
      xml.NetworkConnection(
        'network' => network_name,
        'needsCustomization' => true
      ) {
        xml.NetworkConnectionIndex(config[:network_index] || 0)
        xml.IpAddress config[:ip] if config[:ip]
        xml.IsConnected(config[:is_connected] || true)
        xml.IpAddressAllocationMode config[:ip_allocation_mode] if config[:ip_allocation_mode]
      }
    }
  end

  params = {
    'method'  => :put,
    'command' => "/vApp/vm-#{vm_id}/networkConnectionSection"
  }

  _response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.networkConnectionSection+xml'
  )

  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#set_vm_network_connected(vm_id) ⇒ Object

Set VM Network Connection state



1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1958

def set_vm_network_connected(vm_id)
  params = {
    'method'  => :get,
    'command' => "/vApp/vm-#{vm_id}/networkConnectionSection"
  }
  response, _headers = send_request(params)

  changed = false
  response.css('NetworkConnection').each do |net|
    ic = net.css('IsConnected')
    if ic.text != 'true'
      ic.first.content = 'true'
      changed = true
    end
  end

  if changed
    params = {
      'method'  => :put,
      'command' => "/vApp/vm-#{vm_id}/networkConnectionSection"
    }

    _response, headers = send_request(
      params,
      response.to_xml,
      'application/vnd.vmware.vcloud.networkConnectionSection+xml'
    )

    task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  end
  task_id
end

#shutdown_vm(vm_id) ⇒ Object

Shutdown a given VM Using undeploy with shutdown, without VMware Tools this WILL FAIL.



602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 602

def shutdown_vm(vm_id)
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.UndeployVAppParams(
    'xmlns' => 'http://www.vmware.com/vcloud/v1.5'
  ) { xml.UndeployPowerAction 'shutdown' }
  end

  params = {
    'method'  => :post,
    'command' => "/vApp/vm-#{vm_id}/action/undeploy"
  }

  _response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.undeployVAppParams+xml'
  )
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#suspend_vapp(vapp_id) ⇒ Object

Suspend a given vapp



503
504
505
506
507
508
509
510
511
512
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 503

def suspend_vapp(vapp_id)
  params = {
    'method'  => :post,
    'command' => "/vApp/vapp-#{vapp_id}/power/action/suspend"
  }

  _response, headers = send_request(params)
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#suspend_vm(vm_id) ⇒ Object

Suspend a given VM



625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 625

def suspend_vm(vm_id)
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.UndeployVAppParams(
      'xmlns' => 'http://www.vmware.com/vcloud/v1.5'
    ) { xml.UndeployPowerAction 'suspend' }
  end

  params = {
    'method'  => :post,
    'command' => "/vApp/vm-#{vm_id}/action/undeploy"
  }

  _response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.undeployVAppParams+xml'
  )
  task_id = URI(headers['Location']).path.gsub('/api/task/', '')
  task_id
end

#upload_ovf(vdc_id, vapp_name, vapp_description, ovf_file, catalog_id, upload_options = {}) ⇒ Object

Upload an OVF package

  • vdc_id

  • vappName

  • vappDescription

  • ovfFile

  • catalogId

  • uploadOptions {}



1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1661

def upload_ovf(vdc_id, vapp_name, vapp_description, ovf_file, catalog_id, upload_options = {})
  # if send_manifest is not set, setting it true
  if upload_options[:send_manifest].nil? ||
     upload_options[:send_manifest]
    upload_manifest = 'true'
  else
    upload_manifest = 'false'
  end

  builder = Nokogiri::XML::Builder.new do |xml|
    xml.UploadVAppTemplateParams(
      'xmlns' => 'http://www.vmware.com/vcloud/v1.5',
      'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1',
      'manifestRequired' => upload_manifest,
      'name' => vapp_name) {
      xml.Description vapp_description
    }
  end

  params = {
    'method'  => :post,
    'command' => "/vdc/#{vdc_id}/action/uploadVAppTemplate"
  }

  @logger.debug('Sending uploadVAppTemplate request...')

  response, headers = send_request(
    params,
    builder.to_xml,
    'application/vnd.vmware.vcloud.uploadVAppTemplateParams+xml'
  )

  # Get vAppTemplate Link from location
  vapp_template = URI(headers['Location']).path.gsub(
    '/api/vAppTemplate/vappTemplate-', ''
  )

  @logger.debug("Getting vAppTemplate ID: #{vapp_template}")
  descriptor_upload = URI(response.css(
    "Files Link[rel='upload:default']"
  ).first[:href]).path.gsub('/transfer/', '')
  transfer_guid = descriptor_upload.gsub('/descriptor.ovf', '')

  ovf_file_basename = File.basename(ovf_file, '.ovf')
  ovf_dir = File.dirname(ovf_file)

  # Send OVF Descriptor
  @logger.debug('Sending OVF Descriptor...')
  upload_url = "/transfer/#{descriptor_upload}"
  upload_filename = "#{ovf_dir}/#{ovf_file_basename}.ovf"
  upload_file(
    upload_url,
    upload_filename,
    vapp_template,
    upload_options
  )

  # Begin the catch for upload interruption
  begin
    params = {
      'method'  => :get,
      'command' => "/vAppTemplate/vappTemplate-#{vapp_template}"
    }

    response, _headers = send_request(params)

    task = response.css(
      "VAppTemplate Task[operationName='vdcUploadOvfContents']"
    ).first
    task_id = URI(task['href']).path.gsub('/api/task/', '')

    # Loop to wait for the upload links to show up in the vAppTemplate
    # we just created
    @logger.debug(
      'Waiting for the upload links to show up in the vAppTemplate ' \
      'we just created.'
    )
    while true
      response, _headers = send_request(params)
      @logger.debug('Request...')
      break unless response.css("Files Link[rel='upload:default']").count == 1
      sleep 1
    end

    if upload_manifest == 'true'
      upload_url = "/transfer/#{transfer_guid}/descriptor.mf"
      upload_filename = "#{ovf_dir}/#{ovf_file_basename}.mf"
      upload_file(
        upload_url,
        upload_filename,
        vapp_template,
        upload_options
      )
    end

    # Start uploading OVF VMDK files
    params = {
      'method'  => :get,
      'command' => "/vAppTemplate/vappTemplate-#{vapp_template}"
    }
    response, _headers = send_request(params)
    response.css(
      "Files File[bytesTransferred='0'] Link[rel='upload:default']"
    ).each do |file|
      file_name = URI(file[:href]).path.gsub("/transfer/#{transfer_guid}/", '')
      upload_filename = "#{ovf_dir}/#{file_name}"
      upload_url = "/transfer/#{transfer_guid}/#{file_name}"
      upload_file(
        upload_url,
        upload_filename,
        vapp_template,
        upload_options
      )
    end

    # Add item to the catalog catalog_id
    builder = Nokogiri::XML::Builder.new do |xml|
      xml.CatalogItem(
        'xmlns' => 'http://www.vmware.com/vcloud/v1.5',
        'type' => 'application/vnd.vmware.vcloud.catalogItem+xml',
        'name' => vapp_name) {
        xml.Description vapp_description
        xml.Entity(
          'href' => "#{@api_url}/vAppTemplate/" +
                    "vappTemplate-#{vapp_template}"
          )
      }
    end

    params = {
      'method'  => :post,
      'command' => "/catalog/#{catalog_id}/catalogItems"
    }
    # No debug here (tsugliani)
    _response, _headers = send_request(
      params,
      builder.to_xml,
      'application/vnd.vmware.vcloud.catalogItem+xml'
    )

    task_id

    ######

  rescue Exception => e
    puts "Exception detected: #{e.message}."
    puts 'Aborting task...'

    # Get vAppTemplate Task
    params = {
      'method'  => :get,
      'command' => "/vAppTemplate/vappTemplate-#{vapp_template}"
    }
    response, _headers = send_request(params)

    # Cancel Task
    cancel_hook = URI(response.css(
      "Tasks Task Link[rel='task:cancel']"
    ).first[:href]).path.gsub('/api', '')

    params = {
      'method'  => :post,
      'command' => cancel_hook
    }
    # No debug here (tsugliani)
    _response, _headers = send_request(params)
    raise
  end
end

#wait_task_completion(task_id) ⇒ Object

Poll a given task until completion



1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
# File 'lib/vagrant-vcloud/driver/version_5_1.rb', line 1856

def wait_task_completion(task_id)
  task, errormsg = nil
  loop do
    task = get_task(task_id)
    # @logger.debug(
    #  "Evaluating taskid: #{task_id}, current status #{task[:status]}"
    # )
    break if !['queued','preRunning','running'].include?(task[:status])
    sleep 5
  end

  if task[:status] == 'error'
    @logger.debug('Task Error')
    errormsg = task[:response].css('Error').first
    @logger.debug(
      "Task Error Message #{errormsg['majorErrorCode']} - " +
      "#{errormsg['message']}"
    )
    errormsg =
    "Error code #{errormsg['majorErrorCode']} - #{errormsg['message']}"
  end

  {
    :status     => task[:status],
    :errormsg   => errormsg,
    :start_time => task[:start_time],
    :end_time   => task[:end_time]
  }
end