Class: Fog::Compute::Vsphere::Volume

Inherits:
Model
  • Object
show all
Defined in:
lib/fog/vsphere/models/compute/volume.rb

Constant Summary collapse

DISK_SIZE_TO_GB =
1048576

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Volume

Returns a new instance of Volume.



20
21
22
23
24
25
# File 'lib/fog/vsphere/models/compute/volume.rb', line 20

def initialize(attributes={} )
  # Assign server first to prevent race condition with persisted?
  self.server_id = attributes.delete(:server_id)

  super defaults.merge(attributes)
end

Instance Method Details

#destroyObject



39
40
41
42
43
44
# File 'lib/fog/vsphere/models/compute/volume.rb', line 39

def destroy
  requires :server_id, :key, :unit_number

  service.destroy_vm_volume(self)
  true
end

#saveObject

Raises:

  • (Fog::Errors::Error)


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/fog/vsphere/models/compute/volume.rb', line 46

def save
  raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted?
  requires :server_id, :size, :datastore

  if unit_number.nil?
    used_unit_numbers = server.volumes.map { |volume| volume.unit_number }
    max_unit_number = used_unit_numbers.max

    if max_unit_number > server.volumes.size
      # If the max ID exceeds the number of volumes, there must be a hole in the range. Find a hole and use it.
      self.unit_number = max_unit_number.times.to_a.find { |i| used_unit_numbers.exclude?(i) }
    else
      self.unit_number = max_unit_number + 1
    end
  else
    if server.volumes.any? { |volume| volume.unit_number == self.unit_number && volume.id != self.id }
      raise "A volume already exists with that unit_number, so we can't save the new volume"
    end
  end

  data = service.add_vm_volume(self)

  if data['task_state'] == 'success'
    # We have to query vSphere to get the volume attributes since the task handle doesn't include that info.
    created = server.volumes.all.find { |volume| volume.unit_number == self.unit_number }

    self.id = created.id
    self.key = created.key
    self.filename = created.filename

    true
  else
    false
  end
end

#serverObject



82
83
84
85
# File 'lib/fog/vsphere/models/compute/volume.rb', line 82

def server
  requires :server_id
  service.servers.get(server_id)
end

#size_gbObject



27
28
29
# File 'lib/fog/vsphere/models/compute/volume.rb', line 27

def size_gb
  attributes[:size_gb] ||= attributes[:size].to_i / DISK_SIZE_TO_GB if attributes[:size]
end

#size_gb=(s) ⇒ Object



31
32
33
# File 'lib/fog/vsphere/models/compute/volume.rb', line 31

def size_gb= s
  attributes[:size] = s.to_i * DISK_SIZE_TO_GB if s
end

#to_sObject



35
36
37
# File 'lib/fog/vsphere/models/compute/volume.rb', line 35

def to_s
  name
end