Class: OpenstackController

Inherits:
Object
  • Object
show all
Defined in:
lib/process/cloud/providers/openstack/openstack.rb,
lib/process/cloud/providers/openstack/openstack.rb,
lib/process/cloud/providers/openstack/openstack_get.rb,
lib/process/cloud/providers/openstack/openstack_query.rb,
lib/process/cloud/providers/openstack/openstack_create.rb,
lib/process/cloud/providers/openstack/openstack_create.rb,
lib/process/cloud/providers/openstack/openstack_delete.rb,
lib/process/cloud/providers/openstack/openstack_update.rb,
lib/process/cloud/providers/openstack/openstack_refresh.rb

Overview

Defined Openstack object refresh.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.base_method(crud_type) ⇒ Object



306
307
308
309
310
311
312
313
314
315
316
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 306

def self.base_method(crud_type)
  define_method(crud_type) do |sObjectType, p1|
    method_name = "#{crud_type}_#{sObjectType}"
    if self.class.method_defined? method_name
      send(method_name, p1)
    else
      controller_error "'%s' is not a valid object for '%s'",
                       sObjectType, crud_type
    end
  end
end

.def_cruds(*crud_types) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 269

def self.def_cruds(*crud_types)
  crud_types.each do |crud_type|
    case crud_type
    when :create, :delete, :refresh
      base_method(crud_type)
    when :query, :get
      query_method(crud_type)
    when :update
      update_method(crud_type)
    end
  end
end

.def_get(connection, name, property_name = nil) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/process/cloud/providers/openstack/openstack_get.rb', line 19

def self.def_get(connection, name, property_name = nil)
  property_name = property_name.nil? ? "#{name}s" : property_name.to_s
  define_method("get_#{name}") do |hParams, sUniqId|
    required?(hParams, connection)
    hParams[connection].send(property_name).get(sUniqId)
  end
end

.def_query(requires, name, property_name = nil) ⇒ Object

Implementation of API NOT supporting query Hash The function will filter itself. It must support

  • Regexp

  • simple value equality



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/process/cloud/providers/openstack/openstack_query.rb', line 24

def self.def_query(requires, name, property_name = nil)
  property_name = property_name.nil? ? name.to_s + 's' : property_name.to_s

  define_method("query_#{name}") do |hParams, query|
    requires = [requires] unless requires.is_a?(Array)
    requires.each { |r| required?(hParams, r) }

    connection = requires[0]

    yield hParams, query if block_given?

    func = hParams[connection].send(property_name).method(:all)
    objects = _compat_query(func, __method__, query)
    # Uses :[] or :<key> to match object and query attr.
    Lorj.debug(4, "'%s' gets %d records", __method__, objects.length)
    ctrl_query_each objects, query # Return the select objects.
  end
end

.def_refresh(name) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/process/cloud/providers/openstack/openstack_refresh.rb', line 19

def self.def_refresh(name)
  define_method("refresh_#{name}") do |object|
    ret = false
    if object.class.method_defined?(:reload)
      begin
        object.reload
      rescue => e
        PrcLib.error("'%s': %s", object.class, e)
      else
        Lorj.debug(4, "'%s' refreshed '%s'", __method__, object.class)
        ret = true
      end
    end
    ret
  end
end

.query_method(crud_type) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 294

def self.query_method(crud_type)
  define_method(crud_type) do |sObjectType, sCondition, hParams|
    method_name = "#{crud_type}_#{sObjectType}"
    if self.class.method_defined? method_name
      send(method_name, hParams, sCondition)
    else
      controller_error "'%s' is not a valid object for '%s'",
                       sObjectType, crud_type
    end
  end
end

.update_method(crud_type) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 282

def self.update_method(crud_type)
  define_method(crud_type) do |sObjectType, obj, hParams|
    method_name = "#{crud_type}_#{sObjectType}"
    if self.class.method_defined? method_name
      send(method_name, obj, hParams)
    else
      controller_error "'%s' is not a valid object for '%s'",
                       sObjectType, crud_type
    end
  end
end

Instance Method Details

#_compat_query(func, cur_method, query) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/process/cloud/providers/openstack/openstack_query.rb', line 43

def _compat_query(func, cur_method, query)
  # Ruby 1.9.2 introduce Method.parameters.
  if RUBY_VERSION < '1.9.2'
    Lorj.debug(4, "RUBY '%s': '%s' try Openstack API filter feature.",
               RUBY_VERSION, cur_method)
    begin
      objects = func.call ctrl_query_select(query, String)
    rescue
      Lorj.debug(4, "RUBY '%s': '%s' No filter parameter.",
                 RUBY_VERSION, cur_method)
      objects = func.call
    end
  else
    if func.parameters.length > 0
      Lorj.debug(4, "'%s' uses Openstack API filter feature.", cur_method)
      objects = func.call ctrl_query_select(query, String)
    else
      objects = func.call
    end
  end
  objects
end

#_get_instance_attr(oControlerObject, key) ⇒ Object



383
384
385
386
387
388
389
390
391
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 383

def _get_instance_attr(oControlerObject, key)
  if key[0] == :metadata &&
     oControlerObject.class == Fog::Compute::OpenStack::Server
    return (oControlerObject)
  end
  return nil if oControlerObject.send(key[0]).nil?
  return oControlerObject.send(key[0]) if key.length == 1
  oControlerObject.send(key[0]).rh_get(key[1..-1])
end

#_server_metadata_get(oControlerObject) ⇒ Object



373
374
375
376
377
378
379
380
381
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 373

def (oControlerObject)
  ret = {}
  oControlerObject..each do |m|
    k = m.attributes[:key]
    v = m.attributes[:value]
    ret[k] = v
  end
  ret
end

#addresses_all(hParams) ⇒ Object

:nodoc:



167
168
169
170
171
172
173
174
175
176
177
# File 'lib/process/cloud/providers/openstack/openstack_create.rb', line 167

def addresses_all(hParams)
  addresses = hParams[:compute_connection].addresses.all
  # Search for an available IP
  loop do
    addresses.each { |elem| return elem if elem.fixed_ip.nil? }
    # If no IP are available, create a new one.
    Lorj.debug(3, 'No more Free IP. Allocate a new one.')
    create_floating_ip(hParams)
    addresses.reload
  end
end

#build_result(version, body) ⇒ Object

Function to provide a wel formatted standard data, usable by openstack provider

  • args:

    • version: :v1, :v2 or :v3. Based on openstack authentication version

    • body: result of Internal Fog::OpenStack.retrieve_tokens_v?

  • returns:

    • Hash: Requires at least:

      • :service_catalog : Hash of services available.



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 473

def build_result(version, body)
  case version
  when :v1 # Not supported
    { :service_catalog => {} }
  when :v2 #
    {
      :auth_token => body['access']['token']['id'],
      :expires => body['access']['token']['expires'],
      :service_catalog =>
          get_service_catalog(body['access']['serviceCatalog']),
      :endpoint_url => nil,
      :cdn_endpoint_url => nil
    }
  when :v3 # body is an Array: 0 is the body, and 1 is the header
    {
      :auth_token => body[1]['X-Subject-Token'],
      :expires => body[0]['token']['expires'],
      :service_catalog =>
          get_service_catalog(body[0]['token']['catalog']),
      :endpoint_url => nil,
      :cdn_endpoint_url => nil
    }
  end
end

#connect(sObjectType, hParams) ⇒ Object



321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 321

def connect(sObjectType, hParams)
  case sObjectType
  when :services
    get_services(hParams)
  when :compute_connection
    Fog::Compute.new(
      hParams[:hdata].merge(:provider => :openstack)
    )
  when :network_connection
    Fog::Network::OpenStack.new(hParams[:hdata])
  else
    controller_error "'%s' is not a valid object for 'connect'", sObjectType
  end
end

#create_floating_ip(params) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/process/cloud/providers/openstack/openstack_create.rb', line 179

def create_floating_ip(params)
  required?(params, :network_connection)
  required?(params, :external_network)

  network = params[:network_connection]
  ext_net = params[:external_network]

  # Create a new public IP to add in the pool.
  begin
    network.floating_ips.create(:floating_network_id => ext_net.id)
  rescue => e
    controller_error('Unable to get a new floating IP. %s', e)
  end
end

#create_keypairs(hParams) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
# File 'lib/process/cloud/providers/openstack/openstack_create.rb', line 79

def create_keypairs(hParams)
  required?(hParams, :compute_connection)
  required?(hParams, 'credentials#keypair_name')
  required?(hParams, :public_key)

  # API:
  # https://github.com/fog/fog/blob/master/lib/fog/openstack/docs/compute.md
  service = hParams[:compute_connection]
  service.key_pairs.create(:name => hParams['credentials#keypair_name'],
                           :public_key => hParams[:public_key])
end

#create_network(hParams) ⇒ Object



30
31
32
33
34
35
# File 'lib/process/cloud/providers/openstack/openstack_create.rb', line 30

def create_network(hParams)
  required?(hParams, :network_connection)
  required?(hParams, :network_name)

  hParams[:network_connection].networks.create(hParams[:hdata])
end

#create_public_ip(hParams) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
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
# File 'lib/process/cloud/providers/openstack/openstack_create.rb', line 119

def create_public_ip(hParams)
  required?(hParams, :compute_connection)
  required?(hParams, :server)

  compute_connect = hParams[:compute_connection]
  server = hParams[:server]

  Lorj.debug(3, "Waiting for server '%s' to become ready...", server.name)
  until server.ready?
    sleep(5)
    server = compute_connect.servers.get(server.id)

    if server.state == 'Error'
      controller_error('Unable to assign a Public IP to a server '\
                       "in error '%s'", server.name)
    end
  end

  # if 2 processes run in // to allocate a floating to different server
  # openstack can re-allocate and the last who set the server win.
  # So, we need to set it, and wait to see if the allocation is confirmed
  # To the current server.
  # This is required as there is no guarantee who did the last allocation
  # of this IP.
  # This should reduce strongly the risk but not completely.
  # The best approach is that openstack MUST required to disassociate before
  # associate...
  # And if the second want to do the same, an error should be reported and
  # a retry to be spawned.
  address = nil
  loop do
    address = addresses_all(hParams)
    Lorj.debug(5, "Trying to associate '%s' to '%s'.",
               address.ip, server.name)

    address.server = server # associate the server
    sleep(1 + rand(3))
    address.reload
    break if address.instance_id == server.id
  end
  Lorj.debug(4, "'%s' is confirmed to be associated to '%s'.",
             address.ip, server.name)
  address
end

#create_router(hParams) ⇒ Object



56
57
58
59
60
61
62
63
64
65
# File 'lib/process/cloud/providers/openstack/openstack_create.rb', line 56

def create_router(hParams)
  required?(hParams, :network_connection)
  required?(hParams, :router_name)

  # Forcelly used admin_status_up to true. Coming from HPCloud.
  # But not sure if we need it or not.
  #  hParams[:hdata] = hParams[:hdata].merge(:admin_state_up => true)

  hParams[:network_connection].routers.create(hParams[:hdata])
end

#create_router_interface(hParams) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/process/cloud/providers/openstack/openstack_create.rb', line 67

def create_router_interface(hParams)
  required?(hParams, :network_connection)
  required?(hParams, :router)
  required?(hParams, :subnetwork)

  service = hParams[:network_connection]
  router = hParams[:router]
  result = service.add_router_interface(router.id, hParams[:subnetwork].id)
  fail if result.status != 200
  result
end

#create_rule(hParams) ⇒ Object



50
51
52
53
54
# File 'lib/process/cloud/providers/openstack/openstack_create.rb', line 50

def create_rule(hParams)
  required?(hParams, :network_connection)
  required?(hParams, :security_groups)
  hParams[:network_connection].security_group_rules.create(hParams[:hdata])
end

#create_security_groups(hParams) ⇒ Object



19
20
21
22
23
24
25
26
27
28
# File 'lib/process/cloud/providers/openstack/openstack_create.rb', line 19

def create_security_groups(hParams)
  required?(hParams, :network_connection)
  required?(hParams, :tenants)
  required?(hParams, :security_group)

  service = hParams[:network_connection]

  service.security_groups.create(:name => hParams[:security_group],
                                 :tenant_id => hParams[:tenants].id)
end

#create_server(hParams) ⇒ Object



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/process/cloud/providers/openstack/openstack_create.rb', line 91

def create_server(hParams)
  [:compute_connection, :image,
   :network, :flavor, :keypairs,
   :security_groups, :server_name].each do |required_param|
    required?(hParams, required_param)
  end

  options = {
    :name             => hParams[:server_name],
    :flavor_ref       => hParams[:flavor].id,
    :image_ref        => hParams[:image].id,
    :key_name         => hParams[:keypairs].name,
    :security_groups  => [hParams[:security_groups].name],
    :nics             => [{ :net_id => hParams[:network].id }]
  }

  if hParams[:user_data]
    options[:user_data_encoded] =
      Base64.strict_encode64(hParams[:user_data])
  end
  options[:metadata] = hParams[:meta_data] if hParams[:meta_data]

  compute_connect = hParams[:compute_connection]

  server = compute_connect.servers.create(options)
  compute_connect.servers.get(server.id) if server
end

#create_subnetwork(hParams) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/process/cloud/providers/openstack/openstack_create.rb', line 37

def create_subnetwork(hParams)
  required?(hParams, :network_connection)
  required?(hParams, :network)

  netconn = hParams[:network_connection]
  netconn.subnets.create(
    :network_id => hParams[:network].id,
    :name => hParams[:subnetwork_name],
    :cidr => get_next_subnet(netconn),
    :ip_version => '4'
  )
end

#delete_server(hParams) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/process/cloud/providers/openstack/openstack_delete.rb', line 19

def delete_server(hParams)
  required?(hParams, :compute_connection)
  required?(hParams, :server)

  compute_connect = hParams[:compute_connection]
  server = hParams[:server]

  compute_connect.servers.get(server.id).destroy
end

#get_attr(oControlerObject, key) ⇒ Object



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 355

def get_attr(oControlerObject, key)
  if oControlerObject.is_a?(Excon::Response)
    oControlerObject.data.rh_get(:body, key)
  else
    attributes = oControlerObject.attributes
    controller_error "attribute '%s' is unknown in '%s'."\
                     " Valid one are : '%s'",
                     key[0],
                     oControlerObject.class,
                     oControlerObject.class.attributes unless
                     oControlerObject.class.attributes.include?(key[0])
    return attributes.rh_get(key) if attributes.rh_exist?(key)
    _get_instance_attr(oControlerObject, key)
  end
rescue => e
  controller_error "==>Unable to map '%s'. %s", key, e.message
end

#get_next_subnet(oNetworkConnect) ⇒ Object



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
226
227
228
229
230
231
232
233
234
# File 'lib/process/cloud/providers/openstack/openstack_create.rb', line 194

def get_next_subnet(oNetworkConnect)
  subnet_values = []
  subnets = oNetworkConnect.subnets.all

  subnets.each do|s|
    subnet_values.push(s.cidr)
  end

  gap = false
  count = 0
  range_used = []
  new_subnet = 0
  new_cidr = ''

  subnet_values = subnet_values.sort!

  subnet_values.each do|value|
    range_used.push(value[5])
  end

  range_used.each do |n|
    if count.to_i == n.to_i
    else
    new_subnet = count
    gap = true
    break
    end
    count += 1
  end

  if gap
    new_cidr = format('10.0.%s.0/24', count)
  else
    max_value = range_used.max
    new_subnet = max_value.to_i + 1
    new_cidr  = format('10.0.%s.0/24', new_subnet)
  end
  new_cidr
rescue => e
  Logging.error("%s\n%s", e.message, e.backtrace.join("\n"))
end

#get_server_log(hParams, sUniqId) ⇒ Object



37
38
39
40
# File 'lib/process/cloud/providers/openstack/openstack_get.rb', line 37

def get_server_log(hParams, sUniqId)
  required?(hParams, :server)
  hParams[:server].console(sUniqId)
end

#get_service_catalog(body) ⇒ Object

Build service catalog at the following format:

:<type>:

'name': <name>
:<region> : <url>

where:

  • type : Can be :identity, :orchestration, :volume, …

  • name : Is the name of the service like ‘swift’, ‘heat’, ‘cinder’, …

  • region: Is the region name. Can be any string like ‘regionOne’

  • url : is the exposed url of that service

    like https://swift.company.com/v1/HOSP_...
    

It supports V2/V3 service auth response.



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 513

def get_service_catalog(body)
  fail 'Unable to parse service catalog.' unless body
  service_catalog = {}
  body.each do |s|
    type = s['type']
    next if type.nil?
    type = type.to_sym
    next if s['endpoints'].nil?
    service_catalog[type] = {}
    # V2/V3 auth output
    service_catalog[type]['name'] = s['name']
    parse_service_catalog_endpoint(s, type, service_catalog)
  end
  service_catalog
end

#get_services(hParams) ⇒ Object

function to return a well formatted data for list of services



437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 437

def get_services(hParams)
  # Fog use URI type for auth uri: URI.parse('credentials#auth_uri')
  # Convert openstack_auth_uri to type URI
  openstack_auth_url = hParams[:hdata][:openstack_auth_url]
  hParams[:hdata][:openstack_auth_uri] = URI.parse(openstack_auth_url)

  case openstack_auth_url
  when /v1(\.\d+)?/
    version = :v1
    body = Fog::OpenStack.retrieve_tokens_v1(hParams[:hdata],
                                             hParams[:excon_opts])
  when /v2(\.\d+)?/
    version = :v2
    body = Fog::OpenStack.retrieve_tokens_v2(hParams[:hdata],
                                             hParams[:excon_opts])
  when /v3(\.\d+)?/
    version = :v3
    body = Fog::OpenStack.retrieve_tokens_v3(hParams[:hdata],
                                             hParams[:excon_opts])
  else
    version = :v2
    body = Fog::OpenStack.retrieve_tokens_v2(hParams[:hdata],
                                             hParams[:excon_opts])
  end
  build_result(version, body)
end

#list_services(sObjectType, oParams) ⇒ Object

This function requires to return an Array of values or nil.



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 397

def list_services(sObjectType, oParams)
  case sObjectType
  when :services
    # oParams[sObjectType] will provide the controller object.
    # This one can be interpreted only by controller code,
    # except if controller declares how to map with this object.
    # Processes can deal only process mapped data.
    # Currently there is no services process function. No need to map.
    services = oParams[:services]
    if !oParams[:list_services].is_a?(Array)
      service_to_find = [oParams[:list_services]]
    else
      service_to_find = oParams[:list_services]
    end
    # Search for service. Ex: Can be :Networking or network. I currently do
    # not know why...
    search_services = services.rh_get(:service_catalog)
    service = nil
    service_to_find.each do |sServiceElem|
      if search_services.key?(sServiceElem)
        service = sServiceElem
        break
      end
    end

    controller_error 'Unable to find services %s',
                     service_to_find if service.nil?
    result = services.rh_get(:service_catalog, service).keys
    result.delete('name')
    result.each_index do |iIndex|
      result[iIndex] = result[iIndex].to_s if result[iIndex].is_a?(Symbol)
    end
    return result
  else
    controller_error "'%s' is not a valid object for 'list_services'",
                     sObjectType
  end
end

#parse_service_catalog_endpoint(s, type, service_catalog) ⇒ Object

function which read a list of endpoints of a service to extract the url

v2: Get ‘endpoints’[]/‘publicURL’ v3: Get ‘endpoints’[]/‘url’ if ‘endpoints’[]/‘interface’ == ‘public’



533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 533

def parse_service_catalog_endpoint(s, type, service_catalog)
  s['endpoints'].each do |ep|
    next if ep['region'].nil?

    if ep['interface'] == 'public' # V3 auth output
      service_catalog[type][ep['region'].to_sym] = ep['url']
      break
    end

    next if ep['publicURL'].nil? || ep['publicURL'].empty?
    # V2 auth output
    service_catalog[type][ep['region'].to_sym] = ep['publicURL']
    break
  end
end

#set_attr(oControlerObject, key, value) ⇒ Object



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/process/cloud/providers/openstack/openstack.rb', line 336

def set_attr(oControlerObject, key, value)
  if oControlerObject.is_a?(Excon::Response)
    controller_error "No set feature for '%s'", oControlerObject.class
  end

  attributes = oControlerObject.attributes

  controller_error "attribute '%s' is unknown in '%s'. Valid one are : '%s'",
                   key[0],
                   oControlerObject.class,
                   oControlerObject.class.attributes unless
                   oControlerObject.class.attributes.include?(key[0])

  attributes.rh_set(value, key)
rescue => e
  controller_error "Unable to map '%s' on '%s'. %s",
                   key, oControlerObject, e.message
end

#update_router(obj_to_save, _hParams) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/process/cloud/providers/openstack/openstack_update.rb', line 19

def update_router(obj_to_save, _hParams)
  router = obj_to_save[:object]
  # The optional external_gateway_info must be a The network_id for the
  # external gateway. It cannot be a Hash
  # See API : http://developer.openstack.org/api-ref-networking-v2.html
  router.external_gateway_info = router.external_gateway_info['network_id']
  # Save will restore the Hash.
  begin
    router.save
    true
  rescue => e
    Lorj.error "OpenStack: Router save error.\n%s\n%s",
               e.message, e.backtrace.join("\n")
    false
  end
end