Class: VCenterDriver::ESXHost

Inherits:
Object
  • Object
show all
Includes:
Memoize
Defined in:
lib/host.rb

Overview

Class ESXHost

Constant Summary collapse

PG_CREATE_TIMEOUT =

We will wait for 4 minutes for the pg creation

240

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Memoize

#[], #[]=, #clear, #clear_all

Constructor Details

#initialize(item, vi_client = nil) ⇒ ESXHost

Returns a new instance of ESXHost.



1006
1007
1008
1009
1010
1011
# File 'lib/host.rb', line 1006

def initialize(item, vi_client = nil)
    @net_rollback = []
    @locking = true
    @item = item
    @vi_client = vi_client
end

Instance Attribute Details

#itemObject

Returns the value of attribute item.



1000
1001
1002
# File 'lib/host.rb', line 1000

def item
  @item
end

Class Method Details

.new_from_ref(ref, vi_client) ⇒ Object



1013
1014
1015
# File 'lib/host.rb', line 1013

def self.new_from_ref(ref, vi_client)
    new(RbVmomi::VIM::HostSystem.new(vi_client.vim, ref), vi_client)
end

Instance Method Details

#assign_proxy_switch(dvs, switch_name, pnics, _pnics_available) ⇒ Object

Assign a host to a a distributed vcenter switch (proxy switch)



1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
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
1316
1317
1318
1319
1320
# File 'lib/host.rb', line 1257

def assign_proxy_switch(dvs, switch_name, pnics, _pnics_available)
    dvs = dvs.item

    # Return if host is already assigned
    return dvs unless dvs['config.host']
                      .select do |host|
                          host.config.host._ref == self['_ref']
                      end.empty?

    # Prepare spec for DVS reconfiguration
    config_spec = RbVmomi::VIM::VMwareDVSConfigSpec.new
    config_spec.name = switch_name
    config_spec.configVersion = dvs['config.configVersion']

    # Check if host is already assigned to distributed switch
    operation = 'add'
    # #operation = "edit" if !dvs['config.host'].select
    # { |host| host.config.host._ref == self['_ref'] }.empty?

    # Add host members to the distributed virtual switch
    host_member_spec =
        RbVmomi::VIM::DistributedVirtualSwitchHostMemberConfigSpec
        .new
    host_member_spec.host = @item
    host_member_spec.operation = operation
    host_member_spec.backing =
        RbVmomi::VIM::DistributedVirtualSwitchHostMemberPnicBacking
        .new
    host_member_spec.backing.pnicSpec = []

    # If pnics are needed assign pnics for uplinks
    if pnics
        pnics = pnics.split(',')
        # Get uplink portgroup from dvswitch
        uplink_key = dvs['config.uplinkPortgroup'].select do |ul|
                         ul.name == "#{switch_name}-uplink-pg"
                     end.first.key rescue nil

        unless uplink_key
            raise "Cannot find the uplink portgroup for #{switch_name}"
        end

        pnics.each do |pnic|
            pnic_spec =
                RbVmomi::VIM::DistributedVirtualSwitchHostMemberPnicSpec
                .new
            pnic_spec.pnicDevice = pnic
            pnic_spec.uplinkPortgroupKey = uplink_key
            host_member_spec.backing.pnicSpec << pnic_spec
        end
    end

    config_spec.host = [host_member_spec]

    # The DVS must be reconfigured
    dvs_reconfigure_task = dvs.ReconfigureDvs_Task(:spec => config_spec)
    dvs_reconfigure_task.wait_for_completion
    if dvs_reconfigure_task.info.state != 'success'
        raise "It wasn't possible to assign host \
        #{self['name']} as a member of #{switch_name}'"
    end

    dvs
end

#available_pnicsObject

Get physical nics that are available in a host



1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
# File 'lib/host.rb', line 1197

