hosts.go 9.5 KB

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