-
Notifications
You must be signed in to change notification settings - Fork 7
/
sidekiq.rb
93 lines (81 loc) · 2.29 KB
/
sidekiq.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# frozen_string_literal: true
require 'rack'
module Telegraf
module Sidekiq
# Telegraf::Sidekiq::Middleware
#
# This Sidekiq middleware collects queue metrics and sends them to telegraf.
#
#
# Tags:
#
# * `type`:
# One of "job" or "scheduled_job".
#
# * `queue`:
# The queue this job landed on.
#
# * `worker`:
# The name of the worker class that was executed.
#
# * `errors`:
# Whether or not this job errored.
#
# * `retry`:
# Whether or not this execution was a retry of a previously failed one.
#
#
# Values:
#
# * `app_ms`:
# Total worker processing time.
#
# * `queue_ms`:
# How long did this job wait in the queue before being processed?
# Only present for "normal" (async) jobs (with tag `type` of "job").
#
class Middleware
include ::Telegraf::Plugin
def initialize(agent, options = {})
options[:series] ||= 'sidekiq'
super(
**options,
agent: agent
)
end
def call(worker, job, queue)
job_start = ::Time.now.utc
point = Point.new(
tags: {
**@tags,
type: 'job',
errors: true,
retry: job.key?('retried_at'),
queue: queue,
worker: worker.class.name,
},
values: {
retry_count: job['retry_count'],
}.compact,
)
# The "enqueued_at" key is not present for scheduled jobs.
# See https://github.com/mperham/sidekiq/wiki/Job-Format.
if job.key?('enqueued_at')
enqueued_at = ::Time.at(job['enqueued_at'].to_f).utc
point.values[:queue_ms] = (job_start - enqueued_at) * 1000 # milliseconds
end
# The "at" key is only present for scheduled jobs.
point.tags[:type] = 'scheduled_job' if job.key?('at')
begin
yield
# If we get here, this was a successful execution
point.tags[:errors] = false
ensure
job_stop = ::Time.now.utc
point.values[:app_ms] = (job_stop - job_start) * 1000 # milliseconds
_write(point, before_send_kwargs: {worker: worker, job: job, queue: queue})
end
end
end
end
end