2016-09-08 13:11:39 -04:00
|
|
|
package network
|
|
|
|
|
|
|
|
import (
|
2018-05-03 21:02:44 -04:00
|
|
|
"context"
|
2016-09-08 13:11:39 -04:00
|
|
|
|
2017-04-17 18:07:56 -04:00
|
|
|
"github.com/docker/cli/cli"
|
|
|
|
"github.com/docker/cli/cli/command"
|
2022-03-30 09:27:25 -04:00
|
|
|
"github.com/docker/cli/cli/command/completion"
|
2024-07-03 09:35:44 -04:00
|
|
|
"github.com/docker/docker/api/types/container"
|
2024-07-03 11:04:48 -04:00
|
|
|
"github.com/docker/docker/client"
|
2016-09-08 13:11:39 -04:00
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
|
|
|
type disconnectOptions struct {
|
|
|
|
network string
|
|
|
|
container string
|
|
|
|
force bool
|
|
|
|
}
|
|
|
|
|
2017-06-21 05:25:25 -04:00
|
|
|
func newDisconnectCommand(dockerCli command.Cli) *cobra.Command {
|
2016-09-08 13:11:39 -04:00
|
|
|
opts := disconnectOptions{}
|
|
|
|
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "disconnect [OPTIONS] NETWORK CONTAINER",
|
|
|
|
Short: "Disconnect a container from a network",
|
|
|
|
Args: cli.ExactArgs(2),
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
|
|
opts.network = args[0]
|
|
|
|
opts.container = args[1]
|
2024-07-03 11:04:48 -04:00
|
|
|
return runDisconnect(cmd.Context(), dockerCli.Client(), opts)
|
2016-09-08 13:11:39 -04:00
|
|
|
},
|
2022-03-30 09:27:25 -04:00
|
|
|
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
|
|
|
if len(args) == 0 {
|
|
|
|
return completion.NetworkNames(dockerCli)(cmd, args, toComplete)
|
|
|
|
}
|
|
|
|
network := args[0]
|
|
|
|
return completion.ContainerNames(dockerCli, true, isConnected(network))(cmd, args, toComplete)
|
|
|
|
},
|
2016-09-08 13:11:39 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
flags := cmd.Flags()
|
|
|
|
flags.BoolVarP(&opts.force, "force", "f", false, "Force the container to disconnect from a network")
|
|
|
|
|
|
|
|
return cmd
|
|
|
|
}
|
|
|
|
|
2024-07-03 11:04:48 -04:00
|
|
|
func runDisconnect(ctx context.Context, apiClient client.NetworkAPIClient, opts disconnectOptions) error {
|
|
|
|
return apiClient.NetworkDisconnect(ctx, opts.network, opts.container, opts.force)
|
2016-09-08 13:11:39 -04:00
|
|
|
}
|
2022-03-30 09:27:25 -04:00
|
|
|
|
2024-07-03 09:35:44 -04:00
|
|
|
func isConnected(network string) func(container.Summary) bool {
|
|
|
|
return func(ctr container.Summary) bool {
|
2024-07-03 10:14:40 -04:00
|
|
|
if ctr.NetworkSettings == nil {
|
2022-03-30 09:27:25 -04:00
|
|
|
return false
|
|
|
|
}
|
2024-07-03 10:14:40 -04:00
|
|
|
_, ok := ctr.NetworkSettings.Networks[network]
|
2022-03-30 09:27:25 -04:00
|
|
|
return ok
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-03 09:35:44 -04:00
|
|
|
func not(fn func(container.Summary) bool) func(container.Summary) bool {
|
|
|
|
return func(ctr container.Summary) bool {
|
2024-07-03 10:14:40 -04:00
|
|
|
ok := fn(ctr)
|
2022-03-30 09:27:25 -04:00
|
|
|
return !ok
|
|
|
|
}
|
|
|
|
}
|