server.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. "strconv"
  22. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  23. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/gorilla/mux"
  24. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  25. "github.com/coreos/flannel/subnet"
  26. )
  27. type handler func(context.Context, subnet.Manager, http.ResponseWriter, *http.Request)
  28. func jsonResponse(w http.ResponseWriter, code int, v interface{}) {
  29. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  30. w.WriteHeader(code)
  31. if err := json.NewEncoder(w).Encode(v); err != nil {
  32. log.Error("Error JSON encoding response: %v", err)
  33. }
  34. }
  35. // GET /{network}/config
  36. func handleGetNetworkConfig(ctx context.Context, sm subnet.Manager, w http.ResponseWriter, r *http.Request) {
  37. defer r.Body.Close()
  38. network := mux.Vars(r)["network"]
  39. if network == "_" {
  40. network = ""
  41. }
  42. c, err := sm.GetNetworkConfig(ctx, network)
  43. if err != nil {
  44. w.WriteHeader(http.StatusInternalServerError)
  45. fmt.Fprint(w, err)
  46. return
  47. }
  48. jsonResponse(w, http.StatusOK, c)
  49. }
  50. // POST /{network}/leases
  51. func handleAcquireLease(ctx context.Context, sm subnet.Manager, w http.ResponseWriter, r *http.Request) {
  52. defer r.Body.Close()
  53. network := mux.Vars(r)["network"]
  54. if network == "_" {
  55. network = ""
  56. }
  57. attrs := subnet.LeaseAttrs{}
  58. if err := json.NewDecoder(r.Body).Decode(&attrs); err != nil {
  59. w.WriteHeader(http.StatusBadRequest)
  60. fmt.Fprint(w, "JSON decoding error: ", err)
  61. return
  62. }
  63. lease, err := sm.AcquireLease(ctx, network, &attrs)
  64. if err != nil {
  65. w.WriteHeader(http.StatusInternalServerError)
  66. fmt.Fprint(w, err)
  67. return
  68. }
  69. jsonResponse(w, http.StatusOK, lease)
  70. }
  71. // PUT /{network}/{lease.network}
  72. func handleRenewLease(ctx context.Context, sm subnet.Manager, w http.ResponseWriter, r *http.Request) {
  73. defer r.Body.Close()
  74. network := mux.Vars(r)["network"]
  75. if network == "_" {
  76. network = ""
  77. }
  78. lease := subnet.Lease{}
  79. if err := json.NewDecoder(r.Body).Decode(&lease); err != nil {
  80. w.WriteHeader(http.StatusBadRequest)
  81. fmt.Fprint(w, "JSON decoding error: ", err)
  82. return
  83. }
  84. if err := sm.RenewLease(ctx, network, &lease); err != nil {
  85. w.WriteHeader(http.StatusInternalServerError)
  86. fmt.Fprint(w, err)
  87. return
  88. }
  89. jsonResponse(w, http.StatusOK, lease)
  90. }
  91. func getCursor(u *url.URL) (interface{}, error) {
  92. vals, ok := u.Query()["next"]
  93. if !ok {
  94. return nil, nil
  95. }
  96. index, err := strconv.ParseUint(vals[0], 10, 64)
  97. return index, err
  98. }
  99. // GET /{network}/leases?next=cursor
  100. func handleWatchLeases(ctx context.Context, sm subnet.Manager, w http.ResponseWriter, r *http.Request) {
  101. defer r.Body.Close()
  102. network := mux.Vars(r)["network"]
  103. if network == "_" {
  104. network = ""
  105. }
  106. cursor, err := getCursor(r.URL)
  107. if err != nil {
  108. w.WriteHeader(http.StatusBadRequest)
  109. fmt.Fprint(w, "invalid 'next' value: ", err)
  110. return
  111. }
  112. wr, err := sm.WatchLeases(ctx, network, cursor)
  113. if err != nil {
  114. w.WriteHeader(http.StatusInternalServerError)
  115. fmt.Fprint(w, err)
  116. return
  117. }
  118. jsonResponse(w, http.StatusOK, wr)
  119. }
  120. func bindHandler(h handler, ctx context.Context, sm subnet.Manager) http.HandlerFunc {
  121. return func(resp http.ResponseWriter, req *http.Request) {
  122. h(ctx, sm, resp, req)
  123. }
  124. }
  125. func RunServer(ctx context.Context, sm subnet.Manager, listenAddr string) {
  126. // {network} is always required a the API level but to
  127. // keep backward compat, special "_" network is allowed
  128. // that means "no network"
  129. r := mux.NewRouter()
  130. r.HandleFunc("/{network}/config", bindHandler(handleGetNetworkConfig, ctx, sm)).Methods("GET")
  131. r.HandleFunc("/{network}/leases", bindHandler(handleAcquireLease, ctx, sm)).Methods("POST")
  132. r.HandleFunc("/{network}/leases/{subnet}", bindHandler(handleRenewLease, ctx, sm)).Methods("PUT")
  133. r.HandleFunc("/{network}/leases", bindHandler(handleWatchLeases, ctx, sm)).Methods("GET")
  134. l, err := net.Listen("tcp", listenAddr)
  135. if err != nil {
  136. log.Errorf("Error listening on %v: %v", listenAddr, err)
  137. return
  138. }
  139. c := make(chan error, 1)
  140. go func() {
  141. c <- http.Serve(l, httpLogger(r))
  142. }()
  143. select {
  144. case <-ctx.Done():
  145. l.Close()
  146. <-c
  147. case err := <-c:
  148. log.Errorf("Error serving on %v: %v", listenAddr, err)
  149. }
  150. }