2019-04-07 23:28:01 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2019-04-07 23:58:56 +00:00
|
|
|
"fmt"
|
2019-04-20 06:29:52 +00:00
|
|
|
"github.com/julienschmidt/httprouter"
|
2019-04-07 23:28:01 +00:00
|
|
|
"go.uber.org/zap"
|
2019-04-20 06:29:52 +00:00
|
|
|
"net/http"
|
2019-04-20 18:59:28 +00:00
|
|
|
"strings"
|
2019-04-07 23:28:01 +00:00
|
|
|
)
|
|
|
|
|
2019-04-20 06:29:52 +00:00
|
|
|
type WebsocketMessage struct {
|
2019-04-20 18:59:28 +00:00
|
|
|
// The event to perform. Should be one of the following that are supported:
|
2019-04-20 06:29:52 +00:00
|
|
|
//
|
|
|
|
// - status : Returns the server's power state.
|
|
|
|
// - logs : Returns the server log data at the time of the request.
|
|
|
|
// - power : Performs a power action aganist the server based the data.
|
|
|
|
// - command : Performs a command on a server using the data field.
|
2019-04-20 18:59:28 +00:00
|
|
|
Event string `json:"event"`
|
2019-04-07 23:28:01 +00:00
|
|
|
|
2019-04-20 06:29:52 +00:00
|
|
|
// The data to pass along, only used by power/command currently. Other requests
|
2019-04-20 18:59:28 +00:00
|
|
|
// should either omit the field or pass an empty value as it is ignored.
|
|
|
|
Args []string `json:"args,omitempty"`
|
2019-04-20 06:29:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (rt *Router) routeWebsocket(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
|
|
|
c, err := rt.upgrader.Upgrade(w, r, nil)
|
2019-04-07 23:28:01 +00:00
|
|
|
if err != nil {
|
2019-04-20 06:29:52 +00:00
|
|
|
zap.S().Error(err)
|
|
|
|
return
|
2019-04-07 23:28:01 +00:00
|
|
|
}
|
2019-04-20 06:29:52 +00:00
|
|
|
defer c.Close()
|
|
|
|
|
2019-04-20 18:59:28 +00:00
|
|
|
s := rt.Servers.Get(ps.ByName("server"))
|
|
|
|
|
2019-04-20 06:29:52 +00:00
|
|
|
for {
|
|
|
|
j := WebsocketMessage{}
|
2019-04-07 23:28:01 +00:00
|
|
|
|
2019-04-20 06:29:52 +00:00
|
|
|
// Discard and JSON parse errors into the void and don't continue processing this
|
|
|
|
// specific socket request. If we did a break here the client would get disconnected
|
|
|
|
// from the socket, which is NOT what we want to do.
|
|
|
|
if err := c.ReadJSON(&j); err != nil {
|
2019-04-20 18:59:28 +00:00
|
|
|
break
|
2019-04-20 06:29:52 +00:00
|
|
|
}
|
2019-04-07 23:28:01 +00:00
|
|
|
|
2019-04-20 18:59:28 +00:00
|
|
|
fmt.Printf("%s sent: %s = %s\n", s.Uuid, j.Event, strings.Join(j.Args, " "))
|
2019-04-07 23:28:01 +00:00
|
|
|
|
2019-04-20 18:59:28 +00:00
|
|
|
if err := c.WriteJSON(WebsocketMessage{Event: j.Event, Args: []string{}}); err != nil {
|
2019-04-20 06:29:52 +00:00
|
|
|
zap.S().Warnw("error writing JSON to socket", zap.Error(err))
|
2019-04-20 18:59:28 +00:00
|
|
|
break
|
2019-04-20 06:29:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|