2015-09-07 08:38:58 +00:00
|
|
|
package main
|
|
|
|
import(
|
|
|
|
"github.com/fsouza/go-dockerclient"
|
|
|
|
"github.com/leekchan/gtf"
|
|
|
|
"bytes"
|
|
|
|
"github.com/BurntSushi/toml"
|
2015-09-07 13:25:13 +00:00
|
|
|
"log"
|
2015-09-07 08:38:58 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type DockerProvider struct {
|
|
|
|
dockerClient *docker.Client
|
|
|
|
}
|
|
|
|
|
2015-09-07 13:25:13 +00:00
|
|
|
func (provider *DockerProvider) Provide(serviceChan chan<- *Service){
|
2015-09-07 08:38:58 +00:00
|
|
|
endpoint := "unix:///var/run/docker.sock"
|
|
|
|
provider.dockerClient, _ = docker.NewClient(endpoint)
|
|
|
|
dockerEvents := make(chan *docker.APIEvents)
|
|
|
|
provider.dockerClient.AddEventListener(dockerEvents)
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
event := <-dockerEvents
|
2015-09-07 13:25:13 +00:00
|
|
|
log.Println("Event receveived", event)
|
2015-09-07 08:38:58 +00:00
|
|
|
service:= provider.loadDockerConfig()
|
2015-09-07 13:25:13 +00:00
|
|
|
serviceChan <- service
|
2015-09-07 08:38:58 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
service:= provider.loadDockerConfig()
|
2015-09-07 13:25:13 +00:00
|
|
|
serviceChan <- service
|
2015-09-07 08:38:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (provider *DockerProvider) loadDockerConfig() *Service {
|
|
|
|
service := new(Service)
|
|
|
|
containerList, _ := provider.dockerClient.ListContainers(docker.ListContainersOptions{})
|
|
|
|
containersInspected := []docker.Container{}
|
|
|
|
for _, container := range containerList {
|
|
|
|
containerInspected, _ := provider.dockerClient.InspectContainer(container.ID)
|
|
|
|
containersInspected = append(containersInspected, *containerInspected)
|
|
|
|
}
|
|
|
|
containers := struct {
|
|
|
|
Containers []docker.Container
|
|
|
|
}{
|
|
|
|
containersInspected,
|
|
|
|
}
|
|
|
|
tmpl, err := gtf.New("docker.tmpl").ParseFiles("docker.tmpl")
|
|
|
|
if err != nil {
|
2015-09-07 13:25:13 +00:00
|
|
|
log.Println("Error reading file:", err)
|
|
|
|
return nil
|
2015-09-07 08:38:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var buffer bytes.Buffer
|
|
|
|
|
|
|
|
err = tmpl.Execute(&buffer, containers)
|
|
|
|
if err != nil {
|
2015-09-07 13:25:13 +00:00
|
|
|
log.Println("Error with docker template:", err)
|
|
|
|
return nil
|
2015-09-07 08:38:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := toml.Decode(buffer.String(), service); err != nil {
|
2015-09-07 13:25:13 +00:00
|
|
|
log.Println("Error creating docker service:", err)
|
2015-09-07 08:38:58 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return service
|
|
|
|
}
|