common

package
v0.0.0-...-f515bce Latest Latest
Warning

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

Go to latest
Published: May 6, 2024 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DiveEnclave                        = "dive"
	DiveRemotePackagePath              = "github.com/hugobyte/dive-packages"
	DiveIconNodeScript                 = "services/jvm/icon/src/node-setup/start_icon_node.star"
	DiveIconDecentralizeScript         = "services/jvm/icon/src/node-setup/setup_icon_node.star"
	DiveEthHardhatNodeScript           = "services/evm/eth/src/node-setup/start-eth-node.star"
	DiveArchwayNodeScript              = "services/cosmvm/archway/src/node-setup/start_node.star"
	DiveCosmosDefaultNodeScript        = "services/cosmvm/cosmos_chains.star"
	DiveNeutronNodeScript              = "services/cosmvm/neutron/src/node-setup/start_node.star"
	RelayServiceNameIconToCosmos       = "ibc-relayer"
	DiveNeutronDefaultNodeScript       = "services/cosmvm/neutron/neutron.star"
	DiveBridgeBtpScript                = "/services/bridges/btp/src/bridge.star"
	DiveBridgeIbcScript                = "/services/bridges/ibc/src/bridge.star"
	PolkadotRemotePackagePath          = "github.com/hugobyte/polkadot-kurtosis-package"
	DivePolkadotDefaultNodeSetupScript = "main.star"
	DivePolkadotParachainNodeSetup     = "/parachain/parachain.star"
	DivePolkadotRelayNodeSetupScript   = "/relaychain/relay-chain.star"
	DivePolkaDotUtilsPath              = "/package_io/utils.star"
	DivePolkaDotExplorerPath           = "/package_io/polkadot_js_app.star"
	DivePolkaDotPrometheusPath         = "/package_io/promethues.star"
	DivePolkaDotGrafanaPath            = "/package_io/grafana.star"
	DiveDryRun                         = false
	DiveDefaultParallelism             = 4
	DiveLogDirectory                   = "/logs/%s"
	DiveDitLogFile                     = "dive_%s.log"
	DiveErrorLogFile                   = "error_%s.log"
	DiveOutFileDirectory               = "/output/"
	DiveOutFile                        = "dive_%s_%s.json"
	ServiceFilePath                    = "services_%s_%s.json"
	DiveAppDir                         = ".dive"
)
View Source
const DiveVersion = "v0.1.2"

!!!!!!!!!!! DO NOT UPDATE! WILL BE UPDATED DURING THE RELEASE PROCESS !!!!!!!!!!!!!!!!!!!!!!

Variables

View Source
var (
	ErrUnknown                 = NewBase(UnknownError, "Unknown Error")
	ErrReadFile                = NewBase(FileReadError, "Failed To Read File")
	ErrWriteFile               = NewBase(FileWriteError, "Failed To Write File")
	ErrOpenFile                = NewBase(FileOpenError, "Failed To Open File")
	ErrNotExistsFile           = NewBase(FileNotExistError, "File Doesn't Exists")
	ErrInitializingKurtosis    = NewBase(KurtosisInitError, "Error While Initializing Kurtosis")
	ErrInitializingCLI         = NewBase(CLIInitError, "Error While Initializing CLI")
	ErrEnclaveNameInvalid      = NewBase(InvalidEnclaveError, "Invalid Enclave Name")
	ErrUnsupportedOS           = NewBase(UnsupportedOSError, "Unsupported OS")
	ErrInvalidCommand          = NewBase(InvalidCommandError, "Invalid Command")
	ErrEnclaveNotExist         = NewBase(EnclaveNotExistError, "Enclave Does Not Exist")
	ErrInvalidEnclaveContext   = NewBase(InvalidEnclaveContextError, "Invalid Enclave Context")
	ErrInvalidEnclaveConfig    = NewBase(InvalidEnclaveConfigError, "Invalid Enclave Config")
	ErrInvalidCommandArguments = NewBase(InvalidCommandArgumentsError, "Invalid Command Arguments")
	ErrInvalidKurtosisContext  = NewBase(InvalidKurtosisContextError, "Invalid Kurtosis Context")
	ErrDataMarshall            = NewBase(DataMarshallError, "Data Marshall Error")
	ErrDataUnMarshall          = NewBase(DataUnMarshallError, "Data UnMarshall Error")
	ErrStarlarkRunFailed       = NewBase(StarlarkRunFailedError, "Starlark Run Failed")
	ErrNotFound                = NewBase(NotFoundError, "Not Found")
	ErrStarlarkResponse        = NewBase(StarlarkResponseError, "Starlark Response Error")
	ErrPath                    = NewBase(InvalidPathError, "Failed To Resolve Path")
	ErrInvalidFile             = NewBase(InvalidFileError, "Failed To Resolve to File")
	ErrKurtosisService         = NewBase(KurtosisServiceError, "Kurtosis Service Error")
	ErrInvalidChain            = NewBase(InvalidChain, "Not A Valid Chain")
	ErrPortAllocation          = NewBase(PortError, "Failed To Allocate Port")
	ErrEmptyFields             = NewBase(EmptyFieldsError, "Missing Fields In The Config File")
	ErrMissingFlags            = NewBase(MissingFlagsError, "Missing Flags")
	ErrInvalidFlag             = NewBase(InvalidFlagError, "Invalid Flag Usage")
	ErrInvalidConfig           = NewBase(InvalidConfigError, "Invalid Config")
	ErrFailedPathConversion    = NewBase(PathConversionError, "Failed To Convert Path to Absolute Path")
)
View Source
var DiveLogs bool
View Source
var EnclaveName string

