Class: Fog::Compute::Google::Server

Inherits:
Server
  • Object
show all
Defined in:
lib/fog/compute/google/models/server.rb

Constant Summary collapse

GCE_SCOPE_ALIASES =
{
  "default" => %w(
    https://www.googleapis.com/auth/cloud.useraccounts.readonly
    https://www.googleapis.com/auth/devstorage.read_only
    https://www.googleapis.com/auth/logging.write
    https://www.googleapis.com/auth/monitoring.write
    https://www.googleapis.com/auth/pubsub
    https://www.googleapis.com/auth/service.management.readonly
    https://www.googleapis.com/auth/servicecontrol
    https://www.googleapis.com/auth/trace.append
  ),
  "bigquery" => ["https://www.googleapis.com/auth/bigquery"],
  "cloud-platform" => ["https://www.googleapis.com/auth/cloud-platform"],
  "compute-ro" => ["https://www.googleapis.com/auth/compute.readonly"],
  "compute-rw" => ["https://www.googleapis.com/auth/compute"],
  "datastore" => ["https://www.googleapis.com/auth/datastore"],
  "logging-write" => ["https://www.googleapis.com/auth/logging.write"],
  "monitoring" => ["https://www.googleapis.com/auth/monitoring"],
  "monitoring-write" => ["https://www.googleapis.com/auth/monitoring.write"],
  "service-control" => ["https://www.googleapis.com/auth/servicecontrol"],
  "service-management" => ["https://www.googleapis.com/auth/service.management.readonly"],
  "sql" => ["https://www.googleapis.com/auth/sqlservice"],
  "sql-admin" => ["https://www.googleapis.com/auth/sqlservice.admin"],
  "storage-full" => ["https://www.googleapis.com/auth/devstorage.full_control"],
  "storage-ro" => ["https://www.googleapis.com/auth/devstorage.read_only"],
  "storage-rw" => ["https://www.googleapis.com/auth/devstorage.read_write"],
  "taskqueue" => ["https://www.googleapis.com/auth/taskqueue"],
  "useraccounts-ro" => ["https://www.googleapis.com/auth/cloud.useraccounts.readonly"],
  "useraccounts-rw" => ["https://www.googleapis.com/auth/cloud.useraccounts"],
  "userinfo-email" => ["https://www.googleapis.com/auth/userinfo.email"]
}.freeze

Instance Method Summary collapse

Instance Method Details

#add_ssh_key(username, key, async = true) ⇒ Object



486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/fog/compute/google/models/server.rb', line 486

def add_ssh_key(username, key, async = true)
   = (username, key)

  data = service.(
    identity, zone_name, [:fingerprint], [:items]
  )

  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  reload
end

#addressesArray

Helper method that returns all of server’s ip addresses, both private and public.

Returns:

  • (Array)


266
267
268
# File 'lib/fog/compute/google/models/server.rb', line 266

def addresses
  private_ip_addresses + public_ip_addresses
end

#attach_disk(disk, async = true, attached_disk_options = {}) ⇒ Object

Attach a disk to a running server

Parameters:

  • disk (Object, String)

    disk object or a self-link

  • async (TrueClass) (defaults to: true)

    execute the api call asynchronously

  • options (Hash)

Returns:

  • (Object)


276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/fog/compute/google/models/server.rb', line 276

def attach_disk(disk, async = true, attached_disk_options = {})
  requires :identity, :zone

  if disk.is_a? Disk
    disk_obj = disk.get_attached_disk
  elsif disk.is_a? String
    disk_obj = service.disks.attached_disk_obj(disk, **attached_disk_options)
  end

  data = service.attach_disk(identity, zone_name, disk_obj)
  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  reload
end

#can_ip_forwardBoolean

Returns:

  • (Boolean)


10
# File 'lib/fog/compute/google/models/server.rb', line 10

attribute :can_ip_forward, :aliases => "canIpForward"

#cpu_platformString

Returns:

  • (String)


13
# File 'lib/fog/compute/google/models/server.rb', line 13

attribute :cpu_platform, :aliases => "cpuPlatform"

#creation_timestampString

Returns:

  • (String)


16
# File 'lib/fog/compute/google/models/server.rb', line 16

attribute :creation_timestamp, :aliases => "creationTimestamp"

#deletion_protectionBoolean

Returns:

  • (Boolean)