def available_pnics
    pnics_in_use = []
    pnics_available = []

    # Get pnics in use in standard switches
    @item.config.network.vswitch.each do |vs|
        vs.pnic.each do |pnic|
            next unless pnic.instance_of?(String)

            pnic.slice!('key-vim.host.PhysicalNic-')
            pnics_in_use << pnic
        end
    end

    # Get pnics in host
    self['config.network'].pnic.each do |pnic|
        next if pnics_in_use
                .include?(pnic.device)

        pnics_available << pnic
                           .device
    end

    pnics_available
end

#create_pg(pgname, vswitch, vlan = 0) ⇒ Object

Create a standard port group



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
# File 'lib/host.rb', line 1326

def create_pg(pgname, vswitch, vlan = 0)
    spec = RbVmomi::VIM.HostPortGroupSpec(
        :name => pgname,
        :vlanId => vlan,
        :vswitchName => vswitch,
        :policy => RbVmomi::VIM.HostNetworkPolicy
    )

    nws = self['configManager.networkSystem']

    begin
        nws.AddPortGroup(:portgrp => spec)
    rescue StandardError => e
        raise "A port group with name #{pgname} \
        could not be created. Reason: #{e.message}"
    end

    @net_rollback << { :action => :delete_pg, :name => pgname }

    # wait until the network is ready and we have a reference
    networks = @item['network'].select {|net| net.name == pgname }
    (0..PG_CREATE_TIMEOUT).each do
        break unless networks.empty?

        networks = @item['network'].select {|net| net.name == pgname }
        sleep 1
    end

    if networks.empty?
        raise 'Cannot get VCENTER_NET_REF for new port group'
    end

    networks.first._ref
end

#create_vss(name, num_ports, pnics = nil, mtu = 1500, pnics_available = nil) ⇒ Object

Create a standard vcenter switch in an ESX host



1049
1050
1051
1052
1053
1054
1055
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
# File 'lib/host.rb', line 1049

def create_vss(
    name,
    num_ports,
    pnics = nil,
    mtu = 1500,
    pnics_available = nil
)
    # Get NetworkSystem
    nws = self['configManager.networkSystem']
    hostbridge = nil
    nics = []

    num_ports = 128 if num_ports.nil?

    if pnics
        pnics = pnics.split(',')
        pnics.each do |pnic|
            # Add nics if not in use
            nics << pnic if pnics_available.include?(pnic)
        end

        if !nics.empty?
            hostbridge =
                RbVmomi::VIM::HostVirtualSwitchBondBridge(
                    :nicDevice => nics
                )
        end
    end

    # Create spec
    vswitchspec =
        RbVmomi::VIM::HostVirtualSwitchSpec(
            :bridge => hostbridge,
            :mtu => mtu,
            :numPorts => num_ports
        )

    # add vSwitch to the host
    begin
        nws.AddVirtualSwitch(:vswitchName => name, :spec => vswitchspec)
    rescue StandardError => e
        raise "The standard vSwitch #{name} could not be \
        created. AddVirtualSwitch failed Reason: #{e.message}."
    end

    @net_rollback << { :action => :delete_sw, :name => name }

    name
end

#lockObject

Locking function. Similar to flock



1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
# File 'lib/host.rb', line 1018

def lock
    hostlockname = @item['name'].downcase.tr(' ', '_')

    return unless @locking

    @locking_file =
        File
        .open("/tmp/vcenter-#{hostlockname}-lock", 'w')
    @locking_file.flock(File::LOCK_EX)
end

#network_rollbackObject



1457
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
# File 'lib/host.rb', line 1457

