Documentation
¶
Overview ¶
Package engine executes dtctl command lines in-process for services.
It is the embedding surface described in docs/dev/SERVICE_ENGINE_DESIGN.md: a caller hands over a command string exactly as a user would type it locally, plus the tenant to run it against (environment URL + token) and an optional set of virtual files, and gets back the exact byte streams the CLI would have printed, the exit code, and the final state of the virtual files.
res, err := engine.Execute(ctx, engine.Request{
Command: `apply -f workflow.yaml --write-id --agent`,
EnvironmentURL: "https://abc12345.apps.dynatrace.com",
Token: tenantToken,
Files: map[string][]byte{"workflow.yaml": src},
})
// res.Stdout is byte-identical to local CLI output;
// res.Files["workflow.yaml"] now carries the stamped id.
Every execution is fully isolated from the host process:
- Credentials come only from the request. The host's config file, contexts, keyring, and credential environment variables are scrubbed for the duration of the run (cmd.Session).
- File arguments (-f and friends, including writebacks like `apply --write-id`) resolve against the request's virtual filesystem, never the host disk (pkg/vfs).
- No subprocesses: plugins, shell aliases, apply hooks, editors, and browser opens are all disabled (cmd.Capabilities zero value).
- Host-only commands (config, ctx, auth, ...) are removed from the surface entirely — hidden from `dtctl commands` and help, and guarded with the stable agent-mode error code "unsupported_in_service".
Analysis without running: Parse reports what a command line means — its verb and resource, the files it reads and writes, whether it reads the request's input, and its required scopes with how certain they are — without running it. It needs no token, reads no file, calls no platform API and takes no execution slot, and it applies the same surface and validation as Execute, so a command line Execute would refuse is a *UsageError carrying Execute's error. A host uses it as a preflight, to know which files to attach before it runs a command. Parse is experimental until a second host uses it.
p, err := engine.Parse(ctx, engine.ParseRequest{Command: `apply -f workflow.yaml --write-id`})
// p.InputFiles and p.OutputFiles are ["workflow.yaml"];
// p.Scopes is ScopesInputDependent: the file decides the resource kind.
Concurrency: Execute is safe to call from multiple goroutines, but by default executions serialize on an internal lock (the command tree is process state — see cmd.Run). A service scales by running more engine processes or instances, or opts in on an Engine built with New(limits, WithConcurrentExecution(n)), which runs up to n invocations at once in this process, each on a command tree and state of its own; see docs/dev/CONCURRENT_EXECUTION.md for what that guarantees and costs. Giving every request a WASM instance instead costs about 55ms of CPU to start each one.
Transport: by default every invocation reaches its environment through one process-wide connection pool. An Engine built with New(limits, WithTransport(rt)) sends its invocations' platform requests through rt instead — how a host tests against a stand-in environment (an httptest.Server's URL as EnvironmentURL, its Client().Transport as rt) or gives the engine a TLS configuration of its own. Only the transport changes; credentials, safety and output are what they would be against a real environment.
Request headers: an Engine built with New(limits, WithHeaderPolicy(policy)) lets the host refuse headers a caller passes to `exec api -H` (Host, the X-Forwarded-* family, ...). Which headers matter is the host's decision; without the option only the credential headers are refused.
Admission and resource limits: ExecuteWithLimits (which Execute calls with DefaultLimits) bounds how many requests may queue for an execution slot (MaxQueued, ErrTooManyQueued once exceeded), how long a request may occupy it (MaxDuration, applied as a context.WithTimeout threaded into the command tree via RunOptions.Context), and how much stdout/stderr a command may produce (MaxOutputBytes; excess is dropped and Result.Truncated is set). A zero-value Limits field falls back to DefaultLimits. The package-level functions share one slot; an Engine has slots and a queue of its own.
Cancellation: the context gates the start of an execution (a request cancelled while queued never runs). Once running, a command that observes cmd.Context() (most of the command tree does — see cmd/run.go) is cancelled cooperatively when the caller's context or MaxDuration budget is done. A command that never checks its context, or issues a request with a context of its own, still runs to completion; cmd/query.go's DQL execution is the one tracked exception (see its own comments). Streaming commands (--watch, --follow, query --live) are refused outright in service mode via the LongRunningStreams capability, so they cannot hold the slot indefinitely in the first place.
Index ¶
- Variables
- func UnsupportedCommands() map[string]string
- type Engine
- func (e *Engine) Execute(ctx context.Context, req Request) (*Result, error)
- func (e *Engine) ExecuteWithLimits(ctx context.Context, req Request, limits Limits) (*Result, error)
- func (e *Engine) Limits() Limits
- func (e *Engine) MaxConcurrent() int
- func (e *Engine) Parse(ctx context.Context, req ParseRequest) (*Parsed, error)
- type Limits
- type Option
- type ParseRequest
- type Parsed
- type ParsedFlag
- type Request
- type Result
- type ScopeRequirement
- type UsageError
Constants ¶
This section is empty.
Variables ¶
var ErrTooManyQueued = errors.New("engine: too many queued requests")
ErrTooManyQueued is returned by Execute/ExecuteWithLimits when admission control sheds a request because MaxQueued is already at capacity. Callers that expose the engine over a transport (e.g. pkg/serve) should map this to a "server busy" status (HTTP 503) rather than a client error, and a caller this happens to may retry with backoff.
Functions ¶
func UnsupportedCommands ¶
UnsupportedCommands returns the top-level commands the engine blocks, keyed by command name with the human-readable reason as value. The map is a copy; the policy itself is fixed.
Types ¶
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine executes commands against its own admission budget.
By default an Engine runs one invocation at a time, exactly like the package-level Execute. Built with WithConcurrentExecution, it runs several invocations at once in this process, each on a command tree of its own (cmd.RunOptions.Concurrent) — see docs/dev/CONCURRENT_EXECUTION.md for what that costs and what it guarantees. The zero value is not usable; build one with New.
func New ¶
New builds an Engine with the given budget. Without WithConcurrentExecution it serializes, exactly like the package-level Execute, but with an admission queue of its own.
func (*Engine) Execute ¶
Execute runs one invocation against this engine's budget. Its Result and error read as the package-level Execute documents.
func (*Engine) ExecuteWithLimits ¶
func (e *Engine) ExecuteWithLimits(ctx context.Context, req Request, limits Limits) (*Result, error)
ExecuteWithLimits runs one invocation against this engine's admission budget but with per-request limits. It is how a caller applies the deadline the request asked for — Limits.MaxDuration becomes the context timeout — without building a new Engine (and a new slot) per request. A zero field in limits is filled from the engine's own budget, not from DefaultLimits, so a host that sized MaxOutputBytes at construction keeps it on a request that only names a MaxDuration. The context is the invocation's only deadline: a concurrent invocation carries it on every outgoing request, and nothing preempts code between requests. A concurrent invocation the deadline cut off returns its Result together with the context's error (see Execute).
func (*Engine) MaxConcurrent ¶
MaxConcurrent reports how many invocations this engine runs at once: 1 unless it was built with WithConcurrentExecution.
func (*Engine) Parse ¶
Parse analyses a command line with the rules the package-level Parse applies. It takes no execution slot: it does no I/O, and a host must not see a parse refused because slow executions hold every slot. On an Engine built without WithConcurrentExecution it still waits for a running Execute, as the package-level Parse documents. It refuses the headers the Engine's WithHeaderPolicy refuses.
type Limits ¶
type Limits struct {
// MaxQueued bounds how many requests may be waiting for or holding an
// execution slot at once. Exceeding it returns ErrTooManyQueued. An Engine
// built with WithConcurrentExecution(n) has n slots, and raises MaxQueued
// to n if it is lower.
MaxQueued int
// MaxDuration bounds the whole request (queue wait + execution): it is
// applied as a context.WithTimeout threaded into the command tree via
// RunOptions.Context. Cancellation is cooperative — see the package
// doc's "Cancellation" section for which commands actually observe it.
MaxDuration time.Duration
// MaxOutputBytes caps stdout and stderr independently (so the real
// combined worst case is 2x this value); excess bytes are dropped and
// Result.Truncated is set.
MaxOutputBytes int64
// MaxFileBytes caps the total size of Request.Files (summed) rejected
// up front, before admission control, with no queue slot consumed. It
// does NOT bound growth of the virtual filesystem during execution — a
// command that writes a large file back (e.g. apply --write-id) is not
// capped by this field today.
MaxFileBytes int64
}
Limits controls resource budgets for a single engine execution.
func DefaultLimits ¶
func DefaultLimits() Limits
DefaultLimits returns conservative defaults for production use.
type Option ¶
type Option func(*engineOptions)
Option configures an Engine at construction.
func WithConcurrentExecution ¶
WithConcurrentExecution opts an Engine into running up to maxConcurrent invocations at once in this process (a value below 1 counts as 1). It is the only way in: no Limits field and no default turns it on, so the CLI, `dtctl serve`, the package-level Execute and every Engine built without it keep running one invocation at a time. Meant for a multi-tenant service that has sized its memory for it.
func WithHeaderPolicy ¶
WithHeaderPolicy lets the host refuse request headers a caller passes to `exec api -H`. policy receives the normalized header name (canonicalized, "_" folded to "-", so x_forwarded_for arrives as X-Forwarded-For) and returns why it is refused, or "" to allow it. Without it, only the CLI's own refusals (Authorization, Proxy-Authorization) apply.
Which headers matter is the host's decision, not dtctl's: it depends on where the host runs and what the proxies in front of its upstream trust (Host, Forwarded, X-Forwarded-*, a reserved prefix, ...). A refusal is returned before any request is sent and before --dry-run prints one, with the stable agent-mode error code "header_refused" and exit code 2, and Engine.Parse refuses the same command line. The header sent on the wire is the caller's spelling, not the normalized one. policy is shared by every invocation of the Engine and must be safe for concurrent use.
func WithTransport ¶
func WithTransport(rt http.RoundTripper) Option
WithTransport sends every platform request of this Engine's invocations through rt instead of the process-wide connection pool. It is the seam a host uses to run requests against a stand-in environment — typically an httptest.Server, passing its URL as Request.EnvironmentURL and srv.Client().Transport here, which also trusts the server's TLS certificate — or to give the engine a TLS configuration of its own (an *http.Transport with TLSClientConfig set).
Only the transport changes: the request still names the environment and carries the token, the safety level and the command surface, and dtctl still adds its User-Agent, retries and request-path checks above rt, so the Result is what the same command line would produce against a real environment. rt is shared by every invocation of the Engine and must be safe for concurrent use. nil keeps the default pool.
type ParseRequest ¶
type ParseRequest struct {
Command string // as Request.Command
Argv []string // as Request.Argv; takes precedence over Command
SafetyLevel string
Profile string
MinStability string
StabilityExceptions []string
NoDeprecated bool
// Env is as Request.Env: Profile, when set, overrides an entry for
// DTCTL_PROFILE.
Env map[string]string
}
ParseRequest is one command line to analyse. Each field means what it means on Request, so a host that restricts Execute gets the same answer from Parse. It has no EnvironmentURL or Token: Parse needs neither, and requiring them would make a host mint a credential for a call that uses none.
Experimental: Parse and its types may change until a second host uses them.
type Parsed ¶
type Parsed struct {
Verb string // "get", "apply", "exec", ...
Resource string // "" when the verb takes none (apply)
// InputFiles and OutputFiles are the files the command reads and writes,
// named the way Request.Files and Result.Files name them (vfs.Key), sorted,
// de-duplicated and never nil. The stdin values ("-", "@-") are never a path, but
// ./- is a file named "-" and is reported as one.
InputFiles []string
OutputFiles []string
// RequiresInput is true when the command may read Request.Stdin: a "-"
// file argument, "-d @-", a command such as query given no argument and no
// file, or a command that asks for confirmation (delete, restore) and was
// given neither its skip flag (--yes, --force) nor --plain or --agent.
// --dry-run skips the question too, except on delete breakpoint and delete
// scheduling-rule, which ask before their dry run returns. Without an
// answer on Stdin that command cancels itself and exits 0, so a host that
// cannot supply one should pass the skip flag. It is false under
// --check-scopes, which does not run the command.
RequiresInput bool
// RequiredScopes are the token scopes the command needs, complete when
// Scopes is ScopesKnown, and never nil.
RequiredScopes []string
Scopes ScopeRequirement
// Help is true when the command line asks for help text (--help) or names
// a group that only prints its usage. Nothing would run: Verb and Resource
// name the command whose help it is, and a host building policy from them
// should not read them as a command to run.
Help bool
// Flags are the flags the command line set, by long name (-o is
// "output"), sorted by name. A repeatable flag has one entry per item, in
// the order given, and a comma-separated slice value is split into its
// items (--collections a,b is two entries); a flag left at its default is
// not listed. Args are the positional arguments the command receives, in
// order. Both are never nil, and empty for Help.
Flags []ParsedFlag
Args []string
}
Parsed is what a command line means, without running it.
Experimental, as Parse.
func Parse ¶
func Parse(ctx context.Context, req ParseRequest) (*Parsed, error)
Parse analyses a command line the way Execute would run it, and stops before the command runs. It reads no file, calls no platform API and needs no token.
Parse and Execute use the same command tree, the same surface masks (profile, blocked commands, stability floor, deprecation) and the same validation, so a command line Execute would refuse returns a *UsageError carrying Execute's error. Validation that runs inside a command body is seen by Execute only: a nil error means the command line is well-formed, not that Execute will accept it. Any other error is an engine fault.
Safe to call concurrently. It does not count toward any Engine's admission budget. It shares the invocation lock with Execute, though: while a serialized Execute runs (an Engine built without WithConcurrentExecution, or the package-level Execute), Parse waits for it to finish, and ctx bounds the wait.
Experimental: Parse and its types may change until a second host uses them.
type ParsedFlag ¶
ParsedFlag is one flag value a command line set, as the command reads it: a boolean is "true" or "false", a count its number.
Experimental, as Parse.
type Request ¶
type Request struct {
// Command is the command line exactly as a user would type it after
// "dtctl", e.g. `get workflows -o json`. It is split into arguments with
// POSIX shell rules (quotes and escapes honored; no variable expansion,
// globbing, pipes, or redirection — dtctl is not a shell). Ignored when
// Argv is set.
Command string
// Argv is the pre-split argument vector (os.Args[1:] shape). Callers that
// already have discrete arguments should prefer it over Command — no
// quoting round-trip. Takes precedence over Command.
Argv []string
// EnvironmentURL is the Dynatrace environment to run against
// (e.g. https://abc12345.apps.dynatrace.com). Required.
EnvironmentURL string
// Token authenticates every API call of this request. Required.
Token string
// SafetyLevel bounds mutating operations for this request
// (readonly | readwrite-mine | readwrite-all | dangerously-unrestricted).
// Empty selects the dtctl default (readwrite-all).
SafetyLevel string
// Profile selects a built-in command profile (e.g. "query") that reduces
// the visible command surface for this request. Empty is the full
// (service-supported) surface.
Profile string
// MinStability is the stability floor for this request: the weakest
// contract a command or flag may offer and still be reachable
// (stable | experimental). `development` is rejected — that tier is gated
// at registration, a stage earlier than the floor, and a request has no
// opt-in for it.
//
// Empty selects cmd.SessionDefaultMinStability — `stable`. That is
// stricter than the interactive CLI's default, and deliberately so: a
// request is unattended automation, nobody reads the `[Experimental]`
// badge on its behalf, and an experimental command's shape can change
// under a caller that pinned no dtctl version. Ask for `experimental`
// explicitly when the host is prepared to re-test on upgrade.
MinStability string
// StabilityExceptions admit individual below-floor commands and flags,
// each written as a command path optionally suffixed with one flag
// ("get breakpoints", "query --decode-snapshots"). Naming a command also
// admits the flags that are below the floor only because that command is;
// a flag with a weaker contract of its own needs its own entry.
//
// Prefer this to lowering MinStability: it keeps the request's widened
// surface to what the host has actually tested, instead of also picking up
// whatever lands in the experimental tier in the next release. Unlike the
// floor, there is no environment variable for exceptions — this field is
// the only way to express them in engine mode.
StabilityExceptions []string
// NoDeprecated makes this request refuse every deprecated command and
// flag, as if the removal release had already happened — so a host can
// find out in its own test suite that it still depends on something
// scheduled to go, rather than on the day it is removed.
//
// Not a stability level: a deprecated command is stable in shape and
// satisfies any floor, it merely has a removal date. Off by default.
NoDeprecated bool
// Files is the request's virtual filesystem: every file argument
// (`-f x.yaml`, `--data-file`, ...) resolves against it, and files the
// command writes (e.g. `apply --write-id` stamping an id back into the
// source) land in it. Paths are normalized, so "x.yaml", "./x.yaml" and
// "/x.yaml" are the same file. nil is an empty filesystem — not the host
// disk: a user-named path resolves here or not at all, which the
// TestUserFilePathsGoThroughVFS guard enforces across cmd/ and pkg/.
// (Host state dtctl owns — a temp file, a cache — is a separate matter;
// the commands that use it are blocked or ungranted in a service.)
Files map[string][]byte
// Stdin feeds commands that read standard input (`-f -`). nil is an empty
// stream (immediate EOF) — never the host process's stdin.
Stdin []byte
// Env sets additional environment variables for the run (e.g.
// DTCTL_OUTPUT). Applied after credential scrubbing, so entries here win;
// grant with care — the engine deliberately does not expose this in its
// HTTP reference wrapper. Profile, when set, overrides an Env entry for
// DTCTL_PROFILE.
Env map[string]string
}
Request is one dtctl invocation for one tenant.
type Result ¶
type Result struct {
// ExitCode is the CLI process exit code: 0 success, 1 error, 2 usage,
// 3 not authenticated, 4 not found, 5 permission (pkg/client/errors.go).
ExitCode int
Stdout []byte
Stderr []byte
// Files is the complete final state of the request's virtual filesystem:
// the input files plus anything the command wrote or rewrote.
Files map[string][]byte
// Truncated is true when stdout or stderr was cut at MaxOutputBytes.
// The output is still valid up to the cap; callers should surface this
// so users know the result is incomplete.
Truncated bool
}
Result is the outcome of one execution. Stdout and Stderr are byte-identical to what the dtctl CLI would print for the same command line, credentials, and files — including --agent envelopes, table layouts, and error messages.
func Execute ¶
Execute runs one dtctl invocation and returns its outcome.
A non-nil error with a nil Result means the request never ran: it is malformed (no command, missing tenant credentials, an unparsable command string), was shed at admission, or its context ended before it started. Everything after the run starts — including command failures — is expressed CLI-style in Result: exit code plus stdout/stderr. The one exception is an Engine built with WithConcurrentExecution whose context ended while the command ran: it returns the Result as produced together with the context's error, whatever the exit code (a cancelled query exits 0).
func ExecuteWithLimits ¶
ExecuteWithLimits runs one dtctl invocation with explicit resource budgets. The limits govern queue depth, duration (via context timeout on the command tree), and stdout/stderr size (via capped buffers).
A zero value in any field is filled from DefaultLimits rather than taken literally: a caller that only cares about, say, MaxOutputBytes and leaves the rest at Go's zero value would otherwise get MaxQueued=0 (every request rejected as "too many queued") and MaxDuration=0 (every request cancelled before it starts). There is currently no way to make a budget unbounded; pass DefaultLimits()'s own (generous) values back if a caller needs to widen just one field.
type ScopeRequirement ¶
type ScopeRequirement string
ScopeRequirement says how certain Parsed.RequiredScopes is.
const ( // ScopesNone: the catalog names no scopes for the command. For a local // command (ctx, commands) that is the answer; for a command the catalog is // still missing scopes for, it under-reports. ScopesNone ScopeRequirement = "none" // ScopesKnown: RequiredScopes is the command's requirement. ScopesKnown ScopeRequirement = "known" // ScopesPerCall: the scopes are decided by the call (exec api), and // resolving them needs the environment's API specification. ScopesPerCall ScopeRequirement = "per_call" // ScopesInputDependent: the scopes are decided by the input file's // content (apply), which Parse does not read. ScopesInputDependent ScopeRequirement = "input_dependent" )
type UsageError ¶
UsageError is a command line that Execute would refuse before running the command. ExitCode is the exit code Execute returns for it (2 for a usage error). Code, Message and Suggestions classify the refusal the way the --agent envelope does, and are what Execute prints there for an error in the command line itself (an unknown flag, a missing argument). A refusal of the surface (profile, stability floor, blocked command) is printed by Execute as plain text even under --agent, so for those Code is Parse's classification and not text Execute outputs.
func (*UsageError) Error ¶
func (e *UsageError) Error() string