Skip to content
This repository has been archived by the owner on Jan 29, 2022. It is now read-only.

Rubocop and travis #11

Merged
merged 42 commits into from
Nov 2, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
5cf299f
Rubocop: Fix Style/HashSyntax
alexjfisher Nov 2, 2017
3fa14e1
Rubocop: Fix Layout/SpaceAfterComma
alexjfisher Nov 2, 2017
3b55a70
Rubocop: Fix Style/BracesAroundHashParameters
alexjfisher Nov 2, 2017
4876054
Rubocop: Fix Layout/SpaceAroundOperators
alexjfisher Nov 2, 2017
826a40f
Rubocop: Fix Layout/SpaceInsideHashLiteralBraces
alexjfisher Nov 2, 2017
7537bfe
Rubocop: Fix Style/StringLiterals
alexjfisher Nov 2, 2017
7f46865
Rubocop: Fix Layout/IndentHash
alexjfisher Nov 2, 2017
d0802de
Rubocop: Fix Layout/SpaceBeforeBlockBraces & Layout/SpaceInsideBlockB…
alexjfisher Nov 2, 2017
7c680dd
Rubocop: Fix Layout/CaseIndentation
alexjfisher Nov 2, 2017
79fc006
Rubocop: Fix Layout/SpaceInsideParens
alexjfisher Nov 2, 2017
15d001d
Rubocop: Fix Style/RedundantParentheses
alexjfisher Nov 2, 2017
b1b3dd4
Rubocop: Fix Layout/MultilineOperationIndentation
alexjfisher Nov 2, 2017
08f639f
Rubocop: Fix Layout/SpaceInsideBrackets
alexjfisher Nov 2, 2017
dc67844
Rubocop: Fix Layout/ExtraSpacing
alexjfisher Nov 2, 2017
9d108be
Rubocop: Fix Lint/EndAlignment
alexjfisher Nov 2, 2017
beba7b6
Rubocop: Fix Lint/UselessAssignment
alexjfisher Nov 2, 2017
9a07be5
Rubocop: Fix Style/RedundantBegin
alexjfisher Nov 2, 2017
c332261
Rubocop: Fix Layout/TrailingBlankLines
alexjfisher Nov 2, 2017
974b3ab
Rubocop: Fix Style/PreferredHashMethods
alexjfisher Nov 2, 2017
d80433d
Rubocop: Fix Style/RegexpLiteral
alexjfisher Nov 2, 2017
db4bac5
Rubocop: Fix Style/SymbolArray
alexjfisher Nov 2, 2017
56a4b7b
Rubocop: Fix Style/NumericPredicate
alexjfisher Nov 2, 2017
0c5253d
Rubocop: Fix Style/RedundantReturn
alexjfisher Nov 2, 2017
281d26e
Rubocop: Fix Layout/AlignParameters
alexjfisher Nov 2, 2017
c99b4bd
Rubocop: Fix Style/ConditionalAssignment
alexjfisher Nov 2, 2017
d0c3396
Rubocop: Fix Style/AndOr
alexjfisher Nov 2, 2017
8d2d6a0
Rubocop: Fix Performance/Casecmp
alexjfisher Nov 2, 2017
7ab75db
Rubocop: Fix Style/CommentedKeyword
alexjfisher Nov 2, 2017
c372120
Rubocop: Fix Style/Proc
alexjfisher Nov 2, 2017
e3cfadc
Rubocop: Fix Gemspec/OrderedDependencies
alexjfisher Nov 2, 2017
5c3ed3b
Rubocop: Fix Style/UnlessElse
alexjfisher Nov 2, 2017
868c08c
Rubocop: Fix Style/CommentAnnotation
alexjfisher Nov 2, 2017
fcf182a
Rubocop: Fix Layout/SpaceAfterNot
alexjfisher Nov 2, 2017
71f7a96
Rubocop: Fix Style/IfInsideElse
alexjfisher Nov 2, 2017
1cf5baf
Rubocop: Fix Style/GuardClause
alexjfisher Nov 2, 2017
77f8020
Rubocop: Fix Metrics/LineLength
alexjfisher Nov 2, 2017
b91f7d3
Rubocop: Fix Style/DoubleNegation
alexjfisher Nov 2, 2017
db30f73
Rubocop: Fix Lint/RescueWithoutErrorClass
alexjfisher Nov 2, 2017
64d5fd4
Rubocop: Disable Style/Documentation for now
alexjfisher Nov 2, 2017
260e3d4
Rubocop: Disable Metrics/BlockLength for /payload
alexjfisher Nov 2, 2017
e99ee0b
Rubocop: Disable Style/RescueModifier in data_parsers.rb
alexjfisher Nov 2, 2017
b5ebee0
Enable travis/rubocop
alexjfisher Nov 2, 2017
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
AllCops:
TargetRubyVersion: 2.1
Exclude:
- 'vendor/**/*'

