110 lines
2.1 KiB
Go
110 lines
2.1 KiB
Go
package docker
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
|
|
"github.com/docker/docker/api/types"
|
|
"github.com/docker/docker/api/types/container"
|
|
"github.com/docker/docker/api/types/mount"
|
|
"github.com/docker/docker/api/types/network"
|
|
"github.com/docker/docker/client"
|
|
oci "github.com/opencontainers/image-spec/specs-go/v1"
|
|
)
|
|
|
|
func newCli() (*client.Client, error) {
|
|
return client.NewClientWithOpts(client.FromEnv)
|
|
}
|
|
|
|
func Ps() ([]types.Container, error) {
|
|
cli, err := newCli()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return cli.ContainerList(context.Background(), types.ContainerListOptions{})
|
|
}
|
|
|
|
func PsName() (ret map[string]string, err error) {
|
|
containers, err := Ps()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
ret = map[string]string{}
|
|
for _, container := range containers {
|
|
for _, name := range container.Names {
|
|
ret[name] = container.ID
|
|
}
|
|
}
|
|
|
|
return ret, err
|
|
}
|
|
|
|
func Create(jobtype string, image string, cmd []string, mounts []mount.Mount) (string, error) {
|
|
cli, err := newCli()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
ctnr, err := cli.ContainerCreate(
|
|
context.Background(),
|
|
&container.Config{
|
|
AttachStdout: true,
|
|
AttachStderr: true,
|
|
Image: image,
|
|
Cmd: cmd,
|
|
},
|
|
&container.HostConfig{
|
|
Mounts: mounts,
|
|
},
|
|
&network.NetworkingConfig{},
|
|
&oci.Platform{
|
|
Architecture: "amd64",
|
|
OS: "linux",
|
|
},
|
|
genContainerName(jobtype),
|
|
)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return ctnr.ID, nil
|
|
}
|
|
|
|
func Start(id string) error {
|
|
cli, err := newCli()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = cli.ContainerStart(context.Background(), id, types.ContainerStartOptions{})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func Run(jobtype string, image string, cmd []string, mounts []mount.Mount) (string, error) {
|
|
ctrid, err := Create(jobtype, image, cmd, mounts)
|
|
if err != nil {
|
|
return ctrid, err
|
|
}
|
|
|
|
return ctrid, Start(ctrid)
|
|
}
|
|
|
|
func Logs(id string) (io.ReadCloser, error) {
|
|
cli, err := newCli()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return cli.ContainerLogs(context.Background(), id, types.ContainerLogsOptions{
|
|
ShowStdout: true,
|
|
ShowStderr: true,
|
|
Follow: true,
|
|
})
|
|
}
|