19
# File 'lib/fog/compute/google/models/server.rb', line 19

attribute :deletion_protection, :aliases => "deletionProtection"

#descriptionString

Returns:

  • (String)


22
# File 'lib/fog/compute/google/models/server.rb', line 22

attribute :description

#destroy(async = true) ⇒ Fog::Compute::Google::Operation

Destroy a server.

Parameters:

  • async (TrueClass) (defaults to: true)

    execute the command asynchronously

Returns:



206
207
208
209
210
211
212
213
214
215
# File 'lib/fog/compute/google/models/server.rb', line 206

def destroy(async = true)
  requires :name, :zone

  data = service.delete_server(name, zone_name)
  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  operation
end

#detach_disk(device_name, async = true) ⇒ Object

Detach disk from a running instance

Parameters:

  • device_name (Object)
  • async (TrueClass) (defaults to: true)


298
299
300
301
302
303
304
305
306
307
# File 'lib/fog/compute/google/models/server.rb', line 298

def detach_disk(device_name, async = true)
  requires :identity, :zone

  data = service.detach_disk(identity, zone, device_name)
  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  reload
end

#disksArray<Hash>

New disks may include :initialize_params before save.

Examples:

Minimal disks pre-creation:

[
  {
    :initialize_params => {
      :source_image => "projects/debian-cloud/global/images/family/debian-11"
    }
  }
]

disks post-creation:

[
  {
    :auto_delete => false,
    :boot => true,
    :device_name => "persistent-disk-0",
    :index => 0,
    :interface => "SCSI",
    :kind => "compute#attachedDisk",
    :licenses => ["https://www.googleapis.com/compute/v1/..."],
    :mode => "READ_WRITE",
    :source => "https://www.googleapis.com/compute/v1/.../mydisk",
    :type => "PERSISTENT"
  }
]

Returns:

  • (Array<Hash>)


51
# File 'lib/fog/compute/google/models/server.rb', line 51

attribute :disks

#display_deviceHash<String,Boolean>

Examples:

Enable the display device

{
  :enable_display => true
}

Returns:

  • (Hash<String,Boolean>)


58
# File 'lib/fog/compute/google/models/server.rb', line 58

attribute :display_device, :aliases => "displayDevice"

#ensure_key_comment(key, default_comment = "fog-user") ⇒ Object



585
586
587
588
589
# File 'lib/fog/compute/google/models/server.rb', line 585

def ensure_key_comment(key, default_comment = "fog-user")
  parts = key.strip.split
  parts << default_comment if parts.size < 3
  parts.join(" ")
end

#generate_ssh_key_metadata(username, key) ⇒ Object



569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# File 'lib/fog/compute/google/models/server.rb', line 569

def (username, key)
  if .nil?
    self. = Hash.new
  end
  [:items] = [] if [:items].nil?
   = Hash[[:items].map { |item| [item[:key], item[:value]] }]

  ssh_keys = ["ssh-keys"] || ["sshKeys"] || ""
  ssh_keys += "\n" unless ssh_keys.empty?
  ssh_keys += "#{username}:#{ensure_key_comment(key, username)}"

  ["ssh-keys"] = ssh_keys
  [:items] = ()
  
end

#guest_acceleratorsArray<Hash>

Examples:

Guest accelerators

[
  {
    :accelerator_count => 1,
    :accelerator_type => "...my/accelerator/type"
  }
]

Returns:

  • (Array<Hash>)


68
# File 'lib/fog/compute/google/models/server.rb', line 68

attribute :guest_accelerators, :aliases => "guestAccelerators"

#idFixnum

Returns:

  • (Fixnum)


71
# File 'lib/fog/compute/google/models/server.rb', line 71

attribute :id

#image_nameString

Return the source image of the server’s boot disk

Returns:

  • (String)

    image self link



192
193
194
195
196
197
198
199
200
# File 'lib/fog/compute/google/models/server.rb', line 192

def image_name
  boot_disk = disks.first
  unless boot_disk.is_a?(Disk)
    source = boot_disk[:source]
    match = source.match(%r{/zones/(.*)/disks/(.*)$})
    boot_disk = service.disks.get(match[2], match[1])
  end
  boot_disk.source_image.nil? ? nil : boot_disk.source_image
end

#kindString

Returns:

  • (String)


74
# File 'lib/fog/compute/google/models/server.rb', line 74

