Skip to content

Commit

Permalink
Fix potential race in volume creation
Browse files Browse the repository at this point in the history
Docker-DCO-1.1-Signed-off-by: Brian Goff <cpuguy83@gmail.com> (github: cpuguy83)
  • Loading branch information
cpuguy83 committed Sep 29, 2014
1 parent 2682393 commit 8d7c7bd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
11 changes: 4 additions & 7 deletions daemon/volumes.go
Expand Up @@ -111,12 +111,9 @@ func (container *Container) parseVolumeMountConfig() (map[string]*Mount, error)
return nil, err
}
// Check if a volume already exists for this and use it
vol := container.daemon.volumes.Get(path)
if vol == nil {
vol, err = container.daemon.volumes.NewVolume(path, writable)
if err != nil {
return nil, err
}
vol, err := container.daemon.volumes.FindOrCreateVolume(path, writable)
if err != nil {
return nil, err
}
mounts[mountToPath] = &Mount{container: container, volume: vol, MountToPath: mountToPath, Writable: writable}
}
Expand All @@ -128,7 +125,7 @@ func (container *Container) parseVolumeMountConfig() (map[string]*Mount, error)
continue
}

vol, err := container.daemon.volumes.NewVolume("", true)
vol, err := container.daemon.volumes.FindOrCreateVolume("", true)
if err != nil {
return nil, err
}
Expand Down
27 changes: 22 additions & 5 deletions volumes/repository.go
Expand Up @@ -38,7 +38,7 @@ func NewRepository(configPath string, driver graphdriver.Driver) (*Repository, e
return repo, repo.restore()
}

func (r *Repository) NewVolume(path string, writable bool) (*Volume, error) {
func (r *Repository) newVolume(path string, writable bool) (*Volume, error) {
var (
isBindMount bool
err error
Expand Down Expand Up @@ -73,10 +73,8 @@ func (r *Repository) NewVolume(path string, writable bool) (*Volume, error) {
if err := v.initialize(); err != nil {
return nil, err
}
if err := r.Add(v); err != nil {
return nil, err
}
return v, nil

return v, r.add(v)
}

func (r *Repository) restore() error {
Expand Down Expand Up @@ -113,6 +111,10 @@ func (r *Repository) get(path string) *Volume {
func (r *Repository) Add(volume *Volume) error {
r.lock.Lock()
defer r.lock.Unlock()
return r.add(volume)
}

func (r *Repository) add(volume *Volume) error {
if vol := r.get(volume.Path); vol != nil {
return fmt.Errorf("Volume exists: %s", volume.ID)
}
Expand Down Expand Up @@ -175,3 +177,18 @@ func (r *Repository) createNewVolumePath(id string) (string, error) {

return path, nil
}

func (r *Repository) FindOrCreateVolume(path string, writable bool) (*Volume, error) {
r.lock.Lock()
defer r.lock.Unlock()

if path == "" {
return r.newVolume(path, writable)
}

if v := r.get(path); v != nil {
return v, nil
}

return r.newVolume(path, writable)
}

0 comments on commit 8d7c7bd

Please sign in to comment.