Skip to content

Commit 19307cc

Browse files
fix: fix race conditions in the agent.go file
1 parent 0c47efc commit 19307cc

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

agent.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,9 @@ func (agent *agentS) Ready() bool {
144144

145145
// SendMetrics sends collected entity data to the host agent
146146
func (agent *agentS) SendMetrics(data acceptor.Metrics) error {
147+
agent.mu.RLock()
148+
defer agent.mu.RUnlock()
149+
147150
pid, err := strconv.Atoi(agent.agentComm.from.EntityID)
148151
if err != nil && agent.agentComm.from.EntityID != "" {
149152
agent.logger.Debug("agent got malformed PID %q", agent.agentComm.from.EntityID)
@@ -159,7 +162,11 @@ func (agent *agentS) SendMetrics(data acceptor.Metrics) error {
159162
}
160163

161164
agent.logger.Error("failed to send metrics to the host agent: ", err)
165+
166+
// We need to release the read lock before calling reset() which acquires a write lock
167+
agent.mu.RUnlock()
162168
agent.reset()
169+
agent.mu.RLock()
163170

164171
return err
165172
}
@@ -186,6 +193,9 @@ func (agent *agentS) SendEvent(event *EventData) error {
186193

187194
// SendSpans sends collected spans to the host agent
188195
func (agent *agentS) SendSpans(spans []Span) error {
196+
agent.mu.RLock()
197+
defer agent.mu.RUnlock()
198+
189199
for i := range spans {
190200
spans[i].From = agent.agentComm.from
191201
}
@@ -202,7 +212,11 @@ func (agent *agentS) SendSpans(spans []Span) error {
202212
return nil
203213
} else {
204214
agent.logger.Error("failed to send spans to the host agent: ", err)
215+
216+
// We need to release the read lock before calling reset() which acquires a write lock
217+
agent.mu.RUnlock()
205218
agent.reset()
219+
agent.mu.RLock()
206220
}
207221

208222
return err
@@ -221,6 +235,9 @@ type hostAgentProfile struct {
221235

222236
// SendProfiles sends profile data to the agent
223237
func (agent *agentS) SendProfiles(profiles []autoprofile.Profile) error {
238+
agent.mu.RLock()
239+
defer agent.mu.RUnlock()
240+
224241
agentProfiles := make([]hostAgentProfile, 0, len(profiles))
225242
for _, p := range profiles {
226243
agentProfiles = append(agentProfiles, hostAgentProfile{p, agent.agentComm.from.EntityID})
@@ -233,7 +250,11 @@ func (agent *agentS) SendProfiles(profiles []autoprofile.Profile) error {
233250
}
234251

235252
agent.logger.Error("failed to send profile data to the host agent: ", err)
253+
254+
// We need to release the read lock before calling reset() which acquires a write lock
255+
agent.mu.RUnlock()
236256
agent.reset()
257+
agent.mu.RLock()
237258

238259
return err
239260
}

0 commit comments

Comments
 (0)