hosts.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. package logic
  2. import (
  3. "crypto/md5"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "sort"
  8. "sync"
  9. "github.com/google/uuid"
  10. "golang.org/x/crypto/bcrypt"
  11. "golang.org/x/exp/slog"
  12. "github.com/gravitl/netmaker/database"
  13. "github.com/gravitl/netmaker/logger"
  14. "github.com/gravitl/netmaker/models"
  15. "github.com/gravitl/netmaker/servercfg"
  16. )
  17. var (
  18. hostCacheMutex = &sync.RWMutex{}
  19. hostsCacheMap = make(map[string]models.Host)
  20. )
  21. var (
  22. // ErrHostExists error indicating that host exists when trying to create new host
  23. ErrHostExists error = errors.New("host already exists")
  24. // ErrInvalidHostID
  25. ErrInvalidHostID error = errors.New("invalid host id")
  26. )
  27. func getHostsFromCache() (hosts []models.Host) {
  28. hostCacheMutex.RLock()
  29. for _, host := range hostsCacheMap {
  30. hosts = append(hosts, host)
  31. }
  32. hostCacheMutex.RUnlock()
  33. return
  34. }
  35. func getHostsMapFromCache() (hostsMap map[string]models.Host) {
  36. hostCacheMutex.RLock()
  37. hostsMap = hostsCacheMap
  38. hostCacheMutex.RUnlock()
  39. return
  40. }
  41. func getHostFromCache(hostID string) (host models.Host, ok bool) {
  42. hostCacheMutex.RLock()
  43. host, ok = hostsCacheMap[hostID]
  44. hostCacheMutex.RUnlock()
  45. return
  46. }
  47. func storeHostInCache(h models.Host) {
  48. hostCacheMutex.Lock()
  49. hostsCacheMap[h.ID.String()] = h
  50. hostCacheMutex.Unlock()
  51. }
  52. func deleteHostFromCache(hostID string) {
  53. hostCacheMutex.Lock()
  54. delete(hostsCacheMap, hostID)
  55. hostCacheMutex.Unlock()
  56. }
  57. func loadHostsIntoCache(hMap map[string]models.Host) {
  58. hostCacheMutex.Lock()
  59. hostsCacheMap = hMap
  60. hostCacheMutex.Unlock()
  61. }
  62. const (
  63. maxPort = 1<<16 - 1
  64. minPort = 1025
  65. )
  66. // GetAllHosts - returns all hosts in flat list or error
  67. func GetAllHosts() ([]models.Host, error) {
  68. var currHosts []models.Host
  69. if servercfg.CacheEnabled() {
  70. currHosts := getHostsFromCache()
  71. if len(currHosts) != 0 {
  72. return currHosts, nil
  73. }
  74. }
  75. records, err := database.FetchRecords(database.HOSTS_TABLE_NAME)
  76. if err != nil && !database.IsEmptyRecord(err) {
  77. return nil, err
  78. }
  79. currHostsMap := make(map[string]models.Host)
  80. if servercfg.CacheEnabled() {
  81. defer loadHostsIntoCache(currHostsMap)
  82. }
  83. for k := range records {
  84. var h models.Host
  85. err = json.Unmarshal([]byte(records[k]), &h)
  86. if err != nil {
  87. return nil, err
  88. }
  89. currHosts = append(currHosts, h)
  90. currHostsMap[h.ID.String()] = h
  91. }
  92. return currHosts, nil
  93. }
  94. // GetAllHostsAPI - get's all the hosts in an API usable format
  95. func GetAllHostsAPI(hosts []models.Host) []models.ApiHost {
  96. apiHosts := []models.ApiHost{}
  97. for i := range hosts {
  98. newApiHost := hosts[i].ConvertNMHostToAPI()
  99. apiHosts = append(apiHosts, *newApiHost)
  100. }
  101. return apiHosts[:]
  102. }
  103. // GetHostsMap - gets all the current hosts on machine in a map
  104. func GetHostsMap() (map[string]models.Host, error) {
  105. if servercfg.CacheEnabled() {
  106. hostsMap := getHostsMapFromCache()
  107. if len(hostsMap) != 0 {
  108. return hostsMap, nil
  109. }
  110. }
  111. records, err := database.FetchRecords(database.HOSTS_TABLE_NAME)
  112. if err != nil && !database.IsEmptyRecord(err) {
  113. return nil, err
  114. }
  115. currHostMap := make(map[string]models.Host)
  116. if servercfg.CacheEnabled() {
  117. defer loadHostsIntoCache(currHostMap)
  118. }
  119. for k := range records {
  120. var h models.Host
  121. err = json.Unmarshal([]byte(records[k]), &h)
  122. if err != nil {
  123. return nil, err
  124. }
  125. currHostMap[h.ID.String()] = h
  126. }
  127. return currHostMap, nil
  128. }
  129. // GetHost - gets a host from db given id
  130. func GetHost(hostid string) (*models.Host, error) {
  131. if servercfg.CacheEnabled() {
  132. if host, ok := getHostFromCache(hostid); ok {
  133. return &host, nil
  134. }
  135. }
  136. record, err := database.FetchRecord(database.HOSTS_TABLE_NAME, hostid)
  137. if err != nil {
  138. return nil, err
  139. }
  140. var h models.Host
  141. if err = json.Unmarshal([]byte(record), &h); err != nil {
  142. return nil, err
  143. }
  144. if servercfg.CacheEnabled() {
  145. storeHostInCache(h)
  146. }
  147. return &h, nil
  148. }
  149. // GetHostByPubKey - gets a host from db given pubkey
  150. func GetHostByPubKey(hostPubKey string) (*models.Host, error) {
  151. hosts, err := GetAllHosts()
  152. if err != nil {
  153. return nil, err
  154. }
  155. for _, host := range hosts {
  156. if host.PublicKey.String() == hostPubKey {
  157. return &host, nil
  158. }
  159. }
  160. return nil, errors.New("host not found")
  161. }
  162. // CreateHost - creates a host if not exist
  163. func CreateHost(h *models.Host) error {
  164. hosts, hErr := GetAllHosts()
  165. clients, cErr := GetAllExtClients()
  166. if (hErr != nil && !database.IsEmptyRecord(hErr)) ||
  167. (cErr != nil && !database.IsEmptyRecord(cErr)) ||
  168. len(hosts)+len(clients) >= MachinesLimit {
  169. return errors.New("free tier limits exceeded on machines")
  170. }
  171. _, err := GetHost(h.ID.String())
  172. if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) {
  173. return ErrHostExists
  174. }
  175. // encrypt that password so we never see it
  176. hash, err := bcrypt.GenerateFromPassword([]byte(h.HostPass), 5)
  177. if err != nil {
  178. return err
  179. }
  180. h.HostPass = string(hash)
  181. h.AutoUpdate = servercfg.AutoUpdateEnabled()
  182. checkForZombieHosts(h)
  183. return UpsertHost(h)
  184. }
  185. // UpdateHost - updates host data by field
  186. func UpdateHost(newHost, currentHost *models.Host) {
  187. // unchangeable fields via API here
  188. newHost.DaemonInstalled = currentHost.DaemonInstalled
  189. newHost.OS = currentHost.OS
  190. newHost.IPForwarding = currentHost.IPForwarding
  191. newHost.HostPass = currentHost.HostPass
  192. newHost.MacAddress = currentHost.MacAddress
  193. newHost.Debug = currentHost.Debug
  194. newHost.Nodes = currentHost.Nodes
  195. newHost.PublicKey = currentHost.PublicKey
  196. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  197. // changeable fields
  198. if len(newHost.Version) == 0 {
  199. newHost.Version = currentHost.Version
  200. }
  201. if len(newHost.Name) == 0 {
  202. newHost.Name = currentHost.Name
  203. }
  204. if newHost.MTU == 0 {
  205. newHost.MTU = currentHost.MTU
  206. }
  207. if newHost.ListenPort == 0 {
  208. newHost.ListenPort = currentHost.ListenPort
  209. }
  210. if newHost.PersistentKeepalive == 0 {
  211. newHost.PersistentKeepalive = currentHost.PersistentKeepalive
  212. }
  213. }
  214. // UpdateHostFromClient - used for updating host on server with update recieved from client
  215. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  216. if newHost.PublicKey != currHost.PublicKey {
  217. currHost.PublicKey = newHost.PublicKey
  218. sendPeerUpdate = true
  219. }
  220. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  221. currHost.ListenPort = newHost.ListenPort
  222. sendPeerUpdate = true
  223. }
  224. if newHost.WgPublicListenPort != 0 &&
  225. currHost.WgPublicListenPort != newHost.WgPublicListenPort {
  226. currHost.WgPublicListenPort = newHost.WgPublicListenPort
  227. sendPeerUpdate = true
  228. }
  229. isEndpointChanged := false
  230. if currHost.EndpointIP.String() != newHost.EndpointIP.String() {
  231. currHost.EndpointIP = newHost.EndpointIP
  232. sendPeerUpdate = true
  233. isEndpointChanged = true
  234. }
  235. if currHost.EndpointIPv6.String() != newHost.EndpointIPv6.String() {
  236. currHost.EndpointIPv6 = newHost.EndpointIPv6
  237. sendPeerUpdate = true
  238. isEndpointChanged = true
  239. }
  240. if isEndpointChanged {
  241. for _, nodeID := range currHost.Nodes {
  242. node, err := GetNodeByID(nodeID)
  243. if err != nil {
  244. slog.Error("failed to get node:", "id", node.ID, "error", err)
  245. continue
  246. }
  247. if node.FailedOverBy != uuid.Nil {
  248. ResetFailedOverPeer(&node)
  249. }
  250. }
  251. }
  252. currHost.DaemonInstalled = newHost.DaemonInstalled
  253. currHost.Debug = newHost.Debug
  254. currHost.Verbosity = newHost.Verbosity
  255. currHost.Version = newHost.Version
  256. currHost.IsStaticPort = newHost.IsStaticPort
  257. currHost.IsStatic = newHost.IsStatic
  258. currHost.MTU = newHost.MTU
  259. if newHost.Name != currHost.Name {
  260. // update any rag role ids
  261. for _, nodeID := range newHost.Nodes {
  262. node, err := GetNodeByID(nodeID)
  263. if err == nil && node.IsIngressGateway {
  264. role, err := GetRole(models.GetRAGRoleID(node.Network, currHost.ID.String()))
  265. if err == nil {
  266. role.UiName = models.GetRAGRoleName(node.Network, newHost.Name)
  267. UpdateRole(role)
  268. }
  269. }
  270. }
  271. }
  272. currHost.Name = newHost.Name
  273. if len(newHost.NatType) > 0 && newHost.NatType != currHost.NatType {
  274. currHost.NatType = newHost.NatType
  275. sendPeerUpdate = true
  276. }
  277. return
  278. }
  279. // UpsertHost - upserts into DB a given host model, does not check for existence*
  280. func UpsertHost(h *models.Host) error {
  281. data, err := json.Marshal(h)
  282. if err != nil {
  283. return err
  284. }
  285. err = database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  286. if err != nil {
  287. return err
  288. }
  289. if servercfg.CacheEnabled() {
  290. storeHostInCache(*h)
  291. }
  292. return nil
  293. }
  294. // RemoveHost - removes a given host from server
  295. func RemoveHost(h *models.Host, forceDelete bool) error {
  296. if !forceDelete && len(h.Nodes) > 0 {
  297. return fmt.Errorf("host still has associated nodes")
  298. }
  299. if len(h.Nodes) > 0 {
  300. if err := DisassociateAllNodesFromHost(h.ID.String()); err != nil {
  301. return err
  302. }
  303. }
  304. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  305. if err != nil {
  306. return err
  307. }
  308. if servercfg.CacheEnabled() {
  309. deleteHostFromCache(h.ID.String())
  310. }
  311. go func() {
  312. if servercfg.IsDNSMode() {
  313. SetDNS()
  314. }
  315. }()
  316. return nil
  317. }
  318. // RemoveHostByID - removes a given host by id from server
  319. func RemoveHostByID(hostID string) error {
  320. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  321. if err != nil {
  322. return err
  323. }
  324. if servercfg.CacheEnabled() {
  325. deleteHostFromCache(hostID)
  326. }
  327. return nil
  328. }
  329. // UpdateHostNetwork - adds/deletes host from a network
  330. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  331. for _, nodeID := range h.Nodes {
  332. node, err := GetNodeByID(nodeID)
  333. if err != nil || node.PendingDelete {
  334. continue
  335. }
  336. if node.Network == network {
  337. if !add {
  338. return &node, nil
  339. } else {
  340. return nil, errors.New("host already part of network " + network)
  341. }
  342. }
  343. }
  344. if !add {
  345. return nil, errors.New("host not part of the network " + network)
  346. } else {
  347. newNode := models.Node{}
  348. newNode.Server = servercfg.GetServer()
  349. newNode.Network = network
  350. newNode.HostID = h.ID
  351. if err := AssociateNodeToHost(&newNode, h); err != nil {
  352. return nil, err
  353. }
  354. return &newNode, nil
  355. }
  356. }
  357. // AssociateNodeToHost - associates and creates a node with a given host
  358. // should be the only way nodes get created as of 0.18
  359. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  360. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  361. return ErrInvalidHostID
  362. }
  363. n.HostID = h.ID
  364. err := createNode(n)
  365. if err != nil {
  366. return err
  367. }
  368. currentHost, err := GetHost(h.ID.String())
  369. if err != nil {
  370. return err
  371. }
  372. h.HostPass = currentHost.HostPass
  373. h.Nodes = append(currentHost.Nodes, n.ID.String())
  374. return UpsertHost(h)
  375. }
  376. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  377. // should be the only way nodes are deleted as of 0.18
  378. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  379. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  380. return ErrInvalidHostID
  381. }
  382. if n.HostID != h.ID { // check if node actually belongs to host
  383. return fmt.Errorf("node is not associated with host")
  384. }
  385. if len(h.Nodes) == 0 {
  386. return fmt.Errorf("no nodes present in given host")
  387. }
  388. nList := []string{}
  389. for i := range h.Nodes {
  390. if h.Nodes[i] != n.ID.String() {
  391. nList = append(nList, h.Nodes[i])
  392. }
  393. }
  394. h.Nodes = nList
  395. go func() {
  396. if servercfg.IsPro {
  397. if clients, err := GetNetworkExtClients(n.Network); err != nil {
  398. for i := range clients {
  399. AllowClientNodeAccess(&clients[i], n.ID.String())
  400. }
  401. }
  402. }
  403. }()
  404. if err := DeleteNodeByID(n); err != nil {
  405. return err
  406. }
  407. return UpsertHost(h)
  408. }
  409. // DisassociateAllNodesFromHost - deletes all nodes of the host
  410. func DisassociateAllNodesFromHost(hostID string) error {
  411. host, err := GetHost(hostID)
  412. if err != nil {
  413. return err
  414. }
  415. for _, nodeID := range host.Nodes {
  416. node, err := GetNodeByID(nodeID)
  417. if err != nil {
  418. logger.Log(0, "failed to get host node, node id:", nodeID, err.Error())
  419. continue
  420. }
  421. if err := DeleteNode(&node, true); err != nil {
  422. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  423. continue
  424. }
  425. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  426. }
  427. host.Nodes = []string{}
  428. return UpsertHost(host)
  429. }
  430. // GetDefaultHosts - retrieve all hosts marked as default from DB
  431. func GetDefaultHosts() []models.Host {
  432. defaultHostList := []models.Host{}
  433. hosts, err := GetAllHosts()
  434. if err != nil {
  435. return defaultHostList
  436. }
  437. for i := range hosts {
  438. if hosts[i].IsDefault {
  439. defaultHostList = append(defaultHostList, hosts[i])
  440. }
  441. }
  442. return defaultHostList[:]
  443. }
  444. // GetHostNetworks - fetches all the networks
  445. func GetHostNetworks(hostID string) []string {
  446. currHost, err := GetHost(hostID)
  447. if err != nil {
  448. return nil
  449. }
  450. nets := []string{}
  451. for i := range currHost.Nodes {
  452. n, err := GetNodeByID(currHost.Nodes[i])
  453. if err != nil {
  454. return nil
  455. }
  456. nets = append(nets, n.Network)
  457. }
  458. return nets
  459. }
  460. // GetRelatedHosts - fetches related hosts of a given host
  461. func GetRelatedHosts(hostID string) []models.Host {
  462. relatedHosts := []models.Host{}
  463. networks := GetHostNetworks(hostID)
  464. networkMap := make(map[string]struct{})
  465. for _, network := range networks {
  466. networkMap[network] = struct{}{}
  467. }
  468. hosts, err := GetAllHosts()
  469. if err == nil {
  470. for _, host := range hosts {
  471. if host.ID.String() == hostID {
  472. continue
  473. }
  474. networks := GetHostNetworks(host.ID.String())
  475. for _, network := range networks {
  476. if _, ok := networkMap[network]; ok {
  477. relatedHosts = append(relatedHosts, host)
  478. break
  479. }
  480. }
  481. }
  482. }
  483. return relatedHosts
  484. }
  485. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  486. // with the same endpoint have different listen ports
  487. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  488. func CheckHostPorts(h *models.Host) {
  489. portsInUse := make(map[int]bool, 0)
  490. hosts, err := GetAllHosts()
  491. if err != nil {
  492. return
  493. }
  494. for _, host := range hosts {
  495. if host.ID.String() == h.ID.String() {
  496. // skip self
  497. continue
  498. }
  499. if !host.EndpointIP.Equal(h.EndpointIP) {
  500. continue
  501. }
  502. portsInUse[host.ListenPort] = true
  503. }
  504. // iterate until port is not found or max iteration is reached
  505. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  506. h.ListenPort++
  507. if h.ListenPort > maxPort {
  508. h.ListenPort = minPort
  509. }
  510. }
  511. }
  512. // HostExists - checks if given host already exists
  513. func HostExists(h *models.Host) bool {
  514. _, err := GetHost(h.ID.String())
  515. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  516. }
  517. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  518. func GetHostByNodeID(id string) *models.Host {
  519. hosts, err := GetAllHosts()
  520. if err != nil {
  521. return nil
  522. }
  523. for i := range hosts {
  524. h := hosts[i]
  525. if StringSliceContains(h.Nodes, id) {
  526. return &h
  527. }
  528. }
  529. return nil
  530. }
  531. // ConvHostPassToHash - converts password to md5 hash
  532. func ConvHostPassToHash(hostPass string) string {
  533. return fmt.Sprintf("%x", md5.Sum([]byte(hostPass)))
  534. }
  535. // SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first
  536. func SortApiHosts(unsortedHosts []models.ApiHost) {
  537. sort.Slice(unsortedHosts, func(i, j int) bool {
  538. return unsortedHosts[i].ID < unsortedHosts[j].ID
  539. })
  540. }