-
Notifications
You must be signed in to change notification settings - Fork 898
/
vm_or_template.rb
1722 lines (1426 loc) · 59.5 KB
/
vm_or_template.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 'ancestry'
require 'ostruct'
require 'cgi'
require 'uri'
class VmOrTemplate < ApplicationRecord
include NewWithTypeStiMixin
include RetirementMixin
include ScanningMixin
include SupportsFeatureMixin
include SupportsAttribute
include EmsRefreshMixin
self.table_name = 'vms'
has_ancestry
include Operations
include RetirementManagement
include RightSizing
include Scanning
include Snapshotting
attr_accessor :surrogate_host
@surrogate_host = nil
include ProviderObjectMixin
include ComplianceMixin
include OwnershipMixin
include CustomAttributeMixin
include EventMixin
include ProcessTasksMixin
include TenancyMixin
include ManageIQ::Providers::Inflector::Methods
VENDOR_TYPES = {
# DB Displayed
"azure" => "Azure",
"azure_stack" => "AzureStack",
"vmware" => "VMware",
"microsoft" => "Microsoft",
"xen" => "XenSource",
"parallels" => "Parallels",
"amazon" => "Amazon",
"redhat" => "Red Hat",
"ovirt" => "oVirt",
"openstack" => "OpenStack",
"openshift_infra" => "OpenShift Virtualization",
"oracle" => "Oracle",
"google" => "Google",
"kubevirt" => "KubeVirt",
"ibm_cloud" => "IBM Cloud",
"ibm_power_vs" => "IBM Power Systems Virtual Server",
"ibm_power_vc" => "IBM PowerVC",
"ibm_power_hmc" => "IBM Power HMC",
"ibm_z_vm" => "IBM Z/VM",
"unknown" => "Unknown"
}
POWER_OPS = %w[start stop suspend reset shutdown_guest standby_guest reboot_guest]
REMOTE_REGION_TASKS = POWER_OPS + %w[retire_now]
validates_presence_of :name, :location
validates :vendor, :inclusion => {:in => VENDOR_TYPES.keys}
has_one :operating_system, :dependent => :destroy
has_one :openscap_result, :as => :resource, :dependent => :destroy
has_one :hardware, :dependent => :destroy
has_one :miq_provision, :dependent => :nullify, :as => :destination
has_one :miq_provision_template, :through => "miq_provision", :source => "source", :source_type => "VmOrTemplate"
has_one :miq_server, :foreign_key => :vm_id, :inverse_of => :vm
belongs_to :host
belongs_to :ems_cluster
belongs_to :cloud_tenant
belongs_to :flavor
belongs_to :placement_group
belongs_to :storage
belongs_to :storage_profile
belongs_to :ext_management_system, :foreign_key => "ems_id", :inverse_of => :vms_and_templates
belongs_to :resource_group
belongs_to :tenant
# Accounts - Users and Groups
has_many :accounts, :dependent => :destroy
has_many :users, -> { where(:accttype => 'user') }, :class_name => "Account"
has_many :groups, -> { where(:accttype => 'group') }, :class_name => "Account"
has_many :disks, :through => :hardware
has_many :networks, :through => :hardware
has_many :nics, :through => :hardware
has_many :miq_provisions_from_template, :class_name => "MiqProvision", :as => :source, :dependent => :nullify
has_many :miq_provision_vms, :through => :miq_provisions_from_template, :source => :destination, :source_type => "VmOrTemplate"
has_many :miq_provision_requests, :as => :source
has_many :guest_applications, :dependent => :destroy
has_many :patches, :dependent => :destroy
# System Services - Win32_Services, Kernel drivers, Filesystem drivers
has_many :system_services, :dependent => :destroy
has_many :win32_services, -> { where("typename = 'win32_service'") }, :class_name => "SystemService"
has_many :kernel_drivers, -> { where("typename = 'kernel' OR typename = 'misc'") }, :class_name => "SystemService"
has_many :filesystem_drivers, -> { where("typename = 'filesystem'") }, :class_name => "SystemService"
has_many :linux_initprocesses, -> { where("typename = 'linux_initprocess' OR typename = 'linux_systemd'") }, :class_name => "SystemService"
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"
has_many :scan_histories, :dependent => :destroy
has_many :lifecycle_events, :class_name => "LifecycleEvent"
has_many :advanced_settings, :as => :resource, :dependent => :destroy
# Scan Items
has_many :registry_items, :dependent => :destroy
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 :storage_files, :dependent => :destroy
has_many :storage_files_files, -> { where("rsc_type = 'file'") }, :class_name => "StorageFile"
# EMS Events
has_many :ems_events, ->(vmt) { unscope(:where => :vm_or_template_id).where(["vm_or_template_id = ? OR dest_vm_or_template_id = ?", vmt.id, vmt.id]).order(:timestamp) },
:class_name => "EmsEvent", :inverse_of => :vm_or_template
has_many :ems_events_src, :class_name => "EmsEvent"
has_many :ems_events_dest, :class_name => "EmsEvent", :foreign_key => :dest_vm_or_template_id
has_many :policy_events, ->(vm) { where(["target_id = ? AND target_class = 'VmOrTemplate'", vm.id]).order(:timestamp) }, :foreign_key => "target_id"
has_many :miq_events, :as => :target, :dependent => :destroy
has_many :miq_alert_statuses, :dependent => :destroy, :as => :resource
has_many :service_resources, :as => :resource
has_many :direct_services, :through => :service_resources, :source => :service
has_many :connected_shares, -> { where(:resource_type => "VmOrTemplate") }, :foreign_key => :resource_id, :class_name => "Share"
has_many :labels, -> { where(:section => "labels") }, # rubocop:disable Rails/HasManyOrHasOneDependent
:class_name => "CustomAttribute",
:as => :resource,
:inverse_of => :resource
has_many :ems_custom_attributes, -> { where(:source => 'VC') }, # rubocop:disable Rails/HasManyOrHasOneDependent
:class_name => "CustomAttribute",
:as => :resource,
:inverse_of => :resource
has_many :counterparts, :as => :counterpart, :class_name => "ConfiguredSystem", :dependent => :nullify
has_and_belongs_to_many :storages, :join_table => 'storages_vms_and_templates'
acts_as_miq_taggable
virtual_column :is_evm_appliance, :type => :boolean, :uses => :miq_server
virtual_column :os_image_name, :type => :string, :uses => [:operating_system, :hardware]
virtual_column :platform, :type => :string, :uses => [:operating_system, :hardware]
virtual_column :product_name, :type => :string, :uses => [:operating_system]
virtual_column :vendor_display, :type => :string
virtual_column :v_owning_cluster, :type => :string, :uses => :ems_cluster
virtual_column :v_owning_resource_pool, :type => :string, :uses => :all_relationships
virtual_column :v_owning_datacenter, :type => :string, :uses => {:ems_cluster => :all_relationships}
virtual_column :v_owning_folder, :type => :string, :uses => {:ems_cluster => :all_relationships}
virtual_column :v_owning_folder_path, :type => :string, :uses => {:ems_cluster => :all_relationships}
virtual_column :v_owning_blue_folder, :type => :string, :uses => :all_relationships
virtual_column :v_owning_blue_folder_path, :type => :string, :uses => :all_relationships
virtual_column :v_datastore_path, :type => :string, :uses => :storage
virtual_column :v_parent_blue_folder_display_path, :type => :string, :uses => :all_relationships
virtual_column :thin_provisioned, :type => :boolean, :uses => {:hardware => :disks}
virtual_column :used_storage, :type => :integer, :uses => [:used_disk_storage, :mem_cpu]
virtual_column :used_storage_by_state, :type => :integer, :uses => :used_storage
virtual_column :uncommitted_storage, :type => :integer, :uses => [:provisioned_storage, :used_storage_by_state]
virtual_column :ipaddresses, :type => :string_set, :uses => {:hardware => :ipaddresses}
virtual_column :hostnames, :type => :string_set, :uses => {:hardware => :hostnames}
virtual_column :mac_addresses, :type => :string_set, :uses => {:hardware => :mac_addresses}
virtual_column :memory_exceeds_current_host_headroom, :type => :string, :uses => [:mem_cpu, {:host => [:hardware, :ext_management_system]}]
virtual_column :has_rdm_disk, :type => :boolean, :uses => {:hardware => :disks}
virtual_column :disks_aligned, :type => :string, :uses => {:hardware => {:hard_disks => :partitions_aligned}}
virtual_has_many :processes, :class_name => "OsProcess", :uses => {:operating_system => :processes}
virtual_has_many :event_logs, :uses => {:operating_system => :event_logs}
virtual_has_many :lans, :uses => {:hardware => {:nics => :lan}}
virtual_has_many :child_resources, :class_name => "VmOrTemplate"
virtual_belongs_to :parent_resource_pool, :class_name => "ResourcePool", :uses => :all_relationships
virtual_has_one :direct_service, :class_name => 'Service'
virtual_has_one :service, :class_name => 'Service'
virtual_has_one :parent_resource, :class_name => "VmOrTemplate"
virtual_delegate :name, :to => :host, :prefix => true, :allow_nil => true, :type => :string
virtual_delegate :name, :to => :storage, :prefix => true, :allow_nil => true, :type => :string
virtual_delegate :name, :to => :ems_cluster, :prefix => true, :allow_nil => true, :type => :string
virtual_delegate :vmm_product, :to => :host, :prefix => :v_host, :allow_nil => true, :type => :string
virtual_delegate :v_pct_free_disk_space, :v_pct_used_disk_space, :to => :hardware, :allow_nil => true, :type => :float
virtual_delegate :num_cpu, :to => "hardware.cpu_sockets", :allow_nil => true, :default => 0, :type => :integer
virtual_delegate :cpu_total_cores, :cpu_cores_per_socket, :to => :hardware, :allow_nil => true, :default => 0, :type => :integer
virtual_delegate :annotation, :to => :hardware, :prefix => "v", :allow_nil => true, :type => :string
virtual_delegate :ram_size_in_bytes, :to => :hardware, :allow_nil => true, :default => 0, :type => :integer
virtual_delegate :mem_cpu, :to => "hardware.memory_mb", :allow_nil => true, :default => 0, :type => :integer
virtual_delegate :ram_size, :to => "hardware.memory_mb", :allow_nil => true, :default => 0, :type => :integer
delegate :connect_lans, :disconnect_lans, :to => :hardware, :allow_nil => true
delegate :queue_name_for_ems_operations, :to => :ext_management_system, :allow_nil => true
supports_attribute :feature => :reconfigure_disks
supports_attribute :feature => :reconfigure_disksize
supports_attribute :feature => :reconfigure_cdroms
supports_attribute :feature => :reconfigure_network_adapters
after_save :save_genealogy_information
scope :active, -> { where.not(:ems_id => nil) }
scope :with_type, ->(type) { where(:type => type) }
scope :archived, -> { where(:ems_id => nil, :storage_id => nil) }
scope :orphaned, -> { where(:ems_id => nil).where.not(:storage_id => nil) }
scope :retired, -> { where(:retired => true) }
scope :not_active, -> { where(:ems_id => nil) }
scope :not_archived, -> { where.not(:ems_id => nil).or(where.not(:storage_id => nil)) }
scope :not_orphaned, -> { where.not(:ems_id => nil).or(where(:storage_id => nil)) }
scope :not_retired, -> { where(:retired => false).or(where(:retired => nil)) }
scope :from_cloud_managers, -> { where(:ext_management_system => ManageIQ::Providers::CloudManager.all) }
scope :from_infra_managers, -> { where(:ext_management_system => ManageIQ::Providers::InfraManager.all) }
def from_cloud_manager?
ext_management_system&.kind_of?(ManageIQ::Providers::CloudManager)
end
def from_infra_manager?
ext_management_system&.kind_of?(ManageIQ::Providers::InfraManager)
end
# The SQL form of `#registered?`, with its inverse as well.
# TODO: Vmware Specific (copied (old) TODO from #registered?)
scope :registered, (lambda do
where(arel_table[:template].eq(false).or(arel_table[:ems_id].not_eq(nil)).and(arel_table[:host_id].not_eq(nil)))
end)
scope :unregistered, (lambda do
where(arel_table[:template].eq(true).and(arel_table[:ems_id].eq(nil)).or(arel_table[:host_id].eq(nil)))
end)
alias_method :datastores, :storages # Used by web-services to return datastores as the property name
alias_method :parent_cluster, :ems_cluster
alias_method :owning_cluster, :ems_cluster
# Add virtual columns/methods for specific things derived from advanced_settings
REQUIRED_ADVANCED_SETTINGS = {
'vmi.present' => [:paravirtualization, :boolean],
'vmsafe.enable' => [:vmsafe_enable, :boolean],
'vmsafe.agentAddress' => [:vmsafe_agent_address, :string],
'vmsafe.agentPort' => [:vmsafe_agent_port, :integer],
'vmsafe.failOpen' => [:vmsafe_fail_open, :boolean],
'vmsafe.immutableVM' => [:vmsafe_immutable_vm, :boolean],
'vmsafe.timeoutMS' => [:vmsafe_timeout_ms, :integer],
'entitled_processors' => [:entitled_processors, :float],
'processor_type' => [:processor_share_type, :string],
'pin_policy' => [:processor_pin_policy, :string],
'software_licenses' => [:software_licenses, :string],
}
REQUIRED_ADVANCED_SETTINGS.each do |k, (m, t)|
define_method(m) do
as = advanced_settings.detect { |setting| setting.name == k }
return nil if as.nil? || as.value.nil?
case t
when :boolean then ActiveRecord::Type::Boolean.new.cast(as.value)
when :integer then as.value.to_i
when :float then as.value.to_f
else as.value.to_s
end
end
virtual_column m, :type => t, :uses => :advanced_settings
end
# Add virtual columns/methods for details about each disk
(1..9).each do |i|
disk_methods = [
['disk_type', :string],
['mode', :string],
['size', :integer],
['size_on_disk', :integer],
['used_percent_of_provisioned', :float],
['partitions_aligned', :string]
]
disk_methods.each do |k, t|
m = "disk_#{i}_#{k}".to_sym
define_method(m) do
return nil if hardware.nil?
return nil if hardware.hard_disks.length < i
hardware.hard_disks[i - 1].send(k)
end
virtual_column m, :type => t, :uses => {:hardware => :hard_disks}
end
end
# Add virtual columns/methods for accessing individual folders in a path
(1..9).each do |i|
m = "parent_blue_folder_#{i}_name".to_sym
define_method(m) do
f = parent_blue_folders(:exclude_root_folder => true, :exclude_non_display_folders => true)[i - 1]
f.nil? ? "" : f.name
end
virtual_column m, :type => :string, :uses => :all_relationships
end
include RelationshipMixin
self.default_relationship_type = "genealogy"
self.skip_relationships += ["genealogy"]
include MiqPolicyMixin
include AlertMixin
include DriftStateMixin
include UuidMixin
include Metric::CiMixin
include FilterableMixin
include StorageMixin
def self.manager_class
if module_parent == Object
ExtManagementSystem
else
module_parent
end
end
def self.model_suffix
manager_class.short_token
end
def to_s
name
end
def is_evm_appliance?
!!miq_server
end
alias_method :is_evm_appliance, :is_evm_appliance?
# Determines if the VM is on an EMS or Host
def registered?
# TODO: Vmware specific
return false if template? && ems_id.nil?
host_id.present?
end
# TODO: Vmware specific, and is this even being used anywhere?
def connected_to_ems?
connection_state == 'connected' || connection_state.nil?
end
def terminated?
current_state == 'terminated'
end
def makesmart(_options = {})
self.smart = true
save
end
def run_command_via_parent(verb, options = {})
unless ext_management_system
raise _("VM/Template <%{name}> with Id: <%{id}> is not associated with a provider.") % {:name => name, :id => id}
end
unless ext_management_system.authentication_status_ok?
raise _("VM/Template <%{name}> with Id: <%{id}>: Provider authentication failed.") % {:name => name, :id => id}
end
# TODO: Need to break this logic out into a method that can look at the verb and the vm and decide the best way to invoke it - Virtual Center WS, ESX WS, Storage Proxy.
_log.info("Invoking [#{verb}] through EMS: [#{ext_management_system.name}]")
options = {:user_event => "Console Request Action [#{verb}], VM [#{name}]"}.merge(options)
ext_management_system.send(verb, self, options)
end
def run_command_via_task(task_options, queue_options)
MiqTask.generic_action_with_callback(task_options, command_queue_options(queue_options))
end
def run_command_via_queue(method_name, queue_options = {})
queue_options[:method_name] = method_name
MiqQueue.put(command_queue_options(queue_options))
end
def make_retire_request(requester_id)
self.class.make_retire_request(id, User.find(requester_id))
end
# keep the same method signature as others in retirement mixin
def self.make_retire_request(*src_ids, requester, initiated_by: 'user')
vms = where(:id => src_ids)
missing_ids = src_ids - vms.pluck(:id)
_log.error("Retirement of [Vm] IDs: [#{missing_ids.join(', ')}] skipped - target(s) does not exist") if missing_ids.present?
vms.each do |target|
target.check_policy_prevent('request_vm_retire', "retire_request_after_policy_check", requester.userid, :initiated_by => initiated_by)
end
end
def retire_request_after_policy_check(userid, initiated_by: 'user')
options = {:src_ids => [id], :__initiated_by__ => initiated_by, :__request_type__ => VmRetireRequest.request_types.first}
requester = User.find_by(:userid => userid)
self.class.set_retirement_requester(options[:src_ids], requester)
VmRetireRequest.make_request(nil, options, requester)
end
# policy_event: the event sent to automate for policy resolution
# cb_method: the MiqQueue callback method along with the parameters that is called
# when automate process is done and the event is not prevented to proceed by policy
def check_policy_prevent(policy_event, *cb_method)
enforce_policy(policy_event, {}, {:miq_callback => prevent_callback_settings(*cb_method)}) unless policy_event.nil?
end
def enforce_policy(event, inputs = {}, options = {})
return {"result" => true, :details => []} if event.to_s == "rsop" && host.nil?
raise _("vm does not belong to any host") if host.nil? && ext_management_system.nil?
inputs[:vm] = self
inputs[:host] = host unless host.nil?
inputs[:ext_management_system] = ext_management_system unless ext_management_system.nil?
MiqEvent.raise_evm_event(self, event, inputs, options)
end
# override
def self.validate_task(task, vm, options)
return false unless super
return false if options[:task] == "destroy" || options[:task] == "check_compliance_queue"
return false if vm.has_required_host?
# VM has no host or storage affiliation
if vm.storage.nil?
task.error("#{vm.name}: There is no owning Host or Datastore for this VM, " \
"'#{options[:task]}' is not allowed")
return false
end
# VM belongs to a storage/repository location
# TODO: The following never gets run since the invoke tasks invokes it as a job, and only tasks get to this point ?
unless %w[scan sync].include?(options[:task])
task.error("#{vm.name}: There is no owning Host for this VM, '#{options[:task]}' is not allowed")
return false
end
spid = ::Settings.repository_scanning.defaultsmartproxy
if spid.nil? # No repo scanning SmartProxy configured
task.error("#{vm.name}: No Default Repository SmartProxy is configured, contact your EVM administrator")
return false
elsif MiqProxy.exists?(spid) == false
task.error("#{vm.name}: The Default Repository SmartProxy no longer exists, contact your EVM Administrator")
return false
end
if MiqProxy.find(spid).state != "on" # Repo scanning host iagent s not running
task.error("#{vm.name}: The Default Repository SmartProxy, '#{sp.name}', is not running. " \
"'#{options[:task]}' not attempted")
return false
end
true
end
private_class_method :validate_task
# override
def self.task_invoked_by(options)
%w[scan sync].include?(options[:task]) ? :job : super
end
private_class_method :task_invoked_by
# override
def self.task_arguments(options)
case options[:task]
when "scan", "sync"
[options[:userid]]
when "remove_snapshot", "revert_to_snapshot"
[options[:snap_selected]]
when "create_snapshot"
[options[:name], options[:description], options[:memory]]
else
super
end
end
private_class_method :task_arguments
def powerops_callback(task_id, status, msg, result, _queue_item)
task = MiqTask.find_by(:id => task_id)
task.queue_callback("Finished", status, msg, result) if task
end
# override
def self.invoke_task_local(task, vm, options, args)
user = User.current_user
cb = nil
if task
cb =
if POWER_OPS.include?(options[:task])
{
:class_name => vm.class.base_class.name,
:instance_id => vm.id,
:method_name => :powerops_callback,
:args => [task.id]
}
else
{
:class_name => task.class.to_s,
:instance_id => task.id,
:method_name => :queue_callback,
:args => ["Finished"]
}
end
end
q_hash =
if options[:task] == "destroy"
{
:class_name => base_class.name,
:instance_id => vm.id,
:method_name => options[:task],
:args => args,
:miq_task_id => task&.id,
:miq_callback => cb,
}
else
{
:service => options[:invoke_by] == :job ? "smartstate" : "ems_operations",
:affinity => vm.ext_management_system,
:class_name => base_class.name,
:instance_id => vm.id,
:method_name => options[:task],
:args => args,
:miq_task_id => task&.id,
:miq_callback => cb,
}
end
q_hash.merge!(:user_id => user.id, :group_id => user.current_group.id, :tenant_id => user.current_tenant.id) if user
MiqQueue.submit_job(q_hash)
end
def self.action_for_task(task)
case task
when "retire_now"
"retire"
else
task
end
end
def scan_data_current?
!(last_scan_on.nil? || last_scan_on > last_sync_on)
end
def genealogy_parent
with_relationship_type("genealogy") { parent }
end
def genealogy_parent=(parent)
with_relationship_type('genealogy') do
if use_ancestry?
self.parent = parent
else
@genealogy_parent_object = parent
end
end
end
# save_genealogy_information is only necessary for relationships using genealogy
# when using ancestry, the relationship will be saved after the fact
# when not using ancestry, the relationship is saved on assignment, necessitating the prior save of the vm/template record
# this variable is used to delay that assignment
def save_genealogy_information
if defined?(@genealogy_parent_object) && @genealogy_parent_object
with_relationship_type('genealogy') { self.parent = @genealogy_parent_object }
end
end
def os_image_name
name = OperatingSystem.image_name(self)
if name == 'unknown'
parent = genealogy_parent
name = OperatingSystem.image_name(parent) unless parent.nil?
end
name
end
def platform
name = OperatingSystem.platform(self)
if name == 'unknown'
parent = genealogy_parent
name = OperatingSystem.platform(parent) unless parent.nil?
end
name
end
def product_name
name = try(:operating_system).try(:product_name)
name ||= genealogy_parent.try(:operating_system).try(:product_name)
name ||= ""
name
end
def service_pack
name = try(:operating_system).try(:service_pack)
name ||= genealogy_parent.try(:operating_system).try(:service_pack)
name ||= ""
name
end
def vendor_display
VENDOR_TYPES[vendor]
end
#
# Path/location methods
#
# TODO: Vmware specific URI methods? Next 3 methods
def self.location2uri(location, scheme = "file")
pat = %r{^(file|http|miq)://([^/]*)/(.+)$}
unless pat&.match?(location)
# location = scheme<<"://"<<self.myhost.ipaddress<<":1139/"<<location
location = scheme << ":///" << location
end
location
end
def save_scan_history(datahash)
result = scan_histories.build(
:status => datahash['status'],
:status_code => datahash['status_code'].to_i,
:message => datahash['message'],
:started_on => Time.parse(datahash['start_time']),
:finished_on => Time.parse(datahash['end_time']),
:task_id => datahash['taskid']
)
self.last_scan_on = Time.parse(datahash['start_time'])
save
result
end
def self.repository_parse_path(path)
path.tr!("\\", "/")
# it's empty string for local type
storage_name = ""
# NAS
relative_path = if path.starts_with?("//")
raise _("path, '%{path}', is malformed") % {:path => path} unless %r{^//[^/].*/.+$}.match?(path)
# path is a UNC
storage_name = path.split("/")[0..3].join("/")
path.split("/")[4..path.length].join("/") if path.length > 4
# VMFS
elsif path.starts_with?("[")
raise _("path, '%{path}', is malformed") % {:path => path} unless /^\[[^\]].+\].*$/.match?(path)
# path is a VMWare storage name
/^\[(.*)\](.*)$/ =~ path
storage_name = $1
temp_path = $2.strip
# Some esx servers add a leading "/".
# This needs to be stripped off to allow matching on location
temp_path.sub(/^\//, '')
# local
else
raise _("path, '%{path}', is malformed") % {:path => path}
end
return storage_name, (relative_path.empty? ? "/" : relative_path)
end
#
# Relationship methods
#
def disconnect_inv
disconnect_storage
disconnect_ems
classify_with_parent_folder_path(false)
with_relationship_type('ems_metadata') do
remove_all_parents(:of_type => ['EmsFolder', 'ResourcePool'])
end
disconnect_host
disconnect_stack if respond_to?(:orchestration_stack)
end
def disconnect_stack(stack = nil)
return unless orchestration_stack
return if stack && stack != orchestration_stack
log_text = " from stack [#{orchestration_stack.name}] id [#{orchestration_stack.id}]"
_log.info("Disconnecting Vm [#{name}] id [#{id}]#{log_text}")
self.orchestration_stack = nil
save
end
def connect_ems(e)
unless ext_management_system == e
_log.debug("Connecting Vm [#{name}] id [#{id}] to EMS [#{e.name}] id [#{e.id}]")
self.ext_management_system = e
save
end
end
def disconnect_ems(e = nil)
if e.nil? || 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 Vm [#{name}] id [#{id}]#{log_text}")
self.ext_management_system = nil
self.ems_cluster = nil
self.raw_power_state = "unknown"
save
end
end
def connect_host(h)
unless host == h
_log.debug("Connecting Vm [#{name}] id [#{id}] to Host [#{h.name}] id [#{h.id}]")
self.host = h
save
# Also connect any nics to their lans
connect_lans(h.lans)
end
end
def disconnect_host(h = nil)
if h.nil? || host == h
log_text = " from Host [#{host.name}] id [#{host.id}]" unless host.nil?
_log.info("Disconnecting Vm [#{name}] id [#{id}]#{log_text}")
self.host = nil
save
# Also disconnect any nics from their lans
disconnect_lans
end
end
def connect_storage(s)
unless storage == s
_log.debug("Connecting Vm [#{name}] id [#{id}] to Datastore [#{s.name}] id [#{s.id}]")
self.storage = s
save
end
end
def disconnect_storage(s = nil)
if s.nil? || storage == s || storages.include?(s)
stores = s.nil? ? ([storage] + storages).compact.uniq : [s]
log_text = stores.collect { |x| "Datastore [#{x.name}] id [#{x.id}]" }.join(", ")
_log.info("Disconnecting Vm [#{name}] id [#{id}] from #{log_text}")
if s.nil?
self.storage = nil
self.storages = []
else
self.storage = nil if storage == s
storages.delete(s)
end
save
end
end
# Parent rp, folder and dc methods
# TODO: Replace all with ancestors lookup once multiple parents is sorted out
def parent_resource_pool
with_relationship_type('ems_metadata') do
parent(:of_type => "ResourcePool")
end
end
alias_method :owning_resource_pool, :parent_resource_pool
def parent_blue_folder
with_relationship_type('ems_metadata') do
parent(:of_type => "EmsFolder")
end
end
alias_method :owning_blue_folder, :parent_blue_folder
def parent_blue_folders(*args)
f = parent_blue_folder
f.nil? ? [] : f.folder_path_objs(*args)
end
def under_blue_folder?(folder)
return false unless folder.kind_of?(EmsFolder)
parent_blue_folders.any? { |f| f == folder }
end
def parent_blue_folder_path(*args)
f = parent_blue_folder
f.nil? ? "" : f.folder_path(*args)
end
alias_method :owning_blue_folder_path, :parent_blue_folder_path
def parent_folder
ems_cluster.try(:parent_folder)
end
alias_method :owning_folder, :parent_folder
alias_method :parent_yellow_folder, :parent_folder
def parent_folders(*args)
f = parent_folder
f.nil? ? [] : f.folder_path_objs(*args)
end
alias_method :parent_yellow_folders, :parent_folders
def parent_folder_path(*args)
f = parent_folder
f.nil? ? "" : f.folder_path(*args)
end
alias_method :owning_folder_path, :parent_folder_path
alias_method :parent_yellow_folder_path, :parent_folder_path
def parent_datacenter
ems_cluster.try(:parent_datacenter)
end
alias_method :owning_datacenter, :parent_datacenter
def parent_blue_folder_display_path
parent_blue_folder_path(:exclude_non_display_folders => true)
end
alias_method :v_parent_blue_folder_display_path, :parent_blue_folder_display_path
def lans
!hardware.nil? ? hardware.nics.collect(&:lan).compact : []
end
# Create a hash of this Vm's EMS and Host and their credentials
def ems_host_list
params = {}
[ext_management_system, "ems", host, "host"].each_slice(2) do |ems, type|
if ems
params[type] = {
:hostname => ems.hostname,
:ipaddress => ems.ipaddress,
:username => ems.authentication_userid,
:password => ems.authentication_password_encrypted,
:class_name => ems.class.name
}
params[type][:port] = ems.port if ems.respond_to?(:port) && ems.port.present?
end
end
params
end
def reconnect_events
events = EmsEvent.where("ems_id = ? AND ((vm_ems_ref = ? AND vm_or_template_id IS NULL) OR (dest_vm_ems_ref = ? AND dest_vm_or_template_id IS NULL))", ext_management_system.id, ems_ref, ems_ref)
events.each do |e|
do_save = false
src_vm = e.src_vm_or_template
if src_vm.nil? && e.vm_ems_ref == ems_ref
src_vm = self
e.vm_or_template_id = src_vm.id
e.vm_name = src_vm.name
do_save = true
end
dest_vm = e.dest_vm_or_template
if dest_vm.nil? && e.dest_vm_ems_ref == ems_ref
dest_vm = self
e.dest_vm_or_template_id = dest_vm.id
do_save = true
end
e.save if do_save
# Hook up genealogy after a Clone Task
src_vm.add_genealogy_child(dest_vm) if src_vm && dest_vm && e.event_type == EmsEvent::CLONE_TASK_COMPLETE
end
true
end
def add_genealogy_child(child)
with_relationship_type('genealogy') do
set_child(child)
end
end
def myhost
return @surrogate_host if @surrogate_host
return host unless host.nil?
self.class.proxy_host_for_repository_scans
end
def self.scan_via_ems?
!::Settings.coresident_miqproxy.scan_via_host
end
delegate :scan_via_ems?, :to => :class
# Cache the proxy host for repository scans because the JobProxyDispatch calls this for each Vm scan job in a loop
cache_with_timeout(:proxy_host_for_repository_scans, 30.seconds) do
defaultsmartproxy = ::Settings.repository_scanning.defaultsmartproxy
proxy = nil
proxy = MiqProxy.find_by(:id => defaultsmartproxy.to_i) if defaultsmartproxy
proxy.try(:host)
end
def my_zone
ems = ext_management_system
ems ? ems.my_zone : MiqServer.my_zone
end
def my_zone_obj
Zone.find_by(:name => my_zone)
end
#
# Proxy methods
#
# TODO: Come back to this
def proxies4job(_job = nil)
_log.debug("Enter")
all_proxy_list = storage2proxies
proxies = storage2active_proxies(all_proxy_list)
_log.debug("# proxies = #{proxies.length}")
msg = if all_proxy_list.empty?
"No active SmartProxies found to analyze this VM"
elsif proxies.empty?
"Provide credentials for this VM's Host to perform SmartState Analysis"
else
'Perform SmartState Analysis on this VM'
end
log_all_proxies(all_proxy_list, msg) if proxies.empty?
{:proxies => proxies.flatten, :message => msg}
end
def log_all_proxies(all_proxy_list, message)
proxies = all_proxy_list.collect { |a| "[#{log_proxies_format_instance(a)}]" }
proxies_text = proxies.empty? ? "[none]" : proxies.join(" -- ")
_log.warn("Proxies for #{log_proxies_vm_config} : #{proxies_text}")
_log.warn("Proxies message: #{message}")
end
def log_proxies_vm_config
msg = "[#{log_proxies_format_instance(self)}] on host [#{log_proxies_format_instance(host)}] datastore "
msg << (storage ? "[#{storage.name}-#{storage.store_type}]" : "No storage")
end
def log_proxies_format_instance(object)
return 'Nil' if object.nil?
"#{object.class.name}:#{object.id}-#{object.name}:#{object.try(:state)}"
end
def storage2proxies
@storage_proxies ||= begin
# Support vixDisk scanning of VMware VMs from the vmdb server
miq_server_proxies
end
end
def storage2active_proxies(all_proxy_list = nil)
all_proxy_list ||= storage2proxies
_log.debug("all_proxy_list.length = #{all_proxy_list.length}")
proxies = all_proxy_list.select(&:is_proxy_active?)
_log.debug("proxies1.length = #{proxies.length}")
# MiqServer coresident proxy needs to contact the host and provide credentials.
# Remove any MiqServer instances if we do not have credentials
rsc = scan_via_ems? ? ext_management_system : host
proxies.delete_if { |p| p.is_a?(MiqServer) } if rsc && !rsc.authentication_status_ok?
_log.debug("proxies2.length = #{proxies.length}")
proxies
end
def has_active_proxy?
storage2active_proxies.any?
end
def has_proxy?
storage2proxies.any?
end
# Cache the servers because the JobProxyDispatch calls this for each Vm scan job in a loop
cache_with_timeout(:miq_servers_for_scan, 30.seconds) do
MiqServer.where(:status => "started").includes([:zone, :server_roles]).to_a
end
def miq_server_proxies
case vendor