{"modulePath":"github.com/taskcluster/taskcluster-worker","version":"v0.1.20","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package runtime\n\nPackage runtime contains the generic functionality that an engine and plugins use.\n\n## Variables\n\n```go\nvar ErrFatalInternalError = errors.New(\"Encountered a fatal internal error\")\n```\nErrFatalInternalError is used to signal that a fatal internal error has been logged and that the worker should gracefully terminate/reset.\n\nEngines and plugins can return any unknown error in-order to trigger the same effect. As the worker will report, log and terminate/reset when it encounters an unknown error. This error is ONLY used when the error has already been reported and logged to both system log and task log.\n\nThis is only useful for plugins and engines that wishes to manually handle error reporting.\n\n```go\nvar ErrLogNotClosed = errors.New(\"Log is still open\")\n```\nErrLogNotClosed represents an invalid attempt to extract a log while it is still open.\n\n```go\nvar ErrNonFatalInternalError = errors.New(\"Encountered a non-fatal internal error\")\n```\nErrNonFatalInternalError is used to indicate that the operation failed because of internal error that isn't expected to affect other tasks.\n\nWorker need not worry about logging the error to system log or task log as the engine/plugin which returned this error already reported it, log it and/or deemed the error inconsequential.\n\nWorker should, however, report the task as exception and resolve it with reason 'internal-error'. If the worker gets a lot of these non-fatal internal errors, it may employ a heuristic to decide if it has entered a bad state. For example, worker might reboot if it has seen more than 5 non-fatal internal errors within the span of 15min or 5 tasks.\n\n## Functions\n\n```go\nfunc NewTaskContext(tempLogFile string, task TaskInfo) (*TaskContext, *TaskContextController, error)\n```\nNewTaskContext creates a TaskContext and associated TaskContextController\n\n```go\nfunc RenderDocument(title string, sections []Section) string\n```\nRenderDocument creates a markdown document with given title from a list of sections. Ordering sections alphabetically.\n\n## Types\n\n```go\ntype Environment struct {\n\tGarbageCollector gc.ResourceTracker\n\tTemporaryStorage\n\twebhookserver.WebHookServer // Optional, may be nil if not available\n\tMonitor\n\tWorker        Stoppable\n\tProvisionerID string\n\tWorkerType    string\n\tWorkerGroup   string\n\tWorkerID      string\n}\n```\nEnvironment is a collection of objects that makes up a runtime environment.\n\nThis type is intended to be passed by value, and should only contain pointers and interfaces for that reason.\n\n```go\ntype ErrorArtifact struct {\n\tName    string\n\tMessage string\n\tReason  string\n\tExpires time.Time\n}\n```\nErrorArtifact wraps all of the needed fields to upload an error artifact\n\n```go\ntype ExceptionReason int\n```\nAn ExceptionReason specifies the reason a task reached an exception state.\n\n```go\nconst (\n\tReasonNoException ExceptionReason = iota\n\tReasonCanceled\n\tReasonWorkerShutdown\n\tReasonMalformedPayload\n\tReasonResourceUnavailable\n\tReasonInternalError\n\tReasonSuperseded\n\tReasonIntermittentTask\n)\n```\nReasons why a task can reach an exception state. Implementors should be warned that additional entries may be added in the future.\n\n```go\nfunc (e ExceptionReason) String() string\n```\nString returns a string repesentation of the ExceptionReason for use with the taskcluster-queue API.\n\n```go\ntype LifeCycleTracker struct {\n\tStoppingNow        atomics.Once\n\tStoppingGracefully atomics.Once\n}\n```\nLifeCycleTracker implements Stoppable as two atomics.Once that you can wait for, or get a blocking channel from.\n\n```go\nfunc (s *LifeCycleTracker) StopGracefully()\n```\nStopGracefully does StoppingGracefully\n\n```go\nfunc (s *LifeCycleTracker) StopNow()\n```\nStopNow does StoppingNow and StoppingGracefully\n\n```go\ntype MalformedPayloadError struct {\n\t// contains filtered or unexported fields\n}\n```\nThe MalformedPayloadError error type is used to indicate that some operation failed because of malformed-payload.\n\nFor example a string expected to be path contained invalid characters, a required property was missing, or an integer was outside the permitted range.\n\n```go\nfunc IsMalformedPayloadError(err error) (e *MalformedPayloadError, ok bool)\n```\nIsMalformedPayloadError casts error to MalformedPayloadError.\n\nThis is mostly because it's hard to remember that error isn't supposed to be cast to \\*MalformedPayloadError.\n\n```go\nfunc MergeMalformedPayload(errors ...*MalformedPayloadError) *MalformedPayloadError\n```\nMergeMalformedPayload merges a list of MalformedPayloadError objects\n\n```go\nfunc NewMalformedPayloadError(a ...interface{}) *MalformedPayloadError\n```\nNewMalformedPayloadError creates a MalformedPayloadError object, please make sure to include a detailed description of the error, preferably using multiple lines and with examples.\n\nThese will be printed in the logs and end-users will rely on them to debug their tasks.\n\n```go\nfunc (e *MalformedPayloadError) Error() string\n```\nError returns the error message and adheres to the Error interface\n\n```go\nfunc (e *MalformedPayloadError) Messages() []string\n```\nMessages returns a list of messages explaining why the error.\n\n```go\ntype Monitor interface {\n\t// Measure values in statsum\n\tMeasure(name string, value ...float64)\n\t// Increment counters in statsum\n\tCount(name string, value float64)\n\t// Measure time of fn in statsum\n\tTime(name string, fn func())\n\n\t// Report error/warning to sentry and write to log, returns incidentId which\n\t// can be included in task-logs, if relevant.\n\tReportError(err error, message ...interface{}) string\n\tReportWarning(err error, message ...interface{}) string\n\n\t// CapturePanic reports panics to log/sentry and returns incidentID, if any\n\tCapturePanic(fn func()) (incidentID string)\n\n\t// Write log messages to system log\n\tDebug(...interface{})\n\tDebugln(...interface{})\n\tDebugf(string, ...interface{})\n\tPrint(...interface{})\n\tPrintln(...interface{})\n\tPrintf(string, ...interface{})\n\tInfo(...interface{})\n\tInfoln(...interface{})\n\tInfof(string, ...interface{})\n\tWarn(...interface{})\n\tWarnln(...interface{})\n\tWarnf(string, ...interface{})\n\tError(...interface{})\n\tErrorln(...interface{})\n\tErrorf(string, ...interface{})\n\tPanic(...interface{})\n\tPanicln(...interface{})\n\tPanicf(string, ...interface{})\n\n\t// Create child monitor with given tags (tags don't apply to statsum)\n\tWithTags(tags map[string]string) Monitor\n\tWithTag(key, value string) Monitor\n\t// Create child monitor with given prefix (prefix applies to everything)\n\tWithPrefix(prefix string) Monitor\n}\n```\nA Monitor is responsible for collecting logs, stats and error messages.\n\nA monitor is a context aware object for monitoring. That is to say that a Monitor is used to record metrics, write logs and report errors. When doing so the Monitor object adds meta-data to the metrics, logs and errors. The meta-data added is context dependent tags and prefix. These help identify where a log message, metric or error originates from.\n\nBy encapsulating the context meta-data inside the Monitor object, an implementor gets a Monitor rarely needs to add tags or prefix. For example a monitor will always be prefixed by plugin name before being passed to a plugin, hence, it is easy trace any log message, metric or error report to the plugin that it was created in.\n\nWhen passing a Monitor to a sub-component it often makes sense to add additional tags or prefix. This way a downloader function that takes a Monitor need not worry about being able to distinguish its metrics, logs and errors from that of its parent.\n\nPrefixes should always be constants, such as engine, plugin, function or component names. Values that change such as taskId or runId should not be used as prefixes, such values is however great as tags.\n\nAll metrics reported for a given prefix + name will be aggregated. Hence, if taskId was used as prefix, the dimensionality of metrics would explode and the aggregation wouldn't be useful.\n\n```go\ntype RedirectArtifact struct {\n\tName     string\n\tMimetype string\n\tURL      string\n\tExpires  time.Time\n}\n```\nRedirectArtifact wraps all of the needed fields to upload a redirect artifact\n\n```go\ntype S3Artifact struct {\n\tName              string\n\tMimetype          string\n\tExpires           time.Time\n\tStream            ioext.ReadSeekCloser\n\tAdditionalHeaders map[string]string\n}\n```\nS3Artifact wraps all of the needed fields to upload an s3 artifact\n\n```go\ntype Section struct {\n\tTitle   string // Title of section rendered as headline level 2\n\tContent string // Section contents, maybe contains headline level 3 and higher\n}\n```\nA Section represents a section of markdown documentation.\n\n```go\ntype ShutdownManager interface {\n\tWaitForShutdown() \u003c-chan struct{}\n}\n```\nShutdownManager implements a method for listening for shutdown events.  Consumers\n\n```go\nfunc NewShutdownManager(host string) ShutdownManager\n```\nNewShutdownManager will return a shutdown manager appropriate for the host that the worker is being run on.\n\nShutdown events are triggered different ways depending on where the worker is running. When running in AWS, then notifications are sent on their meta-data api, but running locally could cause the worker to represent to different kind of shutdown events.\n\n```go\ntype Stoppable interface {\n\t// StopNow causes the worker to stop processing tasks, resolving all active\n\t// tasks exception w. worker-shutdown.\n\tStopNow()\n\t// StopGracefully causes the worker to stop claiming tasks and stop gracefully\n\t// when all active tasks have been resolved.\n\tStopGracefully()\n}\n```\nStoppable is an worker with a life-cycle that can be can be stopped.\n\n```go\ntype StoppableOnce struct {\n\tStoppable Stoppable\n\t// contains filtered or unexported fields\n}\n```\nStoppableOnce is a wrapper that ensures we only call StopGracefully and StopNow once and never call StopGracefully after StopNow.\n\nThere is never any harm in wrapping with this, it merely limits excessive calls to StopNow() and StopGracefully(). Please note that Stoppable.StopNow() may still be invoked after Stoppable.StopGracefully(), it can even be invoked concurrently.\n\n```go\nfunc (s *StoppableOnce) StopGracefully()\n```\nStopGracefully calls StopGracefully() on the s.Stoppable, if neither StopGracefully() or StopNow() have been called.\n\n```go\nfunc (s *StoppableOnce) StopNow()\n```\nStopNow calls StopNow() on s.Stoppable, if StopNow() haven't been called yet.\n\n```go\ntype TaskContext struct {\n\tTaskInfo\n\t// contains filtered or unexported fields\n}\n```\nThe TaskContext exposes generic properties and functionality related to a task that is currently being executed.\n\nThis context is used to ensure that every component both engines and plugins that operates on a task have access to some common information about the task. This includes log drains, per-task credentials, generic task properties, and abortion notifications.\n\n```go\nfunc (c *TaskContext) Abort()\n```\nAbort sets the status to aborted\n\n```go\nfunc (c *TaskContext) Authorizer() client.Authorizer\n```\nAuthorizer can sign requests with temporary credentials associated with the task.\n\nNotice, when blindly forwarding requests task.scopes should be set as authorizedScopes, otherwise artifact upload and resolution will possible.\n\n```go\nfunc (c *TaskContext) Cancel()\n```\nCancel sets the status to cancelled\n\n```go\nfunc (context *TaskContext) CreateErrorArtifact(artifact ErrorArtifact) error\n```\nCreateErrorArtifact is responsible for inserting error artifacts into the queue.\n\n```go\nfunc (context *TaskContext) CreateRedirectArtifact(artifact RedirectArtifact) error\n```\nCreateRedirectArtifact is responsible for inserting redirect artifacts into the queue.\n\n```go\nfunc (c *TaskContext) Deadline() (deadline time.Time, ok bool)\n```\nDeadline returns empty time and false, this is implemented to satisfy context.Context.\n\n```go\nfunc (c *TaskContext) Done() \u003c-chan struct{}\n```\nDone returns a channel that is closed when to TaskContext is aborted or canceled.\n\nImplemented in compliance with context.Context.\n\n```go\nfunc (c *TaskContext) Err() error\n```\nErr returns context.Canceled, if task as canceled or aborted.\n\nImplemented in compliance with context.Context.\n\n```go\nfunc (c *TaskContext) ExtractLog() (ioext.ReadSeekCloser, error)\n```\nExtractLog returns an IO object to read the log.\n\n```go\nfunc (c *TaskContext) HasScopes(scopeSets ...[]string) bool\n```\nHasScopes returns true, if task.scopes covers one of the scopeSets given\n\n```go\nfunc (c *TaskContext) IsAborted() bool\n```\nIsAborted returns true if the current status is Aborted\n\n```go\nfunc (c *TaskContext) IsCancelled() bool\n```\nIsCancelled returns true if the current status is Cancelled\n\n```go\nfunc (c *TaskContext) Log(a ...interface{})\n```\nLog writes a log message from the worker\n\nThese log messages will be prefixed \"\\[taskcluster]\" so it's easy to see to that they are worker logs.\n\n```go\nfunc (c *TaskContext) LogDrain() io.Writer\n```\nLogDrain returns a drain to which log message can be written.\n\nUsers should note that multiple writers are writing to this drain concurrently, and it is recommend that writers write in chunks of one line.\n\n```go\nfunc (c *TaskContext) LogError(a ...interface{})\n```\nLogError writes a log error message from the worker\n\nThese log messages will be prefixed \"\\[taskcluster:error]\" so it's easy to see to that they are worker logs.  These errors are also easy to grep from the logs in case of failure.\n\n```go\nfunc (c *TaskContext) NewLogReader() (io.ReadCloser, error)\n```\nNewLogReader returns a ReadCloser that reads the log from the start as the log is written.\n\nCalls to Read() on the resulting ReadCloser are blocking. They will return when data is written or EOF is reached.\n\nConsumers should ensure the ReadCloser is closed before discarding it.\n\n```go\nfunc (c *TaskContext) Queue() client.Queue\n```\nQueue will return a client for the TaskCluster Queue.  This client is useful for plugins that require interactions with the queue, such as creating artifacts.\n\n```go\nfunc (context *TaskContext) UploadS3Artifact(artifact S3Artifact) error\n```\nUploadS3Artifact is responsible for creating new artifacts in the queue and then performing the upload to s3.\n\n```go\nfunc (c *TaskContext) Value(key interface{}) interface{}\n```\nValue returns nil, this is implemented to satisfy context.Context\n\n```go\ntype TaskContextController struct {\n\t*TaskContext\n}\n```\nTaskContextController exposes logic for controlling the TaskContext.\n\nSpliting this out from TaskContext ensures that engines and plugins doesn't accidentally Dispose() the TaskContext.\n\n```go\nfunc (c *TaskContextController) CloseLog() error\n```\nCloseLog will close the log so no more messages can be written.\n\n```go\nfunc (c *TaskContextController) Dispose() error\n```\nDispose will clean-up all resources held by the TaskContext\n\n```go\nfunc (c *TaskContextController) SetCredentials(clientID, accessToken, certificate string)\n```\nSetCredentials is used to provide the task-specific temporary credentials, and update these whenever they change.\n\n```go\nfunc (c *TaskContextController) SetQueueClient(client client.Queue)\n```\nSetQueueClient will set a client for the TaskCluster Queue.  This client can then be used by others that have access to the task context and require interaction with the queue.\n\n```go\ntype TaskInfo struct {\n\tTaskID   string\n\tRunID    int\n\tCreated  time.Time\n\tDeadline time.Time\n\tExpires  time.Time\n\tScopes   []string\n\tTask     interface{} // task definition in map[string]interface{} types..\n}\n```\nThe TaskInfo struct exposes generic properties from a task definition.\n\nNote, do not be tempted to add task definition or status here in its entirety as it can encourage undesired behaviors.  Instead only the data necessary should be exposed and nothing more.  One such anti-pattern could be for a plugin to look at task.extra instead of adding data to task.payload.\n\n```go\ntype TaskStatus string // TODO: (jonasfj) TaskContext shouldn't track status\n\n```\nTaskStatus represents the current status of the task.\n\n```go\nconst (\n\tAborted   TaskStatus = \"Aborted\" // TODO: (jonasfj) Don't distinguish between cancel/abort\n\tCancelled TaskStatus = \"Cancelled\"\n\tSucceeded TaskStatus = \"Succeeded\"\n\tFailed    TaskStatus = \"Failed\"\n\tErrored   TaskStatus = \"Errored\"\n\tClaimed   TaskStatus = \"Claimed\"\n\tReclaimed TaskStatus = \"Reclaimed\"\n)\n```\nEnumerate task status to aid life-cycle decision making Use strings for benefit of simple logging/reporting\n\n```go\ntype TemporaryFile interface {\n\tTruncate(size int64) error\n\tio.ReadWriteSeeker\n\tio.Closer\n\tPath() string\n}\n```\nTemporaryFile is a temporary file that will be removed when closed.\n\n```go\ntype TemporaryFolder interface {\n\tTemporaryStorage\n\tPath() string\n\tRemove() error\n}\n```\nTemporaryFolder is a temporary folder that is backed by the filesystem. User are nicely asked to stay with the folder they've been issued.\n\nWe don't really mock the file system interface as we need to integrate with other applications like docker, so we have to expose real file paths.\n\n```go\nfunc NewTemporaryStorage(path string) (TemporaryFolder, error)\n```\nNewTemporaryStorage return a TemporaryFolder rooted in the given path.\n\n```go\nfunc NewTemporaryTestFolderOrPanic() TemporaryFolder\n```\nNewTemporaryTestFolderOrPanic creates a TemporaryFolder as in a subfolder of os.TempDir, or panics.\n\nThis intended to for use when writing tests using the following pattern:\n\n\tstorage := runtime.NewTemporaryTestFolderOrPanic()\n\tdefer storage.Remove()\n\n```go\ntype TemporaryStorage interface {\n\tNewFolder() (TemporaryFolder, error)\n\tNewFile() (TemporaryFile, error)\n\tNewFilePath() string\n}\n```\nTemporaryStorage can create temporary folders and files.\n\n","path":"github.com/taskcluster/taskcluster-worker/runtime","name":"runtime","synopsis":"Package runtime contains the generic functionality that an engine and plugins use.","isRedistributable":true}
