2022-09-29 18:16:56 +08:00
|
|
|
package docker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-10-08 18:32:02 +08:00
|
|
|
|
2022-09-29 18:16:56 +08:00
|
|
|
"github.com/docker/docker/api/types"
|
|
|
|
"github.com/docker/docker/api/types/filters"
|
|
|
|
"github.com/docker/docker/client"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Client struct {
|
|
|
|
cli *client.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewClient() (Client, error) {
|
|
|
|
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
|
|
|
|
if err != nil {
|
|
|
|
return Client{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return Client{
|
|
|
|
cli: cli,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2022-10-08 18:32:02 +08:00
|
|
|
func NewDockerClient() (*client.Client, error) {
|
|
|
|
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return cli, nil
|
|
|
|
}
|
|
|
|
|
2022-09-29 18:16:56 +08:00
|
|
|
func (c Client) ListAllContainers() ([]types.Container, error) {
|
|
|
|
var options types.ContainerListOptions
|
|
|
|
containers, err := c.cli.ContainerList(context.Background(), options)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return containers, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c Client) ListContainersByName(names []string) ([]types.Container, error) {
|
|
|
|
var options types.ContainerListOptions
|
|
|
|
options.All = true
|
|
|
|
if len(names) > 0 {
|
|
|
|
var array []filters.KeyValuePair
|
|
|
|
for _, n := range names {
|
|
|
|
array = append(array, filters.Arg("name", n))
|
|
|
|
}
|
|
|
|
options.Filters = filters.NewArgs(array...)
|
|
|
|
}
|
|
|
|
containers, err := c.cli.ContainerList(context.Background(), options)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return containers, nil
|
|
|
|
}
|
2022-10-09 23:35:24 +08:00
|
|
|
|
2022-10-10 22:56:42 +08:00
|
|
|
func (c Client) CreateNetwork(name string) error {
|
|
|
|
_, err := c.cli.NetworkCreate(context.Background(), name, types.NetworkCreate{
|
|
|
|
Driver: "bridge",
|
|
|
|
})
|
|
|
|
return err
|
|
|
|
}
|
2022-10-09 23:35:24 +08:00
|
|
|
|
2022-10-10 22:56:42 +08:00
|
|
|
func (c Client) NetworkExist(name string) bool {
|
|
|
|
var options types.NetworkListOptions
|
2022-12-04 21:18:24 +08:00
|
|
|
options.Filters = filters.NewArgs(filters.Arg("name", name))
|
2022-10-10 22:56:42 +08:00
|
|
|
networks, err := c.cli.NetworkList(context.Background(), options)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
2022-10-09 23:35:24 +08:00
|
|
|
}
|
2022-10-10 22:56:42 +08:00
|
|
|
return len(networks) > 0
|
2022-10-09 23:35:24 +08:00
|
|
|
}
|