github.com/containerd/nerdctl@v1.7.7/pkg/composer/container.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package composer 18 19 import ( 20 "context" 21 "fmt" 22 23 "github.com/containerd/containerd" 24 "github.com/containerd/log" 25 "github.com/containerd/nerdctl/pkg/labels" 26 ) 27 28 func (c *Composer) Containers(ctx context.Context, services ...string) ([]containerd.Container, error) { 29 projectLabel := fmt.Sprintf("labels.%q==%s", labels.ComposeProject, c.project.Name) 30 filters := []string{} 31 for _, service := range services { 32 filters = append(filters, fmt.Sprintf("%s,labels.%q==%s", projectLabel, labels.ComposeService, service)) 33 } 34 if len(services) == 0 { 35 filters = append(filters, projectLabel) 36 } 37 log.G(ctx).Debugf("filters: %v", filters) 38 containers, err := c.client.Containers(ctx, filters...) 39 if err != nil { 40 return nil, err 41 } 42 return containers, nil 43 } 44 45 func (c *Composer) containerExists(ctx context.Context, name, service string) (bool, error) { 46 // get list of containers for service 47 containers, err := c.Containers(ctx, service) 48 if err != nil { 49 return false, err 50 } 51 52 for _, container := range containers { 53 containerLabels, err := container.Labels(ctx) 54 if err != nil { 55 return false, err 56 } 57 if name == containerLabels[labels.Name] { 58 // container exists 59 return true, nil 60 } 61 } 62 // container doesn't exist 63 return false, nil 64 }