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 Run(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 } err = cli.ContainerStart(context.Background(), ctnr.ID, types.ContainerStartOptions{}) if err != nil { return "", err } return ctnr.ID, nil } 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, }) }