luci.netpulse 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. #!/usr/bin/ucode
  2. // luci.netpulse — plugin rpcd (protocolo exec) para luci-app-netpulse.
  3. //
  4. // Expone el estado LOCAL del agente sin abrir ningún puerto ni tocar el
  5. // binario del agente (criterio Fase 11: cero superficie/RAM extra):
  6. //
  7. // status → procd/pid, RSS, uptime del proceso, versión del binario,
  8. // heartbeat (/tmp, epoch s) y si el servicio está habilitado.
  9. // logs → últimas N líneas de `logread -e netpulse` (10..300).
  10. // restart → /etc/init.d/netpulse-agent restart (el "rearme" local).
  11. // test → curl al /api/health del servidor desde este router (valida
  12. // conectividad real: DNS, ruta, puerto, server vivo).
  13. //
  14. // rpcd lo invoca como ejecutable: `list` imprime la firma de métodos;
  15. // `call <método>` recibe los argumentos JSON por stdin e imprime el
  16. // resultado JSON. El acceso por sesión lo limita la ACL
  17. // /usr/share/rpcd/acl.d/luci-app-netpulse.json.
  18. //
  19. // ubus se carga con require() dentro de la función (no import top-level):
  20. // si el módulo no está, se degrada a `pidof` en vez de romper el plugin.
  21. 'use strict';
  22. const fs = require('fs');
  23. const INIT = '/etc/init.d/netpulse-agent';
  24. const BIN = '/usr/sbin/netpulse-agent';
  25. const HEARTBEAT = '/tmp/netpulse-agent.heartbeat';
  26. // popen_all ejecuta cmd por shell y devuelve stdout completo (o null).
  27. function popen_all(cmd) {
  28. let p = fs.popen(cmd, 'r');
  29. if (!p)
  30. return null;
  31. let out = p.read('all');
  32. p.close();
  33. return out;
  34. }
  35. // agent_pid: PID vía `ubus service list` (procd, fuente canónica) con
  36. // fallback a pidof (BusyBox) si ubus/el módulo no están disponibles.
  37. function agent_pid() {
  38. try {
  39. let ubus = require('ubus');
  40. let conn = ubus.connect();
  41. if (conn) {
  42. let res = conn.call('service', 'list', { name: 'netpulse-agent' });
  43. conn.disconnect();
  44. let inst = res?.['netpulse-agent']?.instances;
  45. for (let name in inst) {
  46. let i = inst[name];
  47. if (i?.running && int(i.pid) > 0)
  48. return int(i.pid);
  49. }
  50. }
  51. }
  52. catch (e) {
  53. // sin ubus: caemos a pidof
  54. }
  55. let out = popen_all('pidof netpulse-agent 2>/dev/null');
  56. if (out) {
  57. let pid = int(split(trim(out), ' ')[0]);
  58. if (pid > 0)
  59. return pid;
  60. }
  61. return 0;
  62. }
  63. // proc_rss_kb: VmRSS del proceso en KiB (null si no legible).
  64. function proc_rss_kb(pid) {
  65. let st = fs.readfile(sprintf('/proc/%d/status', pid), 8192);
  66. if (!st)
  67. return null;
  68. let m = match(st, /VmRSS:[ \t]+([0-9]+)[ \t]+kB/);
  69. return m ? int(m[1]) : null;
  70. }
  71. // proc_uptime_s: segundos de vida del proceso — starttime (campo 22 de
  72. // /proc/pid/stat, en ticks de 100 Hz) contra /proc/uptime. El comm puede
  73. // llevar espacios/paréntesis: se parte por el ÚLTIMO ')'.
  74. function proc_uptime_s(pid) {
  75. let stat = fs.readfile(sprintf('/proc/%d/stat', pid), 2048);
  76. let up = fs.readfile('/proc/uptime', 128);
  77. if (!stat || !up)
  78. return null;
  79. let rp = rindex(stat, ')');
  80. if (rp < 0)
  81. return null;
  82. let f = split(trim(substr(stat, rp + 2)), ' ');
  83. // f[0] = state (campo 3) → starttime (campo 22) = f[19]
  84. let start_ticks = int(f[19]);
  85. let boot_s = int(split(trim(up), '.')[0]);
  86. if (start_ticks <= 0 || boot_s <= 0)
  87. return null;
  88. let secs = int(boot_s - start_ticks / 100);
  89. return secs >= 0 ? secs : 0;
  90. }
  91. function do_status() {
  92. let pid = agent_pid();
  93. let running = pid > 0;
  94. let res = {
  95. installed: !!fs.access(BIN),
  96. enabled: system([ INIT, 'enabled' ], 5000) == 0,
  97. running: running,
  98. pid: running ? pid : null,
  99. rss_kb: running ? proc_rss_kb(pid) : null,
  100. uptime_s: running ? proc_uptime_s(pid) : null,
  101. version: null,
  102. heartbeat_ts: null,
  103. heartbeat_age_s: null
  104. };
  105. if (res.installed) {
  106. let v = popen_all(BIN + ' --version 2>/dev/null');
  107. if (v && trim(v) != '')
  108. res.version = split(trim(v), '\n')[0];
  109. }
  110. // Heartbeat: epoch en segundos escrito por el agente tras cada push
  111. // (agent/internal/heartbeat). Sin fichero (reboot reciente) → null.
  112. let hb = fs.readfile(HEARTBEAT, 64);
  113. if (hb) {
  114. let ts = int(trim(hb));
  115. if (ts > 0) {
  116. res.heartbeat_ts = ts;
  117. let age = time() - ts;
  118. res.heartbeat_age_s = age >= 0 ? age : 0;
  119. }
  120. }
  121. return res;
  122. }
  123. function do_logs(args) {
  124. let n = int(args?.lines ?? 50);
  125. if (n < 10)
  126. n = 10;
  127. if (n > 300)
  128. n = 300;
  129. // Leemos logread completo y procesamos en memoria (ucode nativo,
  130. // cero shell string y cero pipes). En un router doméstico los logs
  131. // de netpulse son de pocos KB: split/slice/join es más limpio.
  132. let out = popen_all('logread -e netpulse 2>/dev/null');
  133. if (!out)
  134. return { lines: '' };
  135. let lines = split(out, '\n');
  136. if (length(lines) > 0 && lines[length(lines) - 1] === '')
  137. lines = slice(lines, 0, -1);
  138. let start = length(lines) - n;
  139. if (start < 0)
  140. start = 0;
  141. return { lines: join('\n', slice(lines, start)) };
  142. }
  143. function do_restart() {
  144. let rc = system([ INIT, 'restart' ], 20000);
  145. return { ok: rc == 0, code: rc };
  146. }
  147. // do_test: valida conectividad real desde este router al servidor NetPulse.
  148. // Lee la URL de UCI y hace curl al /api/health (sin auth, solo reachability).
  149. function do_test() {
  150. let server = trim(popen_all('uci -q get netpulse-agent.main.server 2>/dev/null') || '');
  151. if (!server)
  152. return { ok: false, error: 'no_server' };
  153. // curl: -sf silencia progreso y errores HTTP; -m 5 timeout 5s;
  154. // -o /dev/null descarta body; -w "%{http_code}" captura el código.
  155. let url = server + '/api/health';
  156. let cmd = sprintf('curl -sf -m 5 -o /dev/null -w "%%{http_code}" %s 2>/dev/null', url);
  157. let code = trim(popen_all(cmd) || '');
  158. if (code == '200')
  159. return { ok: true, code: 200 };
  160. return { ok: false, code: code || 'unreachable' };
  161. }
  162. // ── Dispatcher del protocolo exec de rpcd ────────────────────────────────
  163. if (ARGV[0] == 'list') {
  164. printf('%J\n', { status: {}, logs: { lines: 50 }, restart: {}, test: {} });
  165. exit(0);
  166. }
  167. if (ARGV[0] == 'call') {
  168. let args = {};
  169. try {
  170. let raw = fs.stdin.read('all');
  171. if (raw && trim(raw) != '')
  172. args = json(raw);
  173. }
  174. catch (e) {
  175. args = {};
  176. }
  177. if (ARGV[1] == 'status') {
  178. printf('%J\n', do_status());
  179. exit(0);
  180. }
  181. if (ARGV[1] == 'logs') {
  182. printf('%J\n', do_logs(args));
  183. exit(0);
  184. }
  185. if (ARGV[1] == 'restart') {
  186. printf('%J\n', do_restart());
  187. exit(0);
  188. }
  189. if (ARGV[1] == 'test') {
  190. printf('%J\n', do_test());
  191. exit(0);
  192. }
  193. }
  194. exit(1);