exec

package
v0.46.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 29 Imported by: ? 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

Index

Constants

View Source
const (
	PartialScanLimit   = notifScanLimit
	PartialResultLimit = notifResultLimit
	PartialTimeout     = notifTimeout
	PartialConsumption = notifConsumption
)

Causes of an incomplete result, as reported by PartialCause. They are distinguished because the remedies are not interchangeable: a scan cap wants less data scanned or a bigger cap, a result cap wants aggregation, a timeout wants a narrower read. Collapsing them into one "cut short by a limit" message forces the reader to guess which of three fixes applies.

View Source
const AgentDefaultPrecision = 4

AgentDefaultPrecision is the significant-digit rounding agent mode applies when --precision is not given.

View Source
const DefaultSpillThresholdBytes int64 = 50 * 1024

DefaultSpillThresholdBytes is the default serialised-output size above which a result spills (D5). 50 KB ≈ a screenful, well under any model's budget and above an ordinary capped result.

Variables

This section is empty.

Functions

func ExtractQueryRecords

func ExtractQueryRecords(result *DQLQueryResponse) []map[string]interface{}

ExtractQueryRecords normalizes records returned by DQL APIs across legacy and nested response shapes.

func ParseByteSize

func ParseByteSize(s string) (int64, error)

ParseByteSize parses a human byte size such as "50KB", "50k", "1MB", "1.5MiB" or a bare byte count "51200". All unit suffixes — KB/MB/GB, KiB/MiB/GiB, and bare K/M/G — are treated as 1024-based (binary). This keeps the threshold consistent with the byte counts the agent envelope reports (e.g. "50KB" == 51200 bytes, matching threshold_bytes in the spill manifest).

func ParseParams

func ParseParams(paramStrings []string) (map[string]string, error)

ParseParams parses key=value parameter strings

func PartialCause

func PartialCause(n QueryNotification) string

PartialCause reports why a query notification means the result is incomplete, as one of the Partial* constants, or "" if the notification does not truncate. Sampling is excluded — it is declared in the query text, not a silent truncation.

func ReadFileOrStdin

func ReadFileOrStdin(filename string) (string, error)

ReadFileOrStdin reads content from a file (through the vfs seam, so embedded invocations resolve virtual request files) or stdin.

func ReadFileOrStdinWith

func ReadFileOrStdinWith(env vfs.Env, filename string) (string, error)

ReadFileOrStdinWith is ReadFileOrStdin through the given invocation Env.

func ResultIsPartial

func ResultIsPartial(n QueryNotification) bool

ResultIsPartial reports whether a query notification means the result is incomplete: a record/byte cap, scan limit, fetch timeout, or consumption stop cut it short.

func StorageScopeForDataObject

func StorageScopeForDataObject(name string) (string, bool)

StorageScopeForDataObject returns the storage scope that reads the named data object, and false when that is not known for certain.

func StorageScopesInText

func StorageScopesInText(s string) []string

StorageScopesInText returns the distinct storage read scopes spelled out in s, sorted. Grail's authorization errors sometimes name the scope they wanted.

func TrackUsage

func TrackUsage(c *client.Client, r UsageRecorder)

TrackUsage makes every DQL executor built on c from now on report to r.

Types

type AnalysisTimeframe

type AnalysisTimeframe = sdkquery.AnalysisTimeframe

Re-export SDK types so existing callers continue to compile.

type BucketContribution

type BucketContribution = sdkquery.BucketContribution

Re-export SDK types so existing callers continue to compile.

type ColumnType

type ColumnType = sdkquery.ColumnType

Re-export SDK types so existing callers continue to compile.

type ColumnTypes

type ColumnTypes = sdkquery.ColumnTypes

Re-export SDK types so existing callers continue to compile.

type Contributions

type Contributions = sdkquery.Contributions

Re-export SDK types so existing callers continue to compile.

type DQLExecuteOptions

