hosts.go 14 KB

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