summaryrefslogtreecommitdiff
path: root/lib/gitlab/metrics/samplers/unicorn_sampler.rb
blob: 4c5b849cc5128ee7b8aa8edfcfa54cd7143d9d72 (plain)
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
# frozen_string_literal: true

module Gitlab
  module Metrics
    module Samplers
      class UnicornSampler < BaseSampler
        def initialize(interval)
          super(interval)
        end

        def unicorn_active_connections
          @unicorn_active_connections ||= Gitlab::Metrics.gauge(:unicorn_active_connections, 'Unicorn active connections', {}, :max)
        end

        def unicorn_queued_connections
          @unicorn_queued_connections ||= Gitlab::Metrics.gauge(:unicorn_queued_connections, 'Unicorn queued connections', {}, :max)
        end

        def enabled?
          # Raindrops::Linux.tcp_listener_stats is only present on Linux
          unicorn_with_listeners? && Raindrops::Linux.respond_to?(:tcp_listener_stats)
        end

        def sample
          Raindrops::Linux.tcp_listener_stats(tcp_listeners).each do |addr, stats|
            unicorn_active_connections.set({ socket_type: 'tcp', socket_address: addr }, stats.active)
            unicorn_queued_connections.set({ socket_type: 'tcp', socket_address: addr }, stats.queued)
          end

          Raindrops::Linux.unix_listener_stats(unix_listeners).each do |addr, stats|
            unicorn_active_connections.set({ socket_type: 'unix', socket_address: addr }, stats.active)
            unicorn_queued_connections.set({ socket_type: 'unix', socket_address: addr }, stats.queued)
          end
        end

        private

        def tcp_listeners
          @tcp_listeners ||= Unicorn.listener_names.grep(%r{\A[^/]+:\d+\z})
        end

        def unix_listeners
          @unix_listeners ||= Unicorn.listener_names - tcp_listeners
        end

        def unicorn_with_listeners?
          defined?(Unicorn) && Unicorn.listener_names.any?
        end
      end
    end
  end
end