Class: ZuoraConnect::MetricsMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/middleware/metrics_middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ MetricsMiddleware

Returns a new instance of MetricsMiddleware.



40
41
42
# File 'lib/middleware/metrics_middleware.rb', line 40

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/middleware/metrics_middleware.rb', line 44

def call(env)
  @bad_headers = ["HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED_HOST", "HTTP_X_FORWARDED_PORT", "HTTP_X_FORWARDED_PROTO", "HTTP_X_FORWARDED_SCHEME", "HTTP_X_FORWARDED_SSL"] 
  if !ActionDispatch::Request::HTTP_METHODS.include?(env["REQUEST_METHOD"].upcase)
    [405, {"Content-Type" => "text/plain"}, ["Method Not Allowed"]]
  else
    if (env['HTTP_ZUORA_LAYOUT_FETCH_TEMPLATE_ID'].present?)
      Thread.current[:isHallway] = "/#{env['HTTP_ZUORA_LAYOUT_FETCH_TEMPLATE_ID']}"
      env['PATH_INFO'] = env['PATH_INFO'].gsub(Thread.current[:isHallway], '')
      env['REQUEST_URI'] = env['REQUEST_URI'].gsub(Thread.current[:isHallway], '')
      env['REQUEST_PATH'] = env['REQUEST_PATH'].gsub(Thread.current[:isHallway], '')

      #We need the forwarded host header to identify location of tenant
      whitelist = Regexp.new(".*[\.]zuora[\.]com$|^zuora[\.]com$")
      if whitelist.match(env['HTTP_X_FORWARDED_HOST']).present?
        @bad_headers.delete('HTTP_X_FORWARDED_HOST')
      end
    else
      Thread.current[:isHallway] = nil
    end

    #Remove bad headers
    @bad_headers.each { |header| env.delete(header) }

    #Thread.current[:appinstance] = nil
    start_time = Time.now
    begin
      @status, @headers, @response = @app.call(env)
    ensure 
      
      # If the url contains any CSS or JavaScript files then do not collect metrics for them
      if ["css", "assets", "jpg", "png", "jpeg", "ico"].any? { |word| env['PATH_INFO'].include?(word) } || /.*\.js$/.match(env['PATH_INFO'])
        tags = {status: @status, controller: 'ActionController', action: 'Assets', app_instance: 0}
        values = {response_time: ((Time.now - start_time)*1000).round(2) }
        ZuoraConnect::AppInstanceBase.write_to_telegraf(direction: 'request-inbound-assets', tags: tags, values: values)
      end

      if defined? Prometheus
        #Prometheus Stuff
        if env['PATH_INFO'] == '/connect/internal/metrics'

          #Do something before each scrape
          if defined? Resque.redis
            begin

              Resque.redis.ping

              Prometheus::REDIS_CONNECTION.set({connection:'redis',name: ZuoraConnect::Telegraf.app_name},1)
              Prometheus::FINISHED_JOBS.set({type:'resque',name: ZuoraConnect::Telegraf.app_name},Resque.info[:processed])
              Prometheus::PENDING_JOBS.set({type:'resque',name: ZuoraConnect::Telegraf.app_name},Resque.info[:pending])
              Prometheus::ACTIVE_WORKERS.set({type:'resque',name: ZuoraConnect::Telegraf.app_name},Resque.info[:working])
              Prometheus::WORKERS.set({type:'resque',name: ZuoraConnect::Telegraf.app_name},Resque.info[:workers])
              Prometheus::FAILED_JOBS.set({type:'resque',name: ZuoraConnect::Telegraf.app_name},Resque.info[:failed])

            rescue Redis::CannotConnectError
                Prometheus::REDIS_CONNECTION.set({connection:'redis',name: ZuoraConnect::Telegraf.app_name},0)
            end

            if ZuoraConnect.configuration.custom_prometheus_update_block != nil
              ZuoraConnect.configuration.custom_prometheus_update_block.call()
            end
          end

        end
      end

      # Uncomment following block of code for handling engine requests/requests without controller
      # else
      #   # Handling requests which do not have controllers (engines)
      if env["SCRIPT_NAME"].present?
        controller_path = "#{env['SCRIPT_NAME'][1..-1]}"
        controller_path = controller_path.sub("/", "::")
        request_path = "#{controller_path}#UnknownAction"
      else
        # Writing to telegraf: Handle 404
        if [404, 500].include?(@status)
          content_type = @headers['Content-Type'].split(';')[0] if @headers['Content-Type']
          content_type = content_type.gsub('text/javascript', 'application/javascript')
          tags = {status: @status, content_type: content_type}
       
          tags = tags.merge({controller: 'ActionController'})
          tags = tags.merge({action: 'RoutingError' }) if @status == 404
          
          values = {response_time: ((Time.now - start_time)*1000).round(2) }

          ZuoraConnect::AppInstanceBase.write_to_telegraf(direction: :inbound, tags: tags, values: values)
        end
      end
      Thread.current[:inbound_metric] = nil
    end
    [@status, @headers, @response]
  end
end