contracts

package
v0.0.0-...-0117b6e Latest Latest
Warning

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

Go to latest
Published: May 2, 2024 License: Apache-2.0 Imports: 10 Imported by: 153

Documentation

Overview

Package contracts helps persist documents state to disk

Package contracts provides model definitions for document state

Package contracts provides model definitions for document state

Package contracts contains all necessary interface and models necessary for communication and sharing within the agent.

Package contracts contains objects for parsing and encoding MDS/SSM messages.

Index

Constants

View Source
const (
	ExitWithSuccess int = 168
	ExitWithFailure int = 169
)
View Source
const (
	OnFailureModifier   string = "onFailure"
	OnSuccessModifier   string = "onSuccess"
	FinallyStepModifier string = "finallyStep"
)
View Source
const (
	ModifierValueExit           string = "exit"
	ModifierValueSuccessAndExit string = "successAndExit"
	ModifierValueTrue           string = "true"
)
View Source
const (
	/*
		NOTE: Following constants are meant to be used for setting plugin status only
	*/
	// AssociationStatusPending represents Pending status
	AssociationStatusPending = "Pending"
	// AssociationStatusAssociated represents Associated status
	AssociationStatusAssociated = "Associated"
	// AssociationStatusInProgress represents InProgress status
	AssociationStatusInProgress = "InProgress"
	// AssociationStatusSuccess represents Success status
	AssociationStatusSuccess = "Success"
	// AssociationStatusFailed represents Failed status
	AssociationStatusFailed = "Failed"
	// AssociationStatusTimedOut represents TimedOut status
	AssociationStatusTimedOut = "TimedOut"
)
View Source
const (
	/*
		NOTE: Following constants are meant to be used for setting error codes in plugin status only. If these are used
		for setting plugin status -> the status will not be appropriately aggregated.
	*/
	// AssociationErrorCodeInvalidAssociation represents InvalidAssociation Error
	AssociationErrorCodeInvalidAssociation = "InvalidAssoc"
	// AssociationErrorCodeInvalidExpression represents InvalidExpression Error
	AssociationErrorCodeInvalidExpression = "InvalidExpression"
	// AssociationErrorCodeExecutionError represents Execution Error
	AssociationErrorCodeExecutionError = "ExecutionError"
	// AssociationErrorCodeListAssociationError represents ListAssociation Error
	AssociationErrorCodeListAssociationError = "ListAssocError"
	// AssociationErrorCodeSubmitAssociationError represents SubmitAssociation Error
	AssociationErrorCodeSubmitAssociationError = "SubmitAssocError"
	// AssociationErrorCodeStuckAtInProgressError represents association stuck in InProgress Error
	AssociationErrorCodeStuckAtInProgressError = "StuckAtInProgress"
	// AssociationErrorCodeNoError represents no error
	AssociationErrorCodeNoError = ""
)
View Source
const (
	// DocumentPendingMessages represents the summary message for pending association
	AssociationPendingMessage string = "Association is pending"
	// DocumentInProgressMessage represents the summary message for inprogress association
	AssociationInProgressMessage string = "Executing association"
)
View Source
const (
	// ParamTypeString represents the Param Type is String
	ParamTypeString = "String"
	// ParamTypeStringList represents the Param Type is StringList
	ParamTypeStringList = "StringList"
	// ParamTypeStringMap represents the param type is StringMap
	ParamTypeStringMap = "StringMap"
)

Variables

This section is empty.

Functions

func IsManagedInstanceIncompatibleAWSSSMDocument

func IsManagedInstanceIncompatibleAWSSSMDocument(documentName string) bool

IsManagedInstanceIncompatibleAWSSSMDocument checks if doc could contain incompatible code for managed instance

func IsPreconditionEnabled

func IsPreconditionEnabled(schemaVersion string) (response bool)

IsPreconditionEnabled checks if precondition support is enabled by checking document schema version

func RemoveDependencyOnInstanceMetadata

func RemoveDependencyOnInstanceMetadata(context context.T, docState *DocumentState) error

RemoveDependencyOnInstanceMetadata looks for array of commands which will be executed as a part of this document and replace the incompatible code.

func UpdateDocState

func UpdateDocState(docResult *DocumentResult, docState *DocumentState)

UpdateDocState updates the current document state

Types

type AdditionalInfo

type AdditionalInfo struct {
	Agent                   AgentInfo      `json:"agent"`
	DateTime                string         `json:"dateTime"`
	RunID                   string         `json:"runId"`
	RuntimeStatusCounts     map[string]int `json:"runtimeStatusCounts"`
	AbleToOpenMGSConnection *bool          `json:"ableToOpenMGSConnection,omitempty"`
}

AdditionalInfo section in agent response

type AgentConfiguration

type AgentConfiguration struct {
	AgentInfo  AgentInfo
	InstanceID string
}

AgentConfiguration is a struct that stores information about the agent and instance

type AgentInfo

type AgentInfo struct {
	Lang      string `json:"lang"`
	Name      string `json:"name"`
	Os        string `json:"os"`
	OsVersion string `json:"osver"`
	Version   string `json:"ver"`
}

AgentInfo represents the agent response

type CancelCommandInfo

type CancelCommandInfo struct {
	CancelMessageID string
	CancelCommandID string
	Payload         string
	DebugInfo       string
}

CancelCommandInfo represents information relevant to a cancel-command that agent receives TODO This might be revisited when Agent-cli is written to list previously executed commands

type CloudWatchConfiguration

type CloudWatchConfiguration struct {
	LogGroupName              string
	LogStreamPrefix           string
	LogGroupEncryptionEnabled bool
}

CloudWatchConfiguration represents information relevant to command output in cloudWatch

type Configuration

type Configuration struct {
	Settings                    interface{}
	Properties                  interface{}
	OutputS3KeyPrefix           string
	OutputS3BucketName          string
	S3EncryptionEnabled         bool
	CloudWatchLogGroup          string
	CloudWatchEncryptionEnabled bool
	CloudWatchStreamingEnabled  bool
	OrchestrationDirectory      string
	MessageId                   string
	BookKeepingFileName         string
	PluginName                  string
	PluginID                    string
	DefaultWorkingDirectory     string
	Preconditions               map[string][]PreconditionArgument
	IsPreconditionEnabled       bool
	CurrentAssociations         []string
	SessionId                   string
	ClientId                    string
	KmsKeyId                    string
	RunAsEnabled                bool
	RunAsUser                   string
	ShellProfile                ShellProfileConfig
	SessionOwner                string
	UpstreamServiceName         UpstreamServiceName
}

Configuration represents a plugin configuration as in the json format.

type ConnectionChannel

type ConnectionChannel struct {
	SSMConnectionChannel SSMConnectionChannel
}

type DocumentContent

type DocumentContent struct {
	SchemaVersion string                   `json:"schemaVersion" yaml:"schemaVersion"`
	Description   string                   `json:"description" yaml:"description"`
	RuntimeConfig map[string]*PluginConfig `json:"runtimeConfig" yaml:"runtimeConfig"`
	MainSteps     []*InstancePluginConfig  `json:"mainSteps" yaml:"mainSteps"`
	Parameters    map[string]*Parameter    `json:"parameters" yaml:"parameters"`

	// InvokedPlugin field is set when document is invoked from any other plugin.
	// Currently, InvokedPlugin is set only in runDocument Plugin
	InvokedPlugin string
}

DocumentContent object which represents ssm document content.

type DocumentInfo

type DocumentInfo struct {
	// DocumentID is a unique name for file system
	// For Association, DocumentID = AssociationID.RunID
	// For RunCommand, DocumentID = CommandID
	// For Session, DocumentId = SessionId
	DocumentID      string
	CommandID       string
	AssociationID   string
	InstanceID      string
	MessageID       string
	RunID           string
	CreatedDate     string
	DocumentName    string
	DocumentVersion string
	DocumentStatus  ResultStatus
	RunCount        int
	ProcInfo        OSProcInfo
	ClientId        string
	RunAsUser       string
	SessionOwner    string
}

DocumentInfo represents information stored as interim state for a document

type DocumentResult

type DocumentResult struct {
	DocumentName        string
	DocumentVersion     string
	MessageID           string
	AssociationID       string
	PluginResults       map[string]*PluginResult
	Status              ResultStatus
	LastPlugin          string
	NPlugins            int
	UpstreamServiceName UpstreamServiceName
	ResultType          ResultType
	RelatedDocumentType DocumentType
}

DocumentResult is a struct that stores information about the result of the document

type DocumentState

type DocumentState struct {
	DocumentInformation        DocumentInfo
	DocumentType               DocumentType
	SchemaVersion              string
	InstancePluginsInformation []PluginState
	CancelInformation          CancelCommandInfo
	IOConfig                   IOConfiguration
	UpstreamServiceName        UpstreamServiceName
}