Functions

func AsValue

func AsValue(ptr interface{}, err error) bool

func CheckPort

func CheckPort(port int) bool

Check if a port is available

func Errorc

func Errorc(code ErrorCode, msg string) error

func Errorcf

func Errorcf(code ErrorCode, f string, args ...interface{}) error

func GetAbsolutePath

func GetAbsolutePath(filePath string) (string, error)

The function returns the absolute path for a given relative path

func GetAvailablePort

func GetAvailablePort() (int, error)

The function `GetAvailablePort` generates a random port number between 1024 and 65535 and checks if it is available by calling the `CheckPort` function, and returns the first available port or an error if no port is available.

func GetSerializedData

func GetSerializedData(cliContext *Cli, response chan *kurtosis_core_rpc_api_bindings.StarlarkRunResponseLine) (string, map[string]string, map[string]bool, error)

The function `GetSerializedData` retrieves serialized data, service information, skipped instructions, and any errors from a given response channel.

func GetStarlarkRunConfig

func GetStarlarkRunConfig(params string, relativePathToMainFile string, mainFunctionName string) *starlark_run_config.StarlarkRunConfig

This function returns a StarlarkRunConfig object with the provided parameters.

func Is

func Is(err, target error) bool

Is checks whether err is caused by the target.

func LoadConfig

func LoadConfig(cliContext *Cli, config ConfigLoader, filePath string) error

The function `LoadConfig` loads a configuration either from a default source or from a specified file path.

func NewBase

func NewBase(code ErrorCode, msg string) *baseError

func NewDiveCommandBuilder

func NewDiveCommandBuilder() *diveCommandBuilder

func NewDiveContext1

func NewDiveContext1() *diveContext

func NewDiveFileHandler

func NewDiveFileHandler() *diveFileHandler

The function returns a new instance of the diveFileHandler struct.

func NewDiveLogger

func NewDiveLogger(infoFilePath string, errorFilePath string) *diveLogger

The function `NewDiveLogger` creates a new instance of a logger that logs information and errors to separate files.

func NewDiveSpinner

func NewDiveSpinner() *diveSpinner

The function NewDiveSpinner returns a new instance of the diveSpinner struct.

func OpenFile

func OpenFile(URL string) error

The OpenFile function opens a file using the appropriate command based on the operating system.

func ValidateArgs

func ValidateArgs(args []string) error

The function "ValidateArgs" checks if the given arguments are empty and returns an error if they are not.

func WithCode

func WithCode(err error, code ErrorCode) error

func WrapCodeToError

func WrapCodeToError(e error, c ErrorCode, msg string) error

func WrapCodeToErrorf

func WrapCodeToErrorf(e error, c ErrorCode, f string, args ...interface{}) error

func WrapMessageToError

func WrapMessageToError(e error, msg string) error

