Class: ForemanAzureRm::AzureRm

Inherits:
ComputeResource
  • Object
show all
Includes:
VMExtensions::ManagedVM
Defined in:
app/models/foreman_azure_rm/azure_rm.rb

Defined Under Namespace

Classes: VMContainer

Class Method Summary collapse

Instance Method Summary collapse

Methods included from VMExtensions::ManagedVM

#create_managed_virtual_machine, #create_nics, #create_vm_extension, #create_vm_nvidia_gpu_extension, #define_data_disks, #define_image, #define_managed_storage_profile, #define_network_profile, #disk_caching, #initialize_vm, #marketplace_image_plan, #marketplace_image_reference

Class Method Details

.model_nameObject



79
80
81
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 79

def self.model_name
  ComputeResource.model_name
end

.provider_friendly_nameObject



83
84
85
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 83

def self.provider_friendly_name
  'Azure Resource Manager'
end

Instance Method Details

#app_identObject



37
38
39
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 37

def app_ident
  attrs[:app_ident]
end

#app_ident=(name) ⇒ Object



41
42
43
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 41

def app_ident=(name)
  attrs[:app_ident] = name
end

#associated_host(vm) ⇒ Object



235
236
237
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 235

def associated_host(vm)
  associate_by("ip", [vm.public_ip_address, vm.private_ip_address])
end

#available_networks(attr = {}) ⇒ Object



198
199
200
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 198

def available_networks(attr = {})
  subnets
end

#available_vnets(attr = {}) ⇒ Object



194
195
196
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 194

def available_vnets(attr = {})
  virtual_networks
end

#capabilitiesObject



87
88
89
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 87

def capabilities
  [:image, :new_volume]
end

#cloudObject



45
46
47
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 45

def cloud
  attrs[:cloud] || 'azure'
end

#cloud=(name) ⇒ Object



49
50
51
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 49

def cloud=(name)
  attrs[:cloud] = name
end

#create_vm(args = {}) ⇒ Object



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
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 287

def create_vm(args = {})
  args = args.to_h.deep_symbolize_keys
  args[:vm_name] = args[:name].split('.')[0]
  nics = create_nics(region, args)

  if args[:platform] == 'Linux'
    if args[:password].present? && !args[:ssh_key_data].present?
      if args[:script_command].present?
        # to run the script_cmd given through form as username
        user_command = args[:script_command]
        args[:script_command] = "su - \"#{args[:username]}\" -c \"#{user_command}\""
      end
      disable_password_auth = false
    elsif args[:ssh_key_data].present? && !args[:password].present?
      disable_password_auth = true
    else
      disable_password_auth = false
    end
  end

  vm             = create_managed_virtual_machine(
    name:                            args[:vm_name],
    location:                        region,
    resource_group:                  args[:resource_group],
    vm_size:                         args[:vm_size],
    username:                        args[:username],
    password:                        args[:password],
    ssh_key_data:                    args[:ssh_key_data],
    disable_password_authentication: disable_password_auth,
    network_interface_card_ids:      nics.map(&:id),
    platform:                        args[:platform],
    image_id:                        args[:image_id],
    os_disk_caching:                 args[:os_disk_caching],
    premium_os_disk:                 args[:premium_os_disk],
    os_disk_size_gb:                 args[:os_disk_size_gb],
    data_disks:                      args[:volumes_attributes],
    custom_data:                     args[:user_data],
    script_command:                  args[:script_command],
    script_uris:                     args[:script_uris],
    nvidia_gpu_extension:            args[:nvidia_gpu_extension],
    tags:                            args[:tags],
  )
  logger.debug "Virtual Machine #{args[:vm_name]} Created Successfully."
  # request NVIDIA GPU driver and CUDA stack
  if ActiveRecord::Type::Boolean.new.deserialize(args[:nvidia_gpu_extension])
    create_vm_nvidia_gpu_extension(region, args)
  end
  # as this extension may contains postinstall script, call it after others
  create_vm_extension(region, args)
  # return the vm object using azure_vm
  AzureRmCompute.new(
    azure_vm: vm,
    sdk: sdk,
    resource_group: args[:resource_group],
    nics: vm_nics(vm),
    volumes: vm_disks(vm),
    script_command: user_command,
    script_uris: args[:script_uris],
    nvidia_gpu_extension: ActiveRecord::Type::Boolean.new.deserialize(args[:nvidia_gpu_extension]),
    tags: args[:tags],
  )
rescue RuntimeError => e
  Foreman::Logging.exception('Unhandled AzureRm error', e)
  destroy_vm vm.id if vm
  raise e
end

#destroy_vm(uuid) ⇒ Object



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
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 354

