aboutsummaryrefslogtreecommitdiff
path: root/cmd/podman/networks/connect.go
blob: b0eece06c2e90fcee1299a7e08ca1af4386b83b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package network

import (
	"net"

	"github.com/containers/common/libnetwork/types"
	"github.com/containers/common/pkg/completion"
	"github.com/containers/podman/v3/cmd/podman/common"
	"github.com/containers/podman/v3/cmd/podman/registry"
	"github.com/containers/podman/v3/pkg/domain/entities"
	"github.com/spf13/cobra"
)

var (
	networkConnectDescription = `Add container to a network`
	networkConnectCommand     = &cobra.Command{
		Use:               "connect [options] NETWORK CONTAINER",
		Short:             "network connect",
		Long:              networkConnectDescription,
		RunE:              networkConnect,
		Example:           `podman network connect web secondary`,
		Args:              cobra.ExactArgs(2),
		ValidArgsFunction: common.AutocompleteNetworkConnectCmd,
	}
)

var (
	networkConnectOptions entities.NetworkConnectOptions
	ipv4                  net.IP
	ipv6                  net.IP
	macAddress            string
)

func networkConnectFlags(cmd *cobra.Command) {
	flags := cmd.Flags()
	aliasFlagName := "alias"
	flags.StringSliceVar(&networkConnectOptions.Aliases, aliasFlagName, nil, "network scoped alias for container")
	_ = cmd.RegisterFlagCompletionFunc(aliasFlagName, completion.AutocompleteNone)

	ipAddressFlagName := "ip"
	flags.IPVar(&ipv4, ipAddressFlagName, nil, "set a static ipv4 address for this container network")
	_ = cmd.RegisterFlagCompletionFunc(ipAddressFlagName, completion.AutocompleteNone)

	ipv6AddressFlagName := "ip6"
	flags.IPVar(&ipv6, ipv6AddressFlagName, nil, "set a static ipv6 address for this container network")
	_ = cmd.RegisterFlagCompletionFunc(ipv6AddressFlagName, completion.AutocompleteNone)

	macAddressFlagName := "mac-address"
	flags.StringVar(&macAddress, macAddressFlagName, "", "set a static mac address for this container network")
	_ = cmd.RegisterFlagCompletionFunc(macAddressFlagName, completion.AutocompleteNone)
}

func init() {
	registry.Commands = append(registry.Commands, registry.CliCommand{
		Command: networkConnectCommand,
		Parent:  networkCmd,
	})
	networkConnectFlags(networkConnectCommand)
}

func networkConnect(cmd *cobra.Command, args []string) error {
	networkConnectOptions.Container = args[1]
	if macAddress != "" {
		mac, err := net.ParseMAC(macAddress)
		if err != nil {
			return err
		}
		networkConnectOptions.StaticMAC = types.HardwareAddr(mac)
	}
	for _, ip := range []net.IP{ipv4, ipv6} {
		if ip != nil {
			networkConnectOptions.StaticIPs = append(networkConnectOptions.StaticIPs, ip)
		}
	}

	return registry.ContainerEngine().NetworkConnect(registry.Context(), args[0], networkConnectOptions)
}