type DQLExecuteOptions struct {
	// Output formatting options
	OutputFormat string
	JQFilter     string // jq filter expression applied before rendering
	AgentMode    bool   // Enable agent mode (e.g. for Dynatrace API)
	// AutoFormatByDefault reports that OutputFormat is auto only because it is
	// the agent-mode default (no -o given), so a non-JSON result carries the
	// -o json opt-out suggestion.
	AutoFormatByDefault bool
	Decode              DecodeMode // Snapshot payload decoding mode
	Width               int        // Chart width (0 = default)
	Height              int        // Chart height (0 = default)
	Fullscreen          bool       // Use terminal dimensions for chart

	// Query limit options
	MaxResultRecords       int64   // Maximum number of result records (0 = use default)
	MaxResultBytes         int64   // Maximum result size in bytes (0 = use default)
	DefaultScanLimitGbytes float64 // Scan limit in gigabytes (0 = use default)

	// Query execution options
	DefaultSamplingRatio         float64 // Sampling ratio (0 = use default, normalized to power of 10 <= 100000)
	FetchTimeoutSeconds          int32   // Time limit for fetching data in seconds (0 = use default)
	EnablePreview                bool    // Request preview results
	EnforceQueryConsumptionLimit bool    // Enforce query consumption limit
	IncludeTypes                 bool    // Include type information in results (default: true)
	IncludeContributions         bool    // Include bucket contribution information in results

	// EmitTypes surfaces the DQL per-column type block as a top-level "types"
	// key alongside "records" in structured (json/yaml) output. It is set only
	// when the user explicitly passed --include-types, so the metadata that
	// parquet/--typed request internally is not accidentally emitted. Has no
	// effect unless the API actually returned type information.
	EmitTypes bool

	// TypesRequested reports that the user explicitly asked for the type block:
	// --include-types was passed and is true. EmitTypes is set whenever the flag
	// was passed at all, --include-types=false included; the "has no effect"
	// warning keys off this field instead, so declining the block never warns
	// about not getting it. It does not affect what is printed on stdout.
	TypesRequested bool

	// Typed opts in to casting scalar columns (long, double, duration, boolean)
	// to their native JSON/YAML types using the DQL type metadata, instead of the
	// wire form where integer-valued columns arrive as strings. Off by default so
	// output stays faithful to the API; implies IncludeTypes so the mapping is
	// available. See output.ApplyTrueTypes.
	Typed bool

	// Compact omits null values and hoists the columns that hold one value in
	// every row into a `constant` map (#578). It applies to the agent envelope
	// (inline records and the spill manifest) and to plain json/yaml/toon
	// output; the command layer defaults it on in agent mode. Never applied
	// under --jq, whose program addresses the full rows.
	Compact bool

	// Series selects how the numeric arrays of timeseries records are rendered
	// (--series): full (default, unchanged), a per-series summary, or
	// extreme-preserving downsampling. See output.ApplySeriesMode.
	Series output.SeriesMode

	// Precision rounds every float in the records to this many significant
	// digits (--precision); 0 leaves values unchanged.
	Precision int

	// SeriesDefaulted and PrecisionDefaulted mark Series/Precision as the
	// agent-mode defaults rather than the caller's explicit choice. When a
	// defaulted value actually changed the result, the agent envelope carries
	// one suggestion naming the opt-out.
	SeriesDefaulted    bool
	PrecisionDefaulted bool

	// Timeframe options
	DefaultTimeframeStart string // Query timeframe start timestamp (ISO-8601/RFC3339)
	DefaultTimeframeEnd   string // Query timeframe end timestamp (ISO-8601/RFC3339)

	// Localization options
	Locale   string // Query locale (e.g., "en_US")
	Timezone string // Query timezone (e.g., "UTC", "Europe/Paris")

	// ShowProgress opts in to the live progress bar drawn on stderr while an
	// asynchronous query is polled. It is off by default so internal/library
	// query callers (e.g. describe sub-queries, lookup metadata fetches) stay
	// silent; only the user-facing `query` command sets it. Even when set, the
	// bar is drawn only for interactive terminals and never affects stdout, so
	// structured/piped output is unchanged regardless.
	ShowProgress bool

	// Metadata options
	MetadataFields []string // Metadata fields to include; nil/empty = disabled, ["all"] = all fields, ["minimal"] = lean agent set, specific names = filtered

	// MetadataDefaulted records that agent mode chose MetadataFields
	// (["minimal"]) because -M was not given, so an envelope that dropped
	// something names the -M=all opt-out.
	MetadataDefaulted bool

	// Verbose mirrors -v. Under --metadata=minimal it keeps the inline spill
	// decision's measurement details (threshold/measured bytes) in the envelope.
	Verbose bool

	// Segment options
	Segments []FilterSegmentRef // Filter segments to apply to the query

	// ClientContext is an optional caller-supplied semantic string included as the "context"
	// field in the dt-client-context request header (e.g. "root-cause-analysis").
	ClientContext string

	// Spill holds the fully-resolved result-spill settings. When Spill.Enabled()
	// is false (mode never) the spill path is bypassed entirely and output is
	// unchanged from today's behaviour.
	Spill SpillOptions

	// MaxFieldChars clips every string value in an agent-mode result to this
	// many runes, ending a clipped value in "…(+N chars)" (0 = no cap). Spilled
	// files always keep the full values. The command layer defaults it to
	// output.DefaultAgentMaxFieldChars in agent mode.
	MaxFieldChars int

	// MaxOutputBytes bounds the agent-mode envelope, measured on the bytes
	// actually written to stdout (0 = no budget). An inline result over it keeps
	// the leading rows that fit and marks the cut on the context.
	MaxOutputBytes int64

	// TenantID and ContextName are provenance recorded in the spill manifest and
	// used to partition the spill directory by context (D9). They are not part of
	// query execution and are only consulted on the spill path.
	TenantID    string
	ContextName string

	// Decorate amends the agent envelope context; records is nil when rows streamed to disk.
	Decorate func(ctx *output.ResponseContext, result *DQLQueryResponse, records []map[string]interface{})
	// contains filtered or unexported fields
}

DQLExecuteOptions configures DQL query execution

type DQLExecutor

type DQLExecutor struct {
	// contains filtered or unexported fields
}

DQLExecutor handles DQL query execution

func NewDQLExecutor

func NewDQLExecutor(c *client.Client) *DQLExecutor

NewDQLExecutor creates a new DQL executor

func (*DQLExecutor) CancelQuery

func (e *DQLExecutor) CancelQuery(requestToken string)

CancelQuery sends a best-effort cancellation request for a running query. Errors are written to stderr but not returned — cancellation is best-effort.

func (*DQLExecutor) Execute

func (e *DQLExecutor) Execute(query string, outputFormat string) error

Execute executes a DQL query

func (*DQLExecutor) ExecuteFromFile

func (e *DQLExecutor) ExecuteFromFile(filename string, outputFormat string) error

ExecuteFromFile executes a DQL query from a file

func (*DQLExecutor) ExecuteQuery

func (e *DQLExecutor) ExecuteQuery(query string) (*DQLQueryResponse, error)

ExecuteQuery executes a DQL query and returns the raw result

func (*DQLExecutor) ExecuteQueryWithContext

func (e *DQLExecutor) ExecuteQueryWithContext(ctx context.Context, query string, opts DQLExecuteOptions) (*DQLQueryResponse, error)

ExecuteQueryWithContext executes a DQL query with a cancellable context. If ctx is cancelled while the query is polling, a best-effort cancel request is sent to the Grail backend before returning.

func (*DQLExecutor) ExecuteQueryWithOptions

func (e *DQLExecutor) ExecuteQueryWithOptions(query string, opts DQLExecuteOptions) (*DQLQueryResponse, error)

ExecuteQueryWithOptions executes a DQL query with options and returns the raw result

func (*DQLExecutor) ExecuteWithContext

func (e *DQLExecutor) ExecuteWithContext(ctx context.Context, query string, opts DQLExecuteOptions) error

ExecuteWithContext executes a DQL query with a cancellable context and prints the results.

func (*DQLExecutor) ExecuteWithOptions

func (e *DQLExecutor) ExecuteWithOptions(query string, opts DQLExecuteOptions) error

ExecuteWithOptions executes a DQL query with full options

func (*DQLExecutor) PrintNotifications

func (e *DQLExecutor) PrintNotifications(notifications []QueryNotification)

PrintNotifications prints query notifications/warnings to stderr

func (*DQLExecutor) VerifyQuery

func (e *DQLExecutor) VerifyQuery(query string, opts DQLVerifyOptions) (*DQLVerifyResponse, error)

VerifyQuery verifies a DQL query without executing it

func (*DQLExecutor) VerifyQueryWithContext

func (e *DQLExecutor) VerifyQueryWithContext(ctx context.Context, query string, opts DQLVerifyOptions) (*DQLVerifyResponse, error)

VerifyQueryWithContext is VerifyQuery bound to the caller's context, so an embedding caller that goes away stops waiting on the verification.

func (*DQLExecutor) WithStreams

func (e *DQLExecutor) WithStreams(stdout, stderr io.Writer) *DQLExecutor

WithStreams directs the executor's results to stdout and its notices, progress and diagnostics to stderr, for a caller that owns the invocation's streams. nil keeps the process stream.

func (*DQLExecutor) WithTokenRefresher

func (e *DQLExecutor) WithTokenRefresher(refresher func() (string, error)) *DQLExecutor

WithTokenRefresher sets an optional callback that is invoked when a poll request receives a 401 Unauthorized response (e.g. because the OAuth token expired during a long-running query). The callback must return a fresh access token. The executor updates the underlying HTTP client with the new token and retries the poll.

func (*DQLExecutor) WithUsageRecorder

func (e *DQLExecutor) WithUsageRecorder(r UsageRecorder) *DQLExecutor

WithUsageRecorder sets the recorder this executor reports to, replacing any bound to its client. nil turns recording off.

func (*DQLExecutor) WithVFS

func (e *DQLExecutor) WithVFS(env vfs.Env) *DQLExecutor

WithVFS sets the filesystem and stdin the executor reads query files from. The zero Env keeps the process's.

type DQLMetadata

type DQLMetadata = sdkquery.Metadata

Re-export SDK types so existing callers continue to compile.

type DQLQueryRequest

type DQLQueryRequest = sdkquery.ExecuteRequest

Re-export SDK types so existing callers continue to compile.

type DQLQueryResponse

type DQLQueryResponse = sdkquery.Response

Re-export SDK types so existing callers continue to compile.

type DQLResult

type DQLResult = sdkquery.Result

Re-export SDK types so existing callers continue to compile.

type DQLVerifyOptions

type DQLVerifyOptions struct {
	GenerateCanonicalQuery bool   // Generate a canonical (normalized) version of the query
	Timezone               string // Query timezone (e.g., "UTC", "Europe/Paris")
	Locale                 string // Query locale (e.g., "en_US")
	ClientContext          string // Optional caller-supplied semantic string for the dt-client-context header
}

DQLVerifyOptions configures DQL query verification

type DQLVerifyRequest

type DQLVerifyRequest = sdkquery.VerifyRequest

Re-export SDK types so existing callers continue to compile.

type DQLVerifyResponse

type DQLVerifyResponse = sdkquery.VerifyResponse

Re-export SDK types so existing callers continue to compile.

type DecodeMode

type DecodeMode int

DecodeMode controls snapshot payload decoding behavior.

const (
	// DecodeNone disables snapshot decoding (default).
	DecodeNone DecodeMode = iota
	// DecodeSimplified decodes and simplifies variant wrappers to plain values.
	DecodeSimplified
	// DecodeFull decodes but preserves the full variant tree with type annotations.
	DecodeFull
)

type ExecutionStatus

