diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index f8c0d35f..8e3274e2 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -9,16 +9,16 @@ name: Ruby on: push: - branches: [ master ] + branches: [ main ] pull_request: - branches: [ master ] + branches: [ main ] jobs: test: runs-on: ubuntu-latest strategy: matrix: - ruby-version: ['2.6', '2.7'] + ruby-version: ['2.7'] steps: - uses: actions/checkout@v2 - name: Set up Ruby @@ -28,7 +28,3 @@ jobs: bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run tests run: bundle exec rake - - name: Coveralls - uses: coverallsapp/github-action@master - with: - github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.ruby-version b/.ruby-version deleted file mode 100644 index bc4abe86..00000000 --- a/.ruby-version +++ /dev/null @@ -1 +0,0 @@ -2.3.8 diff --git a/Gemfile b/Gemfile index f463de01..3dc4f6a6 100644 --- a/Gemfile +++ b/Gemfile @@ -7,6 +7,7 @@ source 'http://rubygems.org' gemspec gem "process_manager", "0.0.13", :path => "#{File.expand_path(__FILE__)}/../vendor/gems/process_manager-0.0.13" gem "codedeploy-commands", "1.0.0", :path => "#{File.expand_path(__FILE__)}/../vendor/gems/codedeploy-commands-1.0.0" +gem "simple_pid", "0.2.1", :path => "#{File.expand_path(__FILE__)}/../vendor/gems/simple_pid-0.2.1" group :test do gem 'test-unit' diff --git a/Rakefile b/Rakefile index 0d58db64..802b1a74 100644 --- a/Rakefile +++ b/Rakefile @@ -11,6 +11,7 @@ Rake::TestTask.new(:test) do |t| t.libs << ['test', 'lib', 'test/helpers'] test_files = FileList.new("test/**/*_test.rb") + test_files.exclude("test/instance_agent/plugins/windows/*_test.rb") t.test_files = test_files t.verbose = true end @@ -18,7 +19,7 @@ task :default => [:version_tracking, :test] task :release => [:version_tracking, :test] desc "Run unit tests in spec/" -RSpec::Core::RakeTask.new(:spec) +RSpec::Core::RakeTask.new({:exclude_pattern =>'spec/aws/codedeploy/local/deployer_spec.rb'}) task :test => :spec begin diff --git a/bin/codedeploy-agent b/bin/codedeploy-agent index 8f3560a2..6c84218e 100755 --- a/bin/codedeploy-agent +++ b/bin/codedeploy-agent @@ -2,7 +2,7 @@ $:.unshift File.join(File.dirname(File.expand_path('..', __FILE__)), 'lib') -ruby_versions = ["3.0", "2.7", "2.6", "2.5", "2.4", "2.3", "2.2", "2.1", "2.0"] +ruby_versions = ["3.2", "3.1", "3.0", "2.7", "2.6", "2.5", "2.4", "2.3", "2.2", "2.1", "2.0"] actual_ruby_version = RUBY_VERSION.split('.').map{|s|s.to_i} left_bound = '2.0.0'.split('.').map{|s|s.to_i} ruby_bin = nil diff --git a/bin/codedeploy-local b/bin/codedeploy-local index 4a723be9..6420fcdc 100755 --- a/bin/codedeploy-local +++ b/bin/codedeploy-local @@ -131,7 +131,7 @@ begin rescue Docopt::Exit => e puts e.message exit(false) -rescue AWS::CodeDeploy::Local::CLIValidator::ValidationError,InstanceMetadata::InstanceMetadataError,SystemCallError,ArgumentError => e +rescue AWS::CodeDeploy::Local::CLIValidator::ValidationError,SystemCallError,ArgumentError => e puts "ERROR: #{e.message}" exit(false) rescue Aws::Errors::MissingCredentialsError => e diff --git a/bin/install b/bin/install index bfc25a88..22a12bb2 100755 --- a/bin/install +++ b/bin/install @@ -5,31 +5,39 @@ # than 2.0. Testing on multiple Ruby versions is required for # changes to this part of the code. ################################################################## -class Proxy - instance_methods.each do |m| - undef_method m unless m =~ /(^__|^send$|^object_id$)/ + +class LoggerWrapper + def initialize(loggers) + @loggers = loggers end - def initialize(*targets) - @targets = targets + def debug(message) + @loggers.each do |logger| + logger.debug(message) + end end - def path - @targets.map do |target| - if target.respond_to?(:path) - target.__send__(:path) - else - # default to to_s since it's just used as a label for log statements. - target.__send__(:to_s) - end + def error(message) + @loggers.each do |logger| + logger.error(message) end end - protected + def info(message) + @loggers.each do |logger| + logger.info(message) + end + end - def method_missing(name, *args, &block) - @targets.map do |target| - target.__send__(name, *args, &block) + def level(message) + @loggers.each do |logger| + logger.level = message + end + end + + def warn(message) + @loggers.each do |logger| + logger.warn(message) end end end @@ -40,17 +48,17 @@ require 'logger' if($stdout.isatty) # if we are being run in a terminal, log to stdout and the log file. - @log = Logger.new(Proxy.new(File.open(log_file_path, 'a+'), $stdout)) + @log = LoggerWrapper.new([Logger.new(log_file_path), Logger.new($stdout)]) + @log.level(Logger::INFO) else # keep at most 2MB of old logs rotating out 1MB at a time @log = Logger.new(log_file_path, 2, 1048576) + @log.level = Logger::INFO # make sure anything coming out of ruby ends up in the log file $stdout.reopen(log_file_path, 'a+') $stderr.reopen(log_file_path, 'a+') end -@log.level = Logger::INFO - require 'net/http' # This class is copied (almost directly) from lib/instance_metadata.rb @@ -128,7 +136,7 @@ class IMDS Net::HTTP.start(IP_ADDRESS, 80, :read_timeout => 10, :open_timeout => 10) do |http| response = http.request(request) if block_given? - yield(response) + yield(response) elsif response.kind_of? Net::HTTPSuccess response.body else @@ -153,7 +161,7 @@ class IMDS end class S3Bucket - # Split out as older versions of ruby dont like multi entry attr + # Split out as older versions of ruby dont like multi entry attr attr :domain attr :region attr :bucket @@ -203,8 +211,8 @@ to check for a running agent. To use a HTTP proxy, specify --proxy followed by the proxy server defined by http://hostname:port -This install script needs Ruby version 2.x installed as a prerequisite. -Currently recommended Ruby versions are 2.0.0, 2.1.8, 2.2.4, 2.3, 2.4, 2.5, 2.6 and 2.7. +This install script needs Ruby versions 2.x or 3.x installed as a prerequisite. +Currently recommended Ruby versions are 2.0.0, 2.1.8, 2.2.4, 2.3, 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, and 3.2 If multiple Ruby versions are installed, the default ruby version will be used. If the default ruby version does not satisfy requirement, the newest version will be used. If you do not have a supported Ruby version installed, please install one of them first. @@ -213,7 +221,7 @@ EOF end def supported_ruby_versions - ['3.0', '2.7', '2.6', '2.5', '2.4', '2.3', '2.2', '2.1', '2.0'] + ['3.2','3.1','3.0', '2.7', '2.6', '2.5', '2.4', '2.3', '2.2', '2.1', '2.0'] end # check ruby version, only version 2.x 3.x works @@ -231,8 +239,8 @@ EOF if(File.exist?("/usr/bin/ruby#{version}")) return "/usr/bin/ruby#{version}" elsif (File.symlink?("/usr/bin/ruby#{version}")) - @log.error("The symlink /usr/bin/ruby#{version} exists, but it's linked to a non-existent directory or non-executable file.") - exit(1) + @log.error("The symlink /usr/bin/ruby#{version} exists, but it's linked to a non-existent directory or non-executable file.") + exit(1) end end @@ -299,10 +307,10 @@ EOF # change interpreter when symlink /usr/bin/ruby2.x exists, but running with non-supported ruby version actual_ruby_version = RUBY_VERSION.split('.').map{|s|s.to_i} left_bound = '2.0.0'.split('.').map{|s|s.to_i} - right_bound = '3.0.0'.split('.').map{|s|s.to_i} + right_bound = '3.2.1'.split('.').map{|s|s.to_i} if (actual_ruby_version <=> left_bound) < 0 if(!@reexeced) - @log.info("The current Ruby version is not 2.x or 3.0.x! Restarting the installer with #{ruby_interpreter_path}") + @log.info("The current Ruby version is not 2.x or 3.x! Restarting the installer with #{ruby_interpreter_path}") exec("#{ruby_interpreter_path}", __FILE__, '--re-execed' , *@args) else unsupported_ruby_version_error @@ -393,7 +401,7 @@ EOF exceptions = [OpenURI::HTTPError, OpenSSL::SSL::SSLError] begin uri.open(:ssl_verify_mode => OpenSSL::SSL::VERIFY_PEER, :redirect => true, :read_timeout => 120, :proxy => @http_proxy) do |s3| - package_file.write(s3.read) + package_file.write(s3.read) end rescue *exceptions => e @log.warn("Could not find package to download at '#{uri.to_s}' - Retrying... Attempt: '#{retries.to_s}'") @@ -406,7 +414,7 @@ EOF exit(1) end end -end + end def get_version_file_from_s3(s3_bucket, key) @log.info("Downloading version file from bucket #{s3_bucket.bucket} and key #{key}...") diff --git a/codedeploy_agent.gemspec b/codedeploy_agent.gemspec index 799ac5fe..699e7138 100644 --- a/codedeploy_agent.gemspec +++ b/codedeploy_agent.gemspec @@ -1,6 +1,6 @@ Gem::Specification.new do |spec| spec.name = 'aws_codedeploy_agent' - spec.version = '1.5.0' + spec.version = '1.6.0' spec.summary = 'Packages AWS CodeDeploy agent libraries' spec.description = 'AWS CodeDeploy agent is responsible for doing the actual work of deploying software on an individual EC2 instance' spec.author = 'Amazon Web Services' @@ -9,16 +9,15 @@ Gem::Specification.new do |spec| spec.bindir = ['bin'] spec.require_paths = ['lib'] spec.license = 'Apache-2.0' - spec.required_ruby_version = '~> 2.0' + spec.required_ruby_version = '>= 2.7.0' spec.add_dependency('gli', '~> 2.5') spec.add_dependency('json_pure', '~> 1.6') spec.add_dependency('archive-tar-minitar', '~> 0.5.2') spec.add_dependency('rubyzip', '~> 1.3.0') - spec.add_dependency('logging', '~> 1.8') + spec.add_dependency('logging', '~> 2.2') spec.add_dependency('aws-sdk-core', '~> 3') spec.add_dependency('aws-sdk-s3', '~> 1') - spec.add_dependency('simple_pid', '~> 0.2.1') spec.add_dependency('docopt', '~> 0.5.0') spec.add_dependency('concurrent-ruby', '~> 1.1.9') diff --git a/lib/aws/codedeploy/local/cli_validator.rb b/lib/aws/codedeploy/local/cli_validator.rb index bdf06d5d..89583877 100644 --- a/lib/aws/codedeploy/local/cli_validator.rb +++ b/lib/aws/codedeploy/local/cli_validator.rb @@ -27,7 +27,7 @@ def validate(args) raise ValidationError.new("location #{location} cannot be http, only encrypted (https) url endpoints supported") end - if (uri.scheme != 'https' && uri.scheme != 's3' && !File.exists?(location)) + if (uri.scheme != 'https' && uri.scheme != 's3' && !File.exist?(location)) raise ValidationError.new("location #{location} is specified as a file or directory which does not exist") end @@ -41,10 +41,10 @@ def validate(args) if (type == 'directory' && (uri.scheme != 'https' && uri.scheme != 's3' && File.directory?(location))) appspec_filename = args['--appspec-filename'] - if !appspec_filename.nil? && !File.exists?("#{location}/#{appspec_filename}") + if !appspec_filename.nil? && !File.exist?("#{location}/#{appspec_filename}") raise ValidationError.new("Expecting appspec file at location #{location}/#{appspec_filename} but it is not found there. Please either run the CLI from within a directory containing the #{appspec_filename} file or specify a bundle location containing an #{appspec_filename} file in its root directory") end - if appspec_filename.nil? && !File.exists?("#{location}/appspec.yml") && !File.exists?("#{location}/appspec.yaml") + if appspec_filename.nil? && !File.exist?("#{location}/appspec.yml") && !File.exist?("#{location}/appspec.yaml") raise ValidationError.new("Expecting appspec file at location #{location}/appspec.yml or #{location}/appspec.yaml but it is not found there. Please either run the CLI from within a directory containing the appspec.yml or appspec.yaml file or specify a bundle location containing an appspec.yml or appspec.yaml file in its root directory") end end diff --git a/lib/instance_agent/log.rb b/lib/instance_agent/log.rb index ced996b0..b54aa0f8 100644 --- a/lib/instance_agent/log.rb +++ b/lib/instance_agent/log.rb @@ -8,7 +8,7 @@ class InstanceAgent::DeploymentLog def initialize deployment_logs_dir = File.join(InstanceAgent::Config.config[:root_dir], 'deployment-logs') - FileUtils.mkdir_p(deployment_logs_dir) unless File.exists? deployment_logs_dir + FileUtils.mkdir_p(deployment_logs_dir) unless File.exist? deployment_logs_dir @deployment_log ||= Logger.new(File.join(deployment_logs_dir, "#{InstanceAgent::Config.config[:program_name]}-deployments.log"), 8, 64 * 1024 * 1024) @deployment_log.formatter = proc do |severity, datetime, progname, msg| "[#{datetime.strftime('%Y-%m-%d %H:%M:%S.%L')}] #{msg}\n" diff --git a/lib/instance_agent/plugins/codedeploy/hook_executor.rb b/lib/instance_agent/plugins/codedeploy/hook_executor.rb index a4414121..21884d2e 100644 --- a/lib/instance_agent/plugins/codedeploy/hook_executor.rb +++ b/lib/instance_agent/plugins/codedeploy/hook_executor.rb @@ -210,7 +210,7 @@ def script_error_prefix(script_location, script_run_as_user) private def create_script_log_file_if_needed script_log_file_location = File.join(@current_deployment_root_dir, ScriptLog::SCRIPT_LOG_FILE_RELATIVE_LOCATION) - if(!File.exists?(script_log_file_location)) + if(!File.exist?(script_log_file_location)) unless File.directory?(File.dirname(script_log_file_location)) FileUtils.mkdir_p(File.dirname(script_log_file_location)) end @@ -232,7 +232,7 @@ def script_absolute_path(script) def parse_app_spec app_spec_location = File.join(@deployment_archive_dir, @app_spec_path) log(:debug, "Checking for app spec in #{app_spec_location}") - unless File.exists?(app_spec_location) + unless File.exist?(app_spec_location) raise <<-MESSAGE.gsub(/^[\s\t]*/, '').gsub(/\s*\n/, ' ').strip The CodeDeploy agent did not find an AppSpec file within the unpacked revision directory at revision-relative path "#{@app_spec_path}". The revision was unpacked to directory "#{@deployment_archive_dir}", and the AppSpec file was expected but not found at path @@ -249,7 +249,7 @@ def select_correct_deployment_root_dir(current_deployment_root_dir, last_success hook_deployment_mapping = mapping_between_hooks_and_deployments if(select_correct_mapping_for_hooks == LAST_SUCCESSFUL_DEPLOYMENT && !File.exist?(File.join(@deployment_root_dir, 'deployment-archive'))) @deployment_root_dir = last_successful_deployment_root_dir - elsif(select_correct_mapping_for_hooks == MOST_RECENT_DEPLOYMENT && !File.exists?(File.join(@deployment_root_dir, 'deployment-archive'))) + elsif(select_correct_mapping_for_hooks == MOST_RECENT_DEPLOYMENT && !File.exist?(File.join(@deployment_root_dir, 'deployment-archive'))) @deployment_root_dir = most_recent_deployment_dir end end diff --git a/lib/instance_agent/plugins/codedeploy/installer.rb b/lib/instance_agent/plugins/codedeploy/installer.rb index 9450c88e..b53dd733 100644 --- a/lib/instance_agent/plugins/codedeploy/installer.rb +++ b/lib/instance_agent/plugins/codedeploy/installer.rb @@ -27,7 +27,7 @@ def initialize(opts = {}) def install(deployment_group_id, application_specification) cleanup_file = File.join(deployment_instructions_dir, "#{deployment_group_id}-cleanup") - if File.exists?(cleanup_file) + if File.exist?(cleanup_file) commands = InstanceAgent::Plugins::CodeDeployPlugin::InstallInstruction.parse_remove_commands(File.read(cleanup_file)) commands.each do |cmd| cmd.execute @@ -116,7 +116,7 @@ def generate_directory_copy(i, absolute_source_path, destination, file_exists_be private def generate_normal_copy(i, absolute_source_path, destination, file_exists_behavior) - if File.exists?(destination) + if File.exist?(destination) case file_exists_behavior when "DISALLOW" raise "The deployment failed because a specified file already exists at this location: #{destination}" @@ -136,7 +136,7 @@ def generate_normal_copy(i, absolute_source_path, destination, file_exists_behav def fill_in_missing_ancestors(i, destination) missing_ancestors = [] parent_dir = File.dirname(destination) - while !File.exists?(parent_dir) && + while !File.exist?(parent_dir) && parent_dir != "." && parent_dir != "/" missing_ancestors.unshift(parent_dir) parent_dir = File.dirname(parent_dir) diff --git a/lib/instance_agent/plugins/codedeploy/onpremise_config.rb b/lib/instance_agent/plugins/codedeploy/onpremise_config.rb index 1976da21..774c62e0 100644 --- a/lib/instance_agent/plugins/codedeploy/onpremise_config.rb +++ b/lib/instance_agent/plugins/codedeploy/onpremise_config.rb @@ -7,7 +7,7 @@ class OnPremisesConfig def self.configure file_path = InstanceAgent::Config.config[:on_premises_config_file] file_config = nil - if File.exists?(file_path) && File.readable?(file_path) + if File.readable?(file_path) begin file_config = YAML.load(File.read(file_path)).symbolize_keys rescue diff --git a/spec/aws/codedeploy/local/cli_validator_spec.rb b/spec/aws/codedeploy/local/cli_validator_spec.rb index f3a54e68..fa47d944 100644 --- a/spec/aws/codedeploy/local/cli_validator_spec.rb +++ b/spec/aws/codedeploy/local/cli_validator_spec.rb @@ -32,7 +32,7 @@ end it 'returns the same arguments' do - allow(File).to receive(:exists?).with(VALID_FILE).and_return(true) + allow(File).to receive(:exist?).with(VALID_FILE).and_return(true) expect(validator.validate(args)).to equal(args) end end @@ -93,10 +93,10 @@ end it 'throws a ValidationError' do - allow(File).to receive(:exists?).with(FAKE_DIRECTORY).and_return(true) + allow(File).to receive(:exist?).with(FAKE_DIRECTORY).and_return(true) allow(File).to receive(:directory?).with(FAKE_DIRECTORY).and_return(true) - expect(File).to receive(:exists?).with("#{FAKE_DIRECTORY}/appspec.yml").and_return(false) - expect(File).to receive(:exists?).with("#{FAKE_DIRECTORY}/appspec.yaml").and_return(false) + expect(File).to receive(:exist?).with("#{FAKE_DIRECTORY}/appspec.yml").and_return(false) + expect(File).to receive(:exist?).with("#{FAKE_DIRECTORY}/appspec.yaml").and_return(false) expect{validator.validate(args)}.to raise_error(AWS::CodeDeploy::Local::CLIValidator::ValidationError, "Expecting appspec file at location #{FAKE_DIRECTORY}/appspec.yml or #{FAKE_DIRECTORY}/appspec.yaml but it is not found there. Please either run the CLI from within a directory containing the appspec.yml or appspec.yaml file or specify a bundle location containing an appspec.yml or appspec.yaml file in its root directory") end end @@ -109,9 +109,9 @@ end it 'throws a ValidationError' do - allow(File).to receive(:exists?).with(FAKE_DIRECTORY).and_return(true) + allow(File).to receive(:exist?).with(FAKE_DIRECTORY).and_return(true) allow(File).to receive(:directory?).with(FAKE_DIRECTORY).and_return(true) - expect(File).to receive(:exists?).with("#{FAKE_DIRECTORY}/appspec-override.yaml").and_return(false) + expect(File).to receive(:exist?).with("#{FAKE_DIRECTORY}/appspec-override.yaml").and_return(false) expect{validator.validate(args)}.to raise_error(AWS::CodeDeploy::Local::CLIValidator::ValidationError, "Expecting appspec file at location #{FAKE_DIRECTORY}/appspec-override.yaml but it is not found there. Please either run the CLI from within a directory containing the appspec-override.yaml file or specify a bundle location containing an appspec-override.yaml file in its root directory") end end @@ -129,7 +129,7 @@ end it 'throws a ValidationError' do - allow(File).to receive(:exists?).with(FAKE_FILE_WHICH_DOES_NOT_EXIST).and_return(false) + allow(File).to receive(:exist?).with(FAKE_FILE_WHICH_DOES_NOT_EXIST).and_return(false) expect{validator.validate(args)}.to raise_error(AWS::CodeDeploy::Local::CLIValidator::ValidationError, "location #{FAKE_FILE_WHICH_DOES_NOT_EXIST} is specified as a file or directory which does not exist") end end @@ -147,7 +147,7 @@ end it 'throws a ValidationError' do - allow(File).to receive(:exists?).with(FAKE_FILE).and_return(true) + allow(File).to receive(:exist?).with(FAKE_FILE).and_return(true) allow(File).to receive(:file?).with(FAKE_FILE).and_return(true) expect{validator.validate(args)}.to raise_error(AWS::CodeDeploy::Local::CLIValidator::ValidationError, "location #{FAKE_FILE} is specified with type directory but it is a file") end @@ -173,7 +173,7 @@ end it 'throws a ValidationError' do - allow(File).to receive(:exists?).with(FAKE_DIRECTORY).and_return(true) + allow(File).to receive(:exist?).with(FAKE_DIRECTORY).and_return(true) allow(File).to receive(:directory?).with(FAKE_DIRECTORY).and_return(true) expect{validator.validate(argszip)}.to raise_error(AWS::CodeDeploy::Local::CLIValidator::ValidationError, "location #{FAKE_DIRECTORY} is specified as a compressed local file but it is a directory") expect{validator.validate(argstgz)}.to raise_error(AWS::CodeDeploy::Local::CLIValidator::ValidationError, "location #{FAKE_DIRECTORY} is specified as a compressed local file but it is a directory") @@ -189,9 +189,9 @@ end it 'throws a ValidationError' do - allow(File).to receive(:exists?).with(FAKE_DIRECTORY).and_return(true) + allow(File).to receive(:exist?).with(FAKE_DIRECTORY).and_return(true) allow(File).to receive(:directory?).with(FAKE_DIRECTORY).and_return(true) - expect(File).to receive(:exists?).with("#{FAKE_DIRECTORY}/appspec.yml").and_return(true) + expect(File).to receive(:exist?).with("#{FAKE_DIRECTORY}/appspec.yml").and_return(true) expect{validator.validate(args)}.to raise_error(AWS::CodeDeploy::Local::CLIValidator::ValidationError, "The only events that can be specified before DownloadBundle are BeforeBlockTraffic,AfterBlockTraffic,ApplicationStop. Please fix the order of your specified events: #{args['--events']}") end end @@ -205,9 +205,9 @@ end it 'throws a ValidationError' do - allow(File).to receive(:exists?).with(FAKE_DIRECTORY).and_return(true) + allow(File).to receive(:exist?).with(FAKE_DIRECTORY).and_return(true) allow(File).to receive(:directory?).with(FAKE_DIRECTORY).and_return(true) - expect(File).to receive(:exists?).with("#{FAKE_DIRECTORY}/appspec.yml").and_return(true) + expect(File).to receive(:exist?).with("#{FAKE_DIRECTORY}/appspec.yml").and_return(true) expect{validator.validate(args)}.to raise_error(AWS::CodeDeploy::Local::CLIValidator::ValidationError, "The only events that can be specified before DownloadBundle are BeforeBlockTraffic,AfterBlockTraffic,ApplicationStop. Please fix the order of your specified events: #{args['--events']}") end end @@ -221,9 +221,9 @@ end it 'throws a ValidationError' do - allow(File).to receive(:exists?).with(FAKE_DIRECTORY).and_return(true) + allow(File).to receive(:exist?).with(FAKE_DIRECTORY).and_return(true) allow(File).to receive(:directory?).with(FAKE_DIRECTORY).and_return(true) - expect(File).to receive(:exists?).with("#{FAKE_DIRECTORY}/appspec.yml").and_return(true) + expect(File).to receive(:exist?).with("#{FAKE_DIRECTORY}/appspec.yml").and_return(true) expect{validator.validate(args)}.to raise_error(AWS::CodeDeploy::Local::CLIValidator::ValidationError, "The only events that can be specified before Install are BeforeBlockTraffic,AfterBlockTraffic,ApplicationStop,DownloadBundle,BeforeInstall. Please fix the order of your specified events: #{args['--events']}") end end @@ -237,9 +237,9 @@ end it 'returns the same arguments' do - allow(File).to receive(:exists?).with(FAKE_DIRECTORY).and_return(true) + allow(File).to receive(:exist?).with(FAKE_DIRECTORY).and_return(true) allow(File).to receive(:directory?).with(FAKE_DIRECTORY).and_return(true) - expect(File).to receive(:exists?).with("#{FAKE_DIRECTORY}/appspec.yml").and_return(true) + expect(File).to receive(:exist?).with("#{FAKE_DIRECTORY}/appspec.yml").and_return(true) expect(validator.validate(args)).to equal(args) end end diff --git a/spec/aws/codedeploy/local/deployer_spec.rb b/spec/aws/codedeploy/local/deployer_spec.rb index bdf11077..c22eff03 100644 --- a/spec/aws/codedeploy/local/deployer_spec.rb +++ b/spec/aws/codedeploy/local/deployer_spec.rb @@ -45,11 +45,12 @@ allow(Dir).to receive(:pwd).and_return test_working_directory ProcessManager::Config.config[:root_dir] = test_working_directory allow(AWS::CodeDeploy::Local::Deployer).to receive(:random_deployment_id).and_return(TEST_DEPLOYMENT_ID) - allow(File).to receive(:exists?).with(@config_file_location).and_return(true) + allow(File).to receive(:exist?).with(@config_file_location).and_return(true) allow(File).to receive(:readable?).with(@config_file_location).and_return(true) - allow(File).to receive(:exists?).with(AWS::CodeDeploy::Local::Deployer::CONF_DEFAULT_LOCATION).and_return(false) + allow(File).to receive(:exist?).with(AWS::CodeDeploy::Local::Deployer::CONF_DEFAULT_LOCATION).and_return(false) allow(File).to receive(:readable?).with(AWS::CodeDeploy::Local::Deployer::CONF_DEFAULT_LOCATION).and_return(false) allow(File).to receive(:readable?).with(InstanceAgent::Config.config[:on_premises_config_file]).and_return(false) + allow(File).to receive(:exist?) end def create_config_file(working_directory, log_dir = nil) @@ -114,7 +115,7 @@ def create_config_file(working_directory, log_dir = nil) config_file_location = create_config_file(new_test_working_directory, not_yet_existing_directory) expect(FileUtils).to receive(:mkdir_p).with(not_yet_existing_directory).and_call_original allow(File).to receive(:readable?).with(config_file_location).and_return(true) - allow(File).to receive(:exists?).with(config_file_location).and_return(true) + allow(File).to receive(:exist?).with(config_file_location).and_return(true) AWS::CodeDeploy::Local::Deployer.new(config_file_location) end end @@ -133,7 +134,7 @@ def create_config_file(working_directory, log_dir = nil) end it 'deploys the local file and calls the executor to execute all commands' do - allow(File).to receive(:exists?).with(SAMPLE_FILE_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_FILE_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) expect(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor).to receive(:new). @@ -151,7 +152,7 @@ def create_config_file(working_directory, log_dir = nil) context 'when script fails with script error' do it 'prints the correct error message to the screen and exits' do - allow(File).to receive(:exists?).with(SAMPLE_FILE_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_FILE_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) expect(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor).to receive(:new). @@ -192,7 +193,7 @@ def create_config_file(working_directory, log_dir = nil) end it 'deploys the local file and calls the executor to execute all specified commands after DownloadBundle and Install commands' do - allow(File).to receive(:exists?).with(SAMPLE_FILE_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_FILE_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) all_possible_lifecycle_events = AWS::CodeDeploy::Local::Deployer::DEFAULT_ORDERED_LIFECYCLE_EVENTS.to_set.merge(NON_DEFAULT_LIFECYCLE_EVENTS).to_a @@ -221,7 +222,7 @@ def create_config_file(working_directory, log_dir = nil) end it 'corrects the order of download bundle followed by install' do - allow(File).to receive(:exists?).with(SAMPLE_FILE_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_FILE_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) all_possible_lifecycle_events = AWS::CodeDeploy::Local::Deployer::DEFAULT_ORDERED_LIFECYCLE_EVENTS @@ -254,7 +255,7 @@ def create_config_file(working_directory, log_dir = nil) end it 'deploys the local directory and calls the executor to execute all commands' do - allow(File).to receive(:exists?).with(SAMPLE_DIRECTORY_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_DIRECTORY_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) expect(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor).to receive(:new). @@ -280,7 +281,7 @@ def create_config_file(working_directory, log_dir = nil) end it 'deploys the local directory and calls the executor to execute all commands' do - allow(File).to receive(:exists?).with(SAMPLE_DIRECTORY_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_DIRECTORY_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) expect(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor).to receive(:new). @@ -457,7 +458,7 @@ def create_config_file(working_directory, log_dir = nil) "--version"=>false} end it 'defaults to LocalFleet' do - allow(File).to receive(:exists?).with(SAMPLE_FILE_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_FILE_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) expect(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor).to receive(:new). @@ -486,7 +487,7 @@ def create_config_file(working_directory, log_dir = nil) "--version"=>false} end it 'defaults to the bundle-location' do - allow(File).to receive(:exists?).with(SAMPLE_FILE_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_FILE_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) expect(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor).to receive(:new). @@ -516,7 +517,7 @@ def create_config_file(working_directory, log_dir = nil) "--version"=>false} end it 'generates a spec with the provided value' do - allow(File).to receive(:exists?).with(SAMPLE_FILE_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_FILE_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) expect(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor).to receive(:new). @@ -546,7 +547,7 @@ def create_config_file(working_directory, log_dir = nil) "--version"=>false} end it 'generates a spec with the provided value' do - allow(File).to receive(:exists?).with(SAMPLE_FILE_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_FILE_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) expect(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor).to receive(:new). @@ -576,7 +577,7 @@ def create_config_file(working_directory, log_dir = nil) "--version"=>false} end it 'generates a spec with the provided value' do - allow(File).to receive(:exists?).with(SAMPLE_FILE_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_FILE_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) expect(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor).to receive(:new). @@ -607,7 +608,7 @@ def create_config_file(working_directory, log_dir = nil) "--version"=>false} end it 'generates a spec with the provided value' do - allow(File).to receive(:exists?).with(SAMPLE_FILE_BUNDLE).and_return(true) + allow(File).to receive(:exist?).with(SAMPLE_FILE_BUNDLE).and_return(true) executor = double(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor) expect(InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor).to receive(:new). diff --git a/test/instance_agent/plugins/codedeploy/hook_executor_test.rb b/test/instance_agent/plugins/codedeploy/hook_executor_test.rb index edd9fa37..f710925d 100644 --- a/test/instance_agent/plugins/codedeploy/hook_executor_test.rb +++ b/test/instance_agent/plugins/codedeploy/hook_executor_test.rb @@ -39,8 +39,8 @@ def create_hook_executor(revision_envs = nil) logger = mock logger.stubs(:log) InstanceAgent::DeploymentLog.stubs(:instance).returns(logger) - File.stubs(:exists?).returns(false) - File.stubs(:exists?).with(){|value| value.is_a?(String) && value.end_with?("/app_spec")}.returns(true) + File.stubs(:exist?).returns(false) + File.stubs(:exist?).with(){|value| value.is_a?(String) && value.end_with?("/app_spec")}.returns(true) end context "when creating a hook command" do @@ -90,7 +90,7 @@ def create_hook_executor(revision_envs = nil) end should "fail if app spec not found" do - File.stubs(:exists?).with(){|value| value.is_a?(String) && value.end_with?("/app_spec")}.returns(false) + File.stubs(:exist?).with(){|value| value.is_a?(String) && value.end_with?("/app_spec")}.returns(false) assert_raised_with_message("The CodeDeploy agent did not find an AppSpec file within the unpacked revision directory at revision-relative path \"app_spec\". The revision was unpacked to directory \"deployment/root/dir/deployment-archive\", and the AppSpec file was expected but not found at path \"deployment/root/dir/deployment-archive/app_spec\". Consult the AWS CodeDeploy Appspec documentation for more information at http://docs.aws.amazon.com/codedeploy/latest/userguide/reference-appspec-file.html", RuntimeError)do @hook_executor = create_hook_executor end diff --git a/test/instance_agent/plugins/codedeploy/install_instruction_test.rb b/test/instance_agent/plugins/codedeploy/install_instruction_test.rb index 0a094e8e..4313933f 100644 --- a/test/instance_agent/plugins/codedeploy/install_instruction_test.rb +++ b/test/instance_agent/plugins/codedeploy/install_instruction_test.rb @@ -60,7 +60,7 @@ class InstallInstructionTest < InstanceAgentTestCase @mock_file.stubs(:close) @mock_file.stubs(:exist?).returns(false) File.stubs(:open).returns(@mock_file) - File.stubs(:exists?).returns(false) + File.stubs(:exist?).returns(false) end should "return a collection containing a copy command and a mkdir command" do diff --git a/test/instance_agent/plugins/codedeploy/installer_test.rb b/test/instance_agent/plugins/codedeploy/installer_test.rb index e588c829..a465ab9d 100644 --- a/test/instance_agent/plugins/codedeploy/installer_test.rb +++ b/test/instance_agent/plugins/codedeploy/installer_test.rb @@ -63,8 +63,8 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase .returns(@instruction_builder) @instruction_builder.stubs(:cleanup).returns(nil) - File.stubs(:exists?).returns(false) - File.stubs(:exists?).with("deploy-instructions-dir/ig1-cleanup").returns(false) + File.stubs(:exist?).returns(false) + File.stubs(:exist?).with("deploy-instructions-dir/ig1-cleanup").returns(false) @app_spec.stubs(:permissions).returns([]) @app_spec.stubs(:files).returns([]) @@ -75,7 +75,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase context "with an existing cleanup file" do setup do - File.stubs(:exists?).with("deploy-instructions-dir/ig1-cleanup").returns(true) + File.stubs(:exist?).with("deploy-instructions-dir/ig1-cleanup").returns(true) end should "parse the file, execute the commands and remove the file before generating new install instructions" do @@ -133,8 +133,8 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase :destination => "dst2")]) File.stubs(:directory?).returns(false) - File.stubs(:exists?).returns(false) - File.stubs(:exists?).with(any_of("dst1", "dst2")).returns(true) + File.stubs(:exist?).returns(false) + File.stubs(:exist?).with(any_of("dst1", "dst2")).returns(true) @instruction_builder.stubs(:copy) end @@ -150,7 +150,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase end should "raise an error if the file already exists and @file_exists_behavior is set to 'DISALLOW'" do - File.stubs(:exists?).with("dst2/src2").returns(true) + File.stubs(:exist?).with("dst2/src2").returns(true) assert_raised_with_message("The deployment failed because a specified file already exists at this location: dst2/src2") do @installer.install(@deployment_group_id, @app_spec) @@ -163,7 +163,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase @app_spec .stubs(:file_exists_behavior) .returns("DISALLOW") - File.stubs(:exists?).with("dst2/src2").returns(true) + File.stubs(:exist?).with("dst2/src2").returns(true) assert_raised_with_message("The deployment failed because a specified file already exists at this location: dst2/src2") do @installer.install(@deployment_group_id, @app_spec) @@ -175,7 +175,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase .stubs(:files) .returns([stub(:source => "src1", :destination => "dst1")]) - File.stubs(:exists?).with("dst1/src1").returns(true) + File.stubs(:exist?).with("dst1/src1").returns(true) @instruction_builder .expects(:copy) .with("deploy-archive-dir/src1", "dst1/src1") @@ -190,7 +190,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase .stubs(:files) .returns([stub(:source => "src1", :destination => "dst1")]) - File.stubs(:exists?).with("dst1/src1").returns(true) + File.stubs(:exist?).with("dst1/src1").returns(true) @instruction_builder .expects(:copy) .with("deploy-archive-dir/src1", "dst1/src1") @@ -203,7 +203,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase .stubs(:files) .returns([stub(:source => "src1", :destination => "dst1")]) - File.stubs(:exists?).with("dst1/src1").returns(true) + File.stubs(:exist?).with("dst1/src1").returns(true) @instruction_builder.expects(:copy).never @installer.file_exists_behavior = "RETAIN" @installer.install(@deployment_group_id, @app_spec) @@ -216,14 +216,14 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase .stubs(:files) .returns([stub(:source => "src1", :destination => "dst1")]) - File.stubs(:exists?).with("dst1/src1").returns(true) + File.stubs(:exist?).with("dst1/src1").returns(true) @instruction_builder.expects(:copy).never assert_equal(@installer.file_exists_behavior, "DISALLOW") @installer.install(@deployment_group_id, @app_spec) end should "raise an error if the file already exists and @file_exists_behavior is set to some invalid value" do - File.stubs(:exists?).with("dst2/src2").returns(true) + File.stubs(:exist?).with("dst2/src2").returns(true) @installer.file_exists_behavior = "SOMETHING_WEIRD" assert_raised_with_message("The deployment failed because an invalid option was specified for fileExistsBehavior: #{@installer.file_exists_behavior}. Valid options include OVERWRITE, RETAIN, and DISALLOW.") do @@ -236,7 +236,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase .stubs(:files) .returns([stub(:source => "src1", :destination => "dst1")]) - File.stubs(:exists?).with("dst1").returns(false) + File.stubs(:exist?).with("dst1").returns(false) command_sequence = sequence("command sequence") @instruction_builder @@ -275,7 +275,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase .stubs(:files) .returns([stub(:source => "src1", :destination => "dst1/foo/bar")]) - File.stubs(:exists?).with("dst1").returns(true) + File.stubs(:exist?).with("dst1").returns(true) command_sequence = sequence("command sequence") @instruction_builder @@ -326,7 +326,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase .returns([stub(:source => "src1", :destination => "/dst1/foo/bar")]) - File.stubs(:exists?).with("/dst1").returns(true) + File.stubs(:exist?).with("/dst1").returns(true) command_sequence = sequence("command sequence") @instruction_builder @@ -369,7 +369,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase Dir.stubs(:entries) .with("deploy-archive-dir/src1") .returns([".", "..", "foo", "bar"]) - File.stubs(:exists?).with("dst1/bar").returns(true) + File.stubs(:exist?).with("dst1/bar").returns(true) @instruction_builder.stubs(:mkdir) @instruction_builder.stubs(:copy) @@ -383,7 +383,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase .with("deploy-archive-dir/src1") .returns([".", "..", "foo", "bar"]) File.stubs(:directory?).with("dst1").returns(true) - File.stubs(:exists?).with("dst1/bar").returns(true) + File.stubs(:exist?).with("dst1/bar").returns(true) @instruction_builder .expects(:copy) .with("deploy-archive-dir/src1/foo", "dst1/foo") @@ -401,7 +401,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase .with("deploy-archive-dir/src1") .returns([".", "..", "foo", "bar"]) File.stubs(:directory?).with("dst1").returns(true) - File.stubs(:exists?).with("dst1/bar").returns(true) + File.stubs(:exist?).with("dst1/bar").returns(true) @instruction_builder .expects(:copy) .with("deploy-archive-dir/src1/foo", "dst1/foo") @@ -466,7 +466,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase end should "raise an error if an entry already exists and @file_exists_behavior is set to 'DISALLOW'" do - File.stubs(:exists?).with("dst1/foo/bar").returns(true) + File.stubs(:exist?).with("dst1/foo/bar").returns(true) Dir.stubs(:entries) .with("deploy-archive-dir/src1") .returns([".", "..", "foo"]) @@ -483,7 +483,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase should "generate a copy command if the file already exists and @file_exists_behavior is set to 'OVERWRITE'" do File.stubs(:directory?).with("dst1/foo").returns(true) - File.stubs(:exists?).with("dst1/foo/bar").returns(true) + File.stubs(:exist?).with("dst1/foo/bar").returns(true) Dir.stubs(:entries) .with("deploy-archive-dir/src1") .returns([".", "..", "foo"]) @@ -499,7 +499,7 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase should "neither generate a copy command nor raise an error if the file already exists and @file_exists_behavior is set to 'RETAIN'" do File.stubs(:directory?).with("dst1/foo").returns(true) - File.stubs(:exists?).with("dst1/foo/bar").returns(true) + File.stubs(:exist?).with("dst1/foo/bar").returns(true) Dir.stubs(:entries) .with("deploy-archive-dir/src1") .returns([".", "..", "foo"]) @@ -555,8 +555,8 @@ class CodeDeployPluginInstallerTest < InstanceAgentTestCase Dir.stubs(:entries) .with("deploy-archive-dir/src3/dir1") .returns(["file1", ".", ".."]) - File.stubs(:exists?).returns(false) - File.stubs(:exists?).with(any_of("dst1","dst3")).returns(true) + File.stubs(:exist?).returns(false) + File.stubs(:exist?).with(any_of("dst1","dst3")).returns(true) @instruction_builder.stubs(:copying_file?).returns(false) @instruction_builder.stubs(:copying_file?).with("dst1/src1").returns(true) @instruction_builder.stubs(:making_directory?).returns(false) diff --git a/test/instance_agent/plugins/codedeploy/onpremise_config_test.rb b/test/instance_agent/plugins/codedeploy/onpremise_config_test.rb index df138eb5..53186100 100644 --- a/test/instance_agent/plugins/codedeploy/onpremise_config_test.rb +++ b/test/instance_agent/plugins/codedeploy/onpremise_config_test.rb @@ -4,9 +4,9 @@ class OnPremiseConfigTest < InstanceAgentTestCase linux_path = '/etc/codedeploy-agent/conf/codedeploy.onpremises.yml' - context "Config file doesn't exist" do + context "Config file does not exist or is not readable" do setup do - File.stubs(:exists?).with(linux_path).returns(false) + File.stubs(:readable?).with(linux_path).returns(false) end should "do nothing" do @@ -14,131 +14,115 @@ class OnPremiseConfigTest < InstanceAgentTestCase end end - context "Linux config file exists" do + context "Linux file is readable" do setup do - File.stubs(:exists?).with(linux_path).returns(true) + File.stubs(:readable?).with(linux_path).returns(true) end - context "Linux file is not readable" do + context "Linux file is valid" do + + linux_file = <<-END + region: us-east-test + aws_access_key_id: linuxkey + aws_secret_access_key: linuxsecretkey + iam_user_arn: test:arn + END + setup do - File.stubs(:readable?).with(linux_path).returns(false) + File.stubs(:read).with(linux_path).returns(linux_file) end - should "do nothing" do + should "set the ENV variables correctly" do OnPremisesConfig.configure + assert_equal 'us-east-test', ENV['AWS_REGION'] + assert_equal 'linuxkey', ENV['AWS_ACCESS_KEY'] + assert_equal 'linuxsecretkey', ENV['AWS_SECRET_KEY'] + assert_equal 'test:arn', ENV['AWS_HOST_IDENTIFIER'] end end - - context "Linux file is readable" do + + context "config file with invalid yaml" do + linux_file = <<-END + invalid yaml content + END + setup do - File.stubs(:readable?).with(linux_path).returns(true) + File.stubs(:read).with(linux_path).returns(linux_file) end - - context "Linux file is valid" do - - linux_file = <<-END - region: us-east-test - aws_access_key_id: linuxkey - aws_secret_access_key: linuxsecretkey - iam_user_arn: test:arn - END - - setup do - File.stubs(:read).with(linux_path).returns(linux_file) - end - - should "set the ENV variables correctly" do + + should "raise an exception" do + assert_raise do OnPremisesConfig.configure - assert_equal 'us-east-test', ENV['AWS_REGION'] - assert_equal 'linuxkey', ENV['AWS_ACCESS_KEY'] - assert_equal 'linuxsecretkey', ENV['AWS_SECRET_KEY'] - assert_equal 'test:arn', ENV['AWS_HOST_IDENTIFIER'] - end - end - - context "config file with invalid yaml" do - linux_file = <<-END - invalid yaml content - END - - setup do - File.stubs(:read).with(linux_path).returns(linux_file) - end - - should "raise an exception" do - assert_raise do - OnPremisesConfig.configure - end end end - - context "config file with session configuration" do - credentials_path = "/etc/codedeploy-agent/conf/.aws_credentials" - linux_file = <<-END - region: us-east-test - iam_session_arn: test:arn - aws_credentials_file: #{credentials_path} - END - access_key_id = "fake-access-key-id-#{rand 1000}" - credentials_file = <<-END + end + + context "config file with session configuration" do + credentials_path = "/etc/codedeploy-agent/conf/.aws_credentials" + linux_file = <<-END + region: us-east-test + iam_session_arn: test:arn + aws_credentials_file: #{credentials_path} + END + access_key_id = "fake-access-key-id-#{rand 1000}" + credentials_file = <<-END [default] aws_access_key_id = #{access_key_id} aws_secret_access_key = fake-secret-access-key aws_session_token = fake-session-token END - - setup do - File.stubs(:read).with(linux_path).returns(linux_file) - File.stubs(:read).with(credentials_path).returns(credentials_file) - File.stubs(:exist?).with(credentials_path).returns(true) - File.stubs(:readable?).with(credentials_path).returns(true) - end - - should "set the ENV variables correctly" do + + setup do + File.stubs(:read).with(linux_path).returns(linux_file) + File.stubs(:read).with(credentials_path).returns(credentials_file) + File.stubs(:exist?).with(credentials_path).returns(true) + File.stubs(:readable?).with(credentials_path).returns(true) + end + + should "set the ENV variables correctly" do + OnPremisesConfig.configure + assert_equal 'us-east-test', ENV['AWS_REGION'] + assert_equal 'test:arn', ENV['AWS_HOST_IDENTIFIER'] + assert_equal '/etc/codedeploy-agent/conf/.aws_credentials', ENV['AWS_CREDENTIALS_FILE'] + assert_equal access_key_id, Aws.config[:credentials].credentials.access_key_id + end + end + + context "config file with both session and user arns" do + linux_file = <<-END + region: us-east-test + iam_session_arn: test:arn + aws_credentials_file: /etc/codedeploy-agent/conf/.aws_credentials + aws_access_key_id: linuxkey + aws_secret_access_key: linuxsecretkey + iam_user_arn: test:arn + END + + setup do + File.stubs(:read).with(linux_path).returns(linux_file) + end + + should "raise an exception" do + assert_raise do OnPremisesConfig.configure - assert_equal 'us-east-test', ENV['AWS_REGION'] - assert_equal 'test:arn', ENV['AWS_HOST_IDENTIFIER'] - assert_equal '/etc/codedeploy-agent/conf/.aws_credentials', ENV['AWS_CREDENTIALS_FILE'] - assert_equal access_key_id, Aws.config[:credentials].credentials.access_key_id end end - - context "config file with both session and user arns" do - linux_file = <<-END - region: us-east-test - iam_session_arn: test:arn - aws_credentials_file: /etc/codedeploy-agent/conf/.aws_credentials - aws_access_key_id: linuxkey - aws_secret_access_key: linuxsecretkey - iam_user_arn: test:arn - END - - setup do - File.stubs(:read).with(linux_path).returns(linux_file) - end - - should "raise an exception" do - assert_raise do - OnPremisesConfig.configure - end - end + end + + context "config file missing region" do + linux_file = <<-END + aws_access_key_id: linuxkey + aws_secret_access_key: linuxsecretkey + iam_user_arn: test:arn + END + + setup do + File.stubs(:read).with(linux_path).returns(linux_file) end - - context "config file missing region" do - linux_file = <<-END - aws_access_key_id: linuxkey - aws_secret_access_key: linuxsecretkey - iam_user_arn: test:arn - END - - setup do - File.stubs(:read).with(linux_path).returns(linux_file) - end - - should "raise an exception" do - assert_raise do - OnPremisesConfig.configure - end + + should "raise an exception" do + assert_raise do + OnPremisesConfig.configure end end end diff --git a/test/instance_agent/plugins/windows/winagent_test.rb b/test/instance_agent/plugins/windows/winagent_test.rb index 0940c23e..0ea4fb24 100644 --- a/test/instance_agent/plugins/windows/winagent_test.rb +++ b/test/instance_agent/plugins/windows/winagent_test.rb @@ -16,30 +16,29 @@ class WinAgentTestClass < InstanceAgentTestCase context 'Win agent shell try to start agent' do setup do - # ENV.expects(:[]).at_least_once.returns("") - # - # @fake_runner = mock() - # InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller.stubs(:runner).returns(@fake_runner) - # - # logger_mock = mock() - # ::ProcessManager::Log.stubs(:init).returns(logger_mock) - # - # InstanceAgent::Config.expects(:load_config) - # InstanceAgent::Config.config.expects(:[]).with(:wait_between_runs).at_most(5).returns("0") - # InstanceAgent::Config.config.expects(:[]).at_least_once.returns("") + ENV.expects(:[]).at_least_once.returns("") + + @fake_runner = mock() + InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller.stubs(:runner).returns(@fake_runner) + + logger_mock = mock() + ::ProcessManager::Log.stubs(:init).returns(logger_mock) + + InstanceAgent::Config.expects(:load_config) + InstanceAgent::Config.config.expects(:[]).with(:wait_between_runs).at_most(5).returns("0") + InstanceAgent::Config.config.expects(:[]).at_least_once.returns("") end - #s"Skipped to get Ruby27 build passing. should 'starts succesfully' do - # @fake_runner.stubs(:run).times(2) - # FileUtils.expects(:cp_r).never - # @fake_runner.expects(:graceful_shutdown).never - # - # agent = InstanceAgentService.new - # agent.expects(:running?).times(3).returns(true, true, false) - # - # agent.service_main + @fake_runner.stubs(:run).times(2) + FileUtils.expects(:cp_r).never + @fake_runner.expects(:graceful_shutdown).never + + agent = InstanceAgentService.new + agent.expects(:running?).times(3).returns(true, true, false) + + agent.service_main end end diff --git a/vendor/gems/process_manager-0.0.13/lib/process_manager/config.rb b/vendor/gems/process_manager-0.0.13/lib/process_manager/config.rb index 4a717e20..d8e6fab0 100644 --- a/vendor/gems/process_manager-0.0.13/lib/process_manager/config.rb +++ b/vendor/gems/process_manager-0.0.13/lib/process_manager/config.rb @@ -17,7 +17,7 @@ def self.validate_config end def self.load_config - if File.exists?(config[:config_file]) && File.readable?(config[:config_file]) + if File.readable?(config[:config_file]) file_config = YAML.load(File.read(config[:config_file])).symbolize_keys config.update(file_config) config_loaded_callbacks.each{|c| c.call} @@ -76,8 +76,8 @@ def validate end def validate_log_and_pid_dir(errors) - FileUtils.mkdir_p(ProcessManager::Config.config[:log_dir]) unless File.exists?(ProcessManager::Config.config[:log_dir]) - FileUtils.mkdir_p(ProcessManager::Config.config[:pid_dir]) unless File.exists?(ProcessManager::Config.config[:pid_dir]) + FileUtils.mkdir_p(ProcessManager::Config.config[:log_dir]) unless File.directory?(ProcessManager::Config.config[:log_dir]) + FileUtils.mkdir_p(ProcessManager::Config.config[:pid_dir]) unless File.directory?(ProcessManager::Config.config[:pid_dir]) errors << "Please make sure the path of the log directory exists and is writable: #{config[:log_dir].inspect}" unless file_writable?(config[:log_dir]) && File.directory?(config[:log_dir]) errors << "Please make sure the path of the PID directory exists and is writable: #{config[:pid_dir].inspect}" unless file_writable?(config[:pid_dir]) && File.directory?(config[:pid_dir]) errors @@ -101,7 +101,7 @@ def normalize_log_and_pid_dir def file_writable?(path) return false unless path.present? - if File.exists?(path) + if File.file?(path) || File.directory?(path) File.writable?(path) else File.writable?(File.dirname(path)) diff --git a/vendor/gems/process_manager-0.0.13/lib/process_manager/master.rb b/vendor/gems/process_manager-0.0.13/lib/process_manager/master.rb index 489cf2c1..5b7411cd 100644 --- a/vendor/gems/process_manager-0.0.13/lib/process_manager/master.rb +++ b/vendor/gems/process_manager-0.0.13/lib/process_manager/master.rb @@ -177,7 +177,7 @@ def handle_pid_file if lock_acquired == false ProcessManager::Log.info("Could not acquire lock on #{pid_lock_file} - aborting start!") self.class.abort - elsif File.exists?(pid_file) + elsif File.file?(pid_file) pid = self.class.find_pid if ProcessManager.process_running?(pid) and process_matcher(pid) puts "Pidfile #{pid_file} exists and process #{pid} is running - aborting start!" diff --git a/vendor/gems/simple_pid-0.2.1/README.rdoc b/vendor/gems/simple_pid-0.2.1/README.rdoc new file mode 100644 index 00000000..a70f6d03 --- /dev/null +++ b/vendor/gems/simple_pid-0.2.1/README.rdoc @@ -0,0 +1,61 @@ += simple_pid + +This is a simple library for managing pid files. It was extracted from Kenneth +Kalmer's excellent daemon-kit project (http://github.com/kennethkalmer/daemon-kit). +The daemon-kit framework is amazing for bootstrapping your daemons, but if +you need something more lightweight (e.g., a single file daemon), then you're +out of luck (for now). In the mean time, there weren't any obvious, simple +pid file management libraries that you could trust. This one works well and +has facilities to ensure the process the pid file is pointing to is still running, +so you can handle stale pid files easily. + += Usage + +Some samples of the most common uses: + + require 'rubygems' + require 'simple_pid' + + pid = SimplePid.new("/path/to/your.pid") + + if pid.exists? + unless pid.running? + pid.cleanup + pid.write! + end + else + pid.write! + end + +Most of the above is fairly self-explanatory. You can accomplish all of the +above by calling: + + SimplePid.drop("/path/to/your.pid") + +If the path specified for the pid is unwritable for any reason, it falls back +to using /tmp to store the + +You can cleanup quickly with: + + SimplePid.cleanup("/path/to/your.pid") + +The above cleanup class method returns true if the process wasn't running +and the cleanup was actually run. It returns false if the process was still +running and no cleanup occurred. If you need to force cleanup regardless of +whether the process is running or not, you can do so with: + + SimplePid.cleanup!("/path/to/your.pid") + +You can check to see if the process is running and exit with an error message +if it is like this: + + pid.ensure_stopped! + +The current contents of the pid file can always be accessed like this: + + pid.pid + +== Copyright + +Copyright (c) 2010 Joel Watson. Portions copyright Kenneth +Kalmer. See LICENSE for details. \ No newline at end of file diff --git a/vendor/gems/simple_pid-0.2.1/lib/core_ext.rb b/vendor/gems/simple_pid-0.2.1/lib/core_ext.rb new file mode 100644 index 00000000..204fdfe5 --- /dev/null +++ b/vendor/gems/simple_pid-0.2.1/lib/core_ext.rb @@ -0,0 +1 @@ +require File.dirname(__FILE__) + '/core_ext/string' diff --git a/vendor/gems/simple_pid-0.2.1/lib/core_ext/string.rb b/vendor/gems/simple_pid-0.2.1/lib/core_ext/string.rb new file mode 100644 index 00000000..5a091431 --- /dev/null +++ b/vendor/gems/simple_pid-0.2.1/lib/core_ext/string.rb @@ -0,0 +1,43 @@ +# Extracted from Kenneth Kalmer's excellent daemon-kit project +# on GitHub: http://github.com/kennethkalmer/daemon-kit +# (The MIT License) +# +# Copyright (c) 2009 Kenneth Kalmer (Internet Exchange CC, Clear Planet Information Solutions Pty Ltd) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +# associated documentation files (the 'Software'), to deal in the Software without restriction, +# including without limitation the rights to use, copy, modify, merge, publish, distribute, +# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all copies or substantial +# portions of the Software. +# +# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH +# THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +require 'pathname' + +class String + + # Assuming the string is a file or path name, convert it into an + # absolute path. + def to_absolute_path + # Pathname is incompatible with Windows, but Windows doesn't have + # real symlinks so File.expand_path is safe. + if RUBY_PLATFORM =~ /(:?mswin|mingw)/ + File.expand_path( self ) + + # Otherwise use Pathname#realpath which respects symlinks. + else + begin + File.expand_path( Pathname.new( self ).realpath.to_s ) + rescue Errno::ENOENT + File.expand_path( Pathname.new( self ).cleanpath.to_s ) + end + end + end +end diff --git a/vendor/gems/simple_pid-0.2.1/lib/simple_pid.rb b/vendor/gems/simple_pid-0.2.1/lib/simple_pid.rb new file mode 100644 index 00000000..efc6520d --- /dev/null +++ b/vendor/gems/simple_pid-0.2.1/lib/simple_pid.rb @@ -0,0 +1,92 @@ +# Much of this was extracted from Kenneth Kalmer's excellent +# daemon-kit project on GitHub: http://github.com/kennethkalmer/daemon-kit + +require File.dirname(__FILE__) + '/core_ext' + +class SimplePid + def initialize(path) + @path = path.to_absolute_path + end + + def self.drop(path) + p = self.new(path) + if p.exists? + unless p.running? + p.cleanup + p.write! + end + else + p.write! + end + end + + def self.cleanup(path) + p = self.new(path) + if p.running? + return false + else + p.cleanup + return true + end + end + + def self.cleanup!(path) + p = self.new(path) + p.cleanup if p.exists? + end + + def exists? + File.file?(@path) + end + + # Returns true if the process is running + def running? + return false unless self.exists? + + # Check if process is in existence + # The simplest way to do this is to send signal '0' + # (which is a single system call) that doesn't actually + # send a signal + begin + Process.kill(0, self.pid) + return true + rescue Errno::ESRCH + return false + rescue ::Exception # for example on EPERM (process exists but does not belong to us) + return true + #rescue Errno::EPERM + # return false + end + end + + # Return the pid contained in the pidfile, or nil + def pid + return nil unless self.exists? + + File.open( @path ) { |f| return f.gets.to_i } + end + + def ensure_stopped! + if self.running? + puts "Process already running with id #{self.pid}" + exit 1 + end + end + + def cleanup + begin + File.delete(@path) + rescue Errno::ENOENT + File.delete("/tmp/#{Pathname.new(@path).basename}") + end + end + alias zap cleanup + + def write! + begin + File.open(@path, "w") { |f| f.puts Process.pid } + rescue Errno::ENOENT, Errno::EACCES + File.open("/tmp/#{Pathname.new(@path).basename}", "w") { |f| f.puts Process.pid } + end + end +end \ No newline at end of file diff --git a/vendor/specifications/process_manager-0.0.13.gemspec b/vendor/specifications/process_manager-0.0.13.gemspec index d8d78629..cd81b911 100644 --- a/vendor/specifications/process_manager-0.0.13.gemspec +++ b/vendor/specifications/process_manager-0.0.13.gemspec @@ -21,22 +21,16 @@ Gem::Specification.new do |s| if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q, [">= 0"]) - s.add_runtime_dependency(%q, [">= 0"]) s.add_runtime_dependency(%q, [">= 2.2.1"]) - s.add_runtime_dependency(%q, [">= 0"]) s.add_runtime_dependency(%q, [">= 0"]) else s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 2.2.1"]) - s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 0"]) end else s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 2.2.1"]) - s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 0"]) end end diff --git a/vendor/specifications/simple_pid.gemspec b/vendor/specifications/simple_pid.gemspec new file mode 100644 index 00000000..ceddd970 --- /dev/null +++ b/vendor/specifications/simple_pid.gemspec @@ -0,0 +1,53 @@ +# Generated by jeweler +# DO NOT EDIT THIS FILE DIRECTLY +# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command +# -*- encoding: utf-8 -*- + +Gem::Specification.new do |s| + s.name = %q{simple_pid} + s.version = "0.2.1" + + s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= + s.authors = ["watsonian"] + s.date = %q{2010-06-01} + s.description = %q{A simple, but complete library for managing pidfiles.} + s.email = %q{watsonian@gmail.com} + s.extra_rdoc_files = [ + "LICENSE", + "README.rdoc" + ] + s.files = [ + ".document", + ".gitignore", + "LICENSE", + "README.rdoc", + "Rakefile", + "VERSION", + "lib/core_ext.rb", + "lib/core_ext/string.rb", + "lib/simple_pid.rb", + "simple_pid.gemspec", + "test/helper.rb", + "test/test_simple_pid.rb" + ] + s.homepage = %q{http://github.com/watsonian/simple_pid} + s.rdoc_options = ["--charset=UTF-8"] + s.require_paths = ["lib"] + s.rubygems_version = %q{1.3.7} + s.summary = %q{A simple, but complete library for managing pidfiles.} + s.test_files = [ + "test/helper.rb", + "test/test_simple_pid.rb" + ] + + if s.respond_to? :specification_version then + current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION + s.specification_version = 3 + + if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then + else + end + else + end +end +