hosts.go 15 KB

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