helpers.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. //TODO: Consider restructuring this file/folder "github.com/gorilla/handlers"
  2. //It may make more sense to split into different files and not call it "helpers"
  3. package functions
  4. import (
  5. "context"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "log"
  10. "math/rand"
  11. "net"
  12. "strings"
  13. "time"
  14. "github.com/gravitl/netmaker/models"
  15. "github.com/gravitl/netmaker/mongoconn"
  16. "github.com/gravitl/netmaker/servercfg"
  17. "go.mongodb.org/mongo-driver/bson"
  18. "go.mongodb.org/mongo-driver/bson/primitive"
  19. "go.mongodb.org/mongo-driver/mongo"
  20. "go.mongodb.org/mongo-driver/mongo/options"
  21. )
  22. //Takes in an arbitrary field and value for field and checks to see if any other
  23. //node has that value for the same field within the network
  24. func CreateServerToken(netID string) (string, error) {
  25. fmt.Println("Creating token.")
  26. var network models.Network
  27. var accesskey models.AccessKey
  28. network, err := GetParentNetwork(netID)
  29. if err != nil {
  30. return "", err
  31. }
  32. accesskey.Name = GenKeyName()
  33. accesskey.Value = GenKey()
  34. accesskey.Uses = 1
  35. address := "127.0.0.1:" + servercfg.GetGRPCPort()
  36. privAddr := ""
  37. if *network.IsLocal {
  38. privAddr = network.LocalRange
  39. }
  40. accessstringdec := address + "|" + netID + "|" + accesskey.Value + "|" + privAddr
  41. accesskey.AccessString = base64.StdEncoding.EncodeToString([]byte(accessstringdec))
  42. fmt.Println(" access string: " + accesskey.AccessString)
  43. network.AccessKeys = append(network.AccessKeys, accesskey)
  44. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  45. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  46. // Create filter
  47. filter := bson.M{"netid": netID}
  48. // Read update model from body request
  49. fmt.Println("Adding key to " + network.NetID)
  50. // prepare update model.
  51. update := bson.D{
  52. {"$set", bson.D{
  53. {"accesskeys", network.AccessKeys},
  54. }},
  55. }
  56. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
  57. defer cancel()
  58. if errN != nil {
  59. return "", errN
  60. }
  61. return accesskey.AccessString, nil
  62. }
  63. func GetPeersList(networkName string) ([]models.PeersResponse, error) {
  64. var peers []models.PeersResponse
  65. //Connection mongoDB with mongoconn class
  66. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  67. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  68. //Get all nodes in the relevant network which are NOT in pending state
  69. filter := bson.M{"network": networkName, "ispending": false}
  70. cur, err := collection.Find(ctx, filter)
  71. if err != nil {
  72. return peers, err
  73. }
  74. // Close the cursor once finished and cancel if it takes too long
  75. defer cancel()
  76. for cur.Next(context.TODO()) {
  77. var peer models.PeersResponse
  78. err := cur.Decode(&peer)
  79. if err != nil {
  80. log.Fatal(err)
  81. }
  82. // add the node to our node array
  83. //maybe better to just return this? But then that's just GetNodes...
  84. peers = append(peers, peer)
  85. }
  86. //Uh oh, fatal error! This needs some better error handling
  87. //TODO: needs appropriate error handling so the server doesnt shut down.
  88. if err := cur.Err(); err != nil {
  89. log.Fatal(err)
  90. }
  91. return peers, err
  92. }
  93. func IsFieldUnique(network string, field string, value string) bool {
  94. var node models.Node
  95. isunique := true
  96. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  97. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  98. filter := bson.M{field: value, "network": network}
  99. err := collection.FindOne(ctx, filter).Decode(&node)
  100. defer cancel()
  101. if err != nil {
  102. return isunique
  103. }
  104. if node.Name != "" {
  105. isunique = false
  106. }
  107. return isunique
  108. }
  109. func NetworkExists(name string) (bool, error) {
  110. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  111. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  112. filter := bson.M{"netid": name}
  113. var result bson.M
  114. err := collection.FindOne(ctx, filter).Decode(&result)
  115. defer cancel()
  116. if err != nil {
  117. if err == mongo.ErrNoDocuments {
  118. return false, nil
  119. }
  120. }
  121. return true, err
  122. }
  123. //TODO: This is very inefficient (N-squared). Need to find a better way.
  124. //Takes a list of nodes in a network and iterates through
  125. //for each node, it gets a unique address. That requires checking against all other nodes once more
  126. func UpdateNetworkNodeAddresses(networkName string) error {
  127. //Connection mongoDB with mongoconn class
  128. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  129. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  130. filter := bson.M{"network": networkName}
  131. cur, err := collection.Find(ctx, filter)
  132. if err != nil {
  133. return err
  134. }
  135. defer cancel()
  136. for cur.Next(context.TODO()) {
  137. var node models.Node
  138. err := cur.Decode(&node)
  139. if err != nil {
  140. fmt.Println("error in node address assignment!")
  141. return err
  142. }
  143. ipaddr, iperr := UniqueAddress(networkName)
  144. if iperr != nil {
  145. fmt.Println("error in node address assignment!")
  146. return iperr
  147. }
  148. filter := bson.M{"macaddress": node.MacAddress}
  149. update := bson.D{{"$set", bson.D{{"address", ipaddr}}}}
  150. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  151. defer cancel()
  152. if errN != nil {
  153. return errN
  154. }
  155. }
  156. return err
  157. }
  158. //TODO TODO TODO!!!!!
  159. func UpdateNetworkPrivateAddresses(networkName string) error {
  160. //Connection mongoDB with mongoconn class
  161. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  162. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  163. filter := bson.M{"network": networkName}
  164. cur, err := collection.Find(ctx, filter)
  165. if err != nil {
  166. return err
  167. }
  168. defer cancel()
  169. for cur.Next(context.TODO()) {
  170. var node models.Node
  171. err := cur.Decode(&node)
  172. if err != nil {
  173. fmt.Println("error in node address assignment!")
  174. return err
  175. }
  176. ipaddr, iperr := UniqueAddress(networkName)
  177. if iperr != nil {
  178. fmt.Println("error in node address assignment!")
  179. return iperr
  180. }
  181. filter := bson.M{"macaddress": node.MacAddress}
  182. update := bson.D{{"$set", bson.D{{"address", ipaddr}}}}
  183. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  184. defer cancel()
  185. if errN != nil {
  186. return errN
  187. }
  188. }
  189. return err
  190. }
  191. //Checks to see if any other networks have the same name (id)
  192. func IsNetworkNameUnique(name string) (bool, error) {
  193. isunique := true
  194. dbs, err := ListNetworks()
  195. if err != nil {
  196. return false, err
  197. }
  198. for i := 0; i < len(dbs); i++ {
  199. if name == dbs[i].NetID {
  200. isunique = false
  201. }
  202. }
  203. return isunique, nil
  204. }
  205. func IsNetworkDisplayNameUnique(name string) (bool, error) {
  206. isunique := true
  207. dbs, err := ListNetworks()
  208. if err != nil {
  209. return false, err
  210. }
  211. for i := 0; i < len(dbs); i++ {
  212. if name == dbs[i].DisplayName {
  213. isunique = false
  214. }
  215. }
  216. return isunique, nil
  217. }
  218. func GetNetworkNodeNumber(networkName string) (int, error) {
  219. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  220. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  221. filter := bson.M{"network": networkName}
  222. count, err := collection.CountDocuments(ctx, filter)
  223. returncount := int(count)
  224. //not sure if this is the right way of handling this error...
  225. if err != nil {
  226. return 9999, err
  227. }
  228. defer cancel()
  229. return returncount, err
  230. }
  231. //Kind of a weird name. Should just be GetNetworks I think. Consider changing.
  232. //Anyway, returns all the networks
  233. func ListNetworks() ([]models.Network, error) {
  234. var networks []models.Network
  235. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  236. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  237. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  238. if err != nil {
  239. return networks, err
  240. }
  241. defer cancel()
  242. for cur.Next(context.TODO()) {
  243. var network models.Network
  244. err := cur.Decode(&network)
  245. if err != nil {
  246. return networks, err
  247. }
  248. // add network our array
  249. networks = append(networks, network)
  250. }
  251. if err := cur.Err(); err != nil {
  252. return networks, err
  253. }
  254. return networks, err
  255. }
  256. //Checks to see if access key is valid
  257. //Does so by checking against all keys and seeing if any have the same value
  258. //may want to hash values before comparing...consider this
  259. //TODO: No error handling!!!!
  260. func IsKeyValid(networkname string, keyvalue string) bool {
  261. network, _ := GetParentNetwork(networkname)
  262. var key models.AccessKey
  263. foundkey := false
  264. isvalid := false
  265. for i := len(network.AccessKeys) - 1; i >= 0; i-- {
  266. currentkey := network.AccessKeys[i]
  267. if currentkey.Value == keyvalue {
  268. key = currentkey
  269. foundkey = true
  270. }
  271. }
  272. if foundkey {
  273. if key.Uses > 0 {
  274. isvalid = true
  275. }
  276. }
  277. return isvalid
  278. }
  279. func IsKeyValidGlobal(keyvalue string) bool {
  280. networks, _ := ListNetworks()
  281. var key models.AccessKey
  282. foundkey := false
  283. isvalid := false
  284. for _, network := range networks {
  285. for i := len(network.AccessKeys) - 1; i >= 0; i-- {
  286. currentkey := network.AccessKeys[i]
  287. if currentkey.Value == keyvalue {
  288. key = currentkey
  289. foundkey = true
  290. break
  291. }
  292. }
  293. if foundkey { break }
  294. }
  295. if foundkey {
  296. if key.Uses > 0 {
  297. isvalid = true
  298. }
  299. }
  300. return isvalid
  301. }
  302. //TODO: Contains a fatal error return. Need to change
  303. //This just gets a network object from a network name
  304. //Should probably just be GetNetwork. kind of a dumb name.
  305. //Used in contexts where it's not the Parent network.
  306. func GetParentNetwork(networkname string) (models.Network, error) {
  307. var network models.Network
  308. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  309. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  310. filter := bson.M{"netid": networkname}
  311. err := collection.FindOne(ctx, filter).Decode(&network)
  312. defer cancel()
  313. if err != nil {
  314. return network, err
  315. }
  316. return network, nil
  317. }
  318. func IsIpNet(host string) bool {
  319. return net.ParseIP(host) != nil
  320. }
  321. //Similar to above but checks if Cidr range is valid
  322. //At least this guy's got some print statements
  323. //still not good error handling
  324. func IsIpCIDR(host string) bool {
  325. ip, ipnet, err := net.ParseCIDR(host)
  326. if err != nil {
  327. fmt.Println(err)
  328. fmt.Println("Address Range is not valid!")
  329. return false
  330. }
  331. return ip != nil && ipnet != nil
  332. }
  333. //This is used to validate public keys (make sure they're base64 encoded like all public keys should be).
  334. func IsBase64(s string) bool {
  335. _, err := base64.StdEncoding.DecodeString(s)
  336. return err == nil
  337. }
  338. //This should probably just be called GetNode
  339. //It returns a node based on the ID of the node.
  340. //Why do we need this?
  341. //TODO: Check references. This seems unnecessary.
  342. func GetNodeObj(id primitive.ObjectID) models.Node {
  343. var node models.Node
  344. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  345. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  346. filter := bson.M{"_id": id}
  347. err := collection.FindOne(ctx, filter).Decode(&node)
  348. defer cancel()
  349. if err != nil {
  350. fmt.Println(err)
  351. fmt.Println("Did not get the node...")
  352. return node
  353. }
  354. fmt.Println("Got node " + node.Name)
  355. return node
  356. }
  357. //This checks to make sure a network name is valid.
  358. //Switch to REGEX?
  359. func NameInNetworkCharSet(name string) bool {
  360. charset := "abcdefghijklmnopqrstuvwxyz1234567890-_"
  361. for _, char := range name {
  362. if !strings.Contains(charset, strings.ToLower(string(char))) {
  363. return false
  364. }
  365. }
  366. return true
  367. }
  368. func NameInDNSCharSet(name string) bool {
  369. charset := "abcdefghijklmnopqrstuvwxyz1234567890-."
  370. for _, char := range name {
  371. if !strings.Contains(charset, strings.ToLower(string(char))) {
  372. return false
  373. }
  374. }
  375. return true
  376. }
  377. func NameInNodeCharSet(name string) bool {
  378. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  379. for _, char := range name {
  380. if !strings.Contains(charset, strings.ToLower(string(char))) {
  381. return false
  382. }
  383. }
  384. return true
  385. }
  386. //This returns a node based on its mac address.
  387. //The mac address acts as the Unique ID for nodes.
  388. //Is this a dumb thing to do? I thought it was cool but maybe it's dumb.
  389. //It doesn't really provide a tangible benefit over a random ID
  390. func GetNodeByMacAddress(network string, macaddress string) (models.Node, error) {
  391. var node models.Node
  392. filter := bson.M{"macaddress": macaddress, "network": network}
  393. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  394. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  395. err := collection.FindOne(ctx, filter).Decode(&node)
  396. defer cancel()
  397. if err != nil {
  398. return node, err
  399. }
  400. return node, nil
  401. }
  402. func GetAllExtClients() ([]models.ExtClient, error) {
  403. var extclient models.ExtClient
  404. var extclients []models.ExtClient
  405. collection := mongoconn.Client.Database("netmaker").Collection("extclients")
  406. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  407. // Filter out them ID's again
  408. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  409. if err != nil {
  410. return []models.ExtClient{}, err
  411. }
  412. defer cancel()
  413. for cur.Next(context.TODO()) {
  414. err := cur.Decode(&extclient)
  415. if err != nil {
  416. return []models.ExtClient{}, err
  417. }
  418. // add node to our array
  419. extclients = append(extclients, extclient)
  420. }
  421. //TODO: Fatal error
  422. if err := cur.Err(); err != nil {
  423. return []models.ExtClient{}, err
  424. }
  425. return extclients, nil
  426. }
  427. //This returns a unique address for a node to use
  428. //it iterates through the list of IP's in the subnet
  429. //and checks against all nodes to see if it's taken, until it finds one.
  430. //TODO: We do not handle a case where we run out of addresses.
  431. //We will need to handle that eventually
  432. func UniqueAddress(networkName string) (string, error) {
  433. var network models.Network
  434. network, err := GetParentNetwork(networkName)
  435. if err != nil {
  436. fmt.Println("UniqueAddress encountered an error")
  437. return "666", err
  438. }
  439. offset := true
  440. ip, ipnet, err := net.ParseCIDR(network.AddressRange)
  441. if err != nil {
  442. fmt.Println("UniqueAddress encountered an error")
  443. return "666", err
  444. }
  445. for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); Inc(ip) {
  446. if offset {
  447. offset = false
  448. continue
  449. }
  450. if IsIPUnique(networkName, ip.String()) && IsIPUniqueExtClients(networkName, ip.String()) {
  451. return ip.String(), err
  452. }
  453. }
  454. //TODO
  455. err1 := errors.New("ERROR: No unique addresses available. Check network subnet.")
  456. return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
  457. }
  458. func UniqueAddress6(networkName string) (string, error) {
  459. var network models.Network
  460. network, err := GetParentNetwork(networkName)
  461. if err != nil {
  462. fmt.Println("Network Not Found")
  463. return "", err
  464. }
  465. if network.IsDualStack == nil || *network.IsDualStack == false {
  466. return "", nil
  467. }
  468. offset := true
  469. ip, ipnet, err := net.ParseCIDR(network.AddressRange6)
  470. if err != nil {
  471. fmt.Println("UniqueAddress6 encountered an error")
  472. return "666", err
  473. }
  474. for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); Inc(ip) {
  475. if offset {
  476. offset = false
  477. continue
  478. }
  479. if IsIP6Unique(networkName, ip.String()) {
  480. return ip.String(), err
  481. }
  482. }
  483. //TODO
  484. err1 := errors.New("ERROR: No unique addresses available. Check network subnet.")
  485. return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
  486. }
  487. //generate an access key value
  488. func GenKey() string {
  489. var seededRand *rand.Rand = rand.New(
  490. rand.NewSource(time.Now().UnixNano()))
  491. length := 16
  492. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  493. b := make([]byte, length)
  494. for i := range b {
  495. b[i] = charset[seededRand.Intn(len(charset))]
  496. }
  497. return string(b)
  498. }
  499. //generate a key value
  500. //we should probably just have 1 random string generator
  501. //that can be used across all functions
  502. //have a "base string" a "length" and a "charset"
  503. func GenKeyName() string {
  504. var seededRand *rand.Rand = rand.New(
  505. rand.NewSource(time.Now().UnixNano()))
  506. length := 5
  507. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  508. b := make([]byte, length)
  509. for i := range b {
  510. b[i] = charset[seededRand.Intn(len(charset))]
  511. }
  512. return "key" + string(b)
  513. }
  514. func IsIPUniqueExtClients(network string, ip string) bool {
  515. var extclient models.ExtClient
  516. isunique := true
  517. collection := mongoconn.Client.Database("netmaker").Collection("extclients")
  518. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  519. filter := bson.M{"address": ip, "network": network}
  520. err := collection.FindOne(ctx, filter).Decode(&extclient)
  521. defer cancel()
  522. if err != nil {
  523. fmt.Println(err)
  524. return isunique
  525. }
  526. if extclient.Address == ip {
  527. isunique = false
  528. }
  529. return isunique
  530. }
  531. //checks if IP is unique in the address range
  532. //used by UniqueAddress
  533. func IsIPUnique(network string, ip string) bool {
  534. var node models.Node
  535. isunique := true
  536. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  537. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  538. filter := bson.M{"address": ip, "network": network}
  539. err := collection.FindOne(ctx, filter).Decode(&node)
  540. defer cancel()
  541. if err != nil {
  542. fmt.Println(err)
  543. return isunique
  544. }
  545. if node.Address == ip {
  546. isunique = false
  547. }
  548. return isunique
  549. }
  550. //checks if IP is unique in the address range
  551. //used by UniqueAddress
  552. func IsIP6Unique(network string, ip string) bool {
  553. var node models.Node
  554. isunique := true
  555. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  556. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  557. filter := bson.M{"address6": ip, "network": network}
  558. err := collection.FindOne(ctx, filter).Decode(&node)
  559. defer cancel()
  560. if err != nil {
  561. fmt.Println(err)
  562. return isunique
  563. }
  564. if node.Address6 == ip {
  565. isunique = false
  566. }
  567. return isunique
  568. }
  569. //called once key has been used by createNode
  570. //reduces value by one and deletes if necessary
  571. func DecrimentKey(networkName string, keyvalue string) {
  572. var network models.Network
  573. network, err := GetParentNetwork(networkName)
  574. if err != nil {
  575. return
  576. }
  577. for i := len(network.AccessKeys) - 1; i >= 0; i-- {
  578. currentkey := network.AccessKeys[i]
  579. if currentkey.Value == keyvalue {
  580. network.AccessKeys[i].Uses--
  581. if network.AccessKeys[i].Uses < 1 {
  582. //this is the part where it will call the delete
  583. //not sure if there's edge cases I'm missing
  584. DeleteKey(network, i)
  585. return
  586. }
  587. }
  588. }
  589. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  590. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  591. filter := bson.M{"netid": network.NetID}
  592. update := bson.D{
  593. {"$set", bson.D{
  594. {"accesskeys", network.AccessKeys},
  595. }},
  596. }
  597. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
  598. defer cancel()
  599. if errN != nil {
  600. return
  601. }
  602. }
  603. //takes the logic from controllers.deleteKey
  604. func DeleteKey(network models.Network, i int) {
  605. network.AccessKeys = append(network.AccessKeys[:i],
  606. network.AccessKeys[i+1:]...)
  607. collection := mongoconn.Client.Database("netmaker").Collection("networks")
  608. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  609. // Create filter
  610. filter := bson.M{"netid": network.NetID}
  611. // prepare update model.
  612. update := bson.D{
  613. {"$set", bson.D{
  614. {"accesskeys", network.AccessKeys},
  615. }},
  616. }
  617. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
  618. defer cancel()
  619. if errN != nil {
  620. return
  621. }
  622. }
  623. //increments an IP over the previous
  624. func Inc(ip net.IP) {
  625. for j := len(ip) - 1; j >= 0; j-- {
  626. ip[j]++
  627. if ip[j] > 0 {
  628. break
  629. }
  630. }
  631. }
  632. func GetAllNodes() ([]models.ReturnNode, error) {
  633. var node models.ReturnNode
  634. var nodes []models.ReturnNode
  635. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  636. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  637. // Filter out them ID's again
  638. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  639. if err != nil {
  640. return []models.ReturnNode{}, err
  641. }
  642. defer cancel()
  643. for cur.Next(context.TODO()) {
  644. err := cur.Decode(&node)
  645. if err != nil {
  646. return []models.ReturnNode{}, err
  647. }
  648. // add node to our array
  649. nodes = append(nodes, node)
  650. }
  651. //TODO: Fatal error
  652. if err := cur.Err(); err != nil {
  653. return []models.ReturnNode{}, err
  654. }
  655. return nodes, nil
  656. }