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



479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/fog/compute/google/models/server.rb', line 479

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)


259
260
261
# File 'lib/fog/compute/google/models/server.rb', line 259

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)


269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/fog/compute/google/models/server.rb', line 269

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:



199
200
201
202
203
204
205
206
207
208
# File 'lib/fog/compute/google/models/server.rb', line 199

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)


291
292
293
294
295
296
297
298
299
300
# File 'lib/fog/compute/google/models/server.rb', line 291

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-9"
    }
  }
]

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

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



578
579
580
581
582
# File 'lib/fog/compute/google/models/server.rb', line 578

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



562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/fog/compute/google/models/server.rb', line 562

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


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

attribute :guest_accelerators, :aliases => "guestAccelerators"

#idFixnum

Returns:

  • (Fixnum)


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

attribute :id

#image_nameString

Return the source image of the server’s boot disk

Returns:

  • (String)

    image self link



185
186
187
188
189
190
191
192
193
# File 'lib/fog/compute/google/models/server.rb', line 185

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)


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

attribute :kind

#label_fingerprintString

Returns:

  • (String)


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

attribute :label_fingerprint, :aliases => "labelFingerprint"

#labelsHash<String,String>

Returns:

  • (Hash<String,String>)


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

attribute :labels

#machine_typeString

Returns:

  • (String)


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

attribute :machine_type, :aliases => "machineType"

#map_scopes(scopes) ⇒ Object



498
499
500
501
502
503
504
505
506
507
508
# File 'lib/fog/compute/google/models/server.rb', line 498

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)


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

attribute :metadata

#metadata_as_hHash<String, String>

Returns metadata items as a Hash.

Returns:

  • (Hash<String, String>)

    items



305
306
307
308
309
310
311
# File 'lib/fog/compute/google/models/server.rb', line 305

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

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

#min_cpu_platformString

Returns:

  • (String)


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

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


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

attribute :network_interfaces, :aliases => "networkInterfaces"

#private_ip_addressString

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

Returns:

  • (String)


240
241
242
# File 'lib/fog/compute/google/models/server.rb', line 240

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)


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

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)


449
450
451
# File 'lib/fog/compute/google/models/server.rb', line 449

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)


214
215
216
# File 'lib/fog/compute/google/models/server.rb', line 214

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)


221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/fog/compute/google/models/server.rb', line 221

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)


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

def ready?
  status == "RUNNING"
end

#reboot(async = true) ⇒ Object



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

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



493
494
495
496
# File 'lib/fog/compute/google/models/server.rb', line 493

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

#reset_windows_password(user) ⇒ Object



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

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

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



510
511
512
513
514
515
516
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
# File 'lib/fog/compute/google/models/server.rb', line 510

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)


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

attribute :scheduling

Returns:

  • (String)


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

attribute :self_link, :aliases => "selfLink"

#serial_port_output(port: 1) ⇒ Object



346
347
348
349
350
# File 'lib/fog/compute/google/models/server.rb', line 346

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


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

attribute :service_accounts, :aliases => "serviceAccounts"

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



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/fog/compute/google/models/server.rb', line 352

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)


417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/fog/compute/google/models/server.rb', line 417

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’



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'lib/fog/compute/google/models/server.rb', line 397

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



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/fog/compute/google/models/server.rb', line 371

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



432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/fog/compute/google/models/server.rb', line 432

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)


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

def staging?
  status == "STAGING"
end

#start(async = true) ⇒ Object



324
325
326
327
328
329
330
331
332
333
# File 'lib/fog/compute/google/models/server.rb', line 324

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)


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

attribute :start_restricted, :aliases => "startRestricted"

#statusString

Returns:

  • (String)


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

attribute :status, :aliases => "status"

#status_messageString

Returns:

  • (String)


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

attribute :status_message, :aliases => "statusMessage"

#stop(async = true) ⇒ Object



335
336
337
338
339
340
341
342
343
344
# File 'lib/fog/compute/google/models/server.rb', line 335

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

  data = service.stop_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

#stopped?TrueClass or FalseClass

Check if instance is stopped.

Returns:

  • (TrueClass or FalseClass)


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

def stopped?
  status == "TERMINATED"
end

#tagsHash

Examples:

Tags in API format

Returns:

  • (Hash)


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

attribute :tags

#zoneString

Returns:

  • (String)


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

attribute :zone, :aliases => :zone_name

#zone_nameObject



475
476
477
# File 'lib/fog/compute/google/models/server.rb', line 475

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