-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Machine ID: Refactor tbot CLI
#47130
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
cc5abaf
Machine ID: Refactor `tbot` CLI
timothyb89 cb7f744
Move new CLI handling into lib/tbot/cli; add all new subcommands
timothyb89 9443531
Add sane global handling, convert most other commands to new style
timothyb89 143a819
First batch of tests
timothyb89 4b80861
Remove outdated TODO
timothyb89 1761e4f
Restore TestConfigCLIOnlySample
timothyb89 e629749
Fix lints
timothyb89 59d5d94
Fix missing embedded flag init
timothyb89 bd9db3c
Merge remote-tracking branch 'origin/master' into timothyb89/tbot-cli…
timothyb89 3c98f03
Code review feedback
timothyb89 8fc0154
Add docstrings
timothyb89 807d2d5
Add unit tests for all "start" commands and globals
timothyb89 09b7afe
Fix imports
timothyb89 8b19340
Add helper for repetitive test
strideynet 7ba9478
Fix command name
strideynet 12ff294
Adjust behaviour of `tbot kube credentials` command
strideynet fd3417f
Add tests for remaining commands
strideynet 62240ac
Appease linter
strideynet 64fc6f7
Add godocs
strideynet File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,231 @@ | ||
| /* | ||
| * Teleport | ||
| * Copyright (C) 2024 Gravitational, Inc. | ||
| * | ||
| * This program is free software: you can redistribute it and/or modify | ||
| * it under the terms of the GNU Affero General Public License as published by | ||
| * the Free Software Foundation, either version 3 of the License, or | ||
| * (at your option) any later version. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| * GNU Affero General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Affero General Public License | ||
| * along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| */ | ||
|
|
||
| package cli | ||
|
|
||
| import ( | ||
| "log/slog" | ||
| "strings" | ||
|
|
||
| "github.com/alecthomas/kingpin/v2" | ||
| "github.com/gravitational/trace" | ||
|
|
||
| "github.com/gravitational/teleport" | ||
| "github.com/gravitational/teleport/lib/tbot/config" | ||
| logutils "github.com/gravitational/teleport/lib/utils/log" | ||
| ) | ||
|
|
||
| const ( | ||
| // AuthServerEnvVar is the environment variable that overrides the | ||
| // configured auth server address. | ||
| AuthServerEnvVar = "TELEPORT_AUTH_SERVER" | ||
| // TokenEnvVar is the environment variable that overrides the configured | ||
| // bot token name. | ||
| TokenEnvVar = "TELEPORT_BOT_TOKEN" | ||
| // ProxyServerEnvVar is the environment variable that overrides the | ||
| // configured proxy server address. | ||
| ProxyServerEnvVar = "TELEPORT_PROXY" | ||
| ) | ||
|
|
||
| var log = logutils.NewPackageLogger(teleport.ComponentKey, teleport.ComponentTBot) | ||
|
|
||
| // CommandRunner defines a contract for `TryRun` that allows commands to | ||
| // either execute (possibly returning an error), or pass execution to the next | ||
| // command candidate. | ||
| type CommandRunner interface { | ||
| TryRun(cmd string) (match bool, err error) | ||
| } | ||
|
|
||
| // MutatorAction is an action that is called by a config mutator-style command. | ||
| type MutatorAction func(mutator ConfigMutator) error | ||
|
|
||
| // genericMutatorHandler supplies a generic `TryRun` that works for all commands | ||
| // that - broadly - load config, mutate that config, and run an action. It's | ||
| // meant to be embedded within a command struct to provide the `TryRun` | ||
| // implementation. | ||
| type genericMutatorHandler struct { | ||
| cmd *kingpin.CmdClause | ||
| mutator ConfigMutator | ||
| action MutatorAction | ||
| } | ||
|
|
||
| // newGenericMutatorHandler creates a new generic genericMutatorHandler that | ||
| // provides a generic `TryRun` implementation. | ||
| func newGenericMutatorHandler(cmd *kingpin.CmdClause, mutator ConfigMutator, action MutatorAction) *genericMutatorHandler { | ||
| return &genericMutatorHandler{ | ||
| cmd: cmd, | ||
| mutator: mutator, | ||
| action: action, | ||
| } | ||
| } | ||
|
|
||
| func (g *genericMutatorHandler) TryRun(cmd string) (match bool, err error) { | ||
| switch cmd { | ||
| case g.cmd.FullCommand(): | ||
| err = g.action(g.mutator) | ||
| default: | ||
| return false, nil | ||
| } | ||
|
|
||
| return true, trace.Wrap(err) | ||
| } | ||
|
|
||
| // ConfigMutator is an interface that can apply changes to a BotConfig. | ||
| type ConfigMutator interface { | ||
| ApplyConfig(cfg *config.BotConfig, l *slog.Logger) error | ||
| } | ||
|
|
||
| // genericExecutorHandler is a helper that can be embedded to provide a simpler | ||
| // TryRun implementation that just runs a function. These functions can be | ||
| // passed in while building the CLI to more easily glue behaviors together, or | ||
| // specified directly. | ||
| type genericExecutorHandler[T any] struct { | ||
| cmd *kingpin.CmdClause | ||
| args *T | ||
|
|
||
| // actions is a list of functions to run when `TryRun` matches the `cmd`. | ||
| // Generally at most one action should be exposed to the top level glue in | ||
| // main, but commands might want to inject some handler logic for e.g. | ||
| // flag migrations. | ||
| actions []func(*T) error | ||
| } | ||
|
|
||
| // newGenericExecutorHandler creates a genericExecutorHandler with the given | ||
| // command and action to execute when that command is matched. | ||
| func newGenericExecutorHandler[T any](cmd *kingpin.CmdClause, args *T, actions ...func(*T) error) *genericExecutorHandler[T] { | ||
| return &genericExecutorHandler[T]{ | ||
| cmd: cmd, | ||
| args: args, | ||
| actions: actions, | ||
| } | ||
| } | ||
|
|
||
| func (e *genericExecutorHandler[T]) TryRun(cmd string) (match bool, err error) { | ||
| switch cmd { | ||
| case e.cmd.FullCommand(): | ||
| for _, action := range e.actions { | ||
| err = action(e.args) | ||
| if err != nil { | ||
| break | ||
| } | ||
| } | ||
| default: | ||
| return false, nil | ||
| } | ||
|
|
||
| return true, trace.Wrap(err) | ||
| } | ||
|
|
||
| func applyMutators(l *slog.Logger, cfg *config.BotConfig, mutators ...ConfigMutator) error { | ||
| for _, mutator := range mutators { | ||
| if mutator == nil { | ||
| continue | ||
| } | ||
|
|
||
| if err := mutator.ApplyConfig(cfg, l); err != nil { | ||
| return trace.Wrap(err) | ||
| } | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| // LoadConfigWithMutators builds a config from an optional config file and a CLI | ||
| // mutator. If an empty path is provided, an empty base config is used. The CLI | ||
| // mutator may override or append to the loaded configuration, if any. The | ||
| // GlobalArgs will be applied as a mutator, and `CheckAndSetDefaults()` will be | ||
| // called on the end result. | ||
| func LoadConfigWithMutators(globals *GlobalArgs, mutators ...ConfigMutator) (*config.BotConfig, error) { | ||
| var cfg *config.BotConfig | ||
| var err error | ||
|
|
||
| if globals.staticConfigYAML != "" { | ||
| cfg, err = config.ReadConfig(strings.NewReader(globals.staticConfigYAML), false) | ||
| if err != nil { | ||
| return nil, trace.Wrap(err) | ||
| } | ||
| } else if globals.ConfigPath != "" { | ||
| cfg, err = config.ReadConfigFromFile(globals.ConfigPath, false) | ||
|
|
||
| if err != nil { | ||
| return nil, trace.Wrap(err, "loading bot config from path %s", globals.ConfigPath) | ||
| } | ||
| } else { | ||
| cfg = &config.BotConfig{} | ||
| } | ||
|
|
||
| mutatorsWithGlobals := append([]ConfigMutator{globals}, mutators...) | ||
|
|
||
| l := log.With("config_path", globals.ConfigPath) | ||
| if err := applyMutators(l, cfg, mutatorsWithGlobals...); err != nil { | ||
| return nil, trace.Wrap(err) | ||
| } | ||
|
|
||
| if err := cfg.CheckAndSetDefaults(); err != nil { | ||
| return nil, trace.Wrap(err) | ||
| } | ||
|
|
||
| return cfg, nil | ||
| } | ||
|
|
||
| // BaseConfigWithMutators returns a base bot config with the given CLI mutators | ||
| // applied. `CheckAndSetDefaults()` will be called on the result. This is useful | ||
| // for explicitly _not_ loading a config file, like in `tbot configure ...` | ||
| func BaseConfigWithMutators(mutators ...ConfigMutator) (*config.BotConfig, error) { | ||
| cfg := &config.BotConfig{} | ||
| if err := applyMutators(log, cfg, mutators...); err != nil { | ||
| return nil, trace.Wrap(err) | ||
| } | ||
|
|
||
| if err := cfg.CheckAndSetDefaults(); err != nil { | ||
| return nil, trace.Wrap(err) | ||
| } | ||
|
|
||
| return cfg, nil | ||
| } | ||
|
|
||
| // RemainingArgsList is a custom kingpin parser that consumes all remaining | ||
| // arguments. | ||
| type RemainingArgsList []string | ||
|
|
||
| func (r *RemainingArgsList) Set(value string) error { | ||
| *r = append(*r, value) | ||
| return nil | ||
| } | ||
|
|
||
| func (r *RemainingArgsList) String() string { | ||
| return strings.Join([]string(*r), " ") | ||
| } | ||
|
|
||
| func (r *RemainingArgsList) IsCumulative() bool { | ||
| return true | ||
| } | ||
|
|
||
| // RemainingArgs returns a list of remaining arguments for the given command. | ||
| func RemainingArgs(s kingpin.Settings) (target *[]string) { | ||
| target = new([]string) | ||
| s.SetValue((*RemainingArgsList)(target)) | ||
| return | ||
| } | ||
|
|
||
| // KingpinClause allows commands and flags to mount to either the root app | ||
| // (kingpin.Application) or a subcommand (kingpin.CmdClause) | ||
| type KingpinClause interface { | ||
| Command(name string, help string) *kingpin.CmdClause | ||
| Flag(name string, help string) *kingpin.FlagClause | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks like a more polished version of what tctl uses. Do you see any benefit/problems with moving this into a more common cli package that all of our tools could one day use?
The only tbot specific things I've seen so far is the ConfigMutator, but that could very well be made generic:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TimB's on leave until next week - I figure that since this PR is already pretty large - the overall idea of extracting this to something reusable makes sense but we perhaps ought to do that in another PR. I think there's a few finishing touches/refinements we'll want to add if other folks are going to use this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wasn't so much asking for something in this PR to change, just curious if you all thought it would be a good idea in general.