Class: Dcmgr::Models::Instance

Inherits:
AccountResource show all
Defined in:
lib/dcmgr/models/instance.rb

Overview

Model class for running virtual instance.

Defined Under Namespace

Modules: ValidationMethods Classes: HostError

Constant Summary collapse

RECENT_TERMED_PERIOD =

RECENT_TERMED_PERIOD=(60 * 15)

Dcmgr.conf.recent_terminated_instance_period

Constants inherited from BaseNew

BaseNew::LOCK_TABLES_KEY

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from AccountResource

#account

Methods inherited from BaseNew

Proxy, dataset, default_row_lock_mode=, install_data, install_data_hooks, unlock!, #with_timestamps?

Class Method Details

.entry_new(account, image, spec, params, &blk) ⇒ Object

Factory method for Models::Instance object. This method helps to set association values have to be set mandatry until initial save to the database.

Raises:

  • (ArgumentError)


367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/dcmgr/models/instance.rb', line 367

def self.entry_new(, image, spec, params, &blk)
  raise ArgumentError unless .is_a?(Account)
  raise ArgumentError unless image.is_a?(Image)
  raise ArgumentError unless spec.is_a?(InstanceSpec)
  # Mash is passed in some cases.
  raise ArgumentError unless params.class == ::Hash

  i = self.new &blk
  i. = .canonical_uuid
  i.image = image
  i.instance_spec = spec
  i.cpu_cores = spec.cpu_cores
  i.memory_size = spec.memory_size
  i.quota_weight = spec.quota_weight
  i.request_params = params.dup

  i
end

.lock!Object



340
341
342
343
344
345
346
347
348
# File 'lib/dcmgr/models/instance.rb', line 340

def self.lock!
  super()
  Image.lock!
  InstanceSpec.lock!
  InstanceNic.lock!
  Volume.lock!
  VolumeSnapshot.lock!
  IpLease.lock!
end

Instance Method Details

#add_nic(vif_template) ⇒ Object



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/dcmgr/models/instance.rb', line 280

def add_nic(vif_template)
  # Choose vendor ID of mac address.
  vendor_id = if vif_template[:vendor_id]
                vif_template[:vendor_id]
              elsif Dcmgr.conf.mac_address_vendor_id
                Dcmgr.conf.mac_address_vendor_id
              else
                MacLease.default_vendor_id(self.instance_spec.hypervisor)
              end
  m = MacLease.lease(vendor_id)
  nic = InstanceNic.new(:mac_addr=>m.mac_addr)
  nic.instance = self
  nic.device_index = vif_template[:index]
  nic.save
end

#archObject

Returns the architecture type of the image



272
273
274
# File 'lib/dcmgr/models/instance.rb', line 272

def arch
  self.image.arch
end

#before_destroyObject



119
120
121
122
123
124
125
126
127
128
129
# File 'lib/dcmgr/models/instance.rb', line 119

def before_destroy
  HostnameLease.filter(:account_id=>self., :hostname=>self.hostname).destroy
  self.instance_nic.each { |o| o.destroy }
  self.remove_all_security_groups
  self.volume.each { |v|
    v.instance_id = nil
    v.state = :available
    v.save
  }
  super
end

#before_saveObject



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
# File 'lib/dcmgr/models/instance.rb', line 91

def before_save
  if @update_hostname
    if new?
      HostnameLease.create(:account_id=>self.,
                           :hostname=>self.hostname)
    else
      orig = self.dup.refresh
      # do nothing if orig.hostname == self.hostname
      if orig.hostname != self.hostname
        
        orig_name = HostnameLease.filter(:account_id=>self.,
                                         :hostname=>orig.hostname).first
        orig_name.hostname = self.hostname
        orig_name.save
      end
    end
    @update_hostname = false
  end

  # sum() returns nil if there is no instance rows.
  lives_weight = self.class.filter(:account_id=>self.).lives.sum(:quota_weight) || 0.0
  unless lives_weight <= self..quota.instance_total_weight
    raise HostError, "Out of quota limit: #{self.}'s current weight capacity: #{lives_weight} (<= #{self..quota.instance_total_weight})"
  end

  super
end

#before_validationObject



84
85
86
87
88
89
# File 'lib/dcmgr/models/instance.rb', line 84

def before_validation
  self[:user_data] ||= ''
  self[:hostname] ||= self.uuid
  self[:hostname] = self[:hostname].downcase
  super
end

#configObject



