github.com/ojongerius/docker@v1.11.2/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.RWMutex
     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.RLock()
    29  	res := c.s[id]
    30  	c.RUnlock()
    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 := History(c.all())
    45  	containers.sort()
    46  	return containers
    47  }
    48  
    49  // Size returns the number of containers in the store.
    50  func (c *memoryStore) Size() int {
    51  	c.RLock()
    52  	defer c.RUnlock()
    53  	return len(c.s)
    54  }
    55  
    56  // First returns the first container found in the store by a given filter.
    57  func (c *memoryStore) First(filter StoreFilter) *Container {
    58  	for _, cont := range c.all() {
    59  		if filter(cont) {
    60  			return cont
    61  		}
    62  	}
    63  	return nil
    64  }
    65  
    66  // ApplyAll calls the reducer function with every container in the store.
    67  // This operation is asyncronous in the memory store.
    68  // NOTE: Modifications to the store MUST NOT be done by the StoreReducer.
    69  func (c *memoryStore) ApplyAll(apply StoreReducer) {
    70  	wg := new(sync.WaitGroup)
    71  	for _, cont := range c.all() {
    72  		wg.Add(1)
    73  		go func(container *Container) {
    74  			apply(container)
    75  			wg.Done()
    76  		}(cont)
    77  	}
    78  
    79  	wg.Wait()
    80  }
    81  
    82  func (c *memoryStore) all() []*Container {
    83  	c.RLock()
    84  	containers := make([]*Container, 0, len(c.s))
    85  	for _, cont := range c.s {
    86  		containers = append(containers, cont)
    87  	}
    88  	c.RUnlock()
    89  	return containers
    90  }
    91  
    92  var _ Store = &memoryStore{}