hosts.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. if add {
  139. newNode := models.Node{}
  140. newNode.Server = servercfg.GetServer()
  141. newNode.Network = network
  142. if err := AssociateNodeToHost(&newNode, h); err != nil {
  143. return nil, err
  144. }
  145. return &newNode, nil
  146. }
  147. return nil, errors.New("failed to update host networks")
  148. }
  149. // AssociateNodeToHost - associates and creates a node with a given host
  150. // should be the only way nodes get created as of 0.18
  151. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  152. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  153. return ErrInvalidHostID
  154. }
  155. n.HostID = h.ID
  156. err := createNode(n)
  157. if err != nil {
  158. return err
  159. }
  160. h.Nodes = append(h.Nodes, n.ID.String())
  161. return UpsertHost(h)
  162. }
  163. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  164. // should be the only way nodes are deleted as of 0.18
  165. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  166. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  167. return ErrInvalidHostID
  168. }
  169. if n.HostID != h.ID { // check if node actually belongs to host
  170. return fmt.Errorf("node is not associated with host")
  171. }
  172. if len(h.Nodes) == 0 {
  173. return fmt.Errorf("no nodes present in given host")
  174. }
  175. index := -1
  176. for i := range h.Nodes {
  177. if h.Nodes[i] == n.ID.String() {
  178. index = i
  179. break
  180. }
  181. }
  182. if index < 0 {
  183. if len(h.Nodes) == 0 {
  184. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  185. }
  186. } else {
  187. h.Nodes = RemoveStringSlice(h.Nodes, index)
  188. }
  189. if err := deleteNodeByID(n); err != nil {
  190. return err
  191. }
  192. return UpsertHost(h)
  193. }
  194. // DisassociateAllNodesFromHost - deletes all nodes of the host
  195. func DisassociateAllNodesFromHost(hostID string) error {
  196. host, err := GetHost(hostID)
  197. if err != nil {
  198. return err
  199. }
  200. for _, nodeID := range host.Nodes {
  201. node, err := GetNodeByID(nodeID)
  202. if err != nil {
  203. logger.Log(0, "failed to get host node", err.Error())
  204. continue
  205. }
  206. if err := DeleteNode(&node, true); err != nil {
  207. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  208. continue
  209. }
  210. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  211. }
  212. host.Nodes = []string{}
  213. return UpsertHost(host)
  214. }
  215. // GetDefaultHosts - retrieve all hosts marked as default from DB
  216. func GetDefaultHosts() []models.Host {
  217. defaultHostList := []models.Host{}
  218. hosts, err := GetAllHosts()
  219. if err != nil {
  220. return defaultHostList
  221. }
  222. for i := range hosts {
  223. if hosts[i].IsDefault {
  224. defaultHostList = append(defaultHostList, hosts[i])
  225. }
  226. }
  227. return defaultHostList[:]
  228. }
  229. // AddDefaultHostsToNetwork - adds a node to network for every default host on Netmaker server
  230. func AddDefaultHostsToNetwork(network, server string) error {
  231. // add default hosts to network
  232. defaultHosts := GetDefaultHosts()
  233. for i := range defaultHosts {
  234. newNode := models.Node{}
  235. newNode.Network = network
  236. newNode.Server = server
  237. if err := AssociateNodeToHost(&newNode, &defaultHosts[i]); err != nil {
  238. return err
  239. }
  240. }
  241. return nil
  242. }
  243. // GetHostNetworks - fetches all the networks
  244. func GetHostNetworks(hostID string) []string {
  245. currHost, err := GetHost(hostID)
  246. if err != nil {
  247. return nil
  248. }
  249. nets := []string{}
  250. for i := range currHost.Nodes {
  251. n, err := GetNodeByID(currHost.Nodes[i])
  252. if err != nil {
  253. return nil
  254. }
  255. nets = append(nets, n.Network)
  256. }
  257. return nets
  258. }
  259. // GetRelatedHosts - fetches related hosts of a given host
  260. func GetRelatedHosts(hostID string) []models.Host {
  261. relatedHosts := []models.Host{}
  262. networks := GetHostNetworks(hostID)
  263. networkMap := make(map[string]struct{})
  264. for _, network := range networks {
  265. networkMap[network] = struct{}{}
  266. }
  267. hosts, err := GetAllHosts()
  268. if err == nil {
  269. for _, host := range hosts {
  270. if host.ID.String() == hostID {
  271. continue
  272. }
  273. networks := GetHostNetworks(host.ID.String())
  274. for _, network := range networks {
  275. if _, ok := networkMap[network]; ok {
  276. relatedHosts = append(relatedHosts, host)
  277. break
  278. }
  279. }
  280. }
  281. }
  282. return relatedHosts
  283. }