Fix some typos, fmt and imports :)

Signed-off-by: Vincent Demeester <vincent@sbr.pm>
This commit is contained in:
Vincent Demeester 2015-09-24 17:16:13 +02:00
parent cae02b02ac
commit c038dfbd54
11 changed files with 96 additions and 88 deletions

View file

@ -38,7 +38,7 @@ func notFoundHandler(w http.ResponseWriter, r *http.Request) {
//templatesRenderer.HTML(w, http.StatusNotFound, "notFound", nil) //templatesRenderer.HTML(w, http.StatusNotFound, "notFound", nil)
} }
func LoadDefaultConfig(gloablConfiguration *GlobalConfiguration) *mux.Router { func LoadDefaultConfig(globalConfiguration *GlobalConfiguration) *mux.Router {
router := mux.NewRouter() router := mux.NewRouter()
router.NotFoundHandler = http.HandlerFunc(notFoundHandler) router.NotFoundHandler = http.HandlerFunc(notFoundHandler)
return router return router

View file

@ -31,7 +31,7 @@ type Backend struct {
} }
type Server struct { type Server struct {
Url string URL string `json:"Url"`
Weight int Weight int
} }

View file

@ -2,13 +2,14 @@ package main
import ( import (
"bytes" "bytes"
"net/http"
"strings"
"text/template"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"github.com/BurntSushi/ty/fun" "github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus" log "github.com/Sirupsen/logrus"
"github.com/hashicorp/consul/api" "github.com/hashicorp/consul/api"
"net/http"
"strings"
"text/template"
) )
type Key struct { type Key struct {

View file

@ -3,15 +3,16 @@ package main
import ( import (
"bytes" "bytes"
"errors" "errors"
"strconv"
"strings"
"text/template"
"time"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"github.com/BurntSushi/ty/fun" "github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus" log "github.com/Sirupsen/logrus"
"github.com/cenkalti/backoff" "github.com/cenkalti/backoff"
"github.com/fsouza/go-dockerclient" "github.com/fsouza/go-dockerclient"
"strconv"
"strings"
"text/template"
"time"
) )
type DockerProvider struct { type DockerProvider struct {

View file

@ -1,12 +1,13 @@
package main package main
import ( import (
"github.com/BurntSushi/toml"
log "github.com/Sirupsen/logrus"
"gopkg.in/fsnotify.v1"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/BurntSushi/toml"
log "github.com/Sirupsen/logrus"
"gopkg.in/fsnotify.v1"
) )
type FileProvider struct { type FileProvider struct {

View file

@ -2,13 +2,14 @@ package main
import ( import (
"bytes" "bytes"
"strconv"
"strings"
"text/template"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"github.com/BurntSushi/ty/fun" "github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus" log "github.com/Sirupsen/logrus"
"github.com/gambol99/go-marathon" "github.com/gambol99/go-marathon"
"strconv"
"strings"
"text/template"
) )
type MarathonProvider struct { type MarathonProvider struct {
@ -62,32 +63,32 @@ func (provider *MarathonProvider) Provide(configurationChan chan<- *Configuratio
config := marathon.NewDefaultConfig() config := marathon.NewDefaultConfig()
config.URL = provider.Endpoint config.URL = provider.Endpoint
config.EventsInterface = provider.NetworkInterface config.EventsInterface = provider.NetworkInterface
if client, err := marathon.NewClient(config); err != nil { client, err := marathon.NewClient(config)
if err != nil {
log.Errorf("Failed to create a client for marathon, error: %s", err) log.Errorf("Failed to create a client for marathon, error: %s", err)
return return
} else {
provider.marathonClient = client
update := make(marathon.EventsChannel, 5)
if provider.Watch {
if err := client.AddEventsListener(update, marathon.EVENTS_APPLICATIONS); err != nil {
log.Errorf("Failed to register for subscriptions, %s", err)
} else {
go func() {
for {
event := <-update
log.Debug("Marathon event receveived", event)
configuration := provider.loadMarathonConfig()
if configuration != nil {
configurationChan <- configuration
}
}
}()
}
}
configuration := provider.loadMarathonConfig()
configurationChan <- configuration
} }
provider.marathonClient = client
update := make(marathon.EventsChannel, 5)
if provider.Watch {
if err := client.AddEventsListener(update, marathon.EVENTS_APPLICATIONS); err != nil {
log.Errorf("Failed to register for subscriptions, %s", err)
} else {
go func() {
for {
event := <-update
log.Debug("Marathon event receveived", event)
configuration := provider.loadMarathonConfig()
if configuration != nil {
configurationChan <- configuration
}
}
}()
}
}
configuration := provider.loadMarathonConfig()
configurationChan <- configuration
} }
func (provider *MarathonProvider) loadMarathonConfig() *Configuration { func (provider *MarathonProvider) loadMarathonConfig() *Configuration {

View file

@ -4,8 +4,9 @@ Copyright
package middlewares package middlewares
import ( import (
"github.com/mailgun/oxy/cbreaker"
"net/http" "net/http"
"github.com/mailgun/oxy/cbreaker"
) )
type CircuitBreaker struct { type CircuitBreaker struct {

View file

@ -4,10 +4,11 @@ Copyright
package middlewares package middlewares
import ( import (
"github.com/gorilla/handlers"
"log" "log"
"net/http" "net/http"
"os" "os"
"github.com/gorilla/handlers"
) )
// Logger is a middleware handler that logs the request as it goes in and the response as it goes out. // Logger is a middleware handler that logs the request as it goes in and the response as it goes out.
@ -23,9 +24,8 @@ func NewLogger(file string) *Logger {
log.Fatal("Error opening file", err) log.Fatal("Error opening file", err)
} }
return &Logger{fi} return &Logger{fi}
} else {
return &Logger{nil}
} }
return &Logger{nil}
} }
func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {

View file

@ -5,9 +5,10 @@ package middlewares
import ( import (
"encoding/json" "encoding/json"
"github.com/gorilla/mux"
"log" "log"
"net/http" "net/http"
"github.com/gorilla/mux"
) )
type Routes struct { type Routes struct {

View file

@ -1,6 +1,17 @@
package main package main
import ( import (
fmtlog "log"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"reflect"
"strings"
"syscall"
"time"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
log "github.com/Sirupsen/logrus" log "github.com/Sirupsen/logrus"
"github.com/codegangsta/negroni" "github.com/codegangsta/negroni"
@ -13,16 +24,6 @@ import (
"github.com/tylerb/graceful" "github.com/tylerb/graceful"
"github.com/unrolled/render" "github.com/unrolled/render"
"gopkg.in/alecthomas/kingpin.v2" "gopkg.in/alecthomas/kingpin.v2"
fmtlog "log"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"reflect"
"strings"
"syscall"
"time"
) )
var ( var (
@ -49,20 +50,20 @@ func main() {
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// load global configuration // load global configuration
gloablConfiguration := LoadFileConfig(*globalConfigFile) globalConfiguration := LoadFileConfig(*globalConfigFile)
loggerMiddleware := middlewares.NewLogger(gloablConfiguration.AccessLogsFile) loggerMiddleware := middlewares.NewLogger(globalConfiguration.AccessLogsFile)
defer loggerMiddleware.Close() defer loggerMiddleware.Close()
// logging // logging
level, err := log.ParseLevel(strings.ToLower(gloablConfiguration.LogLevel)) level, err := log.ParseLevel(strings.ToLower(globalConfiguration.LogLevel))
if err != nil { if err != nil {
log.Fatal("Error getting level", err) log.Fatal("Error getting level", err)
} }
log.SetLevel(level) log.SetLevel(level)
if len(gloablConfiguration.TraefikLogsFile) > 0 { if len(globalConfiguration.TraefikLogsFile) > 0 {
fi, err := os.OpenFile(gloablConfiguration.TraefikLogsFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) fi, err := os.OpenFile(globalConfiguration.TraefikLogsFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
defer fi.Close() defer fi.Close()
if err != nil { if err != nil {
log.Fatal("Error opening file", err) log.Fatal("Error opening file", err)
@ -74,7 +75,7 @@ func main() {
log.SetFormatter(&log.TextFormatter{FullTimestamp: true, DisableSorting: true}) log.SetFormatter(&log.TextFormatter{FullTimestamp: true, DisableSorting: true})
} }
configurationRouter = LoadDefaultConfig(gloablConfiguration) configurationRouter = LoadDefaultConfig(globalConfiguration)
// listen new configurations from providers // listen new configurations from providers
go func() { go func() {
@ -86,11 +87,11 @@ func main() {
} else if reflect.DeepEqual(currentConfiguration, configuration) { } else if reflect.DeepEqual(currentConfiguration, configuration) {
log.Info("Skipping same configuration") log.Info("Skipping same configuration")
} else { } else {
newConfigurationRouter, err := LoadConfig(configuration, gloablConfiguration) newConfigurationRouter, err := LoadConfig(configuration, globalConfiguration)
if err == nil { if err == nil {
currentConfiguration = configuration currentConfiguration = configuration
configurationRouter = newConfigurationRouter configurationRouter = newConfigurationRouter
srv.Stop(time.Duration(gloablConfiguration.GraceTimeOut) * time.Second) srv.Stop(time.Duration(globalConfiguration.GraceTimeOut) * time.Second)
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
} else { } else {
log.Error("Error loading new configuration, aborted ", err) log.Error("Error loading new configuration, aborted ", err)
@ -100,24 +101,24 @@ func main() {
}() }()
// configure providers // configure providers
if gloablConfiguration.Docker != nil { if globalConfiguration.Docker != nil {
providers = append(providers, gloablConfiguration.Docker) providers = append(providers, globalConfiguration.Docker)
} }
if gloablConfiguration.Marathon != nil { if globalConfiguration.Marathon != nil {
providers = append(providers, gloablConfiguration.Marathon) providers = append(providers, globalConfiguration.Marathon)
} }
if gloablConfiguration.File != nil { if globalConfiguration.File != nil {
if len(gloablConfiguration.File.Filename) == 0 { if len(globalConfiguration.File.Filename) == 0 {
// no filename, setting to global config file // no filename, setting to global config file
gloablConfiguration.File.Filename = *globalConfigFile globalConfiguration.File.Filename = *globalConfigFile
} }
providers = append(providers, gloablConfiguration.File) providers = append(providers, globalConfiguration.File)
} }
if gloablConfiguration.Web != nil { if globalConfiguration.Web != nil {
providers = append(providers, gloablConfiguration.Web) providers = append(providers, globalConfiguration.Web)
} }
if gloablConfiguration.Consul != nil { if globalConfiguration.Consul != nil {
providers = append(providers, gloablConfiguration.Consul) providers = append(providers, globalConfiguration.Consul)
} }
// start providers // start providers
@ -134,7 +135,7 @@ func main() {
sig := <-sigs sig := <-sigs
log.Infof("I have to go... %+v", sig) log.Infof("I have to go... %+v", sig)
goAway = true goAway = true
srv.Stop(time.Duration(gloablConfiguration.GraceTimeOut) * time.Second) srv.Stop(time.Duration(globalConfiguration.GraceTimeOut) * time.Second)
}() }()
for { for {
@ -151,18 +152,18 @@ func main() {
negroni.UseHandler(configurationRouter) negroni.UseHandler(configurationRouter)
srv = &graceful.Server{ srv = &graceful.Server{
Timeout: time.Duration(gloablConfiguration.GraceTimeOut) * time.Second, Timeout: time.Duration(globalConfiguration.GraceTimeOut) * time.Second,
NoSignalHandling: true, NoSignalHandling: true,
Server: &http.Server{ Server: &http.Server{
Addr: gloablConfiguration.Port, Addr: globalConfiguration.Port,
Handler: negroni, Handler: negroni,
}, },
} }
go func() { go func() {
if len(gloablConfiguration.CertFile) > 0 && len(gloablConfiguration.KeyFile) > 0 { if len(globalConfiguration.CertFile) > 0 && len(globalConfiguration.KeyFile) > 0 {
err := srv.ListenAndServeTLS(gloablConfiguration.CertFile, gloablConfiguration.KeyFile) err := srv.ListenAndServeTLS(globalConfiguration.CertFile, globalConfiguration.KeyFile)
if err != nil { if err != nil {
netOpError, ok := err.(*net.OpError) netOpError, ok := err.(*net.OpError)
if ok && netOpError.Err.Error() != "use of closed network connection" { if ok && netOpError.Err.Error() != "use of closed network connection" {
@ -185,7 +186,7 @@ func main() {
} }
} }
func LoadConfig(configuration *Configuration, gloablConfiguration *GlobalConfiguration) (*mux.Router, error) { func LoadConfig(configuration *Configuration, globalConfiguration *GlobalConfiguration) (*mux.Router, error) {
router := mux.NewRouter() router := mux.NewRouter()
router.NotFoundHandler = http.HandlerFunc(notFoundHandler) router.NotFoundHandler = http.HandlerFunc(notFoundHandler)
backends := map[string]http.Handler{} backends := map[string]http.Handler{}
@ -203,18 +204,18 @@ func LoadConfig(configuration *Configuration, gloablConfiguration *GlobalConfigu
lb, _ := roundrobin.New(fwd) lb, _ := roundrobin.New(fwd)
rb, _ := roundrobin.NewRebalancer(lb, roundrobin.RebalancerLogger(oxyLogger)) rb, _ := roundrobin.NewRebalancer(lb, roundrobin.RebalancerLogger(oxyLogger))
for serverName, server := range configuration.Backends[frontend.Backend].Servers { for serverName, server := range configuration.Backends[frontend.Backend].Servers {
if url, err := url.Parse(server.Url); err != nil { url, err := url.Parse(server.URL)
if err != nil {
return nil, err return nil, err
} else {
log.Debugf("Creating server %s %s", serverName, url.String())
rb.UpsertServer(url, roundrobin.Weight(server.Weight))
} }
log.Debugf("Creating server %s %s", serverName, url.String())
rb.UpsertServer(url, roundrobin.Weight(server.Weight))
} }
backends[frontend.Backend] = rb backends[frontend.Backend] = rb
} else { } else {
log.Debugf("Reusing backend %s", frontend.Backend) log.Debugf("Reusing backend %s", frontend.Backend)
} }
// stream.New(backends[frontend.Backend], stream.Retry("IsNetworkError() && Attempts() <= " + strconv.Itoa(gloablConfiguration.Replay)), stream.Logger(oxyLogger)) // stream.New(backends[frontend.Backend], stream.Retry("IsNetworkError() && Attempts() <= " + strconv.Itoa(globalConfiguration.Replay)), stream.Logger(oxyLogger))
var negroni = negroni.New() var negroni = negroni.New()
negroni.Use(middlewares.NewCircuitBreaker(backends[frontend.Backend], cbreaker.Logger(oxyLogger))) negroni.Use(middlewares.NewCircuitBreaker(backends[frontend.Backend], cbreaker.Logger(oxyLogger)))
newRoute.Handler(negroni) newRoute.Handler(negroni)

9
web.go
View file

@ -3,11 +3,12 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"net/http"
log "github.com/Sirupsen/logrus" log "github.com/Sirupsen/logrus"
"github.com/elazarl/go-bindata-assetfs" "github.com/elazarl/go-bindata-assetfs"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"io/ioutil"
"net/http"
) )
type WebProvider struct { type WebProvider struct {
@ -21,7 +22,7 @@ type Page struct {
func (provider *WebProvider) Provide(configurationChan chan<- *Configuration) { func (provider *WebProvider) Provide(configurationChan chan<- *Configuration) {
systemRouter := mux.NewRouter() systemRouter := mux.NewRouter()
systemRouter.Methods("GET").Path("/").Handler(http.HandlerFunc(GetHtmlConfigHandler)) systemRouter.Methods("GET").Path("/").Handler(http.HandlerFunc(GetHTMLConfigHandler))
systemRouter.Methods("GET").Path("/health").Handler(http.HandlerFunc(GetHealthHandler)) systemRouter.Methods("GET").Path("/health").Handler(http.HandlerFunc(GetHealthHandler))
systemRouter.Methods("GET").Path("/api").Handler(http.HandlerFunc(GetConfigHandler)) systemRouter.Methods("GET").Path("/api").Handler(http.HandlerFunc(GetConfigHandler))
systemRouter.Methods("PUT").Path("/api").Handler(http.HandlerFunc( systemRouter.Methods("PUT").Path("/api").Handler(http.HandlerFunc(
@ -64,7 +65,7 @@ func GetConfigHandler(rw http.ResponseWriter, r *http.Request) {
templatesRenderer.JSON(rw, http.StatusOK, currentConfiguration) templatesRenderer.JSON(rw, http.StatusOK, currentConfiguration)
} }
func GetHtmlConfigHandler(response http.ResponseWriter, request *http.Request) { func GetHTMLConfigHandler(response http.ResponseWriter, request *http.Request) {
templatesRenderer.HTML(response, http.StatusOK, "configuration", Page{Configuration: *currentConfiguration}) templatesRenderer.HTML(response, http.StatusOK, "configuration", Page{Configuration: *currentConfiguration})
} }