agentsdk

package
v2.10.2 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: AGPL-3.0 Imports: 29 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ExternalLogSourceID = uuid.MustParse("3b579bf4-1ed8-4b99-87a8-e9a1e3410410")

ExternalLogSourceID is the statically-defined ID of a log-source that appears as "External" in the dashboard.

This is to support legacy API-consumers that do not create their own log-source. This should be removed in the future.

View Source
var LogLimitExceededError = xerrors.New("Log limit exceeded")

Functions

func AgentScriptFromProto added in v2.8.0

func AgentScriptFromProto(protoScript *proto.WorkspaceAgentScript) (codersdk.WorkspaceAgentScript, error)

func AgentScriptsFromProto added in v2.8.0

func AgentScriptsFromProto(protoScripts []*proto.WorkspaceAgentScript) ([]codersdk.WorkspaceAgentScript, error)

func AppFromProto added in v2.8.0

func AppFromProto(protoApp *proto.WorkspaceApp) (codersdk.WorkspaceApp, error)

func AppHealthPoster added in v2.8.0

func AppHealthPoster(aAPI BatchUpdateAppHealthsClient) func(ctx context.Context, req PostAppHealthsRequest) error

func AppsFromProto added in v2.8.0

func AppsFromProto(protoApps []*proto.WorkspaceApp) ([]codersdk.WorkspaceApp, error)

func LifecycleStateFromProto added in v2.9.0

func LifecycleStateFromProto(s proto.Lifecycle_State) (codersdk.WorkspaceAgentLifecycle, error)

func LogsNotifyChannel

func LogsNotifyChannel(agentID uuid.UUID) string

LogsNotifyChannel returns the channel name responsible for notifying of new logs.

func LogsSender deprecated

func LogsSender(sourceID uuid.UUID, patchLogs func(ctx context.Context, req PatchLogs) error, logger slog.Logger, opts ...func(*logsSenderOptions)) (sendLog func(ctx context.Context, log ...Log) error, flushAndClose func(context.Context) error)

LogsSender will send agent startup logs to the server. Calls to sendLog are non-blocking and will return an error if flushAndClose has been called. Calling sendLog concurrently is not supported. If the context passed to flushAndClose is canceled, any remaining logs will be discarded.

Deprecated: Use NewLogSender instead, based on the v2 Agent API.

func LogsSenderFlushTimeout added in v2.3.0

func LogsSenderFlushTimeout(timeout time.Duration) func(*logsSenderOptions)

LogsSenderFlushTimeout changes the default flush timeout (250ms), this is mostly useful for tests.

func LogsWriter added in v2.2.0

func LogsWriter(ctx context.Context, sender func(ctx context.Context, log ...Log) error, source uuid.UUID, level codersdk.LogLevel) io.WriteCloser

LogsWriter returns an io.WriteCloser that sends logs via the provided sender. The sender is expected to be non-blocking. Calling Close flushes any remaining partially written log lines but is otherwise no-op. If the context passed to LogsWriter is canceled, any remaining logs will be discarded.

Neither Write nor Close is safe for concurrent use and must be used by a single goroutine.

func MetadataDescriptionFromProto added in v2.8.0

func MetadataDescriptionsFromProto added in v2.8.0

func MetadataDescriptionsFromProto(descriptions []*proto.WorkspaceAgentMetadata_Description) []codersdk.WorkspaceAgentMetadataDescription

func ProtoFromApp added in v2.8.0

func ProtoFromApp(a codersdk.WorkspaceApp) (*proto.WorkspaceApp, error)

func ProtoFromAppHealthsRequest added in v2.8.0

func ProtoFromAppHealthsRequest(req PostAppHealthsRequest) (*proto.BatchUpdateAppHealthRequest, error)

func ProtoFromApps added in v2.8.0

func ProtoFromApps(apps []codersdk.WorkspaceApp) ([]*proto.WorkspaceApp, error)

func ProtoFromLifecycle added in v2.9.0

func ProtoFromLifecycle(req PostLifecycleRequest) (*proto.Lifecycle, error)

func ProtoFromLog added in v2.9.0

func ProtoFromLog(log Log) (*proto.Log, error)

func ProtoFromManifest added in v2.8.0

func ProtoFromManifest(manifest Manifest) (*proto.Manifest, error)

func ProtoFromMetadataDescriptions added in v2.8.0

func ProtoFromMetadataDescriptions(descriptions []codersdk.WorkspaceAgentMetadataDescription) []*proto.WorkspaceAgentMetadata_Description

func ProtoFromScript added in v2.8.0

func ProtoFromScripts added in v2.8.0

func ProtoFromScripts(scripts []codersdk.WorkspaceAgentScript) []*proto.WorkspaceAgentScript

func ProtoFromServiceBanner added in v2.8.0

func ProtoFromServiceBanner(sb codersdk.ServiceBannerConfig) *proto.ServiceBanner

func ProtoFromSubsystems added in v2.8.0

func ProtoFromSubsystems(ss []codersdk.AgentSubsystem) ([]proto.Startup_Subsystem, error)

func ServiceBannerFromProto added in v2.8.0

func ServiceBannerFromProto(sbp *proto.ServiceBanner) codersdk.ServiceBannerConfig

Types

type AWSInstanceIdentityToken

type AWSInstanceIdentityToken struct {
	Signature string `json:"signature" validate:"required"`
	Document  string `json:"document" validate:"required"`
}

type AgentMetric

type AgentMetric struct {
	Name   string             `json:"name" validate:"required"`
	Type   AgentMetricType    `json:"type" validate:"required" enums:"counter,gauge"`
	Value  float64            `json:"value" validate:"required"`
	Labels []AgentMetricLabel `json:"labels,omitempty"`
}

type AgentMetricLabel

type AgentMetricLabel struct {
	Name  string `json:"name" validate:"required"`
	Value string `json:"value" validate:"required"`
}

type AgentMetricType

type AgentMetricType string
const (
	AgentMetricTypeCounter AgentMetricType = "counter"
	AgentMetricTypeGauge   AgentMetricType = "gauge"
)

type AuthenticateResponse

type AuthenticateResponse struct {
	SessionToken string `json:"session_token"`
}

AuthenticateResponse is returned when an instance ID has been exchanged for a session token. @typescript-ignore AuthenticateResponse

type AzureInstanceIdentityToken

type AzureInstanceIdentityToken struct {
	Signature string `json:"signature" validate:"required"`
	Encoding  string `json:"encoding" validate:"required"`
}

type BatchUpdateAppHealthsClient added in v2.9.0

type BatchUpdateAppHealthsClient interface {
	BatchUpdateAppHealths(ctx context.Context, req *proto.BatchUpdateAppHealthRequest) (*proto.BatchUpdateAppHealthResponse, error)
}

BatchUpdateAppHealthsClient is a partial interface of proto.DRPCAgentClient.

type Client

type Client struct {
	SDK *codersdk.Client
}

Client wraps `codersdk.Client` with specific functions scoped to a workspace agent.

func New

func New(serverURL *url.URL) *Client

New returns a client that is used to interact with the Coder API from a workspace agent.

func (*Client) AuthAWSInstanceIdentity

func (c *Client) AuthAWSInstanceIdentity(ctx context.Context) (AuthenticateResponse, error)

AuthWorkspaceAWSInstanceIdentity uses the Amazon Metadata API to fetch a signed payload, and exchange it for a session token for a workspace agent.

The requesting instance must be registered as a resource in the latest history for a workspace.

func (*Client) AuthAzureInstanceIdentity

func (c *Client) AuthAzureInstanceIdentity(ctx context.Context) (AuthenticateResponse, error)