type ExecutionStatus struct {
	ID        string     `json:"id"`
	Workflow  string     `json:"workflow"`
	State     string     `json:"state"`
	StateInfo *string    `json:"stateInfo,omitempty"`
	StartedAt time.Time  `json:"startedAt"`
	EndedAt   *time.Time `json:"endedAt,omitempty"`
	Runtime   int        `json:"runtime,omitempty"`
	Result    any        `json:"result,omitempty"`
}

ExecutionStatus represents the status of a workflow execution

func (*ExecutionStatus) IsTerminalState

func (s *ExecutionStatus) IsTerminalState() bool

IsTerminalState returns true if the execution state is terminal (completed, failed, etc.)

type FilterSegmentRef

type FilterSegmentRef = sdkquery.FilterSegmentRef

Re-export SDK types so existing callers continue to compile.

type FilterSegmentVariable

type FilterSegmentVariable = sdkquery.FilterSegmentVariable

Re-export SDK types so existing callers continue to compile.

type FunctionExecuteOptions

type FunctionExecuteOptions struct {
	// For app functions
	AppID        string
	FunctionName string
	Method       string
	Payload      string
	PayloadFile  string

	// For ad-hoc execution
	SourceCode     string
	SourceCodeFile string
	// SDKMajorVersions pins SDK packages for ad-hoc execution. nil leaves
	// sdkMajorVersions out of the request; a non-nil empty map sends {}. The
	// function executor accepts pins only for ad-hoc code, so the option is
	// not used for an app function; the command rejects that combination
	// before it gets here.
	SDKMajorVersions map[string]string

	// For deferred execution
	Defer bool
}

FunctionExecuteOptions contains options for function execution

type FunctionExecutor

type FunctionExecutor struct {
	// contains filtered or unexported fields
}

FunctionExecutor handles function execution

func NewFunctionExecutor

func NewFunctionExecutor(c *client.Client) *FunctionExecutor

NewFunctionExecutor creates a new function executor

func (*FunctionExecutor) Execute

func (e *FunctionExecutor) Execute(opts FunctionExecuteOptions) (interface{}, error)

Execute executes a function based on the provided options

func (*FunctionExecutor) GetSDKVersions

func (e *FunctionExecutor) GetSDKVersions() (*appengine.SDKVersionsResponse, error)

GetSDKVersions returns available SDK versions for the function executor

func (*FunctionExecutor) WithVFS

func (e *FunctionExecutor) WithVFS(env vfs.Env) *FunctionExecutor

WithVFS sets the filesystem and stdin the executor reads code and payload files from. The zero Env keeps the process's.

type GrailMetadata

type GrailMetadata = sdkquery.GrailMetadata

Re-export SDK types so existing callers continue to compile.

type MetadataNotification

type MetadataNotification = sdkquery.VerifyNotification

Re-export SDK types so existing callers continue to compile.

type MetricInfo

type MetricInfo = sdkquery.MetricInfo

Re-export SDK types so existing callers continue to compile.

type Position

type Position = sdkquery.Position

Re-export SDK types so existing callers continue to compile.

type QueryError

type QueryError = sdkquery.QueryError

Re-export SDK types so existing callers continue to compile.

type QueryNotification

type QueryNotification = sdkquery.Notification

Re-export SDK types so existing callers continue to compile.

type QueryStateError

type QueryStateError = sdkquery.StateError

Re-export SDK types so existing callers continue to compile.

type ScopeNeed

type ScopeNeed struct {
	Scope   string
	Because []string
}

ScopeNeed is one Grail storage scope a DQL query provably needs, with the parts of the query that need it (e.g. "fetch logs", "getNodeName()").

func RequiredStorageScopes

func RequiredStorageScopes(query string) []ScopeNeed

RequiredStorageScopes returns the storage scopes the query provably needs, sorted by scope. It is deliberately a lower bound: it recognizes only the commands, data objects and functions whose scope is certain, ignores text in string literals, comments and backtick identifiers, and returns nothing for a query it cannot tokenize. A scope missing from the answer does not mean the query can run; a scope in it means the query cannot run without it.

type SpillMode

type SpillMode string

SpillMode is the tri-state core spill control (D4).

