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