AuthWorkspaceAzureInstanceIdentity uses the Azure Instance Metadata Service to fetch a signed payload, and exchange it for a session token for a workspace agent.

func (*Client) AuthGoogleInstanceIdentity

func (c *Client) AuthGoogleInstanceIdentity(ctx context.Context, serviceAccount string, gcpClient *metadata.Client) (AuthenticateResponse, error)

AuthWorkspaceGoogleInstanceIdentity uses the Google Compute Engine Metadata API to fetch a signed JWT, and exchange it for a session token for a workspace agent.

The requesting instance must be registered as a resource in the latest history for a workspace.

func (*Client) ConnectRPC added in v2.8.0

func (c *Client) ConnectRPC(ctx context.Context) (drpc.Conn, error)

ConnectRPC connects to the workspace agent API and tailnet API

func (*Client) ExternalAuth added in v2.3.0

func (c *Client) ExternalAuth(ctx context.Context, req ExternalAuthRequest) (ExternalAuthResponse, error)

ExternalAuth submits a URL or provider ID to fetch an access token for. nolint:revive

func (*Client) GitSSHKey

func (c *Client) GitSSHKey(ctx context.Context) (GitSSHKey, error)

GitSSHKey will return the user's SSH key pair for the workspace.

func (*Client) PatchLogs deprecated

func (c *Client) PatchLogs(ctx context.Context, req PatchLogs) error

PatchLogs writes log messages to the agent startup script. Log messages are limited to 1MB in total.

Deprecated: use the DRPCAgentClient.BatchCreateLogs instead

func (*Client) PostLifecycle deprecated

func (c *Client) PostLifecycle(ctx context.Context, req PostLifecycleRequest) error

PostLifecycle posts the agent's lifecycle to the Coder server.

Deprecated: Use UpdateLifecycle on the dRPC API instead

func (*Client) PostLogSource added in v2.2.0

func (*Client) PostMetadata deprecated

func (c *Client) PostMetadata(ctx context.Context, req PostMetadataRequest) error

PostMetadata posts agent metadata to the Coder server.

Deprecated: use BatchUpdateMetadata on the agent dRPC API instead

func (*Client) PostStats deprecated

func (c *Client) PostStats(ctx context.Context, stats *Stats) (StatsResponse, error)

PostStats sends agent stats to the coder server

Deprecated: uses agent API v1 endpoint

func (*Client) RewriteDERPMap added in v2.8.0

func (c *Client) RewriteDERPMap(derpMap *tailcfg.DERPMap)

RewriteDERPMap rewrites the DERP map to use the access URL of the SDK as the "embedded relay" access URL. The passed derp map is modified in place.

Agents can provide an arbitrary access URL that may be different that the globally configured one. This breaks the built-in DERP, which would continue to reference the global access URL.

func (*Client) SetSessionToken

func (c *Client) SetSessionToken(token string)

type ExternalAuthRequest added in v2.3.0

type ExternalAuthRequest struct {
	// ID is the ID of a provider to request authentication for.
	ID string
	// Match is an arbitrary string matched against the regex of the provider.
	Match string
	// Listen indicates that the request should be long-lived and listen for
	// a new token to be requested.
	Listen bool
}

ExternalAuthRequest is used to request an access token for a provider. Either ID or Match must be specified, but not both.

type ExternalAuthResponse added in v2.3.0

type ExternalAuthResponse struct {
	AccessToken string                 `json:"access_token"`
	TokenExtra  map[string]interface{} `json:"token_extra"`
	URL         string                 `json:"url"`
	Type        string                 `json:"type"`

	// Deprecated: Only supported on `/workspaceagents/me/gitauth`
	// for backwards compatibility.
	Username string `json:"username"`
	Password string `json:"password"`
}

type GitSSHKey

type GitSSHKey struct {
	PublicKey  string `json:"public_key"`
	PrivateKey string `json:"private_key"`
}

type GoogleInstanceIdentityToken

