93 lines
2.0 KiB
Go
93 lines
2.0 KiB
Go
package controller
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"time"
|
|
|
|
"example.com/monok8s/pkg/kube"
|
|
|
|
"github.com/emicklei/go-restful/v3"
|
|
"k8s.io/apiserver/pkg/server/httplog"
|
|
)
|
|
|
|
var statusesNoTracePred = httplog.StatusIsNot(
|
|
http.StatusOK,
|
|
http.StatusFound,
|
|
http.StatusMovedPermanently,
|
|
http.StatusTemporaryRedirect,
|
|
http.StatusBadRequest,
|
|
http.StatusNotFound,
|
|
http.StatusSwitchingProtocols,
|
|
)
|
|
|
|
type Server struct {
|
|
restfulCont *restful.Container
|
|
|
|
ctx context.Context
|
|
clients *kube.Clients
|
|
namespace string
|
|
nodeName string
|
|
startedAt time.Time
|
|
}
|
|
|
|
type StatusResponse struct {
|
|
OK bool `json:"ok"`
|
|
Service string `json:"service"`
|
|
Namespace string `json:"namespace,omitempty"`
|
|
NodeName string `json:"nodeName,omitempty"`
|
|
UptimeSec int64 `json:"uptimeSec"`
|
|
}
|
|
|
|
func NewServer(ctx context.Context, clients *kube.Clients, namespace, nodeName string) *Server {
|
|
s := &Server{
|
|
ctx: ctx,
|
|
clients: clients,
|
|
namespace: namespace,
|
|
nodeName: nodeName,
|
|
startedAt: time.Now(),
|
|
}
|
|
s.Initialize()
|
|
return s
|
|
}
|
|
|
|
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
if s == nil {
|
|
http.Error(w, "server is nil", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if s.restfulCont == nil {
|
|
http.Error(w, "server not initialized", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
handler := httplog.WithLogging(s.restfulCont, statusesNoTracePred)
|
|
handler.ServeHTTP(w, req)
|
|
}
|
|
|
|
func (s *Server) Initialize() {
|
|
s.restfulCont = restful.NewContainer()
|
|
|
|
ws := new(restful.WebService)
|
|
ws.Path("/")
|
|
ws.Consumes(restful.MIME_JSON)
|
|
ws.Produces(restful.MIME_JSON)
|
|
|
|
ws.Route(ws.GET("/status").To(s.queryStatus).
|
|
Doc("Return basic controller status"))
|
|
|
|
s.restfulCont.Add(ws)
|
|
}
|
|
|
|
func (s *Server) queryStatus(request *restful.Request, response *restful.Response) {
|
|
resp := StatusResponse{
|
|
OK: true,
|
|
Service: "monok8s-controller",
|
|
Namespace: s.namespace,
|
|
NodeName: s.nodeName,
|
|
UptimeSec: int64(time.Since(s.startedAt).Seconds()),
|
|
}
|
|
|
|
_ = response.WriteHeaderAndEntity(http.StatusOK, resp)
|
|
}
|