DocumentState represents information relevant to a command that gets executed by agent

func (*DocumentState) IsAssociation

func (c *DocumentState) IsAssociation() bool

IsAssociation returns if documentType is association

func (*DocumentState) IsRebootRequired

func (c *DocumentState) IsRebootRequired() bool

IsRebootRequired returns if reboot is needed

type DocumentType

type DocumentType string

DocumentType defines the type of document persists locally.

const (
	// SendCommand represents document type for send command
	SendCommand DocumentType = "SendCommand"
	// CancelCommand represents document type for cancel command
	CancelCommand DocumentType = "CancelComamnd"
	// Association represents document type for association
	Association DocumentType = "Association"
	// StartSession represents document type for start session
	StartSession DocumentType = "StartSession"
	// TerminateSession represents document type for terminate session
	TerminateSession DocumentType = "TerminateSession"
	// SendCommandOffline represents document type for send command received from offline service
	SendCommandOffline DocumentType = "SendCommandOffline"
	// CancelCommandOffline represents document type for cancel command received from offline service
	CancelCommandOffline DocumentType = "CancelCommandOffline"
)

type ICoreModule

type ICoreModule interface {
	ModuleName() string
	ModuleExecute() (err error)
	ModuleStop() error
}

ICoreModule is the very much of core itself will be implemented as plugins that are simply hardcoded to run with agent framework. The hardcoded plugins will implement the ICoreModule

type ICoreModuleWrapper

type ICoreModuleWrapper interface {
	ModuleName() string
	ModuleExecute() (err error)

	ModuleStop(waitTime time.Duration) error
}

ICoreModuleWrapper is the

type IOConfiguration

type IOConfiguration struct {
	OrchestrationDirectory string
	OutputS3BucketName     string
	OutputS3KeyPrefix      string
	CloudWatchConfig       CloudWatchConfiguration
}

IOConfiguration represents information relevant to the output sources of a command

type IPlugin

type IPlugin interface {
	Name() string
	Execute(context context.T, input PluginConfig) (output PluginResult, err error)
	RequestStop() (err error)
}

IPlugin is interface for authoring a functionality of work. Every functionality of work is implemented as a plugin.

type IWorkerPlugin

type IWorkerPlugin IPlugin

IWorkerPlugin is the plugins which do not form part of core These plugins are invoked on demand.

type InstancePluginConfig

type InstancePluginConfig struct {
	Action        string              `json:"action" yaml:"action"` // plugin name
	Inputs        interface{}         `json:"inputs" yaml:"inputs"` // Properties
	MaxAttempts   int                 `json:"maxAttempts" yaml:"maxAttempts"`
	Name          string              `json:"name" yaml:"name"` // unique identifier
	OnFailure     string              `json:"onFailure" yaml:"onFailure"`
	Settings      interface{}         `json:"settings" yaml:"settings"`
	Timeout       int                 `json:"timeoutSeconds" yaml:"timeoutSeconds"`
	Preconditions map[string][]string `json:"precondition" yaml:"precondition"`
}

InstancePluginConfig stores plugin configuration

type OSProcInfo

type OSProcInfo struct {
	Pid       int
	StartTime time.Time
}

OSProcInfo represents information about the new process for outofproc

type Parameter

type Parameter struct {
	DefaultVal     interface{} `json:"default" yaml:"default"`
	Description    string      `json:"description" yaml:"description"`
	ParamType      string      `json:"type" yaml:"type"`
	AllowedVal     []string    `json:"allowedValues" yaml:"allowedValues"`
	AllowedPattern string      `json:"allowedPattern" yaml:"allowedPattern"`
	MinChars       json.Number `json:"minChars,omitempty" yaml:"minChars,omitempty"`
	MaxChars       json.Number `json:"maxChars,omitempty" yaml:"maxChars,omitempty"`
	MinItems       json.Number `json:"minItems,omitempty" yaml:"minItems,omitempty"`
	MaxItems       json.Number `json:"maxItems,omitempty" yaml:"maxItems,omitempty"`
}

A Parameter in the DocumentContent of an MDS message.

type Plugin

type Plugin struct {
	Configuration
	PluginResult
}

Plugin wraps the plugin configuration and plugin result.

type PluginConfig

