Module: Azure::VirtualMachineManagement::Serialization

Extended by:
Core::Utility
Defined in:
lib/azure/virtual_machine_management/serialization.rb

Class Method Summary collapse

Methods included from Core::Utility

enable_winrm?, export_der, export_fingerprint, get_certificate, initialize_external_logger, locate_file, random_string, xml_content

Class Method Details

.add_data_disk_to_xml(vm, options) ⇒ Object



411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/azure/virtual_machine_management/serialization.rb', line 411

def self.add_data_disk_to_xml(vm, options)
  if options[:import] && options[:disk_name].nil?
    Azure::Loggerx.error_with_exit "The data disk name is not valid."
  end
  media_link = vm.media_link
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.DataVirtualHardDisk(
      'xmlns' => 'http://schemas.microsoft.com/windowsazure',
      'xmlns:i' => 'http://www.w3.org/2001/XMLSchema-instance'
    ) do
      xml.HostCaching options[:host_caching] || 'ReadOnly'
      xml.DiskLabel options[:disk_label]
      xml.DiskName options[:disk_name] if options[:import]
      xml.LogicalDiskSizeInGB options[:disk_size] || 100
      unless options[:import]
        disk_name = media_link[/([^\/]+)$/]
        media_link = media_link.gsub(/#{disk_name}/, (Time.now.strftime('disk_%Y_%m_%d_%H_%M_%S')) + '.vhd')
        xml.MediaLink media_link
      end
    end
  end
  builder.doc.to_xml
end

.data_disks_from_xml(rolesXML) ⇒ Object



299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/azure/virtual_machine_management/serialization.rb', line 299

def self.data_disks_from_xml(rolesXML)
  data_disks = []
  virtual_hard_disks = rolesXML.css('DataVirtualHardDisks DataVirtualHardDisk')
  virtual_hard_disks.each do |disk|
    data_disk = {}
    data_disk[:name] = xml_content(disk, 'DiskName')
    data_disk[:lun] =  xml_content(disk, 'Lun')
    data_disk[:size_in_gb] = xml_content(disk, 'LogicalDiskSizeInGB')
    data_disk[:media_link] = xml_content(disk, 'MediaLink')
    data_disks << data_disk
  end
  data_disks
end

.default_endpoints_to_xml(xml, options) ⇒ Object



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
# File 'lib/azure/virtual_machine_management/serialization.rb', line 189

def self.default_endpoints_to_xml(xml, options)
  os_type = options[:os_type]
  used_ports = options[:existing_ports]
  endpoints = []
  if os_type == 'Linux'
    preferred_port = '22'
    port_already_opened?(used_ports, options[:ssh_port])
    endpoints << {
      name: 'SSH',
      public_port: options[:ssh_port] || assign_random_port(preferred_port, used_ports),
      protocol: 'TCP',
      local_port: preferred_port
    }
  elsif os_type == 'Windows' && options[:winrm_transport]
    if options[:winrm_transport].include?('http')
      preferred_port = '5985'
      port_already_opened?(used_ports, options[:winrm_http_port])
      endpoints << {
        name: 'WinRm-Http',
        public_port: options[:winrm_http_port] || assign_random_port(preferred_port, used_ports),
        protocol: 'TCP',
        local_port: preferred_port
      }
    end
    if options[:winrm_transport].include?('https')
      preferred_port = '5986'
      port_already_opened?(used_ports, options[:winrm_https_port])
      endpoints << {
        name: 'PowerShell',
        public_port: options[:winrm_https_port] || assign_random_port(preferred_port, used_ports),
        protocol: 'TCP',
        local_port: preferred_port
      }
    end
  end
  endpoints_to_xml(xml, endpoints)
end

.deployment_to_xml(params, image, options) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/azure/virtual_machine_management/serialization.rb', line 59

def self.deployment_to_xml(params, image, options)
  options[:deployment_name] ||= options[:cloud_service_name]
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.Deployment(
      'xmlns' => 'http://schemas.microsoft.com/windowsazure',
      'xmlns:i' => 'http://www.w3.org/2001/XMLSchema-instance'
    ) do
      xml.Name options[:deployment_name]
      xml.DeploymentSlot 'Production'
      xml.Label Base64.encode64(options[:deployment_name]).strip
      xml.RoleList { xml.Role('i:type' => 'PersistentVMRole') }
      if options[:virtual_network_name]
        xml.VirtualNetworkName options[:virtual_network_name]
      end
      if options[:reserved_ip_name]
        xml.ReservedIPName options[:reserved_ip_name]
      end
    end
  end
  builder.doc.at_css('Role') << role_to_xml(params, image, options).at_css('PersistentVMRole').children.to_s
  builder.doc.to_xml
end

.endpoints_from_xml(rolesXML, vm) ⇒ Object



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
# File 'lib/azure/virtual_machine_management/serialization.rb', line 313

def self.endpoints_from_xml(rolesXML, vm)
  vm.tcp_endpoints = []
  vm.udp_endpoints = []
  endpoints = rolesXML.css('ConfigurationSets ConfigurationSet InputEndpoints InputEndpoint')
  endpoints.each do |endpoint|
    lb_name = xml_content(endpoint, 'LoadBalancedEndpointSetName')
    ep = {}
    ep[:name] = xml_content(endpoint, 'Name')
    ep[:vip] = xml_content(endpoint, 'Vip')
    ep[:public_port] = xml_content(endpoint, 'Port')
    ep[:local_port] = xml_content(endpoint, 'LocalPort')
    ep[:protocol] = xml_content(endpoint, 'Protocol')
    server_return = xml_content(endpoint, 'EnableDirectServerReturn')
    ep[:direct_server_return] = server_return if !server_return.empty?
    unless lb_name.empty?
      ep[:protocol] = endpoint.css('Protocol').last.text
      ep[:load_balancer_name] = lb_name
      lb_port = xml_content(endpoint, 'LoadBalancerProbe Port')
      lb_protocol = xml_content(endpoint, 'LoadBalancerProbe Protocol')
      lb_path = xml_content(endpoint, 'LoadBalancerProbe Path')
      lb_interval = xml_content(
        endpoint,
        'LoadBalancerProbe IntervalInSeconds'
      )
      lb_timeout = xml_content(
        endpoint,
        'LoadBalancerProbe TimeoutInSeconds'
      )
      ep[:load_balancer] = {
        port: lb_port,
        path: lb_path,
        protocol: lb_protocol,
        interval: lb_interval,
        timeout: lb_timeout
      }
    end
    if ep[:protocol].downcase == 'tcp'
      vm.tcp_endpoints << ep
    else
      vm.udp_endpoints << ep
    end
  end
end

.endpoints_to_xml(xml, endpoints) ⇒ Object



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
# File 'lib/azure/virtual_machine_management/serialization.rb', line 382

def self.endpoints_to_xml(xml, endpoints)
  endpoints.each do |endpoint|
    endpoint[:load_balancer] ||= {}
    protocol = endpoint[:protocol]
    port = endpoint[:public_port]
    interval = endpoint[:load_balancer][:interval]
    timeout = endpoint[:load_balancer][:timeout]
    path = endpoint[:load_balancer][:path]
    balancer_name = endpoint[:load_balancer_name]
    xml.InputEndpoint do
      xml.LoadBalancedEndpointSetName balancer_name if balancer_name
      xml.LocalPort endpoint[:local_port]
      xml.Name endpoint[:name]
      xml.Port endpoint[:public_port]
      if balancer_name
        xml.LoadBalancerProbe do
          xml.Path path if path
          xml.Port endpoint[:load_balancer][:port] || port
          xml.Protocol endpoint[:load_balancer][:protocol] || 'TCP'
          xml.IntervalInSeconds interval if interval
          xml.TimeoutInSeconds timeout if timeout
        end
      end
      xml.Protocol protocol
      xml.EnableDirectServerReturn endpoint[:direct_server_return] unless endpoint[:direct_server_return].nil?
    end
  end
end

.provisioning_configuration_to_xml(xml, params, options) ⇒ Object



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
# File 'lib/azure/virtual_machine_management/serialization.rb', line 131

def self.provisioning_configuration_to_xml(xml, params, options)
  fingerprint = params[:certificate][:fingerprint]
  if options[:os_type] == 'Linux'
    xml.ConfigurationSet('i:type' => 'LinuxProvisioningConfigurationSet') do
      xml.ConfigurationSetType 'LinuxProvisioningConfiguration'
      xml.HostName params[:vm_name]
      xml.UserName params[:vm_user]
      if params[:password]
        xml.UserPassword params[:password]
        xml.DisableSshPasswordAuthentication 'false'
      end
      if fingerprint
        xml.SSH do
          xml.PublicKeys do
            xml.PublicKey do
              xml.Fingerprint fingerprint.to_s.upcase
              xml.Path "/home/#{params[:vm_user]}/.ssh/authorized_keys"
            end
          end
          xml.KeyPairs do
            xml.KeyPair do
              xml.Fingerprint fingerprint.to_s.upcase
              xml.Path "/home/#{params[:vm_user]}/.ssh/id_rsa"
            end
          end
        end
      end
      xml.CustomData params[:custom_data] if params[:custom_data]
    end
  elsif options[:os_type] == 'Windows'
    xml.ConfigurationSet('i:type' => 'WindowsProvisioningConfigurationSet') do
      xml.ConfigurationSetType 'WindowsProvisioningConfiguration'
      xml.ComputerName params[:vm_name]
      xml.AdminPassword params[:password]
      xml.ResetPasswordOnFirstLogon 'false'
      xml.EnableAutomaticUpdates 'true'
      if enable_winrm?(options[:winrm_transport])
        xml.WinRM do
          xml.Listeners do
            if options[:winrm_transport].include?('http')
              xml.Listener do
                xml.Protocol 'Http'
              end
            end
            if options[:winrm_transport].include?('https')
              xml.Listener do
                xml.Protocol 'Https'
                xml.CertificateThumbprint fingerprint if fingerprint
              end
            end
          end
        end
      end
      xml.AdminUsername params[:vm_user]
    end
  end
end

.restart_virtual_machine_to_xmlObject



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/azure/virtual_machine_management/serialization.rb', line 47

def self.restart_virtual_machine_to_xml
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.RestartRoleOperation(
      'xmlns' => 'http://schemas.microsoft.com/windowsazure',
      'xmlns:i' => 'http://www.w3.org/2001/XMLSchema-instance'
    ) do
      xml.OperationType 'RestartRoleOperation'
    end
  end
  builder.doc.to_xml
end

.role_to_xml(params, image, options) ⇒ Object



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
# File 'lib/azure/virtual_machine_management/serialization.rb', line 82

def self.role_to_xml(params, image, options)
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.PersistentVMRole(
      'xmlns' => 'http://schemas.microsoft.com/windowsazure',
      'xmlns:i' => 'http://www.w3.org/2001/XMLSchema-instance'
    ) do
      xml.RoleName { xml.text params[:vm_name] }
      xml.OsVersion('i:nil' => 'true')
      xml.RoleType 'PersistentVMRole'
      xml.ConfigurationSets do
        provisioning_configuration_to_xml(xml, params, options) if image.image_type == 'OS' || image.image_type == 'VM'
        xml.ConfigurationSet('i:type' => 'NetworkConfigurationSet') do
          xml.ConfigurationSetType 'NetworkConfiguration'
          xml.InputEndpoints do
            default_endpoints_to_xml(xml, options)
            tcp_endpoints_to_xml(
              xml,
              options[:tcp_endpoints],
              options[:existing_ports]
            ) if options[:tcp_endpoints]
          end
          if options[:virtual_network_name] && options[:subnet_name]
            xml.SubnetNames do
              xml.SubnetName options[:subnet_name]
            end
            xml.StaticVirtualNetworkIPAddress options[:static_virtual_network_ipaddress] if options[:static_virtual_network_ipaddress]
          end
        end
      end
      xml.VMImageName image.name if image.image_type == 'VM'
      xml.AvailabilitySetName options[:availability_set_name]
      xml.Label Base64.encode64(params[:vm_name]).strip
      if image.category == 'User'
        storage_host = URI.parse( image.media_link ).host
      else
        storage_host = options[:storage_account_name] + '.blob.core.windows.net'
      end
      if image.image_type == 'OS'
        xml.OSVirtualHardDisk do
          xml.MediaLink 'http://' + storage_host + '/vhds/' + (Time.now.strftime('disk_%Y_%m_%d_%H_%M_%S_%L')) + '.vhd'
          xml.SourceImageName params[:image]
        end
      end
      xml.RoleSize options[:vm_size]
    end
  end
  builder.doc
end

.shutdown_virtual_machine_to_xmlObject



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/azure/virtual_machine_management/serialization.rb', line 22

def self.shutdown_virtual_machine_to_xml
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.ShutdownRoleOperation(
      'xmlns' => 'http://schemas.microsoft.com/windowsazure',
      'xmlns:i' => 'http://www.w3.org/2001/XMLSchema-instance'
    ) do
      xml.OperationType 'ShutdownRoleOperation'
      xml.PostShutdownAction 'StoppedDeallocated'
    end
  end
  builder.doc.to_xml
end

.start_virtual_machine_to_xmlObject



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/azure/virtual_machine_management/serialization.rb', line 35

def self.start_virtual_machine_to_xml
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.StartRoleOperation(
      'xmlns' => 'http://schemas.microsoft.com/windowsazure',
      'xmlns:i' => 'http://www.w3.org/2001/XMLSchema-instance'
    ) do
      xml.OperationType 'StartRoleOperation'
    end
  end
  builder.doc.to_xml
end

.tcp_endpoints_to_xml(xml, tcp_endpoints, existing_ports = []) ⇒ Object



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
# File 'lib/azure/virtual_machine_management/serialization.rb', line 227

def self.tcp_endpoints_to_xml(xml, tcp_endpoints, existing_ports = [])
  endpoints = []

  tcp_endpoints.split(',').each do |endpoint|
    ports = endpoint.split(':')
    tcp_ep = {}

    if ports.length > 1
      port_already_opened?(existing_ports, ports[1])

      tcp_ep[:name] = "TCP-PORT-#{ports[1]}"
      tcp_ep[:public_port] = ports[1]
    else
      port_already_opened?(existing_ports, ports[0])

      tcp_ep[:name] = "TCP-PORT-#{ports[0]}"
      tcp_ep[:public_port] = ports[0]
    end

    tcp_ep[:local_port] = ports[0]
    tcp_ep[:protocol] = 'TCP'

    endpoints << tcp_ep
  end
  endpoints_to_xml(xml, endpoints)
end

.update_role_to_xml(endpoints, vm) ⇒ Object



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 'lib/azure/virtual_machine_management/serialization.rb', line 357

def self.update_role_to_xml(endpoints, vm)
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.PersistentVMRole(
      'xmlns' => 'http://schemas.microsoft.com/windowsazure',
      'xmlns:i' => 'http://www.w3.org/2001/XMLSchema-instance'
    ) do
      xml.ConfigurationSets do
        xml.ConfigurationSet do
          xml.ConfigurationSetType 'NetworkConfiguration'
          xml.InputEndpoints do
            endpoints_to_xml(xml, endpoints)
          end
          xml.SubnetNames do
            xml.SubnetName vm.subnet if vm.subnet
          end
          xml.StaticVirtualNetworkIPAddress vm.static_virtual_network_ipaddress if vm.static_virtual_network_ipaddress
        end
      end
      xml.OSVirtualHardDisk do
      end
    end
  end
  builder.doc.to_xml
end

.virtual_machines_from_xml(deployXML, cloud_service_name) ⇒ Object



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
# File 'lib/azure/virtual_machine_management/serialization.rb', line 254

def self.virtual_machines_from_xml(deployXML, cloud_service_name)
  unless deployXML.nil? or deployXML.at_css('Deployment Name').nil?
    instances = deployXML.css('Deployment RoleInstanceList RoleInstance')
    roles = deployXML.css('Deployment RoleList Role')
    ip = deployXML.css('Deployment VirtualIPs VirtualIP')
    vms = []
    instances.each do |instance|
      vm = VirtualMachine.new
      role_name = xml_content(instance, 'RoleName')
      vm.status = xml_content(instance, 'InstanceStatus')
      vm.vm_name = role_name
      vm.ipaddress = xml_content(ip, 'Address')
      vm.role_size = xml_content(instance, 'InstanceSize')
      vm.hostname = xml_content(instance, 'HostName')
      vm.cloud_service_name = cloud_service_name
      vm.deployment_name = xml_content(deployXML, 'Deployment Name')
      vm.deployment_status = xml_content(deployXML, 'Deployment Status')
      vm.virtual_network_name = xml_content(
        deployXML.css('Deployment'),
        'VirtualNetworkName'
      )
      roles.each do |role|
        if xml_content(role, 'RoleName') == role_name
          vm.availability_set_name = xml_content(role, 'AvailabilitySetName')
          endpoints_from_xml(role, vm)
          vm.data_disks = data_disks_from_xml(role)
          subnet = xml_content(role,
            'ConfigurationSets ConfigurationSet SubnetNames SubnetName'
          )
          vm.subnet = subnet unless subnet.empty?
          static_virtual_network_ipaddress =  xml_content(role,'ConfigurationSets ConfigurationSet StaticVirtualNetworkIPAddress')
          vm.static_virtual_network_ipaddress = static_virtual_network_ipaddress unless static_virtual_network_ipaddress.empty?
          vm.os_type = xml_content(role, 'OSVirtualHardDisk OS')
          vm.disk_name = xml_content(role, 'OSVirtualHardDisk DiskName')
          vm.media_link = xml_content(role, 'OSVirtualHardDisk MediaLink')
          vm.image = xml_content(role, 'OSVirtualHardDisk SourceImageName')
          break
        end
      end
      vms << vm
    end
    vms
  end
end