netgrip_delegate.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "strings"
  9. "time"
  10. "github.com/gnacho/netpulse/agent/executor"
  11. )
  12. const (
  13. netgripAddr = "http://127.0.0.1:8080"
  14. netgripTokenPath = "/etc/netgrip/executor-token"
  15. netgripTimeout = 30 * time.Second
  16. )
  17. func readNetgripToken() (string, error) {
  18. data, err := os.ReadFile(netgripTokenPath)
  19. if err != nil {
  20. return "", err
  21. }
  22. return strings.TrimSpace(string(data)), nil
  23. }
  24. type netgripRequest struct {
  25. Ops []executor.Op `json:"ops"`
  26. }
  27. type netgripResponse struct {
  28. Ok bool `json:"ok"`
  29. Error string `json:"error,omitempty"`
  30. }
  31. func delegateToNetgrip(ops []executor.Op) (executor.ApplyResult, bool) {
  32. token, err := readNetgripToken()
  33. if err != nil {
  34. return executor.ApplyResult{}, false
  35. }
  36. body, err := json.Marshal(netgripRequest{Ops: ops})
  37. if err != nil {
  38. return executor.ApplyResult{}, false
  39. }
  40. req, err := http.NewRequest("POST", netgripAddr+"/api/executor/apply", bytes.NewReader(body))
  41. if err != nil {
  42. return executor.ApplyResult{}, false
  43. }
  44. req.Header.Set("Content-Type", "application/json")
  45. req.Header.Set("Authorization", "Bearer "+token)
  46. client := &http.Client{Timeout: netgripTimeout}
  47. start := time.Now()
  48. resp, err := client.Do(req)
  49. if err != nil {
  50. return executor.ApplyResult{}, false
  51. }
  52. defer resp.Body.Close()
  53. var result netgripResponse
  54. if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
  55. return executor.ApplyResult{
  56. Status: "failed",
  57. Error: fmt.Sprintf("netgrip response parse: %s", err),
  58. DurationMs: time.Since(start).Milliseconds(),
  59. }, true
  60. }
  61. if !result.Ok {
  62. return executor.ApplyResult{
  63. Status: "failed",
  64. Error: fmt.Sprintf("netgrip: %s", result.Error),
  65. DurationMs: time.Since(start).Milliseconds(),
  66. }, true
  67. }
  68. return executor.ApplyResult{
  69. Status: "applied",
  70. DurationMs: time.Since(start).Milliseconds(),
  71. }, true
  72. }