func WrapMessageToErrorf

func WrapMessageToErrorf(e error, f string, args ...interface{}) error

func WriteBridgeResponseData

func WriteBridgeResponseData(serviceName string, data string, cliContext *Cli, fileName string) error

The function writes bridge response data to a JSON file.

func WriteServiceResponseData

func WriteServiceResponseData(serviceName string, data DiveServiceResponse, cliContext *Cli, fileName string) error

The function writes service response data to a JSON file.

Types

type BridgeServices

type BridgeServices map[string]*DiveBridgeResponse

type Cli

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

func GetCli

func GetCli(enclaveName string) *Cli

func GetCliWithKurtosisContext

func GetCliWithKurtosisContext(enclaveName string) *Cli

func (*Cli) Context

func (c *Cli) Context() Context

func (*Cli) Debug

func (c *Cli) Debug(message string)

func (*Cli) Debugf

func (c *Cli) Debugf(format string, args ...interface{})

func (*Cli) Error

func (c *Cli) Error(err error)

func (*Cli) Errorf

func (c *Cli) Errorf(format string, err error, args ...interface{})

func (*Cli) Fatal

func (c *Cli) Fatal(err error)

func (*Cli) Fatalf

func (c *Cli) Fatalf(format string, err error, args ...interface{})

func (*Cli) FileHandler

func (c *Cli) FileHandler() FileHandler

func (*Cli) Info

func (c *Cli) Info(message string)

func (*Cli) Infof

func (c *Cli) Infof(format string, args ...interface{})

func (*Cli) Logger

func (c *Cli) Logger() Logger

func (*Cli) Spinner

func (c *Cli) Spinner() Spinner

func (*Cli) StartSpinnerIfNotVerbose

func (c *Cli) StartSpinnerIfNotVerbose(message string, verbose bool)

func (*Cli) StopSpinnerIfNotVerbose

func (c *Cli) StopSpinnerIfNotVerbose(message string, verbose bool)

func (*Cli) Warn

func (c *Cli) Warn(message string)

func (*Cli) Warnf

func (c *Cli) Warnf(format string, args ...interface{})

type CommandBuilder

type CommandBuilder interface {
	// AddCommand adds a subcommand to the command.
	AddCommand(cmd *cobra.Command) CommandBuilder

	// Add Persistent Bool Flag
	AddBoolPersistentFlag(boolV *bool, name string, value bool, usage string) CommandBuilder

	// Add Persistent Bool Flag with Short hand
	AddBoolPersistentFlagWithShortHand(boolV *bool, name string, value bool, usage string, shorthand string) CommandBuilder

	// Add Persistent String Flag
	AddStringPersistentFlag(stringV *string, name string, value string, usage string) CommandBuilder

	// Add Persistent String Flag with Short hand
	AddStringPersistentFlagWithShortHand(stringV *string, name string, shorthand string, value string, usage string) CommandBuilder

	// Add StringFlag adds a string flag to the command that persists
	AddStringFlag(stringV *string, name string, value string, usage string) CommandBuilder

	// Add StringFlag adds a string flag to the command that persists with short hand
	AddStringFlagWithShortHand(stringV *string, name string, shorthand string, value string, usage string) CommandBuilder

	// Add StringSliceFlag adds a slice of string flag to the command that persists with short hand
	AddStringSliceFlagWithShortHand(stringV *[]string, name string, shorthand string, value []string, usage string) CommandBuilder

	// Add BooFlag adds a boolean flag to the command that persists
	AddBoolFlag(boolV *bool, name string, value bool, usage string) CommandBuilder

	AddBoolFlagWithShortHand(boolV *bool, name string, shorthand string, value bool, usage string) CommandBuilder

	// Build constructs and returns the Cobra command.
	Build() *cobra.Command

	// SetUse sets the Use field of the command.
	SetUse(use string) CommandBuilder

	// SetShort sets the Short field of the command.
	SetShort(short string) CommandBuilder

	// SetLong sets the Long field of the command.
	SetLong(long string) CommandBuilder

	// SetRun sets the Run field of the command.
	SetRun(run func(cmd *cobra.Command, args []string)) CommandBuilder

	// ToggleHelpCommand enables or disables the automatic generation of a help command.
	ToggleHelpCommand(enable bool) CommandBuilder

	// SetRunE sets the RunE field of the command.
	SetRunE(run func(cmd *cobra.Command, args []string) error) CommandBuilder

	// MarkFlagsAsRequired marks multiple flags as required for the command.
	MarkFlagsAsRequired(flags []string) CommandBuilder

	// MarkFlagRequired marks a flag as required for the command.
	MarkFlagRequired(flag string) CommandBuilder

	// AddBoolFlagP adds a boolean flag with shorthand to the command.
	AddBoolFlagP(name string, shorthand string, value bool, usage string) CommandBuilder
}

CommandBuilder is an interface for building a Cobra command.

type ConfigLoader

type ConfigLoader interface {
	LoadDefaultConfig() error
	LoadConfigFromFile(cliContext *Cli, filePath string) error
}

The ConfigLoader interface defines methods for loading default configurations and configurations from a file. @property {error} LoadDefaultConfig - This method is responsible for loading the default configuration. It does not take any arguments and returns an error if there is any issue loading the default configuration. @property {error} LoadConfigFromFile - This method is responsible for loading a configuration file from a given file path. It takes two parameters: a cliContext object, which represents the current command-line interface context, and a filePath string, which represents the path to the configuration file. The method returns an error if there is any issue loading the

type Context

type Context interface {
	// GetContext returns the underlying context.Context.
	GetContext() context.Context

	// GetKurtosisContext returns the Kurtosis context, including configuration and utility functions.
	GetKurtosisContext() (*kurtosis_context.KurtosisContext, error)

	// GetEnclaves retrieves information about all enclaves currently running.
	GetEnclaves() ([]EnclaveInfo, error)

	// GetAllEnclavesServices retrives the all running services for all active enclaves.
	GetAllEnlavesServices() (map[string]map[services.ServiceName]services.ServiceUUID, error)

	// GetEnclaveContext retrieves the context of a specific enclave by its name.
	GetEnclaveContext(enclaveName string) (*enclaves.EnclaveContext, error)

	// IsLocalKurtosisContext checks whether current running kurtosis context is local.
	IsLocalKurtosisContext() (bool, error)

	// CleanEnclaves stops and cleans up all running enclaves.
	CleanEnclaves() ([]*EnclaveInfo, error)

	// CleanEnclaveByName stops and cleans up a specific enclave by its name.
	CleanEnclaveByName(enclaveName string) error

	// CheckSkippedInstructions checks if specific instructions are skipped in the current kurtosis run context.
	CheckSkippedInstructions(instructions map[string]bool) bool

	// StopService stops a specific service within an enclave by name.
	StopService(serviceName string, enclaveName string) error

	// StopServices stops all services within a specific enclave.
	StopServices(enclaveName string) error

	// RemoveServices stops and removes all services within a specific enclave.
	RemoveServices(enclaveName string) error

	// RemoveService stops and removes a specific service within an enclave by name.
	RemoveService(serviceName string, enclaveName string) error

	// RemoveServicesByServiceNames stops and removes services within an enclave based on a map of service names.
	RemoveServicesByServiceNames(services map[string]string, enclaveName string) error

	// CreateEnclave creates a new enclave with the specified name and returns its context.
	CreateEnclave(enclaveName string) (*enclaves.EnclaveContext, error)

	// Get the short UUID of the given enclave.
	GetShortUuid(enclaveName string) (string, error)

	// Exit terminates the execution of the context with the given status code.
	Exit(statusCode int)
}

Context represents a context for managing and interacting with enclaves and services.

type DiveBridgeResponse

type DiveBridgeResponse map[string]interface{}

func (*DiveBridgeResponse) Decode

func (dive *DiveBridgeResponse) Decode(responseData []byte) (*DiveBridgeResponse, error)

type DiveMultipleServiceResponse

type DiveMultipleServiceResponse struct {
	Dive map[string]*DiveServiceResponse
}

func (*DiveMultipleServiceResponse) ConcatenateDiveResults

func (*DiveMultipleServiceResponse) Decode

func (dive *DiveMultipleServiceResponse) Decode(responseData []byte) (*DiveMultipleServiceResponse, error)

func (*DiveMultipleServiceResponse) EncodeToString

