memory_store.go 2.0 KB

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