-
-
Notifications
You must be signed in to change notification settings - Fork 974
Fix stop-app in the interactive CLI without Actuator or JMX #15698
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
Open
jamesfredley
wants to merge
3
commits into
7.0.x
Choose a base branch
from
fix/stop-app-cli
base: 7.0.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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
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
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 |
|---|---|---|
| @@ -1,101 +1,22 @@ | ||
| import javax.management.remote.JMXServiceURL | ||
| import javax.management.remote.JMXConnectorFactory | ||
| import javax.management.ObjectName | ||
| import org.grails.io.support.* | ||
| import groovy.jmx.GroovyMBean | ||
|
|
||
| description("Stops the running Grails application") { | ||
| usage "grails stop-app" | ||
| synonyms 'stop' | ||
| flag name:'port', description:"Specifies the port which the Grails application is running on (defaults to 8080 or 8443 for HTTPS)" | ||
| flag name:'host', description:"Specifies the host the Grails application is bound to" | ||
| } | ||
| System.setProperty("run-app.running", "false") | ||
| def getJMXLocalConnectorAddresses = {-> | ||
| final applicationMainClassName = MainClassFinder.findMainClass() | ||
|
|
||
| if(applicationMainClassName) { | ||
| try { | ||
| final String CONNECTOR_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress" | ||
| def VirtualMachine = getClass().classLoader.loadClass('com.sun.tools.attach.VirtualMachine') | ||
| return VirtualMachine.list() | ||
| .findAll { | ||
| it.displayName() == applicationMainClassName | ||
| } | ||
| .collect { desc -> | ||
| def vm = VirtualMachine.attach(desc.id()) | ||
| try { | ||
| def connectorAddress = vm.agentProperties.getProperty(CONNECTOR_ADDRESS) | ||
| if (connectorAddress == null) { | ||
| // Trying to load agent | ||
| def agent = [vm.systemProperties.getProperty("java.home"), "lib", "management-agent.jar"].join(File.separator) | ||
| vm.loadAgent(agent) | ||
|
|
||
| connectorAddress = vm.agentProperties.getProperty(CONNECTOR_ADDRESS) | ||
| } | ||
| if (connectorAddress) { | ||
| return connectorAddress | ||
| } | ||
| } finally { | ||
| vm.detach() | ||
| } | ||
| }.findAll { it } | ||
|
|
||
| } | ||
| catch(Throwable e) { | ||
| // fallback to REST request if JMX not available | ||
| } | ||
| } | ||
| } | ||
|
|
||
| System.setProperty("run-app.running", "false") | ||
|
|
||
| def addresses = getJMXLocalConnectorAddresses() | ||
| if(addresses) { | ||
| JMXServiceURL url = new JMXServiceURL(addresses[0]) | ||
| def connector = JMXConnectorFactory.connect(url) | ||
|
|
||
| try { | ||
| def server = connector.MBeanServerConnection | ||
| console.updateStatus "Stopping application..." | ||
|
|
||
| def objectName = server.queryNames(null,null).find { it.canonicalName.contains('name=shutdownEndpoint,type=Endpoint') } | ||
| def mbean = new GroovyMBean(server, objectName) | ||
| console.addStatus "Shutting down application..." | ||
| mbean.shutdown() | ||
| console.addStatus "Application shutdown." | ||
| return true | ||
| if (org.grails.cli.gradle.RunningApplicationRegistry.stopAll()) { | ||
| if (org.grails.cli.gradle.RunningApplicationRegistry.awaitStop(30000)) { | ||
| console.updateStatus "Application stopped." | ||
| } | ||
| catch(e) { | ||
| console.addStatus "Application not found via JMX, attempting remote shutdown." | ||
| else { | ||
| console.updateStatus "Application shutdown requested; it may still be stopping." | ||
| } | ||
| finally { | ||
| connector.close() | ||
| } | ||
| } | ||
|
|
||
|
|
||
| Integer port = flag('port')?.toInteger() ?: config.getProperty('server.port', Integer) ?: 8080 | ||
| String host = flag('host') ?: config.getProperty('server.address', String) ?: "localhost" | ||
| String contextPath = config.getProperty('server.context-path') ?: config.getProperty('server.contextPath') ?: "" | ||
| String managementPath = config.getProperty('management.endpoints.web.base-path') ?: config.getProperty('management.endpoints.web.basePath') ?: "/actuator" | ||
| console.updateStatus "Shutting down application..." | ||
| def url = new URL("http://$host:${port}${contextPath}${managementPath}/shutdown") | ||
| try { | ||
| def connection = url.openConnection() | ||
| connection.setRequestMethod("POST") | ||
| connection.doOutput = true | ||
| connection.connect() | ||
| console.updateStatus connection.content.text | ||
| while(isServerAvailable(host, port)) { | ||
| sleep 100 | ||
| } | ||
| console.updateStatus "Application shutdown." | ||
| return true | ||
|
|
||
| return true | ||
| } | ||
| catch (e) { | ||
| console.error "Application not running.", e | ||
| return false | ||
| else { | ||
| console.error "Application not running." | ||
| return false | ||
| } | ||
|
|
||
|
|
||
|
|
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
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
139 changes: 139 additions & 0 deletions
139
grails-shell-cli/src/main/groovy/org/grails/cli/gradle/RunningApplicationRegistry.groovy
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,139 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
| package org.grails.cli.gradle | ||
|
|
||
| import java.util.concurrent.ConcurrentHashMap | ||
|
|
||
| import groovy.transform.CompileStatic | ||
|
|
||
| import org.gradle.tooling.CancellationTokenSource | ||
|
|
||
| import grails.build.logging.GrailsConsole | ||
|
|
||
| /** | ||
| * Tracks the {@link CancellationTokenSource} of Grails applications started by the | ||
| * CLI via the {@code run-app} command (an asynchronous Gradle {@code bootRun} build). | ||
| * | ||
| * <p>This allows the {@code stop-app} command to cancel the underlying Gradle build | ||
| * without exiting the interactive CLI, providing a CLI only shutdown mechanism that | ||
| * does not rely on the Spring Boot Actuator shutdown endpoint or JMX.</p> | ||
| * | ||
| * <p>A {@code run-app} build registers its token before the build runs and removes it | ||
| * when the build finishes (whether it completes normally, fails, or is cancelled). | ||
| * {@link #stopAll()} only requests cancellation; it never removes tokens directly so | ||
| * that the build remains responsible for its own lifecycle.</p> | ||
| * | ||
| * @author Apache Grails Team | ||
| * @since 7.0.0 | ||
| */ | ||
| @CompileStatic | ||
| class RunningApplicationRegistry { | ||
|
|
||
| private static final Set<CancellationTokenSource> RUNNING = ConcurrentHashMap.newKeySet() | ||
|
|
||
| // Monitor used to wake up awaitStop() the moment the last running build deregisters, | ||
| // instead of polling. Only deregister() can empty RUNNING, so only it needs to notify. | ||
| private static final Object MONITOR = new Object() | ||
|
|
||
| private RunningApplicationRegistry() { | ||
| } | ||
|
|
||
| /** | ||
| * Registers the cancellation token source of a running application. | ||
| * | ||
| * @param tokenSource the token source backing the running build | ||
| */ | ||
| static void register(CancellationTokenSource tokenSource) { | ||
| if (tokenSource != null) { | ||
| RUNNING.add(tokenSource) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Removes a previously registered cancellation token source. This should be called | ||
| * by the build once it has finished, regardless of how it terminated. | ||
| * | ||
| * @param tokenSource the token source to remove | ||
| */ | ||
| static void deregister(CancellationTokenSource tokenSource) { | ||
| if (tokenSource != null) { | ||
| RUNNING.remove(tokenSource) | ||
| synchronized (MONITOR) { | ||
| MONITOR.notifyAll() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * @return {@code true} if at least one application started via {@code run-app} is running | ||
| */ | ||
| static boolean isApplicationRunning() { | ||
| !RUNNING.isEmpty() | ||
| } | ||
|
|
||
| /** | ||
| * Requests cancellation of every running application. The registered token sources are | ||
| * not removed here; each running build removes its own token when it terminates. | ||
| * | ||
| * @return {@code true} if at least one running application was found and cancellation requested | ||
| */ | ||
| static boolean stopAll() { | ||
| if (RUNNING.isEmpty()) { | ||
| return false | ||
| } | ||
| // Snapshot to avoid surprises if a build deregisters concurrently while we iterate | ||
| List<CancellationTokenSource> tokenSources = new ArrayList<>(RUNNING) | ||
| for (CancellationTokenSource tokenSource : tokenSources) { | ||
| try { | ||
| tokenSource.cancel() | ||
| } | ||
| catch (Throwable e) { | ||
| GrailsConsole.getInstance().verbose("Failed to request cancellation of a running application: ${e.message}") | ||
| } | ||
| } | ||
| return true | ||
| } | ||
|
|
||
| /** | ||
| * Waits up to the given timeout for all running applications to terminate, i.e. for the | ||
| * cancelled builds to finish tearing down and deregister their token sources. | ||
| * | ||
| * @param timeoutMillis the maximum time to wait in milliseconds | ||
| * @return {@code true} if all applications stopped within the timeout, {@code false} otherwise | ||
| */ | ||
| static boolean awaitStop(long timeoutMillis) { | ||
| long deadline = System.currentTimeMillis() + timeoutMillis | ||
| synchronized (MONITOR) { | ||
| while (!RUNNING.isEmpty()) { | ||
| long remaining = deadline - System.currentTimeMillis() | ||
| if (remaining <= 0) { | ||
| return false | ||
| } | ||
| try { | ||
| MONITOR.wait(remaining) | ||
| } | ||
| catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt() | ||
| return RUNNING.isEmpty() | ||
| } | ||
| } | ||
| return true | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
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.