hosts.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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 = servercfg.AutoUpdateEnabled()
  205. checkForZombieHosts(h)
  206. return UpsertHost(h)
  207. }
  208. // UpdateHost - updates host data by field
  209. func UpdateHost(newHost, currentHost *models.Host) {
  210. // unchangeable fields via API here
  211. newHost.DaemonInstalled = currentHost.DaemonInstalled
  212. newHost.OS = currentHost.OS
  213. newHost.IPForwarding = currentHost.IPForwarding
  214. newHost.HostPass = currentHost.HostPass
  215. newHost.MacAddress = currentHost.MacAddress
  216. newHost.Debug = currentHost.Debug
  217. newHost.Nodes = currentHost.Nodes
  218. newHost.PublicKey = currentHost.PublicKey
  219. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  220. // changeable fields
  221. if len(newHost.Version) == 0 {
  222. newHost.Version = currentHost.Version
  223. }
  224. if len(newHost.Name) == 0 {
  225. newHost.Name = currentHost.Name
  226. }
  227. if newHost.MTU == 0 {
  228. newHost.MTU = currentHost.MTU
  229. }
  230. if newHost.ListenPort == 0 {
  231. newHost.ListenPort = currentHost.ListenPort
  232. }
  233. if newHost.PersistentKeepalive == 0 {
  234. newHost.PersistentKeepalive = currentHost.PersistentKeepalive
  235. }
  236. }
  237. // UpdateHostFromClient - used for updating host on server with update recieved from client
  238. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  239. if newHost.PublicKey != currHost.PublicKey {
  240. currHost.PublicKey = newHost.PublicKey
  241. sendPeerUpdate = true
  242. }
  243. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  244. currHost.ListenPort = newHost.ListenPort
  245. sendPeerUpdate = true
  246. }
  247. if newHost.WgPublicListenPort != 0 &&
  248. currHost.WgPublicListenPort != newHost.WgPublicListenPort {
  249. currHost.WgPublicListenPort = newHost.WgPublicListenPort
  250. sendPeerUpdate = true
  251. }
  252. isEndpointChanged := false
  253. if currHost.EndpointIP.String() != newHost.EndpointIP.String() {
  254. currHost.EndpointIP = newHost.EndpointIP
  255. sendPeerUpdate = true
  256. isEndpointChanged = true
  257. }
  258. if currHost.EndpointIPv6.String() != newHost.EndpointIPv6.String() {
  259. currHost.EndpointIPv6 = newHost.EndpointIPv6
  260. sendPeerUpdate = true
  261. isEndpointChanged = true
  262. }
  263. if isEndpointChanged {
  264. for _, nodeID := range currHost.Nodes {
  265. node, err := GetNodeByID(nodeID)
  266. if err != nil {
  267. slog.Error("failed to get node:", "id", node.ID, "error", err)
  268. continue
  269. }
  270. if node.FailedOverBy != uuid.Nil {
  271. ResetFailedOverPeer(&node)
  272. }
  273. }
  274. }
  275. currHost.DaemonInstalled = newHost.DaemonInstalled
  276. currHost.Debug = newHost.Debug
  277. currHost.Verbosity = newHost.Verbosity
  278. currHost.Version = newHost.Version
  279. currHost.IsStaticPort = newHost.IsStaticPort
  280. currHost.IsStatic = newHost.IsStatic
  281. currHost.MTU = newHost.MTU
  282. currHost.Name = newHost.Name
  283. if len(newHost.NatType) > 0 && newHost.NatType != currHost.NatType {
  284. currHost.NatType = newHost.NatType
  285. sendPeerUpdate = true
  286. }
  287. return
  288. }
  289. // UpsertHost - upserts into DB a given host model, does not check for existence*
  290. func UpsertHost(h *models.Host) error {
  291. data, err := json.Marshal(h)
  292. if err != nil {
  293. return err
  294. }
  295. err = database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  296. if err != nil {
  297. return err
  298. }
  299. if servercfg.CacheEnabled() {
  300. storeHostInCache(*h)
  301. }
  302. return nil
  303. }
  304. // RemoveHost - removes a given host from server
  305. func RemoveHost(h *models.Host, forceDelete bool) error {
  306. if !forceDelete && len(h.Nodes) > 0 {
  307. return fmt.Errorf("host still has associated nodes")
  308. }
  309. if len(h.Nodes) > 0 {
  310. if err := DisassociateAllNodesFromHost(h.ID.String()); err != nil {
  311. return err
  312. }
  313. }
  314. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  315. if err != nil {
  316. return err
  317. }
  318. if servercfg.CacheEnabled() {
  319. deleteHostFromCache(h.ID.String())
  320. }
  321. go func() {
  322. if servercfg.IsDNSMode() {
  323. SetDNS()
  324. }
  325. }()
  326. return nil
  327. }
  328. // RemoveHostByID - removes a given host by id from server
  329. func RemoveHostByID(hostID string) error {
  330. err := database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  331. if err != nil {
  332. return err
  333. }
  334. if servercfg.CacheEnabled() {
  335. deleteHostFromCache(hostID)
  336. }
  337. return nil
  338. }
  339. // UpdateHostNetwork - adds/deletes host from a network
  340. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  341. for _, nodeID := range h.Nodes {
  342. node, err := GetNodeByID(nodeID)
  343. if err != nil || node.PendingDelete {
  344. continue
  345. }
  346. if node.Network == network {
  347. if !add {
  348. return &node, nil
  349. } else {
  350. return nil, errors.New("host already part of network " + network)
  351. }
  352. }
  353. }
  354. if !add {
  355. return nil, errors.New("host not part of the network " + network)
  356. } else {
  357. newNode := models.Node{}
  358. newNode.Server = servercfg.GetServer()
  359. newNode.Network = network
  360. newNode.HostID = h.ID
  361. if err := AssociateNodeToHost(&newNode, h); err != nil {
  362. return nil, err
  363. }
  364. return &newNode, nil
  365. }
  366. }
  367. // AssociateNodeToHost - associates and creates a node with a given host
  368. // should be the only way nodes get created as of 0.18
  369. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  370. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  371. return ErrInvalidHostID
  372. }
  373. n.HostID = h.ID
  374. err := createNode(n)
  375. if err != nil {
  376. return err
  377. }
  378. currentHost, err := GetHost(h.ID.String())
  379. if err != nil {
  380. return err
  381. }
  382. h.HostPass = currentHost.HostPass
  383. h.Nodes = append(currentHost.Nodes, n.ID.String())
  384. return UpsertHost(h)
  385. }
  386. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  387. // should be the only way nodes are deleted as of 0.18
  388. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  389. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  390. return ErrInvalidHostID
  391. }
  392. if n.HostID != h.ID { // check if node actually belongs to host
  393. return fmt.Errorf("node is not associated with host")
  394. }
  395. if len(h.Nodes) == 0 {
  396. return fmt.Errorf("no nodes present in given host")
  397. }
  398. nList := []string{}
  399. for i := range h.Nodes {
  400. if h.Nodes[i] != n.ID.String() {
  401. nList = append(nList, h.Nodes[i])
  402. }
  403. }
  404. h.Nodes = nList
  405. go func() {
  406. if servercfg.IsPro {
  407. if clients, err := GetNetworkExtClients(n.Network); err != nil {
  408. for i := range clients {
  409. AllowClientNodeAccess(&clients[i], n.ID.String())
  410. }
  411. }
  412. }
  413. }()
  414. if err := DeleteNodeByID(n); err != nil {
  415. return err
  416. }
  417. return UpsertHost(h)
  418. }
  419. // DisassociateAllNodesFromHost - deletes all nodes of the host
  420. func DisassociateAllNodesFromHost(hostID string) error {
  421. host, err := GetHost(hostID)
  422. if err != nil {
  423. return err
  424. }
  425. for _, nodeID := range host.Nodes {
  426. node, err := GetNodeByID(nodeID)
  427. if err != nil {
  428. logger.Log(0, "failed to get host node, node id:", nodeID, err.Error())
  429. continue
  430. }
  431. if err := DeleteNode(&node, true); err != nil {
  432. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  433. continue
  434. }
  435. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  436. }
  437. host.Nodes = []string{}
  438. return UpsertHost(host)
  439. }
  440. // GetDefaultHosts - retrieve all hosts marked as default from DB
  441. func GetDefaultHosts() []models.Host {
  442. defaultHostList := []models.Host{}
  443. hosts, err := GetAllHosts()
  444. if err != nil {
  445. return defaultHostList
  446. }
  447. for i := range hosts {
  448. if hosts[i].IsDefault {
  449. defaultHostList = append(defaultHostList, hosts[i])
  450. }
  451. }
  452. return defaultHostList[:]
  453. }
  454. // GetHostNetworks - fetches all the networks
  455. func GetHostNetworks(hostID string) []string {
  456. currHost, err := GetHost(hostID)
  457. if err != nil {
  458. return nil
  459. }
  460. nets := []string{}
  461. for i := range currHost.Nodes {
  462. n, err := GetNodeByID(currHost.Nodes[i])
  463. if err != nil {
  464. return nil
  465. }
  466. nets = append(nets, n.Network)
  467. }
  468. return nets
  469. }
  470. // GetRelatedHosts - fetches related hosts of a given host
  471. func GetRelatedHosts(hostID string) []models.Host {
  472. relatedHosts := []models.Host{}
  473. networks := GetHostNetworks(hostID)
  474. networkMap := make(map[string]struct{})
  475. for _, network := range networks {
  476. networkMap[network] = struct{}{}
  477. }
  478. hosts, err := GetAllHosts()
  479. if err == nil {
  480. for _, host := range hosts {
  481. if host.ID.String() == hostID {
  482. continue
  483. }
  484. networks := GetHostNetworks(host.ID.String())
  485. for _, network := range networks {
  486. if _, ok := networkMap[network]; ok {
  487. relatedHosts = append(relatedHosts, host)
  488. break
  489. }
  490. }
  491. }
  492. }
  493. return relatedHosts
  494. }
  495. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  496. // with the same endpoint have different listen ports
  497. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  498. func CheckHostPorts(h *models.Host) {
  499. portsInUse := make(map[int]bool, 0)
  500. hosts, err := GetAllHosts()
  501. if err != nil {
  502. return
  503. }
  504. for _, host := range hosts {
  505. if host.ID.String() == h.ID.String() {
  506. // skip self
  507. continue
  508. }
  509. if !host.EndpointIP.Equal(h.EndpointIP) {
  510. continue
  511. }
  512. portsInUse[host.ListenPort] = true
  513. }
  514. // iterate until port is not found or max iteration is reached
  515. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  516. if h.ListenPort == 443 {
  517. h.ListenPort = 51821
  518. } else {
  519. h.ListenPort++
  520. }
  521. if h.ListenPort > maxPort {
  522. h.ListenPort = minPort
  523. }
  524. }
  525. }
  526. // HostExists - checks if given host already exists
  527. func HostExists(h *models.Host) bool {
  528. _, err := GetHost(h.ID.String())
  529. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  530. }
  531. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  532. func GetHostByNodeID(id string) *models.Host {
  533. hosts, err := GetAllHosts()
  534. if err != nil {
  535. return nil
  536. }
  537. for i := range hosts {
  538. h := hosts[i]
  539. if StringSliceContains(h.Nodes, id) {
  540. return &h
  541. }
  542. }
  543. return nil
  544. }
  545. // ConvHostPassToHash - converts password to md5 hash
  546. func ConvHostPassToHash(hostPass string) string {
  547. return fmt.Sprintf("%x", md5.Sum([]byte(hostPass)))
  548. }
  549. // SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first
  550. func SortApiHosts(unsortedHosts []models.ApiHost) {
  551. sort.Slice(unsortedHosts, func(i, j int) bool {
  552. return unsortedHosts[i].ID < unsortedHosts[j].ID
  553. })
  554. }