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/**
- recipes/**
- spec/**
Excludes:
- libraries/**
Excludes:
- providers/**
- resources/**

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,3 +1,5 @@
# encoding: UTF-8
#
# Cookbook Name:: openstack-common
# library:: uri
@ -17,23 +19,23 @@
# limitations under the License.
#
require "uri"
require 'uri'
module ::Openstack
# Returns a uri::URI from a hash. If the hash has a "uri" key, the value
module ::Openstack # rubocop:disable Documentation
# 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
# 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.
def uri_from_hash hash
def uri_from_hash(hash)
if hash['uri']
::URI.parse hash['uri']
else
return nil unless hash['host']
scheme = hash['scheme'] ? hash['scheme'] : "http"
scheme = hash['scheme'] ? hash['scheme'] : 'http'
host = hash['host']
port = hash['port'] # 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
leadingslash = paths[0][0] == '/' ? '/' : ''
trailingslash = paths[-1][-1] == '/' ? '/' : ''
paths.map! { |path|
path = path.sub(/^\/+/,'').sub(/\/+$/,'')
}
paths.map! { |path| path.sub(/^\/+/, '').sub(/\/+$/, '') }
leadingslash + paths.join('/') + trailingslash
end
end

View File

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