diff --git a/api/events.go b/api/events.go new file mode 100644 index 0000000..56b70ae --- /dev/null +++ b/api/events.go @@ -0,0 +1,20 @@ +package api + +import ( + "fmt" + "net/http" + + "github.com/Sirupsen/logrus" +) + +func Events(eventChannel chan *logrus.Entry) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + logrus.Info("New events") + flusher, _ := w.(http.Flusher) + for { + e := <-eventChannel + fmt.Fprintf(w, "Ciao %d\n", e.Message) + flusher.Flush() // Trigger "chunked" encoding and send a chunk... + } + } +} diff --git a/api/router.go b/api/router.go index 5961a75..94c789f 100644 --- a/api/router.go +++ b/api/router.go @@ -1,13 +1,15 @@ package api import ( + "github.com/Sirupsen/logrus" "github.com/gianarb/orbiter/core" "github.com/gorilla/mux" ) -func GetRouter(core core.Core) *mux.Router { +func GetRouter(core core.Core, eventChannel chan *logrus.Entry) *mux.Router { r := mux.NewRouter() r.HandleFunc("/handle/{autoscaler_name}/{service_name}", Handle(core.Autoscalers)).Methods("POST") r.HandleFunc("/health", Health()).Methods("GET") + r.HandleFunc("/events", Events(eventChannel)).Methods("GET") return r } diff --git a/cmd/daemon.go b/cmd/daemon.go index ac2d43e..4398cc7 100644 --- a/cmd/daemon.go +++ b/cmd/daemon.go @@ -15,6 +15,7 @@ import ( ) type DaemonCmd struct { + EventChannel chan *logrus.Entry } func (c *DaemonCmd) Run(args []string) int { @@ -51,7 +52,7 @@ func (c *DaemonCmd) Run(args []string) int { logrus.Info("Stopping and cleaning. Bye!") os.Exit(0) }() - router := api.GetRouter(core) + router := api.GetRouter(core, c.EventChannel) logrus.Infof("API Server run on port %s", port) http.ListenAndServe(port, router) return 0 diff --git a/main.go b/main.go index b9ce0d7..6731bd1 100644 --- a/main.go +++ b/main.go @@ -3,17 +3,22 @@ package main import ( "os" + "github.com/Sirupsen/logrus" "github.com/gianarb/orbiter/cmd" + "github.com/gianarb/orbiter/utils/hook" "github.com/mitchellh/cli" ) func main() { + eventChannel := make(chan *logrus.Entry) + logrus.AddHook(hook.NewChannelHook(eventChannel)) + c := cli.NewCLI("orbiter", "0.0.0") c.Args = os.Args[1:] c.Commands = map[string]cli.CommandFactory{ "daemon": func() (cli.Command, error) { - return &cmd.DaemonCmd{}, nil + return &cmd.DaemonCmd{eventChannel}, nil }, } diff --git a/utils/hook/channel.go b/utils/hook/channel.go new file mode 100644 index 0000000..954a31c --- /dev/null +++ b/utils/hook/channel.go @@ -0,0 +1,26 @@ +package hook + +import "github.com/Sirupsen/logrus" + +type Channel struct { + c chan *logrus.Entry +} + +func NewChannelHook(cc chan *logrus.Entry) Channel { + return Channel{ + c: cc, + } +} + +func (channel Channel) Levels() []logrus.Level { + return logrus.AllLevels +} + +func (channel Channel) Fire(entry *logrus.Entry) error { + select { + case channel.c <- entry: + default: + } + + return nil +}