hosts.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. if len(newHost.NatType) > 0 && newHost.NatType != currHost.NatType {
  161. currHost.NatType = newHost.NatType
  162. sendPeerUpdate = true
  163. }
  164. return
  165. }
  166. // UpsertHost - upserts into DB a given host model, does not check for existence*
  167. func UpsertHost(h *models.Host) error {
  168. data, err := json.Marshal(h)
  169. if err != nil {
  170. return err
  171. }
  172. return database.Insert(h.ID.String(), string(data), database.HOSTS_TABLE_NAME)
  173. }
  174. // RemoveHost - removes a given host from server
  175. func RemoveHost(h *models.Host) error {
  176. if len(h.Nodes) > 0 {
  177. return fmt.Errorf("host still has associated nodes")
  178. }
  179. return database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
  180. }
  181. // RemoveHostByID - removes a given host by id from server
  182. func RemoveHostByID(hostID string) error {
  183. return database.DeleteRecord(database.HOSTS_TABLE_NAME, hostID)
  184. }
  185. // UpdateHostNetwork - adds/deletes host from a network
  186. func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error) {
  187. for _, nodeID := range h.Nodes {
  188. node, err := GetNodeByID(nodeID)
  189. if err != nil || node.PendingDelete {
  190. continue
  191. }
  192. if node.Network == network {
  193. if !add {
  194. return &node, nil
  195. } else {
  196. return nil, errors.New("host already part of network " + network)
  197. }
  198. }
  199. }
  200. if !add {
  201. return nil, errors.New("host not part of the network " + network)
  202. } else {
  203. newNode := models.Node{}
  204. newNode.Server = servercfg.GetServer()
  205. newNode.Network = network
  206. newNode.HostID = h.ID
  207. if err := AssociateNodeToHost(&newNode, h); err != nil {
  208. return nil, err
  209. }
  210. return &newNode, nil
  211. }
  212. }
  213. // AssociateNodeToHost - associates and creates a node with a given host
  214. // should be the only way nodes get created as of 0.18
  215. func AssociateNodeToHost(n *models.Node, h *models.Host) error {
  216. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  217. return ErrInvalidHostID
  218. }
  219. n.HostID = h.ID
  220. err := createNode(n)
  221. if err != nil {
  222. return err
  223. }
  224. currentHost, err := GetHost(h.ID.String())
  225. if err != nil {
  226. return err
  227. }
  228. h.HostPass = currentHost.HostPass
  229. h.Nodes = append(currentHost.Nodes, n.ID.String())
  230. return UpsertHost(h)
  231. }
  232. // DissasociateNodeFromHost - deletes a node and removes from host nodes
  233. // should be the only way nodes are deleted as of 0.18
  234. func DissasociateNodeFromHost(n *models.Node, h *models.Host) error {
  235. if len(h.ID.String()) == 0 || h.ID == uuid.Nil {
  236. return ErrInvalidHostID
  237. }
  238. if n.HostID != h.ID { // check if node actually belongs to host
  239. return fmt.Errorf("node is not associated with host")
  240. }
  241. if len(h.Nodes) == 0 {
  242. return fmt.Errorf("no nodes present in given host")
  243. }
  244. index := -1
  245. for i := range h.Nodes {
  246. if h.Nodes[i] == n.ID.String() {
  247. index = i
  248. break
  249. }
  250. }
  251. if index < 0 {
  252. if len(h.Nodes) == 0 {
  253. return fmt.Errorf("node %s, not found in host, %s", n.ID.String(), h.ID.String())
  254. }
  255. } else {
  256. h.Nodes = RemoveStringSlice(h.Nodes, index)
  257. }
  258. if err := deleteNodeByID(n); err != nil {
  259. return err
  260. }
  261. return UpsertHost(h)
  262. }
  263. // DisassociateAllNodesFromHost - deletes all nodes of the host
  264. func DisassociateAllNodesFromHost(hostID string) error {
  265. host, err := GetHost(hostID)
  266. if err != nil {
  267. return err
  268. }
  269. for _, nodeID := range host.Nodes {
  270. node, err := GetNodeByID(nodeID)
  271. if err != nil {
  272. logger.Log(0, "failed to get host node", err.Error())
  273. continue
  274. }
  275. if err := DeleteNode(&node, true); err != nil {
  276. logger.Log(0, "failed to delete node", node.ID.String(), err.Error())
  277. continue
  278. }
  279. logger.Log(3, "deleted node", node.ID.String(), "of host", host.ID.String())
  280. }
  281. host.Nodes = []string{}
  282. return UpsertHost(host)
  283. }
  284. // GetDefaultHosts - retrieve all hosts marked as default from DB
  285. func GetDefaultHosts() []models.Host {
  286. defaultHostList := []models.Host{}
  287. hosts, err := GetAllHosts()
  288. if err != nil {
  289. return defaultHostList
  290. }
  291. for i := range hosts {
  292. if hosts[i].IsDefault {
  293. defaultHostList = append(defaultHostList, hosts[i])
  294. }
  295. }
  296. return defaultHostList[:]
  297. }
  298. // GetHostNetworks - fetches all the networks
  299. func GetHostNetworks(hostID string) []string {
  300. currHost, err := GetHost(hostID)
  301. if err != nil {
  302. return nil
  303. }
  304. nets := []string{}
  305. for i := range currHost.Nodes {
  306. n, err := GetNodeByID(currHost.Nodes[i])
  307. if err != nil {
  308. return nil
  309. }
  310. nets = append(nets, n.Network)
  311. }
  312. return nets
  313. }
  314. // GetRelatedHosts - fetches related hosts of a given host
  315. func GetRelatedHosts(hostID string) []models.Host {
  316. relatedHosts := []models.Host{}
  317. networks := GetHostNetworks(hostID)
  318. networkMap := make(map[string]struct{})
  319. for _, network := range networks {
  320. networkMap[network] = struct{}{}
  321. }
  322. hosts, err := GetAllHosts()
  323. if err == nil {
  324. for _, host := range hosts {
  325. if host.ID.String() == hostID {
  326. continue
  327. }
  328. networks := GetHostNetworks(host.ID.String())
  329. for _, network := range networks {
  330. if _, ok := networkMap[network]; ok {
  331. relatedHosts = append(relatedHosts, host)
  332. break
  333. }
  334. }
  335. }
  336. }
  337. return relatedHosts
  338. }
  339. // CheckHostPort checks host endpoints to ensures that hosts on the same server
  340. // with the same endpoint have different listen ports
  341. // in the case of 64535 hosts or more with same endpoint, ports will not be changed
  342. func CheckHostPorts(h *models.Host) {
  343. portsInUse := make(map[int]bool, 0)
  344. hosts, err := GetAllHosts()
  345. if err != nil {
  346. return
  347. }
  348. for _, host := range hosts {
  349. if host.ID.String() == h.ID.String() {
  350. //skip self
  351. continue
  352. }
  353. if !host.EndpointIP.Equal(h.EndpointIP) {
  354. continue
  355. }
  356. portsInUse[host.ListenPort] = true
  357. portsInUse[host.ProxyListenPort] = true
  358. }
  359. // iterate until port is not found or max iteration is reached
  360. for i := 0; portsInUse[h.ListenPort] && i < maxPort-minPort+1; i++ {
  361. h.ListenPort++
  362. if h.ListenPort > maxPort {
  363. h.ListenPort = minPort
  364. }
  365. }
  366. // allocate h.ListenPort so it is unavailable to h.ProxyListenPort
  367. portsInUse[h.ListenPort] = true
  368. for i := 0; portsInUse[h.ProxyListenPort] && i < maxPort-minPort+1; i++ {
  369. h.ProxyListenPort++
  370. if h.ProxyListenPort > maxPort {
  371. h.ProxyListenPort = minPort
  372. }
  373. }
  374. }
  375. // HostExists - checks if given host already exists
  376. func HostExists(h *models.Host) bool {
  377. _, err := GetHost(h.ID.String())
  378. return (err != nil && !database.IsEmptyRecord(err)) || (err == nil)
  379. }
  380. // GetHostByNodeID - returns a host if found to have a node's ID, else nil
  381. func GetHostByNodeID(id string) *models.Host {
  382. hosts, err := GetAllHosts()
  383. if err != nil {
  384. return nil
  385. }
  386. for i := range hosts {
  387. h := hosts[i]
  388. if StringSliceContains(h.Nodes, id) {
  389. return &h
  390. }
  391. }
  392. return nil
  393. }