github.com/ruphin/docker@v1.10.1/container/memory_store.go (about) 1 package container 2 3 import "sync" 4 5 // memoryStore implements a Store in memory. 6 type memoryStore struct { 7 s map[string]*Container 8 sync.Mutex 9 } 10 11 // NewMemoryStore initializes a new memory store. 12 func NewMemoryStore() Store { 13 return &memoryStore{ 14 s: make(map[string]*Container), 15 } 16 } 17 18 // Add appends a new container to the memory store. 19 // It overrides the id if it existed before. 20 func (c *memoryStore) Add(id string, cont *Container) { 21 c.Lock() 22 c.s[id] = cont 23 c.Unlock() 24 } 25 26 // Get returns a container from the store by id. 27 func (c *memoryStore) Get(id string) *Container { 28 c.Lock() 29 res := c.s[id] 30 c.Unlock() 31 return res 32 } 33 34 // Delete removes a container from the store by id. 35 func (c *memoryStore) Delete(id string) { 36 c.Lock() 37 delete(c.s, id) 38 c.Unlock() 39 } 40 41 // List returns a sorted list of containers from the store. 42 // The containers are ordered by creation date. 43 func (c *memoryStore) List() []*Container { 44 containers := new(History) 45 c.Lock() 46 for _, cont := range c.s { 47 containers.Add(cont) 48 } 49 c.Unlock() 50 containers.sort() 51 return *containers 52 } 53 54 // Size returns the number of containers in the store. 55 func (c *memoryStore) Size() int { 56 c.Lock() 57 defer c.Unlock() 58 return len(c.s) 59 } 60 61 // First returns the first container found in the store by a given filter. 62 func (c *memoryStore) First(filter StoreFilter) *Container { 63 c.Lock() 64 defer c.Unlock() 65 for _, cont := range c.s { 66 if filter(cont) { 67 return cont 68 } 69 } 70 return nil 71 } 72 73 // ApplyAll calls the reducer function with every container in the store. 74 // This operation is asyncronous in the memory store. 75 func (c *memoryStore) ApplyAll(apply StoreReducer) { 76 c.Lock() 77 defer c.Unlock() 78 79 wg := new(sync.WaitGroup) 80 for _, cont := range c.s { 81 wg.Add(1) 82 go func(container *Container) { 83 apply(container) 84 wg.Done() 85 }(cont) 86 } 87 88 wg.Wait() 89 } 90 91 var _ Store = &memoryStore{}