github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/cmd/swarmctl/network/common.go (about)

     1  package network
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/docker/swarmkit/api"
     8  )
     9  
    10  // GetNetwork tries to query for a network as an ID and if it can't be
    11  // found tries to query as a name. If the name query returns exactly
    12  // one entry then it is returned to the caller. Otherwise an error is
    13  // returned.
    14  func GetNetwork(ctx context.Context, c api.ControlClient, input string) (*api.Network, error) {
    15  	// GetService to match via full ID.
    16  	rg, err := c.GetNetwork(ctx, &api.GetNetworkRequest{NetworkID: input})
    17  	if err != nil {
    18  		// If any error (including NotFound), ListServices to match via full name.
    19  		rl, err := c.ListNetworks(ctx,
    20  			&api.ListNetworksRequest{
    21  				Filters: &api.ListNetworksRequest_Filters{
    22  					Names: []string{input},
    23  				},
    24  			},
    25  		)
    26  		if err != nil {
    27  			return nil, err
    28  		}
    29  
    30  		if len(rl.Networks) == 0 {
    31  			return nil, fmt.Errorf("network %s not found", input)
    32  		}
    33  
    34  		if l := len(rl.Networks); l > 1 {
    35  			return nil, fmt.Errorf("network %s is ambiguous (%d matches found)", input, l)
    36  		}
    37  
    38  		return rl.Networks[0], nil
    39  	}
    40  
    41  	return rg.Network, nil
    42  }
    43  
    44  // ResolveServiceNetworks takes a service spec and resolves network names to network IDs.
    45  func ResolveServiceNetworks(ctx context.Context, c api.ControlClient, spec *api.ServiceSpec) error {
    46  	if len(spec.Task.Networks) == 0 {
    47  		return nil
    48  	}
    49  	networks := make([]*api.NetworkAttachmentConfig, 0, len(spec.Task.Networks))
    50  	for _, na := range spec.Task.Networks {
    51  		n, err := GetNetwork(ctx, c, na.Target)
    52  		if err != nil {
    53  			return err
    54  		}
    55  
    56  		networks = append(networks, &api.NetworkAttachmentConfig{
    57  			Target: n.ID,
    58  		})
    59  	}
    60  
    61  	spec.Task.Networks = networks
    62  	return nil
    63  }