Update libraries to be rubocop compliant

- Update .rubocop.yml to include libraries/**
- Update libraries to be rubocop compliant
- Update recipes/default.rb to remove unrequired rubocop:disable

Addresses: blueprint rubocop-for-common
Change-Id: I12a86bec70d1b9127d3b7d52356441637253e4f1
This commit is contained in:
Andy McCrae 2014-01-28 11:27:54 +00:00
parent 0b40a0686b
commit 1d049e7076
9 changed files with 113 additions and 111 deletions

View File

@ -5,8 +5,8 @@ AllCops:
- attributes/** - attributes/**
- recipes/** - recipes/**
- spec/** - spec/**
Excludes:
- libraries/** - libraries/**
Excludes:
- providers/** - providers/**
- resources/** - resources/**

View File

@ -1,3 +1,5 @@
# encoding: UTF-8
# #
# Cookbook Name:: openstack-common # Cookbook Name:: openstack-common
# library:: default # library:: default
@ -22,11 +24,11 @@ module ::Openstack
# service's database and grant read/write access to the # service's database and grant read/write access to the
# given user and password. # given user and password.
# #
# A privileged "super user" and password is determined from the # A privileged 'super user' and password is determined from the
# underlying database cookbooks. For instance, if a MySQL database # underlying database cookbooks. For instance, if a MySQL database
# is used, the node["mysql"]["server_root_password"] is used along # is used, the node['mysql']['server_root_password'] is used along
# with the "root" (super)user. # with the 'root' (super)user.
def db_create_with_user service, user, pass def db_create_with_user(service, user, pass) # rubocop:disable CyclomaticComplexity, MethodLength
root_user_use_databag = node['openstack']['db']['root_user_use_databag'] root_user_use_databag = node['openstack']['db']['root_user_use_databag']
info = db service info = db service
if info if info
@ -35,37 +37,37 @@ module ::Openstack
type = info['db_type'] type = info['db_type']
db_name = info['db_name'] db_name = info['db_name']
case type case type
when "postgresql", "pgsql" when 'postgresql', 'pgsql'
include_recipe "database::postgresql" include_recipe 'database::postgresql'
db_prov = ::Chef::Provider::Database::Postgresql db_prov = ::Chef::Provider::Database::Postgresql
user_prov = ::Chef::Provider::Database::PostgresqlUser user_prov = ::Chef::Provider::Database::PostgresqlUser
super_user = "postgres" super_user = 'postgres'
if root_user_use_databag if root_user_use_databag
user_key = node['openstack']['db']['root_user_key'] user_key = node['openstack']['db']['root_user_key']
super_password = get_password "user", user_key super_password = get_password 'user', user_key
else else
super_password = node['postgresql']['password']['postgres'] super_password = node['postgresql']['password']['postgres']
end end
when "mysql" when 'mysql'
# we have to install the 'mysql' gem, otherwise the provider won't work # we have to install the 'mysql' gem, otherwise the provider won't work
include_recipe "database::mysql" include_recipe 'database::mysql'
db_prov = ::Chef::Provider::Database::Mysql db_prov = ::Chef::Provider::Database::Mysql
user_prov = ::Chef::Provider::Database::MysqlUser user_prov = ::Chef::Provider::Database::MysqlUser
super_user = "root" super_user = 'root'
if root_user_use_databag if root_user_use_databag
user_key = node['openstack']['db']['root_user_key'] user_key = node['openstack']['db']['root_user_key']
super_password = get_password "user", user_key super_password = get_password 'user', user_key
else else
super_password = node['mysql']['server_root_password'] super_password = node['mysql']['server_root_password']
end end
when "db2" when 'db2'
db2_database "create database" do db2_database 'create database' do
db_name db_name db_name db_name
action :create action :create
end end
db2_user "create database user" do db2_user 'create database user' do
db_user user db_user user
db_pass pass db_pass pass
db_name db_name db_name db_name
@ -78,10 +80,10 @@ module ::Openstack
end end
connection_info = { connection_info = {
:host => host, host: host,
:port => port.to_i, port: port.to_i,
:username => super_user, username: super_user,
:password => super_password password: super_password
} }
# create database # create database

View File

@ -1,3 +1,5 @@
# encoding: UTF-8
# #
# Cookbook Name:: openstack-common # Cookbook Name:: openstack-common
# library:: endpoints # library:: endpoints
@ -17,14 +19,14 @@
# limitations under the License. # limitations under the License.
# #
require "uri" require 'uri'
module ::Openstack module ::Openstack # rubocop:disable Documentation
# Shortcut to get the full URI for an endpoint. If the "uri" key isn't # Shortcut to get the full URI for an endpoint. If the 'uri' key isn't
# set in the endpoint hash, we use the ::Openstack.get_uri_from_mash # set in the endpoint hash, we use the ::Openstack.get_uri_from_mash
# library routine from the openstack-common cookbook to grab a URI object # library routine from the openstack-common cookbook to grab a URI object
# and construct the URI object from the endpoint parts. # and construct the URI object from the endpoint parts.
def endpoint name def endpoint(name)
ep = endpoint_for name ep = endpoint_for name
if ep && ep['uri'] if ep && ep['uri']
::URI.parse ::URI.encode(ep['uri']) ::URI.parse ::URI.encode(ep['uri'])
@ -34,7 +36,7 @@ module ::Openstack
end end
# Useful for iterating over the OpenStack endpoints # Useful for iterating over the OpenStack endpoints
def endpoints &block def endpoints(&block)
node['openstack']['endpoints'].each do | name, info | node['openstack']['endpoints'].each do | name, info |
block.call(name, info) block.call(name, info)
end end
@ -42,50 +44,51 @@ module ::Openstack
nil nil
end end
# Instead of specifying the verbose node["openstack"]["db"][service], # Instead of specifying the verbose node['openstack']['db'][service],
# this shortcut allows the simpler and shorter db(service), where # this shortcut allows the simpler and shorter db(service), where
# service is one of 'compute', 'image', 'identity', 'network', # service is one of 'compute', 'image', 'identity', 'network',
# and 'volume' # and 'volume'
def db service def db(service)
node['openstack']['db'][service] node['openstack']['db'][service]
rescue rescue
nil nil
end end
# Shortcut to get the SQLAlchemy DB URI for a named service # Shortcut to get the SQLAlchemy DB URI for a named service
def db_uri service, user, pass def db_uri(service, user, pass) # rubocop:disable MethodLength, CyclomaticComplexity
info = db(service) info = db(service)
if info if info
host = info['host'] host = info['host']
port = info['port'].to_s port = info['port'].to_s
type = info['db_type'] type = info['db_type']
name = info['db_name'] name = info['db_name']
if type == "pgsql" if type == 'pgsql'
# Normalize to the SQLAlchemy standard db type identifier # Normalize to the SQLAlchemy standard db type identifier
type = "postgresql" type = 'postgresql'
end end
case type case type
when "postgresql" when 'postgresql'
result = "#{type}://#{user}:#{pass}@#{host}:#{port}/#{name}" "#{type}://#{user}:#{pass}@#{host}:#{port}/#{name}"
when "mysql" when 'mysql'
result = "#{type}://#{user}:#{pass}@#{host}:#{port}/#{name}?charset=utf8" "#{type}://#{user}:#{pass}@#{host}:#{port}/#{name}?charset=utf8"
when "sqlite" when 'sqlite'
# SQLite uses filepaths not db name # SQLite uses filepaths not db name
# README(galstrom): 3 slashes is a relative path, 4 slashes is an absolute path # README(galstrom): 3 slashes is a relative path, 4 slashes is an absolute path
# example: info['path'] = 'path/to/foo.db' -- will return sqlite:///foo.db # example: info['path'] = 'path/to/foo.db' -- will return sqlite:///foo.db
# example: info['path'] = '/path/to/foo.db' -- will return sqlite:////foo.db # example: info['path'] = '/path/to/foo.db' -- will return sqlite:////foo.db
path = info['path'] path = info['path']
result = "sqlite:///#{path}" "sqlite:///#{path}"
when "db2" when 'db2'
result = "ibm_db_sa://#{user}:#{pass}@#{host}:#{port}/#{name}?charset=utf8" "ibm_db_sa://#{user}:#{pass}@#{host}:#{port}/#{name}?charset=utf8"
end end
end end
end end
private private
# Instead of specifying the verbose node["openstack"]["endpoints"][name],
# Instead of specifying the verbose node['openstack']['endpoints'][name],
# this shortcut allows the simpler and shorter endpoint(name) # this shortcut allows the simpler and shorter endpoint(name)
def endpoint_for name def endpoint_for(name)
node['openstack']['endpoints'][name] node['openstack']['endpoints'][name]
rescue rescue
nil nil

View File

@ -1,3 +1,5 @@
# encoding: UTF-8
# #
# Cookbook Name:: openstack-common # Cookbook Name:: openstack-common
# library:: address # library:: address
@ -23,12 +25,10 @@ module ::Openstack
# @param [String] interface The interface to query. # @param [String] interface The interface to query.
# @param [String] family The protocol family to use. # @param [String] family The protocol family to use.
# @return [String] The IPv4 address. # @return [String] The IPv4 address.
def address_for interface, family="inet" def address_for(interface, family = 'inet')
interface_node = node["network"]["interfaces"][interface]["addresses"] interface_node = node['network']['interfaces'][interface]['addresses']
interface_node.select do |address, data| interface_node.select do |address, data|
if data['family'] == family return address if data['family'] == family
return address
end
end end
end end
end end

View File

@ -1,3 +1,5 @@
# encoding: UTF-8
# #
# Cookbook Name:: openstack-common # Cookbook Name:: openstack-common
# library:: parse # library:: parse
@ -15,10 +17,8 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
#
module ::Openstack module ::Openstack
# The current state of (at least some) OpenStack CLI tools do not provide a # The current state of (at least some) OpenStack CLI tools do not provide a
# mechanism for outputting data in formats other than PrettyTable output. # mechanism for outputting data in formats other than PrettyTable output.
# Therefore this function is intended to parse PrettyTable output into a # Therefore this function is intended to parse PrettyTable output into a
@ -26,38 +26,33 @@ module ::Openstack
# into a single element array. # into a single element array.
# table - the raw PrettyTable output of the CLI command # table - the raw PrettyTable output of the CLI command
# output - array of hashes representing the data. # output - array of hashes representing the data.
def prettytable_to_array table def prettytable_to_array(table) # rubocop:disable MethodLength
ret = [] ret = []
return ret if table == nil return ret if table.nil?
indicies = [] indicies = []
(table.split(/$/).collect{|x| x.strip}).each { |line| (table.split(/$/).map { |x| x.strip }).each do |line|
unless line.start_with?('+--') or line.empty? unless line.start_with?('+--') || line.empty?
cols = line.split('|').collect{|x| x.strip} cols = line.split('|').map { |x| x.strip }
cols.shift cols.shift
if indicies == [] if indicies == []
indicies = cols indicies = cols
next next
end end
newobj = {} newobj = {}
cols.each { |val| cols.each { |val| newobj[indicies[newobj.length]] = val }
newobj[indicies[newobj.length]] = val
}
ret.push(newobj) ret.push(newobj)
end end
} end
# this kinda sucks, but some prettytable data comes # this kinda sucks, but some prettytable data comes
# as Property Value pairs. If this is the case, then # as Property Value pairs. If this is the case, then
# flatten it as expected. # flatten it as expected.
newobj = {} newobj = {}
if indicies == ['Property', 'Value'] if indicies == ['Property', 'Value']
ret.each { |x| ret.each { |x| newobj[x['Property']] = x['Value'] }
newobj[x['Property']] = x['Value']
}
[newobj] [newobj]
else else
ret ret
end end
end end
end end

View File

@ -1,3 +1,5 @@
# encoding: UTF-8
# #
# Cookbook Name:: openstack-common # Cookbook Name:: openstack-common
# library:: passwords # library:: passwords
@ -21,9 +23,9 @@ module ::Openstack
# Library routine that returns an encrypted data bag value # Library routine that returns an encrypted data bag value
# for a supplied string. The key used in decrypting the # for a supplied string. The key used in decrypting the
# encrypted value should be located at # encrypted value should be located at
# node["openstack"]["secret"]["key_path"]. # node['openstack']['secret']['key_path'].
# #
# Note that if node["openstack"]["developer_mode"] is true, # Note that if node['openstack']['developer_mode'] is true,
# then the value of the index parameter is just returned as-is. This # then the value of the index parameter is just returned as-is. This
# means that in developer mode, if a cookbook does this: # means that in developer mode, if a cookbook does this:
# #
@ -33,25 +35,23 @@ module ::Openstack
# end # end
# end # end
# #
# nova_password = secret "passwords", "nova" # nova_password = secret 'passwords', 'nova'
# #
# That means nova_password will == "nova". # That means nova_password will == 'nova'.
def secret bag_name, index def secret(bag_name, index)
if node["openstack"]["developer_mode"] return index if node['openstack']['developer_mode']
return index key_path = node['openstack']['secret']['key_path']
end
key_path = node["openstack"]["secret"]["key_path"]
::Chef::Log.info "Loading encrypted databag #{bag_name}.#{index} using key at #{key_path}" ::Chef::Log.info "Loading encrypted databag #{bag_name}.#{index} using key at #{key_path}"
secret = ::Chef::EncryptedDataBagItem.load_secret key_path secret = ::Chef::EncryptedDataBagItem.load_secret key_path
::Chef::EncryptedDataBagItem.load(bag_name, index, secret)[index] ::Chef::EncryptedDataBagItem.load(bag_name, index, secret)[index]
end end
# Ease-of-use/standarization routine that returns a service/database/user # Ease-of-use/standarization routine that returns a service/database/user
# password for a named OpenStack service/database/user. Accepts "user", # password for a named OpenStack service/database/user. Accepts 'user',
# "service" or "db" as the type. # 'service' or 'db' as the type.
def get_password type, key def get_password(type, key)
if ["db", "user", "service"].include?(type) if ['db', 'user', 'service'].include?(type)
secret node["openstack"]["secret"]["#{type}_passwords_data_bag"], key secret node['openstack']['secret']["#{type}_passwords_data_bag"], key
else else
::Chef::Log.error("Unsupported type for get_password: #{type}") ::Chef::Log.error("Unsupported type for get_password: #{type}")
end end

View File

@ -1,3 +1,4 @@
# encoding: UTF-8
# #
# Cookbook Name:: openstack-common # Cookbook Name:: openstack-common
# library:: search # library:: search
@ -22,66 +23,67 @@ module ::Openstack
# #
# @param [String] The role or recipe to be found. # @param [String] The role or recipe to be found.
# @return [Array] The matching result or an empty list. # @return [Array] The matching result or an empty list.
def search_for r, &block def search_for(r, &block) # rubocop:disable MethodLength
role_query = "(chef_environment:#{node.chef_environment} AND roles:#{r})" role_query = "(chef_environment:#{node.chef_environment} AND roles:#{r})"
recipe_query = "(chef_environment:#{node.chef_environment} AND recipes:#{r})".sub("::","\\:\\:") recipe_query = "(chef_environment:#{node.chef_environment} AND recipes:#{r})".sub('::', '\:\:')
query = "#{role_query} OR #{recipe_query}" query = "#{role_query} OR #{recipe_query}"
count = 1 count = 1
sum = 7 sum = 7
while count < sum do while count < sum
resp = search(:node, query, &block) resp = search(:node, query, &block)
if resp != nil break unless resp.nil?
break
end
sleep 2**count sleep 2**count
count += 1 count += 1
end end
resp ? resp : [] resp ? resp : []
end end
# Returns the value for ["openstack"]["memcached_servers"] when # Returns the value for ['openstack']['memcached_servers'] when
# set, otherwise will perform a search. # set, otherwise will perform a search.
# #
# @param [String] role The role to be found (optional). # @param [String] role The role to be found (optional).
# @return [Array] A list of memcached servers in format # @return [Array] A list of memcached servers in format
# '<ip>:<port>'. # '<ip>:<port>'.
def memcached_servers role="infra-caching" def memcached_servers(role = 'infra-caching') # rubocop:disable MethodLength
unless node['openstack']['memcached_servers'] if !node['openstack']['memcached_servers']
search_for(role).map do |n| search_for(role).map do |n|
listen = n['memcached']['listen'] listen = n['memcached']['listen']
port = n['memcached']['port'] || "11211" port = n['memcached']['port'] || '11211'
"#{listen}:#{port}" "#{listen}:#{port}"
end.sort end.sort
else else
node['openstack']['memcached_servers'].length != 0 ? if node['openstack']['memcached_servers'].length != 0
node['openstack']['memcached_servers'] : [] node['openstack']['memcached_servers']
else
[]
end
end end
end end
# Returns all rabbit servers. # Returns all rabbit servers.
# Uses the value for ["openstack"]["mq"]["servers"] when set, otherwise # Uses the value for ['openstack']['mq']['servers'] when set, otherwise
# will perform a search. # will perform a search.
# #
# @return [String] Rabbit servers joined by a comma in # @return [String] Rabbit servers joined by a comma in
# the format of '<ip>:<port>'. # the format of '<ip>:<port>'.
def rabbit_servers def rabbit_servers # rubocop:disable MethodLength
if node["openstack"]["mq"]["servers"] if node['openstack']['mq']['servers']
servers = node["openstack"]["mq"]["servers"] servers = node['openstack']['mq']['servers']
port = node["openstack"]["mq"]["port"] port = node['openstack']['mq']['port']
servers.map { |s| "#{s}:#{port}" }.join "," servers.map { |s| "#{s}:#{port}" }.join ','
else else
role = node["openstack"]["mq"]["server_role"] role = node['openstack']['mq']['server_role']
search_for(role).map do |n| search_for(role).map do |n|
# The listen attribute should be saved to the node # The listen attribute should be saved to the node
# in the wrapper cookbook. See the reference cookbook # in the wrapper cookbook. See the reference cookbook
# openstack-ops-messaging. # openstack-ops-messaging.
address = n["openstack"]["mq"]["listen"] address = n['openstack']['mq']['listen']
port = n["openstack"]["mq"]["port"] port = n['openstack']['mq']['port']
"#{address}:#{port}" "#{address}:#{port}"
end.sort.join "," end.sort.join ','
end end
end end
end end

View File

@ -1,3 +1,5 @@
# encoding: UTF-8
# #
# Cookbook Name:: openstack-common # Cookbook Name:: openstack-common
# library:: uri # library:: uri
@ -17,23 +19,23 @@
# limitations under the License. # limitations under the License.
# #
require "uri" require 'uri'
module ::Openstack module ::Openstack # rubocop:disable Documentation
# Returns a uri::URI from a hash. If the hash has a "uri" key, the value # Returns a uri::URI from a hash. If the hash has a 'uri' key, the value
# of that is returned. If not, then the routine attempts to construct # of that is returned. If not, then the routine attempts to construct
# the URI from other parts of the hash, notably looking for keys of # the URI from other parts of the hash, notably looking for keys of
# "host", "port", "scheme", and "path" to construct the URI. # 'host', 'port', 'scheme', and 'path' to construct the URI.
# #
# Returns nil if neither "uri" or "host" keys exist in the supplied # Returns nil if neither 'uri' or 'host' keys exist in the supplied
# hash. # hash.
def uri_from_hash hash def uri_from_hash(hash)
if hash['uri'] if hash['uri']
::URI.parse hash['uri'] ::URI.parse hash['uri']
else else
return nil unless hash['host'] return nil unless hash['host']
scheme = hash['scheme'] ? hash['scheme'] : "http" scheme = hash['scheme'] ? hash['scheme'] : 'http'
host = hash['host'] host = hash['host']
port = hash['port'] # Returns nil if missing, which is fine. port = hash['port'] # Returns nil if missing, which is fine.
path = hash['path'] # Returns nil if missing, which is fine. path = hash['path'] # Returns nil if missing, which is fine.
@ -48,9 +50,7 @@ module ::Openstack
return nil if paths.length == 0 return nil if paths.length == 0
leadingslash = paths[0][0] == '/' ? '/' : '' leadingslash = paths[0][0] == '/' ? '/' : ''
trailingslash = paths[-1][-1] == '/' ? '/' : '' trailingslash = paths[-1][-1] == '/' ? '/' : ''
paths.map! { |path| paths.map! { |path| path.sub(/^\/+/, '').sub(/\/+$/, '') }
path = path.sub(/^\/+/,'').sub(/\/+$/,'')
}
leadingslash + paths.join('/') + trailingslash leadingslash + paths.join('/') + trailingslash
end end
end end

View File

@ -27,9 +27,9 @@ when 'debian'
apt_components = node['openstack']['apt']['components'] apt_components = node['openstack']['apt']['components']
# Simple variable substitution for LSB codename and OpenStack release # Simple variable substitution for LSB codename and OpenStack release
apt_components.each do | comp | # rubocop:disable UselessAssignment apt_components.each do | comp |
comp = comp.gsub '%release%', node['openstack']['release'] comp.gsub! '%release%', node['openstack']['release']
comp = comp.gsub '%codename%', node['lsb']['codename'] comp.gsub! '%codename%', node['lsb']['codename']
end end
apt_repository 'openstack-ppa' do apt_repository 'openstack-ppa' do