├── log
└── .keep
├── app
├── mailers
│ └── .keep
├── models
│ ├── .keep
│ ├── concerns
│ │ └── .keep
│ ├── application_record.rb
│ ├── status.rb
│ ├── outage.rb
│ └── service.rb
├── assets
│ ├── images
│ │ └── .keep
│ ├── javascripts
│ │ └── application.js
│ └── stylesheets
│ │ └── application.css
├── controllers
│ ├── concerns
│ │ └── .keep
│ └── application_controller.rb
├── helpers
│ └── application_helper.rb
├── workers
│ └── services_status_fetcher_worker.rb
├── clock.rb
├── services
│ ├── outage_handler.rb
│ ├── outage_notifier.rb
│ ├── statuses_processor.rb
│ ├── services_status_fetcher.rb
│ ├── status_fetcher.rb
│ └── services_status_evaluator.rb
└── views
│ └── layouts
│ └── application.html.erb
├── lib
├── assets
│ └── .keep
└── tasks
│ └── .keep
├── public
├── favicon.ico
├── robots.txt
├── 500.html
├── 422.html
└── 404.html
├── vendor
└── assets
│ ├── javascripts
│ └── .keep
│ └── stylesheets
│ └── .keep
├── .rspec
├── bin
├── rake
├── bundle
├── rails
├── spring
├── update
└── setup
├── config
├── database.yml.travis
├── spring.rb
├── boot.rb
├── routes.rb
├── environment.rb
├── cable.yml
├── initializers
│ ├── session_store.rb
│ ├── mime_types.rb
│ ├── application_controller_renderer.rb
│ ├── filter_parameter_logging.rb
│ ├── cookies_serializer.rb
│ ├── backtrace_silencers.rb
│ ├── assets.rb
│ ├── wrap_parameters.rb
│ ├── inflections.rb
│ └── new_framework_defaults.rb
├── application.rb
├── database.yml
├── locales
│ └── en.yml
├── configurations.rb
├── secrets.yml
├── environments
│ ├── test.rb
│ ├── development.rb
│ └── production.rb
└── puma.rb
├── Procfile
├── config.ru
├── Rakefile
├── db
├── migrate
│ ├── 20161130194304_create_outages.rb
│ ├── 20161129164903_create_statuses.rb
│ └── 20161129164753_create_services.rb
├── seeds.rb
└── schema.rb
├── .travis.yml
├── spec
├── unit
│ └── app
│ │ ├── workers
│ │ └── status_fetcher_worker_spec.rb
│ │ └── services
│ │ ├── outage_notifier_spec.rb
│ │ ├── outage_handler_spec.rb
│ │ ├── services_status_fetcher_spec.rb
│ │ ├── statuses_processor_spec.rb
│ │ ├── services_status_evaluator_spec.rb
│ │ └── status_fetcher_spec.rb
├── rails_helper.rb
└── spec_helper.rb
├── .gitignore
├── Gemfile
├── LICENSE.md
├── Gemfile.lock
└── README.md
/log/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/mailers/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/models/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/lib/assets/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/lib/tasks/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/assets/images/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/models/concerns/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/controllers/concerns/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/vendor/assets/javascripts/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/vendor/assets/stylesheets/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.rspec:
--------------------------------------------------------------------------------
1 | --color
2 | --require spec_helper
3 |
--------------------------------------------------------------------------------
/app/helpers/application_helper.rb:
--------------------------------------------------------------------------------
1 | module ApplicationHelper
2 | end
3 |
--------------------------------------------------------------------------------
/bin/rake:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require_relative '../config/boot'
3 | require 'rake'
4 | Rake.application.run
5 |
--------------------------------------------------------------------------------
/config/database.yml.travis:
--------------------------------------------------------------------------------
1 | test:
2 | adapter: postgresql
3 | database: travis_ci_test
4 | username: postgres
5 |
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | web: bundle exec rails s
2 | worker: bundle exec sidekiq
3 | clock: bundle exec clockwork app/clock.rb
4 |
--------------------------------------------------------------------------------
/app/models/application_record.rb:
--------------------------------------------------------------------------------
1 | class ApplicationRecord < ActiveRecord::Base
2 | self.abstract_class = true
3 | end
4 |
--------------------------------------------------------------------------------
/app/models/status.rb:
--------------------------------------------------------------------------------
1 | class Status < ApplicationRecord
2 | belongs_to :service
3 |
4 | validates_presence_of :code
5 | end
6 |
--------------------------------------------------------------------------------
/app/models/outage.rb:
--------------------------------------------------------------------------------
1 | class Outage < ApplicationRecord
2 | belongs_to :service
3 |
4 | validates_presence_of :service_id, :codes
5 | end
6 |
--------------------------------------------------------------------------------
/bin/bundle:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
3 | load Gem.bin_path('bundler', 'bundle')
4 |
--------------------------------------------------------------------------------
/config/spring.rb:
--------------------------------------------------------------------------------
1 | %w(
2 | .ruby-version
3 | .rbenv-vars
4 | tmp/restart.txt
5 | tmp/caching-dev.txt
6 | ).each { |path| Spring.watch(path) }
7 |
--------------------------------------------------------------------------------
/config/boot.rb:
--------------------------------------------------------------------------------
1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
2 |
3 | require 'bundler/setup' # Set up gems listed in the Gemfile.
4 |
--------------------------------------------------------------------------------
/bin/rails:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | APP_PATH = File.expand_path('../config/application', __dir__)
3 | require_relative '../config/boot'
4 | require 'rails/commands'
5 |
--------------------------------------------------------------------------------
/config/routes.rb:
--------------------------------------------------------------------------------
1 | Rails.application.routes.draw do
2 | # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
3 | end
4 |
--------------------------------------------------------------------------------
/config/environment.rb:
--------------------------------------------------------------------------------
1 | # Load the Rails application.
2 | require_relative 'application'
3 |
4 | # Initialize the Rails application.
5 | Rails.application.initialize!
6 |
--------------------------------------------------------------------------------
/config.ru:
--------------------------------------------------------------------------------
1 | # This file is used by Rack-based servers to start the application.
2 |
3 | require ::File.expand_path('../config/environment', __FILE__)
4 | run Rails.application
5 |
--------------------------------------------------------------------------------
/config/cable.yml:
--------------------------------------------------------------------------------
1 | development:
2 | adapter: async
3 |
4 | test:
5 | adapter: async
6 |
7 | production:
8 | adapter: redis
9 | url: redis://localhost:6379/1
10 |
--------------------------------------------------------------------------------
/config/initializers/session_store.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | Rails.application.config.session_store :cookie_store, key: '_the_nurse_session'
4 |
--------------------------------------------------------------------------------
/config/initializers/mime_types.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new mime types for use in respond_to blocks:
4 | # Mime::Type.register "text/richtext", :rtf
5 |
--------------------------------------------------------------------------------
/app/models/service.rb:
--------------------------------------------------------------------------------
1 | class Service < ApplicationRecord
2 | has_many :statuses
3 | has_many :outages
4 |
5 | validates_presence_of :name, :url
6 |
7 | scope :active, -> { where(active: true) }
8 | end
9 |
--------------------------------------------------------------------------------
/app/workers/services_status_fetcher_worker.rb:
--------------------------------------------------------------------------------
1 | class ServicesStatusFetcherWorker
2 | include Sidekiq::Worker
3 |
4 | def perform
5 | ServicesStatusFetcher.call
6 | ServicesStatusEvaluator.call
7 | end
8 | end
9 |
--------------------------------------------------------------------------------
/config/initializers/application_controller_renderer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # ApplicationController.renderer.defaults.merge!(
4 | # http_host: 'example.org',
5 | # https: false
6 | # )
7 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
2 | #
3 | # To ban all spiders from the entire site uncomment the next two lines:
4 | # User-agent: *
5 | # Disallow: /
6 |
--------------------------------------------------------------------------------
/config/initializers/filter_parameter_logging.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Configure sensitive parameters which will be filtered from the log file.
4 | Rails.application.config.filter_parameters += [:password]
5 |
--------------------------------------------------------------------------------
/app/controllers/application_controller.rb:
--------------------------------------------------------------------------------
1 | class ApplicationController < ActionController::Base
2 | # Prevent CSRF attacks by raising an exception.
3 | # For APIs, you may want to use :null_session instead.
4 | protect_from_forgery with: :exception
5 | end
6 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | # Add your own tasks in files placed in lib/tasks ending in .rake,
2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3 |
4 | require File.expand_path('../config/application', __FILE__)
5 |
6 | Rails.application.load_tasks
7 |
--------------------------------------------------------------------------------
/app/clock.rb:
--------------------------------------------------------------------------------
1 | require 'clockwork'
2 | require './config/boot'
3 | require './config/environment'
4 |
5 | module Clockwork
6 | every Configurations.health_check_rate.minutes, 'service_status.fetch' do
7 | ServicesStatusFetcherWorker.perform_async
8 | end
9 | end
10 |
--------------------------------------------------------------------------------
/app/services/outage_handler.rb:
--------------------------------------------------------------------------------
1 | class OutageHandler
2 | def self.call(service, last_codes_received)
3 | OutageNotifier.call(service, last_codes_received)
4 |
5 | Outage.create(
6 | service: service,
7 | codes: last_codes_received
8 | )
9 | end
10 | end
11 |
--------------------------------------------------------------------------------
/config/initializers/cookies_serializer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Specify a serializer for the signed and encrypted cookie jars.
4 | # Valid options are :json, :marshal, and :hybrid.
5 | Rails.application.config.action_dispatch.cookies_serializer = :json
6 |
--------------------------------------------------------------------------------
/db/migrate/20161130194304_create_outages.rb:
--------------------------------------------------------------------------------
1 | class CreateOutages < ActiveRecord::Migration[5.0]
2 | def change
3 | create_table :outages do |t|
4 | t.references :service, foreign_key: true
5 | t.integer :codes, array: true
6 |
7 | t.timestamps
8 | end
9 | end
10 | end
11 |
--------------------------------------------------------------------------------
/app/services/outage_notifier.rb:
--------------------------------------------------------------------------------
1 | class OutageNotifier
2 | def self.call(service, codes)
3 | uri = URI(Configurations.doctor_url)
4 |
5 | Net::HTTP.post_form(
6 | uri,
7 | service_name: service.name,
8 | service_url: service.url,
9 | 'codes[]' => codes
10 | )
11 | end
12 | end
13 |
--------------------------------------------------------------------------------
/db/migrate/20161129164903_create_statuses.rb:
--------------------------------------------------------------------------------
1 | class CreateStatuses < ActiveRecord::Migration
2 | def change
3 | create_table :statuses do |t|
4 | t.integer :code, null: false
5 | t.references :service, index: true, foreign_key: true
6 |
7 | t.timestamps null: false
8 | end
9 | end
10 | end
11 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: ruby
2 | rvm:
3 | - 2.3.1
4 | cache: bundler
5 | services:
6 | - postgresql
7 | addons:
8 | postgresql: '9.4'
9 | before_script:
10 | - cp config/database.yml.travis config/database.yml
11 | - psql -c 'create database travis_ci_test;' -U postgres
12 | - bundle exec rake db:migrate
13 | script: bundle exec rspec
14 |
--------------------------------------------------------------------------------
/app/services/statuses_processor.rb:
--------------------------------------------------------------------------------
1 | class StatusesProcessor
2 | def self.call(statuses)
3 | statuses.each do |name, code|
4 | service = Service.where(name: name).first
5 |
6 | next if service.nil?
7 |
8 | Status.create(
9 | service: service,
10 | code: code
11 | )
12 | end
13 | end
14 | end
15 |
--------------------------------------------------------------------------------
/db/seeds.rb:
--------------------------------------------------------------------------------
1 | # This file should contain all the record creation needed to seed the database with its default values.
2 | # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
3 | #
4 | # Examples:
5 | #
6 | # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
7 | # Mayor.create(name: 'Emanuel', city: cities.first)
8 |
--------------------------------------------------------------------------------
/app/services/services_status_fetcher.rb:
--------------------------------------------------------------------------------
1 | class ServicesStatusFetcher
2 | def self.call(services = Service.active)
3 | names_and_urls_hash = services.each_with_object({}) do |service, result|
4 | result[service.name] = service.url
5 | end
6 |
7 | statuses = StatusFetcher.call(names_and_urls_hash)
8 |
9 | StatusesProcessor.call(statuses)
10 | end
11 | end
12 |
--------------------------------------------------------------------------------
/db/migrate/20161129164753_create_services.rb:
--------------------------------------------------------------------------------
1 | class CreateServices < ActiveRecord::Migration
2 | def change
3 | create_table :services do |t|
4 | t.string :name, null: false
5 | t.string :url, null: false
6 | t.boolean :active, default: true
7 | t.integer :allowed_codes, array: true
8 |
9 | t.timestamps null: false
10 | end
11 | end
12 | end
13 |
--------------------------------------------------------------------------------
/app/views/layouts/application.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | TheNurse
5 | <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
6 | <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
7 | <%= csrf_meta_tags %>
8 |
9 |
10 |
11 | <%= yield %>
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/config/initializers/backtrace_silencers.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
5 |
6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
7 | # Rails.backtrace_cleaner.remove_silencers!
8 |
--------------------------------------------------------------------------------
/app/services/status_fetcher.rb:
--------------------------------------------------------------------------------
1 | class StatusFetcher
2 | def self.call(services_hash)
3 | return {} if Configurations.sickbay_url.nil?
4 |
5 | uri = URI(Configurations.sickbay_url)
6 |
7 | uri.query = URI.encode_www_form(services_hash)
8 |
9 | response = Net::HTTP.get_response(uri)
10 |
11 | return {} unless response.is_a? Net::HTTPOK
12 |
13 | JSON.parse(response.body)
14 | rescue JSON::ParserError
15 | {}
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/config/initializers/assets.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Version of your assets, change this if you want to expire all your assets.
4 | Rails.application.config.assets.version = '1.0'
5 |
6 | # Add additional assets to the asset load path
7 | # Rails.application.config.assets.paths << Emoji.images_path
8 |
9 | # Precompile additional assets.
10 | # application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
11 | # Rails.application.config.assets.precompile += %w( search.js )
12 |
--------------------------------------------------------------------------------
/bin/spring:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 |
3 | # This file loads spring without using Bundler, in order to be fast.
4 | # It gets overwritten when you run the `spring binstub` command.
5 |
6 | unless defined?(Spring)
7 | require 'rubygems'
8 | require 'bundler'
9 |
10 | lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read)
11 | if spring = lockfile.specs.detect { |spec| spec.name == "spring" }
12 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path
13 | gem 'spring', spring.version
14 | require 'spring/binstub'
15 | end
16 | end
17 |
--------------------------------------------------------------------------------
/config/initializers/wrap_parameters.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # This file contains settings for ActionController::ParamsWrapper which
4 | # is enabled by default.
5 |
6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
7 | ActiveSupport.on_load(:action_controller) do
8 | wrap_parameters format: [:json]
9 | end
10 |
11 | # To enable root element in JSON for ActiveRecord objects.
12 | # ActiveSupport.on_load(:active_record) do
13 | # self.include_root_in_json = true
14 | # end
15 |
--------------------------------------------------------------------------------
/spec/unit/app/workers/status_fetcher_worker_spec.rb:
--------------------------------------------------------------------------------
1 | require 'rails_helper'
2 |
3 | RSpec.describe ServicesStatusFetcherWorker do
4 | describe '.perform' do
5 | before do
6 | allow(ServicesStatusFetcher).to receive(:call)
7 | allow(ServicesStatusEvaluator).to receive(:call)
8 | end
9 |
10 | it 'calls ServicesStatusFetcher and ServicesStatusEvaluator' do
11 | described_class.new.perform
12 |
13 | expect(ServicesStatusFetcher).to have_received(:call).once
14 | expect(ServicesStatusEvaluator).to have_received(:call).once
15 | end
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files.
2 | #
3 | # If you find yourself ignoring temporary files generated by your text editor
4 | # or operating system, you probably want to add a global ignore instead:
5 | # git config --global core.excludesfile '~/.gitignore_global'
6 |
7 | # Ignore bundler config.
8 | /.bundle
9 |
10 | # Ignore the default SQLite database.
11 | /db/*.sqlite3
12 | /db/*.sqlite3-journal
13 |
14 | # Ignore all logfiles and tempfiles.
15 | /log/*
16 | !/log/.keep
17 | /tmp
18 |
19 | # Ignore coverage data
20 |
21 | coverage/
22 |
--------------------------------------------------------------------------------
/app/services/services_status_evaluator.rb:
--------------------------------------------------------------------------------
1 | class ServicesStatusEvaluator
2 | def self.call(services = Service.active)
3 | services.each do |service|
4 | last_codes = service.statuses.last(Configurations.evaluating.entries_fetched).pluck(:code)
5 |
6 | bad_codes_count = 0
7 |
8 | last_codes.each do |code|
9 | bad_codes_count += 1 unless service.allowed_codes.include?(code)
10 | end
11 |
12 | if bad_codes_count >= Configurations.evaluating.entries_expected_to_be_ok
13 | OutageHandler.call(service, last_codes)
14 | end
15 | end
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/config/application.rb:
--------------------------------------------------------------------------------
1 | require_relative 'boot'
2 |
3 | require 'rails/all'
4 |
5 | # Require the gems listed in Gemfile, including any gems
6 | # you've limited to :test, :development, or :production.
7 | Bundler.require(*Rails.groups)
8 |
9 | require File.expand_path('../configurations', __FILE__)
10 |
11 | module TheNurse
12 | class Application < Rails::Application
13 | # Settings in config/environments/* take precedence over those specified here.
14 | # Application configuration should go into files in config/initializers
15 | # -- all .rb files in that directory are automatically loaded.
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/config/database.yml:
--------------------------------------------------------------------------------
1 | # SQLite version 3.x
2 | # gem install sqlite3
3 | #
4 | # Ensure the SQLite 3 gem is defined in your Gemfile
5 | # gem 'sqlite3'
6 | #
7 | default: &default
8 | adapter: postgresql
9 | pool: 5
10 | timeout: 5000
11 |
12 | development:
13 | <<: *default
14 | database: db/development
15 |
16 | # Warning: The database defined as "test" will be erased and
17 | # re-generated from your development database when you run "rake".
18 | # Do not set this db to the same as development or production.
19 | test:
20 | <<: *default
21 | database: db/test
22 |
23 | production:
24 | <<: *default
25 | database: db/production
26 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | ruby '2.3.1'
4 |
5 | gem 'rails', '5.0.0.1'
6 | gem 'sass-rails', '~> 5.0'
7 | gem 'uglifier', '>= 1.3.0'
8 | gem 'coffee-rails', '~> 4.1.0'
9 | gem 'jquery-rails'
10 | gem 'turbolinks'
11 | gem 'jbuilder', '~> 2.0'
12 | gem 'sdoc', '~> 0.4.0', group: :doc
13 |
14 | gem 'clockwork'
15 | gem 'foreman'
16 | gem 'mixlib-config', require: 'mixlib/config'
17 | gem 'pg'
18 | gem 'sidekiq'
19 |
20 | group :development do
21 | gem 'web-console', '~> 2.0'
22 | gem 'spring'
23 | end
24 |
25 | group :development, :test do
26 | gem 'byebug'
27 | gem 'pry'
28 | gem 'rspec-rails'
29 | end
30 |
31 | group :test do
32 | gem 'coveralls', require: false
33 | gem 'webmock'
34 | end
35 |
--------------------------------------------------------------------------------
/config/initializers/inflections.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new inflection rules using the following format. Inflections
4 | # are locale specific, and you may define rules for as many different
5 | # locales as you wish. All of these examples are active by default:
6 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
7 | # inflect.plural /^(ox)$/i, '\1en'
8 | # inflect.singular /^(ox)en/i, '\1'
9 | # inflect.irregular 'person', 'people'
10 | # inflect.uncountable %w( fish sheep )
11 | # end
12 |
13 | # These inflection rules are supported but not enabled by default:
14 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
15 | # inflect.acronym 'RESTful'
16 | # end
17 |
--------------------------------------------------------------------------------
/config/locales/en.yml:
--------------------------------------------------------------------------------
1 | # Files in the config/locales directory are used for internationalization
2 | # and are automatically loaded by Rails. If you want to use locales other
3 | # than English, add the necessary files in this directory.
4 | #
5 | # To use the locales, use `I18n.t`:
6 | #
7 | # I18n.t 'hello'
8 | #
9 | # In views, this is aliased to just `t`:
10 | #
11 | # <%= t('hello') %>
12 | #
13 | # To use a different locale, set it with `I18n.locale`:
14 | #
15 | # I18n.locale = :es
16 | #
17 | # This would use the information in config/locales/es.yml.
18 | #
19 | # To learn more, please read the Rails Internationalization guide
20 | # available at http://guides.rubyonrails.org/i18n.html.
21 |
22 | en:
23 | hello: "Hello world"
24 |
--------------------------------------------------------------------------------
/app/assets/javascripts/application.js:
--------------------------------------------------------------------------------
1 | // This is a manifest file that'll be compiled into application.js, which will include all the files
2 | // listed below.
3 | //
4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
5 | // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
6 | //
7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
8 | // compiled file.
9 | //
10 | // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
11 | // about supported directives.
12 | //
13 | //= require jquery
14 | //= require jquery_ujs
15 | //= require turbolinks
16 | //= require_tree .
17 |
--------------------------------------------------------------------------------
/spec/unit/app/services/outage_notifier_spec.rb:
--------------------------------------------------------------------------------
1 | require 'rails_helper'
2 |
3 | RSpec.describe OutageNotifier do
4 | describe '#call' do
5 | let(:service) do
6 | Service.create(
7 | name: 'ExampleService',
8 | url: 'www.example-service.com',
9 | allowed_codes: [200]
10 | )
11 | end
12 |
13 | let(:codes) do
14 | ["200", "500", "500"]
15 | end
16 |
17 | before do
18 | stub_request(:post, Configurations.doctor_url).
19 | with(:body => {"codes"=> codes, "service_name"=>"ExampleService", "service_url"=>"www.example-service.com"})
20 | end
21 |
22 | it 'sends a POST call to your Doctor endpoint' do
23 | described_class.call(service, codes)
24 | end
25 | end
26 | end
27 |
--------------------------------------------------------------------------------
/app/assets/stylesheets/application.css:
--------------------------------------------------------------------------------
1 | /*
2 | * This is a manifest file that'll be compiled into application.css, which will include all the files
3 | * listed below.
4 | *
5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7 | *
8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9 | * compiled file so the styles you add here take precedence over styles defined in any styles
10 | * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
11 | * file per style scope.
12 | *
13 | *= require_tree .
14 | *= require_self
15 | */
16 |
--------------------------------------------------------------------------------
/config/configurations.rb:
--------------------------------------------------------------------------------
1 | module Configurations
2 | extend Mixlib::Config
3 |
4 | # Sickbay is a service that is able to fetch the status of multiple endpoints at once. You can read more about it and learn how deploy your own instance here:
5 | # https://github.com/IgorMarques/sickbay
6 | default :sickbay_url, ENV.fetch('SICKBAY_URL', 'https://sickbay.herokuapp.com')
7 |
8 | # Doctor is teh service where you can determine actions to be taken when a patient (service) is down for some reason
9 | default :doctor_url, ENV.fetch('DOCTOR_URL', 'https://sickbay.herokuapp.com')
10 |
11 | default :health_check_rate, ENV.fetch('HEALTH_CHECK_RATE', 1).to_i
12 |
13 | config_context :evaluating do
14 | default :entries_fetched, ENV.fetch('ENTRIES_FETCHED', 3).to_i
15 |
16 | default :entries_expected_to_be_ok, ENV.fetch('ENTRIES_OK', 2).to_i
17 | end
18 | end
19 |
--------------------------------------------------------------------------------
/bin/update:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require 'pathname'
3 | require 'fileutils'
4 | include FileUtils
5 |
6 | # path to your application root.
7 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
8 |
9 | def system!(*args)
10 | system(*args) || abort("\n== Command #{args} failed ==")
11 | end
12 |
13 | chdir APP_ROOT do
14 | # This script is a way to update your development environment automatically.
15 | # Add necessary update steps to this file.
16 |
17 | puts '== Installing dependencies =='
18 | system! 'gem install bundler --conservative'
19 | system('bundle check') || system!('bundle install')
20 |
21 | puts "\n== Updating database =="
22 | system! 'bin/rails db:migrate'
23 |
24 | puts "\n== Removing old logs and tempfiles =="
25 | system! 'bin/rails log:clear tmp:clear'
26 |
27 | puts "\n== Restarting application server =="
28 | system! 'bin/rails restart'
29 | end
30 |
--------------------------------------------------------------------------------
/config/secrets.yml:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Your secret key is used for verifying the integrity of signed cookies.
4 | # If you change this key, all old signed cookies will become invalid!
5 |
6 | # Make sure the secret is at least 30 characters and all random,
7 | # no regular words or you'll be exposed to dictionary attacks.
8 | # You can use `rails secret` to generate a secure secret key.
9 |
10 | # Make sure the secrets in this file are kept private
11 | # if you're sharing your code publicly.
12 |
13 | development:
14 | secret_key_base: e197badec81eabef12597087d71a2e0ae7081965d193631ee488e23efcbca48097f23fd5848cf0285b3ac5b22ae67a06e007cc66fee2548a45afdf95f6c8b4c5
15 |
16 | test:
17 | secret_key_base: 72897e2c0dba1a058a06d89f208d6504f5d6d42e9112d019511a42372082a3ed8edccbba8937b40e7f569b2b19587e469b9597f07c97a95821bf87b35aeb7cdb
18 |
19 | # Do not keep production secrets in the repository,
20 | # instead read values from the environment.
21 | production:
22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
23 |
--------------------------------------------------------------------------------
/bin/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require 'pathname'
3 | require 'fileutils'
4 | include FileUtils
5 |
6 | # path to your application root.
7 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
8 |
9 | def system!(*args)
10 | system(*args) || abort("\n== Command #{args} failed ==")
11 | end
12 |
13 | chdir APP_ROOT do
14 | # This script is a starting point to setup your application.
15 | # Add necessary setup steps to this file.
16 |
17 | puts '== Installing dependencies =='
18 | system! 'gem install bundler --conservative'
19 | system('bundle check') || system!('bundle install')
20 |
21 | # puts "\n== Copying sample files =="
22 | # unless File.exist?('config/database.yml')
23 | # cp 'config/database.yml.sample', 'config/database.yml'
24 | # end
25 |
26 | puts "\n== Preparing database =="
27 | system! 'bin/rails db:setup'
28 |
29 | puts "\n== Removing old logs and tempfiles =="
30 | system! 'bin/rails log:clear tmp:clear'
31 |
32 | puts "\n== Restarting application server =="
33 | system! 'bin/rails restart'
34 | end
35 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright © 2016 Igor Marques
4 |
5 | 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:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | 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.
10 |
--------------------------------------------------------------------------------
/config/initializers/new_framework_defaults.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 | #
3 | # This file contains migration options to ease your Rails 5.0 upgrade.
4 | #
5 | # Once upgraded flip defaults one by one to migrate to the new default.
6 | #
7 | # Read the Rails 5.0 release notes for more info on each option.
8 |
9 | # Enable per-form CSRF tokens. Previous versions had false.
10 | Rails.application.config.action_controller.per_form_csrf_tokens = false
11 |
12 | # Enable origin-checking CSRF mitigation. Previous versions had false.
13 | Rails.application.config.action_controller.forgery_protection_origin_check = false
14 |
15 | # Make Ruby 2.4 preserve the timezone of the receiver when calling `to_time`.
16 | # Previous versions had false.
17 | ActiveSupport.to_time_preserves_timezone = false
18 |
19 | # Require `belongs_to` associations by default. Previous versions had false.
20 | Rails.application.config.active_record.belongs_to_required_by_default = false
21 |
22 | # Do not halt callback chains when a callback returns false. Previous versions had true.
23 | ActiveSupport.halt_callback_chains_on_return_false = true
24 |
--------------------------------------------------------------------------------
/spec/unit/app/services/outage_handler_spec.rb:
--------------------------------------------------------------------------------
1 | require 'rails_helper'
2 |
3 | RSpec.describe OutageHandler do
4 | describe '#call' do
5 | before do
6 | allow(OutageNotifier).to receive(:call)
7 | end
8 |
9 | let(:service) do
10 | Service.create(
11 | name: 'ExampleService',
12 | url: 'www.example-service.com',
13 | allowed_codes: [200]
14 | )
15 | end
16 |
17 | let(:last_codes) do
18 | [200, 500, 500]
19 | end
20 |
21 | it 'notifies the outage' do
22 | described_class.call(service, last_codes)
23 |
24 | expect(OutageNotifier).to have_received(:call).with(service, last_codes)
25 | end
26 |
27 | it 'creates an outage' do
28 | expect {
29 | described_class.call(service, last_codes)
30 | }.to change(Outage, :count).by(1)
31 | end
32 |
33 | it 'creates an outage with the given service and status' do
34 | allow(Outage).to receive(:create)
35 |
36 | described_class.call(service, last_codes)
37 |
38 | expect(Outage)
39 | .to have_received(:create)
40 | .with(
41 | service: service,
42 | codes: last_codes
43 | )
44 | end
45 | end
46 | end
47 |
--------------------------------------------------------------------------------
/spec/unit/app/services/services_status_fetcher_spec.rb:
--------------------------------------------------------------------------------
1 | require 'rails_helper'
2 |
3 | RSpec.describe ServicesStatusFetcher do
4 | describe '#call' do
5 | before do
6 | allow(StatusFetcher).to receive(:call).and_return(statuses)
7 |
8 | allow(StatusesProcessor).to receive(:call)
9 | end
10 |
11 | let(:statuses) do
12 | {
13 | 'ExampleService' => '200',
14 | 'AnotherExampleService' => '200'
15 | }
16 | end
17 |
18 | let(:services) do
19 | [
20 | Service.new(
21 | name: 'ExampleService',
22 | url: 'www.example-service.com'
23 | ),
24 | Service.new(
25 | name: 'AnotherExampleService',
26 | url: 'www.another-example-service.com'
27 | )
28 | ]
29 | end
30 |
31 | it 'gets the statuses of the given services' do
32 | described_class.call(services)
33 |
34 | expect(StatusFetcher).to have_received(:call).with(
35 | {
36 | 'ExampleService' => 'www.example-service.com',
37 | 'AnotherExampleService' => 'www.another-example-service.com',
38 | }
39 | )
40 | end
41 |
42 | it 'processes the statuses of the given services' do
43 | described_class.call(services)
44 |
45 | expect(StatusesProcessor).to have_received(:call).with(statuses)
46 | end
47 | end
48 | end
49 |
--------------------------------------------------------------------------------
/spec/unit/app/services/statuses_processor_spec.rb:
--------------------------------------------------------------------------------
1 | require 'rails_helper'
2 |
3 | RSpec.describe StatusesProcessor do
4 | describe '#call' do
5 | context 'when sending a valid list of statuses' do
6 | let(:statuses) do
7 | {
8 | 'ExampleService' => '200',
9 | 'AnotherExampleService' => '200',
10 | 'AnUnregisteredService' => '200'
11 | }
12 | end
13 |
14 | let!(:first_service) do
15 | Service.create(
16 | name: 'ExampleService',
17 | url: 'www.example-service.com'
18 | )
19 | end
20 |
21 | let!(:second_service) do
22 | Service.create(
23 | name: 'AnotherExampleService',
24 | url: 'www.another-example-service.com'
25 | )
26 | end
27 |
28 | it 'creates a Status entry for each existing service in the list' do
29 | expect {
30 | described_class.call(statuses)
31 | }.to change(Status, :count).by(2)
32 | end
33 |
34 | it 'creates a Status entry referencing the given existing services' do
35 | allow(Status).to receive(:create).twice
36 |
37 | described_class.call(statuses)
38 |
39 | expect(Status).to have_received(:create).with(service: first_service, code: '200')
40 |
41 | expect(Status).to have_received(:create).with(service: second_service, code: '200')
42 | end
43 | end
44 |
45 | context 'when sending an empty list of statuses' do
46 | it 'does not raise an error' do
47 | expect{ described_class.call( {} ) }.to_not raise_error
48 | end
49 | end
50 | end
51 | end
52 |
--------------------------------------------------------------------------------
/public/500.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | We're sorry, but something went wrong (500)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
We're sorry, but something went wrong.
62 |
63 |
If you are the application owner check the logs for more information.
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/public/422.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The change you wanted was rejected (422)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The change you wanted was rejected.
62 |
Maybe you tried to change something you didn't have access to.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/public/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The page you were looking for doesn't exist (404)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The page you were looking for doesn't exist.
62 |
You may have mistyped the address or the page may have moved.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/config/environments/test.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # The test environment is used exclusively to run your application's
5 | # test suite. You never need to work with it otherwise. Remember that
6 | # your test database is "scratch space" for the test suite and is wiped
7 | # and recreated between test runs. Don't rely on the data there!
8 | config.cache_classes = true
9 |
10 | # Do not eager load code on boot. This avoids loading your whole application
11 | # just for the purpose of running a single test. If you are using a tool that
12 | # preloads Rails for running tests, you may have to set it to true.
13 | config.eager_load = false
14 |
15 | # Configure public file server for tests with Cache-Control for performance.
16 | config.public_file_server.enabled = true
17 | config.public_file_server.headers = {
18 | 'Cache-Control' => 'public, max-age=3600'
19 | }
20 |
21 | # Show full error reports and disable caching.
22 | config.consider_all_requests_local = true
23 | config.action_controller.perform_caching = false
24 |
25 | # Raise exceptions instead of rendering exception templates.
26 | config.action_dispatch.show_exceptions = false
27 |
28 | # Disable request forgery protection in test environment.
29 | config.action_controller.allow_forgery_protection = false
30 | config.action_mailer.perform_caching = false
31 |
32 | # Tell Action Mailer not to deliver emails to the real world.
33 | # The :test delivery method accumulates sent emails in the
34 | # ActionMailer::Base.deliveries array.
35 | config.action_mailer.delivery_method = :test
36 |
37 | # Print deprecation notices to the stderr.
38 | config.active_support.deprecation = :stderr
39 |
40 | # Raises error for missing translations
41 | # config.action_view.raise_on_missing_translations = true
42 | end
43 |
--------------------------------------------------------------------------------
/config/environments/development.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # In the development environment your application's code is reloaded on
5 | # every request. This slows down response time but is perfect for development
6 | # since you don't have to restart the web server when you make code changes.
7 | config.cache_classes = false
8 |
9 | # Do not eager load code on boot.
10 | config.eager_load = false
11 |
12 | # Show full error reports.
13 | config.consider_all_requests_local = true
14 |
15 | # Enable/disable caching. By default caching is disabled.
16 | if Rails.root.join('tmp/caching-dev.txt').exist?
17 | config.action_controller.perform_caching = true
18 |
19 | config.cache_store = :memory_store
20 | config.public_file_server.headers = {
21 | 'Cache-Control' => 'public, max-age=172800'
22 | }
23 | else
24 | config.action_controller.perform_caching = false
25 |
26 | config.cache_store = :null_store
27 | end
28 |
29 | # Don't care if the mailer can't send.
30 | config.action_mailer.raise_delivery_errors = false
31 |
32 | config.action_mailer.perform_caching = false
33 |
34 | # Print deprecation notices to the Rails logger.
35 | config.active_support.deprecation = :log
36 |
37 | # Raise an error on page load if there are pending migrations.
38 | config.active_record.migration_error = :page_load
39 |
40 | # Debug mode disables concatenation and preprocessing of assets.
41 | # This option may cause significant delays in view rendering with a large
42 | # number of complex assets.
43 | config.assets.debug = true
44 |
45 | # Suppress logger output for asset requests.
46 | config.assets.quiet = true
47 |
48 | # Raises error for missing translations
49 | # config.action_view.raise_on_missing_translations = true
50 |
51 | # Use an evented file watcher to asynchronously detect changes in source code,
52 | # routes, locales, etc. This feature depends on the listen gem.
53 | # config.file_watcher = ActiveSupport::EventedFileUpdateChecker
54 | end
55 |
--------------------------------------------------------------------------------
/db/schema.rb:
--------------------------------------------------------------------------------
1 | # This file is auto-generated from the current state of the database. Instead
2 | # of editing this file, please use the migrations feature of Active Record to
3 | # incrementally modify your database, and then regenerate this schema definition.
4 | #
5 | # Note that this schema.rb definition is the authoritative source for your
6 | # database schema. If you need to create the application database on another
7 | # system, you should be using db:schema:load, not running all the migrations
8 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations
9 | # you'll amass, the slower it'll run and the greater likelihood for issues).
10 | #
11 | # It's strongly recommended that you check this file into your version control system.
12 |
13 | ActiveRecord::Schema.define(version: 20161130194304) do
14 |
15 | # These are extensions that must be enabled in order to support this database
16 | enable_extension "plpgsql"
17 |
18 | create_table "outages", force: :cascade do |t|
19 | t.integer "service_id"
20 | t.integer "codes", array: true
21 | t.datetime "created_at", null: false
22 | t.datetime "updated_at", null: false
23 | t.index ["service_id"], name: "index_outages_on_service_id", using: :btree
24 | end
25 |
26 | create_table "services", force: :cascade do |t|
27 | t.string "name", null: false
28 | t.string "url", null: false
29 | t.boolean "active", default: true
30 | t.integer "allowed_codes", array: true
31 | t.datetime "created_at", null: false
32 | t.datetime "updated_at", null: false
33 | end
34 |
35 | create_table "statuses", force: :cascade do |t|
36 | t.integer "code", null: false
37 | t.integer "service_id"
38 | t.datetime "created_at", null: false
39 | t.datetime "updated_at", null: false
40 | t.index ["service_id"], name: "index_statuses_on_service_id", using: :btree
41 | end
42 |
43 | add_foreign_key "outages", "services"
44 | add_foreign_key "statuses", "services"
45 | end
46 |
--------------------------------------------------------------------------------
/config/puma.rb:
--------------------------------------------------------------------------------
1 | # Puma can serve each request in a thread from an internal thread pool.
2 | # The `threads` method setting takes two numbers a minimum and maximum.
3 | # Any libraries that use thread pools should be configured to match
4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum
5 | # and maximum, this matches the default thread size of Active Record.
6 | #
7 | threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
8 | threads threads_count, threads_count
9 |
10 | # Specifies the `port` that Puma will listen on to receive requests, default is 3000.
11 | #
12 | port ENV.fetch("PORT") { 3000 }
13 |
14 | # Specifies the `environment` that Puma will run in.
15 | #
16 | environment ENV.fetch("RAILS_ENV") { "development" }
17 |
18 | # Specifies the number of `workers` to boot in clustered mode.
19 | # Workers are forked webserver processes. If using threads and workers together
20 | # the concurrency of the application would be max `threads` * `workers`.
21 | # Workers do not work on JRuby or Windows (both of which do not support
22 | # processes).
23 | #
24 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 }
25 |
26 | # Use the `preload_app!` method when specifying a `workers` number.
27 | # This directive tells Puma to first boot the application and load code
28 | # before forking the application. This takes advantage of Copy On Write
29 | # process behavior so workers use less memory. If you use this option
30 | # you need to make sure to reconnect any threads in the `on_worker_boot`
31 | # block.
32 | #
33 | # preload_app!
34 |
35 | # The code in the `on_worker_boot` will be called if you are using
36 | # clustered mode by specifying a number of `workers`. After each worker
37 | # process is booted this block will be run, if you are using `preload_app!`
38 | # option you will want to use this block to reconnect to any threads
39 | # or connections that may have been created at application boot, Ruby
40 | # cannot share connections between processes.
41 | #
42 | # on_worker_boot do
43 | # ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
44 | # end
45 |
46 | # Allow puma to be restarted by `rails restart` command.
47 | plugin :tmp_restart
48 |
--------------------------------------------------------------------------------
/spec/unit/app/services/services_status_evaluator_spec.rb:
--------------------------------------------------------------------------------
1 | require 'rails_helper'
2 |
3 | RSpec.describe ServicesStatusEvaluator do
4 | describe '#call' do
5 | before do
6 | allow(OutageHandler).to receive(:call)
7 | end
8 |
9 | let(:services) do
10 | [service1, service2]
11 | end
12 |
13 | let(:service1) do
14 | Service.create(
15 | name: 'ExampleService',
16 | url: 'www.example-service.com',
17 | allowed_codes: [200]
18 | )
19 | end
20 |
21 | let(:service2) do
22 | Service.create(
23 | name: 'AnotherExampleService',
24 | url: 'www.another-example-service.com',
25 | allowed_codes: [200]
26 | )
27 | end
28 |
29 | before do
30 | 3.times do
31 | Status.create(
32 | code: 200,
33 | service: service1
34 | )
35 | end
36 | end
37 |
38 | context 'when the services are ok' do
39 | before do
40 | 3.times do
41 | Status.create(
42 | code: 200,
43 | service: service2
44 | )
45 | end
46 | end
47 |
48 | it 'does not register an outage' do
49 | described_class.call(services)
50 |
51 | expect(OutageHandler).to_not have_received(:call)
52 | end
53 | end
54 |
55 | context 'when some services are not ok' do
56 | before do
57 | 2.times do
58 | Status.create(
59 | code: 500,
60 | service: service2
61 | )
62 | end
63 |
64 | Status.create(
65 | code: 200,
66 | service: service2
67 | )
68 | end
69 |
70 | it 'registers an outage' do
71 | described_class.call(services)
72 |
73 | expect(OutageHandler).to have_received(:call).with(service2, [500, 500, 200])
74 | end
75 | end
76 |
77 | context 'when the number of statuses of a service is smaller than the number of entries expected to be ok' do
78 | before do
79 | Status.create(
80 | code: 200,
81 | service: service2
82 | )
83 | end
84 |
85 | it 'does not register an outage' do
86 | described_class.call([service2])
87 |
88 | expect(OutageHandler).to_not have_received(:call)
89 | end
90 | end
91 | end
92 | end
93 |
--------------------------------------------------------------------------------
/spec/unit/app/services/status_fetcher_spec.rb:
--------------------------------------------------------------------------------
1 | require 'rails_helper'
2 |
3 | RSpec.describe StatusFetcher do
4 | describe '#call' do
5 | let(:services) do
6 | {
7 | 'ExampleService' => 'www.example-service.com',
8 | 'SomeOtherService' => 'www.some-other-service.com',
9 | }
10 | end
11 |
12 | before do
13 | stub_request(:get, sickbay_url + '?ExampleService=www.example-service.com&SomeOtherService=www.some-other-service.com')
14 | .to_return(
15 | request_return
16 | )
17 | end
18 |
19 | let(:sickbay_url) do
20 | Configurations.sickbay_url
21 | end
22 |
23 | let(:request_return) do
24 | {
25 | body:
26 | {
27 | 'ExampleService' => '200',
28 | 'SomeOtherService' => '500'
29 | }.to_json
30 | }
31 | end
32 |
33 | context 'when the designated sickbay instance is set and available' do
34 | it 'returns the service status of a list of given services' do
35 | expect(described_class.call(services)).to eq(
36 | {
37 | 'ExampleService' => '200',
38 | 'SomeOtherService' => '500',
39 | }
40 | )
41 | end
42 | end
43 |
44 | context 'when there is no designated sickbay instance' do
45 | before do
46 | allow(Configurations).to receive(:sickbay_url).and_return nil
47 | end
48 |
49 | it 'returns an empty hash' do
50 | expect(described_class.call(services)).to eq({})
51 | end
52 | end
53 |
54 | context 'when the designated sickbay instance is not actually a sickbay instance' do
55 | before do
56 | allow(Configurations).to receive(:sickbay_url).and_return 'http://www.google.com'
57 | end
58 |
59 | let(:sickbay_url) do
60 | 'http://www.google.com'
61 | end
62 |
63 | let(:request_return) do
64 | {
65 | body: 'Some Html'
66 | }
67 | end
68 |
69 | it 'returns an empty hash' do
70 | expect(described_class.call(services)).to eq({})
71 | end
72 | end
73 |
74 | context 'when the designated sickbay instance is down' do
75 | let(:request_return) do
76 | {
77 | status: [500, "Internal Server Error"]
78 | }
79 | end
80 |
81 | it 'returns an empty hash' do
82 | expect(described_class.call(services)).to eq({})
83 | end
84 | end
85 | end
86 | end
87 |
--------------------------------------------------------------------------------
/spec/rails_helper.rb:
--------------------------------------------------------------------------------
1 | # This file is copied to spec/ when you run 'rails generate rspec:install'
2 | ENV['RAILS_ENV'] ||= 'test'
3 | require File.expand_path('../../config/environment', __FILE__)
4 | # Prevent database truncation if the environment is production
5 | abort("The Rails environment is running in production mode!") if Rails.env.production?
6 | require 'spec_helper'
7 | require 'rspec/rails'
8 | # Add additional requires below this line. Rails is not loaded until this point!
9 |
10 | # Requires supporting ruby files with custom matchers and macros, etc, in
11 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
12 | # run as spec files by default. This means that files in spec/support that end
13 | # in _spec.rb will both be required and run as specs, causing the specs to be
14 | # run twice. It is recommended that you do not name files matching this glob to
15 | # end with _spec.rb. You can configure this pattern with the --pattern
16 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
17 | #
18 | # The following line is provided for convenience purposes. It has the downside
19 | # of increasing the boot-up time by auto-requiring all files in the support
20 | # directory. Alternatively, in the individual `*_spec.rb` files, manually
21 | # require only the support files necessary.
22 | #
23 | # Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
24 |
25 | # Checks for pending migration and applies them before tests are run.
26 | # If you are not using ActiveRecord, you can remove this line.
27 | ActiveRecord::Migration.maintain_test_schema!
28 |
29 | RSpec.configure do |config|
30 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
31 | config.fixture_path = "#{::Rails.root}/spec/fixtures"
32 |
33 | # If you're not using ActiveRecord, or you'd prefer not to run each of your
34 | # examples within a transaction, remove the following line or assign false
35 | # instead of true.
36 | config.use_transactional_fixtures = true
37 |
38 | # RSpec Rails can automatically mix in different behaviours to your tests
39 | # based on their file location, for example enabling you to call `get` and
40 | # `post` in specs under `spec/controllers`.
41 | #
42 | # You can disable this behaviour by removing the line below, and instead
43 | # explicitly tag your specs with their type, e.g.:
44 | #
45 | # RSpec.describe UsersController, :type => :controller do
46 | # # ...
47 | # end
48 | #
49 | # The different available types are documented in the features, such as in
50 | # https://relishapp.com/rspec/rspec-rails/docs
51 | config.infer_spec_type_from_file_location!
52 |
53 | # Filter lines from Rails gems in backtraces.
54 | config.filter_rails_from_backtrace!
55 | # arbitrary gems may also be filtered via:
56 | # config.filter_gems_from_backtrace("gem name")
57 | end
58 |
--------------------------------------------------------------------------------
/config/environments/production.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # Code is not reloaded between requests.
5 | config.cache_classes = true
6 |
7 | # Eager load code on boot. This eager loads most of Rails and
8 | # your application in memory, allowing both threaded web servers
9 | # and those relying on copy on write to perform better.
10 | # Rake tasks automatically ignore this option for performance.
11 | config.eager_load = true
12 |
13 | # Full error reports are disabled and caching is turned on.
14 | config.consider_all_requests_local = false
15 | config.action_controller.perform_caching = true
16 |
17 | # Disable serving static files from the `/public` folder by default since
18 | # Apache or NGINX already handles this.
19 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
20 |
21 | # Compress JavaScripts and CSS.
22 | config.assets.js_compressor = :uglifier
23 | # config.assets.css_compressor = :sass
24 |
25 | # Do not fallback to assets pipeline if a precompiled asset is missed.
26 | config.assets.compile = false
27 |
28 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
29 |
30 | # Enable serving of images, stylesheets, and JavaScripts from an asset server.
31 | # config.action_controller.asset_host = 'http://assets.example.com'
32 |
33 | # Specifies the header that your server uses for sending files.
34 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
35 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
36 |
37 | # Mount Action Cable outside main process or domain
38 | # config.action_cable.mount_path = nil
39 | # config.action_cable.url = 'wss://example.com/cable'
40 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
41 |
42 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
43 | # config.force_ssl = true
44 |
45 | # Use the lowest log level to ensure availability of diagnostic information
46 | # when problems arise.
47 | config.log_level = :debug
48 |
49 | # Prepend all log lines with the following tags.
50 | config.log_tags = [ :request_id ]
51 |
52 | # Use a different cache store in production.
53 | # config.cache_store = :mem_cache_store
54 |
55 | # Use a real queuing backend for Active Job (and separate queues per environment)
56 | # config.active_job.queue_adapter = :resque
57 | # config.active_job.queue_name_prefix = "the_nurse_#{Rails.env}"
58 | config.action_mailer.perform_caching = false
59 |
60 | # Ignore bad email addresses and do not raise email delivery errors.
61 | # Set this to true and configure the email server for immediate delivery to raise delivery errors.
62 | # config.action_mailer.raise_delivery_errors = false
63 |
64 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
65 | # the I18n.default_locale when a translation cannot be found).
66 | config.i18n.fallbacks = true
67 |
68 | # Send deprecation notices to registered listeners.
69 | config.active_support.deprecation = :notify
70 |
71 | # Use default logging formatter so that PID and timestamp are not suppressed.
72 | config.log_formatter = ::Logger::Formatter.new
73 |
74 | # Use a different logger for distributed setups.
75 | # require 'syslog/logger'
76 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
77 |
78 | if ENV["RAILS_LOG_TO_STDOUT"].present?
79 | logger = ActiveSupport::Logger.new(STDOUT)
80 | logger.formatter = config.log_formatter
81 | config.logger = ActiveSupport::TaggedLogging.new(logger)
82 | end
83 |
84 | # Do not dump schema after migrations.
85 | config.active_record.dump_schema_after_migration = false
86 | end
87 |
--------------------------------------------------------------------------------
/spec/spec_helper.rb:
--------------------------------------------------------------------------------
1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all
2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3 | # The generated `.rspec` file contains `--require spec_helper` which will cause
4 | # this file to always be loaded, without a need to explicitly require it in any
5 | # files.
6 | #
7 | # Given that it is always loaded, you are encouraged to keep this file as
8 | # light-weight as possible. Requiring heavyweight dependencies from this file
9 | # will add to the boot time of your test suite on EVERY test run, even for an
10 | # individual file that may not need all of that loaded. Instead, consider making
11 | # a separate helper file that requires the additional dependencies and performs
12 | # the additional setup, and require it from the spec files that actually need
13 | # it.
14 | #
15 | # The `.rspec` file also contains a few flags that are not defaults but that
16 | # users commonly want.
17 | #
18 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
19 |
20 | require 'webmock/rspec'
21 | require 'coveralls'
22 | Coveralls.wear!
23 |
24 | RSpec.configure do |config|
25 | # rspec-expectations config goes here. You can use an alternate
26 | # assertion/expectation library such as wrong or the stdlib/minitest
27 | # assertions if you prefer.
28 | config.expect_with :rspec do |expectations|
29 | # This option will default to `true` in RSpec 4. It makes the `description`
30 | # and `failure_message` of custom matchers include text for helper methods
31 | # defined using `chain`, e.g.:
32 | # be_bigger_than(2).and_smaller_than(4).description
33 | # # => "be bigger than 2 and smaller than 4"
34 | # ...rather than:
35 | # # => "be bigger than 2"
36 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true
37 | end
38 |
39 | # rspec-mocks config goes here. You can use an alternate test double
40 | # library (such as bogus or mocha) by changing the `mock_with` option here.
41 | config.mock_with :rspec do |mocks|
42 | # Prevents you from mocking or stubbing a method that does not exist on
43 | # a real object. This is generally recommended, and will default to
44 | # `true` in RSpec 4.
45 | mocks.verify_partial_doubles = true
46 | end
47 |
48 | # The settings below are suggested to provide a good initial experience
49 | # with RSpec, but feel free to customize to your heart's content.
50 | =begin
51 | # These two settings work together to allow you to limit a spec run
52 | # to individual examples or groups you care about by tagging them with
53 | # `:focus` metadata. When nothing is tagged with `:focus`, all examples
54 | # get run.
55 | config.filter_run :focus
56 | config.run_all_when_everything_filtered = true
57 |
58 | # Allows RSpec to persist some state between runs in order to support
59 | # the `--only-failures` and `--next-failure` CLI options. We recommend
60 | # you configure your source control system to ignore this file.
61 | config.example_status_persistence_file_path = "spec/examples.txt"
62 |
63 | # Limits the available syntax to the non-monkey patched syntax that is
64 | # recommended. For more details, see:
65 | # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
66 | # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
67 | # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
68 | config.disable_monkey_patching!
69 |
70 | # Many RSpec users commonly either run the entire suite or an individual
71 | # file, and it's useful to allow more verbose output when running an
72 | # individual spec file.
73 | if config.files_to_run.one?
74 | # Use the documentation formatter for detailed output,
75 | # unless a formatter has already been configured
76 | # (e.g. via a command-line flag).
77 | config.default_formatter = 'doc'
78 | end
79 |
80 | # Print the 10 slowest examples and example groups at the
81 | # end of the spec run, to help surface which specs are running
82 | # particularly slow.
83 | config.profile_examples = 10
84 |
85 | # Run specs in random order to surface order dependencies. If you find an
86 | # order dependency and want to debug it, you can fix the order by providing
87 | # the seed, which is printed after each run.
88 | # --seed 1234
89 | config.order = :random
90 |
91 | # Seed global randomization in this process using the `--seed` CLI option.
92 | # Setting this allows you to use `--seed` to deterministically reproduce
93 | # test failures related to randomization by passing the same `--seed` value
94 | # as the one that triggered the failure.
95 | Kernel.srand config.seed
96 | =end
97 | end
98 |
--------------------------------------------------------------------------------
/Gemfile.lock:
--------------------------------------------------------------------------------
1 | GEM
2 | remote: https://rubygems.org/
3 | specs:
4 | actioncable (5.0.0.1)
5 | actionpack (= 5.0.0.1)
6 | nio4r (~> 1.2)
7 | websocket-driver (~> 0.6.1)
8 | actionmailer (5.0.0.1)
9 | actionpack (= 5.0.0.1)
10 | actionview (= 5.0.0.1)
11 | activejob (= 5.0.0.1)
12 | mail (~> 2.5, >= 2.5.4)
13 | rails-dom-testing (~> 2.0)
14 | actionpack (5.0.0.1)
15 | actionview (= 5.0.0.1)
16 | activesupport (= 5.0.0.1)
17 | rack (~> 2.0)
18 | rack-test (~> 0.6.3)
19 | rails-dom-testing (~> 2.0)
20 | rails-html-sanitizer (~> 1.0, >= 1.0.2)
21 | actionview (5.0.0.1)
22 | activesupport (= 5.0.0.1)
23 | builder (~> 3.1)
24 | erubis (~> 2.7.0)
25 | rails-dom-testing (~> 2.0)
26 | rails-html-sanitizer (~> 1.0, >= 1.0.2)
27 | activejob (5.0.0.1)
28 | activesupport (= 5.0.0.1)
29 | globalid (>= 0.3.6)
30 | activemodel (5.0.0.1)
31 | activesupport (= 5.0.0.1)
32 | activerecord (5.0.0.1)
33 | activemodel (= 5.0.0.1)
34 | activesupport (= 5.0.0.1)
35 | arel (~> 7.0)
36 | activesupport (5.0.0.1)
37 | concurrent-ruby (~> 1.0, >= 1.0.2)
38 | i18n (~> 0.7)
39 | minitest (~> 5.1)
40 | tzinfo (~> 1.1)
41 | addressable (2.5.0)
42 | public_suffix (~> 2.0, >= 2.0.2)
43 | arel (7.1.4)
44 | binding_of_caller (0.7.2)
45 | debug_inspector (>= 0.0.1)
46 | builder (3.2.2)
47 | byebug (9.0.6)
48 | clockwork (2.0.0)
49 | activesupport
50 | tzinfo
51 | coderay (1.1.1)
52 | coffee-rails (4.1.1)
53 | coffee-script (>= 2.2.0)
54 | railties (>= 4.0.0, < 5.1.x)
55 | coffee-script (2.4.1)
56 | coffee-script-source
57 | execjs
58 | coffee-script-source (1.11.1)
59 | concurrent-ruby (1.0.2)
60 | connection_pool (2.2.1)
61 | coveralls (0.8.16)
62 | json (>= 1.8, < 3)
63 | simplecov (~> 0.12.0)
64 | term-ansicolor (~> 1.3.0)
65 | thor (~> 0.19.1)
66 | tins (>= 1.6.0, < 2)
67 | crack (0.4.3)
68 | safe_yaml (~> 1.0.0)
69 | debug_inspector (0.0.2)
70 | diff-lcs (1.2.5)
71 | docile (1.1.5)
72 | erubis (2.7.0)
73 | execjs (2.7.0)
74 | foreman (0.78.0)
75 | thor (~> 0.19.1)
76 | globalid (0.3.7)
77 | activesupport (>= 4.1.0)
78 | hashdiff (0.3.1)
79 | i18n (0.7.0)
80 | jbuilder (2.6.1)
81 | activesupport (>= 3.0.0, < 5.1)
82 | multi_json (~> 1.2)
83 | jquery-rails (4.2.1)
84 | rails-dom-testing (>= 1, < 3)
85 | railties (>= 4.2.0)
86 | thor (>= 0.14, < 2.0)
87 | json (1.8.3)
88 | loofah (2.0.3)
89 | nokogiri (>= 1.5.9)
90 | mail (2.6.4)
91 | mime-types (>= 1.16, < 4)
92 | method_source (0.8.2)
93 | mime-types (3.1)
94 | mime-types-data (~> 3.2015)
95 | mime-types-data (3.2016.0521)
96 | mini_portile2 (2.1.0)
97 | minitest (5.9.1)
98 | mixlib-config (2.2.4)
99 | multi_json (1.12.1)
100 | nio4r (1.2.1)
101 | nokogiri (1.6.8.1)
102 | mini_portile2 (~> 2.1.0)
103 | pg (0.19.0)
104 | pry (0.10.4)
105 | coderay (~> 1.1.0)
106 | method_source (~> 0.8.1)
107 | slop (~> 3.4)
108 | public_suffix (2.0.4)
109 | rack (2.0.1)
110 | rack-protection (1.5.3)
111 | rack
112 | rack-test (0.6.3)
113 | rack (>= 1.0)
114 | rails (5.0.0.1)
115 | actioncable (= 5.0.0.1)
116 | actionmailer (= 5.0.0.1)
117 | actionpack (= 5.0.0.1)
118 | actionview (= 5.0.0.1)
119 | activejob (= 5.0.0.1)
120 | activemodel (= 5.0.0.1)
121 | activerecord (= 5.0.0.1)
122 | activesupport (= 5.0.0.1)
123 | bundler (>= 1.3.0, < 2.0)
124 | railties (= 5.0.0.1)
125 | sprockets-rails (>= 2.0.0)
126 | rails-dom-testing (2.0.1)
127 | activesupport (>= 4.2.0, < 6.0)
128 | nokogiri (~> 1.6.0)
129 | rails-html-sanitizer (1.0.3)
130 | loofah (~> 2.0)
131 | railties (5.0.0.1)
132 | actionpack (= 5.0.0.1)
133 | activesupport (= 5.0.0.1)
134 | method_source
135 | rake (>= 0.8.7)
136 | thor (>= 0.18.1, < 2.0)
137 | rake (11.3.0)
138 | rdoc (4.3.0)
139 | redis (3.3.2)
140 | rspec-core (3.5.4)
141 | rspec-support (~> 3.5.0)
142 | rspec-expectations (3.5.0)
143 | diff-lcs (>= 1.2.0, < 2.0)
144 | rspec-support (~> 3.5.0)
145 | rspec-mocks (3.5.0)
146 | diff-lcs (>= 1.2.0, < 2.0)
147 | rspec-support (~> 3.5.0)
148 | rspec-rails (3.5.2)
149 | actionpack (>= 3.0)
150 | activesupport (>= 3.0)
151 | railties (>= 3.0)
152 | rspec-core (~> 3.5.0)
153 | rspec-expectations (~> 3.5.0)
154 | rspec-mocks (~> 3.5.0)
155 | rspec-support (~> 3.5.0)
156 | rspec-support (3.5.0)
157 | safe_yaml (1.0.4)
158 | sass (3.4.22)
159 | sass-rails (5.0.6)
160 | railties (>= 4.0.0, < 6)
161 | sass (~> 3.1)
162 | sprockets (>= 2.8, < 4.0)
163 | sprockets-rails (>= 2.0, < 4.0)
164 | tilt (>= 1.1, < 3)
165 | sdoc (0.4.2)
166 | json (~> 1.7, >= 1.7.7)
167 | rdoc (~> 4.0)
168 | sidekiq (4.2.7)
169 | concurrent-ruby (~> 1.0)
170 | connection_pool (~> 2.2, >= 2.2.0)
171 | rack-protection (>= 1.5.0)
172 | redis (~> 3.2, >= 3.2.1)
173 | simplecov (0.12.0)
174 | docile (~> 1.1.0)
175 | json (>= 1.8, < 3)
176 | simplecov-html (~> 0.10.0)
177 | simplecov-html (0.10.0)
178 | slop (3.6.0)
179 | spring (2.0.0)
180 | activesupport (>= 4.2)
181 | sprockets (3.7.0)
182 | concurrent-ruby (~> 1.0)
183 | rack (> 1, < 3)
184 | sprockets-rails (3.2.0)
185 | actionpack (>= 4.0)
186 | activesupport (>= 4.0)
187 | sprockets (>= 3.0.0)
188 | term-ansicolor (1.3.2)
189 | tins (~> 1.0)
190 | thor (0.19.4)
191 | thread_safe (0.3.5)
192 | tilt (2.0.5)
193 | tins (1.13.0)
194 | turbolinks (5.0.1)
195 | turbolinks-source (~> 5)
196 | turbolinks-source (5.0.0)
197 | tzinfo (1.2.2)
198 | thread_safe (~> 0.1)
199 | uglifier (3.0.3)
200 | execjs (>= 0.3.0, < 3)
201 | web-console (2.3.0)
202 | activemodel (>= 4.0)
203 | binding_of_caller (>= 0.7.2)
204 | railties (>= 4.0)
205 | sprockets-rails (>= 2.0, < 4.0)
206 | webmock (2.1.0)
207 | addressable (>= 2.3.6)
208 | crack (>= 0.3.2)
209 | hashdiff
210 | websocket-driver (0.6.4)
211 | websocket-extensions (>= 0.1.0)
212 | websocket-extensions (0.1.2)
213 |
214 | PLATFORMS
215 | ruby
216 |
217 | DEPENDENCIES
218 | byebug
219 | clockwork
220 | coffee-rails (~> 4.1.0)
221 | coveralls
222 | foreman
223 | jbuilder (~> 2.0)
224 | jquery-rails
225 | mixlib-config
226 | pg
227 | pry
228 | rails (= 5.0.0.1)
229 | rspec-rails
230 | sass-rails (~> 5.0)
231 | sdoc (~> 0.4.0)
232 | sidekiq
233 | spring
234 | turbolinks
235 | uglifier (>= 1.3.0)
236 | web-console (~> 2.0)
237 | webmock
238 |
239 | RUBY VERSION
240 | ruby 2.3.1p112
241 |
242 | BUNDLED WITH
243 | 1.13.1
244 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # The Nurse
2 |
3 | Alert whoever you want when your apps are in a bad shape. It uses [Sickbay](https://github.com/IgorMarques/sickbay) for app monitoring.
4 |
5 | [](https://codeclimate.com/github/IgorMarques/The-Nurse)
6 | [](https://travis-ci.org/IgorMarques/The-Nurse)
7 | [](https://coveralls.io/github/IgorMarques/The-Nurse?branch=master)
8 |
9 | ## How does it work?
10 |
11 | 1. Register the many apps you want to be monitored (with Name, URL to be checked and the HTTP statuses that indicate your app is fine).
12 | - Every X minutes (completely up to you) The Nurse checks your apps
13 | - If N of last M requests (again, completely up to you) returns a status code different from the one you expect, The Nurse will warn the Doctor about it.
14 | - This warn is a POST request containing the name of the service, its URL and the last M HTTP codes received. This POST will be sent to whoever URL you want.
15 |
16 | Notice: The app also registers an entry you your DB for each health check. This way you can easily go back in time and check how was your app at any given time.
17 |
18 | ## Why?
19 |
20 | The Nurse can be used to trigger a Kill Switch mechanism in your app: When your app receives the The Nurse's request into some endpoint, it stops some critical and automatic procedure to keep going.
21 |
22 | This can be extremely useful when dealing with a microservice architecture or when you app depends on external services.
23 |
24 | The Nurse can be also be used as a way to monitoring your apps and warn the right people when something is bad.
25 |
26 | ## Setting up
27 |
28 | This setup assumes you have a proper Ruby workspace setted up with:
29 |
30 | - Ruby 2.3.1
31 | - Rails 5.0.0.1
32 | - PostgreSQL
33 | - Redis
34 |
35 | Just run:
36 |
37 | ```
38 | $ git clone http://github.com/IgorMarques/The-Nurse
39 | $ cd The-Nurse
40 | $ bundle install
41 | $ rake db:create db:migrate
42 | ```
43 |
44 | ## Configuring the app
45 |
46 | The app runs just fine for demo right out of the box (you just need to register some apps). But before putting your instance of The Nurse into production, remember to set it properly for your own needs.
47 |
48 | ### Registering apps
49 |
50 | Using rails console (don't worry, we have plans to add a proper web interface in the near future), create the apps/services you want to monitor. To run the console, run:
51 |
52 | ```shell
53 | $ bundle exec rails console
54 | ```
55 |
56 | And to create the apps, run this inside the console:
57 |
58 | ```
59 | Service.create(name: 'ExampleService', url: 'www.example-service.com/health', allowed_codes: [200])
60 | ```
61 |
62 | **NOTICE: The `allowed_codes` field is an array**
63 |
64 | Now your app will be properly monitored once you run the app.
65 |
66 | ### Your Sickbay instance
67 |
68 | By default, The Nurse uses my instance of [Sickbay](https://github.com/IgorMarques/sickbay) on Heroku (on a free tier plan) to run the checks. If you plan on using this app for real, please set your own Sickbay instance. The deploy on Heroku is pretty straightforward (you literally just need to push the code there).
69 |
70 | After the setup, remember to set the `ENV` variable `SICKBAY_URL` to the proper URL.
71 |
72 | ### Monitoring frequency
73 |
74 | By default, The Nurse will check the Sickbay instance every minute. You can change this by setting up the `ENV` variable `HEALTH_CHECK_RATE` to the time in minutes you desire.
75 |
76 | ### Outage criteria
77 |
78 | By default, if 2 in the last 3 checks to the endpoint of the service return a value that is not present in the `allowed_codes` list, The Nurse will notify your Doctor endpoint. You can custom set both values by setting up the ENV variables `ENTRIES_FETCHED` and `ENTRIES_OK`.
79 |
80 | ### Unregistering apps
81 |
82 | You can disable the monitoring for a specific app setting its `active` attribute to `false`. Only apps with the value `true` are checked.
83 |
84 | ### Warning whoever you want
85 |
86 | Just set the variable `DOCTOR_URL` to whoever app should be notified when an outage happens. This URL should be able to receive a proper `POST` HTTP request with the params like:
87 |
88 | ```json
89 | {
90 | "service_name": "TheFailingService",
91 | "service_url": "www.this_service_failed.com/health",
92 | "codes": ["200", "500", "500"]
93 | }
94 | ```
95 |
96 | ## Running
97 |
98 | Once everything is setted up, this will run your healthchecks :)
99 |
100 | ```shell
101 | $ foreman start
102 | ```
103 |
104 | This will start all the components of the app:
105 | - A Rails server
106 | - [Clockwork](https://github.com/Rykian/clockwork) for recurring jobs
107 | - [Sidekiq](https://github.com/mperham/sidekiq) for background jobs
108 |
109 | You can also start each component alone. Check the Procfile for more info.
110 |
111 | ## Other use cases
112 |
113 | As mentioned earlier, you can use The Nurse to check the health at your app at any given time The Nurse was paying attention to it.
114 |
115 | All health checks are stored into [Statuses](https://github.com/IgorMarques/The-Nurse/blob/master/app/models/status.rb) entries. Feel free to run the SQL or active record queries you like to fetch whatever data you want.
116 |
117 | Example:
118 |
119 | ```ruby
120 | 2.3.1 :001 > Service.first.statuses
121 |
122 | Service Load (28.0ms) SELECT "services".* FROM "services" ORDER BY "services"."id" ASC LIMIT $1 [["LIMIT", 1]]
123 | Status Load (55.4ms) SELECT "statuses".* FROM "statuses" WHERE "statuses"."service_id" = $1 [["service_id", 1]]
124 | => #, #, #, #, #]>
125 | ```
126 |
127 | You can do the same for outages:
128 |
129 | ```ruby
130 | 2.3.1 :013 > Service.first.statuses
131 | Service Load (0.3ms) SELECT "services".* FROM "services" ORDER BY "services"."id" ASC LIMIT $1 [["LIMIT", 1]]
132 | Status Load (40.5ms) SELECT "statuses".* FROM "statuses" WHERE "statuses"."service_id" = $1 [["service_id", 1]]
133 | => #, #, #, #, #]>
134 | ```
135 |
136 | ## Testing
137 |
138 | This app uses Rspec for testing. To run the test suit:
139 |
140 | ```shell
141 | $ rspec
142 | ```
143 |
144 | ## Deploying
145 |
146 | This project is compatible with heroku. Following [their tutorial](https://devcenter.heroku.com/articles/getting-started-with-ruby#introduction) should be enough. You'll need at least one paid dyno, since the free plans only support up to two (and we have three components: the server, Sidekiq and Clockwork). Also remember to properly config a Redis to Go addon.
147 |
148 | ## Plans for the future and contributing
149 |
150 | There's still a lot to be done. Here are some features planed:
151 |
152 | - [ ] Web interface with the live status of each registered service
153 | - [ ] Web interface for managing (creating, editing, deleting, etc) services
154 | - [ ] Support for reading data from multiple Sickbay instances at once
155 |
156 | Feel free to contribute with a PR :)
157 |
--------------------------------------------------------------------------------