2015-09-07 11:38:58 +03:00
package main
2015-09-08 01:15:14 +03:00
import (
2015-09-07 11:38:58 +03:00
"github.com/fsouza/go-dockerclient"
"github.com/leekchan/gtf"
"bytes"
"github.com/BurntSushi/toml"
2015-09-07 16:25:13 +03:00
"log"
2015-09-07 11:38:58 +03:00
)
type DockerProvider struct {
2015-09-08 01:15:14 +03:00
Watch bool
Endpoint string
2015-09-07 11:38:58 +03:00
dockerClient * docker . Client
}
2015-09-08 01:15:14 +03:00
func ( provider * DockerProvider ) Provide ( configurationChan chan <- * Configuration ) {
2015-09-07 18:39:22 +03:00
provider . dockerClient , _ = docker . NewClient ( provider . Endpoint )
2015-09-07 11:38:58 +03:00
dockerEvents := make ( chan * docker . APIEvents )
2015-09-08 01:15:14 +03:00
if ( provider . Watch ) {
2015-09-07 19:10:33 +03:00
provider . dockerClient . AddEventListener ( dockerEvents )
}
2015-09-07 11:38:58 +03:00
go func ( ) {
for {
event := <- dockerEvents
2015-09-07 16:25:13 +03:00
log . Println ( "Event receveived" , event )
2015-09-08 01:15:14 +03:00
configuration := provider . loadDockerConfig ( )
if ( configuration != nil ) {
configurationChan <- configuration
}
2015-09-07 11:38:58 +03:00
}
} ( )
2015-09-08 01:15:14 +03:00
configuration := provider . loadDockerConfig ( )
configurationChan <- configuration
2015-09-07 11:38:58 +03:00
}
2015-09-08 01:15:14 +03:00
func ( provider * DockerProvider ) loadDockerConfig ( ) * Configuration {
configuration := new ( Configuration )
2015-09-07 11:38:58 +03:00
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 16:25:13 +03:00
log . Println ( "Error reading file:" , err )
return nil
2015-09-07 11:38:58 +03:00
}
var buffer bytes . Buffer
err = tmpl . Execute ( & buffer , containers )
if err != nil {
2015-09-07 16:25:13 +03:00
log . Println ( "Error with docker template:" , err )
return nil
2015-09-07 11:38:58 +03:00
}
2015-09-08 01:15:14 +03:00
if _ , err := toml . Decode ( buffer . String ( ) , configuration ) ; err != nil {
log . Println ( "Error creating docker configuration:" , err )
2015-09-07 11:38:58 +03:00
return nil
}
2015-09-08 01:15:14 +03:00
return configuration
2015-09-07 11:38:58 +03:00
}