const (
	// SpillNever forces rows inline regardless of size (the bare-command
	// default; the explicit "give me rows anyway" override).
	SpillNever SpillMode = "never"
	// SpillAuto spills above the threshold and stays inline below (the agent
	// default).
	SpillAuto SpillMode = "auto"
	// SpillAlways always spills (bare --spill, and implied by --spill-to).
	SpillAlways SpillMode = "always"
)

type SpillOptions

type SpillOptions struct {
	Mode SpillMode
	// ToPath is an explicit caller-chosen destination (--spill-to). When set the
	// file is written exactly there, the format is inferred from the extension,
	// and the location opts out of the managed privacy guarantees (D25).
	ToPath string
	// Dir is a preferred managed base dir (config spill.dir / DTCTL_SPILL_DIR).
	// Empty means use the OS user cache dir default (D7). A non-empty Dir is a
	// user-chosen location and also opts out of managed privacy (D25).
	Dir string
	// Format is the spill file format (json|csv for PR2; ndjson/parquet once the
	// dedicated writers land). Ignored when ToPath sets it via extension.
	Format    string
	Threshold int64
	TTL       time.Duration
}

SpillOptions are the fully-resolved spill settings threaded into a query execution. Resolution (flag → env → context-config → global-config → default, D15) happens in the command layer; by the time it reaches here every field is concrete.

func (SpillOptions) Enabled

func (o SpillOptions) Enabled() bool

Enabled reports whether spilling can occur at all (mode is not never).

type SyntaxPosition

type SyntaxPosition = sdkquery.SyntaxPosition

Re-export SDK types so existing callers continue to compile.

type TimeseriesPoint

type TimeseriesPoint struct {
	Value     float64
	Timestamp time.Time
}

TimeseriesPoint represents a numeric datapoint with its timestamp.

func ExtractLatestPointFromTimeseries

func ExtractLatestPointFromTimeseries(records []map[string]interface{}, field string) (TimeseriesPoint, bool)

ExtractLatestPointFromTimeseries returns the latest non-null numeric point for a timeseries field.

type UsageRecorder

type UsageRecorder interface {
	RecordQuery(usage.Sample)
}

UsageRecorder receives one sample per DQL execution: the scan totals the backend reported, whether or not the query succeeded. It must not block or fail the query; usage.Recorder is the ledger-backed implementation.

type WaitOptions

type WaitOptions struct {
	PollInterval time.Duration
	Timeout      time.Duration
}

WaitOptions configures the wait behavior

func DefaultWaitOptions

func DefaultWaitOptions() WaitOptions

DefaultWaitOptions returns sensible defaults for waiting

type WorkflowExecutionRequest

type WorkflowExecutionRequest struct {
	Input   map[string]any         `json:"input,omitempty"`
	Params  map[string]interface{} `json:"params,omitempty"`
	Monitor bool                   `json:"-"`
}

WorkflowExecutionRequest represents a workflow execution request

type WorkflowExecutionResponse

type WorkflowExecutionResponse struct {
	ID       string `json:"id"`
	Workflow string `json:"workflow"`
	State    string `json:"state"`
}

WorkflowExecutionResponse represents a workflow execution response

type WorkflowExecutor

type WorkflowExecutor struct {
	// contains filtered or unexported fields
}

WorkflowExecutor handles workflow execution

func NewWorkflowExecutor

func NewWorkflowExecutor(c *client.Client) *WorkflowExecutor

NewWorkflowExecutor creates a new workflow executor

func (*WorkflowExecutor) Execute

Execute executes a workflow

func (*WorkflowExecutor) GetStatus

func (e *WorkflowExecutor) GetStatus(executionID string) (*ExecutionStatus, error)

GetStatus retrieves the current status of an execution

func (*WorkflowExecutor) WaitForCompletion

func (e *WorkflowExecutor) WaitForCompletion(ctx context.Context, executionID string, opts WaitOptions) (*ExecutionStatus, error)

WaitForCompletion polls the execution status until it reaches a terminal state

Jump to

Keyboard shortcuts

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