mc-router/server/routes.go

191 lines
4.9 KiB
Go
Raw Normal View History

2018-05-08 05:16:01 +02:00
package server
import (
2022-01-07 00:41:10 +01:00
"context"
2018-05-08 05:16:01 +02:00
"encoding/json"
"net/http"
2019-04-28 23:49:43 +02:00
"strings"
"sync"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
2018-05-08 05:16:01 +02:00
)
func init() {
apiRoutes.Path("/routes").Methods("GET").
Headers("Accept", "application/json").
HandlerFunc(routesListHandler)
apiRoutes.Path("/routes").Methods("POST").
Headers("Content-Type", "application/json").
HandlerFunc(routesCreateHandler)
apiRoutes.Path("/defaultRoute").Methods("POST").
Headers("Content-Type", "application/json").
HandlerFunc(routesSetDefault)
2018-05-08 05:16:01 +02:00
apiRoutes.Path("/routes/{serverAddress}").Methods("DELETE").HandlerFunc(routesDeleteHandler)
}
func routesListHandler(writer http.ResponseWriter, request *http.Request) {
mappings := Routes.GetMappings()
bytes, err := json.Marshal(mappings)
if err != nil {
logrus.WithError(err).Error("Failed to marshal mappings")
writer.WriteHeader(http.StatusInternalServerError)
return
}
writer.Write(bytes)
}
func routesDeleteHandler(writer http.ResponseWriter, request *http.Request) {
serverAddress := mux.Vars(request)["serverAddress"]
if serverAddress != "" {
if Routes.DeleteMapping(serverAddress) {
writer.WriteHeader(http.StatusOK)
} else {
writer.WriteHeader(http.StatusNotFound)
}
}
}
func routesCreateHandler(writer http.ResponseWriter, request *http.Request) {
var definition = struct {
ServerAddress string
Backend string
2018-05-08 05:16:01 +02:00
}{}
defer request.Body.Close()
decoder := json.NewDecoder(request.Body)
err := decoder.Decode(&definition)
if err != nil {
logrus.WithError(err).Error("Unable to get request body")
writer.WriteHeader(http.StatusBadRequest)
return
}
2022-01-07 00:41:10 +01:00
Routes.CreateMapping(definition.ServerAddress, definition.Backend, func(ctx context.Context) error { return nil })
2018-05-08 05:16:01 +02:00
writer.WriteHeader(http.StatusCreated)
}
func routesSetDefault(writer http.ResponseWriter, request *http.Request) {
var body = struct {
Backend string
}{}
defer request.Body.Close()
decoder := json.NewDecoder(request.Body)
err := decoder.Decode(&body)
if err != nil {
logrus.WithError(err).Error("Unable to parse request")
writer.WriteHeader(http.StatusBadRequest)
return
}
Routes.SetDefaultRoute(body.Backend)
writer.WriteHeader(http.StatusOK)
}
2018-05-08 05:16:01 +02:00
type IRoutes interface {
RegisterAll(mappings map[string]string)
// FindBackendForServerAddress returns the host:port for the external server address, if registered.
2022-01-07 00:41:10 +01:00
// Otherwise, an empty string is returned. Also returns the normalized version of the given serverAddress.
// The 3rd value returned is an (optional) "waker" function which a caller must invoke to wake up serverAddress.
FindBackendForServerAddress(ctx context.Context, serverAddress string) (string, string, func(ctx context.Context) error)
2018-05-08 05:16:01 +02:00
GetMappings() map[string]string
DeleteMapping(serverAddress string) bool
2022-01-07 00:41:10 +01:00
CreateMapping(serverAddress string, backend string, waker func(ctx context.Context) error)
SetDefaultRoute(backend string)
2018-05-08 05:16:01 +02:00
}
var Routes IRoutes = &routesImpl{}
2019-04-28 23:49:43 +02:00
func NewRoutes() IRoutes {
r := &routesImpl{
2022-01-07 00:41:10 +01:00
mappings: make(map[string]mapping),
2019-04-28 23:49:43 +02:00
}
return r
}
2018-05-08 05:16:01 +02:00
func (r *routesImpl) RegisterAll(mappings map[string]string) {
r.Lock()
defer r.Unlock()
2022-01-07 00:41:10 +01:00
r.mappings = make(map[string]mapping)
for k, v := range mappings {
r.mappings[k] = mapping{backend: v, waker: func(ctx context.Context) error { return nil }}
}
}
type mapping struct {
backend string
waker func(ctx context.Context) error
2018-05-08 05:16:01 +02:00
}
type routesImpl struct {
sync.RWMutex
2022-01-07 00:41:10 +01:00
mappings map[string]mapping
defaultRoute string
}
func (r *routesImpl) SetDefaultRoute(backend string) {
r.defaultRoute = backend
logrus.WithFields(logrus.Fields{
"backend": backend,
}).Info("Using default route")
2018-05-08 05:16:01 +02:00
}
2022-01-07 00:41:10 +01:00
func (r *routesImpl) FindBackendForServerAddress(ctx context.Context, serverAddress string) (string, string, func(ctx context.Context) error) {
2018-05-08 05:16:01 +02:00
r.RLock()
defer r.RUnlock()
2019-04-29 00:02:21 +02:00
addressParts := strings.Split(serverAddress, "\x00")
2019-04-28 23:49:43 +02:00
address := strings.ToLower(addressParts[0])
2019-06-25 20:31:49 +02:00
if r.mappings != nil {
2022-01-07 00:41:10 +01:00
if mapping, exists := r.mappings[address]; exists {
return mapping.backend, address, mapping.waker
}
2018-05-08 05:16:01 +02:00
}
2022-01-07 00:41:10 +01:00
return r.defaultRoute, address, nil
2018-05-08 05:16:01 +02:00
}
func (r *routesImpl) GetMappings() map[string]string {
r.RLock()
defer r.RUnlock()
result := make(map[string]string, len(r.mappings))
for k, v := range r.mappings {
2022-01-07 00:41:10 +01:00
result[k] = v.backend
2018-05-08 05:16:01 +02:00
}
return result
}
func (r *routesImpl) DeleteMapping(serverAddress string) bool {
r.Lock()
defer r.Unlock()
logrus.WithField("serverAddress", serverAddress).Info("Deleting route")
if _, ok := r.mappings[serverAddress]; ok {
delete(r.mappings, serverAddress)
return true
} else {
return false
}
}
2022-01-07 00:41:10 +01:00
func (r *routesImpl) CreateMapping(serverAddress string, backend string, waker func(ctx context.Context) error) {
2018-05-08 05:16:01 +02:00
r.Lock()
defer r.Unlock()
serverAddress = strings.ToLower(serverAddress)
2019-06-25 20:31:49 +02:00
2018-05-08 05:16:01 +02:00
logrus.WithFields(logrus.Fields{
"serverAddress": serverAddress,
"backend": backend,
2018-05-08 05:16:01 +02:00
}).Info("Creating route")
2022-01-07 00:41:10 +01:00
r.mappings[serverAddress] = mapping{backend: backend, waker: waker}
}