attribute :kind

#label_fingerprintString

Returns:

  • (String)


77
# File 'lib/fog/compute/google/models/server.rb', line 77

attribute :label_fingerprint, :aliases => "labelFingerprint"

#labelsHash<String,String>

Returns:

  • (Hash<String,String>)


80
# File 'lib/fog/compute/google/models/server.rb', line 80

attribute :labels

#machine_typeString

Returns:

  • (String)


83
# File 'lib/fog/compute/google/models/server.rb', line 83

attribute :machine_type, :aliases => "machineType"

#map_scopes(scopes) ⇒ Object



505
506
507
508
509
510
511
512
513
514
515
# File 'lib/fog/compute/google/models/server.rb', line 505

def map_scopes(scopes)
  return [] if scopes.nil?
  scopes.flat_map do |scope|
    if GCE_SCOPE_ALIASES.key? scope
      # Expand scope alias to list of related scopes
      GCE_SCOPE_ALIASES[scope]
    else
      [scope_url(scope)]
    end
  end
end

#metadataHash

If set initially before save, the expected format is the API format as shown below.

If you want to pass in a Hash, see #set_metadata. If you want to access the metadata items as a Hash, see #metadata_as_h.

Examples:

Metadata in API format


{
  :fingerprint => "...",
  :items => [
    { :key => "foo", :value => "bar" },
  ]
}

Returns:

  • (Hash)


101
# File 'lib/fog/compute/google/models/server.rb', line 101

attribute :metadata

#metadata_as_hHash<String, String>

Returns metadata items as a Hash.

Returns:

  • (Hash<String, String>)

    items



312
313
314
315
316
317
318
# File 'lib/fog/compute/google/models/server.rb', line 312

def 
  if .nil? || [:items].nil? || [:items].empty?
    return {}
  end

  Hash[[:items].map { |item| [item[:key], item[:value]] }]
end

#min_cpu_platformString

Returns:

  • (String)


104
# File 'lib/fog/compute/google/models/server.rb', line 104

attribute :min_cpu_platform, :aliases => "minCpuPlatform"

#network_interfacesArray<Hash>

Examples:

Network interfaces

[
  {
    :kind => "compute#networkInterface",
    :name => "nic0",
    :network => "https://www.googleapis.com/compute/v1/.../my-network/"
    :network_ip => "0.0.0.0",
    :subnetwork => "https://www.googleapis.com/compute/v1/.../my-subnetwork"
  }
],

Returns:

  • (Array<Hash>)


117
# File 'lib/fog/compute/google/models/server.rb', line 117

attribute :network_interfaces, :aliases => "networkInterfaces"

#private_ip_addressString

Helper method that returns the first private ip address of the instance.

Returns:

  • (String)


247
248
249
# File 'lib/fog/compute/google/models/server.rb', line 247

def private_ip_address
  private_ip_addresses.first
end

#private_ip_addressesArray

Helper method that returns all of server’s private ip addresses.

Returns:

  • (Array)


254
255
256
257
258
259
260
# File 'lib/fog/compute/google/models/server.rb', line 254

def private_ip_addresses
  addresses = []
  if network_interfaces.respond_to? :map
    addresses = network_interfaces.map { |nic| nic[:network_ip] }
  end
  addresses
end

#provisioning?TrueClass or FalseClass

Check if instance is provisioning. On staging vs. provisioning difference: cloud.google.com/compute/docs/instances/checking-instance-status

Returns:

  • (TrueClass or FalseClass)


456
457
458
# File 'lib/fog/compute/google/models/server.rb', line 456

def provisioning?
  status == "PROVISIONING"
end

#public_ip_addressString

Helper method that returns first public ip address needed for Fog::Compute::Server.ssh default behavior.

Returns:

  • (String)


221
222
223
# File 'lib/fog/compute/google/models/server.rb', line 221

def public_ip_address
  public_ip_addresses.first
end

#public_ip_addressesArray

Helper method that returns all of server’s public ip addresses.

Returns:

  • (Array)


228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/fog/compute/google/models/server.rb', line 228

def public_ip_addresses
  addresses = []
  if network_interfaces.respond_to? :flat_map
    addresses = network_interfaces.flat_map do |nic|
      if nic[:access_configs].respond_to? :each
        nic[:access_configs].select { |config| config[:name] == "External NAT" }
                            .map { |config| config[:nat_ip] }
      else
        []
      end
    end
  end
  addresses
