Fase 9 — Rifinitura e consegna in Docker #111
No files matched your search
+38
-10
@@ -1,10 +1,11 @@
|
||||
# CI (SPEC 15.5, ADR 0003/0004): only run steps with git, dotnet and docker, no external actions.
|
||||
# Publishing to the registry on v* tags arrives in phase 9 (issue #70).
|
||||
# The image is published only on v* tags, after the tests and the drill (SPEC 15.5, ADR 0002 and 0020); never on fase-N.
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
@@ -44,10 +45,15 @@ jobs:
|
||||
TESTINGPLATFORM_TELEMETRY_OPTOUT: "1"
|
||||
steps:
|
||||
- name: Checkout
|
||||
# The token goes to git through its environment, so it is on no command line.
|
||||
env:
|
||||
GIT_CONFIG_COUNT: "1"
|
||||
GIT_CONFIG_KEY_0: http.extraHeader
|
||||
GIT_CONFIG_VALUE_0: "Authorization: token ${{ github.token }}"
|
||||
run: |
|
||||
git init -q .
|
||||
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||
git -c http.extraHeader="Authorization: token ${{ github.token }}" fetch -q --depth 1 origin "${{ github.sha }}"
|
||||
git fetch -q --depth 1 origin "${{ github.sha }}"
|
||||
git checkout -q FETCH_HEAD
|
||||
- name: Check
|
||||
run: sh ./tasks.sh check
|
||||
@@ -59,20 +65,42 @@ jobs:
|
||||
image:
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
# Registry settings for phase 9 (issue #70): declared here, not used before then.
|
||||
env:
|
||||
REGISTRY: gitea.encke-hake.ts.net
|
||||
REGISTRY_USER: ${{ github.repository_owner }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
# The Docker daemon of the runner is shared between runs: a name of this run only, so what is published is what was tried.
|
||||
IMAGE: anubis:ci-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
# The token goes to git through its environment, so it is on no command line.
|
||||
env:
|
||||
GIT_CONFIG_COUNT: "1"
|
||||
GIT_CONFIG_KEY_0: http.extraHeader
|
||||
GIT_CONFIG_VALUE_0: "Authorization: token ${{ github.token }}"
|
||||
run: |
|
||||
git init -q .
|
||||
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||
git -c http.extraHeader="Authorization: token ${{ github.token }}" fetch -q --depth 1 origin "${{ github.sha }}"
|
||||
git fetch -q --depth 1 origin "${{ github.sha }}"
|
||||
git checkout -q FETCH_HEAD
|
||||
- name: Build image (no publish)
|
||||
run: docker build -f deploy/docker/Dockerfile -t anubis:ci .
|
||||
- name: Build image
|
||||
env:
|
||||
REF: ${{ github.ref }}
|
||||
REF_NAME: ${{ github.ref_name }}
|
||||
run: |
|
||||
case "$REF" in refs/tags/v*) version=${REF_NAME#v} ;; *) version=dev ;; esac
|
||||
docker build -f deploy/docker/Dockerfile --build-arg "ANUBIS_VERSION=$version" --build-arg "ANUBIS_COMMIT=$(git rev-parse HEAD)" -t "$IMAGE" .
|
||||
# The guard drill inside the image (issue #48): offline, its own SQLite database in a temporary folder.
|
||||
- name: Guard drill in the image
|
||||
run: docker run --rm anubis:ci drill
|
||||
run: docker run --rm "$IMAGE" drill
|
||||
- name: Publish image
|
||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
|
||||
env:
|
||||
REGISTRY: ${{ vars.REGISTRY || 'gitea.encke-hake.ts.net' }}
|
||||
REGISTRY_USER: ${{ vars.REGISTRY_USER || github.actor }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
TAG: ${{ github.ref_name }}
|
||||
GIT_CONFIG_COUNT: "1"
|
||||
GIT_CONFIG_KEY_0: http.extraHeader
|
||||
GIT_CONFIG_VALUE_0: "Authorization: token ${{ github.token }}"
|
||||
run: sh ./deploy/docker/publish.sh "$IMAGE" "$TAG"
|
||||
- name: Remove the image of this run
|
||||
if: always()
|
||||
run: docker image rm -f "$IMAGE" || true
|
||||
@@ -13,7 +13,7 @@
|
||||
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
|
||||
<Company>BalboSoft</Company>
|
||||
<Product>Anubis</Product>
|
||||
<Version>0.7.0</Version>
|
||||
<Version>0.9.0</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Only the packages of ADR 0004, with versions in Directory.Packages.props and lock files committed. -->
|
||||
|
||||
@@ -15,7 +15,7 @@ Database a scelta: PostgreSQL oppure SQLite. Scritto in C# su .NET 10, con inter
|
||||
|
||||
Nell'antico Egitto Anubis, il dio con la testa di sciacallo, pesava il cuore dei defunti contro la piuma di Maat, la verità e l'equilibrio, e custodiva le tombe. Il bot fa lo stesso con i soldi: **pesa** ogni operazione contro il rischio prima di farla e **protegge** il capitale. Il logo è quella bilancia, con il cuore e la piuma in equilibrio (ADR 0005).
|
||||
|
||||
> Stato: **progettazione completata, sviluppo non ancora iniziato.** Il piano è nelle [milestone](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestones) del repository.
|
||||
> Stato: **in simulazione, pronto da installare in Docker.** Il piano è nelle [milestone](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestones) del repository.
|
||||
|
||||

|
||||
|
||||
@@ -29,7 +29,7 @@ Nell'antico Egitto Anubis, il dio con la testa di sciacallo, pesava il cuore dei
|
||||
| [docs/SVILUPPO.md](docs/SVILUPPO.md) | Come si lavora: flusso su Gitea, regole, prove |
|
||||
| [docs/adr/](docs/adr/) | Decisioni prese: nome (0001), Gitea (0002), linguaggio C# (0003), componenti esterni (0004), logo (0005) |
|
||||
| [docs/design/](docs/design/) | Schermate di riferimento e logo |
|
||||
| [deploy/unraid/anubis.xml](deploy/unraid/anubis.xml) | Template Docker per Unraid (bozza) |
|
||||
| [deploy/unraid/anubis.xml](deploy/unraid/anubis.xml) | Template Docker per Unraid |
|
||||
|
||||
## Schermate di riferimento
|
||||
|
||||
|
||||
@@ -17,9 +17,11 @@ COPY docs/design/logo/ docs/design/logo/
|
||||
# The backtest outcomes are read at the first start (SPEC 12.3); .dockerignore lets only their JSON files through.
|
||||
COPY docs/backtests/ docs/backtests/
|
||||
COPY docs/learning/ docs/learning/
|
||||
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app
|
||||
# The commit goes into the version shown by the diagnostics report; empty when not given.
|
||||
ARG ANUBIS_COMMIT=
|
||||
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app ${ANUBIS_COMMIT:+-p:SourceRevisionId=$ANUBIS_COMMIT}
|
||||
# The guard (SPEC 9.3, ADR 0012) is the main process and starts the engine next to it, from the same folder.
|
||||
RUN dotnet publish src/Anubis.Guard/Anubis.Guard.csproj -c Release --no-restore -o /app
|
||||
RUN dotnet publish src/Anubis.Guard/Anubis.Guard.csproj -c Release --no-restore -o /app ${ANUBIS_COMMIT:+-p:SourceRevisionId=$ANUBIS_COMMIT}
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
||||
WORKDIR /app
|
||||
@@ -35,7 +37,16 @@ EXPOSE 8787
|
||||
VOLUME /data
|
||||
# Starts as root only to give /data to PUID:PGID, then runs the guard as that user (entrypoint.sh); the guard starts
|
||||
# the engine. "docker run --rm <image> drill" runs the guard drill instead (issue #48).
|
||||
# Health through bash's /dev/tcp: no curl or wget in the image. 503 (database down) counts as unhealthy.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
||||
# Health through bash's /dev/tcp: no curl or wget in the image. 503 (database down, loops stopped, no prices) counts as unhealthy.
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||||
CMD ["bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/${PORT:-8787} && printf 'GET /health HTTP/1.0\r\nHost: localhost\r\n\r\n' >&3 && head -n 1 <&3 | grep -q ' 200 '"]
|
||||
ENTRYPOINT ["anubis-entrypoint"]
|
||||
ARG ANUBIS_VERSION=dev
|
||||
ARG ANUBIS_COMMIT=
|
||||
LABEL org.opencontainers.image.title="Anubis" \
|
||||
org.opencontainers.image.description="Bot di trading personale: azioni USA e crypto spot, senza leva" \
|
||||
org.opencontainers.image.vendor="BalboSoft" \
|
||||
org.opencontainers.image.url="https://gitea.encke-hake.ts.net/BalboSoft/Anubis" \
|
||||
org.opencontainers.image.source="https://gitea.encke-hake.ts.net/BalboSoft/Anubis" \
|
||||
org.opencontainers.image.version="$ANUBIS_VERSION" \
|
||||
org.opencontainers.image.revision="$ANUBIS_COMMIT"
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/bin/sh
|
||||
# Publishes an image already built and tried (SPEC 15.5, ADR 0002 and 0020).
|
||||
# Usage: publish.sh <local image> <tag vX.Y.Z[-something]>
|
||||
# From the environment: REGISTRY, REGISTRY_USER, REGISTRY_TOKEN (write:package). The token reaches docker only on its
|
||||
# input and stays in a temporary folder removed at the end.
|
||||
set -eu
|
||||
|
||||
image="$1"
|
||||
tag="$2"
|
||||
root=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
fail() {
|
||||
echo "Pubblicazione non riuscita: $1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
printf '%s\n' "$tag" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$' || fail "il tag '$tag' non è una versione (vX.Y.Z)."
|
||||
version=${tag#v}
|
||||
expected=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' "$root/Directory.Build.props")
|
||||
[ "${version%%-*}" = "$expected" ] || fail "il tag $tag non corrisponde alla versione $expected di Directory.Build.props."
|
||||
[ -n "${REGISTRY:-}" ] || fail "manca REGISTRY."
|
||||
[ -n "${REGISTRY_USER:-}" ] || fail "manca REGISTRY_USER."
|
||||
[ -n "${REGISTRY_TOKEN:-}" ] || fail "manca il segreto REGISTRY_TOKEN (token Gitea con il permesso write:package)."
|
||||
name="$REGISTRY/balbosoft/anubis"
|
||||
|
||||
# latest moves only for the highest plain version among the tags of the repository.
|
||||
latest=""
|
||||
case "$version" in
|
||||
*-*) ;;
|
||||
*)
|
||||
tags=$(git -C "$root" ls-remote --tags --refs origin 'v*') || fail "non riesco a leggere i tag del repository."
|
||||
newest=$(printf '%s\n' "$tags" "x refs/tags/$tag" | sed -n 's:.*refs/tags/v\([0-9]*\.[0-9]*\.[0-9]*\)$:\1:p' | sort -t. -k1,1n -k2,2n -k3,3n | tail -n 1)
|
||||
if [ "$newest" = "$version" ]; then latest=1; fi
|
||||
;;
|
||||
esac
|
||||
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
export DOCKER_CONFIG
|
||||
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
|
||||
printf '%s' "$REGISTRY_TOKEN" | docker login "$REGISTRY" --username "$REGISTRY_USER" --password-stdin
|
||||
docker tag "$image" "$name:$version"
|
||||
docker push "$name:$version"
|
||||
if [ -n "$latest" ]; then
|
||||
docker tag "$image" "$name:latest"
|
||||
docker push "$name:latest"
|
||||
fi
|
||||
|
||||
echo "Pubblicata $name:$version${latest:+ (e latest)}."
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0"?>
|
||||
<!--
|
||||
Anubis: bozza del template Docker per Unraid (si completa nella Fase 9).
|
||||
Anubis: template Docker per Unraid (SPEC 15.3, appendice E). Le istruzioni sono in docs/MANUALE.md.
|
||||
L'immagine e' pubblicata nel registry dei pacchetti di Gitea, sotto l'organizzazione BalboSoft.
|
||||
Copia il file in /boot/config/plugins/dockerMan/templates-user/ e scegli
|
||||
"anubis" tra i template nella scheda Docker di Unraid.
|
||||
|
||||
+7
-1
@@ -105,6 +105,12 @@ Le attività `check`, `test` e `dev` sono anche in Terminale → Esegui attivit
|
||||
|
||||
## Pacchetti e consegne
|
||||
|
||||
- **Docker**: immagine `gitea.encke-hake.ts.net/balbosoft/anubis`, pubblicata dalla CI sui tag `v*` nella sezione Packages del repository (ADR 0002). I tag `fase-N` non pubblicano nulla.
|
||||
- **Docker**: immagine `gitea.encke-hake.ts.net/balbosoft/anubis`, pubblicata dalla CI sui tag `v*` nella sezione Packages del repository (ADR 0002 e 0020). I tag `fase-N` non pubblicano nulla.
|
||||
- Prima del tag si porta `<Version>` di `Directory.Build.props` alla versione nuova: se il tag e quel numero non coincidono la pubblicazione si ferma. Il tag si mette solo quando l'utente lo chiede.
|
||||
- `vX.Y.Z` pubblica `X.Y.Z` e sposta `latest` se è la versione più alta fra i tag del repository; `vX.Y.Z-prova` pubblica solo sé stessa.
|
||||
- Servono il segreto delle Actions `REGISTRY_TOKEN` (token Gitea con il permesso `write:package`) e, se il token non è di chi mette il tag, la variabile `REGISTRY_USER`. `REGISTRY` vale `gitea.encke-hake.ts.net` se non c'è.
|
||||
- A mano, senza esecutore di Actions: `tasks ci` (costruisce e prova l'immagine `:ci`), poi da una shell Linux o Git Bash, scrivendo il token senza lasciarlo nella cronologia:
|
||||
`read -rs REGISTRY_TOKEN; export REGISTRY_TOKEN; REGISTRY=gitea.encke-hake.ts.net REGISTRY_USER=<utente> sh deploy/docker/publish.sh gitea.encke-hake.ts.net/balbosoft/anubis:ci vX.Y.Z`
|
||||
- Se il pacchetto non compare nella sezione Packages del repository, lo si collega una volta dalla sua pagina su Gitea.
|
||||
- **Windows**: installatore `Anubis.Setup` (scritto in casa, ADR 0003) costruito con `tasks desktop-win` su Windows e allegato alla release `v*`.
|
||||
- **Unraid**: `deploy/unraid/anubis.xml`, da copiare in `/boot/config/plugins/dockerMan/templates-user/`.
|
||||
@@ -39,7 +39,7 @@ internal static partial class Endpoints
|
||||
Forms.Map(app);
|
||||
}
|
||||
|
||||
// Healthy only when the database answers and the scheduler loop is alive (SPEC 15.2); the body says why not.
|
||||
// Healthy only when the database answers, the loops turn and the prices arrive (SPEC 15.2); the body says why not.
|
||||
private static async Task<IResult> HealthAsync(AnubisHost host, CancellationToken cancellationToken)
|
||||
{
|
||||
var status = host.Status;
|
||||
@@ -62,6 +62,11 @@ internal static partial class Endpoints
|
||||
|
||||
checks["scheduler"] = host.SchedulerRunning ? "ok" : "fermo";
|
||||
healthy &= host.SchedulerRunning;
|
||||
var (loop, loopOk) = HealthRules.Loop(host.Clock.UtcNow, services.Trading is { IsStarted: true }, services.Trading?.LastTurnAt);
|
||||
var (feed, feedOk) = HealthRules.Feed(host.Clock.UtcNow, services.MarketData?.LiveFeed.Since, services.MarketData?.LiveFeed.LastDataAt);
|
||||
checks["motore"] = loop;
|
||||
checks["dati"] = feed;
|
||||
healthy &= loopOk && feedOk;
|
||||
}
|
||||
|
||||
var body = new HealthResponse(healthy ? "ok" : "unavailable", AnubisInfo.Name, AnubisInfo.Version, status.Mode.ToString(), checks);
|
||||
@@ -500,3 +505,29 @@ internal static partial class Endpoints
|
||||
given is not null && expected is not null &&
|
||||
CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(given)), SHA256.HashData(Encoding.UTF8.GetBytes(expected)));
|
||||
}
|
||||
|
||||
/// <summary>What the health check of the container says about the engine's loop and the live prices (SPEC 15.2).</summary>
|
||||
internal static class HealthRules
|
||||
{
|
||||
/// <summary>The same silence after which the guard steps in (SPEC 9.3).</summary>
|
||||
public static readonly TimeSpan LoopLimit = TimeSpan.FromMinutes(2);
|
||||
|
||||
/// <summary>Longer than the silence that blocks new entries (SPEC 6.5): a line that drops for a moment is not an ill container.</summary>
|
||||
public static readonly TimeSpan FeedLimit = TimeSpan.FromMinutes(5);
|
||||
|
||||
public static (string Text, bool Ok) Loop(DateTimeOffset now, bool started, DateTimeOffset? lastTurn) => (started, lastTurn) switch
|
||||
{
|
||||
(false, _) => ("non avviato", true),
|
||||
(_, null) => ("in avvio", true),
|
||||
(_, { } at) when now - at > LoopLimit => ("fermo", false),
|
||||
_ => ("ok", true),
|
||||
};
|
||||
|
||||
public static (string Text, bool Ok) Feed(DateTimeOffset now, DateTimeOffset? since, DateTimeOffset? lastData) => (since, lastData) switch
|
||||
{
|
||||
(null, _) => ("in attesa", true),
|
||||
({ } from, null) when now - from <= FeedLimit => ("in attesa", true),
|
||||
(_, { } at) when now - at <= FeedLimit => ("ok", true),
|
||||
_ => ("fermi", false),
|
||||
};
|
||||
}
|
||||
@@ -147,9 +147,18 @@ internal sealed record SystemView(
|
||||
? new SystemPart("Prezzi di mercato", "aggiornati " + Ago(now - at), now - at > TimeSpan.FromMinutes(5) ? PartState.Warn : PartState.Ok)
|
||||
: new SystemPart("Prezzi di mercato", "in attesa dei primi prezzi", PartState.Off));
|
||||
|
||||
// News arrive with phase 7 (SPEC 10).
|
||||
parts.Add(new SystemPart("Lettura delle notizie", "non ancora attiva", PartState.Off));
|
||||
tiles.Add(new SystemPart("Notizie", "non ancora attive", PartState.Off));
|
||||
// The news sources read every two minutes (SPEC 4.4): the ones the user left on, and when one last answered.
|
||||
var read = market is null || market.Offline ? [] : (await market.News.Store.ListSourcesAsync(cancellationToken).ConfigureAwait(false)).Where(s => s.Enabled).ToList();
|
||||
var heard = read.Max(s => s.LastOkAt);
|
||||
var (newsText, newsState) = (read.Count, heard) switch
|
||||
{
|
||||
(0, _) => ("spenta", PartState.Off),
|
||||
(_, null) => ("in attesa della prima lettura", PartState.Off),
|
||||
(_, { } last) when now - last > TimeSpan.FromMinutes(30) => ("le fonti non rispondono, ultima lettura " + When(last, now, zone) + ": riprovo da solo", PartState.Warn),
|
||||
(_, { } last) => ($"{read.Count} fonti, ultima lettura {When(last, now, zone)}", PartState.Ok),
|
||||
};
|
||||
parts.Add(new SystemPart("Lettura delle notizie", newsText, newsState));
|
||||
tiles.Add(new SystemPart("Notizie", heard is { } h ? "lette " + When(h, now, zone) : newsText, newsState));
|
||||
|
||||
// The database: engine, size, last backup.
|
||||
var engine = services.Db.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite";
|
||||
|
||||
@@ -75,6 +75,12 @@ public sealed partial class MarketCollector
|
||||
/// <summary>True while the live feed is connected.</summary>
|
||||
public bool Connected { get; private set; }
|
||||
|
||||
/// <summary>When the last datum arrived from the live feed, by this computer's clock; null before the first.</summary>
|
||||
public DateTimeOffset? LastDataAt { get; private set; }
|
||||
|
||||
/// <summary>When the live feed was started, by this computer's clock; null before that.</summary>
|
||||
public DateTimeOffset? LiveSince { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Downloads the daily bars after the last one stored (from <paramref name="from"/> the first time) up to yesterday.
|
||||
/// <paramref name="prefetched"/>, when given, are bars already downloaded for many symbols at once: only the second
|
||||
@@ -195,6 +201,7 @@ public sealed partial class MarketCollector
|
||||
foreach (var instrument in instruments)
|
||||
{
|
||||
_freshness.Follow(instrument.Id, instrument.Symbol);
|
||||
LiveSince ??= _clock.UtcNow;
|
||||
}
|
||||
|
||||
var recent = new Dictionary<Guid, List<Bar>>();
|
||||
@@ -248,10 +255,12 @@ public sealed partial class MarketCollector
|
||||
}
|
||||
|
||||
_freshness.Touch(instrument.Id, closed.Bar.OpensAt.AddMinutes(1));
|
||||
LastDataAt = _clock.UtcNow;
|
||||
}
|
||||
else if (item is not BarEvent)
|
||||
{
|
||||
_freshness.Touch(instrument.Id, item.At);
|
||||
LastDataAt = _clock.UtcNow;
|
||||
}
|
||||
|
||||
_bus.Publish(item);
|
||||
|
||||
@@ -113,6 +113,9 @@ public sealed partial class MarketDataService : IDisposable
|
||||
/// <summary>True while the live crypto feed is connected.</summary>
|
||||
public bool LiveConnected => _okxCollector.Connected;
|
||||
|
||||
/// <summary>When the live crypto feed was started and when its last datum arrived: a feed open and silent is not healthy (trap 10).</summary>
|
||||
public (DateTimeOffset? Since, DateTimeOffset? LastDataAt) LiveFeed => (_okxCollector.LiveSince, _okxCollector.LastDataAt);
|
||||
|
||||
/// <summary>When the background worker last finished a round, for the interface.</summary>
|
||||
public DateTimeOffset? LastHistoryRun { get; private set; }
|
||||
|
||||
|
||||
@@ -65,6 +65,10 @@ public static class DockerPlatform
|
||||
var port = ParsePort(Get("PORT"), 8787, "PORT", problems);
|
||||
var puid = ParseInt(Get("PUID"), 99, "PUID", problems);
|
||||
var pgid = ParseInt(Get("PGID"), 100, "PGID", problems);
|
||||
if (puid == 0)
|
||||
{
|
||||
problems.Add(new("PUID", "Anubis non gira come amministratore del sistema.", "Usa un utente normale (99 su Unraid) e riavvia."));
|
||||
}
|
||||
|
||||
var keys = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var name in OptionalKeys.SelectMany(k => new[] { k, k + "_DEMO" }))
|
||||
|
||||
@@ -688,6 +688,9 @@ public sealed partial class TradingService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>When the working loop last finished a turn, for the health check; null before the first.</summary>
|
||||
public DateTimeOffset? LastTurnAt { get; private set; }
|
||||
|
||||
/// <summary>The working loop: quotes from the stream, order updates from the brokers, a turn of every account every few seconds.</summary>
|
||||
public async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -703,6 +706,7 @@ public sealed partial class TradingService : IDisposable
|
||||
}
|
||||
|
||||
await TickAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
LastTurnAt = _clock.UtcNow;
|
||||
BeatIfAlive();
|
||||
if (GuardFiles is not null && _clock.UtcNow - _guardStateAt >= GuardStateEvery)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml.Linq;
|
||||
using Anubis.Platform;
|
||||
using Anubis.Server;
|
||||
using Anubis.Supervision;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>What is delivered: the Unraid template, the image and how it is published (issues #70 and #71, SPEC 15.2, 15.3, 15.5).</summary>
|
||||
[TestClass]
|
||||
public sealed partial class DeliveryTests
|
||||
{
|
||||
private const string Image = "gitea.encke-hake.ts.net/balbosoft/anubis";
|
||||
|
||||
private static string Text(string path) => File.ReadAllText(Path.Combine(Repo.Root.FullName, path.Replace('/', Path.DirectorySeparatorChar))).ReplaceLineEndings("\n");
|
||||
|
||||
private static string Section(string from, string to)
|
||||
{
|
||||
var spec = Text("docs/SPEC.md");
|
||||
var start = spec.IndexOf("\n" + from, StringComparison.Ordinal);
|
||||
Assert.IsGreaterThan(0, start, from);
|
||||
var end = spec.IndexOf("\n" + to, start + 1, StringComparison.Ordinal);
|
||||
return end < 0 ? spec[start..] : spec[start..end];
|
||||
}
|
||||
|
||||
private static XElement Template() => XDocument.Parse(Text("deploy/unraid/anubis.xml")).Root!;
|
||||
|
||||
private static Dictionary<string, XElement> Fields(XElement template)
|
||||
{
|
||||
var fields = new Dictionary<string, XElement>(StringComparer.Ordinal);
|
||||
foreach (var config in template.Elements("Config"))
|
||||
{
|
||||
Assert.IsTrue(fields.TryAdd(config.Attribute("Target")!.Value, config), "Twice: " + config);
|
||||
}
|
||||
|
||||
return fields;
|
||||
}
|
||||
|
||||
private static HashSet<string> VariablesOf151() => VariableName().Matches(string.Join('\n',
|
||||
Section("### 15.1", "### 15.2").Split('\n').Where(l => l.StartsWith("| `", StringComparison.Ordinal)).Select(l => l.Split('|')[1])))
|
||||
.Select(m => m.Groups[1].Value).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
// ---- the Unraid template ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheTemplateHasTheFieldsOfAppendixE()
|
||||
{
|
||||
var template = Template();
|
||||
Assert.AreEqual("Container", template.Name.LocalName);
|
||||
Assert.AreEqual("2", template.Attribute("version")!.Value);
|
||||
var appendix = Section("## Appendice E", "## Appendice F");
|
||||
var draft = appendix[(appendix.IndexOf("```xml\n", StringComparison.Ordinal) + 7)..];
|
||||
var expected = Fields(XDocument.Parse(draft[..draft.IndexOf("\n```", StringComparison.Ordinal)]).Root!);
|
||||
var actual = Fields(template);
|
||||
CollectionAssert.AreEquivalent(expected.Keys.ToList(), actual.Keys.ToList());
|
||||
foreach (var (target, field) in expected)
|
||||
{
|
||||
foreach (var name in new[] { "Type", "Mode", "Display", "Required", "Default", "Mask" })
|
||||
{
|
||||
// The address of the heartbeat is a secret of its service: masked, unlike the draft (ADR 0020).
|
||||
var want = (target, name) == ("ANUBIS_HEARTBEAT_URL", "Mask") ? "true" : field.Attribute(name)!.Value;
|
||||
Assert.AreEqual(want, actual[target].Attribute(name)!.Value, target + " " + name);
|
||||
}
|
||||
|
||||
Assert.AreEqual(field.Value, actual[target].Value, target);
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(actual[target].Attribute("Description")!.Value), target);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void EveryVariableOfTheTemplateIsIn151AndTheAccountKeysAreNot()
|
||||
{
|
||||
var known = VariablesOf151();
|
||||
Assert.IsGreaterThan(20, known.Count);
|
||||
var targets = Fields(Template()).Where(f => f.Value.Attribute("Type")!.Value == "Variable").Select(f => f.Key).ToList();
|
||||
Assert.HasCount(16, targets);
|
||||
CollectionAssert.IsSubsetOf(targets, known.ToList());
|
||||
Assert.IsEmpty(targets.Where(t => t.StartsWith("ALPACA", StringComparison.Ordinal) || t.StartsWith("OKX", StringComparison.Ordinal) || t.EndsWith("_API_KEY", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheTemplateMasksSecretsAndHidesRareFields()
|
||||
{
|
||||
var fields = Fields(Template());
|
||||
foreach (var secret in new[] { "ANUBIS_DB_PASSWORD", "ANUBIS_SECRET_KEY", "ANUBIS_ADMIN_PASSWORD", "TELEGRAM_BOT_TOKEN", "ANUBIS_DB_URL", "ANUBIS_HEARTBEAT_URL" })
|
||||
{
|
||||
Assert.AreEqual("true", fields[secret].Attribute("Mask")!.Value, secret);
|
||||
Assert.AreEqual("", fields[secret].Value, secret);
|
||||
}
|
||||
|
||||
foreach (var rare in new[] { "ANUBIS_ALLOW_LIVE", "TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID", "ANUBIS_HEARTBEAT_URL", "PUID", "PGID", "ANUBIS_DB_URL" })
|
||||
{
|
||||
Assert.AreEqual("advanced", fields[rare].Attribute("Display")!.Value, rare);
|
||||
}
|
||||
|
||||
Assert.AreEqual("0", fields["ANUBIS_ALLOW_LIVE"].Value);
|
||||
Assert.AreEqual("postgres|sqlite", fields["ANUBIS_DB_ENGINE"].Attribute("Default")!.Value);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheTemplatePointsToTheRealImage()
|
||||
{
|
||||
var template = Template();
|
||||
var text = Text("deploy/unraid/anubis.xml");
|
||||
Assert.DoesNotContain("example", text);
|
||||
Assert.DoesNotContain("UTENTE", text);
|
||||
Assert.DoesNotContain("bozza", text);
|
||||
Assert.AreEqual(Image + ":latest", template.Element("Repository")!.Value);
|
||||
StringAssert.Contains(Text("tools/Anubis.Tasks/Program.cs"), Image + ":");
|
||||
StringAssert.Contains(Text("deploy/docker/publish.sh"), "$REGISTRY/balbosoft/anubis");
|
||||
var fields = Fields(template);
|
||||
Assert.AreEqual("8787", fields["8787"].Value);
|
||||
Assert.AreEqual("/mnt/user/appdata/anubis", fields["/data"].Value);
|
||||
var extra = template.Element("ExtraParams")!.Value;
|
||||
StringAssert.Contains(extra, "--memory=4g");
|
||||
var stop = int.Parse(StopTimeout().Match(extra).Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
|
||||
Assert.AreEqual(60, stop);
|
||||
Assert.IsGreaterThan(new GuardOptions().GracefulStop, TimeSpan.FromSeconds(stop));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheIconIsASquarePngWithTransparency()
|
||||
{
|
||||
var url = Template().Element("Icon")!.Value;
|
||||
StringAssert.EndsWith(url, "/deploy/unraid/anubis-icon.png");
|
||||
var png = File.ReadAllBytes(Path.Combine(Repo.Root.FullName, "deploy", "unraid", "anubis-icon.png"));
|
||||
CollectionAssert.AreEqual(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, png[..8]);
|
||||
var width = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(16));
|
||||
Assert.AreEqual(width, BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(20)));
|
||||
Assert.IsGreaterThanOrEqualTo(128, width);
|
||||
Assert.AreEqual(6, (int)png[25], "Colour type 6: red, green, blue and transparency.");
|
||||
}
|
||||
|
||||
// ---- what the loader reads ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheLoaderReadsEveryVariableOf151AndNoOther()
|
||||
{
|
||||
var read = new HashSet<string>(StringComparer.Ordinal);
|
||||
Dictionary<string, string?> Base(string engine) => new() { ["ANUBIS_DB_ENGINE"] = engine, ["ANUBIS_SECRET_KEY"] = new string('k', 40), ["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1" };
|
||||
var withUrl = Base("postgres");
|
||||
withUrl["ANUBIS_DB_URL"] = "postgresql://anubis:a-database-pass@db.example:5432/anubis";
|
||||
var withHost = Base("postgres");
|
||||
(withHost["ANUBIS_DB_HOST"], withHost["ANUBIS_DB_PASSWORD"]) = ("db.example", "a-database-pass");
|
||||
foreach (var env in new[] { withHost, Base("sqlite"), withUrl })
|
||||
{
|
||||
DockerPlatform.Load(new Recorded(env, read), Path.GetTempPath());
|
||||
}
|
||||
|
||||
var expected = VariablesOf151();
|
||||
foreach (var key in DockerPlatform.OptionalKeys)
|
||||
{
|
||||
Assert.Contains(key, expected);
|
||||
expected.Add(key + "_DEMO");
|
||||
}
|
||||
|
||||
CollectionAssert.AreEquivalent(expected.Order(StringComparer.Ordinal).ToList(), read.Order(StringComparer.Ordinal).ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AFieldLeftBlankInTheTemplateIsAsIfItWereNotThere()
|
||||
{
|
||||
var env = Fields(Template()).Where(f => f.Value.Attribute("Type")!.Value == "Variable").ToDictionary(f => f.Key, f => (string?)f.Value.Value, StringComparer.Ordinal);
|
||||
var blank = DockerPlatform.Load(env, Path.GetTempPath());
|
||||
CollectionAssert.AreEquivalent(new[] { "ANUBIS_DB_HOST", "ANUBIS_DB_PASSWORD", "ANUBIS_SECRET_KEY", "ANUBIS_ADMIN_PASSWORD" }, blank.Problems.Select(p => p.Setting).ToList());
|
||||
env["ANUBIS_DB_ENGINE"] = "sqlite";
|
||||
env["ANUBIS_SECRET_KEY"] = new string('k', 40);
|
||||
env["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1";
|
||||
var filled = DockerPlatform.Load(env, Path.GetTempPath());
|
||||
Assert.IsEmpty(filled.Problems);
|
||||
Assert.IsFalse(filled.AllowLive);
|
||||
Assert.IsNull(filled.HeartbeatUrl);
|
||||
env["PUID"] = "0";
|
||||
Assert.AreEqual("PUID", DockerPlatform.Load(env, Path.GetTempPath()).Problems.Single().Setting);
|
||||
}
|
||||
|
||||
// ---- the health of the container (SPEC 15.2) ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void HealthCoversTheLoopAndThePrices()
|
||||
{
|
||||
var now = new DateTimeOffset(2026, 12, 1, 9, 0, 0, TimeSpan.Zero);
|
||||
DateTimeOffset? Ago(double minutes) => now.AddMinutes(-minutes);
|
||||
Assert.IsTrue(HealthRules.Loop(now, false, Ago(60)).Ok, "Not started, as on the error page or without keys.");
|
||||
Assert.IsTrue(HealthRules.Loop(now, true, null).Ok);
|
||||
Assert.IsTrue(HealthRules.Loop(now, true, Ago(1.9)).Ok);
|
||||
Assert.AreEqual(("fermo", false), HealthRules.Loop(now, true, Ago(2.1)));
|
||||
Assert.AreEqual(new GuardOptions().Silence, HealthRules.LoopLimit);
|
||||
|
||||
Assert.IsTrue(HealthRules.Feed(now, null, null).Ok, "No instrument to follow yet.");
|
||||
Assert.IsTrue(HealthRules.Feed(now, Ago(4), null).Ok);
|
||||
Assert.IsFalse(HealthRules.Feed(now, Ago(6), null).Ok, "Open and silent from the start.");
|
||||
Assert.IsTrue(HealthRules.Feed(now, Ago(600), Ago(4)).Ok);
|
||||
Assert.AreEqual(("fermi", false), HealthRules.Feed(now, Ago(600), Ago(6)));
|
||||
}
|
||||
|
||||
// ---- the image ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheImageSaysWhatItIs()
|
||||
{
|
||||
var docker = Text("deploy/docker/Dockerfile");
|
||||
var project = Template().Element("Project")!.Value;
|
||||
StringAssert.Contains(docker, $"org.opencontainers.image.source=\"{project}\"");
|
||||
StringAssert.Contains(docker, "org.opencontainers.image.version=\"$ANUBIS_VERSION\"");
|
||||
StringAssert.Contains(docker, "org.opencontainers.image.revision=\"$ANUBIS_COMMIT\"");
|
||||
var publish = docker.Split('\n').Where(l => l.StartsWith("RUN dotnet publish", StringComparison.Ordinal)).ToList();
|
||||
Assert.HasCount(2, publish);
|
||||
Assert.IsTrue(publish.All(l => l.EndsWith("${ANUBIS_COMMIT:+-p:SourceRevisionId=$ANUBIS_COMMIT}", StringComparison.Ordinal)));
|
||||
CollectionAssert.AreEquivalent(new[] { "mcr.microsoft.com/dotnet/sdk:10.0", "mcr.microsoft.com/dotnet/aspnet:10.0" },
|
||||
docker.Split('\n').Where(l => l.StartsWith("FROM ", StringComparison.Ordinal)).Select(l => l.Split(' ')[1]).ToList());
|
||||
StringAssert.Contains(docker, "${PORT:-8787}");
|
||||
StringAssert.Contains(docker, "EXPOSE 8787\n");
|
||||
StringAssert.Contains(docker, "--timeout=10s", "Longer than the 5 seconds the page waits for the database, so its answer arrives.");
|
||||
var entry = Text("deploy/docker/entrypoint.sh");
|
||||
StringAssert.Contains(entry, "PUID=0");
|
||||
StringAssert.Contains(entry, "--no-new-privs");
|
||||
}
|
||||
|
||||
// ---- the workflow ----
|
||||
|
||||
private static Dictionary<string, object> Workflow() => MiniYaml.Read(Text(".gitea/workflows/ci.yml"));
|
||||
|
||||
private static Dictionary<string, object> At(object map, string key) => (Dictionary<string, object>)((Dictionary<string, object>)map)[key];
|
||||
|
||||
private static List<Dictionary<string, object>> Steps(string job) => ((List<object>)At(At(Workflow(), "jobs"), job)["steps"]).Cast<Dictionary<string, object>>().ToList();
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheWorkflowUsesNoExternalAction()
|
||||
{
|
||||
foreach (var job in At(Workflow(), "jobs").Keys)
|
||||
{
|
||||
Assert.IsNotEmpty(Steps(job));
|
||||
foreach (var step in Steps(job))
|
||||
{
|
||||
Assert.IsTrue(step.ContainsKey("run"), $"{job}: {step["name"]}");
|
||||
Assert.IsFalse(step.ContainsKey("uses"), $"{job}: {step["name"]}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheImageIsPublishedOnlyOnVersionTagsAndAfterTheTests()
|
||||
{
|
||||
var workflow = Workflow();
|
||||
CollectionAssert.AreEqual(new[] { "**" }, ((List<object>)At(At(workflow, "on"), "push")["branches"]).Cast<string>().ToList());
|
||||
CollectionAssert.AreEqual(new[] { "v*" }, ((List<object>)At(At(workflow, "on"), "push")["tags"]).Cast<string>().ToList());
|
||||
Assert.AreEqual("test", At(At(workflow, "jobs"), "image")["needs"]);
|
||||
var matrix = (List<object>)At(At(At(At(workflow, "jobs"), "test"), "strategy"), "matrix")["db"];
|
||||
CollectionAssert.AreEquivalent(new[] { "sqlite", "postgres" }, matrix.Cast<string>().ToList());
|
||||
|
||||
var steps = Steps("image");
|
||||
var publishing = Enumerable.Range(0, steps.Count).Where(i => PublishCommand().IsMatch((string)steps[i]["run"])).ToList();
|
||||
Assert.HasCount(1, publishing);
|
||||
Assert.AreEqual("github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')", steps[publishing[0]]["if"]);
|
||||
Assert.IsGreaterThan(steps.FindIndex(s => ((string)s["run"]).Contains(" drill", StringComparison.Ordinal)), publishing[0]);
|
||||
Assert.IsEmpty(Steps("test").Where(s => PublishCommand().IsMatch((string)s["run"])));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheTokensStayInTheStepsThatNeedThem()
|
||||
{
|
||||
var text = Text(".gitea/workflows/ci.yml");
|
||||
Assert.AreEqual(1, Regex.Count(text, @"secrets\."));
|
||||
Assert.DoesNotContain("set -x", text);
|
||||
foreach (var job in At(Workflow(), "jobs").Keys)
|
||||
{
|
||||
var definition = At(At(Workflow(), "jobs"), job);
|
||||
if (definition.TryGetValue("env", out var env))
|
||||
{
|
||||
Assert.IsEmpty(((Dictionary<string, object>)env).Values.OfType<string>().Where(v => v.Contains("token", StringComparison.OrdinalIgnoreCase) || v.Contains("secrets.", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
foreach (var step in Steps(job))
|
||||
{
|
||||
var run = (string)step["run"];
|
||||
Assert.DoesNotContain("github.token", run);
|
||||
Assert.DoesNotContain("secrets.", run);
|
||||
Assert.DoesNotContain("github.ref", run, "A name chosen by who pushes reaches the shell only as a variable.");
|
||||
}
|
||||
}
|
||||
|
||||
var publish = Steps("image").Single(s => PublishCommand().IsMatch((string)s["run"]));
|
||||
Assert.AreEqual("${{ secrets.REGISTRY_TOKEN }}", At(publish, "env")["REGISTRY_TOKEN"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void WhatIsPublishedIsTheImageThatWasTried()
|
||||
{
|
||||
var name = (string)At(At(At(Workflow(), "jobs"), "image"), "env")["IMAGE"];
|
||||
StringAssert.Contains(name, "github.run_id");
|
||||
var docker = Steps("image").Select(s => (string)s["run"]).Where(r => r.Contains("docker", StringComparison.Ordinal)).ToList();
|
||||
Assert.HasCount(4, docker, "Build, drill, publish, remove.");
|
||||
Assert.IsTrue(docker.All(r => r.Contains("\"$IMAGE\"", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheYamlReaderRefusesWhatItDoesNotKnow()
|
||||
{
|
||||
var read = MiniYaml.Read("# c\na: 1 # c\nb:\n - x\n - k: 'v: w'\n run: |\n one\n two\n\n three\nlist: [\"**\", z]\nfold: >-\n p\n q\n");
|
||||
Assert.AreEqual("1", read["a"]);
|
||||
Assert.AreEqual("x", ((List<object>)read["b"])[0]);
|
||||
Assert.AreEqual("v: w", ((Dictionary<string, object>)((List<object>)read["b"])[1])["k"]);
|
||||
Assert.AreEqual("one\n two\nthree", ((Dictionary<string, object>)((List<object>)read["b"])[1])["run"]);
|
||||
CollectionAssert.AreEqual(new[] { "**", "z" }, ((List<object>)read["list"]).Cast<string>().ToList());
|
||||
Assert.AreEqual("p q", read["fold"]);
|
||||
foreach (var wrong in new[] { "a: 1\n\tb: 2", "a: 1\na: 2", "a: &x 1", "a: *x", "a:\n b: 1\n c: 2", "a: 1\n b: 2", "just text", "a: {b: 1}", "a: [1" })
|
||||
{
|
||||
StringAssert.Contains(Assert.ThrowsExactly<FormatException>(() => MiniYaml.Read(wrong), wrong).Message, "line ");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the script that publishes, with a docker and a git that only take note ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
[OSCondition(OperatingSystems.Linux)]
|
||||
[DataRow("v0.9.0", "v0.7.0", 0, "0.9.0,latest")]
|
||||
[DataRow("v0.9.0", "", 0, "0.9.0,latest")]
|
||||
[DataRow("v0.9.0-rc.1", "v0.7.0", 0, "0.9.0-rc.1")]
|
||||
[DataRow("v0.9.0", "v0.10.0", 0, "0.9.0")]
|
||||
[DataRow("v0.9.0", "v0.10.0-rc.1", 0, "0.9.0,latest")]
|
||||
[DataRow("v0.9.1", "v0.7.0", 1, "")]
|
||||
[DataRow("fase-9", "v0.7.0", 1, "")]
|
||||
[DataRow("v9", "v0.7.0", 1, "")]
|
||||
[DataRow("v0.9.0;id", "v0.7.0", 1, "")]
|
||||
public async Task TheScriptPublishesTheVersionAndMovesLatestOnlyForward(string tag, string others, int exit, string pushed)
|
||||
{
|
||||
using var run = new PublishRun(others);
|
||||
var (code, output) = await run.RunAsync(tag, PublishRun.Token);
|
||||
Assert.AreEqual(exit, code, output);
|
||||
CollectionAssert.AreEqual(pushed.Split(',', StringSplitOptions.RemoveEmptyEntries), run.Pushed(), output);
|
||||
if (exit != 0)
|
||||
{
|
||||
StringAssert.Contains(output, "Pubblicazione non riuscita");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
[OSCondition(OperatingSystems.Linux)]
|
||||
public async Task TheScriptGivesTheTokenToDockerOnlyOnItsInputAndLeavesNothing()
|
||||
{
|
||||
using var run = new PublishRun("v0.7.0");
|
||||
var (code, output) = await run.RunAsync("v0.9.0", PublishRun.Token);
|
||||
Assert.AreEqual(0, code, output);
|
||||
Assert.DoesNotContain(PublishRun.Token, output);
|
||||
Assert.DoesNotContain(PublishRun.Token, run.Calls);
|
||||
Assert.AreEqual(PublishRun.Token, run.Input);
|
||||
var config = run.Config;
|
||||
Assert.IsNotEmpty(config);
|
||||
Assert.IsFalse(Directory.Exists(config), "The folder with the credentials is gone.");
|
||||
|
||||
using var without = new PublishRun("v0.7.0");
|
||||
(code, output) = await without.RunAsync("v0.9.0", "");
|
||||
Assert.AreEqual(1, code);
|
||||
StringAssert.Contains(output, "REGISTRY_TOKEN");
|
||||
Assert.AreEqual("", without.Calls);
|
||||
|
||||
using var offline = new PublishRun("v0.7.0", gitFails: true);
|
||||
(code, output) = await offline.RunAsync("v0.9.0", PublishRun.Token);
|
||||
Assert.AreEqual(1, code, output);
|
||||
Assert.IsEmpty(offline.Pushed());
|
||||
}
|
||||
|
||||
private sealed class PublishRun : IDisposable
|
||||
{
|
||||
public const string Token = "a-token-only-for-the-test";
|
||||
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "anubis-publish-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
public PublishRun(string others, bool gitFails = false)
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(_root, "deploy", "docker"));
|
||||
Directory.CreateDirectory(Path.Combine(_root, "bin"));
|
||||
File.WriteAllText(Path.Combine(_root, "deploy", "docker", "publish.sh"), Text("deploy/docker/publish.sh"));
|
||||
File.WriteAllText(Path.Combine(_root, "Directory.Build.props"), "<Project>\n <Version>0.9.0</Version>\n</Project>\n");
|
||||
Tool("docker", "printf '%s\\n' \"$*\" >> \"$RECORD/calls\"\nif [ \"$1\" = login ]; then cat > \"$RECORD/input\"; printf '%s' \"$DOCKER_CONFIG\" > \"$RECORD/config\"; fi\n");
|
||||
Tool("git", gitFails ? "exit 128\n" : string.Concat(others.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(o => $"printf 'abc\\trefs/tags/{o}\\n'\n")));
|
||||
}
|
||||
|
||||
public string Calls => Recorded("calls");
|
||||
|
||||
public string Input => Recorded("input");
|
||||
|
||||
public string Config => Recorded("config");
|
||||
|
||||
public List<string> Pushed() => Calls.Split('\n').Where(l => l.StartsWith("push registry.test/balbosoft/anubis:", StringComparison.Ordinal)).Select(l => l[(l.LastIndexOf(':') + 1)..]).ToList();
|
||||
|
||||
public async Task<(int Code, string Output)> RunAsync(string tag, string token)
|
||||
{
|
||||
var info = new ProcessStartInfo("sh") { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false };
|
||||
info.ArgumentList.Add(Path.Combine(_root, "deploy", "docker", "publish.sh"));
|
||||
info.ArgumentList.Add("anubis:ci-1-1");
|
||||
info.ArgumentList.Add(tag);
|
||||
info.Environment["PATH"] = Path.Combine(_root, "bin") + ":" + Environment.GetEnvironmentVariable("PATH");
|
||||
info.Environment["RECORD"] = _root;
|
||||
info.Environment["REGISTRY"] = "registry.test";
|
||||
info.Environment["REGISTRY_USER"] = "someone";
|
||||
info.Environment["REGISTRY_TOKEN"] = token;
|
||||
using var process = Process.Start(info)!;
|
||||
var output = process.StandardOutput.ReadToEndAsync();
|
||||
var error = process.StandardError.ReadToEndAsync();
|
||||
await process.WaitForExitAsync();
|
||||
return (process.ExitCode, await output + await error);
|
||||
}
|
||||
|
||||
public void Dispose() => Directory.Delete(_root, recursive: true);
|
||||
|
||||
private string Recorded(string name) => File.Exists(Path.Combine(_root, name)) ? File.ReadAllText(Path.Combine(_root, name)) : "";
|
||||
|
||||
private void Tool(string name, string body)
|
||||
{
|
||||
var path = Path.Combine(_root, "bin", name);
|
||||
File.WriteAllText(path, "#!/bin/sh\n" + body);
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An environment that takes note of the names asked for.</summary>
|
||||
private sealed class Recorded(Dictionary<string, string?> values, HashSet<string> read) : IReadOnlyDictionary<string, string?>
|
||||
{
|
||||
public IEnumerable<string> Keys => values.Keys;
|
||||
|
||||
public IEnumerable<string?> Values => values.Values;
|
||||
|
||||
public int Count => values.Count;
|
||||
|
||||
public string? this[string key] => TryGetValue(key, out var value) ? value : throw new KeyNotFoundException(key);
|
||||
|
||||
public bool ContainsKey(string key)
|
||||
{
|
||||
read.Add(key);
|
||||
return values.ContainsKey(key);
|
||||
}
|
||||
|
||||
public bool TryGetValue(string key, [MaybeNullWhen(false)] out string? value)
|
||||
{
|
||||
read.Add(key);
|
||||
return values.TryGetValue(key, out value);
|
||||
}
|
||||
|
||||
public IEnumerator<KeyValuePair<string, string?>> GetEnumerator() => values.GetEnumerator();
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
||||
}
|
||||
|
||||
[GeneratedRegex("`([A-Z][A-Z0-9_]+)`")]
|
||||
private static partial Regex VariableName();
|
||||
|
||||
[GeneratedRegex(@"--stop-timeout (\d+)")]
|
||||
private static partial Regex StopTimeout();
|
||||
|
||||
[GeneratedRegex(@"publish\.sh|docker (push|login)")]
|
||||
private static partial Regex PublishCommand();
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The part of YAML the workflow of the CI uses, for the tests only: maps, lists, plain and quoted scalars, lists of
|
||||
/// strings in brackets, block text (| and >-) and comments. Anything else is refused with the line number, so a
|
||||
/// workflow written in a way this reader does not understand fails the test instead of passing unread.
|
||||
/// Values are <see cref="Dictionary{TKey,TValue}"/>, <see cref="List{T}"/> or <see cref="string"/>.
|
||||
/// </summary>
|
||||
internal sealed class MiniYaml
|
||||
{
|
||||
private readonly List<(int Number, int Indent, string Text)> _lines = [];
|
||||
private readonly string[] _raw;
|
||||
private int _at;
|
||||
|
||||
private MiniYaml(string text)
|
||||
{
|
||||
_raw = text.ReplaceLineEndings("\n").Split('\n');
|
||||
for (var i = 0; i < _raw.Length; i++)
|
||||
{
|
||||
var indent = _raw[i].Length - _raw[i].TrimStart(' ').Length;
|
||||
var body = _raw[i].Trim(' ');
|
||||
if (_raw[i][indent..].StartsWith('\t'))
|
||||
{
|
||||
throw Bad(i + 1, "tab");
|
||||
}
|
||||
|
||||
_lines.Add((i + 1, indent, body));
|
||||
}
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> Read(string text)
|
||||
{
|
||||
var yaml = new MiniYaml(text);
|
||||
yaml.SkipBlank();
|
||||
var map = yaml.Map(0);
|
||||
yaml.SkipBlank();
|
||||
return yaml._at == yaml._lines.Count ? map : throw Bad(yaml._lines[yaml._at].Number, "unexpected indentation");
|
||||
}
|
||||
|
||||
private static FormatException Bad(int line, string why) => new($"YAML line {line.ToString(CultureInfo.InvariantCulture)}: {why}.");
|
||||
|
||||
private void SkipBlank()
|
||||
{
|
||||
while (_at < _lines.Count && (_lines[_at].Text.Length == 0 || _lines[_at].Text.StartsWith('#')))
|
||||
{
|
||||
_at++;
|
||||
}
|
||||
}
|
||||
|
||||
private object Node(int indent, int line)
|
||||
{
|
||||
SkipBlank();
|
||||
if (_at >= _lines.Count || _lines[_at].Indent < indent)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
var found = _lines[_at];
|
||||
return found.Text.StartsWith("- ", StringComparison.Ordinal) ? List(found.Indent) : found.Indent >= indent ? Map(found.Indent) : throw Bad(line, "indentation");
|
||||
}
|
||||
|
||||
private List<object> List(int indent)
|
||||
{
|
||||
var list = new List<object>();
|
||||
for (SkipBlank(); _at < _lines.Count && _lines[_at].Indent == indent && _lines[_at].Text.StartsWith("- ", StringComparison.Ordinal); SkipBlank())
|
||||
{
|
||||
var (number, _, text) = _lines[_at];
|
||||
var body = text[2..].TrimStart();
|
||||
if (Key(body) is null)
|
||||
{
|
||||
list.Add(Scalar(body, number));
|
||||
_at++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// "- key: value" is a map whose first line starts after the dash.
|
||||
_lines[_at] = (number, indent + (text.Length - body.Length), body);
|
||||
list.Add(Map(_lines[_at].Indent));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private Dictionary<string, object> Map(int indent)
|
||||
{
|
||||
var map = new Dictionary<string, object>(StringComparer.Ordinal);
|
||||
for (SkipBlank(); _at < _lines.Count && _lines[_at].Indent == indent && !_lines[_at].Text.StartsWith("- ", StringComparison.Ordinal); SkipBlank())
|
||||
{
|
||||
var (number, _, text) = _lines[_at];
|
||||
if (Key(text) is not { } key)
|
||||
{
|
||||
throw Bad(number, "not a key");
|
||||
}
|
||||
|
||||
var rest = Uncommented(text[(key.Length + 1)..]).Trim();
|
||||
_at++;
|
||||
object value = rest switch
|
||||
{
|
||||
"" => Node(indent + 1, number),
|
||||
"|" => Block(indent, "\n"),
|
||||
">-" => Block(indent, " "),
|
||||
_ => Scalar(rest, number),
|
||||
};
|
||||
if (!map.TryAdd(key, value))
|
||||
{
|
||||
throw Bad(number, "duplicate key " + key);
|
||||
}
|
||||
}
|
||||
|
||||
return _at < _lines.Count && _lines[_at].Indent > indent ? throw Bad(_lines[_at].Number, "unexpected indentation") : map;
|
||||
}
|
||||
|
||||
private string Block(int indent, string join)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
var margin = -1;
|
||||
while (_at < _lines.Count && (_lines[_at].Text.Length == 0 || _lines[_at].Indent > indent))
|
||||
{
|
||||
if (_lines[_at].Text.Length > 0)
|
||||
{
|
||||
margin = margin < 0 ? _lines[_at].Indent : margin;
|
||||
lines.Add(_raw[_lines[_at].Number - 1][margin..]);
|
||||
}
|
||||
|
||||
_at++;
|
||||
}
|
||||
|
||||
return string.Join(join, lines);
|
||||
}
|
||||
|
||||
// A key is a plain word followed by ": " or by the end of the line.
|
||||
private static string? Key(string text)
|
||||
{
|
||||
var colon = text.IndexOf(':', StringComparison.Ordinal);
|
||||
return colon > 0 && (colon == text.Length - 1 || text[colon + 1] == ' ') && text.Take(colon).All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-') ? text[..colon] : null;
|
||||
}
|
||||
|
||||
private static string Uncommented(string text)
|
||||
{
|
||||
var quote = '\0';
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
if (quote != '\0')
|
||||
{
|
||||
quote = text[i] == quote ? '\0' : quote;
|
||||
}
|
||||
else if (text[i] is '"' or '\'')
|
||||
{
|
||||
quote = text[i];
|
||||
}
|
||||
else if (text[i] == '#' && i > 0 && text[i - 1] == ' ')
|
||||
{
|
||||
return text[..i];
|
||||
}
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
private static object Scalar(string text, int line)
|
||||
{
|
||||
if (text.StartsWith('['))
|
||||
{
|
||||
return text.EndsWith(']') ? text[1..^1].Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Select(t => Scalar(t, line)).ToList()
|
||||
: throw Bad(line, "open list");
|
||||
}
|
||||
|
||||
if (text[0] is '"' or '\'' && text[^1] == text[0] && text.Length > 1)
|
||||
{
|
||||
return text[1..^1];
|
||||
}
|
||||
|
||||
return text[0] is '&' or '*' or '{' or '!' or '|' or '>' or '"' or '@' or '`' ? throw Bad(line, "not supported: " + text) : text;
|
||||
}
|
||||
}
|
||||
@@ -82,7 +82,35 @@ int GuardDrill(string tag) =>
|
||||
|
||||
int BuildImage(string tag) =>
|
||||
Step("Costruzione dell'immagine Docker", "docker",
|
||||
["build", "-f", "deploy/docker/Dockerfile", "-t", $"gitea.encke-hake.ts.net/balbosoft/anubis:{tag}", "."]) ?? 0;
|
||||
["build", "-f", "deploy/docker/Dockerfile", "--build-arg", $"ANUBIS_VERSION={tag}", "--build-arg", $"ANUBIS_COMMIT={Commit()}",
|
||||
"-t", $"gitea.encke-hake.ts.net/balbosoft/anubis:{tag}", "."]) ?? 0;
|
||||
|
||||
// The commit written in the image, so a diagnostics report says which code it comes from; empty without git.
|
||||
string Commit()
|
||||
{
|
||||
var info = new ProcessStartInfo("git") { WorkingDirectory = root, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
info.ArgumentList.Add("rev-parse");
|
||||
info.ArgumentList.Add("HEAD");
|
||||
try
|
||||
{
|
||||
using var git = Process.Start(info)!;
|
||||
var commit = git.StandardOutput.ReadToEnd().Trim();
|
||||
git.WaitForExit();
|
||||
return git.ExitCode == 0 ? commit : "";
|
||||
}
|
||||
catch (System.ComponentModel.Win32Exception)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// The version of Directory.Build.props, the only place where it is written.
|
||||
string Version()
|
||||
{
|
||||
var props = File.ReadAllText(Path.Combine(root, "Directory.Build.props"));
|
||||
var start = props.IndexOf("<Version>", StringComparison.Ordinal) + "<Version>".Length;
|
||||
return props[start..props.IndexOf("</Version>", start, StringComparison.Ordinal)];
|
||||
}
|
||||
|
||||
// Demo data photographed at 1440 and 390 pixels, light and dark, to compare with docs/design (SPEC 13.1). Uses the
|
||||
// Edge or Chrome already on the computer, driven through its DevTools protocol: nothing to install (ADR 0007).
|
||||
@@ -188,9 +216,7 @@ static int FreePort()
|
||||
// the Phase 10 installer exists. It needs the ASP.NET Core 10 runtime on the computer.
|
||||
int ReleaseWindows()
|
||||
{
|
||||
var props = File.ReadAllText(Path.Combine(root, "Directory.Build.props"));
|
||||
var start = props.IndexOf("<Version>", StringComparison.Ordinal) + "<Version>".Length;
|
||||
var version = props[start..props.IndexOf("</Version>", start, StringComparison.Ordinal)];
|
||||
var version = Version();
|
||||
var name = $"anubis-{version}-win-x64";
|
||||
var output = Path.Combine(root, "artifacts", "release");
|
||||
var folder = Path.Combine(output, name);
|
||||
|
||||
Reference in new issue
Block a user