hosts.go 15 KB

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