end

#ready?TrueClass or FalseClass

Check if instance is ready.

Returns:

  • (TrueClass or FalseClass)


478
479
480
# File 'lib/fog/compute/google/models/server.rb', line 478

def ready?
  status == "RUNNING"
end

#reboot(async = true) ⇒ Object



320
321
322
323
324
325
326
327
328
329
# File 'lib/fog/compute/google/models/server.rb', line 320

def reboot(async = true)
  requires :identity, :zone

  data = service.reset_server(identity, zone_name)
  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  operation
end

#reloadObject



500
501
502
503
# File 'lib/fog/compute/google/models/server.rb', line 500

def reload
  data = service.get_server(name, zone_name).to_h
  merge_attributes(data)
end

#reset_windows_password(user) ⇒ Object



591
592
593
# File 'lib/fog/compute/google/models/server.rb', line 591

def reset_windows_password(user)
  service.reset_windows_password(:server => self, :user => user)
end

#save(username: nil, public_key: nil) ⇒ Object



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
# File 'lib/fog/compute/google/models/server.rb', line 517

def save(username: nil, public_key: nil)
  requires :name
  requires :machine_type
  requires :disks
  requires :zone

  (self.username, self.public_key) if self.public_key

  # XXX HACK This is a relic of 1.0 change that for some reason added those arguments
  # to `save` method. This is left in place to keep things backwards-compatible
  # TODO(2.0): Remove arguments from save
  (username, public_key) if public_key

  options = attributes.reject { |_, v| v.nil? }

  if service_accounts && service_accounts[0]
    service_accounts[0][:scopes] = map_scopes(service_accounts[0][:scopes])
    options[:service_accounts] = service_accounts
  end

  if attributes[:external_ip]
    if options[:network_interfaces].nil? || options[:network_interfaces].empty?
      options[:network_interfaces] = [
        {
          :network => "global/networks/#{GOOGLE_COMPUTE_DEFAULT_NETWORK}"
        }
      ]
    end

    # Add external IP as default access config if given
    options[:network_interfaces][0][:access_configs] = [
      {
        :name => "External NAT",
        :type => "ONE_TO_ONE_NAT",
        :nat_ip => attributes[:external_ip]
      }
    ]
  end

  if attributes[:network_ip]
    options[:network_interfaces][0][:network_ip] = attributes[:network_ip]
  end

  data = service.insert_server(name, zone_name, options)

  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? }
  reload
end

#schedulingHash

:automatic_restart => true,
:on_host_maintenance => "MIGRATE",
:preemptible=>false

Examples:

Scheduling object

Returns:

  • (Hash)


126
# File 'lib/fog/compute/google/models/server.rb', line 126

attribute :scheduling

Returns:

  • (String)


129
# File 'lib/fog/compute/google/models/server.rb', line 129

attribute :self_link, :aliases => "selfLink"

#serial_port_output(port: 1) ⇒ Object



353
354
355
356
357
# File 'lib/fog/compute/google/models/server.rb', line 353

def serial_port_output(port: 1)
  requires :identity, :zone

  service.get_server_serial_port_output(identity, zone_name, :port => port).to_h[:contents]
end

#service_accountsArray<Hash>

[

{
  :email => "[email protected]",
  :scopes => [],
}

]

Examples:

Service accounts in API format

Returns:

  • (Array<Hash>)


139
# File 'lib/fog/compute/google/models/server.rb', line 139

attribute :service_accounts, :aliases => "serviceAccounts"

#set_disk_auto_delete(auto_delete, device_name = nil, async = true) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/fog/compute/google/models/server.rb', line 359

def set_disk_auto_delete(auto_delete, device_name = nil, async = true)
  requires :identity, :zone

  if device_name.nil? && disks.count > 1
    raise ArgumentError.new("Device name is required if multiple disks are attached")
  end

  device_name ||= disks.first[:device_name]
  data = service.set_server_disk_auto_delete(
    identity, zone_name, auto_delete, device_name
  )

  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  reload
end

#set_machine_type(new_machine_type, async = true) ⇒ Object

Raises:

  • (Fog::Errors::Error)


424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/fog/compute/google/models/server.rb', line 424

