behavior

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 39 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package behavior defines what osapi can do to a host. A behavior is one directory: a definition, typed inputs and outputs, and the logic for each platform. The API routes, the agent's dispatch, the CLI commands, the OpenAPI document, the config keys and the docs pages are all built from the definition.

Starting one

osapi dsl behavior create --name <name> --description "..." writes the standard layout under internal/behaviors/<name>/, a working behavior that, once go generate has written its mock and gen/, builds, validates and passes every test. internal/behaviors/sysctl is the reference. Every file with code has a test named for it.

behavior.go      the definition, with Define and Register
types.go         the input and output types, with their tags
methods.go       one function per method, calling the provider
provider.go      the Provider interface each platform implements
<platform>.go    a platform's provider and its builder, such as debian.go
settings.go      optional: the behavior's own config, see Config
mocks/           the Provider's double, by mockgen
gen/             written by go generate ./internal/behaviors/all: api.go, the
                 route table; api_<method>.go, each method's handler;
                 cli.go, the commands; api.yaml, the spec; and a test
                 for each Go file

Nothing outside the directory changes but its import in internal/behaviors/all, which osapi dsl behavior create adds.

The definition

Define takes a name, a one-line description and options:

Node          the work runs on a host, through the job system; required
API           serve it over REST and put it in the OpenAPI spec
CLI           generate its commands and docs pages; needs API
Under(group)  nest it: /api/node/{hostname}/<group>/<name>
Config(v)     declare settings, with v as their defaults
Platform(p, build)
              build the provider on platform p, from a host.Host: debian,
              darwin, or linux for every Linux host without its own; on
              a platform not declared, the methods report skipped
Sudo(progs)   programs the providers run with sudo; preflight checks them
Runs(progs)   programs they run without sudo; the agent warns if one is missing
Validator(tag, check, schema, message)
              a validate tag of the behavior's own
Requires(bs)  behaviors it is built on; their providers reach its builder
              through host.Require, and it calls their methods as Go calls
Internal      only other behaviors use it: no route, command or permission
Read(n, fn)   a method that reads the host: GET, <name>:read
Write(n, fn)  a method that changes it: POST, or PUT for update and
              DELETE for delete, <name>:write
Action(n, fn) a write named for what it does, such as restart: POST on
              its path with the name after it, <name>:write

A method is refined with Key (the input field in the path), Describe (one line), Explain (what it touches and what running it twice does) and Example (a sample input and output, rendered onto its docs page).

