register.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package functions
  2. import (
  3. "time"
  4. "log"
  5. "io/ioutil"
  6. "bytes"
  7. "github.com/gravitl/netmaker/netclient/config"
  8. "github.com/gravitl/netmaker/netclient/local"
  9. "github.com/gravitl/netmaker/netclient/wireguard"
  10. "github.com/gravitl/netmaker/models"
  11. "encoding/json"
  12. "net/http"
  13. "errors"
  14. "github.com/davecgh/go-spew/spew"
  15. )
  16. func Register(cfg config.GlobalConfig) error {
  17. postclient := &models.IntClient{
  18. AccessKey: cfg.Client.AccessKey,
  19. PublicKey: cfg.Client.PublicKey,
  20. PrivateKey: cfg.Client.PublicKey,
  21. Address: cfg.Client.Address,
  22. Address6: cfg.Client.Address6,
  23. Network: "comms",
  24. }
  25. jsonstring, err := json.Marshal(postclient)
  26. if err != nil {
  27. return err
  28. }
  29. jsonbytes := []byte(jsonstring)
  30. body := bytes.NewBuffer(jsonbytes)
  31. log.Println(jsonstring)
  32. log.Println("http://"+cfg.Client.ServerEndpoint+"/api/client/register","application/json")
  33. res, err := http.Post("http://"+cfg.Client.ServerEndpoint+"/api/intclient/register","application/json",body)
  34. if err != nil {
  35. return err
  36. }
  37. if res.StatusCode != http.StatusOK {
  38. return errors.New("request to server failed: " + res.Status)
  39. }
  40. bodyBytes, err := ioutil.ReadAll(res.Body)
  41. if err != nil {
  42. return err
  43. }
  44. var wgclient models.IntClient
  45. json.Unmarshal(bodyBytes, &wgclient)
  46. spew.Dump(wgclient)
  47. err = config.ModGlobalConfig(wgclient)
  48. if err != nil {
  49. return err
  50. }
  51. err = wireguard.InitGRPCWireguard(wgclient)
  52. if err != nil {
  53. return err
  54. }
  55. return err
  56. }
  57. func Unregister(cfg config.GlobalConfig) error {
  58. client := &http.Client{ Timeout: 7 * time.Second,}
  59. req, err := http.NewRequest("DELETE", "http://"+cfg.Client.ServerEndpoint+"/api/intclient/"+cfg.Client.ClientID, nil)
  60. if err != nil {
  61. return err
  62. }
  63. res, err := client.Do(req)
  64. if res == nil {
  65. err = local.WipeGRPCClient()
  66. if err == nil {
  67. log.Println("successfully removed grpc client interface")
  68. }
  69. } else {
  70. if res.StatusCode != http.StatusOK {
  71. return errors.New("request to server failed: " + res.Status)
  72. defer res.Body.Close()
  73. }
  74. }
  75. return err
  76. }