2
0

hosts.go 12 KB

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