def destroy_vm(uuid)
  vm           = find_vm_by_uuid(uuid)
  rg_name      = vm.resource_group
  os_disk      = vm.azure_vm.storage_profile.os_disk
  data_disks   = vm.azure_vm.storage_profile.data_disks
  nic_ids      = vm.network_interface_card_ids

  sdk.delete_vm(rg_name, vm.name)

  nic_ids.each do |nic_id|
    nic = sdk.vm_nic(rg_name, nic_id.split('/')[-1])
    if nic.present?
      public_ip = nic.ip_configurations.first.public_ipaddress
      sdk.delete_nic(rg_name, nic_id.split('/')[-1])
      if public_ip.present?
        ip_id = public_ip.id
        sdk.delete_pip(rg_name, ip_id.split('/')[-1])
      end
    end
  end
  sdk.delete_disk(rg_name, os_disk.name) if os_disk.present?
  data_disks.each { |data_disk| sdk.delete_disk(rg_name, data_disk.name) } if data_disks.present?
  true
rescue ActiveRecord::RecordNotFound
  logger.info "Could not find the selected vm."
  true
end

#editable_network_interfaces?Boolean

Returns:

  • (Boolean)


222
223
224
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 222

def editable_network_interfaces?
  true
end

#ensure_attributes_and_valuesObject



61
62
63
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 61

def ensure_attributes_and_values
  validate_region if validate_cloud?
end

#find_vm_by_uuid(uuid) ⇒ Object

Raises:

  • (ActiveRecord::RecordNotFound)


276
277
278
279
280
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 276

def find_vm_by_uuid(uuid)
  vm = vms.all.find { |vm| vm.name == uuid }
  raise ActiveRecord::RecordNotFound unless vm.present?
  vm
end

#image_exists?(image) ⇒ Boolean

Returns:

  • (Boolean)


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
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 156

def image_exists?(image)
  image_type, image_id = image.split('://')
  case image_type
  when 'marketplace'
    begin
      urn = image_id.split(':')
      publisher = urn[0]
      offer     = urn[1]
      sku       = urn[2]
      version   = urn[3]
      if version == "latest"
        all_versions = sdk.list_versions(region, publisher, offer, sku).map(&:name)
        return true if all_versions.any?
      end
      sdk.get_marketplace_image(region, publisher, offer, sku, version).present?
    rescue StandardError => e
      return false
    end
  when 'gallery'
    gallery_images_list = sdk.list_resources(filter: "resourceType eq 'Microsoft.Compute/galleries/images'")
    gallery_image = gallery_images_list.detect { |gal_img| gal_img.id.split('/')[-1] == image_id }
    if gallery_image.present?
      rg_name = gallery_image.id.split('/')[4]
      gallery_name = gallery_image.name.split('/')[0]
      image_versions = sdk.list_gallery_image_versions(rg_name, gallery_name, image_id)
      target_regions = image_versions.map do |image_version|
        image_version.publishing_profile.target_regions.map(&:name)
      end.flatten.uniq.map { |tgt_reg| tgt_reg.gsub(/\s+/, '').downcase }
      return true if target_regions.include? region
    end
  when 'custom'
    custom_image = sdk.list_custom_images.detect { |custom_img| custom_img.name == image_id && custom_img.location == region }
    return custom_image.present?
  else
    false
  end
end

#new_interface(attrs = {}) ⇒ Object



217
218
219
220
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 217

def new_interface(attrs = {})
  args = { :network => "", :public_ip => "", :private_ip => false, 'persisted?' => false }.merge(attrs.to_h)
  OpenStruct.new(args)
end

#new_vm(args = {}) ⇒ Object



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
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 109

def new_vm(args = {})
  return AzureRmCompute.new(sdk: sdk) if args.empty?
  opts = vm_instance_defaults.merge(args.to_h).deep_symbolize_keys
  # convert rails nested_attributes into a plain hash
  [:interfaces, :volumes].each do |collection|
    nested_args = opts.delete("#{collection}_attributes".to_sym)
    opts[collection] = nested_attributes_for(collection, nested_args) if nested_args
  end
  opts.reject! { |k, v| v.nil? }

  raw_vm = initialize_vm(location:        region,
                         resource_group:  opts[:resource_group],
                         vm_size:         opts[:vm_size],
                         username:        opts[:username],
                         password:        opts[:password],
                         platform:        opts[:platform],
                         ssh_key_data:    opts[:ssh_key_data],
                         os_disk_caching: opts[:os_disk_caching],
                         premium_os_disk: opts[:premium_os_disk],
                         os_disk_size_gb: opts[:os_disk_size_gb],
                         nvidia_gpu_extension: opts[:nvidia_gpu_extension],
                        )
  if opts[:interfaces].present?
    ifaces = []
    opts[:interfaces].each_with_index do |iface_attrs, i|
      ifaces << new_interface(iface_attrs)
    end
  end

  vols = opts.fetch(:volumes, []).map { |vols_attrs| new_volume(vols_attrs) } if opts[:volumes].present?

  AzureRmCompute.new(
    azure_vm: raw_vm,
    sdk: sdk,
    resource_group: opts[:resource_group],
    nics: ifaces,
    volumes: vols,
    script_command: opts[:script_command],
    script_uris: opts[:script_uris],
    nvidia_gpu_extension: ActiveRecord::Type::Boolean.new.deserialize(opts[:nvidia_gpu_extension]),
  )
