forked from ManageIQ/manageiq-providers-vmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
refresh_parser.rb
1701 lines (1383 loc) · 67 KB
/
refresh_parser.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
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
721
722
723
724
725
726
727
728
729
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
766
767
768
769
770
771
772
773
774
775
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
914
915
916
917
918
919
920
921
922
923
924
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
require 'miq-uuid'
module ManageIQ::Providers
module Vmware
module InfraManager::RefreshParser
#
# EMS Inventory Parsing
#
def self.ems_inv_to_hashes(inv)
uids = {}
result = {:uid_lookup => uids}
result[:distributed_virtual_switches], uids[:distributed_virtual_switches] = dvs_inv_to_hashes(inv[:dvswitch])
uids[:distributed_virtual_portgroups] = dvpg_inv_to_hashes(inv[:dvportgroup], uids[:distributed_virtual_switches])
result[:storages], uids[:storages] = storage_inv_to_hashes(inv[:storage])
result[:clusters], uids[:clusters] = cluster_inv_to_hashes(inv[:cluster])
result[:storage_profiles], uids[:storage_profiles] = storage_profile_inv_to_hashes(inv[:storage_profile], uids[:storages], inv[:storage_profile_datastore])
result[:hosts], uids[:hosts], uids[:clusters_by_host], uids[:lans], uids[:switches], uids[:guest_devices], uids[:scsi_luns] = host_inv_to_hashes(inv[:host], inv, uids[:storages], uids[:clusters], uids[:distributed_virtual_switches], uids[:distributed_virtual_portgroups])
result[:vms], uids[:vms] = vm_inv_to_hashes(
inv[:vm],
inv[:storage],
inv[:storage_profile_entity],
uids[:storages],
uids[:storage_profiles],
uids[:hosts],
uids[:clusters_by_host],
uids[:lans]
)
result[:folders], uids[:folders] = inv_to_ems_folder_hashes(inv)
result[:resource_pools], uids[:resource_pools] = rp_inv_to_hashes(inv[:rp])
result[:customization_specs] = customization_spec_inv_to_hashes(inv[:customization_specs]) if inv.key?(:customization_specs)
link_ems_metadata(result, inv)
link_root_folder(result)
set_hidden_folders(result)
set_default_rps(result)
result
end
def self.dvs_inv_to_hashes(inv)
result = []
result_uids = {}
result_uids[:by_host_mor] = Hash.new { |h, k| h[k] = [] }
inv.to_a.each do |mor, dvs_inv|
config = dvs_inv.fetch("config", {})
summary = dvs_inv.fetch("summary", {})
mor = dvs_inv["MOR"]
name = config["name"] || summary["name"]
name = URI.decode(name)
security_policy = config.fetch_path("defaultPortConfig", "securityPolicy") || {}
allow_promiscuous = security_policy.fetch_path('allowPromiscuous', 'value')
forged_transmits = security_policy.fetch_path('forgedTransmits', 'value')
mac_changes = security_policy.fetch_path('macChanges', 'value')
new_result = {
:uid_ems => mor,
:name => name,
:ports => config["numPorts"] || 0,
:type => "ManageIQ::Providers::Vmware::InfraManager::DistributedVirtualSwitch",
:allow_promiscuous => allow_promiscuous.nil? ? nil : allow_promiscuous.to_s.casecmp('true') == 0,
:forged_transmits => forged_transmits.nil? ? nil : forged_transmits.to_s.casecmp('true') == 0,
:mac_changes => mac_changes.nil? ? nil : mac_changes.to_s.casecmp('true') == 0,
:lans => [],
:switch_uuid => config["uuid"] || summary["uuid"],
:shared => true
}
result << new_result
result_uids[new_result[:uid_ems]] = new_result
hosts = get_dvswitch_hosts(inv, new_result[:uid_ems])
hosts.each { |host_mor| result_uids[:by_host_mor][host_mor] << new_result }
end
return result, result_uids
end
def self.dvpg_inv_to_hashes(inv, dvs_uids)
result_uids = Hash.new { |h, k| h[k] = {} }
inv.to_a.each do |mor, dvpg_inv|
# skip uplink portgroup
next if dvpg_inv['tag'].detect { |e| e['key'] == 'SYSTEM/DVS.UPLINKPG' }
config = dvpg_inv["config"]
next if config.nil?
dvs = dvs_uids[config["distributedVirtualSwitch"]]
next if dvs.nil?
uid = config["key"]
security_policy = config.fetch_path("defaultPortConfig", "securityPolicy") || {}
new_result = {
:uid_ems => uid,
:name => URI.decode(config["name"]),
:tag => config.fetch_path("defaultPortConfig", "vlan", "vlanId").to_s,
:allow_promiscuous => security_policy.fetch_path('allowPromiscuous', 'value').to_s.casecmp('true') == 0,
:forged_transmits => security_policy.fetch_path('forgedTransmits', 'value').to_s.casecmp('true') == 0,
:mac_changes => security_policy.fetch_path('macChanges', 'value').to_s.casecmp('true') == 0,
}
dvs[:lans] << new_result
dvpg_inv["host"].to_miq_a.each { |h| result_uids[h][new_result[:uid_ems]] = new_result }
end
result_uids
end
def self.storage_inv_to_hashes(inv)
result = []
result_uids = {}
result_locs = {}
return result, result_uids if inv.nil?
inv.each do |mor, storage_inv|
mor = storage_inv['MOR'] # Use the MOR directly from the data since the mor as a key may be corrupt
summary = storage_inv["summary"]
next if summary.nil?
capability = storage_inv["capability"]
loc = uid = normalize_storage_uid(storage_inv)
unless result_locs[loc].nil?
result_uids[mor] = result_locs[loc]
next
end
new_result = {
:ems_ref => mor,
:ems_ref_obj => mor,
:name => summary["name"],
:store_type => summary["type"].to_s.upcase,
:total_space => summary["capacity"],
:free_space => summary["freeSpace"],
:uncommitted => summary["uncommitted"],
:multiplehostaccess => summary["multipleHostAccess"].to_s.downcase == "true",
:location => loc,
}
unless capability.nil?
new_result.merge!(
:directory_hierarchy_supported => capability['directoryHierarchySupported'].blank? ? nil : capability['directoryHierarchySupported'].to_s.downcase == 'true',
:thin_provisioning_supported => capability['perFileThinProvisioningSupported'].blank? ? nil : capability['perFileThinProvisioningSupported'].to_s.downcase == 'true',
:raw_disk_mappings_supported => capability['rawDiskMappingsSupported'].blank? ? nil : capability['rawDiskMappingsSupported'].to_s.downcase == 'true'
)
end
result << new_result
result_uids[mor] = new_result
result_locs[loc] = new_result
end
return result, result_uids
end
def self.storage_profile_inv_to_hashes(profile_inv, storage_uids, placement_inv)
result = []
result_uids = {}
profile_inv.each do |uid, profile|
new_result = {
:ems_ref => uid,
:name => profile.name,
:profile_type => profile.profileCategory,
:storage_profile_storages => []
}
placement_inv[uid].to_miq_a.each do |placement_hub|
datastore = storage_uids[placement_hub.hubId] if placement_hub.hubType == "Datastore"
new_result[:storage_profile_storages] << datastore unless datastore.nil?
end
result << new_result
result_uids[uid] = new_result
end unless profile_inv.nil?
return result, result_uids
end
def self.get_dvswitch_hosts(dvswitch_inv, switch_mor)
hosts_list = dvswitch_inv.fetch_path(switch_mor, 'config', 'host') || []
hosts = hosts_list.collect { |host_data| host_data.fetch_path('config', 'host') }
hosts += dvswitch_inv.fetch_path(switch_mor, 'summary', 'hostMember') || []
hosts.uniq
end
def self.host_inv_to_hashes(inv, ems_inv, storage_uids, cluster_uids, dvs_uids, dvpg_uids)
result = []
result_uids = {}
cluster_uids_by_host = {}
lan_uids = {}
switch_uids = {}
guest_device_uids = {}
scsi_lun_uids = {}
return result, result_uids, lan_uids, switch_uids, guest_device_uids, scsi_lun_uids if inv.nil?
inv.each do |mor, host_inv|
mor = host_inv['MOR'] # Use the MOR directly from the data since the mor as a key may be corrupt
config = host_inv["config"]
dns_config = config.fetch_path('network', 'dnsConfig') unless config.nil?
hostname = dns_config["hostName"] unless dns_config.nil?
domain_name = dns_config["domainName"] unless dns_config.nil?
summary = host_inv["summary"]
product = summary.fetch_path('config', 'product') unless summary.nil?
# Check connection state and log potential issues
connection_state = summary.fetch_path("runtime", "connectionState") unless summary.nil?
maintenance_mode = summary.fetch_path("runtime", "inMaintenanceMode") unless summary.nil?
if ['disconnected', 'notResponding', nil, ''].include?(connection_state)
_log.warn "Host [#{mor}] connection state is [#{connection_state.inspect}]. Inventory data may be missing."
end
# Determine if the data from VC is valid.
invalid, err = if config.nil? || product.nil? || summary.nil?
type = ['config', 'product', 'summary'].find_all { |t| eval(t).nil? }.join(", ")
[true, "Missing configuration for Host [#{mor}]: [#{type}]."]
elsif hostname.blank?
[true, "Missing hostname information for Host [#{mor}]: dnsConfig: #{dns_config.inspect}."]
elsif domain_name.blank?
# Use the name or the summary-config-name as the hostname if either appears to be a FQDN
fqdn = host_inv["name"]
fqdn = summary.fetch_path('config', 'name') unless fqdn =~ /^#{hostname}\./
hostname = fqdn if fqdn =~ /^#{hostname}\./
false
else
hostname = "#{hostname}.#{domain_name}"
false
end
if invalid
_log.warn "#{err} Skipping."
new_result = {
:invalid => true,
:ems_ref => mor,
:ems_ref_obj => mor
}
result << new_result
result_uids[mor] = new_result
next
end
# Remove the domain suffix if it is included in the hostname
hostname = hostname.split(',').first
# Get the IP address
ipaddress = host_inv_to_ip(host_inv, hostname) || hostname
vendor = product["vendor"].split(",").first.to_s.downcase
vendor = "unknown" unless Host::VENDOR_TYPES.include?(vendor)
product_name = product["name"].nil? ? nil : product["name"].to_s.gsub(/^VMware\s*/i, "")
# Collect the hardware, networking, and scsi inventories
switches, switch_uids[mor] = host_inv_to_switch_hashes(host_inv)
_lans, lan_uids[mor] = host_inv_to_lan_hashes(host_inv, switch_uids[mor], dvpg_uids[mor])
hardware = host_inv_to_hardware_hash(host_inv)
hardware[:guest_devices], guest_device_uids[mor] = host_inv_to_guest_device_hashes(host_inv, switch_uids[mor])
hardware[:networks] = host_inv_to_network_hashes(host_inv, guest_device_uids[mor])
_scsi_luns, scsi_lun_uids[mor] = host_inv_to_scsi_lun_hashes(host_inv)
_scsi_targets = host_inv_to_scsi_target_hashes(host_inv, guest_device_uids[mor][:storage], scsi_lun_uids[mor])
# Collect the resource pools inventory
parent_type, parent_mor, parent_data = host_parent_resource(mor, ems_inv)
if parent_type == :host_res
rp_uids = get_mors(parent_data, "resourcePool")
cluster_uids_by_host[mor] = nil
else
rp_uids = []
cluster_uids_by_host[mor] = cluster_uids[parent_mor]
end
# Collect failover host information if in a cluster
failover = nil
if parent_type == :cluster
failover_hosts = parent_data.fetch_path("configuration", "dasConfig", "admissionControlPolicy", "failoverHosts")
failover = failover_hosts && failover_hosts.include?(mor)
end
# Link up the storages
storages = get_mors(host_inv, 'datastore').collect { |s| storage_uids[s] }.compact
# Find the host->storage mount info
host_storages = host_inv_to_host_storages_hashes(host_inv, ems_inv[:storage], storage_uids)
host_dvswitches = dvs_uids[:by_host_mor][mor] || []
# Store the host 'name' value as uid_ems to use as the lookup value with MiqVim
uid_ems = summary.nil? ? nil : summary.fetch_path('config', 'name')
# Get other information
asset_tag = service_tag = nil
host_inv.fetch_path("hardware", "systemInfo", "otherIdentifyingInfo").to_miq_a.each do |info|
next unless info.kind_of?(Hash)
value = info["identifierValue"].to_s.strip
value = nil if value.blank?
case info.fetch_path("identifierType", "key")
when "AssetTag" then asset_tag = value
when "ServiceTag" then service_tag = value
end
end
new_result = {
:type => %w(esx esxi).include?(product_name.to_s.downcase) ? "ManageIQ::Providers::Vmware::InfraManager::HostEsx" : "ManageIQ::Providers::Vmware::InfraManager::Host",
:ems_ref => mor,
:ems_ref_obj => mor,
:name => hostname,
:hostname => hostname,
:ipaddress => ipaddress,
:uid_ems => uid_ems,
:vmm_vendor => vendor,
:vmm_version => product["version"],
:vmm_product => product_name,
:vmm_buildnumber => product["build"],
:connection_state => connection_state,
:power_state => connection_state != "connected" ? "off" : (maintenance_mode.to_s.downcase == "true" ? "maintenance" : "on"),
:admin_disabled => config["adminDisabled"].to_s.downcase == "true",
:maintenance => maintenance_mode.to_s.downcase == "true",
:asset_tag => asset_tag,
:service_tag => service_tag,
:failover => failover,
:hyperthreading => config.fetch_path("hyperThread", "active").to_s.downcase == "true",
:ems_cluster => cluster_uids_by_host[mor],
:operating_system => host_inv_to_os_hash(host_inv, hostname),
:system_services => host_inv_to_system_service_hashes(host_inv),
:hardware => hardware,
:switches => switches,
:storages => storages,
:host_storages => host_storages,
:host_switches => switches + host_dvswitches,
:child_uids => rp_uids,
}
result << new_result
result_uids[mor] = new_result
end
return result, result_uids, cluster_uids_by_host, lan_uids, switch_uids, guest_device_uids, scsi_lun_uids
end
def self.host_inv_to_ip(inv, hostname = nil)
_log.debug("IP lookup for host in VIM inventory data...")
ipaddress = nil
default_gw = inv.fetch_path("config", "network", "ipRouteConfig", "defaultGateway")
unless default_gw.blank?
require 'ipaddr'
default_gw = IPAddr.new(default_gw)
network = inv.fetch_path("config", "network")
vnics = network['consoleVnic'].to_miq_a + network['vnic'].to_miq_a
vnics.each do |vnic|
ip = vnic.fetch_path("spec", "ip", "ipAddress")
subnet_mask = vnic.fetch_path("spec", "ip", "subnetMask")
next if ip.blank? || subnet_mask.blank?
if default_gw.mask(subnet_mask).include?(ip)
ipaddress = ip
_log.debug("IP lookup for host in VIM inventory data...Complete: IP found: [#{ipaddress}]")
break
end
end
end
if ipaddress.nil?
warn_msg = "IP lookup for host in VIM inventory data...Failed."
if [nil, "localhost", "localhost.localdomain", "127.0.0.1"].include?(hostname)
_log.warn warn_msg
else
_log.warn "#{warn_msg} Falling back to reverse lookup."
begin
# IPSocket.getaddress(hostname) is not used because it was appending
# a ".com" to the "esxdev001.localdomain" which resolved to a real
# internet address. Socket.getaddrinfo does the right thing.
# TODO: Can this moved to MiqSockUtil?
_log.debug "IP lookup by hostname [#{hostname}]..."
ipaddress = Socket.getaddrinfo(hostname, nil)[0][3]
_log.debug "IP lookup by hostname [#{hostname}]...Complete: IP found: [#{ipaddress}]"
rescue => err
_log.warn "IP lookup by hostname [#{hostname}]...Failed with the following error: #{err}"
end
end
end
ipaddress
end
def self.host_inv_to_os_hash(inv, hostname)
inv = inv.fetch_path('summary', 'config', 'product')
return nil if inv.nil?
result = {:name => hostname}
result[:product_name] = inv["name"].gsub(/^VMware\s*/i, "") unless inv["name"].blank?
result[:version] = inv["version"] unless inv["version"].blank?
result[:build_number] = inv["build"] unless inv["build"].blank?
result[:product_type] = inv["osType"] unless inv["osType"].blank?
result
end
def self.host_inv_to_hardware_hash(inv)
hardware_serial = inv.fetch_path('hardware', 'systemInfo', 'uuid')
console = inv.fetch_path('config', 'consoleReservation')
inv = inv['summary']
return nil if inv.nil?
result = {}
hdw = inv["hardware"]
unless hdw.blank?
result[:cpu_speed] = hdw["cpuMhz"] unless hdw["cpuMhz"].blank?
result[:cpu_type] = hdw["cpuModel"] unless hdw["cpuModel"].blank?
result[:manufacturer] = hdw["vendor"] unless hdw["vendor"].blank?
result[:model] = hdw["model"] unless hdw["model"].blank?
result[:number_of_nics] = hdw["numNics"] unless hdw["numNics"].blank?
# Value provided by VC is in bytes, need to convert to MB
result[:memory_mb] = is_numeric?(hdw["memorySize"]) ? (hdw["memorySize"].to_f / 1.megabyte).round : nil
unless console.nil?
result[:memory_console] = is_numeric?(console["serviceConsoleReserved"]) ? (console["serviceConsoleReserved"].to_f / 1048576).round : nil
end
result[:cpu_sockets] = hdw["numCpuPkgs"] unless hdw["numCpuPkgs"].blank?
result[:cpu_total_cores] = hdw["numCpuCores"] unless hdw["numCpuCores"].blank?
# Calculate the number of cores per socket by dividing total numCpuCores by numCpuPkgs
result[:cpu_cores_per_socket] = (result[:cpu_total_cores].to_f / result[:cpu_sockets].to_f).to_i unless hdw["numCpuCores"].blank? || hdw["numCpuPkgs"].blank?
result[:serial_number] = hardware_serial
end
config = inv["config"]
unless config.blank?
value = config.fetch_path("product", "name")
unless value.blank?
value = value.to_s.gsub(/^VMware\s*/i, "")
result[:guest_os] = value
result[:guest_os_full_name] = value
end
result[:vmotion_enabled] = config["vmotionEnabled"].to_s.downcase == "true" unless config["vmotionEnabled"].blank?
end
quickStats = inv["quickStats"]
unless quickStats.blank?
result[:cpu_usage] = quickStats["overallCpuUsage"] unless quickStats["overallCpuUsage"].blank?
result[:memory_usage] = quickStats["overallMemoryUsage"] unless quickStats["overallMemoryUsage"].blank?
end
result
end
def self.host_inv_to_switch_hashes(inv)
inv = inv.fetch_path('config', 'network')
result = []
result_uids = {:pnic_id => {}}
return result, result_uids if inv.nil?
inv['vswitch'].to_miq_a.each do |data|
name = uid = data['name']
pnics = data['pnic'].to_miq_a
security_policy = data.fetch_path('spec', 'policy', 'security') || {}
new_result = {
:uid_ems => uid,
:mtu => data['mtu'].nil? ? nil : data['mtu'].to_i,
:name => name,
:ports => data['numPorts'],
:type => self.parent::HostVirtualSwitch.name,
:allow_promiscuous => security_policy['allowPromiscuous'].nil? ? nil : security_policy['allowPromiscuous'].to_s.downcase == 'true',
:forged_transmits => security_policy['forgedTransmits'].nil? ? nil : security_policy['forgedTransmits'].to_s.downcase == 'true',
:mac_changes => security_policy['macChanges'].nil? ? nil : security_policy['macChanges'].to_s.downcase == 'true',
:lans => []
}
result << new_result
result_uids[uid] = new_result
pnics.each { |pnic| result_uids[:pnic_id][pnic] = new_result unless pnic.blank? }
end
return result, result_uids
end
def self.host_inv_to_lan_hashes(inv, switch_uids, dvpg_uids)
inv = inv.fetch_path('config', 'network')
result = []
result_uids = dvpg_uids || {}
return result, result_uids if inv.nil?
inv['portgroup'].to_miq_a.each do |data|
spec = data['spec']
next if spec.nil?
# Find the switch to which this lan is connected
switch = switch_uids[spec['vswitchName']]
next if switch.nil?
name = uid = spec['name']
security_policy = data.fetch_path('spec', 'policy', 'security') || {}
computed_security_policy = data.fetch_path('computedPolicy', 'security') || {}
new_result = {
:uid_ems => uid,
:name => name,
:tag => spec['vlanId'].to_s,
:allow_promiscuous => security_policy['allowPromiscuous'].nil? ? nil : security_policy['allowPromiscuous'].to_s.downcase == 'true',
:forged_transmits => security_policy['forgedTransmits'].nil? ? nil : security_policy['forgedTransmits'].to_s.downcase == 'true',
:mac_changes => security_policy['macChanges'].nil? ? nil : security_policy['macChanges'].to_s.downcase == 'true',
:computed_allow_promiscuous => computed_security_policy['allowPromiscuous'].nil? ? nil : computed_security_policy['allowPromiscuous'].to_s.downcase == 'true',
:computed_forged_transmits => computed_security_policy['forgedTransmits'].nil? ? nil : computed_security_policy['forgedTransmits'].to_s.downcase == 'true',
:computed_mac_changes => computed_security_policy['macChanges'].nil? ? nil : computed_security_policy['macChanges'].to_s.downcase == 'true',
}
result << new_result
result_uids[uid] = new_result
switch[:lans] << new_result
end
return result, result_uids
end
def self.host_inv_to_guest_device_hashes(inv, switch_uids)
inv = inv['config']
result = []
result_uids = {}
return result, result_uids if inv.nil?
network = inv["network"]
storage = inv["storageDevice"]
return result, result_uids if network.nil? && storage.nil?
result_uids[:pnic] = {}
unless network.nil?
network['pnic'].to_miq_a.each do |data|
# Find the switch to which this pnic is connected
switch = switch_uids[:pnic_id][data['key']]
name = uid = data['device']
new_result = {
:uid_ems => uid,
:device_name => name,
:device_type => 'ethernet',
:location => data['pci'],
:present => true,
:controller_type => 'ethernet',
:address => data['mac']
}
new_result[:switch] = switch unless switch.nil?
result << new_result
result_uids[:pnic][uid] = new_result
end
end
result_uids[:storage] = {:adapter_id => {}}
unless storage.nil?
storage['hostBusAdapter'].to_miq_a.each do |data|
name = uid = data['device']
adapter = data['key']
chap_auth_enabled = data.fetch_path('authenticationProperties', 'chapAuthEnabled')
new_result = {
:uid_ems => uid,
:device_name => name,
:device_type => 'storage',
:present => true,
:iscsi_name => data['iScsiName'].blank? ? nil : data['iScsiName'],
:iscsi_alias => data['iScsiAlias'].blank? ? nil : data['iScsiAlias'],
:location => data['pci'].blank? ? nil : data['pci'],
:model => data['model'].blank? ? nil : data['model'],
:chap_auth_enabled => chap_auth_enabled.blank? ? nil : chap_auth_enabled.to_s.downcase == "true"
}
new_result[:controller_type] = case data.xsiType.to_s.split("::").last
when 'HostBlockHba' then 'Block'
when 'HostFibreChannelHba' then 'Fibre'
when 'HostInternetScsiHba' then 'iSCSI'
when 'HostParallelScsiHba' then 'SCSI'
when 'HostBusAdapter' then 'HBA'
end
result << new_result
result_uids[:storage][uid] = new_result
result_uids[:storage][:adapter_id][adapter] = new_result
end
end
return result, result_uids
end
def self.host_inv_to_network_hashes(inv, guest_device_uids)
inv = inv.fetch_path('config', 'network')
result = []
return result if inv.nil?
vnics = inv['consoleVnic'].to_miq_a + inv['vnic'].to_miq_a
vnics.to_miq_a.each do |vnic|
# Find the pnic to which this service console is connected
port_key = vnic['port']
portgroup = inv['portgroup'].to_miq_a.find { |pg| pg['port'].to_miq_a.find { |p| p['key'] == port_key } }
next if portgroup.nil?
vswitch_key = portgroup['vswitch']
vswitch = inv['vswitch'].to_miq_a.find { |v| v['key'] == vswitch_key }
next if vswitch.nil?
pnic_key = vswitch['pnic'].to_miq_a[0]
pnic = inv['pnic'].to_miq_a.find { |p| p['key'] == pnic_key }
next if pnic.nil?
uid = pnic['device']
guest_device = guest_device_uids.fetch_path(:pnic, uid)
# Get the ip section
ip = vnic.fetch_path('spec', 'ip')
next if ip.nil?
new_result = {
:description => uid,
:dhcp_enabled => ip['dhcp'].to_s.downcase == 'true',
:ipaddress => ip['ipAddress'],
:subnet_mask => ip['subnetMask'],
}
result << new_result
guest_device[:network] = new_result unless guest_device.nil?
end
result
end
def self.host_inv_to_scsi_lun_hashes(inv)
inv = inv.fetch_path('config', 'storageDevice')
result = []
result_uids = {}
return result, result_uids if inv.nil?
inv['scsiLun'].to_miq_a.each do |data|
new_result = {
:uid_ems => data['uuid'],
:canonical_name => data['canonicalName'].blank? ? nil : data['canonicalName'],
:lun_type => data['lunType'].blank? ? nil : data['lunType'],
:device_name => data['deviceName'].blank? ? nil : data['deviceName'],
:device_type => data['deviceType'].blank? ? nil : data['deviceType'],
}
# :lun will be set later when we link to scsi targets
cap = data['capacity']
if cap.nil?
new_result[:block] = new_result[:block_size] = new_result[:capacity] = nil
else
block = cap['block'].blank? ? nil : cap['block']
block_size = cap['blockSize'].blank? ? nil : cap['blockSize']
new_result[:block] = block
new_result[:block_size] = block_size
new_result[:capacity] = (block.nil? || block_size.nil?) ? nil : ((block.to_i * block_size.to_i) / 1024)
end
result << new_result
result_uids[data['key']] = new_result
end
return result, result_uids
end
def self.host_inv_to_scsi_target_hashes(inv, guest_device_uids, scsi_lun_uids)
inv = inv.fetch_path('config', 'storageDevice', 'scsiTopology', 'adapter')
result = []
return result if inv.nil?
inv.to_miq_a.each do |adapter|
adapter['target'].to_miq_a.each do |data|
target = uid = data['target'].to_s
new_result = {
:uid_ems => uid,
:target => target
}
transport = data['transport']
if transport.nil?
new_result[:iscsi_name], new_result[:iscsi_alias], new_result[:address] = nil
else
new_result[:iscsi_name] = transport['iScsiName'].blank? ? nil : transport['iScsiName']
new_result[:iscsi_alias] = transport['iScsiAlias'].blank? ? nil : transport['iScsiAlias']
new_result[:address] = transport['address'].blank? ? nil : transport['address']
end
# Link the scsi target to the bus adapter
guest_device = guest_device_uids[:adapter_id][adapter['adapter']]
unless guest_device.nil?
guest_device[:miq_scsi_targets] ||= []
guest_device[:miq_scsi_targets] << new_result
end
# Link the scsi target to the scsi luns
data['lun'].to_miq_a.each do |l|
# We dup here so that later saving of ids doesn't cause a clash
# TODO: Change this if we get to a better normalized structure in
# the database.
lun = scsi_lun_uids[l['scsiLun']].dup
unless lun.nil?
lun[:lun] = l['lun'].to_s
new_result[:miq_scsi_luns] ||= []
new_result[:miq_scsi_luns] << lun
end
end
result << new_result
end
end
result
end
def self.host_inv_to_system_service_hashes(inv)
inv = inv.fetch_path('config', 'service')
result = []
return result if inv.nil?
inv['service'].to_miq_a.each do |data|
result << {
:name => data['key'],
:display_name => data['label'],
:running => data['running'].to_s == 'true',
}
end
result
end
def self.host_inv_to_host_storages_hashes(inv, storage_inv, storage_uids)
result = []
storage_inv.each do |s_mor, s_inv|
# Find the DatastoreHostMount object for this host
host_mount = Array.wrap(s_inv["host"]).detect { |host| host["key"] == inv["MOR"] }
next if host_mount.nil?
mount_info = host_mount["mountInfo"] || {}
read_only = mount_info["accessMode"] == "readOnly"
accessible = mount_info["accessible"].present? ? mount_info["accessible"].to_s.downcase == "true" : true
result << {
:storage => storage_uids[s_mor],
:read_only => read_only,
:accessible => accessible,
:ems_ref => s_mor
}
end
result
end
def self.storage_profile_by_entity(storage_profile_entity_inv, storage_profile_uids)
groupings = {'virtualDiskId' => {}, 'virtualMachine' => {}}
storage_profile_entity_inv.each do |storage_profile_uid, entities|
next if storage_profile_uids[storage_profile_uid][:profile_type] == 'RESOURCE'
entities.each do |entity|
groupings[entity.objectType][entity.key] = storage_profile_uids[storage_profile_uid]
end
end
[groupings['virtualDiskId'], groupings['virtualMachine']]
end
def self.vm_inv_to_hashes(
inv,
storage_inv,
storage_profile_entity_inv,
storage_uids,
storage_profile_uids,
host_uids,
cluster_uids_by_host,
lan_uids
)
result = []
result_uids = {}
guest_device_uids = {}
return result, result_uids if inv.nil?
storage_profile_by_disk_mor, storage_profile_by_vm_mor = storage_profile_by_entity(
storage_profile_entity_inv,
storage_profile_uids
)
inv.each do |mor, vm_inv|
mor = vm_inv['MOR'] # Use the MOR directly from the data since the mor as a key may be corrupt
summary = vm_inv["summary"]
summary_config = summary["config"] unless summary.nil?
pathname = summary_config["vmPathName"] unless summary_config.nil?
config = vm_inv["config"]
# Determine if the data from VC is valid.
invalid, err = if summary_config.nil? || config.nil?
type = ['summary_config', 'config'].find_all { |t| eval(t).nil? }.join(", ")
[true, "Missing configuration for VM [#{mor}]: #{type}."]
elsif summary_config["uuid"].blank? && config["uuid"].blank?
[true, "Missing UUID for VM [#{mor}]."]
elsif pathname.blank?
_log.debug "vmPathname class: [#{pathname.class}] inspect: [#{pathname.inspect}]"
[true, "Missing pathname location for VM [#{mor}]."]
else
false
end
if invalid
_log.warn "#{err} Skipping."
new_result = {
:invalid => true,
:ems_ref => mor,
:ems_ref_obj => mor
}
result << new_result
result_uids[mor] = new_result
next
end
runtime = summary['runtime']
template = summary_config["template"].to_s.downcase == "true"
raw_power_state = template ? "never" : runtime['powerState']
begin
storage_name, location = VmOrTemplate.repository_parse_path(pathname)
rescue => err
_log.warn("Warning: [#{err.message}]")
_log.debug("Problem processing location for VM [#{summary_config["name"]}] location: [#{pathname}]")
location = VmOrTemplate.location2uri(pathname)
end
affinity_set = config.fetch_path('cpuAffinity', 'affinitySet')
# The affinity_set will be an array of integers if set
cpu_affinity = nil
cpu_affinity = affinity_set.kind_of?(Array) ? affinity_set.join(",") : affinity_set.to_s if affinity_set
tools_status = summary.fetch_path('guest', 'toolsStatus')
tools_status = nil if tools_status.blank?
# tools_installed = case tools_status
# when 'toolsNotRunning', 'toolsOk', 'toolsOld' then true
# when 'toolsNotInstalled' then false
# when nil then nil
# else false
# end
boot_time = runtime['bootTime'].blank? ? nil : runtime['bootTime']
standby_act = nil
power_options = config["defaultPowerOps"]
unless power_options.blank?
standby_act = power_options["standbyAction"] if power_options["standbyAction"]
# Other possible keys to look at:
# defaultPowerOffType, defaultResetType, defaultSuspendType
# powerOffType, resetType, suspendType
end
# Other items to possibly include:
# boot_delay = config.fetch_path("bootOptions", "bootDelay")
# virtual_mmu_usage = config.fetch_path("flags", "virtualMmuUsage")
# Collect the reservation information
resource_config = vm_inv["resourceConfig"]
memory = resource_config && resource_config["memoryAllocation"]
cpu = resource_config && resource_config["cpuAllocation"]
# Collect the storages and hardware inventory
storages = get_mors(vm_inv, 'datastore').collect { |s| storage_uids[s] }.compact
storage = storage_uids[normalize_vm_storage_uid(vm_inv, storage_inv)]
host_mor = runtime['host']
hardware = vm_inv_to_hardware_hash(vm_inv)
hardware[:disks] = vm_inv_to_disk_hashes(vm_inv, storage_uids, storage_profile_by_disk_mor)
hardware[:guest_devices], guest_device_uids[mor] = vm_inv_to_guest_device_hashes(vm_inv, lan_uids[host_mor])
hardware[:networks] = vm_inv_to_network_hashes(vm_inv, guest_device_uids[mor])
uid = hardware[:bios]
new_result = {
:type => template ? ManageIQ::Providers::Vmware::InfraManager::Template.name : ManageIQ::Providers::Vmware::InfraManager::Vm.name,
:ems_ref => mor,
:ems_ref_obj => mor,
:uid_ems => uid,
:name => URI.decode(summary_config["name"]),
:vendor => "vmware",
:raw_power_state => raw_power_state,
:location => location,
:tools_status => tools_status,
:boot_time => boot_time,
:standby_action => standby_act,
:connection_state => runtime['connectionState'],
:cpu_affinity => cpu_affinity,
:template => template,
:linked_clone => vm_inv_to_linked_clone(vm_inv),
:fault_tolerance => vm_inv_to_fault_tolerance(vm_inv),
:memory_reserve => memory && memory["reservation"],
:memory_reserve_expand => memory && memory["expandableReservation"].to_s.downcase == "true",
:memory_limit => memory && memory["limit"],
:memory_shares => memory && memory.fetch_path("shares", "shares"),
:memory_shares_level => memory && memory.fetch_path("shares", "level"),
:cpu_reserve => cpu && cpu["reservation"],
:cpu_reserve_expand => cpu && cpu["expandableReservation"].to_s.downcase == "true",
:cpu_limit => cpu && cpu["limit"],
:cpu_shares => cpu && cpu.fetch_path("shares", "shares"),
:cpu_shares_level => cpu && cpu.fetch_path("shares", "level"),
:host => host_uids[host_mor],
:ems_cluster => cluster_uids_by_host[host_mor],
:storages => storages,
:storage => storage,
:storage_profile => storage_profile_by_vm_mor[mor],
:operating_system => vm_inv_to_os_hash(vm_inv),
:hardware => hardware,
:custom_attributes => vm_inv_to_custom_attribute_hashes(vm_inv),
:snapshots => vm_inv_to_snapshot_hashes(vm_inv),
:cpu_hot_add_enabled => config['cpuHotAddEnabled'],
:cpu_hot_remove_enabled => config['cpuHotRemoveEnabled'],
:memory_hot_add_enabled => config['memoryHotAddEnabled'],
:memory_hot_add_limit => config['hotPlugMemoryLimit'],
:memory_hot_add_increment => config['hotPlugMemoryIncrementSize'],
}
result << new_result
result_uids[mor] = new_result
end
return result, result_uids
end
# The next 3 methods determine shared VMs (linked clones or fault tolerance).
# Information found at http://www.vmdev.info/?p=546
def self.vm_inv_to_shared(inv)
unshared = inv.fetch_path("summary", "storage", "unshared")
committed = inv.fetch_path("summary", "storage", "committed")
unshared.nil? || committed.nil? ? nil : unshared.to_i != committed.to_i
end
def self.vm_inv_to_linked_clone(inv)
vm_inv_to_shared(inv) && inv.fetch_path("summary", "config", "ftInfo", "instanceUuids").to_miq_a.length <= 1
end
def self.vm_inv_to_fault_tolerance(inv)
vm_inv_to_shared(inv) && inv.fetch_path("summary", "config", "ftInfo", "instanceUuids").to_miq_a.length > 1
end
def self.vm_inv_to_os_hash(inv)
inv = inv.fetch_path('summary', 'config')
return nil if inv.nil?
result = {
# If the data from VC is empty, default to "Other"
:product_name => inv["guestFullName"].blank? ? "Other" : inv["guestFullName"]
}
result
end
def self.vm_inv_to_hardware_hash(inv)
config = inv['config']
inv = inv.fetch_path('summary', 'config')
return nil if inv.nil?
result = {
# Downcase and strip off the word "guest" to match the value stored in the .vmx config file.
:guest_os => inv["guestId"].blank? ? "Other" : inv["guestId"].to_s.downcase.chomp("guest"),
# If the data from VC is empty, default to "Other"
:guest_os_full_name => inv["guestFullName"].blank? ? "Other" : inv["guestFullName"]