status

package
v0.0.0-...-a8b8e24 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: Apache-2.0 Imports: 8 Imported by: 10

Documentation

Overview

Package status handles chef-automate CLI errors

It's built on and intended to be used in conjunction with the annotated error types provided in the the github.com/pkg/errors library. We build on top of the extended error types and annotate with our own status information.

The library can be used to initialize new errors:

err := status.New(status.MustBeRootError, "You must be root to run this command")

Or to wrap an existing err:

_, err := ioutil.ReadAll("myfile")
if err != nil {
	return status.Wrap(err, FileAccessError, "Unable to read myfile")
}

Each error type is a public constant that reflects the integer representation of the error.

To access the extended information in the error you can use status.Error interface:

if err, ok := err.(status.Error); ok {
	fmt.Println(err.ExitCode())
	fmt.Println(err.Description())

	for _, f := range err.StackTrace() {
		fmt.Printf("%+s:%d", f)
	}
}

Index

Constants

View Source
const (
	Ok      = "OK"
	Failure = "ERROR"
)

Each invocation of the chef-automate CLI results in either a Ok or Failure result.

View Source
const (
	VerifyChecksError                 = 125
	ConfigVerifyError                 = 124
	PromptFailed                      = 126
	FailedToGenConfig                 = 127
	HardwareCalError                  = 128
	IpAccessError                     = 123
	InsufficientSpaceError            = 122
	CalDestDirSizeError               = 121
	CalESDirSizeError                 = 120
	AvailableSpaceError               = 119
	InappropriateSettingError         = 118
	RestartDeploymentServiceError     = 117
	IAMResetV1DatabaseError           = 116
	IAMUpgradeV2DatabaseError         = 115
	APIUnreachableError               = 114
	UnknownError                      = 113
	UpdateExecError                   = 112
	APIError                          = 100
	DeploymentServiceUnreachableError = 99
	DeploymentServiceCallError        = 98
	UnhealthyStatusError              = 97
	InvalidCommandArgsError           = 96
	PreflightError                    = 95
	DeployError                       = 94
	ConfigError                       = 93
	MustBeRootError                   = 92
	DiagnosticsError                  = 91
	FileAccessError                   = 90
	LicenseError                      = 89
	MarshalError                      = 88
	UpgradeError                      = 87
	BackupError                       = 86
	UninstallError                    = 85
	DownloadError                     = 84
	AirgapCreateInstallBundleError    = 83
	AirgapUnpackInstallBundleError    = 82
	ServiceStartError                 = 81
	ServiceUnloadError                = 80
	BackupRestoreError                = 79
	TimedOutError                     = 78
	PackageInstallError               = 77
	GatherLogsError                   = 76
	HabAPIError                       = 75
	HabCommandError                   = 74
	ProfileError                      = 73
	TraceError                        = 72
	CommandExecutionError             = 71
	DatabaseError                     = 70
	SnapshotChecksumMismatchError     = 69
	HabUserAccessError                = 68
)

When an invocation of the chef-automate CLI results in a Failure it exits with one of the following codes that identifies the error types.

Variables

