network.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. package controller
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "github.com/gorilla/mux"
  9. "github.com/gravitl/netmaker/database"
  10. "github.com/gravitl/netmaker/logger"
  11. "github.com/gravitl/netmaker/logic"
  12. "github.com/gravitl/netmaker/logic/acls"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/mq"
  15. "github.com/gravitl/netmaker/servercfg"
  16. )
  17. func networkHandlers(r *mux.Router) {
  18. r.HandleFunc("/api/networks", logic.SecurityCheck(false, http.HandlerFunc(getNetworks))).Methods(http.MethodGet)
  19. r.HandleFunc("/api/networks", logic.SecurityCheck(true, checkFreeTierLimits(networks_l, http.HandlerFunc(createNetwork)))).Methods(http.MethodPost)
  20. r.HandleFunc("/api/networks/{networkname}", logic.SecurityCheck(false, http.HandlerFunc(getNetwork))).Methods(http.MethodGet)
  21. r.HandleFunc("/api/networks/{networkname}", logic.SecurityCheck(true, http.HandlerFunc(deleteNetwork))).Methods(http.MethodDelete)
  22. r.HandleFunc("/api/networks/{networkname}/keyupdate", logic.SecurityCheck(true, http.HandlerFunc(keyUpdate))).Methods(http.MethodPost)
  23. // ACLs
  24. r.HandleFunc("/api/networks/{networkname}/acls", logic.SecurityCheck(true, http.HandlerFunc(updateNetworkACL))).Methods(http.MethodPut)
  25. r.HandleFunc("/api/networks/{networkname}/acls", logic.SecurityCheck(true, http.HandlerFunc(getNetworkACL))).Methods(http.MethodGet)
  26. }
  27. // swagger:route GET /api/networks networks getNetworks
  28. //
  29. // Lists all networks.
  30. //
  31. // Schemes: https
  32. //
  33. // Security:
  34. // oauth
  35. //
  36. // Responses:
  37. // 200: getNetworksSliceResponse
  38. func getNetworks(w http.ResponseWriter, r *http.Request) {
  39. headerNetworks := r.Header.Get("networks")
  40. networksSlice := []string{}
  41. marshalErr := json.Unmarshal([]byte(headerNetworks), &networksSlice)
  42. if marshalErr != nil {
  43. logger.Log(0, r.Header.Get("user"), "error unmarshalling networks: ",
  44. marshalErr.Error())
  45. logic.ReturnErrorResponse(w, r, logic.FormatError(marshalErr, "badrequest"))
  46. return
  47. }
  48. allnetworks := []models.Network{}
  49. var err error
  50. if len(networksSlice) > 0 && networksSlice[0] == logic.ALL_NETWORK_ACCESS {
  51. allnetworks, err = logic.GetNetworks()
  52. if err != nil && !database.IsEmptyRecord(err) {
  53. logger.Log(0, r.Header.Get("user"), "failed to fetch networks: ", err.Error())
  54. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
  55. return
  56. }
  57. } else {
  58. for _, network := range networksSlice {
  59. netObject, parentErr := logic.GetParentNetwork(network)
  60. if parentErr == nil {
  61. allnetworks = append(allnetworks, netObject)
  62. }
  63. }
  64. }
  65. logger.Log(2, r.Header.Get("user"), "fetched networks.")
  66. w.WriteHeader(http.StatusOK)
  67. json.NewEncoder(w).Encode(allnetworks)
  68. }
  69. // swagger:route GET /api/networks/{networkname} networks getNetwork
  70. //
  71. // Get a network.
  72. //
  73. // Schemes: https
  74. //
  75. // Security:
  76. // oauth
  77. //
  78. // Responses:
  79. // 200: networkBodyResponse
  80. func getNetwork(w http.ResponseWriter, r *http.Request) {
  81. // set header.
  82. w.Header().Set("Content-Type", "application/json")
  83. var params = mux.Vars(r)
  84. netname := params["networkname"]
  85. network, err := logic.GetNetwork(netname)
  86. if err != nil {
  87. logger.Log(0, r.Header.Get("user"), fmt.Sprintf("failed to fetch network [%s] info: %v",
  88. netname, err))
  89. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
  90. return
  91. }
  92. logger.Log(2, r.Header.Get("user"), "fetched network", netname)
  93. w.WriteHeader(http.StatusOK)
  94. json.NewEncoder(w).Encode(network)
  95. }
  96. // swagger:route POST /api/networks/{networkname}/keyupdate networks keyUpdate
  97. //
  98. // Update keys for a network.
  99. //
  100. // Schemes: https
  101. //
  102. // Security:
  103. // oauth
  104. //
  105. // Responses:
  106. // 200: networkBodyResponse
  107. func keyUpdate(w http.ResponseWriter, r *http.Request) {
  108. w.Header().Set("Content-Type", "application/json")
  109. var params = mux.Vars(r)
  110. netname := params["networkname"]
  111. network, err := logic.KeyUpdate(netname)
  112. if err != nil {
  113. logger.Log(0, r.Header.Get("user"), fmt.Sprintf("failed to update keys for network [%s]: %v",
  114. netname, err))
  115. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
  116. return
  117. }
  118. logger.Log(2, r.Header.Get("user"), "updated key on network", netname)
  119. w.WriteHeader(http.StatusOK)
  120. json.NewEncoder(w).Encode(network)
  121. nodes, err := logic.GetNetworkNodes(netname)
  122. if err != nil {
  123. logger.Log(0, "failed to retrieve network nodes for network", netname, err.Error())
  124. return
  125. }
  126. for _, node := range nodes {
  127. logger.Log(2, "updating node ", node.ID.String(), " for a key update")
  128. if err = mq.NodeUpdate(&node); err != nil {
  129. logger.Log(1, "failed to send update to node during a network wide key update", node.ID.String(), err.Error())
  130. }
  131. }
  132. }
  133. // swagger:route PUT /api/networks/{networkname}/acls networks updateNetworkACL
  134. //
  135. // Update a network ACL (Access Control List).
  136. //
  137. // Schemes: https
  138. //
  139. // Security:
  140. // oauth
  141. //
  142. // Responses:
  143. // 200: aclContainerResponse
  144. func updateNetworkACL(w http.ResponseWriter, r *http.Request) {
  145. w.Header().Set("Content-Type", "application/json")
  146. var params = mux.Vars(r)
  147. netname := params["networkname"]
  148. var networkACLChange acls.ACLContainer
  149. networkACLChange, err := networkACLChange.Get(acls.ContainerID(netname))
  150. if err != nil {
  151. logger.Log(0, r.Header.Get("user"),
  152. fmt.Sprintf("failed to fetch ACLs for network [%s]: %v", netname, err))
  153. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
  154. return
  155. }
  156. err = json.NewDecoder(r.Body).Decode(&networkACLChange)
  157. if err != nil {
  158. logger.Log(0, r.Header.Get("user"), "error decoding request body: ",
  159. err.Error())
  160. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
  161. return
  162. }
  163. newNetACL, err := networkACLChange.Save(acls.ContainerID(netname))
  164. if err != nil {
  165. logger.Log(0, r.Header.Get("user"),
  166. fmt.Sprintf("failed to update ACLs for network [%s]: %v", netname, err))
  167. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
  168. return
  169. }
  170. logger.Log(1, r.Header.Get("user"), "updated ACLs for network", netname)
  171. // send peer updates
  172. if servercfg.IsMessageQueueBackend() {
  173. if err = mq.PublishPeerUpdate(); err != nil {
  174. logger.Log(0, "failed to publish peer update after ACL update on", netname)
  175. }
  176. }
  177. w.WriteHeader(http.StatusOK)
  178. json.NewEncoder(w).Encode(newNetACL)
  179. }
  180. // swagger:route GET /api/networks/{networkname}/acls networks getNetworkACL
  181. //
  182. // Get a network ACL (Access Control List).
  183. //
  184. // Schemes: https
  185. //
  186. // Security:
  187. // oauth
  188. //
  189. // Responses:
  190. // 200: aclContainerResponse
  191. func getNetworkACL(w http.ResponseWriter, r *http.Request) {
  192. w.Header().Set("Content-Type", "application/json")
  193. var params = mux.Vars(r)
  194. netname := params["networkname"]
  195. var networkACL acls.ACLContainer
  196. networkACL, err := networkACL.Get(acls.ContainerID(netname))
  197. if err != nil {
  198. logger.Log(0, r.Header.Get("user"),
  199. fmt.Sprintf("failed to fetch ACLs for network [%s]: %v", netname, err))
  200. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
  201. return
  202. }
  203. logger.Log(2, r.Header.Get("user"), "fetched acl for network", netname)
  204. w.WriteHeader(http.StatusOK)
  205. json.NewEncoder(w).Encode(networkACL)
  206. }
  207. // swagger:route DELETE /api/networks/{networkname} networks deleteNetwork
  208. //
  209. // Delete a network. Will not delete if there are any nodes that belong to the network.
  210. //
  211. // Schemes: https
  212. //
  213. // Security:
  214. // oauth
  215. //
  216. // Responses:
  217. // 200: stringJSONResponse
  218. func deleteNetwork(w http.ResponseWriter, r *http.Request) {
  219. // Set header
  220. w.Header().Set("Content-Type", "application/json")
  221. var params = mux.Vars(r)
  222. network := params["networkname"]
  223. err := logic.DeleteNetwork(network)
  224. if err != nil {
  225. errtype := "badrequest"
  226. if strings.Contains(err.Error(), "Node check failed") {
  227. errtype = "forbidden"
  228. }
  229. logger.Log(0, r.Header.Get("user"),
  230. fmt.Sprintf("failed to delete network [%s]: %v", network, err))
  231. logic.ReturnErrorResponse(w, r, logic.FormatError(err, errtype))
  232. return
  233. }
  234. logger.Log(1, r.Header.Get("user"), "deleted network", network)
  235. w.WriteHeader(http.StatusOK)
  236. json.NewEncoder(w).Encode("success")
  237. }
  238. // swagger:route POST /api/networks networks createNetwork
  239. //
  240. // Create a network.
  241. //
  242. // Schemes: https
  243. //
  244. // Security:
  245. // oauth
  246. //
  247. // Responses:
  248. // 200: networkBodyResponse
  249. func createNetwork(w http.ResponseWriter, r *http.Request) {
  250. w.Header().Set("Content-Type", "application/json")
  251. var network models.Network
  252. // we decode our body request params
  253. err := json.NewDecoder(r.Body).Decode(&network)
  254. if err != nil {
  255. logger.Log(0, r.Header.Get("user"), "error decoding request body: ",
  256. err.Error())
  257. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
  258. return
  259. }
  260. if network.AddressRange == "" && network.AddressRange6 == "" {
  261. err := errors.New("IPv4 or IPv6 CIDR required")
  262. logger.Log(0, r.Header.Get("user"), "failed to create network: ",
  263. err.Error())
  264. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
  265. return
  266. }
  267. network, err = logic.CreateNetwork(network)
  268. if err != nil {
  269. logger.Log(0, r.Header.Get("user"), "failed to create network: ",
  270. err.Error())
  271. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
  272. return
  273. }
  274. defaultHosts := logic.GetDefaultHosts()
  275. for i := range defaultHosts {
  276. currHost := &defaultHosts[i]
  277. newNode, err := logic.UpdateHostNetwork(currHost, network.NetID, true)
  278. if err != nil {
  279. logger.Log(0, r.Header.Get("user"), "failed to add host to network:", currHost.ID.String(), network.NetID, err.Error())
  280. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
  281. return
  282. }
  283. logger.Log(1, "added new node", newNode.ID.String(), "to host", currHost.Name)
  284. if err = mq.HostUpdate(&models.HostUpdate{
  285. Action: models.JoinHostToNetwork,
  286. Host: *currHost,
  287. Node: *newNode,
  288. }); err != nil {
  289. logger.Log(0, r.Header.Get("user"), "failed to add host to network:", currHost.ID.String(), network.NetID, err.Error())
  290. }
  291. }
  292. logger.Log(1, r.Header.Get("user"), "created network", network.NetID)
  293. w.WriteHeader(http.StatusOK)
  294. json.NewEncoder(w).Encode(network)
  295. }