type PluginConfig struct {
	Settings    interface{} `json:"settings" yaml:"settings"`
	Properties  interface{} `json:"properties" yaml:"properties"`
	Description string      `json:"description" yaml:"description"`
}

PluginConfig stores plugin configuration

type PluginInput

type PluginInput struct {
}

PluginInput represents the input of the plugin.

type PluginOutputter

type PluginOutputter interface {
	String() string
	MarkAsFailed(log log.T, err error)
	MarkAsSucceeded()
	MarkAsInProgress()
	MarkAsSuccessWithReboot()
	MarkAsCancelled()
	MarkAsShutdown()

	AppendInfo(log log.T, message string)
	AppendInfof(log log.T, format string, params ...interface{})
	AppendError(log log.T, message string)
	AppendErrorf(log log.T, format string, params ...interface{})

	// getters/setters
	GetStatus() ResultStatus
	GetStdout() string
	GetStderr() string
	GetExitCode() int

	SetStatus(ResultStatus)
	SetExitCode(int)
}

PluginOutputter defines interface for PluginOutput type

type PluginResult

type PluginResult struct {
	PluginID           string       `json:"pluginID"`
	PluginName         string       `json:"pluginName"`
	Status             ResultStatus `json:"status"`
	Code               int          `json:"code"`
	Output             interface{}  `json:"output"`
	StartDateTime      time.Time    `json:"startDateTime"`
	EndDateTime        time.Time    `json:"endDateTime"`
	OutputS3BucketName string       `json:"outputS3BucketName"`
	OutputS3KeyPrefix  string       `json:"outputS3KeyPrefix"`
	StepName           string       `json:"stepName"`
	Error              string       `json:"error"`
	StandardOutput     string       `json:"standardOutput"`
	StandardError      string       `json:"standardError"`
}

PluginResult represents a plugin execution result.

type PluginRuntimeStatus

type PluginRuntimeStatus struct {
	Status             ResultStatus `json:"status"`
	Code               int          `json:"code"`
	Name               string       `json:"name"`
	Output             string       `json:"output"`
	StartDateTime      string       `json:"startDateTime"`
	EndDateTime        string       `json:"endDateTime"`
	OutputS3BucketName string       `json:"outputS3BucketName"`
	OutputS3KeyPrefix  string       `json:"outputS3KeyPrefix"`
	StepName           string       `json:"stepName"`
	StandardOutput     string       `json:"standardOutput"`
	StandardError      string       `json:"standardError"`
}

PluginRuntimeStatus represents plugin runtime status section in agent response

type PluginState

type PluginState struct {
	Configuration Configuration
	Name          string
	//TODO truncate this struct
	Result PluginResult
	Id     string
}

PluginState represents information stored as interim state for any plugin This has both the configuration with which a plugin gets executed and a corresponding plugin result.

type PreconditionArgument

type PreconditionArgument struct {
	InitialArgumentValue  string
	ResolvedArgumentValue string
}

PreconditionArgument represents a single input value for the plugin precondition operators InitialArgumentValue contains the original value of the argument as specified by the user (e.g. "parameter: {{ paramName }}") ResolvedArgumentValue contains the value of the argument with resolved document parameters (e.g. "parameter: paramValue")

type ResultStatus

type ResultStatus string

ResultStatus provides the granular status of a plugin. These are internal states maintained by agent during the execution of a command/config

const (
	// ResultStatusNotStarted represents NotStarted status
	ResultStatusNotStarted ResultStatus = "NotStarted"
	// ResultStatusInProgress represents InProgress status
	ResultStatusInProgress ResultStatus = "InProgress"
	// ResultStatusSuccess represents Success status
	ResultStatusSuccess ResultStatus = "Success"
	// ResultStatusSuccessAndReboot represents SuccessAndReboot status
	ResultStatusSuccessAndReboot ResultStatus = "SuccessAndReboot"
	// ResultStatusPassedAndReboot represents PassedAndReboot status
	ResultStatusPassedAndReboot ResultStatus = "PassedAndReboot"
	// ResultStatusFailed represents Failed status
	ResultStatusFailed ResultStatus = "Failed"
	// ResultStatusCancelled represents Cancelled status
	ResultStatusCancelled ResultStatus = "Cancelled"
	// ResultStatusTimedOut represents TimedOut status
	ResultStatusTimedOut ResultStatus = "TimedOut"
	// ResultStatusSkipped represents Skipped status
	ResultStatusSkipped ResultStatus = "Skipped"
	// ResultStatusTestFailure represents test failure
	ResultStatusTestFailure ResultStatus = "TestFailure"
	// ResultStatusTestPass represents test passing
	ResultStatusTestPass ResultStatus = "TestPass"
)

