diff --git a/Dockerfile b/Dockerfile index 765e1ea..84da623 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,8 +10,5 @@ RUN CGO_ENABLED=0 go build -ldflags "-X main.Version=${CHECKER_VERSION}" -o /che FROM scratch COPY --from=builder /checker-dummy /checker-dummy -USER 65534:65534 EXPOSE 8080 -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD ["/checker-dummy", "-healthcheck"] ENTRYPOINT ["/checker-dummy"] diff --git a/Makefile b/Makefile index 3271216..6ccbd22 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ CHECKER_SOURCES := main.go $(wildcard checker/*.go) GO_LDFLAGS := -X main.Version=$(CHECKER_VERSION) -.PHONY: all plugin docker test clean +.PHONY: all plugin docker clean all: $(CHECKER_NAME) @@ -21,8 +21,5 @@ $(CHECKER_NAME).so: $(CHECKER_SOURCES) $(wildcard plugin/*.go) docker: docker build --build-arg CHECKER_VERSION=$(CHECKER_VERSION) -t $(CHECKER_IMAGE) . -test: - go test -tags standalone ./... - clean: rm -f $(CHECKER_NAME) $(CHECKER_NAME).so diff --git a/README.md b/README.md index 6e7c166..2ef4d2e 100644 --- a/README.md +++ b/README.md @@ -19,12 +19,11 @@ Use this as a template when you create your own checker. - [Step 5: Write Evaluation Rules](#step-5-write-evaluation-rules) - [Step 6: Wire It Up (main.go)](#step-6-wire-it-up-maingo) - [Step 7: Create the Plugin Entrypoint](#step-7-create-the-plugin-entrypoint) -5. [Optional: Standalone Human UI (`CheckerInteractive`)](#optional-standalone-human-ui-checkerinteractive) -6. [Running the Checker](#running-the-checker) -7. [Testing with curl](#testing-with-curl) -8. [Deploying to happyDomain](#deploying-to-happydomain) -9. [License & happyDomain compatibility](#license--happydomain-compatibility) -10. [Going Further](#going-further) +5. [Running the Checker](#running-the-checker) +6. [Testing with curl](#testing-with-curl) +7. [Deploying to happyDomain](#deploying-to-happydomain) +8. [License & happyDomain compatibility](#license--happydomain-compatibility) +9. [Going Further](#going-further) --- @@ -43,6 +42,34 @@ Every checker does three things: A checker can run in three modes: +### Standalone HTTP Server (External Checker) + +The checker runs as its own process and exposes an HTTP API. happyDomain communicates with it over the network. This is the most flexible option: you can write your checker in any language, deploy it independently, and scale it separately. + +``` +┌─────────────┐ HTTP ┌─────────────────┐ +│ happyDomain │ ──────────► │ checker-dummy │ +│ server │ ◄────────── │ (this program) │ +└─────────────┘ └─────────────────┘ +``` + +### In-Process Plugin + +The checker is compiled as a Go plugin (`.so` file) and loaded directly into the happyDomain process. This is simpler to deploy (single binary) but requires the checker to be written in Go. + +``` +┌──────────────────────────────────────┐ +│ happyDomain server │ +│ │ +│ ┌──────────────────────────────┐ │ +│ │ checker-dummy.so (plugin) │ │ +│ │ checker-ping.so (plugin) │ │ +│ │ checker-matrix.so (plugin) │ │ +│ │ checker-....so (plugin) │ │ +│ └──────────────────────────────┘ │ +└──────────────────────────────────────┘ +``` + ### Built-in Checker The checker package can be imported directly into the happyDomain server and registered at init time: no plugin loading, no separate process. This avoids the operational burden of Go's plugin system (matching toolchain versions, CGO, `.so` distribution) entirely. @@ -66,34 +93,6 @@ This mode is reserved for checkers maintained as part of the happyDomain project **Both standalone, plugin and built-in modes use the same checker code; only the entry point differs.** -### In-Process Plugin - -The checker is compiled as a Go plugin (`.so` file) and loaded directly into the happyDomain process. This is simpler to deploy (single binary) but requires the checker to be written in Go. - -``` -┌──────────────────────────────────────┐ -│ happyDomain server │ -│ │ -│ ┌──────────────────────────────┐ │ -│ │ checker-dummy.so (plugin) │ │ -│ │ checker-ping.so (plugin) │ │ -│ │ checker-matrix.so (plugin) │ │ -│ │ checker-....so (plugin) │ │ -│ └──────────────────────────────┘ │ -└──────────────────────────────────────┘ -``` - -### Standalone HTTP Server (External Checker) - -The checker runs as its own process and exposes an HTTP API. happyDomain communicates with it over the network. This is the most flexible option: you can write your checker in any language, deploy it independently, and scale it separately. - -``` -┌─────────────┐ HTTP ┌─────────────────┐ -│ happyDomain │ ──────────► │ checker-dummy │ -│ server │ ◄────────── │ (this program) │ -└─────────────┘ └─────────────────┘ -``` - ## Repository Structure @@ -161,7 +160,6 @@ You can also implement optional interfaces to unlock additional features: | `CheckerDefinitionProvider` | `/definition` and `/evaluate` endpoints | | `CheckerMetricsReporter` | `/report` endpoint (JSON metrics) | | `CheckerHTMLReporter` | `/report` endpoint (HTML) | -| `CheckerInteractive` | `GET`/`POST /check` human-friendly HTML UI | In this example, we implement all three optional interfaces: @@ -293,19 +291,19 @@ A rule implements the `CheckRule` interface: type CheckRule interface { Name() string Description() string - Evaluate(ctx context.Context, obs ObservationGetter, opts CheckerOptions) []CheckState + Evaluate(ctx context.Context, obs ObservationGetter, opts CheckerOptions) CheckState } ``` Optionally, your rule can also implement `ValidateOptions(opts) error` for early validation. -The `Evaluate` method receives an `ObservationGetter` to retrieve the collected data and returns a **slice** of `CheckState`, one entry per element being evaluated: +The `Evaluate` method receives an `ObservationGetter` to retrieve the collected data: ```go -func (r *dummyRule) Evaluate(ctx context.Context, obs ObservationGetter, opts CheckerOptions) []CheckState { +func (r *dummyRule) Evaluate(ctx context.Context, obs ObservationGetter, opts CheckerOptions) CheckState { var data DummyData if err := obs.Get(ctx, ObservationKeyDummy, &data); err != nil { - return []CheckState{{Status: StatusError, Message: "..."}} + return CheckState{Status: StatusError, Message: "..."} } warningThreshold := sdk.GetFloatOption(opts, "warningThreshold", 50) @@ -313,52 +311,16 @@ func (r *dummyRule) Evaluate(ctx context.Context, obs ObservationGetter, opts Ch switch { case data.Score < criticalThreshold: - return []CheckState{{Status: StatusCrit, ...}} + return CheckState{Status: StatusCrit, ...} case data.Score < warningThreshold: - return []CheckState{{Status: StatusWarn, ...}} + return CheckState{Status: StatusWarn, ...} default: - return []CheckState{{Status: StatusOK, ...}} + return CheckState{Status: StatusOK, ...} } } ``` -**Contract**: `Evaluate` must return at least one state. If a rule has nothing to evaluate, return a single `CheckState` describing that fact (typically `StatusInfo` or `StatusOK`). The SDK server injects a `StatusUnknown` placeholder if a rule returns an empty or nil slice. - -**The `CheckState` struct**: - -```go -type CheckState struct { - Status Status - Message string - RuleName string // set automatically by the server, do not set yourself - Code string // optional, use to distinguish kinds of finding within one rule - Subject string // opaque per-element identifier (hostname, cert serial, …) - Meta map[string]any -} -``` - -- **`Subject`** identifies the element a state refers to (a hostname, a certificate serial, a nameserver FQDN, …). Leave empty for rules that produce a single global result. Do **not** repeat the subject inside `Message`, the UI renders it separately. -- **`RuleName`** is stamped automatically by the server with `rule.Name()` on every returned state. UIs should use `RuleName` (not `Code`) to group, filter, or offer "disable this rule" controls. -- **`Code`** is left untouched by the server. Set it only when your rule emits several kinds of finding (e.g. `too_many_lookups` vs `syntax_error`). - -**One state per subject**: a rule that iterates over N elements should emit N states (one per `Subject`) instead of concatenating them into a single `Message`: - -```go -func (r *CertExpiryRule) Evaluate(...) []CheckState { - out := make([]CheckState, 0, len(certs)) - for _, cert := range certs { - s := evalCert(cert) - s.Subject = cert.Host - out = append(out, s) - } - if len(out) == 0 { - return []CheckState{{Status: StatusInfo, Message: "no certificate to evaluate"}} - } - return out -} -``` - -**Status values**: `StatusOK`, `StatusWarn`, `StatusCrit`, `StatusError`, `StatusUnknown`, `StatusInfo`. +**Status values**: `StatusOK`, `StatusWarn`, `StatusCrit`, `StatusError`, `StatusUnknown`. You can define **multiple rules** per checker. Each rule evaluates the same collected data from a different angle. Users can enable/disable rules individually in the UI. @@ -389,7 +351,6 @@ func main() { | `GET /definition` | - | `CheckerDefinitionProvider` | | `POST /evaluate` | - | `CheckerDefinitionProvider` | | `POST /report` | - | `CheckerMetricsReporter` or `CheckerHTMLReporter` | -| `GET`/`POST /check` | - | `CheckerInteractive` | ### Step 7: Create the Plugin Entrypoint @@ -425,53 +386,6 @@ Then drop the resulting `checker-dummy.so` into one of happyDomain's configured --- -## Optional: Standalone Human UI (`CheckerInteractive`) - -The SDK provides an optional `CheckerInteractive` interface that exposes a browser-friendly `/check` route, letting your checker be used as a standalone DNS-probing tool without a happyDomain instance in front of it. - -```go -type CheckerInteractive interface { - RenderForm() []CheckerOptionField - ParseForm(r *http.Request) (CheckerOptions, error) -} -``` - -When a provider implements it, `NewServer` automatically registers: - -- `GET /check`, renders an HTML form derived from `RenderForm()`. -- `POST /check`, calls `ParseForm`, runs the standard `Collect` → `Evaluate` → `GetHTMLReport` / `ExtractMetrics` pipeline, and returns a consolidated HTML page (states table, metrics table, sandboxed iframe around the HTML report). - -### Why it exists - -Over the HTTP `/evaluate` endpoint, happyDomain fills `AutoFill*`-backed options (zone records, service payload, …) from its execution context. A human hitting `/check` has no such host, `ParseForm` is where the checker does whatever lookups are needed (typically direct DNS queries) to turn a minimal human input (e.g. a domain name) into the full `CheckerOptions` that `Collect` expects. - -### When to implement it - -- You want the checker to be usable as a standalone DNS-probing tool (debug, demo, one-off runs) without a happyDomain instance. -- You are fine doing the auto-fill work yourself from the user's inputs. Checkers whose `Collect` intrinsically requires data only happyDomain can provide (e.g. a full zone diff) should skip this. - -### Minimal implementation - -```go -func (p *dummyProvider) RenderForm() []sdk.CheckerOptionField { - return []sdk.CheckerOptionField{ - {Id: "message", Type: "string", Label: "Custom message", - Placeholder: "Hello!", Required: false}, - } -} - -func (p *dummyProvider) ParseForm(r *http.Request) (sdk.CheckerOptions, error) { - return sdk.CheckerOptions{ - "message": strings.TrimSpace(r.FormValue("message")), - }, nil -} -``` - -Returning an error from `ParseForm` re-renders the form with the error message displayed so the user can correct and resubmit. - ---- - - ## Running the Checker ### Build and run locally @@ -553,15 +467,12 @@ Response (score 42.5 is below the warning threshold of 50): { "status": 3, "message": "Score: 42.5 - test", - "rule_name": "dummy_score_check", "code": "dummy_score_check" } ] } ``` -Each entry in `states` carries a `rule_name` (server-stamped) and may include a `subject` field when the rule evaluates multiple elements. - Status codes: `1` = OK, `3` = Warning, `4` = Critical. ### Extract metrics @@ -605,7 +516,7 @@ The types and helpers your checker depends on live in [`checker-sdk-go`](https:/ **What this means for the deployment mode you choose:** - **Standalone HTTP checker:** your checker is a separate process communicating with happyDomain over the network. It is *not* a derivative work of happyDomain and you can license it however you want (proprietary, MIT, GPL, anything). -- **In-process plugin (`.so`):** your checker is loaded into the happyDomain process via `plugin.Open`, but it only links against the Apache-licensed SDK, not against any AGPL code. You are free to license your plugin however you want. +- **In-process plugin (`.so`):** your checker is loaded into the happyDomain process via `plugin.Open`, but it only links against the Apache-licensed SDK — not against any AGPL code. You are free to license your plugin however you want. - **Built-in checker** (imported directly into the happyDomain source tree): same as above on the linking side. Built-in checkers maintained inside the happyDomain repository are conventionally distributed under AGPL-3.0 to stay consistent with the rest of the project, but this is a project policy, not a legal requirement coming from the SDK. If your checker imports anything *else* from the happyDomain repository (for example service abstractions like `happydns.ServiceMessage`), then that code *is* AGPL-licensed and the AGPL constraint comes back. The SDK alone is safe; the rest of happyDomain is not. diff --git a/checker/provider.go b/checker/provider.go index 9aee115..5543940 100644 --- a/checker/provider.go +++ b/checker/provider.go @@ -44,9 +44,9 @@ func (p *dummyProvider) Definition() *sdk.CheckerDefinition { // ExtractMetrics implements sdk.CheckerMetricsReporter. // This is called when happyDomain (or the /report endpoint) needs to turn // raw observation data into time-series metrics for graphing. -func (p *dummyProvider) ExtractMetrics(ctx sdk.ReportContext, collectedAt time.Time) ([]sdk.CheckMetric, error) { +func (p *dummyProvider) ExtractMetrics(raw json.RawMessage, collectedAt time.Time) ([]sdk.CheckMetric, error) { var data DummyData - if err := json.Unmarshal(ctx.Data(), &data); err != nil { + if err := json.Unmarshal(raw, &data); err != nil { return nil, err } diff --git a/checker/rule.go b/checker/rule.go index 85c3475..2427468 100644 --- a/checker/rule.go +++ b/checker/rule.go @@ -58,15 +58,15 @@ func (r *dummyRule) ValidateOptions(opts sdk.CheckerOptions) error { // The ObservationGetter.Get method deserialises the stored JSON into your data // struct. Always check the error: the observation may not be available if // collection failed. -func (r *dummyRule) Evaluate(ctx context.Context, obs sdk.ObservationGetter, opts sdk.CheckerOptions) []sdk.CheckState { +func (r *dummyRule) Evaluate(ctx context.Context, obs sdk.ObservationGetter, opts sdk.CheckerOptions) sdk.CheckState { // Retrieve the observation data by key. var data DummyData if err := obs.Get(ctx, ObservationKeyDummy, &data); err != nil { - return []sdk.CheckState{{ + return sdk.CheckState{ Status: sdk.StatusError, Message: fmt.Sprintf("Failed to get dummy data: %v", err), Code: "dummy_error", - }} + } } // Read thresholds from options. @@ -84,7 +84,7 @@ func (r *dummyRule) Evaluate(ctx context.Context, obs sdk.ObservationGetter, opt status = sdk.StatusOK } - return []sdk.CheckState{{ + return sdk.CheckState{ Status: status, Message: fmt.Sprintf("Score: %.1f - %s", data.Score, data.Message), Code: "dummy_score_check", @@ -92,5 +92,5 @@ func (r *dummyRule) Evaluate(ctx context.Context, obs sdk.ObservationGetter, opt "score": data.Score, "message": data.Message, }, - }} + } } diff --git a/go.mod b/go.mod index 1b83b1e..f1e1248 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,4 @@ module git.happydns.org/checker-dummy go 1.25.0 -require git.happydns.org/checker-sdk-go v1.5.0 +require git.happydns.org/checker-sdk-go v1.0.0 diff --git a/go.sum b/go.sum index c389c68..65fbd86 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,2 @@ -git.happydns.org/checker-sdk-go v1.5.0 h1:5uD5Cm6xJ+lwnhbJ09iCXGHbYS9zRh+Yh0NeBHkAPBY= -git.happydns.org/checker-sdk-go v1.5.0/go.mod h1:aNAcfYFfbhvH9kJhE0Njp5GX0dQbxdRB0rJ0KvSC5nI= +git.happydns.org/checker-sdk-go v1.0.0 h1:5u8vnvoH2KEbHtAqPu/Wh6xBQ8PWgle9iZ1j7HTZXd8= +git.happydns.org/checker-sdk-go v1.0.0/go.mod h1:aNAcfYFfbhvH9kJhE0Njp5GX0dQbxdRB0rJ0KvSC5nI= diff --git a/main.go b/main.go index 9360f60..2ab77ee 100644 --- a/main.go +++ b/main.go @@ -5,7 +5,7 @@ import ( "log" dummy "git.happydns.org/checker-dummy/checker" - "git.happydns.org/checker-sdk-go/checker/server" + sdk "git.happydns.org/checker-sdk-go/checker" ) // Version is the standalone binary's version. It defaults to "custom-build" @@ -23,8 +23,8 @@ func main() { // CheckerDefinition.Version. dummy.Version = Version - srv := server.New(dummy.Provider()) - if err := srv.ListenAndServe(*listenAddr); err != nil { + server := sdk.NewServer(dummy.Provider()) + if err := server.ListenAndServe(*listenAddr); err != nil { log.Fatalf("server error: %v", err) } }