Skip to content

Commit

Permalink
add defer file.Close to avoid potential fd leak
Browse files Browse the repository at this point in the history
Signed-off-by: allencloud <allen.sun@daocloud.io>
  • Loading branch information
allencloud committed Aug 10, 2016
1 parent 2684459 commit 0ead624
Show file tree
Hide file tree
Showing 25 changed files with 91 additions and 24 deletions.
1 change: 1 addition & 0 deletions api/client/image/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ func runBuild(dockerCli *client.DockerCli, options buildOptions) error {
if err != nil && !os.IsNotExist(err) {
return err
}
defer f.Close()

var excludes []string
if err == nil {
Expand Down
4 changes: 3 additions & 1 deletion builder/dockerfile/internals.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,9 @@ func (b *Builder) download(srcURL string) (fi builder.FileInfo, err error) {
// ignoring error because the file was already opened successfully
tmpFileSt, err := tmpFile.Stat()
if err != nil {
tmpFile.Close()
return
}
tmpFile.Close()

// Set the mtime to the Last-Modified header value if present
// Otherwise just remove atime and mtime
Expand All @@ -272,6 +272,8 @@ func (b *Builder) download(srcURL string) (fi builder.FileInfo, err error) {
}
}

tmpFile.Close()

if err = system.Chtimes(tmpFileName, mTime, mTime); err != nil {
return
}
Expand Down
1 change: 1 addition & 0 deletions builder/dockerfile/parser/dumper/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func main() {
if err != nil {
panic(err)
}
defer f.Close()

d := parser.Directive{LookingForDirectives: true}
parser.SetEscapeToken(parser.DefaultEscapeToken, &d)
Expand Down
3 changes: 1 addition & 2 deletions builder/dockerfile/parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,14 @@ func TestTestNegative(t *testing.T) {
if err != nil {
t.Fatalf("Dockerfile missing for %s: %v", dir, err)
}
defer df.Close()

d := Directive{LookingForDirectives: true}
SetEscapeToken(DefaultEscapeToken, &d)
_, err = Parse(df, &d)
if err == nil {
t.Fatalf("No error parsing broken dockerfile for %s", dir)
}

df.Close()
}
}

Expand Down
1 change: 1 addition & 0 deletions builder/dockerignore.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ func (c DockerIgnoreContext) Process(filesToRemove []string) error {
return err
}
excludes, _ := dockerignore.ReadAll(f)
f.Close()
filesToRemove = append([]string{".dockerignore"}, filesToRemove...)
for _, fileToRemove := range filesToRemove {
rm, _ := fileutils.Matches(fileToRemove, excludes)
Expand Down
4 changes: 2 additions & 2 deletions builder/dockerignore/dockerignore.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ import (
// ReadAll reads a .dockerignore file and returns the list of file patterns
// to ignore. Note this will trim whitespace from each line as well
// as use GO's "clean" func to get the shortest/cleanest path for each.
func ReadAll(reader io.ReadCloser) ([]string, error) {
func ReadAll(reader io.Reader) ([]string, error) {
if reader == nil {
return nil, nil
}
defer reader.Close()

scanner := bufio.NewScanner(reader)
var excludes []string
currentLine := 0
Expand Down
2 changes: 2 additions & 0 deletions builder/dockerignore/dockerignore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ func TestReadAll(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer diFd.Close()

di, err = ReadAll(diFd)
if err != nil {
t.Fatal(err)
Expand Down
4 changes: 4 additions & 0 deletions cliconfig/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,8 @@ func TestJsonSaveWithNoFile(t *testing.T) {

fn := filepath.Join(tmpHome, ConfigFileName)
f, _ := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
defer f.Close()

err = config.SaveToWriter(f)
if err != nil {
t.Fatalf("Failed saving to file: %q", err)
Expand Down Expand Up @@ -522,6 +524,8 @@ func TestLegacyJsonSaveWithNoFile(t *testing.T) {

fn := filepath.Join(tmpHome, ConfigFileName)
f, _ := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
defer f.Close()

if err = config.SaveToWriter(f); err != nil {
t.Fatalf("Failed saving to file: %q", err)
}
Expand Down
3 changes: 3 additions & 0 deletions daemon/logger/jsonfilelog/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ func (l *JSONFileLogger) readLogs(logWatcher *logger.LogWatcher, config logger.R
}
continue
}
defer f.Close()

files = append(files, f)
}

Expand All @@ -63,6 +65,7 @@ func (l *JSONFileLogger) readLogs(logWatcher *logger.LogWatcher, config logger.R
logWatcher.Err <- err
return
}
defer latestFile.Close()

if config.Tail != 0 {
tailer := ioutils.MultiReadSeeker(append(files, latestFile)...)
Expand Down
22 changes: 12 additions & 10 deletions image/tarexport/save.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,17 +174,18 @@ func (s *saveSession) save(outStream io.Writer) error {

if len(reposLegacy) > 0 {
reposFile := filepath.Join(tempDir, legacyRepositoriesFileName)
f, err := os.OpenFile(reposFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
rf, err := os.OpenFile(reposFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
f.Close()
return err
}
if err := json.NewEncoder(f).Encode(reposLegacy); err != nil {
return err
}
if err := f.Close(); err != nil {

if err := json.NewEncoder(rf).Encode(reposLegacy); err != nil {
rf.Close()
return err
}

rf.Close()

if err := system.Chtimes(reposFile, time.Unix(0, 0), time.Unix(0, 0)); err != nil {
return err
}
Expand All @@ -193,15 +194,16 @@ func (s *saveSession) save(outStream io.Writer) error {
manifestFileName := filepath.Join(tempDir, manifestFileName)
f, err := os.OpenFile(manifestFileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
f.Close()
return err
}

if err := json.NewEncoder(f).Encode(manifest); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}

f.Close()

if err := system.Chtimes(manifestFileName, time.Unix(0, 0), time.Unix(0, 0)); err != nil {
return err
}
Expand Down
4 changes: 4 additions & 0 deletions integration-cli/docker_cli_daemon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1151,6 +1151,8 @@ func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefault(c *check.C) {
if err != nil {
c.Fatal(err)
}
defer f.Close()

var res struct {
Log string `json:"log"`
Stream string `json:"stream"`
Expand Down Expand Up @@ -1229,6 +1231,8 @@ func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) {
if err != nil {
c.Fatal(err)
}
defer f.Close()

var res struct {
Log string `json:"log"`
Stream string `json:"stream"`
Expand Down
1 change: 1 addition & 0 deletions integration-cli/docker_cli_push_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ func testPushEmptyLayer(c *check.C) {

freader, err := os.Open(emptyTarball.Name())
c.Assert(err, check.IsNil, check.Commentf("Could not open test tarball"))
defer freader.Close()

importCmd := exec.Command(dockerBinary, "import", "-", repoName)
importCmd.Stdin = freader
Expand Down
1 change: 1 addition & 0 deletions integration-cli/docker_cli_save_load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ func (s *DockerSuite) TestSaveDirectoryPermissions(c *check.C) {

f, err := os.Open(layerPath)
c.Assert(err, checker.IsNil, check.Commentf("failed to open %s: %s", layerPath, err))
defer f.Close()

entries, err := listTar(f)
for _, e := range entries {
Expand Down
1 change: 1 addition & 0 deletions integration-cli/docker_cli_save_load_unix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ func (s *DockerSuite) TestSaveAndLoadRepoStdout(c *check.C) {

tmpFile, err = os.Open(tmpFile.Name())
c.Assert(err, check.IsNil)
defer tmpFile.Close()

deleteImages(repoName)

Expand Down
2 changes: 2 additions & 0 deletions integration-cli/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ http:
if err != nil {
return nil, err
}
defer config.Close()

if _, err := fmt.Fprintf(config, template, tmp, privateRegistryURL, authTemplate); err != nil {
os.RemoveAll(tmp)
return nil, err
Expand Down
1 change: 1 addition & 0 deletions integration-cli/requirements.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ var (

// We need extra check on redhat based distributions
if f, err := os.Open("/sys/module/user_namespace/parameters/enable"); err == nil {
defer f.Close()
b := make([]byte, 1)
_, _ = f.Read(b)
if string(b) == "N" {
Expand Down
5 changes: 3 additions & 2 deletions integration-cli/trust_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ func newTestNotary(c *check.C) (*testNotary, error) {
}
confPath := filepath.Join(tmp, "config.json")
config, err := os.Create(confPath)
defer config.Close()
if err != nil {
return nil, err
}
defer config.Close()

workingDir, err := os.Getwd()
if err != nil {
Expand All @@ -78,10 +78,11 @@ func newTestNotary(c *check.C) (*testNotary, error) {
// generate client config
clientConfPath := filepath.Join(tmp, "client-config.json")
clientConfig, err := os.Create(clientConfPath)
defer clientConfig.Close()
if err != nil {
return nil, err
}
defer clientConfig.Close()

template = `{
"trust_dir" : "%s",
"remote_server": {
Expand Down
6 changes: 4 additions & 2 deletions layer/layer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -741,18 +741,20 @@ func TestTarStreamVerification(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer src.Close()

dst, err := os.Create(filepath.Join(tmpdir, id2.Algorithm().String(), id2.Hex(), "tar-split.json.gz"))
if err != nil {
t.Fatal(err)
}
defer dst.Close()

if _, err := io.Copy(dst, src); err != nil {
t.Fatal(err)
}

src.Close()
dst.Close()
src.Sync()
dst.Sync()

ts, err := layer2.TarStream()
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions libcontainerd/remote_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,11 +216,11 @@ func (r *remote) Client(b Backend) (Client, error) {

func (r *remote) updateEventTimestamp(t time.Time) {
f, err := os.OpenFile(r.eventTsPath, syscall.O_CREAT|syscall.O_WRONLY|syscall.O_TRUNC, 0600)
defer f.Close()
if err != nil {
logrus.Warnf("libcontainerd: failed to open event timestamp file: %v", err)
return
}
defer f.Close()

b, err := t.MarshalText()
if err != nil {
Expand All @@ -245,11 +245,11 @@ func (r *remote) getLastEventTimestamp() time.Time {
}

f, err := os.Open(r.eventTsPath)
defer f.Close()
if err != nil {
logrus.Warnf("libcontainerd: Unable to access last event ts: %v", err)
return t
}
defer f.Close()

b := make([]byte, fi.Size())
n, err := f.Read(b)
Expand Down Expand Up @@ -329,10 +329,10 @@ func (r *remote) handleEventStream(events containerd.API_EventsClient) {
func (r *remote) runContainerdDaemon() error {
pidFilename := filepath.Join(r.stateDir, containerdPidFilename)
f, err := os.OpenFile(pidFilename, os.O_RDWR|os.O_CREATE, 0600)
defer f.Close()
if err != nil {
return err
}
defer f.Close()

// File exist, check if the daemon is alive
b := make([]byte, 8)
Expand Down
22 changes: 22 additions & 0 deletions pkg/archive/archive_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,11 @@ func TestDecompressStreamGzip(t *testing.T) {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
archive, err := os.Open(tmp + "archive.gz")
if err != nil {
t.Fatalf("Fail to open file archive.gz")
}
defer archive.Close()

_, err = DecompressStream(archive)
if err != nil {
t.Fatalf("Failed to decompress a gzip file.")
Expand All @@ -114,6 +119,11 @@ func TestDecompressStreamBzip2(t *testing.T) {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
archive, err := os.Open(tmp + "archive.bz2")
if err != nil {
t.Fatalf("Fail to open file archive.bz2")
}
defer archive.Close()

_, err = DecompressStream(archive)
if err != nil {
t.Fatalf("Failed to decompress a bzip2 file.")
Expand All @@ -130,6 +140,10 @@ func TestDecompressStreamXz(t *testing.T) {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
archive, err := os.Open(tmp + "archive.xz")
if err != nil {
t.Fatalf("Fail to open file archive.xz")
}
defer archive.Close()
_, err = DecompressStream(archive)
if err != nil {
t.Fatalf("Failed to decompress an xz file.")
Expand All @@ -141,6 +155,8 @@ func TestCompressStreamXzUnsuported(t *testing.T) {
if err != nil {
t.Fatalf("Fail to create the destination file")
}
defer dest.Close()

_, err = CompressStream(dest, Xz)
if err == nil {
t.Fatalf("Should fail as xz is unsupported for compression format.")
Expand All @@ -152,6 +168,8 @@ func TestCompressStreamBzip2Unsupported(t *testing.T) {
if err != nil {
t.Fatalf("Fail to create the destination file")
}
defer dest.Close()

_, err = CompressStream(dest, Xz)
if err == nil {
t.Fatalf("Should fail as xz is unsupported for compression format.")
Expand All @@ -163,6 +181,8 @@ func TestCompressStreamInvalid(t *testing.T) {
if err != nil {
t.Fatalf("Fail to create the destination file")
}
defer dest.Close()

_, err = CompressStream(dest, -1)
if err == nil {
t.Fatalf("Should fail as xz is unsupported for compression format.")
Expand Down Expand Up @@ -795,6 +815,8 @@ func TestUntarUstarGnuConflict(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer f.Close()

found := false
tr := tar.NewReader(f)
// Iterate through the files in the archive.
Expand Down
4 changes: 4 additions & 0 deletions pkg/tarsum/builder_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ func TestTarSumRemoveNonExistent(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer reader.Close()

ts, err := NewTarSum(reader, false, Version0)
if err != nil {
t.Fatal(err)
Expand Down Expand Up @@ -42,6 +44,8 @@ func TestTarSumRemove(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer reader.Close()

ts, err := NewTarSum(reader, false, Version0)
if err != nil {
t.Fatal(err)
Expand Down
Loading

0 comments on commit 0ead624

Please sign in to comment.