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(opts types.ContainerListOptions) ([]types.Container, error) { cli, err := newCli() if err != nil { return nil, err } return cli.ContainerList(context.Background(), opts) } func PsName() (ret map[string]string, err error) { containers, err := Ps(types.ContainerListOptions{}) 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 GetContainer(containerID string) (ctr types.ContainerJSON, err error) { cli, err := newCli() if err != nil { return types.ContainerJSON{}, err } return cli.ContainerInspect(context.Background(), containerID) } func HasStarted(containerID string) bool { ctr, err := GetContainer(containerID) if err != nil { return false } return ctr.State.Status == "running" || ctr.State.Status == "paused" || ctr.State.Status == "restarting" || ctr.State.Status == "removing" || ctr.State.Status == "exited" || ctr.State.Status == "dead" } 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, }) }