target

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: ISC Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// HostKeyPolicyAcceptNew verifies against KnownHostsFile; an unknown host
	// is trusted on first use and its key is appended to the file, while a
	// known host with a mismatched key is rejected. This is the default.
	HostKeyPolicyAcceptNew = "accept-new"
	// HostKeyPolicyStrict verifies against KnownHostsFile only; both unknown
	// hosts and mismatched keys are rejected.
	HostKeyPolicyStrict = "strict"
	// HostKeyPolicyInsecure disables host-key verification entirely.
	HostKeyPolicyInsecure = "insecure"
)

Host-key verification policies for SSHConfig.HostKeyPolicy.

Variables

View Source
var ErrEnsureNotHandled = errors.New("ensure not handled")

ErrEnsureNotHandled is returned by EnsureModule.Ensure to signal that it cannot handle the given params and the caller should fall back to the standard Check+Apply path.

Functions

func CatalogKnownModule

func CatalogKnownModule(name string) bool

CatalogKnownModule reports whether name is a catalog built-in module.

func CatalogNames

func CatalogNames(cap Capability) []string

CatalogNames returns module names whose capability includes the given mask.

func CatalogRequiresRoot

func CatalogRequiresRoot(name string) bool

CatalogRequiresRoot reports whether the catalog marks name as requiring an effective root user on POSIX. Root-requiring modules fail before Check() when the effective execution user is not root — enforced by the shared execution layer, not by individual modules. An unknown module returns false (it is handled as unknown elsewhere).

func CatalogSet

func CatalogSet(cap Capability) map[string]struct{}

CatalogSet returns a set of module names whose capability includes the given mask.

func CatalogSupportsRuntime

func CatalogSupportsRuntime(name string, kind RuntimeKind) bool

CatalogSupportsRuntime reports whether the catalog marks name as supported on the given runtime kind.

func IsKnownModule

func IsKnownModule(name string, controllerRegistry ModuleRegistry) bool

IsKnownModule reports whether name is a catalog built-in or present in the controller registry (i.e. a discovered plugin). It is the plan-time name-check shared by every transport.

func IsPluginModule

func IsPluginModule(name string, controllerRegistry ModuleRegistry) bool

IsPluginModule reports whether name is a discovered plugin in the controller registry. Plugins bypass the runtime support matrix: controller-side execution makes them supported on every runtime.

func IsUnreachable

func IsUnreachable(err error) bool

IsUnreachable reports whether err represents a failure to reach the target at all, rather than a failure of some operation on an already-reachable target. Used to classify apply-start connection failures as target_unreachable in the run log instead of a generic target/task failure. See wrapUnreachable for why errors.Is is safe here where Op-string inspection was not.

func NewSDKModuleAdapter

func NewSDKModuleAdapter(name string, mod Module) sdk.Module

func NormalizeArchitecture

func NormalizeArchitecture(raw string) string

NormalizeArchitecture converts common operating-system architecture names to the Go architecture names used by platform declarations and bundles.

func ReasonCodeForError

func ReasonCodeForError(err error) string

ReasonCodeForError extracts a stable reason code from an error chain. It recognizes *ModuleSupportError and *BecomeEnvError; other errors return the empty string so callers can leave the reason field absent for untyped failures.

func ValidateModuleForPlan

func ValidateModuleForPlan(module string, kind RuntimeKind, kindKnown bool, controllerRegistry ModuleRegistry) error

ValidateModuleForPlan checks a module name against the catalog matrix and controller registry at plan time. It returns a *ModuleSupportError when the module is unknown or (for transports with a knowable runtime) unsupported on the target's runtime. Plugins bypass the runtime check.

When kindKnown is false (SSH), only the unknown-module name-check runs.

func ValidateModuleForRuntime

func ValidateModuleForRuntime(module string, kind RuntimeKind, controllerRegistry ModuleRegistry) error

