Browse code

Cleanup docker tmp dir on start

Signed-off-by: Kenfe-Mickael Laventure <mickael.laventure@gmail.com>

Kenfe-Mickael Laventure authored on 2017/03/11 02:47:25
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
 	}
... ...
@@ -922,12 +922,29 @@ func (daemon *Daemon) GetRemappedUIDGID() (int, int) {
922 922
 	return uid, gid
923 923
 }
924 924
 
925
-// tempDir returns the default directory to use for temporary files.
926
-func tempDir(rootDir string, rootUID, rootGID int) (string, error) {
925
+// prepareTempDir prepares and returns the default directory to use
926
+// for temporary files.
927
+// If it doesn't exist, it is created. If it exists, its content is removed.
928
+func prepareTempDir(rootDir string, rootUID, rootGID int) (string, error) {
927 929
 	var tmpDir string
928 930
 	if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
929 931
 		tmpDir = filepath.Join(rootDir, "tmp")
932
+		newName := tmpDir + "-old"
933
+		if err := os.Rename(tmpDir, newName); err != nil {
934
+			go func() {
935
+				if err := os.RemoveAll(newName); err != nil {
936
+					logrus.Warnf("failed to delete old tmp directory: %s", newName)
937
+				}
938
+			}()
939
+		} else {
940
+			logrus.Warnf("failed to rename %s for background deletion: %s. Deleting synchronously", tmpDir, err)
941
+			if err := os.RemoveAll(tmpDir); err != nil {
942
+				logrus.Warnf("failed to delete old tmp directory: %s", tmpDir)
943
+			}
944
+		}
930 945
 	}
946
+	// We don't remove the content of tmpdir if it's not the default,
947
+	// it may hold things that do not belong to us.
931 948
 	return tmpDir, idtools.MkdirAllAs(tmpDir, 0700, rootUID, rootGID)
932 949
 }
933 950