github.com/containerd/nerdctl@v1.7.7/pkg/composer/orphans.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/nerdctl/pkg/composer/serviceparser" 25 "github.com/containerd/nerdctl/pkg/labels" 26 ) 27 28 func (c *Composer) getOrphanContainers(ctx context.Context, parsedServices []*serviceparser.Service) ([]containerd.Container, error) { 29 // get all running containers for project 30 var filters = []string{fmt.Sprintf("labels.%q==%s", labels.ComposeProject, c.project.Name)} 31 containers, err := c.client.Containers(ctx, filters...) 32 if err != nil { 33 return nil, err 34 } 35 36 parsedSvcNames := make(map[string]bool) 37 for _, svc := range parsedServices { 38 parsedSvcNames[svc.Unparsed.Name] = true 39 } 40 41 var orphanContainers []containerd.Container 42 for _, container := range containers { 43 // orphan containers doesn't have a `ComposeService` label corresponding 44 // to any name of given services. 45 containerLabels, err := container.Labels(ctx) 46 if err != nil { 47 return nil, fmt.Errorf("error getting container labels: %s", err) 48 } 49 containerSvc := containerLabels[labels.ComposeService] 50 if inServices := parsedSvcNames[containerSvc]; !inServices { 51 orphanContainers = append(orphanContainers, container) 52 } 53 } 54 55 return orphanContainers, nil 56 }