ValidateModuleForRuntime validates a module against the runtime kind resolved at apply-start by Info(). The runtime is always known by then, so the full matrix check runs — unlike ValidateModuleForPlan, which can only name-check transports whose runtime is unknown until probe (SSH). Plugins bypass the matrix: controller-side execution makes them supported on every runtime. The apply-start support gate calls this for every runnable task.

Types

type ApplyResult

type ApplyResult struct {
	// Message is an optional human-readable summary. When non-empty it
	// overrides the runner's default "change applied" message.
	Message string
}

ApplyResult is the outcome of a module's Apply method.

type BecomeEnvClass

type BecomeEnvClass string

BecomeEnvClass enumerates the environment-prerequisite failures raised before Check() when a task needs privileges the target does not provide. These join the §7 reason taxonomy as run-log reason codes.

const (
	// ClassRequiresRootViolation: a requires_root module was run with an
	// effective user that is not root. The task must run as root or via
	// become to root.
	ClassRequiresRootViolation BecomeEnvClass = "requires-root-violation"
	// ClassSudoMissing: become is enabled on POSIX but the sudo binary is
	// not present on the target. sudo is required only when become is used.
	ClassSudoMissing BecomeEnvClass = "sudo-missing"
	// ClassSudoPasswordRequired: the no-password sudo wrap (sudo -n) failed
	// because sudo requires a password and none was supplied. Deterministic
	// fail-fast so a password prompt never hangs the run.
	ClassSudoPasswordRequired BecomeEnvClass = "sudo-password-required"
	// ClassSudoAuthFailed: sudo rejected the supplied password (bad
	// password, locked account, etc.).
	ClassSudoAuthFailed BecomeEnvClass = "sudo-auth-failed"
)

type BecomeEnvError

type BecomeEnvError struct {
	Class       BecomeEnvClass
	Module      string // empty for non-module errors (e.g. sudo-missing)
	RuntimeKind RuntimeKind
}

BecomeEnvError is the typed error for POSIX privilege-escalation environment failures. It carries the target's runtime kind and a class that doubles as the run-log reason code. Every transport constructs and renders it the same way via ReasonCodeForError.

func NewRequiresRootViolationError

func NewRequiresRootViolationError(module string, kind RuntimeKind) *BecomeEnvError

NewRequiresRootViolationError constructs a requires-root-violation error for a requires_root module run with a non-root effective user. The wording names the module and offers both fixes: run as root, or set become.

func NewSudoAuthFailedError

func NewSudoAuthFailedError(kind RuntimeKind) *BecomeEnvError

NewSudoAuthFailedError constructs a sudo-auth-failed error for a sudo run that rejected the supplied password.

func NewSudoMissingError

func NewSudoMissingError(kind RuntimeKind) *BecomeEnvError

NewSudoMissingError constructs a sudo-missing error for a POSIX target with become enabled but no sudo binary.

func NewSudoPasswordRequiredError

func NewSudoPasswordRequiredError(kind RuntimeKind) *BecomeEnvError

NewSudoPasswordRequiredError constructs a sudo-password-required error for a no-password sudo wrap that failed because sudo wanted a password.

func (*BecomeEnvError) Error

func (e *BecomeEnvError) Error() string

Error renders a uniform message. The requires-root class names the module and offers both fixes; the sudo classes name what failed.

func (*BecomeEnvError) ReasonCode

func (e *BecomeEnvError) ReasonCode() string

ReasonCode returns the stable run-log reason code for this error.

type BecomeOptions

type BecomeOptions struct {
	Enabled     bool   `json:"enabled,omitempty"`
	User        string `json:"user,omitempty"`
	Password    string `json:"password,omitempty"`
	Method      string `json:"method,omitempty"`
	LoadProfile *bool  `json:"load_profile,omitempty"`
}

BecomeOptions describe task execution under another user identity.

type Capability

type Capability uint8

Capability describes which runtimes and environments a built-in module can execute in.

