Movatterモバイル変換


[0]ホーム

URL:


agentsdk

package
v2.23.0Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2025 License:AGPL-3.0Imports:31Imported by:6

Details

Repository

github.com/coder/coder

Links

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (ErrTransmissionSourceClosed =xerrors.New("transmission source closed")ErrTransmissionTargetClosed =xerrors.New("transmission target closed"))
View Source
var ErrLogLimitExceeded =xerrors.New("Log limit exceeded")
View Source
var ExternalLogSourceID =uuid.MustParse("3b579bf4-1ed8-4b99-87a8-e9a1e3410410")

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

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

Functions

funcAgentScriptFromProtoadded inv2.8.0

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

funcAgentScriptsFromProtoadded inv2.8.0

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

funcAppFromProtoadded inv2.8.0

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

funcAppHealthPosteradded inv2.8.0

funcAppsFromProtoadded inv2.8.0

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

funcBannerConfigFromProtoadded inv2.12.0

func BannerConfigFromProto(sbp *proto.BannerConfig)codersdk.BannerConfig

funcDevcontainersFromProtoadded inv2.21.0

funcLifecycleStateFromProtoadded inv2.9.0

funcLogsNotifyChannel

func LogsNotifyChannel(agentIDuuid.UUID)string

LogsNotifyChannel returns the channel name responsible for notifyingof new logs.

funcLogsSenderdeprecated

func LogsSender(sourceIDuuid.UUID, patchLogs func(ctxcontext.Context, reqPatchLogs)error, loggerslog.Logger, opts ...func(*logsSenderOptions)) (sendLog func(ctxcontext.Context, log ...Log)error, flushAndClose func(context.Context)error)

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

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

funcLogsSenderFlushTimeoutadded inv2.3.0

func LogsSenderFlushTimeout(timeouttime.Duration) func(*logsSenderOptions)

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

funcLogsWriteradded inv2.2.0

func LogsWriter(ctxcontext.Context, sender func(ctxcontext.Context, log ...Log)error, sourceuuid.UUID, levelcodersdk.LogLevel)io.WriteCloser

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

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

funcMetadataDescriptionsFromProtoadded inv2.8.0

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

funcPrebuildClaimedChanneladded inv2.22.0

func PrebuildClaimedChannel(iduuid.UUID)string

funcProtoFromAppadded inv2.8.0

funcProtoFromAppHealthsRequestadded inv2.8.0

func ProtoFromAppHealthsRequest(reqPostAppHealthsRequest) (*proto.BatchUpdateAppHealthRequest,error)

funcProtoFromAppsadded inv2.8.0

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

funcProtoFromBannerConfigadded inv2.12.0

func ProtoFromBannerConfig(sbcodersdk.BannerConfig) *proto.BannerConfig

funcProtoFromConnectionTypeadded inv2.20.0

func ProtoFromConnectionType(typConnectionType) (proto.Connection_Type,error)

funcProtoFromDevcontainersadded inv2.21.0

funcProtoFromLifecycleadded inv2.9.0

func ProtoFromLifecycle(reqPostLifecycleRequest) (*proto.Lifecycle,error)

funcProtoFromLifecycleStateadded inv2.13.0

funcProtoFromLogadded inv2.9.0

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

funcProtoFromManifestadded inv2.8.0

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

funcProtoFromMetadataDescriptionsadded inv2.8.0

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

funcProtoFromScriptsadded inv2.8.0

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

funcProtoFromServiceBanneradded inv2.8.0

func ProtoFromServiceBanner(sbcodersdk.BannerConfig) *proto.ServiceBanner

funcProtoFromSubsystemsadded inv2.8.0

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

funcServiceBannerFromProtoadded inv2.8.0

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

funcWaitForReinitLoopadded inv2.22.0

func WaitForReinitLoop(ctxcontext.Context, loggerslog.Logger, client *Client) <-chanReinitializationEvent

Types

typeAWSInstanceIdentityToken

type AWSInstanceIdentityToken struct {Signaturestring `json:"signature" validate:"required"`Documentstring `json:"document" validate:"required"`}

typeAgentMetric

type AgentMetric struct {Namestring             `json:"name" validate:"required"`TypeAgentMetricType    `json:"type" validate:"required" enums:"counter,gauge"`Valuefloat64            `json:"value" validate:"required"`Labels []AgentMetricLabel `json:"labels,omitempty"`}

typeAgentMetricLabel

type AgentMetricLabel struct {Namestring `json:"name" validate:"required"`Valuestring `json:"value" validate:"required"`}

