hosts.go 8.4 KB

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