Event stream

This commit is contained in:
Gianluca Arbezzano 2017-02-24 00:16:28 +00:00
parent 92aa62d363
commit 1709cf5150
5 changed files with 57 additions and 3 deletions

20
api/events.go Normal file
View File

@ -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...
}
}
}

View File

@ -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
}

View File

@ -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

View File

@ -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
},
}

26
utils/hook/channel.go Normal file
View File

@ -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
}