hosts.go 11 KB

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