An example also describes the host it runs on and what it changes there, with After (call another method first), Prints (a command's output), PrintsAfter (its output once another command has run, for state a program keeps), Exists (a file already there), Wrote, Removed and Ran. Those are the provider's tests: see Testing.

Fails declares a call the method refuses, with text its error contains: bad input, or a host it cannot act on.

A method function has the shape

func(ctx context.Context, p Provider, in In) (Out, error)

The agent finds p by its type among the providers it builds. A write's Out has a changed bool.

Tags on input and output types

json:"key"        the name in the request, the flag, the column and --json
validate:"..."    checked before a job is queued; becomes spec constraints
doc:"..."         the description in the spec, the flag help and the docs
render:"..."      on an output: "-" hides the column; bytes, age, status
telemetry:"attr"  on an input: recorded on the method's span; the field
                  a method names with Key is recorded without it

A secret is a type, not a tag: an input field of type secret.Value, or a map of them, is redacted from the audit log, write-only in the spec, never on a span, and a reference or [redacted] in a chain record.

A custom validate rule needs a schema, from Validator or rule.Register, so the spec checks what the server does.

Settings

Config declares a struct of standing agent config under behaviors.<name>, with the same mapstructure, doc and validate tags as osapi's config. Each field gets an OSAPI_BEHAVIORS_<NAME>_<FIELD> variable and an osapi agent start flag, --<name>-<field>. A method reads them with Settings. A value that changes per call belongs in the input, not here.

Testing

A behavior's tests above its provider are inferred from the definition and run for every registered behavior, in internal/behaviors/all:

  • every example runs on a fake host with each platform's provider, and must produce its output and its declared effects; a write must declare effects, and run twice must report changed: false the second time; each filesystem, command and store call failing in turn, and each store read returning a damaged record, must not panic; each refusal must fail with its text (package behaviortest);
  • every example is sent through the real API handler and middleware on an HTTP server, and the responses, broadcast, 401, 403, 404, 500 and each missing required field are checked against the generated spec;
  • every example's flags, given to its generated command, send its input.

A behavior's own test calls behaviortest.Run, which osapi dsl behavior create writes; the examples and refusals reach the methods through the provider. A test by hand is only for what an example cannot show.

Checking one

go generate ./internal/behaviors/all   write gen/, the spec and the docs pages
osapi dsl behavior validate          the rules, see Validate
osapi dsl behavior get --name <name> what was registered: routes, schemas
just test                        including behavior-gen-check
Example

A behavior is a definition. Everything served for it is derived from the definition: the route, the command and the permission of each method.

package main

import (
	"context"
	"fmt"

	"github.com/osapi-io/osapi/internal/behavior"
)

// MotdProvider is what each platform implements for the example behavior.
type MotdProvider interface {
	Read(ctx context.Context) (string, error)
	Write(ctx context.Context, text string) (bool, error)
}

// MotdGetInput is get's input; it has no fields.
type MotdGetInput struct{}

// MotdUpdateInput is update's input.
type MotdUpdateInput struct {
	Text string `json:"text" validate:"required,max=1024" doc:"The message to show at login"`
}

// Motd is get's output.
type Motd struct {
	Text string `json:"text" doc:"The message shown at login"`
}

// MotdResult is update's output. A write reports whether it changed the host.
type MotdResult struct {
	Changed bool `json:"changed" doc:"Whether the message changed"`
}

func getMotd(
	ctx context.Context,
	p MotdProvider,
	_ MotdGetInput,
) (Motd, error) {
	text, err := p.Read(ctx)

	return Motd{Text: text}, err
}

func updateMotd(
	ctx context.Context,
	p MotdProvider,
	in MotdUpdateInput,
) (MotdResult, error) {
	changed, err := p.Write(ctx, in.Text)

	return MotdResult{Changed: changed}, err
}

func main() {
	motd := behavior.Define("motd", "The message shown at login",
		behavior.Node,
		behavior.API, behavior.Area("config"),
		behavior.CLI,
		behavior.Read("get", getMotd).
			Describe("Get the message of the day"),
		behavior.Write("update", updateMotd).
			Describe("Set the message of the day").
			Explain("Writes the file and reports changed: false when it already holds the text."),
	)

	for _, m := range motd.Methods {
		fmt.Println(m.HTTPMethod(), motd.Path(m), motd.Permission(m.PermissionVerb()))
		fmt.Println("  ", motd.Command(m))
	}

}
Output:
GET /api/node/{hostname}/motd motd:read
   osapi client node motd get
PUT /api/node/{hostname}/motd motd:write
   osapi client node motd update

Index

Examples

Constants

View Source
const (
	// RuleCalled: each call of a provider goes to a behavior that its
	// behavior requires.
	RuleCalled = "called"
	// RuleUsed: an example calls each behavior that a behavior requires.
	RuleUsed = "used"
)

The chain rules, by the name a problem reports. RuleRequires and RuleInternal hold when the behaviors are built; RuleCalled and RuleUsed hold when the examples run, because only a run shows which behaviors a provider calls.

View Source
const (
	KindChain    = "chain"
	KindFailStep = "fail"
)

The kinds of the chain spec that the behavior spec does not have.

View Source
const (
	TestOutput     = "output"
	TestEffects    = "effects"
	TestIdempotent = "idempotent"
	TestErrors     = "errors"
	TestState      = "state"
	TestRefusal    = "refusal"
	TestTraversal  = "traversal"
	TestNewLine    = "newline"
	TestOption     = "option"
	TestShell      = "shell"
	TestRuns       = "runs"
	TestGohai      = "gohai"
	TestWrites     = "writes"
	TestFileSpan   = "file-span"
	TestKeepsState = "keeps-state"
	TestCall       = "call"
	TestPlatforms  = "platforms"
)

The checks that behaviortest.Run makes when go test runs a behavior's examples on a fake host, by the name in TestChecks.

View Source
const (
	KindDefinition = "definition"
	KindOption     = "option"
	KindMethod     = "method"
	KindRefine     = "refine"
	KindExample    = "example"
	KindCall       = "call"
	KindHost       = "host"
	KindError      = "error"
	KindCompose    = "compose"
	KindBlock      = "block"
	KindTag        = "tag"
	KindTemplate   = "template"
	KindGenerated  = "generated"
	KindNotYet     = "not-yet"
)

The kinds of term in Spec, in the order that a behavior is written.

View Source
const (
	AttrBehavior = attribute.Key("osapi.behavior.name")
	AttrMethod   = attribute.Key("osapi.behavior.method")
	AttrVerb     = attribute.Key("osapi.behavior.verb")
	AttrOutcome  = attribute.Key("osapi.behavior.outcome")
	AttrChanged  = attribute.Key("osapi.behavior.changed")
)

Attribute keys, under osapi.behavior.

View Source
const (
	OutcomeOK    = "ok"
	OutcomeError = "error"
)

Outcomes a call ends in.

View Source
const (
	RuleName        = "name"
	RulePlacement   = "placement"
	RuleDoc         = "doc"
	RuleMethods     = "methods"
	RuleDuplicate   = "duplicate"
	RuleKey         = "key"
	RuleSchema      = "schema"
	RuleChanged     = "changed"
	RuleOutputShape = "output"
	RuleSurface     = "surface"
	RuleExample     = "example"
	RuleVerb        = "verb"
	RuleRoute       = "route"
	// RuleParent: a behavior declared with Of is under a registered
	// behavior that has a key, and does not also declare Under.
	RuleParent = "parent"
	// RuleSettings fails settings that are not a struct, or a field
	// without the mapstructure name or doc the config needs.
	RuleSettings = "settings"
	// RuleRequires: every behavior required is registered, and none
	// requires itself through others.
	RuleRequires = "requires"
	// RuleSecret: a secret.Value input field is not recorded on the
	// method's span, and is not in the URL of its route: not its key, and
	// not an input of a read. When the examples run, a chain gives a secret
	// only to a secret.Value field of a child.
	RuleSecret = "secret"
	// RuleValidate: each input field has a validate tag. The endpoint DSL
	// holds its inputs to the same check, from package rule.
	RuleValidate = "validate"
	// RuleFails: each rule of an input field has a .Fails input that breaks
	// it. The endpoint DSL holds its inputs to the same check.
	RuleFails = "fails"
	// RuleOptional: an optional field of a write's request body is left out
	// of the JSON when it is empty, so the client does not send "" for it.
	RuleOptional = "optional"
	// RuleInput: each input field has a json name, a doc and no default,
	// and is not named hostname or target, which every request has.
	RuleInput = "input"
	// RulePlatform: a behavior declares a provider for at least one
	// platform, once each, and each implements every method's provider type.
	RulePlatform = "platform"
	// RuleInternal: an internal behavior is required by another. Nothing
	// else can reach it, because it has no API and no CLI.
	RuleInternal = "internal"
	// RuleWrites: each path a behavior declares with Writes is "*", or an
	// absolute path.Match pattern.
	RuleWrites = "writes"
	// RuleSpan: a write records on its span what it acts on, through Key or
	// a field tagged telemetry:"attr". Thus a trace says what each write
	// changed. A write whose input has no field that can be recorded is
	// exempt.
	//
	// Checks has the requirement and the fix of each rule.
	RuleSpan = "span"
	// RuleTemplate: a field tagged template:"<vars>" is a string, and <vars>
	// names an input field of type map[string]string.
	RuleTemplate = "template"
	// RuleTag: each struct tag of an input field has a known key
	// (command.KnownTags), and telemetry is "attr" on an input or an output
	// field. A typo drops what the tag does with no error.
	RuleTag = "tag"
	// RuleBefore: a .Before step is func(context.Context, In) (In, error),
	// on a served method with a secret field, and each field tagged before
	// is set by one.
	RuleBefore = "before"
	// RuleReadBack: each write example that the integration test runs on
	// the live host says what a read answers after it, with Reads or
	// ReadsNone, or says why no read can, with NoReadBack or ReadsNothing.
	RuleReadBack = "readback"
)

The rules Validate checks, by the name a Problem reports.

View Source
const AnyProgram = "*"

AnyProgram is the program name Runs takes for each program.

View Source
const SettingsPrefix = "behaviors"

SettingsPrefix is where every behavior's settings sit in osapi's config: behaviors.<name>.<field>.

View Source
const TagBefore = "before"

TagBefore is the struct tag of an input field that the controller step of its method sets, before:"set". A caller does not send the field: it is not in the request, the command or the UI, and the step fills it from the fields that the caller sends.

Variables

View Source
var (
	// ErrUnsupported means the operation is not supported on this host's
	// platform. The method reports skipped rather than failed.
	ErrUnsupported = errors.New("operation not supported on this OS family")

	// ErrNotFound means the thing the request named is not on the host: a
	// user, a group, a service, a cron entry, a sysctl key, a package.
	ErrNotFound = errors.New("not found")

	// ErrNotManaged means the thing exists on the host but osapi did not
	// deploy it, so osapi will not change or remove it.
	ErrNotManaged = errors.New("not managed by osapi")

	// ErrNotInstalled means a program the operation depends on is absent.
	ErrNotInstalled = errors.New("not installed")

	// ErrInvalid means the host refuses the input, which the route's
	// validate tags cannot see, such as a path that is a directory where
	// the method reads a file.
	ErrInvalid = errors.New("invalid input")
)

The causes a provider can report that the API answers differently. A provider returns one of these wrapped in an error that says which thing and where; the agent turns it into a code on the response, and the controller into a status, so nothing has to read the sentence back.

They are here, in the package every behavior imports, because every behavior's provider returns them. internal/provider gives the hand-written providers the same values under its own names until they migrate.

View Source
var ChainChecks = guide.Checks{
	{
		Rule:     RuleRequires,
		Requires: "Each required behavior is registered, and no behavior requires itself through others.",
		Fix:      "Import the required behavior in internal/behaviors/all, or remove the requirement that makes the cycle.",
	},
	{
		Rule:     RuleInternal,
		Requires: "Another behavior requires each internal behavior. Nothing else can call it, because it has no API and no CLI.",
		Fix:      "Add behavior.Requires(it) to the behavior that uses it, or remove behavior.Internal if an operator calls it.",
	},
	{
		Rule:     RuleCalled,
		Requires: "A provider calls only the behaviors that its behavior requires. The agent builds the provider of each required behavior, and no other.",
		Fix:      "Add the behavior that it calls to behavior.Requires, and read its provider with host.Require.",
	},
	{
		Rule:     RuleUsed,
		Requires: "An example calls each behavior that a behavior requires. A requirement that no example calls is not tested, or is not needed.",
		Fix:      "Add an example whose provider calls the required behavior, or remove the requirement.",
	},
	{
		Rule:     RuleSecret,
		Requires: "A call gives a secret of its input only to a secret.Value field of the behavior that it calls. A field of another type, such as a string, records the value in its chain record, its span or an audit entry. The examples run each chain, so their tests check it.",
		Fix:      "Give the field of the called behavior the type secret.Value, and read it there with Reveal.",
	},
}

ChainChecks are the rules of a chain: the behaviors that a behavior requires, and the calls that it makes to them. osapi dsl chain validate checks each one; dsl behavior validate checks the ones that hold when the behaviors are built, and go test checks the ones that need a run.

View Source
var ChainSpec = guide.Spec{
	Kinds: []guide.Kind{
		{Kind: KindChain, Title: "What a chain is"},
		{Kind: KindCompose, Title: "Building on other behaviors"},
		{Kind: KindCall, Title: "Calls between behaviors"},
		{Kind: KindFailStep, Title: "When a step fails"},
	},
	Terms: []guide.Term{
		{
			Kind: KindChain,
			Name: "A chain",
			Does: "The behaviors that a behavior calls, and the ones that they call: dns calls netplan, and netplan calls managedfile. The chain has the name of the behavior at its top. It is not declared on its own: Requires on each behavior makes it.",
			When: "osapi dsl chain list shows each chain; osapi dsl chain get --name <behavior> shows its tree.",
		},
		{
			Kind: KindChain,
			Name: "The calls of an example",
			Does: "osapi dsl chain get runs each example of the behavior on the fake host that go test uses, and records each Call: the behavior, the method, the input, and the output or the error. Thus the tree shows what the code does now.",
			When: "To see what a behavior sends to the behaviors that it calls, before a change or when one fails.",
		},
		{
			Kind: KindCompose,
			Name: "Use a building block",
			Does: "A building block is an internal behavior that does one generic job, such as writing a file that osapi manages. Its spans, checks and records come with it. \"Building blocks\" lists the ones in this binary.",
			When: "Before a provider does generic work itself: a managed file, a service reload, a call to an outside API. Require the block with Requires, and call it with Call. osapi dsl behavior create --requires <block> writes the Requires, the host.Require and a field of the provider; you write each Call.",
		},
		{
			Kind: KindCompose,
			Name: "Make a building block",
			Does: "Generic work that no block does yet becomes a new internal behavior. The behavior that needs it requires it.",
			When: "When the work is not about the one thing that the behavior manages, or a second behavior would need it.",
		},
		{
			Kind: KindCompose,
			Name: "One host, one step",
			Does: "A behavior acts on one host, in one job. Its building blocks run on the same host, in the same job.",
			When: "Work across hosts, or in ordered steps, is an osapi-orchestrator workflow, not a behavior.",
		},
		{
			Kind: KindCall,
			Name: "Call(ctx, other.Behavior, other.Method, p, in)",
			Does: "Runs a method of a required behavior in its own span, so the trace shows it as a step. It checks in against its validate tags first, as the API does for a served method: an input that breaks one is an error, and the method does not run.",
			When: "Each time a provider uses a required behavior. A direct call fails the tests.",
		},
		{
			Kind: KindCall,
			Name: "host.Require[P](h)",
			Does: "Returns the provider of a required behavior, in a builder.",
			When: "In the builder of a behavior that uses Requires.",
		},
		{
			Kind: KindFailStep,
			Name: "The error goes up",
			Does: "Call returns the error of a step to the provider that called it. The provider returns it, with what it was doing, or handles it. The job fails with the message, and the trace marks the span of the step that failed.",
			When: "In each provider that calls another behavior.",
		},
		{
			Kind: KindFailStep,
			Name: "A step undoes its own change",
			Does: "A building block that changes the host and then fails puts the host back before it returns the error: netplan gives its file back the content that it had, or removes a new file, when netplan generate refuses it. The caller does not undo the work of a block.",
			When: "In a building block whose change can fail after it started.",
		},
		{
			Kind: KindFailStep,
			Name: "Skipped on a platform",
			Does: "A behavior that a chain needs, and that cannot run on a platform, makes the behavior at the top report skipped there too.",
			When: "When a building block declares fewer platforms than the behavior that requires it.",
		},
	},
}

ChainSpec is every term of a chain: what one is, how a behavior builds on others, how it calls them, and what happens when a step fails. osapi dsl chain spec get prints it, with the building blocks of the binary.

View Source
var Checks = guide.Checks{
	{
		Rule:     RuleName,
		Requires: "The behavior and each method have a name of lowercase letters and digits, starting with a letter: the generators make Go names of it, so a dash does not compile. No behavior is named all.",
		Fix:      "Rename it, such as sysctl or connectivity. A name that is a Go keyword, such as package, takes osapi dsl behavior create --package for its Go package.",
	},
	{
		Rule:     RulePlacement,
		Requires: "The behavior has a placement.",
		Fix:      "Add behavior.Node to Define.",
	},
	{
		Rule:     RuleDoc,
		Requires: "The behavior and each method have a description. No description or .Explain text has < > { or }: the docs site reads them as markup, and the page fails to build.",
		Fix:      "Give Define a one-line description, and each method .Describe(\"...\"). Name a placeholder with an example, such as osapi-dns-eth0.yaml for eth0, not osapi-dns-<interface>.yaml.",
	},
	{
		Rule:     RuleMethods,
		Requires: "The behavior has one or more methods.",
		Fix:      "Add behavior.Read or behavior.Write to Define.",
	},
	{
		Rule:     RuleDuplicate,
		Requires: "Each behavior is registered one time, and each method name is used one time.",
		Fix:      "Rename or remove the second one.",
	},
	{
		Rule:     RuleVerb,
		Requires: "A read is named list, get or status. A write is named create, update or delete. An action, declared with Action, is named for what it does with one of the CLI's actions, such as restart, and not with a standard verb.",
		Fix:      "Rename the method to the standard verb that the message names, or declare a write named for what it does with behavior.Action and a name from osapi dsl command spec get.",
	},
	{
		Rule:     RuleRoute,
		Requires: "No two methods have the same route.",
		Fix:      "Give one of them a key with .Key(\"field\").",
	},
	{
		Rule:     RuleKey,
		Requires: "The key of a method is a field of its input, and is required: it is a path segment, which is never empty. Its name in the spec, the TypeName and its title, is not also the name of a row type of the behavior.",
		Fix:      "Give .Key the JSON name of an input field, or add the field to the input, and tag it validate:\"required,...\". When the message names a type, rename the type, such as Part to PartEntry.",
	},
	{
		Rule:     RuleParent,
		Requires: "A child is under a registered behavior. A child declared with Of is under an item of the parent, so the parent's items have a key, such as name for a user. A child declared with Under is under the parent's collection, and its name is not the name of an action of the parent, whose route it would take.",
		Fix:      "Give Of a behavior that has a keyed method, such as user, or use Under for a parent whose items have no key, such as log. Rename a child of Under that has the name of an action of the parent. The child takes the parent's path, command and permissions.",
	},
	{
		Rule:     RuleSchema,
		Requires: "Each input is a struct, and each input and output type has a JSON Schema. A struct that an input or output holds is named in one spec for every behavior, so no two behaviors have a different type of the same name.",
		Fix:      "Use structs of strings, numbers, bools, lists and structs. Declare a custom validate tag with behavior.Validator. Rename a held struct that another behavior's type already names, such as Usage to MemoryUsage, or hold that behavior's type.",
	},
	{
		Rule:     RuleOutputShape,
		Requires: "Each output is a struct or a list of structs, with no field named hostname, status or error. Each field has a json name, no field is an array, and each render tag is one the output knows (osapi dsl command spec get lists them).",
		Fix:      "Put the value in a struct, rename a field that has one of those names, tag each field json:\"name\", use a slice for an array, and use a render value the output knows.",
	},
	{
		Rule:     RuleChanged,
		Requires: "The output of a write has Changed bool with json:\"changed\".",
		Fix:      "Add Changed bool `json:\"changed\"` to the output, and set it to true only when the call changed the host.",
	},
	{
		Rule:     RuleSpan,
		Requires: "A write records on its span the item that it acts on, so that a trace shows what each call changed.",
		Fix:      "Name the item with .Key(\"field\"). A method without a key, such as a create, tags that field telemetry:\"attr\".",
	},
	{
		Rule:     RuleTemplate,
		Requires: "A field tagged template:\"<vars>\" is a string, and <vars> is the JSON name of an input field of type map[string]string.",
		Fix:      "Tag the string field that holds the template with template:\"vars\", and add Vars map[string]string `json:\"vars\"` to the input.",
	},
	{
		Rule:     RuleValidate,
		Requires: rule.Requires,
		Fix:      rule.Fix,
	},
	{
		Rule:     RuleOptional,
		Requires: "An optional field of a write's request body, with omitempty in its validate tag, has omitempty in its json tag too, so the client leaves it out when it is empty. The endpoint DSL owns the rule; dsl endpoint validate checks it the same way.",
		Fix:      "Add ,omitempty to the field's json tag, such as json:\"version,omitempty\".",
	},
	{
		Rule:     RuleInput,
		Requires: "Each input field has a json name and a doc, has no default, which the server does not apply, is not an array, and is not named hostname or target: every request has the target host as its hostname path segment and its --target flag.",
		Fix:      "Tag the field json:\"name\" and doc:\"...\", drop the default tag and make the provider treat the empty value as the default, use a slice for an array, and rename a field called hostname or target.",
	},
	{
		Rule:     RuleFails,
		Requires: rule.FailsRequires,
		Fix:      rule.FailsFix,
	},
	{
		Rule:     RuleSecret,
		Requires: "No secret.Value input field is tagged telemetry:\"attr\", is the key of a method that the API serves, or is an input of a read that the API serves: the key goes in the path and a read's input in the query, and a URL goes in logs.",
		Fix:      "Remove telemetry:\"attr\" from the secret field, give the method a key that is not a secret, or make the method a write, which sends its input in the body.",
	},
	{
		Rule:     RuleBefore,
		Requires: "A .Before step is func(context.Context, In) (In, error), on a method that the API serves and that has a secret.Value input field. Each input field tagged before:\"set\" has a step to set it.",
		Fix:      "Give the step the method's input type in and out, serve the behavior, give the plain secret the type secret.Value, and tag only the fields that the step fills before:\"set\".",
	},
	{
		Rule:     RuleReadBack,
		Requires: "Each write example that runs on the live host of the integration test says what a read of the behavior answers after it: behavior.Reads, or behavior.ReadsNone for an item that the example removed. A write whose result no read shows, such as a command's run, says why with behavior.NoReadBack on the example or .ReadsNothing on the method. A read back names a read of the behavior or its parent by its input, wants a value of the read's row type, and names only fields of it.",
		Fix:      "Add behavior.Reads(GetInput{...}, Entry{...}) to the example with the fields that the write set, or name the fields to compare a zero value, such as managed for false.",
	},
	{
		Rule:     RuleTag,
		Requires: "Each struct tag of an input field has a known key (command.KnownTags), and telemetry is \"attr\". A secret is the type secret.Value: the tag secret is not a key.",
		Fix:      "Correct the key or the value: a misspelled telemetry tag leaves the field off the span. Give a secret the type secret.Value of internal/secret in place of the tag secret:\"true\".",
	},
	{
		Rule:     RuleSurface,
		Requires: "A behavior with CLI also has API, and a behavior with API has an Area of the UI. An internal behavior has no API or CLI. Each input field of a CLI behavior has a type a flag holds: string, bool, int, []string, map[string]string, []byte (a file), secret.Value or map[string]secret.Value. The CLI owns the list; its generator builds each.",
		Fix:      "Add behavior.API, add behavior.Area(...) to a served behavior, remove API and CLI from the internal behavior, or give the field a type that a flag can hold.",
	},
	{
		Rule:     RuleExample,
		Requires: "Each method of a CLI behavior has an example. Each example and refusal has a description, and the input and output types of its method. A refusal has error text and no effects.",
		Fix:      "Add .Example(\"...\", In{...}, Out{...}) to the method, and correct the example or refusal that the message names.",
	},
	{
		Rule:     RuleSettings,
		Requires: "Settings are a struct. Each field has a mapstructure name and a doc.",
		Fix:      "Add mapstructure:\"name\" and doc:\"...\" to each settings field.",
	},
	{
		Rule:     RulePlatform,
		Requires: "The behavior has a provider for one or more platforms, each platform one time, and each provider implements the provider type of each method.",
		Fix:      "Add behavior.Platform(\"debian\", newDebian), remove the second declaration, or add the missing method to the provider.",
	},
	{
		Rule: RuleRequires,
		Requires: ChainChecks.Requires(
			RuleRequires,
		) + " The chain layer owns this rule: osapi dsl chain validate.",
		Fix: ChainChecks.Fix(RuleRequires),
	},
	{
		Rule: RuleInternal,
		Requires: ChainChecks.Requires(
			RuleInternal,
		) + " The chain layer owns this rule: osapi dsl chain validate.",
		Fix: ChainChecks.Fix(RuleInternal),
	},
	{
		Rule:     RuleWrites,
		Requires: "Each path given to Writes is \"*\" or an absolute path.Match pattern.",
		Fix:      "Use a pattern such as \"/etc/sysctl.d/osapi-*.conf\".",
	},
}

Checks are the rules that Validate applies, in the order that a behavior is usually written. dsl behavior validate --help prints each one, and each problem that Validate reports carries the fix of its rule. Thus an author, or an agent, can read the rules before it breaks one. Each Rule constant has one entry; a test fails on a rule without one.

HostFamilies are the platforms that gohai's family.Detect names, in the order the UI lists them. A Linux host whose platform has no family gets its own name, which is none of these.

View Source
var Spec = guide.Spec{
	Kinds: []guide.Kind{
		{Kind: KindDefinition, Title: "Definition"},
		{Kind: KindOption, Title: "Options of Define"},
		{Kind: KindMethod, Title: "Methods"},
		{Kind: KindRefine, Title: "Refinements of a method"},
		{Kind: KindExample, Title: "Hosts and effects of an example"},
		{Kind: KindHost, Title: "The host a provider gets"},
		{Kind: KindCall, Title: "Calls in a provider"},
		{Kind: KindError, Title: "Errors a provider returns"},
		{Kind: KindCompose, Title: "Building on other behaviors"},
		{Kind: KindTag, Title: "Tags on input, output and settings fields"},
		{Kind: KindTemplate, Title: "What a template reads"},
		{Kind: KindGenerated, Title: "Generated, never edited"},
		{Kind: KindNotYet, Title: "Not supported yet"},
	},
	Terms: []guide.Term{
		{
			Kind: KindDefinition,
			Name: `Register(Define(name, doc, options...))`,
			Does: "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 dsl behavior create --package sets when the name is a Go keyword.",
			When: "One time, in behavior.go: var Behavior = behavior.Register(behavior.Define(...)).",
		},

		{
			Kind: KindOption,
			Name: "Node",
			Does: "Runs the methods on a host, through the job system.",
			When: "Always. It is the only placement.",
		},
		{
			Kind: KindOption,
			Name: "API",
			Does: "Serves the methods over REST, with routes, permissions and the OpenAPI spec.",
			When: "When an operator or a program calls the behavior.",
		},
		{
			Kind: KindOption,
			Name: "CLI",
			Does: "Makes osapi client commands and their docs pages. Needs API.",
			When: "When an operator calls the behavior from a shell.",
		},
		{
			Kind: KindOption,
			Name: `Title("Package updates")`,
			Does: "Gives the behavior the title that a person reads: the title of its reference and chain pages, the name of its API tag, and its name on the UI's Behaviors page and on its steps of a plan. Without it, the title is the name with a capital letter, such as Sysctl.",
			When: "When the name does not read well with a capital letter: an initialism such as DNS, two words such as Package updates or Container image, or a child, which names its parent, such as User SSH key.",
		},
		{
			Kind: KindOption,
			Name: "Of(parent.Behavior)",
			Does: "Puts the behavior's items under an item of another behavior: Of(user.Behavior) puts sshkey at /api/node/{hostname}/user/{name}/sshkey and osapi client node user sshkey. Each input has the parent's key, such as name, which goes in the path before the method's own key. The permissions are the parent's: the keys of a user need user:read and user:write. The parent's provider is not required: a child that needs it declares Requires too.",
			When: "For a resource that exists only inside an item of another, such as the SSH keys of a user. For a child of the whole collection, use Under.",
		},
		{
			Kind: KindOption,
			Name: `Area(area.Name)`,
			Does: "Puts a served behavior in an area, one of area.All: its section of the UI's Behaviors page and of the list of steps of the Plans page, the folder of its SDK page, of its reference page and of its chain's page, and its section of the docs site's SDK and Behaviors menus. Use a constant of package area, such as area.Config or area.Hardware. area.All has the label and the order of each area.",
			When: "On each behavior with API. dsl behavior validate refuses a served behavior with none.",
		},
		{
			Kind: KindOption,
			Name: "Under(parent.Behavior)",
			Does: "Puts the behavior under the collection of another behavior, with no key of the parent: Under(log.Behavior) puts source at /api/node/{hostname}/log/source and osapi client node log source. The permissions are the parent's: the sources of the log need log:read. A behavior with neither Of nor Under is directly under node, by its own name.",
			When: "For a resource of a parent whose items have no key, such as the sources of the log, or that is about the whole collection, such as the updates of the packages. Not for a category: a behavior is never nested only to sort it, because the area sorts it.",
		},
		{
			Kind: KindOption,
			Name: "Internal",
			Does: "Gives the behavior no route, command or permission. Only the behaviors that require it can call it.",
			When: "For work that two behaviors share, such as writing a file.",
		},
		{
			Kind: KindOption,
			Name: "Requires(behaviors...)",
			Does: "Builds the providers of those behaviors first. The builder gets them with host.Require.",
			When: "When the behavior uses the methods of another behavior.",
		},
		{
			Kind: KindOption,
			Name: `Platform(PlatformDebian, build)`,
			Does: "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 a constant: PlatformDebian, PlatformSUSE, PlatformDarwin or PlatformLinux. dsl behavior validate refuses a name outside KnownPlatforms, here and in On, RunsOnPlatform and OnPlatform.",
			When: "One time for each platform that the behavior supports.",
		},
		{
			Kind: KindOption,
			Name: "Sudo(programs...)",
			Does: "Lists the programs that the providers run with sudo. The agent preflight checks that sudo allows each.",
			When: "For each program that needs root.",
		},
		{
			Kind: KindOption,
			Name: "Runs(programs...)",
			Does: "Lists the programs that the providers run without sudo. The agent warns when one is not installed. Runs(behavior.AnyProgram), \"*\", is each program: the agent and the integration test look for none.",
			When: "For each program that does not need root. AnyProgram only for a behavior that runs the program its caller names, such as command.",
		},
		{
			Kind: KindOption,
			Name: "RunsOnPlatform(platform, programs...)",
			Does: "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.",
			When: "For a program that only one platform has, such as vm_stat or sw_vers on darwin.",
		},
		{
			Kind: KindOption,
			Name: "SudoOnPlatform(platform, programs...)",
			Does: "Lists the programs that the provider declared for one platform runs with sudo. They hold on each host that this provider serves, so linux does not hold on debian when the behavior declares a debian provider. The agent and the integration test ask for them there only.",
			When: "For a program that each platform's provider runs in its own way, such as update-ca-certificates on debian and update-ca-trust on linux.",
		},
		{
			Kind: KindOption,
			Name: "RunsIfPresent(programs...)",
			Does: "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.",
			When: "For a program that a provider reads without, when it is missing, such as zfs.",
		},
		{
			Kind: KindOption,
			Name: `Writes("/etc/x.d/osapi-*.conf")`,
			Does: "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.",
			When: "For each path, also when a required behavior, such as managedfile, does the write.",
		},
		{
			Kind: KindOption,
			Name: "KeepsState",
			Does: "Says that the providers keep a record in the file-state bucket. Each read and write of it is a kv span.",
			When: "When the behavior keeps a record of what it wrote.",
		},
		{
			Kind: KindOption,
			Name: "Config(defaults)",
			Does: "Declares settings under behaviors.<name>, with a flag and an environment variable for each. A provider reads them with Settings.",
			When: "For standing config of the agent. A value for one call is an input.",
		},
		{
			Kind: KindOption,
			Name: `Validator("tag", check, schema, message)`,
			Does: "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).",
			When: "When no standard validate tag checks a value.",
		},

		{
			Kind: KindMethod,
			Name: `Read("name", fn)`,
			Does: "A method that reads the host: GET and <name>:read. Named list, get or status.",
			When: "For each read. fn is func(ctx, p Provider, in In) (Out, error).",
		},
		{
			Kind: KindMethod,
			Name: `Write("name", fn)`,
			Does: "A method that changes the host: POST, PUT or DELETE, and <name>:write. Named create, update or delete. Out has Changed bool.",
			When: "For each change. fn is func(ctx, p Provider, in In) (Out, error).",
		},
		{
			Kind: KindMethod,
			Name: `Action("name", fn)`,
			Does: "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 <name>:execute, which the operator role gets and automation does not. Named with one of the CLI's actions. Out has Changed bool.",
			When: "For a change that create, update and delete do not say, such as start, stop, restart, enable, signal or reboot.",
		},

		{
			Kind: KindRefine,
			Name: `.Key("field")`,
			Does: "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.",
			When: "On each method that acts on one item, such as get, update and delete of a key.",
		},
		{
			Kind: KindRefine,
			Name: `.NotAFact("why")`,
			Does: "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.",
			When: "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.",
		},
		{
			Kind: KindHost,
			Name: "h.Platform, h.Container, h.Hostname",
			Does: "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.",
			When: "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.",
		},
		{
			Kind: KindHost,
			Name: "h.Facts",
			Does: "The facts that the agent collected last, by their JSON names, as a func that returns them. A template that the provider renders with behavior.Render reads them as .Facts. The tests give none, so a template example reads only its vars.",
			When: "Only to render a template that a person uploaded. A value that the provider uses itself comes from a gohai collector.",
		},
		{
			Kind: KindHost,
			Name: "h.FS",
			Does: "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.",
			When: "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.",
		},
		{
			Kind: KindHost,
			Name: "h.Exec",
			Does: "Runs a program: RunCmd as the agent's user, RunPrivilegedCmd with sudo, RunPrivilegedCmdWithStdin for a secret, RunPrivilegedCmdFull for a command whose standard output, standard error and exit code the caller gets, such as docker exec, with a secret on standard input when it has one, RunCmdFull for the same as the agent's user, in a directory and with a timeout, such as command exec. 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.",
			When: "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().",
		},
		{
			Kind: KindHost,
			Name: "h.CommandEnabled",
			Does: "The agent's agent.command.enabled: false refuses each command that a caller names. The tests give true.",
			When: "In a method that runs a command the caller names, such as docker exec: refuse the call when it is false, as the command DSL does.",
		},
		{
			Kind: KindHost,
			Name: "h.Sources()",
			Does: "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.",
			When: "For each read of a fact of the host. The gohai test check fails a read that runs a command another way.",
		},
		{
			Kind: KindHost,
			Name: "h.FileState, h.FileStateBucket",
			Does: "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.",
			When: "Only through managedfile, which declares KeepsState. A provider does not read or write records itself.",
		},
		{
			Kind: KindHost,
			Name: "h.Objects",
			Does: "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.",
			When: "Only through the object building block, which the behavior requires.",
		},
		{
			Kind: KindHost,
			Name: "h.Settings, h.Required",
			Does: "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.",
			When: "Through Settings[T](h) and Require[P](h, b), not the fields.",
		},
		{
			Kind: KindHost,
			Name: "h.Now, h.Time()",
			Does: "The clock of the host. Time reads it. The tests give behaviortest.Now, 2026-01-02 03:04:05 UTC.",
			When: "For each time that a provider computes, such as an uptime from a boot time. Never time.Now.",
		},
		{
			Kind: KindHost,
			Name: "h.Resolver, h.Logger",
			Does: "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.",
			When: "The resolver goes to gohai through h.Sources(). Log with h.Logger only what a span does not carry.",
		},
		{
			Kind: KindCall,
			Name: "collector.NewWith(h.Sources())",
			Does: "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.",
			When: "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.",
		},
		{
			Kind: KindRefine,
			Name: ".PermitAs(verb) on an action",
			Does: "Makes the action's permission <name>:<verb> in place of <name>:execute, such as " +
				"docker:exec with types.VerbExec. Thus the action does not share a permission " +
				"with the other actions of its behavior, which the operator role gets. Only the admin " +
				"role gets the verb: types.VerbExec or types.VerbShell. dsl behavior validate refuses " +
				"it on a method that is not an action, and a different verb.",
			When: "For an action that runs a command that the caller gives, such as docker exec, " +
				"when the other actions of its behavior are for the operator role, such as docker start.",
		},
		{
			Kind: KindRefine,
			Name: ".Shell() on an action",
			Does: "Is .PermitAs(types.VerbShell): the action's permission is <name>:shell. Only the admin role gets a shell permission. dsl behavior validate refuses it on a method that is not an action.",
			When: "For an action that runs a shell command line, such as command shell.",
		},
		{
			Kind: KindRefine,
			Name: `.Always()`,
			Does: "Marks a method that changes the host each time it runs: an action such as restart, or an update whose input the host cannot compare with what it has, such as a password that the controller hashes with a new salt. Its output reports changed: true on each run, and the generated test does not run it again to see changed: false. dsl behavior validate refuses it on a create, a delete and a read.",
			When: "On an action that has no state to compare, or an update of a secret that the host keeps only as a hash, so a second run is not unchanged.",
		},
		{
			Kind: KindRefine,
			Name: `.ReadsNothing("why")`,
			Does: "Says why no read of the behavior shows what the method's examples change: its result is its own output, as a command's run or a ping is. dsl behavior validate takes it in place of a Reads on each example.",
			When: "On a write or an action that changes nothing that a read shows.",
		},
		{
			Kind: KindRefine,
			Name: `.Disrupts("why")`,
			Does: "Marks a method that takes the host down, such as a reboot or a shutdown, and says why. Its examples run on the fake host, but the integration test never runs them on a live host. dsl behavior validate refuses it with no reason.",
			When: "On a method whose run would take down the host that the test runs on.",
		},
		{
			Kind: KindRefine,
			Name: `.Describe("text")`,
			Does: "The one-line description of the method, in the help, the spec and the docs.",
			When: "On each method.",
		},
		{
			Kind: KindRefine,
			Name: `.On(platform...)`,
			Does: "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.",
			When: "When one method cannot run where the others do: a hostname read works on " +
				"macOS, but its update runs only on debian.",
		},
		{
			Kind: KindRefine,
			Name: "`.Sudo(program...)` and `.Runs(program...)` on a method",
			Does: "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.",
			When: "With On, for a program the other platforms do not have, such as hostnamectl " +
				"for a hostname update.",
		},
		{
			Kind: KindRefine,
			Name: ".Before(fn) on a method",
			Does: "Runs fn, func(ctx context.Context, in In) (In, error), on the controller in the method's " +
				"route, in a span of its own, before osapi queues the job. It changes what the caller sent " +
				"into what the agent gets, such as a password into its hash with password.Hash. A " +
				"secret.Value field that it leaves set goes to the job sealed for the target agents.",
			When: "When the agent must not see a secret in plain text. Tag the field that the step fills " +
				"before:\"set\", and clear the secret in the step.",
		},
		{
			Kind: KindRefine,
			Name: ".AdminOnly() on a method",
			Does: "Makes the permission of the method's verb, such as <name>:write, one that only the " +
				"admin role grants. With no mark, admin gets each permission; operator each read and each execute permission, and automation each read and each write permission, that is not admin only; read each read that is not admin only; auditor and observer get their lists. An action's permission is " +
				"<name>:execute. Each method with the same verb must agree. osapi controller role get " +
				"--name automation shows what a role gets.",
			When: "For a write that is a trust decision or reaches root, which automation must not make, such as an account or a cron entry.",
		},
		{
			Kind: KindRefine,
			Name: `.Explain("text")`,
			Does: "The longer description: what the method touches, and what a second call does.",
			When: "When one line does not say what the method changes.",
		},
		{
			Kind: KindRefine,
			Name: `.Example("doc", in, out, host...)`,
			Does: "A sample call. The docs page shows it, and the provider tests run it on a fake host.",
			When: "On each method. A CLI behavior needs one.",
		},
		{
			Kind: KindRefine,
			Name: `.Fails("doc", in, "error text", host...)`,
			Does: "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. " + rule.FailsRequires,
			When: rule.FailsWhen,
		},

		{
			Kind: KindExample,
			Name: "After(input)",
			Does: "Runs the method of that input before the example.",
			When: "When the example needs state, such as a parameter that is already managed.",
		},
		{
			Kind: KindExample,
			Name: `Prints("command", "output")`,
			Does: "Says what a command prints on the fake host.",
			When: "For each command that the provider reads.",
		},
		{
			Kind: KindExample,
			Name: `PrintsAfter("after", "command", "output")`,
			Does: "Says what a command prints after another command has run.",
			When: "For state that a program keeps, not a file.",
		},
		{
			Kind: KindExample,
			Name: `Exits("command", 1)`,
			Does: "Says the exit code of a command on the fake host, as RunCmdFull returns it. A command with no Exits exits 0.",
			When: "For a method that answers with the exit code of the command it runs, such as command exec.",
		},
		{
			Kind: KindExample,
			Name: `Stored(name, content, contentType)`,
			Does: "Says the object store of the fleet has the object name, with its content and its content type, client.ContentRaw or client.ContentTemplate, as osapi client file upload stores it. A provider reads it with h.Objects.Object.",
			When: "For an example of a behavior that deploys an uploaded file, such as through the object building block.",
		},
		{
			Kind: KindExample,
			Name: `Exists("path", "content")`,
			Does: "Puts a file on the fake host before the call.",
			When: "When the call reads or changes a file that is there.",
		},
		{
			Kind: KindExample,
			Name: `ExistsAfter("after", "path", "content")`,
			Does: "Says what a file holds on the fake host after a command has run.",
			When: "For a file that a program changes, such as /etc/group after groupadd. Declare its content before with Exists.",
		},
		{
			Kind: KindExample,
			Name: `Reads(GetInput{...}, Entry{...}, "field"...)`,
			Does: "Says what a read of the behavior, or of its parent, answers on the live host after a write example: the read whose input type the first value is answers a row with each named field of the want, or with no names, each field of the want that is not zero. ReadsNone says that no row answers it, or that the read reports not found: the example removed the item. The integration test runs each one after the example, so a write that reports changed but does nothing fails. dsl behavior validate checks that a read takes the input, that the want is its row type, and that each name is a field of it.",
			When: "On each write example that runs on the live host. Name a field to compare its zero value, such as managed for false after a delete. A list matches a list that has each of its values, as an interface's addresses also have its link-local address.",
		},
		{
			Kind: KindExample,
			Name: `NoReadBack("why")`,
			Does: "Says why no read shows what a write example changed. dsl behavior validate takes it in place of a Reads.",
			When: "Only when the item that the example acts on is not on the live host, or no read of the behavior names it.",
		},
		{
			Kind: KindExample,
			Name: `NotLive("why")`,
			Does: "Keeps an example or a refusal off the live host of the integration test, which skips it and says why. The provider tests still run it on the fake host.",
			When: "Only when a real host cannot be given the example's state through the behavior's own methods, such as the process that a signal stops, or when a real host differs from the fake one, such as a group nobody that Fedora has. Test it in the lab by hand, and say how in the definition.",
		},
		{
			Kind: KindExample,
			Name: `Live("field", fact)`,
			Does: "On the live host of the integration test, puts the target's value of fact in the input's field, by its JSON name, in place of the example's value. The provider tests keep the example's value. FactInterface is the target's primary interface, FactAdminGroup root or wheel on macOS, FactUser root, FactPID 1, FactSSHService ssh on the Debian family or else sshd, and FactSSHUnit that service with .service.",
			When: "For a read example whose item the fake host has but a real host names differently, such as eth0. A unit gate checks that the field exists and is a string or an int.",
		},
		{
			Kind: KindExample,
			Name: `Links("path", "target")`,
			Does: "Puts a symbolic link to target on the fake host before the call.",
			When: "When the call reads a link, such as /etc/localtime for the timezone.",
		},
		{
			Kind: KindExample,
			Name: `Wrote("path", "content")`,
			Does: "Says that the call leaves the file with that content.",
			When: "For each file that the call writes.",
		},
		{
			Kind: KindExample,
			Name: `Removed("path")`,
			Does: "Says that the call removes the file.",
			When: "For each file that the call removes.",
		},
		{
			Kind: KindExample,
			Name: `Ran("program", args...)`,
			Does: "Says that the call runs the command.",
			When: "For each command that the call runs to make a change.",
		},

		{
			Kind: KindCall,
			Name: "atomicfile.Write(ctx, h.FS, path, content, mode)",
			Does: "Writes the file atomically, in a file.write span. atomicfile.Remove and atomicfile.Chmod make file.remove and file.chmod spans.",
			When: "In a building block that writes files. A behavior that manages a file requires managedfile instead. A change through h.FS fails the tests.",
		},
		{
			Kind: KindCall,
			Name: "Render(text, TemplateData{Facts, Vars, Hostname})",
			Does: "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.",
			When: "In the provider of a method with a template input. The input is checked at the API already.",
		},
		{
			Kind: KindCall,
			Name: "Settings[T](Behavior)",
			Does: "Returns the settings of the behavior, or the defaults.",
			When: "In a builder or a method that reads a setting.",
		},
		{
			Kind: KindCall,
			Name: rule.RegisterName,
			Does: rule.RegisterDoes,
			When: rule.RegisterWhen,
		},

		{
			Kind: KindCompose,
			Name: "Chains",
			Does: "A behavior that requires others calls them on the same host, in the same job: dns calls netplan, and netplan calls managedfile. osapi dsl chain spec get has how to build one, its rules and the building blocks in this binary; osapi dsl chain get shows what each call sends and gets.",
			When: "Before a provider does generic work itself, such as writing a file that osapi manages.",
		},

		{
			Kind: KindError,
			Name: "behavior.ErrNotFound",
			Does: "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.",
			When: "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.",
		},
		{
			Kind: KindError,
			Name: "behavior.ErrNotManaged",
			Does: "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.",
			When: "Before a write over an item that something else owns. Ask managedfile, not the path: the agent's own unit is osapi-agent.service.",
		},
		{
			Kind: KindError,
			Name: "behavior.ErrNotInstalled",
			Does: "A program that the method needs is not on the host. The API answers 409.",
			When: "When a method needs a program that the platform does not always have, and Runs or RunsIfPresent does not say it.",
		},
		{
			Kind: KindError,
			Name: "behavior.ErrInvalid",
			Does: "The host refuses the input, which the validate tags cannot see, such as a path that is a directory where the method reads a file. On one host the API answers 400; on a broadcast the row of the host is failed with the message.",
			When: "Wrap it with what is wrong: fmt.Errorf(\"%s: a directory, not a file: %w\", path, behavior.ErrInvalid). Use a validate tag when the input alone tells it.",
		},
		{
			Kind: KindError,
			Name: "behavior.ErrUnsupported",
			Does: "The method does not apply to this host: its platform, or a container. The row of the host is skipped, not failed.",
			When: "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.",
		},
		{
			Kind: KindExample,
			Name: "A write example on a live host",
			Does: "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() method once. Prints, PrintsAfter and Exists only answer the fake host.",
			When: "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.",
		},
		{
			Kind: KindTag,
			Name: `json:"name"`,
			Does: "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.",
			When: "On each field.",
		},
		{
			Kind: KindTag,
			Name: rule.TagName,
			Does: rule.TagDoes + " 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.",
			When: rule.TagWhen,
		},
		{
			Kind: KindTag,
			Name: `default:"..."`,
			Does: "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.",
			When: "Never on a behavior input. The provider treats the empty value as the default, and the doc says what it is.",
		},
		{
			Kind: KindTag,
			Name: `doc:"..."`,
			Does: "The description in the spec, the flag help and the docs pages. The input rule fails an input field with none.",
			When: "On each field.",
		},
		{
			Kind: KindTag,
			Name: `render:"..."`,
			Does: `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.`,
			When: "On an output field that a table must show differently.",
		},
		{
			Kind: KindTag,
			Name: `telemetry:"attr"`,
			Does: "Records the input field on the span of the method. The field that .Key names is recorded without it.",
			When: "On the field that names the item, when the method has no key, and on other fields a trace must show.",
		},
		{
			Kind: KindTag,
			Name: `template:"vars"`,
			Does: "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.",
			When: "On an input that holds a template, such as the content of a file. Render it with Render.",
		},
		{
			Kind: KindTag,
			Name: "secret.Value",
			Does: "Not a tag: the type of an input field that holds a secret, from internal/secret; map[string]secret.Value is a map of them, such as the env of a container. It is a reference, secret://<vault>/<key>, or the value. Redacted from the audit log by name, but a reference stays; a string of format password, writeOnly and x-osapi-secret in the spec, with a description that says what it takes; never recorded on a span; its reference or [redacted] in a chain record. Its flag takes a reference, or - to read the value from standard input, and refuses a value; an example with a value shows -. The provider reads it with Reveal. The route resolves a reference from its vault, after the limits of use: secret:use, and the targets of the vault. The job client seals the value for the target agents, and the dispatch of the agent opens it. The secret rule refuses one with telemetry:\"attr\", one that is the key, and one in a read, which goes in the query. A chain gives a secret only to a secret.Value of the behavior it calls: the tests of the examples check it.",
			When: "On each input that holds a password, a key or a token. Not a string: a string whose name is on the audit denylist fails TestSecretsAreTyped.",
		},
		{
			Kind: KindTag,
			Name: `before:"set"`,
			Does: "The method's .Before step sets the field. It is not in the request, the command or the UI: the caller does not send it.",
			When: "On the field that the step fills, such as password_hash.",
		},
		{
			Kind: KindTag,
			Name: `mapstructure:"name"`,
			Does: "The config key of a settings field.",
			When: "On each field of the struct given to Config.",
		},

		{
			Kind: KindTemplate,
			Name: ".Vars.<name>",
			Does: "A value from the vars of the request. The API refuses a template that reads a var that the request does not give.",
			When: "For a value that the caller gives with each call.",
		},
		{
			Kind: KindTemplate,
			Name: ".Hostname",
			Does: "The hostname of the agent that renders the template.",
			When: "For a value that names the host.",
		},
		{
			Kind: KindTemplate,
			Name: ".Facts.<key>",
			Does: "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.",
			When: "For a value that differs from host to host.",
		},
		{
			Kind: KindGenerated,
			Name: "internal/behaviors/<name>/gen/",
			Does: "The routes, handlers, commands, spec and tests of the behavior, from go generate ./internal/behaviors/all.",
			When: "Change the definition, then generate. A generated test that fails is fixed in the definition or in internal/behavior/gen.",
		},
		{
			Kind: KindGenerated,
			Name: "internal/behaviors/<name>/mocks/",
			Does: "The double of the provider, from go generate ./internal/behaviors/<name>/mocks.",
			When: "Run it again after provider.go changes.",
		},
		{
			Kind: KindGenerated,
			Name: "docs/docs/sidebar/reference/behaviors/<area>/<name>/",
			Does: "The docs page of the behavior, in the folder of its area, or of internal for an internal behavior: the output of osapi dsl behavior get and osapi dsl behavior method get, as markdown, from just cli-docs-generate (osapi dsl docs generate).",
			When: "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.",
		},
		{
			Kind: KindGenerated,
			Name: "docs/docs/sidebar/usage/cli/",
			Does: "The CLI pages, from just cli-docs-generate. The help of a behavior command comes from .Describe, .Explain, .Example and .Fails.",
			When: "Change the definition, then generate. A generated test that fails is fixed in the definition or in internal/behavior/gen.",
		},
		{
			Kind: KindGenerated,
			Name: "internal/controller/api/gen/, pkg/sdk/client/*.gen.go, ui/src/sdk/gen/, docs/docs/gen/",
			Does: "The full spec, the SDK, the UI client and the API pages, from just generate.",
			When: "Change the definition, then generate. A generated test that fails is fixed in the definition or in internal/behavior/gen.",
		},
		{
			Kind: KindNotYet,
			Name: "A command or a shell from the caller",
			Does: "There is no execute permission.",
			When: "Stop, and tell the person what is missing. Do not build around it.",
		},
		{
			Kind: KindNotYet,
			Name: "Streaming and uploads",
			Does: "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.",
			When: "Stop, and tell the person what is missing. Do not build around it.",
		},
	},
}

Spec is every term of the behavior DSL. osapi dsl behavior spec get prints it, so an author, or an agent, learns the DSL from the binary that it builds. A test fails on an exported option, method, refinement or example part of this package without an entry, and on a field tag that this package reads without one.

View Source
var TestChecks = guide.Checks{
	{
		Rule:     TestPlatforms,
		Requires: "Each platform that a method serves runs at least one of its examples.",
		Fix:      "Add an example for the platform, or name it in an example's OnPlatform.",
	},
	{
		Rule:     TestOutput,
		Requires: "Each example runs without an error, and returns the output that it declares.",
		Fix:      "Correct the output of the example, or the provider that returns a different one.",
	},
	{
		Rule:     TestEffects,
		Requires: "An example of a write that changes the host declares its effects, and the host has each one after the call.",
		Fix:      "Add Wrote, Removed or Ran to the example, or correct the effect that the provider did not make.",
	},
	{
		Rule:     TestIdempotent,
		Requires: "A second call with the same input reports changed: false.",
		Fix:      "Compare the host with the input before the provider acts, and change nothing when they agree.",
	},
	{
		Rule:     TestErrors,
		Requires: "The provider does not panic when a file, command or store call fails.",
		Fix:      "Check each error, and return it. Do not use the zero value of a call that failed.",
	},
	{
		Rule:     TestState,
		Requires: "The provider does not panic when a record in the file-state bucket is damaged.",
		Fix:      "Check the record before the provider uses it, and return an error when it is not complete.",
	},
	{
		Rule:     TestRefusal,
		Requires: "Each refusal declared with .Fails fails, with an error that contains its text.",
		Fix:      "Refuse the input in the provider or with a validate tag, or correct the error text of the refusal.",
	},
	{
		Rule:     TestTraversal,
		Requires: "No string input writes a file outside the directories that the example writes.",
		Fix:      "Add a validate pattern to the field, or check it in the provider and declare the refusal with .Fails.",
	},
	{
		Rule:     TestNewLine,
		Requires: "No string input adds a line to a file.",
		Fix:      "Refuse \r and \n in the field, with the validate tag no_linebreak.",
	},
	{
		Rule:     TestOption,
		Requires: "No string input reaches a command as an option.",
		Fix:      "Refuse a leading - in the field, or pass -- before it.",
	},
	{
		Rule:     TestShell,
		Requires: "No input reaches a shell script.",
		Fix:      "Run the program with its arguments, not through sh -c.",
	},
	{
		Rule:     TestRuns,
		Requires: "Each program that the provider runs is declared.",
		Fix:      "Add behavior.Runs(\"program\"), or behavior.Sudo(\"program\") for a program run as root.",
	},
	{
		Rule:     TestGohai,
		Requires: "A read runs each command through gohai: it reads the facts of the host with a gohai collector and h.Sources(), not with h.Exec.",
		Fix:      "Read the fact with the gohai collector that has it, such as services.NewWith(h.Sources()). A fact that gohai does not read is a change to gohai first. A read of what is not a fact of the host, such as the updates of the package index, declares why with .NotAFact(\"...\").",
	},
	{
		Rule:     TestWrites,
		Requires: "Each path that the provider writes, removes or changes the mode of is declared, also through a required behavior.",
		Fix:      "Add a pattern that covers the path to behavior.Writes.",
	},
	{
		Rule:     TestFileSpan,
		Requires: "Each change to a file goes through the atomicfile package, which writes it atomically and makes its file.write, file.remove or file.chmod span.",
		Fix:      "For a file that osapi manages, require managedfile and call it with behavior.Call. Otherwise use atomicfile.Write, atomicfile.Remove or atomicfile.Chmod with the ctx of the method, not h.FS.",
	},
	{
		Rule:     TestKeepsState,
		Requires: "A behavior that uses the file-state bucket declares it.",
		Fix:      "Add behavior.KeepsState, or require the behavior that keeps the record.",
	},
	{
		Rule:     TestCall,
		Requires: "A provider calls the methods of a required behavior through behavior.Call, so that the trace shows each call as a step.",
		Fix:      "Call it with behavior.Call(ctx, other.Behavior, other.Method, provider, in).",
	},
}

TestChecks are what the tests of every behavior check, when go test runs its examples and refusals on a fake host. dsl behavior validate --help prints each one, and the message of each failure ends with its fix.

Functions

func Call

func Call[P any, In any, Out any](
	ctx context.Context,
	b *Behavior,
	fn func(ctx context.Context, p P, in In) (Out, error),
	p P,
	in In,
) (Out, error)

Call runs fn, a method of b, with p, b's provider, inside the span and the metrics of that method, as the agent runs a method. A behavior calls the behaviors it requires through Call, so a trace shows each one as its own step: behavior.sysctl.create, then behavior.managedfile.update under it. A direct call of fn skips the span, and behaviortest.Run fails it.

Call checks in against its validate tags before fn runs, as the API does for a served method, so an internal behavior's rules hold for each caller. An input that breaks one is an error, and fn does not run.

result, err := behavior.Call(ctx, managedfile.Behavior, managedfile.Update, d.files, in)

func Changed

func Changed(
	out any,
) (changed bool, ok bool)

Changed reports a write's changed field: the bool field whose JSON name is changed. ok is false when out has none.

func CheckTemplates

func CheckTemplates(
	in any,
) (string, bool)

CheckTemplates checks each template field of in before a job is queued: it parses, it starts each field with .Facts, .Vars or .Hostname, and each .Vars.<name> it reads is in its vars. Facts are known only on each host, so they are not checked here. The message names the field and what is wrong.

func ChildSpans

func ChildSpans(
	b *Behavior,
) []string

ChildSpans are the spans a call of b can make under its own span, from what b and the behaviors it requires declare: the span of each required behavior's methods, a command span for each program, the file spans when a behavior declares Writes, and the kv spans of the file-state bucket when one declares KeepsState. Each appears once, in that order.

func CurrentChainSpec

func CurrentChainSpec() guide.Spec

CurrentChainSpec is ChainSpec, with "Building blocks": each internal behavior in the registry, with what it does and its methods. Thus the list agrees with the binary.

func CurrentSpec

func CurrentSpec(
	factKeys ...string,
) guide.Spec

CurrentSpec is Spec, with factKeys, the keys that .Facts has, added to that term. Thus the list agrees with the binary.

func FieldShape

func FieldShape(
	t reflect.Type,
	input bool,
) string

FieldShape is t with its top-level JSON fields, as Shape shows a type, from its struct tags alone: a required input field, validate:"required", is marked *. It does not walk into the fields, so a type that holds itself, such as a span tree, has a shape too.

func GroupOf

func GroupOf(
	b *Behavior,
) *endpoint.Group

GroupOf is b's endpoint group, or nil when its gen package was not imported or b has no API.

func InputAttributes

func InputAttributes(
	in any,
	fields []string,
) []attribute.KeyValue

InputAttributes returns a span attribute for each field of in named in fields, by JSON name, keyed by that name. A secret is never recorded.

func JSONName

func JSONName(
	f reflect.StructField,
) string

JSONName is the field's name in JSON: the json tag's name, or the Go name.

func ReadMethod

func ReadMethod(
	b *Behavior,
	input any,
) (*Behavior, *Method)

ReadMethod is the read of b, or of b's parent, whose input type is the type of input, and the behavior that has it, or nil. A ReadBack names its read this way, as After names its method.

func ReadRow

func ReadRow(
	m *Method,
) reflect.Type

ReadRow is the type of one row of m's output: the element of a list, or the output itself.

func Record

func Record(
	ctx context.Context,
	s *Step,
) context.Context

Record is ctx with s as the step that each Call under it adds its own step to. Without it, Call records nothing.

func Redact

func Redact(
	in any,
) any

Redact is in as a step records it: when it holds a secret.Value, its JSON as a map, in which each secret is its reference or [redacted], at each depth. Anything else is in unchanged.

func RegisterGroup

func RegisterGroup(
	name string,
	g *endpoint.Group,
)

RegisterGroup records g as the endpoint group of the behavior with the given name. The generated gen/group.go of each behavior with an API calls it, and the endpoint layer makes the behavior's spec from the group.

func Render

func Render(
	text string,
	data TemplateData,
) (string, error)

Render renders text, a template, with data. A key that data does not have is an error, not an empty value.

func Reset

func Reset()

Reset empties the registry. Tests use it to start from nothing.

func Scaffold

func Scaffold(
	root string,
	name string,
	goPackage string,
	doc string,
	requires []string,
) ([]string, error)

Scaffold writes a new behavior's standard layout under internal/behaviors/<package>/, in the osapi checkout at root, and registers it in internal/behaviors/all. It returns the files written, relative to root, the registration last. Everything is rendered and checked before anything is written, so a taken name or a root that is not a checkout writes nothing.

requires names registered behaviors that the new one is built on. The scaffold writes the wiring of each one: behavior.Requires in the definition, host.Require in the builder and a field of the provider. The author then writes the behavior.Call of each, which the tests ask for.

func Secret

func Secret(
	f reflect.StructField,
) bool

Secret reports whether f carries a secret: its type is secret.Value, or a map, a slice or a pointer of it. A secret is redacted from the audit log, marked write-only in the spec, and never recorded on a span.

func SecretFields

func SecretFields() map[string]bool

SecretFields are the JSON names of every secret.Value input field, at each depth, across every registered behavior's methods. The audit log redacts each by name.

func SecretLeaks

func SecretLeaks(
	parent *Step,
	child *Step,
) []string

SecretLeaks are the secrets that the call of parent gives to a field of the call of child that is not a secret.Value: a literal value of a secret field of the parent's input, in a string of the child's input. The child records such a field in its chain record, its span or an audit entry, so a chain gives a secret only to a secret.Value. The examples run each chain, so their tests check it, under RuleSecret.

func SetByBefore

func SetByBefore(
	f reflect.StructField,
) bool

SetByBefore reports whether the controller step of f's method sets f.

func SetMeterProvider

func SetMeterProvider(
	mp metric.MeterProvider,
)

SetMeterProvider creates the behavior instruments on mp. The agent calls it with the provider it exports metrics through. Until then the global meter provider is used, which records nothing unless one was installed.

func Settings

func Settings[T any](
	b *Behavior,
) T

Settings returns b's decoded settings as T, the struct passed to Config. Before the config is loaded, or in a process that never loads it, it returns the declared defaults.

func Shape

func Shape(
	t reflect.Type,
	s *Schema,
	input bool,
) string

Shape is t with the fields of its schema s, as dsl behavior get and dsl endpoint get show a type: CreateInput { key*, value* }, with each required field of an input marked *.

func TestFailure

func TestFailure(
	rule string,
	message string,
) string

TestFailure is message, followed by the fix of the test check rule.

func Tree

func Tree(
	b *Behavior,
) string

Tree is b and the behaviors that it calls, down the chain: dns → netplan → managedfile, or status → (hostname, uptime) when a behavior calls more than one.

func TypeName

func TypeName(
	t reflect.Type,
) string

TypeName is the name of t as a type list shows it: []Entry for a list.

Types

type Behavior

type Behavior struct {
	// Name is the behavior's name: the path segment, the CLI command and the
	// permission prefix. A child has its parent's permission prefix.
	Name string
	// Doc says what the behavior manages, in one line.
	Doc string
	// Title is the behavior's name as a person reads it: the title of its
	// pages, its API tag and its blocks in the UI. Define sets it from Name,
	// capitalized, when the definition does not give one with Title.
	Title string
	// Placement is where the work runs.
	Placement Placement
	// Area is the area of the behavior's operations, one of area.All. Area
	// sets it.
	Area area.Name
	// Parent is the behavior this one is nested under, set with Of or
	// Under: a user's SSH keys are under the user. Nil for a behavior of
	// the host.
	Parent *Behavior
	// UnderCollection is true for a child declared with Under: it is under
	// the parent's collection, with no key of the parent in its path, as
	// the log sources are under the log. A child declared with Of is under
	// an item of the parent.
	UnderCollection bool
	// API serves the behavior over REST: routes, the OpenAPI spec and its
	// API docs. Without it the behavior is reachable only through another
	// behavior or the job system.
	API bool
	// CLI gives the behavior client commands and CLI docs pages. The
	// commands call the API, so CLI needs API.
	CLI bool
	// Requires are the behaviors this one is built on. The agent builds each
	// one's provider first and hands it to this one's builder, and this
	// one's methods call theirs as Go calls on the same host.
	Requires []*Behavior
	// Internal marks a behavior only other behaviors use: it has no route,
	// no command, no spec and no permissions.
	Internal bool
	// Methods are the operations, in the order they were declared.
	Methods []*Method
	// Defaults is the behavior's settings struct as declared with Config,
	// its field values the defaults. Nil when the behavior has none.
	Defaults any

	// Platforms are how the behavior's provider is built on each platform it
	// supports, in the order declared. On any other platform its methods are
	// skipped.
	Platforms []*PlatformProvider
	// Sudo lists the programs the behavior's providers run with sudo, which
	// the agent's preflight checks it may run.
	Sudo []string
	// Runs lists the programs its providers run without sudo, declared with
	// Runs.
	Runs []string
	// PlatformRuns lists the programs its providers run on some platforms
	// only, declared with RunsOnPlatform.
	PlatformRuns []PlatformPrograms
	// ProviderSudo lists the programs that one platform's provider runs with
	// sudo, declared with SudoOnPlatform.
	ProviderSudo []PlatformPrograms
	// RunsIfPresent lists the programs its providers run only when the host
	// has them, declared with RunsIfPresent.
	RunsIfPresent []string
	// Writes lists the paths its providers write, remove or change the mode
	// of, as path.Match patterns, declared with Writes. "*" is any path.
	Writes []string
	// KeepsState is set when its providers keep a record in the file-state
	// bucket, declared with KeepsState.
	KeepsState bool
	// contains filtered or unexported fields
}

Behavior is one area of a host that osapi manages, such as kernel parameters or DNS resolver settings.

func All

func All() []*Behavior

All returns every registered behavior, in the order of the words of its command: a group's behaviors are with each other, and a behavior that Of nests, such as sshkey, is after its parent, as osapi client node lists them.

func Define

func Define(
	name string,
	doc string,
	opts ...Option,
) *Behavior

Define declares a behavior. Methods are options too, so a definition reads top to bottom as name, description, placement and methods.

func Lookup

func Lookup(
	name string,
) *Behavior

Lookup returns the behavior with the given name, or nil.

func Register

func Register(
	b *Behavior,
) *Behavior

Register adds b to the registry and returns it, so a behavior's package can declare and register in one statement:

var Behavior = behavior.Register(behavior.Define("sysctl", ...))

A behavior is registered when its package is imported, and internal/behaviors/all imports every one. Registering two behaviors with the same name keeps the last; dsl behavior validate reports the clash.

func RequiredBy

func RequiredBy(
	b *Behavior,
) []*Behavior

RequiredBy are the registered behaviors that require b, in registry order.

func (*Behavior) Command

func (b *Behavior) Command(
	m *Method,
) string

Command is the method's CLI command, such as osapi client node dns get.

func (*Behavior) CurrentSettings

func (b *Behavior) CurrentSettings() any

CurrentSettings is b's decoded settings, or its declared defaults before the config is read, or nil when it declares none: what the agent puts in the host it builds b's provider with.

func (*Behavior) Method

func (b *Behavior) Method(
	name string,
) *Method

Method returns the method with the given name, or nil.

func (*Behavior) Operation

func (b *Behavior) Operation(
	m *Method,
) string

Operation is the job operation name the agent dispatches on, such as sysctl.get.

func (*Behavior) OperationID

func (b *Behavior) OperationID(
	m *Method,
) string

OperationID is the method's operationId, by the rule the hand-written specs follow: the HTTP method, the placement, the behavior, and ByKey on a keyed read so it does not collide with the list.

func (*Behavior) ParentKey

func (b *Behavior) ParentKey() string

ParentKey is the key of the parent's items, such as name for a user: the key that the parent's keyed methods have. Empty for a behavior with no parent, a child declared with Under, or a parent with no keyed method.

func (*Behavior) Path

func (b *Behavior) Path(
	m *Method,
) string

Path is the method's route: /api/node/{hostname}, the group and name, the key when the method addresses one item, and an action's name.

func (*Behavior) Permission

func (b *Behavior) Permission(
	v types.Verb,
) types.Permission

Permission is the permission a method needs: the behavior's name and the verb, so sysctl get needs sysctl:read. A child has its parent's permission: the sources of the log need log:read.

func (*Behavior) Programs

func (b *Behavior) Programs(
	platform PlatformName,
) (sudo []string, runs []string)

Programs are the programs b runs on platform, with sudo and without: the behavior's own, and each method's that runs there, once each. An empty platform is every platform. A behavior that declares providers and has none for platform runs nothing there, so it needs no program there: an agent on Fedora does not ask for the apt-get of a Debian-only behavior.

func (*Behavior) Provider

func (b *Behavior) Provider(
	platform PlatformName,
	h any,
) (any, error)

Provider builds b's provider for platform with h, the host.Host the agent passes: the provider declared for platform itself, or else, on a platform other than macOS, the one declared for PlatformLinux. The agent runs on Linux and macOS only, so every platform name but darwin is a Linux distribution. It returns nil and no error when b declares neither.

func (*Behavior) ProviderSudoOn

func (b *Behavior) ProviderSudoOn(
	platform PlatformName,
) []string

ProviderSudoOn is the programs that SudoOnPlatform declares for the provider of a host whose platform is platform. An empty platform is every provider.

func (*Behavior) RunBefore

func (b *Behavior) RunBefore(
	ctx context.Context,
	m *Method,
	in any,
) (any, error)

RunBefore is in after the controller step of b's method m, in a span of its own on the controller. Without a step, it is in. It fails when the step fails.

func (*Behavior) RunsOnHost

func (b *Behavior) RunsOnHost(
	m *Method,
	platform PlatformName,
) bool

RunsOnHost reports whether m runs on a host whose platform is platform, as the agent decides: b has a provider there, and m runs there.

func (*Behavior) Serves

func (b *Behavior) Serves(
	m *Method,
	platform PlatformName,
) bool

Serves reports whether the provider b declares for platform builds the provider m runs with on some platform: every provider without On, else the one each platform On names resolves to, as Provider resolves it.

func (*Behavior) SetSettings

func (b *Behavior) SetSettings(
	v any,
)

SetSettings stores the decoded settings. The config loader calls it once the config is read; a behavior reads them with Settings.

func (*Behavior) SettingFlag

func (b *Behavior) SettingFlag(
	path string,
) string

SettingFlag is the agent start flag for one setting, such as sysctl-dir: the behavior's name, then the key's path with dots and underscores as dashes.

func (*Behavior) SettingsKey

func (b *Behavior) SettingsKey() string

SettingsKey is the config key the behavior's settings sit under, such as behaviors.sysctl.

func (*Behavior) SettingsType

func (b *Behavior) SettingsType() reflect.Type

SettingsType is the type of the behavior's settings struct, or nil when it declares none.

func (*Behavior) SpanName

func (b *Behavior) SpanName(
	m *Method,
) string

SpanName is the name of the span a method's call opens on the agent.

func (*Behavior) Tag

func (b *Behavior) Tag() string

Tag is the spec tag the docs site groups the behavior's operations under, such as sysctl_operations.

func (*Behavior) TypeName

func (b *Behavior) TypeName() string

TypeName is the prefix of every schema, parameter and operation name the spec gives this behavior: sysctl is Sysctl, and a route under the interface is InterfaceRoute.

type Effect

type Effect struct {
	Kind EffectKind `json:"kind"`
	// Path is the file, for EffectWrote and EffectRemoved.
	Path string `json:"path,omitempty"`
	// Content is the file's whole content, for EffectWrote.
	Content string `json:"content,omitempty"`
	// Command is the command line, for EffectRan.
	Command string `json:"command,omitempty"`
}

Effect is one change an example makes on the host.

func Ran

func Ran(
	name string,
	args ...string,
) Effect

Ran says the call runs a command, with or without sudo.

func Removed

func Removed(
	path string,
) Effect

Removed says the call leaves path absent.

func Wrote

func Wrote(
	path string,
	content string,
) Effect

Wrote says the call leaves path holding exactly content.

type EffectKind

type EffectKind string

EffectKind is what an Effect checks.

const (
	// EffectWrote checks a file holds exactly some content.
	EffectWrote EffectKind = "wrote"
	// EffectRemoved checks a file is gone.
	EffectRemoved EffectKind = "removed"
	// EffectRan checks a command ran.
	EffectRan EffectKind = "ran"
)

type Example

type Example struct {
	// Doc says what the example shows.
	Doc string `json:"doc"`
	// Input is a value of the method's input type.
	Input any `json:"input"`
	// Output is a value of the method's output type, as one host would
	// return it.
	Output any `json:"output,omitempty"`
	// Given is the host the example runs on, and Effects what the call
	// changes on it. The provider tests run every example against a fake host
	// built from Given and check its Output and Effects; see HostOption.
	Given   []Given  `json:"given,omitempty"`
	Effects []Effect `json:"effects,omitempty"`
	// Platforms limits the example to these platforms, as Platform names
	// them; OnPlatform sets it. An example with none runs on each platform
	// the method serves.
	Platforms []PlatformName `json:"platforms,omitempty"`
	// NotLive is why the example runs only on the fake host, not on the
	// live host of the integration test; NotLive sets it. Empty runs it on
	// both.
	NotLive string `json:"not_live,omitempty"`
	// ReadBacks are the reads that show what a write example changed, which
	// Reads and ReadsNone add. The integration test runs each one on the
	// live host after the example.
	ReadBacks []ReadBack `json:"read_backs,omitempty"`
	// NoReadBack is why no read shows what a write example changed, which
	// NoReadBack sets.
	NoReadBack string `json:"no_read_back,omitempty"`
	// Live are the fields of Input that the integration test fills with a
	// fact of the live target, which Live sets.
	Live []LiveField `json:"live,omitempty"`
}

Example is one sample call of a method, used for the docs pages.

func (Example) RunsOn

func (e Example) RunsOn(
	platform PlatformName,
) bool

RunsOn reports whether the example runs on platform.

type Fact

type Fact string

Fact is a value of the live target that an example's input can take in the integration test, in place of the value that it names for the fake host.

const (
	// FactInterface is the target's primary network interface, such as
	// enp0s1, as agent get reports it.
	FactInterface Fact = "interface"
	// FactAdminGroup is the group of the administrator: root on Linux,
	// wheel on macOS.
	FactAdminGroup Fact = "admin_group"
	// FactUser is a user that each host has: root.
	FactUser Fact = "user"
	// FactPID is a process that each host runs: 1, the init process.
	FactPID Fact = "pid"
	// FactSSHService is the SSH server's service: ssh on the Debian
	// family, sshd on the others.
	FactSSHService Fact = "ssh_service"
	// FactSSHUnit is FactSSHService's systemd unit, such as ssh.service.
	FactSSHUnit Fact = "ssh_unit"
)

type Given

type Given struct {
	Kind GivenKind `json:"kind"`
	// Input is the call's input, for GivenCall; the method is the one whose
	// input type it is.
	Input any `json:"input,omitempty"`
	// Command is the command line, for GivenOutput.
	Command string `json:"command,omitempty"`
	// Path and Content are the file, for GivenFile; Content is also the
	// command's output, for GivenOutput.
	Path    string `json:"path,omitempty"`
	Content string `json:"content,omitempty"`
	// After is the command line that must have run before Command prints
	// Content, for a GivenOutput declared with PrintsAfter, or before the
	// file holds Content, for a GivenFile declared with ExistsAfter.
	After string `json:"after,omitempty"`
	// ExitCode is the command's exit code, for GivenOutput declared with
	// Exits.
	ExitCode int `json:"exit_code,omitempty"`
	// ContentType is the object's content type, for GivenObject, whose name
	// is Path.
	ContentType types.ContentType `json:"content_type,omitempty"`
}

Given is one thing true of the host before an example runs.

func After

func After(
	input any,
) Given

After runs another of the behavior's methods with input before the example: the method whose input type input is. Use it for the state a read or a change needs, such as a parameter that must already be managed. The method can be the parent's, for a behavior that is Of one: the keys of a user need the user.

func Exists

func Exists(
	path string,
	content string,
) Given

Exists says a file holds content before the example runs.

func ExistsAfter

func ExistsAfter(
	after string,
	path string,
	content string,
) Given

ExistsAfter says a file holds content once a command line, after, has run: a file that a program changes, such as /etc/group after groupadd. Declare the file before with Exists and its later content with ExistsAfter, as PrintsAfter does for a command's output.

func Exits

func Exits(
	command string,
	code int,
) Given

Exits says a command exits with code when it runs, as RunCmdFull returns it. A command with no Exits exits 0.

func Links(
	path string,
	target string,
) Given

Links gives the host a symbolic link at path to target before the call, such as /etc/localtime to the zone file of the host's timezone.

func Prints

func Prints(
	command string,
	output string,
) Given

Prints says a command prints output when it runs.

func PrintsAfter

func PrintsAfter(
	after string,
	command string,
	output string,
) Given

PrintsAfter says a command prints output once another command line, after, has run. It is for state a program keeps rather than a file: a package query that prints "not installed" until the install runs, and "installed" from then on. Declare the first answer with Prints and the later one with PrintsAfter.

func Stored

func Stored(
	name string,
	content string,
	contentType types.ContentType,
) Given

Stored says the object store of the fleet has the object name, with content and the content type its uploader gave it, raw or template, as osapi client file upload stores it.

type GivenKind

type GivenKind string

GivenKind is what a Given sets up.

const (
	// GivenCall runs another of the behavior's methods first.
	GivenCall GivenKind = "call"
	// GivenOutput is what a command prints.
	GivenOutput GivenKind = "output"
	// GivenFile is a file already on the host.
	GivenFile GivenKind = "file"
	// GivenLink is a symbolic link already on the host.
	GivenLink GivenKind = "link"
	// GivenObject is an object in the object store of the fleet.
	GivenObject GivenKind = "object"
)

type HostOption

type HostOption interface {
	// contains filtered or unexported methods
}

A HostOption describes the host an example runs on, or what the call changes there. The provider tests build a fake host from an example's options, run the method on it with each platform's provider, and check the example's output and effects, so the example a docs page shows is also the test that proves it.

func Live

func Live(
	field string,
	fact Fact,
) HostOption

Live says that on the live target of the integration test, the input's field, by its JSON name, takes fact in place of the value that the example names for the fake host: an eth0 that the target does not have becomes its own interface. The provider tests keep the example's value.

func NoReadBack

func NoReadBack(
	why string,
) HostOption

NoReadBack says why no read of the behavior shows what a write example changed, such as a command's run, whose output is its result. The gate takes it in place of a Reads.

func NotLive

func NotLive(
	why string,
) HostOption

NotLive keeps a write example off the live host of the integration test, for one whose state a real host cannot be given through the behavior's own methods, such as the process that a signal stops: After can only call the behavior's methods, and none of process's starts a process. why says so, and the docs page shows it. The provider tests still run it on the fake host.

func OnPlatform

func OnPlatform(
	platforms ...PlatformName,
) HostOption

OnPlatform limits an example to platforms, for a read whose answer is the platform's own, such as the name of the operating system: an Ubuntu host reads ubuntu, and a Mac reads darwin. The provider tests run the example only with these platforms' providers, and each platform the method serves must still have an example.

func Reads

func Reads(
	input any,
	want any,
	fields ...string,
) HostOption

Reads says what a read answers on the live host after a write example: the read whose input type input is, run with input, answers a row with the fields of want that fields names, or with none, each field of want that is not its zero value. Name a field to compare its zero value, such as managed for false. A list matches a list that has each of its values. The read can be the parent's, as a key's read for a user. The integration test runs it, so a write that reports changed but does nothing fails.

func ReadsNone

func ReadsNone(
	input any,
	want any,
	fields ...string,
) HostOption

ReadsNone says that after a write example no row of the read whose input type input is answers want, or the read reports the item not found: the example removed it. fields names the fields of want to compare, as for Reads.

type LiveField

type LiveField struct {
	Field string `json:"field"`
	Fact  Fact   `json:"fact"`
}

LiveField is a field of an example's input, by its JSON name, and the fact of the live target that the integration test puts in it.

type Method

type Method struct {
	// Name is the method's name: the CLI subcommand and the operation suffix.
	Name string
	// Doc says what the method does, in one line. It is the command's short
	// help, the operation's summary, and the docs page's first line.
	Doc string
	// Long is what a reader needs beyond Doc: what the method touches on the
	// host and how it behaves when run twice. It is the command's long help
	// and the body of its docs page. Optional.
	Long string
	// Verb is read or write. An action is a write.
	Verb types.Verb
	// Admin is true for a method declared with .AdminOnly: only the admin
	// role gets its permission, not write or read.
	Admin bool
	// Action is true for a write declared with Action: it is named for what
	// it does, such as restart, and its route ends in its name.
	Action bool
	// Always is true for a method declared with .Always: it changes the
	// host each time it runs, as restart does, so no run is unchanged.
	AlwaysChanges bool
	// Disruptive is true for a method declared with .Disrupts: it takes the
	// host down, as a reboot does, so its examples never run on a live host.
	Disruptive bool
	// Disruption is why, as .Disrupts gives it.
	Disruption string
	// NoReadBack is why no read shows what the method's examples change,
	// as .ReadsNothing gives it, for a write whose result is its own output,
	// such as a command's run.
	NoReadBack string
	// PermitVerb is the permission verb of an action declared with
	// .PermitAs or .Shell, such as exec: its permission is <name>:exec in
	// place of <name>:execute, which only the admin role gets. Empty for
	// each other method.
	PermitVerb types.Verb
	// NonFact is why a read runs a command outside gohai, set with
	// .NotAFact: what it reads is not a fact of the host.
	NonFact string
	// KeyField is the input field that goes in the path, by its JSON name.
	// Empty means the method addresses the whole collection.
	KeyField string
	// In and Out are the method's input and output types. An output that is a
	// slice becomes one result row per element, each with the host's name.
	In  reflect.Type
	Out reflect.Type
	// Examples are sample calls for the docs pages.
	Examples []Example
	// Refusals are calls the method fails, for the docs pages and the
	// provider's tests.
	Refusals []Refusal
	// Platforms limits the method to these of its behavior's platforms. Empty
	// means every platform the behavior declares. On any other platform the
	// method reports skipped, and its examples do not run there.
	Platforms []PlatformName
	// SudoPrograms and RunsPrograms are the programs only this method runs,
	// with and without sudo. A host needs them only where the method runs.
	SudoPrograms []string
	RunsPrograms []string
	// contains filtered or unexported fields
}

Method is one operation of a behavior.

func Action

func Action[P any, In any, Out any](
	name string,
	fn func(ctx context.Context, p P, in In) (Out, error),
) *Method

Action declares a write named for what it does to the host, such as restart or reboot, which no create, update or delete says. Its permission is <group>:execute. It is a write in each other way: a modify job, and an output that reports Changed. Its route is POST on the method's path with its name after it, /service/{name}/restart, so two actions on one item have two routes. The name is one of the CLI's actions, osapi dsl command spec get lists them.

func Read

func Read[P any, In any, Out any](
	name string,
	fn func(ctx context.Context, p P, in In) (Out, error),
) *Method

Read declares a method that reads the host.

func Write

func Write[P any, In any, Out any](
	name string,
	fn func(ctx context.Context, p P, in In) (Out, error),
) *Method

Write declares a method that changes the host. Its output type reports whether anything changed, through a Changed bool field tagged json:"changed"; dsl behavior validate fails a write without one.

func (*Method) AdminOnly

func (m *Method) AdminOnly() *Method

AdminOnly makes the method's permission one that only the admin role grants. Each method of the behavior with that verb must agree.

func (*Method) AdminRole

func (m *Method) AdminRole() bool

AdminRole reports whether only the admin role gets the method's permission: it is declared with .AdminOnly, or with .PermitAs or .Shell, whose verb only the admin role gets.

func (*Method) Always

func (m *Method) Always() *Method

Always marks a method that changes the host each time it runs: an action such as restart, or an update whose input the host cannot compare with what it has, such as the password of a user, which the controller hashes with a new salt on each call. It reports changed: true on each run, and the generated test does not run it a second time to see changed: false. dsl behavior validate refuses it on a create, a delete and a read.

func (*Method) Before

func (m *Method) Before(
	fn any,
) *Method

Before gives the method a controller step: fn runs in the generated route on the controller, before osapi queues the job, as func(ctx context.Context, in In) (In, error). It changes the input that the caller sent into the input that the agent gets, such as a password into its hash. A secret.Value field that the step leaves set goes to the job sealed to the target agents, when the controller has PKI. dsl behavior validate checks fn's signature.

func (*Method) Check

func (m *Method) Check(
	ctx context.Context,
	input []byte,
) error

Check decodes input as the method's input type and checks it against its validate tags, as the API does before it queues a job. The agent calls it before Invoke, so a job that did not come through the API, such as one published to NATS by hand, is held to the same rules.

func (*Method) Describe

func (m *Method) Describe(
	doc string,
) *Method

Describe sets the method's one-line description.

func (*Method) Disrupts

func (m *Method) Disrupts(
	why string,
) *Method

Disrupts marks a method that takes the host down, such as a reboot, and says why. Its examples run on the fake host as each example does, but the integration test never runs them on a live host, because the host would go down under the test. dsl behavior validate refuses it without a reason.

func (*Method) Example

func (m *Method) Example(
	doc string,
	input any,
	output any,
	host ...HostOption,
) *Method

Example adds a sample call for the docs pages.

func (*Method) Explain

func (m *Method) Explain(
	long string,
) *Method

Explain sets the method's longer description, for its command's help and its docs page.

func (*Method) Fails

func (m *Method) Fails(
	doc string,
	input any,
	errorText string,
	host ...HostOption,
) *Method

Fails declares a call the method fails, with text its error contains, such as a key with a slash in it or a parameter osapi does not manage. host sets up the fake host the call runs on, as for Example. The docs page lists what a method refuses, and the provider tests check each.

func (*Method) Func

func (m *Method) Func() string

Func is the name of the method's Go function, such as github.com/osapi-io/osapi/internal/behaviors/managedfile.Update.

func (*Method) HTTPMethod

func (m *Method) HTTPMethod() string

HTTPMethod is the method's HTTP verb: GET for a read, POST for an action, and for a write POST, PUT or DELETE by the method's name.

func (*Method) HasBefore

func (m *Method) HasBefore() bool

HasBefore reports whether the method has a controller step.

func (*Method) InPath

func (m *Method) InPath(
	name string,
) bool

InPath reports whether the input field name, by its JSON name, goes in the method's path.

func (*Method) Invoke

func (m *Method) Invoke(
	ctx context.Context,
	provider any,
	input []byte,
) (any, error)

Invoke decodes input as the method's input type and calls it with provider, inside the span and metrics every behavior gets (see telemetry.go). The agent calls this after Check. Invoke itself does not validate: behaviortest sends each .Fails input through it to the provider, to prove the provider refuses it too.

func (*Method) Key

func (m *Method) Key(
	field string,
) *Method

Key names the input field, by its JSON name, that is addressed in the path.

Example

Key puts an input field in the path, for a method that addresses one item.

package main

import (
	"context"
	"fmt"

	"github.com/osapi-io/osapi/internal/behavior"
)

// MotdProvider is what each platform implements for the example behavior.
type MotdProvider interface {
	Read(ctx context.Context) (string, error)
	Write(ctx context.Context, text string) (bool, error)
}

// Motd is get's output.
type Motd struct {
	Text string `json:"text" doc:"The message shown at login"`
}

// MotdUserInput addresses one user's message.
type MotdUserInput struct {
	User string `json:"user" validate:"required" doc:"The user whose message to read"`
}

func getUserMotd(
	ctx context.Context,
	p MotdProvider,
	_ MotdUserInput,
) (Motd, error) {
	text, err := p.Read(ctx)

	return Motd{Text: text}, err
}

func main() {
	b := behavior.Define("motd", "The message shown at login",
		behavior.Node,
		behavior.Read("get", getUserMotd).Key("user").Describe("Get one user's message"),
	)

	m := b.Methods[0]
	fmt.Println(m.HTTPMethod(), b.Path(m))

}
Output:
GET /api/node/{hostname}/motd/{user}

func (*Method) NotAFact

func (m *Method) NotAFact(
	why string,
) *Method

NotAFact marks a read that runs a command outside gohai, and says why: what it reads is not a fact of the host, such as the updates that the package index has, which are what the repositories have. A read of a fact goes through gohai, with h.Sources(); a fact that gohai does not read is a change to gohai first.

func (*Method) On

func (m *Method) On(
	platforms ...PlatformName,
) *Method

On limits the method to platforms, as Platform names them: a hostname read can run on every platform its behavior declares while the update runs only on debian. Elsewhere the method reports skipped.

func (*Method) PathKeys

func (m *Method) PathKeys() []string

PathKeys are the input fields that go in the method's path, by their JSON names: the parent's key for a behavior with Of, then the method's own key.

func (*Method) PermissionVerb

func (m *Method) PermissionVerb() types.Verb

PermissionVerb is the verb of the method's permission: the verb of .PermitAs, else execute for an action, else its verb.

func (*Method) PermitAs

func (m *Method) PermitAs(
	verb types.Verb,
) *Method

PermitAs makes an action's permission <name>:<verb>, in place of <name>:execute, such as docker:exec for docker exec. Thus the action does not share a permission with the other actions of its behavior. The verb is one that only the admin role gets: types.VerbShell or types.VerbExec. dsl behavior validate refuses it on a method that is not an action, and a verb that is not one of these.

func (*Method) ProviderType

func (m *Method) ProviderType() reflect.Type

ProviderType is the type the method's function takes as its provider.

func (*Method) ReadsNothing

func (m *Method) ReadsNothing(
	why string,
) *Method

ReadsNothing says why no read of the behavior shows what the write's examples change, for a write whose result is its own output, such as the output of a command that it runs. The gate takes it in place of a Reads on each example.

func (*Method) Runs

func (m *Method) Runs(
	programs ...string,
) *Method

Runs declares programs only this method runs without sudo.

func (*Method) RunsOn

func (m *Method) RunsOn(
	platform PlatformName,
) bool

RunsOn reports whether the method runs on a host whose platform is platform: every platform without On, else one On names, or any platform but darwin when On names PlatformLinux.

func (*Method) Shell

func (m *Method) Shell() *Method

Shell makes an action's permission <name>:shell, in place of <name>:execute: the action runs a shell command line. It is PermitAs(types.VerbShell).

func (*Method) SpanInputs

func (m *Method) SpanInputs() []string

SpanInputs are the input fields, by JSON name, that a call of m records on its span: the fields of its path first, then each field tagged telemetry:"attr". A secret is never one of them.

func (*Method) Sudo

func (m *Method) Sudo(
	programs ...string,
) *Method

Sudo declares programs only this method runs with sudo, such as hostnamectl for a hostname update limited with On. The behavior's Sudo is for programs every method can run.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures a behavior in Define.

var API Option = optionFunc(func(b *Behavior) { b.API = true })

API serves a behavior over REST: its routes, its part of the OpenAPI spec, and its API reference pages.

var CLI Option = optionFunc(func(b *Behavior) { b.CLI = true })

CLI gives a behavior client commands, generated into cmd/next, and CLI docs pages. It needs API, because the commands call it.

var Internal Option = optionFunc(func(b *Behavior) { b.Internal = true })

Internal marks a behavior that only other behaviors use. It gets no route, no command, no spec and no permissions; dsl behavior list and dsl behavior get still show it, with what uses it. A primitive can start internal and be exposed later by removing the option.

var KeepsState Option = optionFunc(func(b *Behavior) { b.KeepsState = true })

KeepsState declares that the behavior's providers keep a record in the file-state bucket. Each read and write of it is a kv span in a trace. The examples fail when a behavior uses the bucket without it; a behavior that requires one that keeps state gets it from there.

var Node Option = optionFunc(func(b *Behavior) { b.Placement = NodePlacement })

Node places a behavior on the hosts, through the job system.

func Area

func Area(
	name area.Name,
) Option

Area puts a served behavior in an area, one of area.All: Area(area.Hardware) puts disk under Hardware on the UI's Behaviors page, and its SDK page under Hardware. dsl behavior validate refuses a behavior with API and no area, or an area that is not one of area.All.

func Config

func Config(
	defaults any,
) Option

Config declares a behavior's own settings. defaults is a struct whose fields carry mapstructure, doc and validate tags, the same as osapi's own config, and whose field values are the defaults. The settings join osapi's config under behaviors.<name>: config list shows them, OSAPI_ environment variables and agent start flags set them, and config validate checks them. Settings are standing configuration of the agent, which runs the methods; a method's per-call values are its input, never a setting.

Example

Config declares settings. Their keys sit under behaviors.<name>, each with an agent start flag, and a method reads the decoded struct with Settings.

package main

import (
	"context"
	"fmt"

	"github.com/osapi-io/osapi/internal/behavior"
)

// MotdProvider is what each platform implements for the example behavior.
type MotdProvider interface {
	Read(ctx context.Context) (string, error)
	Write(ctx context.Context, text string) (bool, error)
}

// MotdGetInput is get's input; it has no fields.
type MotdGetInput struct{}

// Motd is get's output.
type Motd struct {
	Text string `json:"text" doc:"The message shown at login"`
}

// MotdSettings are the behavior's standing agent config.
type MotdSettings struct {
	Path string `mapstructure:"path" doc:"File the message is written to" validate:"required,startswith=/"`
}

func getMotd(
	ctx context.Context,
	p MotdProvider,
	_ MotdGetInput,
) (Motd, error) {
	text, err := p.Read(ctx)

	return Motd{Text: text}, err
}

func main() {
	b := behavior.Define("motd", "The message shown at login",
		behavior.Node,
		behavior.Config(MotdSettings{Path: "/etc/motd"}),
		behavior.Read("get", getMotd).Describe("Get the message of the day"),
	)

	fmt.Println(b.SettingsKey())
	fmt.Println("--" + b.SettingFlag("path"))

	// At startup the agent decodes the config and hands it over; a method
	// then reads it.
	b.SetSettings(MotdSettings{Path: "/etc/motd"})
	fmt.Println(behavior.Settings[MotdSettings](b).Path)

}
Output:
behaviors.motd
--motd-path
/etc/motd

func Of

func Of(
	parent *Behavior,
) Option

Of puts a behavior's items under an item of parent: Of(user.Behavior) puts sshkey at /api/node/{hostname}/user/{name}/sshkey and `osapi client node user sshkey`. Each input of the behavior has the parent's key, such as name, which goes in the path. Its permissions are the parent's, so the keys of a user need user:read and user:write.

func Platform

func Platform[H any, P any](
	name PlatformName,
	build func(h H) (P, error),
) Option

Platform declares how the behavior's provider is built on one platform, as gohai's family.Detect names it: debian, darwin and so on, or PlatformLinux for every Linux host without a provider of its own. build takes the host.Host from internal/behavior/host, which is kept out of this package so the SDK does not import what only the agent needs. The agent builds the provider for its own platform once, at startup, and hands it to every method. On a platform the behavior does not declare, or when build returns ErrUnsupported, its methods are skipped rather than failed.

The provider P must implement the provider type of every method, which osapi dsl behavior validate checks.

Example

Platform declares how the provider is built on each platform. The agent builds the one for its own platform at startup, with its settings; on any other platform the behavior's methods are skipped.

package main

import (
	"context"
	"fmt"

	"github.com/osapi-io/osapi/internal/behavior"
	"github.com/osapi-io/osapi/internal/behavior/host"
)

// MotdProvider is what each platform implements for the example behavior.
type MotdProvider interface {
	Read(ctx context.Context) (string, error)
	Write(ctx context.Context, text string) (bool, error)
}

// MotdGetInput is get's input; it has no fields.
type MotdGetInput struct{}

// Motd is get's output.
type Motd struct {
	Text string `json:"text" doc:"The message shown at login"`
}

// MotdSettings are the behavior's standing agent config.
type MotdSettings struct {
	Path string `mapstructure:"path" doc:"File the message is written to" validate:"required,startswith=/"`
}

func getMotd(
	ctx context.Context,
	p MotdProvider,
	_ MotdGetInput,
) (Motd, error) {
	text, err := p.Read(ctx)

	return Motd{Text: text}, err
}

// motdFile is the example's Linux provider: it keeps the message in a file.
type motdFile struct {
	path string
	text string
}

func (f *motdFile) Read(context.Context) (string, error) { return f.text, nil }

func (f *motdFile) Write(_ context.Context, text string) (bool, error) {
	changed := f.text != text
	f.text = text

	return changed, nil
}

func main() {
	motd := behavior.Define("motd", "The message shown at login",
		behavior.Node,
		behavior.Config(MotdSettings{Path: "/etc/motd"}),
		behavior.Platform("debian", func(h host.Host) (MotdProvider, error) {
			return &motdFile{path: host.Settings[MotdSettings](h).Path}, nil
		}),
		behavior.Sudo("tee"),
		behavior.Read("get", getMotd).Describe("Get the message of the day"),
	)
	motd.SetSettings(MotdSettings{Path: "/etc/motd"})

	// The agent puts the behavior's settings in the host it passes.
	h := host.Host{Settings: motd.CurrentSettings()}

	p, _ := motd.Provider("debian", h)
	fmt.Println(p.(*motdFile).path)

	p, _ = motd.Provider("darwin", h)
	fmt.Println(p == nil)

}
Output:
/etc/motd
true

func Requires

func Requires(
	behaviors ...*Behavior,
) Option

Requires declares the behaviors this one is built on. The agent builds each required behavior's provider before this one's and hands it to this one's builder, which reads it with host.Require; this behavior's provider then calls the required behavior's methods as Go calls, on the same host in the same job. Chaining behaviors across hosts or steps is a workflow, not a requirement.

func Runs

func Runs(
	programs ...string,
) Option

Runs declares the programs the behavior's providers run without sudo, such as ip or dpkg-query. The agent warns when one is not installed, at start or at a later heartbeat, the integration test fails when its image lacks one, and the docs page lists them. A program declared with Sudo need not be declared again. AnyProgram, "*", is each program: a behavior such as command, which runs the program its caller names, declares it, and the agent and the integration test look for none.

func RunsIfPresent

func RunsIfPresent(
	programs ...string,
) Option

RunsIfPresent declares the programs the behavior's providers run only when the host has them, such as zfs: a provider that does not find one reads without it. The fake host permits them, and the agent and the integration test do not require them.

func RunsOnPlatform

func RunsOnPlatform(
	platform PlatformName,
	programs ...string,
) Option

RunsOnPlatform declares the programs the behavior's providers run without sudo on platform only. linux is each platform that is not darwin. Thus the agent and the integration test of a Linux host do not look for a program that only macOS has.

func Sudo

func Sudo(
	programs ...string,
) Option

Sudo declares the programs the behavior's providers run with sudo. The agent's preflight checks it may run each one, and the behavior's docs page lists them.

func SudoOnPlatform

func SudoOnPlatform(
	platform PlatformName,
	programs ...string,
) Option

SudoOnPlatform declares the programs that the provider declared for platform runs with sudo, such as update-ca-certificates on debian and update-ca-trust on linux. They hold on each host that this provider serves: linux holds on a Debian host only when the behavior declares no provider for debian. Thus the agent and the integration test do not ask a host for a program that its provider does not run.

func Title

func Title(
	title string,
) Option

Title gives a behavior the title that a person reads, such as "Package updates" for updates, when its capitalized name does not read well: an initialism such as DNS, two words such as Container image, or the parent of a child, such as User SSH key.

func Under

func Under(
	parent *Behavior,
) Option

Under puts a behavior under the collection of parent, with no key of the parent: Under(log.Behavior) puts source at /api/node/{hostname}/log/source and `osapi client node log source`. Its permissions are the parent's, so the sources of the log need log:read. Use it for a child of a parent whose items have no key, or that is about the whole collection, as the updates of the packages are. Of puts a child under an item of the parent.

Example

Under puts a behavior under the collection of a parent, with no key of the parent. Its permission is the parent's.

package main

import (
	"context"
	"fmt"

	"github.com/osapi-io/osapi/internal/behavior"
)

// MotdProvider is what each platform implements for the example behavior.
type MotdProvider interface {
	Read(ctx context.Context) (string, error)
	Write(ctx context.Context, text string) (bool, error)
}

// MotdGetInput is get's input; it has no fields.
type MotdGetInput struct{}

// Motd is get's output.
type Motd struct {
	Text string `json:"text" doc:"The message shown at login"`
}

func getMotd(
	ctx context.Context,
	p MotdProvider,
	_ MotdGetInput,
) (Motd, error) {
	text, err := p.Read(ctx)

	return Motd{Text: text}, err
}

func main() {
	log := behavior.Define("log", "The entries of the journal",
		behavior.Node,
		behavior.Read("list", getMotd).Describe("List the entries"),
	)
	source := behavior.Define("source", "The sources of the journal",
		behavior.Node,
		behavior.Under(log),
		behavior.Read("list", getMotd).Describe("List the sources"),
	)

	m := source.Methods[0]
	fmt.Println(source.Path(m), source.Permission(m.PermissionVerb()))

}
Output:
/api/node/{hostname}/log/source log:read

func Validator

func Validator(
	tag string,
	check func(value string) bool,
	schema func(t rule.Target),
	message string,
) Option

Validator declares a validate tag for the behavior's input fields, so a behavior that needs its own rule keeps it in its own directory. The server checks it before a job is queued, the spec carries schema, and a value that fails reads "<value> <message>". The tag is usable by any behavior once declared.

func Writes

func Writes(
	paths ...string,
) Option

Writes declares the paths the behavior's providers write, remove or change the mode of, as path.Match patterns such as "/etc/sysctl.d/osapi-*.conf". "*" is any path: a behavior such as managedfile, which writes the path its caller names, declares it, and each behavior that requires it declares its own paths. The examples fail on a path that is not declared, and the docs page and dsl behavior get list them. Each such call is a file span in a trace.

type Placement

type Placement string

Placement says where a behavior's work happens.

const NodePlacement Placement = "node"

NodePlacement is the only placement: the work runs on a host, through the job system. What the controller answers itself is not a behavior.

type PlatformName

type PlatformName string

PlatformName is a platform that a behavior can name: PlatformLinux, or a platform as gohai's family.Detect names it. Use a constant: behavior validate fails on a name that is not one of KnownPlatforms, because a host never reports it and the declaration would never apply.

const (
	// PlatformLinux is any Linux host: the provider for a host whose own
	// platform the behavior does not declare, unless it is macOS. A behavior
	// that works the same on every distribution, such as one reading /proc,
	// declares it once.
	PlatformLinux PlatformName = "linux"
	// PlatformDarwin is macOS.
	PlatformDarwin PlatformName = family.Darwin
	// PlatformDebian is the Debian family, as gohai names it: Debian,
	// Ubuntu, Raspbian, Linux Mint and the others of Ohai's table.
	PlatformDebian PlatformName = family.Debian
	// PlatformSUSE is the SUSE family, as gohai names it: openSUSE, SLES,
	// SLED and SLE Micro.
	PlatformSUSE PlatformName = family.SUSE
)

The platforms a behavior can name.

func KnownPlatforms

func KnownPlatforms() []PlatformName

KnownPlatforms are the platforms that a behavior can name. Add a constant here before a behavior names a new family of gohai.

type PlatformPrograms

type PlatformPrograms struct {
	Platform PlatformName
	Programs []string
}

PlatformPrograms are the programs that a behavior runs on one platform only, such as vm_stat on darwin.

type PlatformProvider

type PlatformProvider struct {
	// Name is the platform, as gohai's family.Detect names it.
	Name PlatformName
	// Type is the provider type the builder returns.
	Type reflect.Type
	// contains filtered or unexported fields
}

PlatformProvider is how a behavior's provider is built on one platform.

type Problem

type Problem struct {
	Behavior string `json:"behavior"`
	Method   string `json:"method,omitempty"`
	Rule     string `json:"rule"`
	Message  string `json:"message"`
	// Fix is how to fix it, from the check of Rule.
	Fix string `json:"fix" table:"-"`
}

Problem is one rule a behavior breaks.

func ChainProblems

func ChainProblems() []Problem

ChainProblems are the problems of the chain rules that hold when the behaviors are built: RuleRequires and RuleInternal.

func Validate

func Validate() []Problem

Validate checks every registered behavior against the rules the platform relies on, and returns what each breaks. No problems means every route, command and schema can be built.

func ValidateBehavior

func ValidateBehavior(
	b *Behavior,
) []Problem

ValidateBehavior checks one behavior.

Example

ValidateBehavior reports what a definition gets wrong, as osapi dsl behavior validate does for every registered one.

package main

import (
	"context"
	"fmt"

	"github.com/osapi-io/osapi/internal/behavior"
)

// MotdProvider is what each platform implements for the example behavior.
type MotdProvider interface {
	Read(ctx context.Context) (string, error)
	Write(ctx context.Context, text string) (bool, error)
}

// MotdGetInput is get's input; it has no fields.
type MotdGetInput struct{}

// Motd is get's output.
type Motd struct {
	Text string `json:"text" doc:"The message shown at login"`
}

func getMotd(
	ctx context.Context,
	p MotdProvider,
	_ MotdGetInput,
) (Motd, error) {
	text, err := p.Read(ctx)

	return Motd{Text: text}, err
}

func main() {
	b := behavior.Define("motd", "The message shown at login",
		behavior.Node,
		behavior.Read("get", getMotd),
	)

	for _, p := range behavior.ValidateBehavior(b) {
		fmt.Println(p.Rule)
	}

}
Output:
platform
doc

type ReadBack

type ReadBack struct {
	// Input is a value of the read's input type.
	Input any `json:"input"`
	// Want is a value of the read's output type, or of its element for a
	// read that answers a list.
	Want any `json:"want"`
	// Fields are the JSON names of the fields of Want to compare. With
	// none, each field of Want that is not its zero value.
	Fields []string `json:"fields,omitempty"`
	// None is a read that no row of answers Want: the item is gone, or the
	// read reports that it is not found.
	None bool `json:"none,omitempty"`
}

ReadBack is a read of the behavior, or of its parent, that shows what a write example changed: the read whose input type Input is, run with Input, and the fields of Want that it must answer. With None, no row answers them: the example removed the item.

type Refusal

type Refusal struct {
	Example
	// Error is text the error contains.
	Error string `json:"error"`
}

Refusal is a call a method fails: an input it rejects, or a host it cannot act on. The provider tests run it on a fake host set up as Given says and check the error contains Error.

type Schema

type Schema struct {
	Type        string             `json:"type,omitempty"`
	Description string             `json:"description,omitempty"`
	Properties  map[string]*Schema `json:"properties,omitempty"`
	// Order is the order the properties were declared in, for rendering.
	Order                []string `json:"-"`
	Required             []string `json:"required,omitempty"`
	Items                *Schema  `json:"items,omitempty"`
	AdditionalProperties *Schema  `json:"additionalProperties,omitempty"`
	Enum                 []string `json:"enum,omitempty"`
	Pattern              string   `json:"pattern,omitempty"`
	Format               string   `json:"format,omitempty"`
	MinLength            *int     `json:"minLength,omitempty"`
	MaxLength            *int     `json:"maxLength,omitempty"`
	Minimum              *float64 `json:"minimum,omitempty"`
	Maximum              *float64 `json:"maximum,omitempty"`
	MinItems             *int     `json:"minItems,omitempty"`
	MaxItems             *int     `json:"maxItems,omitempty"`
	// WriteOnly marks a value a client sends and is never shown back, such as
	// a secret.
	WriteOnly bool `json:"writeOnly,omitempty"`
	// Secret marks a secret.Value: a reference, secret://<vault>/<key>, or
	// the value.
	Secret bool `json:"x-osapi-secret,omitempty"`
	// Validate is the field's whole validate tag, which the spec carries in
	// rule.Extension.
	Validate string `json:"-"`
}

Schema is a JSON Schema for one type, as much of the draft as osapi's inputs and outputs use.

func SchemaFor

func SchemaFor(
	t reflect.Type,
) (*Schema, error)

SchemaFor builds the JSON Schema for t from its struct tags: json names the field, doc describes it, and validate gives its constraints. A struct that holds itself, such as a step whose steps are steps, is expanded one time: inside itself it is an object that names its type.

type Step

type Step struct {
	Behavior string  `json:"behavior"`
	Method   string  `json:"method"`
	Input    any     `json:"input,omitempty"`
	Output   any     `json:"output,omitempty"`
	Error    string  `json:"error,omitempty"`
	Steps    []*Step `json:"steps,omitempty"`
	// Duration is how long the call ran. It is left out of the JSON of a
	// test, which compares the same chain run after run.
	Duration time.Duration `json:"-"`
	// contains filtered or unexported fields
}

A Step is one call of a method in a chain, with the calls it made. The examples record them: Record gives a context, and each Call under it adds its step, so osapi dsl chain get shows what each call sent and got.

func NewStep

func NewStep(
	behavior string,
	method string,
	in any,
) *Step

NewStep is the step of a call of method of the behavior with in: the root of a chain, which each Call under it adds its step to.

func (*Step) Wire

func (s *Step) Wire() []types.Step

Wire are the calls that s made, as a job's response carries them: each step's behavior, method, whether it changed the host, its error and its duration. The input and the output stay out: an output is not redacted, and the content of a managed file can be large. The job's request and response have the input and the output of the method at the top.

type TemplateData

type TemplateData struct {
	// Facts are the facts of the agent that renders the template, by their
	// JSON names, such as architecture.
	Facts map[string]any
	// Vars are the values that the request gives, from the field that the
	// template tag names.
	Vars map[string]string
	// Hostname is the hostname of the agent.
	Hostname string
}

TemplateData is what a template that a behavior renders can read. A field tagged template:"<vars>" holds such a template, and the input field named <vars> holds its .Vars.

type TemplateField

type TemplateField struct {
	// Field is the template's field, by its JSON name.
	Field string
	// Vars is the field of the vars, by its JSON name.
	Vars string
	// contains filtered or unexported fields
}

TemplateField is an input field that holds a template, and the field that holds its vars.

func TemplateFields

func TemplateFields(
	t reflect.Type,
) []TemplateField

TemplateFields are the fields of t tagged template:"<vars>".

Directories

Path Synopsis
Package behaviortest runs a behavior's examples and refusals against a fake host, so a behavior's provider is tested from its definition.
Package behaviortest runs a behavior's examples and refusals against a fake host, so a behavior's provider is tested from its definition.
Package collectors lists gohai's collectors in the behavior spec, from gohai's own description of them (gohai.Collectors).
Package collectors lists gohai's collectors in the behavior spec, from gohai's own description of them (gohai.Collectors).
Package command holds what the generated behavior commands share: flags derived from an input type's tags, and the one table layout every behavior's output renders in, driven by its output type's tags.
Package command holds what the generated behavior commands share: flags derived from an input type's tags, and the one table layout every behavior's output renders in, driven by its output type's tags.
commandtest
Package commandtest runs a behavior's generated commands for the gen/cli_public_test.go each one gets, with the SDK call faked.
Package commandtest runs a behavior's generated commands for the gen/cli_public_test.go each one gets, with the SDK call faked.
Package dispatch runs a behavior's method for the endpoint layer: it sends the job to the host, or to each host, that the target names, and makes the answer of each host a result row.
Package dispatch runs a behavior's method for the endpoint layer: it sends the job to the host, or to each host, that the target names, and makes the answer of each host a result row.
servertest
Package servertest runs the HTTP cases each behavior's generated gen/api_<method>_public_test.go lists.
Package servertest runs the HTTP cases each behavior's generated gen/api_<method>_public_test.go lists.
gen
Command gen writes the files built from behaviors.
Command gen writes the files built from behaviors.
group command
Command group writes what the endpoint layer makes from each behavior's endpoint group: its spec, routes, decoders and commands.
Command group writes what the endpoint layer makes from each behavior's endpoint group: its spec, routes, decoders and commands.
Package host is what the agent hands a behavior's provider builder: the platform it runs on and the shared things a provider reaches the host through.
Package host is what the agent hands a behavior's provider builder: the platform it runs on and the shared things a provider reaches the host through.
mocks
Package mocks provides mock implementations for testing.
Package mocks provides mock implementations for testing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL