Skip to content

Commit

Permalink
More optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
axsuul committed Nov 12, 2023
1 parent 832c12b commit 8668ee4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ services:
# Can be set in .env
- PLEX_ADDR=${PLEX_ADDR}
- PLEX_TOKEN=${PLEX_TOKEN}
- PLEX_TIMEOUT=${PLEX_TIMEOUT}
- PLEX_RETRIES_COUNT=${PLEX_RETRIES_COUNT}
- METRICS_MEDIA_COLLECTING_INTERVAL_SECONDS=300
volumes:
Expand Down
41 changes: 34 additions & 7 deletions lib/middleware/collector.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,21 +56,32 @@ def initialize(app)
end

def call(env)
case env["PATH_INFO"]
when "/metrics"
collect_metrics
end

@app.call(env)
end

def collect_metrics
log(step: "collect_metrics")

begin
capabilities_resource = send_plex_api_request(method: :get, endpoint: "/").dig("MediaContainer")
capabilities_resource = send_plex_api_request(method: :get, endpoint: "/identity").dig("MediaContainer")
metric_up_value = 1

log(plex_up: true)

set_gauge_metric_values_or_reset_missing(
metric: @metrics[:info],
values: {
{ version: capabilities_resource.dig("version") } => 1,
},
)

collect_session_metrics
collect_activity_metrics
collect_media_metrics
rescue HTTP::Error
log(plex_up: false)

# Value of 0 means there's no heartbeat
metric_up_value = 0
ensure
Expand All @@ -82,11 +93,23 @@ def call(env)
)
end

@app.call(env)
[
-> { collect_session_metrics },
-> { collect_activity_metrics },
-> { collect_media_metrics },
].each do |collection|
collection.call
rescue HTTP::Error
# Skip if it errors out
end
end

private

def log(**labels)
puts(labels.to_a.map { |k, v| "#{k}=#{v}" }.join(" "))
end

def collect_activity_metrics
values = Hash.new { |h, k| h[k] = 0 }

Expand Down Expand Up @@ -209,13 +232,17 @@ def send_plex_api_request(method:, endpoint:, **options)

# Keep trying request if it fails until number of retries have been exhausted
loop do
url = "#{@plex_addr}#{endpoint}"

log(method: method, url: url)

response = HTTP
.timeout(@plex_timeout)
.headers(
"X-Plex-Token" => @plex_token,
"Accept" => "application/json",
)
.public_send(method, "#{@plex_addr}#{endpoint}", **options)
.public_send(method, url, **options)

return JSON.parse(response)
rescue HTTP::Error => e
Expand Down

0 comments on commit 8668ee4

Please sign in to comment.