telemetry.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // Package telemetry: aviso diario ANÓNIMO de instancia activa (#822).
  2. //
  3. // Manda, como mucho una vez al día, un GET a un endpoint del proyecto con un
  4. // identificador aleatorio de instalación (generado en local y guardado en kv),
  5. // la versión y el os/arch. No envía ni IPs, ni MACs, ni hostnames, ni datos de
  6. // red, y no guarda nada fuera de su propia instalación. Es fail-silent (un
  7. // fallo no afecta a la app) y se desactiva con NETPULSE_TELEMETRY=0.
  8. package telemetry
  9. import (
  10. "context"
  11. "crypto/rand"
  12. "database/sql"
  13. "encoding/hex"
  14. "fmt"
  15. "net/http"
  16. "net/url"
  17. "os"
  18. "runtime"
  19. "strings"
  20. "time"
  21. "github.com/gnacho/netpulse/server-go/internal/db"
  22. )
  23. const (
  24. defaultURL = "https://netpulse.cloudless.club/instances"
  25. kvInstallID = "telemetry.install_id"
  26. kvLastSent = "telemetry.last_sent"
  27. // minGap: no reenviar antes de 23 h (el objetivo es ~1/día; el margen
  28. // evita reenvíos por reinicios con reloj ligeramente distinto).
  29. minGap = 23 * time.Hour
  30. checkEvery = time.Hour
  31. maxJitter = 3 * time.Minute
  32. )
  33. // Agent envía el ping anónimo diario.
  34. type Agent struct {
  35. db *db.DB
  36. url string
  37. version string
  38. enabled bool
  39. client *http.Client
  40. now func() time.Time
  41. newID func() (string, error)
  42. }
  43. // New construye el agente desde el entorno. Queda desactivado si DEMO_MODE=1
  44. // (una demo no es una instancia real) o si NETPULSE_TELEMETRY es 0/false/off/no.
  45. // NETPULSE_TELEMETRY_URL permite cambiar el endpoint (por defecto, el del proyecto).
  46. func New(d *db.DB, version string, demo bool) *Agent {
  47. a := &Agent{
  48. db: d,
  49. url: defaultURL,
  50. version: version,
  51. enabled: !demo,
  52. client: &http.Client{Timeout: 10 * time.Second},
  53. now: time.Now,
  54. newID: randomID,
  55. }
  56. if v := strings.TrimSpace(os.Getenv("NETPULSE_TELEMETRY_URL")); v != "" {
  57. a.url = strings.TrimRight(v, "/")
  58. }
  59. if v, ok := os.LookupEnv("NETPULSE_TELEMETRY"); ok {
  60. switch strings.ToLower(strings.TrimSpace(v)) {
  61. case "0", "false", "off", "no":
  62. a.enabled = false
  63. }
  64. }
  65. return a
  66. }
  67. // Enabled indica si el aviso está activo.
  68. func (a *Agent) Enabled() bool { return a.enabled }
  69. func randomID() (string, error) {
  70. b := make([]byte, 16)
  71. if _, err := rand.Read(b); err != nil {
  72. return "", err
  73. }
  74. return hex.EncodeToString(b), nil
  75. }
  76. // installID devuelve el id de instalación, creándolo (una vez) si no existe.
  77. func (a *Agent) installID() (string, error) {
  78. var v string
  79. err := a.db.QueryRow("SELECT value FROM kv WHERE key = ?", kvInstallID).Scan(&v)
  80. if err == nil && v != "" {
  81. return v, nil
  82. }
  83. if err != nil && err != sql.ErrNoRows {
  84. return "", err
  85. }
  86. id, idErr := a.newID()
  87. if idErr != nil {
  88. return "", idErr
  89. }
  90. if _, err := a.setKV(kvInstallID, id); err != nil {
  91. return "", err
  92. }
  93. return id, nil
  94. }
  95. func (a *Agent) setKV(key, value string) (sql.Result, error) {
  96. return a.db.Exec(
  97. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
  98. key, value)
  99. }
  100. func (a *Agent) lastSent() time.Time {
  101. var v string
  102. if err := a.db.QueryRow("SELECT value FROM kv WHERE key = ?", kvLastSent).Scan(&v); err != nil {
  103. return time.Time{}
  104. }
  105. t, err := time.Parse(time.RFC3339, v)
  106. if err != nil {
  107. return time.Time{}
  108. }
  109. return t
  110. }
  111. // Due indica si toca enviar: nunca se envió o hace más de minGap.
  112. func (a *Agent) Due() bool {
  113. last := a.lastSent()
  114. if last.IsZero() {
  115. return true
  116. }
  117. return a.now().Sub(last) >= minGap
  118. }
  119. // pingURL construye la URL del ping. Solo lleva id, versión y os/arch.
  120. func (a *Agent) pingURL(id string) string {
  121. q := url.Values{}
  122. q.Set("v", a.version)
  123. q.Set("os", runtime.GOOS+"-"+runtime.GOARCH)
  124. return a.url + "/" + url.PathEscape(id) + "?" + q.Encode()
  125. }
  126. // SendOnce envía el ping si está activo y toca, y persiste last_sent. Nunca
  127. // devuelve error al llamante en el bucle: es fail-silent por diseño.
  128. func (a *Agent) SendOnce(ctx context.Context) error {
  129. if !a.enabled || !a.Due() {
  130. return nil
  131. }
  132. id, err := a.installID()
  133. if err != nil {
  134. return err
  135. }
  136. req, err := http.NewRequestWithContext(ctx, http.MethodGet, a.pingURL(id), nil)
  137. if err != nil {
  138. return err
  139. }
  140. req.Header.Set("User-Agent", "netpulse-instance")
  141. res, err := a.client.Do(req)
  142. if err != nil {
  143. return err
  144. }
  145. res.Body.Close()
  146. if res.StatusCode >= 400 {
  147. return fmt.Errorf("telemetry: HTTP %d", res.StatusCode)
  148. }
  149. _, _ = a.setKV(kvLastSent, a.now().UTC().Format(time.RFC3339))
  150. return nil
  151. }
  152. // Start lanza el bucle en segundo plano (jitter inicial + chequeo horario).
  153. // No hace nada si el aviso está desactivado.
  154. func (a *Agent) Start(ctx context.Context) {
  155. if !a.enabled {
  156. return
  157. }
  158. go func() {
  159. select {
  160. case <-ctx.Done():
  161. return
  162. case <-time.After(jitter()):
  163. }
  164. _ = a.SendOnce(ctx)
  165. t := time.NewTicker(checkEvery)
  166. defer t.Stop()
  167. for {
  168. select {
  169. case <-ctx.Done():
  170. return
  171. case <-t.C:
  172. _ = a.SendOnce(ctx)
  173. }
  174. }
  175. }()
  176. }
  177. // jitter reparte los envíos para no sincronizar todas las instancias.
  178. func jitter() time.Duration {
  179. b := make([]byte, 4)
  180. if _, err := rand.Read(b); err != nil {
  181. return 0
  182. }
  183. ms := int64(b[0])<<24 | int64(b[1])<<16 | int64(b[2])<<8 | int64(b[3])
  184. return time.Duration(ms%int64(maxJitter/time.Millisecond)) * time.Millisecond
  185. }