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, #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



70
71
72
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 70

def self.model_name
  ComputeResource.model_name
end

.provider_friendly_nameObject



74
75
76
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 74

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



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

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

#available_networks(attr = {}) ⇒ Object



179
180
181
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 179

def available_networks(attr = {})
  subnets
end

#available_vnets(attr = {}) ⇒ Object



175
176
177
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 175

def available_vnets(attr = {})
  virtual_networks
end

#capabilitiesObject



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

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]
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



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

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?
      # Any change to sudoers_cmd and formation of new
      # args[:script_command] must be accordingly changed
      # in script_command method in AzureRmCompute class
      sudoers_cmd = "$echo #{args[:password]} | sudo -S echo '\"#{args[:username]}\" ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/waagent"
      if args[:script_command].present?
        # to run the script_cmd given through form as username
        user_command = args[:script_command]
        args[:script_command] =  sudoers_cmd + " ; su - \"#{args[:username]}\" -c \"#{user_command}\""
      else
        args[:script_command] =  sudoers_cmd
      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],
  )
  logger.debug "Virtual Machine #{args[:vm_name]} Created Successfully."
  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])
rescue RuntimeError => e
  Foreman::Logging.exception('Unhandled AzureRm error', e)
  destroy_vm vm.id if vm
  raise e
end

#destroy_vm(uuid) ⇒ Object



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

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)


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

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
end

#find_vm_by_uuid(uuid) ⇒ Object

Raises:

  • (ActiveRecord::RecordNotFound)


257
258
259
260
261
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 257

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)


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

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



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

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



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

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]
                        )
  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])
end

#new_volume(attrs = {}) ⇒ Object



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

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

#provided_attributesObject



133
134
135
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 133

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

#regionsObject



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

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

#resource_groupsObject



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

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



250
251
252
253
254
255
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 250

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



187
188
189
190
191
192
193
194
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 187

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



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

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)


264
265
266
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 264

def user_data_supported?
  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



183
184
185
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 183

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

#vm_disks(vm) ⇒ Object



237
238
239
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 237

def vm_disks(vm)
  vm.storage_profile.data_disks
end

#vm_instance_defaultsObject



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

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

#vm_nics(vm) ⇒ Object



227
228
229
230
231
232
233
234
235
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 227

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



212
213
214
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 212

def vm_sizes
  sdk.list_vm_sizes(region)
end

#vms(attrs = {}) ⇒ Object



241
242
243
244
245
246
247
248
# File 'app/models/foreman_azure_rm/azure_rm.rb', line 241

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