hosts.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. // UpdateHostFromClient - used for host update recieved from netclient
  117. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  118. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  119. currHost.ListenPort = newHost.ListenPort
  120. sendPeerUpdate = true
  121. }
  122. if newHost.ProxyListenPort != 0 && currHost.ProxyListenPort != newHost.ProxyListenPort {
  123. currHost.ProxyListenPort = newHost.ProxyListenPort
  124. sendPeerUpdate = true
  125. }
  126. if currHost.ProxyEnabled != newHost.ProxyEnabled {
  127. currHost.ProxyEnabled = newHost.ProxyEnabled
  128. sendPeerUpdate = true
  129. }
  130. if currHost.EndpointIP.String() != newHost.EndpointIP.String() {
  131. currHost.EndpointIP = newHost.EndpointIP
  132. sendPeerUpdate = true
  133. }
  134. currHost.DaemonInstalled = newHost.DaemonInstalled
  135. currHost.Debug = newHost.Debug
  136. currHost.Verbosity = newHost.Verbosity
  137. currHost.Version = newHost.Version
  138. return
  139. }
  140. // UpsertHost - upserts into DB a given host model, does not check for existence*
  141. func UpsertHost(h *models.Host) error {
  142. data, err := json.Marshal(h)
  143. if err != nil {
  144. return err
  145. }
  146. return database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  147. }
  148. // RemoveHost - removes a given host from server
  149. func RemoveHost(h *models.Host) error {
  150. if len(h.Nodes) > 0 {
  151. return fmt.Errorf("host still has associated nodes")
  152. }
  153. return database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  154. }
  155. // UpdateHostNetworks - updates a given host's networks
  156. func UpdateHostNetworks(h *models.Host, server string, nets []string) ([]string, []string, error) {
  157. newNets := []string{}
  158. delNets := []string{}
  159. if len(h.Nodes) > 0 {
  160. for i := range h.Nodes {
  161. n, err := GetNodeByID(h.Nodes[i])
  162. if err != nil {
  163. return newNets, delNets, err
  164. }
  165. // loop through networks and remove need for updating existing networks
  166. found := false
  167. for j := range nets {
  168. if len(nets[j]) > 0 && nets[j] == n.Network {
  169. nets[j] = "" // mark as ignore
  170. found = true
  171. }
  172. }
  173. if !found { // remove the node/host from that network
  174. if err = DissasociateNodeFromHost(&n, h); err != nil {
  175. return newNets, delNets, err
  176. }
  177. delNets = append(delNets, n.Network)
  178. }
  179. }
  180. } else {
  181. h.Nodes = []string{}
  182. }
  183. for i := range nets {
  184. // create a node for each non zero network remaining
  185. if len(nets[i]) > 0 {
  186. newNode := models.Node{}
  187. newNode.Server = server
  188. newNode.Network = nets[i]
  189. if err := AssociateNodeToHost(&newNode, h); err != nil {
  190. return newNets, delNets, err
  191. }
  192. newNets = append(newNets, newNode.Network)
  193. logger.Log(1, "added new node", newNode.ID.String(), "to host", h.Name)
  194. }
  195. }
  196. return newNets, delNets, nil
  197. }
  198. // AssociateNodeToHost - associates and creates a node with a given host
  199. // should be the only way nodes get created as of 0.18
  200. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  201. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  202. return ErrInvalidHostID
  203. }
  204. n.HostID = h.ID
  205. err := createNode(n)
  206. if err != nil {
  207. return err
  208. }
  209. h.Nodes = append(h.Nodes, n.ID.String())
  210. return UpsertHost(h)
  211. }
  212. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  213. // should be the only way nodes are deleted as of 0.18
  214. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  215. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  216. return ErrInvalidHostID
  217. }
  218. if n.HostID != h.ID { // check if node actually belongs to host
  219. return fmt.Errorf("node is not associated with host")
  220. }
  221. if len(h.Nodes) == 0 {
  222. return fmt.Errorf("no nodes present in given host")
  223. }
  224. index := -1
  225. for i := range h.Nodes {
  226. if h.Nodes[i] == n.ID.String() {
  227. index = i
  228. break
  229. }
  230. }
  231. if index < 0 {
  232. if len(h.Nodes) == 0 {
  233. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  234. }
  235. } else {
  236. h.Nodes = RemoveStringSlice(h.Nodes, index)
  237. }
  238. if err := deleteNodeByID(n); err != nil {
  239. return err
  240. }
  241. return UpsertHost(h)
  242. }
  243. // GetDefaultHosts - retrieve all hosts marked as default from DB
  244. func GetDefaultHosts() []models.Host {
  245. defaultHostList := []models.Host{}
  246. hosts, err := GetAllHosts()
  247. if err != nil {
  248. return defaultHostList
  249. }
  250. for i := range hosts {
  251. if hosts[i].IsDefault {
  252. defaultHostList = append(defaultHostList, hosts[i])
  253. }
  254. }
  255. return defaultHostList[:]
  256. }
  257. // AddDefaultHostsToNetwork - adds a node to network for every default host on Netmaker server
  258. func AddDefaultHostsToNetwork(network, server string) error {
  259. // add default hosts to network
  260. defaultHosts := GetDefaultHosts()
  261. for i := range defaultHosts {
  262. newNode := models.Node{}
  263. newNode.Network = network
  264. newNode.Server = server
  265. if err := AssociateNodeToHost(&newNode, &defaultHosts[i]); err != nil {
  266. return err
  267. }
  268. }
  269. return nil
  270. }
  271. // GetHostNetworks - fetches all the networks
  272. func GetHostNetworks(hostID string) []string {
  273. currHost, err := GetHost(hostID)
  274. if err != nil {
  275. return nil
  276. }
  277. nets := []string{}
  278. for i := range currHost.Nodes {
  279. n, err := GetNodeByID(currHost.Nodes[i])
  280. if err != nil {
  281. return nil
  282. }
  283. nets = append(nets, n.Network)
  284. }
  285. return nets
  286. }
  287. // GetRelatedHosts - fetches related hosts of a given host
  288. func GetRelatedHosts(hostID string) []models.Host {
  289. relatedHosts := []models.Host{}
  290. networks := GetHostNetworks(hostID)
  291. networkMap := make(map[string]struct{})
  292. for _, network := range networks {
  293. networkMap[network] = struct{}{}
  294. }
  295. hosts, err := GetAllHosts()
  296. if err == nil {
  297. for _, host := range hosts {
  298. if host.ID.String() == hostID {
  299. continue
  300. }
  301. networks := GetHostNetworks(host.ID.String())
  302. for _, network := range networks {
  303. if _, ok := networkMap[network]; ok {
  304. relatedHosts = append(relatedHosts, host)
  305. break
  306. }
  307. }
  308. }
  309. }
  310. return relatedHosts
  311. }
  312. func GetNodeByNetwork(hostID, network string) (models.Node, error) {
  313. currHost, err := GetHost(hostID)
  314. if err != nil {
  315. return models.Node{}, err
  316. }
  317. for i := range currHost.Nodes {
  318. n, err := GetNodeByID(currHost.Nodes[i])
  319. if err != nil {
  320. continue
  321. }
  322. if n.Network == network {
  323. return n, nil
  324. }
  325. }
  326. return models.Node{}, errors.New("node not found")
  327. }