Skip to content

Commit fa6f779

Browse files
fix: close all opened resources if an error occurs (#9665)
Signed-off-by: Fabrizio Sestito <[email protected]>
1 parent 807bbbd commit fa6f779

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

pkg/commands/artifact/run.go

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,7 @@ const (
5252
TargetK8s TargetKind = "k8s"
5353
)
5454

55-
var (
56-
SkipScan = errors.New("skip subsequent processes")
57-
)
55+
var SkipScan = errors.New("skip subsequent processes")
5856

5957
// InitializeScanService defines the initialize function signature of scan service
6058
type InitializeScanService func(context.Context, ScannerConfig) (scan.Service, func(), error)
@@ -116,12 +114,20 @@ func WithInitializeService(f InitializeScanService) RunnerOption {
116114

117115
// NewRunner initializes Runner that provides scanning functionalities.
118116
// It is possible to return SkipScan and it must be handled by caller.
119-
func NewRunner(ctx context.Context, cliOptions flag.Options, targetKind TargetKind, opts ...RunnerOption) (Runner, error) {
117+
func NewRunner(ctx context.Context, cliOptions flag.Options, targetKind TargetKind, opts ...RunnerOption) (_ Runner, err error) {
120118
r := &runner{}
121119
for _, opt := range opts {
122120
opt(r)
123121
}
124122

123+
defer func() {
124+
if err != nil {
125+
if cErr := r.Close(ctx); cErr != nil {
126+
log.ErrorContext(ctx, "failed to close runner: %s", cErr)
127+
}
128+
}
129+
}()
130+
125131
// Set the default HTTP transport
126132
xhttp.SetDefaultTransport(xhttp.NewTransport(xhttp.Options{
127133
Insecure: cliOptions.Insecure,
@@ -171,8 +177,10 @@ func (r *runner) Close(ctx context.Context) error {
171177
}
172178
}
173179

174-
if err := r.module.Close(ctx); err != nil {
175-
errs = multierror.Append(errs, err)
180+
if r.module != nil {
181+
if err := r.module.Close(ctx); err != nil {
182+
errs = multierror.Append(errs, err)
183+
}
176184
}
177185

178186
// silently check if there is notifications

0 commit comments

Comments
 (0)