github.com/CPtung/libcompose@v0.4.3/project/project_containers.go (about)

     1  package project
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  
     7  	"golang.org/x/net/context"
     8  
     9  	"github.com/docker/libcompose/project/events"
    10  )
    11  
    12  // Containers lists the containers for the specified services. Can be filter using
    13  // the Filter struct.
    14  func (p *Project) Containers(ctx context.Context, filter Filter, services ...string) ([]string, error) {
    15  	containers := []string{}
    16  	var lock sync.Mutex
    17  
    18  	err := p.forEach(services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) {
    19  		wrapper.Do(nil, events.NoEvent, events.NoEvent, func(service Service) error {
    20  			serviceContainers, innerErr := service.Containers(ctx)
    21  			if innerErr != nil {
    22  				return innerErr
    23  			}
    24  
    25  			for _, container := range serviceContainers {
    26  				running := container.IsRunning(ctx)
    27  				switch filter.State {
    28  				case Running:
    29  					if !running {
    30  						continue
    31  					}
    32  				case Stopped:
    33  					if running {
    34  						continue
    35  					}
    36  				case AnyState:
    37  					// Don't do a thing
    38  				default:
    39  					// Invalid state filter
    40  					return fmt.Errorf("Invalid container filter: %s", filter.State)
    41  				}
    42  				containerID := container.ID()
    43  				lock.Lock()
    44  				containers = append(containers, containerID)
    45  				lock.Unlock()
    46  			}
    47  			return nil
    48  		})
    49  	}), nil)
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  	return containers, nil
    54  }