2021-05-17 20:33:00 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-06-07 10:45:32 +08:00
|
|
|
"os"
|
2021-05-17 20:33:00 +08:00
|
|
|
|
|
|
|
"github.com/docker/docker/api/types"
|
|
|
|
"github.com/docker/docker/api/types/container"
|
|
|
|
"github.com/docker/docker/client"
|
|
|
|
)
|
|
|
|
|
|
|
|
func startContainer(cfg *container.Config, hostCfg *container.HostConfig, name string) (string, error) {
|
2021-07-18 19:26:51 +08:00
|
|
|
c, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
|
2021-05-17 20:33:00 +08:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer c.Close()
|
|
|
|
|
|
|
|
if !isDarwin {
|
|
|
|
hostCfg.NetworkMode = "host"
|
|
|
|
}
|
|
|
|
|
|
|
|
container, err := c.ContainerCreate(context.Background(), cfg, hostCfg, nil, nil, name)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = c.ContainerStart(context.Background(), container.ID, types.ContainerStartOptions{}); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2022-06-07 10:45:32 +08:00
|
|
|
response, err := c.ContainerAttach(context.Background(), container.ID, types.ContainerAttachOptions{
|
|
|
|
Stdout: true,
|
|
|
|
Stderr: true,
|
|
|
|
Logs: true,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
response.Reader.WriteTo(os.Stderr)
|
|
|
|
}()
|
|
|
|
|
2021-05-17 20:33:00 +08:00
|
|
|
return container.ID, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func cleanContainer(id string) error {
|
2021-07-18 19:26:51 +08:00
|
|
|
c, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
|
2021-05-17 20:33:00 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer c.Close()
|
|
|
|
|
|
|
|
removeOpts := types.ContainerRemoveOptions{Force: true}
|
|
|
|
return c.ContainerRemove(context.Background(), id, removeOpts)
|
|
|
|
}
|