This repository has been archived on 2024-03-03. You can view files and clone it, but cannot push or open issues or pull requests.
minifaas/engine/docker/docker.go

70 lines
1.3 KiB
Go
Raw Normal View History

2021-05-02 11:47:08 +00:00
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"
2021-05-02 11:47:08 +00:00
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
oci "github.com/opencontainers/image-spec/specs-go/v1"
)
2021-05-02 14:26:23 +00:00
func newCli() (*client.Client, error) {
return client.NewClientWithOpts(client.FromEnv)
}
func Run(image string, cmd []string, mounts []mount.Mount) (string, error) {
2021-05-02 14:26:23 +00:00
cli, err := newCli()
2021-05-02 11:47:08 +00:00
if err != nil {
2021-05-02 14:26:23 +00:00
return "", err
2021-05-02 11:47:08 +00:00
}
ctnr, err := cli.ContainerCreate(
context.Background(),
&container.Config{
AttachStdout: true,
AttachStderr: true,
2021-05-02 14:26:23 +00:00
Image: image,
2021-05-02 15:59:55 +00:00
Cmd: cmd,
Volumes: map[string]struct{}{
"/data": {},
},
},
&container.HostConfig{
Mounts: mounts,
2021-05-02 11:47:08 +00:00
},
&network.NetworkingConfig{},
&oci.Platform{
Architecture: "amd64",
OS: "linux",
},
"",
)
if err != nil {
2021-05-02 14:26:23 +00:00
return "", err
2021-05-02 11:47:08 +00:00
}
err = cli.ContainerStart(context.Background(), ctnr.ID, types.ContainerStartOptions{})
2021-05-02 14:26:23 +00:00
if err != nil {
return "", err
}
return ctnr.ID, nil
}
func Logs(id string) (io.ReadCloser, error) {
cli, err := newCli()
2021-05-02 11:47:08 +00:00
if err != nil {
return nil, err
}
2021-05-02 14:26:23 +00:00
return cli.ContainerLogs(context.Background(), id, types.ContainerLogsOptions{
2021-05-02 11:47:08 +00:00
ShowStdout: true,
ShowStderr: true,
Follow: true,
})
}