type GoogleInstanceIdentityToken struct {
	JSONWebToken string `json:"json_web_token" validate:"required"`
}

type Log

type Log struct {
	CreatedAt time.Time         `json:"created_at"`
	Output    string            `json:"output"`
	Level     codersdk.LogLevel `json:"level"`
}

type LogSender added in v2.9.0

type LogSender struct {
	*sync.Cond
	// contains filtered or unexported fields
}

LogSender is a component that handles enqueuing logs and then sending them over the agent API. Things that need to log call Enqueue and Flush. When the agent API becomes available, call SendLoop to send pending logs.

func NewLogSender added in v2.9.0

func NewLogSender(logger slog.Logger) *LogSender

func (*LogSender) Enqueue added in v2.9.0

func (l *LogSender) Enqueue(src uuid.UUID, logs ...Log)

func (*LogSender) Flush added in v2.9.0

func (l *LogSender) Flush(src uuid.UUID)

func (*LogSender) GetScriptLogger added in v2.9.0

func (l *LogSender) GetScriptLogger(logSourceID uuid.UUID) ScriptLogger

func (*LogSender) SendLoop added in v2.9.0

func (l *LogSender) SendLoop(ctx context.Context, dest logDest) error

SendLoop sends any pending logs until it hits an error or the context is canceled. It does not retry as it is expected that a higher layer retries establishing connection to the agent API and calls SendLoop again.

func (*LogSender) WaitUntilEmpty added in v2.9.0

func (l *LogSender) WaitUntilEmpty(ctx context.Context) error

WaitUntilEmpty waits until the LogSender's queues are empty or the given context expires.

type LogSource added in v2.2.0

type LogSource struct {
	ID          uuid.UUID `json:"id"`
	DisplayName string    `json:"display_name"`
	Icon        string    `json:"icon"`
}

type LogsNotifyMessage

type LogsNotifyMessage struct {
	CreatedAfter int64 `json:"created_after"`
}

type Manifest

type Manifest struct {
	AgentID   uuid.UUID `json:"agent_id"`
	AgentName string    `json:"agent_name"`
	// OwnerName and WorkspaceID are used by an open-source user to identify the workspace.
	// We do not provide insurance that this will not be removed in the future,
	// but if it's easy to persist lets keep it around.
	OwnerName     string    `json:"owner_name"`
	WorkspaceID   uuid.UUID `json:"workspace_id"`
	WorkspaceName string    `json:"workspace_name"`
	// GitAuthConfigs stores the number of Git configurations
	// the Coder deployment has. If this number is >0, we
	// set up special configuration in the workspace.
	GitAuthConfigs           int                                          `json:"git_auth_configs"`
	VSCodePortProxyURI       string                                       `json:"vscode_port_proxy_uri"`
	Apps                     []codersdk.WorkspaceApp                      `json:"apps"`
	DERPMap                  *tailcfg.DERPMap                             `json:"derpmap"`
	DERPForceWebSockets      bool                                         `json:"derp_force_websockets"`
	EnvironmentVariables     map[string]string                            `json:"environment_variables"`
	Directory                string                                       `json:"directory"`
	MOTDFile                 string                                       `json:"motd_file"`
	DisableDirectConnections bool                                         `json:"disable_direct_connections"`
	Metadata                 []codersdk.WorkspaceAgentMetadataDescription `json:"metadata"`
	Scripts                  []codersdk.WorkspaceAgentScript              `json:"scripts"`
}

func ManifestFromProto added in v2.8.0

func ManifestFromProto(manifest *proto.Manifest) (Manifest, error)

type Metadata added in v2.3.1

type Metadata struct {
	Key string `json:"key"`
	codersdk.WorkspaceAgentMetadataResult
}

func MetadataFromProto added in v2.9.0

func MetadataFromProto(m *proto.Metadata) Metadata

type PatchLogs

