Skip to content

Commit

Permalink
client/v3: fix open file memory leak
Browse files Browse the repository at this point in the history
- reference: etcd-io#18085
- defer close and catch errors if unsuccessful

Signed-off-by: vivekpatani <9080894+vivekpatani@users.noreply.github.com>
  • Loading branch information
vivekpatani committed Jun 18, 2024
1 parent 9cff960 commit 33c6db6
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions client/v3/snapshot/v3_snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,29 @@ func SaveWithVersion(ctx context.Context, lg *zap.Logger, cfg clientv3.Config, d
if err != nil {
return "", err
}
defer cli.Close()
defer func(cli *clientv3.Client) {
err = cli.Close()
if err != nil {
lg.Error("failed to close etcd client", zap.Error(err))
}
}(cli)

partpath := dbPath + ".part"
defer os.RemoveAll(partpath)
defer func(path string) {
err = os.RemoveAll(path)
if err != nil {
lg.Error("failed to remove path", zap.String("path", path), zap.Error(err))
}
}(partpath)

var f *os.File
f, err = os.OpenFile(partpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileutil.PrivateFileMode)
defer func(f *os.File) {
err = f.Close()
if err != nil {
lg.Error("failed to close file", zap.Error(err))
}
}(f)
if err != nil {
return "", fmt.Errorf("could not open %s (%v)", partpath, err)
}
Expand All @@ -84,9 +100,6 @@ func SaveWithVersion(ctx context.Context, lg *zap.Logger, cfg clientv3.Config, d
if err = fileutil.Fsync(f); err != nil {
return resp.Version, err
}
if err = f.Close(); err != nil {
return resp.Version, err
}
lg.Info("fetched snapshot",
zap.String("endpoint", cfg.Endpoints[0]),
zap.String("size", humanize.Bytes(uint64(size))),
Expand Down

0 comments on commit 33c6db6

Please sign in to comment.