hosts.go 14 KB

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