2
0

hosts.go 14 KB

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