hosts.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. package logic
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "sort"
  8. "github.com/google/uuid"
  9. "github.com/gravitl/netmaker/database"
  10. "github.com/gravitl/netmaker/logger"
  11. "github.com/gravitl/netmaker/models"
  12. "github.com/gravitl/netmaker/servercfg"
  13. "golang.org/x/crypto/bcrypt"
  14. )
  15. var (
  16. // ErrHostExists error indicating that host exists when trying to create new host
  17. ErrHostExists error = errors.New("host already exists")
  18. // ErrInvalidHostID
  19. ErrInvalidHostID error = errors.New("invalid host id")
  20. )
  21. const (
  22. maxPort = 1<<16 - 1
  23. minPort = 1025
  24. )
  25. // GetAllHosts - returns all hosts in flat list or error
  26. func GetAllHosts() ([]models.Host, error) {
  27. currHostMap, err := GetHostsMap()
  28. if err != nil {
  29. return nil, err
  30. }
  31. var currentHosts = []models.Host{}
  32. for k := range currHostMap {
  33. var h = *currHostMap[k]
  34. currentHosts = append(currentHosts, h)
  35. }
  36. return currentHosts, nil
  37. }
  38. // GetAllHostsAPI - get's all the hosts in an API usable format
  39. func GetAllHostsAPI(hosts []models.Host) []models.ApiHost {
  40. apiHosts := []models.ApiHost{}
  41. for i := range hosts {
  42. newApiHost := hosts[i].ConvertNMHostToAPI()
  43. apiHosts = append(apiHosts, *newApiHost)
  44. }
  45. return apiHosts[:]
  46. }
  47. // GetHostsMap - gets all the current hosts on machine in a map
  48. func GetHostsMap() (map[string]*models.Host, error) {
  49. records, err := database.FetchRecords(database.HOSTS_TABLE_NAME)
  50. if err != nil && !database.IsEmptyRecord(err) {
  51. return nil, err
  52. }
  53. currHostMap := make(map[string]*models.Host)
  54. for k := range records {
  55. var h models.Host
  56. err = json.Unmarshal([]byte(records[k]), &h)
  57. if err != nil {
  58. return nil, err
  59. }
  60. currHostMap[h.ID.String()] = &h
  61. }
  62. return currHostMap, nil
  63. }
  64. // GetHost - gets a host from db given id
  65. func GetHost(hostid string) (*models.Host, error) {
  66. record, err := database.FetchRecord(database.HOSTS_TABLE_NAME, hostid)
  67. if err != nil {
  68. return nil, err
  69. }
  70. var h models.Host
  71. if err = json.Unmarshal([]byte(record), &h); err != nil {
  72. return nil, err
  73. }
  74. return &h, nil
  75. }
  76. // CreateHost - creates a host if not exist
  77. func CreateHost(h *models.Host) error {
  78. _, err := GetHost(h.ID.String())
  79. if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) {
  80. return ErrHostExists
  81. }
  82. // encrypt that password so we never see it
  83. hash, err := bcrypt.GenerateFromPassword([]byte(h.HostPass), 5)
  84. if err != nil {
  85. return err
  86. }
  87. h.HostPass = string(hash)
  88. h.AutoUpdate = servercfg.AutoUpdateEnabled()
  89. // if another server has already updated proxyenabled, leave it alone
  90. if !h.ProxyEnabledSet {
  91. log.Println("checking default proxy", servercfg.GetServerConfig().DefaultProxyMode)
  92. if servercfg.GetServerConfig().DefaultProxyMode.Set {
  93. h.ProxyEnabledSet = true
  94. h.ProxyEnabled = servercfg.GetServerConfig().DefaultProxyMode.Value
  95. log.Println("set proxy enabled to ", h.ProxyEnabled)
  96. }
  97. }
  98. checkForZombieHosts(h)
  99. return UpsertHost(h)
  100. }
  101. // UpdateHost - updates host data by field
  102. func UpdateHost(newHost, currentHost *models.Host) {
  103. // unchangeable fields via API here
  104. newHost.DaemonInstalled = currentHost.DaemonInstalled
  105. newHost.OS = currentHost.OS
  106. newHost.IPForwarding = currentHost.IPForwarding
  107. newHost.HostPass = currentHost.HostPass
  108. newHost.MacAddress = currentHost.MacAddress
  109. newHost.Debug = currentHost.Debug
  110. newHost.Nodes = currentHost.Nodes
  111. newHost.PublicKey = currentHost.PublicKey
  112. newHost.InternetGateway = currentHost.InternetGateway
  113. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  114. // changeable fields
  115. if len(newHost.Version) == 0 {
  116. newHost.Version = currentHost.Version
  117. }
  118. if len(newHost.Name) == 0 {
  119. newHost.Name = currentHost.Name
  120. }
  121. if newHost.MTU == 0 {
  122. newHost.MTU = currentHost.MTU
  123. }
  124. if newHost.ListenPort == 0 {
  125. newHost.ListenPort = currentHost.ListenPort
  126. }
  127. if newHost.ProxyListenPort == 0 {
  128. newHost.ProxyListenPort = currentHost.ProxyListenPort
  129. }
  130. newHost.PublicListenPort = currentHost.PublicListenPort
  131. }
  132. // UpdateHostFromClient - used for updating host on server with update recieved from client
  133. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  134. if newHost.PublicKey != currHost.PublicKey {
  135. currHost.PublicKey = newHost.PublicKey
  136. sendPeerUpdate = true
  137. }
  138. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  139. currHost.ListenPort = newHost.ListenPort
  140. sendPeerUpdate = true
  141. }
  142. if newHost.ProxyListenPort != 0 && currHost.ProxyListenPort != newHost.ProxyListenPort {
  143. currHost.ProxyListenPort = newHost.ProxyListenPort
  144. sendPeerUpdate = true
  145. }
  146. if newHost.PublicListenPort != 0 && currHost.PublicListenPort != newHost.PublicListenPort {
  147. currHost.PublicListenPort = newHost.PublicListenPort
  148. sendPeerUpdate = true
  149. }
  150. if currHost.ProxyEnabled != newHost.ProxyEnabled {
  151. currHost.ProxyEnabled = newHost.ProxyEnabled
  152. sendPeerUpdate = true
  153. }
  154. if currHost.EndpointIP.String() != newHost.EndpointIP.String() {
  155. currHost.EndpointIP = newHost.EndpointIP
  156. sendPeerUpdate = true
  157. }
  158. currHost.DaemonInstalled = newHost.DaemonInstalled
  159. currHost.Debug = newHost.Debug
  160. currHost.Verbosity = newHost.Verbosity
  161. currHost.Version = newHost.Version
  162. if newHost.Name != "" {
  163. currHost.Name = newHost.Name
  164. }
  165. if len(newHost.NatType) > 0 && newHost.NatType != currHost.NatType {
  166. currHost.NatType = newHost.NatType
  167. sendPeerUpdate = true
  168. }
  169. return
  170. }
  171. // UpsertHost - upserts into DB a given host model, does not check for existence*
  172. func UpsertHost(h *models.Host) error {
  173. data, err := json.Marshal(h)
  174. if err != nil {
  175. return err
  176. }
  177. return database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  178. }
  179. // RemoveHost - removes a given host from server
  180. func RemoveHost(h *models.Host) error {
  181. if len(h.Nodes) > 0 {
  182. return fmt.Errorf("host still has associated nodes")
  183. }
  184. return database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  185. }
  186. // RemoveHostByID - removes a given host by id from server
  187. func RemoveHostByID(hostID string) error {
  188. return database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  189. }
  190. // UpdateHostNetwork - adds/deletes host from a network
  191. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  192. for _, nodeID := range h.Nodes {
  193. node, err := GetNodeByID(nodeID)
  194. if err != nil || node.PendingDelete {
  195. continue
  196. }
  197. if node.Network == network {
  198. if !add {
  199. return &node, nil
  200. } else {
  201. return nil, errors.New("host already part of network " + network)
  202. }
  203. }
  204. }
  205. if !add {
  206. return nil, errors.New("host not part of the network " + network)
  207. } else {
  208. newNode := models.Node{}
  209. newNode.Server = servercfg.GetServer()
  210. newNode.Network = network
  211. newNode.HostID = h.ID
  212. if err := AssociateNodeToHost(&newNode, h); err != nil {
  213. return nil, err
  214. }
  215. return &newNode, nil
  216. }
  217. }
  218. // AssociateNodeToHost - associates and creates a node with a given host
  219. // should be the only way nodes get created as of 0.18
  220. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  221. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  222. return ErrInvalidHostID
  223. }
  224. n.HostID = h.ID
  225. err := createNode(n)
  226. if err != nil {
  227. return err
  228. }
  229. currentHost, err := GetHost(h.ID.String())
  230. if err != nil {
  231. return err
  232. }
  233. h.HostPass = currentHost.HostPass
  234. h.Nodes = append(currentHost.Nodes, n.ID.String())
  235. return UpsertHost(h)
  236. }
  237. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  238. // should be the only way nodes are deleted as of 0.18
  239. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  240. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  241. return ErrInvalidHostID
  242. }
  243. if n.HostID != h.ID { // check if node actually belongs to host
  244. return fmt.Errorf("node is not associated with host")
  245. }
  246. if len(h.Nodes) == 0 {
  247. return fmt.Errorf("no nodes present in given host")
  248. }
  249. index := -1
  250. for i := range h.Nodes {
  251. if h.Nodes[i] == n.ID.String() {
  252. index = i
  253. break
  254. }
  255. }
  256. if index < 0 {
  257. if len(h.Nodes) == 0 {
  258. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  259. }
  260. } else {
  261. h.Nodes = RemoveStringSlice(h.Nodes, index)
  262. }
  263. if err := deleteNodeByID(n); err != nil {
  264. return err
  265. }
  266. return UpsertHost(h)
  267. }
  268. // DisassociateAllNodesFromHost - deletes all nodes of the host
  269. func DisassociateAllNodesFromHost(hostID string) error {
  270. host, err := GetHost(hostID)
  271. if err != nil {
  272. return err
  273. }
  274. for _, nodeID := range host.Nodes {
  275. node, err := GetNodeByID(nodeID)
  276. if err != nil {
  277. logger.Log(0, "failed to get host node", err.Error())
  278. continue
  279. }
  280. if err := DeleteNode(&node, true); err != nil {
  281. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  282. continue
  283. }
  284. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  285. }
  286. host.Nodes = []string{}
  287. return UpsertHost(host)
  288. }
  289. // GetDefaultHosts - retrieve all hosts marked as default from DB
  290. func GetDefaultHosts() []models.Host {
  291. defaultHostList := []models.Host{}
  292. hosts, err := GetAllHosts()
  293. if err != nil {
  294. return defaultHostList
  295. }
  296. for i := range hosts {
  297. if hosts[i].IsDefault {
  298. defaultHostList = append(defaultHostList, hosts[i])
  299. }
  300. }
  301. return defaultHostList[:]
  302. }
  303. // GetHostNetworks - fetches all the networks
  304. func GetHostNetworks(hostID string) []string {
  305. currHost, err := GetHost(hostID)
  306. if err != nil {
  307. return nil
  308. }
  309. nets := []string{}
  310. for i := range currHost.Nodes {
  311. n, err := GetNodeByID(currHost.Nodes[i])
  312. if err != nil {
  313. return nil
  314. }
  315. nets = append(nets, n.Network)
  316. }
  317. return nets
  318. }
  319. // GetRelatedHosts - fetches related hosts of a given host
  320. func GetRelatedHosts(hostID string) []models.Host {
  321. relatedHosts := []models.Host{}
  322. networks := GetHostNetworks(hostID)
  323. networkMap := make(map[string]struct{})
  324. for _, network := range networks {
  325. networkMap[network] = struct{}{}
  326. }
  327. hosts, err := GetAllHosts()
  328. if err == nil {
  329. for _, host := range hosts {
  330. if host.ID.String() == hostID {
  331. continue
  332. }
  333. networks := GetHostNetworks(host.ID.String())
  334. for _, network := range networks {
  335. if _, ok := networkMap[network]; ok {
  336. relatedHosts = append(relatedHosts, host)
  337. break
  338. }
  339. }
  340. }
  341. }
  342. return relatedHosts
  343. }
  344. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  345. // with the same endpoint have different listen ports
  346. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  347. func CheckHostPorts(h *models.Host) {
  348. portsInUse := make(map[int]bool, 0)
  349. hosts, err := GetAllHosts()
  350. if err != nil {
  351. return
  352. }
  353. for _, host := range hosts {
  354. if host.ID.String() == h.ID.String() {
  355. //skip self
  356. continue
  357. }
  358. if !host.EndpointIP.Equal(h.EndpointIP) {
  359. continue
  360. }
  361. portsInUse[host.ListenPort] = true
  362. portsInUse[host.ProxyListenPort] = true
  363. }
  364. // iterate until port is not found or max iteration is reached
  365. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  366. h.ListenPort++
  367. if h.ListenPort > maxPort {
  368. h.ListenPort = minPort
  369. }
  370. }
  371. // allocate h.ListenPort so it is unavailable to h.ProxyListenPort
  372. portsInUse[h.ListenPort] = true
  373. for i := 0; portsInUse[h.ProxyListenPort] && i < maxPort-minPort+1; i++ {
  374. h.ProxyListenPort++
  375. if h.ProxyListenPort > maxPort {
  376. h.ProxyListenPort = minPort
  377. }
  378. }
  379. }
  380. // HostExists - checks if given host already exists
  381. func HostExists(h *models.Host) bool {
  382. _, err := GetHost(h.ID.String())
  383. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  384. }
  385. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  386. func GetHostByNodeID(id string) *models.Host {
  387. hosts, err := GetAllHosts()
  388. if err != nil {
  389. return nil
  390. }
  391. for i := range hosts {
  392. h := hosts[i]
  393. if StringSliceContains(h.Nodes, id) {
  394. return &h
  395. }
  396. }
  397. return nil
  398. }
  399. // SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first
  400. func SortApiHosts(unsortedHosts []models.ApiHost) {
  401. sort.Slice(unsortedHosts, func(i, j int) bool {
  402. return unsortedHosts[i].ID < unsortedHosts[j].ID
  403. })
  404. }