Providers file & docker

Sleep between restart
Check same service
This commit is contained in:
emile 2015-09-07 15:25:13 +02:00
parent bf37869b8f
commit afb4286b20
5 changed files with 95 additions and 88 deletions

View file

@ -1,17 +1,17 @@
package main package main
import( import(
"github.com/fsouza/go-dockerclient" "github.com/fsouza/go-dockerclient"
"fmt"
"github.com/leekchan/gtf" "github.com/leekchan/gtf"
"bytes" "bytes"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"log"
) )
type DockerProvider struct { type DockerProvider struct {
dockerClient *docker.Client dockerClient *docker.Client
} }
func (provider *DockerProvider) Provide(serviceChan chan<- Service){ func (provider *DockerProvider) Provide(serviceChan chan<- *Service){
endpoint := "unix:///var/run/docker.sock" endpoint := "unix:///var/run/docker.sock"
provider.dockerClient, _ = docker.NewClient(endpoint) provider.dockerClient, _ = docker.NewClient(endpoint)
dockerEvents := make(chan *docker.APIEvents) dockerEvents := make(chan *docker.APIEvents)
@ -19,15 +19,14 @@ func (provider *DockerProvider) Provide(serviceChan chan<- Service){
go func() { go func() {
for { for {
event := <-dockerEvents event := <-dockerEvents
fmt.Println("Event receveived", event) log.Println("Event receveived", event)
service:= provider.loadDockerConfig() service:= provider.loadDockerConfig()
serviceChan <- *service serviceChan <- service
} }
}() }()
service:= provider.loadDockerConfig() service:= provider.loadDockerConfig()
fmt.Println("Sending service") serviceChan <- service
serviceChan <- *service
} }
func (provider *DockerProvider) loadDockerConfig() *Service { func (provider *DockerProvider) loadDockerConfig() *Service {
@ -55,10 +54,8 @@ func (provider *DockerProvider) loadDockerConfig() *Service {
panic(err) panic(err)
} }
fmt.Println(buffer.String())
if _, err := toml.Decode(buffer.String(), service); err != nil { if _, err := toml.Decode(buffer.String(), service); err != nil {
fmt.Println(err) log.Fatal(err)
return nil return nil
} }
return service return service

57
file.go Normal file
View file

@ -0,0 +1,57 @@
package main
import (
"log"
"gopkg.in/fsnotify.v1"
"github.com/BurntSushi/toml"
)
type FileProvider struct {
}
func (provider *FileProvider) Provide(serviceChan chan<- *Service){
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
err = watcher.Add(".")
if err != nil {
log.Fatal(err)
}
done := make(chan bool)
// Process events
go func() {
for {
select {
case event := <-watcher.Events:
if(event.Name == "./tortuous.toml"){
log.Println("event:", event)
service := provider.LoadFileConfig()
serviceChan <- service
}
case error := <-watcher.Errors:
log.Println("error:", error)
}
}
}()
service:= provider.LoadFileConfig()
serviceChan <- service
<-done
log.Println("DONE")
}
func (provider *FileProvider) LoadFileConfig() *Service {
service := new(Service)
if _, err := toml.DecodeFile("tortuous.toml", service); err != nil {
log.Println(err)
return nil
}
return service
}

View file

@ -1,5 +1,5 @@
package main package main
type Provider interface { type Provider interface {
Provide(chan<- Service) Provide(chan<- *Service)
} }

View file

@ -1,12 +1,7 @@
package main package main
import ( import (
"bytes"
"fmt"
"github.com/BurntSushi/toml"
"github.com/fsouza/go-dockerclient"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/leekchan/gtf"
"github.com/mailgun/oxy/forward" "github.com/mailgun/oxy/forward"
"github.com/mailgun/oxy/roundrobin" "github.com/mailgun/oxy/roundrobin"
"github.com/tylerb/graceful" "github.com/tylerb/graceful"
@ -19,17 +14,19 @@ import (
"reflect" "reflect"
"syscall" "syscall"
"time" "time"
"log"
) )
var srv *graceful.Server var srv *graceful.Server
var userRouter *mux.Router var systemRouter *mux.Router
var renderer = render.New() var renderer = render.New()
var currentService = new(Service) var currentService = new(Service)
var serviceChan = make(chan Service) var serviceChan = make(chan *Service)
var providers = []Provider{} var providers = []Provider{}
func main() { func main() {
providers = append(providers, new(DockerProvider)) //providers = append(providers, new(DockerProvider))
providers = append(providers, new(FileProvider))
sigs := make(chan os.Signal, 1) sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
@ -42,21 +39,30 @@ func main() {
go func() { go func() {
for { for {
service := <-serviceChan service := <-serviceChan
fmt.Println("Service receveived", service) log.Println("Service receveived", service)
currentService = &service if service == nil {
userRouter = LoadConfig(service) log.Println("Skipping nil service")
srv.Stop(10 * time.Second) } else if(reflect.DeepEqual(currentService, service)){
log.Println("Skipping same service")
} else{
currentService = service
systemRouter = LoadConfig(service)
srv.Stop(10 * time.Second)
time.Sleep(3 * time.Second)
}
} }
}() }()
for _, provider := range providers { go func() {
provider.Provide(serviceChan) for _, provider := range providers {
} provider.Provide(serviceChan)
}
}()
goAway := false goAway := false
go func() { go func() {
sig := <-sigs sig := <-sigs
fmt.Println("I have to go...", sig) log.Println("I have to go...", sig)
goAway = true goAway = true
srv.Stop(10 * time.Second) srv.Stop(10 * time.Second)
}() }()
@ -75,87 +81,35 @@ func main() {
Server: &http.Server{ Server: &http.Server{
Addr: ":8001", Addr: ":8001",
Handler: userRouter, Handler: systemRouter,
}, },
} }
go srv.ListenAndServe() go srv.ListenAndServe()
fmt.Println("Started") log.Println("Started")
<-srv.StopChan() <-srv.StopChan()
fmt.Println("Stopped") log.Println("Stopped")
} }
} }
func LoadDockerConfig(client *docker.Client, service Service) { func LoadConfig(service *Service) *mux.Router {
containerList, _ := client.ListContainers(docker.ListContainersOptions{})
containersInspected := []docker.Container{}
for _, container := range containerList {
containerInspected, _ := client.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 {
panic(err)
}
var buffer bytes.Buffer
err = tmpl.Execute(&buffer, containers)
if err != nil {
panic(err)
}
fmt.Println(buffer.String())
if _, err := toml.Decode(buffer.String(), service); err != nil {
fmt.Println(err)
return
}
}
func LoadFileConfig(service Service) {
if _, err := toml.DecodeFile("tortuous.toml", service); err != nil {
fmt.Println(err)
return
}
}
func LoadConfig(service Service) *mux.Router {
/*endpoint := "unix:///var/run/docker.sock"
client, _ := docker.NewClient(endpoint)
dockerEvents := make(chan *docker.APIEvents)
LoadDockerConfig(client)
client.AddEventListener(dockerEvents)
go func() {
for {
event := <-dockerEvents
fmt.Println("Event receveived", event)
}
}()*/
//LoadFileConfig()
router := mux.NewRouter() router := mux.NewRouter()
for routeName, route := range service.Routes { for routeName, route := range service.Routes {
fmt.Println("Creating route", routeName) log.Println("Creating route", routeName)
fwd, _ := forward.New() fwd, _ := forward.New()
newRoutes := []*mux.Route{} newRoutes := []*mux.Route{}
for ruleName, rule := range route.Rules { for ruleName, rule := range route.Rules {
fmt.Println("Creating rule", ruleName) log.Println("Creating rule", ruleName)
newRouteReflect := Invoke(router.NewRoute(), rule.Category, rule.Value) newRouteReflect := Invoke(router.NewRoute(), rule.Category, rule.Value)
newRoute := newRouteReflect[0].Interface().(*mux.Route) newRoute := newRouteReflect[0].Interface().(*mux.Route)
newRoutes = append(newRoutes, newRoute) newRoutes = append(newRoutes, newRoute)
} }
for _, backendName := range route.Backends { for _, backendName := range route.Backends {
fmt.Println("Creating backend", backendName) log.Println("Creating backend", backendName)
lb, _ := roundrobin.New(fwd) lb, _ := roundrobin.New(fwd)
rb, _ := roundrobin.NewRebalancer(lb) rb, _ := roundrobin.NewRebalancer(lb)
for serverName, server := range service.Backends[backendName].Servers { for serverName, server := range service.Backends[backendName].Servers {
fmt.Println("Creating server", serverName) log.Println("Creating server", serverName)
url, _ := url.Parse(server.Url) url, _ := url.Parse(server.Url)
rb.UpsertServer(url) rb.UpsertServer(url)
} }
@ -168,7 +122,7 @@ func LoadConfig(service Service) *mux.Router {
} }
func DeployService() { func DeployService() {
userRouter = LoadConfig(*currentService) systemRouter = LoadConfig(currentService)
} }
func ReloadConfigHandler(rw http.ResponseWriter, r *http.Request) { func ReloadConfigHandler(rw http.ResponseWriter, r *http.Request) {

View file

@ -16,4 +16,3 @@
[routes.route2.rules.test_zenika_2] [routes.route2.rules.test_zenika_2]
category = "Path" category = "Path"
value = "/test" value = "/test"