const (
	CapabilityInline         Capability = 1 << iota // usable as an inline YAML field in a task
	CapabilityRemote                                // usable over a remote transport (SSH, WinRM)
	CapabilityBuiltinCommon                         // available on any platform
	CapabilityBuiltinWindows                        // Windows-only
	CapabilityBuiltinPOSIX                          // POSIX-only (posix-shell runtime)
)

type CheckResult

type CheckResult struct {
	// NeedsChange reports whether Apply must run to bring the system to the
	// desired state.
	NeedsChange bool
	// Message is an optional human-readable summary. When non-empty it
	// overrides the runner's default status message ("already in desired
	// state" or "would apply change (dry-run)").
	Message string
}

CheckResult is the outcome of a module's Check method.

type EnsureModule

type EnsureModule interface {
	Module
	Ensure(ctx context.Context, params map[string]any, dryRun bool, out OutputFunc) (EnsureResult, error)
}

EnsureModule is an optional capability for modules that can combine Check and Apply into a single round trip. Worthwhile on high-latency transports (e.g. WinRM) where two separate invocations double overhead. Implementations may return ErrEnsureNotHandled to fall back to the standard Check+Apply path (e.g. when params don't support the fast path).

type EnsureResult

type EnsureResult struct {
	// Changed reports whether the module made (or, in dry-run, would have
	// made) a change.
	Changed bool
	// Message is an optional human-readable summary.
	Message string
}

EnsureResult is the outcome of an ensure single-round-trip operation.

type ExecResult

type ExecResult struct {
	Stdout   string
	Stderr   string
	ExitCode int
}

ExecResult is the outcome of a TargetOps.Exec call: the script runs in the target's native shell (POSIX sh or PowerShell per TargetInfo.RuntimeKind) and returns separated stdout/stderr and the exit code.

type ExecutionOptions

type ExecutionOptions struct {
	Become *BecomeOptions `json:"become,omitempty"`
}

ExecutionOptions are task-level execution settings applied outside module params.

func NormalizeExecutionOptions

func NormalizeExecutionOptions(raw map[string]any) (ExecutionOptions, error)

NormalizeExecutionOptions validates a rendered execution-options map.

func (ExecutionOptions) Enabled

func (o ExecutionOptions) Enabled() bool

Enabled reports whether task execution should switch identity.

func (ExecutionOptions) ToMap

func (o ExecutionOptions) ToMap() map[string]any

ToMap converts the execution options back to a generic map for hashing and staging.

type LocalTarget

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

LocalTarget executes modules in-process on the local machine.

func NewLocalTarget

func NewLocalTarget(registry ModuleRegistry) *LocalTarget

NewLocalTarget creates a LocalTarget backed by the given registry.

func (*LocalTarget) Close

func (t *LocalTarget) Close() error

Close releases any module-level resources owned by this target instance. Idempotent: subsequent calls are no-ops once the registry has been drained.

func (*LocalTarget) CopyFile

func (t *LocalTarget) CopyFile(_ context.Context, src, dst string) error

CopyFile copies src (local path) to dst (local path), preserving file permissions.

func (*LocalTarget) Exec

func (t *LocalTarget) Exec(ctx context.Context, script string) (ExecResult, error)

Exec implements TargetOps: runs script in the target's native shell (POSIX sh or PowerShell per runtimeKindForLocal) and returns separated stdout/stderr and the exit code.

func (*LocalTarget) Execute

func (t *LocalTarget) Execute(ctx context.Context, taskID string, module string, params map[string]any, opts ExecutionOptions, dryRun bool, onOutput OutputFunc) (Result, error)

Execute looks up the named module and dispatches through the unified executeModule executor. Both the in-process registry path (no become) and the become-via-subprocess path share one executor, since both produce ModuleRegistry values whose entries satisfy the same Module interface.

func (*LocalTarget) GetFile

func (t *LocalTarget) GetFile(ctx context.Context, path string) ([]byte, error)

GetFile implements TargetOps: reads the contents of path on the local machine. The plugin's target effects flow through the handle even locally.

func (*LocalTarget) Info

func (t *LocalTarget) Info(ctx context.Context) (TargetInfo, error)

Info returns basic facts about the local machine. On POSIX hosts the cached runtime detection probe is used so Info() and the facts gatherer share one detection path; on Windows the probe is not applicable and the Go-runtime values are used directly.

func (*LocalTarget) PutFile

func (t *LocalTarget) PutFile(_ context.Context, path string, data []byte) error

PutFile implements TargetOps: writes data to path on the local machine.

func (*LocalTarget) Reachable

func (t *LocalTarget) Reachable(_ context.Context) (bool, error)

Reachable always returns true for the local target.

func (*LocalTarget) ReadFile

func (t *LocalTarget) ReadFile(_ context.Context, path string) ([]byte, error)

ReadFile reads and returns the contents of path on the local machine.

func (*LocalTarget) RunPowerShell

func (t *LocalTarget) RunPowerShell(ctx context.Context, script string) (string, error)

RunPowerShell executes a PowerShell script on the local machine.

func (*LocalTarget) Transport

func (t *LocalTarget) Transport() Transport

Transport identifies the local target connection type.

type Module

type Module interface {
	Check(ctx context.Context, params map[string]any, out OutputFunc) (CheckResult, error)
	Apply(ctx context.Context, params map[string]any, out OutputFunc) (ApplyResult, error)
}

Module is the interface implemented by all built-in modules, plugin adapters, and remote-execution closures. A single contract replaces what used to be three parallel ones (in-process Module, target.remoteModule, optional CheckStreamingModule / StreamingModule upgrades).

Output streaming is part of the main signature: implementations call out(line) for each line they want to surface; callers pass nil when they do not care. Modules that do not stream simply ignore the OutputFunc.

type ModuleRegistry

type ModuleRegistry map[string]Module

ModuleRegistry maps module names to their implementations.

func (ModuleRegistry) Lookup

func (r ModuleRegistry) Lookup(name string) (Module, bool)

Lookup returns the Module registered under name, and whether it was found.

type ModuleSupportClass

type ModuleSupportClass string

ModuleSupportClass enumerates the reasons a module cannot run on a target. Every transport surfaces the same set so error wording and run-log reason codes stay uniform across local, SSH, and WinRM.

const (
	// ClassUnknownModule: the module name is neither a catalog built-in nor a
	// discovered plugin.
	ClassUnknownModule ModuleSupportClass = "unknown_module"
	// ClassUnsupportedOnRuntime: a catalog built-in that is not supported on
	// the target's runtime. SupportedRuntimes lists where it does run.
	ClassUnsupportedOnRuntime ModuleSupportClass = "unsupported_on_runtime"
	// ClassMissingPrerequisite: the module is supported on this runtime in
	// principle but an environment prerequisite is absent (e.g. no pwsh
	// binary for the powershell module on posix-shell). Detail names it.
	ClassMissingPrerequisite ModuleSupportClass = "missing_prerequisite"
	// ClassPluginBecome: a plugin module was invoked with become enabled;
	// plugin+become is refused.
	ClassPluginBecome ModuleSupportClass = "plugin_become"
	// ClassPluginProtocol: a plugin failed the protocol handshake (version
	// mismatch / pre-v1 plugin rejected).
	ClassPluginProtocol ModuleSupportClass = "plugin_protocol"
)

type ModuleSupportError

type ModuleSupportError struct {
	Class             ModuleSupportClass
	Module            string
	RuntimeKind       RuntimeKind
	SupportedRuntimes []RuntimeKind
	Detail            string
}

ModuleSupportError is the single typed error for module-by-runtime gaps. It carries the module name, the target's runtime kind (when known), and the runtimes that do support the module (for the unsupported class). Every transport constructs and renders it the same way.

func NewMissingPrerequisiteError

func NewMissingPrerequisiteError(module string, kind RuntimeKind, detail string) *ModuleSupportError

NewMissingPrerequisiteError constructs a missing_prerequisite error.

func NewPluginBecomeError

func NewPluginBecomeError(module string) *ModuleSupportError

NewPluginBecomeError constructs a plugin_become error.

func NewPluginProtocolError

func NewPluginProtocolError(module string, detail string) *ModuleSupportError

NewPluginProtocolError constructs a plugin_protocol error.

func NewUnknownModuleError

func NewUnknownModuleError(module string) *ModuleSupportError

NewUnknownModuleError constructs an unknown_module error. RuntimeKind is unknown because the module was never recognized.

func NewUnsupportedOnRuntimeError

func NewUnsupportedOnRuntimeError(module string, kind RuntimeKind) *ModuleSupportError

NewUnsupportedOnRuntimeError constructs an unsupported_on_runtime error for a catalog built-in, deriving the supporting runtimes from the catalog.

func (*ModuleSupportError) Error

func (e *ModuleSupportError) Error() string

Error renders a uniform, prose-free message. Every class names the module; unsupported_on_runtime also names the target runtime and the supporting runtimes. No did-you-mean, no remediation.

func (*ModuleSupportError) ReasonCode

func (e *ModuleSupportError) ReasonCode() string

ReasonCode returns the stable run-log reason code for this error.

type OSFamily

type OSFamily string

OSFamily is a normalized operating-system family used for behavior checks.

const (
	OSFamilyUnknown OSFamily = "unknown"
	OSFamilyWindows OSFamily = "windows"
	OSFamilyLinux   OSFamily = "linux"
	OSFamilyDarwin  OSFamily = "darwin"
)

type OutputFunc

type OutputFunc func(line string)

OutputFunc is a callback invoked with each line of output emitted by a module during execution.

var NoOutput OutputFunc

NoOutput is a nil OutputFunc that can be passed to modules which do not produce streaming output. Passing nil directly is equivalent; this named form makes the intent explicit at call sites and in tests.

type Platform

type Platform struct {
	OS   OSFamily `json:"os" yaml:"os"`
	Arch string   `json:"arch" yaml:"arch"`
}

Platform identifies the operating system family and architecture a staged bundle will execute on. Inventory declarations use this when the target cannot be probed during staging.

func (Platform) RuntimeKind

func (p Platform) RuntimeKind() (RuntimeKind, bool)

RuntimeKind derives the module runtime used by a declared destination platform. Inventory schema validation keeps declarations within the known OS families; false protects programmatic callers from an unknown value.

type PluggableModule

type PluggableModule interface {
	Module
	// PluginPath is the path to the backing plugin executable.
	PluginPath() string
	// BindTarget returns a fresh adapter bound to the given target ops backend.
	// The returned Module owns its own client state; the receiver stays unbound
	// so another target can bind it independently.
	BindTarget(ops TargetOps) Module
}

PluggableModule is implemented by modules that delegate to an out-of-process adapter (typically a preflight plugin executable). Targets clone these per-instance so each target gets its own adapter client state, and transports that cannot delegate to an external process consult this interface for clearer "not supported on this transport" diagnostics.

type PowerShellRunner

type PowerShellRunner interface {
	RunPowerShell(ctx context.Context, script string) (string, error)
}

PowerShellRunner is implemented by targets that can execute an inline PowerShell script. Callers that need PowerShell (e.g. Windows fact gathering) consult this capability rather than assuming every target supports it. Non-Windows transports that genuinely cannot reach a PowerShell host need not implement it.

type Probe

type Probe struct {
	Hostname       string
	Kernel         string // uname -s
	Arch           string // uname -m
	OSName         string // os-release ID (e.g. "ubuntu", "rocky")
	OSVersion      string // os-release VERSION_ID
	PackageManager string // "apt" | "dnf" | ""
	Init           string // "systemd" | ""

	// EffectiveUID is the numeric effective user id of the session user (id -u).
	// Internal runtime state, not exposed as facts in v1. Used by the
	// requires_root pre-Check() probe to fail fast when a root-requiring module
	// runs as a non-root user without become.
	EffectiveUID string
	// SudoAvailable reports whether the sudo binary is present on the target
	// (command -v sudo). Internal runtime state, not exposed as facts. Used to
	// raise sudo-missing before a become run attempts to invoke sudo.
	SudoAvailable bool
}

Probe holds the lazily-collected POSIX runtime detection signals for a target. One probe runs per target per run; it is cached so that Info() and the facts gatherer read the same result without re-probing, leaving no second detection path.

Absent signals are empty strings: a missing source (e.g. no os-release on macOS, no supported package manager) empties that field without failing the probe. Only a transport-level failure errors, via the existing Info() error path.

This struct is also the future home of the effective-uid / sudo-availability ticket (internal runtime state, not exposed as facts) and the enriched TargetInfo handed to plugins.

type Result

type Result struct {
	TaskID  string
	Status  Status
	Message string
	Output  []string
	Error   error
}

Result holds the outcome of a single task execution.

type RoundTripCounter

type RoundTripCounter interface {
	RoundTripCount() int64
}

RoundTripCounter is optionally implemented by targets that can report the number of transport round-trips made during execution. The count is surfaced in the run log and under -v as a performance-tuning observable.

type RuntimeKind

type RuntimeKind string
const (
	RuntimeKindWindowsPowerShell RuntimeKind = "windows-powershell"
	RuntimeKindPOSIXShell        RuntimeKind = "posix-shell"
)

func CatalogSupportedRuntimes

func CatalogSupportedRuntimes(name string) []RuntimeKind

CatalogSupportedRuntimes returns the runtime kinds the catalog marks as supporting the named module. BuiltinCommon modules run on both windows-powershell and posix-shell; BuiltinWindows modules run on windows-powershell only. An unknown module returns nil.

func PlanRuntimeForTransport

func PlanRuntimeForTransport(t Transport) (RuntimeKind, bool)

PlanRuntimeForTransport returns the runtime kind a transport implies at plan time, before any remote probe. WinRM is always windows-powershell and local is GOOS-derived; both are knowable offline. SSH returns ok=false because its runtime is only known after probing the remote host — plan-time can only name-check SSH tasks.

type SSHConfig

type SSHConfig struct {
	Host       string
	Port       int
	Username   string
	Password   string
	PrivateKey string
	// PrivateKeyPassphrase is the passphrase for an encrypted PrivateKey.
	PrivateKeyPassphrase string
	// KnownHostsFile is the path to a known_hosts file used to verify the
	// remote host key, per HostKeyPolicy. When empty, it defaults to
	// known_hosts under sshUserKeyDir (normally ~/.ssh/known_hosts).
	KnownHostsFile string
	// HostKeyPolicy controls how the remote host key is verified. Valid
	// values are HostKeyPolicyAcceptNew (default), HostKeyPolicyStrict, and
	// HostKeyPolicyInsecure. Any other non-empty value is a configuration
	// error.
	HostKeyPolicy string
	// HostKeyAlgorithms restricts the accepted host key algorithms during the
	// SSH handshake. When nil, the SSH client library's built-in default
	// host-key algorithm list is used. This field applies regardless of
	// HostKeyPolicy.
	HostKeyAlgorithms []string
	// Timeout bounds both the TCP connect and the SSH handshake. Zero means
	// the 30s default (defaultSSHTimeout) is used.
	Timeout time.Duration
	// Jump, when set, configures a single-hop SSH bastion (a ProxyJump) to
	// dial through before reaching Host. The jump host has its own
	// independent auth and host-key policy; it does not inherit anything
	// from the target config it fronts. Jump.Jump must be nil — nested
	// (multi-hop) bastions are not supported.
	Jump *SSHConfig
}

type SSHTarget

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

SSHTarget communicates with a remote machine over SSH.

func NewSSHTarget

func NewSSHTarget(cfg SSHConfig, registry ModuleRegistry) *SSHTarget

func (*SSHTarget) Close

func (t *SSHTarget) Close() error

func (*SSHTarget) Config

func (t *SSHTarget) Config() SSHConfig

Config returns the SSHConfig that was used to construct this target.

func (*SSHTarget) CopyFile

func (t *SSHTarget) CopyFile(ctx context.Context, src, dst string) error

func (*SSHTarget) Exec

func (t *SSHTarget) Exec(ctx context.Context, script string) (ExecResult, error)

Exec implements TargetOps: runs script in the target's native shell (POSIX sh or PowerShell per the detected runtime) and returns separated stdout/stderr and the exit code. A non-zero exit is a result, not an error.

func (*SSHTarget) Execute

func (t *SSHTarget) Execute(ctx context.Context, taskID string, module string, params map[string]any, opts ExecutionOptions, dryRun bool, onOutput OutputFunc) (Result, error)

func (*SSHTarget) GetFile

func (t *SSHTarget) GetFile(ctx context.Context, path string) ([]byte, error)

GetFile implements TargetOps: reads the contents of path on the remote host. The plugin's target effects flow through the handle even remotely.

func (*SSHTarget) Info

func (t *SSHTarget) Info(ctx context.Context) (TargetInfo, error)

func (*SSHTarget) PutFile

func (t *SSHTarget) PutFile(ctx context.Context, path string, data []byte) error

PutFile implements TargetOps: writes data to path on the remote host, creating parent directories as needed. Dispatches to the detected runtime.

func (*SSHTarget) Reachable

func (t *SSHTarget) Reachable(ctx context.Context) (bool, error)

func (*SSHTarget) ReadFile

func (t *SSHTarget) ReadFile(ctx context.Context, path string) ([]byte, error)

func (*SSHTarget) RunPowerShell

func (t *SSHTarget) RunPowerShell(ctx context.Context, script string) (string, error)

func (*SSHTarget) Transport

func (t *SSHTarget) Transport() Transport

type Status

type Status string

Status represents the outcome of a task execution.

const (
	StatusOK      Status = "ok"
	StatusChanged Status = "changed"
	StatusFailed  Status = "failed"
	StatusSkipped Status = "skipped"
)

type Target

type Target interface {
	// Execute runs a named module with the given params against the target.
	// If dryRun is true, only Check() is called — no changes are made.
	Execute(ctx context.Context, taskID string, module string, params map[string]any, opts ExecutionOptions, dryRun bool, onOutput OutputFunc) (Result, error)

	// Info returns basic facts about the target machine.
	Info(ctx context.Context) (TargetInfo, error)

	// Transport returns the connection type used to reach the target.
	Transport() Transport
}

Target is the central abstraction for all operations against a machine. The runner is always injected with a Target and never assumes local execution.

type TargetInfo

type TargetInfo struct {
	Hostname       string
	OSVersion      string
	OSBuild        string
	OSName         string // os-release ID on POSIX; friendly name on Windows
	Arch           string
	OSFamily       OSFamily
	PackageManager string // apt | dnf | "" (POSIX only)
	Init           string // systemd | "" (POSIX only)
	RuntimeKind    RuntimeKind
	Transport      Transport
}

TargetInfo holds basic facts about a target machine.

POSIX fields (OSName, PackageManager, Init) are populated by the cached runtime detection probe and are empty on Windows. Plugins receive this struct so they branch on enriched OS facts without re-detecting.

RuntimeKind is the resolved runtime the target's modules speak (windows-powershell or posix-shell), set by every Info() implementation after the runtime is probed. The apply-start support gate reads it to validate every runnable task against the support matrix.

func (TargetInfo) IsLocal

func (i TargetInfo) IsLocal() bool

IsLocal reports whether the target is the controller machine.

func (TargetInfo) IsWindows

func (i TargetInfo) IsWindows() bool

IsWindows reports whether the target belongs to the Windows OS family.

type TargetOps

type TargetOps interface {
	Exec(ctx context.Context, script string) (ExecResult, error)
	PutFile(ctx context.Context, path string, data []byte) error
	GetFile(ctx context.Context, path string) ([]byte, error)
	Info(ctx context.Context) (TargetInfo, error)
}

TargetOps is the backend a plugin handle binds to. Every transport implements it (Local, SSH-POSIX, SSH-Windows, WinRM). The plugin's target effects all flow through it — including against the local target — so plugins are brought in line with first-class modules. Info returns the same enriched TargetInfo delivered to a plugin at initialize.

type Transport

type Transport string

Transport identifies how the controller reaches a target.

const (
	TransportLocal Transport = "local"
	TransportSSH   Transport = "ssh"
	TransportWinRM Transport = "winrm"
)

type WinRMConfig

type WinRMConfig struct {
	Host     string
	Port     int
	Username string
	Password string
	HTTPS    bool
	Insecure bool
	Timeout  time.Duration
}

type WinRMTarget

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

WinRMTarget communicates with a remote Windows machine via WinRM.

func NewWinRMTarget

func NewWinRMTarget(cfg WinRMConfig, registry ModuleRegistry) *WinRMTarget

func (*WinRMTarget) Close

func (t *WinRMTarget) Close() error

Close releases the persistent PS session if one was created and tears down any lazily-spawned plugin subprocesses bound to this target. The underlying WinRM connection is managed by the client and is not explicitly closed.

func (*WinRMTarget) CopyFile

func (t *WinRMTarget) CopyFile(ctx context.Context, src, dst string) error

func (*WinRMTarget) Exec

func (t *WinRMTarget) Exec(ctx context.Context, script string) (ExecResult, error)

Exec implements TargetOps: runs script in the target's native PowerShell and returns separated stdout/stderr and the exit code. A non-zero exit is a result, not an error. Uses the per-invocation path (not the persistent session) because plugin scripts may call `exit N`, which is incompatible with a persistent PowerShell REPL (a non-zero exit kills the host process). The winrm library drains stdout and stderr concurrently, so this path respects the channel discipline without a long-lived shell to keepalive.

func (*WinRMTarget) Execute

func (t *WinRMTarget) Execute(ctx context.Context, taskID string, module string, params map[string]any, opts ExecutionOptions, dryRun bool, onOutput OutputFunc) (Result, error)

func (*WinRMTarget) GetFile

func (t *WinRMTarget) GetFile(ctx context.Context, path string) ([]byte, error)

GetFile implements TargetOps: reads the contents of path on the remote host.

func (*WinRMTarget) Info

func (t *WinRMTarget) Info(ctx context.Context) (TargetInfo, error)

func (*WinRMTarget) PutFile

func (t *WinRMTarget) PutFile(ctx context.Context, path string, data []byte) error

PutFile implements TargetOps: writes data to path on the remote host, creating parent directories as needed. Reuses the chunked upload machinery (32 KiB chunks over the persistent session, 1.5 KiB fallback), respecting the WinRM envelope limit and concurrent-stderr-drain discipline.

func (*WinRMTarget) Reachable

func (t *WinRMTarget) Reachable(ctx context.Context) (bool, error)

func (*WinRMTarget) ReadFile

func (t *WinRMTarget) ReadFile(ctx context.Context, path string) ([]byte, error)

func (*WinRMTarget) RemoteTempDir

func (t *WinRMTarget) RemoteTempDir() string

func (*WinRMTarget) RoundTripCount

func (t *WinRMTarget) RoundTripCount() int64

RoundTripCount returns the number of WinRM round-trips made so far. It is safe to call concurrently and can be queried at any point during or after execution.

func (*WinRMTarget) RunPowerShell

func (t *WinRMTarget) RunPowerShell(ctx context.Context, script string) (string, error)

func (*WinRMTarget) RunPowerShellScript

func (t *WinRMTarget) RunPowerShellScript(ctx context.Context, script string) (string, error)

func (*WinRMTarget) Transport

func (t *WinRMTarget) Transport() Transport

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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