hosts.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. package logic
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "github.com/google/uuid"
  8. "github.com/gravitl/netmaker/database"
  9. "github.com/gravitl/netmaker/logger"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/servercfg"
  12. "golang.org/x/crypto/bcrypt"
  13. )
  14. var (
  15. // ErrHostExists error indicating that host exists when trying to create new host
  16. ErrHostExists error = errors.New("host already exists")
  17. // ErrInvalidHostID
  18. ErrInvalidHostID error = errors.New("invalid host id")
  19. )
  20. // GetAllHosts - returns all hosts in flat list or error
  21. func GetAllHosts() ([]models.Host, error) {
  22. currHostMap, err := GetHostsMap()
  23. if err != nil {
  24. return nil, err
  25. }
  26. var currentHosts = []models.Host{}
  27. for k := range currHostMap {
  28. var h = *currHostMap[k]
  29. currentHosts = append(currentHosts, h)
  30. }
  31. return currentHosts, nil
  32. }
  33. // GetAllHostsAPI - get's all the hosts in an API usable format
  34. func GetAllHostsAPI(hosts []models.Host) []models.ApiHost {
  35. apiHosts := []models.ApiHost{}
  36. for i := range hosts {
  37. newApiHost := hosts[i].ConvertNMHostToAPI()
  38. apiHosts = append(apiHosts, *newApiHost)
  39. }
  40. return apiHosts[:]
  41. }
  42. // GetHostsMap - gets all the current hosts on machine in a map
  43. func GetHostsMap() (map[string]*models.Host, error) {
  44. records, err := database.FetchRecords(database.HOSTS_TABLE_NAME)
  45. if err != nil && !database.IsEmptyRecord(err) {
  46. return nil, err
  47. }
  48. currHostMap := make(map[string]*models.Host)
  49. for k := range records {
  50. var h models.Host
  51. err = json.Unmarshal([]byte(records[k]), &h)
  52. if err != nil {
  53. return nil, err
  54. }
  55. currHostMap[h.ID.String()] = &h
  56. }
  57. return currHostMap, nil
  58. }
  59. // GetHost - gets a host from db given id
  60. func GetHost(hostid string) (*models.Host, error) {
  61. record, err := database.FetchRecord(database.HOSTS_TABLE_NAME, hostid)
  62. if err != nil {
  63. return nil, err
  64. }
  65. var h models.Host
  66. if err = json.Unmarshal([]byte(record), &h); err != nil {
  67. return nil, err
  68. }
  69. return &h, nil
  70. }
  71. // CreateHost - creates a host if not exist
  72. func CreateHost(h *models.Host) error {
  73. _, err := GetHost(h.ID.String())
  74. if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) {
  75. return ErrHostExists
  76. }
  77. //encrypt that password so we never see it
  78. hash, err := bcrypt.GenerateFromPassword([]byte(h.HostPass), 5)
  79. if err != nil {
  80. return err
  81. }
  82. h.HostPass = string(hash)
  83. return UpsertHost(h)
  84. }
  85. // UpdateHost - updates host data by field
  86. func UpdateHost(newHost, currentHost *models.Host) {
  87. // unchangeable fields via API here
  88. newHost.DaemonInstalled = currentHost.DaemonInstalled
  89. newHost.OS = currentHost.OS
  90. newHost.IPForwarding = currentHost.IPForwarding
  91. newHost.HostPass = currentHost.HostPass
  92. newHost.MacAddress = currentHost.MacAddress
  93. newHost.Debug = currentHost.Debug
  94. newHost.Nodes = currentHost.Nodes
  95. newHost.PublicKey = currentHost.PublicKey
  96. newHost.InternetGateway = currentHost.InternetGateway
  97. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  98. // changeable fields
  99. if len(newHost.Version) == 0 {
  100. newHost.Version = currentHost.Version
  101. }
  102. if len(newHost.Name) == 0 {
  103. newHost.Name = currentHost.Name
  104. }
  105. if newHost.MTU == 0 {
  106. newHost.MTU = currentHost.MTU
  107. }
  108. if newHost.ListenPort == 0 {
  109. newHost.ListenPort = currentHost.ListenPort
  110. }
  111. if newHost.ProxyListenPort == 0 {
  112. newHost.ProxyListenPort = currentHost.ProxyListenPort
  113. }
  114. }
  115. // UpsertHost - upserts into DB a given host model, does not check for existence*
  116. func UpsertHost(h *models.Host) error {
  117. data, err := json.Marshal(h)
  118. if err != nil {
  119. return err
  120. }
  121. return database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  122. }
  123. // RemoveHost - removes a given host from server
  124. func RemoveHost(h *models.Host) error {
  125. if len(h.Nodes) > 0 {
  126. return fmt.Errorf("host still has associated nodes")
  127. }
  128. return database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  129. }
  130. // RemoveHostByID - removes a given host by id from server
  131. func RemoveHostByID(hostID string) error {
  132. return database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  133. }
  134. // UpdateHostNetwork - adds/deletes host from a network
  135. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  136. if add {
  137. newNode := models.Node{}
  138. newNode.Server = servercfg.GetServer()
  139. newNode.Network = network
  140. if err := AssociateNodeToHost(&newNode, h); err != nil {
  141. return nil, err
  142. }
  143. return &newNode, nil
  144. }
  145. return nil, errors.New("failed to update host networks")
  146. }
  147. // AssociateNodeToHost - associates and creates a node with a given host
  148. // should be the only way nodes get created as of 0.18
  149. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  150. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  151. return ErrInvalidHostID
  152. }
  153. n.HostID = h.ID
  154. err := createNode(n)
  155. if err != nil {
  156. return err
  157. }
  158. h.Nodes = append(h.Nodes, n.ID.String())
  159. return UpsertHost(h)
  160. }
  161. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  162. // should be the only way nodes are deleted as of 0.18
  163. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  164. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  165. return ErrInvalidHostID
  166. }
  167. if n.HostID != h.ID { // check if node actually belongs to host
  168. return fmt.Errorf("node is not associated with host")
  169. }
  170. if len(h.Nodes) == 0 {
  171. return fmt.Errorf("no nodes present in given host")
  172. }
  173. index := -1
  174. for i := range h.Nodes {
  175. if h.Nodes[i] == n.ID.String() {
  176. index = i
  177. break
  178. }
  179. }
  180. if index < 0 {
  181. if len(h.Nodes) == 0 {
  182. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  183. }
  184. } else {
  185. h.Nodes = RemoveStringSlice(h.Nodes, index)
  186. }
  187. if err := deleteNodeByID(n); err != nil {
  188. return err
  189. }
  190. return UpsertHost(h)
  191. }
  192. // DisassociateAllNodesFromHost - deletes all nodes of the host
  193. func DisassociateAllNodesFromHost(hostID string) error {
  194. host, err := GetHost(hostID)
  195. if err != nil {
  196. return err
  197. }
  198. for _, nodeID := range host.Nodes {
  199. node, err := GetNodeByID(nodeID)
  200. if err != nil {
  201. logger.Log(0, "failed to get host node", err.Error())
  202. continue
  203. }
  204. if err := DeleteNode(&node, true); err != nil {
  205. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  206. continue
  207. }
  208. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  209. }
  210. host.Nodes = []string{}
  211. return UpsertHost(host)
  212. }
  213. // GetDefaultHosts - retrieve all hosts marked as default from DB
  214. func GetDefaultHosts() []models.Host {
  215. defaultHostList := []models.Host{}
  216. hosts, err := GetAllHosts()
  217. if err != nil {
  218. return defaultHostList
  219. }
  220. for i := range hosts {
  221. if hosts[i].IsDefault {
  222. defaultHostList = append(defaultHostList, hosts[i])
  223. }
  224. }
  225. return defaultHostList[:]
  226. }
  227. // AddDefaultHostsToNetwork - adds a node to network for every default host on Netmaker server
  228. func AddDefaultHostsToNetwork(network, server string) error {
  229. // add default hosts to network
  230. defaultHosts := GetDefaultHosts()
  231. for i := range defaultHosts {
  232. newNode := models.Node{}
  233. newNode.Network = network
  234. newNode.Server = server
  235. if err := AssociateNodeToHost(&newNode, &defaultHosts[i]); err != nil {
  236. return err
  237. }
  238. }
  239. return nil
  240. }
  241. // GetHostNetworks - fetches all the networks
  242. func GetHostNetworks(hostID string) []string {
  243. currHost, err := GetHost(hostID)
  244. if err != nil {
  245. return nil
  246. }
  247. nets := []string{}
  248. for i := range currHost.Nodes {
  249. n, err := GetNodeByID(currHost.Nodes[i])
  250. if err != nil {
  251. return nil
  252. }
  253. nets = append(nets, n.Network)
  254. }
  255. return nets
  256. }
  257. // GetRelatedHosts - fetches related hosts of a given host
  258. func GetRelatedHosts(hostID string) []models.Host {
  259. relatedHosts := []models.Host{}
  260. networks := GetHostNetworks(hostID)
  261. networkMap := make(map[string]struct{})
  262. for _, network := range networks {
  263. networkMap[network] = struct{}{}
  264. }
  265. hosts, err := GetAllHosts()
  266. if err == nil {
  267. for _, host := range hosts {
  268. if host.ID.String() == hostID {
  269. continue
  270. }
  271. networks := GetHostNetworks(host.ID.String())
  272. for _, network := range networks {
  273. if _, ok := networkMap[network]; ok {
  274. relatedHosts = append(relatedHosts, host)
  275. break
  276. }
  277. }
  278. }
  279. }
  280. return relatedHosts
  281. }
  282. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  283. // with the same endpoint have different listen ports
  284. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  285. func CheckHostPorts(h *models.Host) {
  286. listenPort := h.ListenPort
  287. proxyPort := h.ProxyListenPort
  288. count := 0
  289. reset := false
  290. hosts, err := GetAllHosts()
  291. if err != nil {
  292. return
  293. }
  294. for _, host := range hosts {
  295. if host.EndpointIP.Equal(h.EndpointIP) {
  296. if host.ListenPort == h.ListenPort || host.ProxyListenPort == h.ProxyListenPort ||
  297. host.ListenPort == h.ProxyListenPort || host.ProxyListenPort == h.ListenPort {
  298. updateListenPorts(h)
  299. count++
  300. //protect against endless recursion
  301. if count > (math.MaxInt16 - 1000) {
  302. reset = true
  303. break
  304. }
  305. CheckHostPorts(h)
  306. }
  307. }
  308. }
  309. if reset {
  310. h.ListenPort = listenPort
  311. h.ProxyListenPort = proxyPort
  312. }
  313. }
  314. // HostExists - checks if given host already exists
  315. func HostExists(h *models.Host) bool {
  316. _, err := GetHost(h.ID.String())
  317. if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) {
  318. return true
  319. }
  320. return false
  321. }
  322. func updateListenPorts(h *models.Host) {
  323. h.ListenPort++
  324. h.ProxyListenPort++
  325. if h.ListenPort > math.MaxInt16 || h.ProxyListenPort > math.MaxInt16 {
  326. h.ListenPort = 1000
  327. h.ProxyListenPort = 1001
  328. }
  329. }