Documentation
¶
Index ¶
- Constants
- func AddCommand(c *cobra.Command)
- func AddDevelopmentCommand(c *cobra.Command, feature string)
- func CheckSafety(cfg *config.Config, op safety.Operation, ownership safety.ResourceOwnership) error
- func DevelopmentFeatureEnabled(feature string) bool
- func Execute()
- func GetAgentMode() bool
- func GetChunkSize() int64
- func GetPlainMode() bool
- func LoadConfig() (*config.Config, error)
- func NewClientFromConfig(cfg *config.Config) (*client.Client, error)
- func NewDQLExecutorFromConfig(cfg *config.Config, c *client.Client) *exec.DQLExecutor
- func NewPrinter() output.Printer
- func NewSafetyChecker(cfg *config.Config) (*safety.Checker, error)
- func Run(argv []string, opts RunOptions) (code int)
- func RunActive() bool
- func Setup() (*config.Config, *client.Client, output.Printer, error)
- func SetupAccount() (*httpclient.Client, string, error)
- func SetupAccountWithSafety(op safety.Operation) (*httpclient.Client, string, error)
- func SetupClient() (*config.Config, *client.Client, error)
- func SetupWithSafety(op safety.Operation) (*config.Config, *client.Client, error)
- func SetupWithSafetyAndPrinter(op safety.Operation) (*config.Config, *client.Client, output.Printer, error)
- func StabilityLint() []error
- func StabilityManifest() string
- func StabilitySinceVersions() map[string][]string
- func StabilityUndeclaredCommands() []string
- type Capabilities
- type CapabilityError
- type ContextListItem
- type DeprecatedError
- type DevelopmentError
- type DocumentTypeCount
- type HeaderRefusedError
- type ParseError
- type ParseOptions
- type ParseResult
- type ParsedFlag
- type ProfileError
- type RunOptions
- type ScopeCheckResult
- type ScopeError
- type Session
- type SessionStatus
- type StabilityError
- type UnsupportedCommandError
- type WhoamiResult
Constants ¶
const ( ExitCodeNoDiff = 0 ExitCodeHasDiff = 1 ExitCodeError = 2 )
const SessionDefaultMinStability = config.StabilityStable
SessionDefaultMinStability is the floor a session-backed invocation gets when it names none. See Session.MinStability for why it is stricter than the CLI default.
Variables ¶
This section is empty.
Functions ¶
func AddCommand ¶
AddCommand registers an additional top-level command on the dtctl root. It exists for commands that live outside this package because they import packages that themselves import cmd — registering from here would be an import cycle. `dtctl serve` (pkg/serve, wired in main) is the canonical case. Call before the first Execute/Run.
func AddDevelopmentCommand ¶
AddDevelopmentCommand registers a top-level development-tier command. It is the gated counterpart of AddCommand and exists for the same reason: commands that live outside this package because they import packages that import cmd. `dtctl serve` (pkg/serve, wired in main) is the canonical case.
The command is *declared* immediately — so a block message can name it — but only attached to the tree when its feature is enabled.
func CheckSafety ¶
CheckSafety applies the context's safety level to a mutating operation -- and is the single place that exempts a dry run from it.
A dry run reads to build its preview and writes nothing, so it is gated like a read, not like the mutation it describes. Checking it would refuse the preview in exactly the context that wants one most: `readonly` exists for someone who wants to look without touching, and `dtctl get dashboard X` already succeeds there, so refusing the same GET under `delete --dry-run` would be inconsistent rather than safer.
The exemption is sound only because --dry-run is opt-in per command (dryRunCommands): a command that reaches this function with dryRun set has a dry-run branch that returns before any write. TestDryRunNeedsNoSafetyLevel holds that invariant by running every such command against a readonly context and a mock environment whose writes fail.
It resolves the process-level state. Code that runs inside an invocation uses checkSafety, which reads the state carried on its context.
func DevelopmentFeatureEnabled ¶
DevelopmentFeatureEnabled reports whether one development feature is opted into, resolving from the ambient config and environment.
It exists for the one caller that cannot wait for the registration stage: main must decide whether to dispatch `dtctl serve` before the command pipeline runs at all, because a server has to start outside the per-invocation lock. Everything inside the pipeline uses the resolved set.
It resolves the process-level state. Code that runs inside an invocation uses developmentFeatureEnabled, which reads the state carried on its context.
func Execute ¶
func Execute()
Execute runs the CLI process: one invocation from os.Args, then exit. Embedders use Run instead, which returns the exit code without terminating the process. Routing through Run (rather than executeArgs directly) keeps a single execution path, and ensures deferred functions (e.g. tracing shutdown/flush) run before os.Exit, which os.Exit would otherwise bypass.
func GetAgentMode ¶
func GetAgentMode() bool
GetAgentMode returns the current agent mode setting
It resolves the process-level state. Code that runs inside an invocation uses getAgentMode, which reads the state carried on its context.
func GetChunkSize ¶
func GetChunkSize() int64
GetChunkSize returns the current chunk size setting for pagination
It resolves the process-level state. Code that runs inside an invocation uses getChunkSize, which reads the state carried on its context.
func GetPlainMode ¶
func GetPlainMode() bool
GetPlainMode returns the current plain mode setting
It resolves the process-level state. Code that runs inside an invocation uses getPlainMode, which reads the state carried on its context.
func LoadConfig ¶
LoadConfig loads the config and applies the context override, if any. Precedence: --context flag > DTCTL_CONTEXT env var > current-context in the config file. Both overrides are session-local — the config file is never written, so a scripted `DTCTL_CONTEXT=x dtctl ...` cannot repoint other processes on the machine.
It resolves the process-level state. Code that runs inside an invocation uses loadConfig, which reads the state carried on its context.
func NewClientFromConfig ¶
NewClientFromConfig creates a new client from config with verbose mode configured
It resolves the process-level state. Code that runs inside an invocation uses newClientFromConfig, which reads the state carried on its context.
func NewDQLExecutorFromConfig ¶
NewDQLExecutorFromConfig creates a DQL executor from a config and client, with OAuth token refresh support. When the OAuth token expires during a long-running query poll (which can exceed the 5-minute token lifetime), the executor automatically fetches a fresh token and retries without aborting the query.
It resolves the process-level state. Code that runs inside an invocation uses newDQLExecutorFromConfig, which reads the state carried on its context.
func NewPrinter ¶
NewPrinter creates a new printer respecting agent and plain mode settings
It resolves the process-level state. Code that runs inside an invocation uses newPrinterCtx, which reads the state carried on its context.
func NewSafetyChecker ¶
NewSafetyChecker creates a new safety checker for the current context. For auto-discovered local configs, the safety level is clamped to min(local, global) so a rogue .dtctl.yaml cannot escalate past the global guard (see Config.GetEffectiveSafetyLevel).
func Run ¶
func Run(argv []string, opts RunOptions) (code int)
Run executes one dtctl invocation in-process and returns its exit code. argv is the command line without the program name (os.Args[1:] shape).
Run is the embedding seam for the service engine and for `dtctl serve`: unlike Execute it never terminates the process, and every invocation starts from a pristine command tree — flag values reset to declared defaults, and per-run tree mutations (command-profile masks, scope-preflight wraps) undone. Concurrent calls are safe; they execute one at a time unless opts.Concurrent is set, in which case each runs on a tree of its own.
func RunActive ¶
func RunActive() bool
RunActive reports whether a Run invocation is currently executing. Long- running commands that themselves embed Run — `dtctl serve` accepting requests — use it to refuse execution from inside another invocation: blocking in a RunE would hold the invocation lock for the server's whole lifetime and deadlock every request (main dispatches serve outside Run for exactly this reason).
func Setup ¶
Setup creates a Config, Client, and Printer for read-only commands. It consolidates the common LoadConfig → NewClientFromConfig → NewPrinter boilerplate.
It resolves the process-level state. Code that runs inside an invocation uses setup, which reads the state carried on its context.
func SetupAccount ¶
func SetupAccount() (*httpclient.Client, string, error)
SetupAccount resolves account credentials and builds an account-plane httpclient. Use for read-only account commands (no safety check).
It resolves the process-level state. Code that runs inside an invocation uses setupAccount, which reads the state carried on its context.
func SetupAccountWithSafety ¶
SetupAccountWithSafety resolves account credentials, runs a safety check, and builds an account-plane httpclient. Use for mutating account commands.
It resolves the process-level state. Code that runs inside an invocation uses setupAccountWithSafety, which reads the state carried on its context.
func SetupClient ¶
SetupClient creates a Config and Client without a Printer. Use this for commands that need the client but handle output differently (e.g., exec commands, log streaming, or commands with conditional printers).
It resolves the process-level state. Code that runs inside an invocation uses setupClient, which reads the state carried on its context.
func SetupWithSafety ¶
SetupWithSafety creates a Config + Client for mutating commands, performing a safety check before the client is created. Use this for commands where ownership is unknown (i.e., the resource doesn't need to be fetched first to determine the owner). A Printer is not included because many mutating commands don't use one.
Under --dry-run the check is skipped: see CheckSafety for why, and for the invariant that makes it sound.
It resolves the process-level state. Code that runs inside an invocation uses setupWithSafety, which reads the state carried on its context.
func SetupWithSafetyAndPrinter ¶
func SetupWithSafetyAndPrinter(op safety.Operation) (*config.Config, *client.Client, output.Printer, error)
SetupWithSafetyAndPrinter is SetupWithSafety plus a Printer, for mutating commands that render their result through the normal output pipeline.
It resolves the process-level state. Code that runs inside an invocation uses setupWithSafetyAndPrinter, which reads the state carried on its context.
func StabilityLint ¶
func StabilityLint() []error
StabilityLint reports declarations that are internally inconsistent across the complete command tree. Same reason for being exported as StabilityManifest.
func StabilityManifest ¶
func StabilityManifest() string
StabilityManifest renders the stability manifest for the complete command tree — every development-tier feature registered, whether or not this environment opted into it.
It is exported for the manifest generator and its CI gate, which live outside this package: they must see `dtctl serve` too, and serve is wired in main because pkg/serve imports pkg/engine, which imports cmd.
func StabilitySinceVersions ¶
StabilitySinceVersions returns every version named by a stability-since declaration in the complete command tree, mapped to the commands and flags that name it.
A since-version is a promise about a *release*: "experimental as of 0.39.0" tells a caller which version withdrew the guarantee. The declarations are written before that release exists, so they are the one part of the manifest that can be falsified by the release itself simply being numbered differently. Exported so test/stability can check them against the version the next release will carry.
func StabilityUndeclaredCommands ¶
func StabilityUndeclaredCommands() []string
StabilityUndeclaredCommands returns the paths of commands that declare no stability tier at all, across the complete command tree.
StabilityLint reports these too, among its other findings. This exists so the CI gate can fail on *just* this rule with a message about this rule: it is the one a new command trips by omission rather than by a mistake, and its author needs to be told that silence is not stable rather than handed a list of unrelated lint categories.
Types ¶
type Capabilities ¶
type Capabilities struct {
// PluginDispatch allows unknown commands to exec dtctl-* binaries from
// PATH (full process replacement on Unix).
PluginDispatch bool
// ShellAliases allows shell-form aliases ("!...") to run via sh -c.
ShellAliases bool
// ApplyHooks allows configured pre-/post-apply hook commands to run.
ApplyHooks bool
// Editor allows `edit` commands to spawn $EDITOR.
Editor bool
// BrowserOpen allows `open` to spawn the OS URL handler.
BrowserOpen bool
// HostDiskSpill allows large results to spill to a file on the host disk
// (`--spill`, `--spill-to`, and the automatic spill in agent mode). The
// spilled file and the path returned to the caller are both host state, so
// an embedded invocation returns its rows inline instead.
HostDiskSpill bool
// HostUsageLedger allows a context that opted into usage tracking to tally
// its DQL scan volume in the local usage ledger under the host's XDG state
// directory (pkg/usage). The ledger is host state that outlives the
// request, so an embedded invocation records nothing.
HostUsageLedger bool
// LongRunningStreams allows commands that can run indefinitely: --watch on
// get subcommands and --follow on logs. The service engine leaves this
// false so a streaming request cannot hold the execution slot forever.
LongRunningStreams bool
}
Capabilities enumerates the process-level abilities the host grants the command tree: spawning a subprocess (or handing the process over entirely, as Unix plugin dispatch does via exec), and reaching for the host's disk outside the vfs seam. Every such path is gated on one of these, so an embedding caller — the service engine, `dtctl serve`, tests — can make it structurally unreachable instead of relying on configuration. The CLI binary grants everything; embedded callers grant nothing (see docs/dev/SERVICE_ENGINE_DESIGN.md).
func AllCapabilities ¶
func AllCapabilities() Capabilities
AllCapabilities is the CLI default: everything granted.
func SetCapabilities ¶
func SetCapabilities(c Capabilities) Capabilities
SetCapabilities replaces the granted capability set. It returns the previous set so tests can restore it.
type CapabilityError ¶
type CapabilityError struct {
// Feature is the human-readable name of the blocked ability.
Feature string
}
CapabilityError reports a feature that is not granted in this environment. In agent mode it renders as a structured envelope with code "capability_disabled".
func (*CapabilityError) Error ¶
func (e *CapabilityError) Error() string
type ContextListItem ¶
type ContextListItem struct {
Current string `table:"CURRENT"`
Name string `table:"NAME"`
Environment string `table:"ENVIRONMENT"`
SafetyLevel string `table:"SAFETY-LEVEL"`
Profile string `table:"PROFILE,wide"`
Description string `table:"DESCRIPTION,wide"`
}
ContextListItem is a flattened view of a context for table display
type DeprecatedError ¶
type DeprecatedError struct {
// Command is the space-joined command path relative to root.
Command string
// Flag is the flag name without dashes, or "" when the whole command is
// deprecated.
Flag string
// Note is the deprecation clause, rendered by stability.Deprecation.Note
// for a command and taken from pflag for a flag, so the wording here is the
// same wording help and the manifest use.
Note string
}
DeprecatedError reports that a deprecated command or flag was invoked by a caller who asked to be shown the world without it (DTCTL_NO_DEPRECATED).
It is not a StabilityError. A deprecated command is still stable in shape, and conflating the two would tell a caller their contract had been weakened when in fact it is scheduled for removal on a published date -- a different problem with a different fix.
func (*DeprecatedError) Error ¶
func (e *DeprecatedError) Error() string
func (*DeprecatedError) Headline ¶
func (e *DeprecatedError) Headline() string
Headline states the block, shared with the agent-mode ErrorDetail.
Reason first, then the target and its note. The note is rendered by whoever owns the deprecation -- stability.Deprecation.Note for a command, pflag's own message for a flag -- so the wording matches help and the manifest, and the clause order avoids the "is deprecated ... deprecated since" stutter that putting the reason last produces.
func (*DeprecatedError) Suggestions ¶
func (e *DeprecatedError) Suggestions() []string
Suggestions tell the caller what to do about it. Unsetting the variable is listed last on purpose: the caller set it precisely to be told this, so the useful answer is the replacement, not a way to silence the finding.
type DevelopmentError ¶
type DevelopmentError struct {
// Command is the command path the caller typed.
Command string
// Feature is the opt-in key that would enable it.
Feature string
}
DevelopmentError reports that an invoked command exists in this binary but is a development-tier feature that was not opted into.
It is produced only when the caller has already demonstrated knowledge of the mechanism (see developmentSignposting). Otherwise a disabled development command is indistinguishable from one that does not exist, which is the whole point of gating by *registration* rather than by hiding.
func (*DevelopmentError) Error ¶
func (e *DevelopmentError) Error() string
func (*DevelopmentError) Headline ¶
func (e *DevelopmentError) Headline() string
Headline is the one-line statement of the block.
func (*DevelopmentError) Suggestions ¶
func (e *DevelopmentError) Suggestions() []string
Suggestions are the remediation hints, shared with the agent-mode ErrorDetail.
type DocumentTypeCount ¶
type DocumentTypeCount struct {
Type string `table:"TYPE" json:"type" yaml:"type"`
Count int `table:"COUNT" json:"count" yaml:"count"`
}
DocumentTypeCount holds a count per document type (for --types flag)
type HeaderRefusedError ¶
type HeaderRefusedError struct {
// Header is the header name as the caller typed it, canonicalized.
Header string
// Reason is the policy's explanation.
Reason string
}
HeaderRefusedError is returned when the embedding caller's header policy (RunOptions.HeaderPolicy) refuses a header passed to `exec api -H`. Which headers a caller may set 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. Agent mode renders it with the stable code "header_refused" (see errorToDetail), so a host can map the refusal to a client error.
func (*HeaderRefusedError) Error ¶
func (e *HeaderRefusedError) Error() string
func (*HeaderRefusedError) Headline ¶
func (e *HeaderRefusedError) Headline() string
Headline is the one-line statement of the refusal, shared by the human-readable Error() string and the structured agent-mode ErrorDetail so the two never drift.
type ParseError ¶
ParseError is a command line that Execute would refuse before running the command body. ExitCode is the exit code Execute returns for it. 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 (the profile, the stability floor, a 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 (*ParseError) Error ¶
func (e *ParseError) Error() string
type ParseOptions ¶
type ParseOptions struct {
SafetyLevel config.SafetyLevel
MinStability config.StabilityLevel
StabilityExceptions []string
NoDeprecated bool
// Env sets environment variables for the analysis, as RunOptions.Env
// does for a run (e.g. DTCTL_PROFILE).
Env map[string]string
// BlockedCommands removes top-level commands from the surface, as
// RunOptions.BlockedCommands does.
BlockedCommands map[string]string
// HeaderPolicy refuses `exec api -H` headers, as RunOptions.HeaderPolicy
// does.
HeaderPolicy func(name string) string
// Context bounds the wait for a serialized invocation to finish. nil is
// context.Background().
Context context.Context
}
ParseOptions configures Parse. Each field means what its counterpart on Session or RunOptions means for Run, so a caller that restricts what it runs gets the same answer from Parse.
type ParseResult ¶
type ParseResult 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,
// as vfs.Key names, sorted, de-duplicated and never nil. The stdin values ("-",
// "@-") are never one; a path that only resolves to the key "-" (./-) is a
// file, as it is at run time.
InputFiles []string
OutputFiles []string
// RequiresInput is true when the command may read stdin: a "-" file value,
// "-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, or --dry-run where the dry run
// returns before the question) nor --plain or --agent. restore trash asks
// only for a single document; breakpoint commands only when existing
// breakpoints are affected, which Parse cannot know, so it reports them as
// asking. A refused or missing answer cancels the command with exit 0. It
// is false under --check-scopes, which does not run the command.
RequiresInput bool
// RequiredScopes are the token scopes the catalog names for the command,
// never nil, and complete only when Scopes is "known". Scopes is "none" (the catalog names
// none; for a command the catalog is missing scopes for, that
// under-reports), "known", "per_call" (decided by the call, exec api) or
// "input_dependent" (decided by the input file's content, apply).
RequiredScopes []string
Scopes string
// Help is true when the command line asks for help text (--help) or names
// a group that only prints its usage: nothing would run, and Verb and
// Resource name the command whose help it is, not a command to run. Scopes
// is "none" because nothing is called.
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
}
ParseResult is what a command line means, without running it.
func Parse ¶
func Parse(argv []string, opts ParseOptions) (*ParseResult, error)
Parse analyses a command line the way Run would run it, and stops where the command body would start: by then cobra has parsed the flags, validated the arguments and required flags, and run the pre-run hooks. It reads no file, calls no platform API and needs no token.
It goes through the pipeline Run does — a fresh tree, the same surface masks, cobra's validation, the same error classification — so a command line Execute would refuse returns a *ParseError with the error Execute reports. Validation inside a command body is the one thing it cannot see. Any other error is a fault in Parse itself.
Parse runs on a tree of its own and takes the invocation lock shared, like a concurrent Run, so it is safe to call from many goroutines.
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.
type ProfileError ¶
type ProfileError struct {
// Command is the space-joined command path relative to root (e.g. "auth login").
Command string
// Profile is the name of the active profile that masks the command.
Profile string
}
ProfileError is returned when a command that is masked by the active profile is invoked. Because the command is hidden but still parseable by Cobra, the guard produces a specific, signposted error rather than a generic "unknown command". It is a surface (topic) error, distinct from a safety (permission) error — see docs/dev/COMMAND_PROFILES_DESIGN.md.
func (*ProfileError) Error ¶
func (e *ProfileError) Error() string
func (*ProfileError) Headline ¶
func (e *ProfileError) Headline() string
Headline is the one-line statement of the block, shared by the human-readable Error() string and the structured agent-mode ErrorDetail (errorToDetail) so the two never drift.
func (*ProfileError) Suggestions ¶
func (e *ProfileError) Suggestions() []string
Suggestions are the remediation hints, shared with the agent-mode ErrorDetail.
type RunOptions ¶
type RunOptions struct {
// Capabilities restricts process-level abilities (subprocess spawns) for
// this invocation. nil grants everything (the CLI default); embedded
// callers typically pass &Capabilities{} to grant nothing.
Capabilities *Capabilities
// Session, when non-nil, pins the invocation to one environment + token
// and detaches it from the host's config file, contexts, keyring, and
// credential env vars. See Session.
Session *Session
// Env sets environment variables for the duration of the invocation
// (restored afterwards), e.g. DTCTL_PROFILE to select a command profile
// per request. Applied after session scrubbing, so an explicit entry wins.
// For a serialized invocation the mutation is process-wide while it runs;
// a Concurrent one records the entries on itself instead — see
// applyRunEnvironment.
Env map[string]string
// FS resolves user-supplied file paths (-f and friends) for this
// invocation, including writebacks like `apply --write-id`. nil reads and
// writes the host filesystem (the CLI default); embedded callers pass a
// vfs.MapFS built from the request's virtual files. See pkg/vfs.
FS vfs.FS
// Stdout and Stderr receive the invocation's output; Stdin feeds commands
// that read it ("-" file arguments, piped input). nil means the process
// streams (the CLI default). The redirection captures every output path —
// fmt.Print*, the output package, cobra help, error envelopes — as the
// exact byte stream the CLI would print. See redirectStdio.
Stdout io.Writer
Stderr io.Writer
Stdin io.Reader
// BlockedCommands removes top-level commands (with their whole subtree)
// from this invocation's surface: hidden from help, the `dtctl commands`
// catalog, and completion, and guarded so dispatch returns an
// UnsupportedCommandError (agent-mode code "unsupported_in_service").
// Keyed by top-level command name; the value is the human-readable reason.
// nil is the full surface (the CLI default). See applyBlockedCommands.
BlockedCommands map[string]string
// HeaderPolicy lets the embedding caller refuse request headers passed to
// `exec api -H`. It receives the normalized header name (canonicalized,
// "_" folded to "-") and returns why the header is refused, or "" to allow
// it. A refusal is a HeaderRefusedError (agent-mode code "header_refused"),
// returned before any request is sent and before --dry-run prints one. nil
// applies only the CLI's own refusals (Authorization, Proxy-Authorization).
HeaderPolicy func(name string) string
// Context carries the request's context into the Cobra command tree so
// command bodies can observe cancellation and deadlines via cmd.Context().
// nil defaults to context.Background(), preserving CLI behaviour.
Context context.Context
// Concurrent opts this invocation out of the whole-invocation lock, so it
// overlaps with other Concurrent invocations in the same process.
//
// The invocation runs on a
// command tree of its own (newCommandTree), with every flag bound to
// storage only it can reach, and its streams, environment, filesystem,
// session and capabilities travel on its context instead of being swapped
// process-wide. A panic in the command fails this invocation (exit code
// ExitError, message on its stderr) rather than the embedding process.
//
// Requires a Session: config resolution reads the host's contexts, which a
// tree of its own cannot select (--context), so Run refuses the combination
// with ExitUsageError.
//
// Its wait for a serialized invocation to finish ends with Context: Run
// then returns ExitError without having started (OnStart is not called).
Concurrent bool
// OnStart, when set, is called on Run's goroutine once the invocation holds
// the invocation lock, before anything else of it runs.
OnStart func()
}
RunOptions configures a single embedded invocation. The zero value is the CLI default: every capability granted, config and credentials resolved from the host (config file, env, keyring), host environment untouched.
type ScopeCheckResult ¶
type ScopeCheckResult struct {
Verb string `json:"verb" yaml:"verb"`
Resource string `json:"resource,omitempty" yaml:"resource,omitempty"`
Status string `json:"status" yaml:"status"` // ok | insufficient_scope | unknown
RequiredScopes []string `json:"required_scopes" yaml:"required_scopes"`
// AlternativeScopes are scope sets the endpoint accepts in place of
// RequiredScopes; holding any one set in full is as good as holding them.
AlternativeScopes [][]string `json:"alternative_scopes,omitempty" yaml:"alternative_scopes,omitempty"`
// SatisfiedBy is the alternative set an ok verdict rests on, when the
// token lacks RequiredScopes but holds one of AlternativeScopes.
SatisfiedBy []string `json:"satisfied_by,omitempty" yaml:"satisfied_by,omitempty"`
GrantedScopes []string `json:"granted_scopes,omitempty" yaml:"granted_scopes,omitempty"`
MissingScopes []string `json:"missing_scopes,omitempty" yaml:"missing_scopes,omitempty"`
Suggestions []string `json:"suggestions,omitempty" yaml:"suggestions,omitempty"`
}
ScopeCheckResult is the verdict emitted by `--check-scopes`.
type ScopeError ¶
type ScopeError struct {
Verb string
Resource string
Required []string
Granted []string
Missing []string
// Alternatives are scope sets accepted in place of Required; the token
// holds none of them in full.
Alternatives [][]string
// Reason, when set, replaces the generic message: it says which part of
// the invocation needs the missing scopes.
Reason string
// Advice, when set, replaces the generic suggestions.
Advice []string
}
ScopeError is returned by the agent-mode auto-preflight when a mutating command is missing required scopes, and by the DQL scope precheck. It is rendered as an insufficient_scope envelope (see errorToDetail) and exits with ExitPermissionError.
func (*ScopeError) Error ¶
func (e *ScopeError) Error() string
type Session ¶
type Session struct {
// 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 invocation. Required.
Token string
// SafetyLevel bounds mutating operations for this invocation
// (readonly | readwrite-mine | readwrite-all | dangerously-unrestricted).
// Empty selects the dtctl default (readwrite-all).
SafetyLevel config.SafetyLevel
// MinStability is the stability floor for this invocation: 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 session has no
// opt-in for it.
//
// Empty selects SessionDefaultMinStability — `stable`, which is *stricter*
// than the CLI's default. The difference is deliberate: the CLI's default
// admits experimental surface because a human or interactive agent reads
// the `[Experimental]` badge and decides. An embedded caller reads no
// badge, and a service request is unattended automation by construction —
// precisely what "may change in any release" is a warning to. A host that
// wants the wider surface asks for it in this field.
MinStability config.StabilityLevel
// 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.
//
// This is the field a host reaches for rather than lowering the floor: a
// floor of `experimental` grants the entire experimental surface, including
// flags added to already-allowed stable commands in a later release, which
// is almost never what a service intended.
StabilityExceptions []string
// NoDeprecated makes this invocation refuse every deprecated command and
// flag, as if the removal release had already happened. It is how a host
// finds out it still depends on something scheduled to go while that is
// still a test failure rather than an outage.
//
// Orthogonal to MinStability: a deprecated command is stable in shape and
// passes any floor, it merely has a removal date. Off by default, because
// a host that has not asked to be broken early should not be.
NoDeprecated bool
// Transport, when non-nil, carries every platform request this invocation
// sends, in place of the process-wide connection pool. It is how a host
// points a session at a stand-in environment — an httptest server's
// Client().Transport, or an *http.Transport with its own TLS
// configuration — without the invocation knowing it is not talking to
// Dynatrace. Everything above the transport (base URL, bearer token,
// User-Agent, retries, request-path guard) is unchanged, so the bytes a
// command prints are the bytes it would print against a real environment.
//
// The RoundTripper is shared by every client the invocation builds, and,
// when the host reuses it, by overlapping invocations: it must be safe for
// concurrent use, as http.RoundTripper requires.
Transport http.RoundTripper
// contains filtered or unexported fields
}
Session is a per-invocation target + credential override for embedded callers. When set on RunOptions, the invocation runs against exactly this environment and token: the host's config file, contexts, keyring, and credential env vars are all out of the picture, which is what a multi-tenant service needs — every request brings its own tenant (docs/dev/SERVICE_ENGINE_DESIGN.md).
A session replaces credential *resolution*, not command *policy*: blocking commands that make no sense service-side (config, ctx, login) is the engine's job, on top of this seam.
type SessionStatus ¶
type SessionStatus struct {
Context string `json:"context" yaml:"context"`
Environment string `json:"environment" yaml:"environment"`
IsOAuth bool `json:"isOAuth" yaml:"isOAuth"`
Storage string `json:"storage,omitempty" yaml:"storage,omitempty"`
AccessTokenPresent bool `json:"accessTokenPresent" yaml:"accessTokenPresent"`
AccessTokenExpiresAt *time.Time `json:"accessTokenExpiresAt,omitempty" yaml:"accessTokenExpiresAt,omitempty"`
RefreshTokenPresent bool `json:"refreshTokenPresent" yaml:"refreshTokenPresent"`
RefreshTokenExpiresAt *time.Time `json:"refreshTokenExpiresAt,omitempty" yaml:"refreshTokenExpiresAt,omitempty"`
GrantedScopes []string `json:"grantedScopes,omitempty" yaml:"grantedScopes,omitempty"`
// contains filtered or unexported fields
}
SessionStatus summarizes OAuth token state for display by `auth status` and `doctor`.
type StabilityError ¶
type StabilityError struct {
// Command is the space-joined command path relative to root ("get workflows").
Command string
// Flag is the flag name (without dashes) when a flag rather than the whole
// command is below the floor, and "" otherwise.
Flag string
// Level is the target's effective stability tier.
Level stability.Level
// Floor is the tier the active context requires.
Floor stability.Level
}
StabilityError is returned when a command or flag whose contract is weaker than the active stability floor is invoked. It is a *contract* error, and so distinct from both ProfileError (the topical surface axis) and safety.SafetyError (the permission axis) — the three answer different questions and a caller resolves them differently.
func (*StabilityError) Error ¶
func (e *StabilityError) Error() string
func (*StabilityError) Headline ¶
func (e *StabilityError) Headline() string
Headline is the one-line statement of the block, shared by the human-readable Error() string and the structured agent-mode ErrorDetail (errorToDetail) so the two never drift.
func (*StabilityError) Suggestions ¶
func (e *StabilityError) Suggestions() []string
Suggestions are the remediation hints, shared with the agent-mode ErrorDetail. The narrow opt-in is listed first deliberately: lowering the floor grants the entire below-floor surface, including flags added to already-allowed commands in a later release, which is almost never what the caller wanted.
type UnsupportedCommandError ¶
type UnsupportedCommandError struct {
// Command is the space-joined command path relative to root (e.g. "config view").
Command string
// Reason says why the command is out of scope for this environment.
Reason string
}
UnsupportedCommandError is returned when an invocation names a top-level command that the embedding caller has removed from the surface via RunOptions.BlockedCommands — commands that only make sense on a host CLI (config, ctx, auth, ...) and are meaningless or unsafe inside a service. It is a surface error like ProfileError, distinct from safety (permission) and capability (process-ability) errors; agent mode renders it with the stable code "unsupported_in_service" (see errorToDetail).
func (*UnsupportedCommandError) Error ¶
func (e *UnsupportedCommandError) Error() string
func (*UnsupportedCommandError) Headline ¶
func (e *UnsupportedCommandError) Headline() string
Headline is the one-line statement of the block, shared by the human-readable Error() string and the structured agent-mode ErrorDetail so the two never drift.
func (*UnsupportedCommandError) Suggestions ¶
func (e *UnsupportedCommandError) Suggestions() []string
Suggestions are the remediation hints, shared with the agent-mode ErrorDetail.
type WhoamiResult ¶
type WhoamiResult struct {
UserID string `json:"userId" yaml:"userId"`
UserName string `json:"userName,omitempty" yaml:"userName,omitempty"`
EmailAddress string `json:"emailAddress,omitempty" yaml:"emailAddress,omitempty"`
Context string `json:"context" yaml:"context"`
Environment string `json:"environment" yaml:"environment"`
}
WhoamiResult contains the current user information for output
Source Files
¶
- account.go
- account_login.go
- account_service_user.go
- account_status.go
- account_token.go
- agent_helpers.go
- alias.go
- alias_resolve.go
- apply.go
- apply_extension_configs.go
- auth.go
- blocked.go
- breakpoint_helpers.go
- breakpoint_output.go
- capabilities.go
- check_scopes.go
- claim.go
- commands.go
- completion.go
- config.go
- config_development.go
- create.go
- create_anomalydetector.go
- create_aws.go
- create_azure.go
- create_breakpoints.go
- create_buckets.go
- create_documents.go
- create_edgeconnects.go
- create_extensions.go
- create_gcp.go
- create_lookups.go
- create_providers.go
- create_scheduling_rules.go
- create_segments.go
- create_settings.go
- create_slos.go
- create_workflows.go
- ctx.go
- delete.go
- delete_aws.go
- delete_breakpoints.go
- delete_gcp.go
- describe.go
- describe_actions.go
- describe_analyzers.go
- describe_anomalydetector.go
- describe_api.go
- describe_apps.go
- describe_aws.go
- describe_breakpoints.go
- describe_buckets.go
- describe_documents.go
- describe_edgeconnects.go
- describe_extension_configs.go
- describe_extensions.go
- describe_function.go
- describe_gcp.go
- describe_hub_extensions.go
- describe_iam.go
- describe_intent.go
- describe_lookups.go
- describe_platform.go
- describe_scheduling_rules.go
- describe_segments.go
- describe_settings.go
- describe_slos.go
- describe_workflows.go
- diff.go
- disable.go
- disable_aws.go
- disable_azure.go
- disable_gcp.go
- disable_providers.go
- doctor.go
- document_admin_access.go
- document_snapshot_flags.go
- document_type.go
- download.go
- dryrun.go
- edit.go
- edit_anomalydetector.go
- edit_aws.go
- edit_azure.go
- edit_documents.go
- edit_gcp.go
- edit_segments.go
- edit_settings.go
- edit_workflows.go
- enable.go
- enable_aws.go
- enable_azure.go
- enable_gcp.go
- enable_providers.go
- exec.go
- exec_analyzer_shape.go
- exec_analyzers.go
- exec_api.go
- exec_copilot.go
- exec_dql.go
- exec_forward_unix.go
- exec_functions.go
- exec_preview_processor.go
- exec_slos.go
- exec_workflows.go
- file_flags.go
- file_input.go
- find.go
- find_intents.go
- get.go
- get_actions.go
- get_analyzers.go
- get_anomalydetector.go
- get_apis.go
- get_apps.go
- get_aws.go
- get_azure.go
- get_buckets.go
- get_documents.go
- get_edgeconnects.go
- get_extensions.go
- get_functions.go
- get_gcp.go
- get_hub_extensions.go
- get_iam.go
- get_intents.go
- get_list_shape.go
- get_lookups.go
- get_notifications.go
- get_platform.go
- get_providers.go
- get_scheduling_rules.go
- get_segments.go
- get_settings.go
- get_slos.go
- get_snapshots.go
- get_wfe_task_result.go
- get_workflows.go
- header_policy.go
- help_topics.go
- history.go
- inspect.go
- inspect_list.go
- inspect_output.go
- inspect_spill.go
- invalid_input.go
- inventory.go
- inventory_signals.go
- invocation.go
- logs.go
- nonempty_flag.go
- open.go
- open_intent.go
- output_bounds.go
- parse.go
- plugin.go
- plugin_dispatch.go
- preview_notice.go
- profile.go
- query.go
- query_error_hints.go
- query_input.go
- query_mangle.go
- query_mangle_unix.go
- query_scopes.go
- query_series.go
- query_window.go
- querylimits.go
- restore.go
- root.go
- root_factory.go
- rootflags.go
- run.go
- runlock.go
- session.go
- share.go
- skills.go
- spill.go
- stability.go
- stability_export.go
- stability_pre_1_0.go
- stdio.go
- translate.go
- translate_classic_pipelines.go
- translate_lql_to_dql.go
- unknown_noun.go
- update.go
- update_aws.go
- update_azure.go
- update_breakpoints.go
- update_documents.go
- update_extensions.go
- update_gcp.go
- update_providers.go
- usage.go
- verify.go
- verify_analyzer.go
- verify_openpipeline_dql_processor.go
- verify_openpipeline_matcher.go
- verify_query.go
- version.go
- wait.go