github.com/yasker/longhorn-engine@v0.0.0-20160621014712-6ed6cfca0729/controller/rest/replica.go (about) 1 package rest 2 3 import ( 4 "net/http" 5 6 "github.com/gorilla/mux" 7 "github.com/rancher/go-rancher/api" 8 "github.com/rancher/go-rancher/client" 9 "github.com/rancher/longhorn/types" 10 ) 11 12 func (s *Server) ListReplicas(rw http.ResponseWriter, req *http.Request) error { 13 apiContext := api.GetApiContext(req) 14 resp := client.GenericCollection{} 15 for _, r := range s.c.ListReplicas() { 16 resp.Data = append(resp.Data, NewReplica(r.Address, r.Mode)) 17 } 18 19 resp.ResourceType = "replica" 20 resp.CreateTypes = map[string]string{ 21 "replica": apiContext.UrlBuilder.Collection("replica"), 22 } 23 24 apiContext.Write(&resp) 25 return nil 26 } 27 28 func (s *Server) GetReplica(rw http.ResponseWriter, req *http.Request) error { 29 apiContext := api.GetApiContext(req) 30 vars := mux.Vars(req) 31 id, err := DencodeID(vars["id"]) 32 if err != nil { 33 rw.WriteHeader(http.StatusNotFound) 34 return nil 35 } 36 37 apiContext.Write(s.getReplica(id)) 38 return nil 39 } 40 41 func (s *Server) CreateReplica(rw http.ResponseWriter, req *http.Request) error { 42 var replica Replica 43 apiContext := api.GetApiContext(req) 44 if err := apiContext.Read(&replica); err != nil { 45 return err 46 } 47 48 if err := s.c.AddReplica(replica.Address); err != nil { 49 return err 50 } 51 52 apiContext.Write(s.getReplica(replica.Address)) 53 return nil 54 } 55 56 func (s *Server) getReplica(id string) *Replica { 57 for _, r := range s.c.ListReplicas() { 58 if r.Address == id { 59 return NewReplica(r.Address, r.Mode) 60 } 61 } 62 return nil 63 } 64 65 func (s *Server) DeleteReplica(rw http.ResponseWriter, req *http.Request) error { 66 vars := mux.Vars(req) 67 id, err := DencodeID(vars["id"]) 68 if err != nil { 69 rw.WriteHeader(http.StatusNotFound) 70 return nil 71 } 72 73 return s.c.RemoveReplica(id) 74 } 75 76 func (s *Server) UpdateReplica(rw http.ResponseWriter, req *http.Request) error { 77 vars := mux.Vars(req) 78 id, err := DencodeID(vars["id"]) 79 if err != nil { 80 rw.WriteHeader(http.StatusNotFound) 81 return nil 82 } 83 84 var replica Replica 85 apiContext := api.GetApiContext(req) 86 apiContext.Read(&replica) 87 88 if err := s.c.SetReplicaMode(id, types.Mode(replica.Mode)); err != nil { 89 return err 90 } 91 92 apiContext.Write(s.getReplica(id)) 93 return nil 94 }