hosts.go 11 KB

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