From b7148872b6c03521b0e094df713a6e27779b219a Mon Sep 17 00:00:00 2001 From: Boyan Dimitrov Date: Tue, 25 Apr 2017 12:15:02 +0200 Subject: [PATCH] Fix rsp body closing on error and empty buffer flush to agent --- agent.go | 3 ++- recorder.go | 47 ++++++++++++++++++++++++++--------------------- 2 files changed, 28 insertions(+), 22 deletions(-) diff --git a/agent.go b/agent.go index 24235ab15..de8fba70f 100644 --- a/agent.go +++ b/agent.go @@ -117,10 +117,11 @@ func (r *agentS) fullRequestResponse(url string, method string, data interface{} client := &http.Client{Timeout: 5 * time.Second} resp, err = client.Do(req) if err == nil { + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { err = errors.New(resp.Status) } else { - defer resp.Body.Close() log.debug("agent response:", url, resp.Status) diff --git a/recorder.go b/recorder.go index 2245f5b42..6902c17c6 100644 --- a/recorder.go +++ b/recorder.go @@ -145,18 +145,21 @@ func collectLogs(rawSpan basictracer.RawSpan) map[uint64]map[string]interface{} func (r *SpanRecorder) init() { r.reset() - if !r.testMode { - ticker := time.NewTicker(1 * time.Second) - go func() { - for range ticker.C { - // Only attempt to send spans if we're announced. - if sensor.agent.canSend() { - log.debug("Sending spans to agent", len(r.spans)) - r.send() - } - } - }() + if r.testMode { + return } + + ticker := time.NewTicker(1 * time.Second) + go func() { + for range ticker.C { + // Only attempt to send spans if we're announced and if the buffer is not empty + if sensor.agent.canSend() && len(r.spans) > 0 { + log.debug("Sending spans to agent", len(r.spans)) + r.send() + } + } + }() + } func (r *SpanRecorder) reset() { @@ -217,7 +220,11 @@ func (r *SpanRecorder) RecordSpan(rawSpan basictracer.RawSpan) { From: sensor.agent.from, Data: &data}) - if !r.testMode && (len(r.spans) == sensor.options.ForceTransmissionStartingAt) { + if r.testMode || !sensor.agent.canSend() { + return + } + + if len(r.spans) >= sensor.options.ForceTransmissionStartingAt { log.debug("Forcing spans to agent", len(r.spans)) r.send() @@ -225,15 +232,13 @@ func (r *SpanRecorder) RecordSpan(rawSpan basictracer.RawSpan) { } func (r *SpanRecorder) send() { - if sensor.agent.canSend() && !r.testMode { - go func() { - _, err := sensor.agent.request(sensor.agent.makeURL(AgentTracesURL), "POST", r.spans) + go func() { + _, err := sensor.agent.request(sensor.agent.makeURL(AgentTracesURL), "POST", r.spans) - r.reset() + r.reset() - if err != nil { - sensor.agent.reset() - } - }() - } + if err != nil { + sensor.agent.reset() + } + }() }