Project

General

Profile

« Previous | Next » 

Revision 651078df

Added by Michael Moll over 4 years ago

Fixes #29176 - Fix Style/MethodDefParentheses cop

View differences:

.rubocop_todo.yml
Style/MethodCallWithoutArgsParentheses:
Enabled: false
# Offense count: 70
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: require_parentheses, require_no_parentheses, require_no_parentheses_except_multiline
Style/MethodDefParentheses:
Enabled: false
# Offense count: 3
Style/MethodMissingSuper:
Enabled: false
lib/proxy/dependency_injection.rb
end
module Accessors
def inject_attr reference, local_var
def inject_attr(reference, local_var)
container = container_instance
define_method(local_var.to_sym) do
if instance_variable_get("@#{local_var}").nil?
lib/proxy/helpers.rb
# Accepts a html error code and a message, which is then returned to the caller after adding to the proxy log
# OR a block which is executed and its errors handled in a similar way.
# If no code is supplied when the block is declared then the html error used is 400.
def log_halt code=nil, exception_or_msg=nil, custom_msg=nil
def log_halt(code=nil, exception_or_msg=nil, custom_msg=nil)
message = exception_or_msg.to_s
message = "#{custom_msg}: #{message}" if custom_msg
exception = exception_or_msg.is_a?(Exception) ? exception_or_msg : Exception.new(exception_or_msg)
lib/proxy/kerberos.rb
require 'rkerberos'
module Proxy::Kerberos
def init_krb5_ccache keytab, principal
def init_krb5_ccache(keytab, principal)
krb5 = Kerberos::Krb5.new
ccache = Kerberos::Krb5::CredentialsCache.new
lib/proxy/validations.rb
class Error < RuntimeError; end
private
def valid_mac? mac
def valid_mac?(mac)
return false if mac.nil?
return true if mac =~ MAC_REGEXP_48BIT || mac =~ MAC_REGEXP_64BIT
false
end
# validates the ip address
def validate_ip ip
def validate_ip(ip)
raise Error, "Invalid IP Address #{ip}" unless ip =~ /(\d{1,3}\.){3}\d{1,3}/
ip
end
# validates the mac
def validate_mac mac
def validate_mac(mac)
raise Error, "Invalid MAC #{mac}" unless valid_mac?(mac)
mac.downcase
end
def validate_subnet subnet
def validate_subnet(subnet)
raise Error, "Invalid Subnet #{subnet}" unless subnet.is_a?(Proxy::DHCP::Subnet)
subnet
end
def validate_server server
def validate_server(server)
raise Proxy::DHCP::Error, "Invalid Server #{server}" unless server.is_a?(Proxy::DHCP::Server)
server
end
def validate_record record
def validate_record(record)
raise Proxy::DHCP::Error, "Invalid Record #{record}" unless record.is_a?(Proxy::DHCP::Record)
record
end
modules/dhcp_common/isc/configuration_parser.rb
# rubocop:enable Style/StructInheritance
class Literal < Rsec::Binary
def _parse ctx
def _parse(ctx)
buffer = StringIO.new
bs = false
end_of_string = false
......
end
end
def literal &p
def literal(&p)
Literal.new.map p
end
modules/dhcp_common/isc/omapi_provider.rb
om_disconnect("Removed DHCP reservation for #{record.name} => #{record}")
end
def add_record options = {}
def add_record(options = {})
record = super(options)
om_add_record(record)
record
......
output.map{|x| "omshell= #{x.chomp}"}.join("\n")
end
def report msg, response=""
def report(msg, response="")
logger.debug(format_omshell_output(response))
if response.nil? || (!response.empty? && !response.grep(/can't|no more|not connected|Syntax error/).empty?)
logger.error "Omshell failed: " + (response.nil? ? "Problem launching omshell" : format_omshell_output(response))
modules/dhcp_common/isc/subnet_service_initialization.rb
a_str
end
def hex2ip hex
def hex2ip(hex)
hex.split(":").map{|h| h.to_i(16).to_s}.join(".")
end
end
modules/dhcp_common/monkey_patch_subnet.rb
class Array
# Ruby1.8 doesn't have a rotate function, so we add our own...
def rotate n = 1
def rotate(n = 1)
return self if empty?
n %= length
self[n..-1]+self[0...n]
modules/dhcp_common/pingable.rb
require 'socket'
module Proxy::DHCP::Pingable
def tcp_pingable? ip
def tcp_pingable?(ip)
# This code is from net-ping, and stripped down for use here
# We don't need all the ldap dependencies net-ping brings in
......
true
end
def icmp_pingable? ip
def icmp_pingable?(ip)
# Always shell to ping, instead of using net-ping
if RUBY_PLATFORM =~ /mingw/
# Windows uses different options for ping and does not have /dev/null
modules/dhcp_common/record.rb
"#{ip} / #{mac}"
end
def [] opt
def [](opt)
options[opt.to_sym]
rescue
nil
modules/dhcp_common/record/reservation.rb
"#{name} (#{ip} / #{mac})"
end
def method_missing arg
def method_missing(arg)
options[arg]
end
modules/dhcp_common/server.rb
end
# Abstracted Subnet options loader method
def load_subnet_options subnet
def load_subnet_options(subnet)
logger.debug "Loading Subnet options for #{subnet}"
end
......
# like a HashWithIndifferentAccess to symbol and string keys.
# Delete keys with string names before adding them back with symbol names,
# otherwise there will be duplicate information.
def add_record options = {}
def add_record(options = {})
related_macs = options.delete("related_macs") || []
logger.debug "Ignoring duplicates for macs: #{related_macs.inspect}" unless related_macs.empty?
......
[name || hostname, ip, mac, subnet, options.merge!(:hostname => hostname || name)]
end
def vendor_options_included? options
def vendor_options_included?(options)
!options.keys.grep(/^</).empty?
end
modules/dhcp_common/subnet.rb
include Proxy::Validations
include Proxy::DHCP::Pingable
def initialize network, netmask, options = {}
def initialize(network, netmask, options = {})
@network = validate_ip network
@netmask = validate_ip netmask
@ipaddr = IPAddr.new(to_s)
......
@m = Monitor.new
end
def include? ip
def include?(ip)
if ip.is_a?(IPAddr)
ipaddr = ip
else
......
[::Proxy::DHCP.i_to_ipv4(range_start_address), ::Proxy::DHCP.i_to_ipv4(range_end_address)]
end
def <=> other
def <=>(other)
network <=> other.network
end
modules/dns_common/dns_common.rb
raise Proxy::Dns::NotFound.new("Cannot find DNS entry for #{value}")
end
def ptr_to_ip ptr
def ptr_to_ip(ptr)
if ptr =~ /\.in-addr\.arpa$/
ptr.split('.')[0..-3].reverse.join('.')
elsif ptr =~ /\.ip6\.arpa$/
......
record_conflicts_name(name, Resolv::DNS::Resource::IN::PTR, content)
end
def to_ipaddress ip
def to_ipaddress(ip)
logger.warn('Deprecated: Proxy::Dns::Record#to_ipaddress is deprecated and will be removed in 1.24')
IPAddr.new(ip) rescue false
end
modules/dns_dnscmd/dns_dnscmd_main.rb
nil
end
def execute cmd, msg=nil, error_only=false
def execute(cmd, msg=nil, error_only=false)
tsecs = 5
response = nil
interpreter = Proxy::SETTINGS.x86_64 ? 'c:\windows\sysnative\cmd.exe' : 'c:\windows\system32\cmd.exe'
......
response
end
def report msg, response, error_only
def report(msg, response, error_only)
if response.grep(/completed successfully/).empty?
logger.error "Command dnscmd failed:\n" + response.join("\n")
msg.sub!(/Removed/, "remove")
modules/dns_libvirt/dns_libvirt_main.rb
# libvirt does not support PTR
end
def find_ip_for_host host
def find_ip_for_host(host)
begin
doc = REXML::Document.new xml = libvirt_network.dump_xml
doc.elements.each("network/dns/host/hostname") do |e|
modules/dns_nsupdate/dns_nsupdate_main.rb
@om.close unless @om.nil? || @om.closed?
end
def nsupdate cmd
def nsupdate(cmd)
logger.debug "nsupdate: executed - #{cmd}"
@om.puts cmd
end
modules/libvirt_common/libvirt_network.rb
connection.lookup_network_by_name(@network)
end
def network_update command, section, xml
def network_update(command, section, xml)
flags = ::Libvirt::Network::NETWORK_UPDATE_AFFECT_LIVE | ::Libvirt::Network::NETWORK_UPDATE_AFFECT_CONFIG
logger.debug "Libvirt update: #{xml}"
find_network.update command, section, -1, xml, flags
modules/puppet_proxy_common/puppet_class.rb
module Proxy::Puppet
class PuppetClass
def initialize name, params = {}
def initialize(name, params = {})
@klass = name || raise("Must provide puppet class name")
@params = params
end
modules/puppetca_hostname_whitelisting/puppetca_hostname_whitelisting_autosigner.rb
end
# remove certname from autosign if exists
def disable certname
def disable(certname)
raise "No such file #{autosign_file}" unless File.exist?(autosign_file)
found = false
......
# add certname to puppet autosign file
# parameter is certname to use
def autosign certname, ttl
def autosign(certname, ttl)
FileUtils.touch(autosign_file) unless File.exist?(autosign_file)
open(autosign_file, File::RDWR) do |autosign|
modules/puppetca_puppet_cert/puppetca_impl.rb
include ::Proxy::Log
include ::Proxy::Util
def sign certname
def sign(certname)
puppetca("sign", certname)
end
def clean certname
def clean(certname)
puppetca("clean", certname)
end
......
end
# parse the puppetca --list output
def certificate str
def certificate(str)
case str
when /(\+|\-)\s+["]{0,1}(.*\w)["]{0,1}\s+\((\S+)\)/
state = ($1 == "-") ? "revoked" : "valid"
......
Set.new(OpenSSL::X509::CRL.new(crl_cert_contents).revoked.collect {|r| r.serial.to_i})
end
def puppetca mode, certname
def puppetca(mode, certname)
raise "Invalid mode #{mode}" unless mode =~ /^(clean|sign)$/
find_puppetca
certname.downcase!
modules/puppetca_token_whitelisting/puppetca_token_whitelisting_autosigner.rb
end
# Invalidate a token based on the certname
def disable certname
def disable(certname)
storage.remove_if do |token|
decoded = JWT.decode(token, smartproxy_cert.public_key, true, algorithm: JWT_ALGORITHM)
decoded.first['certname'] == certname
......
end
# Create a new token for a certname
def autosign certname, ttl
def autosign(certname, ttl)
ttl = (ttl.to_i > 0) ? ttl.to_i : token_ttl
payload = { certname: certname, exp: Time.now.to_i + ttl * 60 }
token = JWT.encode payload, smartproxy_cert, JWT_ALGORITHM
......
# Check whether a csr is valid and should be signed
# by checking its token if it exists
def validate_csr csr
def validate_csr(csr)
if csr.nil?
logger.warn "Request did not include a CSR."
return false
......
validate_token token
end
def validate_token token
def validate_token(token)
# token didnt expire?
begin
JWT.decode(token, smartproxy_cert.public_key, true, algorithm: JWT_ALGORITHM)
modules/puppetca_token_whitelisting/puppetca_token_whitelisting_token_storage.rb
include ::Proxy::Log
include ::Proxy::Util
def initialize tokens_file
def initialize(tokens_file)
@tokens_file = tokens_file
ensure_file
end
......
YAML.safe_load File.read @tokens_file
end
def write content
def write(content)
lock do
unsafe_write content
end
end
def unsafe_write content
def unsafe_write(content)
File.write @tokens_file, content.to_yaml
end
def lock &block
def lock(&block)
File.open(@tokens_file, "r+") do |f|
f.flock File::LOCK_EX
yield
......
end
end
def add entry
def add(entry)
write read.push entry
end
def remove entry
def remove(entry)
write read.delete_if { |data| data == entry }
end
def remove_if &block
def remove_if(&block)
lock do
unsafe_write read.delete_if { |token| yield(token) }
end
modules/realm_freeipa/provider.rb
ipa
end
def check_realm realm
def check_realm(realm)
raise Exception.new "Unknown realm #{realm}" unless realm.casecmp(ipa_config.realm).zero?
end
def find hostname
def find(hostname)
ipa_call("host_show", [hostname])
rescue XMLRPC::FaultException => e
if e.message =~ /not found/
......
end
end
def create realm, hostname, params
def create(realm, hostname, params)
check_realm realm
# Send params to FreeIPA, may want to send more than one in the future
......
ipa_call('host_add', [hostname], options)
end
def delete realm, hostname
def delete(realm, hostname)
check_realm realm
begin
result = ipa_call("host_del", [hostname], "updatedns" => remove_dns)
modules/tftp/server.rb
class Server
include Proxy::Log
# Creates TFTP pxeconfig file
def set mac, config
def set(mac, config)
raise "Invalid parameters received" if mac.nil? || config.nil?
pxeconfig_file(mac).each do |file|
write_file file, config
......
end
# Removes pxeconfig files
def del mac
def del(mac)
pxeconfig_file(mac).each do |file|
delete_file file
end
......
end
# Gets the contents of one of pxeconfig files
def get mac
def get(mac)
file = pxeconfig_file(mac).first
read_file(file)
end
# Creates a default menu file
def create_default config
def create_default(config)
raise "Default config not supplied" if config.nil?
pxe_default.each do |file|
write_file file, config
......
["#{pxeconfig_dir}/default"]
end
def pxeconfig_file mac
def pxeconfig_file(mac)
["#{pxeconfig_dir}/01-"+mac.tr(':', "-").downcase]
end
end
......
["#{pxeconfig_dir}/menu.lst", "#{pxeconfig_dir}/efidefault"]
end
def pxeconfig_file mac
def pxeconfig_file(mac)
["#{pxeconfig_dir}/menu.lst.01"+mac.delete(':').upcase, "#{pxeconfig_dir}/01-"+mac.tr(':', '-').upcase]
end
end
......
["#{pxeconfig_dir}/grub.cfg"]
end
def pxeconfig_file mac
def pxeconfig_file(mac)
["#{pxeconfig_dir}/grub.cfg-01-"+mac.tr(':', '-').downcase, "#{pxeconfig_dir}/grub.cfg-#{mac.downcase}"]
end
end
......
[pxeconfig_dir]
end
def pxeconfig_file mac
def pxeconfig_file(mac)
["#{pxeconfig_dir}/"+mac.delete(':').upcase, "#{pxeconfig_dir}/"+mac.delete(':').upcase+".cfg"]
end
end
......
[pxeconfig_dir]
end
def pxeconfig_file mac
def pxeconfig_file(mac)
["#{pxeconfig_dir}/"+mac.delete(':').upcase]
end
end
......
["#{pxeconfig_dir}/default.ipxe"]
end
def pxeconfig_file mac
def pxeconfig_file(mac)
["#{pxeconfig_dir}/01-"+mac.tr(':', "-").downcase+".ipxe"]
end
end
def self.fetch_boot_file dst, src
def self.fetch_boot_file(dst, src)
filename = boot_filename(dst, src)
destination = Pathname.new(File.expand_path(filename, Proxy::TFTP::Plugin.settings.tftproot)).cleanpath
tftproot = Pathname.new(Proxy::TFTP::Plugin.settings.tftproot).cleanpath
modules/tftp/tftp_api.rb
VARIANTS = ["Syslinux", "Pxelinux", "Pxegrub", "Pxegrub2", "Ztp", "Poap", "Ipxe"].freeze
helpers do
def instantiate variant, mac=nil
def instantiate(variant, mac=nil)
# Filenames must end in a hex representation of a mac address but only if mac is not empty
log_halt 403, "Invalid MAC address: #{mac}" unless valid_mac?(mac) || mac.nil?
log_halt 403, "Unrecognized pxeboot config type: #{variant}" unless VARIANTS.include?(variant.capitalize)
Object.const_get("Proxy").const_get('TFTP').const_get(variant.capitalize).new
end
def create variant, mac
def create(variant, mac)
tftp = instantiate variant, mac
log_halt(400, "TFTP: Failed to create pxe config file: ") {tftp.set(mac, (params[:pxeconfig] || params[:syslinux_config]))}
end
def delete variant, mac
def delete(variant, mac)
tftp = instantiate variant, mac
log_halt(400, "TFTP: Failed to delete pxe config file: ") {tftp.del(mac)}
end
def create_default variant
def create_default(variant)
tftp = instantiate variant
log_halt(400, "TFTP: Failed to create PXE default file: ") { tftp.create_default params[:menu]}
end
test/dhcp/isc_omapi_provider_test.rb
@input_commands = []
end
def puts str
def puts(str)
@input_commands << str
end
end

Also available in: Unified diff