Skip to content

Commit 199ea34

Browse files
authored
Merge pull request #9538 from priyawadhwa/network-flag
Add --network flag to select docker network to run with docker driver
2 parents 9a0be2e + e210a72 commit 199ea34

File tree

8 files changed

+131
-6
lines changed

8 files changed

+131
-6
lines changed

cmd/minikube/cmd/start_flags.go

+7
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ const (
107107
forceSystemd = "force-systemd"
108108
kicBaseImage = "base-image"
109109
ports = "ports"
110+
network = "network"
110111
startNamespace = "namespace"
111112
trace = "trace"
112113
)
@@ -152,6 +153,7 @@ func initMinikubeFlags() {
152153
startCmd.Flags().Bool(preload, true, "If set, download tarball of preloaded images if available to improve start time. Defaults to true.")
153154
startCmd.Flags().Bool(deleteOnFailure, false, "If set, delete the current cluster if start fails and try again. Defaults to false.")
154155
startCmd.Flags().Bool(forceSystemd, false, "If set, force the container runtime to use sytemd as cgroup manager. Currently available for docker and crio. Defaults to false.")
156+
startCmd.Flags().StringP(network, "", "", "network to run minikube with. Only available with the docker/podman drivers. If left empty, minikube will create a new network.")
155157
startCmd.Flags().StringVarP(&outputFormat, "output", "o", "text", "Format to print stdout in. Options include: [text,json]")
156158
startCmd.Flags().StringP(trace, "", "", "Send trace events. Options include: [gcp]")
157159
}
@@ -293,12 +295,17 @@ func generateClusterConfig(cmd *cobra.Command, existing *config.ClusterConfig, k
293295
out.WarningT("With --network-plugin=cni, you will need to provide your own CNI. See --cni flag as a user-friendly alternative")
294296
}
295297

298+
if !driver.IsKIC(drvName) && viper.GetString(network) != "" {
299+
out.WarningT("--network flag is only valid with the docker/podman drivers, it will be ignored")
300+
}
301+
296302
cc = config.ClusterConfig{
297303
Name: ClusterFlagValue(),
298304
KeepContext: viper.GetBool(keepContext),
299305
EmbedCerts: viper.GetBool(embedCerts),
300306
MinikubeISO: viper.GetString(isoURL),
301307
KicBaseImage: viper.GetString(kicBaseImage),
308+
Network: viper.GetString(network),
302309
Memory: mem,
303310
CPUs: viper.GetInt(cpus),
304311
DiskSize: diskSize,

pkg/drivers/kic/kic.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,14 @@ func (d *Driver) Create() error {
8686
APIServerPort: d.NodeConfig.APIServerPort,
8787
}
8888

89-
if gateway, err := oci.CreateNetwork(d.OCIBinary, d.NodeConfig.ClusterName); err != nil {
89+
networkName := d.NodeConfig.Network
90+
if networkName == "" {
91+
networkName = d.NodeConfig.ClusterName
92+
}
93+
if gateway, err := oci.CreateNetwork(d.OCIBinary, networkName); err != nil {
9094
out.WarningT("Unable to create dedicated network, this might result in cluster IP change after restart: {{.error}}", out.V{"error": err})
91-
} else {
92-
params.Network = d.NodeConfig.ClusterName
95+
} else if gateway != nil {
96+
params.Network = networkName
9397
ip := gateway.To4()
9498
// calculate the container IP based on guessing the machine index
9599
ip[3] += byte(driver.IndexFromMachineName(d.NodeConfig.MachineName))

pkg/drivers/kic/oci/network_create.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -44,17 +44,21 @@ const dockerDefaultBridge = "bridge"
4444
const podmanDefaultBridge = "podman"
4545

4646
// CreateNetwork creates a network returns gateway and error, minikube creates one network per cluster
47-
func CreateNetwork(ociBin string, clusterName string) (net.IP, error) {
47+
func CreateNetwork(ociBin string, networkName string) (net.IP, error) {
4848
var defaultBridgeName string
4949
if ociBin == Docker {
5050
defaultBridgeName = dockerDefaultBridge
5151
}
5252
if ociBin == Podman {
5353
defaultBridgeName = podmanDefaultBridge
5454
}
55+
if networkName == defaultBridgeName {
56+
klog.Infof("skipping creating network since default network %s was specified", networkName)
57+
return nil, nil
58+
}
5559

5660
// check if the network already exists
57-
info, err := containerNetworkInspect(ociBin, clusterName)
61+
info, err := containerNetworkInspect(ociBin, networkName)
5862
if err == nil {
5963
klog.Infof("Found existing network %+v", info)
6064
return info.gateway, nil
@@ -71,7 +75,7 @@ func CreateNetwork(ociBin string, clusterName string) (net.IP, error) {
7175
// Rather than iterate through all of the valid subnets, give up at 20 to avoid a lengthy user delay for something that is unlikely to work.
7276
// will be like 192.168.49.0/24 ,...,192.168.239.0/24
7377
for attempts < 20 {
74-
info.gateway, err = tryCreateDockerNetwork(ociBin, subnetAddr, defaultSubnetMask, info.mtu, clusterName)
78+
info.gateway, err = tryCreateDockerNetwork(ociBin, subnetAddr, defaultSubnetMask, info.mtu, networkName)
7579
if err == nil {
7680
return info.gateway, nil
7781
}

pkg/drivers/kic/types.go

+1
Original file line numberDiff line numberDiff line change
@@ -61,5 +61,6 @@ type Config struct {
6161
Envs map[string]string // key,value of environment variables passed to the node
6262
KubernetesVersion string // Kubernetes version to install
6363
ContainerRuntime string // container runtime kic is running
64+
Network string // network to run with kic
6465
ExtraArgs []string // a list of any extra option to pass to oci binary during creation time, for example --expose 8080...
6566
}

pkg/minikube/config/types.go

+1
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ type ClusterConfig struct {
7373
StartHostTimeout time.Duration
7474
ScheduledStop *ScheduledStopConfig
7575
ExposedPorts []string // Only used by the docker and podman driver
76+
Network string // only used by docker driver
7677
MultiNodeRequested bool
7778
}
7879

pkg/minikube/registry/drvs/docker/docker.go

+1
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ func configure(cc config.ClusterConfig, n config.Node) (interface{}, error) {
7979
KubernetesVersion: cc.KubernetesConfig.KubernetesVersion,
8080
ContainerRuntime: cc.KubernetesConfig.ContainerRuntime,
8181
ExtraArgs: extraArgs,
82+
Network: cc.Network,
8283
}), nil
8384
}
8485

site/content/en/docs/commands/start.md

+1
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ minikube start [flags]
7777
--namespace string The named space to activate after start (default "default")
7878
--nat-nic-type string NIC Type used for nat network. One of Am79C970A, Am79C973, 82540EM, 82543GC, 82545EM, or virtio (virtualbox driver only) (default "virtio")
7979
--native-ssh Use native Golang SSH client (default true). Set to 'false' to use the command line 'ssh' command when accessing the docker machine. Useful for the machine drivers when they will not start with 'Waiting for SSH'. (default true)
80+
--network string network to run minikube with. Only available with the docker/podman drivers. If left empty, minikube will create a new network.
8081
--network-plugin string Kubelet network plug-in to use (default: auto)
8182
--nfs-share strings Local folders to share with Guest via NFS mounts (hyperkit driver only)
8283
--nfs-shares-root string Where to root the NFS Shares, defaults to /nfsshares (hyperkit driver only) (default "/nfsshares")
+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// +build integration
2+
3+
/*
4+
Copyright 2020 The Kubernetes Authors All rights reserved.
5+
6+
Licensed under the Apache License, Version 2.0 (the "License");
7+
you may not use this file except in compliance with the License.
8+
You may obtain a copy of the License at
9+
10+
http://www.apache.org/licenses/LICENSE-2.0
11+
12+
Unless required by applicable law or agreed to in writing, software
13+
distributed under the License is distributed on an "AS IS" BASIS,
14+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
See the License for the specific language governing permissions and
16+
limitations under the License.
17+
*/
18+
19+
package integration
20+
21+
import (
22+
"context"
23+
"fmt"
24+
"os/exec"
25+
"strings"
26+
"testing"
27+
28+
"k8s.io/minikube/pkg/drivers/kic/oci"
29+
)
30+
31+
func TestKicCustomNetwork(t *testing.T) {
32+
if !KicDriver() {
33+
t.Skip("only runs with docker driver")
34+
}
35+
36+
tests := []struct {
37+
description string
38+
networkName string
39+
}{
40+
{
41+
description: "create custom network",
42+
}, {
43+
description: "use default bridge network",
44+
networkName: "bridge",
45+
},
46+
}
47+
48+
for _, test := range tests {
49+
t.Run(test.description, func(t *testing.T) {
50+
profile := UniqueProfileName("docker-network")
51+
ctx, cancel := context.WithTimeout(context.Background(), Minutes(5))
52+
defer Cleanup(t, profile, cancel)
53+
54+
startArgs := []string{"start", "-p", profile, fmt.Sprintf("--network=%s", test.networkName)}
55+
c := exec.CommandContext(ctx, Target(), startArgs...)
56+
rr, err := Run(t, c)
57+
if err != nil {
58+
t.Fatalf("%v failed: %v\n%v", rr.Command(), err, rr.Output())
59+
}
60+
nn := test.networkName
61+
if nn == "" {
62+
nn = profile
63+
}
64+
verifyNetworkExists(ctx, t, nn)
65+
})
66+
}
67+
}
68+
69+
func TestKicExistingNetwork(t *testing.T) {
70+
if !KicDriver() {
71+
t.Skip("only runs with docker driver")
72+
}
73+
// create custom network
74+
networkName := "existing-network"
75+
if _, err := oci.CreateNetwork(oci.Docker, networkName); err != nil {
76+
t.Fatalf("error creating network: %v", err)
77+
}
78+
defer func() {
79+
if err := oci.DeleteKICNetworks(oci.Docker); err != nil {
80+
t.Logf("error deleting kic network, may need to delete manually: %v", err)
81+
}
82+
}()
83+
profile := UniqueProfileName("existing-network")
84+
ctx, cancel := context.WithTimeout(context.Background(), Minutes(5))
85+
defer Cleanup(t, profile, cancel)
86+
87+
verifyNetworkExists(ctx, t, networkName)
88+
89+
startArgs := []string{"start", "-p", profile, fmt.Sprintf("--network=%s", networkName)}
90+
c := exec.CommandContext(ctx, Target(), startArgs...)
91+
rr, err := Run(t, c)
92+
if err != nil {
93+
t.Fatalf("%v failed: %v\n%v", rr.Command(), err, rr.Output())
94+
}
95+
}
96+
97+
func verifyNetworkExists(ctx context.Context, t *testing.T, networkName string) {
98+
c := exec.CommandContext(ctx, "docker", "network", "ls", "--format", "{{.Name}}")
99+
rr, err := Run(t, c)
100+
if err != nil {
101+
t.Fatalf("%v failed: %v\n%v", rr.Command(), err, rr.Output())
102+
}
103+
if output := rr.Output(); !strings.Contains(output, networkName) {
104+
t.Fatalf("%s network is not listed by [%v]: %v", networkName, c.Args, output)
105+
}
106+
}

0 commit comments

Comments
 (0)