hosts.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. // UpdateHostNetworks - updates a given host's networks
  132. func UpdateHostNetworks(h *models.Host, server string, nets []string) error {
  133. if len(h.Nodes) > 0 {
  134. for i := range h.Nodes {
  135. n, err := GetNodeByID(h.Nodes[i])
  136. if err != nil {
  137. return err
  138. }
  139. // loop through networks and remove need for updating existing networks
  140. found := false
  141. for j := range nets {
  142. if len(nets[j]) > 0 && nets[j] == n.Network {
  143. nets[j] = "" // mark as ignore
  144. found = true
  145. }
  146. }
  147. if !found { // remove the node/host from that network
  148. if err = DissasociateNodeFromHost(&n, h); err != nil {
  149. return err
  150. }
  151. }
  152. }
  153. } else {
  154. h.Nodes = []string{}
  155. }
  156. for i := range nets {
  157. // create a node for each non zero network remaining
  158. if len(nets[i]) > 0 {
  159. newNode := models.Node{}
  160. newNode.Server = server
  161. newNode.Network = nets[i]
  162. if err := AssociateNodeToHost(&newNode, h); err != nil {
  163. return err
  164. }
  165. logger.Log(1, "added new node", newNode.ID.String(), "to host", h.Name)
  166. }
  167. }
  168. return nil
  169. }
  170. // AssociateNodeToHost - associates and creates a node with a given host
  171. // should be the only way nodes get created as of 0.18
  172. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  173. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  174. return ErrInvalidHostID
  175. }
  176. n.HostID = h.ID
  177. err := createNode(n)
  178. if err != nil {
  179. return err
  180. }
  181. h.Nodes = append(h.Nodes, n.ID.String())
  182. return UpsertHost(h)
  183. }
  184. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  185. // should be the only way nodes are deleted as of 0.18
  186. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  187. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  188. return ErrInvalidHostID
  189. }
  190. if n.HostID != h.ID { // check if node actually belongs to host
  191. return fmt.Errorf("node is not associated with host")
  192. }
  193. if len(h.Nodes) == 0 {
  194. return fmt.Errorf("no nodes present in given host")
  195. }
  196. index := -1
  197. for i := range h.Nodes {
  198. if h.Nodes[i] == n.ID.String() {
  199. index = i
  200. break
  201. }
  202. }
  203. if index < 0 {
  204. if len(h.Nodes) == 0 {
  205. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  206. }
  207. } else {
  208. h.Nodes = RemoveStringSlice(h.Nodes, index)
  209. }
  210. if err := deleteNodeByID(n); err != nil {
  211. return err
  212. }
  213. return UpsertHost(h)
  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. }