github.com/justincormack/cli@v0.0.0-20201215022714-831ebeae9675/cli/command/network/connect.go (about) 1 package network 2 3 import ( 4 "context" 5 "fmt" 6 "strings" 7 8 "github.com/docker/cli/cli" 9 "github.com/docker/cli/cli/command" 10 "github.com/docker/cli/opts" 11 "github.com/docker/docker/api/types/network" 12 "github.com/spf13/cobra" 13 ) 14 15 type connectOptions struct { 16 network string 17 container string 18 ipaddress string 19 ipv6address string 20 links opts.ListOpts 21 aliases []string 22 linklocalips []string 23 driverOpts []string 24 } 25 26 func newConnectCommand(dockerCli command.Cli) *cobra.Command { 27 options := connectOptions{ 28 links: opts.NewListOpts(opts.ValidateLink), 29 } 30 31 cmd := &cobra.Command{ 32 Use: "connect [OPTIONS] NETWORK CONTAINER", 33 Short: "Connect a container to a network", 34 Args: cli.ExactArgs(2), 35 RunE: func(cmd *cobra.Command, args []string) error { 36 options.network = args[0] 37 options.container = args[1] 38 return runConnect(dockerCli, options) 39 }, 40 } 41 42 flags := cmd.Flags() 43 flags.StringVar(&options.ipaddress, "ip", "", "IPv4 address (e.g., 172.30.100.104)") 44 flags.StringVar(&options.ipv6address, "ip6", "", "IPv6 address (e.g., 2001:db8::33)") 45 flags.Var(&options.links, "link", "Add link to another container") 46 flags.StringSliceVar(&options.aliases, "alias", []string{}, "Add network-scoped alias for the container") 47 flags.StringSliceVar(&options.linklocalips, "link-local-ip", []string{}, "Add a link-local address for the container") 48 flags.StringSliceVar(&options.driverOpts, "driver-opt", []string{}, "driver options for the network") 49 return cmd 50 } 51 52 func runConnect(dockerCli command.Cli, options connectOptions) error { 53 client := dockerCli.Client() 54 55 driverOpts, err := convertDriverOpt(options.driverOpts) 56 if err != nil { 57 return err 58 } 59 epConfig := &network.EndpointSettings{ 60 IPAMConfig: &network.EndpointIPAMConfig{ 61 IPv4Address: options.ipaddress, 62 IPv6Address: options.ipv6address, 63 LinkLocalIPs: options.linklocalips, 64 }, 65 Links: options.links.GetAll(), 66 Aliases: options.aliases, 67 DriverOpts: driverOpts, 68 } 69 70 return client.NetworkConnect(context.Background(), options.network, options.container, epConfig) 71 } 72 73 func convertDriverOpt(opts []string) (map[string]string, error) { 74 driverOpt := make(map[string]string) 75 for _, opt := range opts { 76 parts := strings.SplitN(opt, "=", 2) 77 if len(parts) != 2 { 78 return nil, fmt.Errorf("invalid key/value pair format in driver options") 79 } 80 key := strings.TrimSpace(parts[0]) 81 value := strings.TrimSpace(parts[1]) 82 driverOpt[key] = value 83 } 84 return driverOpt, nil 85 }