func (dive *DiveMultipleServiceResponse) EncodeToString() (string, error)

type DiveServiceResponse

type DiveServiceResponse struct {
	ServiceName          string `json:"service_name,omitempty"`
	PublicEndpoint       string `json:"endpoint_public,omitempty"`
	PrivateEndpoint      string `json:"endpoint,omitempty"`
	KeyPassword          string `json:"keypassword,omitempty"`
	KeystorePath         string `json:"keystore_path,omitempty"`
	Network              string `json:"network,omitempty"`
	NetworkName          string `json:"network_name,omitempty"`
	NetworkId            string `json:"nid,omitempty"`
	ChainId              string `json:"chain_id,omitempty"`
	ChainKey             string `json:"chain_key,omitempty"`
	PrometheusEndpoint   string `json:"endpoint_prometheus,omitempty"`
	Prometheus           bool   `json:"prometheus,omitempty"`
	IpAddress            string `json:"ip_address,omitempty"`
	Node                 string `json:"node-type,omitempty"`
	PrometheusPort       int    `json:"prometheus_port,omitempty"`
	PrometheusPublicPort int    `json:"prometheus_public_port,omitempty"`
}

func (*DiveServiceResponse) Decode

func (dive *DiveServiceResponse) Decode(responseData []byte) (*DiveServiceResponse, error)

The `Decode` function is a method of the `DiveServiceResponse` struct. It takes a byte slice `responseData` as input and attempts to decode it into a `DiveServiceResponse` object.

func (*DiveServiceResponse) EncodeToString

func (dive *DiveServiceResponse) EncodeToString() (string, error)

The `EncodeToString` function is a method of the `DiveServiceResponse` struct. It encodes the `DiveServiceResponse` object into a JSON string representation.

type EnclaveInfo

type EnclaveInfo struct {
	Name        string
	Uuid        string
	ShortUuid   string
	CreatedTime string
	Status      string
}

The EnclaveInfo type represents information about an enclave, including its name, UUID, short UUID, creation time, and status. @property {string} Name - The name of the enclave. @property {string} Uuid - The Uuid property is a unique identifier for the enclave. It is used to distinguish one enclave from another. @property {string} ShortUuid - The ShortUuid property is a shortened version of the Uuid property. It is typically used to provide a more concise representation of the unique identifier for the Enclave. @property {string} CreatedTime - The CreatedTime property in the EnclaveInfo struct represents the timestamp when the enclave was created. It is a string that typically follows a specific date and time format, such as "YYYY-MM-DD HH:MM:SS". @property {string} Status - The "Status" property in the EnclaveInfo struct represents the current status of the enclave. It can have different values depending on the implementation, but some common values could be "active", "inactive", "error", or "unavailable".

type ErrorCode

type ErrorCode int
const (
	UnknownError ErrorCode = ErrorCodeGeneral + iota
	FileReadError
	FileWriteError
	FileOpenError
	FileNotExistError
	KurtosisInitError
	CLIInitError
	InvalidEnclaveNameError
	UnsupportedOSError
	InvalidCommandError
	InvalidEnclaveError
	EnclaveNotExistError
	InvalidEnclaveContextError
	InvalidEnclaveConfigError
	InvalidCommandArgumentsError
	InvalidKurtosisContextError
	DataMarshallError
	DataUnMarshallError
	StarlarkRunFailedError
	NotFoundError
	StarlarkResponseError
	InvalidPathError
	InvalidFileError
	KurtosisServiceError
	InvalidChain
	PortError
	EmptyFieldsError
	MissingFlagsError
	InvalidFlagError
	InvalidConfigError
	PathConversionError
)
const (
	ErrorCodeGeneral ErrorCode = iota + 1000
)

func CodeOf

func CodeOf(e error) ErrorCode

func (ErrorCode) Equals

func (c ErrorCode) Equals(e error) bool

func (ErrorCode) Errorf

func (c ErrorCode) Errorf(f string, args ...interface{}) error

func (ErrorCode) New

func (c ErrorCode) New(msg string) error

func (ErrorCode) Wrap

func (c ErrorCode) Wrap(e error, msg string) error

func (ErrorCode) Wrapf

func (c ErrorCode) Wrapf(e error, f string, args ...interface{}) error

type ErrorCoder

type ErrorCoder interface {
	error
	ErrorCode() ErrorCode
}

Extract Code from Custom Error Messages

func CoderOf

func CoderOf(e error) (ErrorCoder, bool)

type FileHandler

type FileHandler interface {
	// ReadFile reads the contents of a file specified by the filePath.
	ReadFile(filePath string) ([]byte, error)

	// ReadJson reads the contents of a JSON file specified by the fileName
	// and unmarshals it into the provided object (obj).
	ReadJson(fileName string, obj interface{}) error

	// ReadAppFile reads the contents of an application-specific file specified by the fileName.
	ReadAppFile(fileName string) ([]byte, error)

	// WriteFile writes the provided data to a file specified by the fileName.
	WriteFile(fileName string, data []byte) error

	// WriteJson writes the provided data, marshaled as JSON, to a file specified by the fileName.
	WriteJson(fileName string, data interface{}) error

	// WriteAppFile writes the provided data to an application-specific file specified by the fileName.
	WriteAppFile(fileName string, data []byte) error

	// GetPwd returns the current working directory.
	GetPwd() (string, error)

	// GetHomeDir returns the home directory of the user.
	GetHomeDir() (string, error)

	// MkdirAll creates a directory along with any necessary parents,
	// and sets the specified permission.
	MkdirAll(dirPath string, permission fs.FileMode) error

	// OpenFile opens a file with the specified fileOpenMode and permission.
	OpenFile(filePath string, fileOpenMode string, permission int) (*os.File, error)

	// RemoveFile removes the file specified by the fileName.
	RemoveFile(fileName string) error

	// RemoveFiles removes multiple files specified by the fileNames.
	RemoveFiles(fileNames []string) error

	// RemoveDir removes the output directories by enclaveName.
	RemoveDir(enclaveName string) error

	// RemoveDir removes all the output directories.
	RemoveAllDir() error

	// GetAppDirPathOrAppFilePath returns the path to the application directory or a specific file within it
	// based on the provided fileName.
	GetAppDirPathOrAppFilePath(fileName string) (string, error)
}

FileHandler defines methods for handling file-related operations.

type Logger

type Logger interface {
	// SetErrorToStderr configures the logger to output error messages to stderr.
	SetErrorToStderr()

	// SetOutputToStdout configures the logger to output messages to stdout.
	SetOutputToStdout()

	// Debug logs a debug message.
	Debug(message string)

	// Info logs an informational message.
	Info(message string)

	// Warn logs a warning message.
	Warn(message string)

	// Error logs an error with an error code and a corresponding error message.
	Error(errorCode ErrorCode, errorMessage string)

	// Fatal logs a fatal error with an error code and a corresponding error message,
	// and then exits the program.
	Fatal(errorCode ErrorCode, errorMessage string)

	// Infof logs a formatted informational message.
	Infof(format string, args ...interface{})

	// Warnf logs a formatted warning message.
	Warnf(format string, args ...interface{})

	// Debugf logs a formatted debug message.
	Debugf(format string, args ...interface{})

	// Errorf logs a formatted error with an error code and a corresponding error message.
	Errorf(errorCode ErrorCode, format string, args ...interface{})

	// Fatalf logs a formatted fatal error with an error code and a corresponding error message,
	// and then exits the program.
	Fatalf(errorCode ErrorCode, format string, args ...interface{})
}

Logger represents a generic logging interface with various log levels and formatting options.

type Services

type Services map[string]*DiveServiceResponse

type Spinner

type Spinner interface {
	// SetSuffixMessage sets a suffix message to be displayed beside the spinner.
	SetSuffixMessage(message, color string)

	// SetPrefixMessage sets a prefix message to be displayed beside the spinner.
	SetPrefixMessage(message string)

	// SetColor sets the color of the spinner.
	SetColor(color string)

	// Start starts the spinner with the specified color.
	Start(color string)

	// StartWithMessage starts the spinner with a specified message and color.
	StartWithMessage(message, color string)

	// Stop stops the spinner.
	Stop()

	// StopWithMessage stops the spinner and displays a final message.
	StopWithMessage(message string)
}

Spinner is an interface for managing and controlling a terminal spinner.

Jump to

Keyboard shortcuts

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