276
277
278
# File 'lib/dcmgr/models/instance.rb', line 276

def config
  self.instance_spec.config
end

#deleteObject

override Sequel::Model#delete not to delete rows but to set delete flags.



133
134
135
136
137
138
# File 'lib/dcmgr/models/instance.rb', line 133

def delete
  self.terminated_at ||= Time.now
  self.state = :terminated if self.state != :terminated
  self.status = :offline if self.status != :offline
  self.save
end

#fqdn_hostnameObject



318
319
320
# File 'lib/dcmgr/models/instance.rb', line 318

def fqdn_hostname
  self.nic.first.fqdn_hostname
end

#hypervisorObject

Returns the hypervisor type for the instance.



267
268
269
# File 'lib/dcmgr/models/instance.rb', line 267

def hypervisor
  self.instance_spec.hypervisor
end

#ipsObject



314
315
316
# File 'lib/dcmgr/models/instance.rb', line 314

def ips
  self.instance_nic.map { |nic| nic.ip }
end

#join_security_group(security_group_uuids) ⇒ Object

Join this instance to the list of security group using group’s uuid.

Parameters:

  • security_group_uuids (String, Array)


298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/dcmgr/models/instance.rb', line 298

def join_security_group(security_group_uuids)
  security_group_uuids = [security_group_uuids] if security_group_uuids.is_a?(String)
  joined_group_uuids = self.security_groups.map { |security_group|
    security_group.canonical_uuid
  }
  target_group_uuids = security_group_uuids.uniq - joined_group_uuids.uniq
  target_group_uuids.uniq!

  target_group_uuids.map { |target_group_uuid|
    if sg = SecurityGroup[target_group_uuid]
      InstanceSecurityGroup.create(:instance_id => self.id,
                                   :security_group_id => sg.id)
    end
  }
end

#live?Boolean

Returns:

  • (Boolean)


350
351
352
# File 'lib/dcmgr/models/instance.rb', line 350

def live?
  self.terminated_at.nil?
end

#nat_fqdn_hostnameObject



322
323
324
# File 'lib/dcmgr/models/instance.rb', line 322

def nat_fqdn_hostname
  self.nic.first.nat_fqdn_hostname
end

#networksArray[Models::Network]

Retrieve all networks belong to this instance

Returns:



328
329
330
331
332
333
334
335
336
337
338
# File 'lib/dcmgr/models/instance.rb', line 328

def networks
  instance_nic.select { |nic|
    !nic.ip.nil?
  }.map { |nic|
    nic.ip.network
  }.group_by { |net|
    net.canonical_uuid
  }.values.map { |i|
    i.first
  }
end

#set_ssh_key_pair(ssh_key_pair) ⇒ Object

Raises:

  • (ArgumentError)


354
355
356
357
358
359
360
361
# File 'lib/dcmgr/models/instance.rb', line 354

def set_ssh_key_pair(ssh_key_pair)
  raise ArgumentError unless ssh_key_pair.is_a?(SshKeyPair)
  self.ssh_key_data = ssh_key_pair.to_hash
  # Do not copy private key.
  self.ssh_key_data.delete(:private_key)
  # TODO: remove ssh_key_pair_id column
  self.ssh_key_pair_id = ssh_key_pair.canonical_uuid
end

#to_api_documentObject

returns hash data for API response on GET instances/

{ :id=>

:cpu_cores
:memory_size
:image_id
:network => [{:network_name=>'nw-xxxxxxx', :ipaddr=>'111.111.111.111'}]
:volume => [{'uuid'=>{:guest_device_name=>,}]
:ssh_key_pair => 'xxxxx',
:security_groups => ['rule1', 'rule2']
:created_at
:state
:status
:vif => {'vif-xxxxx'=>{:ipv4=>{:address=>'8.8.8.8', :nat_address=>'9.9.9.9.9'}}}

}



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
226
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
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/dcmgr/models/instance.rb', line 201

def to_api_document
  h = {
    :id => canonical_uuid,
    :host_node   => self.host_node && self.host_node.canonical_uuid,
    :cpu_cores   => cpu_cores,
    :memory_size => memory_size,
    :arch        => spec.arch,
    :image_id    => image.canonical_uuid,
    :created_at  => self.created_at,
    :state => self.state,
    :status => self.status,
    :ssh_key_pair => nil,
    :network => [],
    :volume => [],
    :security_groups => self.security_groups.map {|n| n.canonical_uuid },
    :vif => [],
    :hostname => hostname,
    :ha_enabled => ha_enabled,
    :instance_spec_id => instance_spec.canonical_uuid,
  }
  if self.ssh_key_data
    h[:ssh_key_pair] = self.ssh_key_data[:uuid]
  end

  instance_nic.each { |vif|
    direct_lease_ds = vif.direct_ip_lease_dataset
    if direct_lease_ds.first
      outside_lease_ds = vif.nat_ip_lease_dataset

      h[:network] << {
        :network_name => vif.network.canonical_uuid,
        :ipaddr => direct_lease_ds.all.map {|lease| lease.ipv4 }.compact,
        :dns_name => vif.network.domain_name && self.fqdn_hostname,
        :nat_network_name => vif.nat_network && vif.nat_network.canonical_uuid,
        :nat_ipaddr => outside_lease_ds.all.map {|lease| lease.ipv4 }.compact,
        :nat_dns_name => vif.nat_network && vif.nat_network.domain_name && self.nat_fqdn_hostname,
      }
    end

    ent = {
      :vif_id=>vif.canonical_uuid,
    }
    direct_lease = direct_lease_ds.first
    if direct_lease.nil?
    else
      outside_lease = direct_lease.nat_outside_lease
      ent[:ipv4] = {
        :address=> direct_lease.ipv4,
        :nat_address => outside_lease.nil? ? nil : outside_lease.ipv4,
      }
    end
    h[:vif] << ent
  }

  self.volume.each { |v|
    h[:volume] << {
      :vol_id => v.canonical_uuid,
      :guest_device_name=>v.guest_device_name,
      :state=>v.state,
    }
  }

  h
end

#to_hashObject

dump column data as hash with details of associated models. this is for internal use.



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
# File 'lib/dcmgr/models/instance.rb', line 142

def to_hash
  h = super
  h.merge!({:user_data => user_data.to_s, # Sequel::BLOB -> String
             :runtime_config => self.runtime_config, # yaml -> hash
             :ssh_key_data => self.ssh_key_data, # yaml -> hash
             :image=>image.to_hash,
             :host_node=> (host_node.nil? ? nil : host_node.to_hash),
             :instance_nics=>instance_nic.map {|n| n.to_hash },
             :ips => instance_nic.map { |n| n.ip.map {|i| unless i.is_natted? then i.ipv4 else nil end} if n.ip }.flatten.compact,
             :nat_ips => instance_nic.map { |n| n.ip.map {|i| if i.is_natted? then i.ipv4 else nil end} if n.ip }.flatten.compact,
             :security_groups => self.security_groups.map {|n| n.canonical_uuid },
             :vif=>[],
          })
  h.merge!({:instance_spec=>instance_spec.to_hash}) unless instance_spec.nil?
  h[:volume]={}
  if self.volume
    self.volume.each { |v|
      h[:volume][v.canonical_uuid] = v.to_hash
    }
  end
  if self.instance_nic
    self.instance_nic.each { |vif|
      ent = vif.to_hash.merge({
        :vif_id=>vif.canonical_uuid,
      })
      direct_lease = vif.direct_ip_lease.first
      if direct_lease.nil?
      else
        outside_lease = direct_lease.nat_outside_lease
        ent[:ipv4] = {
          :network => vif.network.nil? ? nil : vif.network.to_hash,
          :address=> direct_lease.ipv4,
          :nat_network => vif.nat_network.nil? ? nil : vif.nat_network.to_hash,
          :nat_address => outside_lease.nil? ? nil : outside_lease.ipv4,
        }
      end
      h[:vif] << ent
    }
  end
  h
end

#validateObject



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
81
82
# File 'lib/dcmgr/models/instance.rb', line 54

def validate
  super
  # do not run validation if the row is maked as deleted.
  return true if self.terminated_at

  unless self.hostname =~ /\A[0-9a-z][0-9a-z\-]{0,31}\Z/
    errors.add(:hostname, "Invalid hostname syntax")
  end

  # uniqueness check for hostname
  if changed_columns.include?(:hostname)
    proc_test = lambda {
      unless ValidationMethods.hostname_uniqueness(self., self.hostname)
        errors.add(:hostname, "Duplicated hostname: #{self.hostname}")
      end
    }
    
    if new?
      proc_test.call
    else
      orig = self.dup.refresh
      # do nothing if orig.hostname == self.hostname
      if orig.hostname != self.hostname
        proc_test.call
      end
    end
    @update_hostname = true
  end
end