hosts.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. checkForZombieHosts(h)
  87. return UpsertHost(h)
  88. }
  89. // UpdateHost - updates host data by field
  90. func UpdateHost(newHost, currentHost *models.Host) {
  91. // unchangeable fields via API here
  92. newHost.DaemonInstalled = currentHost.DaemonInstalled
  93. newHost.OS = currentHost.OS
  94. newHost.IPForwarding = currentHost.IPForwarding
  95. newHost.HostPass = currentHost.HostPass
  96. newHost.MacAddress = currentHost.MacAddress
  97. newHost.Debug = currentHost.Debug
  98. newHost.Nodes = currentHost.Nodes
  99. newHost.PublicKey = currentHost.PublicKey
  100. newHost.InternetGateway = currentHost.InternetGateway
  101. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  102. // changeable fields
  103. if len(newHost.Version) == 0 {
  104. newHost.Version = currentHost.Version
  105. }
  106. if len(newHost.Name) == 0 {
  107. newHost.Name = currentHost.Name
  108. }
  109. if newHost.MTU == 0 {
  110. newHost.MTU = currentHost.MTU
  111. }
  112. if newHost.ListenPort == 0 {
  113. newHost.ListenPort = currentHost.ListenPort
  114. }
  115. if newHost.ProxyListenPort == 0 {
  116. newHost.ProxyListenPort = currentHost.ProxyListenPort
  117. }
  118. newHost.PublicListenPort = currentHost.PublicListenPort
  119. }
  120. // UpdateHostFromClient - used for updating host on server with update recieved from client
  121. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  122. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  123. currHost.ListenPort = newHost.ListenPort
  124. sendPeerUpdate = true
  125. }
  126. if newHost.ProxyListenPort != 0 && currHost.ProxyListenPort != newHost.ProxyListenPort {
  127. currHost.ProxyListenPort = newHost.ProxyListenPort
  128. sendPeerUpdate = true
  129. }
  130. if newHost.PublicListenPort != 0 && currHost.PublicListenPort != newHost.PublicListenPort {
  131. currHost.PublicListenPort = newHost.PublicListenPort
  132. sendPeerUpdate = true
  133. }
  134. if currHost.ProxyEnabled != newHost.ProxyEnabled {
  135. currHost.ProxyEnabled = newHost.ProxyEnabled
  136. sendPeerUpdate = true
  137. }
  138. if currHost.EndpointIP.String() != newHost.EndpointIP.String() {
  139. currHost.EndpointIP = newHost.EndpointIP
  140. sendPeerUpdate = true
  141. }
  142. currHost.DaemonInstalled = newHost.DaemonInstalled
  143. currHost.Debug = newHost.Debug
  144. currHost.Verbosity = newHost.Verbosity
  145. currHost.Version = newHost.Version
  146. if newHost.Name != "" {
  147. currHost.Name = newHost.Name
  148. }
  149. return
  150. }
  151. // UpsertHost - upserts into DB a given host model, does not check for existence*
  152. func UpsertHost(h *models.Host) error {
  153. data, err := json.Marshal(h)
  154. if err != nil {
  155. return err
  156. }
  157. return database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  158. }
  159. // RemoveHost - removes a given host from server
  160. func RemoveHost(h *models.Host) error {
  161. if len(h.Nodes) > 0 {
  162. return fmt.Errorf("host still has associated nodes")
  163. }
  164. return database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  165. }
  166. // RemoveHostByID - removes a given host by id from server
  167. func RemoveHostByID(hostID string) error {
  168. return database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  169. }
  170. // UpdateHostNetwork - adds/deletes host from a network
  171. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  172. for _, nodeID := range h.Nodes {
  173. node, err := GetNodeByID(nodeID)
  174. if err != nil || node.PendingDelete {
  175. continue
  176. }
  177. if node.Network == network {
  178. if !add {
  179. return &node, nil
  180. } else {
  181. return nil, errors.New("host already part of network " + network)
  182. }
  183. }
  184. }
  185. if !add {
  186. return nil, errors.New("host not part of the network " + network)
  187. } else {
  188. newNode := models.Node{}
  189. newNode.Server = servercfg.GetServer()
  190. newNode.Network = network
  191. newNode.HostID = h.ID
  192. if err := AssociateNodeToHost(&newNode, h); err != nil {
  193. return nil, err
  194. }
  195. return &newNode, nil
  196. }
  197. }
  198. // AssociateNodeToHost - associates and creates a node with a given host
  199. // should be the only way nodes get created as of 0.18
  200. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  201. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  202. return ErrInvalidHostID
  203. }
  204. n.HostID = h.ID
  205. err := createNode(n)
  206. if err != nil {
  207. return err
  208. }
  209. h.Nodes = append(h.Nodes, n.ID.String())
  210. return UpsertHost(h)
  211. }
  212. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  213. // should be the only way nodes are deleted as of 0.18
  214. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  215. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  216. return ErrInvalidHostID
  217. }
  218. if n.HostID != h.ID { // check if node actually belongs to host
  219. return fmt.Errorf("node is not associated with host")
  220. }
  221. if len(h.Nodes) == 0 {
  222. return fmt.Errorf("no nodes present in given host")
  223. }
  224. index := -1
  225. for i := range h.Nodes {
  226. if h.Nodes[i] == n.ID.String() {
  227. index = i
  228. break
  229. }
  230. }
  231. if index < 0 {
  232. if len(h.Nodes) == 0 {
  233. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  234. }
  235. } else {
  236. h.Nodes = RemoveStringSlice(h.Nodes, index)
  237. }
  238. if err := deleteNodeByID(n); err != nil {
  239. return err
  240. }
  241. return UpsertHost(h)
  242. }
  243. // DisassociateAllNodesFromHost - deletes all nodes of the host
  244. func DisassociateAllNodesFromHost(hostID string) error {
  245. host, err := GetHost(hostID)
  246. if err != nil {
  247. return err
  248. }
  249. for _, nodeID := range host.Nodes {
  250. node, err := GetNodeByID(nodeID)
  251. if err != nil {
  252. logger.Log(0, "failed to get host node", err.Error())
  253. continue
  254. }
  255. if err := DeleteNode(&node, true); err != nil {
  256. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  257. continue
  258. }
  259. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  260. }
  261. host.Nodes = []string{}
  262. return UpsertHost(host)
  263. }
  264. // GetDefaultHosts - retrieve all hosts marked as default from DB
  265. func GetDefaultHosts() []models.Host {
  266. defaultHostList := []models.Host{}
  267. hosts, err := GetAllHosts()
  268. if err != nil {
  269. return defaultHostList
  270. }
  271. for i := range hosts {
  272. if hosts[i].IsDefault {
  273. defaultHostList = append(defaultHostList, hosts[i])
  274. }
  275. }
  276. return defaultHostList[:]
  277. }
  278. // GetHostNetworks - fetches all the networks
  279. func GetHostNetworks(hostID string) []string {
  280. currHost, err := GetHost(hostID)
  281. if err != nil {
  282. return nil
  283. }
  284. nets := []string{}
  285. for i := range currHost.Nodes {
  286. n, err := GetNodeByID(currHost.Nodes[i])
  287. if err != nil {
  288. return nil
  289. }
  290. nets = append(nets, n.Network)
  291. }
  292. return nets
  293. }
  294. // GetRelatedHosts - fetches related hosts of a given host
  295. func GetRelatedHosts(hostID string) []models.Host {
  296. relatedHosts := []models.Host{}
  297. networks := GetHostNetworks(hostID)
  298. networkMap := make(map[string]struct{})
  299. for _, network := range networks {
  300. networkMap[network] = struct{}{}
  301. }
  302. hosts, err := GetAllHosts()
  303. if err == nil {
  304. for _, host := range hosts {
  305. if host.ID.String() == hostID {
  306. continue
  307. }
  308. networks := GetHostNetworks(host.ID.String())
  309. for _, network := range networks {
  310. if _, ok := networkMap[network]; ok {
  311. relatedHosts = append(relatedHosts, host)
  312. break
  313. }
  314. }
  315. }
  316. }
  317. return relatedHosts
  318. }
  319. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  320. // with the same endpoint have different listen ports
  321. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  322. func CheckHostPorts(h *models.Host) {
  323. portsInUse := make(map[int]bool)
  324. hosts, err := GetAllHosts()
  325. if err != nil {
  326. return
  327. }
  328. for _, host := range hosts {
  329. if host.ID == h.ID {
  330. //skip self
  331. continue
  332. }
  333. if !host.EndpointIP.Equal(h.EndpointIP) {
  334. continue
  335. }
  336. portsInUse[host.ListenPort] = true
  337. portsInUse[host.ProxyListenPort] = true
  338. }
  339. // iterate until port is not found or max iteration is reached
  340. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  341. updatePort(&h.ListenPort)
  342. }
  343. // allocate h.ListenPort so it is unavailable to h.ProxyListenPort
  344. portsInUse[h.ListenPort] = true
  345. for i := 0; portsInUse[h.ProxyListenPort] && i < maxPort-minPort+1; i++ {
  346. updatePort(&h.ProxyListenPort)
  347. }
  348. }
  349. // HostExists - checks if given host already exists
  350. func HostExists(h *models.Host) bool {
  351. _, err := GetHost(h.ID.String())
  352. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  353. }
  354. func updatePort(p *int) {
  355. *p++
  356. if *p > maxPort {
  357. *p = minPort
  358. }
  359. }