type PatchLogs struct {
	LogSourceID uuid.UUID `json:"log_source_id"`
	Logs        []Log     `json:"logs"`
}

type PostAppHealthsRequest

type PostAppHealthsRequest struct {
	// Healths is a map of the workspace app name and the health of the app.
	Healths map[uuid.UUID]codersdk.WorkspaceAppHealth
}

type PostLifecycleRequest

type PostLifecycleRequest struct {
	State     codersdk.WorkspaceAgentLifecycle `json:"state"`
	ChangedAt time.Time                        `json:"changed_at"`
}

type PostLogSource added in v2.2.0

type PostLogSource struct {
	// ID is a unique identifier for the log source.
	// It is scoped to a workspace agent, and can be statically
	// defined inside code to prevent duplicate sources from being
	// created for the same agent.
	ID          uuid.UUID `json:"id"`
	DisplayName string    `json:"display_name"`
	Icon        string    `json:"icon"`
}

type PostMetadataRequest

type PostMetadataRequest struct {
	Metadata []Metadata `json:"metadata"`
}

type PostMetadataRequestDeprecated added in v2.3.1

type PostMetadataRequestDeprecated = codersdk.WorkspaceAgentMetadataResult

In the future, we may want to support sending back multiple values for performance.

type PostStartupRequest

type PostStartupRequest struct {
	Version           string                    `json:"version"`
	ExpandedDirectory string                    `json:"expanded_directory"`
	Subsystems        []codersdk.AgentSubsystem `json:"subsystems"`
}

type Script added in v2.2.0

type Script struct {
	Script string `json:"script"`
}

type ScriptLogger added in v2.9.0

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

func (ScriptLogger) Flush added in v2.9.0

func (s ScriptLogger) Flush(ctx context.Context) error

func (ScriptLogger) Send added in v2.9.0

func (s ScriptLogger) Send(ctx context.Context, log ...Log) error

type Stats

type Stats struct {
	// ConnectionsByProto is a count of connections by protocol.
	ConnectionsByProto map[string]int64 `json:"connections_by_proto"`
	// ConnectionCount is the number of connections received by an agent.
	ConnectionCount int64 `json:"connection_count"`
	// ConnectionMedianLatencyMS is the median latency of all connections in milliseconds.
	ConnectionMedianLatencyMS float64 `json:"connection_median_latency_ms"`
	// RxPackets is the number of received packets.
	RxPackets int64 `json:"rx_packets"`
	// RxBytes is the number of received bytes.
	RxBytes int64 `json:"rx_bytes"`
	// TxPackets is the number of transmitted bytes.
	TxPackets int64 `json:"tx_packets"`
	// TxBytes is the number of transmitted bytes.
	TxBytes int64 `json:"tx_bytes"`

	// SessionCountVSCode is the number of connections received by an agent
	// that are from our VS Code extension.
	SessionCountVSCode int64 `json:"session_count_vscode"`
	// SessionCountJetBrains is the number of connections received by an agent
	// that are from our JetBrains extension.
	SessionCountJetBrains int64 `json:"session_count_jetbrains"`
	// SessionCountReconnectingPTY is the number of connections received by an agent
	// that are from the reconnecting web terminal.
	SessionCountReconnectingPTY int64 `json:"session_count_reconnecting_pty"`
	// SessionCountSSH is the number of connections received by an agent
	// that are normal, non-tagged SSH sessions.
	SessionCountSSH int64 `json:"session_count_ssh"`

	// Metrics collected by the agent
	Metrics []AgentMetric `json:"metrics"`
}

Stats records the Agent's network connection statistics for use in user-facing metrics and debugging.

func (Stats) SessionCount added in v2.5.0

func (s Stats) SessionCount() int64

type StatsResponse

type StatsResponse struct {
	// ReportInterval is the duration after which the agent should send stats
	// again.
	ReportInterval time.Duration `json:"report_interval"`
}

Jump to

Keyboard shortcuts

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