Skip to content

Commit

Permalink
Merge pull request kubernetes#28034 from krousey/kubeconfig_filelock
Browse files Browse the repository at this point in the history
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?

kubernetes#23964

(cherry picked from commit cd422ad)
  • Loading branch information
k8s-merge-robot authored and eparis committed Jun 29, 2016
1 parent fb1ee58 commit 905ef29
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
26 changes: 26 additions & 0 deletions pkg/client/unversioned/clientcmd/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
16 changes: 16 additions & 0 deletions pkg/client/unversioned/clientcmd/loader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down

0 comments on commit 905ef29

Please sign in to comment.