-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathstate.go
74 lines (65 loc) · 1.77 KB
/
state.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package web
import (
"io"
"net/http"
"github.com/cybozu-go/sabakan/v2"
)
func (s Server) handleState(w http.ResponseWriter, r *http.Request) {
serial := r.URL.Path[len("/api/v1/state/"):]
if len(serial) == 0 {
renderError(r.Context(), w, APIErrBadRequest)
return
}
switch r.Method {
case "GET":
s.handleStateGet(w, r, serial)
return
case "PUT":
s.handleStatePut(w, r, serial)
return
}
renderError(r.Context(), w, APIErrBadMethod)
}
func (s Server) handleStateGet(w http.ResponseWriter, r *http.Request, serial string) {
m, err := s.Model.Machine.Get(r.Context(), serial)
switch err {
case sabakan.ErrNotFound:
renderError(r.Context(), w, APIErrNotFound)
return
case nil:
default:
renderError(r.Context(), w, InternalServerError(err))
return
}
w.Header().Set("content-type", "text/plain")
io.WriteString(w, m.Status.State.String())
}
func (s Server) handleStatePut(w http.ResponseWriter, r *http.Request, serial string) {
state, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 128))
if err != nil {
renderError(r.Context(), w, InternalServerError(err))
return
}
ms := sabakan.MachineState(state)
switch ms {
case sabakan.StateUninitialized, sabakan.StateHealthy, sabakan.StateUnhealthy, sabakan.StateUnreachable, sabakan.StateUpdating, sabakan.StateRetiring, sabakan.StateRetired:
default:
renderError(r.Context(), w, BadRequest("invalid state: "+string(state)))
return
}
err = s.Model.Machine.SetState(r.Context(), serial, ms)
if err == nil {
return
}
switch err {
case sabakan.ErrNotFound:
renderError(r.Context(), w, APIErrNotFound)
return
case sabakan.ErrBadRequest, sabakan.ErrEncryptionKeyExists:
renderError(r.Context(), w, APIErrBadRequest)
return
default:
renderError(r.Context(), w, InternalServerError(err))
return
}
}