Skip to content

Commit

Permalink
Make it multiple goroutines friendly
Browse files Browse the repository at this point in the history
  • Loading branch information
xetorthio committed Aug 3, 2017
1 parent 3906bd3 commit defe855
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions docker/local_cached_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,17 @@ import (

type localCachedFactory struct {
rw sync.Mutex
irw sync.Mutex
sessionClient DockerApi
instanceClients map[string]DockerApi
instanceClients map[string]*instanceEntry
storage storage.StorageApi
}

type instanceEntry struct {
rw sync.Mutex
client DockerApi
}

func (f *localCachedFactory) GetForSession(sessionId string) (DockerApi, error) {
f.rw.Lock()
defer f.rw.Unlock()
Expand All @@ -46,12 +52,22 @@ func (f *localCachedFactory) GetForSession(sessionId string) (DockerApi, error)
}

func (f *localCachedFactory) GetForInstance(sessionId, instanceName string) (DockerApi, error) {
f.rw.Lock()
defer f.rw.Unlock()
key := sessionId + instanceName

f.irw.Lock()
c, found := f.instanceClients[key]
if !found {
c := &instanceEntry{}
f.instanceClients[key] = c
}
c = f.instanceClients[key]
f.irw.Unlock()

c.rw.Lock()
defer c.rw.Unlock()

c, found := f.instanceClients[sessionId+instanceName]
if found {
return c, nil
if c.client != nil {
return c.client, nil
}

instance, err := f.storage.InstanceGet(sessionId, instanceName)
Expand Down Expand Up @@ -91,7 +107,7 @@ func (f *localCachedFactory) GetForInstance(sessionId, instanceName string) (Doc
return nil, err
}
dockerClient := NewDocker(dc)
f.instanceClients[sessionId+instance.Name] = dockerClient
c.client = dockerClient

return dockerClient, nil
}
Expand Down Expand Up @@ -120,7 +136,7 @@ func (f *localCachedFactory) check(c *client.Client) error {

func NewLocalCachedFactory(s storage.StorageApi) *localCachedFactory {
return &localCachedFactory{
instanceClients: make(map[string]DockerApi),
instanceClients: make(map[string]*instanceEntry),
storage: s,
}
}

0 comments on commit defe855

Please sign in to comment.