k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/cmd/kubeadm/app/util/copy.go (about) 1 /* 2 Copyright 2023 The Kubernetes 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 util 18 19 import ( 20 "io" 21 "os" 22 "strings" 23 24 "github.com/pkg/errors" 25 26 "k8s.io/klog/v2" 27 ) 28 29 // CopyFile copies a file from src to dest. 30 func CopyFile(src, dest string) error { 31 sourceFileInfo, err := os.Stat(src) 32 if err != nil { 33 return err 34 } 35 36 sourceFile, err := os.Open(src) 37 if err != nil { 38 return err 39 } 40 defer func() { 41 _ = sourceFile.Close() 42 }() 43 44 destFile, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, sourceFileInfo.Mode()) 45 if err != nil { 46 return err 47 } 48 defer func() { 49 _ = destFile.Close() 50 }() 51 52 _, err = io.Copy(destFile, sourceFile) 53 54 return err 55 } 56 57 // MoveFile moves a file from src to dest. 58 func MoveFile(src, dest string) error { 59 err := os.Rename(src, dest) 60 if err != nil && strings.Contains(err.Error(), "invalid cross-device link") { 61 // When calling os.Rename(), an "invalid cross-device link" error may occur 62 // if the source and destination files are on different file systems. 63 // In this case, the file is moved by copying and then deleting the source file, 64 // although it is less efficient than os.Rename(). 65 klog.V(4).Infof("cannot rename %v to %v due to %v, attempting an alternative method", src, dest, err) 66 if err := CopyFile(src, dest); err != nil { 67 return errors.Wrapf(err, "failed to copy file %v to %v", src, dest) 68 } 69 return os.Remove(src) 70 } 71 return err 72 }