github.com/containers/libpod@v1.9.4-0.20220419124438-4284fd425507/pkg/domain/infra/tunnel/helpers.go (about)

     1  package tunnel
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  
     7  	"github.com/containers/libpod/libpod/define"
     8  	"github.com/containers/libpod/pkg/bindings"
     9  	"github.com/containers/libpod/pkg/bindings/containers"
    10  	"github.com/containers/libpod/pkg/bindings/pods"
    11  	"github.com/containers/libpod/pkg/domain/entities"
    12  	"github.com/containers/libpod/pkg/util"
    13  	"github.com/pkg/errors"
    14  )
    15  
    16  func getContainersByContext(contextWithConnection context.Context, all bool, namesOrIds []string) ([]entities.ListContainer, error) {
    17  	var (
    18  		cons []entities.ListContainer
    19  	)
    20  	if all && len(namesOrIds) > 0 {
    21  		return nil, errors.New("cannot lookup containers and all")
    22  	}
    23  	c, err := containers.List(contextWithConnection, nil, &bindings.PTrue, nil, nil, nil, &bindings.PTrue)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	if all {
    28  		return c, err
    29  	}
    30  	for _, id := range namesOrIds {
    31  		var found bool
    32  		for _, con := range c {
    33  			if id == con.ID || strings.HasPrefix(con.ID, id) || util.StringInSlice(id, con.Names) {
    34  				cons = append(cons, con)
    35  				found = true
    36  				break
    37  			}
    38  		}
    39  		if !found {
    40  			return nil, errors.Errorf("unable to find container %q", id)
    41  		}
    42  	}
    43  	return cons, nil
    44  }
    45  
    46  func getPodsByContext(contextWithConnection context.Context, all bool, namesOrIds []string) ([]*entities.ListPodsReport, error) {
    47  	var (
    48  		sPods []*entities.ListPodsReport
    49  	)
    50  	if all && len(namesOrIds) > 0 {
    51  		return nil, errors.New("cannot lookup specific pods and all")
    52  	}
    53  
    54  	fPods, err := pods.List(contextWithConnection, nil)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  	if all {
    59  		return fPods, nil
    60  	}
    61  	for _, nameOrId := range namesOrIds {
    62  		var found bool
    63  		for _, f := range fPods {
    64  			if f.Name == nameOrId || strings.HasPrefix(f.Id, nameOrId) {
    65  				sPods = append(sPods, f)
    66  				found = true
    67  				break
    68  			}
    69  		}
    70  		if !found {
    71  			return nil, errors.Wrapf(define.ErrNoSuchPod, "unable to find pod %q", nameOrId)
    72  		}
    73  	}
    74  	return sPods, nil
    75  }