Repository navigation
Conversation
…r and looking up command registry (v2 legacy)
…mand calls and cleanup warning outputs
|
would like to mention that the CVE check failures applies to the current live branch, when those are updated a fork sync will also solve it. |
There was a problem hiding this comment.
🤖 AI-Assisted Architectural & Compatibility Review
Thank you for putting together this proof of concept! Migrating the CLI plugin RPC layer from Cloud Controller V2 to V3 is a critical and long-awaited step (#3621).
We conducted an adversarial review and empirical test validation of the proposed changes against origin/v8. While the overall direction of using v7action.Actor and configv3.Config is sound, we identified two blocking launch/lifecycle regressions and several public model mapping discrepancies that would break existing plugins relying on backward compatibility:
Key Findings Summary
- [Blocker] Offline Plugin Launch (F1):
PluginRunner.Rununconditionally dials Cloud Controller before starting the RPC listener, failing withNo API endpoint setwhen no target is configured (plugin/runner/runner.go:79). - [Blocker] Lifecycle Service Nil Dereference (F2): Lifecycle commands (
uninstall-plugin) createRpcServicewithnildependencies; plugin uninstall callbacks callingAccessToken()panic on nil dereference (command/plugin/shared/rpc.go:46). - [Should-Fix] Public Model Mapping Regressions:
UserEmail()returns username rather than the JWT email claim (plugin/rpc/cli_rpc_server.go:255).GetSpaceduplicates security groups bound to both running and staging (plugin/rpc/cli_rpc_server.go:618).- Application
Statecasing changes from"started"to"STARTED"(plugin/rpc/mappings.go:381). - Role strings change from legacy constants (
RoleOrgManager) to v3 enums (organization_manager) (plugin/rpc/mappings.go:118). - Unlimited quota limits become
0instead of-1due to null unmarshaling (plugin/rpc/mappings.go:189). Domain.Namereceives full route URLs rather than domain names (plugin/rpc/mappings.go:462).GetAppreturns binding names instead of service instance names (plugin/rpc/mappings.go:471).GetServicesdropsServicePlan.Guid(plugin/rpc/mappings.go:84).GetAppsreports observed live instances instead of desired scale for stopped apps (plugin/rpc/mappings.go:503).GetAppexposes redacted start command[PRIVATE DATA HIDDEN IN LISTS]and omits environment variables (plugin/rpc/cli_rpc_server.go:331).
- [Should-Fix] Concurrency Data Race (F4):
CallCoreCommandshares an unsynchronizedbytes.Bufferacross stdout and stderr interceptors (plugin/rpc/cli_rpc_server.go:53). - [Should-Fix] Credential Persistence (F19): Token refreshed during RPC
AccessToken()is not saved to disk on exit, risking UAA refresh token invalidation (plugin/rpc/cli_rpc_server.go:315).
Detailed inline review comments with citations to current origin/v8 source code and suggested fixes are attached below.
…avoid panics during plugin-uninstall
…lugin GetServices
|
All inline review threads are addressed (replies on each thread). Beyond the review, I synced the branch with
Compatibility notes (worth reading for plugin authors):
Proposed for follow-up PRs (out of scope here):
Still not populated (known gaps): Testing: unit tests for every change (RED → GREEN), |
|
Hi @jcvrabo, thanks for the detailed follow-up and for working through the earlier review round. I'm still reviewing this. It touches the plugin launch path, Statements that are now out of date
Changes worth adding to the description
Minor
Thanks again, more to follow. |
|
Thank you for your feedback @anujc25. I'll proceed to update the pr description as soon as i have time, as indeed, it stopped being a POC to become a bonafide PR. |
| } | ||
|
|
||
| // Use the command parser to execute the command | ||
| exitCode, err := cmd.commandParser.ParseCommandFromArgs(pluginUI, args) |
There was a problem hiding this comment.
[Blocking] Flag values carry over between CliCommand calls
ParseCommandFromArgs parses into the global common.Commands struct every time. go-flags only resets options that have a default tag; boolean and string options without one keep their value from the previous call. The legacy runner built a fresh flags.NewFlagContext for each call, so this didn't happen before.
Verified:
- In a unit test, parsing
delete app1 -f -rand thendelete app2leavesForce=trueandDeleteMappedRoutes=true. - With a built
cf, a plugin callingCliCommandWithoutTerminalOutput("plugins", "--checksum")and thenCliCommandWithoutTerminalOutput("plugins")gets thesha1column on the second call too. Onv8it doesn't.
This can be destructive: a plugin could delete an app and its routes without a prompt, or push with flags left over from an earlier push.
Suggestion: parse each call into a fresh command struct (e.g. a new zero commandList per call, if parse can take it), or reset common.Commands before each core command. A regression test with two calls in a row would cover it.
There was a problem hiding this comment.
Fixed in 8fa4d24bf. Each top-level command parse now gets a fresh common.CommandList, rather than parsing into the global command table. Global verbosity is read from that invocation too; recursive help handling shares only its current invocation's table. Regression coverage includes checksum→plain plugin listing, string flags, help/error paths, verbosity, and separate parser instances, plus a real net/rpc sequence that calls plugins --checksum followed by plugins. The second call no longer has the checksum column.
| // Like core commands, persist the config once the plugin is done, so tokens | ||
| // refreshed by any RPC call survive. Deferred first, so it runs after Stop. | ||
| defer func() { | ||
| if writeErr := r.config.WriteConfig(); writeErr != nil { |
There was a problem hiding this comment.
[Blocking] Writing the config when the plugin exits overwrites changes made on disk during the run
r.config is the copy loaded when cf started. Writing it unconditionally on exit replaces anything that changed config.json while the plugin ran: a cf subprocess started by the plugin (a common pattern), the user in another terminal, or the plugin itself.
Verified: a plugin that runs cf config --locale fr-FR as a subprocess. Afterwards, Locale is empty with this branch and fr-FR with v8. The same would happen to cf target, cf login or cf api run that way, and the user would silently end up back on the old target or credentials.
Legacy coreconfig only saved when something changed. Since AccessToken() already saves as soon as the tokens change, could this deferred write be dropped? If refreshes done by the actor's request wrappers also need to be kept, an alternative is to write only when the tokens differ from the values at launch, ideally reloading from disk and merging just the token fields.
There was a problem hiding this comment.
Fixed the unconditional exit write in 6f20eb129. The runner records the access/refresh token pair at launch and writes on exit only if either changed. The comparison and write use the RPC mutex. This retains wrapper-triggered token refreshes, including a request that fails after refreshing, while leaving external disk edits alone when the plugin's tokens are unchanged. Immediate AccessToken() persistence remains. The subprocess cf config --locale fr-FR reproduction now preserves fr-FR, and tests cover plugin success/failure, access-only/refresh-only rotations, and no-write behavior.
This is deliberately the narrower change. I also checked current upstream: its legacy token setters save a cached whole config and can overwrite an external edit during a genuine token save. We have not introduced token-only merging or interprocess conflict handling here; changed-token writes retain that existing limitation. As an improvement, it can be addressed in another pr.
| // Without a target the plugin still runs. RPC calls that need Cloud | ||
| // Controller return rpc.ErrNoAPISet. | ||
| var actor *v7action.Actor | ||
| if r.commandUI != nil && r.config.Target() != "" { |
There was a problem hiding this comment.
[Blocking] The actor is built once at launch and doesn't follow target changes
actor (with its CC, UAA and routing clients) is created once from the target at launch:
- If the plugin then calls
CliCommand("api", url)orCliCommand("login", "-a", other), laterGet*calls still go to the original endpoint. - If the plugin started with no target,
actorstaysnil, sogetActor()returnsErrActorUnavailablefor the rest of the run, even afterapi/loginsucceed throughCliCommand.
Legacy repositories looked up config.APIEndpoint() on every request, so both cases worked before. (This one is from reading the code; I didn't test it against a CF.)
Suggestion: create the actor on demand in getActor(), and rebuild it when cliConfig.Target() differs from the endpoint it was built for. Keep it under the same lock as CallCoreCommand.
There was a problem hiding this comment.
I'll question this one. I'm not in agreement with the cli supporting this... actually I think the plugins should be forbidden of calling any cli commands that would interfere with plugin life-cycle and session management (aside token refreshing). Changing targets within the plugin could be considered a subversive action. Same thing related to install and uninstall plugin actions (whose calls by the plugin are unsupported with this pr).
Personally I think these actions should be simply unsupported and blocked (the blocking part would go through another pr), and it's preferable to have the user explicitly setting a new target, and more importantly, explicitly calling the login command directly instead of delegating these actions to the plugin
|
|
||
| translatedErr := translatableerror.ConvertToTranslatableError(passedErr) | ||
| if r.commandUI != nil { | ||
| r.commandUI.DisplayError(translatedErr) |
There was a problem hiding this comment.
[Should-fix] Extra error output when a plugin exits non-zero
The *exec.ExitError goes through ConvertToTranslatableError and DisplayError, and then main.go:61 adds Error running plugin: command failed. A plugin that prints its own error and exits 3 now produces:
exit status 3
FAILED
Error running plugin: command failed
Legacy (RunMethodIfExists) just exited with code 1 and printed nothing extra (verified with the same plugin on v8). Plugins that report their own errors would now show this extra output after them.
Suggestion: treat *exec.ExitError as "the plugin already reported it" and exit quietly. It would also be nice to pass the plugin's exit code through instead of always using 1, but that's optional; legacy also always used 1.
There was a problem hiding this comment.
Fixed in a04e0ee26. The runner preserves *exec.ExitError without displaying it, and main suppresses its additional error message for that case. The plugin owns its diagnostics. CLI exit status remains 1, matching legacy rather than adding optional exact-code passthrough. A full-process regression covers a plugin diagnostic followed by exit 3, silent exit 3, success, and a missing executable: the first two have no extra CLI output, while executable-start failures remain visible.
| return nil | ||
| } | ||
|
|
||
| func (cmd *CliRpcCmd) AccessToken(args string, retVal *string) error { |
There was a problem hiding this comment.
[Should-fix] AccessToken() / Get* are not serialized with CallCoreCommand
Only CallCoreCommand, DisableTerminalOutput and GetOutputAndReset take coreCommandMutex. Since net/rpc serves each connection on its own goroutine, a plugin calling AccessToken() (which refreshes the token and calls WriteConfig()) or any Get* while a core command is running can change cliConfig concurrently with a command that is changing it and writing it to disk itself (e.g. target, login).
Suggestion: take the same lock (or an RW lock: readers for Get*, writer for core commands and token refresh) around calls that touch cliConfig or the actor.
There was a problem hiding this comment.
Fixed in e85ba8f43. All RPC handlers using mutable config/actor state take the same exclusive mutex as CallCoreCommand, for the entire operation. Get calls are not treated as read-lock operations because their CC wrappers may refresh tokens. Internal helpers run under the caller's lock without reacquiring it. Channel-coordinated net/rpc tests cover 24 config/actor operations waiting for a core command and the reverse ordering with real actor token refresh/config persistence. RPC and runner race tests pass. This is per-service synchronization, not interprocess config locking.
| // Get detailed app summary; withObfuscatedValues fetches each process | ||
| // individually, so the start command is not redacted | ||
| summary, warnings, err := actor.GetDetailedAppSummary(appName, spaceGUID, true) | ||
| if err != nil { |
There was a problem hiding this comment.
[Should-fix, minor] CC warnings are dropped on errors
Here, and in most Get* handlers, the code returns the error before calling displayWarnings, so any warnings that came with a failing request are lost. The v7 commands usually display warnings first and then check the error:
summary, warnings, err := actor.GetDetailedAppSummary(appName, spaceGUID, true)
cmd.displayWarnings(warnings)
if err != nil {
return err
}A few calls in GetApp already do it this way (e.g. the service bindings and stacks lookups); it would be good to do it everywhere.
There was a problem hiding this comment.
Fixed in 6bed4209f. Warning display now immediately follows each affected actor/client call, before checking its error. The regression table covers all 28 request stages across the Get handlers: 24 reproduced the lost warnings and four existing GetApp stages were already correct. All now preserve the error and emit each warning once on stderr, without plugin stdout output. Existing forbidden-environment behavior is unchanged.
| os.Exit(1) | ||
| } | ||
|
|
||
| rpcService, err := rpc.NewRpcService(v3Config, server, nil, nil, nil) |
There was a problem hiding this comment.
[Minor] Unreachable legacy code is still being changed
After 62b1d947c, nothing reaches cf/cmd.Main anymore (it isn't linked into the binary), and the same goes for cf/commands/plugin/{install,uninstall}_plugin.go. These edits only keep the code compiling. Related leftovers that could go in the planned cleanup:
plugin/rpc/run_plugin.go(RunMethodIfExists), which onlycf/cmduses;plugin/rpc/fakecommand/*, still dot-imported byplugin/rpc/cli_rpc_server_test.go;plugin/plugin_examples/test_rpc_server_example, which still importscf/flags.
Not a blocker, but it would help to list these explicitly in the "follow-up" section so they don't get missed.
There was a problem hiding this comment.
description has been updated
| github.com/fsnotify/fsnotify v1.6.0 // indirect | ||
| github.com/fxamacker/cbor/v2 v2.9.1 // indirect | ||
| github.com/go-logr/logr v1.4.4 // indirect | ||
| github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab // indirect |
There was a problem hiding this comment.
[Minor] go-cfclient's test-only dependencies end up in go.mod
go mod why shows martini, martini-contrib/render, codegangsta/inject, bpool and testify come in through go-cfclient/v3/client → go-cfclient/v3/testutil. They're // indirect and go mod tidy is clean, so nothing is wrong locally. But because CfClient() is on the public plugin package, every plugin module gets these entries (and the v3.0.0-alpha.20 pin) too. It might be worth raising with go-cfclient (separating testutil from the client package's tests) together with the request for a non-alpha release.
There was a problem hiding this comment.
cf-client v3.0.0 has just been released, fork is getting updated with it. The test packages are something to improve on the cf-client side and not directly related to this, so... will consider this one done.
| // CommandArgs returns the command line starting at the command: leading | ||
| // arguments starting with "-" are global options (which take no values) and are | ||
| // skipped. It returns nil when there is no command. | ||
| func CommandArgs(args []string) []string { |
There was a problem hiding this comment.
[Minor] CommandArgs assumes global options take no value
That's true for today's global options (-v, --version, -h, --help). But if one that takes a value is ever added (e.g. --config path), the value would be taken as the plugin command name. A short comment stating the assumption, or a table-driven test listing the supported global options, would make that clear.
There was a problem hiding this comment.
Documented and tested in 95d153338. The helper already stated that leading global options take no values; it now names the current options (-v, --version, -h, --help) and explicitly says a value-bearing global option requires updating it. The table covers each option, combinations, flags-only input, and retaining flags after the command. The misleading --verbose example has been replaced. Parsing behavior is unchanged.
| return nil | ||
| } | ||
|
|
||
| func (cmd *CliRpcCmd) CallCoreCommand(args []string, retVal *bool) error { |
There was a problem hiding this comment.
@jcvrabo, following up on compatibility note 1 from your summary comment:
CliCommandoutput is now v7 output. Upstream'sCallCoreCommandran the legacy v6 commands, so plugins received v6 output. Core commands called from plugins now produce v7 output (different tables, headers and wording). Plugins that scrapeCliCommandoutput may need changes; …
Thanks for calling this out so clearly. I think this might be treated as a breaking change for plugins, and probably the biggest one in this PR. Many plugins call CliCommand/CliCommandWithoutTerminalOutput and parse the returned lines, because for a long time that was the only way to get data the Get* models don't expose. For example, cf apps goes from
name requested state instances memory disk urls
to
name requested state processes routes
so a plugin that splits rows into columns would get different fields, or index out of range, with no error from the CLI. Plugin authors would only find out when users report it after upgrading. The Get* model fixes keep the structured side compatible, but text output can't be mapped back the same way.
Since this targets v8, I think we need to plan how we roll this out rather than switch it in one release.
I will think about some options regarding this as well.
cc @vuil for his opinion here.
There was a problem hiding this comment.
I basically think this whole plugin structure is running on borrowed time. I understand the decision to leave it behind when doing the actions refactoring, but we were left with a rather sensitive situation where a plugin framework has been left outdated until quite recently and increased the complexity to handle the v2 phase-out.
I see three options here, either this pr can be refactored to be a main branch pr and the v8 cli should see its end-of-life happening in sync with the complete phase-out of v2 (this one contradicts https://github.com/cloudfoundry/community/blob/main/toc/rfc/rfc-0056-cli-v2-plugins-transition.md), we implement yet another translation layer to make the output compatible with the pre-actions implementation (more inline with rfc0056 but this pr is out of scope for that), or we proceed with the pr as a candidate, check which official plugins (those listed in the cli repository) are actually parsing outputs to check which ones are eligible to be updated and remove from the repo whose which are not, and we end up with a new v8 version which has, in fact, breaking changes for some plugins, but which I wager will be able to support the majority of them.
let me know what's what as to decide if any further attention should be given to this pr. Would like to point out that I hope we can get to some conclusion as this is a subject that is being dragged for quite a long time and runs the risk of being resolved when doing anything on v8 would in fact be a waste (I do know there is a general preference of converging on a single branch to maintain, so perhaps thinking about releasing v9 and phasing out v8 may be a good option).
Description of the change
This PR addresses #3621 by moving the CLI's plugin RPC implementation from legacy Cloud Controller v2 repositories to CAPI v3-backed actors and
configv3.Config.The existing plugin RPC method names and structured model types remain available, with the
Get*methods deprecated in favor of direct API access through the newCliConnection.CfClient()method. This does not mean full backward compatibility: captured command output, third-party interface implementations, and lifecycle callback capabilities change as described below. Plugins that call v2 endpoints themselves must migrate those calls separately.Breaking changes and rollout
CliCommandandCliCommandWithoutTerminalOutputnow return v7 command output rather than legacy v6 output. Tables, headers, columns, and wording differ. For example,cf appschanges fromname / requested state / instances / memory / disk / urlstoname / requested state / processes / routes. Plugins that split returned lines into columns can break, even though the RPC protocol has not changed. Both stdout and stderr from core commands are still captured together. TheGet*models andCfClient()are structured alternatives, but not a guarantee that all scraping plugins can migrate unchanged. The rollout of this breaking behavior onv8is unresolved and requires agreement with maintainers before release.CfClient()to the publicplugin.CliConnectioninterface breaks custom implementations of that interface when updating the plugin dependencies, they still work as is calling only the back-compatible methods, including third-party fakes, until they implement the new method. It also addsgithub.com/cloudfoundry/go-cfclient/v3 v3.0.0and its dependency graph to plugin modules. Some additional indirect modules come from go-cfclient's test-helper dependencies and are being reviewed for upstream follow-up; indirect module selection should not be confused with runtime linkage.Get*andCliCommandreturn errors, andAccessToken()returns the stored token without refreshing it. Legacy callbacks could access Cloud Controller through the legacy registry. The new policy reserves these callbacks for cleaning up plugin files and notifying outside services.Launch and RPC execution
plugin/runnerpackage replacesutil/pluginandplugin/transitionfor ordinary plugin execution.Get*calls then reportNo API endpoint set, while config-only calls remain usable.-v. Options after the command are passed to the plugin. Today's supported global options take no values; skipped options are not otherwise applied to plugin RPC requests.CallCoreCommanduses the v7 command parser in-process. Output interception uses a shared synchronized buffer, and core command/output-control operations are serialized.Get*calls are written to stderr rather than plugin stdout.Token and configuration handling
AccessToken()refreshes through the actor when available and writes config immediately if access or refresh tokens changed.CfClient()is initialized using the current access token, not the refresh token. Its client is valid only until that token expires. Long-running plugins should callCfClient()again, which goes throughAccessToken(), to obtain a client using a refreshed token where actor access is available. Automatic refresh inside go-cfclient is currently deferred to another pr.Actor, config, and command changes
Get*implementations usev7action.Actorand, where needed, its CloudControllerClient for CAPI v3 resources.v7action.ServiceInstanceexposes GUID, ServicePlanGUID, LastOperationType, and LastOperationState for plugin mappings.v7action.DomainNameFromRouteURLand reused by plugin models.pluginaction.RemovePluginRepositoryandGetPluginsFromRepositories, plusconfigv3.RemovePluginRepository.configv3.FindPluginByCommandandPluginCommandNames; user config now includesUser.Emaildecoded from token claims.list-plugin-repos,repo-plugins, andremove-plugin-repoare ported to v7 rather than delegating to legacy main.Legacy model compatibility fixes
org-users -asemantics: only ordinary org members, rather than the default manager/billing-manager/auditor roles.-1, with explicit values preserved.GetApp; inaccessible environment variables do not make the rest of the app unavailable for a space auditor.GetServices.ServicePlan.Guidpopulated.Legacy architecture removal
The legacy-main fallback has been removed from
main.go/util/command_parser.TriggerLegacyPushandUnrefactoredCommanderrors are deleted. The normal CLI executable no longer routes plugin/core command execution throughcf/cmd,cf/commands, or the legacy command registry.Legacy source remains under
cf/and is still built where repository tests/examples require it. This PR does not claim all legacy source or every v2 reference has been deleted. Removing the unreachable legacy code is separate cleanup work.Known model gaps
GetAppdoes not populateDetectedStartCommand,PackageUpdatedAt, orStagingFailedReason.GetAppsroute domains do not populateOwningOrganizationGuidorShared; this does not describe all domain mappings in other models.GetOrgUsers/GetSpaceUsersreportIsAdmin=false, matching legacy behavior without additional per-user UAA lookups.Proposed follow-ups
v8.CfClient(), preferably using an RPC-backed token source rather than exposing the refresh token.install-plugin/uninstall-pluginwhen called through pluginCliCommandso a running plugin cannot replace/delete installed plugins, including itself.cf/cmdand legacy plugin commands;plugin/rpc/run_plugin.go(RunMethodIfExists);plugin/rpc/fakecommand/*and the RPC tests that import them; andplugin/plugin_examples/test_rpc_server_example, which still usescf/flags.Value and urgency
Removing the plugin RPC layer's reliance on Cloud Controller v2 permits foundations to disable v2 without losing these CLI-backed plugin methods. Compatibility and rollout still need review; plugins making their own v2 requests remain responsible for migrating them.
Applicable issue and affected users
#3621
Affected parties include plugin users, plugin authors, and library consumers implementing CLI interfaces.