helpers.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // helpers.go: utilidades HTTP compartidas por apply y upgrade.
  2. package runtime
  3. import (
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "net/http"
  8. "time"
  9. "github.com/gnacho/netpulse/agent/internal/tlspin"
  10. )
  11. func buildTransport(opts Options) (*http.Transport, error) {
  12. return tlspin.BuildTransport(opts.Server, opts.ServerFP)
  13. }
  14. func jsonUnmarshal(data string, v any) error {
  15. return json.Unmarshal([]byte(data), v)
  16. }
  17. // postJSON envía un POST JSON autenticado (Bearer) al servidor; los
  18. // fallos se loguean y se descartan (fire-and-forget).
  19. func postJSON(opts Options, transport http.RoundTripper, path string, body any) {
  20. payload, err := json.Marshal(body)
  21. if err != nil {
  22. return
  23. }
  24. if err := postJSONBytes(opts, transport, path, payload); err != nil {
  25. opts.logger().Warn("[netpulse-agent] POST falló", "path", path, "err", err)
  26. }
  27. }
  28. // postJSONBytes hace el POST y devuelve el error de transporte/estado.
  29. func postJSONBytes(opts Options, transport http.RoundTripper, path string, payload []byte) error {
  30. req, err := http.NewRequest("POST", opts.Server+path, bytes.NewReader(payload))
  31. if err != nil {
  32. return err
  33. }
  34. req.Header.Set("Content-Type", "application/json")
  35. req.Header.Set("Authorization", "Bearer "+opts.Token)
  36. hc := &http.Client{Transport: transport, Timeout: 10 * time.Second}
  37. resp, err := hc.Do(req)
  38. if err != nil {
  39. return err
  40. }
  41. defer resp.Body.Close()
  42. if resp.StatusCode >= 300 {
  43. return fmt.Errorf("status %d", resp.StatusCode)
  44. }
  45. return nil
  46. }
  47. // postJSONWithRetry reintenta un POST crítico con backoff. Para el
  48. // apply-result: un plan cuyo resultado no se reporta queda "applying" para
  49. // siempre en el server, y aplicar ops como `service network restart` corta
  50. // la red del propio agente justo cuando toca reportar (#500). Corre en
  51. // goroutine: no bloquea el stream SSE.
  52. func postJSONWithRetry(opts Options, transport http.RoundTripper, path string, body any, what string) {
  53. payload, err := json.Marshal(body)
  54. if err != nil {
  55. return
  56. }
  57. go func() {
  58. backoff := []time.Duration{2 * time.Second, 5 * time.Second, 10 * time.Second, 20 * time.Second, 40 * time.Second,
  59. time.Minute, time.Minute, time.Minute, time.Minute, time.Minute}
  60. for i, wait := range backoff {
  61. if err := postJSONBytes(opts, transport, path, payload); err == nil {
  62. return
  63. }
  64. opts.logger().Warn("[netpulse-agent] "+what+" falló, reintentando", "intento", i+1, "espera", wait.String())
  65. time.Sleep(wait)
  66. }
  67. opts.logger().Error("[netpulse-agent] " + what + " no reportado tras reintentos")
  68. }()
  69. }