cmd

package
v1.28.1 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Overview

Package cmd contains all the main commands for the `geneos` program

Index

Constants

View Source
const (
	CommandGroupConfig      = "config"
	CommandGroupComponents  = "components"
	CommandGroupCredentials = "credentials"
	CommandGroupManage      = "manage"
	CommandGroupOther       = "other"
	CommandGroupProcess     = "process"
	CommandGroupSubsystems  = "subsystems"
	CommandGroupView        = "view"
)

Available command groups for Cobra command set-up. This influences the display of the help text for the top-level `geneos` command.

View Source
const (
	// CmdWildcardNames should be "true" or "false". True will pass all
	// names through a path.Match style lookup
	CmdWildcardNames = "wildcard"

	// CmdNonInstanceArgsError should be "true" to cause a failure if
	// any args do not match any instances. This should prevent
	// misspelled instance names from dropping through as parameters.
	CmdNonInstanceArgsError = "noninstanceargserror"

	// CmdAllInstancesMustMatch should be "true" to cause a failure if
	// any instance name patterns do not match any instances. This
	// should prevent misspelled instance names from being ignored.
	CmdAllInstancesMustMatch = "allmustmatch"

	// CmdKeepHosts should be "true" to not expand "@host", for command
	// like copy/move
	CmdKeepHosts = "hosts"

	// CmdReplacedBy should be set to the new command that replaces
	// this one. It should be a full path without the executable, e.g.
	// "package install"
	CmdReplacedBy = "replacedby"

	// CmdRequireHome shouw be "true" if the command requires the Geneos
	// home directory to be set, initialised or not
	CmdRequireHome = "needshomedir"

	// CmdGlobal should be "true" if an empty list of instances should
	// mean all instances.
	CmdGlobal = "global"

	// CmdAllowRoot should be "true" to allow running as root, otherwise
	// the command will fail if the effective user ID is 0. This can be
	// overridden by the `--allow-root` flag, which will set this
	// annotation to "true" for the duration of the command, or the
	// global configuration option `allow-root` which will set this
	// annotation to "true" for all commands.
	CmdAllowRoot = "allowroot"
)

Command annotation types for command behaviour

Annotations must be read-only.

View Source
const CmdKey = CmdKeyType("data")

Variables

View Source
var AllowRoot bool
View Source
var Cmd = &cobra.Command{
	Use:   cordial.ExecutableName() + " COMMAND [flags] [TYPE] [NAME...] [parameters...]",
	Short: "Take control of your Geneos environments",
	Long:  geneosCmdDescription,
	Example: strings.ReplaceAll(`
geneos init demo -u email@example.com -l
geneos ps
geneos restart
`, "|", "`"),

	Annotations: map[string]string{
		CmdRequireHome: "true",
		CmdAllowRoot:   "true",
	},
	CompletionOptions: cobra.CompletionOptions{
		DisableDefaultCmd: true,
	},
	Version:               cordial.VERSION,
	DisableAutoGenTag:     true,
	DisableSuggestions:    true,
	DisableFlagsInUseLine: true,

	PersistentPreRunE: func(command *cobra.Command, args []string) (err error) {
		ctx := context.WithValue(context.Background(), CmdKey, &CmdValType{})
		command.SetContext(ctx)

		command.Root().ParseFlags(args)

		if os.Geteuid() == 0 && !AllowRoot && command.Annotations[CmdAllowRoot] != "true" && command.Name() != "help" {
			return fmt.Errorf("running as root is not allowed, use --allow-root to override")
		}

		// check for AnnotationReplacedBy annotation, warn the user, run the new
		// command later (after prerun) but if the help flag is set
		// output the help for the new command and cleanly exit.
		var realcmd *cobra.Command

		if r, ok := command.Annotations[CmdReplacedBy]; ok {
			var newargs []string
			realcmd, newargs, err = command.Root().Find(append(strings.Split(r, " "), args...))
			if err != nil {
				log.Error("error finding replacement command", slog.Any("error", err))
				return err
			}
			if realcmd != nil {
				fmt.Printf("*** Please note that the %q command has been replaced by %q\n\n", command.CommandPath(), realcmd.CommandPath())
				command.RunE = func(cmd *cobra.Command, args []string) error {
					realcmd.ParseFlags(newargs)
					ParseArgs(realcmd, newargs)
					return realcmd.RunE(realcmd, realcmd.Flags().Args())
				}
			}
		}

		if r, ok := command.Annotations[CmdReplacedBy]; ok {
			var newargs []string
			realcmd, newargs, err = command.Root().Find(append(strings.Split(r, " "), args...))
			if err != nil {
				log.Error("error finding replacement command", slog.Any("error", err))
				return err
			}
			if realcmd != nil {
				command.RunE = func(cmd *cobra.Command, args []string) error {
					realcmd.ParseFlags(newargs)
					ParseArgs(realcmd, newargs)
					return realcmd.RunE(realcmd, realcmd.Flags().Args())
				}
			}
		}

		if realcmd != nil {
			if t, _ := command.Flags().GetBool("help"); t {
				command.RunE = nil

				command.Run = func(cmd *cobra.Command, args []string) {
					realcmd.Usage()
				}
				return nil
			}
		}

		if t, _ := command.Flags().GetBool("help"); t {
			command.RunE = nil

			command.Run = func(cmd *cobra.Command, args []string) {
				command.Usage()
			}
			return nil
		}

		if command.Annotations[CmdRequireHome] == "true" && geneos.LocalRoot() == "" && len(geneos.RemoteHosts(false)) == 0 {
			command.SetUsageTemplate(" ")
			return GeneosUnsetError
		}
		if command.Name() == "help" {

			return nil
		}

		return ParseArgs(command, args)
	},
}

Cmd represents the base command when called without any subcommands

View Source
var GeneosUnsetError = errors.New(strings.ReplaceAll(`Geneos location not set.

You can do one of the following:
* Run |geneos config set geneos=/PATH| (where |/PATH| is the location of the Geneos installation)
* Run |geneos init| or |geneos init /PATH| to initialise an installation
  * There are also variations on the |init| command, please see help for the command
* Set the |GENEOS_HOME| or |ITRS_HOME| environment variables, either once or in your |.profile|:
  * |export GENEOS_HOME=/PATH|

`, "|", "`"))
View Source
var Hostname string

Hostname is the cmd package global host selected ny the `--host`/`-H` option

View Source
var RunPlaceholder = func(command *cobra.Command, args []string) {}

RunPlaceholder is an empty function for commands that have to run but no do anything

Used to allow PersistentPreRun to check for aliases for legacy commands

UserKeyFile is the path to the user's key file. It starts as DefaultUserKeyFile but can be changed.

Functions

func AddInstance added in v1.5.0

func AddInstance(ct *geneos.Component, name string, port uint16, extras values.Values, options ...AddOption) (err error)

AddInstance add an instance of component type ct the the optional extra configuration values extras

func Execute

func Execute()

Execute adds all child commands to the root command and sets flags appropriately. This is called by main.main(). It only needs to happen once to the RootCmd.

func FetchArgs added in v1.26.0

func FetchArgs(command *cobra.Command) (ct *geneos.Component, args, params []string, err error)

FetchArgs parses the ct, args and params set by ParseArgs in a Pre run and returns the ct and a slice of names and a slice of params.

If the command annotation CmdNonInstanceArgsError is "true" then an error will be returned if any params are found, otherwise they are returned as a slice of strings.

func ImportFiles added in v1.5.0

func ImportFiles(ct *geneos.Component, args []string, params []string) (err error)

ImportFiles add a file to an instance, from local or URL overwrites without asking - use case is license files, setup files etc. backup / history track older files (date/time?) no restart or reload of components?

func ParseArgs added in v1.10.0

func ParseArgs(c *cobra.Command, args []string) (err error)

ParseArgs does the heavy lifting of sorting out non-flag command line ares for the various commands. The results are passed in the command context value "data" as a CmdValType struct. The main RunE function for each command can then call ParseTypeNames or ParseTypeNamesParams to get the results.

func ReloadInstance added in v1.8.0

func ReloadInstance(i geneos.Instance, _ ...any) (resp *responses.General)

func RunE added in v1.5.0

func RunE(root *cobra.Command, path []string, args []string) (err error)

RunE runs a command in a sub-package to avoid import loops. It is named to align with the cobra struct member of the same name.

The caller must have:

DisableFlagParsing: true,

set in their command struct for flags to work. Then hook this function like this in the command struct:

RunE: func(command *cobra.Command, args []string) (err error) {
     return RunE(command.Root(), []string{"host", "ls"}, args)
},

func Start added in v1.5.0

func Start(ct *geneos.Component, watchlogs bool, autostart bool, names []string) (err error)

Start is a single entrypoint for multiple commands to start instances. ct is the component type, nil means all. watchlogs is a flag to, well, watch logs while autostart is a flag to indicate if Start() is being called as part of a group of instances - this is for use by autostart checking.

Types

type AddOption added in v1.28.1

type AddOption func(*addOptions)

func Base added in v1.28.1

func Base(base string) AddOption

func CertBundle added in v1.28.1

func CertBundle(bundle string) AddOption

func CertBundlePassword added in v1.28.1

func CertBundlePassword(password config.Secret) AddOption

func Imports added in v1.28.1

func Imports(imports []string) AddOption

func Insecure added in v1.28.1

func Insecure(insecure bool) AddOption

func Keyfile added in v1.28.1

func Keyfile(keyfile string) AddOption

func KeyfileCRC added in v1.28.1

func KeyfileCRC(crc string) AddOption

func LogsAfterAdd added in v1.28.1

func LogsAfterAdd(logs bool) AddOption

func StartAfterAdd added in v1.28.1

func StartAfterAdd(start bool) AddOption

func Template added in v1.28.1

func Template(template string) AddOption

type CmdKeyType added in v1.14.2

type CmdKeyType string

type CmdValType added in v1.14.2

type CmdValType struct {
	sync.Mutex
	// contains filtered or unexported fields
}

CmdValType is the struct used to store the results of parsing the command line arguments in a PreRun function and pass them to the main RunE function.

Directories

Path Synopsis
Package aescmd groups related AES256 keyfile and crypto commands
Package aescmd groups related AES256 keyfile and crypto commands
Package cfgcmd groups config commands in their own package
Package cfgcmd groups config commands in their own package
Package hostcmd contains all the host subsystem commands
Package hostcmd contains all the host subsystem commands
Package initcmd contains all the init subsystem commands
Package initcmd contains all the init subsystem commands
Package pkgcmd contains all the package subsystem commands
Package pkgcmd contains all the package subsystem commands
Package tlscmd contains all the TLS subsystem commands
Package tlscmd contains all the TLS subsystem commands

Jump to

Keyboard shortcuts

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