hosts.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. for i := range h.Nodes {
  128. id := h.Nodes[i]
  129. n, err := GetNodeByID(id)
  130. if err == nil {
  131. if err = DissasociateNodeFromHost(&n, h); err != nil {
  132. return err // must remove associated nodes before removing a host
  133. }
  134. }
  135. }
  136. }
  137. return database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  138. }
  139. // UpdateHostNetworks - updates a given host's networks
  140. func UpdateHostNetworks(h *models.Host, server string, nets []string) error {
  141. if len(h.Nodes) > 0 {
  142. for i := range h.Nodes {
  143. n, err := GetNodeByID(h.Nodes[i])
  144. if err != nil {
  145. return err
  146. }
  147. // loop through networks and remove need for updating existing networks
  148. found := false
  149. for j := range nets {
  150. if len(nets[j]) > 0 && nets[j] == n.Network {
  151. nets[j] = "" // mark as ignore
  152. found = true
  153. }
  154. }
  155. if !found { // remove the node/host from that network
  156. if err = DissasociateNodeFromHost(&n, h); err != nil {
  157. return err
  158. }
  159. }
  160. }
  161. } else {
  162. h.Nodes = []string{}
  163. }
  164. for i := range nets {
  165. // create a node for each non zero network remaining
  166. if len(nets[i]) > 0 {
  167. newNode := models.Node{}
  168. newNode.Server = server
  169. newNode.Network = nets[i]
  170. if err := AssociateNodeToHost(&newNode, h); err != nil {
  171. return err
  172. }
  173. logger.Log(1, "added new node", newNode.ID.String(), "to host", h.Name)
  174. }
  175. }
  176. return nil
  177. }
  178. // AssociateNodeToHost - associates and creates a node with a given host
  179. // should be the only way nodes get created as of 0.18
  180. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  181. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  182. return ErrInvalidHostID
  183. }
  184. n.HostID = h.ID
  185. err := createNode(n)
  186. if err != nil {
  187. return err
  188. }
  189. h.Nodes = append(h.Nodes, n.ID.String())
  190. return UpsertHost(h)
  191. }
  192. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  193. // should be the only way nodes are deleted as of 0.18
  194. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  195. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  196. return ErrInvalidHostID
  197. }
  198. if n.HostID != h.ID { // check if node actually belongs to host
  199. return fmt.Errorf("node is not associated with host")
  200. }
  201. if len(h.Nodes) == 0 {
  202. return fmt.Errorf("no nodes present in given host")
  203. }
  204. index := -1
  205. for i := range h.Nodes {
  206. if h.Nodes[i] == n.ID.String() {
  207. index = i
  208. break
  209. }
  210. }
  211. if index < 0 {
  212. if len(h.Nodes) == 0 {
  213. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  214. }
  215. }
  216. if err := deleteNodeByID(n); err != nil {
  217. return err
  218. }
  219. h.Nodes = RemoveStringSlice(h.Nodes, index)
  220. return UpsertHost(h)
  221. }
  222. // GetDefaultHosts - retrieve all hosts marked as default from DB
  223. func GetDefaultHosts() []models.Host {
  224. defaultHostList := []models.Host{}
  225. hosts, err := GetAllHosts()
  226. if err != nil {
  227. return defaultHostList
  228. }
  229. for i := range hosts {
  230. if hosts[i].IsDefault {
  231. defaultHostList = append(defaultHostList, hosts[i])
  232. }
  233. }
  234. return defaultHostList[:]
  235. }
  236. // AddDefaultHostsToNetwork - adds a node to network for every default host on Netmaker server
  237. func AddDefaultHostsToNetwork(network, server string) error {
  238. // add default hosts to network
  239. defaultHosts := GetDefaultHosts()
  240. for i := range defaultHosts {
  241. newNode := models.Node{}
  242. newNode.Network = network
  243. newNode.Server = server
  244. if err := AssociateNodeToHost(&newNode, &defaultHosts[i]); err != nil {
  245. return err
  246. }
  247. }
  248. return nil
  249. }