Skip to content

Instantly share code, notes, and snippets.

@calavera
Created January 22, 2016 21:45
Show Gist options
  • Save calavera/afd3ddca7f24b2e057de to your computer and use it in GitHub Desktop.
Save calavera/afd3ddca7f24b2e057de to your computer and use it in GitHub Desktop.
Concurrent docker exercise tool
package main
import (
"io"
"io/ioutil"
"log"
"time"
"github.com/docker/engine-api/client"
"github.com/docker/engine-api/types"
"github.com/docker/engine-api/types/container"
"github.com/docker/engine-api/types/strslice"
)
var docker *client.Client
func init() {
// Init the client
defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
c, err := client.NewClient("unix:///tmp/docker.sock", "", nil, defaultHeaders)
if err != nil {
log.Fatal(err)
}
docker = c
}
func stopper() {
options := types.ContainerListOptions{All: true}
for range time.Tick(300 * time.Millisecond) {
start := time.Now()
cs, err := docker.ContainerList(options)
if err != nil {
log.Printf("[ERROR] List: %v\n", err)
}
log.Printf("PS time: %v\n", time.Since(start))
for _, c := range cs {
if start.Unix()-c.Created > 10 {
rmStart := time.Now()
rOpts := types.ContainerRemoveOptions{
ContainerID: c.ID,
Force: true,
RemoveVolumes: true,
}
if err := docker.ContainerRemove(rOpts); err != nil {
log.Printf("[ERROR] Remove: %v\n", err)
}
log.Printf("Removal: %v", time.Since(rmStart))
}
}
}
}
func starter() {
for range time.Tick(500 * time.Millisecond) {
// Create a container
containerConfig := &container.Config{
Image: "ruby:latest",
Cmd: strslice.New("irb"),
AttachStdin: true,
Tty: true,
}
hostConfig := &container.HostConfig{
Resources: container.Resources{
Memory: 200 * 1024 * 1024,
},
}
resp, err := docker.ContainerCreate(containerConfig, hostConfig, nil, "")
if err != nil {
log.Fatal(err)
}
aOpts := types.ContainerAttachOptions{
ContainerID: resp.ID,
Stdin: true,
Stdout: true,
Stderr: true,
Stream: true,
}
rd, err := docker.ContainerAttach(aOpts)
if err != nil {
log.Fatal(err)
}
defer rd.Conn.Close()
go io.Copy(ioutil.Discard, rd.Reader)
// Start the container
err = docker.ContainerStart(resp.ID)
if err != nil {
log.Printf("Start: %v\n", err)
}
}
}
func main() {
go stopper()
go starter()
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment