hosts.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. package logic
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "github.com/google/uuid"
  8. "github.com/gravitl/netmaker/database"
  9. "github.com/gravitl/netmaker/logger"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/servercfg"
  12. "golang.org/x/crypto/bcrypt"
  13. )
  14. var (
  15. // ErrHostExists error indicating that host exists when trying to create new host
  16. ErrHostExists error = errors.New("host already exists")
  17. // ErrInvalidHostID
  18. ErrInvalidHostID error = errors.New("invalid host id")
  19. )
  20. const (
  21. maxPort = 1<<16 - 1
  22. minPort = 1025
  23. )
  24. // GetAllHosts - returns all hosts in flat list or error
  25. func GetAllHosts() ([]models.Host, error) {
  26. currHostMap, err := GetHostsMap()
  27. if err != nil {
  28. return nil, err
  29. }
  30. var currentHosts = []models.Host{}
  31. for k := range currHostMap {
  32. var h = *currHostMap[k]
  33. currentHosts = append(currentHosts, h)
  34. }
  35. return currentHosts, nil
  36. }
  37. // GetAllHostsAPI - get's all the hosts in an API usable format
  38. func GetAllHostsAPI(hosts []models.Host) []models.ApiHost {
  39. apiHosts := []models.ApiHost{}
  40. for i := range hosts {
  41. newApiHost := hosts[i].ConvertNMHostToAPI()
  42. apiHosts = append(apiHosts, *newApiHost)
  43. }
  44. return apiHosts[:]
  45. }
  46. // GetHostsMap - gets all the current hosts on machine in a map
  47. func GetHostsMap() (map[string]*models.Host, error) {
  48. records, err := database.FetchRecords(database.HOSTS_TABLE_NAME)
  49. if err != nil && !database.IsEmptyRecord(err) {
  50. return nil, err
  51. }
  52. currHostMap := make(map[string]*models.Host)
  53. for k := range records {
  54. var h models.Host
  55. err = json.Unmarshal([]byte(records[k]), &h)
  56. if err != nil {
  57. return nil, err
  58. }
  59. currHostMap[h.ID.String()] = &h
  60. }
  61. return currHostMap, nil
  62. }
  63. // GetHost - gets a host from db given id
  64. func GetHost(hostid string) (*models.Host, error) {
  65. record, err := database.FetchRecord(database.HOSTS_TABLE_NAME, hostid)
  66. if err != nil {
  67. return nil, err
  68. }
  69. var h models.Host
  70. if err = json.Unmarshal([]byte(record), &h); err != nil {
  71. return nil, err
  72. }
  73. return &h, nil
  74. }
  75. // CreateHost - creates a host if not exist
  76. func CreateHost(h *models.Host) error {
  77. _, err := GetHost(h.ID.String())
  78. if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) {
  79. return ErrHostExists
  80. }
  81. // encrypt that password so we never see it
  82. hash, err := bcrypt.GenerateFromPassword([]byte(h.HostPass), 5)
  83. if err != nil {
  84. return err
  85. }
  86. h.HostPass = string(hash)
  87. // if another server has already updated proxyenabled, leave it alone
  88. if !h.ProxyEnabledSet {
  89. log.Println("checking default proxy", servercfg.GetServerConfig().DefaultProxyMode)
  90. if servercfg.GetServerConfig().DefaultProxyMode.Set {
  91. h.ProxyEnabledSet = true
  92. h.ProxyEnabled = servercfg.GetServerConfig().DefaultProxyMode.Value
  93. log.Println("set proxy enabled to ", h.ProxyEnabled)
  94. }
  95. }
  96. checkForZombieHosts(h)
  97. return UpsertHost(h)
  98. }
  99. // UpdateHost - updates host data by field
  100. func UpdateHost(newHost, currentHost *models.Host) {
  101. // unchangeable fields via API here
  102. newHost.DaemonInstalled = currentHost.DaemonInstalled
  103. newHost.OS = currentHost.OS
  104. newHost.IPForwarding = currentHost.IPForwarding
  105. newHost.HostPass = currentHost.HostPass
  106. newHost.MacAddress = currentHost.MacAddress
  107. newHost.Debug = currentHost.Debug
  108. newHost.Nodes = currentHost.Nodes
  109. newHost.PublicKey = currentHost.PublicKey
  110. newHost.InternetGateway = currentHost.InternetGateway
  111. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  112. // changeable fields
  113. if len(newHost.Version) == 0 {
  114. newHost.Version = currentHost.Version
  115. }
  116. if len(newHost.Name) == 0 {
  117. newHost.Name = currentHost.Name
  118. }
  119. if newHost.MTU == 0 {
  120. newHost.MTU = currentHost.MTU
  121. }
  122. if newHost.ListenPort == 0 {
  123. newHost.ListenPort = currentHost.ListenPort
  124. }
  125. if newHost.ProxyListenPort == 0 {
  126. newHost.ProxyListenPort = currentHost.ProxyListenPort
  127. }
  128. newHost.PublicListenPort = currentHost.PublicListenPort
  129. }
  130. // UpdateHostFromClient - used for updating host on server with update recieved from client
  131. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  132. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  133. currHost.ListenPort = newHost.ListenPort
  134. sendPeerUpdate = true
  135. }
  136. if newHost.ProxyListenPort != 0 && currHost.ProxyListenPort != newHost.ProxyListenPort {
  137. currHost.ProxyListenPort = newHost.ProxyListenPort
  138. sendPeerUpdate = true
  139. }
  140. if newHost.PublicListenPort != 0 && currHost.PublicListenPort != newHost.PublicListenPort {
  141. currHost.PublicListenPort = newHost.PublicListenPort
  142. sendPeerUpdate = true
  143. }
  144. if currHost.ProxyEnabled != newHost.ProxyEnabled {
  145. currHost.ProxyEnabled = newHost.ProxyEnabled
  146. sendPeerUpdate = true
  147. }
  148. if currHost.EndpointIP.String() != newHost.EndpointIP.String() {
  149. currHost.EndpointIP = newHost.EndpointIP
  150. sendPeerUpdate = true
  151. }
  152. currHost.DaemonInstalled = newHost.DaemonInstalled
  153. currHost.Debug = newHost.Debug
  154. currHost.Verbosity = newHost.Verbosity
  155. currHost.Version = newHost.Version
  156. if newHost.Name != "" {
  157. currHost.Name = newHost.Name
  158. }
  159. return
  160. }
  161. // UpsertHost - upserts into DB a given host model, does not check for existence*
  162. func UpsertHost(h *models.Host) error {
  163. data, err := json.Marshal(h)
  164. if err != nil {
  165. return err
  166. }
  167. return database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  168. }
  169. // RemoveHost - removes a given host from server
  170. func RemoveHost(h *models.Host) error {
  171. if len(h.Nodes) > 0 {
  172. return fmt.Errorf("host still has associated nodes")
  173. }
  174. return database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  175. }
  176. // RemoveHostByID - removes a given host by id from server
  177. func RemoveHostByID(hostID string) error {
  178. return database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  179. }
  180. // UpdateHostNetwork - adds/deletes host from a network
  181. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  182. for _, nodeID := range h.Nodes {
  183. node, err := GetNodeByID(nodeID)
  184. if err != nil || node.PendingDelete {
  185. continue
  186. }
  187. if node.Network == network {
  188. if !add {
  189. return &node, nil
  190. } else {
  191. return nil, errors.New("host already part of network " + network)
  192. }
  193. }
  194. }
  195. if !add {
  196. return nil, errors.New("host not part of the network " + network)
  197. } else {
  198. newNode := models.Node{}
  199. newNode.Server = servercfg.GetServer()
  200. newNode.Network = network
  201. newNode.HostID = h.ID
  202. if err := AssociateNodeToHost(&newNode, h); err != nil {
  203. return nil, err
  204. }
  205. return &newNode, nil
  206. }
  207. }
  208. // AssociateNodeToHost - associates and creates a node with a given host
  209. // should be the only way nodes get created as of 0.18
  210. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  211. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  212. return ErrInvalidHostID
  213. }
  214. n.HostID = h.ID
  215. err := createNode(n)
  216. if err != nil {
  217. return err
  218. }
  219. currentHost, err := GetHost(h.ID.String())
  220. if err != nil {
  221. return err
  222. }
  223. h.HostPass = currentHost.HostPass
  224. h.Nodes = append(currentHost.Nodes, n.ID.String())
  225. return UpsertHost(h)
  226. }
  227. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  228. // should be the only way nodes are deleted as of 0.18
  229. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  230. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  231. return ErrInvalidHostID
  232. }
  233. if n.HostID != h.ID { // check if node actually belongs to host
  234. return fmt.Errorf("node is not associated with host")
  235. }
  236. if len(h.Nodes) == 0 {
  237. return fmt.Errorf("no nodes present in given host")
  238. }
  239. index := -1
  240. for i := range h.Nodes {
  241. if h.Nodes[i] == n.ID.String() {
  242. index = i
  243. break
  244. }
  245. }
  246. if index < 0 {
  247. if len(h.Nodes) == 0 {
  248. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  249. }
  250. } else {
  251. h.Nodes = RemoveStringSlice(h.Nodes, index)
  252. }
  253. if err := deleteNodeByID(n); err != nil {
  254. return err
  255. }
  256. return UpsertHost(h)
  257. }
  258. // DisassociateAllNodesFromHost - deletes all nodes of the host
  259. func DisassociateAllNodesFromHost(hostID string) error {
  260. host, err := GetHost(hostID)
  261. if err != nil {
  262. return err
  263. }
  264. for _, nodeID := range host.Nodes {
  265. node, err := GetNodeByID(nodeID)
  266. if err != nil {
  267. logger.Log(0, "failed to get host node", err.Error())
  268. continue
  269. }
  270. if err := DeleteNode(&node, true); err != nil {
  271. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  272. continue
  273. }
  274. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  275. }
  276. host.Nodes = []string{}
  277. return UpsertHost(host)
  278. }
  279. // GetDefaultHosts - retrieve all hosts marked as default from DB
  280. func GetDefaultHosts() []models.Host {
  281. defaultHostList := []models.Host{}
  282. hosts, err := GetAllHosts()
  283. if err != nil {
  284. return defaultHostList
  285. }
  286. for i := range hosts {
  287. if hosts[i].IsDefault {
  288. defaultHostList = append(defaultHostList, hosts[i])
  289. }
  290. }
  291. return defaultHostList[:]
  292. }
  293. // GetHostNetworks - fetches all the networks
  294. func GetHostNetworks(hostID string) []string {
  295. currHost, err := GetHost(hostID)
  296. if err != nil {
  297. return nil
  298. }
  299. nets := []string{}
  300. for i := range currHost.Nodes {
  301. n, err := GetNodeByID(currHost.Nodes[i])
  302. if err != nil {
  303. return nil
  304. }
  305. nets = append(nets, n.Network)
  306. }
  307. return nets
  308. }
  309. // GetRelatedHosts - fetches related hosts of a given host
  310. func GetRelatedHosts(hostID string) []models.Host {
  311. relatedHosts := []models.Host{}
  312. networks := GetHostNetworks(hostID)
  313. networkMap := make(map[string]struct{})
  314. for _, network := range networks {
  315. networkMap[network] = struct{}{}
  316. }
  317. hosts, err := GetAllHosts()
  318. if err == nil {
  319. for _, host := range hosts {
  320. if host.ID.String() == hostID {
  321. continue
  322. }
  323. networks := GetHostNetworks(host.ID.String())
  324. for _, network := range networks {
  325. if _, ok := networkMap[network]; ok {
  326. relatedHosts = append(relatedHosts, host)
  327. break
  328. }
  329. }
  330. }
  331. }
  332. return relatedHosts
  333. }
  334. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  335. // with the same endpoint have different listen ports
  336. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  337. func CheckHostPorts(h *models.Host) {
  338. portsInUse := make(map[int]bool, 0)
  339. hosts, err := GetAllHosts()
  340. if err != nil {
  341. return
  342. }
  343. for _, host := range hosts {
  344. if host.ID.String() == h.ID.String() {
  345. //skip self
  346. continue
  347. }
  348. if !host.EndpointIP.Equal(h.EndpointIP) {
  349. continue
  350. }
  351. portsInUse[host.ListenPort] = true
  352. portsInUse[host.ProxyListenPort] = true
  353. }
  354. // iterate until port is not found or max iteration is reached
  355. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  356. h.ListenPort++
  357. if h.ListenPort > maxPort {
  358. h.ListenPort = minPort
  359. }
  360. }
  361. // allocate h.ListenPort so it is unavailable to h.ProxyListenPort
  362. portsInUse[h.ListenPort] = true
  363. for i := 0; portsInUse[h.ProxyListenPort] && i < maxPort-minPort+1; i++ {
  364. h.ProxyListenPort++
  365. if h.ProxyListenPort > maxPort {
  366. h.ProxyListenPort = minPort
  367. }
  368. }
  369. }
  370. // HostExists - checks if given host already exists
  371. func HostExists(h *models.Host) bool {
  372. _, err := GetHost(h.ID.String())
  373. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  374. }
  375. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  376. func GetHostByNodeID(id string) *models.Host {
  377. hosts, err := GetAllHosts()
  378. if err != nil {
  379. return nil
  380. }
  381. for i := range hosts {
  382. h := hosts[i]
  383. if StringSliceContains(h.Nodes, id) {
  384. return &h
  385. }
  386. }
  387. return nil
  388. }