Skip to content
This repository has been archived by the owner on Oct 13, 2023. It is now read-only.

[18.09 backport] Handle the error case when a container reattaches to the same network #278

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions daemon/container_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,15 @@ func (daemon *Daemon) findAndAttachNetwork(container *container.Container, idOrN
if container.Managed || !n.Info().Dynamic() {
return n, nil, nil
}
// Throw an error if the container is already attached to the network
if container.NetworkSettings.Networks != nil {
networkName := n.Name()
containerName := strings.TrimPrefix(container.Name, "/")
if network, ok := container.NetworkSettings.Networks[networkName]; ok && network.EndpointID != "" {
err := fmt.Errorf("%s is already attached to network %s", containerName, networkName)
return n, nil, errdefs.Conflict(err)
}
}
}

var addresses []string
Expand Down
40 changes: 40 additions & 0 deletions integration/service/network_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,43 @@ func TestDockerNetworkConnectAlias(t *testing.T) {
assert.Check(t, is.Equal(len(ng2.NetworkSettings.Networks[name].Aliases), 2))
assert.Check(t, is.Equal(ng2.NetworkSettings.Networks[name].Aliases[0], "bbb"))
}

func TestDockerNetworkReConnect(t *testing.T) {
skip.If(t, testEnv.DaemonInfo.OSType == "windows")
defer setupTest(t)()
d := swarm.NewSwarm(t, testEnv)
defer d.Stop(t)
client := d.NewClientT(t)
defer client.Close()
ctx := context.Background()

name := t.Name() + "dummyNet"
net.CreateNoError(t, ctx, client, name,
net.WithDriver("overlay"),
net.WithAttachable(),
)

c1 := container.Create(t, ctx, client, func(c *container.TestContainerConfig) {
c.NetworkingConfig = &network.NetworkingConfig{
EndpointsConfig: map[string]*network.EndpointSettings{
name: {},
},
}
})

err := client.NetworkConnect(ctx, name, c1, &network.EndpointSettings{})
assert.NilError(t, err)

err = client.ContainerStart(ctx, c1, types.ContainerStartOptions{})
assert.NilError(t, err)

n1, err := client.ContainerInspect(ctx, c1)
assert.NilError(t, err)

err = client.NetworkConnect(ctx, name, c1, &network.EndpointSettings{})
assert.ErrorContains(t, err, "is already attached to network")

n2, err := client.ContainerInspect(ctx, c1)
assert.NilError(t, err)
assert.Check(t, is.DeepEqual(n1, n2))
}