Last active
April 19, 2018 04:47
-
-
Save diskshima/becc3364a73459627e81357d59eb54f6 to your computer and use it in GitHub Desktop.
Mackerel CLI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source 'https://rubygems.org' | |
gem 'mackerel-client' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env ruby | |
# vim: set ft=ruby: | |
# frozen_string_literal: true | |
require 'mackerel/client' | |
require 'optparse' | |
SECRET_FILE = '.mackerel' | |
def api_key | |
File.read(File.join(Dir.home, SECRET_FILE)).chomp | |
end | |
def client | |
Mackerel::Client.new(mackerel_api_key: api_key) | |
end | |
def host_ids(hosts, only_non_working = true) | |
tmp_hosts = if only_non_working | |
hosts.reject { |h| h.status == 'working' } | |
else | |
hosts | |
end | |
tmp_hosts.map(&:id) | |
end | |
def retire_hosts(options) | |
hosts = client.get_hosts | |
all = options[:a] | |
hids(hosts, !all).each do |hid| | |
mackerel.retire_host(hid) | |
puts "Retired #{hid}." | |
end | |
end | |
def check_reason(reason) | |
return if reason && reason.chomp != '' | |
puts 'Please specify reason.' | |
exit(-1) | |
end | |
def close_alerts(options) | |
reason = options[:reason] | |
check_reason(reason) | |
alerts = client.get_alerts | |
alert_ids = alerts.map(&:id) | |
alert_ids.each do |aid| | |
client.close_alerts(aid, reason) | |
puts "Closed alert ##{aid}." | |
end | |
end | |
options = {} | |
subcommands = { | |
'hosts' => { | |
opts: OptionParser.new do |opts| | |
opts.banner = 'List hosts' | |
end | |
}, | |
'retire' => { | |
opts: OptionParser.new do |opts| | |
opts.banner = 'Retire hosts' | |
opts.on('-a', '--all', 'All hosts (otherwise only non-working)') do |a| | |
options[:all] = a | |
end | |
end, | |
call: :retire_hosts | |
}, | |
'close_alerts' => { | |
opts: OptionParser.new do |opts| | |
opts.banner = 'Close alerts' | |
opts.on('-r REASON', '--reason', 'Close all alerts') do |reason| | |
options[:reason] = reason | |
end | |
end, | |
call: :close_alerts | |
} | |
} | |
subcommand = subcommands[ARGV.shift] | |
if subcommand | |
subcommand[:opts].order! | |
method = self.method(subcommand[:call]) | |
method.call(options) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Preparation
.mackerel
in your home directory and paste the API key from ⬆️bundle install
Retiring hosts
bundle exec ruby mck.rb retire
Closing Alerts
bundle exec ruby mck.rb close_alerts