/
host.rb
1974 lines (1637 loc) · 62.6 KB
/
host.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
$LOAD_PATH << File.join(GEMS_PENDING_ROOT, "util/xml")
$LOAD_PATH << File.join(GEMS_PENDING_ROOT, "util/win32")
$LOAD_PATH << File.join(GEMS_PENDING_ROOT, "metadata/linux")
require 'ostruct'
require 'MiqSockUtil'
require 'xml_utils'
require 'cgi' # Used for URL encoding/decoding
require 'LinuxUsers'
require 'LinuxUtils'
$LOAD_PATH << File.join(GEMS_PENDING_ROOT, "metadata/ScanProfile")
require 'HostScanProfiles'
class Host < ActiveRecord::Base
include NewWithTypeStiMixin
VENDOR_TYPES = {
# DB Displayed
"microsoft" => "Microsoft",
"redhat" => "RedHat",
"vmware" => "VMware",
"openstack_infra" => "OpenStack Infrastructure",
"unknown" => "Unknown",
nil => "Unknown",
}
HOST_DISCOVERY_TYPES = {
'vmware' => 'esx',
'ipmi' => 'ipmi'
}
HOST_CREATE_OS_TYPES = {
'VMware ESX' => 'linux_generic',
# 'Microsoft Hyper-V' => 'windows_generic'
}
validates_presence_of :name
validates_uniqueness_of :name
validates_inclusion_of :user_assigned_os, :in => ["linux_generic", "windows_generic", nil]
validates_inclusion_of :vmm_vendor, :in => VENDOR_TYPES.values
belongs_to :ext_management_system, :foreign_key => "ems_id"
belongs_to :ems_cluster
has_one :operating_system, :dependent => :destroy
has_one :hardware, :dependent => :destroy
has_many :vms_and_templates, :dependent => :nullify
has_many :vms
has_many :miq_templates
has_and_belongs_to_many :storages
has_many :switches, :dependent => :destroy
has_many :patches, :dependent => :destroy
has_many :system_services, :dependent => :destroy
has_many :host_services, :class_name => "SystemService", :foreign_key => "host_id"
has_many :metrics, :as => :resource # Destroy will be handled by purger
has_many :metric_rollups, :as => :resource # Destroy will be handled by purger
has_many :vim_performance_states, :as => :resource # Destroy will be handled by purger
has_many :ems_events, -> { where("host_id = ? OR dest_host_id = ?", id, id).order(:timestamp) }, :class_name => "EmsEvent"
has_many :ems_events_src, :class_name => "EmsEvent"
has_many :ems_events_dest, :class_name => "EmsEvent", :foreign_key => :dest_host_id
has_many :policy_events, -> { order("timestamp") }
has_many :guest_applications, :dependent => :destroy
has_many :filesystems, :as => :resource, :dependent => :destroy
has_many :directories, -> { where("rsc_type = 'dir'") }, :as => :resource, :class_name => "Filesystem"
has_many :files, -> { where("rsc_type = 'file'") }, :as => :resource, :class_name => "Filesystem"
# Accounts - Users and Groups
has_many :accounts, :dependent => :destroy
has_many :users, -> { where("accttype = 'user'") }, :class_name => "Account", :foreign_key => "host_id"
has_many :groups, -> { where("accttype = 'group'") }, :class_name => "Account", :foreign_key => "host_id"
has_many :advanced_settings, :as => :resource, :dependent => :destroy
has_many :miq_alert_statuses, :dependent => :destroy, :as => :resource
has_one :miq_cim_instance, :as => :vmdb_obj, :dependent => :destroy
has_many :host_service_groups, :dependent => :destroy
serialize :settings
# TODO: Remove all callers of address
alias_attribute :address, :hostname
def settings
super || self.settings = VMDB::Config.new("hostdefaults").get(:host)
end
include SerializedEmsRefObjMixin
include ProviderObjectMixin
include WebServiceAttributeMixin
include EventMixin
include CustomAttributeMixin
has_many :ems_custom_attributes, -> { where("source = 'VC'") }, :as => :resource, :dependent => :destroy, :class_name => "CustomAttribute"
acts_as_miq_taggable
include ReportableMixin
virtual_column :os_image_name, :type => :string, :uses => [:operating_system, :hardware]
virtual_column :platform, :type => :string, :uses => [:operating_system, :hardware]
virtual_column :v_owning_cluster, :type => :string, :uses => :ems_cluster
virtual_column :v_owning_datacenter, :type => :string, :uses => :all_relationships
virtual_column :v_owning_folder, :type => :string, :uses => :all_relationships
virtual_column :v_total_storages, :type => :integer, :uses => :storages
virtual_column :v_total_vms, :type => :integer, :uses => :vms
virtual_column :v_total_miq_templates, :type => :integer, :uses => :miq_templates
virtual_column :total_vcpus, :type => :integer, :uses => :logical_cpus
virtual_column :num_cpu, :type => :integer, :uses => :hardware
virtual_column :logical_cpus, :type => :integer, :uses => :hardware
virtual_column :cores_per_socket, :type => :integer, :uses => :hardware
virtual_column :ram_size, :type => :integer
virtual_column :enabled_inbound_ports, :type => :numeric_set # The following are not set to use anything
virtual_column :enabled_outbound_ports, :type => :numeric_set # because get_ports ends up re-querying the
virtual_column :enabled_udp_inbound_ports, :type => :numeric_set # database anyway.
virtual_column :enabled_udp_outbound_ports, :type => :numeric_set
virtual_column :enabled_tcp_inbound_ports, :type => :numeric_set
virtual_column :enabled_tcp_outbound_ports, :type => :numeric_set
virtual_column :all_enabled_ports, :type => :numeric_set
virtual_column :service_names, :type => :string_set, :uses => :system_services
virtual_column :enabled_run_level_0_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_1_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_2_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_3_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_4_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_5_services, :type => :string_set, :uses => :host_services
virtual_column :enabled_run_level_6_services, :type => :string_set, :uses => :host_services
virtual_column :last_scan_on, :type => :time, :uses => :last_drift_state_timestamp
virtual_column :v_annotation, :type => :string, :uses => :hardware
virtual_column :ipmi_enabled, :type => :boolean
virtual_has_many :resource_pools, :uses => :all_relationships
virtual_has_many :lans, :uses => {:switches => :lans}
virtual_has_many :miq_scsi_luns, :uses => {:hardware => {:storage_adapters => {:miq_scsi_targets => :miq_scsi_luns}}}
virtual_has_many :processes, :class_name => "OsProcess", :uses => {:operating_system => :processes}
virtual_has_many :event_logs, :uses => {:operating_system => :event_logs}
virtual_has_many :firewall_rules, :uses => {:operating_system => :firewall_rules}
virtual_has_many :base_storage_extents, :class_name => "CimStorageExtent"
virtual_has_many :storage_systems, :class_name => "CimComputerSystem"
virtual_has_many :file_shares, :class_name => 'SniaFileShare'
virtual_has_many :storage_volumes, :class_name => 'CimStorageVolume'
virtual_has_many :logical_disks, :class_name => 'CimLogicalDisk'
alias datastores storages # Used by web-services to return datastores as the property name
alias parent_cluster ems_cluster
alias owning_cluster ems_cluster
include RelationshipMixin
self.default_relationship_type = "ems_metadata"
include DriftStateMixin
alias last_scan_on last_drift_state_timestamp
include UuidMixin
include MiqPolicyMixin
include AlertMixin
include Metric::CiMixin
include FilterableMixin
include AuthenticationMixin
include AsyncDeleteMixin
include ComplianceMixin
include VimConnectMixin
before_create :make_smart
after_save :process_events
def authentication_check_role
'smartstate'
end
def to_s
name
end
def v_annotation
hardware.try(:annotation)
end
# host settings
def autoscan
settings[:autoscan]
end
def autoscan=(switch)
settings[:autoscan] = switch
end
def inherit_mgt_tags
settings[:inherit_mgt_tags]
end
def inherit_mgt_tags=(switch)
settings[:inherit_mgt_tags] = switch
end
def scan_frequency
settings[:scan_frequency]
end
def scan_frequency=(switch)
settings[:scan_frequency] = switch
end
# end host settings
def my_zone
ems = ext_management_system
ems ? ems.my_zone : MiqServer.my_zone
end
def make_smart
self.smart = true
end
def process_events
return unless ems_cluster_id_changed?
raise_cluster_event(ems_cluster_id_was, "host_remove_from_cluster") if ems_cluster_id_was
raise_cluster_event(ems_cluster, "host_add_to_cluster") if ems_cluster_id
end # after_save
def raise_cluster_event(ems_cluster, event)
# accept ids or objects
ems_cluster = EmsCluster.find(ems_cluster) unless ems_cluster.kind_of? EmsCluster
inputs = {:ems_cluster => ems_cluster, :host => self}
begin
MiqEvent.raise_evm_event(self, event, inputs)
_log.info("Raised EVM Event: [#{event}, host: #{name}(#{id}), cluster: #{ems_cluster.name}(#{ems_cluster.id})]")
rescue => err
_log.warn("Error raising EVM Event: [#{event}, host: #{name}(#{id}), cluster: #{ems_cluster.name}(#{ems_cluster.id})], '#{err.message}'")
end
end
private :raise_cluster_event
# is_available?
# Returns: true or false
#
# The UI calls this method to determine if a feature is supported for this Host
# and determines if a button should be displayed. This method should return true
# even if a function is not 'currently' available due to some condition that is not
# being met.
def is_available?(request_type)
send("validate_#{request_type}")[:available]
end
# is_available_now_error_message
# Returns an error message string if there is an error.
# Returns nil to indicate no errors.
# This method is used by the UI along with the is_available? methods.
def is_available_now_error_message(request_type)
send("validate_#{request_type}")[:message]
end
def raise_is_available_now_error_message(request_type)
msg = send("validate_#{request_type}")[:message]
raise MiqException::MiqVmError, msg unless msg.nil?
end
def validate_reboot
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_shutdown
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_standby
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_enter_maint_mode
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_exit_maint_mode
validate_esx_host_connected_to_vc_with_power_state('maintenance')
end
def validate_enable_vmotion
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_disable_vmotion
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_vmotion_enabled?
validate_esx_host_connected_to_vc_with_power_state('on')
end
def validate_start
validate_ipmi('off')
end
def validate_stop
validate_ipmi('on')
end
def validate_reset
validate_ipmi
end
def validate_ipmi(pstate = nil)
return {:available => false, :message => "The Host is not configured for IPMI"} if ipmi_address.blank?
return {:available => false, :message => "The Host has no IPMI credentials"} if authentication_type(:ipmi).nil?
return {:available => false, :message => "The Host has invalid IPMI credentials"} if authentication_userid(:ipmi).blank? || authentication_password(:ipmi).blank?
msg = validate_power_state(pstate)
return msg unless msg.nil?
{:available => true, :message => nil }
end
def validate_esx_host_connected_to_vc_with_power_state(pstate)
msg = validate_esx_host_connected_to_vc
return msg unless msg.nil?
msg = validate_power_state(pstate)
return msg unless msg.nil?
{:available => true, :message => nil }
end
def validate_power_state(pstate)
return nil if pstate.nil?
case pstate.class.name
when 'String'
return {:available => false, :message => "The Host is not powered '#{pstate}'"} unless power_state == pstate
when 'Array'
return {:available => false, :message => "The Host is not powered #{pstate.inspect}"} unless pstate.include?(power_state)
end
end
def validate_esx_host_connected_to_vc
# Check the basic require to interact with a VM.
return {:available => false, :message => "The Host is not connected to an active #{ui_lookup(:table => "ext_management_systems")}"} unless has_active_ems?
return {:available => false, :message => "The Host is not VMware ESX"} unless is_vmware_esx?
nil
end
def has_active_ems?
!!ext_management_system
end
def run_ipmi_command(verb)
require 'miq-ipmi'
_log.info("Invoking [#{verb}] for Host: [#{name}], IPMI Address: [#{ipmi_address}], IPMI Username: [#{authentication_userid(:ipmi)}]")
ipmi = MiqIPMI.new(ipmi_address, *auth_user_pwd(:ipmi))
ipmi.send(verb)
end
def policy_prevented?(request)
MiqEvent.raise_evm_event(self, request, {:host => self})
rescue MiqException::PolicyPreventAction => err
_log.info "#{err}"
true
else
false
end
def ipmi_power_on
run_ipmi_command :power_on
end
def ipmi_power_off
run_ipmi_command :power_off
end
def ipmi_power_reset
run_ipmi_command :power_reset
end
def reset
msg = validate_reset
if msg[:available]
ipmi_power_reset unless policy_prevented?("request_host_reset")
else
_log.warn("Cannot stop because <#{msg[:message]}>")
end
end
def start
if validate_start[:available] && power_state == 'standby' && respond_to?(:vim_power_up_from_standby)
vim_power_up_from_standby unless policy_prevented?("request_host_start")
else
msg = validate_ipmi
if msg[:available]
pstate = run_ipmi_command(:power_state)
if pstate == 'off'
ipmi_power_on unless policy_prevented?("request_host_start")
else
_log.warn("Non-Startable IPMI power state = <#{pstate.inspect}>")
end
else
_log.warn("Cannot start because <#{msg[:message]}>")
end
end
end
def stop
msg = validate_stop
if msg[:available]
ipmi_power_off unless policy_prevented?("request_host_stop")
else
_log.warn("Cannot stop because <#{msg[:message]}>")
end
end
def standby
msg = validate_standby
if msg[:available]
if power_state == 'on' && respond_to?(:vim_power_down_to_standby)
vim_power_down_to_standby unless policy_prevented?("request_host_standby")
else
_log.warn("Cannot go into standby mode from power state = <#{power_state.inspect}>")
end
else
_log.warn("Cannot go into standby mode because <#{msg[:message]}>")
end
end
def enter_maint_mode
msg = validate_enter_maint_mode
if msg[:available]
if power_state == 'on' && respond_to?(:vim_enter_maintenance_mode)
vim_enter_maintenance_mode unless policy_prevented?("request_host_enter_maintenance_mode")
else
_log.warn("Cannot enter maintenance mode from power state = <#{power_state.inspect}>")
end
else
_log.warn("Cannot enter maintenance mode because <#{msg[:message]}>")
end
end
def exit_maint_mode
msg = validate_enter_maint_mode
if msg[:available] && respond_to?(:vim_exit_maintenance_mode)
vim_exit_maintenance_mode unless policy_prevented?("request_host_exit_maintenance_mode")
else
_log.warn("Cannot exit maintenance mode because <#{msg[:message]}>")
end
end
def shutdown
msg = validate_shutdown
if msg[:available] && respond_to?(:vim_shutdown)
vim_shutdown unless policy_prevented?("request_host_shutdown")
else
_log.warn("Cannot shutdown because <#{msg[:message]}>")
end
end
def reboot
msg = validate_reboot
if msg[:available] && respond_to?(:vim_reboot)
vim_reboot unless policy_prevented?("request_host_reboot")
else
_log.warn("Cannot reboot because <#{msg[:message]}>")
end
end
def enable_vmotion
msg = validate_enable_vmotion
if msg[:available] && respond_to?(:vim_enable_vmotion)
vim_enable_vmotion unless policy_prevented?("request_host_enable_vmotion")
else
_log.warn("Cannot enable vmotion because <#{msg[:message]}>")
end
end
def disable_vmotion
msg = validate_disable_vmotion
if msg[:available] && respond_to?(:vim_disable_vmotion)
vim_disable_vmotion unless policy_prevented?("request_host_disable_vmotion")
else
_log.warn("Cannot disable vmotion because <#{msg[:message]}>")
end
end
def vmotion_enabled?
msg = validate_vmotion_enabled?
if msg[:available] && respond_to?(:vim_vmotion_enabled?)
vim_vmotion_enabled? unless policy_prevented?("request_host_vmotion_enabled")
else
_log.warn("Cannot check if vmotion is enabled because <#{msg[:message]}>")
end
end
def resolve_hostname!
addr = MiqSockUtil.resolve_hostname(hostname)
update_attributes!(:ipaddress => addr) unless addr.nil?
end
# Scan for VMs in a path defined in a repository
def add_elements(data)
if data.kind_of?(Hash) && data[:type] == :ems_events
_log.info("Adding HASH elements for Host id:[#{id}]-[#{name}] from [#{data[:type]}]")
add_ems_events(data)
end
rescue => err
_log.log_backtrace(err)
end
def ipaddresses
hardware.nil? ? [] : hardware.ipaddresses
end
def hostnames
hardware.nil? ? [] : hardware.hostnames
end
def mac_addresses
hardware.nil? ? [] : hardware.mac_addresses
end
def has_config_data?
!operating_system.nil? && !hardware.nil?
end
def os_image_name
OperatingSystem.image_name(self)
end
def platform
OperatingSystem.platform(self)
end
def product_name
operating_system.nil? ? "" : operating_system.product_name
end
def service_pack
operating_system.nil? ? "" : operating_system.service_pack
end
def arch
if vmm_product.to_s.include?('ESX')
return 'x86_64' if vmm_version.to_i >= 4
return 'x86'
end
return "unknown" unless hardware && !hardware.cpu_type.nil?
cpu = hardware.cpu_type.to_s.downcase
return cpu if cpu.include?('x86')
return "x86" if cpu.starts_with? "intel"
"unknown"
end
def platform_arch
ret = [os_image_name.split("_")[0], arch == "unknown" ? "x86" : arch]
ret.include?("unknown") ? nil : ret
end
def acts_as_ems?
product = vmm_product.to_s.downcase
['hyperv', 'hyper-v'].any? { |p| product.include?(p) }
end
def refreshable_status
if ext_management_system
return {:show => true, :enabled => true, :message => ""}
end
{:show => false, :enabled => false, :message => "Host not configured for refresh"}
end
def scannable_status
s = refreshable_status
return s if s[:show] || s[:enabled]
s[:show] = true
if has_credentials?(:ipmi) && ipmi_address.present?
s.merge!(:enabled => true, :message => "")
elsif ipmi_address.blank?
s.merge!(:enabled => false, :message => "Provide an IPMI Address")
elsif missing_credentials?(:ipmi)
s.merge!(:enabled => false, :message => "Provide credentials for IPMI")
end
s
end
def is_refreshable?
refreshable_status[:show]
end
def is_refreshable_now?
refreshable_status[:enabled]
end
def is_refreshable_now_error_message
refreshable_status[:message]
end
def self.refresh_ems(host_ids)
host_ids = [host_ids] unless host_ids.kind_of?(Array)
host_ids = host_ids.collect { |id| [Host, id] }
EmsRefresh.queue_refresh(host_ids)
end
def refresh_ems
raise "No #{ui_lookup(:table => "ext_management_systems")} defined" unless ext_management_system
raise "No #{ui_lookup(:table => "ext_management_systems")} credentials defined" unless ext_management_system.has_credentials?
raise "#{ui_lookup(:table => "ext_management_systems")} failed last authentication check" unless ext_management_system.authentication_status_ok?
EmsRefresh.queue_refresh(self)
end
def is_scannable?
scannable_status[:show]
end
def is_scannable_now?
scannable_status[:enabled]
end
def is_scannable_now_error_message
scannable_status[:message]
end
def is_vmware?
vmm_vendor.to_s.strip.downcase == 'vmware'
end
def is_vmware_esx?
is_vmware? && vmm_product.to_s.strip.downcase.starts_with?('esx')
end
def is_vmware_esxi?
product = vmm_product.to_s.strip.downcase
is_vmware? && product.starts_with?('esx') && product.ends_with?('i')
end
def state
power_state
end
def state=(new_state)
return if power_state == new_state
# state_changed_on = Time.now.utc
# previous_state = power_state
self.power_state = new_state
end
def self.lookUpHost(hostname, ipaddr)
h = Host.where("lower(hostname) = ?", hostname.downcase).where(:ipaddress => ipaddr).first if hostname && ipaddr
h ||= Host.where("lower(hostname) = ?", hostname.downcase).first if hostname
h ||= Host.where(:ipaddress => ipaddr).first if ipaddr
h ||= Host.where("lower(hostname) LIKE ?", "#{hostname.downcase}.%").first if hostname
h
end
def vmm_vendor
VENDOR_TYPES[read_attribute(:vmm_vendor)]
end
def vmm_vendor=(v)
v = VENDOR_TYPES.key(v) if VENDOR_TYPES.value?(v)
v = nil unless VENDOR_TYPES.key?(v)
self[:vmm_vendor] = v
end
#
# Relationship methods
#
def disconnect_inv
disconnect_ems
remove_all_parents(:of_type => ['EmsFolder', 'EmsCluster'])
end
def connect_ems(e)
return if ext_management_system == e
_log.debug "Connecting Host [#{name}] id [#{id}] to EMS [#{e.name}] id [#{e.id}]"
self.ext_management_system = e
save
end
def disconnect_ems(e=nil)
if e.nil? || self.ext_management_system == e
log_text = " from EMS [#{ext_management_system.name}] id [#{ext_management_system.id}]" unless ext_management_system.nil?
_log.info "Disconnecting Host [#{name}] id [#{id}]#{log_text}"
self.ext_management_system = nil
self.state = "unknown"
save
end
end
def connect_storage(s)
unless storages.include?(s)
_log.debug "Connecting Host [#{name}] id [#{id}] to Storage [#{s.name}] id [#{s.id}]"
storages << s
save
end
end
def disconnect_storage(s)
_log.info "Disconnecting Host [#{name}] id [#{id}] from Storage [#{s.name}] id [#{s.id}]"
storages.delete(s)
save
end
# Vm relationship methods
def direct_vms
# Look for only the Vms at the second depth (default RP + 1)
rels = descendant_rels(:of_type => 'Vm').select { |r| (r.depth - depth) == 2 }
Relationship.resources(rels).sort_by { |r| r.name.downcase }
end
# Resource Pool relationship methods
def default_resource_pool
Relationship.resource(child_rels(:of_type => 'ResourcePool').first)
end
def resource_pools
# Look for only the resource_pools at the second depth (default depth + 1)
rels = descendant_rels(:of_type => 'ResourcePool')
min_depth = rels.collect(&:depth).min
rels = rels.select { |r| r.depth == min_depth + 1 }
Relationship.resources(rels).sort_by { |r| r.name.downcase }
end
def resource_pools_with_default
# Look for only the resource_pools up to the second depth (default depth + 1)
rels = descendant_rels(:of_type => 'ResourcePool')
min_depth = rels.collect(&:depth).min
rels = rels.select { |r| r.depth <= min_depth + 1 }
Relationship.resources(rels).sort_by { |r| r.name.downcase }
end
# All RPs under this Host and all child RPs
def all_resource_pools
descendants(:of_type => 'ResourcePool')[1..-1].sort_by { |r| r.name.downcase }
end
def all_resource_pools_with_default
descendants(:of_type => 'ResourcePool').sort_by { |r| r.name.downcase }
end
# Parent relationship methods
def parent_folder
p = parent
p.kind_of?(EmsFolder) ? p : nil
end
def owning_folder
detect_ancestor(:of_type => "EmsFolder") { |a| !a.is_datacenter && !["host", "vm"].include?(a.name) }
end
def parent_datacenter
detect_ancestor(:of_type => "EmsFolder") { |a| a.is_datacenter }
end
alias owning_datacenter parent_datacenter
def lans
all_lans = []
switches.each { |s| all_lans += s.lans unless s.lans.nil? } unless switches.nil?
all_lans
end
def self.save_metadata(id, dataArray)
begin
_log.info "for host [#{id}]"
host = Host.find_by_id(id)
data, data_type = dataArray
if data_type.include?('yaml')
data.replace(MIQEncode.decode(data)) if data_type.include?('b64,zlib')
doc = YAML.load(data)
else
data.replace(MIQEncode.decode(data)) if data_type.include?('b64,zlib')
doc = MiqXml.load(data)
end
host.add_elements(doc)
host.save!
_log.info "for host [#{id}] host saved"
rescue => err
_log.log_backtrace(err)
return false
end
end
def self.rss_settings_changes(name, options)
find_by_audit_for_rss("agent_settings_change", options)
end
def self.rss_version_changes(name, options)
find_by_audit_for_rss("agent_version_activate", options)
end
def self.find_by_audit_for_rss(event_name, options = {})
result = []
AuditEvent.where(:target_class => 'Host', :event => event_name).
order(options[:orderby]).
limit(options[:limit_to_count]).
each do |event|
if options[:tags] && options[:tags_include]
any_or_all = options[:tags_include].to_sym
host = Host.find_tagged_with(
any_or_all => options[:tags],
:ns => options[:tag_ns]
).where(:id => event.target_id).first
else
host = Host.find(event.target_id)
end
result.push(OpenStruct.new(host.attributes.merge(event.attributes))) unless host.nil?
end
result
end
def self.multi_host_update(host_ids, attr_hash = {}, creds = {})
errors = []
return true if host_ids.blank?
host_ids.each do |id|
begin
host = Host.find(id)
host.update_authentication(creds)
host.update_attributes!(attr_hash)
rescue ActiveRecord::RecordNotFound => err
_log.warn("#{err.class.name}-#{err}")
next
rescue => err
errors << err.to_s
_log.error("#{err.class.name}-#{err}")
next
end
end
return errors.empty? ? true : errors
end
def verify_credentials(auth_type=nil, options={})
raise MiqException::MiqHostError, "No credentials defined" if self.missing_credentials?(auth_type)
raise MiqException::MiqHostError, "Logon to platform [#{self.os_image_name}] not supported" if auth_type.to_s != 'ipmi' && self.os_image_name !~ /linux_*/
case auth_type.to_s
when 'remote' then verify_credentials_with_ssh(auth_type, options)
when 'ws' then verify_credentials_with_ws(auth_type)
when 'ipmi' then verify_credentials_with_ipmi(auth_type)
else
verify_credentials_with_ws(auth_type)
end
true
end
def verify_credentials_with_ws(_auth_type = nil, _options = {})
raise MiqException::MiqHostError, "Web Services authentication is not supported for hosts of this type."
end
def verify_credentials_with_ssh(auth_type=nil, options={})
raise MiqException::MiqHostError, "No credentials defined" if self.missing_credentials?(auth_type)
raise MiqException::MiqHostError, "Logon to platform [#{self.os_image_name}] not supported" unless self.os_image_name =~ /linux_*/
begin
# connect_ssh logs address and user name(s) being used to make connection
_log.info "Verifying Host SSH credentials for [#{name}]"
connect_ssh(options) {|ssu| ssu.exec("uname -a")}
rescue Net::SSH::AuthenticationFailed
raise MiqException::MiqInvalidCredentialsError, "Login failed due to a bad username or password."
rescue Net::SSH::HostKeyMismatch
raise # Re-raise the error so the UI can prompt the user to allow the keys to be reset.
rescue Exception => err
_log.warn("#{err.inspect}")
raise MiqException::MiqHostError, "Unexpected response returned from system, see log for details"
else
true
end
end
def verify_credentials_with_ipmi(auth_type=nil)
raise "No credentials defined for IPMI" if missing_credentials?(auth_type)
require 'miq-ipmi'
address = ipmi_address
raise MiqException::MiqHostError, "IPMI address is not configured for this Host" if address.blank?
if MiqIPMI.is_available?(address)
ipmi = MiqIPMI.new(address, *auth_user_pwd(auth_type))
raise MiqException::MiqInvalidCredentialsError, "Login failed due to a bad username or password." unless ipmi.connected?
else
raise MiqException::MiqHostError, "IPMI is not available on this Host"
end
end
def self.discoverByIpRange(starting, ending, options={:ping => true})
options[:timeout] ||= 10
pattern = %r{^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$}
raise "Starting address is malformed" if (starting =~ pattern).nil?
raise "Ending address is malformed" if (ending =~ pattern).nil?
starting.split(".").each_index {|i|
raise "IP address octets must be 0 to 255" if starting.split(".")[i].to_i > 255 || ending.split(".")[i].to_i > 255
raise "Ending address must be greater than starting address" if starting.split(".")[i].to_i > ending.split(".")[i].to_i
}
network_id = starting.split(".")[0..2].join(".")
host_start = starting.split(".").last.to_i
host_end = ending.split(".").last.to_i
host_start.upto(host_end) {|h|
ipaddr = network_id + "." + h.to_s
unless Host.find_by_ipaddress(ipaddr).nil? # skip discover for existing hosts
_log.info "ipaddress '#{ipaddr}' exists, skipping discovery"
next
end
discover_options = {:ipaddr => ipaddr,
:usePing => options[:ping],
:timeout => options[:timeout],
:discover_types => options[:discover_types],
:credentials => options[:credentials]
}
# Add Windows domain credentials for HyperV WMI checks
default_zone = Zone.find_by_name('default')
if !default_zone.nil? && default_zone.has_authentication_type?(:windows_domain)
discover_options[:windows_domain] = [default_zone.authentication_userid(:windows_domain), default_zone.authentication_password_encrypted(:windows_domain)]
end
MiqQueue.put(:class_name => "Host", :method_name => "discoverHost", :data => Marshal.dump(discover_options), :server_guid => MiqServer.my_guid)
}
end
def reset_discoverable_fields
raise "Host Not Resettable - No IPMI Address" if ipmi_address.blank?
cred = self.authentication_type(:ipmi)
raise "Host Not Resettable - No IPMI Credentials" if cred.nil?
run_callbacks(:destroy) { false } # Run only the before_destroy callbacks to destroy all associations
reload
attributes.each do |key, value|
next if %w{id guid ipmi_address mac_address name created_on updated_on vmm_vendor}.include?(key)
send("#{key}=", nil)
end
make_smart # before_create callback
self.settings = VMDB::Config.new("hostdefaults").get(:host)
self.name = "IPMI <#{ipmi_address}>"
self.vmm_vendor = 'unknown'
save!
authentications.create(cred.attributes) unless cred.nil?
self
end
def detect_discovered_os(ost)
# Determine os
os_type = nil
if vmm_vendor == "vmware"
os_name = "VMware ESX Server"
elsif ost.os.include?(:linux)
os_name = "linux"
elsif ost.os.include?(:mswin)
os_name = "windows"
os_type = os_name
else
os_name = nil
end
return os_name, os_type
end
def detect_discovered_hypervisor(ost, ipaddr)
find_method = :find_by_ipaddress
if ost.hypervisor.include?(:hyperv)
self.name = "Microsoft Hyper-V (#{ipaddr})"
self.type = "HostMicrosoft"
self.ipaddress = ipaddr
self.vmm_vendor = "microsoft"
self.vmm_product = "Hyper-V"
elsif ost.hypervisor.include?(:esx)
self.name = "VMware ESX Server (#{ipaddr})"
self.ipaddress = ipaddr
self.vmm_vendor = "vmware"
self.vmm_product = "Esx"
if has_credentials?(:ws)
begin
with_provider_connection(:ip => ipaddr) do |vim|
_log.info "VIM Information for ESX Host with IP Address: [#{ipaddr}], Information: #{vim.about.inspect}"
self.vmm_product = vim.about['name'].dup.split(' ').last
self.vmm_version = vim.about['version']
self.vmm_buildnumber = vim.about['build']
self.name = "#{vim.about['name']} (#{ipaddr})"
end
rescue => err
_log.warn "Cannot connect to ESX Host with IP Address: [#{ipaddr}], Username: [#{authentication_userid(:ws)}] because #{err.message}"
end
end
self.type = %w(esx esxi).include?(vmm_product.to_s.downcase) ? "ManageIQ::Providers::Vmware::InfraManager::HostEsx" : "ManageIQ::Providers::Vmware::InfraManager::Host"
elsif ost.hypervisor.include?(:ipmi)
find_method = :find_by_ipmi_address
self.name = "IPMI (#{ipaddr})"
self.type = "Host"