View Source
var ErrorMetadata = map[int][]string{
	VerifyChecksError:                 {"125", "VerifyChecksError", "Verify Checks failed"},
	ConfigVerifyError:                 {"124", "ConfigVerifyError", "Config Verification failed"},
	HardwareCalError:                  {"128", "HardwareCalError", "Hardware Calculator failed to provide Hardware Estimates"},
	PromptFailed:                      {"126", "PromptFailed", "Prompt failed and exited with error"},
	FailedToGenConfig:                 {"127", "FailedToGenConfig", "Failed to Generate config with given inputs"},
	InsufficientSpaceError:            {"122", "InsufficientSpaceError", "Insufficient disk space"},
	CalDestDirSizeError:               {"121", "CalDestDirSizeError", "Error in calculating Dest directory size"},
	CalESDirSizeError:                 {"120", "CalESDirSizeError", "Error in calculating ES directory size"},
	AvailableSpaceError:               {"119", "AvailableSpaceError", "Error in getting available space"},
	InappropriateSettingError:         {"118", "InappropriateSettingError", "Settings are not appropriate"},
	RestartDeploymentServiceError:     {"117", "DeploymentServiceError", "Failed to restart Deployment Service"},
	IAMResetV1DatabaseError:           {"116", "UnknownError", "Failed to reset IAM state to v1"},
	IAMUpgradeV2DatabaseError:         {"115", "UnknownError", "Failed to upgrade IAM to v2"},
	APIUnreachableError:               {"114", "APIUnreachableError", "Could not connect to Automate API"},
	UnknownError:                      {"113", "UnknownError", "An unknown issue occurred during execution"},
	UpdateExecError:                   {"112", "UpdateExecError", "An issue occurred when trying to run an auto-updated CLI executable"},
	APIError:                          {"100", "APIError", "An API error occurred during execution"},
	DeploymentServiceUnreachableError: {"99", "DeploymentServiceUnreachableError", "Unable to make a request to the deployment-service"},
	DeploymentServiceCallError:        {"98", "DeploymentServiceCallError", "A request to the deployment-service failed"},
	UnhealthyStatusError:              {"97", "UnhealthyStatusError", "System status is unhealthy"},
	InvalidCommandArgsError:           {"96", "InvalidCommandArgsError", "The arguments provided are invalid"},
	PreflightError:                    {"95", "PreflightError", "One or more preflight checks failed"},
	DeployError:                       {"94", "DeployError", "Unable to install, configure and start the service"},
	ConfigError:                       {"93", "ConfigError", "The configuration is invalid"},
	MustBeRootError:                   {"92", "MustBeRootError", "The command must be run as the root user"},
	DiagnosticsError:                  {"91", "DiagnosticsError", "One or more diagnostics checks failed"},
	FileAccessError:                   {"90", "FileAccessError", "Unable to access the file or directory"},
	LicenseError:                      {"89", "LicenseError", "The license is invalid, expired or incomplete"},
	MarshalError:                      {"88", "MarshalError", "Unable to convert or deconvert a textual representation of an internal object"},
	UpgradeError:                      {"87", "UpgradeError", "An issue occurred during the upgrade"},
	BackupError:                       {"86", "BackupError", "An issue occurred when creating or restoring a backup"},
	UninstallError:                    {"85", "UninstallError", "An issue occurred when attempting to uninstall Chef Automate"},
	DownloadError:                     {"84", "DownloadError", "An issue occurred when attempting to perform a file download"},
	AirgapCreateInstallBundleError:    {"83", "AirgapCreateInstallBundleError", "An issue occurred when attempting to create the airgap install bundle"},
	AirgapUnpackInstallBundleError:    {"82", "AirgapUnpackInstallBundleError", "An issue occurred when attempting to unpack the airgap install bundle"},
	ServiceStartError:                 {"81", "ServiceStartError", "Unable to start the habitat service"},
	ServiceUnloadError:                {"80", "ServiceUnloadError", "Unable to unload the habitat service"},
	BackupRestoreError:                {"79", "BackupRestoreError", "Unable to restore backup"},
	TimedOutError:                     {"78", "TimedOutError", "Timed out waiting for the operation to complete"},
	PackageInstallError:               {"77", "PackageInstallError", "Unable to install the habitat package"},
	GatherLogsError:                   {"76", "GatherLogsError", "Unable to complete log gathering"},
	HabAPIError:                       {"75", "HabAPIError", "An issue occurred when attempting to query the Habitat API"},
	HabCommandError:                   {"74", "HabCommandError", "An issue occurred when running a hab command"},
	ProfileError:                      {"73", "ProfileError", "An issue occurred when attempting to profile the request"},
	TraceError:                        {"72", "TraceError", "An issue occurred when attempting to trace the request"},
	CommandExecutionError:             {"71", "CommandExecutionError", "An issue occurred when running an executable command"},
	DatabaseError:                     {"70", "DatabaseError", "An issue occurred with the database"},
	SnapshotChecksumMismatchError:     {"69", "SnapshotChecksumMismatchError", "A file in the snapshot did not have the expected checksum"},
	HabUserAccessError:                {"68", "HabUserAccessError", "Unable to access file or directory with the hab user"},
}