Metrics/LineLength:
Max: 140

Metrics/AbcSize:
Enabled: false

Metrics/CyclomaticComplexity:
Enabled: false

Metrics/MethodLength:
Enabled: false

Metrics/BlockLength:
Exclude:
- spec/**/*_spec.rb

Metrics/PerceivedComplexity:
Enabled: false

Metrics/ModuleLength:
Max: 175

Style/RegexpLiteral:
EnforcedStyle: percent_r
Enabled: True
27 changes: 27 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
sudo: false
language: ruby
cache: bundler
dist: trusty
before_install:
- bundle -v
- rm Gemfile.lock || true
- gem update --system
- gem update bundler
- bundle -v
script:
- 'bundle exec rake test'
rvm:
- 2.1.9
- 2.4.2
branches:
only:
- master
- /^v\d/
notifications:
email: false
irc:
on_success: always
on_failure: always
channels:
- "chat.freenode.org#voxpupuli-notifications"
8 changes: 8 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
desc 'Run all tests'
task test: %i[rubocop spec]

require 'rubocop/rake_task'
RuboCop::RakeTask.new

require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec)
6 changes: 3 additions & 3 deletions bin/puppet_webhook
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,16 @@ opts = {
ServerType: server_type,
ServerSoftware: settings.server_software,
SSLEnable: settings.enable_ssl,
StartCallBack: Proc.new { File.open(PIDFILE, 'w') { |f| f.write Process.pid } }
StartCallBack: proc { File.open(PIDFILE, 'w') { |f| f.write Process.pid } }
}

if settings.enable_ssl
opts[:SSLVerifyClient] = settings.verify_ssl
opts[:SSLCertificate] = OpenSSL::X509::Certificate.new(File.open(settings.public_key_path).read)
opts[:SSLPrivateKey] = OpenSSL::PKey::RSA.new(File.open(settings.private_key_path).read)
opts[:SSLCertName] = [ [ 'CN', WEBrick::Utils.getservername ] ]
opts[:SSLCertName] = [['CN', WEBrick::Utils.getservername]]
end

Rack::Handler::WEBrick.run(PuppetWebhook, opts) do |server|
[:INT, :TERM].each { |sig| trap(sig) { server.stop} }
%i[INT TERM].each { |sig| trap(sig) { server.stop } }
end
7 changes: 5 additions & 2 deletions lib/helpers/data_parsers.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
require 'shellwords'

module DataParsers
module DataParsers # rubocop:disable Style/Documentation
def sanitize_input(input_string)
sanitized = Shellwords.shellescape(input_string)
LOGGER.info("Module or Branch name #{sanitized} had to be escaped") unless input_string == sanitized
Expand All @@ -16,6 +16,8 @@ def verify_signature(payload_body)
throw(:halt, [500, "Signatures didn't match!\n"]) unless Rack::Utils.secure_compare(signature, request.env['HTTP_X_HUB_SIGNATURE'])
end

# rubocop:disable Style/RescueModifier
# TODO: Move the code from these methods to our parser class
def repo_name(data)
# Only tested with Github
# TODO: Extend for Bitbucket, Bitbucket Server, and Gitlab
Expand All @@ -27,4 +29,5 @@ def repo_user(data)
# TODO: Extend for Bitbucket, Bitbucket Server, and Gitlab
data['repository']['owner']['login'] rescue nil
end
end
# rubocop:enable Style/RescueModifier
end
92 changes: 43 additions & 49 deletions lib/helpers/deployments.rb
Original file line number Diff line number Diff line change
@@ -1,56 +1,50 @@
module Deployments
module Deployments # rubocop:disable Style/Documentation
def deploy(branch, deleted)
begin
if settings.use_mco_ruby
result = mco(branch).first
if result.results[:statuscode] == 0
message = result.results[:statusmsg]
else
raise result.results[:statusmsg]
end
else
if settings.use_mcollective
command = "#{COMMAND_PREFIX} mco r10k deploy #{branch} #{settings.mco_arguments}"
else
# If you don't use mcollective then this hook needs to be running as r10k's user i.e. root
command = "#{COMMAND_PREFIX} r10k deploy environment #{branch} #{settings.r10k_deploy_arguments}"
end
message = run_command(command)
end
status_message = { status: :success, message: message.to_s, branch: branch, status_code: 200 }
LOGGER.info("message: #{message} branch: #{branch}")
unless deleted
generate_types(branch) if types?
end
notify_slack(status_message) if slack?
status_message.to_json
rescue => e
status_message = {status: :fail, message: e.message, trace: e.backtrace, branch: branch, status_code: 500 }
LOGGER.error("message: #{e.message} trace: #{e.backtrace}")
status 500
notify_slack(status_message) if slack?
status_message.to_json
if settings.use_mco_ruby
result = mco(branch).first
raise result.results[:statusmsg] unless result.results[:statuscode].zero?

message = result.results[:statusmsg]
else
command = if settings.use_mcollective
"#{COMMAND_PREFIX} mco r10k deploy #{branch} #{settings.mco_arguments}"
else
# If you don't use mcollective then this hook needs to be running as r10k's user i.e. root
"#{COMMAND_PREFIX} r10k deploy environment #{branch} #{settings.r10k_deploy_arguments}"
end
message = run_command(command)
end
status_message = { status: :success, message: message.to_s, branch: branch, status_code: 200 }
LOGGER.info("message: #{message} branch: #{branch}")
unless deleted
generate_types(branch) if types?
end
notify_slack(status_message) if slack?
status_message.to_json
rescue StandardError => e
status_message = { status: :fail, message: e.message, trace: e.backtrace, branch: branch, status_code: 500 }
LOGGER.error("message: #{e.message} trace: #{e.backtrace}")
status 500
notify_slack(status_message) if slack?
status_message.to_json
end

def deploy_module(module_name)
begin
if settings.use_mcollective
command = "#{COMMAND_PREFIX} mco r10k deploy_module #{module_name} #{settings.mco_arguments}"
else
command = "#{COMMAND_PREFIX} r10k deploy module #{module_name}"
end
message = run_command(command)
LOGGER.info("message: #{message} module_name: #{module_name}")
status_message = { status: :success, message: message.to_s, module_name: module_name, status_code: 200 }
notify_slack(status_message) if slack?
status_message.to_json
rescue => e
LOGGER.error("message: #{e.message} trace: #{e.backtrace}")
status 500
status_message = { status: :fail, message: e.message, trace: e.backtrace, module_name: module_name, status_code: 500 }
notify_slack(status_message) if slack?
status_message.to_json
end
command = if settings.use_mcollective
"#{COMMAND_PREFIX} mco r10k deploy_module #{module_name} #{settings.mco_arguments}"
else
"#{COMMAND_PREFIX} r10k deploy module #{module_name}"
end
message = run_command(command)
LOGGER.info("message: #{message} module_name: #{module_name}")
status_message = { status: :success, message: message.to_s, module_name: module_name, status_code: 200 }
notify_slack(status_message) if slack?
status_message.to_json
rescue StandardError => e
LOGGER.error("message: #{e.message} trace: #{e.backtrace}")
status 500
status_message = { status: :fail, message: e.message, trace: e.backtrace, module_name: module_name, status_code: 500 }
notify_slack(status_message) if slack?
status_message.to_json
end
end
89 changes: 40 additions & 49 deletions lib/helpers/tasks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,22 @@
require 'mcollective'
include MCollective::RPC

module Tasks
module Tasks # rubocop:disable Style/Documentation
def ignore_env?(env)
list = settings.ignore_environments
return false if list.nil? or list.empty?
return false if list.nil? || list.empty?

list.each do |l|
# Even unquoted array elements wrapped by slashes becomes strings after YAML parsing
# So we need to convert it into Regexp manually
if l =~ /^\/.+\/$/
if l =~ %r{^/.+/$}
return true if env =~ Regexp.new(l[1..-2])
else
return true if env == l
elsif env == 1
return true
end
end

return false
false
end

# Check to see if this is an event we care about. Default to responding to all events
Expand All @@ -30,7 +30,7 @@ def ignore_event?
event = request.env['HTTP_X_GITHUB_EVENT']

# Negate this, because we should respond if any of these conditions are true
! (list.nil? or list == event or list.include?(event))
!(list.nil? || (list == event) || list.include?(event))
end

def run_command(command)
Expand All @@ -46,7 +46,7 @@ def run_command(command)
message = "triggered: #{command}\n#{stdout}\n#{stderr}"
else
message = "forked: #{command}"
Process.detach(fork{ exec "#{command} &"})
Process.detach(fork { exec "#{command} &" })
exit_status = 0
end
raise "#{stdout}\n#{stderr}" if exit_status != 0
Expand All @@ -55,50 +55,39 @@ def run_command(command)
end

def generate_types(environment)
begin
command = "#{COMMAND_PREFIX} /opt/puppetlabs/puppet/bin generate types --environment #{environment}"

message = run_command(command)
LOGGER.info("message: #{message} environment: #{environment}")
status_message = {status: :success, message: message.to_s, environment: environment, status_code: 200 }
notify_slack(status_message) if slack?
rescue => e
LOGGER.error("message: #{e.message} trace: #{e.backtrace}")
status_message = {:status => :fail, :message => e.message, :trace => e.backtrace, :environment => environment, :status_code => 500}
notify_slack(status_message) if slack?
end
command = "#{COMMAND_PREFIX} /opt/puppetlabs/puppet/bin generate types --environment #{environment}"

message = run_command(command)
LOGGER.info("message: #{message} environment: #{environment}")
status_message = { status: :success, message: message.to_s, environment: environment, status_code: 200 }
notify_slack(status_message) if slack?
rescue StandardError => e
LOGGER.error("message: #{e.message} trace: #{e.backtrace}")
status_message = { status: :fail, message: e.message, trace: e.backtrace, environment: environment, status_code: 500 }
notify_slack(status_message) if slack?
end

def notify_slack(status_message)
return unless settings.slack_webhook

if settings.slack_channel
slack_channel = settings.slack_channel
else
slack_channel = '#default'
end

if settings.slack_username
slack_user = settings.slack_username
else
slack_user = 'r10k'
end
slack_channel = settings.slack_channel || '#default'
slack_user = settings.slack_username || 'r10k'

if settings.slack_proxy_url
uri = URI(settings.slack_proxy_url)
http_options = {
proxy_address: uri.hostname,
proxy_port: uri.port,
proxy_from_env: false
}
proxy_address: uri.hostname,
proxy_port: uri.port,
proxy_from_env: false
}
else
http_options = {}
end

notifier = Slack::Notifier.new settings.slack_webhook do
defaults channel: slack_channel,
username: slack_user,
icon_emoji: ":ocean:",
icon_emoji: ':ocean:',
http_options: http_options
end

Expand All @@ -116,13 +105,13 @@ def notify_slack(status_message)
case status_message[:status_code]
when 200
message.merge!(
color: "good",
color: 'good',
text: "Successfully deployed #{target}",
fallback: "Successfully deployed #{target}"
)
when 500
message.merge!(
color: "bad",
color: 'bad',
text: "Failed to deploy #{target}",
fallback: "Failed to deploy #{target}"
)
Expand All @@ -132,40 +121,42 @@ def notify_slack(status_message)
end

def slack?
!!settings.slack_webhook
return false if settings.slack_webhook.nil?
settings.slack_webhook
end

def types?
!!settings.generate_tasks
return false if settings.generate_tasks.nil?
settings.generate_tasks
end

def authorized?
# TODO add token-based authentication?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
# TODO: add token-based authentication?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
@auth.provided? && @auth.basic? && @auth.credentials &&
@auth.credentials == [settings.user,settings.pass]
@auth.credentials == [settings.user, settings.pass]
end

def verify_signature?
true unless settings.github_secret.nil?
end

def protected!
unless authorized?
if authorized?
LOGGER.info("Authenticated as user #{settings.user} from IP #{request.ip}")
else
response['WWW-Authenticate'] = %(Basic realm="Restricted Area")
LOGGER.error("Authentication failure from IP #{request.ip}")
throw(:halt, [401, "Not authorized\n"])
else
LOGGER.info("Authenticated as user #{settings.user} from IP #{request.ip}")
end
end

def mco(branch)
options = MCollective::Util.default_options
options = MCollective::Util.default_options
options[:config] = settings.client_cfg
client = rpcclient('r10k', :exit_on_failure => false,:options => options)
client = rpcclient('r10k', exit_on_failure: false, options: options)
client.discovery_timeout = settings.discovery_timeout
client.timeout = settings.client_timeout
result = client.send('deploy',{:environment => branch})
client.send('deploy', environment: branch)
end
end
Loading