github.com/xmidt-org/webpa-common@v1.11.9/device/drain/start.go (about) 1 package drain 2 3 import ( 4 "encoding/json" 5 "io/ioutil" 6 "net/http" 7 "time" 8 9 "github.com/go-kit/kit/log/level" 10 "github.com/gorilla/schema" 11 "github.com/xmidt-org/webpa-common/device/devicegate" 12 "github.com/xmidt-org/webpa-common/logging" 13 "github.com/xmidt-org/webpa-common/xhttp" 14 "github.com/xmidt-org/webpa-common/xhttp/converter" 15 ) 16 17 type Start struct { 18 Drainer Interface 19 } 20 21 func (s *Start) ServeHTTP(response http.ResponseWriter, request *http.Request) { 22 logger := logging.GetLogger(request.Context()) 23 if err := request.ParseForm(); err != nil { 24 logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "unable to parse form", logging.ErrorKey(), err) 25 xhttp.WriteError(response, http.StatusBadRequest, err) 26 return 27 } 28 29 var ( 30 decoder = schema.NewDecoder() 31 input Job 32 reqBody devicegate.FilterRequest 33 ) 34 35 decoder.RegisterConverter(time.Duration(0), converter.Duration) 36 if err := decoder.Decode(&input, request.Form); err != nil { 37 logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "unable to decode request", logging.ErrorKey(), err) 38 xhttp.WriteError(response, http.StatusBadRequest, err) 39 return 40 } 41 42 msgBytes, e := ioutil.ReadAll(request.Body) 43 defer request.Body.Close() 44 45 if e != nil { 46 logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "unable to read request body", logging.ErrorKey(), e) 47 xhttp.WriteError(response, http.StatusBadRequest, e) 48 return 49 } 50 51 if len(msgBytes) > 0 { 52 if err := json.Unmarshal(msgBytes, &reqBody); err != nil { 53 logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "unable to unmarshal request body", logging.ErrorKey(), err) 54 xhttp.WriteError(response, http.StatusBadRequest, err) 55 return 56 } 57 58 if len(reqBody.Key) > 0 && len(reqBody.Values) > 0 { 59 fg := devicegate.FilterGate{FilterStore: make(devicegate.FilterStore)} 60 fg.SetFilter(reqBody.Key, reqBody.Values) 61 62 input.DrainFilter = &drainFilter{ 63 filter: &fg, 64 filterRequest: reqBody, 65 } 66 } 67 } 68 69 _, output, err := s.Drainer.Start(input) 70 if err != nil { 71 logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "unable to start drain job", logging.ErrorKey(), err) 72 xhttp.WriteError(response, http.StatusConflict, err) 73 return 74 } 75 76 if message, err := json.Marshal(output.ToMap()); err != nil { 77 logger.Log(level.Key(), level.ErrorValue(), logging.MessageKey(), "unable to marshal response", logging.ErrorKey(), err) 78 } else { 79 response.Header().Set("Content-Type", "application/json") 80 response.Write(message) 81 } 82 }