diff options
author | Stan Hu <stanhu@gmail.com> | 2020-07-31 12:58:42 +0000 |
---|---|---|
committer | Igor Drozdov <idrozdov@gitlab.com> | 2020-07-31 12:58:42 +0000 |
commit | 87402ed127d9855b8123e5e08a4c89d373cc79e8 (patch) | |
tree | 6a28feda2a62ec88e889593d7fbf3ae950659e35 /client/gitlabnet.go | |
parent | 701ebca0b5d4a8451afe677c3bdb19cc92a5a2f0 (diff) | |
download | gitlab-shell-87402ed127d9855b8123e5e08a4c89d373cc79e8.tar.gz |
Generate and log correlation IDs
This will make it easier to tie an SSH access request to Rails API and
Gitaly requests.
Diffstat (limited to 'client/gitlabnet.go')
-rw-r--r-- | client/gitlabnet.go | 30 |
1 files changed, 21 insertions, 9 deletions
diff --git a/client/gitlabnet.go b/client/gitlabnet.go index 7fbf63e..0657ca0 100644 --- a/client/gitlabnet.go +++ b/client/gitlabnet.go @@ -2,6 +2,7 @@ package client import ( "bytes" + "context" "encoding/base64" "encoding/json" "fmt" @@ -11,6 +12,7 @@ import ( "time" log "github.com/sirupsen/logrus" + "gitlab.com/gitlab-org/labkit/correlation" ) const ( @@ -57,23 +59,32 @@ func normalizePath(path string) string { return path } -func newRequest(method, host, path string, data interface{}) (*http.Request, error) { +func newRequest(method, host, path string, data interface{}) (*http.Request, string, error) { var jsonReader io.Reader if data != nil { jsonData, err := json.Marshal(data) if err != nil { - return nil, err + return nil, "", err } jsonReader = bytes.NewReader(jsonData) } - request, err := http.NewRequest(method, host+path, jsonReader) + correlationID, err := correlation.RandomID() + ctx := context.Background() + if err != nil { - return nil, err + log.WithError(err).Warn("unable to generate correlation ID") + } else { + ctx = correlation.ContextWithCorrelation(ctx, correlationID) + } + + request, err := http.NewRequestWithContext(ctx, method, host+path, jsonReader) + if err != nil { + return nil, "", err } - return request, nil + return request, correlationID, nil } func parseError(resp *http.Response) error { @@ -100,7 +111,7 @@ func (c *GitlabNetClient) Post(path string, data interface{}) (*http.Response, e } func (c *GitlabNetClient) DoRequest(method, path string, data interface{}) (*http.Response, error) { - request, err := newRequest(method, c.httpClient.Host, path, data) + request, correlationID, err := newRequest(method, c.httpClient.Host, path, data) if err != nil { return nil, err } @@ -119,9 +130,10 @@ func (c *GitlabNetClient) DoRequest(method, path string, data interface{}) (*htt start := time.Now() response, err := c.httpClient.Do(request) fields := log.Fields{ - "method": method, - "url": request.URL.String(), - "duration_ms": time.Since(start) / time.Millisecond, + "correlation_id": correlationID, + "method": method, + "url": request.URL.String(), + "duration_ms": time.Since(start) / time.Millisecond, } logger := log.WithFields(fields) |