Skip to content

Migrate plugin RPC server to CAPI v3, add CfClient(), remove legacy main fallback - #3751

Open
jcvrabo wants to merge 50 commits into
cloudfoundry:v8from
jcvrabo:v8
Open

jcvrabo wants to merge 50 commits into
cloudfoundry:v8from
jcvrabo:v8

Conversation

@jcvrabo

@jcvrabo jcvrabo commented Mar 31, 2026 •

Copy link
Copy Markdown
Member

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 new CliConnection.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

  1. CliCommand and CliCommandWithoutTerminalOutput now return v7 command output rather than legacy v6 output. Tables, headers, columns, and wording differ. For example, cf apps changes from name / requested state / instances / memory / disk / urls to name / 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. The Get* models and CfClient() are structured alternatives, but not a guarantee that all scraping plugins can migrate unchanged. The rollout of this breaking behavior on v8 is unresolved and requires agreement with maintainers before release.
  2. Adding CfClient() to the public plugin.CliConnection interface 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 adds github.com/cloudfoundry/go-cfclient/v3 v3.0.0 and 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.
  3. Install/uninstall lifecycle callbacks have no Cloud Controller actor or core-command parser. In these contexts, Get* and CliCommand return errors, and AccessToken() 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

  • The new plugin/runner package replaces util/plugin and plugin/transition for ordinary plugin execution.
  • Plugins can launch without an API target. Cloud Controller-dependent Get* calls then report No API endpoint set, while config-only calls remain usable.
  • Leading global options are skipped to locate the plugin command, so a command can be found after -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.
  • Unknown-command diagnostics name the command token rather than a preceding global flag.
  • CallCoreCommand uses the v7 command parser in-process. Output interception uses a shared synchronized buffer, and core command/output-control operations are serialized.
  • Warnings from 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.
  • The current runner also writes config when the plugin exits if tokens have been refreshed, including failed executions, to retain refreshes performed by actor request wrappers.
  • 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 call CfClient() again, which goes through AccessToken(), 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 use v7action.Actor and, where needed, its CloudControllerClient for CAPI v3 resources.
  • v7action.ServiceInstance exposes GUID, ServicePlanGUID, LastOperationType, and LastOperationState for plugin mappings.
  • The existing route-domain extraction helper is exported as v7action.DomainNameFromRouteURL and reused by plugin models.
  • Plugin repository support adds pluginaction.RemovePluginRepository and GetPluginsFromRepositories, plus configv3.RemovePluginRepository.
  • Plugin lookup uses configv3.FindPluginByCommand and PluginCommandNames; user config now includes User.Email decoded from token claims.
  • list-plugin-repos, repo-plugins, and remove-plugin-repo are ported to v7 rather than delegating to legacy main.

Legacy model compatibility fixes

  • Lowercase app and instance states.
  • Legacy role names in deterministic legacy order, and legacy org-users -a semantics: only ordinary org members, rather than the default manager/billing-manager/auditor roles.
  • Unlimited/null quota limits represented as -1, with explicit values preserved.
  • Desired instance counts rather than observed running counts; apps without a web process fall back to their first process.
  • Real domain names rather than full route URLs, including HTTP paths and TCP ports.
  • Unredacted start commands and user-provided environment variables in GetApp; inaccessible environment variables do not make the rest of the app unavailable for a space auditor.
  • Service instance names rather than binding names, with repeated bindings deduplicated per instance.
  • Security groups bound to running and staging lifecycles deduplicated.
  • GetServices.ServicePlan.Guid populated.
  • The user's email taken from the JWT email claim, not the username.

Legacy architecture removal

The legacy-main fallback has been removed from main.go / util/command_parser. TriggerLegacyPush and UnrefactoredCommand errors are deleted. The normal CLI executable no longer routes plugin/core command execution through cf/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

  • GetApp does not populate DetectedStartCommand, PackageUpdatedAt, or StagingFailedReason.
  • GetApps route domains do not populate OwningOrganizationGuid or Shared; this does not describe all domain mappings in other models.
  • GetOrgUsers / GetSpaceUsers report IsAdmin=false, matching legacy behavior without additional per-user UAA lookups.
  • The single legacy buildpack field reports the first buildpack from the current droplet rather than representing multiple buildpacks.

Proposed follow-ups

  • Agree the rollout strategy for the v6→v7 command-output break before releasing this PR on v8.
  • Automatic token refresh inside CfClient(), preferably using an RPC-backed token source rather than exposing the refresh token.
  • Block install-plugin / uninstall-plugin when called through plugin CliCommand so a running plugin cannot replace/delete installed plugins, including itself.
  • Apply leading global options, such as verbose request logging, to plugin runs rather than only skipping them during command discovery.
  • Complete legacy cleanup, explicitly covering remaining cf/cmd and legacy plugin commands; plugin/rpc/run_plugin.go (RunMethodIfExists); plugin/rpc/fakecommand/* and the RPC tests that import them; and plugin/plugin_examples/test_rpc_server_example, which still uses cf/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.

@jcvrabo jcvrabo mentioned this pull request Mar 31, 2026
@jcvrabo

jcvrabo commented Mar 31, 2026

Copy link
Copy Markdown
Member Author

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.

@Gerg
Gerg self-requested a review October 13, 2026 14:51
@anujc25
anujc25 self-requested a review October 14, 2026 18:26
@Gerg
Gerg requested a review from vuil October 22, 2026 21:24

@Gerg Gerg left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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

  1. [Blocker] Offline Plugin Launch (F1): PluginRunner.Run unconditionally dials Cloud Controller before starting the RPC listener, failing with No API endpoint set when no target is configured (plugin/runner/runner.go:79).
  2. [Blocker] Lifecycle Service Nil Dereference (F2): Lifecycle commands (uninstall-plugin) create RpcService with nil dependencies; plugin uninstall callbacks calling AccessToken() panic on nil dereference (command/plugin/shared/rpc.go:46).
  3. [Should-Fix] Public Model Mapping Regressions:
  4. [Should-Fix] Concurrency Data Race (F4): CallCoreCommand shares an unsynchronized bytes.Buffer across stdout and stderr interceptors (plugin/rpc/cli_rpc_server.go:53).
  5. [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.

Comment thread plugin/runner/runner.go Resolved
Comment thread plugin/runner/runner.go Resolved
Comment thread command/plugin/shared/rpc.go Resolved
Comment thread plugin/rpc/cli_rpc_server.go Resolved
Comment thread plugin/rpc/cli_rpc_server.go Resolved
Comment thread plugin/rpc/mappings.go Resolved
Comment thread plugin/rpc/mappings.go Resolved
Comment thread plugin/rpc/mappings.go Resolved
Comment thread plugin/cli_connection.go Resolved
Comment thread main.go Resolved
@jcvrabo

jcvrabo commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

All inline review threads are addressed (replies on each thread). Beyond the review, I synced the branch with upstream/v8 (this fixes check-cves), and fixed several things the review didn't cover:

  • Build: plugin/pluginfakes/fake_cli_connection.go wasn't regenerated after adding CfClient(), so go build ./... failed for anyone importing pluginfakes (c9c2b8aaa). plugin/cli_connection.go was also re-indented with tabs.
  • Legacy fallback: The last three v7 commands that still fell back to the legacy main (list-plugin-repos, repo-plugins, remove-plugin-repo) are now ported to v7 (pluginaction + configv3). Plugins calling them through CliCommand run them in-process again, as upstream did through the legacy registry, instead of re-entering the legacy main with the host's arguments. (eba7304c3) With that, nothing triggers the legacy-main fallback anymore, so it's removed (62b1d947c): util/command_parser no longer calls cf/cmd.Main, and cf/cmd (with the legacy command registry) is no longer linked into the binary. The legacy cf/... code stays in the repo for a separate removal. This also removes the path through which a plugin's CliCommand re-entered the legacy main with the host's os.Args (re-launching the plugin).
  • Warnings on stdout: Get* RPC methods used to print Warning: … on stdout. Legacy suppressed all output for these calls, so this would have corrupted plugin stdout. Warnings now go to stderr through UI.DisplayWarnings, the same as v7 commands. (12a026907)
  • Instance state in GetApp().Instances had the same casing regression as the app state (RUNNING vs running) and is lowercased too (ceefa4b8d).
  • Lint: Marking the Get* methods deprecated makes staticcheck flag the two test plugins that still call them on purpose. Those 15 calls now carry //nolint:staticcheck with a reason. stopPlugin explicitly ignores the Kill/Wait errors. With this, the branch adds no lint issues compared to upstream/v8 (and it removes 4). (4dfbdda42)

Compatibility notes (worth reading for plugin authors):

  1. CliCommand output is now v7 output. Upstream's CallCoreCommand ran 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 scrape CliCommand output may need changes; the structured alternatives are the Get* models or CfClient(). Stdout and stderr are still captured together, as before.
  2. Install/uninstall callbacks have no Cloud Controller access. In CLI-MESSAGE-UNINSTALL, Get* and CliCommand return errors, and AccessToken() returns the stored token without refreshing it. Upstream gave these callbacks full access through the legacy registry. This is deliberate: the hook is for cleaning up the plugin's own files and notifying outside services.
  3. CfClient() on the public CliConnection interface breaks third-party code that implements that interface (custom fakes), and adds github.com/cloudfoundry/go-cfclient/v3 v3.0.0-alpha.20 (an alpha release, which is stable and production ready... I have requested already for a final release and even though it was agreed, it is still waiting) to every plugin's dependency graph. The client is valid only until the current access token expires (documented on the method).

Proposed for follow-up PRs (out of scope here):

  • Token refresh inside CfClient() (a RefreshToken RPC or, preferably, an RPC-backed oauth2.TokenSource, which needs a go-cfclient option).
  • Blocking plugin lifecycle commands (install-plugin/uninstall-plugin) from CliCommand, so a running plugin can't replace or delete installed plugins, itself included.
  • Applying leading global options (e.g. -v verbose request logging) to plugin runs. They are currently only skipped to find the command.
  • Removing the now-unreachable legacy cf/... code.

Still not populated (known gaps): GetApp DetectedStartCommand, PackageUpdatedAt and StagingFailedReason; GetApps route Domain.OwningOrganizationGuid and Domain.Shared. GetOrgUsers/GetSpaceUsers IsAdmin is always false, which already matched legacy.

Testing: unit tests for every change (RED → GREEN), -race on plugin/rpc and plugin/runner, and smoke runs of a built cf against a fixture plugin and a local plugin repository. Not run: the CF-backed integration suites.

@jcvrabo
jcvrabo requested a review from Gerg November 1, 2026 22:15
@anujc25

anujc25 commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

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, CliCommand behavior and the public CliConnection interface, so it needs some more thought, and I'll follow up with detailed review comments separately. In the meantime, here are some suggestions to bring the PR description in line with what the PR does now that it is not just a POC. A lot of the current state is only in your follow-up comment, and the description is what reviewers and the release notes will rely on.

Statements that are now out of date

  • "no new Actor methods were added": the PR now adds or changes v7action.ServiceInstance (GUID, ServicePlanGUID, LastOperationType, LastOperationState), exports v7action.DomainNameFromRouteURL, adds pluginaction.RemovePluginRepository / GetPluginsFromRepositories, and adds configv3 RemovePluginRepository, FindPluginByCommand, PluginCommandNames and User.Email.
  • Caveat about domain.name returning the full route URL: fixed in 52a4f5039, so this can be removed.
  • Caveat that the plugin commands (install, uninstall, repo, etc.) "still work as before": list-plugin-repos, repo-plugins and remove-plugin-repo are now ported to v7. Install/uninstall callbacks also changed: Get* and CliCommand return errors there, and AccessToken() returns the stored token without refreshing it.
  • "legacy command architecture is eligible to be removed (not done in this pr)": the legacy-main fallback is now removed from main.go and util/command_parser, so cf/cmd, cf/commands and the legacy registry are no longer compiled into the binary. The TriggerLegacyPush and UnrefactoredCommand errors are deleted as well. Only the source under cf/ remains.
  • "keeps the RPC protocol and plugin implementation unchanged, with the exception of adding … CfClient": true at the protocol level, but adding CfClient() to the public CliConnection interface breaks third-party code that implements it (custom fakes). It also adds github.com/cloudfoundry/go-cfclient/v3 v3.0.0-alpha.20 and its indirect dependencies to every plugin's dependency graph.
  • The opening framing ("may not be considered for merging" / proof of concept): could you clarify whether this is now intended for merge? That changes how we review it.

Changes worth adding to the description

  • New plugin/runner package, which replaces util/plugin and plugin/transition.
  • Plugin launch changes:
    • plugins start without an API target, and Get* calls then return "No API endpoint set";
    • leading global options are skipped to find the command (cf -v my-plugin-cmd);
    • unknown-command errors now report the actual command name.
  • Token and config handling: a refreshed token is saved to disk right away, and the config is written when the plugin exits.
  • CliCommand output is now v7 output instead of v6. This is probably the most important compatibility change for plugin authors and should be easy to find in the description.
  • Warnings from Get* calls now go to stderr instead of stdout.
  • Legacy-compatibility mappings in the Get* models:
    • lowercase app and instance states;
    • legacy role names and order, plus -a handling for org users;
    • unlimited quotas as -1;
    • desired instance count;
    • unredacted start command and environment variables in GetApp;
    • service instance names instead of binding names;
    • de-duplicated security groups;
    • ServicePlan.Guid filled in;
    • the user's email taken from the token.
  • Known gaps:
    • GetApp doesn't fill DetectedStartCommand, PackageUpdatedAt or StagingFailedReason;
    • GetApps doesn't fill the route domain's OwningOrganizationGuid or Shared;
    • IsAdmin is always false. It would help to note that legacy behaved the same way.
  • Testing done (unit tests, -race, smoke runs) and not done (the CF-backed integration suites).
  • Proposed follow-ups:
    • token refresh inside CfClient();
    • blocking install-plugin/uninstall-plugin from CliCommand;
    • passing global options such as -v through to plugin runs;
    • removing the unreachable cf/... code.

Minor

  • The title could mention the user-visible parts, e.g. "Migrate plugin RPC server to CAPI v3, add CfClient(), remove legacy main fallback".

Thanks again, more to follow.

@jcvrabo

jcvrabo commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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 -r and then delete app2 leaves Force=true and DeleteMappedRoutes=true.
  • With a built cf, a plugin calling CliCommandWithoutTerminalOutput("plugins", "--checksum") and then CliCommandWithoutTerminalOutput("plugins") gets the sha1 column on the second call too. On v8 it 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread plugin/runner/runner.go Outdated
// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread plugin/runner/runner.go
// 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() != "" {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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) or CliCommand("login", "-a", other), later Get* calls still go to the original endpoint.
  • If the plugin started with no target, actor stays nil, so getActor() returns ErrActorUnavailable for the rest of the run, even after api/login succeed through CliCommand.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread plugin/runner/runner.go

translatedErr := translatableerror.ConvertToTranslatableError(passedErr)
if r.commandUI != nil {
r.commandUI.DisplayError(translatedErr)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread cf/cmd/cmd.go
os.Exit(1)
}

rpcService, err := rpc.NewRpcService(v3Config, server, nil, nil, nil)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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 only cf/cmd uses;
  • plugin/rpc/fakecommand/*, still dot-imported by plugin/rpc/cli_rpc_server_test.go;
  • plugin/plugin_examples/test_rpc_server_example, which still imports cf/flags.

Not a blocker, but it would help to list these explicitly in the "follow-up" section so they don't get missed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

description has been updated

Comment thread go.mod
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@jcvrabo jcvrabo Nov 24, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread plugin/runner/runner.go
// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jcvrabo, following up on compatibility note 1 from your summary comment:

CliCommand output is now v7 output. Upstream's CallCoreCommand ran 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 scrape CliCommand output 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@jcvrabo jcvrabo changed the title migrate rpc server to v3 cc api and prepare for future plugin interface refactoring Migrate plugin RPC server to CAPI v3, add CfClient(), remove legacy main fallback Nov 24, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants