Module: Fog::OpenStack

Extended by:
Provider
Defined in:
lib/fog/openstack.rb,
lib/fog/openstack/core.rb,
lib/fog/openstack/errors.rb,
lib/fog/openstack/version.rb,
lib/fog/planning/openstack.rb,
lib/fog/openstack/models/model.rb,
lib/fog/openstack/models/collection.rb,
lib/fog/planning/openstack/models/plan.rb,
lib/fog/planning/openstack/models/role.rb,
lib/fog/planning/openstack/models/plans.rb,
lib/fog/planning/openstack/models/roles.rb,
lib/fog/planning/openstack/requests/get_plan.rb,
lib/fog/planning/openstack/requests/list_plans.rb,
lib/fog/planning/openstack/requests/list_roles.rb,
lib/fog/planning/openstack/requests/patch_plan.rb,
lib/fog/planning/openstack/requests/create_plan.rb,
lib/fog/planning/openstack/requests/delete_plan.rb,
lib/fog/planning/openstack/requests/add_role_to_plan.rb,
lib/fog/planning/openstack/requests/get_plan_templates.rb,
lib/fog/planning/openstack/requests/remove_role_from_plan.rb

Defined Under Namespace

Modules: Core, Errors Classes: Collection, Model, Planning

Constant Summary collapse

VERSION =
'0.1.28'.freeze

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.token_cacheObject

Returns the value of attribute token_cache.



119
120
121
# File 'lib/fog/openstack.rb', line 119

def token_cache
  @token_cache
end

Class Method Details

.[](service) ⇒ Object

TODO: get rid of inconform self.[] & self.new & self.services



130
131
132
# File 'lib/fog/planning/openstack.rb', line 130

def self.[](service)
  new(:service => service)
end

.authenticate(options, connection_options = {}) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/fog/openstack.rb', line 126

def self.authenticate(options, connection_options = {})
  case options[:openstack_auth_uri].path
  when /v1(\.\d+)?/
    authenticate_v1(options, connection_options)
  when /v2(\.\d+)?/
    authenticate_v2(options, connection_options)
  when /v3(\.\d+)?/
    authenticate_v3(options, connection_options)
  else
    authenticate_v2(options, connection_options)
  end
end

.authenticate_v1(options, connection_options = {}) ⇒ Object

legacy v1.0 style auth



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/fog/openstack.rb', line 140

def self.authenticate_v1(options, connection_options = {})
  uri = options[:openstack_auth_uri]
  connection = Fog::Core::Connection.new(uri.to_s, false, connection_options)
  @openstack_api_key  = options[:openstack_api_key]
  @openstack_username = options[:openstack_username]

  response = connection.request({
    :expects  => [200, 204],
    :headers  => {
      'X-Auth-Key'  => @openstack_api_key,
      'X-Auth-User' => @openstack_username
    },
    :method   => 'GET',
    :path     =>  (uri.path and not uri.path.empty?) ? uri.path : 'v1.0'
  })

  return {
    :token => response.headers['X-Auth-Token'],
    :server_management_url => response.headers['X-Server-Management-Url'] || response.headers['X-Storage-Url'],
    :identity_public_endpoint => response.headers['X-Keystone']
  }
end

.authenticate_v2(options, connection_options = {}) ⇒ Object

Keystone Style Auth



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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
235
236
237
238
239
240
241
242
243
244
# File 'lib/fog/openstack.rb', line 164

def self.authenticate_v2(options, connection_options = {})
  uri                   = options[:openstack_auth_uri]
  tenant_name           = options[:openstack_tenant]
  service_type          = options[:openstack_service_type]
  service_name          = options[:openstack_service_name]
  identity_service_type = options[:openstack_identity_service_type]
  endpoint_type         = (options[:openstack_endpoint_type] || 'publicURL').to_s
  openstack_region      = options[:openstack_region]

  body = retrieve_tokens_v2(options, connection_options)
  service = get_service(body, service_type, service_name)

  options[:unscoped_token] = body['access']['token']['id']

  unless service
    unless tenant_name
      response = Fog::Core::Connection.new(
        "#{uri.scheme}://#{uri.host}:#{uri.port}/v2.0/tenants", false, connection_options).request({
        :expects => [200, 204],
        :headers => {'Content-Type' => 'application/json',
                     'Accept' => 'application/json',
                     'X-Auth-Token' => body['access']['token']['id']},
        :method  => 'GET'
      })

      body = Fog::JSON.decode(response.body)
      if body['tenants'].empty?
        raise Fog::Errors::NotFound.new('No Tenant Found')
      else
        options[:openstack_tenant] = body['tenants'].first['name']
      end
    end

    body = retrieve_tokens_v2(options, connection_options)
    service = get_service(body, service_type, service_name)

  end

  unless service
    available = body['access']['serviceCatalog'].map { |endpoint|
      endpoint['type']
    }.sort.join ', '

    missing = service_type.join ', '

    message = "Could not find service #{missing}.  Have #{available}"

    raise Fog::Errors::NotFound, message
  end

  service['endpoints'] = service['endpoints'].select do |endpoint|
    endpoint['region'] == openstack_region
  end if openstack_region

  if service['endpoints'].empty?
    raise Fog::Errors::NotFound.new("No endpoints available for region '#{openstack_region}'")
  end if openstack_region

  regions = service["endpoints"].map{ |e| e['region'] }.uniq
  if regions.count > 1
    raise Fog::Errors::NotFound.new("Multiple regions available choose one of these '#{regions.join(',')}'")
  end

  identity_service = get_service(body, identity_service_type) if identity_service_type
  tenant = body['access']['token']['tenant']
  user = body['access']['user']

  management_url = service['endpoints'].find{|s| s[endpoint_type]}[endpoint_type]
  identity_url   = identity_service['endpoints'].find{|s| s['publicURL']}['publicURL'] if identity_service

  {
    :user                     => user,
    :tenant                   => tenant,
    :identity_public_endpoint => identity_url,
    :server_management_url    => management_url,
    :token                    => body['access']['token']['id'],
    :expires                  => body['access']['token']['expires'],
    :current_user_id          => body['access']['user']['id'],
    :unscoped_token           => options[:unscoped_token]
  }
end

.authenticate_v3(options, connection_options = {}) ⇒ Object

Keystone Style Auth



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/fog/openstack.rb', line 247

def self.authenticate_v3(options, connection_options = {})
  uri                   = options[:openstack_auth_uri]
  project_name          = options[:openstack_project_name]
  service_type          = options[:openstack_service_type]
  service_name          = options[:openstack_service_name]
  identity_service_type = options[:openstack_identity_service_type]
  endpoint_type         = map_endpoint_type(options[:openstack_endpoint_type] || 'publicURL')
  openstack_region      = options[:openstack_region]

  token, body = retrieve_tokens_v3 options, connection_options

  service = get_service_v3(body, service_type, service_name, openstack_region, options)

  options[:unscoped_token] = token

  unless service
    unless project_name
      request_body = {
          :expects => [200],
          :headers => {'Content-Type' => 'application/json',
                       'Accept' => 'application/json',
                       'X-Auth-Token' => token},
          :method => 'GET'
      }
      user_id = body['token']['user']['id']
      project_uri = uri.clone
      project_uri.path = uri.path.sub('/auth/tokens', "/users/#{user_id}/projects")
      project_uri_param = "#{project_uri.scheme}://#{project_uri.host}:#{project_uri.port}#{project_uri.path}"
      response = Fog::Core::Connection.new(project_uri_param, false, connection_options).request(request_body)

      projects_body = Fog::JSON.decode(response.body)
      if projects_body['projects'].empty?
        options[:openstack_domain_id] = body['token']['user']['domain']['id']
      else
        options[:openstack_project_id] = projects_body['projects'].first['id']
        options[:openstack_project_name] = projects_body['projects'].first['name']
        options[:openstack_domain_id] = projects_body['projects'].first['domain_id']
      end
    end

    token, body = retrieve_tokens_v3(options, connection_options)
    service = get_service_v3(body, service_type, service_name, openstack_region, options)
  end

  # If no identity endpoint is found, try the auth uri (slicing /auth/tokens)
  # It covers the case where identityv3 endpoint is not present in the catalog but we have to use it
  unless service
    if service_type.include? "identity"
      identity_uri = uri.to_s.sub('/auth/tokens', '')
      response = Fog::Core::Connection.new(identity_uri, false, connection_options).request({:method => 'GET'})
      if response.status == 200
        service = {
          "endpoints" => [{
             "url"       => identity_uri,
             "region"    => openstack_region,
             "interface" => endpoint_type
          }],
          "type"      => service_type,
          "name"      => service_name
        }
      end
    end
  end

  unless service
    available_services = body['token']['catalog'].map { |service|
      service['type']
    }.sort.join ', '

    available_regions = body['token']['catalog'].map { |service|
      service['endpoints'].map { |endpoint|
        endpoint['region']
      }.uniq
    }.uniq.sort.join ', '

    missing = service_type.join ', '

    message = "Could not find service #{missing}#{(' in region '+openstack_region) if openstack_region}."+
        " Have #{available_services}#{(' in regions '+available_regions) if openstack_region}"

    raise Fog::Errors::NotFound, message
  end

  service['endpoints'] = service['endpoints'].select do |endpoint|
    endpoint['region'] == openstack_region && endpoint['interface'] == endpoint_type
  end if openstack_region

  if service['endpoints'].empty?
    raise Fog::Errors::NotFound.new("No endpoints available for region '#{openstack_region}'")
  end if openstack_region

  regions = service["endpoints"].map { |e| e['region'] }.uniq
  if regions.count > 1
    raise Fog::Errors::NotFound.new("Multiple regions available choose one of these '#{regions.join(',')}'")
  end

  identity_service = get_service_v3(body, identity_service_type, nil, nil, :openstack_endpoint_path_matches => /\/v3/) if identity_service_type

  management_url = service['endpoints'].find { |e| e['interface']==endpoint_type }['url']
  identity_url = identity_service['endpoints'].find { |e| e['interface']=='public' }['url'] if identity_service

  if body['token']['project']
    tenant = body['token']['project']
  elsif body['token']['user']['project']
    tenant = body['token']['user']['project']
  end

  return {
      :user                     => body['token']['user']['name'],
      :tenant                   => tenant,
      :identity_public_endpoint => identity_url,
      :server_management_url    => management_url,
      :token                    => token,
      :expires                  => body['token']['expires_at'],
      :current_user_id          => body['token']['user']['id'],
      :unscoped_token           => options[:unscoped_token]
  }
end

.clear_token_cacheObject



122
123
124
# File 'lib/fog/openstack.rb', line 122

def self.clear_token_cache
  Fog::OpenStack.token_cache = {}
end

.endpoint_path_match?(endpoint, match_regex) ⇒ Boolean

Returns:

  • (Boolean)


541
542
543
# File 'lib/fog/openstack.rb', line 541

def self.endpoint_path_match?(endpoint, match_regex)
  match_regex.nil? || URI(endpoint['url']).path =~ match_regex
end

.endpoint_region?(endpoint, region) ⇒ Boolean

Returns:

  • (Boolean)


537
538
539
# File 'lib/fog/openstack.rb', line 537

def self.endpoint_region?(endpoint, region)
  region.nil? || endpoint['region'] == region
end

.escape(str, extra_exclude_chars = '') ⇒ Object

CGI.escape, but without special treatment on spaces



568
569
570
571
572
# File 'lib/fog/openstack.rb', line 568

def self.escape(str, extra_exclude_chars = '')
  str.gsub(/([^a-zA-Z0-9_.-#{extra_exclude_chars}]+)/) do
    '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
  end
end

.extract_version_from_body(body, supported_versions) ⇒ Object



604
605
606
607
608
609
610
611
612
613
614
615
# File 'lib/fog/openstack.rb', line 604

def self.extract_version_from_body(body, supported_versions)
  return nil if body['versions'].empty?
  versions = body['versions'].kind_of?(Array) ? body['versions'] : body['versions']['values']
  version = nil
  # order is important, preffered status should be first
  %w(CURRENT stable SUPPORTED DEPRECATED).each do |status|
    version = versions.find { |x| x['id'].match(supported_versions) && (x['status'] == status) }
    break if version
  end

  version
end

.get_service(body, service_type = [], service_name = nil) ⇒ Object



366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/fog/openstack.rb', line 366

def self.get_service(body, service_type=[], service_name=nil)
  if not body['access'].nil?
    body['access']['serviceCatalog'].find do |s|
      if service_name.nil? or service_name.empty?
        service_type.include?(s['type'])
      else
        service_type.include?(s['type']) and s['name'] == service_name
      end
    end
  elsif not body['token']['catalog'].nil?
    body['token']['catalog'].find do |s|
      if service_name.nil? or service_name.empty?
        service_type.include?(s['type'])
      else
        service_type.include?(s['type']) and s['name'] == service_name
      end
    end

  end
end

.get_service_v3(hash, service_type = [], service_name = nil, region = nil, options = {}) ⇒ Object



519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/fog/openstack.rb', line 519

def self.get_service_v3(hash, service_type=[], service_name=nil, region=nil, options={})

  # Find all services matching any of the types in service_type, filtered by service_name if it's non-nil
  services = hash['token']['catalog'].find_all do |s|
    if service_name.nil? or service_name.empty?
      service_type.include?(s['type'])
    else
      service_type.include?(s['type']) and s['name'] == service_name
    end
  end if hash['token']['catalog']

  # Filter the found services by region (if specified) and whether the endpoint path matches the given regex (e.g. /\/v3/)
  services.find do |s|
    s['endpoints'].any? { |ep| endpoint_region?(ep, region) && endpoint_path_match?(ep, options[:openstack_endpoint_path_matches])}
  end if services

end

.get_supported_microversion(supported_versions, uri, auth_token, connection_options = {}) ⇒ Object



562
563
564
565
# File 'lib/fog/openstack.rb', line 562

def self.get_supported_microversion(supported_versions, uri, auth_token, connection_options = {})
  supported_version = get_version(supported_versions, uri, auth_token, connection_options)
  supported_version['version'] if supported_version
end

.get_supported_version(supported_versions, uri, auth_token, connection_options = {}) ⇒ Object



545
546
547
548
549
550
551
# File 'lib/fog/openstack.rb', line 545

def self.get_supported_version(supported_versions, uri, auth_token, connection_options = {})
  supported_version = get_version(supported_versions, uri, auth_token, connection_options)
  version = supported_version['id'] if supported_version
  version_raise(supported_versions) if version.nil?

  version
end

.get_supported_version_path(supported_versions, uri, auth_token, connection_options = {}) ⇒ Object



553
554
555
556
557
558
559
560
# File 'lib/fog/openstack.rb', line 553

def self.get_supported_version_path(supported_versions, uri, auth_token, connection_options = {})
  supported_version = get_version(supported_versions, uri, auth_token, connection_options)
  link = supported_version['links'].find { |l| l['rel'] == 'self' } if supported_version
  path = URI.parse(link['href']).path if link
  version_raise(supported_versions) if path.nil?

  path.chomp '/'
end

.get_version(supported_versions, uri, auth_token, connection_options = {}) ⇒ Object



586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/fog/openstack.rb', line 586

def self.get_version(supported_versions, uri, auth_token, connection_options = {})
  version_cache = "#{uri}#{supported_versions}"
  return @version[version_cache] if @version && @version[version_cache]
  connection = Fog::Core::Connection.new("#{uri.scheme}://#{uri.host}:#{uri.port}", false, connection_options)
  response = connection.request(
    :expects => [200, 204, 300],
    :headers => {'Content-Type' => 'application/json',
                 'Accept'       => 'application/json',
                 'X-Auth-Token' => auth_token},
    :method  => 'GET'
  )

  body = Fog::JSON.decode(response.body)

  @version                = {} unless @version
  @version[version_cache] = extract_version_from_body(body, supported_versions)
end

.map_endpoint_type(type) ⇒ Object



574
575
576
577
578
579
580
581
582
583
584
# File 'lib/fog/openstack.rb', line 574

def self.map_endpoint_type type
  case type
    when "publicURL"
      "public"
    when "internalURL"
      "internal"
    when "adminURL"
      "admin"
  end

end

.new(attributes) ⇒ Object

Raises:

  • (ArgumentError)


134
135
136
137
138
139
140
141
142
# File 'lib/fog/planning/openstack.rb', line 134

def self.new(attributes)
  attributes = attributes.dup # Prevent delete from having side effects
  service = attributes.delete(:service).to_s.downcase.to_sym
  if services.include?(service)
    require "fog/#{service}/openstack"
    return Fog::OpenStack.const_get(service.to_s.capitalize).new(attributes)
  end
  raise ArgumentError, "Openstack has no #{service} service"
end

.retrieve_tokens_v2(options, connection_options = {}) ⇒ Object



387
388
389
390
391
392
393
394
395
396
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
# File 'lib/fog/openstack.rb', line 387

def self.retrieve_tokens_v2(options, connection_options = {})
  api_key           = options[:openstack_api_key].to_s
  username          = options[:openstack_username].to_s
  tenant_name       = options[:openstack_tenant].to_s
  auth_token        = options[:openstack_auth_token] || options[:unscoped_token]
  uri               = options[:openstack_auth_uri]
  omit_default_port = options[:openstack_auth_omit_default_port]

  identity_v2_connection = Fog::Core::Connection.new(uri.to_s, false, connection_options)
  request_body = {:auth => Hash.new}

  if auth_token
    request_body[:auth][:token] = {
      :id => auth_token
    }
  else
    request_body[:auth][:passwordCredentials] = {
      :username => username,
      :password => api_key
    }
  end
  request_body[:auth][:tenantName] = tenant_name if tenant_name

  request = {
    :expects => [200, 204],
    :headers => {'Content-Type' => 'application/json'},
    :body    => Fog::JSON.encode(request_body),
    :method  => 'POST',
    :path    => (uri.path and not uri.path.empty?) ? uri.path : 'v2.0'
  }
  request[:omit_default_port] = omit_default_port unless omit_default_port.nil?

  response = identity_v2_connection.request(request)

  Fog::JSON.decode(response.body)
end

.retrieve_tokens_v3(options, connection_options = {}) ⇒ Object



424
425
426
427
428
429
430
431
432
433
434
435
436
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/fog/openstack.rb', line 424

def self.retrieve_tokens_v3(options, connection_options = {})

  api_key           = options[:openstack_api_key].to_s
  username          = options[:openstack_username].to_s
  userid            = options[:openstack_userid]
  domain_id         = options[:openstack_domain_id]
  domain_name       = options[:openstack_domain_name]
  project_domain    = options[:openstack_project_domain]
  project_domain_id = options[:openstack_project_domain_id]
  user_domain       = options[:openstack_user_domain]
  user_domain_id    = options[:openstack_user_domain_id]
  project_name      = options[:openstack_project_name]
  project_id        = options[:openstack_project_id]
  auth_token        = options[:openstack_auth_token] || options[:unscoped_token]
  uri               = options[:openstack_auth_uri]
  omit_default_port = options[:openstack_auth_omit_default_port]
  cache_ttl         = options[:openstack_cache_ttl] || 0

  connection = Fog::Core::Connection.new(uri.to_s, false, connection_options)
  request_body = {:auth => {}}

  scope = {}

  if project_name || project_id
    scope[:project] = if project_id.nil? then
                        if project_domain || project_domain_id
                          {:name => project_name, :domain => project_domain_id.nil? ? {:name => project_domain} : {:id => project_domain_id}}
                        else
                          {:name => project_name, :domain => domain_id.nil? ? {:name => domain_name} : {:id => domain_id}}
                        end
                      else
                        {:id => project_id}
                      end
  elsif domain_name || domain_id
    scope[:domain] = domain_id.nil? ? {:name => domain_name} : {:id => domain_id}
  else
    # unscoped token
  end

  if auth_token
    request_body[:auth][:identity] = {
        :methods => %w{token},
        :token => {
            :id => auth_token
        }
    }
  else
    request_body[:auth][:identity] = {
        :methods => %w{password},
        :password => {
            :user => {
                :password => api_key
            }
        }
    }

    if userid
      request_body[:auth][:identity][:password][:user][:id] = userid
    else
      if user_domain || user_domain_id
        request_body[:auth][:identity][:password][:user].merge! :domain => user_domain_id.nil? ? {:name => user_domain} : {:id => user_domain_id}
      elsif domain_name || domain_id
        request_body[:auth][:identity][:password][:user].merge! :domain => domain_id.nil? ? {:name => domain_name} : {:id => domain_id}
      end
      request_body[:auth][:identity][:password][:user][:name] = username
    end

  end
  request_body[:auth][:scope] = scope unless scope.empty?

  path     = (uri.path and not uri.path.empty?) ? uri.path : 'v3'

  response, expires = Fog::OpenStack.token_cache[{:body => request_body, :path => path}] if cache_ttl > 0

  unless response && expires > Time.now
    request = {
      :expects => [201],
      :headers => {'Content-Type' => 'application/json'},
      :body    => Fog::JSON.encode(request_body),
      :method  => 'POST',
      :path    => path
    }
    request[:omit_default_port] = omit_default_port unless omit_default_port.nil?

    response = connection.request(request)
    if cache_ttl > 0
      cache = Fog::OpenStack.token_cache
      cache[{:body => request_body, :path => path}] = response, Time.now + cache_ttl
      Fog::OpenStack.token_cache = cache
    end
  end

  [response.headers["X-Subject-Token"], Fog::JSON.decode(response.body)]
end

.servicesObject



144
145
146
147
# File 'lib/fog/planning/openstack.rb', line 144

def self.services
  # Ruby 1.8.7 compatibility for select returning Array of Arrays (pairs)
  Hash[Fog.services.select { |_service, providers| providers.include?(:openstack) }].keys
end

.version_raise(supported_versions) ⇒ Object



617
618
619
620
# File 'lib/fog/openstack.rb', line 617

def self.version_raise(supported_versions)
  raise Fog::OpenStack::Errors::ServiceUnavailable,
        "OpenStack service only supports API versions #{supported_versions.inspect}"
end