renew_handler.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package v2
  2. import (
  3. "path"
  4. "net/http"
  5. "strconv"
  6. "github.com/gorilla/mux"
  7. )
  8. // renewLockHandler attempts to update the TTL on an existing lock.
  9. // Returns a 200 OK if successful. Returns non-200 on error.
  10. func (h *handler) renewLockHandler(w http.ResponseWriter, req *http.Request) {
  11. h.client.SyncCluster()
  12. // Read the lock path.
  13. vars := mux.Vars(req)
  14. keypath := path.Join(prefix, vars["key"])
  15. // Parse new TTL parameter.
  16. ttl, err := strconv.Atoi(req.FormValue("ttl"))
  17. if err != nil {
  18. http.Error(w, "invalid ttl: " + err.Error(), http.StatusInternalServerError)
  19. return
  20. }
  21. // Read and set defaults for index and value.
  22. index := req.FormValue("index")
  23. value := req.FormValue("value")
  24. if len(index) == 0 && len(value) == 0 {
  25. // The index or value is required.
  26. http.Error(w, "renew lock error: index or value required", http.StatusInternalServerError)
  27. return
  28. }
  29. if len(index) == 0 {
  30. // If index is not specified then look it up by value.
  31. resp, err := h.client.Get(keypath, true, true)
  32. if err != nil {
  33. http.Error(w, "renew lock index error: " + err.Error(), http.StatusInternalServerError)
  34. return
  35. }
  36. nodes := lockNodes{resp.Node.Nodes}
  37. node, _ := nodes.FindByValue(value)
  38. if node == nil {
  39. http.Error(w, "renew lock error: cannot find: " + value, http.StatusInternalServerError)
  40. return
  41. }
  42. index = path.Base(node.Key)
  43. } else if len(value) == 0 {
  44. // If value is not specified then default it to the previous value.
  45. resp, err := h.client.Get(path.Join(keypath, index), true, false)
  46. if err != nil {
  47. http.Error(w, "renew lock value error: " + err.Error(), http.StatusInternalServerError)
  48. return
  49. }
  50. value = resp.Node.Value
  51. }
  52. // Renew the lock, if it exists.
  53. _, err = h.client.Update(path.Join(keypath, index), value, uint64(ttl))
  54. if err != nil {
  55. http.Error(w, "renew lock error: " + err.Error(), http.StatusInternalServerError)
  56. return
  57. }
  58. }