Add prometheus metrics at /api/v1/metrics

This commit is contained in:
wint3rmute 2023-01-18 00:33:55 +01:00 committed by Wint3rmute
parent 26ea676b8d
commit deed262083
4 changed files with 24 additions and 0 deletions

View file

@ -233,3 +233,11 @@ def proxy_file(response, env)
IO.copy response.body_io, env.response
end
end
def to_prometheus_metrics(metrics_struct : Hash(String, Number)) : String
return String.build do |str|
metrics_struct.each.each do |key, value|
str << key << " " << value << "\n"
end
end
end

View file

@ -20,6 +20,11 @@ class Invidious::Jobs::StatisticsRefreshJob < Invidious::Jobs::BaseJob
},
}
STATISTICS_PROMETHEUS = {
"invidious_updated_at" => Time.utc.to_unix,
"invidious_last_channel_refreshed_at" => 0_i64,
}
private getter db : DB::Database
def initialize(@db, @software_config : Hash(String, String))
@ -52,6 +57,9 @@ class Invidious::Jobs::StatisticsRefreshJob < Invidious::Jobs::BaseJob
users["activeHalfyear"] = Invidious::Database::Statistics.count_users_active_1m
users["activeMonth"] = Invidious::Database::Statistics.count_users_active_6m
STATISTICS_PROMETHEUS["invidious_updated_at"] = Time.utc.to_unix
STATISTICS_PROMETHEUS["invidious_last_channel_refreshed_at"] = Invidious::Database::Statistics.channel_last_update.try &.to_unix || 0_i64
STATISTICS["metadata"] = {
"updatedAt" => Time.utc.to_unix,
"lastChannelRefreshedAt" => Invidious::Database::Statistics.channel_last_update.try &.to_unix || 0_i64,

View file

@ -10,6 +10,11 @@ module Invidious::Routes::API::V1::Misc
end
end
def self.metrics(env)
env.response.content_type = "text/plain"
return to_prometheus_metrics(Invidious::Jobs::StatisticsRefreshJob::STATISTICS_PROMETHEUS)
end
# APIv1 currently uses the same logic for both
# user playlists and Invidious playlists. This means that we can't
# reasonably split them yet. This should be addressed in APIv2

View file

@ -286,6 +286,9 @@ module Invidious::Routing
# Misc
get "/api/v1/stats", {{namespace}}::Misc, :stats
if CONFIG.statistics_enabled
get "/api/v1/metrics", {{namespace}}::Misc, :metrics
end
get "/api/v1/playlists/:plid", {{namespace}}::Misc, :get_playlist
get "/api/v1/auth/playlists/:plid", {{namespace}}::Misc, :get_playlist
get "/api/v1/mixes/:rdid", {{namespace}}::Misc, :mixes