hosts.go 14 KB

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