github.com/lalkh/containerd@v1.4.3/mount/temp.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package mount 18 19 import ( 20 "context" 21 "io/ioutil" 22 "os" 23 24 "github.com/containerd/containerd/log" 25 "github.com/pkg/errors" 26 ) 27 28 var tempMountLocation = getTempDir() 29 30 // WithTempMount mounts the provided mounts to a temp dir, and pass the temp dir to f. 31 // The mounts are valid during the call to the f. 32 // Finally we will unmount and remove the temp dir regardless of the result of f. 33 func WithTempMount(ctx context.Context, mounts []Mount, f func(root string) error) (err error) { 34 root, uerr := ioutil.TempDir(tempMountLocation, "containerd-mount") 35 if uerr != nil { 36 return errors.Wrapf(uerr, "failed to create temp dir") 37 } 38 // We use Remove here instead of RemoveAll. 39 // The RemoveAll will delete the temp dir and all children it contains. 40 // When the Unmount fails, RemoveAll will incorrectly delete data from 41 // the mounted dir. However, if we use Remove, even though we won't 42 // successfully delete the temp dir and it may leak, we won't loss data 43 // from the mounted dir. 44 // For details, please refer to #1868 #1785. 45 defer func() { 46 if uerr = os.Remove(root); uerr != nil { 47 log.G(ctx).WithError(uerr).WithField("dir", root).Errorf("failed to remove mount temp dir") 48 } 49 }() 50 51 // We should do defer first, if not we will not do Unmount when only a part of Mounts are failed. 52 defer func() { 53 if uerr = UnmountAll(root, 0); uerr != nil { 54 uerr = errors.Wrapf(uerr, "failed to unmount %s", root) 55 if err == nil { 56 err = uerr 57 } else { 58 err = errors.Wrap(err, uerr.Error()) 59 } 60 } 61 }() 62 if uerr = All(mounts, root); uerr != nil { 63 return errors.Wrapf(uerr, "failed to mount %s", root) 64 } 65 return errors.Wrapf(f(root), "mount callback failed on %s", root) 66 } 67 68 func getTempDir() string { 69 if xdg := os.Getenv("XDG_RUNTIME_DIR"); xdg != "" { 70 return xdg 71 } 72 return os.TempDir() 73 }