Codebase list ruby-health-check / bfc6145d-bf1f-427f-bd20-814c86ed71ff/main
New upstream release. Debian Janitor 2 years ago
33 changed file(s) with 1170 addition(s) and 299 deletion(s). Raw diff Collapse all Expand all
2323 railsapps/
2424 test/*.gemfile.lock
2525 ,*
26 .vagrant
27 ubuntu*console.log
2628
2729 # See: https://gist.github.com/ianheggie/9327010
2830 # for Global git ignore for OS/IDE/temp/backup files
0 sudo: false
0 dest: xenial
1 os: linux
2 # Released April 2018, Support ended: April 2023
3 # ruby 2.4.9, 2.5.3, 2.5.7, 2.6.5 (default) and 2.7.0 pre-installed on travis
14 addons:
25 apt:
36 packages:
2225
2326 script: ./test/test_with_railsapp
2427
25 matrix:
28 jobs:
2629 fast_finish: true
30
31 allow_failures:
32
33 - rvm: 3.0.1
34 gemfile: test/rails_6.1.gemfile
35 env:
36 - RAILS_VERSION=6.1
37 - MIDDLEWARE=YES
38
39 - rvm: 3.0.1
40 gemfile: test/rails_edge.gemfile
41 env:
42 - RAILS_VERSION=edge
43 - MIDDLEWARE=YES
44 - SMTP_STARTTLS=DISABLED
45
46 - rvm: ruby-head
47 gemfile: test/rails_6.1.gemfile
48 env:
49 - RAILS_VERSION=6.1
50 - MIDDLEWARE=YES
51 - SMTP_STARTTLS=DISABLED
52
53 - rvm: ruby-head
54 gemfile: test/rails_edge.gemfile
55 env:
56 - RAILS_VERSION=edge
57 - MIDDLEWARE=YES
58 - SMTP_STARTTLS=DISABLED
59
2760
2861 include:
2962 # -------------------------------------
3366
3467 - rvm: 2.2.2
3568 gemfile: test/rails_5.0.gemfile
36 env: RAILS_VERSION=5.0 MIDDLEWARE=no
69 env:
70 - RAILS_VERSION=5.0
71 - MIDDLEWARE=no
72 - RUBYGEMS_VERSION=2.7.11
73 - BUNDLER_VERSION=1.17.3
3774
3875 - rvm: 2.3.6
3976 gemfile: test/rails_5.0.gemfile
40 env: RAILS_VERSION=5.0 MIDDLEWARE=no
77 env:
78 - RAILS_VERSION=5.0
79 - MIDDLEWARE=no
4180
4281 # rails 5.1 sometime before May 2017
4382
4483 - rvm: 2.2.2
4584 gemfile: test/rails_5.1.gemfile
46 env: RAILS_VERSION=5.1 MIDDLEWARE=no
85 env:
86 - RAILS_VERSION=5.1
87 - MIDDLEWARE=no
88 - RUBYGEMS_VERSION=2.7.11
89 - BUNDLER_VERSION=1.17.3
4790
4891 - rvm: 2.3.6
4992 gemfile: test/rails_5.1.gemfile
50 env: RAILS_VERSION=5.1 MIDDLEWARE=no
93 env:
94 - RAILS_VERSION=5.1
95 - MIDDLEWARE=no
96 - BUNDLER_VERSION=1.17.3
5197
5298 - rvm: 2.4.3
5399 gemfile: test/rails_5.1.gemfile
54 env: RAILS_VERSION=5.1 MIDDLEWARE=no
100 env:
101 - RAILS_VERSION=5.1
102 - MIDDLEWARE=no
55103
56104 # -------------------------------------
57105 # Middleware
60108
61109 - rvm: 2.2.2
62110 gemfile: test/rails_5.0.gemfile
63 env: RAILS_VERSION=5.0 MIDDLEWARE=yes
111 env:
112 - RAILS_VERSION=5.0
113 - MIDDLEWARE=yes
114 - RUBYGEMS_VERSION=2.7.11
115 - BUNDLER_VERSION=1.17.3
64116
65117 - rvm: 2.3.6
66118 gemfile: test/rails_5.0.gemfile
67 env: RAILS_VERSION=5.0 MIDDLEWARE=yes
119 env:
120 - RAILS_VERSION=5.0
121 - MIDDLEWARE=yes
68122
69123 # rails 5.1 sometime before May 2017
70124
71125 - rvm: 2.2.2
72126 gemfile: test/rails_5.1.gemfile
73 env: RAILS_VERSION=5.1 MIDDLEWARE=yes
127 env:
128 - RAILS_VERSION=5.1
129 - MIDDLEWARE=yes
130 - RUBYGEMS_VERSION=2.7.11
131 - BUNDLER_VERSION=1.17.3
74132
75133 - rvm: 2.4.3
76134 gemfile: test/rails_5.1.gemfile
77 env: RAILS_VERSION=5.1 MIDDLEWARE=yes
78
135 env:
136 - RAILS_VERSION=5.1
137 - MIDDLEWARE=yes
138
139
140 # rails 5.2 April 2018
141 # -------------------------------------
142 # INSTALLED AS MIDDLEWARE
143
144
145 # rails 6.0
146
147 - rvm: 2.5.0
148 gemfile: test/rails_6.0.gemfile
149 env:
150 - RAILS_VERSION=6.0
151 - MIDDLEWARE=YES
152
153 - rvm: 2.6.7
154 gemfile: test/rails_6.0.gemfile
155 env:
156 - RAILS_VERSION=6.0
157 - MIDDLEWARE=YES
158
159 # Not testing past recommended ruby version as listed on https://www.fastruby.io/blog/ruby/rails/versions/compatibility-table.html
160
161 # --------------------------------------
162 - rvm: 2.5.0
163 gemfile: test/rails_6.1.gemfile
164 env:
165 - RAILS_VERSION=6.1
166 - MIDDLEWARE=YES
167
168 - rvm: 2.6.6
169 gemfile: test/rails_6.1.gemfile
170 env:
171 - RAILS_VERSION=6.1
172 - MIDDLEWARE=YES
173
174 - rvm: 2.7.3
175 gemfile: test/rails_6.1.gemfile
176 env:
177 - RAILS_VERSION=6.1
178 - MIDDLEWARE=YES
179
180 - rvm: 3.0.1
181 gemfile: test/rails_6.1.gemfile
182 env:
183 - RAILS_VERSION=6.1
184 - MIDDLEWARE=YES
185 - SMTP_STARTTLS=DISABLED
186
187 # ------------------
188 # FIXME
189 # ------------------
190
191 - rvm: 3.0.1
192 gemfile: test/rails_6.1.gemfile
193 env:
194 - RAILS_VERSION=6.1
195 - MIDDLEWARE=YES
196
197 - rvm: 3.0.1
198 gemfile: test/rails_edge.gemfile
199 env:
200 - RAILS_VERSION=edge
201 - MIDDLEWARE=YES
202 - SMTP_STARTTLS=DISABLED
203
204 - rvm: ruby-head
205 gemfile: test/rails_6.1.gemfile
206 env:
207 - RAILS_VERSION=6.1
208 - MIDDLEWARE=YES
209 - SMTP_STARTTLS=DISABLED
210
211 - rvm: ruby-head
212 gemfile: test/rails_edge.gemfile
213 env:
214 - RAILS_VERSION=edge
215 - MIDDLEWARE=YES
216 - SMTP_STARTTLS=DISABLED
217
00 = Change Log =
1
2 * 3.1.0 - 26 May 2021
3 * Updated README to clarify railsN branch status (they are intended to be stable, development to be a feature branch off them or master)
4 * Updated README with all the settings
5 * Updated all the branches to work with the latest travis and gem changes, as some gems needed to be locked down.
6 * Updated to test rails 6.0 and 6.1
7 * Got all travis tests passing
8 * Removed old, unused branches
9 * Merged PR Fix broken Cache-Control headers #93 from felixbuenemann
10 * Merged PR S3 should not depend on Rails secrets file #77 by natefaerber
11 * Merged PR RabbitMQ Health check #98 from rhuanbarreto
12 * Merged PR Use remote_ip to accept proxy-forwarded requests #102 by alessio-signorini but made it optional
13 * Fixed up failure setting to match previous output on error, and use it as a prefix when the error message is also output (not by default)
14 * Always log the error to rails log even if not including in html response
15 * Merged PR ensure REDIS connections are closed #88 from yld
16 * Merged PR more robust cache check #90 from masciugo
17 * Merged PR Add log_level config setting which defaults to 'info'. #97 from FloHeinle
18 * Merged PR get rid of old school hash rockets syntax #92 from DmytroStepaniuk
19 * Merged PR Converted whitelist testing to use IPAddr objects. #64 jordanyaker
20 * Added on_success and on_failure callbacks
21 * Makes sure errors are seperated by a period and a space and a period always ends the list of errors
122
223 * 3.0.0
324 * First release on rails5 branch
00 = health_check gem
11
2 Simple health check of Rails 5.x apps for use with Pingdom, NewRelic, EngineYard or uptime.openacs.org etc.
2 Simple health check of Rails 5.x and 6.x apps for use with Pingdom, NewRelic, EngineYard etc.
33
44 The basic goal is to quickly check that rails is up and running and that it has access to correctly configured resources (database, email gateway)
55
66 Check the latest README {master}[https://github.com/ianheggie/health_check/tree/master] for other versions
7
8 Use gem versions for stable releases:
9 * ~> 3.x for Rails 5.x and 6.x (etc until there is a proven need to split off another branch),
10 * ~> 2.x for Rails 4.x,
11 * ~> 1.7 for Rails 3.x,
12 * ~> 1.6.3 for Rails 2.3
13
14 Note: it is best to pin to a specific commit if using a development branch as sometimes tests break.
715
816 health_check provides various monitoring URIs, for example:
917
2331 You may also issue POST calls instead of GET to these urls.
2432
2533 On failure (detected by health_check) a 500 http status is returned with a simple explanation of the failure
34 (if include_error_in_response_body is true)
2635
2736 curl localhost:3000/health_check/fail
2837 health_check failed: invalid argument to health_test.
3847 * database - checks that the current migration level can be read from the database
3948 * email - basic check of email - :test returns true, :sendmail checks file is present and executable, :smtp sends HELO command to server and checks response
4049 * migration - checks that the database migration level matches that in db/migrations
50 * rabbitmq - RabbitMQ Health Check
4151 * redis / redis-if-present - checks Redis connectivity
4252 * resque-redis / resque-redis-if-present - checks Resque connectivity to Redis
4353 * s3 / s3-if-present - checks proper permissions to s3 buckets
4454 * sidekiq-redis / sidekiq-redis-if-present - checks Sidekiq connectivity to Redis
55 * elasticsearch / elasticsearch-if-present - checks Elasticsearch connectivity
4556 * site - checks rails is running sufficiently to render text
4657
4758 Some checks have a *-if-present form, which only runs the check if the corresponding library has been required.
5465
5566 == Installation
5667
57 Add the following line to Gemfile
58
59 gem "health_check"
68 Add the following line to Gemfile (after the rails gems are listed)
69
70 gem 'health_check'
6071
6172 And then execute
6273
7788
7889 # Text output upon success
7990 config.success = 'success'
91
92 # Text output upon failure
93 config.failure = 'health_check failed'
94
95 # Disable the error message to prevent /health_check from leaking
96 # sensitive information
97 config.include_error_in_response_body = false
98
99 # Log level (success or failure message with error details is sent to rails log unless this is set to nil)
100 config.log_level = 'info'
80101
81102 # Timeout in seconds used when checking smtp server
82103 config.smtp_timeout = 30.0
88109 config.http_status_for_error_text = 500
89110
90111 # http status code used when an error object is output (json or xml)
91 # Set to 200 if you want your want to distinguish between partial (healthy property == false) and
112 # Set to 200 if you want to distinguish between partial (healthy property == false) and
92113 # total failure of rails application (http status of 500 etc)
93114
94115 config.http_status_for_error_object = 500
128149 config.basic_auth_username = 'my_username'
129150 config.basic_auth_password = 'my_password'
130151
131 # Whitelist requesting IPs
132 # Defaults to blank and allows any IP
133 config.origin_ip_whitelist = %w(123.123.123.123)
152 # Whitelist requesting IPs by a list of IP and/or CIDR ranges, either IPv4 or IPv6 (uses IPAddr.include? method to check)
153 # Defaults to blank which allows any IP
154 config.origin_ip_whitelist = %w(123.123.123.123 10.11.12.0/24 2400:cb00::/32)
155
156 # Use ActionDispatch::Request's remote_ip method when behind a proxy to pick up the real remote IP for origin_ip_whitelist check
157 # Otherwise uses Rack::Request's ip method (the default, and always used by Middleware), which is more susceptable to spoofing
158 # See https://stackoverflow.com/questions/10997005/whats-the-difference-between-request-remote-ip-and-request-ip-in-rails
159 config.accept_proxied_requests = false
134160
135161 # http status code used when the ip is not allowed for the request
136162 config.http_status_for_ip_whitelist_error = 403
137163
138 # When redis url is non-standard
139 config.redis_url = 'redis_url'
164 # rabbitmq
165 config.rabbitmq_config = {}
166
167 # When redis url/password is non-standard
168 config.redis_url = 'redis_url' # default ENV['REDIS_URL']
169 # Only included if set, as url can optionally include passwords as well
170 config.redis_password = 'redis_password' # default ENV['REDIS_PASSWORD']
171
172 # Failure Hooks to do something more ...
173 # checks lists the checks requested
174 config.on_failure do |checks, msg|
175 # log msg somewhere
176 end
177
178 config.on_success do |checks|
179 # flag that everything is well
180 end
181
182
140183 end
141184
142185 You may call add_custom_check multiple times with different tests. These tests will be included in the default list ("standard").
150193 eg DB connection errors from QueryCache. The "middleware" check will fail if you have not installed health_check as middleware.
151194
152195 To install health_check as middleware add the following line to the config/application.rb:
153 config.middleware.insert_after "Rails::Rack::Logger", HealthCheck::MiddlewareHealthcheck
196 config.middleware.insert_after Rails::Rack::Logger, HealthCheck::MiddlewareHealthcheck
154197
155198 Note: health_check is installed as a full rails engine even if it has been installed as middleware. This is so the
156199 remaining checks continue to run through the complete rails stack.
173216
174217 * Pingdom Website Monitoring - https://www.pingdom.com
175218 * NewRelic Availability Monitoring - http://newrelic.com/docs/features/availability-monitoring-faq
176 * Uptime by OpenACS - http://uptime.openacs.org/uptime/
177219 * Engine Yard's guide - https://support.cloud.engineyard.com/entries/20996821-monitor-application-uptime (although the guide is based on fitter_happier plugin it will also work with this gem)
178220 * Nagios check_http (with -s success) - https://www.nagios-plugins.org/doc/man/check_http.html
179221 * Any other montoring service that can be set to check for the word success in the text returned from a url
235277
236278 == Known Issues
237279
280 * See https://github.com/ianheggie/health_check/issues
238281 * No inline documentation for methods
239282 * <b>rvm gemsets breaks the test</b> - specifically <tt>rvm use 1.9.3</tt> works but <tt>rvm gemset use ruby-1.9.3-p385@health_check --create</tt> triggers a "Could not find gem 'coffee-rails (~> 3.2.1) ruby' in the gems available on this machine." error in the last call to bundle (installing health_check as a gem via a path into the temp railsapp)
240283
241284 == Similar projects
242285
243286 * fitter_happier plugin by atmos - plugin with similar goals, but not compatible with uptime, and does not check email gateway
287 * HealthBit - inspired by this gem but with a fresh start as a simpler rack only application, no travis CI tests (yet?) but looks interesting.
244288
245289 == Testing
246290
247291 === Automated testing and other checks
248292
249 * {<img src="https://travis-ci.org/ianheggie/health_check.svg?branch=rails5">}[https://travis-ci.org/ianheggie/health_check.svg?branch=rails5] - Travis CI
293 * {<img src="https://badge.fury.io/rb/health_check.svg" alt="Gem Version" />}[http://badge.fury.io/rb/health_check] - Latest Gem
294 * {<img src="https://travis-ci.org/ianheggie/health_check.svg">}[https://travis-ci.org/ianheggie/health_check] - Travis CI
295 * {<img src="https://codeclimate.com/github/ianheggie/health_check.svg" />}[https://codeclimate.com/github/ianheggie/health_check] - Code quality
296 * {<img src="https://gemnasium.com/ianheggie/health_check.svg">}[https://gemnasium.com/ianheggie/health_check] - Gem dependencies
250297
251298 === Manual testing
252299
253 The instructions have been changed to using a vagrant virtual box for consistant results.
254
255 Install vagrant 1.9.7 or later and virtual_box or other local virtual machine providor.
300 The instructions have been changed to using a vagrant virtual box for consistent results.
301
302 Install vagrant 1.9.7 or later and virtual_box or other local virtual machine provider. Add the vagrant plugin called vbguest.
303
304 vagrant plugin install vagrant-vbguest
256305
257306 Create a temp directory for throw away testing, and clone the health_check gem into it
258307
280329
281330 cd /vagrant # the current directory on your host is mounted here on the virtual machine
282331
283 chruby 2.2.2 # or some other ruby version
332 chruby 2.2.2 # or some other ruby version (run chruby with no arguments to see the current list)
284333
285334 test/test_with_railsapp
286335
287 exit # from viretual machine when finished
336 exit # from virtual machine when finished
288337
289338 The script will first call `test/setup_railsapp` to setup a rails app with health_check installed and then
290339 run up the rails server and perform veraious tests.
296345
297346 == Copyright
298347
299 Copyright (c) 2010-2017 Ian Heggie, released under the MIT license.
348 Copyright (c) 2010-2021 Ian Heggie, released under the MIT license.
300349 See MIT-LICENSE for details.
301350
302351 == Contributors
304353 Thanks go to the various people who have given feedback and suggestions via the issues list and pull requests.
305354
306355 === Contributing
356
357 Use gem versions for stable releases, or github branch / commits for development versions:
358 * for Rails 5.x and 6.x use feature branched off master {master}[https://github.com/ianheggie/health_check/tree/master] for development;
359 * for Rails 4.x use feature branches off the {rails4}[https://github.com/ianheggie/health_check/tree/rails4] stable branch for development;
360 * for Rails 3.x use feature branches off the {rails3}[https://github.com/ianheggie/health_check/tree/rails3] stable branch for development;
361 * for Rails 2.3 use feature branches off the {rails2.3}[https://github.com/ianheggie/health_check/tree/rails2.3] stable branch for development;
307362
308363 1. Fork it
309364 2. Create your feature branch (`git checkout -b my-new-feature`)
310 3. Commit your changes (`git commit -am 'Add some feature'`)
311 4. Push to the branch (`git push origin my-new-feature`)
312 5. Create new Pull Request (Code with BDD tests are favoured)
313
314 <em>Feedback welcome! Especially with suggested replacement code and corresponding tests</em>
365 3. Create a test that confirms your changes work
366 4. Update README.rdoc to explain enhancements, or add succinct comment in code when fixing bugs
367 5. Commit your changes (`git commit -am 'Add some feature'`)
368 6. Push to the branch (`git push origin my-new-feature`)
369 7. Create new Pull Request (Code with BDD tests and documentation are highly favoured)
370
371 <em>Feedback welcome! Especially with suggested replacement code, tests and documentation</em>
77 exec '/bin/bash', './test/test_with_railsapp'
88 end
99
10 task :default => :test
10 task default: :test
1111
1212 begin
1313 gem 'rdoc'
44 # For a complete reference, please see the online documentation at
55 # https://docs.vagrantup.com.
66
7 config.vm.box = "ubuntu/xenial64"
7 config.vm.box = "ubuntu/focal64"
88
99 # set auto_update to false, if you do NOT want to check the correct
1010 # additions version when booting this machine
1616 # provision with a shell script.
1717 config.vm.provision "shell", path: "./test/provision_vagrant"
1818
19 config.vm.provider "virtualbox" do |v|
20 # travis allocates 7.5 GB, but this is sufficient
21 v.memory = 2048
22 v.cpus = 2
23 end
24
25 # if File.file?('.git') && IO.read('.git') =~ %r{\Agitdir: (.+)/.git/worktrees.*}
26 # # Handle git worktrees ...
27 # path = $1
28 # config.vm.synced_folder path, path
29 # end
30
1931 end
00 unless HealthCheck::Engine.routes_explicitly_defined
1 Rails.application.routes.draw do
1 ::Rails.application.routes.draw do
22 add_health_check_routes()
33 end
44 end
0 ruby-health-check (3.1.0-1) UNRELEASED; urgency=low
1
2 * New upstream release.
3
4 -- Debian Janitor <janitor@jelmer.uk> Fri, 04 Jun 2021 22:27:45 -0000
5
06 ruby-health-check (3.0.0-1) unstable; urgency=medium
17
28 * Team Upload
88 gem.required_rubygems_version = Gem::Requirement.new(">= 0") if gem.respond_to? :required_rubygems_version=
99 gem.authors = ["Ian Heggie"]
1010 gem.email = ["ian@heggie.biz"]
11 gem.summary = %q{Simple health check of Rails app for uptime monitoring with Pingdom, NewRelic, EngineYard or uptime.openacs.org etc.}
11 gem.summary = %q{Simple health check of Rails app for uptime monitoring with Pingdom, NewRelic, EngineYard etc.}
1212 gem.description = <<-EOF
13 Simple health check of Rails app for uptime monitoring with Pingdom, NewRelic, EngineYard or uptime.openacs.org etc.
13 Simple health check of Rails app for uptime monitoring with Pingdom, NewRelic, EngineYard etc.
1414 EOF
1515 gem.homepage = "https://github.com/ianheggie/health_check"
16 gem.license = "MIT"
1617
1718 gem.files = `git ls-files`.split($/)
18 gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
1919 gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
2020 gem.extra_rdoc_files = [ "README.rdoc" ]
2121 gem.require_paths = ["lib"]
2424 gem.add_development_dependency(%q<smarter_bundler>, [">= 0.1.0"])
2525 gem.add_development_dependency(%q<rake>, [">= 0.8.3"])
2626 gem.add_development_dependency(%q<shoulda>, ["~> 2.11.0"])
27 gem.add_development_dependency(%q<bundler>, ["~> 1.2"])
27 gem.add_development_dependency(%q<bundler>, [">= 1.2"])
2828 end
0 module HealthCheck
1 class ElasticsearchHealthCheck
2 extend BaseHealthCheck
3
4 def self.check
5 unless defined?(::Elasticsearch)
6 raise "Wrong configuration. Missing 'elasticsearch' gem"
7 end
8 res = ::Elasticsearch::Client.new.ping
9 res == true ? '' : "Elasticsearch returned #{res.inspect} instead of true"
10 rescue Exception => e
11 create_error 'elasticsearch', e.message
12 end
13 end
14 end
0 # Copyright (c) 2010-2013 Ian Heggie, released under the MIT license.
0 # Copyright (c) 2010-2021 Ian Heggie, released under the MIT license.
11 # See MIT-LICENSE for details.
2 require "ipaddr"
23
34 module HealthCheck
45 class HealthCheckController < ActionController::Base
1314 if max_age > 1
1415 last_modified = Time.at((last_modified.to_f / max_age).floor * max_age).utc
1516 end
16 public = (max_age > 1) && ! HealthCheck.basic_auth_username
17 if stale?(:last_modified => last_modified, :public => public)
17 is_public = (max_age > 1) && ! HealthCheck.basic_auth_username
18 if stale?(last_modified: last_modified, public: is_public)
1819 checks = params[:checks] ? params[:checks].split('_') : ['standard']
1920 checks -= HealthCheck.middleware_checks if HealthCheck.installed_as_middleware
2021 begin
2223 rescue Exception => e
2324 errors = e.message.blank? ? e.class.to_s : e.message.to_s
2425 end
25 response.headers['Cache-control'] = (public ? 'public' : 'private') + ', no-cache, must-revalidate' + (max_age > 0 ? ", max-age=#{max_age}" : '')
26 response.headers['Cache-Control'] = "must-revalidate, max-age=#{max_age}"
2627 if errors.blank?
27 send_response nil, :ok, :ok
28 send_response true, nil, :ok, :ok
29 if HealthCheck.success_callbacks
30 HealthCheck.success_callbacks.each do |callback|
31 callback.call(checks)
32 end
33 end
2834 else
29 msg = "health_check failed: #{errors}"
30 send_response msg, HealthCheck.http_status_for_error_text, HealthCheck.http_status_for_error_object
35 msg = HealthCheck.include_error_in_response_body ? "#{HealthCheck.failure}: #{errors}" : nil
36 send_response false, msg, HealthCheck.http_status_for_error_text, HealthCheck.http_status_for_error_object
37
3138 # Log a single line as some uptime checkers only record that it failed, not the text returned
32 if logger
33 logger.info msg
39 msg = "#{HealthCheck.failure}: #{errors}"
40 logger.send(HealthCheck.log_level, msg) if logger && HealthCheck.log_level
41 if HealthCheck.failure_callbacks
42 HealthCheck.failure_callbacks.each do |callback|
43 callback.call(checks, msg)
44 end
3445 end
3546 end
3647 end
3849
3950 protected
4051
41 def send_response(msg, text_status, obj_status)
42 healthy = !msg
43 msg ||= HealthCheck.success
44 obj = { :healthy => healthy, :message => msg}
52 def send_response(healthy, msg, text_status, obj_status)
53 msg ||= healthy ? HealthCheck.success : HealthCheck.failure
54 obj = { healthy: healthy, message: msg}
4555 respond_to do |format|
46 format.html { render :plain => msg, :status => text_status, :content_type => 'text/plain' }
47 format.json { render :json => obj, :status => obj_status }
48 format.xml { render :xml => obj, :status => obj_status }
49 format.any { render :plain => msg, :status => text_status, :content_type => 'text/plain' }
56 format.html { render plain: msg, status: text_status, content_type: 'text/plain' }
57 format.json { render json: obj, status: obj_status }
58 format.xml { render xml: obj, status: obj_status }
59 format.any { render plain: msg, status: text_status, content_type: 'text/plain' }
5060 end
5161 end
5262
5868 end
5969
6070 def check_origin_ip
71 request_ipaddr = IPAddr.new(HealthCheck.accept_proxied_requests ? request.remote_ip : request.ip)
6172 unless HealthCheck.origin_ip_whitelist.blank? ||
62 HealthCheck.origin_ip_whitelist.include?(request.ip)
63 render :plain => 'Health check is not allowed for the requesting IP',
64 :status => HealthCheck.http_status_for_ip_whitelist_error,
65 :content_type => 'text/plain'
73 HealthCheck.origin_ip_whitelist.any? { |addr| IPAddr.new(addr).include? request_ipaddr }
74 render plain: 'Health check is not allowed for the requesting IP',
75 status: HealthCheck.http_status_for_ip_whitelist_error,
76 content_type: 'text/plain'
6677 end
6778 end
6879
77
88 def add_health_check_routes(prefix = nil)
99 HealthCheck.uri = prefix if prefix
10 match "#{HealthCheck.uri}(/:checks)(.:format)", :to => 'health_check/health_check#index', via: [:get, :post], :defaults => { :format => 'txt' }
10 match "#{HealthCheck.uri}(/:checks)(.:format)", controller: 'health_check/health_check', action: :index, via: [:get, :post], defaults: { format: 'txt' }
1111 end
1212
1313 end
0 # Copyright (c) 2010-2021 Ian Heggie, released under the MIT license.
1 # See MIT-LICENSE for details.
2 require 'ipaddr'
3
04 module HealthCheck
15 class MiddlewareHealthcheck
26
5862 def ip_blocked(env)
5963 return false if HealthCheck.origin_ip_whitelist.blank?
6064 req = Rack::Request.new(env)
61 unless HealthCheck.origin_ip_whitelist.include?(req.ip)
65 request_ipaddr = IPAddr.new(req.ip)
66 unless HealthCheck.origin_ip_whitelist.any? { |addr| IPAddr.new(addr).include? request_ipaddr }
6267 [ HealthCheck.http_status_for_ip_whitelist_error,
6368 { 'Content-Type' => 'text/plain' },
6469 [ 'Health check is not allowed for the requesting IP' ]
0 module HealthCheck
1 class RabbitMQHealthCheck
2 extend BaseHealthCheck
3 def self.check
4 unless defined?(::Bunny)
5 raise "Wrong configuration. Missing 'bunny' gem"
6 end
7 connection = Bunny.new(HealthCheck.rabbitmq_config)
8 connection.start
9 connection.close
10 ''
11 rescue Exception => e
12 create_error 'rabbitmq', e.message
13 end
14 end
15 end
0 # frozen_string_literal: true
1
02 module HealthCheck
13 class RedisHealthCheck
24 extend BaseHealthCheck
35
4 def self.check
5 unless defined?(::Redis)
6 raise "Wrong configuration. Missing 'redis' gem"
6 class << self
7 def check
8 raise "Wrong configuration. Missing 'redis' gem" unless defined?(::Redis)
9
10 client.ping == 'PONG' ? '' : "Redis.ping returned #{res.inspect} instead of PONG"
11 rescue Exception => err
12 create_error 'redis', err.message
13 ensure
14 client.close if client.connected?
715 end
8 res = ::Redis.new(url: HealthCheck.redis_url).ping
9 res == 'PONG' ? '' : "Redis.ping returned #{res.inspect} instead of PONG"
10 rescue Exception => e
11 create_error 'redis', e.message
16
17 def client
18 @client ||= Redis.new(
19 {
20 url: HealthCheck.redis_url,
21 password: HealthCheck.redis_password
22 }.reject { |k, v| v.nil? }
23 )
24 end
1225 end
1326 end
1427 end
44 class << self
55 def check
66 unless defined?(::Aws)
7 raise "Wrong configuration. Missing 'aws-sdk' gem"
7 raise "Wrong configuration. Missing 'aws-sdk' or 'aws-sdk-s3' gem"
88 end
99 return create_error 's3', 'Could not connect to aws' if aws_s3_client.nil?
1010 HealthCheck.buckets.each do |bucket_name, permissions|
2626
2727 private
2828
29 # We already assume you are using Rails. Let's also assume you have an initializer
30 # created for your Aws config. We will set the region here so you can use an
31 # instance profile and simply set the region in your environment.
2932 def configure_client
30 return unless defined?(Rails)
33 ::Aws.config[:s3] = { force_path_style: true }
34 ::Aws.config[:region] ||= ENV['AWS_REGION'] || ENV['DEFAULT_AWS_REGION']
3135
32 aws_configuration = {
33 region: Rails.application.secrets.aws_default_region,
34 credentials: ::Aws::Credentials.new(
35 Rails.application.secrets.aws_access_key_id,
36 Rails.application.secrets.aws_secret_access_key
37 ),
38 force_path_style: true
39 }
40
41 ::Aws::S3::Client.new aws_configuration
36 ::Aws::S3::Client.new
4237 end
4338
4439 def aws_s3_client
5146
5247 def W(bucket)
5348 aws_s3_client.put_object(bucket: bucket,
54 key: "healthcheck_#{Rails.application.class.parent_name}",
49 key: "healthcheck_#{::Rails.application.class.parent_name}",
5550 body: Time.new.to_s)
5651 end
5752
5853 def D(bucket)
5954 aws_s3_client.delete_object(bucket: bucket,
60 key: "healthcheck_#{Rails.application.class.parent_name}")
55 key: "healthcheck_#{::Rails.application.class.parent_name}")
6156 end
6257 end
6358 end
55
66 @@default_smtp_settings =
77 {
8 :address => "localhost",
9 :port => 25,
10 :domain => 'localhost.localdomain',
11 :user_name => nil,
12 :password => nil,
13 :authentication => nil,
14 :enable_starttls_auto => true,
8 address: "localhost",
9 port: 25,
10 domain: 'localhost.localdomain',
11 user_name: nil,
12 password: nil,
13 authentication: nil,
14 enable_starttls_auto: true
1515 }
1616
1717 cattr_accessor :default_smtp_settings
5454 errors << HealthCheck::RedisHealthCheck.check if defined?(::Redis)
5555 when 's3-if-present'
5656 errors << HealthCheck::S3HealthCheck.check if defined?(::Aws)
57 when 'elasticsearch-if-present'
58 errors << HealthCheck::ElasticsearchHealthCheck.check if defined?(::Elasticsearch)
5759 when 'resque-redis'
5860 errors << HealthCheck::ResqueHealthCheck.check
5961 when 'sidekiq-redis'
6264 errors << HealthCheck::RedisHealthCheck.check
6365 when 's3'
6466 errors << HealthCheck::S3HealthCheck.check
67 when 'elasticsearch'
68 errors << HealthCheck::ElasticsearchHealthCheck.check
69 when 'rabbitmq'
70 errors << HealthCheck::RabbitMQHealthCheck.check
6571 when "standard"
6672 errors << HealthCheck::Utils.process_checks(HealthCheck.standard_checks, called_from_middleware)
6773 when "middleware"
8389 return "invalid argument to health_test."
8490 end
8591 end
92 errors << '. ' unless errors == '' || errors.end_with?('. ')
8693 end
87 return errors
94 return errors.strip
8895 rescue => e
8996 return e.message
9097 end
9198
9299 def self.db_migrate_path
93100 # Lazy initialisation so Rails.root will be defined
94 @@db_migrate_path ||= File.join(Rails.root, 'db', 'migrate')
101 @@db_migrate_path ||= File.join(::Rails.root, 'db', 'migrate')
95102 end
96103
97104 def self.db_migrate_path=(value)
134141 status = ''
135142 begin
136143 if @skip_external_checks
137 status = '221'
144 status = '250'
138145 else
139 Timeout::timeout(timeout) do |timeout_length|
140 t = TCPSocket.new(settings[:address], settings[:port])
141 begin
142 status = t.gets
143 while status != nil && status !~ /^2/
144 status = t.gets
145 end
146 t.puts "HELO #{settings[:domain]}\r"
147 while status != nil && status !~ /^250/
148 status = t.gets
149 end
150 t.puts "QUIT\r"
151 status = t.gets
152 ensure
153 t.close
154 end
146 smtp = Net::SMTP.new(settings[:address], settings[:port])
147 smtp.enable_starttls if settings[:enable_starttls_auto]
148 smtp.open_timeout = timeout
149 smtp.read_timeout = timeout
150 smtp.start(settings[:domain], settings[:user_name], settings[:password], settings[:authentication]) do
151 status = smtp.helo(settings[:domain]).status
155152 end
156153 end
157 rescue Errno::EBADF => ex
158 status = "Unable to connect to service"
159154 rescue Exception => ex
160155 status = ex.to_s
161156 end
162 (status =~ /^221/) ? '' : "SMTP: #{status || 'unexpected EOF on socket'}. "
157 (status =~ /^250/) ? '' : "SMTP: #{status || 'unexpected error'}. "
163158 end
164159
165160 def self.check_cache
166 Rails.cache.write('__health_check_cache_test__', 'ok', :expires_in => 1.second) ? '' : 'Unable to write to cache. '
161 t = Time.now.to_i
162 value = "ok #{t}"
163 ret = ::Rails.cache.read('__health_check_cache_test__')
164 if ret.to_s =~ /^ok (\d+)$/
165 diff = ($1.to_i - t).abs
166 return('Cache expiry is broken. ') if diff > 30
167 elsif ret
168 return 'Cache is returning garbage. '
169 end
170 if ::Rails.cache.write('__health_check_cache_test__', value, expires_in: 2.seconds)
171 ret = ::Rails.cache.read('__health_check_cache_test__')
172 if ret =~ /^ok (\d+)$/
173 diff = ($1.to_i - t).abs
174 (diff < 2 ? '' : 'Out of date cache or time is skewed. ')
175 else
176 'Unable to read from cache. '
177 end
178 else
179 'Unable to write to cache. '
180 end
167181 end
168182
169183 end
00 module HealthCheck
1 VERSION = "3.0.0"
1 VERSION = "3.1.0"
22 end
22
33 module HealthCheck
44
5 class Engine < Rails::Engine
6 cattr_accessor :routes_explicitly_defined
5 class Engine < ::Rails::Engine
6 cattr_accessor :routes_explicitly_defined
77 end
8
9 # Log level
10 mattr_accessor :log_level
11 self.log_level = 'info'
812
913 # Text output upon success
1014 mattr_accessor :success
1115 self.success = "success"
16
17 # Text output upon failure
18 mattr_accessor :failure
19 self.failure = "health_check failed"
1220
1321 # Timeout in seconds used when checking smtp server
1422 mattr_accessor :smtp_timeout
2634 mattr_accessor :http_status_for_ip_whitelist_error
2735 self.http_status_for_ip_whitelist_error = 403
2836
37 # check remote_ip rather than ip for ip whitelist
38 mattr_accessor :accept_proxied_requests
39 self.accept_proxied_requests = false
40
2941 # ips allowed to perform requests
3042 mattr_accessor :origin_ip_whitelist
3143 self.origin_ip_whitelist = []
3850 # s3 buckets
3951 mattr_accessor :buckets
4052 self.buckets = {}
53
54 # rabbitmq
55 mattr_accessor :rabbitmq_config
56 self.rabbitmq_config = {}
4157
4258 # health check uri path
4359 mattr_accessor :uri
5369 mattr_accessor :full_checks
5470 mattr_accessor :standard_checks
5571 self.custom_checks = { }
56 self.full_checks = ['database', 'migrations', 'custom', 'email', 'cache', 'redis-if-present', 'sidekiq-redis-if-present', 'resque-redis-if-present', 's3-if-present']
72 self.full_checks = ['database', 'migrations', 'custom', 'email', 'cache', 'redis-if-present', 'sidekiq-redis-if-present', 'resque-redis-if-present', 's3-if-present', 'elasticsearch-if-present']
5773 self.standard_checks = [ 'database', 'migrations', 'custom', 'emailconf' ]
5874
5975 # Middleware based checks
6278
6379 mattr_accessor :installed_as_middleware
6480
65 # Allow non-standard redis url
81 # Allow non-standard redis url and password
6682 mattr_accessor :redis_url
67 self.redis_url = nil
83 self.redis_url = ENV['REDIS_URL']
84
85 mattr_accessor :redis_password
86 self.redis_password = 'some-password'
87
88 # Include the error in the response body.
89 # You should only do this where your /health_check endpoint is NOT open to the public internet
90 mattr_accessor :include_error_in_response_body
91 self.include_error_in_response_body = false
92
93 # used for on_failure and on_success
94 mattr_accessor :success_callbacks
95 mattr_accessor :failure_callbacks
6896
6997 def self.add_custom_check(name = 'custom', &block)
7098 custom_checks[name] ||= [ ]
7199 custom_checks[name] << block
100 end
101
102 def self.on_success(&block)
103 success_callbacks ||= [ ]
104 success_callbacks << block
105 end
106
107 def self.on_failure(&block)
108 failure_callbacks ||= [ ]
109 failure_callbacks << block
72110 end
73111
74112 def self.setup
82120 require 'health_check/resque_health_check'
83121 require 'health_check/s3_health_check'
84122 require 'health_check/redis_health_check'
123 require 'health_check/elasticsearch_health_check'
85124 require 'health_check/sidekiq_health_check'
86125 require 'health_check/utils'
87126 require 'health_check/health_check_controller'
88127 require 'health_check/health_check_routes'
89128 require 'health_check/middleware_health_check'
129 require 'health_check/rabbitmq_health_check'
90130
91131 # vi: sw=2 sm ai:
00 #!/usr/bin/env ruby
11
22 require 'socket'
3 require 'openssl'
34
4 port = 3555
5 class FakeSmtpServer
6 def initialize(port)
7 @port = port
8 @socket = TCPServer.new(@port)
9 @client = @orig_client = nil
10 end
511
12 def start
13 return unless @client.nil?
614
7 server = TCPServer.new port
8 puts "fake_smtp_server: Waiting for one connection to port #{port} ..."
15 puts "fake_smtp_server: Waiting for one connection to port #{@port} ..."
16 @client = @socket.accept
917
10 def send(client, line)
11 client.puts line
12 puts "> #{line}"
18 send '220 dummy-smtp.example.com SMTP'
19 cmd = receive
20
21 while cmd !~ /^QUIT\r/
22 if cmd =~ /^HELO(.*)\r/
23 if ENV['FAIL_SMTP'] == 'HELO'
24 send '550 Access Denied – Invalid HELO name'
25 else
26 send '250-Welcome to a dummy smtp server'
27 unless ENV['SMTP_STARTTLS'] == 'DISABLED'
28 send '250-STARTTLS'
29 end
30 send '250-AUTH PLAIN LOGIN'
31 send '250 Ok'
32 end
33 elsif cmd =~ /^AUTH(.*)\r/
34 if ENV['FAIL_SMTP'] == 'AUTH'
35 send '535 5.7.8 Authentication credentials invalid'
36 else
37 send '235 2.7.0 Authentication successful'
38 end
39 elsif cmd =~ /^STARTTLS\r/
40 if ENV['SMTP_STARTTLS'] == 'DISABLED'
41 send '502 STARTTLS is disabled!'
42 end
43 send '220 Ready to start TLS'
44 if ENV['FAIL_SMTP'] == 'STARTTLS'
45 cmd = receive
46 return close
47 end
48 @orig_client = @client
49 @client = tlsconnect(@client)
50 else
51 send '502 I am so dumb I only understand HELO, AUTH, STARTTLS and QUIT which always return a success status'
52 end
53
54 cmd = receive
55 end
56 send '221 Bye Bye'
57
58 close
59 end
60
61 private
62
63 def close
64 @client.close unless @client.nil?
65 @orig_client.close unless @orig_client.nil?
66 end
67
68 def send(line)
69 @client.puts line
70 puts "-> #{line}"
71 end
72
73 def receive
74 line = @client.gets
75 puts "<- #{line}"
76 line
77 end
78
79 def ssl_socket(client, context)
80 OpenSSL::SSL::SSLSocket.new(client, context)
81 end
82
83 def ssl_context
84 @_ssl_context ||= begin
85 key, cert = generate_certificate
86
87 context = OpenSSL::SSL::SSLContext.new
88 context.key = key
89 context.cert = cert
90 context.verify_mode = OpenSSL::SSL::VERIFY_NONE
91 context.min_version = nil
92 context
93 end
94 end
95
96 # Pass socket from TCPServer.new accept
97 def tlsconnect(client)
98 ssl_client = ssl_socket(client, ssl_context)
99 puts '=> TLS connection started'
100 ssl_client.accept
101 puts '=> TLS connection established'
102
103 ssl_client
104 end
105
106 def generate_certificate
107 key = OpenSSL::PKey::RSA.new(2048)
108 name = OpenSSL::X509::Name.parse('CN=localhost')
109
110 cert = OpenSSL::X509::Certificate.new
111 cert.version = 2
112 cert.serial = 0
113 cert.not_before = Time.now
114 cert.not_after = Time.now + 3600
115
116 cert.public_key = key.public_key
117 cert.subject = name
118
119 extension_factory = OpenSSL::X509::ExtensionFactory.new nil, cert
120
121 cert.add_extension extension_factory.create_extension('basicConstraints', 'CA:FALSE', true)
122 cert.add_extension extension_factory.create_extension('keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature')
123 cert.add_extension extension_factory.create_extension('subjectKeyIdentifier', 'hash')
124
125 cert.issuer = name
126 cert.sign key, OpenSSL::Digest::SHA256.new
127
128 [key, cert]
129 end
13130 end
14131
15 def receive(client)
16 line = client.gets
17 puts "< #{line}"
18 line
19 end
132 FakeSmtpServer.new(3555).start
20133
21 client = server.accept # Wait for a client to connect
22 send(client, "220 dummy-smtp.example.com SMTP")
23 cmd = receive(client)
134 puts 'fake_smtp_server: Exiting now the conversation has finished.'
135 exit 0
24136
25 while cmd !~ /^QUIT\r/
26 if cmd =~ /^HELO(.*)\r/
27 send(client, "250 Welcome to a dummy smtp server")
28 else
29 send(client, "502 I am so dumb I only understand HELO and QUIT")
30 end
31 cmd = receive(client)
32 end
33 send(client, "221 Bye Bye")
34
35 client.close
36 puts "fake_smtp_server: Exiting now the conversation has finished."
37 exit 0
137 # Tested with irb script:
138 # require 'net/smtp'
139 #
140 # status = ''
141 # begin
142 # if @skip_external_checks
143 # status = '250'
144 # else
145 # smtp = Net::SMTP.new('localhost', 3555)
146 # smtp.enable_starttls
147 # smtp.open_timeout = 10
148 # smtp.read_timeout = 10
149 # smtp.start('domain', 'user_name', 'password', :plain) do
150 # status = smtp.helo('domain').status
151 # end
152 # end
153 # rescue Exception => ex
154 # status = ex.to_s
155 # end
156 # (status =~ /^250/) ? 'PASS' : "FAILED SMTP: #{status || 'unexpected error'}. "
00 #!/bin/bash
11
22 # Any failure causes exit
3 set -e
3 set -eE -o functrace
4
5 report_failure() {
6 local lineno=$2
7 local fn=$3
8 local exitstatus=$4
9 local msg=$5
10 local lineno_fns=${1% 0}
11 if [[ $lineno_fns != "0" ]] ; then
12 lineno="${lineno} ${lineno_fns}"
13 fi
14 if [[ $exitstatus == 0 ]] ; then
15 echo "${BASH_SOURCE[1]}: Finished!"
16 else
17 echo "${BASH_SOURCE[1]}:${fn}[${lineno}] Failed with status ${exitstatus}: $msg"
18 fi
19 }
20
21 trap 'report_failure "${BASH_LINENO[*]}" "$LINENO" "${FUNCNAME[*]:-script}" "$?" "$BASH_COMMAND"' ERR
422
523 echo Setting RAILS_ENV=test RACK_ENV=test
624 export RAILS_ENV=test RACK_ENV=test
00 class CreateUsers < ActiveRecord::Migration[5.0]
11 def self.up
2 create_table "users", :force => true do |t|
2 create_table "users", force: true do |t|
33 t.column :name, :string
44 end
55 end
66 exec echo Must be run as root
77 ;;
88 esac
9 set -xe
9
10 chruby_version=0.3.9
11 chruby=chruby-${chruby_version}
12 set -x
13 set -eE -o functrace
14
15 report_failure() {
16 local lineno=$2
17 local fn=$3
18 local exitstatus=$4
19 local msg=$5
20 local lineno_fns=${1% 0}
21 if [[ $lineno_fns != "0" ]] ; then
22 lineno="${lineno} ${lineno_fns}"
23 fi
24 if [[ $exitstatus == 0 ]] ; then
25 echo "${BASH_SOURCE[1]}: Finished!"
26 else
27 echo "${BASH_SOURCE[1]}:${fn}[${lineno}] Failed with status ${exitstatus}: $msg"
28 fi
29 }
30
31 trap 'report_failure "${BASH_LINENO[*]}" "$LINENO" "${FUNCNAME[*]:-script}" "$?" "$BASH_COMMAND"' ERR
32
33
1034 id
1135 pwd
1236 export DEBIAN_FRONTEND=noninteractive
1337 find /tmp/got-apt-update -mtime -1 || ( apt-get update && touch /tmp/got-apt-update )
14 apt install --yes --force-yes -q build-essential ruby ruby-dev sqlite3 libsqlite3-dev nodejs
15
38 apt install --yes -q build-essential ruby ruby-dev sqlite3 libsqlite3-dev nodejs git git-core
39 apt install --yes -q gcc autoconf bison libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm-dev
40 apt install --yes -q libgdbm3
41 # useful when debugging
42 apt install --yes -q silversearcher-ag vim exuberant-ctags
43 apt install --yes -q unattended-upgrades
44 unattended-upgrade
45 # The following is not required for testing, install if you are doing manual tests with extra gems
46 # apt install --yes -q mysql-client mysql-server libmysqlclient-dev
47 # apt install --yes -q libcurl4-openssl-dev libncurses5-dev libxml2-dev libxslt1-dev
1648 (
1749 echo Install chruby
18 [ -s chruby-0.3.9.tar.gz ] || wget -q -O chruby-0.3.9.tar.gz https://github.com/postmodern/chruby/archive/v0.3.9.tar.gz
19 [ chruby-0.3.9 ] || tar -xzf chruby-0.3.9.tar.gz
20 cd chruby-0.3.9/
50 [ -s ${chruby}.tar.gz ] || wget -q -O ${chruby}.tar.gz https://github.com/postmodern/chruby/archive/v${chruby_version}.tar.gz
51 [ -d ${chruby} ] || tar -xzf ${chruby}.tar.gz
52 cd ${chruby}/
2153 ./scripts/setup.sh
2254 cat > /etc/profile.d/chruby.sh <<'EOF'
2355 if [ -n "$BASH_VERSION" ] || [ -n "$ZSH_VERSION" ]; then
2456 source /usr/local/share/chruby/chruby.sh
57 #source /usr/local/share/chruby/auto
2558 fi
2659 EOF
2760 chmod a+r /etc/profile.d/chruby.sh
3265 which ruby-build || PREFIX=/usr/local ./ruby-build/install.sh
3366
3467 mkdir -p /opt/rubies
35 [ -x /opt/rubies/1.9.3-p551/bin/bundle ] || ( ruby-build 1.9.3-p551 /opt/rubies/1.9.3-p551 && /opt/rubies/1.9.3-p551/bin/gem install bundler )
36
37 for v in 2.2.0
68 for v in 2.2.2
3869 do
39 [ -x /opt/rubies/$v/bin/bundle ] || ( ruby-build $v /opt/rubies/$v && /opt/rubies/$v/bin/gem install bundler )
70 [ -x /opt/rubies/$v/bin/ruby ] || ( ruby-build $v /opt/rubies/$v )
71 [ -x /opt/rubies/${v}/bin/bundle ] || ( /opt/rubies/${v}/bin/gem install bundler -v '<2.0' )
72 done
73
74 for v in 2.3.8 2.4.10 2.5.9 2.5.0 2.6.6 2.6.7 2.7.1 2.7.3 3.0.1
75 do
76 [ -x /opt/rubies/$v/bin/ruby ] || ( ruby-build $v /opt/rubies/$v )
77 [ -x /opt/rubies/$v/bin/bundle ] || ( /opt/rubies/$v/bin/gem install bundler )
4078 done
4179 )
4280
4381 echo Setup system ruby
44 which bundle || gem install bundler
82 which bundle || gem install bundler || gem install bundler -v '<2.0'
83 which bundle || gem install bundler -v '< 2.0'
4584 bundle --version
4685 set +x
4786 cat <<EOF
4887
4988 Now test by running the following commands:
5089
90 vagrant ssh
91 cd /vagrant
92
5193 chruby RUBY_VERSION
5294 or
5395 chruby system # for system version 2.3.1
5496
55 vagrant ssh
56 cd /vagrant
5797 ./test/test_with_railsapp
98
99 exit
58100
59101 EOF
60102 exit
1616 gem 'sqlite3', "~> 1.3.7"
1717 end
1818 gem 'shoulda'
19 end
1920
20 # redis based checks
21 gem 'sidekiq', :require => !ENV['SIDEKIQ'].nil?
22 gem 'redis', :require => !ENV['REDIS_URL'].nil?
23 gem 'resque', :require => !ENV['RESQUE'].nil?
24 # s3 check
25 gem 'aws-sdk', :require => !ENV['AWS_ACCESS_KEY_ID'].nil?
26 end
21 # redis based checks
22 gem 'sidekiq', '~> 5.2.9', require: !ENV['SIDEKIQ'].nil? # REQUIRED
23 gem 'redis', '~> 4.0.3', require: !ENV['REDIS_URL'].nil? # REQUIRED
24 gem 'resque', '~> 1.27.4', require: !ENV['RESQUE'].nil? # REQUIRED
25 gem 'elasticsearch', '~> 6.3.1', require: !ENV['ELASTICSEARCH_URL'].nil? # REQUIRED
26 # s3 check
27 gem 'aws-sdk-s3', require: !ENV['AWS_ACCESS_KEY_ID'].nil? # REQUIRED
2728
2222 gem 'sqlite3', "~> 1.3.7"
2323 end
2424 gem 'shoulda'
25
26 # redis based checks
27 gem 'sidekiq', :require => !ENV['SIDEKIQ'].nil?
28 gem 'redis', :require => !ENV['REDIS_URL'].nil?
29 gem 'resque', :require => !ENV['RESQUE'].nil?
30 # s3 check
31 gem 'aws-sdk', :require => !ENV['AWS_ACCESS_KEY_ID'].nil?
32
3325 end
3426
27 # redis based checks
28 gem 'sidekiq', '~> 5.2.9', require: !ENV['SIDEKIQ'].nil? # REQUIRED
29 gem 'redis', '~> 4.0.3', require: !ENV['REDIS_URL'].nil? # REQUIRED
30 gem 'resque', '~> 1.27.4', require: !ENV['RESQUE'].nil? # REQUIRED
31 gem 'elasticsearch', '~> 6.3.1', require: !ENV['ELASTICSEARCH_URL'].nil? # REQUIRED
32 # s3 check
33 gem 'aws-sdk', require: !ENV['AWS_ACCESS_KEY_ID'].nil? # REQUIRED
0 # Gemfile for health_test testing
1
2 source 'https://rubygems.org'
3
4 ruby RUBY_VERSION < '2.2.2' ? '2.2.2' : RUBY_VERSION
5
6 gem 'rails', '~> 5.2.0'
7 gem 'rake', '>= 0.8.7'
8
9 # spring-watcher-listen was resolved to 2.0.1, which depends on
10 # listen was resolved to 3.1.5, which depends on
11 # ruby_dep
12 # and ruby_dep 1.5 requires 2.2.3 or later
13 gem 'ruby_dep', '~> 1.3.0' # REQUIRED
14
15 gem 'listen', '<3.1.2' # REQUIRED
16
17 group :development, :test do
18 if defined?(JRUBY_VERSION)
19 gem 'jruby-openssl'
20 gem 'activerecord-jdbcsqlite3-adapter'
21 else
22 gem 'sqlite3', "~> 1.3.7"
23 end
24 gem 'shoulda'
25 end
26
27 # redis based checks
28 gem 'sidekiq', '~> 5.2.9', require: !ENV['SIDEKIQ'].nil? # REQUIRED
29 gem 'redis', '~> 4.0.3', require: !ENV['REDIS_URL'].nil? # REQUIRED
30 gem 'resque', '~> 1.27.4', require: !ENV['RESQUE'].nil? # REQUIRED
31 gem 'elasticsearch', '~> 6.3.1', require: !ENV['ELASTICSEARCH_URL'].nil? # REQUIRED
32 # s3 check
33 gem 'aws-sdk', require: !ENV['AWS_ACCESS_KEY_ID'].nil? # REQUIRED
0 # Gemfile for health_test testing
1
2 source 'https://rubygems.org'
3
4 ruby RUBY_VERSION < '2.5' ? '2.5.0' : RUBY_VERSION
5
6 gem 'rails', '~> 6.0.0'
7 gem 'rake', '>= 0.8.7'
8
9 gem 'listen', '<3.1.2' # REQUIRED
10
11 group :development, :test do
12 if defined?(JRUBY_VERSION)
13 gem 'jruby-openssl'
14 gem 'activerecord-jdbcsqlite3-adapter'
15 else
16 gem 'sqlite3', "~> 1.3.7"
17 end
18 gem 'shoulda'
19 end
20
21 # redis based checks
22 gem 'sidekiq', '~> 5.2.9', require: !ENV['SIDEKIQ'].nil? # REQUIRED
23 gem 'redis', '~> 4.0.3', require: !ENV['REDIS_URL'].nil? # REQUIRED
24 gem 'resque', '~> 1.27.4', require: !ENV['RESQUE'].nil? # REQUIRED
25 gem 'elasticsearch', '~> 6.3.1', require: !ENV['ELASTICSEARCH_URL'].nil? # REQUIRED
26 # s3 check
27 gem 'aws-sdk-s3', require: !ENV['AWS_ACCESS_KEY_ID'].nil? # REQUIRED
28
29 gem 'webpacker', '~> 4.0.7' # REQUIRED
0 # Gemfile for health_test testing
1
2 source 'https://rubygems.org'
3
4 ruby RUBY_VERSION < '2.5' ? '2.5.0' : RUBY_VERSION
5
6 gem 'rails', '~> 6.1.0'
7 gem 'rake', '>= 0.8.7'
8
9 group :development, :test do
10 if defined?(JRUBY_VERSION)
11 gem 'jruby-openssl'
12 gem 'activerecord-jdbcsqlite3-adapter'
13 else
14 gem 'sqlite3', "~> 1.3.7"
15 end
16 gem 'shoulda'
17 end
18
19 # redis based checks
20 gem 'sidekiq', require: !ENV['SIDEKIQ'].nil? # REQUIRED
21 gem 'redis', require: !ENV['REDIS_URL'].nil? # REQUIRED
22 gem 'resque', require: !ENV['RESQUE'].nil? # REQUIRED
23 # s3 check
24 gem 'aws-sdk-s3', require: !ENV['AWS_ACCESS_KEY_ID'].nil? # REQUIRED
25
26 gem 'webpacker', '~> 4.0.7' # REQUIRED
27 gem 'rexml', '~> 3.2.4' # REQUIRED for ruby 3.0
28 gem 'webrick' # REQUIRED for ruby 3.0
0 # Gemfile for health_test testing
1
2 source 'https://rubygems.org'
3
4 ruby RUBY_VERSION < '2.5' ? '2.5.0' : RUBY_VERSION
5
6 gem 'rails', '~> 6.2.0'
7 gem 'rake', '>= 0.8.7'
8
9 group :development, :test do
10 if defined?(JRUBY_VERSION)
11 gem 'jruby-openssl'
12 gem 'activerecord-jdbcsqlite3-adapter'
13 else
14 gem 'sqlite3', "~> 1.3.7"
15 end
16 gem 'shoulda'
17 end
18
19 # redis based checks
20 gem 'sidekiq', '~> 5.2.9', require: !ENV['SIDEKIQ'].nil? # REQUIRED
21 gem 'redis', '~> 4.0.3', require: !ENV['REDIS_URL'].nil? # REQUIRED
22 gem 'resque', '~> 1.27.4', require: !ENV['RESQUE'].nil? # REQUIRED
23 gem 'elasticsearch', '~> 6.3.1', require: !ENV['ELASTICSEARCH_URL'].nil? # REQUIRED
24 # s3 check
25 gem 'aws-sdk-s3', require: !ENV['AWS_ACCESS_KEY_ID'].nil? # REQUIRED
26
27 gem 'webpacker', '~> 4.0.7' # REQUIRED
28 gem 'rexml', '~> 3.2.4' # REQUIRED for ruby 3.0
29 gem 'webrick' # REQUIRED for ruby 3.0
0 # Gemfile for health_test testing
1
2 source 'https://rubygems.org'
3
4 # Bundle edge Rails instead:
5
6 ruby RUBY_VERSION < '2.2.2' ? '2.2.2' : RUBY_VERSION
7
8 gem 'rails'
9 gem 'rake'
10 gem 'rack'
11
12 group :development, :test do
13 if defined?(JRUBY_VERSION)
14 gem 'jruby-openssl'
15 gem 'activerecord-jdbcsqlite3-adapter'
16 else
17 gem 'sqlite3'
18 end
19 gem 'shoulda'
20 end
21
22 # redis based checks
23 gem 'sidekiq', '~> 5.2.9', require: !ENV['SIDEKIQ'].nil? # REQUIRED
24 gem 'redis', '~> 4.0.3', require: !ENV['REDIS_URL'].nil? # REQUIRED
25 gem 'resque', '~> 1.27.4', require: !ENV['RESQUE'].nil? # REQUIRED
26 gem 'elasticsearch', '~> 6.3.1', require: !ENV['ELASTICSEARCH_URL'].nil? # REQUIRED
27 # s3 check
28 gem 'aws-sdk-s3', require: !ENV['AWS_ACCESS_KEY_ID'].nil? # REQUIRED
29
30 # Initial Gemfile has therubyracer commented out
31 gem 'therubyrhino', platform: :jruby # REQUIRED
32 gem 'therubyracer', platform: :ruby # REQUIRED
33
34 gem 'webpacker', '~> 4.0.7' # REQUIRED
35 gem 'rexml', '~> 3.2.4' # REQUIRED for ruby 3.0
36 gem 'webrick' # REQUIRED for ruby 3.0
11
22 route_prefix=medical_check
33
4 err_report() {
5 echo "$0: Error on line $1 - aborted"
6 exit 1
4 # Any failure causes exit
5 set -eE -o functrace
6
7 report_failure() {
8 local lineno=$2
9 local fn=$3
10 local exitstatus=$4
11 local msg=$5
12 local lineno_fns=${1% 0}
13 if [[ $lineno_fns != "0" ]] ; then
14 lineno="${lineno} ${lineno_fns}"
15 fi
16 if [[ $exitstatus == 0 ]] ; then
17 echo "${BASH_SOURCE[1]}: Finished!"
18 else
19 echo "${BASH_SOURCE[1]}:${fn}[${lineno}] Failed with status ${exitstatus}: $msg"
20 fi
721 }
822
9 trap 'err_report $LINENO' ERR
10
11 # Any failure causes exit
12 set -e
23 trap 'report_failure "${BASH_LINENO[*]}" "$LINENO" "${FUNCNAME[*]:-script}" "$?" "$BASH_COMMAND"' ERR
24
1325
1426 case "$1" in
1527 [0-9]*)
5365 if $rbenv_which bundle ; then
5466 echo Bundler is installed
5567 else
56 gem install bundler
68 gem install bundler ${BUNDLER_VERSION:+-v ${BUNDLER_VERSION}}
5769 $rehash
5870 fi
5971
6173 if ! smarter_bundle ; then
6274 echo "Test aborted (missing required gems)"
6375 exit 2
76 elif [ ! -s $BUNDLE_GEMFILE.lock ] ; then
77 echo "Error: smarter_bundler return OK status BUT lock file ($BUNDLE_GEMFILE.lock) is missing!"
78 exit 3
79 else
80 echo bundle passed - lock file contains:
81 cat $BUNDLE_GEMFILE.lock
82 echo
6483 fi
6584 $rehash
6685
6887 rake="$base_dir/test/bin/rake"
6988
7089 echo Checking $rails is present ...
71 [ -f $rails -a -f $rake ] || bundle exec rake rails:update:bin || echo '(ignored rake rails:update:bin exit status)'
72 [ -f $rails ] || bundle binstubs railties || echo '(ignored bundle exit status)'
73 [ -f $rails ] || bundle binstubs rails || echo '(ignored bundle exit status)'
90 [ -f $rails -a -f $rake ] || bundle ${BUNDLER_VERSION:+_${BUNDLER_VERSION}_} exec rake rails:update:bin || echo '(ignored rake rails:update:bin exit status)'
91 [ -f $rails ] || bundle ${BUNDLER_VERSION:+_${BUNDLER_VERSION}_} binstubs railties || echo '(ignored bundle exit status)'
92 [ -f $rails ] || bundle ${BUNDLER_VERSION:+_${BUNDLER_VERSION}_} binstubs rails || echo '(ignored bundle exit status)'
7493 if [ ! -f $rails ]; then
7594 echo "Test aborted (unable to create $rails)"
7695 exit 2
7897
7998 if [ ! -f $rake ]; then
8099 echo "Running bundle binstubs rake ..."
81 if ! bundle binstubs rake || [ ! -f $rake ]; then
100 if ! bundle ${BUNDLER_VERSION:+_${BUNDLER_VERSION}_} binstubs rake || [ ! -f $rake ]; then
82101 echo "Test aborted (unable to create $rake)"
83102 exit 2
84103 fi
123142
124143 echo "Creating $actual_rails_version app in $tmp_dir/railsapp using adapter $db"
125144 case "$actual_rails_version" in
126 *' '[12].*)
127 $rails railsapp -d $db
128 ;;
129145 *' '[345].*)
146 args="--skip-bundle -d $db"
130147 case "$BUNDLE_GEMFILE" in
131148 *rails_edge.gemfile)
132 $rails new railsapp --skip-bundle -d $db --edge
149 $rails new railsapp $args --edge
133150 ;;
134151 *)
135 $rails new railsapp --skip-bundle -d $db
152 $rails new railsapp $args
136153 ;;
137154 esac
138155 ;;
156 *' '[6].*)
157 args="--skip-bundle -d $db --skip-git --skip-bootsnap"
158 case "$BUNDLE_GEMFILE" in
159 *rails_edge.gemfile)
160 $rails new railsapp $args --edge
161 ;;
162 *)
163 $rails new railsapp $args
164 ;;
165 esac
166 ;;
139167 *)
140168 echo "Unknown rails version"
141169 ;;
154182 cat >> config/environment.rb <<'!EOF!'
155183
156184 ActionMailer::Base.delivery_method = :smtp
157 ActionMailer::Base.smtp_settings = { :address => "localhost", :port => 3555 }
185 ActionMailer::Base.smtp_settings = { address: "localhost", port: 3555 }
158186
159187 !EOF!
160188
161189 echo Adding an initializer for health_check gem ...
162190 mkdir -p config/initializers
163191 tee config/initializers/health_check.rb <<!
164 HealthCheck.setup do |config|
165 config.success = "$success"
166 config.smtp_timeout = 60.0
167 config.http_status_for_error_text = 550
168 config.http_status_for_error_object = 555
169 config.uri = '$route_prefix'
170 config.origin_ip_whitelist = ENV['IP_WHITELIST'].split(',') unless ENV['IP_WHITELIST'].blank?
171 config.basic_auth_username = ENV['AUTH_USER'] unless ENV['AUTH_USER'].blank?
172 config.basic_auth_password = ENV['AUTH_PASSWORD'] unless ENV['AUTH_PASSWORD'].blank?
173
174 config.add_custom_check do
175 File.exists?("$custom_file") ? '' : '$custom_file is missing!'
192 require 'fileutils'
193
194 if defined? HealthCheck
195 HealthCheck.setup do |config|
196 config.success = "$success"
197 config.smtp_timeout = 60.0
198 config.http_status_for_error_text = 550
199 config.http_status_for_error_object = 555
200 config.uri = '$route_prefix'
201 config.origin_ip_whitelist = ENV['IP_WHITELIST'].split(',') unless ENV['IP_WHITELIST'].blank?
202 config.basic_auth_username = ENV['AUTH_USER'] unless ENV['AUTH_USER'].blank?
203 config.basic_auth_password = ENV['AUTH_PASSWORD'] unless ENV['AUTH_PASSWORD'].blank?
204
205 config.add_custom_check do
206 File.exists?("$custom_file") ? '' : '$custom_file is missing!'
207 end
208
209 config.add_custom_check('pass') do
210 ''
211 end
212
213 config.on_failure do |checks, msg|
214 File.open('tmp/health_check_failure.txt', 'w') do |f|
215 f.puts "FAILED: #{checks}, MESSAGE: #{msg}"
216 end
217 end
218
219 config.on_success do |checks|
220 File.open('tmp/health_check_success.txt', 'w') do |f|
221 f.puts "PASSED: #{checks}"
222 end
223 end
224
225 config.include_error_in_response_body = ENV['HIDE_ERROR_RESPONSE'].to_s !~ /^[1tTyY]/
176226 end
177
178 config.add_custom_check('pass') do
179 ''
180 end
181
182227 end
183228 !
184229
193238 exit 2
194239 fi
195240 echo Adding health_check as gem to Gemfile...
196 echo "gem 'health_check', :path => '$base_dir'" >> Gemfile
241 echo "gem 'health_check', path: '$base_dir'" >> Gemfile
197242
198243 case "$RAILS_SERVER" in
199244 webrick|'')
204249 echo "gem '$RAILS_SERVER'" >> Gemfile
205250 ;;
206251 esac
207
208 sed -i.bak -e '/listen/s/^/#Earlier version required # /' Gemfile
209
210 egrep REQUIRED < ${INITIAL_BUNDLE_GEMFILE} >> Gemfile || echo No required gems found...
252 TAB=$'\t'
253 QUOTES='"'"'"
254 case "$actual_rails_version" in
255 *' '5.0*)
256 if egrep -i 'gem.*sqlite3' Gemfile ; then
257 # Can't do this as a require as we may go back to testing JRuby
258 echo Force sqlite to 1.3.13+ version for Rails 5.0 ...
259 gem=sqlite3
260 sed -i.bak -e "s/^\([ ${TAB}]*gem[ ${TAB}]*[${QUOTES}]${gem}[${QUOTES}]\)\(.*\)$/\1, '~> 1.3.13' # overriden: \2/" Gemfile
261 fi
262 ;;
263 esac
264 if egrep -q REQUIRED ${INITIAL_BUNDLE_GEMFILE} ; then
265 sed -n "s/^[ ${TAB}]*gem[ ${TAB}]*[${QUOTES}]\([^${QUOTES}]*\)[${QUOTES}].*REQUIRED.*/\1/p" ${INITIAL_BUNDLE_GEMFILE} | while read gem
266 do
267 echo "Commenting out gem '$gem' line in Gemfile"
268 sed -i.bak -e "s/^\([ ${TAB}]*gem[ ${TAB}]*[${QUOTES}]${gem}[${QUOTES}].*\)$/# overriden by REQUIRED below: \1/" Gemfile
269 done
270 echo Adding Required gems
271 egrep REQUIRED ${INITIAL_BUNDLE_GEMFILE} | tee -a Gemfile
272 else
273 echo No required gems to be added to Gemfile
274 fi
211275
212276 echo
213 echo ================= Gemfile ===================
277 echo ================= $PWD/Gemfile ===================
214278 cat Gemfile
215279 echo
216 echo running bundle install
217 smarter_bundle ${BUNDLER_VERSION:+_${BUNDLER_VERSION}_} install
280 echo ==================================================
281 echo running smarter_bundle install
282 smarter_bundle install
218283 $rehash
284
285 if egrep webpacker Gemfile && [ ! -f config/webpacker.yml ] ; then
286 echo completing setup by running rails webpacker:install ...
287 $rails webpacker:install
288 fi
289
219290 echo "Using binstubs in $railsapp/bin for rails and rake commands"
220291 rails="$railsapp/bin/rails"
221292 rake="$railsapp/bin/rake"
222293
223294 echo Checking $rails is present ...
224 [ -f $rails -a -f $rake ] || bundle exec rake rails:update:bin || echo '(ignored rake rails:update:bin exit status)'
225 [ -f $rails ] || bundle binstubs railties || echo '(ignored bundle exit status)'
226 [ -f $rails ] || bundle binstubs rails || echo '(ignored bundle exit status)'
295 [ -f $rails -a -f $rake ] || bundle ${BUNDLER_VERSION:+_${BUNDLER_VERSION}_} exec rake rails:update:bin || echo '(ignored rake rails:update:bin exit status)'
296 [ -f $rails ] || bundle ${BUNDLER_VERSION:+_${BUNDLER_VERSION}_} binstubs railties || echo '(ignored bundle exit status)'
297 [ -f $rails ] || bundle ${BUNDLER_VERSION:+_${BUNDLER_VERSION}_} binstubs rails || echo '(ignored bundle exit status)'
227298 if [ ! -f $rails ]; then
228299 echo "Test aborted (unable to create $rails)"
229300 exit 2
230301 fi
231302
232303 echo Checking $rake is present ...
233 [ -f $rake ] || bundle binstubs rake || echo '(ignored bundle exit status)'
304 [ -f $rake ] || bundle ${BUNDLER_VERSION:+_${BUNDLER_VERSION}_} binstubs rake || echo '(ignored bundle exit status)'
234305 if [ ! -f $rake ]; then
235306 echo "Test aborted (unable to create $rake)"
236307 exit 2
239310 $rehash
240311 # Fix for rvm, otherwise bundle run from rails create fails
241312 export PATH="`pwd`/bin:$PATH"
242 echo ================= Gemfile.lock ===================
313 echo ================= $PWD/Gemfile.lock ===================
243314 cat Gemfile.lock
315 echo ==================================================
244316 echo
245317
246318 for e in test ${RAILS_ENV2:-production}
254326 echo
255327 fi
256328 done
257 echo "============== config/environment.rb ============="
329
330 if egrep -q 'bootsnap.setup' config/boot.rb ; then
331 echo Commenting out bootsnap from config/boot.rb
332 sed -i.bak -e 's/^\(.*bootsnap.setup\)/# \1/' config/boot.rb
333 echo "============== $PWD/config/boot.rb ============="
334 cat config/boot.rb
335 echo ==================================================
336 fi
337 rm -rf tmp/cache/bootsnap*
338 echo
339
340 echo "============== $PWD/config/environment.rb ============="
258341 cat config/environment.rb
259342 echo
260343
261 echo ========================
344 echo =========================================================
262345 case $db in
263346 jdbcsqlite3)
264347 for e in test ${RAILS_ENV2:-production}
349432 class ExampleController < ApplicationController
350433
351434 def index
352 render :plain => 'example page'
435 render plain: 'example page'
353436 end
354437
355438 def catchall
356 render :plain => 'catch all route'
439 render plain: 'catch all route'
357440 end
358441
359442 end
387470
388471 #echo =============== config/application.rb-old ========================
389472 #cat config/application.rb-old
390 echo =============== config/application.rb ========================
473 echo =============== $PWD/config/application.rb ========================
391474 cat config/application.rb
392475 else
393476 echo FAILED: NO config/application.rb file!!
411494 # rails 3.0+
412495 echo " # -----------------------------------------"
413496 echo " # START OF SECTION FOR TESTING HEALTH_CHECK"
414 echo " get 'example(/:action(/:id))(.:format)' => 'example'"
497 echo " get 'example/catchall(.:format)', controller: :example, action: :catchall"
498 echo " get 'example(.:format)', controller: :example, action: :index"
415499 echo " if File.exists?('$catchall_file')"
416500 echo " health_check_routes"
417501 echo " # CATCH ALL ROUTE"
418 echo " get '*path', :to => 'example#catchall'"
502 echo " get '*path', controller: :example, action: :catchall"
419503 echo " end"
420504 echo " # END OF SECTION FOR TESTING HEALTH_CHECK"
421505 echo " # ---------------------------------------"
11
22 route_prefix=medical_check
33
4 err_report() {
5 echo "$0: Error on line $1 - aborted"
6 exit 1
4 # Any failure causes exit
5 set -eE -o functrace
6
7 report_failure() {
8 local lineno=$2
9 local fn=$3
10 local exitstatus=$4
11 local msg=$5
12 local lineno_fns=${1% 0}
13 if [[ $lineno_fns != "0" ]] ; then
14 lineno="${lineno} ${lineno_fns}"
15 fi
16 if [[ $exitstatus == 0 ]] ; then
17 echo "${BASH_SOURCE[1]}: Finished!"
18 else
19 echo "${BASH_SOURCE[1]}:${fn}[${lineno}] Failed with status ${exitstatus}: $msg"
20 fi
721 }
822
9 trap 'err_report $LINENO' ERR
23 trap 'report_failure "${BASH_LINENO[*]}" "$LINENO" "${FUNCNAME[*]:-script}" "$?" "$BASH_COMMAND"' ERR
24
1025
1126 # Any failure causes exit
12 set -e
27 set -eE -o functrace
28
29 report_failure() {
30 local lineno=$2
31 local fn=$3
32 local exitstatus=$4
33 local msg=$5
34 local lineno_fns=${1% 0}
35 if [[ $lineno_fns != "0" ]] ; then
36 lineno="${lineno} ${lineno_fns}"
37 fi
38 if [[ $exitstatus == 0 ]] ; then
39 echo "${BASH_SOURCE[1]}: Finished!"
40 else
41 echo "${BASH_SOURCE[1]}:${fn}[${lineno}] Failed with status ${exitstatus}: $msg"
42 fi
43 }
44
45 trap 'report_failure "${BASH_LINENO[*]}" "$LINENO" "${FUNCNAME[*]:-script}" "$?" "$BASH_COMMAND"' ERR
46
1347 export DISABLE_SPRING=1
1448
1549 cleanup_db()
90124 bundle_prefix='bundle exec'
91125 fi
92126 server_arg=${RAILS_SERVER:-webrick}
127 case "$actual_rails_version" in
128 *' '[12345].*)
129 ;;
130 *)
131 server_arg="-u $server_arg"
132 ;;
133 esac
93134 echo "start_server called using: `env | egrep '^RAILS|^RACK|^PATH='` $bundle_prefix $server_arg"
94135 case "$server_arg" in
95 puma)
136 *puma)
96137 $bundle_prefix puma -b tcp://127.0.0.1:$port &
97138 ;;
98 passenger)
139 *passenger)
99140 $bundle_prefix passenger start -p $port &
100141 ;;
101 thin)
142 *thin)
102143 $bundle_prefix thin start -p $port &
103144 ;;
104 unicorn)
145 *unicorn)
105146 $bundle_prefix unicorn_rails -l 127.0.0.1:$port &
106147 ;;
107148 *)
211252 test_no=$1
212253
213254 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
214 echo "${test_no}: CHECKING routes exist..."
255 echo "${test_no}[line $LINENO]: CHECKING routes exist..."
215256 $rake routes | tee /tmp/t$$
216257 echo
217258 case `egrep ${route_prefix} /tmp/t$$ || true` in
224265
225266 test_no=`expr 1 + $test_no`
226267 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
227 echo "${test_no}: TESTING can get a static file ..."
268 echo "${test_no}[line $LINENO]: TESTING can get a static file ..."
228269 case "$RAILS_ENV=`egrep '^\s*config.serve_static_[asetfil]* *= *false' config/environments/${RAILS_ENV}.rb`" in
229270 production*static*false*)
230271 echo " SKIPPED (disabled in production)"
237278 echo
238279 fi
239280
240 test_no=`expr 1 + $test_no`
241 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
242 echo "${test_no}: TESTING can get an example controller ..."
281 rm -f tmp/health_check_success.txt tmp/health_check_failure.txt
282
283 test_no=`expr 1 + $test_no`
284 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
285 echo "${test_no}[line $LINENO]: TESTING can get an example controller ..."
243286 $testurl ${host}/example 200 text/plain 'example page'
244287 echo
245288 fi
246289
247290 test_no=`expr 1 + $test_no`
248291 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
249 echo "${test_no}: TESTING direct call to catchall method on example controller ..."
292 echo "${test_no}[line $LINENO]: TESTING direct call to catchall method on example controller ..."
250293 $testurl ${host}/example/catchall 200 text/plain 'catch all route'
251294 echo
252295 fi
253296
254 test_no=`expr 1 + $test_no`
255 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
256 echo "${test_no}: TESTING ${route_prefix}/migration should pass with no database migrations ..."
297 if [ -f tmp/health_check_success.txt ] ; then
298 echo "FAIL tmp/health_check_success.txt exists on line $LINENO"
299 else
300 echo "PASS tmp/health_check_success.txt is missing as expected on line $LINENO"
301 fi
302 if [ -f tmp/health_check_failure.txt ] ; then
303 echo "FAIL tmp/health_check_failure.txt exists on line $LINENO"
304 else
305 echo "PASS tmp/health_check_failure.txt is missing as expected on line $LINENO"
306 fi
307
308 test_no=`expr 1 + $test_no`
309 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
310 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/migration should pass with no database migrations ..."
257311 ls db/migrate
312 rm -f tmp/health_check_success.txt tmp/health_check_failure.txt
258313 $testurl ${host}/${route_prefix}/migration 200 text/plain $success
259 echo
260 fi
261
262 test_no=`expr 1 + $test_no`
263 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
264 echo "${test_no}: TESTING ${route_prefix}/migration should fail without initial database migration ..."
314 if [ -f tmp/health_check_success.txt ] ; then
315 echo "PASS tmp/health_check_success.txt exists as expected on line $LINENO"
316 cat tmp/health_check_success.txt
317 else
318 echo "FAIL tmp/health_check_success.txt is missing on line $LINENO"
319 fi
320 if [ -f tmp/health_check_failure.txt ] ; then
321 echo "FAIL tmp/health_check_failure.txt exists on line $LINENO"
322 else
323 echo "PASS tmp/health_check_failure.txt is missing as expected on line $LINENO"
324 fi
325 echo
326 fi
327
328 test_no=`expr 1 + $test_no`
329 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
330 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/migration should fail without initial database migration ..."
265331 cp $base_dir/test/migrate/nine/* db/migrate
266332 ls db/migrate
333 rm -f tmp/health_check_success.txt tmp/health_check_failure.txt
267334 $testurl ${host}/${route_prefix}/migration 550 text/plain failed
268 echo
269 fi
270
271 test_no=`expr 1 + $test_no`
272 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
273 echo "${test_no}: TESTING ${route_prefix}/database should pass without initial database migration (since it ignores the difference) ..."
335 if [ -f tmp/health_check_success.txt ] ; then
336 echo "FAIL tmp/health_check_success.txt exists on line $LINENO"
337 else
338 echo "PASS tmp/health_check_success.txt is missing as expected on line $LINENO"
339 fi
340 if [ -f tmp/health_check_failure.txt ] ; then
341 echo "PASS tmp/health_check_failure.txt exists as expected on line $LINENO"
342 cat tmp/health_check_failure.txt
343 else
344 echo "FAIL tmp/health_check_failure.txt is missing on line $LINENO"
345 fi
346 echo
347 fi
348
349 test_no=`expr 1 + $test_no`
350 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
351 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/database should pass without initial database migration (since it ignores the difference) ..."
274352 $testurl ${host}/${route_prefix}/database 200 text/plain $success
275353 echo
276354 fi
279357
280358 test_no=`expr 1 + $test_no`
281359 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
282 echo "${test_no}: TESTING ${route_prefix}/site should pass ..."
360 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/site should pass ..."
283361 $testurl ${host}/${route_prefix}/site 200 text/plain $success
284362 echo
285363 fi
286364
287365 test_no=`expr 1 + $test_no`
288366 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
289 echo "${test_no}: TESTING ${route_prefix}/migration should pass after initial database migration ..."
367 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/migration should pass after initial database migration ..."
290368 $rake db:migrate
291369 $testurl ${host}/${route_prefix}/migration 200 text/plain $success
292370 echo
302380
303381 test_no=`expr 1 + $test_no`
304382 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
305 echo "${test_no}: TESTING ${route_prefix}/database should fail if the database has been corrupted ..."
306
307 $testurl ${host}/${route_prefix}/database 550 text/plain failed
308 echo
309 fi
310
311 test_no=`expr 1 + $test_no`
312 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
313 echo "${test_no}: TESTING ${route_prefix}/site should pass ..."
383 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/database should fail if the database has been corrupted ..."
384
385 $testurl ${host}/${route_prefix}/database 550 text/plain failed:
386 echo
387 fi
388
389 export HIDE_ERROR_RESPONSE=true
390 stop_server
391 start_server
392
393 test_no=`expr 1 + $test_no`
394 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
395 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/database should have response body 'health_check failed' but no error details if include_error_in_response_body is false"
396 $testurl ${host}/${route_prefix}/database 550 text/plain 'health_check failed' failed:
397 echo
398 fi
399
400 unset HIDE_ERROR_RESPONSE
401 stop_server
402 start_server
403
404 test_no=`expr 1 + $test_no`
405 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
406 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/site should pass ..."
314407 $testurl ${host}/${route_prefix}/site 200 text/plain $success
315408 if $has_middleware; then
316 echo "${test_no}: TESTING ${route_prefix}/middleware_site should pass ..."
409 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/middleware_site should pass ..."
317410 $testurl ${host}/${route_prefix}/middleware_site 200 text/plain $success
318411 fi
319412 echo
324417
325418 test_no=`expr 1 + $test_no`
326419 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
327 echo "${test_no}: TESTING ${route_prefix}/migration should fail without all migrations ..."
420 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/migration should fail without all migrations ..."
328421 cp $base_dir/test/migrate/twelve/* db/migrate
329422
330423 ls db/migrate
334427
335428 test_no=`expr 1 + $test_no`
336429 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
337 echo "${test_no}: TESTING ${route_prefix}/migration should pass after both database migrations ..."
430 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/migration should pass after both database migrations ..."
338431 $rake db:migrate
339432 $testurl ${host}/${route_prefix}/migration 200 text/plain $success
340433 echo
342435
343436 test_no=`expr 1 + $test_no`
344437 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
345 echo "${test_no}: TESTING ${route_prefix}/migration should pass after both database migrations ..."
438 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/migration should pass after both database migrations ..."
346439 $rake db:migrate
347440 $testurl ${host}/${route_prefix}/migration 200 text/plain $success
348441 echo
350443
351444 test_no=`expr 1 + $test_no`
352445 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
353 echo "${test_no}: TESTING ${route_prefix}/email should fail without smtp available ..."
446 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/email should fail without smtp available ..."
354447 $testurl ${host}/${route_prefix}/email 550 text/plain failed
355448 echo
356449 fi
357450
358451 test_no=`expr 1 + $test_no`
359452 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
360 echo "${test_no}: TESTING ${route_prefix}/email should pass with smtp available ..."
453 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/email should pass with smtp available ..."
361454 $fake_smtp_server &
362455 fake_smtp_pid=$!
363456 sleep 5
367460
368461 test_no=`expr 1 + $test_no`
369462 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
370 echo "${test_no}: TESTING ${route_prefix} (all) should fail without smtp available ..."
463 echo "${test_no}[line $LINENO]: TESTING ${route_prefix} (all) should fail without smtp available ..."
371464 $testurl ${host}/${route_prefix} 550 text/plain failed
372465 echo
373466 fi
374467
375468 test_no=`expr 1 + $test_no`
376469 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
377 echo "${test_no}: TESTING ${route_prefix}/all should fail without smtp available ..."
470 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/all should fail without smtp available ..."
378471 $testurl ${host}/${route_prefix} 550 text/plain failed
379472 echo
380473 fi
382475 kill -9 $fake_smtp_pid || echo fake_smtp_server had finished as expected
383476 test_no=`expr 1 + $test_no`
384477 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
385 echo "${test_no}: TESTING ${route_prefix} (all) should pass with smtp available ..."
478 echo "${test_no}[line $LINENO]: TESTING ${route_prefix} (all) should pass with smtp available ..."
386479 $fake_smtp_server &
387480 fake_smtp_pid=$!
388481 sleep 5
393486 kill -9 $fake_smtp_pid || echo fake_smtp_server had finished as expected
394487 test_no=`expr 1 + $test_no`
395488 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
396 echo "${test_no}: TESTING ${route_prefix}/all should pass with smtp available ..."
489 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/all should pass with smtp available ..."
397490 $fake_smtp_server &
398491 fake_smtp_pid=$!
399492 sleep 5
403496
404497 test_no=`expr 1 + $test_no`
405498 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
406 echo "${test_no}: TESTING ${route_prefix}/pass should pass ..."
499 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/pass should pass ..."
407500 $testurl ${host}/${route_prefix}/pass 200 text/plain $success
408501 echo
409502 fi
410503
411504 test_no=`expr 1 + $test_no`
412505 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
413 echo "${test_no}: TESTING ${route_prefix}/custom should pass ..."
506 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/custom should pass ..."
414507 $testurl ${host}/${route_prefix}/custom 200 text/plain $success
415508 echo
416509 fi
417510
418511 test_no=`expr 1 + $test_no`
419512 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
420 echo "${test_no}: TESTING ${route_prefix}/custom.html should pass (returning plain text) ..."
513 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/custom.html should pass (returning plain text) ..."
421514 $testurl ${host}/${route_prefix}/custom.html 200 text/plain $success
422515 echo
423516 fi
424517
425518 test_no=`expr 1 + $test_no`
426519 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
427 echo "${test_no}: TESTING ${route_prefix}/custom.json should pass ..."
520 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/custom.json should pass ..."
428521 $testurl ${host}/${route_prefix}/custom.json 200 application/json '"healthy":true'
429522 $testurl ${host}/${route_prefix}/custom.json 200 application/json "\"message\":\"$success\""
430523 echo
432525
433526 test_no=`expr 1 + $test_no`
434527 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
435 echo "${test_no}: TESTING ${route_prefix}/custom.xml should pass ..."
528 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/custom.xml should pass ..."
436529 $testurl ${host}/${route_prefix}/custom.xml 200 application/xml '<healthy type="boolean">true</healthy>'
437530 $testurl ${host}/${route_prefix}/custom.xml 200 application/xml "<message>$success</message>"
438531 echo
441534 test_no=`expr 1 + $test_no`
442535 rm -f $custom_file
443536 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
444 echo "${test_no}: TESTING ${route_prefix}/custom should fail when custom returns string ..."
537 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/custom should fail when custom returns string ..."
445538 $testurl ${host}/${route_prefix}/custom 550 text/plain failed
446539 echo
447540 fi
448541
449542 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
450 echo "${test_no}: TESTING ${route_prefix}/pass should pass even if other custom test returns string ..."
543 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/pass should pass even if other custom test returns string ..."
451544 $testurl ${host}/${route_prefix}/pass 200 text/plain $success
452545 echo
453546 fi
454547
455548 test_no=`expr 1 + $test_no`
456549 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
457 echo "${test_no}: TESTING ${route_prefix} (all) should fail when custom check fails ..."
550 echo "${test_no}[line $LINENO]: TESTING ${route_prefix} (all) should fail when custom check fails ..."
458551 $testurl ${host}/${route_prefix} 550 text/plain "$custom_file is missing!"
459552 echo
460553 fi
461554
462555 test_no=`expr 1 + $test_no`
463556 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
464 echo "${test_no}: TESTING ${route_prefix}.json (all) should fail when custom check fails ..."
557 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}.json (all) should fail when custom check fails ..."
465558 $testurl ${host}/${route_prefix}.json 555 application/json '"healthy":false'
466559 $testurl ${host}/${route_prefix}.json 555 application/json "$custom_file is missing!"
467560 echo
469562
470563 test_no=`expr 1 + $test_no`
471564 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
472 echo "${test_no}: TESTING ${route_prefix}.xml (all) should fail when custom check fails ..."
565 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}.xml (all) should fail when custom check fails ..."
473566 $testurl ${host}/${route_prefix}.xml 555 application/xml '<healthy type="boolean">false</healthy>'
474567 echo
475568 fi
477570 test_no=`expr 1 + $test_no`
478571 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
479572 if $has_middleware; then
480 echo "${test_no}: TESTING ${route_prefix}/middleware_site should pass ..."
573 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/middleware_site should pass ..."
481574 $testurl ${host}/${route_prefix}/middleware_site 200 text/plain $success
482575 else
483 echo "${test_no}: TESTING ${route_prefix}/middleware_site should fail ..."
576 echo "${test_no}[line $LINENO]: TESTING ${route_prefix}/middleware_site should fail ..."
484577 $testurl ${host}/${route_prefix}/middleware_site 550 text/plain failed
485578 fi
486579 echo
488581
489582 test_no=`expr 1 + $test_no`
490583 if [ -z "$run_test" ] || [ $test_no == "$run_test" ]; then
491 echo "${test_no}: TESTING log files to check for deprecation warnings ..."
584 echo "${test_no}[line $LINENO]: TESTING log files to check for deprecation warnings ..."
492585 if egrep ' is deprecated|DEPRECATION WARNING' $railsapp/log/[tp][er][so][td]*.log
493586 then
494587 echo Found deprecation warnings - failed test
6161 end
6262 end
6363
64 if ARGV[4] and ARGV[4] != ''
65 if !page_content.to_s.include? ARGV[4]
66 puts "PASS (did not find #{ARGV[4]})"
67 else
68 puts "FAIL (found #{ARGV[4]}) - page contents:" , page_content.to_s, 'END-OF-CONTENTS'
69 exit 3
70 end
71 end
72
6473 exit 0