func DocumentResultAggregator

func DocumentResultAggregator(log log.T,
	pluginID string,
	pluginOutputs map[string]*PluginResult) (documentStatus ResultStatus, runtimeStatusCounts map[string]int,
	runtimeStatusesFiltered map[string]*PluginRuntimeStatus, runtimeStatuses map[string]*PluginRuntimeStatus)

DocumentResultAggregator aggregates the result from the plugins to construct the agent response

func MergeResultStatus

func MergeResultStatus(current ResultStatus, new ResultStatus) (merged ResultStatus)

MergeResultStatus takes two ResultStatuses (presumably from sub-tasks) and decides what the overall task status should be

func (ResultStatus) IsReboot

func (rs ResultStatus) IsReboot() bool

IsReboot checks whether the result is reboot or not

func (ResultStatus) IsSuccess

func (rs ResultStatus) IsSuccess() bool

IsSuccess checks whether the result is success or not

type ResultType

type ResultType string

ResultType represents document Result types

const (
	// RunCommandResult represents result sent by document worker which ran runCommand documents
	RunCommandResult ResultType = "RunCommandResult"
	// SessionResult represents result sent by session worker to service
	SessionResult ResultType = "SessionResult"
)

type SSMConnectionChannel

type SSMConnectionChannel string
const (
	MGS SSMConnectionChannel = "ssmmessages"
	MDS SSMConnectionChannel = "ec2messages"
)

type SessionDocumentContent

type SessionDocumentContent struct {
	SchemaVersion string                `json:"schemaVersion" yaml:"schemaVersion"`
	Description   string                `json:"description" yaml:"description"`
	SessionType   string                `json:"sessionType" yaml:"sessionType"`
	Inputs        SessionInputs         `json:"inputs" yaml:"inputs"`
	Parameters    map[string]*Parameter `json:"parameters" yaml:"parameters"`
	Properties    interface{}           `json:"properties" yaml:"properties"`
}

SessionDocumentContent object which represents ssm session content.

type SessionInputs

type SessionInputs struct {
	S3BucketName                string             `json:"s3BucketName" yaml:"s3BucketName"`
	S3KeyPrefix                 string             `json:"s3KeyPrefix" yaml:"s3KeyPrefix"`
	S3EncryptionEnabled         interface{}        `json:"s3EncryptionEnabled" yaml:"s3EncryptionEnabled"`
	CloudWatchLogGroupName      string             `json:"cloudWatchLogGroupName" yaml:"cloudWatchLogGroupName"`
	CloudWatchStreamingEnabled  bool               `json:"cloudWatchStreamingEnabled" yaml:"cloudWatchStreamingEnabled"`
	CloudWatchEncryptionEnabled interface{}        `json:"cloudWatchEncryptionEnabled" yaml:"cloudWatchEncryptionEnabled"`
	KmsKeyId                    string             `json:"kmsKeyId" yaml:"kmsKeyId"`
	RunAsEnabled                interface{}        `json:"runAsEnabled" yaml:"runAsEnabled"`
	RunAsDefaultUser            string             `json:"runAsDefaultUser" yaml:"runAsDefaultUser"`
	ShellProfile                ShellProfileConfig `json:"shellProfile" yaml:"shellProfile"`
}

SessionInputs stores session configuration

type ShellProfileConfig

type ShellProfileConfig struct {
	Windows string `json:"windows" yaml:"windows"`
	Linux   string `json:"linux" yaml:"linux"`
}

ShellProfileConfig stores shell profile config

type StatusComm

type StatusComm struct {
	TerminationChan chan struct{}
	DoneChan        chan struct{}
}

StatusComm is a struct that holds channels to pass status between ssmAgentCore go routine and agent's main go routine

type UpstreamServiceName

type UpstreamServiceName string

UpstreamServiceName defines which upstream service (MGS or MDS) the document request came from

const (
	// MessageGatewayService represents messages that came from MGS
	MessageGatewayService UpstreamServiceName = "MessageGatewayService"
	// MessageDeliveryService represents messages that came from MDS
	MessageDeliveryService UpstreamServiceName = "MessageDeliveryService"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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