Skip to content

Instantly share code, notes, and snippets.

@patorash

patorash/mackerel.rake

Last active Feb 17, 2021
Embed
What would you like to do?
Post custom metrics(table count, column count, and comment count) to mackerei.io
require 'mackerel/client'
namespace :mackerel do
namespace :service_metric do
namespace :database do
desc 'Post table count, column count, and comment count to mackerel.'
task post: :environment do
client = Mackerel::Client.new(mackerel_api_key: ENV['MACKEREL_API_KEY'])
service_name = ENV['MACKEREL_SERVICE_NAME']
time = Time.zone.now.to_i
system_view_names = %w(
pg_stat_statements
geography_columns
geometry_columns
raster_columns
raster_overviews
)
tables = ApplicationRecord.connection.tables
views = ApplicationRecord.connection.views - system_view_names
columns = (tables + views).map { |table| ApplicationRecord.connection.columns(table) }.flatten
comments = columns.reject { |column| column.comment.nil? }
metrics = [
{
name: 'database.tables',
time: time,
value: tables.count + views.count,
},
{
name: 'database.columns',
time: time,
value: columns.count,
},
{
name: 'database.comments',
time: time,
value: comments.count,
},
]
# 通信ができない場合やMackerel API Keyがない場合に例外が起きても無視する
begin
client.post_service_metrics(service_name, metrics)
rescue
nil
end
end
end
end
end
# マイグレーションタスクを実行されたら、Mackerelに送る。実装はannotateを参考にした。
# see https://github.com/ctran/annotate_models/blob/516ed58e5662e32fca5114c6dbe20be93a4e5507/lib/tasks/annotate_models_migrate.rake
migration_tasks = %w(db:migrate db:migrate:up db:migrate:down db:migrate:reset db:migrate:redo db:rollback)
if defined?(Rails::Application) && Rails.version.split('.').first.to_i >= 6
require 'active_record'
databases = ActiveRecord::Tasks::DatabaseTasks.setup_initial_database_yaml
ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |spec_name|
migration_tasks.concat(%w(db:migrate db:migrate:up db:migrate:down).map { |task| "#{task}:#{spec_name}" })
end
end
migration_tasks.each do |task|
next unless Rake::Task.task_defined?(task)
Rake::Task[task].enhance do
Rake::Task[Rake.application.top_level_tasks.last].enhance do
Rake::Task['mackerel:service_metric:database:post'].invoke if Rails.env.development?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment