server.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package remote
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "net"
  19. "net/http"
  20. "net/url"
  21. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  22. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/gorilla/mux"
  23. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  24. "github.com/coreos/flannel/subnet"
  25. )
  26. type handler func(context.Context, subnet.Manager, http.ResponseWriter, *http.Request)
  27. func jsonResponse(w http.ResponseWriter, code int, v interface{}) {
  28. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  29. w.WriteHeader(code)
  30. if err := json.NewEncoder(w).Encode(v); err != nil {
  31. log.Error("Error JSON encoding response: %v", err)
  32. }
  33. }
  34. // GET /{network}/config
  35. func handleGetNetworkConfig(ctx context.Context, sm subnet.Manager, w http.ResponseWriter, r *http.Request) {
  36. defer r.Body.Close()
  37. network := mux.Vars(r)["network"]
  38. if network == "_" {
  39. network = ""
  40. }
  41. c, err := sm.GetNetworkConfig(ctx, network)
  42. if err != nil {
  43. w.WriteHeader(http.StatusInternalServerError)
  44. fmt.Fprint(w, err)
  45. return
  46. }
  47. jsonResponse(w, http.StatusOK, c)
  48. }
  49. // POST /{network}/leases
  50. func handleAcquireLease(ctx context.Context, sm subnet.Manager, w http.ResponseWriter, r *http.Request) {
  51. defer r.Body.Close()
  52. network := mux.Vars(r)["network"]
  53. if network == "_" {
  54. network = ""
  55. }
  56. attrs := subnet.LeaseAttrs{}
  57. if err := json.NewDecoder(r.Body).Decode(&attrs); err != nil {
  58. w.WriteHeader(http.StatusBadRequest)
  59. fmt.Fprint(w, "JSON decoding error: ", err)
  60. return
  61. }
  62. lease, err := sm.AcquireLease(ctx, network, &attrs)
  63. if err != nil {
  64. w.WriteHeader(http.StatusInternalServerError)
  65. fmt.Fprint(w, err)
  66. return
  67. }
  68. jsonResponse(w, http.StatusOK, lease)
  69. }
  70. // PUT /{network}/{lease.network}
  71. func handleRenewLease(ctx context.Context, sm subnet.Manager, w http.ResponseWriter, r *http.Request) {
  72. defer r.Body.Close()
  73. network := mux.Vars(r)["network"]
  74. if network == "_" {
  75. network = ""
  76. }
  77. lease := subnet.Lease{}
  78. if err := json.NewDecoder(r.Body).Decode(&lease); err != nil {
  79. w.WriteHeader(http.StatusBadRequest)
  80. fmt.Fprint(w, "JSON decoding error: ", err)
  81. return
  82. }
  83. if err := sm.RenewLease(ctx, network, &lease); err != nil {
  84. w.WriteHeader(http.StatusInternalServerError)
  85. fmt.Fprint(w, err)
  86. return
  87. }
  88. jsonResponse(w, http.StatusOK, lease)
  89. }
  90. func getCursor(u *url.URL) interface{} {
  91. vals, ok := u.Query()["next"]
  92. if !ok {
  93. return nil
  94. }
  95. return vals[0]
  96. }
  97. // GET /{network}/leases?next=cursor
  98. func handleWatchLeases(ctx context.Context, sm subnet.Manager, w http.ResponseWriter, r *http.Request) {
  99. defer r.Body.Close()
  100. network := mux.Vars(r)["network"]
  101. if network == "_" {
  102. network = ""
  103. }
  104. cursor := getCursor(r.URL)
  105. wr, err := sm.WatchLeases(ctx, network, cursor)
  106. if err != nil {
  107. w.WriteHeader(http.StatusInternalServerError)
  108. fmt.Fprint(w, err)
  109. return
  110. }
  111. switch wr.Cursor.(type) {
  112. case string:
  113. case fmt.Stringer:
  114. wr.Cursor = wr.Cursor.(fmt.Stringer).String()
  115. default:
  116. w.WriteHeader(http.StatusInternalServerError)
  117. fmt.Fprint(w, fmt.Errorf("internal error: watch cursor is of unknown type"))
  118. return
  119. }
  120. jsonResponse(w, http.StatusOK, wr)
  121. }
  122. func bindHandler(h handler, ctx context.Context, sm subnet.Manager) http.HandlerFunc {
  123. return func(resp http.ResponseWriter, req *http.Request) {
  124. h(ctx, sm, resp, req)
  125. }
  126. }
  127. func RunServer(ctx context.Context, sm subnet.Manager, listenAddr string) {
  128. // {network} is always required a the API level but to
  129. // keep backward compat, special "_" network is allowed
  130. // that means "no network"
  131. r := mux.NewRouter()
  132. r.HandleFunc("/{network}/config", bindHandler(handleGetNetworkConfig, ctx, sm)).Methods("GET")
  133. r.HandleFunc("/{network}/leases", bindHandler(handleAcquireLease, ctx, sm)).Methods("POST")
  134. r.HandleFunc("/{network}/leases/{subnet}", bindHandler(handleRenewLease, ctx, sm)).Methods("PUT")
  135. r.HandleFunc("/{network}/leases", bindHandler(handleWatchLeases, ctx, sm)).Methods("GET")
  136. l, err := net.Listen("tcp", listenAddr)
  137. if err != nil {
  138. log.Errorf("Error listening on %v: %v", listenAddr, err)
  139. return
  140. }
  141. c := make(chan error, 1)
  142. go func() {
  143. c <- http.Serve(l, httpLogger(r))
  144. }()
  145. select {
  146. case <-ctx.Done():
  147. l.Close()
  148. <-c
  149. case err := <-c:
  150. log.Errorf("Error serving on %v: %v", listenAddr, err)
  151. }
  152. }