-
Notifications
You must be signed in to change notification settings - Fork 991
/
compute_resource.rb
477 lines (383 loc) · 12.7 KB
/
compute_resource.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
class ComputeResource < ApplicationRecord
audited :except => [:attrs]
include Taxonomix
include Encryptable
include Authorizable
include Parameterizable::ByIdName
encrypts :password
ALLOWED_KEYBOARD_LAYOUTS = %w(ar de-ch es fo fr-ca hu ja mk no pt-br sv da en-gb et fr fr-ch is lt nl pl ru th de en-us fi fr-be hr it lv nl-be pt sl tr)
validates_lengths_from_database
serialize :attrs, Hash
belongs_to :http_proxy
before_destroy EnsureNotUsedBy.new(:hosts)
validates :name, :presence => true, :uniqueness => true
validate :ensure_provider_not_changed, :on => :update
validates :provider, :presence => true, :inclusion => { :in => proc { providers } }
scoped_search :on => :name, :complete_value => :true
scoped_search :on => :type, :complete_value => :true
scoped_search :on => :id, :complete_enabled => false, :only_explicit => true, :validator => ScopedSearch::Validators::INTEGER
before_save :sanitize_url
has_many_hosts
has_many :hostgroups, :dependent => :nullify
has_many :images, :dependent => :destroy
before_validation :set_attributes_hash
has_many :compute_attributes, :dependent => :destroy
has_many :compute_profiles, :through => :compute_attributes
# The DB may contain compute resource from disabled plugins - filter them out here
scope :live_descendants, -> { where(:type => descendants.map(&:to_s)) unless Rails.env.development? }
# with proc support, default_scope can no longer be chained
# include all default scoping here
default_scope lambda {
with_taxonomy_scope do
order("compute_resources.name")
end
}
graphql_type '::Types::ComputeResource'
def self.supported_providers
{
'Libvirt' => 'Foreman::Model::Libvirt',
'Ovirt' => 'Foreman::Model::Ovirt',
'EC2' => 'Foreman::Model::EC2',
'Vmware' => 'Foreman::Model::Vmware',
'Openstack' => 'Foreman::Model::Openstack',
'GCE' => 'Foreman::Model::GCE',
}
end
def self.registered_providers
Foreman::Plugin.all.map(&:compute_resources).each_with_object({}) do |providers, prov_hash|
providers.each { |provider| prov_hash.update(provider.split('::').last => provider) }
end
end
def self.all_providers
supported_providers.merge(registered_providers)
end
# Providers in Foreman core that have optional installation should override this to check if
# they are installed. Plugins should not need to override this, as their dependencies should
# always be present.
def self.available?
true
end
def self.providers
supported_providers.merge(registered_providers).select do |provider_name, class_name|
class_name.constantize.available?
end
end
def self.providers_requiring_url
_("Libvirt, oVirt and OpenStack")
end
def self.provider_class(name)
all_providers[name]
end
# allows to create a specific compute class based on the provider.
def self.new_provider(args)
provider = args.delete(:provider)
raise ::Foreman::Exception.new(N_("must provide a provider")) unless provider
providers.each do |provider_name, provider_class|
return provider_class.constantize.new(args) if provider_name.downcase == provider.downcase
end
raise ::Foreman::Exception.new N_("unknown provider")
end
def capabilities
[]
end
def capable?(feature)
capabilities.include?(feature)
end
# attributes that this provider can provide back to the host object
def provided_attributes
{:uuid => :identity}
end
def test_connection(options = {})
valid?
end
def ping
test_connection
errors
end
def save_vm(uuid, attr)
vm = find_vm_by_uuid(uuid)
vm.attributes.merge!(attr.deep_symbolize_keys)
vm.save
end
def to_label
"#{name} (#{provider_friendly_name})"
end
def connection_options
http_proxy ? {:proxy => http_proxy.full_url} : {}
end
# Override this method to specify provider name
def self.provider_friendly_name
name.split('::').last()
end
def provider_friendly_name
self.class.provider_friendly_name
end
def host_compute_attrs(host)
{ :name => host.vm_name,
:provision_method => host.provision_method,
:firmware_type => host.firmware_type,
"#{interfaces_attrs_name}_attributes" => host_interfaces_attrs(host) }.with_indifferent_access
end
def host_interfaces_attrs(host)
host.interfaces.select(&:physical?).each.with_index.reduce({}) do |hash, (nic, index)|
hash.merge(index.to_s => nic.compute_attributes.merge(ip: nic.ip, ip6: nic.ip6))
end
end
def image_param_name
:image_id
end
def interfaces_attrs_name
:interfaces
end
# returns a new fog server instance
def new_vm(attr = {})
test_connection
client.servers.new vm_instance_defaults.merge(attr.to_hash.deep_symbolize_keys) if errors.empty?
end
# return fog new interface ( network adapter )
def new_interface(attr = {})
client.interfaces.new attr
end
# return a list of virtual machines
def vms(attrs = {})
client.servers(attrs)
end
def supports_vms_pagination?
false
end
def find_vm_by_uuid(uuid)
client.servers.get(uuid) || raise(ActiveRecord::RecordNotFound)
end
def start_vm(uuid)
find_vm_by_uuid(uuid).start
end
def stop_vm(uuid)
find_vm_by_uuid(uuid).stop
end
def create_vm(args = {})
options = vm_instance_defaults.merge(args.to_hash.deep_symbolize_keys)
logger.debug("creating VM with the following options: #{options.inspect}")
client.servers.create options
end
def destroy_vm(uuid)
find_vm_by_uuid(uuid).destroy
rescue ActiveRecord::RecordNotFound
# if the VM does not exists, we don't really care.
true
end
def provider
self[:type].to_s.split('::').last
end
def provider=(value)
if self.class.providers.include? value
self.type = self.class.provider_class(value)
else
self.type = value # this will trigger validation error since value is one of supported_providers
logger.debug("unknown provider for compute resource")
end
end
def vm_instance_defaults
ActiveSupport::HashWithIndifferentAccess.new(:name => "foreman_#{Time.now.to_i}")
end
def templates(opts = {})
end
def template(id, opts = {})
end
def update_required?(old_attrs, new_attrs)
old_attrs.deep_symbolize_keys.merge(new_attrs.deep_symbolize_keys) do |k, old_v, new_v|
if old_v.is_a?(Hash) && new_v.is_a?(Hash)
return true if update_required?(old_v, new_v)
elsif old_v.to_s != new_v.to_s
Rails.logger.debug "Scheduling compute instance update because #{k} changed it's value from '#{old_v}' (#{old_v.class}) to '#{new_v}' (#{new_v.class})"
return true
end
new_v
end
false
end
def console(uuid = nil)
raise ::Foreman::Exception.new(N_("%s console is not supported at this time"), provider_friendly_name)
end
# by default, our compute providers do not support updating an existing instance
def supports_update?
false
end
def storage_domain(storage_domain)
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
def storage_pod(storage_pod)
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
def available_zones
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
def available_images
[]
end
def available_virtual_machines
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
def available_networks(cluster_id = nil)
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
def available_clusters
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
def available_folders
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
def available_flavors
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
def available_resource_pools
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
def available_security_groups
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
def available_storage_domains(cluster_id = nil)
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
def available_storage_pods(cluster_id = nil)
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
# if this method is overridden in a provider, new_volume_errors should be also overridden
# method should return nil in case it can't build new volume because of some misconfiguration or runtime issue
def new_volume(attr = {})
raise ::Foreman::Exception.new(N_("Not implemented for %s"), provider_friendly_name)
end
# returs an array of translated errors that prevents to build a volume on this provider
def new_volume_errors
[]
end
# this method is overwritten for Libvirt and OVirt
def editable_network_interfaces?
networks.any?
end
# this method is overwritten for Libvirt and VMware
def set_console_password?
false
end
alias_method :set_console_password, :set_console_password?
# this method is overwritten for Libvirt and VMware
def set_console_password=(setpw)
attrs[:setpw] = nil
end
# this method is overwritten for Libvirt, oVirt & VMWare
def display_type=(_)
end
# this method is overwritten for Libvirt, oVirt & VMWare
def display_type
nil
end
# this method is overwritten for oVirt
def keyboard_layout=(_)
end
# this method is overwritten for oVirt
def keyboard_layout
nil
end
def keyboard_layouts
ALLOWED_KEYBOARD_LAYOUTS
end
def compute_profile_for(id)
compute_attributes.find_by_compute_profile_id(id)
end
def compute_profile_attributes_for(id)
compute_profile_for(id).try(:vm_attrs) || {}
end
def vm_compute_attributes_for(uuid)
vm = find_vm_by_uuid(uuid)
return {} unless vm
vm_compute_attributes(vm)
rescue ActiveRecord::RecordNotFound
logger.warn("VM with UUID '#{uuid}' not found on #{self}")
{}
end
def vm_compute_attributes(vm)
vm_attrs = vm.attributes rescue {}
vm_attrs = vm_attrs.reject { |k, v| k == :id }
vm_attrs = set_vm_volumes_attributes(vm, vm_attrs)
vm_attrs = set_vm_interfaces_attributes(vm, vm_attrs)
vm_attrs
end
def vm_ready(vm)
vm.wait_for { ready? }
end
def user_data_supported?
false
end
def image_exists?(image)
true
end
def supports_host_association?
respond_to?(:associated_host)
end
def normalize_vm_attrs(vm_attrs)
vm_attrs
end
protected
def memory_gb_to_bytes(memory_size)
memory_size.to_s.gsub(/[^0-9]/, '').to_i * 1.gigabyte
end
def to_bool(value)
['1', 'true'].include?(value.to_s.downcase) unless value.nil?
end
def slice_vm_attributes(vm_attrs, fields)
fields.inject({}) do |slice, f|
slice.merge({f => (vm_attrs[f].to_s.empty? ? nil : vm_attrs[f])})
end
end
def client
raise ::Foreman::Exception.new N_("Not implemented")
end
def sanitize_url
self.url = url.chomp("/") unless url.empty?
end
def random_password
return nil unless set_console_password?
SecureRandom.hex(8)
end
def nested_attributes_for(type, opts)
return [] unless opts
opts = opts.to_hash if opts.class == ActionController::Parameters
opts = opts.dup # duplicate to prevent changing the origin opts.
unless opts.is_a?(Array)
opts.delete("new_#{type}") || opts.delete("new_#{type}".to_sym) # delete template
# convert our options hash into a sorted array (e.g. to preserve nic / disks order)
opts = opts.sort { |l, r| l[0].to_s.sub('new_', '').to_i <=> r[0].to_s.sub('new_', '').to_i }.map { |e| Hash[e[1]] }
end
opts.map do |v|
if v[:_delete] == '1' && v[:id].blank?
nil
else
v.deep_symbolize_keys # convert to symbols deeper hashes
end
end.compact
end
def associate_by(name, attributes)
attributes = Array.wrap(attributes).map { |mac| Net::Validations.normalize_mac(mac) } if name == 'mac'
Host.authorized(:view_hosts, Host).joins(:primary_interface).
where(:nics => {:primary => true}).
where("nics.#{name}" => attributes).
readonly(false).
first
end
private
def set_vm_volumes_attributes(vm, vm_attrs)
if vm.respond_to?(:volumes)
volumes = vm.volumes || []
vm_attrs[:volumes_attributes] = Hash[volumes.each_with_index.map { |volume, idx| [idx.to_s, volume.attributes] }]
end
vm_attrs
end
def set_attributes_hash
self.attrs ||= {}
end
def ensure_provider_not_changed
errors.add(:provider, _("cannot be changed")) if type_changed?
end
def set_vm_interfaces_attributes(_vm, vm_attrs)
vm_attrs
end
end