def set_machine_type(new_machine_type, async = true)
  requires :identity, :zone

  raise Fog::Errors::Error.new("Instance must be stopped to change machine type") unless stopped?

  data = service.set_server_machine_type(
    identity, zone_name, new_machine_type
  )
  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  reload
end

#set_metadata(new_metadata = {}, async = true) ⇒ Object

Set an instance metadata

Parameters:

  • async (Bool) (defaults to: true)

    Perform the operation asyncronously

  • new_metadata (Hash) (defaults to: {})

    A new metadata object Format: => ‘bar’, ‘baz’=>‘foo’



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/fog/compute/google/models/server.rb', line 404

def ( = {}, async = true)
  requires :identity, :zone

  unless .is_a?(Hash)
    raise Fog::Errors::Error.new("Instance metadata should be a hash")
  end

  # If metadata is presented in {'foo' => 'bar', 'baz'=>'foo'}
   = .each.map { |k, v| { :key => k.to_s, :value => v.to_s } }

  data = service.(
    identity, zone_name, [:fingerprint], 
  )
  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  reload
end

#set_scheduling(async = true, on_host_maintenance: nil, automatic_restart: nil, preemptible: nil) ⇒ Object



378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/fog/compute/google/models/server.rb', line 378

def set_scheduling(async = true,
                   on_host_maintenance: nil,
                   automatic_restart: nil,
                   preemptible: nil)
  requires :identity, :zone
  data = service.set_server_scheduling(
    identity, zone_name,
    :on_host_maintenance => on_host_maintenance,
    :automatic_restart => automatic_restart,
    :preemptible => preemptible
  )

  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  reload
end

#set_tags(new_tags = [], async = true) ⇒ Object



439
440
441
442
443
444
445
446
447
448
449
450
# File 'lib/fog/compute/google/models/server.rb', line 439

def set_tags(new_tags = [], async = true)
  requires :identity, :zone

  data = service.set_server_tags(
    identity, zone_name, tags[:fingerprint], new_tags
  )
  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  reload
end

#staging?TrueClass or FalseClass

Check if instance is staging. On staging vs. provisioning difference: cloud.google.com/compute/docs/instances/checking-instance-status

Returns:

  • (TrueClass or FalseClass)


464
465
466
# File 'lib/fog/compute/google/models/server.rb', line 464

def staging?
  status == "STAGING"
end

#start(async = true) ⇒ Object



331
332
333
334
335
336
337
338
339
340
# File 'lib/fog/compute/google/models/server.rb', line 331

def start(async = true)
  requires :identity, :zone

  data = service.start_server(identity, zone_name)
  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  operation
end

#start_restrictedBoolean

Returns:

  • (Boolean)


142
# File 'lib/fog/compute/google/models/server.rb', line 142

attribute :start_restricted, :aliases => "startRestricted"

#statusString

Returns:

  • (String)


145
# File 'lib/fog/compute/google/models/server.rb', line 145

attribute :status, :aliases => "status"

#status_messageString

Returns:

  • (String)


148
# File 'lib/fog/compute/google/models/server.rb', line 148

attribute :status_message, :aliases => "statusMessage"

#stop(async = true, discard_local_ssd = false) ⇒ Object



342
343
344
345
346
347
348
349
350
351
# File 'lib/fog/compute/google/models/server.rb', line 342

def stop(async = true, discard_local_ssd=false)
  requires :identity, :zone

  data = service.stop_server(identity, zone_name, discard_local_ssd)
  operation = Fog::Compute::Google::Operations
              .new(:service => service)
              .get(data.name, data.zone)
  operation.wait_for { ready? } unless async
  operation
end

#stopped?TrueClass or FalseClass

Check if instance is stopped.

Returns:

  • (TrueClass or FalseClass)


471
472
473
# File 'lib/fog/compute/google/models/server.rb', line 471

def stopped?
  status == "TERMINATED"
end

#tagsHash

Examples:

Tags in API format

Returns:

  • (Hash)


152
# File 'lib/fog/compute/google/models/server.rb', line 152

attribute :tags

#zoneString

Returns:

  • (String)


155
# File 'lib/fog/compute/google/models/server.rb', line 155

attribute :zone, :aliases => :zone_name

#zone_nameObject



482
483
484
# File 'lib/fog/compute/google/models/server.rb', line 482

def zone_name
  zone.nil? ? nil : zone.split("/")[-1]
end