github.com/click2cloud/libcompose@v0.4.1-0.20170816121048-7c20f79ac6b9/project/project_containers.go (about)

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