Merge pull request #28034 from krousey/kubeconfig_filelock

Automatic merge from submit-queue

Adding lock files for kubeconfig updating

This is to prevent concurrent executions from corrupting the kubeconfig file. 

Also, release note?

#23964
This commit is contained in:
k8s-merge-robot 2016-06-24 14:37:50 -07:00 committed by GitHub
commit cd422ada25
2 changed files with 42 additions and 0 deletions

View File

@ -381,12 +381,38 @@ func WriteToFile(config clientcmdapi.Config, filename string) error {
return err
}
}
err = lockFile(filename)
if err != nil {
return err
}
defer unlockFile(filename)
if err := ioutil.WriteFile(filename, content, 0600); err != nil {
return err
}
return nil
}
func lockFile(filename string) error {
// TODO: find a way to do this with actual file locks. Will
// probably need seperate solution for windows and linux.
f, err := os.OpenFile(lockName(filename), os.O_CREATE|os.O_EXCL, 0)
if err != nil {
return err
}
f.Close()
return nil
}
func unlockFile(filename string) error {
return os.Remove(lockName(filename))
}
func lockName(filename string) string {
return filename + ".lock"
}
// Write serializes the config to yaml.
// Encapsulates serialization without assuming the destination is a file.
func Write(config clientcmdapi.Config) ([]byte, error) {

View File

@ -376,6 +376,22 @@ func TestMigratingFileSourceMissingSkip(t *testing.T) {
}
}
func TestFileLocking(t *testing.T) {
f, _ := ioutil.TempFile("", "")
defer os.Remove(f.Name())
err := lockFile(f.Name())
if err != nil {
t.Errorf("unexpected error while locking file: %v", err)
}
defer unlockFile(f.Name())
err = lockFile(f.Name())
if err == nil {
t.Error("expected error while locking file.")
}
}
func Example_noMergingOnExplicitPaths() {
commandLineFile, _ := ioutil.TempFile("", "")
defer os.Remove(commandLineFile.Name())