Skip to content

Instantly share code, notes, and snippets.

@wliao008
Last active December 19, 2016 22:04
Show Gist options
  • Save wliao008/0d99ad0e2740314d97f7f3c2b058058e to your computer and use it in GitHub Desktop.
Save wliao008/0d99ad0e2740314d97f7f3c2b058058e to your computer and use it in GitHub Desktop.
monitor docker events
package main
import (
"flag"
"fmt"
"os"
"text/template"
"io/ioutil"
dockerapi "github.com/fsouza/go-dockerclient"
)
func main() {
var sourceDir = flag.String("dir", "/etc/sumo", "Directory path where the new source config will be written")
var dockerSocket = flag.String("socket", "unix:///var/run/docker.sock", "Docker socket")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
fmt.Fprintf(os.Stderr, " %s [options]\n\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
fmt.Println("dir=%s", *sourceDir)
fmt.Println("socket=%s", *dockerSocket)
dockerHost := os.Getenv("DOCKER_HOST")
if dockerHost == "" {
os.Setenv("DOCKER_HOST", "unix:///tmp/docker.sock")
}
docker, err := dockerapi.NewClient(*dockerSocket)
if err != nil {
fmt.Println("error")
}
events := make(chan *dockerapi.APIEvents)
fmt.Println("listening for docker events...")
docker.AddEventListener(events)
quit := make(chan struct{})
for msg := range events {
switch msg.Status {
case "start":
fmt.Println("container started: %+v", msg)
///TODO: create sumo source config file here
parseTemplate("templates/app.tmpl", msg)
case "die":
fmt.Println("container died: %+v", msg)
}
}
<-quit
}
func parseTemplate(path string, event *dockerapi.APIEvents) bool {
tmplStr, err := getTemplate(path)
if err != nil {
return false
}
tmpl, err := template.New("tmpl").Parse(tmplStr)
if err != nil {
return false
}
data := struct {
HostName string
AppName string
Prefix string
}{
HostName: "i-wei-speedtest",
AppName: event.Actor.Attributes["name"],
Prefix: "THOR_",
}
err = tmpl.Execute(os.Stdout, data)
if err != nil {
return false
}
return true
}
func getTemplate(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
str, err := ioutil.ReadAll(file)
if err != nil {
return "", err
}
return string(str), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment