hosts.go 15 KB

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