typeAgentMetricType

type AgentMetricTypestring
const (AgentMetricTypeCounterAgentMetricType = "counter"AgentMetricTypeGaugeAgentMetricType = "gauge")

typeAuthenticateResponse

type AuthenticateResponse struct {SessionTokenstring `json:"session_token"`}

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

typeAzureInstanceIdentityToken

type AzureInstanceIdentityToken struct {Signaturestring `json:"signature" validate:"required"`Encodingstring `json:"encoding" validate:"required"`}

typeBatchUpdateAppHealthsClientadded inv2.9.0

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

BatchUpdateAppHealthsClient is a partial interface of proto.DRPCAgentClient.

typeClient

type Client struct {SDK *codersdk.Client}

Client wraps `codersdk.Client` with specific functionsscoped to a workspace agent.

funcNew

func New(serverURL *url.URL) *Client

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

func (*Client)AuthAWSInstanceIdentity

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

AuthWorkspaceAWSInstanceIdentity uses the Amazon Metadata API tofetch 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(ctxcontext.Context) (AuthenticateResponse,error)

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

func (*Client)AuthGoogleInstanceIdentity

func (c *Client) AuthGoogleInstanceIdentity(ctxcontext.Context, serviceAccountstring, gcpClient *metadata.Client) (AuthenticateResponse,error)

AuthWorkspaceGoogleInstanceIdentity uses the Google Compute Engine Metadata API tofetch 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)ConnectRPCadded inv2.8.0

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

ConnectRPC connects to the workspace agent API and tailnet API

func (*Client)ConnectRPC20added inv2.14.0

func (c *Client) ConnectRPC20(ctxcontext.Context) (proto.DRPCAgentClient20,error)

ConnectRPC20 returns a dRPC client to the Agent API v2.0. Notably, it is missingGetAnnouncementBanners, but is useful when you want to be maximally compatible with CoderdRelease Versions from 2.9+Deprecated: use ConnectRPC20WithTailnet

func (*Client)ConnectRPC20WithTailnetadded inv2.18.0

ConnectRPC20WithTailnet returns a dRPC client to the Agent API v2.0. Notably, it is missingGetAnnouncementBanners, but is useful when you want to be maximally compatible with CoderdRelease Versions from 2.9+

func (*Client)ConnectRPC21added inv2.14.0

func (c *Client) ConnectRPC21(ctxcontext.Context) (proto.DRPCAgentClient21,error)

ConnectRPC21 returns a dRPC client to the Agent API v2.1. It is useful when you want to bemaximally compatible with Coderd Release Versions from 2.12+Deprecated: use ConnectRPC21WithTailnet

func (*Client)ConnectRPC21WithTailnetadded inv2.18.0

ConnectRPC21WithTailnet returns a dRPC client to the Agent API v2.1. It is useful when you want to bemaximally compatible with Coderd Release Versions from 2.12+

func (*Client)ConnectRPC22added inv2.18.0

ConnectRPC22 returns a dRPC client to the Agent API v2.2. It is useful when you want to bemaximally compatible with Coderd Release Versions from 2.13+

func (*Client)ConnectRPC23added inv2.18.0

ConnectRPC23 returns a dRPC client to the Agent API v2.3. It is useful when you want to bemaximally compatible with Coderd Release Versions from 2.18+

func (*Client)ConnectRPC24added inv2.20.0

ConnectRPC24 returns a dRPC client to the Agent API v2.4. It is useful when you want to bemaximally compatible with Coderd Release Versions from 2.20+

func (*Client)ConnectRPC25added inv2.23.0

ConnectRPC25 returns a dRPC client to the Agent API v2.5. It is useful when you want to bemaximally compatible with Coderd Release Versions from 2.xx+ // TODO(DanielleMaywood): Update version

func (*Client)ExternalAuthadded inv2.3.0

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

func (*Client)GitSSHKey

func (c *Client) GitSSHKey(ctxcontext.Context) (GitSSHKey,error)

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

func (*Client)PatchAppStatusadded inv2.21.0

func (c *Client) PatchAppStatus(ctxcontext.Context, reqPatchAppStatus)error

func (*Client)PatchLogsdeprecated

func (c *Client) PatchLogs(ctxcontext.Context, reqPatchLogs)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)PostLogSourceadded inv2.2.0

func (*Client)RewriteDERPMapadded inv2.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 theglobally configured one. This breaks the built-in DERP, which would continueto reference the global access URL.

func (*Client)SetSessionToken

func (c *Client) SetSessionToken(tokenstring)

