diff --git a/.circleci/config.yml b/.circleci/config.yml index f147b56..959a36e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -5,6 +5,7 @@ jobs: - image: circleci/ruby:2.4-node steps: - checkout + - run: gem install bundler - run: bundle install - run: bundle exec rake diff --git a/.rubocop.yml b/.rubocop.yml index f47daf2..bfbb247 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,6 +1,9 @@ AllCops: DisplayCopNames: true DisplayStyleGuide: true + SuggestExtensions: false + TargetRubyVersion: 2.4 + NewCops: enable Exclude: - "module/**/*" - "vendor/**/*" @@ -25,9 +28,6 @@ Style/TrailingUnderscoreVariable: Lint/NonLocalExitFromIterator: Enabled: false -Style/TrailingUnderscoreVariable: - Enabled: false - Naming/ClassAndModuleCamelCase: Enabled: false @@ -46,6 +46,9 @@ Style/StringLiterals: Style/FormatString: EnforcedStyle: percent +Style/FormatStringToken: + EnforcedStyle: unannotated + Style/SpecialGlobalVars: Enabled: false @@ -70,9 +73,6 @@ Layout/SpaceInsideBlockBraces: Layout/SpaceInsideHashLiteralBraces: EnforcedStyle: no_space -Style/Documentation: - Severity: warning - Style/EachWithObject: Enabled: false @@ -87,6 +87,7 @@ Style/DoubleNegation: Style/Documentation: Enabled: false + Severity: warning Style/PerlBackrefs: Enabled: false @@ -106,7 +107,7 @@ Lint/UnusedMethodArgument: Lint/AssignmentInCondition: Enabled: false -Metrics/LineLength: +Layout/LineLength: Max: 180 Metrics/PerceivedComplexity: @@ -133,9 +134,6 @@ Metrics/ModuleLength: Metrics/BlockLength: Enabled: false -Performance/Casecmp: - Enabled: false - Style/FrozenStringLiteralComment: Enabled: false @@ -145,21 +143,22 @@ Style/SymbolArray: Security/MarshalLoad: Enabled: false -Layout/IndentHeredoc: +Layout/HeredocIndentation: Enabled: false # @todo use safe_load but its a big change Security/YAMLLoad: Enabled: false -Performance/RegexpMatch: +Style/SafeNavigation: Enabled: false -Style/SafeNavigation: +Style/RescueStandardError: Enabled: false -Lint/RescueWithoutErrorClass: +Style/OptionalBooleanParameter: Enabled: false -Performance/StringReplacement: +Naming/MemoizedInstanceVariableName: Enabled: false + diff --git a/Gemfile b/Gemfile index 107ea69..df0ea07 100644 --- a/Gemfile +++ b/Gemfile @@ -7,16 +7,15 @@ group :development, :test do gem "coveralls" gem "diplomat", "~> 2" gem "etcdv3", "~> 0.6.0" - gem "guard-rspec" - gem "guard-shell" gem "jgrep", ">= 1.5.0" + gem "json", "2.4.1" gem "json-schema-rspec" gem "listen", "~> 3" - gem "mocha" + gem "mocha", "~> 0.12.2" gem "puppet", "~> 6" - gem "rake" - gem "rspec" - gem "rubocop", "0.51.0" + gem "rake", ">= 12.3.3" + gem "rspec", "~> 3.9.0" + gem "rubocop", "1.6.1" gem "semantic_puppet" gem "webmock" gem "yard" diff --git a/Gemfile.lock b/Gemfile.lock index d602c18..9987aa4 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -3,36 +3,35 @@ GEM specs: addressable (2.7.0) public_suffix (>= 2.0.2, < 5.0) - ast (2.4.0) - choria-mcorpc-support (2.20.0) - json (~> 2.1, >= 2.1.0) + ast (2.4.1) + choria-mcorpc-support (2.22.1) + nats-pure (~> 0.6) systemu (~> 2.6, >= 2.6.4) - coderay (1.1.2) - concurrent-ruby (1.1.5) + concurrent-ruby (1.1.7) coveralls (0.8.23) json (>= 1.8, < 3) simplecov (~> 0.16.1) term-ansicolor (~> 1.3) thor (>= 0.19.4, < 2.0) tins (~> 1.6) - crack (0.4.3) - safe_yaml (~> 1.0.0) + crack (0.4.4) deep_merge (1.2.1) - diff-lcs (1.3) - diplomat (2.2.5) + diff-lcs (1.4.4) + diplomat (2.4.2) deep_merge (~> 1.0, >= 1.0.1) - faraday (~> 0.9) - docile (1.3.2) + faraday (>= 0.9, < 1.1.0) + docile (1.3.3) etcdv3 (0.6.0) faraday (= 0.11.0) grpc (= 1.2.5) - facter (2.5.6) + facter (4.0.47) + hocon (~> 1.3) + thor (>= 1.0.1, < 2.0) faraday (0.11.0) multipart-post (>= 1.2, < 3) fast_gettext (1.8.0) - ffi (1.11.2) - formatador (0.2.5) - google-protobuf (3.10.1) + ffi (1.14.1) + google-protobuf (3.14.0-x86_64-linux) googleauth (0.5.1) faraday (~> 0.9) jwt (~> 1.4) @@ -41,72 +40,45 @@ GEM multi_json (~> 1.11) os (~> 0.9) signet (~> 0.7) - grpc (1.2.5) + grpc (1.2.5-x86_64-linux) google-protobuf (~> 3.1) googleauth (~> 0.5.1) - guard (2.16.1) - formatador (>= 0.2.4) - listen (>= 2.7, < 4.0) - lumberjack (>= 1.0.12, < 2.0) - nenv (~> 0.1) - notiffany (~> 0.0) - pry (>= 0.9.12) - shellany (~> 0.0) - thor (>= 0.18.1) - guard-compat (1.2.1) - guard-rspec (4.7.3) - guard (~> 2.1) - guard-compat (~> 1.1) - rspec (>= 2.99.0, < 4.0) - guard-shell (0.7.1) - guard (>= 2.0.0) - guard-compat (~> 1.0) - hashdiff (1.0.0) + hashdiff (1.0.1) hiera (3.6.0) - hocon (1.3.0) + hocon (1.3.1) httpclient (2.8.3) jgrep (1.5.4) - json (2.3.1) + json (2.4.1) json-schema (2.8.1) addressable (>= 2.4) json-schema-rspec (0.0.4) json-schema (~> 2.5) rspec jwt (1.5.6) - listen (3.2.0) + listen (3.3.3) rb-fsevent (~> 0.10, >= 0.10.3) rb-inotify (~> 0.9, >= 0.9.10) little-plugger (1.1.4) - locale (2.1.2) - logging (2.2.2) + locale (2.1.3) + logging (2.3.0) little-plugger (~> 1.1) - multi_json (~> 1.10) - lumberjack (1.0.13) - memoist (0.16.1) + multi_json (~> 1.14) + memoist (0.16.2) metaclass (0.0.4) - method_source (0.9.2) - mocha (1.9.0) + mocha (0.12.10) metaclass (~> 0.0.1) - multi_json (1.14.1) + multi_json (1.15.0) multipart-post (2.1.1) nats-pure (0.6.2) - nenv (0.3.0) - notiffany (0.1.3) - nenv (~> 0.1) - shellany (~> 0.0) os (0.9.6) - parallel (1.19.0) - parser (2.6.5.0) - ast (~> 2.4.0) - powerpack (0.1.2) - pry (0.12.2) - coderay (~> 1.1.0) - method_source (~> 0.9.0) + parallel (1.20.1) + parser (2.7.2.0) + ast (~> 2.4.1) public_suffix (4.0.6) - puppet (6.11.1) + puppet (6.19.1) concurrent-ruby (~> 1.0) deep_merge (~> 1.0) - facter (> 2.0.1, < 4) + facter (> 2.0.1, < 5) fast_gettext (~> 1.1) hiera (>= 3.2.1, < 4) httpclient (~> 2.8) @@ -114,38 +86,41 @@ GEM multi_json (~> 1.10) puppet-resource_api (~> 1.5) semantic_puppet (~> 1.0) - puppet-resource_api (1.8.7) + puppet-resource_api (1.8.13) hocon (>= 1.0) - rainbow (2.2.2) - rake - rake (13.0.1) - rb-fsevent (0.10.3) - rb-inotify (0.10.0) + rainbow (3.0.0) + rake (13.0.3) + rb-fsevent (0.10.4) + rb-inotify (0.10.1) ffi (~> 1.0) + regexp_parser (2.0.1) + rexml (3.2.4) rspec (3.9.0) rspec-core (~> 3.9.0) rspec-expectations (~> 3.9.0) rspec-mocks (~> 3.9.0) - rspec-core (3.9.0) - rspec-support (~> 3.9.0) - rspec-expectations (3.9.0) + rspec-core (3.9.3) + rspec-support (~> 3.9.3) + rspec-expectations (3.9.4) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.9.0) - rspec-mocks (3.9.0) + rspec-mocks (3.9.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.9.0) - rspec-support (3.9.0) - rubocop (0.51.0) + rspec-support (3.9.4) + rubocop (1.6.1) parallel (~> 1.10) - parser (>= 2.3.3.1, < 3.0) - powerpack (~> 0.1) - rainbow (>= 2.2.2, < 3.0) + parser (>= 2.7.1.5) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8, < 3.0) + rexml + rubocop-ast (>= 1.2.0, < 2.0) ruby-progressbar (~> 1.7) - unicode-display_width (~> 1.0, >= 1.0.1) + unicode-display_width (>= 1.4.0, < 2.0) + rubocop-ast (1.3.0) + parser (>= 2.7.1.5) ruby-progressbar (1.10.1) - safe_yaml (1.0.5) semantic_puppet (1.0.2) - shellany (0.0.1) signet (0.12.0) addressable (~> 2.3) faraday (~> 0.9) @@ -156,40 +131,42 @@ GEM json (>= 1.8, < 3) simplecov-html (~> 0.10.0) simplecov-html (0.10.2) + sync (0.5.0) systemu (2.6.5) term-ansicolor (1.7.1) tins (~> 1.0) - thor (0.20.3) - tins (1.22.2) - unicode-display_width (1.6.0) - webmock (3.7.6) + thor (1.0.1) + tins (1.26.0) + sync + unicode-display_width (1.7.0) + webmock (3.11.0) addressable (>= 2.3.6) crack (>= 0.3.2) hashdiff (>= 0.4.0, < 2.0.0) - yard (0.9.20) + yard (0.9.25) PLATFORMS ruby + x86_64-linux DEPENDENCIES choria-mcorpc-support coveralls diplomat (~> 2) etcdv3 (~> 0.6.0) - guard-rspec - guard-shell jgrep (>= 1.5.0) + json (= 2.4.1) json-schema-rspec listen (~> 3) - mocha + mocha (~> 0.12.2) nats-pure (~> 0.6) puppet (~> 6) - rake - rspec - rubocop (= 0.51.0) + rake (>= 12.3.3) + rspec (~> 3.9.0) + rubocop (= 1.6.1) semantic_puppet webmock yard BUNDLED WITH - 1.15.4 + 2.2.1 diff --git a/Rakefile b/Rakefile index 708304a..0950e4b 100644 --- a/Rakefile +++ b/Rakefile @@ -11,7 +11,7 @@ task :default => ["spec", "rubocop"] desc "Run rubycop style checks" task :rubocop do - sh("rubocop -f progress -f offenses") + sh("rubocop") end namespace :doc do @@ -43,13 +43,13 @@ task :prep_version do File.open("CHANGELOG.md", "w") do |cl| changelog.each do |line| - # rubocop:disable Metrics/LineLength + # rubocop:disable Layout/LineLength cl.puts line if line =~ /^\|----------/ cl.puts "|%s| |Release %s |" % [Time.now.strftime("%Y/%m/%d"), ENV["CHORIA_VERSION"]] end - # rubocop:enable Metrics/LineLength + # rubocop:enable Layout/LineLength end end diff --git a/lib/mcollective/agent/bolt_tasks.rb b/lib/mcollective/agent/bolt_tasks.rb index f967ab1..fcb8091 100644 --- a/lib/mcollective/agent/bolt_tasks.rb +++ b/lib/mcollective/agent/bolt_tasks.rb @@ -112,9 +112,7 @@ class Bolt_tasks < RPC::Agent reply_task_status(status) - if reply.statuscode == 0 && !status["wrapper_spawned"] - reply.fail!("Could not spawn task %s: %s" % [request[:task], status["wrapper_error"]]) - end + reply.fail!("Could not spawn task %s: %s" % [request[:task], status["wrapper_error"]]) if reply.statuscode == 0 && !status["wrapper_spawned"] end def caller_only_status? diff --git a/lib/mcollective/application/choria.rb b/lib/mcollective/application/choria.rb index 76fd482..6a0b92a 100644 --- a/lib/mcollective/application/choria.rb +++ b/lib/mcollective/application/choria.rb @@ -17,7 +17,7 @@ class Choria < Application The batching works a bit different than typical, it will only batch based on a sorted list of certificate names, this means the batches will always run in predictable order. - USAGE + USAGE exclude_argument_sections "common", "filter", "rpc" @@ -47,9 +47,7 @@ def post_option_parser(configuration) def validate_configuration(configuration) Util.loadclass("MCollective::Util::Choria") - unless valid_commands.include?(configuration[:command]) - abort("Unknown command %s, valid commands are: %s" % [configuration[:command], valid_commands.join(", ")]) - end + abort("Unknown command %s, valid commands are: %s" % [configuration[:command], valid_commands.join(", ")]) unless valid_commands.include?(configuration[:command]) if !choria.has_client_public_cert? && !["request_cert", "show_config"].include?(configuration[:command]) abort("A certificate is needed from the Puppet CA for `%s`, please use the `request_cert` command" % choria.certname) @@ -59,7 +57,7 @@ def validate_configuration(configuration) def main send("%s_command" % configuration[:command]) rescue Util::Choria::UserError - STDERR.puts("Encountered a critical error: %s" % Util.colorize(:red, $!.to_s)) + warn("Encountered a critical error: %s" % Util.colorize(:red, $!.to_s)) rescue Util::Choria::Abort exit(1) end @@ -70,13 +68,9 @@ def main def request_cert_command disconnect - unless choria.puppet_security? - raise(Util::Choria::UserError, "Cannot only request certificates in Puppet security mode") - end + raise(Util::Choria::UserError, "Cannot only request certificates in Puppet security mode") unless choria.puppet_security? - if choria.has_client_public_cert? - raise(Util::Choria::UserError, "Already have a certificate '%s', cannot request a new one" % choria.client_public_cert) - end + raise(Util::Choria::UserError, "Already have a certificate '%s', cannot request a new one" % choria.client_public_cert) if choria.has_client_public_cert? choria.ca = configuration[:ca] if configuration[:ca] @@ -246,9 +240,9 @@ def valid_commands def confirm(msg) print("%s (y/n) " % msg) - STDOUT.flush + $stdout.flush - exit(1) unless STDIN.gets.strip.match?(/^(?:y|yes)$/i) + exit(1) unless $stdin.gets.strip.match?(/^(?:y|yes)$/i) end end end diff --git a/lib/mcollective/application/federation.rb b/lib/mcollective/application/federation.rb index 0c79340..fa87a80 100644 --- a/lib/mcollective/application/federation.rb +++ b/lib/mcollective/application/federation.rb @@ -10,15 +10,15 @@ class Federation < Application trace - trace the path to a client -USAGE + USAGE exclude_argument_sections "common", "filter", "rpc" option :collective, :description => "Target messages to a specific sub collective", - :arguments => ["-T", "--target COLLECTIVE"], - :type => String, - :required => false + :arguments => ["-T", "--target COLLECTIVE"], + :type => String, + :required => false # Publish a specially crafted 'ping' with seen-by headers # embedded, this signals to the entire collective to record @@ -45,9 +45,7 @@ def trace_node(node) found_time = Time.now.to_f - unless reply[:senderid] == node - abort("Received a response from %s while expecting a response from %s" % [reply[:senderid], node]) - end + abort("Received a response from %s while expecting a response from %s" % [reply[:senderid], node]) unless reply[:senderid] == node route = message.headers["seen-by"] end @@ -162,9 +160,10 @@ def trace_command route = result[:route] puts "Reported Route:" puts - if route.size == 5 + case route.size + when 5 display_federated_route(route) - elsif route.size == 3 + when 3 display_unfederated_route(route) end @@ -216,9 +215,7 @@ def post_option_parser(configuration) def validate_configuration(configuration) Util.loadclass("MCollective::Util::Choria") - unless valid_commands.include?(configuration[:command]) - abort("Unknown command %s, valid commands are: %s" % [configuration[:command], valid_commands.join(", ")]) - end + abort("Unknown command %s, valid commands are: %s" % [configuration[:command], valid_commands.join(", ")]) unless valid_commands.include?(configuration[:command]) if !choria.has_client_public_cert? && !["request_cert", "show_config"].include?(configuration[:command]) abort("A certificate is needed from the Puppet CA for `%s`, please use the `request_cert` command" % choria.certname) diff --git a/lib/mcollective/application/playbook.rb b/lib/mcollective/application/playbook.rb index cd77f5d..67d924e 100644 --- a/lib/mcollective/application/playbook.rb +++ b/lib/mcollective/application/playbook.rb @@ -16,7 +16,7 @@ class Playbook < Application flags and help related to the specific playbook. Any inputs to the playbook should be given on the CLI. - USAGE + USAGE exclude_argument_sections "common", "filter", "rpc" @@ -58,15 +58,15 @@ def runner(plan, loglevel=nil) ) unless plan_runner.exist? - STDERR.puts("Cannot find supplied Playbook %s" % plan) - STDERR.puts - STDERR.puts("Module Path:") - STDERR.puts + warn("Cannot find supplied Playbook %s" % plan) + $stderr.puts + warn("Module Path:") + $stderr.puts if configuration[:__modulepath] - STDERR.puts(Util.align_text(configuration[:__modulepath].split(":").join("\n"))) + warn(Util.align_text(configuration[:__modulepath].split(":").join("\n"))) else - STDERR.puts(Util.align_text("Puppet Default")) + warn(Util.align_text("Puppet Default")) end exit(1) @@ -137,9 +137,7 @@ def post_option_parser(configuration) def validate_configuration(configuration) abort("Please specify a playbook to run") unless configuration[:__playbook] - if options[:verbose] && !configuration.include?(:loglevel) - configuration[:__loglevel] = "debug" - end + configuration[:__loglevel] = "debug" if options[:verbose] && !configuration.include?(:loglevel) end # List of valid commands this application respond to @@ -158,12 +156,12 @@ def run_command run_plan(pb, pb_config) end - def run_plan(pb, pb_config) + def run_plan(playbook, pb_config) startime = Time.now success = true - result = pb.run!(pb_config) + result = playbook.run!(pb_config) rescue success = false ensure @@ -190,10 +188,10 @@ def run_plan(pb, pb_config) puts puts "Result: " puts - if result.class != String - puts Util.align_text(JSON.pretty_generate(result), 10000) - else + if result.instance_of?(String) puts result + else + puts Util.align_text(JSON.pretty_generate(result), 10000) end puts end diff --git a/lib/mcollective/application/tasks.rb b/lib/mcollective/application/tasks.rb index d3acbef..2058451 100644 --- a/lib/mcollective/application/tasks.rb +++ b/lib/mcollective/application/tasks.rb @@ -254,9 +254,7 @@ def status_command abort("Please specify a task id to display") unless taskid if configuration[:__metadata] - unless options[:verbose] - say("Requesting task metadata for request %s" % Util.colorize(:bold, taskid)) - end + say("Requesting task metadata for request %s" % Util.colorize(:bold, taskid)) unless options[:verbose] bolt_tasks.task_status(:task_id => taskid).each do |status| cli.print_result_metadata(status) @@ -264,9 +262,7 @@ def status_command cli.print_rpc_stats(bolt_tasks.stats) else - unless options[:verbose] - say("Requesting task status for request %s, showing failures only pass --verbose for all output" % Util.colorize(:bold, taskid)) - end + say("Requesting task status for request %s, showing failures only pass --verbose for all output" % Util.colorize(:bold, taskid)) unless options[:verbose] request_and_report(:task_status, {:task_id => taskid}, taskid) end @@ -368,7 +364,7 @@ def show_task_help(task) end def bolt_tasks - @__bolt_tasks ||= rpcclient("bolt_tasks") + @_bolt_tasks ||= rpcclient("bolt_tasks") end def reset_client! @@ -391,18 +387,18 @@ def valid_commands def choria Util.loadclass("MCollective::Util::Choria") - @__choria ||= Util::Choria.new + @_choria ||= Util::Choria.new end def tasks_support - @__tasks ||= choria.tasks_support + @_tasks_support ||= choria.tasks_support end def cli format = configuration[:__json_format] ? :json : :default if options - @__cli ||= tasks_support.cli(format, options[:verbose]) + @_cli ||= tasks_support.cli(format, options[:verbose]) else tasks_support.cli(format, false) end diff --git a/lib/mcollective/connector/nats.rb b/lib/mcollective/connector/nats.rb index 42582fc..e3e6227 100644 --- a/lib/mcollective/connector/nats.rb +++ b/lib/mcollective/connector/nats.rb @@ -7,7 +7,7 @@ module Connector class Nats < Base attr_reader :connection - def initialize + def initialize # rubocop:disable Lint/MissingSuper @config = Config.instance @subscriptions = [] @connection = Util::NatsWrapper.new @@ -107,7 +107,7 @@ def configure_ngs(parameters) raise("nkeys rubygem is required for connections with credentials") unless choria.nkeys? tls = OpenSSL::SSL::SSLContext.new - tls.ssl_version = :TLSv1_2 + tls.ssl_version = :TLSv1_2 # rubocop:disable Naming/VariableNumber parameters[:tls] = {:context => tls} end @@ -141,9 +141,7 @@ def headers_for(msg) headers["reply-to"] = make_target(msg.agent, :reply, msg.collective) end - if msg.headers.include?("seen-by") - headers["seen-by"] << [@config.identity, connected_server.to_s] - end + headers["seen-by"] << [@config.identity, connected_server.to_s] if msg.headers.include?("seen-by") elsif msg.type == :reply if msg.request.headers.include?("seen-by") headers["seen-by"] = msg.request.headers["seen-by"] @@ -329,11 +327,8 @@ def publish_connected_broadcast(msg) } # only happens when replying - if received_message = msg.request - if received_message.headers.include?("federation") - data["headers"]["federation"] = received_message.headers["federation"] - end - end + received_message = msg.request + data["headers"]["federation"] = received_message.headers["federation"] if received_message && received_message.headers.include?("federation") Log.debug("Sending a broadcast message to NATS target '%s' for message type %s" % [target.inspect, msg.type]) @@ -387,9 +382,7 @@ def receive end end - if msg["headers"].include?("seen-by") - msg["headers"]["seen-by"] << [connected_server.to_s, @config.identity] - end + msg["headers"]["seen-by"] << [connected_server.to_s, @config.identity] if msg["headers"].include?("seen-by") Message.new(msg["data"], msg, :base64 => true, :headers => msg["headers"]) end diff --git a/lib/mcollective/discovery/choria.rb b/lib/mcollective/discovery/choria.rb index a501d4f..ad6e0e3 100644 --- a/lib/mcollective/discovery/choria.rb +++ b/lib/mcollective/discovery/choria.rb @@ -183,9 +183,10 @@ def discover_nodes(filter) nil else pql = filter.map do |ident| - if ident =~ /^pql:\s*(.+)$/ + case ident + when /^pql:\s*(.+)$/ "certname in %s" % $1 - elsif ident =~ /^\/(.+)\/$/ + when /^\/(.+)\/$/ 'certname ~ "%s"' % string_regexi($1) else 'certname = "%s"' % ident diff --git a/lib/mcollective/security/choria.rb b/lib/mcollective/security/choria.rb index 829cc93..669be4e 100644 --- a/lib/mcollective/security/choria.rb +++ b/lib/mcollective/security/choria.rb @@ -119,10 +119,11 @@ def encodereply(sender_agent, msg, requestid, requestcallerid=nil) def decodemsg(message) secure_payload = deserialize(message.payload) - if secure_payload["protocol"] == "choria:secure:request:1" + case secure_payload["protocol"] + when "choria:secure:request:1" decode_request(message, secure_payload) - elsif secure_payload["protocol"] == "choria:secure:reply:1" + when "choria:secure:reply:1" decode_reply(secure_payload) else @@ -161,7 +162,7 @@ def decode_request(message, secure_payload) # at core its not compatible with this JSON stuff as is begin request["message"] = deserialize(request["message"], default_serializer) - rescue # rubocop:disable Lint/HandleExceptions + rescue # rubocop:disable Lint/SuppressedException end else record_legacy_request(request) @@ -174,9 +175,7 @@ def decode_request(message, secure_payload) # # @param request [Hash] decoded request def record_legacy_request(request) - if request["envelope"] && request["envelope"]["requestid"] - Cache.write(:choria_security, request["envelope"]["requestid"], true) - end + Cache.write(:choria_security, request["envelope"]["requestid"], true) if request["envelope"] && request["envelope"]["requestid"] end # Determines if a specific requestid was a previously seen legacy request @@ -216,7 +215,7 @@ def decode_reply(secure_payload) # at core its not compatible with this JSON stuff as is begin reply["message"] = deserialize(reply["message"], default_serializer) - rescue # rubocop:disable Lint/HandleExceptions + rescue # rubocop:disable Lint/SuppressedException end end @@ -428,7 +427,7 @@ def client_pubcert_metadata(envelope, pubcert) # # @return [Mutex] def client_cache_mutex - @_ccmutex ||= Mutex.new + @_client_cache_mutex ||= Mutex.new end # Caches the public certificate of a sender @@ -448,10 +447,12 @@ def cache_client_pubcert(envelope, pubcert) certfile = public_certfile(callerid) certmetadata = public_cert_metadatafile(callerid) - if !File.exist?(certfile) - unless should_cache_certname?(pubcert, callerid) - raise("Received an invalid certificate for %s" % callerid) - end + if File.exist?(certfile) + Log.debug("Already have a cert from %s in %s" % [callerid, certfile]) + + false + else + raise("Received an invalid certificate for %s" % callerid) unless should_cache_certname?(pubcert, callerid) Log.info("Saving verified pubcert for %s in %s" % [callerid, certfile]) @@ -464,10 +465,6 @@ def cache_client_pubcert(envelope, pubcert) end true - else - Log.debug("Already have a cert from %s in %s" % [callerid, certfile]) - - false end end end @@ -490,7 +487,7 @@ def public_cert_metadatafile(callerid) # @return [String] the certificate name # @raise [StandardError] when a unexpected format id is received def certname_from_callerid(id) - if id =~ /^choria=([\w\.\-]+)/ + if id =~ /^choria=([\w.\-]+)/ $1 else raise("Received a callerid in an unexpected format: %s" % id) @@ -612,7 +609,7 @@ def sign(string, id=nil) end key = OpenSSL::PKey::RSA.new(File.read(key)) - signed = key.sign(OpenSSL::Digest::SHA256.new, string) + signed = key.sign(OpenSSL::Digest.new("SHA256"), string) Base64.encode64(signed).chomp end @@ -636,7 +633,7 @@ def verify_signature(string, signature, callerid, allow_privileged=false) next unless File.exist?(certname) key = OpenSSL::X509::Certificate.new(File.read(certname)).public_key - result = key.verify(OpenSSL::Digest::SHA256.new, Base64.decode64(signature), string) + result = key.verify(OpenSSL::Digest.new("SHA256"), Base64.decode64(signature), string) if result Log.debug("Message validated using certificate in %s (allow_privileged=%s)" % [certname, allow_privileged]) diff --git a/lib/mcollective/signer/base.rb b/lib/mcollective/signer/base.rb index af60c73..b0727a1 100644 --- a/lib/mcollective/signer/base.rb +++ b/lib/mcollective/signer/base.rb @@ -4,6 +4,7 @@ class Base # Register plugins that inherits base def self.inherited(klass) PluginManager << {:type => "choria_signer_plugin", :class => klass.to_s} + super end def initialize diff --git a/lib/mcollective/signer/choria.rb b/lib/mcollective/signer/choria.rb index 01eae9d..8b251e3 100644 --- a/lib/mcollective/signer/choria.rb +++ b/lib/mcollective/signer/choria.rb @@ -27,9 +27,7 @@ def token if file file = File.expand_path(file) - unless File.exist?(file) - raise("No token found in %s, please authenticate using your configured authentication service" % file) - end + raise("No token found in %s, please authenticate using your configured authentication service" % file) unless File.exist?(file) return File.read(file).chomp end @@ -127,9 +125,7 @@ def remote_sign!(secure_request) raise("Could not get remote signature: %s: %s" % [resp.code, resp.body]) end - if signature["error"] - raise("Could not get remote signature: %s" % signature["error"]) - end + raise("Could not get remote signature: %s" % signature["error"]) if signature["error"] signed_request = JSON.parse(Base64.decode64(signature["secure_request"])) signed_request.each do |k, v| diff --git a/lib/mcollective/util/bolt_support.rb b/lib/mcollective/util/bolt_support.rb index 490679c..2fc5d6b 100644 --- a/lib/mcollective/util/bolt_support.rb +++ b/lib/mcollective/util/bolt_support.rb @@ -10,7 +10,7 @@ module MCollective module Util class BoltSupport def choria - @__choria ||= Choria.new + @_choria ||= Choria.new end # Converts the current Puppet loglevel to one we understand @@ -18,9 +18,7 @@ def choria # @return ["debug", "info", "warn", "error", "fatal"] def self.loglevel case Puppet::Util::Log.level - when :notice - "warn" - when :warning + when :notice, :warning "warn" when :err "error" @@ -35,9 +33,7 @@ def self.loglevel # # @return [BoltSupport] def self.init_choria - unless Config.instance.configured - Config.instance.loadconfig(Util.config_file_for_user) - end + Config.instance.loadconfig(Util.config_file_for_user) unless Config.instance.configured new end @@ -47,11 +43,11 @@ def self.init_choria # @return [Playbook] def playbook @_playbook ||= begin - pb = Playbook.new(self.class.loglevel) - pb.logger = Playbook::Puppet_Logger - pb.set_logger_level - pb - end + pb = Playbook.new(self.class.loglevel) + pb.logger = Playbook::Puppet_Logger + pb.set_logger_level + pb + end end def nodes diff --git a/lib/mcollective/util/bolt_support/plan_runner.rb b/lib/mcollective/util/bolt_support/plan_runner.rb index a7cc7e7..95dacdb 100644 --- a/lib/mcollective/util/bolt_support/plan_runner.rb +++ b/lib/mcollective/util/bolt_support/plan_runner.rb @@ -76,11 +76,9 @@ def plan_signature end # Yields a PAL script compiler in the temporary environment - def with_script_compiler + def with_script_compiler(&block) in_environment do |env| - env.with_script_compiler do |compiler| - yield(compiler) - end + env.with_script_compiler(&block) end end @@ -98,12 +96,10 @@ def initialize_settings end # Sets up a temporary environment - def in_environment + def in_environment(&block) initialize_settings - Puppet::Pal.in_tmp_environment("choria", :modulepath => @modulepath, :facts => facts) do |env| - yield(env) - end + Puppet::Pal.in_tmp_environment("choria", :modulepath => @modulepath, :facts => facts, &block) end # Converts a Puppet type into something mcollective understands diff --git a/lib/mcollective/util/bolt_support/task_result.rb b/lib/mcollective/util/bolt_support/task_result.rb index a071b3b..76f5401 100644 --- a/lib/mcollective/util/bolt_support/task_result.rb +++ b/lib/mcollective/util/bolt_support/task_result.rb @@ -23,8 +23,8 @@ def to_hash {@host => @result} end - def to_json(o={}) - to_hash.to_json(o) + def to_json(obj={}) + to_hash.to_json(obj) end # A error object if this represents an error diff --git a/lib/mcollective/util/bolt_support/task_results.rb b/lib/mcollective/util/bolt_support/task_results.rb index 57b6bd3..c4864c6 100644 --- a/lib/mcollective/util/bolt_support/task_results.rb +++ b/lib/mcollective/util/bolt_support/task_results.rb @@ -26,15 +26,15 @@ def initialize(results, exception=nil) @exception = exception end - def to_json(o={}) - @results.to_json(o) + def to_json(obj={}) + @results.to_json(obj) end # Iterate over all results # # @yield [TaskResult] - def each - @results.each {|r| yield r} + def each(&block) + @results.each(&block) end # Set of all the results that are errors regardless of fail_ok @@ -66,6 +66,7 @@ def fail_ok def message return exception.to_s if exception + @message end diff --git a/lib/mcollective/util/choria.rb b/lib/mcollective/util/choria.rb index 7ba6c3a..18e62c5 100644 --- a/lib/mcollective/util/choria.rb +++ b/lib/mcollective/util/choria.rb @@ -5,6 +5,7 @@ module MCollective module Util class Choria class UserError < StandardError; end + class Abort < StandardError; end unless defined?(Choria::VERSION) # rubocop:disable Style/IfUnlessModifier @@ -222,7 +223,7 @@ def sort_srv_answers(answers) sorted_answers = [] # this is roughly based on the resolv-srv and supposedly mostly rfc2782 compliant - answers.each do |_, available| # rubocop:disable Performance/HashEachMethods + answers.each do |_, available| total_weight = available.inject(0) {|a, e| a + e.weight + 1 } until available.empty? @@ -382,9 +383,7 @@ def have_ssl_files?(log=true) def valid_certificate?(pubcert, name, log=true) return false unless name - unless File.readable?(ca_path) - raise("Cannot find or read the CA in %s, cannot verify public certificate" % ca_path) - end + raise("Cannot find or read the CA in %s, cannot verify public certificate" % ca_path) unless File.readable?(ca_path) certs = parse_pubcert(pubcert, log) @@ -402,9 +401,7 @@ def valid_certificate?(pubcert, name, log=true) end unless ca.verify(incoming, chain) - if log - Log.warn("Failed to verify certificate %s against CA %s in %s" % [incoming.subject.to_s, incoming.issuer.to_s, ca_path]) - end + Log.warn("Failed to verify certificate %s against CA %s in %s" % [incoming.subject.to_s, incoming.issuer.to_s, ca_path]) if log return false end @@ -478,9 +475,7 @@ def check_ssl_setup(log=true) return true if $choria_unsafe_disable_protocol_security # rubocop:disable Style/GlobalVars return true if anon_tls? - if Process.uid == 0 && PluginManager["security_plugin"].initiated_by == :client - raise(UserError, "The Choria client cannot be run as root") - end + raise(UserError, "The Choria client cannot be run as root") if Process.uid == 0 && PluginManager["security_plugin"].initiated_by == :client raise(UserError, "Not all required SSL files exist") unless have_ssl_files?(log) @@ -742,7 +737,7 @@ def puppet_setting(setting) def ssl_context context = OpenSSL::SSL::SSLContext.new context.ca_file = ca_path - context.ssl_version = :TLSv1_2 + context.ssl_version = :TLSv1_2 # rubocop:disable Naming/VariableNumber if anon_tls? context.verify_mode = OpenSSL::SSL::VERIFY_NONE @@ -783,13 +778,13 @@ def ssl_context # # @return [String] def ssl_dir - @__ssl_dir ||= if has_option?("choria.ssldir") - File.expand_path(get_option("choria.ssldir")) - elsif Util.windows? || Process.uid == 0 - puppet_setting(:ssldir) - else - File.expand_path("~/.puppetlabs/etc/puppet/ssl") - end + @_ssl_dir ||= if has_option?("choria.ssldir") + File.expand_path(get_option("choria.ssldir")) + elsif Util.windows? || Process.uid == 0 + puppet_setting(:ssldir) + else + File.expand_path("~/.puppetlabs/etc/puppet/ssl") + end end # Determines the security provider @@ -964,9 +959,7 @@ def create_rsa_key(bits) # @return [OpenSSL::PKey::RSA] # @raise [StandardError] when the key already exist def write_key - if has_client_private_key? - raise("Refusing to overwrite existing key in %s" % client_private_key) - end + raise("Refusing to overwrite existing key in %s" % client_private_key) if has_client_private_key? key = create_rsa_key(4096) File.open(client_private_key, "w", 0o0640) {|f| f.write(key.to_pem)} @@ -977,17 +970,17 @@ def write_key # Creates a basic CSR # # @return [OpenSSL::X509::Request] signed CSR - def create_csr(cn, ou, key) + def create_csr(comonname, orgunit, key) csr = OpenSSL::X509::Request.new csr.version = 0 csr.public_key = key.public_key csr.subject = OpenSSL::X509::Name.new( [ - ["CN", cn, OpenSSL::ASN1::UTF8STRING], - ["OU", ou, OpenSSL::ASN1::UTF8STRING] + ["CN", comonname, OpenSSL::ASN1::UTF8STRING], + ["OU", orgunit, OpenSSL::ASN1::UTF8STRING] ] ) - csr.sign(key, OpenSSL::Digest::SHA1.new) + csr.sign(key, OpenSSL::Digest.new("SHA1")) csr end diff --git a/lib/mcollective/util/playbook.rb b/lib/mcollective/util/playbook.rb index b1c1875..2304a5f 100644 --- a/lib/mcollective/util/playbook.rb +++ b/lib/mcollective/util/playbook.rb @@ -165,7 +165,7 @@ def save_input_data # # @return [String] def lock_path(lock) - lock =~ /^[a-zA-Z0-9\-\_]+\/.+$/ ? lock : "%s/choria/locks/playbook/%s" % [lock, name] + lock =~ /^[a-zA-Z0-9\-_]+\/.+$/ ? lock : "%s/choria/locks/playbook/%s" % [lock, name] end # Obtains the playbook level locks diff --git a/lib/mcollective/util/playbook/data_stores.rb b/lib/mcollective/util/playbook/data_stores.rb index eea6544..6257e5b 100644 --- a/lib/mcollective/util/playbook/data_stores.rb +++ b/lib/mcollective/util/playbook/data_stores.rb @@ -31,7 +31,7 @@ def valid_path?(path) # @return [String, String] store name and key name # @raise [StandardError] for incorrectly formatted paths def parse_path(path) - if path =~ /^([a-zA-Z0-9\-\_]+)\/(.+)$/ + if path =~ /^([a-zA-Z0-9\-_]+)\/(.+)$/ [$1, $2] else raise("Invalid data store path %s" % [path]) diff --git a/lib/mcollective/util/playbook/data_stores/file_data_store.rb b/lib/mcollective/util/playbook/data_stores/file_data_store.rb index f232db4..d57d42f 100644 --- a/lib/mcollective/util/playbook/data_stores/file_data_store.rb +++ b/lib/mcollective/util/playbook/data_stores/file_data_store.rb @@ -49,18 +49,20 @@ def data def parse_data return({}) if File.size(@file) == 0 - if @format == "json" + case @format + when "json" JSON.parse(File.read(@file)) - elsif @format == "yaml" + when "yaml" YAML.load(File.read(@file)) end end def save_data(raw_data) File.open(@file, "w") do |f| - if @format == "json" + case @format + when "json" f.print(JSON.dump(raw_data)) - elsif @format == "yaml" + when "yaml" f.print(YAML.dump(raw_data)) end end diff --git a/lib/mcollective/util/playbook/data_stores/shell_data_store.rb b/lib/mcollective/util/playbook/data_stores/shell_data_store.rb index f756594..dcc7441 100644 --- a/lib/mcollective/util/playbook/data_stores/shell_data_store.rb +++ b/lib/mcollective/util/playbook/data_stores/shell_data_store.rb @@ -54,6 +54,7 @@ def run_command(command, options) def validate_key(key) raise("Valid keys must match ^[a-zA-Z0-9_-]+$") unless key =~ /^[a-zA-Z0-9_-]+$/ + true end diff --git a/lib/mcollective/util/playbook/inputs.rb b/lib/mcollective/util/playbook/inputs.rb index ef0e24e..b7aa98f 100644 --- a/lib/mcollective/util/playbook/inputs.rb +++ b/lib/mcollective/util/playbook/inputs.rb @@ -68,9 +68,7 @@ def add_cli_options(application, set_required) option_params[:arguments] = ["--%s" % input.downcase] if type == :boolean - if set_required && !i_props.include?("data") - option_params[:required] = i_props["required"] - end + option_params[:required] = i_props["required"] if set_required && !i_props.include?("data") application.class.option(input, option_params) end @@ -231,9 +229,10 @@ def validate_data(input, value) validator = @inputs[input][:properties]["validation"] - if validator =~ /^:(.+)/ + case validator + when /^:(.+)/ validator = $1.intern - elsif validator =~ /^\/(.+)\/$/ + when /^\/(.+)\/$/ validator = Regexp.new($1) end diff --git a/lib/mcollective/util/playbook/nodes.rb b/lib/mcollective/util/playbook/nodes.rb index 9de0415..bd882e4 100644 --- a/lib/mcollective/util/playbook/nodes.rb +++ b/lib/mcollective/util/playbook/nodes.rb @@ -133,9 +133,7 @@ def test_nodes ) success, msg, _ = rpc.run - unless success - raise("Connectivity test failed for some nodes: %s" % [msg]) - end + raise("Connectivity test failed for some nodes: %s" % [msg]) unless success end # Checks that discovered nodes matches stated expectations @@ -145,9 +143,7 @@ def test_nodes def validate_nodes(nodes) return if properties(nodes)["empty_ok"] - unless self[nodes].size >= properties(nodes)["at_least"] - raise("Node set %s needs at least %d nodes, got %d" % [nodes, properties(nodes)["at_least"], self[nodes].size]) - end + raise("Node set %s needs at least %d nodes, got %d" % [nodes, properties(nodes)["at_least"], self[nodes].size]) unless self[nodes].size >= properties(nodes)["at_least"] end # Handles an empty discovered list @@ -155,9 +151,7 @@ def validate_nodes(nodes) # @param nodes [String] node set name # @raise [StandardError] when empty def check_empty(nodes) - if self[nodes].empty? && !properties(nodes)["empty_ok"] - raise(properties(nodes)["when_empty"] || "Did not discover any nodes for nodeset %s" % nodes) - end + raise(properties(nodes)["when_empty"] || "Did not discover any nodes for nodeset %s" % nodes) if self[nodes].empty? && !properties(nodes)["empty_ok"] end # Limits the discovered list for a node set based on the playbook limits diff --git a/lib/mcollective/util/playbook/nodes/terraform_nodes.rb b/lib/mcollective/util/playbook/nodes/terraform_nodes.rb index 2543b03..9fc53cb 100644 --- a/lib/mcollective/util/playbook/nodes/terraform_nodes.rb +++ b/lib/mcollective/util/playbook/nodes/terraform_nodes.rb @@ -6,10 +6,7 @@ class TerraformNodes def prepare; end def validate_configuration! - if @terraform - raise("The supplied terraform path %s is not executable" % @terraform) unless File.executable?(@terraform) - end - + raise("The supplied terraform path %s is not executable" % @terraform) if @terraform && !File.executable?(@terraform) raise("A terraform state file is needed") unless @state raise("The terraform statefile %s is not readable" % @state) unless File.readable?(@state) raise("An output name is needed") unless @output diff --git a/lib/mcollective/util/playbook/playbook_logger.rb b/lib/mcollective/util/playbook/playbook_logger.rb index 49eb9eb..6f798ed 100644 --- a/lib/mcollective/util/playbook/playbook_logger.rb +++ b/lib/mcollective/util/playbook/playbook_logger.rb @@ -17,7 +17,7 @@ def start set_level(@playbook.loglevel.intern) end - def log(level, from, msg, normal_output=STDERR, last_resort_output=STDERR) + def log(level, from, msg, normal_output=$stderr, last_resort_output=$stderr) if @playbook.loglevel != "debug" if should_show? console_from = "%s#%-25s" % [@playbook.name, @playbook.context] diff --git a/lib/mcollective/util/playbook/puppet_logger.rb b/lib/mcollective/util/playbook/puppet_logger.rb index 28ad6da..7d642c3 100644 --- a/lib/mcollective/util/playbook/puppet_logger.rb +++ b/lib/mcollective/util/playbook/puppet_logger.rb @@ -17,7 +17,7 @@ def start set_level(@playbook.loglevel.intern) end - def log(level, from, msg, normal_output=STDERR, last_resort_output=STDERR) + def log(level, from, msg, normal_output=$stderr, last_resort_output=$stderr) return unless should_show?(level) logmethod = case level diff --git a/lib/mcollective/util/playbook/task_result.rb b/lib/mcollective/util/playbook/task_result.rb index c717190..c28fb05 100644 --- a/lib/mcollective/util/playbook/task_result.rb +++ b/lib/mcollective/util/playbook/task_result.rb @@ -2,8 +2,7 @@ module MCollective module Util class Playbook class TaskResult - attr_accessor :success, :msg, :data, :ran, :task, :set - attr_accessor :start_time, :end_time, :description + attr_accessor :success, :msg, :data, :ran, :task, :set, :start_time, :end_time, :description def initialize(task) @start_time = Time.now diff --git a/lib/mcollective/util/playbook/tasks.rb b/lib/mcollective/util/playbook/tasks.rb index 1e70d47..a1b774b 100644 --- a/lib/mcollective/util/playbook/tasks.rb +++ b/lib/mcollective/util/playbook/tasks.rb @@ -179,9 +179,10 @@ def load_tasks(data, set) end def from_hash(data) - if data.is_a?(Array) + case data + when Array load_tasks(data, "tasks") - elsif data.is_a?(Hash) + when Hash data.each do |set, tasks| load_tasks(tasks, set) end diff --git a/lib/mcollective/util/playbook/tasks/graphite_event_task.rb b/lib/mcollective/util/playbook/tasks/graphite_event_task.rb index 0f1bea1..d97a2db 100644 --- a/lib/mcollective/util/playbook/tasks/graphite_event_task.rb +++ b/lib/mcollective/util/playbook/tasks/graphite_event_task.rb @@ -19,11 +19,11 @@ def request end def webhook_task - return @__webhook if @__webhook + return @_webhook if @_webhook - @__webhook = Tasks::WebhookTask.new(@playbook) + @_webhook = Tasks::WebhookTask.new(@playbook) - @__webhook.from_hash( + @_webhook.from_hash( "description" => @description, "headers" => @headers, "uri" => @graphite, @@ -31,7 +31,7 @@ def webhook_task "data" => request ) - @__webhook + @_webhook end def validate_configuration! diff --git a/lib/mcollective/util/playbook/tasks/mcollective_task.rb b/lib/mcollective/util/playbook/tasks/mcollective_task.rb index e720504..3b89cfb 100644 --- a/lib/mcollective/util/playbook/tasks/mcollective_task.rb +++ b/lib/mcollective/util/playbook/tasks/mcollective_task.rb @@ -245,15 +245,11 @@ def log_failure(stats, replies) Log.warn("Failed request %s for %s#%s in %0.2fs" % [stats.requestid, @agent, @action, stats.totaltime]) - unless stats.noresponsefrom.empty? - Log.warn("No responses from: %s" % stats.noresponsefrom.join(", ")) - end + Log.warn("No responses from: %s" % stats.noresponsefrom.join(", ")) unless stats.noresponsefrom.empty? if stats.failcount > 0 replies.each do |reply| - if reply.results[:statuscode] > 0 - Log.warn("Failed result from %s: %s" % [reply.results[:sender], reply.results[:statusmsg]]) - end + Log.warn("Failed result from %s: %s" % [reply.results[:sender], reply.results[:statusmsg]]) if reply.results[:statuscode] > 0 end end end @@ -261,6 +257,7 @@ def log_failure(stats, replies) def log_reply(reply) if reply.results[:statuscode] == 0 return unless @log_replies + Log.info("%s %s#%s success: %s" % [reply.results[:sender], @agent, @action, reply.results[:data].inspect]) else Log.warn("%s %s#%s failure: %s" % [reply.results[:sender], @agent, @action, reply.results[:data].inspect]) diff --git a/lib/mcollective/util/playbook/tasks/webhook_task.rb b/lib/mcollective/util/playbook/tasks/webhook_task.rb index db95870..ba8c9df 100644 --- a/lib/mcollective/util/playbook/tasks/webhook_task.rb +++ b/lib/mcollective/util/playbook/tasks/webhook_task.rb @@ -67,6 +67,7 @@ def http_post_request(uri) def http_request(uri) return http_get_request(uri) if @method == "GET" return http_post_request(uri) if @method == "POST" + raise("Unknown request method %s" % @method) end diff --git a/lib/mcollective/util/playbook/template_util.rb b/lib/mcollective/util/playbook/template_util.rb index 69ec68c..42335fe 100644 --- a/lib/mcollective/util/playbook/template_util.rb +++ b/lib/mcollective/util/playbook/template_util.rb @@ -15,15 +15,16 @@ module TemplateUtil def t(data) data = Marshal.load(Marshal.dump(data)) - if data.is_a?(String) + case data + when String __template_process_string(data) - elsif data.is_a?(Hash) + when Hash data.each do |k, v| data[k] = t(v) end data - elsif data.is_a?(Array) + when Array data.map do |v| t(v) end @@ -70,21 +71,20 @@ def __template_process_string(string) combined_regex = Regexp.union(data_regex, date_regex, task_regex, singles_regex) - if req = string.match(/^#{data_regex}$/) + if req = (string.match(/^#{data_regex}$/) || string.match(/^#{task_regex}$/)) __template_resolve(req["type"], req["item"]) elsif req = string.match(/^#{date_regex}$/) __template_resolve(req["type"], req["format"]) - elsif req = string.match(/^#{task_regex}$/) - __template_resolve(req["type"], req["item"]) elsif req = string.match(/^#{singles_regex}$/) __template_resolve(req["type"], "") else string.gsub(/#{combined_regex}/) do |part| value = __template_process_string(part) - if value.is_a?(Array) + case value + when Array value.join(", ") - elsif value.is_a?(Hash) + when Hash value.to_json else value diff --git a/lib/mcollective/util/playbook/uses.rb b/lib/mcollective/util/playbook/uses.rb index d21dd13..0ceab57 100644 --- a/lib/mcollective/util/playbook/uses.rb +++ b/lib/mcollective/util/playbook/uses.rb @@ -36,7 +36,7 @@ def agent_inventory(nodes) # based structures inventory.each do |node| node["data"][:agents].each do |agent| - agent.keys.each do |key| # rubocop:disable Performance/HashEachMethods + agent.keys.each do |key| # rubocop:disable Style/HashEachMethods agent[key.intern] = agent.delete(key) if key.is_a?(String) end end diff --git a/lib/mcollective/util/tasks_support.rb b/lib/mcollective/util/tasks_support.rb index 6fa3301..8a202e0 100644 --- a/lib/mcollective/util/tasks_support.rb +++ b/lib/mcollective/util/tasks_support.rb @@ -469,9 +469,7 @@ def task_status(requestid) result["stderr"] = File.read(stderr) if File.exist?(stderr) result["wrapper_spawned"] = File.exist?(wrapper_stderr) && file_size(wrapper_stderr) == 0 - if File.exist?(wrapper_stderr) && file_size(wrapper_stderr) > 0 - result["wrapper_error"] = File.read(wrapper_stderr) - end + result["wrapper_error"] = File.read(wrapper_stderr) if File.exist?(wrapper_stderr) && file_size(wrapper_stderr) > 0 if File.exist?(wrapper_pid) && file_size(wrapper_pid) > 0 result["start_time"] = File::Stat.new(wrapper_pid).mtime.utc diff --git a/lib/mcollective/util/tasks_support/cli.rb b/lib/mcollective/util/tasks_support/cli.rb index 25370f8..c9cf438 100644 --- a/lib/mcollective/util/tasks_support/cli.rb +++ b/lib/mcollective/util/tasks_support/cli.rb @@ -21,7 +21,7 @@ def initialize(support, format, verbose) # @param environment [String] the environment to query # @param detail [Boolean] show task descriptions # @param out [IO] - def show_task_list(environment, detail, out=STDOUT) + def show_task_list(environment, detail, out=$stdout) out.puts "Known tasks in the %s environment" % environment out.puts @@ -53,7 +53,7 @@ def show_task_list(environment, detail, out=STDOUT) # # @param environment [String] the environment to query # @param detail [Boolean] show task descriptions - def task_list(environment, detail, out=STDOUT) + def task_list(environment, detail, out=$stdout) tasks = {} out.print("Retrieving tasks....") @@ -79,7 +79,7 @@ def task_list(environment, detail, out=STDOUT) # @param task [String] task name # @param environment [String] environment to feetch task from # @param out [IO] - def show_task_help(task, environment, out=STDOUT) + def show_task_help(task, environment, out=$stdout) out.puts("Retrieving task metadata for task %s from the Puppet Server" % task) begin @@ -155,6 +155,7 @@ def task_input(configuration) configuration.each do |item, value| next if item.to_s.start_with?("__") + result[item.to_s] = value end @@ -232,11 +233,11 @@ def transform_hash_strings(meta, input) # @param task [String] the task to fetch # @param environment [String] Puppet environment def task_metadata(task, environment) - @__metadata ||= {} + @_metadata ||= {} - return @__metadata[task] if @__metadata[task] + return @_metadata[task] if @_metadata[task] - @__metadata[task] = @support.task_metadata(task, environment) + @_metadata[task] = @support.task_metadata(task, environment) end # Draw a compact CLI progress indicator diff --git a/lib/mcollective/util/tasks_support/default_formatter.rb b/lib/mcollective/util/tasks_support/default_formatter.rb index ebac161..921aa60 100644 --- a/lib/mcollective/util/tasks_support/default_formatter.rb +++ b/lib/mcollective/util/tasks_support/default_formatter.rb @@ -5,7 +5,7 @@ class CLI class DefaultFormatter attr_reader :out - def initialize(cli, verbose=false, out=STDOUT) + def initialize(cli, verbose=false, out=$stdout) @cli = cli @verbose = verbose @out = out @@ -77,7 +77,7 @@ def print_result(result) stdout_text.delete("_error") stdout_text = stdout_text.to_json stdout_text = nil if stdout_text == "{}" - rescue # rubocop:disable Lint/HandleExceptions + rescue # rubocop:disable Lint/SuppressedException end end diff --git a/lib/mcollective/util/tasks_support/json_formatter.rb b/lib/mcollective/util/tasks_support/json_formatter.rb index fd7ae1f..0ed03f9 100644 --- a/lib/mcollective/util/tasks_support/json_formatter.rb +++ b/lib/mcollective/util/tasks_support/json_formatter.rb @@ -5,7 +5,7 @@ class CLI class JSONFormatter attr_reader :out - def initialize(cli, verbose=false, out=STDOUT) + def initialize(cli, verbose=false, out=$stdout) @cli = cli @verbose = verbose @out = out @@ -41,7 +41,7 @@ def print_task_summary(taskid, names, callers, completed, running, task_not_know "callers" => callers, "completed" => completed, "running" => running, - "task_not_known" => task_not_known, + "task_not_known" => task_not_known, "wrapper_failure" => wrapper_failure, "success" => success, "failed" => fails, @@ -87,7 +87,7 @@ def print_result(result) begin item["stdout"] = JSON.parse(item["stdout"]) item["stdout"] = item["stdout"].delete("_output") if item["stdout"]["_output"] - rescue # rubocop:disable Lint/HandleExceptions + rescue # rubocop:disable Lint/SuppressedException end out.puts "," unless @first_item diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 5880c06..895ba0e 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -12,8 +12,6 @@ require "rspec" require "mcollective" -require "rspec/mocks" -require "mocha" require "webmock/rspec" require "json-schema-rspec" diff --git a/spec/unit/mcollective/connector/nats_spec.rb b/spec/unit/mcollective/connector/nats_spec.rb index e6889f5..8f5889d 100644 --- a/spec/unit/mcollective/connector/nats_spec.rb +++ b/spec/unit/mcollective/connector/nats_spec.rb @@ -294,10 +294,11 @@ module MCollective end describe "#publish_connected_broadcast" do - it "should support broacasts" do + it "should support broadcasts" do msg.collective = "mcollective" msg.agent = "rspec_agent" msg.type = :request + connector.connection.expects(:publish).with("mcollective.broadcast.agent.rspec_agent", any_parameters) connector.publish_connected_broadcast(msg) diff --git a/spec/unit/mcollective/discovery/choria_spec.rb b/spec/unit/mcollective/discovery/choria_spec.rb index 3bb6f90..a6318a8 100644 --- a/spec/unit/mcollective/discovery/choria_spec.rb +++ b/spec/unit/mcollective/discovery/choria_spec.rb @@ -107,11 +107,11 @@ module MCollective describe "#discover_agents" do it "should search for correct classes" do - # rubocop:disable Metrics/LineLength + # rubocop:disable Layout/LineLength expect( discovery.discover_agents(["rpcutil", "rspec1", "/rs/"]) ).to eq('(resources {type = "Class" and title = "Mcollective::Service"} or resources {type = "Class" and title = "Choria::Service"}) and resources {type = "File" and tag = "mcollective_agent_rspec1_server"} and resources {type = "File" and tag ~ "mcollective_agent_.*?[rR][sS].*?_server"}') - # rubocop:enable Metrics/LineLength + # rubocop:enable Layout/LineLength end end diff --git a/spec/unit/mcollective/util/choria_spec.rb b/spec/unit/mcollective/util/choria_spec.rb index 67d74e8..d493d33 100644 --- a/spec/unit/mcollective/util/choria_spec.rb +++ b/spec/unit/mcollective/util/choria_spec.rb @@ -393,7 +393,7 @@ module Util end it "should support proc defaults" do - expect(choria.get_option("choria.fail", ->() { "lambda result" })).to eq("lambda result") + expect(choria.get_option("choria.fail", -> { "lambda result" })).to eq("lambda result") end it "should support normal defaults" do diff --git a/spec/unit/mcollective/util/tasks_support_spec.rb b/spec/unit/mcollective/util/tasks_support_spec.rb index 5f9832e..e24e211 100644 --- a/spec/unit/mcollective/util/tasks_support_spec.rb +++ b/spec/unit/mcollective/util/tasks_support_spec.rb @@ -184,7 +184,7 @@ module Util err = <<-ERROR terminate called after throwing an instance of 'leatherman::json_container::data_key_error' what(): unknown object entry with key: executable -ERROR + ERROR expect(status).to eq( "spool" => spool,