Skip to content

Commit dcba2dd

Browse files
author
Takashi Kusumi
authored
Fix potential panic in stern.Run() (#267)
1 parent 65204cc commit dcba2dd

File tree

1 file changed

+11
-20
lines changed

1 file changed

+11
-20
lines changed

stern/stern.go

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -171,15 +171,14 @@ func Run(ctx context.Context, config *Config) error {
171171
}
172172
}
173173

174+
eg, nctx := errgroup.WithContext(ctx)
174175
var numRequests atomic.Int64
175-
errCh := make(chan error)
176-
defer close(errCh)
177176
for _, n := range namespaces {
178-
selector, err := chooseSelector(ctx, client, n, resource.kind, resource.name, config.LabelSelector)
177+
selector, err := chooseSelector(nctx, client, n, resource.kind, resource.name, config.LabelSelector)
179178
if err != nil {
180179
return err
181180
}
182-
a, err := WatchTargets(ctx,
181+
a, err := WatchTargets(nctx,
183182
client.CoreV1().Pods(n),
184183
selector,
185184
config.FieldSelector,
@@ -189,39 +188,31 @@ func Run(ctx context.Context, config *Config) error {
189188
return errors.Wrap(err, "failed to set up watch")
190189
}
191190

192-
go func() {
191+
eg.Go(func() error {
193192
for {
194193
select {
195194
case target, ok := <-a:
196195
if !ok {
197-
errCh <- fmt.Errorf("lost watch connection")
198-
return
196+
return fmt.Errorf("lost watch connection")
199197
}
200198
numRequests.Add(1)
201199
if numRequests.Load() > int64(config.MaxLogRequests) {
202-
errCh <- fmt.Errorf(
200+
return fmt.Errorf(
203201
"stern reached the maximum number of log requests (%d),"+
204202
" use --max-log-requests to increase the limit",
205203
config.MaxLogRequests)
206-
return
207204
}
208205
go func() {
209-
tailTarget(ctx, target)
206+
tailTarget(nctx, target)
210207
numRequests.Add(-1)
211208
}()
212-
case <-ctx.Done():
213-
return
209+
case <-nctx.Done():
210+
return nil
214211
}
215212
}
216-
}()
217-
}
218-
219-
select {
220-
case e := <-errCh:
221-
return e
222-
case <-ctx.Done():
223-
return nil
213+
})
224214
}
215+
return eg.Wait()
225216
}
226217

227218
func chooseSelector(ctx context.Context, client clientset.Interface, namespace, kind, name string, selector labels.Selector) (labels.Selector, error) {

0 commit comments

Comments
 (0)