cli: carlos system pdf status
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+381
−3
apimode.go+26 −0docs/site/cli.md+6 −0internal/console/apisystem.go+78 −0internal/console/apisystem_test.go+131 −0internal/console/authcli.go+1 −0internal/console/claim_invariant_fixtures_test.go+1 −0internal/console/claim_invariant_probes_read_test.go+1 −0internal/console/svcroutes_test.go+3 −2internal/console/testdata/claim-routes.txt+1 −0system.go+50 −1system_test.go+83 −0
CI failed — run details
diff --git a/apimode.go b/apimode.go| index f65f9d99c..20e3bf86a 100644 |
| --- a/apimode.go |
| +++ b/apimode.go |
| @@ -2204,6 +2204,32 @@ func (s *apiSession) systemAntivirusStatus(ctx context.Context) (apiSystemAntivi |
| return out, nil |
| } |
| +type systemPDFStatus struct { |
| + Configured bool `json:"configured"` |
| + Addr string `json:"addr"` |
| + Healthy bool `json:"healthy"` |
| + Version string `json:"version"` |
| + Error string `json:"error"` |
| + Rendered24h int64 `json:"rendered_24h"` |
| + Refused24h int64 `json:"refused_24h"` |
| + Failed24h int64 `json:"failed_24h"` |
| +} |
| + |
| +func (a *apiSession) systemPDFStatus(ctx context.Context) (systemPDFStatus, error) { |
| + status, body, err := a.getJSON(ctx, "/api/cli/system/pdf") |
| + if err != nil { |
| + return systemPDFStatus{}, err |
| + } |
| + if status != http.StatusOK { |
| + return systemPDFStatus{}, apiErrorFromBody(status, body) |
| + } |
| + var out systemPDFStatus |
| + if err := json.Unmarshal(body, &out); err != nil { |
| + return systemPDFStatus{}, err |
| + } |
| + return out, nil |
| +} |
| + |
| func storeOperatorError(status int, body []byte) error { |
| var e struct { |
| Error string `json:"error"` |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index f0462cce6..a0016ae65 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -2754,6 +2754,12 @@ Before starting claim-enabled services on a box with legacy journals, stop the e |
| The migration census reads the backfill plan `backfill-collect` wrote. It reports each ordinary instance route on the box as that box's installation, so `backfill-adopt` can give the host to this box. If the window masks units by moving each unit file aside and linking `/dev/null` in its place, pass `--window DIR`, the window's directory, with the originals in `DIR/held`. The census then accepts those masks and no others. |
| +#### carlos system pdf status |
| + |
| +```sh |
| +carlos system pdf status |
| +``` |
| + |
| #### Deployment-wide object scanning |
| ```sh |
diff --git a/internal/console/apisystem.go b/internal/console/apisystem.go| index 8e2309b1a..e82976122 100644 |
| --- a/internal/console/apisystem.go |
| +++ b/internal/console/apisystem.go |
| @@ -22,8 +22,10 @@ package console |
| import ( |
| "context" |
| "errors" |
| + "io" |
| "log" |
| "net/http" |
| + "net/url" |
| "os" |
| "strings" |
| "time" |
| @@ -220,6 +222,82 @@ func (s *Server) handleAPISystemAntivirusGet(w http.ResponseWriter, r *http.Requ |
| writeJSON(w, http.StatusOK, s.systemAntivirusReply(ctx)) |
| } |
| +func (s *Server) handleAPISystemPDFGet(w http.ResponseWriter, r *http.Request) { |
| + if _, ok := s.apiSystemOperator(w, r); !ok { |
| + return |
| + } |
| + rendered, refused, failed, err := s.store.PDFRenderSummary(r.Context(), time.Now().Add(-24*time.Hour)) |
| + if err != nil { |
| + log.Printf("console: system pdf summary: %v", err) |
| + jsonError(w, http.StatusInternalServerError, err.Error()) |
| + return |
| + } |
| + out := map[string]any{ |
| + "configured": s.cfg.PDFEngine != "", |
| + "addr": s.cfg.PDFEngine, |
| + "healthy": false, |
| + "version": "", |
| + "error": "", |
| + "rendered_24h": rendered, |
| + "refused_24h": refused, |
| + "failed_24h": failed, |
| + } |
| + if s.cfg.PDFEngine != "" { |
| + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) |
| + defer cancel() |
| + version, err := systemPDFEngineStatus(ctx, s.cfg.PDFEngine) |
| + if err != nil { |
| + out["error"] = err.Error() |
| + } else { |
| + out["healthy"], out["version"] = true, version |
| + } |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
| + |
| +func systemPDFEngineStatus(ctx context.Context, addr string) (string, error) { |
| + engine, err := url.Parse(addr) |
| + if err != nil || engine.Scheme != "http" || engine.Hostname() == "" { |
| + return "", errors.New(pdfText("pdf.engine_down")) |
| + } |
| + transport := http.DefaultTransport.(*http.Transport).Clone() |
| + transport.Proxy = nil |
| + defer transport.CloseIdleConnections() |
| + client := &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { |
| + return http.ErrUseLastResponse |
| + }} |
| + var version string |
| + for _, path := range []string{"/health", "/version"} { |
| + target := url.URL{Scheme: engine.Scheme, Host: engine.Host, Path: path} |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil) |
| + if err != nil { |
| + return "", err |
| + } |
| + resp, err := client.Do(req) |
| + if err != nil { |
| + return "", err |
| + } |
| + if resp.StatusCode != http.StatusOK { |
| + resp.Body.Close() |
| + return "", errors.New(resp.Status) |
| + } |
| + if path == "/version" { |
| + body, err := io.ReadAll(io.LimitReader(resp.Body, 4097)) |
| + resp.Body.Close() |
| + if err != nil { |
| + return "", err |
| + } |
| + version = strings.TrimSpace(string(body)) |
| + if version == "" || len(body) > 4096 { |
| + return "", errors.New(pdfText("pdf.engine_down")) |
| + } |
| + } else { |
| + resp.Body.Close() |
| + } |
| + } |
| + return version, nil |
| +} |
| + |
| // handleAPISystemAntivirusSet answers `enable` and `disable`. |
| // |
| // `enable` refuses when no engine is wired: a record claiming enabled with |
diff --git a/internal/console/apisystem_test.go b/internal/console/apisystem_test.go| index 6b700cc96..c1b439273 100644 |
| --- a/internal/console/apisystem_test.go |
| +++ b/internal/console/apisystem_test.go |
| @@ -2,13 +2,18 @@ package console |
| import ( |
| "context" |
| + "io" |
| "net/http" |
| + "net/http/httptest" |
| + "reflect" |
| "strings" |
| + "sync/atomic" |
| "testing" |
| "time" |
| "github.com/carlosframework/platform/internal/objstore" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| ) |
| const systemAntivirusURL = "/api/cli/system/antivirus" |
| @@ -177,3 +182,129 @@ func TestSystemAntivirusDisableRepairsAnUnreadableRecord(t *testing.T) { |
| t.Fatalf("by = %q, want the operator who repaired it", av.By) |
| } |
| } |
| + |
| +func TestSystemPDFStatus(t *testing.T) { |
| + const path = "/api/cli/system/pdf" |
| + t.Run("healthy and deployment summary", func(t *testing.T) { |
| + var health, version atomic.Int32 |
| + engine := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method != http.MethodGet || r.Header.Get("Authorization") != "" { |
| + t.Errorf("engine request = %s, auth %q", r.Method, r.Header.Get("Authorization")) |
| + } |
| + switch r.URL.Path { |
| + case "/health": |
| + health.Add(1) |
| + io.WriteString(w, `{ "status": "up" }`) |
| + case "/version": |
| + version.Add(1) |
| + io.WriteString(w, "8.21.1\n") |
| + default: |
| + t.Errorf("unexpected engine path %q", r.URL.Path) |
| + http.NotFound(w, r) |
| + } |
| + })) |
| + defer engine.Close() |
| + fx, token := systemArmed(t, "code-pdf-status") |
| + fx.srv.cfg.PDFEngine = engine.URL |
| + now := time.Now() |
| + for _, row := range []pdfRenderRow{ |
| + {Account: fixtureAcct, App: fixtureApp, Outcome: pdfRendered, At: now}, |
| + {Account: "other", App: "shop", Outcome: pdfRendered, At: now}, |
| + {Account: fixtureAcct, App: fixtureApp, Outcome: pdfRefused, At: now}, |
| + {Account: fixtureAcct, App: fixtureApp, Outcome: pdfEngineError, At: now}, |
| + {Account: fixtureAcct, App: fixtureApp, Outcome: pdfFailed, At: now}, |
| + {Account: fixtureAcct, App: fixtureApp, Outcome: pdfAborted, At: now}, |
| + {Account: fixtureAcct, App: fixtureApp, Outcome: pdfRendered, At: now.Add(-25 * time.Hour)}, |
| + {Account: fixtureAcct, App: fixtureApp, Outcome: pdfRefused, At: now.Add(-25 * time.Hour)}, |
| + {Account: fixtureAcct, App: fixtureApp, Outcome: pdfFailed, At: now.Add(-25 * time.Hour)}, |
| + } { |
| + if err := fx.st.RecordPDFRender(t.Context(), row); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + status, out := getJSON(t, fx.ts.URL+path, token) |
| + want := map[string]any{"configured": true, "addr": engine.URL, "healthy": true, "version": "8.21.1", "error": "", "rendered_24h": float64(2), "refused_24h": float64(1), "failed_24h": float64(3)} |
| + if status != http.StatusOK || !reflect.DeepEqual(out, want) { |
| + t.Fatalf("status = %d, body = %#v; want 200, %#v", status, out, want) |
| + } |
| + if health.Load() != 1 || version.Load() != 1 { |
| + t.Fatalf("engine requests: health=%d version=%d", health.Load(), version.Load()) |
| + } |
| + }) |
| + t.Run("unconfigured", func(t *testing.T) { |
| + fx, token := systemArmed(t, "code-pdf-unconfigured") |
| + status, out := getJSON(t, fx.ts.URL+path, token) |
| + want := map[string]any{"configured": false, "addr": "", "healthy": false, "version": "", "error": "", "rendered_24h": float64(0), "refused_24h": float64(0), "failed_24h": float64(0)} |
| + if status != http.StatusOK || !reflect.DeepEqual(out, want) { |
| + t.Fatalf("status = %d, body = %#v; want 200, %#v", status, out, want) |
| + } |
| + }) |
| + t.Run("operator only", func(t *testing.T) { |
| + var calls atomic.Int32 |
| + engine := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1) })) |
| + defer engine.Close() |
| + fx, token := systemArmed(t, "code-pdf-operator") |
| + fx.srv.cfg.PDFEngine = engine.URL |
| + fx.srv.cfg.StoreOperators = []string{"someone-else@keymail.dev"} |
| + if status, out := getJSON(t, fx.ts.URL+path, token); status != http.StatusForbidden { |
| + t.Fatalf("non-operator = %d %v, want 403", status, out) |
| + } |
| + service := serviceToken(t, fx.st, OpsAccountID, "pdf-status", fixtureApp, svcrole.Service) |
| + status, out := getJSON(t, fx.ts.URL+path, service) |
| + avStatus, _ := getJSON(t, fx.ts.URL+systemAntivirusURL, service) |
| + if status != avStatus || status != http.StatusForbidden { |
| + t.Fatalf("Service token = %d %v; antivirus = %d, want matching 403", status, out, avStatus) |
| + } |
| + if calls.Load() != 0 { |
| + t.Fatalf("unauthorized requests contacted engine %d times", calls.Load()) |
| + } |
| + }) |
| + for _, failedPath := range []string{"/health", "/version"} { |
| + t.Run(failedPath+" fails", func(t *testing.T) { |
| + engine := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path == failedPath { |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + return |
| + } |
| + io.WriteString(w, "ok") |
| + })) |
| + defer engine.Close() |
| + fx, token := systemArmed(t, "code-pdf-failed") |
| + fx.srv.cfg.PDFEngine = engine.URL |
| + status, out := getJSON(t, fx.ts.URL+path, token) |
| + if status != http.StatusOK || out["configured"] != true || out["healthy"] != false || out["error"] == "" { |
| + t.Fatalf("failed engine = %d %v", status, out) |
| + } |
| + }) |
| + } |
| + t.Run("unreachable", func(t *testing.T) { |
| + engine := httptest.NewServer(http.NotFoundHandler()) |
| + engine.Close() |
| + fx, token := systemArmed(t, "code-pdf-unreachable") |
| + fx.srv.cfg.PDFEngine = engine.URL |
| + status, out := getJSON(t, fx.ts.URL+path, token) |
| + if status != http.StatusOK || out["configured"] != true || out["healthy"] != false || out["error"] == "" { |
| + t.Fatalf("unreachable engine = %d %v", status, out) |
| + } |
| + }) |
| + t.Run("five second budget includes version body", func(t *testing.T) { |
| + engine := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path == "/version" { |
| + w.WriteHeader(http.StatusOK) |
| + w.(http.Flusher).Flush() |
| + <-r.Context().Done() |
| + } |
| + })) |
| + defer engine.Close() |
| + fx, token := systemArmed(t, "code-pdf-timeout") |
| + fx.srv.cfg.PDFEngine = engine.URL |
| + start := time.Now() |
| + status, out := getJSON(t, fx.ts.URL+path, token) |
| + if elapsed := time.Since(start); elapsed < 4*time.Second || elapsed > 7*time.Second { |
| + t.Errorf("timeout took %s, want 5s", elapsed) |
| + } |
| + if status != http.StatusOK || out["healthy"] != false || out["error"] == "" { |
| + t.Fatalf("timeout = %d %v", status, out) |
| + } |
| + }) |
| +} |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index a60d22049..c0f2b249b 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -1139,6 +1139,7 @@ func (s *Server) registerCLIRoutes() { |
| s.cliRoute("GET /api/cli/system/layout", svcrole.Set{}, s.handleAPISystemLayoutGet) |
| s.cliRoute("POST /api/cli/system/layout", svcrole.Set{}, s.handleAPISystemLayoutSet) |
| s.cliRoute("GET /api/cli/system/antivirus", svcrole.Set{}, s.handleAPISystemAntivirusGet) |
| + s.cliRoute("GET /api/cli/system/pdf", svcrole.Set{}, s.handleAPISystemPDFGet) |
| s.cliRoute("POST /api/cli/system/antivirus", svcrole.Set{}, s.handleAPISystemAntivirusSet) |
| s.cliRoute("POST /api/cli/system/antivirus/rotate-webhook-key", svcrole.Set{}, s.handleAPISystemWebhookRotate) |
| // Platform GeoIP (geoip spec §4.2): apiSystemRoller, like the update |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 9cb5f30e7..169eab9a9 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -901,6 +901,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route GET /api/cli/system/hosts-used/status": claimRead("operator view of the hostname history: its mode, a count of control/hosts-used/ marks, closed fleets and the floor; writes nothing"), |
| "route GET /api/cli/system/jobs/{id}": claimRead("reads a system update job"), |
| "route GET /api/cli/system/layout": claimRead("reads the deployment layout intent"), |
| + "route GET /api/cli/system/pdf": claimRead("reads PDF engine health, version and render counts; writes nothing"), |
| "route GET /api/cli/system/pointer-digests": claimRead("operator report of each account's pointer digest marker and the channels whose head has no digest; writes nothing"), |
| "route GET /api/cli/system/status": claimRead("reads platform release status"), |
| "route GET /apps": claimRead("legacy redirect into the account"), |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index f0adf4e6c..9120893ce 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -358,6 +358,7 @@ var claimReadProbes = map[string]claimProbe{ |
| "/api/cli/accounts/bab/plan", `"plan":"free"`), |
| "route GET /api/cli/billing/problems": claimAPIRead(claimBillingProblemWorld, "/api/cli/billing/problems", `"reason":"unrecognised"`), |
| "route GET /api/cli/system/antivirus": claimAPIRead(nil, "/api/cli/system/antivirus", `"wired":true`), |
| + "route GET /api/cli/system/pdf": claimAPIRead(nil, "/api/cli/system/pdf", `"configured":false`, `"rendered_24h":0`, `"refused_24h":0`, `"failed_24h":0`), |
| "route GET /api/cli/system/geoip": func() claimProbe { |
| p := claimAPIRead(claimWorldGeoip, "/api/cli/system/geoip", `"pointer"`, "GeoIP2-City") |
| p.serial = "claimWorldGeoip swaps the package variable geoipProbeAddrs (withFixtureProbes)" |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index 6816dc5f8..fed493d37 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -105,6 +105,7 @@ var closedDoors = []string{ |
| // across every store on the deployment — an owner's decision, not a |
| // credential's. |
| "GET /api/cli/system/antivirus", |
| + "GET /api/cli/system/pdf", |
| "POST /api/cli/system/antivirus", |
| "POST /api/cli/system/antivirus/rotate-webhook-key", |
| // Platform GeoIP (geoip spec §4.2): deployment-wide, operator-only, a |
| @@ -1153,8 +1154,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) { |
| } |
| seen++ |
| } |
| - if seen != len(closedDoors) || seen != 79 { |
| - t.Errorf("walked %d closed doors, want all %d (and 79 today: three domain purchase doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)", |
| + if seen != len(closedDoors) || seen != 80 { |
| + t.Errorf("walked %d closed doors, want all %d (and 80 today: three domain purchase doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, the PDF status door, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)", |
| seen, len(closedDoors)) |
| } |
| } |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 5bafac76a..c33982f6f 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -127,6 +127,7 @@ route GET /api/cli/system/geoip |
| route GET /api/cli/system/hosts-used/status |
| route GET /api/cli/system/jobs/{id} |
| route GET /api/cli/system/layout |
| +route GET /api/cli/system/pdf |
| route GET /api/cli/system/pointer-digests |
| route GET /api/cli/system/status |
| route GET /apps |
diff --git a/system.go b/system.go| index 5fa5241e0..2fdeb848a 100644 |
| --- a/system.go |
| +++ b/system.go |
| @@ -52,7 +52,7 @@ func systemVerb(args []string) (verb string, rest []string, component string) { |
| // untouched in rest for runSystemAntivirusVerb to read. |
| // layout is a family too: migrate|revert|status stay in rest for |
| // runSystemLayout. |
| - case "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "host-env", "db-worker", "named-units", "help", "-h", "--help": |
| + case "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "pdf", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "host-env", "db-worker", "named-units", "help", "-h", "--help": |
| return args[0], args[1:], component |
| } |
| return "", args, component |
| @@ -85,6 +85,8 @@ func runSystem(args []string) { |
| runSystemCancelActivation(rest) |
| case "antivirus": |
| runSystemAntivirusVerb(rest) |
| + case "pdf": |
| + runSystemPDFVerb(rest) |
| case "layout": |
| runSystemLayout(rest) |
| case "geoip": |
| @@ -144,6 +146,7 @@ func systemUsage() { |
| fmt.Fprint(os.Stderr, `usage: carlos system <verb> [flags] |
| carlos system router <verb> [flags] |
| carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags] |
| + carlos system pdf status |
| carlos system geoip <publish|status|off> [flags] |
| carlos system seeds-floor publish --min-release <release> |
| carlos system legacy-routes assign --name <name> --to <account>/<app> |
| @@ -195,6 +198,8 @@ A box a region's group launches (region HA): |
| Deployment-wide settings (CARLOS_STORE_OPERATORS): |
| + pdf status |
| + |
| antivirus status is object scanning wired, switched on, and answering? |
| Reports wiring and policy separately, because they fail |
| separately. |
| @@ -625,6 +630,50 @@ func runSystemRollback(args []string) { |
| fmt.Fprintf(stdout, "%s %s → %s\n", colorFor(stdout).ok("rolled back"), *channel, out.Version) |
| } |
| +func runSystemPDFVerb(rest []string) { |
| + if len(rest) == 0 { |
| + systemUsage() |
| + os.Exit(2) |
| + } |
| + switch rest[0] { |
| + case "help", "-h", "--help": |
| + systemUsage() |
| + return |
| + case "status": |
| + default: |
| + systemUsage() |
| + os.Exit(2) |
| + } |
| + fs := flag.NewFlagSet("system pdf status", flag.ExitOnError) |
| + consoleFlag := consoleOption(fs, "console to act through (default: the only logged-in one)") |
| + fs.Usage = flagUsage(fs, "") |
| + fs.Parse(rest[1:]) |
| + if fs.NArg() != 0 { |
| + fs.Usage() |
| + os.Exit(2) |
| + } |
| + sess := requireStoreAPISession(*consoleFlag) |
| + st, err := sess.systemPDFStatus(context.Background()) |
| + if err != nil { |
| + log.Fatal(err) |
| + } |
| + printSystemPDF(stdout, st) |
| +} |
| + |
| +func printSystemPDF(w io.Writer, st systemPDFStatus) { |
| + if !st.Configured { |
| + fmt.Fprintln(w, "engine: not configured") |
| + } else { |
| + fmt.Fprintf(w, "engine: configured at %s\n", st.Addr) |
| + if st.Healthy { |
| + fmt.Fprintf(w, "health: ok (Gotenberg %s)\n", st.Version) |
| + } else { |
| + fmt.Fprintf(w, "health: not answering (%s)\n", st.Error) |
| + } |
| + } |
| + fmt.Fprintf(w, "last 24 hours: %d rendered, %d refused, %d failed\n", st.Rendered24h, st.Refused24h, st.Failed24h) |
| +} |
| + |
| // ---- carlos system antivirus ------------------------------------------- |
| // runSystemAntivirusVerb reads the sub-verb off rest. systemVerb hands the |
diff --git a/system_test.go b/system_test.go| index 36b8d734b..02c3592de 100644 |
| --- a/system_test.go |
| +++ b/system_test.go |
| @@ -2,8 +2,14 @@ package main |
| import ( |
| "bytes" |
| + "context" |
| "errors" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| "os/exec" |
| + "path/filepath" |
| "strings" |
| "testing" |
| "time" |
| @@ -22,6 +28,7 @@ func TestSystemVerbAcceptsTheComponentForm(t *testing.T) { |
| // The system units' floor gate: both file paths stay in rest. |
| {[]string{"floor-allows-prev", "/data/.moves/floor.min-release", "/opt/carlos/carlos.prev.allowed"}, "floor-allows-prev", "router", 2}, |
| // antivirus is a family: its sub-verb stays in rest untouched. |
| + {[]string{"pdf", "status"}, "pdf", "router", 1}, |
| {[]string{"antivirus", "status"}, "antivirus", "router", 1}, |
| {[]string{"antivirus", "enable", "--console", "x"}, "antivirus", "router", 3}, |
| {[]string{"antivirus"}, "antivirus", "router", 0}, |
| @@ -338,3 +345,79 @@ func TestSystemJoinVerbGone(t *testing.T) { |
| t.Fatalf("join still a verb: %q", v) |
| } |
| } |
| + |
| +func TestPrintSystemPDF(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + st systemPDFStatus |
| + want string |
| + }{ |
| + {"unconfigured", systemPDFStatus{}, "engine: not configured\nlast 24 hours: 0 rendered, 0 refused, 0 failed\n"}, |
| + {"healthy", systemPDFStatus{Configured: true, Addr: "http://pdf:3000", Healthy: true, Version: "8.21.1", Rendered24h: 12, Refused24h: 3, Failed24h: 4}, "engine: configured at http://pdf:3000\nhealth: ok (Gotenberg 8.21.1)\nlast 24 hours: 12 rendered, 3 refused, 4 failed\n"}, |
| + {"unhealthy", systemPDFStatus{Configured: true, Addr: "http://pdf:3000", Error: "connection refused", Rendered24h: 7}, "engine: configured at http://pdf:3000\nhealth: not answering (connection refused)\nlast 24 hours: 7 rendered, 0 refused, 0 failed\n"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + var out bytes.Buffer |
| + printSystemPDF(&out, tc.st) |
| + if out.String() != tc.want { |
| + t.Fatalf("output = %q, want %q", out.String(), tc.want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestSystemPDFClient(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + status int |
| + body string |
| + wantErr bool |
| + }{ |
| + {"ok", http.StatusOK, `{"configured":true,"addr":"http://pdf:3000","healthy":true,"version":"8.21.1","error":"","rendered_24h":12,"refused_24h":3,"failed_24h":4}`, false}, |
| + {"forbidden", http.StatusForbidden, `{"error":"operator required"}`, true}, |
| + {"malformed", http.StatusOK, `{`, true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method != http.MethodGet || r.URL.Path != "/api/cli/system/pdf" || r.Header.Get("Authorization") != "Bearer cli-token" { |
| + t.Errorf("request = %s %s, auth = %q", r.Method, r.URL.Path, r.Header.Get("Authorization")) |
| + } |
| + w.WriteHeader(tc.status) |
| + io.WriteString(w, tc.body) |
| + })) |
| + defer ts.Close() |
| + st, err := newTestSession(ts.URL).systemPDFStatus(context.Background()) |
| + if (err != nil) != tc.wantErr { |
| + t.Fatalf("status = %+v, error = %v", st, err) |
| + } |
| + if !tc.wantErr && st != (systemPDFStatus{Configured: true, Addr: "http://pdf:3000", Healthy: true, Version: "8.21.1", Rendered24h: 12, Refused24h: 3, Failed24h: 4}) { |
| + t.Fatalf("decoded status = %+v", st) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestSystemPDFThroughTheBinary(t *testing.T) { |
| + bin := buildCarlos(t) |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method != http.MethodGet || r.URL.Path != "/api/cli/system/pdf" || r.Header.Get("Authorization") != "Bearer tok-operator" { |
| + t.Errorf("request = %s %s, auth = %q", r.Method, r.URL.Path, r.Header.Get("Authorization")) |
| + http.NotFound(w, r) |
| + return |
| + } |
| + io.WriteString(w, `{"configured":true,"addr":"http://pdf:3000","healthy":true,"version":"8.21.1","error":"","rendered_24h":12,"refused_24h":3,"failed_24h":4}`) |
| + })) |
| + defer ts.Close() |
| + credPath := filepath.Join(t.TempDir(), "credentials") |
| + if err := os.WriteFile(credPath, []byte(`{"version":1,"credentials":[{"console":"`+ts.URL+`","address":"paul@keymail.dev","token":"tok-operator"}]}`), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := exec.Command(bin, "system", "pdf", "status", "--console", ts.URL) |
| + cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+credPath) |
| + cmd.Dir = t.TempDir() |
| + out, err := cmd.Output() |
| + want := "engine: configured at http://pdf:3000\nhealth: ok (Gotenberg 8.21.1)\nlast 24 hours: 12 rendered, 3 refused, 4 failed\n" |
| + if err != nil || string(out) != want { |
| + t.Fatalf("command = %v, output = %q; want %q", err, out, want) |
| + } |
| +} |