Skip to content

Instantly share code, notes, and snippets.

@nasa9084
Created September 30, 2019 16:09
Show Gist options
  • Select an option

  • Save nasa9084/ed294c5c39912c11086f5d278bde405e to your computer and use it in GitHub Desktop.

Select an option

Save nasa9084/ed294c5c39912c11086f5d278bde405e to your computer and use it in GitHub Desktop.
package main
import (
"context"
"io"
"log"
"os"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/strslice"
"github.com/docker/docker/client"
"github.com/jessevdk/go-flags"
"gopkg.in/yaml.v2"
)
// the content of File is like:
//
// ---
// image: centos:7
// command: echo Foobar
type options struct {
File string `short:"f" long:"file"`
}
func main() {
if err := execute(); err != nil {
log.Printf("error: %+v", err)
os.Exit(1)
}
}
type command struct {
Image string `yaml:"image"`
Command string `yaml:"command"`
}
func execute() error {
var opts options
if _, err := flags.Parse(&opts); err != nil {
if fe, ok := err.(*flags.Error); ok && fe.Type == flags.ErrHelp {
return nil
}
return err
}
cli, err := client.NewEnvClient()
if err != nil {
return err
}
defer cli.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var cmd command
f, err := os.Open(opts.File)
if err != nil {
return err
}
defer f.Close()
if err := yaml.NewDecoder(f).Decode(&cmd); err != nil {
return err
}
createCfg := &container.Config{
Image: cmd.Image,
Cmd: strslice.StrSlice(strings.Split(cmd.Command, " ")),
}
hostCfg := &container.HostConfig{
AutoRemove: true,
}
created, err := cli.ContainerCreate(ctx, createCfg, hostCfg, nil, "test")
if err != nil {
return err
}
log.Printf("created: %s", created.ID)
startOpts := types.ContainerStartOptions{
CheckpointID: "",
CheckpointDir: "",
}
if err := cli.ContainerStart(ctx, created.ID, startOpts); err != nil {
return err
}
logOpts := types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
}
log, err := cli.ContainerLogs(ctx, created.ID, logOpts)
if err != nil {
return err
}
io.Copy(os.Stdout, log)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment