Skip to content

Commit 9b98e84

Browse files
fix(go/exporter): Make sure all channels readers/writers are context-cancellable (google#4223)
When the context was being cancelled, the `ecosystemRouter` seems to have been getting stuck, causing go to ungracefully terminate the program due to deadlock. --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
1 parent bdd266f commit 9b98e84

1 file changed

Lines changed: 27 additions & 4 deletions

File tree

go/cmd/exporter/exporter.go

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,18 @@ func ecosystemRouter(ctx context.Context, inCh <-chan *osvschema.Vulnerability,
138138

139139
allEcosystemWorker := newAllEcosystemWorker(ctx, outCh, &workersWg)
140140

141-
for vuln := range inCh {
141+
RouterLoop:
142+
for {
143+
var vuln *osvschema.Vulnerability
144+
var ok bool
145+
select {
146+
case <-ctx.Done():
147+
break RouterLoop
148+
case vuln, ok = <-inCh:
149+
if !ok {
150+
break RouterLoop
151+
}
152+
}
142153
vulnCounter++
143154
ecosystems := make(map[string]struct{})
144155
for _, aff := range vuln.GetAffected() {
@@ -164,15 +175,27 @@ func ecosystemRouter(ctx context.Context, inCh <-chan *osvschema.Vulnerability,
164175
worker = newEcosystemWorker(ctx, eco, outCh, &workersWg)
165176
workers[eco] = worker
166177
}
167-
worker.inCh <- vuln
178+
select {
179+
case worker.inCh <- vuln:
180+
case <-ctx.Done():
181+
break RouterLoop
182+
}
183+
}
184+
select {
185+
case allEcosystemWorker.inCh <- vulnAndEcos{Vulnerability: vuln, ecosystems: ecoNames}:
186+
case <-ctx.Done():
187+
break RouterLoop
168188
}
169-
allEcosystemWorker.inCh <- vulnAndEcos{Vulnerability: vuln, ecosystems: ecoNames}
170189
}
171190

172191
for _, worker := range workers {
173192
worker.Finish()
174193
}
175194
allEcosystemWorker.Finish()
176195
workersWg.Wait()
177-
logger.Info("ecosystem router finished, all vulnerabilities dispatched", slog.Int("total_vulnerabilities", vulnCounter))
196+
if ctx.Err() == nil {
197+
logger.Info("ecosystem router finished, all vulnerabilities dispatched", slog.Int("total_vulnerabilities", vulnCounter))
198+
} else {
199+
logger.Info("ecosystem router cancelled", slog.Any("err", ctx.Err()))
200+
}
178201
}

0 commit comments

Comments
 (0)