end

#new_volume(attrs = {}) ⇒ Object



226
227
228
229
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 226

def new_volume(attrs = {})
  args = { :disk_size_gb => 0, :data_disk_caching => "", 'persisted?' => false }.merge(attrs.to_h)
  OpenStruct.new(args)
end

#provided_attributesObject



152
153
154
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 152

def provided_attributes
  super.merge({ :ip => :provisioning_ip_address })
end

#regionsObject



91
92
93
94
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 91

def regions
  return unless sub_id.present?
  sdk.list_regions(sub_id).value.map { |loc| [loc.display_name, loc.name] }
end

#resource_groupsObject



96
97
98
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 96

def resource_groups
  sdk.rgs
end

#sdkObject



53
54
55
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 53

def sdk
  @sdk ||= ForemanAzureRm::AzureSdkAdapter.new(tenant, app_ident, secret_key, sub_id, azure_environment)
end

#setup_key_pairObject



269
270
271
272
273
274
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 269

def setup_key_pair
  require 'sshkey'
  name = "foreman-#{id}#{Foreman.uuid}"
  key  = ::SSHKey.generate
  build_key_pair :name => name, :secret => key.private_key, :public => key.ssh_public_key
end

#subnetsObject Also known as: available_subnets



206
207
208
209
210
211
212
213
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 206

def subnets
  vnets   = virtual_networks
  subnets = []
  vnets.each do |vnet|
    subnets.concat(sdk.subnets(vnet.resource_group, vnet.name))
  end
  subnets
end

#test_connection(options = {}) ⇒ Object



100
101
102
103
104
105
106
107
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 100

def test_connection(options = {})
  super
  errors[:user].empty? && errors[:password].empty? && errors[:uuid].empty? && errors[:app_ident].empty? && errors[:cloud].empty? && regions
rescue StandardError => e
  errors[:base] << e.message
rescue Excon::Error::Socket => e
  errors[:base] << e.message
end

#to_labelObject



57
58
59
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 57

def to_label
  "#{name} (#{provider_friendly_name})"
end

#user_data_supported?Boolean

user data support

Returns:

  • (Boolean)


283
284
285
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 283

def user_data_supported?
  true
end

#validate_cloud?Boolean

Returns:

  • (Boolean)


70
71
72
73
74
75
76
77
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 70

def validate_cloud?
  valid_clouds = ['azure', 'azureusgovernment', 'azurechina', 'azuregermancloud']
  unless valid_clouds.include?(cloud)
  	errors.add(:cloud, _("is not valid. Valid choices are %s.") % valid_clouds.join(", "))
   return false
  end
  true
end

#validate_regionObject



65
66
67
68
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 65

def validate_region
  return unless regions.present?
  errors.add(:region, _("is not valid, must be lowercase eg. 'eastus'. No special characters allowed.")) unless regions.collect(&:second).include?(region)
end

#virtual_networksObject



202
203
204
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 202

def virtual_networks
  @virtual_networks ||= sdk.vnets.select { |vnet| vnet.location == region }
end

#vm_disks(vm) ⇒ Object



256
257
258
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 256

def vm_disks(vm)
  vm.storage_profile.data_disks
end

#vm_instance_defaultsObject



239
240
241
242
243
244
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 239

def vm_instance_defaults
  super.deep_merge(
    interfaces: [new_interface],
    volumes: [new_volume]
  )
end

#vm_nics(vm) ⇒ Object



246
247
248
249
250
251
252
253
254
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 246

def vm_nics(vm)
  ifaces = []
  vm.network_profile.network_interfaces.each do |nic|
    nic_rg = (split_nic_id = nic.id.split('/'))[4]
    nic_name = split_nic_id[-1]
    ifaces << sdk.vm_nic(nic_rg, nic_name)
  end
  ifaces
end

#vm_sizesObject



231
232
233
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 231

def vm_sizes
  sdk.list_vm_sizes(region)
end

#vms(attrs = {}) ⇒ Object



260
261
262
263
264
265
266
267
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 260

def vms(attrs = {})
  container = VMContainer.new
  # Load all vms of the region
  sdk.list_vms(region).each do |vm|
    container.virtualmachines << AzureRmCompute.new(azure_vm: vm, sdk:sdk, nics: vm_nics(vm))
  end
  container
end