| @@ -1,5 +1,27 @@ | |||||
| # Changelog | # Changelog | ||||
| ## 1.0.6 — 2026-09-21 — Monotonic overrun handling and selective syslog | |||||
| - Las transiciones PRE-PRESSURE/PRESSURE se basan en tiempo monotónico real y | |||||
| ya no pierden duración acumulada por ticks omitidos del muestreo. | |||||
| - Un salto tardío directo a `free <= desfree` entra en CRITICAL y | |||||
| `free <= minfree` conserva entrada inmediata a EMERGENCY; el log indica | |||||
| `reason=threshold_jump` y los estados omitidos. | |||||
| - `sampling_overrun` incluye retraso, estado y páginas libres, sin activar un | |||||
| recorrido `/proc` ni borrar la caché de candidatos. | |||||
| - Añadido syslog nativo selectivo, activado por defecto en `local5`, con ident, | |||||
| facility y severidades verificadas; el archivo `guard.log` permanece completo. | |||||
| - `signal_sent` sólo se emite tras una señal real confirmada y nunca en dry-run. | |||||
| Un fallo de syslog no altera la decisión ni el resultado de señalización. | |||||
| - Añadido el fixture y el informe del episodio real del 21 de septiembre: | |||||
| SIGTERM/SIGKILL sobre `clamd`, recuperación aproximada de 1,21 GiB y ausencia | |||||
| de `pageout_deadman`; se documenta como evidencia fuerte, no causalidad absoluta. | |||||
| - Añadidas regresiones de tiempos irregulares, saltos de estado, ruta O(1), | |||||
| inclusión/exclusión de syslog, facility, severidad, claves, duplicados, | |||||
| desactivación y fallo de syslog. | |||||
| - Conservados umbrales, ranking, presupuestos, TERM/KILL, dry-run distribuido, | |||||
| cero UUID autorizados y SMF deshabilitado. No hubo despliegue desde esta tarea. | |||||
| ## 1.0.5 — 2026-09-21 — Production SMF activation contract | ## 1.0.5 — 2026-09-21 — Production SMF activation contract | ||||
| - Retirado `--force-dry-run` del método start del manifiesto SMF versionado para | - Retirado `--force-dry-run` del método start del manifiesto SMF versionado para | ||||
| @@ -756,3 +756,18 @@ grep 'event=zone ' \ | |||||
| ``` | ``` | ||||
| La pregunta inmediata no es si el daemon mide memoria correctamente; eso ya está aceptado. La pregunta pendiente es si el ranking por PID identifica de manera repetible al proceso que mejor explica el crecimiento y que más memoria podría liberar, respetando la política de zonas, antes de que se autorice cualquier acción real. | La pregunta inmediata no es si el daemon mide memoria correctamente; eso ya está aceptado. La pregunta pendiente es si el ranking por PID identifica de manera repetible al proceso que mejor explica el crecimiento y que más memoria podría liberar, respetando la política de zonas, antes de que se autorice cualquier acción real. | ||||
| ## 19. Addendum v1.0.6 — episodio de rescate del 2026-09-21 | |||||
| Una validación posterior observó EMERGENCY a las 11:31:14 con | |||||
| `free_pages=49077`, `minfree=49077` y `nscan=4171921`. La caché global eligió | |||||
| `clamd` (PID 17850, alias `servidor.consultaerte.com`, RSS aproximado 1,32 GiB). | |||||
| Tras SIGTERM a las 11:31:17 y SIGKILL a las 11:31:23, el host alcanzó RECOVERY | |||||
| con unas 367.019 páginas libres a las 11:31:24 y después NORMAL. La recuperación | |||||
| aproximada fue 1,21 GiB y no apareció `pageout_deadman`. | |||||
| Los retrasos del muestreo (hasta unos 4,459 s) demostraron que las confirmaciones | |||||
| no deben depender de ticks exactos de un segundo. v1.0.6 conserva tiempo | |||||
| monotónico a través de `sampling_overrun`, registra saltos de umbral y añade | |||||
| syslog nativo selectivo. La evidencia y sus límites causales están en | |||||
| `INCIDENT_PAGEOUT_DEADMAN_AVOIDED_2026_09_21.md`. | |||||
| @@ -0,0 +1,59 @@ | |||||
| # Aparente prevención de `pageout_deadman` — 2026-09-21 | |||||
| ## Alcance de la conclusión | |||||
| Este documento conserva un episodio real observado en SmartOS durante una | |||||
| ejecución armada anterior. La secuencia aporta **evidencia fuerte compatible | |||||
| con una prevención efectiva**: el guard detectó emergencia, eligió un candidato | |||||
| autorizado, envió TERM y KILL, y la memoria libre aumentó inmediatamente sin que | |||||
| se produjera un nuevo `pageout_deadman`. No demuestra causalidad absoluta ni | |||||
| garantiza que el mismo resultado se repita bajo otra carga. | |||||
| La preparación de v1.0.6 no desplegó código, no modificó el nodo y no envió | |||||
| señales. Los datos siguientes son evidencia histórica proporcionada para la | |||||
| regresión y documentación. | |||||
| ## Cronología preservada | |||||
| | Hora | Observación | | |||||
| | --- | --- | | |||||
| | 11:31:09 | `free_pages=79960`, por debajo de `lotsfree=130875`. | | |||||
| | 11:31:14 | EMERGENCY con `free_pages=49077` (`minfree=49077`) y `nscan=4171921`. | | |||||
| | 11:31:17 | SIGTERM real al candidato cacheado `clamd`, PID 17850, alias `servidor.consultaerte.com`, RSS aproximado 1,32 GiB; `free_pages≈48653`. | | |||||
| | 11:31:21 | Decisión de escalada al no haberse recuperado memoria suficiente. | | |||||
| | 11:31:23 | SIGKILL real sobre la misma identidad revalidada. | | |||||
| | 11:31:24 | RECOVERY con `free_pages≈367019`. | | |||||
| | posterior | Memoria estable sobre `lotsfree`; transición final a NORMAL. | | |||||
| La memoria libre pasó aproximadamente de 190 MiB a 1,40 GiB: una recuperación | |||||
| aproximada de 1,21 GiB, coherente con el RSS del proceso terminado. No apareció | |||||
| un panic `pageout_deadman` durante el episodio observado. | |||||
| El planificador registró retrasos aproximados de 0,918, 2,331, 1,890 y 4,459 s. | |||||
| Esos overruns son el motivo directo de la regresión v1.0.6: un tick perdido no | |||||
| puede borrar el tiempo monotónico que la memoria lleva bajo `lotsfree`. La ruta | |||||
| CRITICAL/EMERGENCY siguió usando la caché preconstruida y no inició un scan | |||||
| completo de `/proc` durante el rescate. | |||||
| ## Fixture y propiedades comprobables | |||||
| `tests/fixtures/successful_pageout_deadman_avoidance_2026_09_21.csv` conserva | |||||
| los puntos de memoria, scanner, retrasos y fases. La prueba de política exige: | |||||
| 1. entrada inmediata en EMERGENCY al llegar a `minfree`, aunque falten ticks; | |||||
| 2. permanencia en emergencia durante TERM/escalada/KILL; | |||||
| 3. entrada en RECOVERY al recuperar `desfree`; | |||||
| 4. retorno a NORMAL sólo después de 15 s monotónicos sobre `lotsfree` con | |||||
| `nscan=0`. | |||||
| Las señales de la cronología no se reproducen: las pruebas enlazan backends | |||||
| simulados y no pueden enviar señales nativas. | |||||
| ## Límites | |||||
| RSS puede contar páginas compartidas y no equivale exactamente a memoria física | |||||
| recuperable. Otras tareas, ARC y actividad del kernel pudieron contribuir a la | |||||
| variación. La ausencia de panic en una observación tampoco prueba que el panic | |||||
| fuera inevitable sin intervención. Por eso la formulación correcta es | |||||
| “aparente prevención con evidencia temporal y cuantitativa fuerte”, no una | |||||
| garantía ni una atribución causal exclusiva. | |||||
| @@ -15,7 +15,7 @@ native-check: | |||||
| o6h-memory-guard: $(SOURCES) src/guard.h | native-check | o6h-memory-guard: $(SOURCES) src/guard.h | native-check | ||||
| $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $(SOURCES) $(LDLIBS) | $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $(SOURCES) $(LDLIBS) | ||||
| test-guard: tests/test_guard.c tests/fixtures/pageout_deadman_real_incident_2026_09.csv src/core.c src/config.c src/guard.h | |||||
| test-guard: tests/test_guard.c tests/fixtures/pageout_deadman_real_incident_2026_09.csv tests/fixtures/successful_pageout_deadman_avoidance_2026_09_21.csv src/core.c src/config.c src/guard.h | |||||
| $(CC) $(TESTFLAGS) -o $@ tests/test_guard.c src/core.c src/config.c | $(CC) $(TESTFLAGS) -o $@ tests/test_guard.c src/core.c src/config.c | ||||
| test-runtime: tests/test_runtime.c tests/fixtures/global_victim_ranking_smartos_2026_09.csv src/main.c src/core.c src/config.c src/guard.h | test-runtime: tests/test_runtime.c tests/fixtures/global_victim_ranking_smartos_2026_09.csv src/main.c src/core.c src/config.c src/guard.h | ||||
| @@ -1,4 +1,4 @@ | |||||
| # o6h-memory-guard 1.0.5 | |||||
| # o6h-memory-guard 1.0.6 | |||||
| Primera implementación para SmartOS global zone: daemon C de 64 bits, libkstat, | Primera implementación para SmartOS global zone: daemon C de 64 bits, libkstat, | ||||
| /proc, identidad UUID + generación de zona + PID + instante de creación, | /proc, identidad UUID + generación de zona + PID + instante de creación, | ||||
| @@ -32,6 +32,8 @@ Activación real | |||||
| SmartOS real, además del estado exacto y los requisitos antes de `armed`. | SmartOS real, además del estado exacto y los requisitos antes de `armed`. | ||||
| - `INCIDENT_PAGEOUT_DEADMAN_2026_09.md`: cronología del panic real observado | - `INCIDENT_PAGEOUT_DEADMAN_2026_09.md`: cronología del panic real observado | ||||
| con v1.0.2, endurecimiento de v1.0.3 y corrección del ranking global en v1.0.4. | con v1.0.2, endurecimiento de v1.0.3 y corrección del ranking global en v1.0.4. | ||||
| - `INCIDENT_PAGEOUT_DEADMAN_AVOIDED_2026_09_21.md`: evidencia de campo de un | |||||
| episodio en el que la acción real liberó memoria antes de un nuevo panic. | |||||
| - `CHANGELOG.md`: evolución de versiones y revisión documental del paquete. | - `CHANGELOG.md`: evolución de versiones y revisión documental del paquete. | ||||
| El checkpoint es cronológicamente posterior a `VALIDATION.md`; por ello amplía | El checkpoint es cronológicamente posterior a `VALIDATION.md`; por ello amplía | ||||
| @@ -45,12 +47,12 @@ Si no hay herramientas de desarrollo, compilar en una **zona nativa SmartOS** | |||||
| de la misma plataforma (no LX), ejecutar allí `gmake test`, y copiar el binario | de la misma plataforma (no LX), ejecutar allí `gmake test`, y copiar el binario | ||||
| junto a este árbol al host. No instalar un compilador en un nodo bajo presión. | junto a este árbol al host. No instalar un compilador en un nodo bajo presión. | ||||
| Copiar el archivo distribuido a `/var/tmp/o6h-memory-guard-1.0.5.tar.gz`: | |||||
| Copiar el archivo distribuido a `/var/tmp/o6h-memory-guard-1.0.6.tar.gz`: | |||||
| ```sh | ```sh | ||||
| mkdir -p /opt/custom/src | mkdir -p /opt/custom/src | ||||
| cd /opt/custom/src | cd /opt/custom/src | ||||
| gzip -dc /var/tmp/o6h-memory-guard-1.0.5.tar.gz | tar -xf - | |||||
| gzip -dc /var/tmp/o6h-memory-guard-1.0.6.tar.gz | tar -xf - | |||||
| cd /opt/custom/src/o6h-memory-guard | cd /opt/custom/src/o6h-memory-guard | ||||
| gmake CC=gcc | gmake CC=gcc | ||||
| gmake test CC=gcc | gmake test CC=gcc | ||||
| @@ -175,7 +177,7 @@ una prueba de que un proceso concreto causó la presión. | |||||
| | Estado/condición de entrada | Comportamiento predeterminado | | | Estado/condición de entrada | Comportamiento predeterminado | | ||||
| | --- | --- | | | --- | --- | | ||||
| | NORMAL | Sin intervención; muestreo VM de 1 s. | | | NORMAL | Sin intervención; muestreo VM de 1 s. | | ||||
| | PRE-PRESSURE | Dos muestras bajo `lotsfree` (1 s por defecto); refresca candidatos, sin señales. | | |||||
| | PRE-PRESSURE | Bajo `lotsfree` durante 1 s monotónico por defecto; refresca candidatos, sin señales. | | |||||
| | PRESSURE | Bajo `lotsfree` durante 2 s, o caída rápida corroborada; no exige que `nscan` haya arrancado. Refresca candidatos cada segundo. | | | PRESSURE | Bajo `lotsfree` durante 2 s, o caída rápida corroborada; no exige que `nscan` haya arrancado. Refresca candidatos cada segundo. | | ||||
| | CRITICAL | Bajo `desfree` con presión corroborada continua durante 2 s; usa caché, sin scan nuevo, y propone TERM. | | | CRITICAL | Bajo `desfree` con presión corroborada continua durante 2 s; usa caché, sin scan nuevo, y propone TERM. | | ||||
| | EMERGENCY | `free <= minfree`; entrada inmediata. Usa caché y gracia TERM de 1 s. | | | EMERGENCY | `free <= minfree`; entrada inmediata. Usa caché y gracia TERM de 1 s. | | ||||
| @@ -191,9 +193,16 @@ La ocupación física jamás es un trigger único: sin pageout creciente y memor | |||||
| bajo `lotsfree` no cambia el estado. El compromiso virtual tampoco se interpreta | bajo `lotsfree` no cambia el estado. El compromiso virtual tampoco se interpreta | ||||
| como pageout. | como pageout. | ||||
| Los tiempos son segundos monotónicos transcurridos, no número de filas leídas. | Los tiempos son segundos monotónicos transcurridos, no número de filas leídas. | ||||
| Un hueco de más de 2,5 s reinicia las confirmaciones. La gravedad se retiene | |||||
| hasta recuperar `desfree`; `action_pressure` indica si el estado retenido aún | |||||
| permite una decisión de rescate. | |||||
| Un `sampling_overrun` no borra el tiempo ya observado bajo un umbral: si las | |||||
| muestras llegan en t+1,8 y t+4,2, la segunda puede confirmar PRESSURE aunque no | |||||
| existan filas exactas por segundo. Si después de un retraso la siguiente muestra | |||||
| salta desde encima de `desfree` a `free <= desfree`, entra directamente en | |||||
| CRITICAL; `free <= minfree` siempre entra directamente en EMERGENCY. El | |||||
| `state_transition` registra `reason=threshold_jump` y `skipped_states` cuando | |||||
| se omiten estados intermedios. Sólo una muestra inválida, obsoleta o con reloj | |||||
| monotónico no creciente reinicia la confirmación. La gravedad se retiene hasta | |||||
| recuperar `desfree`; `action_pressure` indica si el estado retenido aún permite | |||||
| una decisión de rescate. | |||||
| Las gracias son configurables: 5 s en CRITICAL, 1 s en EMERGENCY y 0 s al floor | Las gracias son configurables: 5 s en CRITICAL, 1 s en EMERGENCY y 0 s al floor | ||||
| por defecto. Una lectura kstat fresca debe seguir bajo `desfree`. Recuperar | por defecto. Una lectura kstat fresca debe seguir bajo `desfree`. Recuperar | ||||
| @@ -342,9 +351,44 @@ Los eventos `state_transition`, `candidate_cache`, `action_decision` y | |||||
| `recovery_check` permiten reconstruir el estado, origen/rank/edad del candidato, | `recovery_check` permiten reconstruir el estado, origen/rank/edad del candidato, | ||||
| resultado del último scan, componentes del score y cualquier override de presupuesto. | resultado del último scan, componentes del score y cualquier override de presupuesto. | ||||
| ### Syslog nativo selectivo | |||||
| `guard.log` sigue siendo el registro completo. Con `SYSLOG_ENABLED yes` se | |||||
| envía además un subconjunto operativo mediante `openlog(3C)`, `syslog(3C)` y | |||||
| `closelog(3C)`, con ident `o6h-memory-guard` y facility configurable | |||||
| `local0`…`local7` (`local5` por defecto). No se invoca `logger`, shell ni un | |||||
| proceso auxiliar. `SYSLOG_ENABLED no` lo desactiva. | |||||
| | Evento/condición | Severidad | | |||||
| | --- | --- | | |||||
| | `start`, `recovery_complete`, transición a NORMAL/RECOVERY | INFO | | |||||
| | transición a PRE-PRESSURE | NOTICE | | |||||
| | transición a PRESSURE, `action_blocked` | WARNING | | |||||
| | transición a CRITICAL, `SIGTERM` | ERR | | |||||
| | transición a EMERGENCY/floor, `SIGKILL`, error interno grave | CRIT | | |||||
| También se envían `state_transition`, `signal_sent`, `action_blocked` e | |||||
| `internal_error`. `signal_sent` se construye **después** de que el backend haya | |||||
| confirmado el envío real e incluye estado, señal, UUID, alias, PID, nombre, RSS | |||||
| y memoria libre; nunca existe en dry-run. `sample`, `delta`, `candidate_cache`, | |||||
| `top_process`, `proc_scan` y `zone` no se duplican en syslog. Un fallo al enviar | |||||
| a syslog se ignora para la decisión: no revierte ni cambia el resultado de una | |||||
| señal y las notificaciones de estado crítico se difieren hasta después de la | |||||
| ruta O(1) de acción. | |||||
| Antes de asumir un archivo de destino, inspeccionar la configuración local: | |||||
| ```sh | |||||
| grep -v '^[[:space:]]*#' /etc/syslog.conf | |||||
| ``` | |||||
| Localizar allí el destino de `local5`; el guard no modifica `syslog.conf` ni | |||||
| presupone `/var/adm/messages`. Un reenvío futuro a syslog central o mediante | |||||
| Alloy/Loki puede configurarse fuera del guard, pero esta entrega no lo hace. | |||||
| ## Modelo de activación real (operación futura; no ejecutada en esta entrega) | ## Modelo de activación real (operación futura; no ejecutada en esta entrega) | ||||
| v1.0.5 debe compilarse y observarse primero en SmartOS con `ACTION_MODE dry-run`. | |||||
| v1.0.6 debe compilarse y observarse primero en SmartOS con `ACTION_MODE dry-run`. | |||||
| El manifiesto ya no contiene una segunda puerta oculta. Cuando exista aprobación | El manifiesto ya no contiene una segunda puerta oculta. Cuando exista aprobación | ||||
| operativa explícita, el único cambio de modo es editar la configuración: | operativa explícita, el único cambio de modo es editar la configuración: | ||||
| @@ -1,25 +1,26 @@ | |||||
| 887569535302f7deba4d7c6ffb2103f1fb90bd96a40280240ff238eddc2e3a6f ./.gitignore | 887569535302f7deba4d7c6ffb2103f1fb90bd96a40280240ff238eddc2e3a6f ./.gitignore | ||||
| e45fac9145e5cdd63490c3e4b9c8f6eb34894b05c90ef1af6ca8886cb7cee741 ./CHANGELOG.md | |||||
| ebfca7d4b5eaf0c0cc9910cf49d8c85f6aa7ff69972d7f21d17e61d1a2e23bc2 ./CHECKPOINT.md | |||||
| 61974bf5d994ca3945d29721ec9d23458dc22263aa90e92589105de0e8dfd3ad ./CHANGELOG.md | |||||
| b9c80b9523c0d371302907d50bc27f3a207f1990c60b4208c310713f8f859aa3 ./CHECKPOINT.md | |||||
| a0f96300e751d08ceeef1360325ed54008b703fa6bd07df9d5368674e580f113 ./INCIDENT_PAGEOUT_DEADMAN_2026_09.md | a0f96300e751d08ceeef1360325ed54008b703fa6bd07df9d5368674e580f113 ./INCIDENT_PAGEOUT_DEADMAN_2026_09.md | ||||
| 7e735ae0ca694e748b0051a47873b53424d8d934f735f8d055ccba186de08a80 ./Makefile | |||||
| 6894f18fd377502ada7b9b51ec846f6d6ffe263531c457a81a50366b7d27fc3b ./README.md | |||||
| fa95db79696c6a1526d3ed94277911bcd9157b9bff74f9e5a997e4ab02fd669c ./VALIDATION.md | |||||
| a4727d5ac7d5ba06f59dd1ae459fcb12e1d0d966e823bec1ed9409077d986ae7 ./etc/o6h-memory-guard.conf | |||||
| fb6b65a2655ccd808d102fd917b4866cbe939f24fac4e4aeef226a6aeda6d588 ./INCIDENT_PAGEOUT_DEADMAN_AVOIDED_2026_09_21.md | |||||
| a4c564791ca7aeedbebbd68589e72d3a5af24ca494bb46661a55d0aaa289ee43 ./Makefile | |||||
| 26ef74ede1362441f02c27dbcce446c11797ae3457a872df220b0f808d50f93a ./README.md | |||||
| 6ffb6af2a439133d6e9587723fd0c7ff39273dd32747d7fc758ec66609897958 ./VALIDATION.md | |||||
| e6142ab575d390a5744e18ff4a73f023b1cdac4b274e9597f71a111a82354c49 ./etc/o6h-memory-guard.conf | |||||
| f6565d0e1ece0a08721c9893f9ed071d2ab0a2818fa93ed0a14e0050d358ce99 ./install.sh | f6565d0e1ece0a08721c9893f9ed071d2ab0a2818fa93ed0a14e0050d358ce99 ./install.sh | ||||
| 24c1b9bc39fda71d459d6fad6a8d889b0d9b92be89d303677643b3d0b93caf4b ./logs/distribution-tests.log | 24c1b9bc39fda71d459d6fad6a8d889b0d9b92be89d303677643b3d0b93caf4b ./logs/distribution-tests.log | ||||
| 50626dec1924e19b4ca92eec30416fb39c3fe7cff28d98a8e120ccf6247d2834 ./logs/example.log | 50626dec1924e19b4ca92eec30416fb39c3fe7cff28d98a8e120ccf6247d2834 ./logs/example.log | ||||
| b7d6826f353765641a95025344c30e6f5eb228772f29e04399a9ec78e3fb5595 ./logs/policy-tests.log | |||||
| 08a771544b1e8f29eefc07477af6b83f71ab4824192edd32567e1a9182631bfa ./logs/portability.log | |||||
| ed9246c2a7a82ed42a49dc72439cd452f2ab8a76b4dcd1aaf466ba23eb75fc5c ./logs/runtime-tests.log | |||||
| 2632e52bc306f5ccc947aac41d91f0b7ad54043a4192a0c4d7ed69616b1183c5 ./logs/sanitizers.log | |||||
| 812482297ae6dfb2a0881998781459ed77288ef073f202a18f22055437518fa6 ./logs/policy-tests.log | |||||
| d96eedca75907852ca6852310b619cc75a9837d15cbad46f8940ad2a54be6c8a ./logs/portability.log | |||||
| 5388d1968ee02f90654aa9e8bb9903f9c6f93018373f14b98a88414bd6b60182 ./logs/runtime-tests.log | |||||
| 670e23e9b1866de59a488a024d16c4e202ae1824315df111e4f7c9449579ebab ./logs/sanitizers.log | |||||
| 55cf49840cf1d22e4e02bedf579a10207856a0a5b40c86ae2cf6ee2f00d3f972 ./smf/o6h-memory-guard.xml | 55cf49840cf1d22e4e02bedf579a10207856a0a5b40c86ae2cf6ee2f00d3f972 ./smf/o6h-memory-guard.xml | ||||
| 9a4468d9acc3f1da078b009f764c7cb7bf337682d6584b8cbaf7b540c520d5f5 ./src/config.c | |||||
| c1f81909ec63fdb85948bbe58642478a80105b26a7c64eaf463c0e6fc42de203 ./src/core.c | |||||
| 4d8d30d2903d9da67c25f73cc58179bb5dfd297d3697df1fa1fe3aee47071f95 ./src/guard.h | |||||
| 99e1fb6a90a7bd2c1002ad09320cd3f21c2deb2499212eff2baddc14f3bdf0e6 ./src/config.c | |||||
| 659da2facd27577c763484694a2ff62eef42aea48ebc496b878853b0164b6539 ./src/core.c | |||||
| 3fc9eff261b150e5595f74dc15cc5aac0250dcb11611049819c3e9177a815747 ./src/guard.h | |||||
| 32ab75bb6a1ff2bbbeb6a1ea658abcb96a03fcc06246f38d019faec7fdc184b8 ./src/illumos.c | 32ab75bb6a1ff2bbbeb6a1ea658abcb96a03fcc06246f38d019faec7fdc184b8 ./src/illumos.c | ||||
| 4b643eb55f7846c5b1ae5906a13dec3f7ac9b6191778c8352cffd39ca0bf2bfd ./src/main.c | |||||
| 2cb2b4c50fd42051fde4a702e8955e07d63979d5e3216e02420ed9b54fb67578 ./src/support.c | |||||
| 9280f8f2b47917752ea923d28d64fbb45c9c761c173e0243582de544ae5287e4 ./src/main.c | |||||
| 1f09afd342ba86580a21f6c04a030d9ea2551a60b669e257295fbf4f43b2fad7 ./src/support.c | |||||
| f754e71d91d65403ab8e84e9701cfbb89bdd91e13766e668445e689e6890b369 ./tests/api-sketch/kstat.h | f754e71d91d65403ab8e84e9701cfbb89bdd91e13766e668445e689e6890b369 ./tests/api-sketch/kstat.h | ||||
| f0d06353d2e326c7bdce776bee6f0a8606cda50d5de957dfdd586b6848fca8da ./tests/api-sketch/procfs.h | f0d06353d2e326c7bdce776bee6f0a8606cda50d5de957dfdd586b6848fca8da ./tests/api-sketch/procfs.h | ||||
| 1c4fcb7bc48ec0a2774b1ecd73346dd45feb969a9250eb7056809d5d11ad40fe ./tests/api-sketch/sys/swap.h | 1c4fcb7bc48ec0a2774b1ecd73346dd45feb969a9250eb7056809d5d11ad40fe ./tests/api-sketch/sys/swap.h | ||||
| @@ -27,6 +28,7 @@ f0d06353d2e326c7bdce776bee6f0a8606cda50d5de957dfdd586b6848fca8da ./tests/api-sk | |||||
| 9b99e272008ad00ad0abb366e1e8720dd6c51fc050821c5d1d878eae5719c22b ./tests/api-sketch/zone.h | 9b99e272008ad00ad0abb366e1e8720dd6c51fc050821c5d1d878eae5719c22b ./tests/api-sketch/zone.h | ||||
| 4aa08ded8e98cf25d2a8762543de7a9273f0ebf00b4c7e5b359603ceda46eb56 ./tests/fixtures/global_victim_ranking_smartos_2026_09.csv | 4aa08ded8e98cf25d2a8762543de7a9273f0ebf00b4c7e5b359603ceda46eb56 ./tests/fixtures/global_victim_ranking_smartos_2026_09.csv | ||||
| c5d9d7fc7a39354474d30cd316ea9f122205c2b38e57f927f4a08306b8a62c81 ./tests/fixtures/pageout_deadman_real_incident_2026_09.csv | c5d9d7fc7a39354474d30cd316ea9f122205c2b38e57f927f4a08306b8a62c81 ./tests/fixtures/pageout_deadman_real_incident_2026_09.csv | ||||
| 5e80231bf4e9d04e9fbfc5f78b05c561925614346e5876986e1701a1b76efaa3 ./tests/test_distribution.sh | |||||
| b7ac53f6b26b4e7e2e19d7258b570a64462182ffe85c93374856caf77ec0c871 ./tests/test_guard.c | |||||
| 76c0a6d64a3feb74678f0455ad32a4392cea169aee735035f65b17837b82a931 ./tests/test_runtime.c | |||||
| facc4580ffadef29cdce84bf1226a696cba3880bbbec80161beaceb2752bfd77 ./tests/fixtures/successful_pageout_deadman_avoidance_2026_09_21.csv | |||||
| 9866c935703149aad042e84aef90d4c3a3083cf00245a809380234da9f0c1e8f ./tests/test_distribution.sh | |||||
| 7c0cfe5fc6719d27258bb87b9e68388be7b580d7031a5ed6deac34ddb3050f25 ./tests/test_guard.c | |||||
| 1da113327176396dca621664ea339f101d990f0412f41a3859376a56a81a68b4 ./tests/test_runtime.c | |||||
| @@ -1,115 +1,103 @@ | |||||
| # Validación de la entrega v1.0.5 | |||||
| Fecha: 2026-09-21. v1.0.3 se desplegó y se está validando en SmartOS real sólo | |||||
| en `dry-run`; confirmó la telemetría, SMF, scans y caché persistente, pero reveló | |||||
| que `zone_score` podía monopolizar el top‑3. **v1.0.5 no se ha desplegado, no ha | |||||
| activado `armed` y no ha enviado señales reales.** El manifiesto de producción | |||||
| ya no fuerza `--force-dry-run`; la configuración distribuida mantiene | |||||
| `ACTION_MODE dry-run`, la instancia SMF viene deshabilitada y no se distribuye | |||||
| ningún UUID `allow`. | |||||
| `CHECKPOINT.md` conserva la validación operativa previa de v1.0.2. | |||||
| `INCIDENT_PAGEOUT_DEADMAN_2026_09.md` documenta el incidente, el endurecimiento | |||||
| v1.0.3 y el hallazgo que motivó v1.0.4. v1.0.5 sólo cambia el contrato de | |||||
| activación SMF y su documentación; la telemetría nativa no se ha refactorizado. | |||||
| ## Evidencia real que motiva esta revisión | |||||
| El host pasó de 143.127 páginas libres a 48.893 en unos siete segundos y cruzó | |||||
| `lotsfree=130875` hasta `minfree=49077` en aproximadamente seis. V1.0.2 llegó a | |||||
| EMERGENCY y produjo `WOULD_ACTION`, pero permaneció correctamente en dry-run. | |||||
| Un `proc_scan` degradó de 10–15 ms a unos 9,5 s, quedó incompleto y la ruta de | |||||
| acción registró bloqueos por scan/presupuesto. El fixture | |||||
| `tests/fixtures/pageout_deadman_real_incident_2026_09.csv` reproduce los puntos | |||||
| de la cronología disponibles. | |||||
| En la validación posterior de v1.0.3, `candidate_cache` contenía tres PHP-FPM de | |||||
| `web5` de unos 245–285 MiB mientras el mismo scan mostraba `clamd` elegibles de | |||||
| aproximadamente 1,33 GiB en cuatro zonas menores. El fixture | |||||
| `tests/fixtures/global_victim_ranking_smartos_2026_09.csv` conserva esas | |||||
| proporciones y procesos `mysqld` protegidos. | |||||
| ## Comprobaciones automatizadas de v1.0.5 | |||||
| - `make test` completa 138 comprobaciones de política y 138 de runtime. | |||||
| - La prueba de distribución exige `ACTION_MODE dry-run`, los doce parámetros | |||||
| operativos 1/2/2/15, 5/1/0/15 y 4/4/8/12, el exec SMF sin | |||||
| `--force-dry-run`, el `common_name` neutral y la permanencia de la opción CLI. | |||||
| - La suite de política cubre configuración estricta, seis estados, transición | |||||
| temprana, fixture real, telemetría, identidades, protecciones, TERM/KILL, | |||||
| recuperación y presupuesto jerárquico. | |||||
| - La suite runtime incluye `src/main.c` con backend totalmente simulado y prueba | |||||
| la ruta usada por el daemon: top‑3 global multizona, componentes d5/d15/d60, | |||||
| zona contextual acotada, preservación tras scan incompleto, fallback O(1), | |||||
| rechazo de PID reutilizado y cero señales reales en dry-run. | |||||
| - Un contador de backend demuestra que `act()` no llama `platform_walk()` en | |||||
| EMERGENCY, incluso cuando el último scan fue incompleto. | |||||
| - Se conserva la regresión del contrato de logging de v1.0.2 para compromiso, | |||||
| swap físico y pageout anónimo con ventanas 5/15/60. | |||||
| - `make test-sanitize` ejecuta AddressSanitizer y UndefinedBehaviorSanitizer. | |||||
| Cuando el entorno supervisado impide LeakSanitizer se usa | |||||
| `ASAN_OPTIONS=detect_leaks=0`; no se atribuye una comprobación de fugas. | |||||
| - `make portability` aplica C99 estricto, warnings como errores, GCC | |||||
| `-fanalyzer` por unidad, `sh -n` y XML bien formado con `xmllint`. | |||||
| - Los `tests/api-sketch` sólo permiten comprobar consistencia C en Linux; no | |||||
| sustituyen cabeceras, ABI, enlace ni ejecución nativa illumos. | |||||
| - La búsqueda de producción no encuentra `system`, `popen`, `exec*` ni | |||||
| `kill(2)`. El envío real sigue aislado en el backend nativo y no se enlaza en | |||||
| las pruebas. | |||||
| Los resultados exactos se guardan en `logs/distribution-tests.log`, | |||||
| # Validación de la entrega v1.0.6 | |||||
| Fecha: 2026-09-21. Esta entrega se preparó como código fuente. **No se desplegó, | |||||
| no modificó el nodo SmartOS, no activó `armed` y no envió señales reales.** La | |||||
| configuración distribuida mantiene `ACTION_MODE dry-run`, no contiene UUID | |||||
| `allow` y la instancia SMF sigue deshabilitada de fábrica. | |||||
| ## Evidencia de campo preservada | |||||
| La telemetría y ejecución nativas de versiones anteriores ya habían validado | |||||
| SMF, muestreo, kstat, swap físico/virtual, pageout anónimo, scans y caché. El | |||||
| episodio del 21 de septiembre añadió una observación de rescate real: | |||||
| - 11:31:09: 79.960 páginas libres, bajo `lotsfree=130875`. | |||||
| - 11:31:14: EMERGENCY a `minfree=49077`, `nscan=4171921`. | |||||
| - 11:31:17: SIGTERM real a `clamd`, PID 17850, RSS aproximado 1,32 GiB. | |||||
| - 11:31:23: SIGKILL real tras persistir la emergencia. | |||||
| - 11:31:24: RECOVERY con unas 367.019 páginas libres; después NORMAL. | |||||
| - Recuperación aproximada: 1,21 GiB. No apareció `pageout_deadman`. | |||||
| Hubo overruns aproximados de 0,918, 2,331, 1,890 y 4,459 s. La correlación entre | |||||
| señal, terminación y recuperación es evidencia fuerte de prevención aparente, | |||||
| pero no prueba causalidad absoluta. El detalle y sus límites están en | |||||
| `INCIDENT_PAGEOUT_DEADMAN_AVOIDED_2026_09_21.md`. | |||||
| ## Cambios verificados en v1.0.6 | |||||
| 1. PRE-PRESSURE/PRESSURE usan duración monotónica real, no número de muestras. | |||||
| La secuencia t0 normal, t+1,8 bajo `lotsfree`, t+4,2 aún baja alcanza | |||||
| PRESSURE sin reiniciarse por los ticks omitidos. | |||||
| 2. Una muestra tardía que salta desde encima de `desfree` a `free <= desfree` | |||||
| entra en CRITICAL. `free <= minfree` entra inmediatamente en EMERGENCY. | |||||
| 3. Los saltos registran `reason=threshold_jump` y `skipped_states`; el evento | |||||
| `sampling_overrun` incluye `late_seconds`, `state` y `free_pages`. | |||||
| 4. Sólo un error real de muestra/reloj reinicia las confirmaciones. Los overruns | |||||
| no borran la caché ni ejecutan un scan `/proc` en la ruta de rescate. | |||||
| 5. Swap físico y pageout siguen siendo corroboración bajo `lotsfree`, nunca un | |||||
| trigger único. Umbrales, ranking, presupuestos 4/4/8/12 y TERM/KILL no cambian. | |||||
| 6. Syslog usa sólo `openlog/syslog/closelog`, ident `o6h-memory-guard`, facility | |||||
| validada `local0`…`local7` y `local5` por defecto. | |||||
| 7. `guard.log` conserva todos los eventos. Syslog recibe start, transiciones, | |||||
| señales confirmadas, bloqueos, recovery completo y errores; nunca el flujo | |||||
| de `sample`, `delta`, cache, top, scan o zona. | |||||
| 8. `signal_sent` sólo se genera después del éxito de una señal real y contiene | |||||
| estado, señal, UUID, alias, PID, nombre, RSS y memoria libre. Dry-run no lo | |||||
| genera. Un fallo simulado de syslog no cambia ni bloquea la acción. | |||||
| ## Pruebas y análisis ejecutados | |||||
| - `gmake test`: política, runtime simulado y contrato de distribución. | |||||
| - Política: 175 comprobaciones, incluida la fixture | |||||
| `successful_pageout_deadman_avoidance_2026_09_21`. | |||||
| - Runtime: 180 comprobaciones con backend simulado y ninguna señal nativa. | |||||
| - Regresiones syslog: eventos incluidos/excluidos, ident, facility, severidad, | |||||
| pares clave=valor, ausencia de duplicados, desactivación y fallo aislado. | |||||
| - Regresión O(1): la acción EMERGENCY no llama `platform_walk`, incluso con un | |||||
| scan previo incompleto o un candidato rank 1 obsoleto. | |||||
| - `gmake test-sanitize`: AddressSanitizer y UndefinedBehaviorSanitizer. Se usó | |||||
| `ASAN_OPTIONS=detect_leaks=0` porque LeakSanitizer no funciona bajo el ptrace | |||||
| del entorno supervisado; no se atribuye una comprobación de fugas. | |||||
| - `gmake portability`: C99 estricto, warnings como errores, `-fanalyzer`, | |||||
| sintaxis shell y XML bien formado. | |||||
| - Validación de manifiesto/distribución: SMF no fuerza dry-run, configuración | |||||
| mantiene dry-run y los parámetros 1/2/2/15, 5/1/0/15 y 4/4/8/12. | |||||
| - Checksums SHA-256 regenerados sobre la entrega source-only. | |||||
| Los logs exactos se guardan en `logs/distribution-tests.log`, | |||||
| `logs/policy-tests.log`, `logs/runtime-tests.log`, `logs/sanitizers.log` y | `logs/policy-tests.log`, `logs/runtime-tests.log`, `logs/sanitizers.log` y | ||||
| `logs/portability.log`. | |||||
| ## Propiedades verificadas por las pruebas nuevas | |||||
| 1. El fixture sale de NORMAL en la segunda muestra bajo `lotsfree` y alcanza | |||||
| PRESSURE antes de `minfree`. | |||||
| 2. Sólo un scan completo reemplaza la caché; un parcial conserva top‑1/2/3. | |||||
| 3. Una acción puede decidir con `scan_complete=0` usando una caché reciente. | |||||
| 4. La ruta de acción no inicia un scan completo. | |||||
| 5. Una identidad rank 1 obsoleta cae a rank 2/3. | |||||
| 6. PID + instante de inicio detectan reutilización. | |||||
| 7. `allow` sigue siendo obligatorio; protect/observe/unmapped/global quedan fuera. | |||||
| 8. CRITICAL respeta el límite normal; EMERGENCY y floor sólo amplían hasta sus | |||||
| límites configurados y registran el override. | |||||
| 9. Recuperar `desfree` entra en RECOVERY y cancela el pendiente; NORMAL requiere | |||||
| estabilidad sobre `lotsfree`. | |||||
| 10. Dry-run produce `WOULD_ACTION` y cero solicitudes de señal real. | |||||
| 11. El fixture multizona sitúa tres `clamd` de más de 1,3 millones de KiB por | |||||
| delante de PHP-FPM de 245–285 mil KiB aunque `web5` sume unos 8 GiB. | |||||
| 12. `mysqld`, relleno protegido, unmapped y global nunca entran en la caché. | |||||
| 13. Un PHP-FPM todavía menor asciende a rank 1 al crecer con rapidez en d5. | |||||
| 14. El contexto de zona nunca supera el 25 % del RSS del proceso. | |||||
| 15. El warmup armed bloquea sólo la señal con `reason=armed_warmup`; detección, | |||||
| scan y caché siguen activos durante los 60 s. | |||||
| ## Validación obligatoria pendiente en SmartOS | |||||
| 1. Compilar con cabeceras nativas (`gmake CC=gcc`), ejecutar `gmake test CC=gcc` | |||||
| y comprobar ELF de 64 bits y dependencias. | |||||
| 2. Ejecutar `--probe --force-dry-run` y contrastar la telemetría ya conocida. | |||||
| 3. Validar e importar el manifiesto, confirmar que `start/exec` no contiene | |||||
| `--force-dry-run` y que `event=start` sigue mostrando `mode=dry-run` por la | |||||
| configuración distribuida. | |||||
| 4. Confirmar que el top‑3 es global: los `clamd` grandes de zonas menores deben | |||||
| superar a PHP-FPM pequeños de `web5`, sin incluir ningún `mysqld` protegido. | |||||
| 5. Confirmar que un scan lento/incompleto no retrasa ni borra la decisión | |||||
| cacheada; medir `candidate_age_ms` y latencia de `action_decision`. | |||||
| 6. Revisar manualmente todos los UUID y eventos `WOULD_ACTION` de varios | |||||
| episodios. No provocar presión peligrosa en producción para obtenerlos. | |||||
| 7. Sólo en laboratorio desechable y en una fase posterior: probar PCKILL, | |||||
| supervisores, cooldown, 4/8/12 y rollback. `armed` continúa siendo NO GO. | |||||
| La opción CLI `--force-dry-run` continúa probándose y se conserva para `--probe` | |||||
| y validaciones manuales. Su ausencia se exige únicamente en el manifiesto SMF | |||||
| de producción. | |||||
| ## Límites conocidos | |||||
| La caché sólo contiene tres procesos y puede quedar sin candidato si todos | |||||
| cambian o superan 15 s de edad. En ese caso el diseño falla cerrado y no recorre | |||||
| todo `/proc` bajo emergencia. RSS sobrecuenta memoria compartida y una señal no | |||||
| garantiza liberar páginas. Kstat, ZFS, libc, logging y la revalidación puntual | |||||
| todavía pueden bloquear. No hay fsync por muestra. Este guard reduce una ventana | |||||
| de riesgo; no garantiza evitar `pageout_deadman`. | |||||
| `logs/portability.log`. Los sketches API de Linux verifican consistencia C, no | |||||
| sustituyen cabeceras, ABI, enlace ni ejecución nativa illumos. | |||||
| ## Validación local de syslog en SmartOS | |||||
| No se presupone un archivo de destino. El operador debe inspeccionar: | |||||
| ```sh | |||||
| grep -v '^[[:space:]]*#' /etc/syslog.conf | |||||
| ``` | |||||
| y localizar la regla para `local5`. Esta entrega no cambia `syslog.conf`, no | |||||
| configura forwarding y no implanta Alloy/Loki. Un recolector central puede | |||||
| añadirse posteriormente fuera del proceso guard. | |||||
| ## Validación nativa pendiente | |||||
| 1. Compilar y ejecutar la suite con cabeceras nativas SmartOS/illumos. | |||||
| 2. Validar/importar SMF manteniendo `ACTION_MODE dry-run` y comprobar | |||||
| `event=start version=1.0.6 mode=dry-run`. | |||||
| 3. Provocar sólo overruns controlados en laboratorio y confirmar continuidad | |||||
| monotónica, saltos registrados y ausencia de scans en rescate. | |||||
| 4. Confirmar en el destino local de `local5` las severidades y que muestras y | |||||
| deltas permanecen exclusivamente en `guard.log`. | |||||
| 5. Simular fallo/indisponibilidad del receptor syslog en laboratorio y medir | |||||
| que no cambia la decisión ni el resultado de señalización. | |||||
| 6. Mantener `armed` como NO GO en producción hasta una revisión humana explícita. | |||||
| ## Límites | |||||
| La caché sólo contiene tres candidatos y falla cerrada si envejecen. RSS puede | |||||
| sobrestimar memoria recuperable. kstat, ZFS, libc, logging y syslog locales | |||||
| pueden experimentar latencia; el diseño difiere la notificación crítica hasta | |||||
| después de la ruta de acción, pero no ofrece tiempo real estricto. El guard | |||||
| reduce una ventana de riesgo y no garantiza evitar `pageout_deadman`. | |||||
| @@ -1,6 +1,8 @@ | |||||
| # o6h-memory-guard 1.0.5 -- whitespace-separated, no shell evaluation. | |||||
| # o6h-memory-guard 1.0.6 -- whitespace-separated, no shell evaluation. | |||||
| # Restart required for configuration changes. Duplicate scalar keys are errors. | # Restart required for configuration changes. Duplicate scalar keys are errors. | ||||
| ACTION_MODE dry-run | ACTION_MODE dry-run | ||||
| SYSLOG_ENABLED yes | |||||
| SYSLOG_FACILITY local5 | |||||
| PRE_SECONDS 1 | PRE_SECONDS 1 | ||||
| PRESSURE_SECONDS 2 | PRESSURE_SECONDS 2 | ||||
| @@ -1,10 +1,11 @@ | |||||
| PASS strict configuration, safe defaults, explicit UUID authorization | PASS strict configuration, safe defaults, explicit UUID authorization | ||||
| PASS mandatory protections, PID reuse and zone incarnation identity | PASS mandatory protections, PID reuse and zone incarnation identity | ||||
| PASS timestamped 5/15/60s windows, missing data, signed growth, overflow | PASS timestamped 5/15/60s windows, missing data, signed growth, overflow | ||||
| PASS all six states, corroboration, hysteresis, recovery and sampling gaps | |||||
| PASS all six states, monotonic overruns, threshold jumps, corroboration and recovery | |||||
| PASS pageout_deadman_real_incident_2026_09 exits NORMAL before minfree | PASS pageout_deadman_real_incident_2026_09 exits NORMAL before minfree | ||||
| PASS successful_pageout_deadman_avoidance_2026_09_21 incident fixture | |||||
| SIMULATED t=100 state=CRITICAL UUID=11111111-1111-4111-8111-111111111111 pid=123 WOULD_ACTION=SIGTERM | SIMULATED t=100 state=CRITICAL UUID=11111111-1111-4111-8111-111111111111 pid=123 WOULD_ACTION=SIGTERM | ||||
| SIMULATED t=105 state=CRITICAL pid=123 WOULD_ACTION=SIGKILL reason=memory_not_recovered | SIMULATED t=105 state=CRITICAL pid=123 WOULD_ACTION=SIGKILL reason=memory_not_recovered | ||||
| SIMULATED state=EMERGENCY floor=1 WOULD_ACTION=SIGKILL reason=floor | SIMULATED state=EMERGENCY floor=1 WOULD_ACTION=SIGKILL reason=floor | ||||
| PASS TERM/KILL sequencing, emergency grace, floor, cooldown, budgets and no-action protections | PASS TERM/KILL sequencing, emergency grace, floor, cooldown, budgets and no-action protections | ||||
| PASS 138 checks; no native backend linked, no signals sent | |||||
| PASS 175 checks; no native backend linked, no signals sent | |||||
| @@ -1,4 +1,4 @@ | |||||
| make portability | |||||
| gmake portability | |||||
| PASS C99 syntax with -Wall -Wextra -Werror -Wformat=2 -pedantic | PASS C99 syntax with -Wall -Wextra -Werror -Wformat=2 -pedantic | ||||
| PASS GCC -fanalyzer for every production translation unit | PASS GCC -fanalyzer for every production translation unit | ||||
| PASS sh -n install.sh tests/test_distribution.sh | PASS sh -n install.sh tests/test_distribution.sh | ||||
| @@ -5,4 +5,5 @@ PASS global score uses process RSS/growth; protected zones and global zone exclu | |||||
| PASS SmartOS fixture produces a global cross-zone top-3 and bounded zone context | PASS SmartOS fixture produces a global cross-zone top-3 and bounded zone context | ||||
| PASS incomplete scan preserves cache; emergency uses O(1) fallback without a new walk | PASS incomplete scan preserves cache; emergency uses O(1) fallback without a new walk | ||||
| PASS PID/start-time reuse rejects rank 1 and selects cached fallback | PASS PID/start-time reuse rejects rank 1 and selects cached fallback | ||||
| PASS 138 runtime checks; all platform calls mocked, no signals sent | |||||
| PASS selective native syslog ident/facility/severity, exclusions, signal ordering, disable and failure isolation | |||||
| PASS 180 runtime checks; all platform calls mocked, no signals sent | |||||
| @@ -1,5 +1,27 @@ | |||||
| ASAN_OPTIONS=detect_leaks=0 make test-sanitize | |||||
| GCC 11.4.0; AddressSanitizer + UndefinedBehaviorSanitizer | |||||
| PASS test-sanitize-guard: 138 checks; no native backend linked, no signals sent | |||||
| PASS test-sanitize-runtime: 138 checks; all platform calls mocked, no signals sent | |||||
| LeakSanitizer was intentionally disabled because the supervised environment can reject ptrace; no leak-check result is claimed. | |||||
| gcc -std=c99 -O1 -g -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700 -Isrc -Wall -Wextra -Werror -Wformat=2 -pedantic -fsanitize=address,undefined -fno-omit-frame-pointer -o test-sanitize-guard tests/test_guard.c src/core.c src/config.c | |||||
| ./test-sanitize-guard | |||||
| PASS strict configuration, safe defaults, explicit UUID authorization | |||||
| PASS mandatory protections, PID reuse and zone incarnation identity | |||||
| PASS timestamped 5/15/60s windows, missing data, signed growth, overflow | |||||
| PASS all six states, monotonic overruns, threshold jumps, corroboration and recovery | |||||
| PASS pageout_deadman_real_incident_2026_09 exits NORMAL before minfree | |||||
| PASS successful_pageout_deadman_avoidance_2026_09_21 incident fixture | |||||
| SIMULATED t=100 state=CRITICAL UUID=11111111-1111-4111-8111-111111111111 pid=123 WOULD_ACTION=SIGTERM | |||||
| SIMULATED t=105 state=CRITICAL pid=123 WOULD_ACTION=SIGKILL reason=memory_not_recovered | |||||
| SIMULATED state=EMERGENCY floor=1 WOULD_ACTION=SIGKILL reason=floor | |||||
| PASS TERM/KILL sequencing, emergency grace, floor, cooldown, budgets and no-action protections | |||||
| PASS 175 checks; no native backend linked, no signals sent | |||||
| gcc -std=c99 -O1 -g -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700 -Isrc -Wall -Wextra -Werror -Wformat=2 -pedantic -fsanitize=address,undefined -fno-omit-frame-pointer -o test-sanitize-runtime tests/test_runtime.c src/core.c src/config.c | |||||
| ./test-sanitize-runtime | |||||
| PASS actual daemon dry-run path records WOULD_ACTION=SIGTERM/SIGKILL; zero real requests | |||||
| PASS continuous sample contract and 5/15/60 deltas for commitment, physical swap and pageout | |||||
| PASS armed-path mock requests, explicit warmup, stale cache, logging/sampling failures, stop and fresh floor | |||||
| PASS global score uses process RSS/growth; protected zones and global zone excluded | |||||
| PASS SmartOS fixture produces a global cross-zone top-3 and bounded zone context | |||||
| PASS incomplete scan preserves cache; emergency uses O(1) fallback without a new walk | |||||
| PASS PID/start-time reuse rejects rank 1 and selects cached fallback | |||||
| PASS selective native syslog ident/facility/severity, exclusions, signal ordering, disable and failure isolation | |||||
| PASS 180 runtime checks; all platform calls mocked, no signals sent | |||||
| LeakSanitizer was intentionally disabled because the supervised environment rejects ptrace; no leak-check result is claimed. | |||||
| ASAN_OPTIONS=detect_leaks=0 gmake test-sanitize | |||||
| GCC AddressSanitizer + UndefinedBehaviorSanitizer | |||||
| @@ -7,6 +7,7 @@ | |||||
| void defaults(config_t *c) | void defaults(config_t *c) | ||||
| { | { | ||||
| memset(c, 0, sizeof (*c)); | memset(c, 0, sizeof (*c)); | ||||
| c->syslog_enabled = 1; c->syslog_facility = 5; | |||||
| c->pre_s = 1; c->pressure_s = 2; c->critical_s = 2; | c->pre_s = 1; c->pressure_s = 2; c->critical_s = 2; | ||||
| c->recovery_s = 15; c->critical_term_s = 5; | c->recovery_s = 15; c->critical_term_s = 5; | ||||
| c->emergency_term_s = 1; c->floor_kill_delay_s = 0; | c->emergency_term_s = 1; c->floor_kill_delay_s = 0; | ||||
| @@ -124,6 +125,20 @@ int config_read(FILE *f, config_t *c, char *error, size_t cap) | |||||
| else if (strcmp(value, "dry-run")) goto invalid; | else if (strcmp(value, "dry-run")) goto invalid; | ||||
| continue; | continue; | ||||
| } | } | ||||
| if (!strcmp(key, "SYSLOG_ENABLED")) { | |||||
| if (seen & (1u << 19)) goto invalid; | |||||
| seen |= 1u << 19; | |||||
| if (!strcmp(value, "yes")) c->syslog_enabled = 1; | |||||
| else if (!strcmp(value, "no")) c->syslog_enabled = 0; | |||||
| else goto invalid; | |||||
| continue; | |||||
| } | |||||
| if (!strcmp(key, "SYSLOG_FACILITY")) { | |||||
| if ((seen & (1u << 20)) || strlen(value) != 6 || | |||||
| memcmp(value, "local", 5) || value[5] < '0' || value[5] > '7') | |||||
| goto invalid; | |||||
| seen |= 1u << 20; c->syslog_facility = value[5] - '0'; continue; | |||||
| } | |||||
| #define OPT(name, field, low, high, bit) \ | #define OPT(name, field, low, high, bit) \ | ||||
| if (!strcmp(key, name)) { \ | if (!strcmp(key, name)) { \ | ||||
| if ((seen & (1u << bit)) || number(value, low, high, &n)) goto invalid; \ | if ((seen & (1u << bit)) || number(value, low, high, &n)) goto invalid; \ | ||||
| @@ -64,16 +64,20 @@ void engine_init(engine_t *e) | |||||
| void engine_gap(engine_t *e) | void engine_gap(engine_t *e) | ||||
| { | { | ||||
| e->low_since = e->critical_since = e->recovery_since = -1; | e->low_since = e->critical_since = e->recovery_since = -1; | ||||
| e->low_samples = 0; e->have_last = 0; e->danger = 0; e->floor = 0; | |||||
| e->state = NORMAL; e->low_samples = 0; e->have_last = 0; | |||||
| e->danger = 0; e->floor = 0; | |||||
| } | } | ||||
| void engine_step(engine_t *e, const config_t *c, const sample_t *s, | void engine_step(engine_t *e, const config_t *c, const sample_t *s, | ||||
| delta_t free_d5, delta_t physical_swap_d5, delta_t pageout_d5) | delta_t free_d5, delta_t physical_swap_d5, delta_t pageout_d5) | ||||
| { | { | ||||
| int stress, falling, rapid_fall; | |||||
| int stress, falling, rapid_fall, delayed_threshold_jump = 0; | |||||
| enum state desired = NORMAL; | enum state desired = NORMAL; | ||||
| if (e->have_last && (s->at - e->last_at > 2.5 || s->at <= e->last_at)) | |||||
| if (e->have_last && s->at <= e->last_at) | |||||
| engine_gap(e); | engine_gap(e); | ||||
| if (e->have_last && s->at - e->last_at > 1.5 && | |||||
| e->last_free > s->des && s->free <= s->des) | |||||
| delayed_threshold_jump = 1; | |||||
| falling = (free_d5.valid && free_d5.value < 0) || | falling = (free_d5.valid && free_d5.value < 0) || | ||||
| (e->have_last && s->free < e->last_free); | (e->have_last && s->free < e->last_free); | ||||
| rapid_fall = e->have_last && e->last_free > s->free && | rapid_fall = e->have_last && e->last_free > s->free && | ||||
| @@ -90,14 +94,14 @@ void engine_step(engine_t *e, const config_t *c, const sample_t *s, | |||||
| if (s->free < s->des && stress) { | if (s->free < s->des && stress) { | ||||
| if (e->critical_since < 0) e->critical_since = s->at; | if (e->critical_since < 0) e->critical_since = s->at; | ||||
| } else e->critical_since = -1; | } else e->critical_since = -1; | ||||
| if (e->low_since >= 0 && e->low_samples >= 2 && | |||||
| s->at - e->low_since >= c->pre_s) | |||||
| if (e->low_since >= 0 && s->at - e->low_since >= c->pre_s) | |||||
| desired = PRE_PRESSURE; | desired = PRE_PRESSURE; | ||||
| if (e->low_since >= 0 && (s->at - e->low_since >= c->pressure_s || | if (e->low_since >= 0 && (s->at - e->low_since >= c->pressure_s || | ||||
| (e->low_samples >= 3 && rapid_fall))) | (e->low_samples >= 3 && rapid_fall))) | ||||
| desired = PRESSURE; | desired = PRESSURE; | ||||
| if (e->critical_since >= 0 && s->at - e->critical_since >= c->critical_s) | if (e->critical_since >= 0 && s->at - e->critical_since >= c->critical_s) | ||||
| desired = CRITICAL; | desired = CRITICAL; | ||||
| if (delayed_threshold_jump) desired = CRITICAL; | |||||
| if (s->free <= s->min) desired = EMERGENCY; | if (s->free <= s->min) desired = EMERGENCY; | ||||
| if (desired >= PRE_PRESSURE && desired <= EMERGENCY) { | if (desired >= PRE_PRESSURE && desired <= EMERGENCY) { | ||||
| e->recovery_since = -1; | e->recovery_since = -1; | ||||
| @@ -13,7 +13,7 @@ | |||||
| #define CONF_PATH "/opt/custom/etc/o6h-memory-guard.conf" | #define CONF_PATH "/opt/custom/etc/o6h-memory-guard.conf" | ||||
| #define LOG_DIR "/opt/custom/var/log/o6h-memory-guard" | #define LOG_DIR "/opt/custom/var/log/o6h-memory-guard" | ||||
| #define RUN_DIR "/opt/custom/var/run" | #define RUN_DIR "/opt/custom/var/run" | ||||
| #define VERSION "1.0.5" | |||||
| #define VERSION "1.0.6" | |||||
| enum state { NORMAL, PRE_PRESSURE, PRESSURE, CRITICAL, EMERGENCY, RECOVERY }; | enum state { NORMAL, PRE_PRESSURE, PRESSURE, CRITICAL, EMERGENCY, RECOVERY }; | ||||
| enum policy { OBSERVE, ALLOW, PROTECT }; | enum policy { OBSERVE, ALLOW, PROTECT }; | ||||
| @@ -31,6 +31,7 @@ typedef struct { | |||||
| typedef struct { char uuid[37], alias[64]; enum policy policy; } zone_rule_t; | typedef struct { char uuid[37], alias[64]; enum policy policy; } zone_rule_t; | ||||
| typedef struct { | typedef struct { | ||||
| int armed; | int armed; | ||||
| int syslog_enabled, syslog_facility; | |||||
| unsigned pre_s, pressure_s, critical_s, recovery_s, critical_term_s; | unsigned pre_s, pressure_s, critical_s, recovery_s, critical_term_s; | ||||
| unsigned emergency_term_s, floor_kill_delay_s, max_cached_candidate_age_s; | unsigned emergency_term_s, floor_kill_delay_s, max_cached_candidate_age_s; | ||||
| unsigned normal_scan_s, scan_budget_ms, cooldown_s, max_victims; | unsigned normal_scan_s, scan_budget_ms, cooldown_s, max_victims; | ||||
| @@ -98,4 +99,7 @@ int platform_signal(const config_t *, const process_t *, enum action, int, uint6 | |||||
| double monotime(void); | double monotime(void); | ||||
| int secure_file(const char *, int, unsigned); | int secure_file(const char *, int, unsigned); | ||||
| int secure_directory(const char *); | int secure_directory(const char *); | ||||
| int platform_syslog_open(const char *, int); | |||||
| int platform_syslog_write(int, const char *); | |||||
| void platform_syslog_close(void); | |||||
| #endif | #endif | ||||
| @@ -11,6 +11,7 @@ | |||||
| #include <errno.h> | #include <errno.h> | ||||
| #include <string.h> | #include <string.h> | ||||
| #include <stdlib.h> | #include <stdlib.h> | ||||
| #include <syslog.h> | |||||
| typedef struct { | typedef struct { | ||||
| process_t p; history_t rss; unsigned seen; double last; | process_t p; history_t rss; unsigned seen; double last; | ||||
| @@ -58,10 +59,20 @@ static unsigned scan_generation; | |||||
| static double scan_at, latest_complete_scan_at, started; | static double scan_at, latest_complete_scan_at, started; | ||||
| static int scan_complete; | static int scan_complete; | ||||
| static int logfd = -1, log_ok = 1, lockfd = -1; | static int logfd = -1, log_ok = 1, lockfd = -1; | ||||
| static int syslog_ready, syslog_init_failed; | |||||
| static uint64_t log_bytes; | static uint64_t log_bytes; | ||||
| static volatile sig_atomic_t stopping, reopen_log; | static volatile sig_atomic_t stopping, reopen_log; | ||||
| static void delta_text(char *, size_t, delta_t); | static void delta_text(char *, size_t, delta_t); | ||||
| static void syslog_event(int priority, const char *fmt, ...) | |||||
| { | |||||
| char message[1536]; va_list ap; int n; | |||||
| if (!syslog_ready) return; | |||||
| va_start(ap, fmt); n = vsnprintf(message, sizeof (message), fmt, ap); va_end(ap); | |||||
| if (n < 0 || (size_t)n >= sizeof (message)) return; | |||||
| (void)platform_syslog_write(priority, message); | |||||
| } | |||||
| static void handler(int sig) | static void handler(int sig) | ||||
| { | { | ||||
| if (sig == SIGHUP) reopen_log = 1; | if (sig == SIGHUP) reopen_log = 1; | ||||
| @@ -107,10 +118,59 @@ static int emit(const char *fmt, ...) | |||||
| log_bytes += len; return 0; | log_bytes += len; return 0; | ||||
| failed: | failed: | ||||
| log_ok = 0; | log_ok = 0; | ||||
| syslog_event(LOG_CRIT, "event=internal_error reason=persistent_logging_failed actions=inhibited"); | |||||
| fprintf(stderr, "o6h-memory-guard: persistent logging failed; actions inhibited until restart\n"); | fprintf(stderr, "o6h-memory-guard: persistent logging failed; actions inhibited until restart\n"); | ||||
| return -1; | return -1; | ||||
| } | } | ||||
| static int emit_important(int priority, const char *fmt, ...) | |||||
| { | |||||
| char message[1536]; va_list ap; int n, result; | |||||
| va_start(ap, fmt); n = vsnprintf(message, sizeof (message), fmt, ap); va_end(ap); | |||||
| if (n < 0 || (size_t)n >= sizeof (message)) return -1; | |||||
| result = emit("%s", message); | |||||
| syslog_event(priority, "%s", message); | |||||
| return result; | |||||
| } | |||||
| static int state_priority(enum state state, int floor) | |||||
| { | |||||
| if (floor || state == EMERGENCY) return LOG_CRIT; | |||||
| if (state == CRITICAL) return LOG_ERR; | |||||
| if (state == PRESSURE) return LOG_WARNING; | |||||
| if (state == PRE_PRESSURE) return LOG_NOTICE; | |||||
| return LOG_INFO; | |||||
| } | |||||
| static int transition_message(char *out, size_t cap, enum state from, | |||||
| enum state to, const sample_t *s, unsigned low_samples) | |||||
| { | |||||
| static const char *const skipped_names[] = {"NORMAL", "PRE-PRESSURE", | |||||
| "PRESSURE", "CRITICAL", "EMERGENCY"}; | |||||
| char skipped[128] = ""; size_t used = 0; int n; enum state i; | |||||
| if (from <= EMERGENCY && to <= EMERGENCY && to > from + 1) { | |||||
| for (i = from + 1; i < to; i++) { | |||||
| n = snprintf(skipped + used, sizeof (skipped) - used, "%s%s", | |||||
| used ? "," : "", skipped_names[i]); | |||||
| if (n < 0 || (size_t)n >= sizeof (skipped) - used) return -1; | |||||
| used += (size_t)n; | |||||
| } | |||||
| } | |||||
| n = snprintf(out, cap, "event=state_transition from=%s to=%s free_pages=%" PRIu64 | |||||
| " lotsfree=%" PRIu64 " desfree=%" PRIu64 " minfree=%" PRIu64 | |||||
| " low_samples=%u%s%s", state_name(from), state_name(to), s->free, | |||||
| s->lots, s->des, s->min, low_samples, | |||||
| used ? " reason=threshold_jump skipped_states=" : "", | |||||
| used ? skipped : ""); | |||||
| return n < 0 || (size_t)n >= cap ? -1 : 0; | |||||
| } | |||||
| static void log_sampling_overrun(double late, const sample_t *s) | |||||
| { | |||||
| emit("event=sampling_overrun late_seconds=%.3f state=%s free_pages=%" PRIu64, | |||||
| late, state_name(engine.state), s ? s->free : 0); | |||||
| } | |||||
| static uint64_t saturated_add(uint64_t a, uint64_t b) | static uint64_t saturated_add(uint64_t a, uint64_t b) | ||||
| { | { | ||||
| return b > UINT64_MAX - a ? UINT64_MAX : a + b; | return b > UINT64_MAX - a ? UINT64_MAX : a + b; | ||||
| @@ -409,15 +469,20 @@ static void act(sample_t *sample) | |||||
| return; | return; | ||||
| } | } | ||||
| if (!log_ok) { | if (!log_ok) { | ||||
| emit("event=action_blocked reason=log_failure"); return; | |||||
| emit_important(LOG_WARNING, | |||||
| "event=action_blocked reason=log_failure state=%s", | |||||
| state_name(engine.state)); return; | |||||
| } | } | ||||
| if (cfg.armed && monotime() - started < 60) { | if (cfg.armed && monotime() - started < 60) { | ||||
| emit("event=action_blocked reason=armed_warmup elapsed_seconds=%.1f" | |||||
| " required_seconds=60", monotime() - started); return; | |||||
| emit_important(LOG_WARNING, | |||||
| "event=action_blocked reason=armed_warmup state=%s elapsed_seconds=%.1f" | |||||
| " required_seconds=60", state_name(engine.state), monotime() - started); return; | |||||
| } | } | ||||
| /* O(1) critical path: kstat refresh + cached identity validation, no walk. */ | /* O(1) critical path: kstat refresh + cached identity validation, no walk. */ | ||||
| if (platform_sample(&fresh) || monotime() - fresh.at > 2 || fresh.free >= fresh.des) { | if (platform_sample(&fresh) || monotime() - fresh.at > 2 || fresh.free >= fresh.des) { | ||||
| emit("event=action_blocked reason=refresh_failed_or_above_desfree"); return; | |||||
| emit_important(LOG_WARNING, | |||||
| "event=action_blocked reason=refresh_failed_or_above_desfree state=%s", | |||||
| state_name(engine.state)); return; | |||||
| } | } | ||||
| current_engine = engine; | current_engine = engine; | ||||
| current_engine.floor = fresh.free <= fresh.min / 2; | current_engine.floor = fresh.free <= fresh.min / 2; | ||||
| @@ -428,7 +493,8 @@ retry_candidate: | |||||
| if (controller.has_pending) { | if (controller.has_pending) { | ||||
| plan = action_plan(&controller, &cfg, ¤t_engine, &fresh, NULL); | plan = action_plan(&controller, &cfg, ¤t_engine, &fresh, NULL); | ||||
| if (plan.action == NONE) { | if (plan.action == NONE) { | ||||
| emit("event=action_blocked reason=%s state=%s", plan.reason, | |||||
| emit_important(LOG_WARNING, | |||||
| "event=action_blocked reason=%s state=%s", plan.reason, | |||||
| state_name(current_engine.state)); return; | state_name(current_engine.state)); return; | ||||
| } | } | ||||
| if (platform_signal(&cfg, &plan.target, plan.action, 0, 0)) { | if (platform_signal(&cfg, &plan.target, plan.action, 0, 0)) { | ||||
| @@ -461,7 +527,8 @@ retry_candidate: | |||||
| validated = 1; break; | validated = 1; break; | ||||
| } | } | ||||
| if (!validated) { | if (!validated) { | ||||
| emit("event=action_blocked reason=%s state=%s scan_complete=%d" | |||||
| emit_important(LOG_WARNING, | |||||
| "event=action_blocked reason=%s state=%s scan_complete=%d" | |||||
| " latest_complete_age_ms=%.1f", blocked_reason, | " latest_complete_age_ms=%.1f", blocked_reason, | ||||
| state_name(current_engine.state), scan_complete, | state_name(current_engine.state), scan_complete, | ||||
| latest_complete_scan_at > 0 ? | latest_complete_scan_at > 0 ? | ||||
| @@ -488,6 +555,20 @@ retry_candidate: | |||||
| !strcmp(plan.reason, "floor") ? fresh.min / 2 + 1 : fresh.des); err = errno; | !strcmp(plan.reason, "floor") ? fresh.min / 2 + 1 : fresh.des); err = errno; | ||||
| emit("event=action_result pid=%d signal=%s result=%s errno=%d", plan.target.pid, | emit("event=action_result pid=%d signal=%s result=%s errno=%d", plan.target.pid, | ||||
| plan.action == TERM ? "SIGTERM" : "SIGKILL", rc ? "failed" : "sent", rc ? err : 0); | plan.action == TERM ? "SIGTERM" : "SIGKILL", rc ? "failed" : "sent", rc ? err : 0); | ||||
| syslog_event(plan.action == TERM ? LOG_ERR : LOG_CRIT, | |||||
| "event=action_decision state=%s signal=%s result=%s UUID=%s alias=%s" | |||||
| " pid=%d free_pages=%" PRIu64, | |||||
| state_name(current_engine.state), | |||||
| plan.action == TERM ? "SIGTERM" : "SIGKILL", rc ? "failed" : "sent", | |||||
| plan.target.uuid, alias_for(plan.target.uuid), plan.target.pid, fresh.free); | |||||
| if (!rc) | |||||
| emit_important(plan.action == TERM ? LOG_ERR : LOG_CRIT, | |||||
| "event=signal_sent state=%s signal=%s UUID=%s alias=%s pid=%d" | |||||
| " comm=%s rss_kib=%" PRIu64 " free_pages=%" PRIu64, | |||||
| state_name(current_engine.state), | |||||
| plan.action == TERM ? "SIGTERM" : "SIGKILL", plan.target.uuid, | |||||
| alias_for(plan.target.uuid), plan.target.pid, plan.target.name, | |||||
| plan.target.rss_kib, fresh.free); | |||||
| if (rc) controller.has_pending = 0; | if (rc) controller.has_pending = 0; | ||||
| } | } | ||||
| } | } | ||||
| @@ -576,15 +657,23 @@ int main(int argc, char **argv) | |||||
| platform_fini(); return 0; | platform_fini(); return 0; | ||||
| } | } | ||||
| if (acquire_lock() || secure_directory(LOG_DIR) || log_open()) { perror("lock/log initialization"); return 1; } | if (acquire_lock() || secure_directory(LOG_DIR) || log_open()) { perror("lock/log initialization"); return 1; } | ||||
| if (cfg.syslog_enabled) { | |||||
| if (platform_syslog_open("o6h-memory-guard", cfg.syslog_facility) == 0) | |||||
| syslog_ready = 1; | |||||
| else syslog_init_failed = 1; | |||||
| } | |||||
| memset(&sa, 0, sizeof (sa)); sa.sa_handler = handler; sigemptyset(&sa.sa_mask); | memset(&sa, 0, sizeof (sa)); sa.sa_handler = handler; sigemptyset(&sa.sa_mask); | ||||
| if (sigaction(SIGTERM, &sa, NULL) || sigaction(SIGINT, &sa, NULL) || sigaction(SIGHUP, &sa, NULL)) return 1; | if (sigaction(SIGTERM, &sa, NULL) || sigaction(SIGINT, &sa, NULL) || sigaction(SIGHUP, &sa, NULL)) return 1; | ||||
| engine_init(&engine); started = monotime(); next = started; | engine_init(&engine); started = monotime(); next = started; | ||||
| /* Touch all fixed working storage before allowing armed operation. */ | /* Touch all fixed working storage before allowing armed operation. */ | ||||
| memset(processes, 0, sizeof (processes)); memset(zone_stats, 0, sizeof (zone_stats)); | memset(processes, 0, sizeof (processes)); memset(zone_stats, 0, sizeof (zone_stats)); | ||||
| memset(candidate_cache, 0, sizeof (candidate_cache)); | memset(candidate_cache, 0, sizeof (candidate_cache)); | ||||
| if (emit("event=start version=%s pid=%ld mode=%s page_bytes=%ld fixed_storage_bytes=%zu armed_warmup=60", | |||||
| if (emit_important(LOG_INFO, | |||||
| "event=start version=%s pid=%ld mode=%s page_bytes=%ld fixed_storage_bytes=%zu armed_warmup=60", | |||||
| VERSION, (long)getpid(), cfg.armed ? "armed" : "dry-run", sysconf(_SC_PAGESIZE), | VERSION, (long)getpid(), cfg.armed ? "armed" : "dry-run", sysconf(_SC_PAGESIZE), | ||||
| sizeof (processes) + sizeof (zone_stats) + sizeof (candidate_cache))) return 1; | sizeof (processes) + sizeof (zone_stats) + sizeof (candidate_cache))) return 1; | ||||
| if (syslog_init_failed) | |||||
| emit("event=internal_error reason=syslog_initialization_failed continuation=guard_log_only"); | |||||
| if (readyfd >= 0) { | if (readyfd >= 0) { | ||||
| if (write(readyfd, "R", 1) != 1) return 1; | if (write(readyfd, "R", 1) != 1) return 1; | ||||
| close(readyfd); | close(readyfd); | ||||
| @@ -595,25 +684,31 @@ int main(int argc, char **argv) | |||||
| if (reopen_log) { | if (reopen_log) { | ||||
| reopen_log = 0; | reopen_log = 0; | ||||
| if (logfd >= 0) close(logfd); | if (logfd >= 0) close(logfd); | ||||
| if (log_open()) log_ok = 0; | |||||
| if (log_open()) { | |||||
| log_ok = 0; | |||||
| syslog_event(LOG_CRIT, | |||||
| "event=internal_error reason=log_reopen_failed actions=inhibited"); | |||||
| } | |||||
| emit("event=log_reopen configuration=unchanged"); | emit("event=log_reopen configuration=unchanged"); | ||||
| } | } | ||||
| if (platform_sample(&sample) || monotime() - sample.at > 2) { | if (platform_sample(&sample) || monotime() - sample.at > 2) { | ||||
| int err = errno; | int err = errno; | ||||
| engine_gap(&engine); controller.has_pending = 0; scan_complete = 0; | engine_gap(&engine); controller.has_pending = 0; scan_complete = 0; | ||||
| emit("event=sample_error errno=%d actions=inhibited", err); | emit("event=sample_error errno=%d actions=inhibited", err); | ||||
| syslog_event(LOG_ERR, | |||||
| "event=internal_error reason=sample_error errno=%d actions=inhibited", err); | |||||
| } else { | } else { | ||||
| enum state previous = engine.state; | enum state previous = engine.state; | ||||
| char transition[512] = ""; | |||||
| record_metrics(&sample); | record_metrics(&sample); | ||||
| engine_step(&engine, &cfg, &sample, | engine_step(&engine, &cfg, &sample, | ||||
| history_delta(&metrics[METRIC_FREE], sample.at, 5), | history_delta(&metrics[METRIC_FREE], sample.at, 5), | ||||
| history_delta(&metrics[METRIC_SWAP_PHYSICAL_USED], sample.at, 5), | history_delta(&metrics[METRIC_SWAP_PHYSICAL_USED], sample.at, 5), | ||||
| history_delta(&metrics[METRIC_ANON_PAGEOUT], sample.at, 5)); | history_delta(&metrics[METRIC_ANON_PAGEOUT], sample.at, 5)); | ||||
| if (engine.state != previous) | |||||
| emit("event=state_transition from=%s to=%s free_pages=%" PRIu64 | |||||
| " lotsfree=%" PRIu64 " desfree=%" PRIu64 " minfree=%" PRIu64 | |||||
| " low_samples=%u", state_name(previous), state_name(engine.state), | |||||
| sample.free, sample.lots, sample.des, sample.min, engine.low_samples); | |||||
| if (engine.state != previous && | |||||
| !transition_message(transition, sizeof (transition), previous, | |||||
| engine.state, &sample, engine.low_samples)) | |||||
| emit("%s", transition); | |||||
| log_sample(&sample); | log_sample(&sample); | ||||
| if (previous != RECOVERY && engine.state == RECOVERY) | if (previous != RECOVERY && engine.state == RECOVERY) | ||||
| emit("event=recovery_check free_pages=%" PRIu64 | emit("event=recovery_check free_pages=%" PRIu64 | ||||
| @@ -637,10 +732,23 @@ int main(int argc, char **argv) | |||||
| if (sample.free < sample.lots && !engine.danger) (void)candidate(); | if (sample.free < sample.lots && !engine.danger) (void)candidate(); | ||||
| } | } | ||||
| } | } | ||||
| /* Critical notifications are deferred until after the O(1) action path. */ | |||||
| if (transition[0]) | |||||
| syslog_event(state_priority(engine.state, engine.floor), "%s", transition); | |||||
| if (previous != RECOVERY && engine.state == RECOVERY) | |||||
| syslog_event(LOG_INFO, | |||||
| "event=recovery_check phase=entered free_pages=%" PRIu64 | |||||
| " target=desfree target_pages=%" PRIu64 " reached=%d", | |||||
| sample.free, sample.des, sample.free >= sample.des); | |||||
| if (previous == RECOVERY && engine.state == NORMAL) | |||||
| emit_important(LOG_INFO, | |||||
| "event=recovery_complete state=NORMAL free_pages=%" PRIu64 | |||||
| " lotsfree=%" PRIu64 " stable_seconds=%u", | |||||
| sample.free, sample.lots, cfg.recovery_s); | |||||
| } | } | ||||
| next += 1; | next += 1; | ||||
| if (monotime() > next) { | if (monotime() > next) { | ||||
| emit("event=sampling_overrun late_seconds=%.3f", monotime() - next); | |||||
| log_sampling_overrun(monotime() - next, &sample); | |||||
| next = monotime() + 1; | next = monotime() + 1; | ||||
| } | } | ||||
| while (!stopping && !reopen_log && monotime() < next) { | while (!stopping && !reopen_log && monotime() < next) { | ||||
| @@ -651,6 +759,7 @@ int main(int argc, char **argv) | |||||
| } | } | ||||
| } | } | ||||
| emit("event=stop"); | emit("event=stop"); | ||||
| platform_syslog_close(); syslog_ready = 0; | |||||
| platform_fini(); | platform_fini(); | ||||
| if (logfd >= 0) close(logfd); | if (logfd >= 0) close(logfd); | ||||
| if (lockfd >= 0) close(lockfd); | if (lockfd >= 0) close(lockfd); | ||||
| @@ -8,6 +8,32 @@ | |||||
| #include <stdlib.h> | #include <stdlib.h> | ||||
| #include <errno.h> | #include <errno.h> | ||||
| #include <limits.h> | #include <limits.h> | ||||
| #include <syslog.h> | |||||
| static int syslog_opened; | |||||
| int platform_syslog_open(const char *ident, int facility) | |||||
| { | |||||
| static const int facilities[] = {LOG_LOCAL0, LOG_LOCAL1, LOG_LOCAL2, | |||||
| LOG_LOCAL3, LOG_LOCAL4, LOG_LOCAL5, LOG_LOCAL6, LOG_LOCAL7}; | |||||
| if (!ident || facility < 0 || facility > 7) { errno = EINVAL; return -1; } | |||||
| openlog(ident, LOG_PID | LOG_NDELAY, facilities[facility]); | |||||
| syslog_opened = 1; | |||||
| return 0; | |||||
| } | |||||
| int platform_syslog_write(int priority, const char *message) | |||||
| { | |||||
| if (!syslog_opened || !message) { errno = EINVAL; return -1; } | |||||
| syslog(priority, "%s", message); | |||||
| return 0; | |||||
| } | |||||
| void platform_syslog_close(void) | |||||
| { | |||||
| if (syslog_opened) closelog(); | |||||
| syslog_opened = 0; | |||||
| } | |||||
| double monotime(void) | double monotime(void) | ||||
| { | { | ||||
| @@ -0,0 +1,8 @@ | |||||
| seconds,free_pages,nscan_pages,late_seconds,event | |||||
| 0,79960,0,0.918,low | |||||
| 5,49077,4171921,2.331,emergency | |||||
| 8,48653,4171921,1.890,sigterm | |||||
| 12,48653,4171921,4.459,escalation | |||||
| 14,48653,4171921,0.000,sigkill | |||||
| 15,367019,0,0.000,recovery | |||||
| 30,367019,0,0.000,normal | |||||
| @@ -12,6 +12,8 @@ fi | |||||
| test "$(grep -Fxc ' exec="/opt/custom/bin/o6h-memory-guard --daemon --config /opt/custom/etc/o6h-memory-guard.conf"' "$manifest")" -eq 1 | test "$(grep -Fxc ' exec="/opt/custom/bin/o6h-memory-guard --daemon --config /opt/custom/etc/o6h-memory-guard.conf"' "$manifest")" -eq 1 | ||||
| test "$(grep -Fxc ' <common_name><loctext xml:lang="C">o6h memory pressure guard</loctext></common_name>' "$manifest")" -eq 1 | test "$(grep -Fxc ' <common_name><loctext xml:lang="C">o6h memory pressure guard</loctext></common_name>' "$manifest")" -eq 1 | ||||
| test "$(grep -Fxc 'ACTION_MODE dry-run' "$config")" -eq 1 | test "$(grep -Fxc 'ACTION_MODE dry-run' "$config")" -eq 1 | ||||
| test "$(grep -Fxc 'SYSLOG_ENABLED yes' "$config")" -eq 1 | |||||
| test "$(grep -Fxc 'SYSLOG_FACILITY local5' "$config")" -eq 1 | |||||
| while IFS= read -r setting; do | while IFS= read -r setting; do | ||||
| test "$(grep -Fxc "$setting" "$config")" -eq 1 | test "$(grep -Fxc "$setting" "$config")" -eq 1 | ||||
| @@ -31,4 +33,11 @@ MAX_FLOOR_VICTIMS_EPISODE 12 | |||||
| EOF | EOF | ||||
| grep -Fq -- '"--force-dry-run"' src/main.c | grep -Fq -- '"--force-dry-run"' src/main.c | ||||
| grep -Fq 'openlog(ident, LOG_PID | LOG_NDELAY' src/support.c | |||||
| grep -Fq 'syslog(priority, "%s", message)' src/support.c | |||||
| grep -Fq 'closelog()' src/support.c | |||||
| if grep -Eq '(system|popen|execl|execv)[[:space:]]*\(' src/support.c; then | |||||
| echo 'FAIL syslog backend must not invoke commands or a shell' >&2 | |||||
| exit 1 | |||||
| fi | |||||
| echo 'PASS distribution defaults to ACTION_MODE dry-run; production SMF does not force it' | echo 'PASS distribution defaults to ACTION_MODE dry-run; production SMF does not force it' | ||||
| @@ -47,6 +47,15 @@ static void configs(void) | |||||
| c.pressure_s == 2 && c.max_cached_candidate_age_s == 15 && | c.pressure_s == 2 && c.max_cached_candidate_age_s == 15 && | ||||
| c.max_emergency_victims == 8 && c.max_floor_victims == 12); | c.max_emergency_victims == 8 && c.max_floor_victims == 12); | ||||
| CHECK(parse("ACTION_MODE dry-run\nprotect_process postgres\n", &c) == 0); | CHECK(parse("ACTION_MODE dry-run\nprotect_process postgres\n", &c) == 0); | ||||
| CHECK(c.syslog_enabled && c.syslog_facility == 5); | |||||
| CHECK(parse("SYSLOG_ENABLED no\nSYSLOG_FACILITY local0\n", &c) == 0 && | |||||
| !c.syslog_enabled && c.syslog_facility == 0); | |||||
| CHECK(parse("SYSLOG_ENABLED yes\nSYSLOG_FACILITY local7\n", &c) == 0 && | |||||
| c.syslog_enabled && c.syslog_facility == 7); | |||||
| CHECK(parse("SYSLOG_ENABLED maybe\n", &c) != 0); | |||||
| CHECK(parse("SYSLOG_FACILITY daemon\n", &c) != 0); | |||||
| CHECK(parse("SYSLOG_FACILITY local8\n", &c) != 0); | |||||
| CHECK(parse("SYSLOG_FACILITY local5\nSYSLOG_FACILITY local6\n", &c) != 0); | |||||
| CHECK(parse("ACTION_MODE armd\n", &c) != 0); | CHECK(parse("ACTION_MODE armd\n", &c) != 0); | ||||
| CHECK(parse("ACTION_MODE armed\n", &c) != 0); | CHECK(parse("ACTION_MODE armed\n", &c) != 0); | ||||
| CHECK(parse("ACTION_MODE dry-run\nACTION_MODE armed\n", &c) != 0); | CHECK(parse("ACTION_MODE dry-run\nACTION_MODE armed\n", &c) != 0); | ||||
| @@ -131,8 +140,9 @@ static void states(void) | |||||
| step(&e, &c, 11, 100000, 0); CHECK(e.state == PRE_PRESSURE); | step(&e, &c, 11, 100000, 0); CHECK(e.state == PRE_PRESSURE); | ||||
| step(&e, &c, 12, 100000, 0); | step(&e, &c, 12, 100000, 0); | ||||
| CHECK(e.state == PRESSURE && !e.danger); | CHECK(e.state == PRESSURE && !e.danger); | ||||
| step(&e, &c, 21, 60000, 1); step(&e, &c, 22, 59000, 1); | |||||
| CHECK(!e.danger); | |||||
| step(&e, &c, 21, 60000, 1); | |||||
| CHECK(e.state == CRITICAL && e.danger); /* delayed threshold jump */ | |||||
| step(&e, &c, 22, 59000, 1); CHECK(e.danger); | |||||
| step(&e, &c, 23, 58000, 1); CHECK(e.state == CRITICAL && e.danger); | step(&e, &c, 23, 58000, 1); CHECK(e.state == CRITICAL && e.danger); | ||||
| step(&e, &c, 24, 140000, 0); CHECK(e.state == RECOVERY && !e.danger); | step(&e, &c, 24, 140000, 0); CHECK(e.state == RECOVERY && !e.danger); | ||||
| for (i = 25; i <= 39; i++) step(&e, &c, i, 140000, 0); | for (i = 25; i <= 39; i++) step(&e, &c, i, 140000, 0); | ||||
| @@ -147,9 +157,16 @@ static void states(void) | |||||
| CHECK(!e.danger); /* low but stable, no scanner */ | CHECK(!e.danger); /* low but stable, no scanner */ | ||||
| engine_init(&e); | engine_init(&e); | ||||
| step(&e, &c, 0, 60000, 1); step(&e, &c, 20, 59000, 1); | step(&e, &c, 0, 60000, 1); step(&e, &c, 20, 59000, 1); | ||||
| CHECK(!e.danger); /* gaps do not count as sustained samples */ | |||||
| CHECK(e.danger); /* monotonic elapsed time survives delayed sampling */ | |||||
| engine_gap(&e); step(&e, &c, 21, 58000, 1); CHECK(!e.danger); | engine_gap(&e); step(&e, &c, 21, 58000, 1); CHECK(!e.danger); | ||||
| step(&e, &c, 22, 57000, 1); step(&e, &c, 23, 56000, 1); CHECK(e.danger); | step(&e, &c, 22, 57000, 1); step(&e, &c, 23, 56000, 1); CHECK(e.danger); | ||||
| engine_init(&e); | |||||
| step(&e, &c, 0.0, 150000, 0); | |||||
| step(&e, &c, 1.8, 100000, 0); CHECK(e.state == NORMAL); | |||||
| step(&e, &c, 4.2, 95000, 0); CHECK(e.state == PRESSURE && !e.danger); | |||||
| engine_init(&e); | |||||
| step(&e, &c, 0.0, 150000, 0); | |||||
| step(&e, &c, 3.1, 65000, 1); CHECK(e.state == CRITICAL && e.danger); | |||||
| { | { | ||||
| sample_t s = sample(1, 60000, 0); | sample_t s = sample(1, 60000, 0); | ||||
| delta_t none = {0, 0, 0}, rising = {1, 5, 4096}; | delta_t none = {0, 0, 0}, rising = {1, 5, 4096}; | ||||
| @@ -167,7 +184,26 @@ static void states(void) | |||||
| } | } | ||||
| CHECK(e.state == CRITICAL && e.danger); | CHECK(e.state == CRITICAL && e.danger); | ||||
| } | } | ||||
| puts("PASS all six states, corroboration, hysteresis, recovery and sampling gaps"); | |||||
| puts("PASS all six states, monotonic overruns, threshold jumps, corroboration and recovery"); | |||||
| } | |||||
| static void successful_avoidance_fixture(void) | |||||
| { | |||||
| config_t c = allowed(); engine_t e; FILE *f; char line[256], event[64]; | |||||
| double at, late; uint64_t free_pages, nscan; unsigned rows = 0; | |||||
| engine_init(&e); | |||||
| f = fopen("tests/fixtures/successful_pageout_deadman_avoidance_2026_09_21.csv", "r"); | |||||
| CHECK(f != NULL); CHECK(fgets(line, sizeof (line), f) != NULL); | |||||
| while (fscanf(f, "%lf,%" SCNu64 ",%" SCNu64 ",%lf,%63s", | |||||
| &at, &free_pages, &nscan, &late, event) == 5) { | |||||
| step(&e, &c, at, free_pages, nscan); rows++; | |||||
| CHECK(late >= 0.0); | |||||
| if (!strcmp(event, "emergency")) CHECK(e.state == EMERGENCY && e.danger); | |||||
| if (!strcmp(event, "recovery")) CHECK(e.state == RECOVERY && !e.danger); | |||||
| if (!strcmp(event, "normal")) CHECK(e.state == NORMAL && !e.danger); | |||||
| } | |||||
| fclose(f); CHECK(rows == 7); CHECK(e.state == NORMAL); | |||||
| puts("PASS successful_pageout_deadman_avoidance_2026_09_21 incident fixture"); | |||||
| } | } | ||||
| static void real_incident_fixture(void) | static void real_incident_fixture(void) | ||||
| { | { | ||||
| @@ -251,7 +287,8 @@ static void actions(void) | |||||
| } | } | ||||
| int main(void) | int main(void) | ||||
| { | { | ||||
| configs(); protections(); histories(); states(); real_incident_fixture(); actions(); | |||||
| configs(); protections(); histories(); states(); real_incident_fixture(); | |||||
| successful_avoidance_fixture(); actions(); | |||||
| printf("PASS %u checks; no native backend linked, no signals sent\n", checks); | printf("PASS %u checks; no native backend linked, no signals sent\n", checks); | ||||
| return 0; | return 0; | ||||
| } | } | ||||
| @@ -8,6 +8,11 @@ static sample_t fake_sample; | |||||
| static process_t fixtures[32]; | static process_t fixtures[32]; | ||||
| static unsigned nfixtures, real_requests, validation_requests, walk_requests, checks; | static unsigned nfixtures, real_requests, validation_requests, walk_requests, checks; | ||||
| static int fail_validation, fail_sample, partial, invalid_pid; | static int fail_validation, fail_sample, partial, invalid_pid; | ||||
| typedef struct { int priority; char message[1536]; } syslog_record_t; | |||||
| static syslog_record_t syslog_records[64]; | |||||
| static unsigned syslog_count, syslog_open_count, syslog_close_count; | |||||
| static int syslog_facility, fail_syslog; | |||||
| static char syslog_ident[64]; | |||||
| #define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL runtime line %d: %s\n", __LINE__, #x); exit(1); } checks++; } while (0) | #define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL runtime line %d: %s\n", __LINE__, #x); exit(1); } checks++; } while (0) | ||||
| double monotime(void) { return fake_now; } | double monotime(void) { return fake_now; } | ||||
| @@ -16,6 +21,23 @@ int secure_file(const char *p, int flags, unsigned mode) | |||||
| int secure_directory(const char *p) { (void)p; return -1; } | int secure_directory(const char *p) { (void)p; return -1; } | ||||
| int platform_init(void) { return 0; } | int platform_init(void) { return 0; } | ||||
| void platform_fini(void) { } | void platform_fini(void) { } | ||||
| int platform_syslog_open(const char *ident, int facility) | |||||
| { | |||||
| syslog_open_count++; syslog_facility = facility; | |||||
| snprintf(syslog_ident, sizeof (syslog_ident), "%s", ident); | |||||
| return fail_syslog ? -1 : 0; | |||||
| } | |||||
| int platform_syslog_write(int priority, const char *message) | |||||
| { | |||||
| if (fail_syslog) { errno = EIO; return -1; } | |||||
| CHECK(syslog_count < sizeof (syslog_records) / sizeof (syslog_records[0])); | |||||
| syslog_records[syslog_count].priority = priority; | |||||
| snprintf(syslog_records[syslog_count].message, | |||||
| sizeof (syslog_records[syslog_count].message), "%s", message); | |||||
| syslog_count++; | |||||
| return 0; | |||||
| } | |||||
| void platform_syslog_close(void) { syslog_close_count++; } | |||||
| int platform_sample(sample_t *s) | int platform_sample(sample_t *s) | ||||
| { *s = fake_sample; s->at = fake_now; return fail_sample ? -1 : 0; } | { *s = fake_sample; s->at = fake_now; return fail_sample ? -1 : 0; } | ||||
| int platform_walk(int (*fn)(const process_t *, void *), void *arg, unsigned budget) | int platform_walk(int (*fn)(const process_t *, void *), void *arg, unsigned budget) | ||||
| @@ -52,6 +74,9 @@ static void reset(void) | |||||
| memset(&controller, 0, sizeof (controller)); memset(fixtures, 0, sizeof (fixtures)); | memset(&controller, 0, sizeof (controller)); memset(fixtures, 0, sizeof (fixtures)); | ||||
| engine_init(&engine); engine.state = CRITICAL; engine.danger = 1; | engine_init(&engine); engine.state = CRITICAL; engine.danger = 1; | ||||
| stopping = 0; started = 0; log_ok = 1; log_bytes = 0; | stopping = 0; started = 0; log_ok = 1; log_bytes = 0; | ||||
| syslog_ready = syslog_init_failed = 0; | |||||
| syslog_count = syslog_open_count = syslog_close_count = 0; | |||||
| syslog_facility = -1; fail_syslog = 0; syslog_ident[0] = 0; | |||||
| scan_generation = 0; scan_complete = 0; latest_complete_scan_at = 0; | scan_generation = 0; scan_complete = 0; latest_complete_scan_at = 0; | ||||
| fake_now = 100; partial = fail_sample = fail_validation = invalid_pid = 0; | fake_now = 100; partial = fail_sample = fail_validation = invalid_pid = 0; | ||||
| real_requests = validation_requests = walk_requests = 0; | real_requests = validation_requests = walk_requests = 0; | ||||
| @@ -279,6 +304,64 @@ int main(void) | |||||
| act(&fake_sample); | act(&fake_sample); | ||||
| CHECK(controller.has_pending && !same_process(&controller.pending, &candidate_cache[0].p)); | CHECK(controller.has_pending && !same_process(&controller.pending, &candidate_cache[0].p)); | ||||
| puts("PASS PID/start-time reuse rejects rank 1 and selects cached fallback"); | puts("PASS PID/start-time reuse rejects rank 1 and selects cached fallback"); | ||||
| reset(); | |||||
| CHECK(platform_syslog_open("o6h-memory-guard", cfg.syslog_facility) == 0); | |||||
| syslog_ready = 1; | |||||
| CHECK(!strcmp(syslog_ident, "o6h-memory-guard") && syslog_facility == 5 && | |||||
| syslog_open_count == 1); | |||||
| emit_important(LOG_INFO, "event=start version=%s mode=dry-run", VERSION); | |||||
| CHECK(syslog_count == 1 && syslog_records[0].priority == LOG_INFO && | |||||
| strstr(syslog_records[0].message, "event=start version=1.0.6") != NULL); | |||||
| log_sample(&fake_sample); scan_processes(0); | |||||
| CHECK(syslog_count == 1); /* High-volume sample/delta/proc/cache events stay local. */ | |||||
| { | |||||
| char message[512]; sample_t s = fake_sample; | |||||
| s.free = s.min; | |||||
| CHECK(!transition_message(message, sizeof (message), NORMAL, EMERGENCY, &s, 1)); | |||||
| CHECK(strstr(message, "reason=threshold_jump") != NULL); | |||||
| CHECK(strstr(message, "skipped_states=PRE-PRESSURE,PRESSURE,CRITICAL") != NULL); | |||||
| syslog_event(state_priority(EMERGENCY, 0), "%s", message); | |||||
| CHECK(syslog_count == 2 && syslog_records[1].priority == LOG_CRIT); | |||||
| } | |||||
| cfg.armed = 0; act(&fake_sample); | |||||
| CHECK(syslog_count == 2 && real_requests == 0); | |||||
| reset(); cfg.armed = 1; started = 80; fake_now = 100; | |||||
| CHECK(platform_syslog_open("o6h-memory-guard", cfg.syslog_facility) == 0); | |||||
| syslog_ready = 1; act(&fake_sample); | |||||
| CHECK(real_requests == 0 && syslog_count == 1 && | |||||
| syslog_records[0].priority == LOG_WARNING && | |||||
| strstr(syslog_records[0].message, "event=action_blocked reason=armed_warmup") != NULL); | |||||
| reset(); cfg.armed = 1; | |||||
| CHECK(platform_syslog_open("o6h-memory-guard", cfg.syslog_facility) == 0); | |||||
| syslog_ready = 1; act(&fake_sample); | |||||
| CHECK(real_requests == 1 && syslog_count == 2); | |||||
| CHECK(syslog_records[0].priority == LOG_ERR && | |||||
| strstr(syslog_records[0].message, "event=action_decision state=CRITICAL") != NULL && | |||||
| strstr(syslog_records[0].message, "result=sent") != NULL); | |||||
| CHECK(syslog_records[1].priority == LOG_ERR && | |||||
| strstr(syslog_records[1].message, "event=signal_sent state=CRITICAL") != NULL && | |||||
| strstr(syslog_records[1].message, "signal=SIGTERM") != NULL && | |||||
| strstr(syslog_records[1].message, "UUID=") != NULL && | |||||
| strstr(syslog_records[1].message, "alias=web-a") != NULL && | |||||
| strstr(syslog_records[1].message, "pid=123") != NULL && | |||||
| strstr(syslog_records[1].message, "comm=php-fpm") != NULL && | |||||
| strstr(syslog_records[1].message, "rss_kib=100000") != NULL && | |||||
| strstr(syslog_records[1].message, "free_pages=60000") != NULL); | |||||
| reset(); cfg.armed = 1; fail_syslog = 1; syslog_ready = 1; | |||||
| act(&fake_sample); CHECK(real_requests == 1 && controller.has_pending); | |||||
| reset(); cfg.syslog_enabled = 0; syslog_ready = 0; | |||||
| emit_important(LOG_INFO, "event=start disabled_test=yes"); CHECK(syslog_count == 0); | |||||
| CHECK(state_priority(PRE_PRESSURE, 0) == LOG_NOTICE); | |||||
| CHECK(state_priority(PRESSURE, 0) == LOG_WARNING); | |||||
| CHECK(state_priority(CRITICAL, 0) == LOG_ERR); | |||||
| CHECK(state_priority(EMERGENCY, 0) == LOG_CRIT); | |||||
| CHECK(state_priority(RECOVERY, 0) == LOG_INFO); | |||||
| CHECK(state_priority(NORMAL, 1) == LOG_CRIT); | |||||
| log_sampling_overrun(4.459, &fake_sample); | |||||
| CHECK(fflush(log) == 0 && fseek(log, 0, SEEK_SET) == 0); | |||||
| n = fread(contents, 1, sizeof (contents) - 1, log); contents[n] = 0; | |||||
| CHECK(strstr(contents, "event=sampling_overrun late_seconds=4.459 state=CRITICAL free_pages=60000") != NULL); | |||||
| puts("PASS selective native syslog ident/facility/severity, exclusions, signal ordering, disable and failure isolation"); | |||||
| fclose(log); | fclose(log); | ||||
| printf("PASS %u runtime checks; all platform calls mocked, no signals sent\n", checks); | printf("PASS %u runtime checks; all platform calls mocked, no signals sent\n", checks); | ||||
| return 0; | return 0; | ||||