Skip to main content

Behavior DSL

Each part of a behavior definition: what it makes osapi do, and when to use it. osapi behavior spec get prints the same list from this build. Building a behavior tells how to write one.

Definition​

Register(Define(name, doc, options...))​

Declares the behavior and adds it to the registry. The agent, the server, the CLI and the generator read the registry. The name is the route, the command, the permission and the docs page: lowercase letters and digits, no dash. The Go package is where the definition lives, which osapi behavior create --package sets when the name is a Go keyword.

Use: One time, in behavior.go: var Behavior = behavior.Register(behavior.Define(...)).

Options of Define​

Node​

Runs the methods on a host, through the job system.

Use: Always. It is the only placement.

API​

Serves the methods over REST, with routes, permissions and the OpenAPI spec.

Use: When an operator or a program calls the behavior.

CLI​

Makes osapi client commands and their docs pages. Needs API.

Use: When an operator calls the behavior from a shell.

Under("group")​

Nests the behavior in a group: its routes, commands and directory.

Use: When the behavior belongs to a group, such as network.

Internal​

Gives the behavior no route, command or permission. Only the behaviors that require it can call it.

Use: For work that two behaviors share, such as writing a file.

Requires(behaviors...)​

Builds the providers of those behaviors first. The builder gets them with host.Require.

Use: When the behavior uses the methods of another behavior.

Platform("debian", build)​

Builds the provider on that platform: a distribution, darwin, or linux for each Linux host without its own. On another platform, the methods report skipped.

Use: One time for each platform that the behavior supports.

Sudo(programs...)​

Lists the programs that the providers run with sudo. The agent preflight checks that sudo allows each.

Use: For each program that needs root.

Runs(programs...)​

Lists the programs that the providers run without sudo. The agent warns when one is not installed.

Use: For each program that does not need root.

RunsOnPlatform(platform, programs...)​

Lists the programs that the providers run without sudo on one platform only. linux is each platform that is not darwin. The agent and the integration test ask for them on that platform only.

Use: For a program that only one platform has, such as vm_stat or sw_vers on darwin.

RunsIfPresent(programs...)​

Lists the programs that the providers run only when the host has them. The fake host permits them, and the agent and the integration test do not ask for them.

Use: For a program that a provider reads without, when it is missing, such as zfs.

Writes("/etc/x.d/osapi-*.conf")​

Lists the paths that the providers write, remove or change the mode of. Each such call is a file span in a trace. "*" is the path that the caller names.

Use: For each path, also when a required behavior, such as managedfile, does the write.

KeepsState​

Says that the providers keep a record in the file-state bucket. Each read and write of it is a kv span.

Use: When the behavior keeps a record of what it wrote.

Config(defaults)​

Declares settings under behaviors.<name>, with a flag and an environment variable for each. A provider reads them with Settings.

Use: For standing config of the agent. A value for one call is an input.

Validator("tag", check, schema, message)​

Declares a validate tag of the behavior, with the check that the server runs and its schema in the spec, such as rule.Pattern(re).

Use: When no standard validate tag checks a value.

Methods​

Read("name", fn)​

A method that reads the host: GET and <group>:read. Named list, get or status.

Use: For each read. fn is func(ctx, p Provider, in In) (Out, error).

Write("name", fn)​

A method that changes the host: POST, PUT or DELETE, and <group>:write. Named create, update or delete. Out has Changed bool.

Use: For each change. fn is func(ctx, p Provider, in In) (Out, error).

Action("name", fn)​

A write named for what it does, such as restart: POST on the method's path with the name after it, /service/{name}/restart, and <group>:write. Named with one of the CLI's actions. Out has Changed bool.

Use: For a change that create, update and delete do not say, such as start, stop, restart, enable, signal or reboot.

Refinements of a method​

.Key("field")​

Puts that input field in the route and the CLI, and records it on the span of each call. The field is validate:"required": a path segment is never empty.

Use: On each method that acts on one item, such as get, update and delete of a key.

.NotAFact("why")​

Says why a read runs a command outside gohai: what it reads is not a fact of the host, such as the updates of the package index. Without it, the tests of a read fail on each command that does not go through gohai.

Use: Only when no gohai collector can have the value, because the host does not own it. A fact that gohai does not read is a change to gohai first.

.Always()​

Marks an action that changes the host each time it runs, such as restart. Its output reports changed: true on each run, and the generated test does not run it again to see changed: false. behavior validate refuses it on a method that is not an action.

Use: On an action that has no state to compare, so a second run is not unchanged.

.Describe("text")​

