Class: Firetail::Run
- Inherits:
-
Object
- Object
- Firetail::Run
- Defined in:
- lib/firetail-rails.rb
Constant Summary collapse
- MAX_BULK_SIZE_IN_BYTES =
1 MB
1 * 1024 * 1024
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ Run
constructor
A new instance of Run.
- #log(env, response, status, res_headers, body, started_on, ended_on, exception = nil) ⇒ Object
- #send_to_backend(payload) ⇒ Object
Constructor Details
#initialize(app) ⇒ Run
Returns a new instance of Run.
16 17 18 19 20 |
# File 'lib/firetail-rails.rb', line 16 def initialize app @app = app @reqres ||= [] # request data in stored in array memory @init_time ||= Time.now # initialize time end |
Instance Method Details
#call(env) ⇒ Object
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 |
# File 'lib/firetail-rails.rb', line 22 def call(env) # This block initialises the configuration and checks # sets the values for certain necessary configuration # If it is Rails if defined?(Rails) begin default_location = File.join(Rails.root, "config/firetail.yml") config = YAML.load_file(default_location) rescue Errno::ENOENT # error message if firetail is not installed puts "" puts "Please run 'rails generate firetail:install' first" puts "" end else # other frameworks config = YAML.load_file("firetail.yml") end raise Error.new "Please run 'rails generate firetail:install' first" if config.nil? raise Error.new "Token is missing from firetail.yml configuration" if config['token'].nil? raise Error.new "API Key is missing from firetail.yml configuration" if config['api_key'].nil? @token = config['token'] @api_key = config['api_key'] @url = config['url'] ? config['url'] : "https://ingest.eu-west-1.dev.firetail.app/ingest/request" # default goes to dev @log_drains_timeout = config['log_drains_timeout'] ? config['log_drains_timeout'] : 5 @network_timeout = config['network_timeout'] ? config['network_timeout'] : 10 @number_of_retries = config['number_of_retries'] ? config['number_of_retries'] : 4 @retry_timeout = config['retry_timeout'] ? config['retry_timeout'] : 2 # End of configuration initialization # Gets the rack middleware requests request = Rack::Request.new(env) started_on = Time.now begin status, res_headers, body = response = @app.call(env) log(env, response, status, res_headers, body, started_on, Time.now) rescue Exception => exception log(env, response, status, res_headers, body, started_on, Time.now, exception) raise exception end response end |
#log(env, response, status, res_headers, body, started_on, ended_on, exception = nil) ⇒ Object
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 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
# File 'lib/firetail-rails.rb', line 67 def log(env, response, status, res_headers, body, started_on, ended_on, exception = nil) # request values req_url = env['REQUEST_URI'] req_path = env['PATH_INFO'] time_spent = ended_on - started_on req_user_agent = env['HTTP_USER_AGENT'] req_ip = defined?(Rails) ? env['action_dispatch.remote_ip'].calculate_ip : env['REMOTE_ADDR'] req_method = env['REQUEST_METHOD'] req_http_host = env['HTTP_HOST'] req_http_version = env['HTTP_VERSION'] req_http_encoding = env['HTTP_ACCEPT_ENCODING'] req_http_accept = env['HTTP_ACCEPT'] req_query_string = env['QUERY_STRING'] req_path = env['REQUEST_PATH'] req_uri = env['REQUEST_URI'] req_server_software = env['SERVER_SOFTWARE'] req_server_port = env['SERVER_PORT'] req_gateway_interface = env['GATEWAY_INTERFACE'] req_http_connection = env['HTTP_CONNECTION'] # get the request "HTTP_" headers req_headers = env.select {|k,v| k.start_with? 'HTTP_'} .collect {|key, val| [key.sub(/^HTTP_/, ''), val]} .collect {|key, val| "#{key}: #{val}<br>"} .sort # add the request and response data # to array of data for batching up @reqres.push({ version: "1.1", dateCreated: Time.now.utc.to_i, execution_time: time_spent, #dateCreated: 1663763942581, #execution_time: 3.74, req: { httpProtocol: req_http_version, headers: req_headers.to_s, path: req_path, method: req_method, oPath: req_path, fPath: req_path, args: req_query_string, ip: req_ip, pathParams: req_path, user_agent: req_user_agent # maybe need this? }, resp: { status_code: status, content_len: res_headers['Content-Length'], content_enc: res_headers['Content-Encoding'], body: body ? body.body : body[0], headers: res_headers.to_s, content_type: res_headers['Content-Type'], error_type: exception&.class&.name, # maybe need this? error_message: exception&. # maybe need this? can be removed } }) # the time we calculate if request that is # buffered max is 120 seconds current_time = Time.now # duration in millseconds duration = (current_time - @init_time) * 1000.0 #Firetail.logger.debug "size in bytes #{ObjectSpace.memsize_of(@request_data.to_s)}" #request data size in bytes #request_data_size = ObjectSpace.memsize_of(@request_data.to_s) # It is difficult to calculate the object size in bytes, # seems to not return the accurate values # This will send the data we need in batches of 5 requests or when it is more than 120 seconds # if there are more than 5 requests or is more than # 2 minutes, then send to backend - this is for testing if @reqres.length >= 5 || duration > 120 #Firetail.logger.debug "request data #{@request_data.length}" payload = "" # begin of data will have a newline @reqres.each do |data| # append string in-place json = data.to_json payload = json + "\n" end #puts "Our data: #{payload}" # send the data to backend API # This is an async task Async do |task| task.async do send_to_backend(payload) end end # reset back tohe conditions payload = nil @reqres = [] @init_time = Time.now end rescue Exception => exception Firetail.logger.error(exception.) end |
#send_to_backend(payload) ⇒ Object
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/firetail-rails.rb', line 175 def send_to_backend(payload) #Firetail.logger.debug datas.to_json # Parse it as URI uri = URI(@url) # Send the request http = Net::HTTP.new(uri.hostname, uri.port) #http.set_debug_output($stdout) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER # Create a new request req = CustomPost.new(uri.path, { 'Content-Type': 'text/plain', 'x-api-key': @api_key, 'X-FT-API-KEY': @token }) # debug code #req.body = "{\"version\": \"1.1\", \"dateCreated\": 1663763942581, \"execution_time\": 3.74, \"req\": {}, \"resp\": {}}" #req.body = '{"version": "1.1", "dateCreated": 1663763942581, "execution_time": 3.74, "req": {}, "resp": {}}\n{"version": "1.1", "dateCreated": 1663763942581, "execution_time": 3.74, "req": {}, "resp": {}}' req.body = payload res = http.request(req) Firetail.logger.debug "response from firetail: #{res}" end |