hosts.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. "golang.org/x/crypto/bcrypt"
  11. )
  12. var (
  13. // ErrHostExists error indicating that host exists when trying to create new host
  14. ErrHostExists error = errors.New("host already exists")
  15. // ErrInvalidHostID
  16. ErrInvalidHostID error = errors.New("invalid host id")
  17. )
  18. // GetAllHosts - returns all hosts in flat list or error
  19. func GetAllHosts() ([]models.Host, error) {
  20. currHostMap, err := GetHostsMap()
  21. if err != nil {
  22. return nil, err
  23. }
  24. var currentHosts = []models.Host{}
  25. for k := range currHostMap {
  26. var h = *currHostMap[k]
  27. currentHosts = append(currentHosts, h)
  28. }
  29. return currentHosts, nil
  30. }
  31. // GetAllHostsAPI - get's all the hosts in an API usable format
  32. func GetAllHostsAPI(hosts []models.Host) []models.ApiHost {
  33. apiHosts := []models.ApiHost{}
  34. for i := range hosts {
  35. newApiHost := hosts[i].ConvertNMHostToAPI()
  36. apiHosts = append(apiHosts, *newApiHost)
  37. }
  38. return apiHosts[:]
  39. }
  40. // GetHostsMap - gets all the current hosts on machine in a map
  41. func GetHostsMap() (map[string]*models.Host, error) {
  42. records, err := database.FetchRecords(database.HOSTS_TABLE_NAME)
  43. if err != nil && !database.IsEmptyRecord(err) {
  44. return nil, err
  45. }
  46. currHostMap := make(map[string]*models.Host)
  47. for k := range records {
  48. var h models.Host
  49. err = json.Unmarshal([]byte(records[k]), &h)
  50. if err != nil {
  51. return nil, err
  52. }
  53. currHostMap[h.ID.String()] = &h
  54. }
  55. return currHostMap, nil
  56. }
  57. // GetHost - gets a host from db given id
  58. func GetHost(hostid string) (*models.Host, error) {
  59. record, err := database.FetchRecord(database.HOSTS_TABLE_NAME, hostid)
  60. if err != nil {
  61. return nil, err
  62. }
  63. var h models.Host
  64. if err = json.Unmarshal([]byte(record), &h); err != nil {
  65. return nil, err
  66. }
  67. return &h, nil
  68. }
  69. // CreateHost - creates a host if not exist
  70. func CreateHost(h *models.Host) error {
  71. _, err := GetHost(h.ID.String())
  72. if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) {
  73. return ErrHostExists
  74. }
  75. //encrypt that password so we never see it
  76. hash, err := bcrypt.GenerateFromPassword([]byte(h.HostPass), 5)
  77. if err != nil {
  78. return err
  79. }
  80. h.HostPass = string(hash)
  81. return UpsertHost(h)
  82. }
  83. // UpdateHost - updates host data by field
  84. func UpdateHost(newHost, currentHost *models.Host) {
  85. // unchangeable fields via API here
  86. newHost.DaemonInstalled = currentHost.DaemonInstalled
  87. newHost.OS = currentHost.OS
  88. newHost.IPForwarding = currentHost.IPForwarding
  89. newHost.HostPass = currentHost.HostPass
  90. newHost.MacAddress = currentHost.MacAddress
  91. newHost.Debug = currentHost.Debug
  92. newHost.Nodes = currentHost.Nodes
  93. newHost.PublicKey = currentHost.PublicKey
  94. newHost.InternetGateway = currentHost.InternetGateway
  95. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  96. // changeable fields
  97. if len(newHost.Version) == 0 {
  98. newHost.Version = currentHost.Version
  99. }
  100. if len(newHost.Name) == 0 {
  101. newHost.Name = currentHost.Name
  102. }
  103. if newHost.LocalRange.String() != currentHost.LocalRange.String() {
  104. newHost.LocalRange = currentHost.LocalRange
  105. }
  106. if newHost.MTU == 0 {
  107. newHost.MTU = currentHost.MTU
  108. }
  109. if newHost.ListenPort == 0 {
  110. newHost.ListenPort = currentHost.ListenPort
  111. }
  112. if newHost.ProxyListenPort == 0 {
  113. newHost.ProxyListenPort = currentHost.ProxyListenPort
  114. }
  115. }
  116. // UpsertHost - upserts into DB a given host model, does not check for existence*
  117. func UpsertHost(h *models.Host) error {
  118. data, err := json.Marshal(h)
  119. if err != nil {
  120. return err
  121. }
  122. return database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  123. }
  124. // RemoveHost - removes a given host from server
  125. func RemoveHost(h *models.Host) error {
  126. if len(h.Nodes) > 0 {
  127. return fmt.Errorf("host still has associated nodes")
  128. }
  129. return database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  130. }
  131. // RemoveHostByID - removes a given host by id from server
  132. func RemoveHostByID(hostID string) error {
  133. return database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  134. }
  135. // UpdateHostNetworks - updates a given host's networks
  136. func UpdateHostNetworks(h *models.Host, server string, nets []string) error {
  137. if len(h.Nodes) > 0 {
  138. for i := range h.Nodes {
  139. n, err := GetNodeByID(h.Nodes[i])
  140. if err != nil {
  141. return err
  142. }
  143. // loop through networks and remove need for updating existing networks
  144. found := false
  145. for j := range nets {
  146. if len(nets[j]) > 0 && nets[j] == n.Network {
  147. nets[j] = "" // mark as ignore
  148. found = true
  149. }
  150. }
  151. if !found { // remove the node/host from that network
  152. if err = DissasociateNodeFromHost(&n, h); err != nil {
  153. return err
  154. }
  155. }
  156. }
  157. } else {
  158. h.Nodes = []string{}
  159. }
  160. for i := range nets {
  161. // create a node for each non zero network remaining
  162. if len(nets[i]) > 0 {
  163. newNode := models.Node{}
  164. newNode.Server = server
  165. newNode.Network = nets[i]
  166. if err := AssociateNodeToHost(&newNode, h); err != nil {
  167. return err
  168. }
  169. logger.Log(1, "added new node", newNode.ID.String(), "to host", h.Name)
  170. }
  171. }
  172. return nil
  173. }
  174. // AssociateNodeToHost - associates and creates a node with a given host
  175. // should be the only way nodes get created as of 0.18
  176. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  177. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  178. return ErrInvalidHostID
  179. }
  180. n.HostID = h.ID
  181. err := createNode(n)
  182. if err != nil {
  183. return err
  184. }
  185. h.Nodes = append(h.Nodes, n.ID.String())
  186. return UpsertHost(h)
  187. }
  188. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  189. // should be the only way nodes are deleted as of 0.18
  190. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  191. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  192. return ErrInvalidHostID
  193. }
  194. if n.HostID != h.ID { // check if node actually belongs to host
  195. return fmt.Errorf("node is not associated with host")
  196. }
  197. if len(h.Nodes) == 0 {
  198. return fmt.Errorf("no nodes present in given host")
  199. }
  200. index := -1
  201. for i := range h.Nodes {
  202. if h.Nodes[i] == n.ID.String() {
  203. index = i
  204. break
  205. }
  206. }
  207. if index < 0 {
  208. if len(h.Nodes) == 0 {
  209. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  210. }
  211. } else {
  212. h.Nodes = RemoveStringSlice(h.Nodes, index)
  213. }
  214. if err := deleteNodeByID(n); err != nil {
  215. return err
  216. }
  217. return UpsertHost(h)
  218. }
  219. // DisassociateAllNodesFromHost - deletes all nodes of the host
  220. func DisassociateAllNodesFromHost(hostID string) error {
  221. host, err := GetHost(hostID)
  222. if err != nil {
  223. return err
  224. }
  225. for _, nodeID := range host.Nodes {
  226. node, err := GetNodeByID(nodeID)
  227. if err != nil {
  228. logger.Log(0, "failed to get host node", err.Error())
  229. continue
  230. }
  231. if err := DeleteNode(&node, true); err != nil {
  232. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  233. continue
  234. }
  235. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  236. }
  237. host.Nodes = []string{}
  238. return UpsertHost(host)
  239. }
  240. // GetDefaultHosts - retrieve all hosts marked as default from DB
  241. func GetDefaultHosts() []models.Host {
  242. defaultHostList := []models.Host{}
  243. hosts, err := GetAllHosts()
  244. if err != nil {
  245. return defaultHostList
  246. }
  247. for i := range hosts {
  248. if hosts[i].IsDefault {
  249. defaultHostList = append(defaultHostList, hosts[i])
  250. }
  251. }
  252. return defaultHostList[:]
  253. }
  254. // AddDefaultHostsToNetwork - adds a node to network for every default host on Netmaker server
  255. func AddDefaultHostsToNetwork(network, server string) error {
  256. // add default hosts to network
  257. defaultHosts := GetDefaultHosts()
  258. for i := range defaultHosts {
  259. newNode := models.Node{}
  260. newNode.Network = network
  261. newNode.Server = server
  262. if err := AssociateNodeToHost(&newNode, &defaultHosts[i]); err != nil {
  263. return err
  264. }
  265. }
  266. return nil
  267. }
  268. // GetHostNetworks - fetches all the networks
  269. func GetHostNetworks(hostID string) []string {
  270. currHost, err := GetHost(hostID)
  271. if err != nil {
  272. return nil
  273. }
  274. nets := []string{}
  275. for i := range currHost.Nodes {
  276. n, err := GetNodeByID(currHost.Nodes[i])
  277. if err != nil {
  278. return nil
  279. }
  280. nets = append(nets, n.Network)
  281. }
  282. return nets
  283. }
  284. // GetRelatedHosts - fetches related hosts of a given host
  285. func GetRelatedHosts(hostID string) []models.Host {
  286. relatedHosts := []models.Host{}
  287. networks := GetHostNetworks(hostID)
  288. networkMap := make(map[string]struct{})
  289. for _, network := range networks {
  290. networkMap[network] = struct{}{}
  291. }
  292. hosts, err := GetAllHosts()
  293. if err == nil {
  294. for _, host := range hosts {
  295. if host.ID.String() == hostID {
  296. continue
  297. }
  298. networks := GetHostNetworks(host.ID.String())
  299. for _, network := range networks {
  300. if _, ok := networkMap[network]; ok {
  301. relatedHosts = append(relatedHosts, host)
  302. break
  303. }
  304. }
  305. }
  306. }
  307. return relatedHosts
  308. }