Browse code

Merge pull request #31741 from mlaventure/cleanup-tmp-on-start

Cleanup docker tmp dir on start

Sebastiaan van Stijn authored on 2017/03/30 10:14:55
Showing 1 changed files
... ...
@@ -505,7 +505,7 @@ func NewDaemon(config *config.Config, registryService registry.Service, containe
505 505
 	}
506 506
 
507 507
 	// set up the tmpDir to use a canonical path
508
-	tmp, err := tempDir(config.Root, rootUID, rootGID)
508
+	tmp, err := prepareTempDir(config.Root, rootUID, rootGID)
509 509
 	if err != nil {
510 510
 		return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
511 511
 	}
... ...
@@ -924,12 +924,29 @@ func (daemon *Daemon) GetRemappedUIDGID() (int, int) {
924 924
 	return uid, gid
925 925
 }
926 926
 
927
-// tempDir returns the default directory to use for temporary files.
928
-func tempDir(rootDir string, rootUID, rootGID int) (string, error) {
927
+// prepareTempDir prepares and returns the default directory to use
928
+// for temporary files.
929
+// If it doesn't exist, it is created. If it exists, its content is removed.
930
+func prepareTempDir(rootDir string, rootUID, rootGID int) (string, error) {
929 931
 	var tmpDir string
930 932
 	if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
931 933
 		tmpDir = filepath.Join(rootDir, "tmp")
934
+		newName := tmpDir + "-old"
935
+		if err := os.Rename(tmpDir, newName); err != nil {
936
+			go func() {
937
+				if err := os.RemoveAll(newName); err != nil {
938
+					logrus.Warnf("failed to delete old tmp directory: %s", newName)
939
+				}
940
+			}()
941
+		} else {
942
+			logrus.Warnf("failed to rename %s for background deletion: %s. Deleting synchronously", tmpDir, err)
943
+			if err := os.RemoveAll(tmpDir); err != nil {
944
+				logrus.Warnf("failed to delete old tmp directory: %s", tmpDir)
945
+			}
946
+		}
932 947
 	}
948
+	// We don't remove the content of tmpdir if it's not the default,
949
+	// it may hold things that do not belong to us.
933 950
 	return tmpDir, idtools.MkdirAllAs(tmpDir, 0700, rootUID, rootGID)
934 951
 }
935 952