The one-line description of the method, in the help, the spec and the docs.

Use: On each method.

.On(platform...)​

Limits the method to some of the platforms the behavior declares, such as behavior.PlatformDebian. Elsewhere it reports skipped, and its examples run only with the providers that serve it.

Use: When one method cannot run where the others do: a hostname read works on macOS, but its update runs only on debian.

`.Sudo(program...)` and `.Runs(program...)` on a method​

Programs only this method runs, with sudo or without. A host needs them only where the method runs, so the agent's startup check and the integration test ask for them there only.

Use: With On, for a program the other platforms do not have, such as hostnamectl for a hostname update.

.Explain("text")​

The longer description: what the method touches, and what a second call does.

Use: When one line does not say what the method changes.

.Example("doc", in, out, host...)​

A sample call. The docs page shows it, and the provider tests run it on a fake host.

Use: On each method. A CLI behavior needs one.

.Fails("doc", in, "error text", host...)​

A call that the method refuses. The docs page lists it, the provider tests check the error, and an input that breaks a validate rule is a generated HTTP test that answers 400. Each rule of an input field has a .Fails input that breaks it, which the API refuses with 400. An endpoint's required needs one, with the field empty; a behavior's needs none, as its generated tests leave the field out. A path field's required, and a min of 1 on a string that is required, optional or in the path, need none: their only bad value is empty.

Use: For each rule of each input field, as validate requires, and for each input that the method refuses for another reason.

Hosts and effects of an example​

After(input)​

Runs the method of that input before the example.

Use: When the example needs state, such as a parameter that is already managed.

Prints("command", "output")​

Says what a command prints on the fake host.

Use: For each command that the provider reads.

PrintsAfter("after", "command", "output")​

Says what a command prints after another command has run.

Use: For state that a program keeps, not a file.

Stored(name, content, contentType)​

Says the object store of the fleet has the object name, with its content and its content type, raw or template, as osapi client file upload stores it. A provider reads it with h.Objects.Object.

Use: For an example of a behavior that deploys an uploaded file, such as through the object building block.

Exists("path", "content")​

Puts a file on the fake host before the call.

Use: When the call reads or changes a file that is there.

Links("path", "target")​

Puts a symbolic link to target on the fake host before the call.

Use: When the call reads a link, such as /etc/localtime for the timezone.

Wrote("path", "content")​

Says that the call leaves the file with that content.

Use: For each file that the call writes.

Removed("path")​

Says that the call removes the file.

Use: For each file that the call removes.

Ran("program", args...)​

Says that the call runs the command.

Use: For each command that the call runs to make a change.

A write example on a live host​

CI runs each write example as root on a throwaway Linux runner, with OSAPI_INTEGRATION_WRITE_BEHAVIORS=1, and the lab can run it too. Each example starts with its item deleted, runs the calls of After, then must report its changed, and changed: false when it runs again. The test uploads each object of Stored first, and runs an .Always() action once. Prints, PrintsAfter and Exists only answer the fake host.

Use: For each write example: give the state that it starts from with After, which a real host can run, such as After(StartInput{...}) before a stop, and make the content real, such as a unit file whose ExecStart exists. Run it against the lab with go test -tags integration before you push.

The host a provider gets​

h.Platform, h.Container, h.Hostname​

The platform of the agent as gohai names it, such as debian or darwin; whether the agent runs in a container; and its hostname. The tests build the provider once for each platform that the behavior declares, with behaviortest.Hostname.

Use: To choose what a builder returns. A builder that cannot manage the host, such as a writer in a container, returns the reader, or ErrUnsupported so the methods report skipped.

h.FS​

The filesystem of the host, an avfs.VFS. The agent gives the real one. The tests give an in-memory one, so an example says the files before the call with Exists and Links, and the files after it with Wrote and Removed.

Use: For each file that the provider reads or writes itself, never the os package. A file that osapi owns goes through managedfile; atomicfile.Write writes one in place.

h.Exec​

Runs a program: RunCmd as the agent's user, RunPrivilegedCmd with sudo, RunPrivilegedCmdWithStdin for a secret. The tests give a generated mock that records each command line and prints what the example says with Prints and PrintsAfter; Ran checks a command after. Each program is declared with Runs or Sudo.

Use: For a write, such as systemctl start or apt-get install, and for a read of what is not a fact of the host, with .NotAFact. A read of a fact goes through h.Sources().

h.Sources()​

The sources that a gohai collector reads the host through: h.FS, h.Exec, h.Now and h.Resolver. Thus services.NewWith(h.Sources()).Collect(ctx, nil) reads the real host on an agent and the fake host in the tests, with the files of Exists and the commands of Prints.

Use: For each read of a fact of the host. The gohai test check fails a read that runs a command another way.

h.FileState, h.FileStateBucket​

The KV store where osapi keeps a record of each file that it wrote, and its bucket. nil when the agent has no store. The tests give an in-memory store.

Use: Only through managedfile, which declares KeepsState. A provider does not read or write records itself.

h.Objects​

Reads an object of the Object Store, such as a file that osapi client file upload stored. nil when the agent has no store. The tests give the objects of Stored.

Use: Only through the object building block, which the behavior requires.

h.Settings, h.Required​

The decoded settings of the behavior, which Settings[T](h) reads, and the providers of the behaviors that it requires, which Require reads. The tests give the defaults of Config and the real providers of the required behaviors, on the same fake host.

Use: Through Settings[T](h) and Require[P](h, b), not the fields.

h.Now, h.Time()​

The clock of the host. Time reads it. The tests give behaviortest.Now, 2026-01-02 03:04:05 UTC.

Use: For each time that a provider computes, such as an uptime from a boot time. Never time.Now.

h.Resolver, h.Logger​

The name resolver that gohai uses, such as for the canonical FQDN, and the logger of the agent. The tests give a resolver that answers without the network, and a logger that discards.

Use: The resolver goes to gohai through h.Sources(). Log with h.Logger only what a span does not carry.

Calls in a provider​

collector.NewWith(h.Sources())​

Reads the facts of the host through gohai, such as services.NewWith(h.Sources()).Collect(ctx, nil). Sources gives gohai the host's filesystem and commands, so the tests run it on the fake host.

Use: For each read of a fact of the host: its packages, services, interfaces, routes, disks. A provider runs h.Exec for writes, and reads with it only what is not a fact, with .NotAFact.

atomicfile.Write(ctx, h.FS, path, content, mode)​

Writes the file atomically, in a file.write span. atomicfile.Remove and atomicfile.Chmod make file.remove and file.chmod spans.

Use: In a building block that writes files. A behavior that manages a file requires managedfile instead. A change through h.FS fails the tests.

Render(text, TemplateData{Facts, Vars, Hostname})​

Renders a template with the facts of the agent, the vars of the request and the hostname. A key that the data does not have is an error.

Use: In the provider of a method with a template input. The input is checked at the API already.

Settings[T](Behavior)​

Returns the settings of the behavior, or the defaults.

Use: In a builder or a method that reads a setting.

rule.Register("tag", rule.Pattern(re))​

Declares what a custom validate rule means in the spec: rule.Pattern(re), rule.Format(f), or rule.None for a rule that the spec cannot show, such as a target the controller resolves.

Use: Beside the validator of a new custom rule, in internal/validation.

Errors a provider returns​

behavior.ErrNotFound​

The item that the request names is not on the host: a service, a package, a key, or an object of a deploy. On one host the API answers 404, on any method; on a broadcast the row of the host is failed with the message.

Use: Wrap it with what was missing: fmt.Errorf("service %q: %w", name, behavior.ErrNotFound). An update, a delete or an action on an item that osapi does not have is not found; a delete of it is changed: false instead.

behavior.ErrNotManaged​

The item is on the host, but osapi did not deploy it, so osapi does not change it, such as a file with no record in managedfile. The API answers 409.

Use: Before a write over an item that something else owns. Ask managedfile, not the path: the agent's own unit is osapi-agent.service.

behavior.ErrNotInstalled​

A program that the method needs is not on the host. The API answers 409.

Use: When a method needs a program that the platform does not always have, and Runs or RunsIfPresent does not say it.

behavior.ErrUnsupported​

The method does not apply to this host: its platform, or a container. The row of the host is skipped, not failed.

Use: From a builder, for a platform or a host that it cannot manage, or from a method that does not apply. Use .On or a reader builder first, so the definition says it.

Building on other behaviors​

Chains​

A behavior that requires others calls them on the same host, in the same job: dns calls netplan, and netplan calls managedfile. osapi behavior chain spec get has how to build one, its rules and the building blocks in this binary; osapi behavior chain get shows what each call sends and gets.

Use: Before a provider does generic work itself, such as writing a file that osapi manages.

Tags on input, output and settings fields​

json:"name"​

The name of the field in the request, the flag, the column and --json. A field with no json name fails the input or output rule, because the CLI and the tables cannot show it. An optional field of a write's body, validate:"omitempty,...", is json:"name,omitempty" too, or the client sends "" for it (the optional rule). No input field is named hostname or target: every request has those.

Use: On each field.

validate:"..."​

The rules the server checks before the method runs: a value that breaks one is a 400 with {"error": "..."}. required makes the field required, oneof gives an enum, min, max and len the length of a string, the items of an array or the bounds of a number, startswith a pattern, and uuid, email, hostname, ip, ipv4, ipv6, cidr, url and uri a format. The spec carries these, and the whole tag in x-oapi-codegen-extra-tags. A custom rule, such as sysctl_key, needs its schema from rule.Register; a rule with none fails the spec. In a behavior, the agent and behavior.Call check the same rules before each method runs, so an internal behavior's rules hold too; the author writes no check.

Use: On each input field. A field with no limit is validate:"omitempty"; validate refuses an input field with no tag.

default:"..."​

Not on a behavior input: the spec and the flag would show the default, but the server does not apply it, so a caller of the API gets the zero value. The input rule fails it.

Use: Never on a behavior input. The provider treats the empty value as the default, and the doc says what it is.

doc:"..."​

The description in the spec, the flag help and the docs pages. The input rule fails an input field with none.

Use: On each field.

render:"..."​

How an output column shows: "-" hides it; bytes, age, time, duration, duration=ms, status or short=N. The output rule fails a value the output does not know; the CLI owns the list.

Use: On an output field that a table must show differently.

telemetry:"attr"​

Records the input field on the span of the method. The field that .Key names is recorded without it.

Use: On the field that names the item, when the method has no key, and on other fields a trace must show.

template:"vars"​

Marks a string input as a Go template, whose .Vars are in the input field vars, a map[string]string. The API refuses a template that does not parse, that reads a field other than .Facts, .Vars and .Hostname, or that reads a var the request does not give. Each such method gets a generated 400 test.

Use: On an input that holds a template, such as the content of a file. Render it with Render.

secret:"true"​

Redacted from the audit log, write-only with the password format in the spec that ships, never recorded on a span.

Use: On each input that holds a password, a key or a token.

mapstructure:"name"​

The config key of a settings field.

Use: On each field of the struct given to Config.

What a template reads​

.Vars.<name>​

A value from the vars of the request. The API refuses a template that reads a var that the request does not give.

Use: For a value that the caller gives with each call.

.Hostname​

The hostname of the agent that renders the template.

Use: For a value that names the host.

.Facts.<key>​

A fact of the agent that renders the template. Facts are known only on each host, so a fact that a host does not have fails on that host. The keys: architecture, kernel_version, cpu_count, fqdn, service_mgr, package_mgr, containerized, interfaces, primary_interface, routes, facts.

Use: For a value that differs from host to host.

Generated, never edited​

internal/behaviors/<name>/gen/​

The routes, handlers, commands, spec and tests of the behavior, from go generate ./internal/behaviors/all.

Use: Change the definition, then generate. A generated test that fails is fixed in the definition or in internal/behavior/gen.

internal/behaviors/<name>/mocks/​

The double of the provider, from go generate ./internal/behaviors/<name>/mocks.

Use: Run it again after provider.go changes.

docs/docs/sidebar/reference/behaviors/<name>/​

The docs page of the behavior: the output of osapi behavior get and osapi behavior method get, as markdown, from just cli-docs-generate (osapi cli docs reference generate).

Use: Change the definition, then run just cli-docs-generate. A page that shows the wrong thing is fixed in the definition, or in the get command that shows it.

docs/docs/sidebar/usage/cli/​

The CLI pages, from just cli-docs-generate. The help of a behavior command comes from .Describe, .Explain, .Example and .Fails.

Use: Change the definition, then generate. A generated test that fails is fixed in the definition or in internal/behavior/gen.

internal/controller/api/gen/, pkg/sdk/client/gen/, ui/src/sdk/gen/, docs/docs/gen/​

The joined spec, the SDK, the UI client and the API pages, from just generate.

Use: Change the definition, then generate. A generated test that fails is fixed in the definition or in internal/behavior/gen.

Not supported yet​

A command or a shell from the caller​

There is no execute permission.

Use: Stop, and tell the person what is missing. Do not build around it.

A resource under another​

Two keys in the path, such as the SSH keys of a user.

Use: Stop, and tell the person what is missing. Do not build around it.

Streaming and uploads​

A method that streams its output, or that takes a file in its request. A behavior reads an object that osapi client file upload stored, with the object building block.

Use: Stop, and tell the person what is missing. Do not build around it.

A step on the controller​

Work before osapi queues the job, such as a password hash.

Use: Stop, and tell the person what is missing. Do not build around it.