ErrorMetadata is a map keyed by an error code that returns a slice of strings with metadata for the error. The metadata is used both to translate between an error code and its type and a description, but also as a way to generate documentation.

View Source
var GlobalResult interface{}

GlobalResult is used to report command results in structured format (JSON) in support of managed service integrations.

Functions

func Annotate

func Annotate(err error, exitCode int) error

Annotate takes an error and exit code and restores a status.Error that wraps and annotates the error with the help text associated with the error code. This is useful for adding exit code information but a wrap message isn't required.

func Cause

func Cause(err error) error

Cause returns the first error in the causal chain

func Description

func Description(err error) string

Description take an error and returns a formatted description of the error causal chain.

func ErrorType

func ErrorType(err error) string

func Errorf

func Errorf(exitCode int, fmtStr string, args ...interface{}) error

Errorf takes an exit code, format string and format args and returns a new status.Error.

func ExitCode

func ExitCode(err error) int

ExitCode follows the error cause chain until it finds the oldest status error and returns its error code.

func IsStatusError

func IsStatusError(err error) bool

IsStatusError returns true if the error is an error with a status

func New

func New(exitCode int, message string) error

New takes an exit code and message and returns a new status.Error.

func Recovery

func Recovery(err error) string

Recovery returns the first error in the causal chain that includes recovery information

func StackTrace

func StackTrace(err error) errors.StackTrace

StackTrace follows the error cause chain until it finds the oldest traceable error and returns its stack trace.

func WithRecovery

func WithRecovery(err error, rec string) error

WithRecovery sets optional recovery instructions on an error

func Wrap

func Wrap(err error, exitCode int, message string) error

Wrap takes an error, exit code and message and returns a status.Error that wraps the origin error.

func Wrapf

func Wrapf(err error, exitCode int, fmtStr string, args ...interface{}) error

Wrapf takes an error, exit code, format string and format args and returns a status.Error that wraps the origin error with a formatted message.

Types

type CmdResult

type CmdResult struct {
	// The command that was run with args
	Command string `json:"command"`
	// Either Ok ("OK") or Failure ("ERROR") indicating whether the operation
	// succeeded or not.
	Status string `json:"status"`
	// Integer error code uniquely identifying the error. Also used as the exit
	// code for the command (will be 0 when Status is Ok).
	ErrorCode int `json:"error_code"`
	// Human readable summary of the error.
	ErrorDescription string `json:"error_description"`
	// Description of the inner error that caused the failure. Useful for
	// debugging; may not be a user-friendly description.
	ErrorCause string `json:"error_cause"`
	// The call stack trace.
	ErrorStackTrace string `json:"error_stack_trace"`
	// Optional recovery instructions
	ErrorRecovery string `json:"error_recovery"`
	// The error type
	ErrorType string `json:"error_type"`

	Result interface{} `json:"result,omitempty"`
}

CmdResult represents the result of an invocation of the chef-automate CLI. It translates errors into standard error codes and allows us to serialize command results to JSON.

func NewCmdResult

func NewCmdResult(err error) *CmdResult

NewCmdResult takes an error and returns a new instance of CmdResult.

func (*CmdResult) WriteFile

func (cr *CmdResult) WriteFile(path string)

WriteFile serializes the CmdResult to JSON and writes the result to path. Errors encountered are logged and ignored.

type Error

type Error interface {
	error
	// contains filtered or unexported methods
}

Error is an interface that extends the errors interface to include an exit code and description.

Jump to

Keyboard shortcuts

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