-
Notifications
You must be signed in to change notification settings - Fork 4.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Heartbeat] Capture HTTP Response Bodies #13022
Changes from all commits
7019a77
9a2a3b3
9c097f1
598aa42
9173812
a3b7ad8
011dc8f
5ccb8c9
8a2ff61
8e6b927
c96e5e3
3a91546
aff722d
38dd2e9
629dfd2
486cfe4
37b9078
c6bd5f1
d7f34c8
84fcf11
2c2bec4
38126f5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -31,10 +31,11 @@ import ( | |
) | ||
|
||
type Config struct { | ||
URLs []string `config:"urls" validate:"required"` | ||
ProxyURL string `config:"proxy_url"` | ||
Timeout time.Duration `config:"timeout"` | ||
MaxRedirects int `config:"max_redirects"` | ||
URLs []string `config:"urls" validate:"required"` | ||
ProxyURL string `config:"proxy_url"` | ||
Timeout time.Duration `config:"timeout"` | ||
MaxRedirects int `config:"max_redirects"` | ||
Response responseConfig `config:"response"` | ||
|
||
Mode monitors.IPSettings `config:",inline"` | ||
|
||
|
@@ -49,6 +50,11 @@ type Config struct { | |
Check checkConfig `config:"check"` | ||
} | ||
|
||
type responseConfig struct { | ||
IncludeBody string `config:"include_body"` | ||
IncludeBodyMaxBytes int `config:"include_body_max_bytes"` | ||
} | ||
|
||
type checkConfig struct { | ||
Request requestParameters `config:"request"` | ||
Response responseParameters `config:"response"` | ||
|
@@ -87,7 +93,11 @@ type compressionConfig struct { | |
var defaultConfig = Config{ | ||
Timeout: 16 * time.Second, | ||
MaxRedirects: 10, | ||
Mode: monitors.DefaultIPSettings, | ||
Response: responseConfig{ | ||
IncludeBody: "on_error", | ||
IncludeBodyMaxBytes: 2048, | ||
}, | ||
Mode: monitors.DefaultIPSettings, | ||
Check: checkConfig{ | ||
Request: requestParameters{ | ||
Method: "GET", | ||
|
@@ -103,6 +113,20 @@ var defaultConfig = Config{ | |
}, | ||
} | ||
|
||
func (r *responseConfig) Validate() error { | ||
switch strings.ToLower(r.IncludeBody) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do you really want to do the strings to lower? I would enforce users to write it correctly. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I mean, I don't see one way as being correct or another. Some people like typing in upper case. It's not a big deal to me however. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agree, just personal preference. Both options ok for me. |
||
case "always", "on_error", "never": | ||
default: | ||
return fmt.Errorf("unknown option for `include_body`: '%s', please use one of 'always', 'on_error', 'never'", r.IncludeBody) | ||
} | ||
|
||
if r.IncludeBodyMaxBytes <= 0 { | ||
return fmt.Errorf("include_body_max_bytes must be a positive integer, got %d", r.IncludeBodyMaxBytes) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (r *requestParameters) Validate() error { | ||
switch strings.ToUpper(r.Method) { | ||
case "HEAD", "GET", "POST": | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
// Licensed to Elasticsearch B.V. under one or more contributor | ||
// license agreements. See the NOTICE file distributed with | ||
// this work for additional information regarding copyright | ||
// ownership. Elasticsearch B.V. licenses this file to you under | ||
// the Apache License, Version 2.0 (the "License"); you may | ||
// not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
package http | ||
|
||
import ( | ||
"crypto/sha256" | ||
"encoding/hex" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"unicode/utf8" | ||
|
||
"github.com/elastic/beats/heartbeat/eventext" | ||
"github.com/elastic/beats/libbeat/common" | ||
|
||
"github.com/elastic/beats/heartbeat/reason" | ||
"github.com/elastic/beats/libbeat/beat" | ||
) | ||
|
||
func handleRespBody(event *beat.Event, resp *http.Response, responseConfig responseConfig, errReason reason.Reason) error { | ||
defer resp.Body.Close() | ||
|
||
sampleMaxBytes := responseConfig.IncludeBodyMaxBytes | ||
|
||
includeSample := responseConfig.IncludeBody == "always" || (responseConfig.IncludeBody == "on_error" && errReason != nil) | ||
|
||
// No need to return any actual body bytes if we'll discard them anyway. This should save on allocation | ||
if !includeSample { | ||
sampleMaxBytes = 0 | ||
} | ||
|
||
sampleStr, bodyBytes, bodyHash, err := readResp(resp, sampleMaxBytes) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
evtBodyMap := common.MapStr{ | ||
"hash": bodyHash, | ||
"bytes": bodyBytes, | ||
} | ||
if includeSample { | ||
evtBodyMap["content"] = sampleStr | ||
} | ||
|
||
eventext.MergeEventFields(event, common.MapStr{ | ||
"http": common.MapStr{ | ||
"response": common.MapStr{"body": evtBodyMap}, | ||
}, | ||
}) | ||
|
||
return nil | ||
} | ||
|
||
// readResp reads the first sampleSize bytes from the httpResponse, | ||
// then closes the body (which closes the connection). It doesn't return any errors | ||
// but does log them. During an error case the return values will be (nil, -1). | ||
// The maxBytes params controls how many bytes will be returned in a string, not how many will be read. | ||
// We always read the full response here since we want to time downloading the full thing. | ||
// This may return a nil body if the response is not valid UTF-8 | ||
func readResp(resp *http.Response, maxSampleBytes int) (bodySample string, bodySize int64, hashStr string, err error) { | ||
if resp == nil { | ||
return "", -1, "", fmt.Errorf("cannot readResp of nil HTTP response") | ||
} | ||
|
||
respSize, bodySample, hash, err := readPrefixAndHash(resp.Body, maxSampleBytes) | ||
|
||
return bodySample, respSize, hash, err | ||
} | ||
|
||
func readPrefixAndHash(body io.ReadCloser, maxPrefixSize int) (respSize int64, prefix string, hashStr string, err error) { | ||
hash := sha256.New() | ||
// Function to lazily get the body of the response | ||
rawBuf := make([]byte, 1024) | ||
|
||
// Buffer to hold the prefix output along with tracking info | ||
prefixBuf := make([]byte, maxPrefixSize) | ||
prefixRemainingBytes := maxPrefixSize | ||
prefixWriteOffset := 0 | ||
for { | ||
readSize, readErr := body.Read(rawBuf) | ||
|
||
respSize += int64(readSize) | ||
hash.Write(rawBuf[:readSize]) | ||
|
||
if prefixRemainingBytes > 0 { | ||
if readSize >= prefixRemainingBytes { | ||
copy(prefixBuf[prefixWriteOffset:maxPrefixSize], rawBuf[:prefixRemainingBytes]) | ||
prefixWriteOffset += prefixRemainingBytes | ||
prefixRemainingBytes = 0 | ||
} else { | ||
copy(prefixBuf[prefixWriteOffset:prefixWriteOffset+readSize], rawBuf[:readSize]) | ||
prefixWriteOffset += readSize | ||
prefixRemainingBytes -= readSize | ||
} | ||
} | ||
|
||
if readErr == io.EOF { | ||
break | ||
} | ||
|
||
if readErr != nil { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sorry, just seeing this now. Shouldn't this line directly be after line 95? I get that if you have an EOF that you also want to get the content first, but if you have an actual error, I assume also the readSize is probably 0 ? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nope! See https://golang.org/pkg/io/#Reader
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for the reminder 👍 |
||
return 0, "", "", readErr | ||
} | ||
} | ||
|
||
// We discard the body if it is not valid UTF-8 | ||
if utf8.Valid(prefixBuf[:prefixWriteOffset]) { | ||
prefix = string(prefixBuf[:prefixWriteOffset]) | ||
} | ||
return respSize, prefix, hex.EncodeToString(hash.Sum(nil)), nil | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does also not seem to be documented. How does it overlap with the truncate? Probably see it in the code below.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is in the documentation! I documented the whole
response
block as one thing here. Glad to change it, but it's in keeping with the style of some other feature's documentation.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry, missed that. Seems my
command - F
foo failed me.