func (*Client)WaitForReinitadded inv2.22.0

func (c *Client) WaitForReinit(ctxcontext.Context) (*ReinitializationEvent,error)

WaitForReinit polls a SSE endpoint, and receives an event back under the following conditions:- ping: ignored, keepalive- prebuild claimed: a prebuilt workspace is claimed, so the agent must reinitialize.

typeConnectionTypeadded inv2.20.0

type ConnectionTypestring

ConnectionType is the type of connection that the agent is receiving.

const (ConnectionTypeUnspecifiedConnectionType = "Unspecified"ConnectionTypeSSHConnectionType = "SSH"ConnectionTypeVSCodeConnectionType = "VS Code"ConnectionTypeJetBrainsConnectionType = "JetBrains"ConnectionTypeReconnectingPTYConnectionType = "Web Terminal")

Connection type enums.

funcConnectionTypeFromProtoadded inv2.20.0

func ConnectionTypeFromProto(typproto.Connection_Type) (ConnectionType,error)

typeExternalAuthRequestadded inv2.3.0

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

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

typeExternalAuthResponseadded inv2.3.0

type ExternalAuthResponse struct {AccessTokenstring                 `json:"access_token"`TokenExtra  map[string]interface{} `json:"token_extra"`URLstring                 `json:"url"`Typestring                 `json:"type"`// Deprecated: Only supported on `/workspaceagents/me/gitauth`// for backwards compatibility.Usernamestring `json:"username"`Passwordstring `json:"password"`}

typeGitSSHKey

type GitSSHKey struct {PublicKeystring `json:"public_key"`PrivateKeystring `json:"private_key"`}

typeGoogleInstanceIdentityToken

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

typeLog

type Log struct {CreatedAttime.Time         `json:"created_at"`Outputstring            `json:"output"`Levelcodersdk.LogLevel `json:"level"`}

typeLogDestadded inv2.14.0

type LogDest interface {BatchCreateLogs(ctxcontext.Context, request *proto.BatchCreateLogsRequest) (*proto.BatchCreateLogsResponse,error)}

typeLogSenderadded inv2.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, callSendLoop to send pending logs.

funcNewLogSenderadded inv2.9.0

func NewLogSender(loggerslog.Logger) *LogSender

func (*LogSender)Enqueueadded inv2.9.0

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

func (*LogSender)Flushadded inv2.9.0

func (l *LogSender) Flush(srcuuid.UUID)

func (*LogSender)GetScriptLoggeradded inv2.9.0

func (l *LogSender) GetScriptLogger(logSourceIDuuid.UUID)ScriptLogger

func (*LogSender)SendLoopadded inv2.9.0

func (l *LogSender) SendLoop(ctxcontext.Context, destLogDest)error

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

func (*LogSender)WaitUntilEmptyadded inv2.9.0

func (l *LogSender) WaitUntilEmpty(ctxcontext.Context)error

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

typeLogSourceadded inv2.2.0

type LogSource struct {IDuuid.UUID `json:"id"`DisplayNamestring    `json:"display_name"`Iconstring    `json:"icon"`}

typeLogsNotifyMessage

type LogsNotifyMessage struct {CreatedAfterint64 `json:"created_after"`}

typeManifest

type Manifest struct {AgentIDuuid.UUID `json:"agent_id"`AgentNamestring    `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.OwnerNamestring    `json:"owner_name"`WorkspaceIDuuid.UUID `json:"workspace_id"`WorkspaceNamestring    `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.GitAuthConfigsint                                          `json:"git_auth_configs"`VSCodePortProxyURIstring                                       `json:"vscode_port_proxy_uri"`Apps                     []codersdk.WorkspaceApp                      `json:"apps"`DERPMap                  *tailcfg.DERPMap                             `json:"derpmap"`DERPForceWebSocketsbool                                         `json:"derp_force_websockets"`EnvironmentVariables     map[string]string                            `json:"environment_variables"`Directorystring                                       `json:"directory"`MOTDFilestring                                       `json:"motd_file"`DisableDirectConnectionsbool                                         `json:"disable_direct_connections"`Metadata                 []codersdk.WorkspaceAgentMetadataDescription `json:"metadata"`Scripts                  []codersdk.WorkspaceAgentScript              `json:"scripts"`Devcontainers            []codersdk.WorkspaceAgentDevcontainer        `json:"devcontainers"`}

funcManifestFromProtoadded inv2.8.0

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

typeMetadataadded inv2.3.1

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

funcMetadataFromProtoadded inv2.9.0

func MetadataFromProto(m *proto.Metadata)Metadata

typePatchAppStatusadded inv2.21.0

type PatchAppStatus struct {AppSlugstring                           `json:"app_slug"`Statecodersdk.WorkspaceAppStatusState `json:"state"`Messagestring                           `json:"message"`URIstring                           `json:"uri"`// Deprecated: this field is unused and will be removed in a future version.Iconstring `json:"icon"`// Deprecated: this field is unused and will be removed in a future version.NeedsUserAttentionbool `json:"needs_user_attention"`}

PatchAppStatus updates the status of a workspace app.

typePatchLogs

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

typePostAppHealthsRequest

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

typePostLifecycleRequest

type PostLifecycleRequest struct {Statecodersdk.WorkspaceAgentLifecycle `json:"state"`ChangedAttime.Time                        `json:"changed_at"`}

typePostLogSourceRequestadded inv2.13.0

type PostLogSourceRequest 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.IDuuid.UUID `json:"id"`DisplayNamestring    `json:"display_name"`Iconstring    `json:"icon"`}

typePostMetadataRequest

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

typePostMetadataRequestDeprecatedadded inv2.3.1

type PostMetadataRequestDeprecated =codersdk.WorkspaceAgentMetadataResult

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

typePostStartupRequest

type PostStartupRequest struct {Versionstring                    `json:"version"`ExpandedDirectorystring                    `json:"expanded_directory"`Subsystems        []codersdk.AgentSubsystem `json:"subsystems"`}

typeReinitializationEventadded inv2.22.0

type ReinitializationEvent struct {WorkspaceIDuuid.UUIDReasonReinitializationReason `json:"reason"`}

typeReinitializationReasonadded inv2.22.0

type ReinitializationReasonstring
const (ReinitializeReasonPrebuildClaimedReinitializationReason = "prebuild_claimed")

typeSSEAgentReinitReceiveradded inv2.22.0

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

funcNewSSEAgentReinitReceiveradded inv2.22.0

func NewSSEAgentReinitReceiver(rio.ReadCloser) *SSEAgentReinitReceiver

func (*SSEAgentReinitReceiver)Receiveadded inv2.22.0

typeSSEAgentReinitTransmitteradded inv2.22.0

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

funcNewSSEAgentReinitTransmitteradded inv2.22.0

func NewSSEAgentReinitTransmitter(loggerslog.Logger, rwhttp.ResponseWriter, r *http.Request) *SSEAgentReinitTransmitter

func (*SSEAgentReinitTransmitter)Transmitadded inv2.22.0

func (s *SSEAgentReinitTransmitter) Transmit(ctxcontext.Context, reinitEvents <-chanReinitializationEvent)error

Transmit will read from the given chan and send events for as long as:* the chan remains open* the context has not been canceled* not timed out* the connection to the receiver remains open

typeScriptadded inv2.2.0

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

typeScriptLoggeradded inv2.9.0

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

func (ScriptLogger)Flushadded inv2.9.0

func (ScriptLogger)Sendadded inv2.9.0

func (sScriptLogger) Send(ctxcontext.Context, log ...Log)error

typeStats

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.ConnectionCountint64 `json:"connection_count"`// ConnectionMedianLatencyMS is the median latency of all connections in milliseconds.ConnectionMedianLatencyMSfloat64 `json:"connection_median_latency_ms"`// RxPackets is the number of received packets.RxPacketsint64 `json:"rx_packets"`// RxBytes is the number of received bytes.RxBytesint64 `json:"rx_bytes"`// TxPackets is the number of transmitted bytes.TxPacketsint64 `json:"tx_packets"`// TxBytes is the number of transmitted bytes.TxBytesint64 `json:"tx_bytes"`// SessionCountVSCode is the number of connections received by an agent// that are from our VS Code extension.SessionCountVSCodeint64 `json:"session_count_vscode"`// SessionCountJetBrains is the number of connections received by an agent// that are from our JetBrains extension.SessionCountJetBrainsint64 `json:"session_count_jetbrains"`// SessionCountReconnectingPTY is the number of connections received by an agent// that are from the reconnecting web terminal.SessionCountReconnectingPTYint64 `json:"session_count_reconnecting_pty"`// SessionCountSSH is the number of connections received by an agent// that are normal, non-tagged SSH sessions.SessionCountSSHint64 `json:"session_count_ssh"`// Metrics collected by the agentMetrics []AgentMetric `json:"metrics"`}

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

func (Stats)SessionCountadded inv2.5.0

func (sStats) SessionCount()int64

typeStatsResponse

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

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp