collector_api.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package httpapi
  2. import (
  3. "net/http"
  4. "strconv"
  5. "time"
  6. "github.com/gnacho/netpulse/server-go/internal/collectorreader"
  7. )
  8. func (s *server) handleCollectorMetrics(w http.ResponseWriter, r *http.Request) {
  9. if s.collectorReader == nil {
  10. writeJSON(w, http.StatusOK, map[string]any{"metrics": []any{}, "available": false})
  11. return
  12. }
  13. metrics, err := s.collectorReader.ListMetrics()
  14. if err != nil {
  15. writeError(w, http.StatusInternalServerError, "collector_error", err.Error())
  16. return
  17. }
  18. writeJSON(w, http.StatusOK, map[string]any{"metrics": metrics, "available": true})
  19. }
  20. func (s *server) handleCollectorSeries(w http.ResponseWriter, r *http.Request) {
  21. if s.collectorReader == nil {
  22. writeError(w, http.StatusServiceUnavailable, "collector_unavailable")
  23. return
  24. }
  25. metric := r.URL.Query().Get("metric")
  26. if metric == "" {
  27. writeError(w, http.StatusBadRequest, "invalid_input", "metric required")
  28. return
  29. }
  30. now := time.Now().Unix()
  31. fromStr := r.URL.Query().Get("from")
  32. toStr := r.URL.Query().Get("to")
  33. pointsStr := r.URL.Query().Get("points")
  34. from := now - 86400
  35. to := now
  36. points := 500
  37. if fromStr != "" {
  38. if v, err := strconv.ParseInt(fromStr, 10, 64); err == nil {
  39. from = v
  40. }
  41. }
  42. if toStr != "" {
  43. if v, err := strconv.ParseInt(toStr, 10, 64); err == nil {
  44. to = v
  45. }
  46. }
  47. if pointsStr != "" {
  48. if v, err := strconv.Atoi(pointsStr); err == nil && v > 0 {
  49. points = v
  50. }
  51. }
  52. resolution, data, err := s.collectorReader.Series(metric, from, to, points)
  53. if err != nil {
  54. writeError(w, http.StatusBadRequest, "series_error", err.Error())
  55. return
  56. }
  57. if data == nil {
  58. data = []collectorreader.Point{}
  59. }
  60. writeJSON(w, http.StatusOK, map[string]any{
  61. "metric": metric, "resolution": resolution, "points": data,
  62. "from": from, "to": to,
  63. })
  64. }