From 9c451ad0f2afdb598110539aac9f731a36deb6cf Mon Sep 17 00:00:00 2001 From: Kenfe-Mickael Laventure Date: Fri, 10 Mar 2017 09:47:25 -0800 Subject: [PATCH] Cleanup docker tmp dir on start Signed-off-by: Kenfe-Mickael Laventure --- daemon/daemon.go | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/daemon/daemon.go b/daemon/daemon.go index 4ecd2fa50a..922b21cf4c 100644 --- a/daemon/daemon.go +++ b/daemon/daemon.go @@ -505,7 +505,7 @@ func NewDaemon(config *config.Config, registryService registry.Service, containe } // set up the tmpDir to use a canonical path - tmp, err := tempDir(config.Root, rootUID, rootGID) + tmp, err := prepareTempDir(config.Root, rootUID, rootGID) if err != nil { return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err) } @@ -922,12 +922,29 @@ func (daemon *Daemon) GetRemappedUIDGID() (int, int) { return uid, gid } -// tempDir returns the default directory to use for temporary files. -func tempDir(rootDir string, rootUID, rootGID int) (string, error) { +// prepareTempDir prepares and returns the default directory to use +// for temporary files. +// If it doesn't exist, it is created. If it exists, its content is removed. +func prepareTempDir(rootDir string, rootUID, rootGID int) (string, error) { var tmpDir string if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" { tmpDir = filepath.Join(rootDir, "tmp") + newName := tmpDir + "-old" + if err := os.Rename(tmpDir, newName); err != nil { + go func() { + if err := os.RemoveAll(newName); err != nil { + logrus.Warnf("failed to delete old tmp directory: %s", newName) + } + }() + } else { + logrus.Warnf("failed to rename %s for background deletion: %s. Deleting synchronously", tmpDir, err) + if err := os.RemoveAll(tmpDir); err != nil { + logrus.Warnf("failed to delete old tmp directory: %s", tmpDir) + } + } } + // We don't remove the content of tmpdir if it's not the default, + // it may hold things that do not belong to us. return tmpDir, idtools.MkdirAllAs(tmpDir, 0700, rootUID, rootGID) }