hosts.go 11 KB

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