Repository: MightySignal/slackiq Branch: master Commit: 5de9aaecc98e Files: 12 Total size: 12.9 KB Directory structure: gitextract_pzzyaxu7/ ├── .gitignore ├── CODE_OF_CONDUCT.md ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── bin/ │ ├── console │ └── setup ├── lib/ │ ├── slackiq/ │ │ ├── time_helper.rb │ │ └── version.rb │ └── slackiq.rb └── slackiq.gemspec ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /.bundle/ /.yardoc /Gemfile.lock /_yardoc/ /coverage/ /doc/ /pkg/ /spec/reports/ /tmp/ ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Code of Conduct As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion. Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/) ================================================ FILE: Gemfile ================================================ source 'https://rubygems.org' # Specify your gem's dependencies in slackiq.gemspec gemspec ================================================ FILE: LICENSE.txt ================================================ The MIT License (MIT) Copyright (c) 2015 Jason Lew Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Slackiq [![Gem Version](https://badge.fury.io/rb/slackiq.svg)](http://badge.fury.io/rb/slackiq) Slackiq (pronounced *slack-kick*) integrates [Slack](https://slack.com/) and [Sidekiq](http://sidekiq.org) so that you can have vital information about your Sidekiq jobs sent directly to your team's Slack. ![demo](http://i.imgur.com/4NLq2rP.gif) ## Installation Add this line to your Gemfile: ```ruby gem 'slackiq' ``` Then run: ``` bundle install ``` ## Configuration First, set up any number of Slack Incoming Webhooks [from your Slack](https://slack.com/services/new/incoming-webhook). Then, you only need to call the `configure` method when your application launches to configure all of the webhooks to which you want to post. If you're using Rails, create an initializer at `config/initializers/slackiq.rb`. Here's an example: ```ruby Slackiq.configure( web_scrapes: 'https://hooks.slack.com/services/HA298HF2/ALSKF2451/lknsaHHA2323KKDKND', data_processing: 'https://hooks.slack.com/services/HA298HF2/ALSKF2451/H24dLKAHD22423') ``` `:web_scrapes` and `data_processing` are examples of keys. Use whatever keys you want. ## Usage You can call `notify` to send a nicely-formatted notification to your Slack. You can call `notify` * Inside the Sidekiq Pro `on_success` or `on_complete` callback (not available on regular Sidekiq--only Pro) * From inside a Sidekiq worker while it's running, in which case you should pass in the `bid` to the `perform` method of the worker The `notify` method has a single Hash parameter. Here are the keys and values in the Hash: * `:webhook_name` The name of the webhook (Symbol) that you configured (eg. `:web_scrapes` or `:data_processing`) * `:title` The title of the notification (String) * `:status` An instance of `Sidekiq::Batch::Status` * Any other keys and values (both Strings) can be added too, and they'll be added to the Slack notification! If you haven't used batches with Sidekiq Pro before, [read this first](https://github.com/mperham/sidekiq/wiki/Batches). Here's an example showing how you would use Slackiq to send a notification to your Slack when your Sidekiq batch completes: ```ruby class WebScraper class << self # Scrape the first 100 URLs in the database def scrape_100 batch = Sidekiq::Batch.new batch.description = 'Scrape the first 100 URLs!' batch.on(:complete, self) batch.jobs do urls = Url.limit(100) # Url is a Rails model in this case urls.each do |url| ScraperWorker.perform_async(url.id) end end end def on_complete(status, options) Slackiq.notify(webhook_name: :web_scrapes, status: status, title: 'Scrape Completed!', 'Total URLs in DB' => URL.count.to_s, 'Servers' => "#{Server.active_count} active, #{Server.inactive_count} inactive") end end ``` Note that in this case, `'Total URLs in DB'` and `'Servers'` are custom fields that will also appear in Slack! ### Want to send a message to Slack that isn't Sidekiq-related? No prob. Just: ```ruby Slackiq.message('Server 5 is overloaded!', webhook_name: :data_processing) ``` ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/MightySignal/slackiq. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct. ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). ## Blog Post about Slackiq https://blog.mightysignal.com/slackiq-a-ruby-gem-that-connects-slack-and-sidekiq-a2308c1974b7 ## More Open Source Projects * [Slacktivity](https://github.com/MightySignal/slacktivity) ================================================ FILE: Rakefile ================================================ require "bundler/gem_tasks" task :console do exec "irb -r slackiq -I ./lib" end task c: :console ================================================ FILE: bin/console ================================================ #!/usr/bin/env ruby require "bundler/setup" require "slackiq" # You can add fixtures and/or initialization code here to make experimenting # with your gem easier. You can also use a different console, if you like. # (If you use this, don't forget to add pry to your Gemfile!) # require "pry" # Pry.start require "irb" IRB.start ================================================ FILE: bin/setup ================================================ #!/bin/bash set -euo pipefail IFS=$'\n\t' bundle install # Do any other automated setup that you need to do here ================================================ FILE: lib/slackiq/time_helper.rb ================================================ require 'date' module Slackiq module TimeHelper class << self def elapsed_time_humanized(t0, t1) humanize(elapsed_seconds(t0, t1)) end def elapsed_seconds(t0, t1) dt0 = t0.to_datetime dt1 = t1.to_datetime ((dt1-dt0)*24*60*60).to_i end # http://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails def humanize(secs) [[60, :s], [60, :m], [24, :h], [1000, :d]].map{ |count, name| if secs > 0 secs, n = secs.divmod(count) "#{n.to_i}#{name}" end }.compact.reverse.join(' ') end def format(time) time.strftime('%D @ %r').gsub('PM', 'pm').gsub('AM', 'am') end end end end ================================================ FILE: lib/slackiq/version.rb ================================================ module Slackiq VERSION = "1.1.4" end ================================================ FILE: lib/slackiq.rb ================================================ require 'slackiq/version' require 'net/http' require 'json' require 'httparty' require 'slackiq/time_helper' require 'active_support' #for Hash#except module Slackiq class << self # Configure all of the webhook URLs you're going to use # @author Jason Lew def configure(webhook_urls={}) raise 'Argument must be a Hash' unless webhook_urls.class == Hash @@webhook_urls = webhook_urls end # Send a notification to Slack with Sidekiq info about the batch # @author Jason Lew def notify(options={}) url = @@webhook_urls[options[:webhook_name]] title = options[:title] #description = options[:description] status = options[:status] if (bid = options[:bid]) && status.nil? raise "Sidekiq::Batch::Status is not defined. Are you sure Sidekiq Pro is set up correctly?" unless defined?(Sidekiq::Batch::Status) status = Sidekiq::Batch::Status.new(bid) end extra_fields = options.except(:webhook_name, :title, :description, :status) fields = [] if status created_at = status.created_at if created_at time_now = Time.now duration = Slackiq::TimeHelper.elapsed_time_humanized(created_at, time_now) time_now_title = (status.complete? ? 'Completed' : 'Now') end total_jobs = status.total failures = status.failures jobs_run = total_jobs - status.pending completion_percentage = (jobs_run/total_jobs.to_f)*100 failure_percentage = (failures/total_jobs.to_f)*100 if total_jobs && failures # round to two decimal places decimal_places = 2 completion_percentage = completion_percentage.round(decimal_places) failure_percentage = failure_percentage.round(decimal_places) description = status.description fields += [ { 'title' => 'Created', 'value' => Slackiq::TimeHelper.format(created_at), 'short' => true }, { 'title' => time_now_title, 'value' => Slackiq::TimeHelper.format(time_now), 'short' => true }, { 'title' => "Duration", 'value' => duration, 'short' => true }, { 'title' => "Total Jobs", 'value' => total_jobs, 'short' => true }, { 'title' => "Jobs Run", 'value' => jobs_run, 'short' => true }, { 'title' => "Completion %", 'value' => "#{completion_percentage}%", 'short' => true }, { 'title' => "Failures", 'value' => status.failures, 'short' => true }, { 'title' => "Failure %", 'value' => "#{failure_percentage}%", 'short' => true }, ] end # add extra fields fields += extra_fields.map do |title, value| { 'title' => title, 'value' => value, 'short' => false } end attachments = [ { 'fallback' => title, 'color' => '#00ff66', 'title' => title, 'text' => description, 'fields' => fields, } ] body = {attachments: attachments}.to_json HTTParty.post(url, body: body) end # Send a notification without Sidekiq batch info # @author Jason Lew def message(text, options) url = @@webhook_urls[options[:webhook_name]] body = { 'text' => text }.to_json HTTParty.post(url, body: body) end end end ================================================ FILE: slackiq.gemspec ================================================ # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'slackiq/version' Gem::Specification.new do |spec| spec.name = "slackiq" spec.version = Slackiq::VERSION spec.authors = ['Jason Lew'] spec.email = ['jason@mightysignal.com'] spec.summary = 'MightySignal: Slack and Sidekiq Pro integration' spec.description = "Slackiq (by MightySignal) integrates Slack and Sidekiq so that you can have vital information about your Sidekiq jobs sent directly to your team's Slack." spec.homepage = 'https://github.com/MightySignal/slackiq' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_dependency 'httparty' spec.add_development_dependency "bundler", "~> 1.10" spec.add_development_dependency "rake", "~> 10.0" end