hosts.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. h.AutoUpdate = servercfg.AutoUpdateEnabled()
  88. // if another server has already updated proxyenabled, leave it alone
  89. if !h.ProxyEnabledSet {
  90. log.Println("checking default proxy", servercfg.GetServerConfig().DefaultProxyMode)
  91. if servercfg.GetServerConfig().DefaultProxyMode.Set {
  92. h.ProxyEnabledSet = true
  93. h.ProxyEnabled = servercfg.GetServerConfig().DefaultProxyMode.Value
  94. log.Println("set proxy enabled to ", h.ProxyEnabled)
  95. }
  96. }
  97. checkForZombieHosts(h)
  98. return UpsertHost(h)
  99. }
  100. // UpdateHost - updates host data by field
  101. func UpdateHost(newHost, currentHost *models.Host) {
  102. // unchangeable fields via API here
  103. newHost.DaemonInstalled = currentHost.DaemonInstalled
  104. newHost.OS = currentHost.OS
  105. newHost.IPForwarding = currentHost.IPForwarding
  106. newHost.HostPass = currentHost.HostPass
  107. newHost.MacAddress = currentHost.MacAddress
  108. newHost.Debug = currentHost.Debug
  109. newHost.Nodes = currentHost.Nodes
  110. newHost.PublicKey = currentHost.PublicKey
  111. newHost.InternetGateway = currentHost.InternetGateway
  112. newHost.TrafficKeyPublic = currentHost.TrafficKeyPublic
  113. // changeable fields
  114. if len(newHost.Version) == 0 {
  115. newHost.Version = currentHost.Version
  116. }
  117. if len(newHost.Name) == 0 {
  118. newHost.Name = currentHost.Name
  119. }
  120. if newHost.MTU == 0 {
  121. newHost.MTU = currentHost.MTU
  122. }
  123. if newHost.ListenPort == 0 {
  124. newHost.ListenPort = currentHost.ListenPort
  125. }
  126. if newHost.ProxyListenPort == 0 {
  127. newHost.ProxyListenPort = currentHost.ProxyListenPort
  128. }
  129. newHost.PublicListenPort = currentHost.PublicListenPort
  130. }
  131. // UpdateHostFromClient - used for updating host on server with update recieved from client
  132. func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool) {
  133. if newHost.ListenPort != 0 && currHost.ListenPort != newHost.ListenPort {
  134. currHost.ListenPort = newHost.ListenPort
  135. sendPeerUpdate = true
  136. }
  137. if newHost.ProxyListenPort != 0 && currHost.ProxyListenPort != newHost.ProxyListenPort {
  138. currHost.ProxyListenPort = newHost.ProxyListenPort
  139. sendPeerUpdate = true
  140. }
  141. if newHost.PublicListenPort != 0 && currHost.PublicListenPort != newHost.PublicListenPort {
  142. currHost.PublicListenPort = newHost.PublicListenPort
  143. sendPeerUpdate = true
  144. }
  145. if currHost.ProxyEnabled != newHost.ProxyEnabled {
  146. currHost.ProxyEnabled = newHost.ProxyEnabled
  147. sendPeerUpdate = true
  148. }
  149. if currHost.EndpointIP.String() != newHost.EndpointIP.String() {
  150. currHost.EndpointIP = newHost.EndpointIP
  151. sendPeerUpdate = true
  152. }
  153. currHost.DaemonInstalled = newHost.DaemonInstalled
  154. currHost.Debug = newHost.Debug
  155. currHost.Verbosity = newHost.Verbosity
  156. currHost.Version = newHost.Version
  157. if newHost.Name != "" {
  158. currHost.Name = newHost.Name
  159. }
  160. return
  161. }
  162. // UpsertHost - upserts into DB a given host model, does not check for existence*
  163. func UpsertHost(h *models.Host) error {
  164. data, err := json.Marshal(h)
  165. if err != nil {
  166. return err
  167. }
  168. return database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  169. }
  170. // RemoveHost - removes a given host from server
  171. func RemoveHost(h *models.Host) error {
  172. if len(h.Nodes) > 0 {
  173. return fmt.Errorf("host still has associated nodes")
  174. }
  175. return database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  176. }
  177. // RemoveHostByID - removes a given host by id from server
  178. func RemoveHostByID(hostID string) error {
  179. return database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  180. }
  181. // UpdateHostNetwork - adds/deletes host from a network
  182. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  183. for _, nodeID := range h.Nodes {
  184. node, err := GetNodeByID(nodeID)
  185. if err != nil || node.PendingDelete {
  186. continue
  187. }
  188. if node.Network == network {
  189. if !add {
  190. return &node, nil
  191. } else {
  192. return nil, errors.New("host already part of network " + network)
  193. }
  194. }
  195. }
  196. if !add {
  197. return nil, errors.New("host not part of the network " + network)
  198. } else {
  199. newNode := models.Node{}
  200. newNode.Server = servercfg.GetServer()
  201. newNode.Network = network
  202. newNode.HostID = h.ID
  203. if err := AssociateNodeToHost(&newNode, h); err != nil {
  204. return nil, err
  205. }
  206. return &newNode, nil
  207. }
  208. }
  209. // AssociateNodeToHost - associates and creates a node with a given host
  210. // should be the only way nodes get created as of 0.18
  211. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  212. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  213. return ErrInvalidHostID
  214. }
  215. n.HostID = h.ID
  216. err := createNode(n)
  217. if err != nil {
  218. return err
  219. }
  220. currentHost, err := GetHost(h.ID.String())
  221. if err != nil {
  222. return err
  223. }
  224. h.HostPass = currentHost.HostPass
  225. h.Nodes = append(currentHost.Nodes, n.ID.String())
  226. return UpsertHost(h)
  227. }
  228. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  229. // should be the only way nodes are deleted as of 0.18
  230. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  231. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  232. return ErrInvalidHostID
  233. }
  234. if n.HostID != h.ID { // check if node actually belongs to host
  235. return fmt.Errorf("node is not associated with host")
  236. }
  237. if len(h.Nodes) == 0 {
  238. return fmt.Errorf("no nodes present in given host")
  239. }
  240. index := -1
  241. for i := range h.Nodes {
  242. if h.Nodes[i] == n.ID.String() {
  243. index = i
  244. break
  245. }
  246. }
  247. if index < 0 {
  248. if len(h.Nodes) == 0 {
  249. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  250. }
  251. } else {
  252. h.Nodes = RemoveStringSlice(h.Nodes, index)
  253. }
  254. if err := deleteNodeByID(n); err != nil {
  255. return err
  256. }
  257. return UpsertHost(h)
  258. }
  259. // DisassociateAllNodesFromHost - deletes all nodes of the host
  260. func DisassociateAllNodesFromHost(hostID string) error {
  261. host, err := GetHost(hostID)
  262. if err != nil {
  263. return err
  264. }
  265. for _, nodeID := range host.Nodes {
  266. node, err := GetNodeByID(nodeID)
  267. if err != nil {
  268. logger.Log(0, "failed to get host node", err.Error())
  269. continue
  270. }
  271. if err := DeleteNode(&node, true); err != nil {
  272. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  273. continue
  274. }
  275. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  276. }
  277. host.Nodes = []string{}
  278. return UpsertHost(host)
  279. }
  280. // GetDefaultHosts - retrieve all hosts marked as default from DB
  281. func GetDefaultHosts() []models.Host {
  282. defaultHostList := []models.Host{}
  283. hosts, err := GetAllHosts()
  284. if err != nil {
  285. return defaultHostList
  286. }
  287. for i := range hosts {
  288. if hosts[i].IsDefault {
  289. defaultHostList = append(defaultHostList, hosts[i])
  290. }
  291. }
  292. return defaultHostList[:]
  293. }
  294. // GetHostNetworks - fetches all the networks
  295. func GetHostNetworks(hostID string) []string {
  296. currHost, err := GetHost(hostID)
  297. if err != nil {
  298. return nil
  299. }
  300. nets := []string{}
  301. for i := range currHost.Nodes {
  302. n, err := GetNodeByID(currHost.Nodes[i])
  303. if err != nil {
  304. return nil
  305. }
  306. nets = append(nets, n.Network)
  307. }
  308. return nets
  309. }
  310. // GetRelatedHosts - fetches related hosts of a given host
  311. func GetRelatedHosts(hostID string) []models.Host {
  312. relatedHosts := []models.Host{}
  313. networks := GetHostNetworks(hostID)
  314. networkMap := make(map[string]struct{})
  315. for _, network := range networks {
  316. networkMap[network] = struct{}{}
  317. }
  318. hosts, err := GetAllHosts()
  319. if err == nil {
  320. for _, host := range hosts {
  321. if host.ID.String() == hostID {
  322. continue
  323. }
  324. networks := GetHostNetworks(host.ID.String())
  325. for _, network := range networks {
  326. if _, ok := networkMap[network]; ok {
  327. relatedHosts = append(relatedHosts, host)
  328. break
  329. }
  330. }
  331. }
  332. }
  333. return relatedHosts
  334. }
  335. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  336. // with the same endpoint have different listen ports
  337. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  338. func CheckHostPorts(h *models.Host) {
  339. portsInUse := make(map[int]bool, 0)
  340. hosts, err := GetAllHosts()
  341. if err != nil {
  342. return
  343. }
  344. for _, host := range hosts {
  345. if host.ID.String() == h.ID.String() {
  346. //skip self
  347. continue
  348. }
  349. if !host.EndpointIP.Equal(h.EndpointIP) {
  350. continue
  351. }
  352. portsInUse[host.ListenPort] = true
  353. portsInUse[host.ProxyListenPort] = true
  354. }
  355. // iterate until port is not found or max iteration is reached
  356. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  357. h.ListenPort++
  358. if h.ListenPort > maxPort {
  359. h.ListenPort = minPort
  360. }
  361. }
  362. // allocate h.ListenPort so it is unavailable to h.ProxyListenPort
  363. portsInUse[h.ListenPort] = true
  364. for i := 0; portsInUse[h.ProxyListenPort] && i < maxPort-minPort+1; i++ {
  365. h.ProxyListenPort++
  366. if h.ProxyListenPort > maxPort {
  367. h.ProxyListenPort = minPort
  368. }
  369. }
  370. }
  371. // HostExists - checks if given host already exists
  372. func HostExists(h *models.Host) bool {
  373. _, err := GetHost(h.ID.String())
  374. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  375. }
  376. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  377. func GetHostByNodeID(id string) *models.Host {
  378. hosts, err := GetAllHosts()
  379. if err != nil {
  380. return nil
  381. }
  382. for i := range hosts {
  383. h := hosts[i]
  384. if StringSliceContains(h.Nodes, id) {
  385. return &h
  386. }
  387. }
  388. return nil
  389. }