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
94
95
96
97
98
99
100
101
102
103
module Gitlab
module Metrics
# Class for storing metrics information of a single transaction.
class Transaction
THREAD_KEY = :_gitlab_metrics_transaction
attr_reader :tags, :values
attr_accessor :action
def self.current
Thread.current[THREAD_KEY]
end
# action - A String describing the action performed, usually the class
# plus method name.
def initialize(action = nil)
@metrics = []
@started_at = nil
@finished_at = nil
@values = Hash.new(0)
@tags = {}
@action = action
@memory_before = 0
@memory_after = 0
end
def duration
@finished_at ? (@finished_at - @started_at) * 1000.0 : 0.0
end
def allocated_memory
@memory_after - @memory_before
end
def run
Thread.current[THREAD_KEY] = self
@memory_before = System.memory_usage
@started_at = Time.now
yield
ensure
@memory_after = System.memory_usage
@finished_at = Time.now
Thread.current[THREAD_KEY] = nil
end
def add_metric(series, values, tags = {})
prefix = sidekiq? ? 'sidekiq_' : 'rails_'
@metrics << Metric.new("#{prefix}#{series}", values, tags)
end
def increment(name, value)
@values[name] += value
end
def set(name, value)
@values[name] = value
end
def add_tag(key, value)
@tags[key] = value
end
def finish
track_self
submit
end
def track_self
values = { duration: duration, allocated_memory: allocated_memory }
@values.each do |name, value|
values[name] = value
end
add_metric('transactions', values, @tags)
end
def submit
metrics = @metrics.map do |metric|
hash = metric.to_hash
hash[:tags][:action] ||= @action if @action
hash
end
Metrics.submit_metrics(metrics)
end
def sidekiq?
Sidekiq.server?
end
end
end
end