def network_rollback
    nws = self['configManager.networkSystem']

    @net_rollback.reverse_each do |nr|
        case nr[:action]
        when :update_pg
            begin
                nws
                    .UpdatePortGroup(
                        :pgName => nr[:name],
                        :portgrp => nr[:spec]
                    )
            rescue StandardError => e
                raise "A rollback operation for standard \
                port group #{nr[:name]} could not \
                be performed. Reason: #{e.message}"
            end
        when :update_sw
            begin
                nws
                    .UpdateVirtualSwitch(
                        :vswitchName => nr[:name],
                        :spec => nr[:spec]
                    )
            rescue StandardError => e
                raise "A rollback operation for standard \
                switch #{nr[:name]} could not \
                be performed. Reason: #{e.message}"
            end
        when :delete_sw
            begin
                nws.RemoveVirtualSwitch(:vswitchName=> nr[:name])
            rescue RbVmomi::VIM::ResourceInUse
                next # Ignore if switch in use
            rescue RbVmomi::VIM::NotFound
                next # Ignore if switch not found
            rescue StandardError => e
                raise "A rollback operation for standard \
                switch #{nr[:name]} could not \
                be performed. Reason: #{e.message}"
            end
        when :delete_pg
            begin
                nws.RemovePortGroup(:pgName => nr[:name])
            rescue RbVmomi::VIM::ResourceInUse
                next # Ignore if pg in use
            rescue RbVmomi::VIM::NotFound
                next # Ignore if pg not found
            rescue StandardError => e
                raise "A rollback operation for \
                standard port group #{nr[:name]} could \
                not be performed. Reason: #{e.message}"
            end
        end
    end
end

#pg_changes_sw?(pg, switch_name) ⇒ Boolean

Is the switch for the pg different?

Returns:

  • (Boolean)


1375
1376
1377
1378
1379
1380
1381
1382
1383
# File 'lib/host.rb', line 1375

def pg_changes_sw?(pg, switch_name)
    pg
        .spec
        .respond_to?(
            :vswitchName
        ) && pg
            .spec
            .vswitchName != switch_name
end

#pg_exists(pg_name) ⇒ Object

Check if standard port group exists in host



1365
1366
1367
1368
1369
# File 'lib/host.rb', line 1365

def pg_exists(pg_name)
    nws = self['configManager.networkSystem']
    portgroups = nws.networkInfo.portgroup
    portgroups.select {|pg| pg.spec.name == pg_name }.first rescue nil
end

#pg_inside_hostObject

Get networks inside a host



1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
# File 'lib/host.rb', line 1226

def pg_inside_host
    pg_inside = {}

    # Get pnics in use in standard switches
    @item.config.network.vswitch.each do |vs|
        pg_inside[vs.name] = []
        vs.portgroup.each do |pg|
            pg.slice!('key-vim.host.PortGroup-')
            pg_inside[vs.name] << pg
        end
    end

    pg_inside
end

#proxy_switch_exists(switch_name) ⇒ Object

Check if proxy switch exists in host for distributed virtual switch



1245
1246
1247
1248
1249
1250
1251
# File 'lib/host.rb', line 1245

def proxy_switch_exists(switch_name)
    nws = self['configManager.networkSystem']
    proxy_switches = nws.networkInfo.proxySwitch
    proxy_switches
        .select {|ps| ps.dvsName == switch_name }
        .first rescue nil
end

#remove_pg(pgname) ⇒ Object

Remove a standard port group from the host



1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
# File 'lib/host.rb', line 1427

def remove_pg(pgname)
    nws = self['configManager.networkSystem']

    swname = nil
    begin
        portgroups = nws.networkConfig.portgroup
        portgroups.each do |pg|
            if pg.spec.name == pgname
                swname = pg.spec.vswitchName
                break
            end
        end
        nws.RemovePortGroup(:pgName => pgname)
    rescue RbVmomi::VIM::ResourceInUse
        STDERR.puts "The standard portgroup \
        #{pgname} is in use so it cannot be deleted"
        return
    rescue RbVmomi::VIM::NotFound
        STDERR.puts "The standard portgroup \
        #{pgname} was not found in vCenter"
        return
    rescue StandardError => e
        raise "There was a failure while \
        deleting a standard portgroup #{pgname} \
        in vCenter. Reason: #{e.message}"
    end

    swname
end

#remove_vss(vswitch_name) ⇒ Object

Remove a standard vswitch from the host



1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
# File 'lib/host.rb', line 1173

def remove_vss(vswitch_name)
    nws = self['configManager.networkSystem']

    begin
        nws.RemoveVirtualSwitch(:vswitchName => vswitch_name)
    rescue RbVmomi::VIM::ResourceInUse
        STDERR.puts "The standard switch #{vswitch_name} \
        is in use so it cannot be deleted"
        return
    rescue RbVmomi::VIM::NotFound
        STDERR.puts "The standard switch #{vswitch_name} \
        was not found in vCenter"
        return
    rescue StandardError => e
        raise "There was a failure while deleting a vcenter \
        standard switch #{vswitch_name}. Reason: #{e.message}"
    end

    vswitch_name
end

#unlockObject

Unlock driver execution mutex



1030
1031
1032
1033
1034
# File 'lib/host.rb', line 1030

def unlock
    return unless @locking

    @locking_file.close
end

#update_pg(pg, switch_name, vlan_id) ⇒ Object

Update a standard port group



1389
1390
1391
1392
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
# File 'lib/host.rb', line 1389

def update_pg(pg, switch_name, vlan_id)
    unless pg.spec.respond_to?(:vlanId) && pg.spec.vlanId != vlan_id
        return; end

    # Backup original spec
    orig_spec = pg.spec

    # Create new spec
    pg_name = pg.spec.name

    spec = RbVmomi::VIM.HostPortGroupSpec(
        :name => pg_name,
        :vlanId => vlan_id,
        :vswitchName => switch_name,
        :policy => RbVmomi::VIM.HostNetworkPolicy
    )

    nws = self['configManager.networkSystem']

    begin
        nws.UpdatePortGroup(:pgName => pg_name, :portgrp => spec)
    rescue StandardError => e
        raise "A port group with name #{pg_name} \
        could not be updated. Reason: #{e.message}"
    end

    # Set rollback operation
    @net_rollback << {
        :action => :update_pg,
        :name => pg_name,
            :spec => orig_spec
    }
end

#update_vss(switch, name, pnics, num_ports, mtu) ⇒ Object

Update a standard vcenter switch in an ESX host



1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
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
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
# File 'lib/host.rb', line 1102

def update_vss(switch, name, pnics, num_ports, mtu)
    pnics = pnics.split(',') rescue []

    # Backup switch spec for rollback
    orig_spec = switch.spec

    # Compare current configuration and return if switch hasn't changed
    switch_has_pnics = switch
                       .spec
                       .respond_to?(
                           :bridge
                       ) && switch
                       .spec
                       .bridge
                       .respond_to?(
                           :nicDevice
                       )

    same_switch = switch.spec.respond_to?(:mtu) && switch
                  .spec
                  .mtu == mtu &&
                  switch
                  .spec
                  .respond_to?(
                      :numPorts
                  ) && switch.spec.numPorts == num_ports &&
                  (!switch_has_pnics && pnics.empty? ||
                   switch_has_pnics && switch
                   .spec
                   .bridge
                   .nicDevice
                   .uniq
                   .sort == pnics.uniq.sort)
    return if same_switch

    # Let's create a new spec and update the switch
    hostbridge = nil
    nws = self['configManager.networkSystem']
    unless pnics.empty?
        hostbridge =
            RbVmomi::VIM::HostVirtualSwitchBondBridge(
                :nicDevice => pnics
            )
    end
    vswitchspec =
        RbVmomi::VIM::HostVirtualSwitchSpec(
            :bridge => hostbridge,
            :mtu => mtu,
            :numPorts => num_ports
        )
    begin
        nws
            .UpdateVirtualSwitch(
                :vswitchName => name,
                :spec => vswitchspec
            )
    rescue StandardError => e
        raise "The standard switch with name #{name} \
        could not be updated. Reason: #{e.message}"
    end

    @net_rollback << {
        :action => :update_sw,
        :name => name,
        :spec => orig_spec
    }
end

#vss_exists(vswitch_name) ⇒ Object

Check if standard switch exists in host



1040
1041
1042
1043
# File 'lib/host.rb', line 1040

def vss_exists(vswitch_name)
    vswitches = @item.configManager.networkSystem.networkInfo.vswitch
    vswitches.select {|vs| vs.name == vswitch_name }.first rescue nil
end