Compare commits
9
Commits
fase-7
...
drill-offline
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5a6918dae | ||
|
|
a77aa1b7eb | ||
|
|
63ae9d580a | ||
|
|
a66e3439d8 | ||
|
|
74809068af | ||
|
|
73f2345047 | ||
|
|
6ea303e1dc | ||
|
|
72f4cbe0a5 | ||
|
|
0a9a8a38ec |
No files matched your search
+12
-2
@@ -23,10 +23,16 @@ jobs:
|
||||
POSTGRES_DB: anubis
|
||||
POSTGRES_USER: anubis
|
||||
POSTGRES_PASSWORD: anubis-ci
|
||||
# A throwaway server on a slow disk: without syncs to disk, the checkpoint that every DROP DATABASE of the
|
||||
# tests forces takes milliseconds instead of up to 37 seconds (ADR 0015). Never for a real database.
|
||||
POSTGRES_INITDB_ARGS: "--no-sync -c fsync=off -c synchronous_commit=off -c full_page_writes=off"
|
||||
# --init and a pg_isready that gives up before Docker does (ADR 0015, issue #98). Without them a health
|
||||
# check that outlives its timeout leaves pg_isready to PostgreSQL as PID 1, and its exit restarts the server.
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U anubis -d anubis"
|
||||
--init
|
||||
--health-cmd "pg_isready -U anubis -d anubis -t 5"
|
||||
--health-interval 3s
|
||||
--health-timeout 3s
|
||||
--health-timeout 15s
|
||||
--health-retries 20
|
||||
env:
|
||||
ANUBIS_TEST_DB: ${{ matrix.db }}
|
||||
@@ -45,6 +51,10 @@ jobs:
|
||||
git checkout -q FETCH_HEAD
|
||||
- name: Check
|
||||
run: sh ./tasks.sh check
|
||||
# The log of the PostgreSQL service, read through the Docker socket the runner mounts in the job (issue #98).
|
||||
- name: PostgreSQL log
|
||||
if: always() && matrix.db == 'postgres'
|
||||
run: sh ./tasks.sh ci-service-log postgres
|
||||
|
||||
image:
|
||||
needs: test
|
||||
|
||||
+5
-2
@@ -31,6 +31,9 @@ services:
|
||||
|
||||
postgres:
|
||||
image: postgres:18
|
||||
# An init as PID 1 and a pg_isready that gives up before Docker does (ADR 0015): otherwise a slow health check
|
||||
# leaves pg_isready to PostgreSQL, and its exit makes the server restart every connection.
|
||||
init: true
|
||||
environment:
|
||||
POSTGRES_DB: anubis
|
||||
POSTGRES_USER: anubis
|
||||
@@ -38,9 +41,9 @@ services:
|
||||
ports:
|
||||
- "127.0.0.1:55432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U anubis -d anubis"]
|
||||
test: ["CMD-SHELL", "pg_isready -U anubis -d anubis -t 5"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
timeout: 15s
|
||||
retries: 20
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# 0015 — PostgreSQL nei container con un processo init; nella CI, senza sincronizzazioni su disco
|
||||
|
||||
Data: 2026-11-15 · Stato: accettata · Precisa la CI (SPEC 15.5, ADR 0007) e il `docker-compose.yml` di sviluppo, issue #98, senza componenti esterni nuovi
|
||||
|
||||
## Contesto
|
||||
|
||||
Dal 14 novembre 2026 il lavoro `test (postgres)` della CI falliva spesso, ma non sempre. Dopo uno-cinque minuti di test, il PostgreSQL di servizio chiudeva tutte le connessioni. I test rimasti fallivano con `57P03: the database system is in recovery mode` o con `EndOfStreamException`. Rilanciando il lavoro passava. In locale la suite passava sempre.
|
||||
|
||||
Il registro del lavoro non mostrava quello del server. Per vederlo, la CI ora stampa a fine lavoro registro, stato e memoria del contenitore PostgreSQL (`tasks ci-service-log`). Li legge dal socket di Docker che l'esecutore monta nel lavoro, senza il client `docker` né altro da installare.
|
||||
|
||||
In una prova con la suite ripetuta tre volte sullo stesso server, il server si è riavviato quattro volte. Ogni volta il registro dice la stessa cosa:
|
||||
|
||||
```
|
||||
LOG: untracked child process (PID 248) exited with exit code 2
|
||||
LOG: terminating any other active server processes
|
||||
LOG: all server processes terminated; reinitializing
|
||||
```
|
||||
|
||||
Nessun processo ucciso per memoria (`OOMKilled false`, nessun evento `oom` di Docker) e nessun segnale. Il processo "sconosciuto" che esce con codice 2 è `pg_isready`. Il codice 2 vuol dire "il server non ha risposto".
|
||||
|
||||
Che cosa succede:
|
||||
1. Docker esegue il controllo di salute dentro il contenitore come `/bin/sh -c "pg_isready …"`.
|
||||
2. Sull'esecutore di Unraid il disco è lento. Ogni `DROP DATABASE` dei test forza un checkpoint immediato, con fino a 21 secondi di scrittura sul disco. In quei momenti il server può metterci più di 3 secondi a rispondere.
|
||||
3. Passato il tempo massimo del controllo (`--health-timeout 3s`), Docker chiude la shell. `pg_isready` resta senza genitore e il sistema lo affida al processo 1 del contenitore. L'immagine `postgres` non ha un processo init, quindi il processo 1 è PostgreSQL stesso.
|
||||
4. Quando `pg_isready` si arrende ed esce, PostgreSQL vede morire un figlio che non conosce. Per prudenza lo tratta come un suo processo andato in crash: chiude tutte le connessioni e rifà il recupero dal registro delle scritture.
|
||||
|
||||
Spiega anche gli altri indizi:
|
||||
- capita solo a volte, perché serve un server lento proprio mentre scade il controllo;
|
||||
- si vede da quando la suite è cresciuta con il commit della raccolta dei dati (issue #95), cioè più database creati e cancellati;
|
||||
- in locale non capita, perché il disco è veloce.
|
||||
|
||||
Non c'entrano la memoria, `/dev/shm` (64 MiB, il server ne usa poco) e `pg_database_size` del campionatore. Il `CREATE`/`DROP DATABASE` dei test rende il server lento, ma da solo non lo fa ripartire.
|
||||
|
||||
**Seconda causa, vista dopo la prima correzione.** In un'esecuzione con la correzione il server non è più ripartito, ma 7 test sono falliti lo stesso:
|
||||
- `Timeout during reading attempt` dopo circa 1 minuto e 18 secondi;
|
||||
- `/primo-avvio?errore=database` nel test del primo avvio desktop, lo stesso errore visto il 14 novembre nell'esecuzione 304.
|
||||
|
||||
Il registro del server mostra il motivo:
|
||||
- ogni `DROP DATABASE` forza un checkpoint immediato, e i checkpoint passano uno alla volta;
|
||||
- sul disco dell'esecutore la sola sincronizzazione su disco ha richiesto fino a 37 secondi (`sync=36.849 s`);
|
||||
- i `DROP DATABASE` in coda hanno superato i 30 secondi di attesa del client (`canceling statement due to user request`);
|
||||
- il test desktop non ha avuto la connessione nei 5 secondi dell'applicazione.
|
||||
|
||||
Il server era vivo, ma fermo ad aspettare il disco.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Un processo init davanti a PostgreSQL.** Il servizio `postgres` della CI parte con `--init`, e quello di `docker-compose.yml` con `init: true`. Il processo 1 diventa il piccolo init di Docker: raccoglie lui i processi rimasti senza genitore, e PostgreSQL non li vede più.
|
||||
2. **`pg_isready` si arrende prima di Docker.** Il controllo è `pg_isready -U anubis -d anubis -t 5` con `--health-timeout 15s`. Così Docker non chiude mai la shell mentre `pg_isready` sta ancora aspettando. L'intervallo resta di 3 secondi, quindi l'avvio non rallenta.
|
||||
3. **Nella CI il PostgreSQL dei test non sincronizza su disco.** Il servizio nasce con `POSTGRES_INITDB_ARGS: "--no-sync -c fsync=off -c synchronous_commit=off -c full_page_writes=off"` (l'opzione `-c` di `initdb` esiste da PostgreSQL 16). Così il checkpoint forzato da ogni `DROP DATABASE` scrive solo nella memoria del sistema e dura millisecondi. È ammesso solo perché quel server vive per un lavoro e poi si butta. Non vale per `docker-compose.yml` né per nessun database vero: lì un'interruzione di corrente senza `fsync` può rovinare i dati.
|
||||
4. **Il registro del server resta nella CI.** Il passo `PostgreSQL log` gira sempre a fine lavoro `test (postgres)`. Mostra anche se l'init è attivo e com'è il controllo di salute. Il prossimo problema del server si legge lì, senza rilanciare alla cieca.
|
||||
|
||||
Le misure 1 e 2 si coprono a vicenda: ognuna da sola basta a togliere la prima causa. La 3 toglie la seconda, e rende anche più raro un controllo di salute lento.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Il lavoro `test (postgres)` non perde più il server a metà. Rilanciarlo per farlo passare nascondeva la causa, e ora non serve più.
|
||||
- Nessun test e nessuna parte di Anubis cambia: il difetto era nel modo in cui gira il contenitore, non nel bot.
|
||||
- I test su PostgreSQL nella CI non provano la durata dei dati dopo un'interruzione. Non lo facevano neanche prima: quella è una proprietà di PostgreSQL, non di Anubis.
|
||||
- **Per l'installazione su Unraid:** se il PostgreSQL che usa Anubis gira in un container con un controllo di salute basato su `pg_isready` e senza init, ha lo stesso rischio sotto carico. Il rimedio è lo stesso: l'opzione `--init` (in Unraid, "Extra Parameters") oppure un controllo con `-t` più breve del suo tempo massimo. Il template `deploy/unraid/anubis.xml` non installa PostgreSQL, quindi lì non cambia niente.
|
||||
@@ -0,0 +1,35 @@
|
||||
# 0016 — Il motore dell'esercitazione della guardia non esce dal computer
|
||||
|
||||
Data: 2026-11-16 · Stato: accettata · Precisa l'ADR 0012 (punto 5), issue #102, senza componenti esterni nuovi
|
||||
|
||||
## Contesto
|
||||
|
||||
L'esercitazione della guardia (`Anubis.Guard drill`, nell'immagine `anubis drill`, e il test `TheGuardDrillPassesWithTheRealEngineAsChildProcess`) avvia il motore vero come processo figlio. L'ADR 0012 dice che i prezzi vengono da un finto OKX locale (`ANUBIS_DRILL_OKX_URL`, solo su indirizzi loopback). La documentazione della prova aggiunge che dal computer non esce nulla.
|
||||
|
||||
Dalla Fase 7 non era più vero. Il motore della prova faceva il suo lavoro normale anche sul resto della rete:
|
||||
- la lettura delle notizie ogni 2 minuti, sui feed RSS veri (ANSA, CNBC, CoinDesk e gli altri);
|
||||
- lo scaricamento del modello ONNX del tono da Hugging Face;
|
||||
- e, già da prima, i cambi della BCE, l'umore del mercato, il calendario economico e gli archivi di Binance.
|
||||
|
||||
Si vede nella CI, esecuzione 331, lavoro 1122: righe "News from ANSA…" e "News classifier ready" dal motore della prova. Sull'esecutore lento della CI è lavoro in più proprio mentre la prova misura i tempi del motore.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **La prova si riconosce da sola, senza variabili nuove.** Il motore è nella prova quando gira sotto la guardia e `ANUBIS_DRILL_OKX_URL` punta a un indirizzo locale: le stesse condizioni per cui usa già il finto OKX. Fuori dalla guardia la variabile non conta, come prima.
|
||||
2. **Nella prova la raccolta dei dati non esce dal computer** (`MarketDataService` con `offline`):
|
||||
- il lavoro `notizie` non è in programma;
|
||||
- il modello del tono non si scarica;
|
||||
- tutte le richieste della raccolta passano da `LoopbackOnlyHandler`. Quelle verso il computer stesso (il finto OKX) partono. Le altre ricevono subito, senza partire, una risposta 403 con la frase "Esercitazione della guardia: nessuna richiesta esce dal computer.".
|
||||
3. **Il 403 è una risposta definitiva, non un errore di rete.** Un errore di rete farebbe ripetere la richiesta dopo 2, 4 e 8 secondi. Così invece ogni fonte fallisce subito e lo annota come al solito, e i lavori del motore tengono il loro ritmo.
|
||||
4. **Un ottavo controllo nella prova**, dopo i sette dell'ADR 0012: nessuna notizia letta e nessun file nella cartella `models`. Vale nei test e nell'immagine Docker.
|
||||
5. **Un test senza processi** (`TheDrillsEngineReadsNoNewsAndSendsNothingOutsideLoopback`) costruisce la raccolta dei dati come la costruisce il motore nella prova. Su una rete finta esegue una volta ogni lavoro, un giro dello storico e un giro delle notizie, e controlla:
|
||||
- nessun lavoro `notizie`;
|
||||
- tutte le richieste arrivate alla rete sono verso loopback;
|
||||
- ogni feed è stato provato e fermato;
|
||||
- nessuna notizia e nessun modello.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- La documentazione della prova torna vera per la raccolta dei dati: i prezzi vengono dal finto OKX e il resto non parte. Il motore della prova non ha chiavi né per Alpaca né per Telegram e non riceve l'indirizzo del segnale di vita: neanche quelle parti mandano richieste.
|
||||
- Nel registro della prova compaiono le fonti rifiutate (cambi, umore, calendario, Binance) come fonti che non rispondono. È atteso: nella prova non servono.
|
||||
- Il bot vero non cambia. Senza la guardia, o senza il finto OKX locale, la raccolta dei dati è quella di sempre.
|
||||
@@ -313,9 +313,13 @@ internal sealed partial class AnubisHost(
|
||||
}
|
||||
|
||||
var scheduler = new Scheduler(clock, bus);
|
||||
|
||||
// The guard drill's engine: prices from the drill's local OKX, and then nothing else leaves the computer either
|
||||
// (no news, no model, no other source: ADR 0016). Honored only under a guard, like the drill's OKX itself.
|
||||
var drill = Guard is null ? null : GuardDrill.DrillOkx(environment);
|
||||
_market = MarketDataEnabled
|
||||
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger,
|
||||
Guard is null ? null : GuardDrill.DrillOkx(environment))
|
||||
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger, drill,
|
||||
offline: drill is not null)
|
||||
: null;
|
||||
_trading = TradingEnabled && (identity.File ?? Installation.ReadFile(Config.Data)) is { } file
|
||||
? new TradingService(_db, clock, bus, secrets, _market, new FxStore(_db, clock), TradingConsent.From(Config), file.InstallationId,
|
||||
|
||||
@@ -54,7 +54,7 @@ public sealed partial class MarketDataService : IDisposable
|
||||
private (string Key, string Secret, AlpacaClient Client)? _alpaca;
|
||||
|
||||
public MarketDataService(Database db, IClock clock, EventBus bus, SettingsStore settings, SecretStore secrets, DataDirectory? data,
|
||||
HttpMessageHandler? handler = null, Func<IWebSocketTransport>? sockets = null, ILogger? logger = null, OkxOptions? okx = null)
|
||||
HttpMessageHandler? handler = null, Func<IWebSocketTransport>? sockets = null, ILogger? logger = null, OkxOptions? okx = null, bool offline = false)
|
||||
{
|
||||
_db = db;
|
||||
_clock = clock;
|
||||
@@ -63,13 +63,8 @@ public sealed partial class MarketDataService : IDisposable
|
||||
_data = data;
|
||||
_sockets = sockets;
|
||||
_logger = logger ?? NullLogger.Instance;
|
||||
_http = handler is null
|
||||
? new HttpClient(new SocketsHttpHandler
|
||||
{
|
||||
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
|
||||
AutomaticDecompression = System.Net.DecompressionMethods.All,
|
||||
})
|
||||
: new HttpClient(handler, disposeHandler: false);
|
||||
Offline = offline;
|
||||
_http = Client(handler, offline);
|
||||
_http.Timeout = TimeSpan.FromSeconds(60);
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
|
||||
|
||||
@@ -82,9 +77,15 @@ public sealed partial class MarketDataService : IDisposable
|
||||
_universes = new UniverseStore(db, clock);
|
||||
_builder = new UniverseBuilder(db, clock);
|
||||
_states = new SourceStateStore(db, clock);
|
||||
News = new News.NewsCollector(_http, db, clock, _logger) { ModelFolder = data is null ? null : Path.Combine(data.Root, "models") };
|
||||
News = new News.NewsCollector(_http, db, clock, _logger) { ModelFolder = offline || data is null ? null : Path.Combine(data.Root, "models") };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The guard drill's engine (ADR 0016): no news job, no model to download, and no request leaves the computer;
|
||||
/// prices come from the drill's local OKX.
|
||||
/// </summary>
|
||||
public bool Offline { get; }
|
||||
|
||||
public OkxClient Okx { get; }
|
||||
|
||||
public FreshnessMonitor Freshness { get; }
|
||||
@@ -125,7 +126,7 @@ public sealed partial class MarketDataService : IDisposable
|
||||
RefreshCorporateActionsAsync) { MaxLateness = TimeSpan.FromMinutes(50) },
|
||||
new("dati-pulizia", "Pulizia delle barre al minuto e degli spread vecchi", Schedule.Daily(new TimeOnly(3, 45), Zones.Rome), PruneAsync)
|
||||
{ MaxLateness = TimeSpan.FromHours(12), CatchUpWithin = TimeSpan.FromDays(3650) },
|
||||
News.Job(),
|
||||
.. Offline ? Array.Empty<ScheduledJob>() : [News.Job()],
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
@@ -157,6 +158,24 @@ public sealed partial class MarketDataService : IDisposable
|
||||
_http.Dispose();
|
||||
}
|
||||
|
||||
// The connection pool shared by every source; offline, only this computer's own addresses are reached.
|
||||
private static HttpClient Client(HttpMessageHandler? handler, bool offline)
|
||||
{
|
||||
var owned = handler is null;
|
||||
var network = handler ?? new SocketsHttpHandler
|
||||
{
|
||||
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
|
||||
AutomaticDecompression = System.Net.DecompressionMethods.All,
|
||||
};
|
||||
if (offline)
|
||||
{
|
||||
network = new Supervision.LoopbackOnlyHandler(network, owned);
|
||||
owned = true;
|
||||
}
|
||||
|
||||
return new HttpClient(network, disposeHandler: owned);
|
||||
}
|
||||
|
||||
/// <summary>The Alpaca client with the paper account keys, or null when they are missing.</summary>
|
||||
public async Task<AlpacaClient?> AlpacaAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -21,7 +21,8 @@ public sealed record DrillResult(bool Passed, IReadOnlyList<string> Lines);
|
||||
/// decided; the engine starts with the fault that blocks its main loop right after the sale leaves, with the stop
|
||||
/// removed. The drill passes when the guard intervened, the engine restarted, the sale left open was canceled, the
|
||||
/// stop came back for the whole quantity and the guard's note reached the diary. Prices come from a small local
|
||||
/// server that answers like OKX: nothing leaves the computer. Same drill in the tests and in the Docker image.
|
||||
/// server that answers like OKX, and the engine sends nothing else out (ADR 0016): no news, no model to download,
|
||||
/// any other source refused before it leaves the computer. Same drill in the tests and in the Docker image.
|
||||
/// </summary>
|
||||
public static class GuardDrill
|
||||
{
|
||||
@@ -126,6 +127,12 @@ public static class GuardDrill
|
||||
passed &= Check(stops.Any(q => q == held), $"Lo stop è tornato per tutti i {Format.Quantity(held)} BTC.", "Lo stop non è tornato per l'intera quantità.", Say);
|
||||
passed &= Check(again > 0, "La vendita già decisa è ripartita con un ordine nuovo.", "La vendita già decisa non è ripartita.", Say);
|
||||
passed &= Check(noted > 0, "La nota della guardia è nel diario.", "La nota della guardia non è nel diario.", Say);
|
||||
|
||||
// The engine of the drill stays on this computer (ADR 0016): it reads no news and downloads no model.
|
||||
var news = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_items"), cancellationToken).ConfigureAwait(false);
|
||||
var model = Directory.Exists(data.Models) && Directory.EnumerateFileSystemEntries(data.Models).Any();
|
||||
passed &= Check(news == 0 && !model, "Il motore non ha letto notizie né scaricato il modello: è rimasto sul computer.",
|
||||
$"Il motore è uscito dal computer: {news} notizie lette{(model ? ", modello scaricato" : "")}.", Say);
|
||||
}
|
||||
|
||||
return new DrillResult(passed, lines);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
|
||||
namespace Anubis.Supervision;
|
||||
|
||||
/// <summary>
|
||||
/// The network of the guard drill's engine (ADR 0016): a request to this computer's own addresses (loopback) passes,
|
||||
/// any other is answered here with 403 and never leaves. The answer is final, not a failure to retry, so a job that
|
||||
/// would have gone out fails at once and the engine keeps its usual pace.
|
||||
/// </summary>
|
||||
public sealed class LoopbackOnlyHandler(HttpMessageHandler inner, bool ownsInner) : HttpMessageHandler
|
||||
{
|
||||
public const string Refusal = "Esercitazione della guardia: nessuna richiesta esce dal computer.";
|
||||
|
||||
private readonly HttpMessageInvoker _inner = new(inner, ownsInner);
|
||||
private int _refused;
|
||||
|
||||
/// <summary>How many requests were stopped here.</summary>
|
||||
public int Refused => Volatile.Read(ref _refused);
|
||||
|
||||
public static bool Allowed(Uri? url) => url is { IsAbsoluteUri: true, IsLoopback: true };
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (Allowed(request.RequestUri))
|
||||
{
|
||||
return _inner.SendAsync(request, cancellationToken);
|
||||
}
|
||||
|
||||
Interlocked.Increment(ref _refused);
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Forbidden)
|
||||
{
|
||||
RequestMessage = request,
|
||||
ReasonPhrase = "Forbidden in the guard drill",
|
||||
Content = new StringContent(Refusal, Encoding.UTF8, "text/plain"),
|
||||
});
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_inner.Dispose();
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
@@ -297,6 +297,63 @@ public sealed class GuardTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The drill's engine stays on this computer (issue #102, ADR 0016). Its market data, built as the host builds it
|
||||
/// under a guard with the drill's OKX, has no news job. Every job once, a history round and a news round send
|
||||
/// nothing outside loopback: the news sources were tried and refused before reaching the network, and no model came.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheDrillsEngineReadsNoNewsAndSendsNothingOutsideLoopback()
|
||||
{
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 11, 16, 9, 0, 0, TimeSpan.Zero));
|
||||
var folder = TempFolder.Create("drill-data");
|
||||
try
|
||||
{
|
||||
var data = new Anubis.Platform.DataDirectory(folder);
|
||||
data.Ensure();
|
||||
using var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("""{"code":"0","msg":"","data":[]}"""));
|
||||
var okx = GuardDrill.DrillOkx(new Dictionary<string, string?>(StringComparer.Ordinal) { [GuardDrill.DrillOkxVariable] = "http://127.0.0.1:9/" });
|
||||
Assert.IsNotNull(okx);
|
||||
var bus = new EventBus();
|
||||
using var market = new MarketDataService(test.Db, clock, bus, new SettingsStore(test.Db, clock, bus), new SecretStore(test.Db, clock, new byte[32]), data,
|
||||
network, () => new FakeSocket(), NullLogger.Instance, okx, offline: true);
|
||||
|
||||
var jobs = market.Jobs();
|
||||
Assert.IsFalse(jobs.Any(j => j.Name == Anubis.News.NewsCollector.JobName), "no news job in the drill");
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(2));
|
||||
foreach (var job in jobs)
|
||||
{
|
||||
await job.Run(timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await market.HistoryRoundAsync(timeout.Token).ConfigureAwait(false);
|
||||
|
||||
// The news round pauses a second between two feeds, on the manual clock.
|
||||
var reading = market.News.RunOnceAsync(timeout.Token);
|
||||
while (!reading.IsCompleted)
|
||||
{
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
await Task.Delay(10, _none).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await reading.ConfigureAwait(false);
|
||||
|
||||
var urls = network.Urls.ToList();
|
||||
Assert.IsTrue(urls.Count > 0, "the drill's OKX answers");
|
||||
Assert.IsTrue(urls.All(LoopbackOnlyHandler.Allowed), string.Join(", ", urls.Select(u => u.Host).Distinct()));
|
||||
var sources = await market.News.Store.ListSourcesAsync(_none).ConfigureAwait(false);
|
||||
Assert.IsTrue(sources.Where(s => s.Enabled && s.Kind == Anubis.News.NewsSourceKinds.Rss).All(s => s.Failures > 0), "every feed was stopped here");
|
||||
Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_items"), _none).ConfigureAwait(false));
|
||||
Assert.IsFalse(Directory.EnumerateFileSystemEntries(data.Models).Any(), "no model downloaded");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The same proof with real processes (the drill that also runs in the Docker image): the real guard, the real
|
||||
/// engine as its child, a sale blocked halfway on the internal simulator, then the restart by SPEC 9.4.
|
||||
|
||||
@@ -19,6 +19,7 @@ return command switch
|
||||
"seed-demo" => Run("dotnet", ["run", "--project", "src/Anubis.Server", "-c", "Release", "--", "--demo", .. rest]),
|
||||
"screenshots" => Screenshots(rest),
|
||||
"release-win" => ReleaseWindows(),
|
||||
"ci-service-log" => ServiceLog.Print(rest.Length > 0 ? rest[0] : "postgres"),
|
||||
"desktop-win" => NotYet("desktop-win", 10),
|
||||
_ => Help(),
|
||||
};
|
||||
@@ -237,6 +238,7 @@ int Help()
|
||||
tasks seed-demo avvia la modalità dimostrativa (dati dell'appendice F, database a parte)
|
||||
tasks screenshots fotografa le schermate dimostrative a 1440 e 390 pixel
|
||||
tasks release-win zip di prova per Windows in artifacts/release (ADR 0013)
|
||||
tasks ci-service-log nella CI: registro e memoria del PostgreSQL dei test
|
||||
tasks desktop-win installatore Windows (Fase 10)
|
||||
""");
|
||||
return command == "help" ? 0 : 1;
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
using System.Globalization;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
/// <summary>
|
||||
/// Prints what the CI cannot see from inside the job: the log, state and memory of the service containers next to this
|
||||
/// one (the PostgreSQL of the tests). It talks to the Docker Engine API through the socket the runner mounts in the job
|
||||
/// container, so it needs neither the docker client nor anything else to install (ADR 0004).
|
||||
/// </summary>
|
||||
internal static class ServiceLog
|
||||
{
|
||||
private const string Socket = "/var/run/docker.sock";
|
||||
|
||||
public static int Print(string imagePrefix)
|
||||
{
|
||||
if (!File.Exists(Socket))
|
||||
{
|
||||
Console.WriteLine($"Nessun {Socket}: il registro dei servizi si legge solo nella CI.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
using var http = new HttpClient(new SocketsHttpHandler
|
||||
{
|
||||
ConnectCallback = async (_, token) =>
|
||||
{
|
||||
var socket = new System.Net.Sockets.Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
|
||||
await socket.ConnectAsync(new UnixDomainSocketEndPoint(Socket), token).ConfigureAwait(false);
|
||||
return new NetworkStream(socket, ownsSocket: true);
|
||||
},
|
||||
})
|
||||
{
|
||||
BaseAddress = new Uri("http://docker/"),
|
||||
Timeout = TimeSpan.FromMinutes(2),
|
||||
};
|
||||
|
||||
var info = Json(http, "info");
|
||||
Console.WriteLine($"Host: {info["Name"]}, {info["NCPU"]} CPU, {Mib(info["MemTotal"])} di memoria, kernel {info["KernelVersion"]}");
|
||||
|
||||
var self = Json(http, $"containers/{Uri.EscapeDataString(Environment.MachineName)}/json");
|
||||
var networks = self["NetworkSettings"]?["Networks"]?.AsObject().Select(pair => pair.Key).ToList() ?? [];
|
||||
var found = 0;
|
||||
foreach (var network in networks)
|
||||
{
|
||||
var filter = Uri.EscapeDataString($$"""{"network":["{{network}}"]}""");
|
||||
foreach (var container in Json(http, $"containers/json?all=1&filters={filter}").AsArray())
|
||||
{
|
||||
var image = container?["Image"]?.GetValue<string>() ?? "";
|
||||
if (!image.StartsWith(imagePrefix, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
found++;
|
||||
var id = container!["Id"]!.GetValue<string>();
|
||||
Describe(http, id, image);
|
||||
}
|
||||
}
|
||||
|
||||
if (found == 0)
|
||||
{
|
||||
Console.WriteLine($"Nessun contenitore '{imagePrefix}*' sulle reti {string.Join(", ", networks)}.");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static void Describe(HttpClient http, string id, string image)
|
||||
{
|
||||
var inspect = Json(http, $"containers/{id}/json");
|
||||
var state = inspect["State"];
|
||||
var host = inspect["HostConfig"];
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"== {image} {id[..12]}");
|
||||
Console.WriteLine($"Stato: {state?["Status"]}, avviato {state?["StartedAt"]}, riavvii {inspect["RestartCount"]}, OOMKilled {state?["OOMKilled"]}, uscita {state?["ExitCode"]}");
|
||||
Console.WriteLine($"Limiti: memoria {Mib(host?["Memory"])}, /dev/shm {Mib(host?["ShmSize"])}, init {host?["Init"]?.ToString() ?? "no"}");
|
||||
Console.WriteLine($"Controllo di salute: {inspect["Config"]?["Healthcheck"]?["Test"]?.ToJsonString()}, timeout {(inspect["Config"]?["Healthcheck"]?["Timeout"]?.GetValue<long>() ?? 0) / 1_000_000_000} s");
|
||||
|
||||
if (state?["Running"]?.GetValue<bool>() == true)
|
||||
{
|
||||
var stats = Json(http, $"containers/{id}/stats?stream=false");
|
||||
var memory = stats["memory_stats"];
|
||||
Console.WriteLine($"Memoria ora: {Mib(memory?["usage"])}, limite visto dal contenitore {Mib(memory?["limit"])}, massimo {Mib(memory?["max_usage"])}");
|
||||
}
|
||||
|
||||
// Out-of-memory kills and signals as Docker saw them, from the container's start until now.
|
||||
var since = DateTimeOffset.Parse(state?["StartedAt"]?.GetValue<string>() ?? "", CultureInfo.InvariantCulture).ToUnixTimeSeconds();
|
||||
var until = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
var events = Uri.EscapeDataString($$"""{"container":["{{id}}"]}""");
|
||||
using (var answer = http.GetAsync(new Uri($"events?since={since}&until={until}&filters={events}", UriKind.Relative)).GetAwaiter().GetResult())
|
||||
{
|
||||
answer.EnsureSuccessStatusCode();
|
||||
var lines = answer.Content.ReadAsStringAsync().GetAwaiter().GetResult()
|
||||
.Split('\n', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(line => JsonNode.Parse(line))
|
||||
.Where(e => e?["Action"]?.GetValue<string>() is not { } action
|
||||
|| !(action.StartsWith("exec_", StringComparison.Ordinal) || action == "health_status: healthy"))
|
||||
.Select(e => $" {DateTimeOffset.FromUnixTimeSeconds(e?["time"]?.GetValue<long>() ?? 0):O} {e?["Action"]}")
|
||||
.ToList();
|
||||
Console.WriteLine($"Eventi di Docker: {(lines.Count == 0 ? "nessuno" : "")}");
|
||||
lines.ForEach(Console.WriteLine);
|
||||
}
|
||||
|
||||
Console.WriteLine("-- registro");
|
||||
using var response = http.GetAsync(new Uri($"containers/{id}/logs?stdout=1&stderr=1×tamps=1", UriKind.Relative)).GetAwaiter().GetResult();
|
||||
response.EnsureSuccessStatusCode();
|
||||
var bytes = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
|
||||
var raw = response.Content.Headers.ContentType?.MediaType == "application/vnd.docker.raw-stream";
|
||||
Console.Write(raw ? Encoding.UTF8.GetString(bytes) : Demultiplex(bytes));
|
||||
Console.WriteLine("-- fine del registro");
|
||||
}
|
||||
|
||||
// Without a terminal the log arrives in frames: one byte for the stream, three zeros, four bytes of length.
|
||||
private static string Demultiplex(byte[] bytes)
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
var at = 0;
|
||||
while (at + 8 <= bytes.Length)
|
||||
{
|
||||
var length = (bytes[at + 4] << 24) | (bytes[at + 5] << 16) | (bytes[at + 6] << 8) | bytes[at + 7];
|
||||
var size = Math.Min(length, bytes.Length - at - 8);
|
||||
text.Append(Encoding.UTF8.GetString(bytes, at + 8, size));
|
||||
at += 8 + length;
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static JsonNode Json(HttpClient http, string path)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(path, UriKind.Relative));
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
using var response = http.Send(request);
|
||||
response.EnsureSuccessStatusCode();
|
||||
using var stream = response.Content.ReadAsStream();
|
||||
return JsonNode.Parse(stream) ?? new JsonObject();
|
||||
}
|
||||
|
||||
private static string Mib(JsonNode? bytes)
|
||||
{
|
||||
var value = bytes?.GetValue<long>() ?? 0;
|
||||
return value == 0 ? "nessuno" : (value / 1048576.0).ToString("0", CultureInfo.InvariantCulture) + " MiB";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user