hosts.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. currentHost, err := GetHost(h.ID.String())
  210. if err != nil {
  211. return err
  212. }
  213. h.HostPass = currentHost.HostPass
  214. h.Nodes = append(currentHost.Nodes, n.ID.String())
  215. return UpsertHost(h)
  216. }
  217. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  218. // should be the only way nodes are deleted as of 0.18
  219. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  220. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  221. return ErrInvalidHostID
  222. }
  223. if n.HostID != h.ID { // check if node actually belongs to host
  224. return fmt.Errorf("node is not associated with host")
  225. }
  226. if len(h.Nodes) == 0 {
  227. return fmt.Errorf("no nodes present in given host")
  228. }
  229. index := -1
  230. for i := range h.Nodes {
  231. if h.Nodes[i] == n.ID.String() {
  232. index = i
  233. break
  234. }
  235. }
  236. if index < 0 {
  237. if len(h.Nodes) == 0 {
  238. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  239. }
  240. } else {
  241. h.Nodes = RemoveStringSlice(h.Nodes, index)
  242. }
  243. if err := deleteNodeByID(n); err != nil {
  244. return err
  245. }
  246. return UpsertHost(h)
  247. }
  248. // DisassociateAllNodesFromHost - deletes all nodes of the host
  249. func DisassociateAllNodesFromHost(hostID string) error {
  250. host, err := GetHost(hostID)
  251. if err != nil {
  252. return err
  253. }
  254. for _, nodeID := range host.Nodes {
  255. node, err := GetNodeByID(nodeID)
  256. if err != nil {
  257. logger.Log(0, "failed to get host node", err.Error())
  258. continue
  259. }
  260. if err := DeleteNode(&node, true); err != nil {
  261. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  262. continue
  263. }
  264. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  265. }
  266. host.Nodes = []string{}
  267. return UpsertHost(host)
  268. }
  269. // GetDefaultHosts - retrieve all hosts marked as default from DB
  270. func GetDefaultHosts() []models.Host {
  271. defaultHostList := []models.Host{}
  272. hosts, err := GetAllHosts()
  273. if err != nil {
  274. return defaultHostList
  275. }
  276. for i := range hosts {
  277. if hosts[i].IsDefault {
  278. defaultHostList = append(defaultHostList, hosts[i])
  279. }
  280. }
  281. return defaultHostList[:]
  282. }
  283. // GetHostNetworks - fetches all the networks
  284. func GetHostNetworks(hostID string) []string {
  285. currHost, err := GetHost(hostID)
  286. if err != nil {
  287. return nil
  288. }
  289. nets := []string{}
  290. for i := range currHost.Nodes {
  291. n, err := GetNodeByID(currHost.Nodes[i])
  292. if err != nil {
  293. return nil
  294. }
  295. nets = append(nets, n.Network)
  296. }
  297. return nets
  298. }
  299. // GetRelatedHosts - fetches related hosts of a given host
  300. func GetRelatedHosts(hostID string) []models.Host {
  301. relatedHosts := []models.Host{}
  302. networks := GetHostNetworks(hostID)
  303. networkMap := make(map[string]struct{})
  304. for _, network := range networks {
  305. networkMap[network] = struct{}{}
  306. }
  307. hosts, err := GetAllHosts()
  308. if err == nil {
  309. for _, host := range hosts {
  310. if host.ID.String() == hostID {
  311. continue
  312. }
  313. networks := GetHostNetworks(host.ID.String())
  314. for _, network := range networks {
  315. if _, ok := networkMap[network]; ok {
  316. relatedHosts = append(relatedHosts, host)
  317. break
  318. }
  319. }
  320. }
  321. }
  322. return relatedHosts
  323. }
  324. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  325. // with the same endpoint have different listen ports
  326. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  327. func CheckHostPorts(h *models.Host) {
  328. portsInUse := make(map[int]bool)
  329. hosts, err := GetAllHosts()
  330. if err != nil {
  331. return
  332. }
  333. for _, host := range hosts {
  334. if host.ID == h.ID {
  335. //skip self
  336. continue
  337. }
  338. if !host.EndpointIP.Equal(h.EndpointIP) {
  339. continue
  340. }
  341. portsInUse[host.ListenPort] = true
  342. portsInUse[host.ProxyListenPort] = true
  343. }
  344. // iterate until port is not found or max iteration is reached
  345. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  346. updatePort(&h.ListenPort)
  347. }
  348. // allocate h.ListenPort so it is unavailable to h.ProxyListenPort
  349. portsInUse[h.ListenPort] = true
  350. for i := 0; portsInUse[h.ProxyListenPort] && i < maxPort-minPort+1; i++ {
  351. updatePort(&h.ProxyListenPort)
  352. }
  353. }
  354. // HostExists - checks if given host already exists
  355. func HostExists(h *models.Host) bool {
  356. _, err := GetHost(h.ID.String())
  357. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  358. }
  359. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  360. func GetHostByNodeID(id string) *models.Host {
  361. hosts, err := GetAllHosts()
  362. if err != nil {
  363. return nil
  364. }
  365. for i := range hosts {
  366. h := hosts[i]
  367. if StringSliceContains(h.Nodes, id) {
  368. return &h
  369. }
  370. }
  371. return nil
  372. }
  373. func updatePort(p *int) {
  374. *p++
  375. if *p > maxPort {
  376. *p = minPort
  377. }
  378. }