From 46862ae319e0719e798950be6575977cab28315b Mon Sep 17 00:00:00 2001 From: Stefan Prodan Date: Sat, 27 Jan 2018 18:37:42 +0200 Subject: [PATCH] long running job --- README.md | 2 ++ pkg/server/handlers.go | 36 ++++++++++++++++++++++++++++++++++++ pkg/server/server.go | 1 + 3 files changed, 39 insertions(+) diff --git a/README.md b/README.md index e28ddf2..b93204c 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,8 @@ Web API: * `POST /readyz/enable` signals the Kubernetes LB that this instance is ready to receive traffic * `POST /readyz/disable` signals the Kubernetes LB to stop sending requests to this instance * `GET /panic` crashes the process with exit code 255 +* `POST /echo` echos the posted content +* `POST /job` long running job, json body: `{"wait":2}` ### Deployment diff --git a/pkg/server/handlers.go b/pkg/server/handlers.go index 2e2ade2..58c5c22 100644 --- a/pkg/server/handlers.go +++ b/pkg/server/handlers.go @@ -8,6 +8,8 @@ import ( "github.com/golang/glog" "github.com/stefanprodan/k8s-podinfo/pkg/version" "gopkg.in/yaml.v2" + "encoding/json" + "time" ) func (s *Server) index(w http.ResponseWriter, r *http.Request) { @@ -53,6 +55,40 @@ func (s *Server) echo(w http.ResponseWriter, r *http.Request) { } } +func (s *Server) job(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case "POST": + body, err := ioutil.ReadAll(r.Body) + if err != nil { + glog.Errorf("Reading the request body failed: %v", err) + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + glog.Infof("Payload received from %s: %s", r.RemoteAddr, string(body)) + + job := struct{ + Wait int `json:"wait"` + }{ + Wait: 0, + } + err = json.Unmarshal(body, &job) + if err != nil { + glog.Errorf("Reading the request body failed: %v", err) + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + if job.Wait > 0 { + time.Sleep(time.Duration(job.Wait) * time.Second) + } + w.WriteHeader(http.StatusAccepted) + w.Write([]byte("Job done")) + default: + w.WriteHeader(http.StatusNotAcceptable) + } +} + func (s *Server) version(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/version" { w.WriteHeader(http.StatusNotFound) diff --git a/pkg/server/server.go b/pkg/server/server.go index 22779be..249cd6c 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -33,6 +33,7 @@ func NewServer(options ...func(*Server)) *Server { s.mux.HandleFunc("/readyz/enable", s.enable) s.mux.HandleFunc("/readyz/disable", s.disable) s.mux.HandleFunc("/echo", s.echo) + s.mux.HandleFunc("/job", s.job) s.mux.HandleFunc("/panic", s.panic) s.mux.HandleFunc("/version", s.version) s.mux.Handle("/metrics", promhttp.Handler())