hosts.go 14 KB

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