relay.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package controller
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/gorilla/mux"
  6. "github.com/gravitl/netmaker/logger"
  7. "github.com/gravitl/netmaker/logic"
  8. "github.com/gravitl/netmaker/models"
  9. "github.com/gravitl/netmaker/mq"
  10. )
  11. func createRelay(w http.ResponseWriter, r *http.Request) {
  12. var relay models.RelayRequest
  13. var params = mux.Vars(r)
  14. w.Header().Set("Content-Type", "application/json")
  15. err := json.NewDecoder(r.Body).Decode(&relay)
  16. if err != nil {
  17. returnErrorResponse(w, r, formatError(err, "internal"))
  18. return
  19. }
  20. relay.NetID = params["network"]
  21. relay.NodeID = params["nodeid"]
  22. node, err := logic.CreateRelay(relay)
  23. if err != nil {
  24. returnErrorResponse(w, r, formatError(err, "internal"))
  25. return
  26. }
  27. if err = runServerPeerUpdate(relay.NetID, true); err != nil {
  28. logger.Log(1, "internal error when creating relay on node:", relay.NodeID)
  29. }
  30. go func() {
  31. if err := mq.NodeUpdate(&node); err != nil {
  32. logger.Log(1, "error publishing node update"+err.Error())
  33. }
  34. if err := mq.UpdatePeers(&node); err != nil {
  35. logger.Log(1, "error publishing peer update "+err.Error())
  36. return
  37. }
  38. }()
  39. logger.Log(1, r.Header.Get("user"), "created relay on node", relay.NodeID, "on network", relay.NetID)
  40. w.WriteHeader(http.StatusOK)
  41. json.NewEncoder(w).Encode(node)
  42. }
  43. func deleteRelay(w http.ResponseWriter, r *http.Request) {
  44. w.Header().Set("Content-Type", "application/json")
  45. var params = mux.Vars(r)
  46. nodeid := params["nodeid"]
  47. netid := params["network"]
  48. node, err := logic.DeleteRelay(netid, nodeid)
  49. if err != nil {
  50. returnErrorResponse(w, r, formatError(err, "internal"))
  51. return
  52. }
  53. if err = runServerPeerUpdate(netid, true); err != nil {
  54. logger.Log(1, "internal error when deleting relay on node:", nodeid)
  55. }
  56. go func() {
  57. if err := mq.NodeUpdate(&node); err != nil {
  58. logger.Log(1, "error publishing node update"+err.Error())
  59. }
  60. if err := mq.UpdatePeers(&node); err != nil {
  61. logger.Log(1, "error publishing peer update "+err.Error())
  62. return
  63. }
  64. }()
  65. logger.Log(1, r.Header.Get("user"), "deleted relay server", nodeid, "on network", netid)
  66. w.WriteHeader(http.StatusOK)
  67. json.NewEncoder(w).Encode(node)
  68. }