mem.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // mem.go — cálculo del uso de RAM de un router a partir de los campos de
  2. // memoria (issue #513).
  3. package adapters
  4. import "math"
  5. // memUsagePct devuelve el % de RAM en uso.
  6. //
  7. // Prioridad: si el agente reporta `usedProc` (suma de VmRSS de procesos) lo
  8. // usamos directamente, porque es lo que el usuario percibe como uso real.
  9. // Si no llega, con Cached > 0 usa la fórmula clásica que no cuenta la caché de
  10. // ficheros como consumida (paridad LuCI/htop): used = total - free - buffered
  11. // - cached. Sin Cached cae a la fórmula previa basada en MemAvailable, que en
  12. // root ubifs/overlay tiende a sobreestimar el uso (#513).
  13. func memUsagePct(total, free, buffered, cached, available, usedProc float64) int {
  14. if total <= 0 {
  15. return 0
  16. }
  17. if usedProc > 0 && usedProc < total {
  18. return int(math.Round(usedProc / total * 100))
  19. }
  20. if cached > 0 {
  21. used := total - free - buffered - cached
  22. if used < 0 {
  23. used = 0
  24. }
  25. return int(math.Round(used / total * 100))
  26. }
  27. avail := available
  28. if avail == 0 {
  29. avail = free + buffered
  30. }
  31. used := total - avail
  32. if used < 0 {
  33. used = 0
  34. }
  35. return int(math.Round(used / total * 100))
  36. }
  37. // memUsedBytes: mismos criterios que memUsagePct pero en bytes, para que el
  38. // server envíe la cifra de uso autoritativa (#1501): derivarla en el front
  39. // desde el porcentaje redondeado (pct × total) acumula hasta ~2% de error
  40. // visible en el texto "X MB used of Y MB".
  41. func memUsedBytes(total, free, buffered, cached, available, usedProc float64) float64 {
  42. if total <= 0 {
  43. return 0
  44. }
  45. if usedProc > 0 && usedProc < total {
  46. return usedProc
  47. }
  48. if cached > 0 {
  49. used := total - free - buffered - cached
  50. if used < 0 {
  51. used = 0
  52. }
  53. return used
  54. }
  55. avail := available
  56. if avail == 0 {
  57. avail = free + buffered
  58. }
  59. used := total - avail
  60. if used < 0 {
  61. used = 0
  62. }
  63. return used
  64. }