This is an automated email from the ASF dual-hosted git repository. borinquenkid pushed a commit to branch 9.0.x-h7-improvement-phase3 in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit 46eb13d5a4154588b9fbfc8ddab82bec9cf5a550 Author: Walter Duque de Estrada <[email protected]> AuthorDate: Tue Oct 6 23:31:19 2026 -0500 refactor: convert startup progress Java sources to Groovy Converts StartupTask and the grails-startup-progress classes to @CompileStatic Groovy with behaviour unchanged. Package and class names are kept, so spring.factories and the configuration metadata still apply. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../src/main/groovy/grails/boot/StartupTask.groovy | 71 ++-- .../org/apache/grails/startup/StartupAccess.groovy | 83 ++-- .../apache/grails/startup/StartupBrowser.groovy | 47 ++- .../apache/grails/startup/StartupProgress.groovy | 450 +++++++++++---------- .../StartupProgressApplicationStartup.groovy | 262 ++++++------ .../grails/startup/StartupProgressFilter.groovy | 110 ++--- .../grails/startup/StartupProgressLifecycle.groovy | 44 +- .../grails/startup/StartupProgressPage.groovy | 120 +++--- .../startup/StartupProgressProperties.groovy | 108 ++--- .../grails/startup/StartupProgressResponder.groovy | 144 +++---- .../startup/StartupProgressRunListener.groovy | 301 +++++++------- .../grails/startup/StartupProgressServer.groovy | 140 +++---- 12 files changed, 991 insertions(+), 889 deletions(-) diff --git a/grails-core/src/main/groovy/grails/boot/StartupTask.groovy b/grails-core/src/main/groovy/grails/boot/StartupTask.groovy index 0018a0d4a2..c385b8a9d2 100644 --- a/grails-core/src/main/groovy/grails/boot/StartupTask.groovy +++ b/grails-core/src/main/groovy/grails/boot/StartupTask.groovy @@ -16,12 +16,14 @@ * specific language governing permissions and limitations * under the License. */ -package grails.boot; +package grails.boot -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.metrics.ApplicationStartup; -import org.springframework.core.metrics.StartupStep; +import groovy.transform.CompileStatic + +import org.springframework.context.ApplicationContext +import org.springframework.context.ConfigurableApplicationContext +import org.springframework.core.metrics.ApplicationStartup +import org.springframework.core.metrics.StartupStep /** * Reports the progress of a piece of work an application or plugin does while the application starts, @@ -49,36 +51,37 @@ import org.springframework.core.metrics.StartupStep; * * @since 8.1 */ -public final class StartupTask implements AutoCloseable { +@CompileStatic +final class StartupTask implements AutoCloseable { /** The name of the startup step that records a task. */ - public static final String TASK_STEP = "grails.startup.task"; + public static final String TASK_STEP = 'grails.startup.task' /** The name of the startup step that records one item of a task's work. */ - public static final String ITEM_STEP = "grails.startup.task.item"; + public static final String ITEM_STEP = 'grails.startup.task.item' /** The tag of a task's step that describes the task. */ - public static final String DESCRIPTION_TAG = "description"; + public static final String DESCRIPTION_TAG = 'description' /** The tag of a task's step that says how many items the task will do, when that is known. */ - public static final String TOTAL_TAG = "total"; + public static final String TOTAL_TAG = 'total' /** The tag of an item's step that names the item. */ - public static final String ITEM_TAG = "item"; + public static final String ITEM_TAG = 'item' - private final ApplicationStartup startup; + private final ApplicationStartup startup - private final StartupStep step; + private final StartupStep step - private StartupStep item; + private StartupStep item private StartupTask(ApplicationStartup startup, String description, int total) { - this.startup = startup; - StartupStep taskStep = startup.start(TASK_STEP).tag(DESCRIPTION_TAG, description); + this.startup = startup + StartupStep taskStep = startup.start(TASK_STEP).tag(DESCRIPTION_TAG, description) if (total >= 0) { - taskStep.tag(TOTAL_TAG, String.valueOf(total)); + taskStep.tag(TOTAL_TAG, String.valueOf(total)) } - this.step = taskStep; + this.step = taskStep } /** @@ -88,8 +91,8 @@ public final class StartupTask implements AutoCloseable { * @param description what the task does, such as {@code Running database migrations} * @param total how many items the task will do, or a negative number when that is not known */ - public static StartupTask start(ApplicationContext context, String description, int total) { - return start(applicationStartup(context), description, total); + static StartupTask start(ApplicationContext context, String description, int total) { + return start(applicationStartup(context), description, total) } /** @@ -99,40 +102,40 @@ public final class StartupTask implements AutoCloseable { * @param description what the task does, such as {@code Running database migrations} * @param total how many items the task will do, or a negative number when that is not known */ - public static StartupTask start(ApplicationStartup startup, String description, int total) { - return new StartupTask(startup, description, total); + static StartupTask start(ApplicationStartup startup, String description, int total) { + return new StartupTask(startup, description, total) } /** * Whether anything records the start of the given context, without which a task can skip work done * only to report it. */ - public static boolean isRecorded(ApplicationContext context) { - return applicationStartup(context) != ApplicationStartup.DEFAULT; + static boolean isRecorded(ApplicationContext context) { + return !applicationStartup(context).is(ApplicationStartup.DEFAULT) } /** Begins the next item of work, ending the one before if it has not been ended. */ - public void startItem(String name) { - endItem(); - item = startup.start(ITEM_STEP).tag(ITEM_TAG, name); + void startItem(String name) { + endItem() + item = startup.start(ITEM_STEP).tag(ITEM_TAG, name) } /** Ends the item of work in progress, if there is one. */ - public void endItem() { + void endItem() { if (item != null) { - item.end(); - item = null; + item.end() + item = null } } /** Ends the task, and the item of work in progress if there is one. */ @Override - public void close() { - endItem(); - step.end(); + void close() { + endItem() + step.end() } private static ApplicationStartup applicationStartup(ApplicationContext context) { - return context instanceof ConfigurableApplicationContext configurable ? configurable.getApplicationStartup() : ApplicationStartup.DEFAULT; + return context instanceof ConfigurableApplicationContext ? ((ConfigurableApplicationContext) context).getApplicationStartup() : ApplicationStartup.DEFAULT } } diff --git a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupAccess.groovy b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupAccess.groovy index 5510dfb328..fb70b0fe16 100644 --- a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupAccess.groovy +++ b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupAccess.groovy @@ -16,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.grails.startup; +package org.apache.grails.startup -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import java.security.SecureRandom + +import groovy.transform.CompileStatic +import groovy.transform.PackageScope /** * Decides who sees the details of a start: the bean being created, the slowest beans, why a start failed, @@ -35,102 +35,111 @@ import java.util.List; * made once per JVM, so a page signed in stays signed in when Spring Boot DevTools restarts the * application.</p> */ +@CompileStatic final class StartupAccess { /** The query parameter that carries the token in the logged address. */ - static final String TOKEN_PARAMETER = "grailsStartupToken"; + @PackageScope + static final String TOKEN_PARAMETER = 'grailsStartupToken' - private static final String TOKEN = newToken(); + private static final String TOKEN = newToken() - private final boolean showDetails; + private final boolean showDetails - private volatile String cookieName; + private volatile String cookieName /** * @param showDetails whether details are shown at all, to a browser that has signed in * @param port the application's port, which names the cookie, since browsers share cookies between the * ports of a host and two applications on one machine would otherwise sign each other out */ + @PackageScope StartupAccess(boolean showDetails, int port) { - this.showDetails = showDetails; - usePort(port); + this.showDetails = showDetails + usePort(port) } /** * Names the cookie for the port the web server listens on, which for a random port is only known once the * web server has started. */ + @PackageScope void usePort(int port) { if (port > 0) { - cookieName = "GRAILS_STARTUP_" + port; + cookieName = 'GRAILS_STARTUP_' + port } else if (cookieName == null) { - cookieName = "GRAILS_STARTUP"; + cookieName = 'GRAILS_STARTUP' } } /** Whether a browser has to sign in to see details, which it only does when there are details to see. */ + @PackageScope boolean isSignInRequired() { - return showDetails; + return showDetails } /** The query that signs a browser in, for the address the application logs and opens a browser on. */ + @PackageScope String signInQuery() { - return TOKEN_PARAMETER + "=" + TOKEN; + return TOKEN_PARAMETER + '=' + TOKEN } /** * The address to send a browser on to when its request carries the token, which is the address it asked * for without the token, or {@code null} when the request does not sign in. */ + @PackageScope String signInRedirect(String rawPath, String rawQuery) { if (!showDetails || rawQuery == null || rawQuery.isEmpty()) { - return null; + return null } - boolean signedIn = false; - List<String> kept = new ArrayList<>(); - for (String parameter : rawQuery.split("&")) { - if (parameter.startsWith(TOKEN_PARAMETER + "=")) { - signedIn |= matches(parameter.substring(TOKEN_PARAMETER.length() + 1)); + boolean signedIn = false + List<String> kept = new ArrayList<>() + for (String parameter : rawQuery.split('&')) { + if (parameter.startsWith(TOKEN_PARAMETER + '=')) { + signedIn |= matches(parameter.substring(TOKEN_PARAMETER.length() + 1)) } else if (!parameter.isEmpty()) { - kept.add(parameter); + kept.add(parameter) } } if (!signedIn) { - return null; + return null } - return kept.isEmpty() ? rawPath : rawPath + "?" + String.join("&", kept); + return kept.isEmpty() ? rawPath : rawPath + '?' + String.join('&', kept) } /** The {@code Set-Cookie} header value that keeps a browser signed in. */ + @PackageScope String signInCookie() { - return cookieName + "=" + TOKEN + "; Path=/; HttpOnly; SameSite=Strict"; + return cookieName + '=' + TOKEN + '; Path=/; HttpOnly; SameSite=Strict' } /** Whether a request, by the {@code Cookie} headers it sent, may see details. */ + @PackageScope boolean showsDetails(List<String> cookieHeaders) { if (!showDetails || cookieHeaders == null) { - return false; + return false } for (String header : cookieHeaders) { - for (String cookie : header.split(";")) { - String trimmed = cookie.trim(); - if (trimmed.startsWith(cookieName + "=") && matches(trimmed.substring(cookieName.length() + 1))) { - return true; + for (String cookie : header.split(';')) { + String trimmed = cookie.trim() + if (trimmed.startsWith(cookieName + '=') && matches(trimmed.substring(cookieName.length() + 1))) { + return true } } } - return false; + return false } private static boolean matches(String candidate) { - return MessageDigest.isEqual(TOKEN.getBytes(StandardCharsets.US_ASCII), candidate.getBytes(StandardCharsets.US_ASCII)); + return MessageDigest.isEqual(TOKEN.getBytes(StandardCharsets.US_ASCII), candidate.getBytes(StandardCharsets.US_ASCII)) } private static String newToken() { - byte[] bytes = new byte[32]; - new SecureRandom().nextBytes(bytes); - return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + byte[] bytes = new byte[32] + new SecureRandom().nextBytes(bytes) + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) } } diff --git a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupBrowser.groovy b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupBrowser.groovy index 8f3b4c6571..52a542fd06 100644 --- a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupBrowser.groovy +++ b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupBrowser.groovy @@ -16,32 +16,30 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.grails.startup; +package org.apache.grails.startup -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentHashMap -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import groovy.transform.CompileStatic +import groovy.transform.PackageScope + +import org.slf4j.Logger +import org.slf4j.LoggerFactory /** * Opens a browser on the starting application with the operating system's own command, rather than * {@code java.awt.Desktop}, which refuses to work in the headless mode Spring Boot runs applications in. */ +@CompileStatic final class StartupBrowser { - private static final Logger LOG = LoggerFactory.getLogger(StartupBrowser.class); + private static final Logger LOG = LoggerFactory.getLogger(StartupBrowser) /** * The addresses a browser has been opened on in this JVM. Spring Boot DevTools restarts an application * in the JVM it started in, and a developer who has the page open does not want another window each time. */ - private static final Set<String> OPENED = ConcurrentHashMap.newKeySet(); + private static final Set<String> OPENED = ConcurrentHashMap.newKeySet() private StartupBrowser() { } @@ -52,33 +50,34 @@ final class StartupBrowser { * @param command the command to run, given the address as its last argument, or empty for the * operating system's own */ + @PackageScope static void open(URI address, List<String> command) { if (!OPENED.add(address.toString())) { - return; + return } - List<String> commandLine = new ArrayList<>(command.isEmpty() ? systemCommand() : command); - commandLine.add(address.toString()); + List<String> commandLine = new ArrayList<>(command.isEmpty() ? systemCommand() : command) + commandLine.add(address.toString()) try { new ProcessBuilder(commandLine) .redirectOutput(ProcessBuilder.Redirect.DISCARD) .redirectError(ProcessBuilder.Redirect.DISCARD) - .start(); - LOG.debug("Opened a browser on {} with {}", address, commandLine); + .start() + LOG.debug('Opened a browser on {} with {}', address, commandLine) } catch (IOException ex) { - LOG.warn("Could not open a browser on {} with {}: {}", address, commandLine, ex.getMessage()); + LOG.warn('Could not open a browser on {} with {}: {}', address, commandLine, ex.getMessage()) } } private static List<String> systemCommand() { - String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT); - if (os.contains("mac")) { - return List.of("open"); + String os = System.getProperty('os.name', '').toLowerCase(Locale.ROOT) + if (os.contains('mac')) { + return List.of('open') } - if (os.contains("win")) { + if (os.contains('win')) { // unlike "cmd /c start", hands the address over without a shell interpreting its characters - return List.of("rundll32", "url.dll,FileProtocolHandler"); + return List.of('rundll32', 'url.dll,FileProtocolHandler') } - return List.of("xdg-open"); + return List.of('xdg-open') } } diff --git a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgress.groovy b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgress.groovy index c345506455..cb8698002a 100644 --- a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgress.groovy +++ b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgress.groovy @@ -16,199 +16,213 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.grails.startup; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLongArray; +package org.apache.grails.startup + +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLongArray + +import groovy.transform.CompileStatic +import groovy.transform.PackageScope /** * The state of one application start, written by the startup steps and run listener callbacks on * the starting thread and read, as JSON, by whichever server is answering the progress page's polls, * and once the application is ready, by the startup report. */ +@CompileStatic final class StartupProgress { /** * Response header naming the current phase. The progress page treats any poll answered without it * as the application itself answering, which is its signal to reload. */ - static final String PHASE_HEADER = "Grails-Startup-Phase"; + @PackageScope + static final String PHASE_HEADER = 'Grails-Startup-Phase' /** * How recently a status poll must have arrived for a failure to be worth waiting on: a browser * showing the progress page polls well inside this window, so a quieter start has nobody watching. */ - private static final long WATCHED_WINDOW_NANOS = TimeUnit.SECONDS.toNanos(3); + private static final long WATCHED_WINDOW_NANOS = TimeUnit.SECONDS.toNanos(3) /** * How long to keep answering after a page has been told about a failure, so the other pages open on the * application, which poll on their own schedule, are told too. It is a little over the page's polling * interval. */ - private static final long FAILURE_LINGER_MILLIS = 750; + private static final long FAILURE_LINGER_MILLIS = 750 - private static final int SLOWEST_BEAN_LIMIT = 10; + private static final int SLOWEST_BEAN_LIMIT = 10 /** How many of the tasks reported during a start are kept, which bounds what a start that reports many keeps. */ - private static final int TASK_LIMIT = 50; + private static final int TASK_LIMIT = 50 - private static final int STACK_TRACE_LIMIT = 64 * 1024; + private static final int STACK_TRACE_LIMIT = 64 * 1024 /** The phases of a start, in order, with the progress reached when each begins. */ enum Phase { + PREPARING(2), LOADING_DEFINITIONS(5), CREATING_BEANS(15), STARTING_WEB_SERVER(92), INITIALIZING(96), READY(100), - FAILED(100); + FAILED(100) - private final int progress; + @PackageScope + final int progress Phase(int progress) { - this.progress = progress; + this.progress = progress } } - private final String runId = UUID.randomUUID().toString(); - private final String applicationName; - private final String grailsVersion; - private final long runStartNanos; - private final AtomicLongArray phaseStarts = new AtomicLongArray(Phase.values().length); - private final Set<String> createdBeans = ConcurrentHashMap.newKeySet(); - private final AtomicInteger createdExpectedBeans = new AtomicInteger(); - private final List<BeanTiming> slowestBeans = new ArrayList<>(); - private final CountDownLatch failureDelivered = new CountDownLatch(1); - private final List<Task> tasks = new CopyOnWriteArrayList<>(); - - private volatile Phase phase = Phase.PREPARING; - private volatile Phase failedPhase; - private volatile String activity; - private volatile Set<String> expectedBeans; - private volatile String failureType; - private volatile String failureMessage; - private volatile String failureStackTrace; - private volatile long lastStatusNanos; - private volatile long startedNanos; + private final String runId = UUID.randomUUID().toString() + private final String applicationName + private final String grailsVersion + private final long runStartNanos + private final AtomicLongArray phaseStarts = new AtomicLongArray(Phase.values().length) + private final Set<String> createdBeans = ConcurrentHashMap.newKeySet() + private final AtomicInteger createdExpectedBeans = new AtomicInteger() + private final List<BeanTiming> slowestBeans = new ArrayList<>() + private final CountDownLatch failureDelivered = new CountDownLatch(1) + private final List<Task> tasks = new CopyOnWriteArrayList<>() + + private volatile Phase phase = Phase.PREPARING + private volatile Phase failedPhase + private volatile String activity + private volatile Set<String> expectedBeans + private volatile String failureType + private volatile String failureMessage + private volatile String failureStackTrace + private volatile long lastStatusNanos + private volatile long startedNanos /** * @param runStartNanos when the run of the application began, so the times reported match the time * Spring Boot reports the application started in */ + @PackageScope StartupProgress(String applicationName, String grailsVersion, long runStartNanos) { - this.applicationName = applicationName; - this.grailsVersion = grailsVersion; - this.runStartNanos = runStartNanos; - phaseStarts.set(Phase.PREPARING.ordinal(), runStartNanos); + this.applicationName = applicationName + this.grailsVersion = grailsVersion + this.runStartNanos = runStartNanos + phaseStarts.set(Phase.PREPARING.ordinal(), runStartNanos) } + @PackageScope Phase getPhase() { - return phase; + return phase } /** Whether the status endpoint still answers, which it stops doing once the application is ready. */ + @PackageScope boolean isReporting() { - return phase != Phase.READY; + return phase != Phase.READY } + @PackageScope void loadingDefinitions() { - advanceTo(Phase.LOADING_DEFINITIONS); + advanceTo(Phase.LOADING_DEFINITIONS) } /** * Moves to bean creation, given the names of the beans the refresh will create eagerly. Beans created * before the names were known, such as post-processors, count towards them. */ + @PackageScope void creatingBeans(Set<String> expected) { - int created = 0; + int created = 0 for (String name : createdBeans) { if (expected.contains(name)) { - created++; + created++ } } - createdExpectedBeans.set(created); - expectedBeans = expected; - advanceTo(Phase.CREATING_BEANS); + createdExpectedBeans.set(created) + expectedBeans = expected + advanceTo(Phase.CREATING_BEANS) } + @PackageScope void beanCreationStarted(String beanName) { - activity = beanName; + activity = beanName } /** * Records a created bean with the time spent creating it, not counting the beans created on its behalf. */ + @PackageScope void beanCreated(String beanName, long durationNanos) { - Set<String> expected = expectedBeans; + Set<String> expected = expectedBeans if (createdBeans.add(beanName) && expected != null && expected.contains(beanName)) { - createdExpectedBeans.incrementAndGet(); + createdExpectedBeans.incrementAndGet() } synchronized (slowestBeans) { - if (slowestBeans.size() < SLOWEST_BEAN_LIMIT || durationNanos > slowestBeans.get(slowestBeans.size() - 1).nanos) { - slowestBeans.removeIf(timing -> timing.name.equals(beanName)); - slowestBeans.add(new BeanTiming(beanName, durationNanos)); - slowestBeans.sort(Comparator.comparingLong(BeanTiming::nanos).reversed()); + if (slowestBeans.size() < SLOWEST_BEAN_LIMIT || durationNanos > slowestBeans.get(slowestBeans.size() - 1).nanos()) { + slowestBeans.removeIf((BeanTiming timing) -> timing.name().equals(beanName)) + slowestBeans.add(new BeanTiming(beanName, durationNanos)) + Comparator<BeanTiming> slowestFirst = (BeanTiming first, BeanTiming second) -> Long.compare(second.nanos(), first.nanos()) + slowestBeans.sort(slowestFirst) if (slowestBeans.size() > SLOWEST_BEAN_LIMIT) { - slowestBeans.remove(slowestBeans.size() - 1); + slowestBeans.remove(slowestBeans.size() - 1) } } } } /** Records a task reported with {@link grails.boot.StartupTask} beginning, and returns it to report on. */ + @PackageScope Task taskStarted() { - Task task = new Task(); + Task task = new Task() if (tasks.size() < TASK_LIMIT) { - tasks.add(task); + tasks.add(task) } - return task; + return task } + @PackageScope void startingWebServer() { - activity = null; - advanceTo(Phase.STARTING_WEB_SERVER); + activity = null + advanceTo(Phase.STARTING_WEB_SERVER) } + @PackageScope void initializing() { - advanceTo(Phase.INITIALIZING); + advanceTo(Phase.INITIALIZING) } /** * Records that the application has started, which is the moment Spring Boot measures the time it * reports the application started in to, before the application runners run. */ + @PackageScope void started() { if (startedNanos == 0) { - startedNanos = System.nanoTime(); + startedNanos = System.nanoTime() } } + @PackageScope void ready() { - advanceTo(Phase.READY); + advanceTo(Phase.READY) } + @PackageScope void failed(Throwable exception) { if (phase == Phase.FAILED || phase == Phase.READY) { - return; + return } - failedPhase = phase; - failureType = exception.getClass().getName(); - failureMessage = exception.getMessage(); - failureStackTrace = stackTrace(exception); - phaseStarts.set(Phase.FAILED.ordinal(), System.nanoTime()); - phase = Phase.FAILED; + failedPhase = phase + failureType = exception.getClass().getName() + failureMessage = exception.getMessage() + failureStackTrace = stackTrace(exception) + phaseStarts.set(Phase.FAILED.ordinal(), System.nanoTime()) + phase = Phase.FAILED } /** @@ -218,27 +232,30 @@ final class StartupProgress { * @param showDetails whether the page may see the details of the start * @param signInForDetails whether there are details the page would see if it signed in */ + @PackageScope Status report(boolean showDetails, boolean signInForDetails) { - lastStatusNanos = System.nanoTime(); - return snapshot(showDetails, signInForDetails); + lastStatusNanos = System.nanoTime() + return snapshot(showDetails, signInForDetails) } /** * The status as the startup report shows it. A client reading the report is not a page that would be * told about a failure, so a failed start does not wait for it. */ + @PackageScope Status snapshot(boolean showDetails, boolean signInForDetails) { - Phase current = phase; - return new Status(current, toJson(current, showDetails, signInForDetails)); + Phase current = phase + return new Status(current, toJson(current, showDetails, signInForDetails)) } /** * Records that a status has been written out in full, which for a failure means the page has been * told, so the failed start can carry on and release the port without cutting the response short. */ + @PackageScope void delivered(Status status) { if (status.phase() == Phase.FAILED) { - failureDelivered.countDown(); + failureDelivered.countDown() } } @@ -248,152 +265,153 @@ final class StartupProgress { * page has polled recently, so a start nobody is watching fails as quickly as it would without the * progress page. */ + @PackageScope void awaitFailureDelivery(long timeoutMillis) { - long last = lastStatusNanos; + long last = lastStatusNanos if (last == 0 || System.nanoTime() - last > WATCHED_WINDOW_NANOS) { - return; + return } try { if (failureDelivered.await(timeoutMillis, TimeUnit.MILLISECONDS)) { - Thread.sleep(FAILURE_LINGER_MILLIS); + Thread.sleep(FAILURE_LINGER_MILLIS) } } - catch (InterruptedException ex) { - Thread.currentThread().interrupt(); + catch (InterruptedException ignored) { + Thread.currentThread().interrupt() } } private int progress(Phase current) { if (current != Phase.CREATING_BEANS) { - return current.progress; + return current.progress } - Set<String> expected = expectedBeans; - int span = Phase.STARTING_WEB_SERVER.progress - Phase.CREATING_BEANS.progress; + Set<String> expected = expectedBeans + int span = Phase.STARTING_WEB_SERVER.progress - Phase.CREATING_BEANS.progress if (expected == null || expected.isEmpty()) { - return current.progress; + return current.progress } - return current.progress + Math.min(span - 1, createdExpectedBeans.get() * span / expected.size()); + return current.progress + Math.min(span - 1, Math.divideExact(createdExpectedBeans.get() * span, expected.size())) } private String toJson(Phase current, boolean showDetails, boolean signInForDetails) { - long now = System.nanoTime(); - StringBuilder json = new StringBuilder(512).append('{'); - member(json, "runId").append(string(runId)).append(','); - member(json, "application").append(string(applicationName)).append(','); - member(json, "phase").append(string(current.name())).append(','); - member(json, "progress").append(progress(current)).append(','); - long end = now; + long now = System.nanoTime() + StringBuilder json = new StringBuilder(512).append('{') + member(json, 'runId').append(string(runId)).append(',') + member(json, 'application').append(string(applicationName)).append(',') + member(json, 'phase').append(string(current.name())).append(',') + member(json, 'progress').append(progress(current)).append(',') + long end = now if (current == Phase.READY && startedNanos != 0) { - end = startedNanos; + end = startedNanos } else if (current == Phase.READY || current == Phase.FAILED) { - end = phaseStarts.get(current.ordinal()); + end = phaseStarts.get(current.ordinal()) } - member(json, "elapsedMillis").append(TimeUnit.NANOSECONDS.toMillis(end - runStartNanos)).append(','); - member(json, "showDetails").append(showDetails).append(','); - member(json, "signInForDetails").append(signInForDetails); + member(json, 'elapsedMillis').append(TimeUnit.NANOSECONDS.toMillis(end - runStartNanos)).append(',') + member(json, 'showDetails').append(showDetails).append(',') + member(json, 'signInForDetails').append(signInForDetails) // how the start is going is for everyone; how the application is put together is a detail if (showDetails) { - json.append(','); - appendPhases(json, now); - Set<String> expected = expectedBeans; - json.append(','); - member(json, "beansCreated").append(expected != null ? createdExpectedBeans.get() : createdBeans.size()).append(','); - member(json, "beansExpected").append(expected != null ? expected.size() : -1).append(','); - member(json, "grailsVersion").append(string(grailsVersion)); - String currentActivity = activity; + json.append(',') + appendPhases(json, now) + Set<String> expected = expectedBeans + json.append(',') + member(json, 'beansCreated').append(expected != null ? createdExpectedBeans.get() : createdBeans.size()).append(',') + member(json, 'beansExpected').append(expected != null ? expected.size() : -1).append(',') + member(json, 'grailsVersion').append(string(grailsVersion)) + String currentActivity = activity if (current == Phase.CREATING_BEANS && currentActivity != null) { - json.append(','); - member(json, "activity").append(string(currentActivity)); + json.append(',') + member(json, 'activity').append(string(currentActivity)) } - json.append(','); - appendTasks(json, now); - json.append(','); - member(json, "slowestBeans").append('['); - List<BeanTiming> slowest; + json.append(',') + appendTasks(json, now) + json.append(',') + member(json, 'slowestBeans').append('[') + List<BeanTiming> slowest synchronized (slowestBeans) { - slowest = List.copyOf(slowestBeans); + slowest = List.copyOf(slowestBeans) } for (int i = 0; i < slowest.size(); i++) { - BeanTiming timing = slowest.get(i); + BeanTiming timing = slowest.get(i) if (i > 0) { - json.append(','); + json.append(',') } - json.append('{'); - member(json, "name").append(string(timing.name)).append(','); - member(json, "millis").append(TimeUnit.NANOSECONDS.toMillis(timing.nanos)); - json.append('}'); + json.append('{') + member(json, 'name').append(string(timing.name())).append(',') + member(json, 'millis').append(TimeUnit.NANOSECONDS.toMillis(timing.nanos())) + json.append('}') } - json.append(']'); + json.append(']') } if (current == Phase.FAILED) { - json.append(','); + json.append(',') if (showDetails) { - member(json, "failedPhase").append(string(failedPhase.name())).append(','); + member(json, 'failedPhase').append(string(failedPhase.name())).append(',') } - member(json, "failure").append('{'); + member(json, 'failure').append('{') if (showDetails) { - member(json, "type").append(string(failureType)).append(','); - member(json, "message").append(string(failureMessage)).append(','); - member(json, "stackTrace").append(string(failureStackTrace)); + member(json, 'type').append(string(failureType)).append(',') + member(json, 'message').append(string(failureMessage)).append(',') + member(json, 'stackTrace').append(string(failureStackTrace)) } - json.append('}'); + json.append('}') } - return json.append('}').toString(); + return json.append('}').toString() } private void advanceTo(Phase next) { - Phase current = phase; + Phase current = phase if (current != Phase.FAILED && current.ordinal() < next.ordinal()) { // the start time is in place before the phase is, so a reader seeing the phase sees when it began - phaseStarts.set(next.ordinal(), System.nanoTime()); - phase = next; + phaseStarts.set(next.ordinal(), System.nanoTime()) + phase = next } } /** Each task reported, in the order they began, with how far each has got and how long it took. */ private void appendTasks(StringBuilder json, long now) { - member(json, "tasks").append('['); - boolean first = true; + member(json, 'tasks').append('[') + boolean first = true for (Task task : tasks) { if (!first) { - json.append(','); + json.append(',') } - first = false; - long end = task.endNanos; - json.append('{'); - member(json, "description").append(string(task.description)).append(','); - member(json, "completed").append(task.completed.get()).append(','); - member(json, "total").append(task.total).append(','); - member(json, "running").append(end == 0).append(','); + first = false + long end = task.endNanos + json.append('{') + member(json, 'description').append(string(task.description)).append(',') + member(json, 'completed').append(task.completed.get()).append(',') + member(json, 'total').append(task.total).append(',') + member(json, 'running').append(end == 0).append(',') if (end == 0 && task.item != null) { - member(json, "item").append(string(task.item)).append(','); + member(json, 'item').append(string(task.item)).append(',') } - member(json, "millis").append(TimeUnit.NANOSECONDS.toMillis((end == 0 ? now : end) - task.startNanos)); - json.append('}'); + member(json, 'millis').append(TimeUnit.NANOSECONDS.toMillis((end == 0 ? now : end) - task.startNanos)) + json.append('}') } - json.append(']'); + json.append(']') } /** Each phase begun, in order, with how long it took, or has taken so far. */ private void appendPhases(StringBuilder json, long now) { - member(json, "phases").append('['); - boolean first = true; + member(json, 'phases').append('[') + boolean first = true for (Phase each : List.of(Phase.PREPARING, Phase.LOADING_DEFINITIONS, Phase.CREATING_BEANS, Phase.STARTING_WEB_SERVER, Phase.INITIALIZING)) { - long start = phaseStarts.get(each.ordinal()); + long start = phaseStarts.get(each.ordinal()) if (start == 0) { - continue; + continue } if (!first) { - json.append(','); + json.append(',') } - first = false; - json.append('{'); - member(json, "name").append(string(each.name())).append(','); - member(json, "millis").append(TimeUnit.NANOSECONDS.toMillis(endOf(each, now) - start)); - json.append('}'); + first = false + json.append('{') + member(json, 'name').append(string(each.name())).append(',') + member(json, 'millis').append(TimeUnit.NANOSECONDS.toMillis(endOf(each, now) - start)) + json.append('}') } - json.append(']'); + json.append(']') } /** @@ -402,55 +420,65 @@ final class StartupProgress { */ private long endOf(Phase phase, long now) { if (phase == Phase.INITIALIZING && startedNanos != 0) { - return startedNanos; + return startedNanos } for (int later = phase.ordinal() + 1; later < Phase.values().length; later++) { - long start = phaseStarts.get(later); + long start = phaseStarts.get(later) if (start != 0) { - return start; + return start } } - return now; + return now } private static String stackTrace(Throwable exception) { - StringWriter writer = new StringWriter(); - exception.printStackTrace(new PrintWriter(writer)); - String trace = writer.toString(); - return trace.length() > STACK_TRACE_LIMIT ? trace.substring(0, STACK_TRACE_LIMIT) + "\n\t..." : trace; + StringWriter writer = new StringWriter() + exception.printStackTrace(new PrintWriter(writer)) + String trace = writer.toString() + return trace.length() > STACK_TRACE_LIMIT ? trace.substring(0, STACK_TRACE_LIMIT) + '\n\t...' : trace } private static StringBuilder member(StringBuilder json, String name) { - return json.append('"').append(name).append("\":"); + return json.append('"').append(name).append('":') } /** * A JSON string literal, escaped so it can also sit inside an HTML {@code <script>} element. */ + @PackageScope static String string(String value) { if (value == null) { - return "null"; + return 'null' } - StringBuilder escaped = new StringBuilder(value.length() + 16).append('"'); + StringBuilder escaped = new StringBuilder(value.length() + 16).append('"') for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); + char c = value.charAt(i) switch (c) { - case '"' -> escaped.append("\\\""); - case '\\' -> escaped.append("\\\\"); - case '\n' -> escaped.append("\\n"); - case '\r' -> escaped.append("\\r"); - case '\t' -> escaped.append("\\t"); - default -> { - if (c < 0x20 || c == '<' || c == '>' || c == '&' || c == '\u2028' || c == '\u2029') { - escaped.append(String.format("\\u%04x", (int) c)); + case '"': + escaped.append('\\"') + break + case '\\': + escaped.append('\\\\') + break + case '\n': + escaped.append('\\n') + break + case '\r': + escaped.append('\\r') + break + case '\t': + escaped.append('\\t') + break + default: + if ((int) c < 0x20 || c == '<' || c == '>' || c == '&' || c == 0x2028 || c == 0x2029) { + escaped.append(String.format('\\u%04x', (int) c)) } else { - escaped.append(c); + escaped.append(c) } - } } } - return escaped.append('"').toString(); + return escaped.append('"').toString() } /** @@ -459,38 +487,54 @@ final class StartupProgress { */ static final class Task { - private final long startNanos = System.nanoTime(); - private final AtomicInteger completed = new AtomicInteger(); - private volatile String description; - private volatile int total = -1; - private volatile String item; - private volatile long endNanos; + @PackageScope + final long startNanos = System.nanoTime() + + @PackageScope + final AtomicInteger completed = new AtomicInteger() + + @PackageScope + volatile String description + + @PackageScope + volatile int total = -1 + + @PackageScope + volatile String item + + @PackageScope + volatile long endNanos + @PackageScope void described(String value) { - description = value; + description = value } + @PackageScope void totalled(String value) { try { - total = Integer.parseInt(value); + total = Integer.parseInt(value) } - catch (NumberFormatException ex) { - total = -1; + catch (NumberFormatException ignored) { + total = -1 } } + @PackageScope void itemStarted(String name) { - item = name; + item = name } + @PackageScope void itemEnded() { - completed.incrementAndGet(); - item = null; + completed.incrementAndGet() + item = null } + @PackageScope void ended() { - item = null; - endNanos = System.nanoTime(); + item = null + endNanos = System.nanoTime() } } diff --git a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressApplicationStartup.groovy b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressApplicationStartup.groovy index 84e5a6eb5b..4f68aaa587 100644 --- a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressApplicationStartup.groovy +++ b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressApplicationStartup.groovy @@ -16,23 +16,24 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.grails.startup; +package org.apache.grails.startup -import java.util.HashSet; -import java.util.Set; -import java.util.function.Predicate; -import java.util.function.Supplier; +import java.util.function.Predicate +import java.util.function.Supplier -import org.springframework.beans.factory.BeanFactoryUtils; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup; -import org.springframework.boot.context.metrics.buffering.StartupTimeline; -import org.springframework.core.SimpleAliasRegistry; -import org.springframework.core.metrics.ApplicationStartup; -import org.springframework.core.metrics.StartupStep; +import groovy.transform.CompileStatic +import groovy.transform.PackageScope -import grails.boot.StartupTask; +import org.springframework.beans.factory.BeanFactoryUtils +import org.springframework.beans.factory.config.BeanDefinition +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory +import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup +import org.springframework.boot.context.metrics.buffering.StartupTimeline +import org.springframework.core.SimpleAliasRegistry +import org.springframework.core.metrics.ApplicationStartup +import org.springframework.core.metrics.StartupStep + +import grails.boot.StartupTask /** * Reads the context's progress from the startup steps Spring records during a refresh, and from the @@ -41,30 +42,31 @@ import grails.boot.StartupTask; * {@code startup} endpoint sees the same steps it would without the progress page. Once the application * is ready it reads no more, so what the application creates from then on is no part of the report. */ +@CompileStatic final class StartupProgressApplicationStartup implements ApplicationStartup { - private static final String BEAN_POST_PROCESS_STEP = "spring.context.beans.post-process"; + private static final String BEAN_POST_PROCESS_STEP = 'spring.context.beans.post-process' - private static final String BEAN_INSTANTIATE_STEP = "spring.beans.instantiate"; + private static final String BEAN_INSTANTIATE_STEP = 'spring.beans.instantiate' - private static final String BEAN_NAME_TAG = "beanName"; + private static final String BEAN_NAME_TAG = 'beanName' - private final ApplicationStartup delegate; + private final ApplicationStartup delegate - private final StartupProgress progress; + private final StartupProgress progress - private final ConfigurableListableBeanFactory beanFactory; + private final ConfigurableListableBeanFactory beanFactory /** The innermost bean being created on each thread, so a bean's own time can exclude its dependencies'. */ - private final ThreadLocal<BeanCreationStep> creating = new ThreadLocal<>(); + private final ThreadLocal<BeanCreationStep> creating = new ThreadLocal<>() /** The innermost task running on each thread, which the items reported on that thread belong to. */ - private final ThreadLocal<TaskStep> running = new ThreadLocal<>(); + private final ThreadLocal<TaskStep> running = new ThreadLocal<>() private StartupProgressApplicationStartup(ApplicationStartup delegate, StartupProgress progress, ConfigurableListableBeanFactory beanFactory) { - this.delegate = delegate; - this.progress = progress; - this.beanFactory = beanFactory; + this.delegate = delegate + this.progress = progress + this.beanFactory = beanFactory } /** @@ -73,27 +75,31 @@ final class StartupProgressApplicationStartup implements ApplicationStartup { * Actuator only serves its {@code startup} endpoint for one, and the endpoint reports what the given one * recorded. */ + @PackageScope static ApplicationStartup create(ApplicationStartup delegate, StartupProgress progress, ConfigurableListableBeanFactory beanFactory) { - StartupProgressApplicationStartup startup = new StartupProgressApplicationStartup(delegate, progress, beanFactory); - return delegate instanceof BufferingApplicationStartup buffering ? new Buffering(buffering, startup) : startup; + StartupProgressApplicationStartup startup = new StartupProgressApplicationStartup(delegate, progress, beanFactory) + return delegate instanceof BufferingApplicationStartup ? new Buffering((BufferingApplicationStartup) delegate, startup) : startup } @Override - public StartupStep start(String name) { - StartupStep step = delegate.start(name); + StartupStep start(String name) { + StartupStep step = delegate.start(name) if (!progress.isReporting()) { - return step; + return step + } + switch (name) { + case BEAN_INSTANTIATE_STEP: + return new BeanCreationStep(step) + case BEAN_POST_PROCESS_STEP: + progress.loadingDefinitions() + return new BeanPostProcessStep(step) + case StartupTask.TASK_STEP: + return new TaskStep(step) + case StartupTask.ITEM_STEP: + return running.get() != null ? new ItemStep(step, running.get().task) : step + default: + return step } - return switch (name) { - case BEAN_INSTANTIATE_STEP -> new BeanCreationStep(step); - case BEAN_POST_PROCESS_STEP -> { - progress.loadingDefinitions(); - yield new BeanPostProcessStep(step); - } - case StartupTask.TASK_STEP -> new TaskStep(step); - case StartupTask.ITEM_STEP -> running.get() != null ? new ItemStep(step, running.get().task) : step; - default -> step; - }; } /** @@ -101,14 +107,14 @@ final class StartupProgressApplicationStartup implements ApplicationStartup { * registered every definition, which is when the set stops changing. */ private Set<String> eagerSingletons() { - Set<String> names = new HashSet<>(); + Set<String> names = new HashSet<>() for (String name : beanFactory.getBeanDefinitionNames()) { - BeanDefinition definition = beanFactory.getBeanDefinition(name); + BeanDefinition definition = beanFactory.getBeanDefinition(name) if (definition.isSingleton() && !definition.isAbstract() && !definition.isLazyInit()) { - names.add(name); + names.add(name) } } - return names; + return names } /** @@ -116,8 +122,8 @@ final class StartupProgressApplicationStartup implements ApplicationStartup { * factory that makes it. */ private String definedName(String requested) { - String name = BeanFactoryUtils.transformedBeanName(requested); - return beanFactory instanceof SimpleAliasRegistry aliases ? aliases.canonicalName(name) : name; + String name = BeanFactoryUtils.transformedBeanName(requested) + return beanFactory instanceof SimpleAliasRegistry ? ((SimpleAliasRegistry) beanFactory).canonicalName(name) : name } /** @@ -126,204 +132,206 @@ final class StartupProgressApplicationStartup implements ApplicationStartup { */ private static final class Buffering extends BufferingApplicationStartup { - private final BufferingApplicationStartup recording; + private final BufferingApplicationStartup recording - private final StartupProgressApplicationStartup progress; + private final StartupProgressApplicationStartup progress Buffering(BufferingApplicationStartup recording, StartupProgressApplicationStartup progress) { - super(1); - this.recording = recording; - this.progress = progress; + super(1) + this.recording = recording + this.progress = progress } @Override - public StartupStep start(String name) { - return progress.start(name); + StartupStep start(String name) { + return progress.start(name) } @Override - public void startRecording() { - recording.startRecording(); + void startRecording() { + recording.startRecording() } @Override - public void addFilter(Predicate<StartupStep> filter) { - recording.addFilter(filter); + void addFilter(Predicate<StartupStep> filter) { + recording.addFilter(filter) } @Override - public StartupTimeline getBufferedTimeline() { - return recording.getBufferedTimeline(); + StartupTimeline getBufferedTimeline() { + return recording.getBufferedTimeline() } @Override - public StartupTimeline drainBufferedTimeline() { - return recording.drainBufferedTimeline(); + StartupTimeline drainBufferedTimeline() { + return recording.drainBufferedTimeline() } } private abstract static class ForwardingStep implements StartupStep { - final StartupStep step; + @PackageScope + final StartupStep step ForwardingStep(StartupStep step) { - this.step = step; + this.step = step } @Override - public String getName() { - return step.getName(); + String getName() { + return step.getName() } @Override - public long getId() { - return step.getId(); + long getId() { + return step.getId() } @Override - public Long getParentId() { - return step.getParentId(); + Long getParentId() { + return step.getParentId() } @Override - public StartupStep tag(String key, String value) { - step.tag(key, value); - return this; + StartupStep tag(String key, String value) { + step.tag(key, value) + return this } @Override - public StartupStep tag(String key, Supplier<String> value) { - step.tag(key, value); - return this; + StartupStep tag(String key, Supplier<String> value) { + step.tag(key, value) + return this } @Override - public Tags getTags() { - return step.getTags(); + StartupStep.Tags getTags() { + return step.getTags() } @Override - public void end() { - step.end(); + void end() { + step.end() } } private final class BeanPostProcessStep extends ForwardingStep { BeanPostProcessStep(StartupStep step) { - super(step); + super(step) } @Override - public void end() { - super.end(); - progress.creatingBeans(eagerSingletons()); + void end() { + super.end() + StartupProgressApplicationStartup.this.progress.creatingBeans(StartupProgressApplicationStartup.this.eagerSingletons()) } } private final class BeanCreationStep extends ForwardingStep { - private final long startNanos = System.nanoTime(); + private final long startNanos = System.nanoTime() - private final BeanCreationStep enclosing; + private final BeanCreationStep enclosing - private long nestedNanos; + private long nestedNanos - private String beanName; + private String beanName BeanCreationStep(StartupStep step) { - super(step); - enclosing = creating.get(); - creating.set(this); + super(step) + enclosing = StartupProgressApplicationStartup.this.creating.get() + StartupProgressApplicationStartup.this.creating.set(this) } @Override - public StartupStep tag(String key, String value) { + StartupStep tag(String key, String value) { if (BEAN_NAME_TAG.equals(key) && value != null) { - beanName = definedName(value); - progress.beanCreationStarted(beanName); + beanName = StartupProgressApplicationStartup.this.definedName(value) + StartupProgressApplicationStartup.this.progress.beanCreationStarted(beanName) } - return super.tag(key, value); + return super.tag(key, value) } @Override - public void end() { - super.end(); - long elapsedNanos = System.nanoTime() - startNanos; - if (beanName != null && beanFactory.containsBeanDefinition(beanName)) { - progress.beanCreated(beanName, elapsedNanos - nestedNanos); + void end() { + super.end() + long elapsedNanos = System.nanoTime() - startNanos + if (beanName != null && StartupProgressApplicationStartup.this.beanFactory.containsBeanDefinition(beanName)) { + StartupProgressApplicationStartup.this.progress.beanCreated(beanName, elapsedNanos - nestedNanos) } if (enclosing != null) { - enclosing.nestedNanos += elapsedNanos; - creating.set(enclosing); + enclosing.@nestedNanos = enclosing.@nestedNanos + elapsedNanos + StartupProgressApplicationStartup.this.creating.set(enclosing) // the bean this one was created for is being created again, not the one that has just finished - if (enclosing.beanName != null) { - progress.beanCreationStarted(enclosing.beanName); + if (enclosing.@beanName != null) { + StartupProgressApplicationStartup.this.progress.beanCreationStarted(enclosing.@beanName) } } else { - creating.remove(); + StartupProgressApplicationStartup.this.creating.remove() } } } private final class TaskStep extends ForwardingStep { - private final StartupProgress.Task task = progress.taskStarted(); + @PackageScope + final StartupProgress.Task task = StartupProgressApplicationStartup.this.progress.taskStarted() - private final TaskStep enclosing; + private final TaskStep enclosing TaskStep(StartupStep step) { - super(step); - enclosing = running.get(); - running.set(this); + super(step) + enclosing = StartupProgressApplicationStartup.this.running.get() + StartupProgressApplicationStartup.this.running.set(this) } @Override - public StartupStep tag(String key, String value) { + StartupStep tag(String key, String value) { if (StartupTask.DESCRIPTION_TAG.equals(key)) { - task.described(value); + task.described(value) } else if (StartupTask.TOTAL_TAG.equals(key)) { - task.totalled(value); + task.totalled(value) } - return super.tag(key, value); + return super.tag(key, value) } @Override - public void end() { - super.end(); - task.ended(); + void end() { + super.end() + task.ended() if (enclosing != null) { - running.set(enclosing); + StartupProgressApplicationStartup.this.running.set(enclosing) } else { - running.remove(); + StartupProgressApplicationStartup.this.running.remove() } } } private static final class ItemStep extends ForwardingStep { - private final StartupProgress.Task task; + private final StartupProgress.Task task ItemStep(StartupStep step, StartupProgress.Task task) { - super(step); - this.task = task; + super(step) + this.task = task } @Override - public StartupStep tag(String key, String value) { + StartupStep tag(String key, String value) { if (StartupTask.ITEM_TAG.equals(key)) { - task.itemStarted(value); + task.itemStarted(value) } - return super.tag(key, value); + return super.tag(key, value) } @Override - public void end() { - super.end(); - task.itemEnded(); + void end() { + super.end() + task.itemEnded() } } } diff --git a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressFilter.groovy b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressFilter.groovy index 84b3eb79cd..2941a79c62 100644 --- a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressFilter.groovy +++ b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressFilter.groovy @@ -16,25 +16,24 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.grails.startup; - -import java.io.IOException; -import java.util.Collections; -import java.util.List; - -import jakarta.servlet.DispatcherType; -import jakarta.servlet.Filter; -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletRequest; -import jakarta.servlet.ServletResponse; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.Ordered; -import org.springframework.web.context.ConfigurableWebApplicationContext; +package org.apache.grails.startup + +import jakarta.servlet.DispatcherType +import jakarta.servlet.Filter +import jakarta.servlet.FilterChain +import jakarta.servlet.ServletException +import jakarta.servlet.ServletRequest +import jakarta.servlet.ServletResponse +import jakarta.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletResponse + +import groovy.transform.CompileStatic +import groovy.transform.PackageScope + +import org.springframework.boot.web.servlet.FilterRegistrationBean +import org.springframework.context.ConfigurableApplicationContext +import org.springframework.core.Ordered +import org.springframework.web.context.ConfigurableWebApplicationContext /** * Answers for the startup progress from inside the application, once the embedded web server has the port, @@ -49,91 +48,94 @@ import org.springframework.web.context.ConfigurableWebApplicationContext; * servlet mapped to {@code /} guarantees. Everything that touches the Servlet API lives here, so the run * listener can decide the application is not a servlet application without loading it.</p> */ +@CompileStatic final class StartupProgressFilter implements Filter { - private final StartupProgressResponder responder; + private final StartupProgressResponder responder - private final StartupProgressResponder.Takes takes; + private final StartupProgressResponder.Takes takes private StartupProgressFilter(StartupProgressResponder responder, StartupProgressResponder.Takes takes) { - this.responder = responder; - this.takes = takes; + this.responder = responder + this.takes = takes } /** * Whether refreshing this context starts an embedded web server, rather than joining a servlet * container that is already running, as a deployed war does. */ + @PackageScope static boolean startsEmbeddedServer(ConfigurableApplicationContext context) { - return context instanceof ConfigurableWebApplicationContext webContext && webContext.getServletContext() == null; + return context instanceof ConfigurableWebApplicationContext && ((ConfigurableWebApplicationContext) context).getServletContext() == null } /** * @param servesProgressPage whether browsers loading a page while the application starts get the progress page */ + @PackageScope static FilterRegistrationBean<Filter> registration(StartupProgressResponder responder, boolean servesProgressPage) { - StartupProgressResponder.Takes takes = servesProgressPage ? StartupProgressResponder.Takes.PAGE_LOADS : StartupProgressResponder.Takes.OWN_PATHS_ONLY; - FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>(new StartupProgressFilter(responder, takes)); - registration.setName("grailsStartupProgressFilter"); - registration.addUrlPatterns("/*"); - registration.setDispatcherTypes(DispatcherType.REQUEST); - registration.setOrder(Ordered.HIGHEST_PRECEDENCE); - return registration; + StartupProgressResponder.Takes takes = servesProgressPage ? StartupProgressResponder.Takes.PAGE_LOADS : StartupProgressResponder.Takes.OWN_PATHS_ONLY + FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<Filter>(new StartupProgressFilter(responder, takes)) + registration.setName('grailsStartupProgressFilter') + registration.addUrlPatterns('/*') + registration.setDispatcherTypes(DispatcherType.REQUEST) + registration.setOrder(Ordered.HIGHEST_PRECEDENCE) + return registration } @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - if (request instanceof HttpServletRequest httpRequest && response instanceof HttpServletResponse httpResponse && - responder.respond(new ServletExchange(httpRequest, httpResponse), takes)) { - return; + void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + if (request instanceof HttpServletRequest && response instanceof HttpServletResponse && + responder.respond(new ServletExchange((HttpServletRequest) request, (HttpServletResponse) response), takes)) { + return } - chain.doFilter(request, response); + chain.doFilter(request, response) } /** A request to the web server, as the responder answers it. */ private record ServletExchange(HttpServletRequest request, HttpServletResponse response) implements StartupProgressResponder.Exchange { @Override - public String method() { - return request.getMethod(); + String method() { + return request.getMethod() } @Override - public String path() { - return request.getRequestURI(); + String path() { + return request.getRequestURI() } @Override - public String query() { - return request.getQueryString(); + String query() { + return request.getQueryString() } @Override - public String header(String name) { - return request.getHeader(name); + String header(String name) { + return request.getHeader(name) } @Override - public List<String> headers(String name) { - return Collections.list(request.getHeaders(name)); + List<String> headers(String name) { + return Collections.list(request.getHeaders(name)) } @Override - public void setHeader(String name, String value) { - response.setHeader(name, value); + void setHeader(String name, String value) { + response.setHeader(name, value) } @Override - public void send(int status, String contentType, byte[] body) throws IOException { - response.setStatus(status); + void send(int status, String contentType, byte[] body) throws IOException { + response.setStatus(status) if (contentType != null) { - response.setContentType(contentType); + response.setContentType(contentType) } - response.setContentLength(body.length); + response.setContentLength(body.length) if (body.length > 0) { - response.getOutputStream().write(body); + response.getOutputStream().write(body) } - response.flushBuffer(); + response.flushBuffer() } } } diff --git a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressLifecycle.groovy b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressLifecycle.groovy index e3aff814dd..54e03611f5 100644 --- a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressLifecycle.groovy +++ b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressLifecycle.groovy @@ -16,55 +16,61 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.grails.startup; +package org.apache.grails.startup -import org.springframework.boot.web.server.context.WebServerApplicationContext; -import org.springframework.context.SmartLifecycle; +import groovy.transform.CompileStatic +import groovy.transform.PackageScope + +import org.springframework.boot.web.server.context.WebServerApplicationContext +import org.springframework.context.SmartLifecycle /** * Runs an action when the context's lifecycle reaches a phase next to the embedded web server's own: * just before the server starts, to hand the port over, or just after, to say the application is * now running its startup hooks. */ +@CompileStatic final class StartupProgressLifecycle implements SmartLifecycle { - private final int phase; + private final int phase - private final Runnable action; + private final Runnable action - private volatile boolean running; + private volatile boolean running private StartupProgressLifecycle(int phase, Runnable action) { - this.phase = phase; - this.action = action; + this.phase = phase + this.action = action } + @PackageScope static StartupProgressLifecycle beforeWebServer(Runnable action) { - return new StartupProgressLifecycle(WebServerApplicationContext.START_STOP_LIFECYCLE_PHASE - 1, action); + return new StartupProgressLifecycle(WebServerApplicationContext.START_STOP_LIFECYCLE_PHASE - 1, action) } + @PackageScope static StartupProgressLifecycle afterWebServer(Runnable action) { - return new StartupProgressLifecycle(WebServerApplicationContext.START_STOP_LIFECYCLE_PHASE + 1, action); + return new StartupProgressLifecycle(WebServerApplicationContext.START_STOP_LIFECYCLE_PHASE + 1, action) } @Override - public void start() { - running = true; - action.run(); + void start() { + running = true + action.run() } @Override - public void stop() { - running = false; + void stop() { + running = false } @Override - public boolean isRunning() { - return running; + boolean isRunning() { + return running } @Override - public int getPhase() { - return phase; + int getPhase() { + return phase } } diff --git a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressPage.groovy b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressPage.groovy index b6cd894493..1e93756b7e 100644 --- a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressPage.groovy +++ b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressPage.groovy @@ -16,51 +16,53 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.grails.startup; +package org.apache.grails.startup -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import java.nio.charset.StandardCharsets +import java.util.regex.Matcher +import java.util.regex.Pattern + +import groovy.transform.CompileStatic +import groovy.transform.PackageScope /** * Renders the progress page from its template. The page is static apart from the application name * and a small JSON configuration block; everything that changes during startup is fetched by the page * and written into it as text, never as markup. */ +@CompileStatic final class StartupProgressPage { /** The page runs only its own inline script and style, and talks only to the application. */ + @PackageScope static final String CONTENT_SECURITY_POLICY = - "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"; + "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" /** How long a client turned away while the application starts is asked to wait before trying again. */ - static final String RETRY_AFTER_SECONDS = "5"; + @PackageScope + static final String RETRY_AFTER_SECONDS = '5' - private static final String TEMPLATE_RESOURCE = "startup-progress.html"; + private static final String TEMPLATE_RESOURCE = 'startup-progress.html' - private static final Pattern PLACEHOLDER = Pattern.compile("\\{\\{(APPLICATION_NAME|GRAILS_VERSION|CONFIG)}}"); + private static final Pattern PLACEHOLDER = Pattern.compile('\\{\\{(APPLICATION_NAME|GRAILS_VERSION|CONFIG)}}') /** A part of the page included only for some requests, so it is not in the page at all for the others. */ - private static final Pattern SECTION = Pattern.compile("\\{\\{#(DETAILS|SIGN_IN)}}(.*?)\\{\\{/\\1}}", Pattern.DOTALL); + private static final Pattern SECTION = Pattern.compile('\\{\\{#(DETAILS|SIGN_IN)}}(.*?)\\{\\{/\\1}}', Pattern.DOTALL) - private final String applicationName; + private final String applicationName - private final String statusPath; + private final String statusPath - private final String grailsVersion; + private final String grailsVersion /** * @param grailsVersion the version shown in the footer to a browser that may see the details of the start */ + @PackageScope StartupProgressPage(String applicationName, String statusPath, String grailsVersion) { - this.applicationName = applicationName; - this.statusPath = statusPath; - this.grailsVersion = grailsVersion; + this.applicationName = applicationName + this.statusPath = statusPath + this.grailsVersion = grailsVersion } /** @@ -71,9 +73,10 @@ final class StartupProgressPage { * @param showDetails whether the browser may see the details of the start, the Grails version among them * @param signInForDetails whether the browser would see the details by signing in */ + @PackageScope String render(String method, boolean showDetails, boolean signInForDetails) { - boolean reload = "GET".equals(method) || "HEAD".equals(method); - return render(showDetails, signInForDetails, ",\"reload\":" + reload); + boolean reload = 'GET'.equals(method) || 'HEAD'.equals(method) + return render(showDetails, signInForDetails, ',"reload":' + reload) } /** @@ -81,70 +84,85 @@ final class StartupProgressPage { * * @param status the status of the start, as JSON */ + @PackageScope String renderReport(String status, boolean showDetails, boolean signInForDetails) { - return render(showDetails, signInForDetails, ",\"report\":" + status); + return render(showDetails, signInForDetails, ',"report":' + status) } private String render(boolean showDetails, boolean signInForDetails, String extraConfig) { - String config = "{\"statusPath\":" + StartupProgress.string(statusPath) + - ",\"phaseHeader\":" + StartupProgress.string(StartupProgress.PHASE_HEADER) + extraConfig + "}"; + String config = '{"statusPath":' + StartupProgress.string(statusPath) + + ',"phaseHeader":' + StartupProgress.string(StartupProgress.PHASE_HEADER) + extraConfig + '}' Map<String, String> values = Map.of( - "APPLICATION_NAME", escapeHtml(applicationName), - "GRAILS_VERSION", escapeHtml(showDetails && grailsVersion != null ? grailsVersion : ""), - "CONFIG", config); + 'APPLICATION_NAME', escapeHtml(applicationName), + 'GRAILS_VERSION', escapeHtml(showDetails && grailsVersion != null ? grailsVersion : ''), + 'CONFIG', config) // the details are left out of the page, not hidden in it, for a browser that may not see them String sections = SECTION.matcher(Template.TEXT).replaceAll(match -> { - boolean include = "DETAILS".equals(match.group(1)) ? showDetails : signInForDetails; - return include ? Matcher.quoteReplacement(match.group(2)) : ""; - }); - return PLACEHOLDER.matcher(sections).replaceAll(match -> Matcher.quoteReplacement(values.get(match.group(1)))); + boolean include = 'DETAILS'.equals(match.group(1)) ? showDetails : signInForDetails + return include ? Matcher.quoteReplacement(match.group(2)) : '' + }) + return PLACEHOLDER.matcher(sections).replaceAll(match -> Matcher.quoteReplacement(values.get(match.group(1)))) } /** * Whether a request for the startup report asks for it as data, with an {@code Accept} header naming * JSON but not HTML, or with a {@code format=json} parameter as Grails takes elsewhere. */ + @PackageScope static boolean wantsJson(String accept, String rawQuery) { - if (rawQuery != null && Arrays.asList(rawQuery.split("&")).contains("format=json")) { - return true; + if (rawQuery != null && Arrays.asList(rawQuery.split('&')).contains('format=json')) { + return true } - return accept != null && accept.contains("application/json") && !accept.contains("text/html"); + return accept != null && accept.contains('application/json') && !accept.contains('text/html') } + @PackageScope String plainText() { - return applicationName + " is starting. Try again shortly.\n"; + return applicationName + ' is starting. Try again shortly.\n' } private static String escapeHtml(String value) { - StringBuilder escaped = new StringBuilder(value.length()); + StringBuilder escaped = new StringBuilder(value.length()) for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); + String c = value.substring(i, i + 1) switch (c) { - case '<' -> escaped.append("<"); - case '>' -> escaped.append(">"); - case '&' -> escaped.append("&"); - case '"' -> escaped.append("""); - case '\'' -> escaped.append("'"); - default -> escaped.append(c); + case '<': + escaped.append('<') + break + case '>': + escaped.append('>') + break + case '&': + escaped.append('&') + break + case '"': + escaped.append('"') + break + case '\'': + escaped.append(''') + break + default: + escaped.append(c) } } - return escaped.toString(); + return escaped.toString() } /** Loads the template the first time a page is rendered rather than on every start. */ private static final class Template { - static final String TEXT = load(); + @PackageScope + static final String TEXT = load() private static String load() { - try (InputStream in = StartupProgressPage.class.getResourceAsStream(TEMPLATE_RESOURCE)) { - if (in == null) { - throw new IllegalStateException("Missing startup progress page template " + TEMPLATE_RESOURCE); + try (InputStream input = StartupProgressPage.getResourceAsStream(TEMPLATE_RESOURCE)) { + if (input == null) { + throw new IllegalStateException('Missing startup progress page template ' + TEMPLATE_RESOURCE) } - return new String(in.readAllBytes(), StandardCharsets.UTF_8); + return new String(input.readAllBytes(), StandardCharsets.UTF_8) } catch (IOException ex) { - throw new UncheckedIOException(ex); + throw new UncheckedIOException(ex) } } } diff --git a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressProperties.groovy b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressProperties.groovy index ec7b037fde..0837c10aef 100644 --- a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressProperties.groovy +++ b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressProperties.groovy @@ -16,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.grails.startup; +package org.apache.grails.startup -import java.util.ArrayList; -import java.util.List; +import groovy.transform.CompileStatic +import groovy.transform.PackageScope -import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.ConfigurationProperties -import grails.util.Environment; +import grails.util.Environment /** * Settings for the page Grails serves on the application's port while the application starts, @@ -35,45 +35,47 @@ import grails.util.Environment; * * @since 8.1 */ -@ConfigurationProperties(prefix = "grails.startup.progress") -public class StartupProgressProperties { +@ConfigurationProperties(prefix = 'grails.startup.progress') +@CompileStatic +class StartupProgressProperties { - static final String DEFAULT_STATUS_PATH = "/__grails/startup-progress"; + @PackageScope + static final String DEFAULT_STATUS_PATH = '/__grails/startup-progress' - private Boolean enabled; + private Boolean enabled - private String statusPath = DEFAULT_STATUS_PATH; + private String statusPath = DEFAULT_STATUS_PATH - private Boolean showDetails; + private Boolean showDetails - private boolean openBrowser; + private boolean openBrowser - private List<String> browserCommand = new ArrayList<>(); + private List<String> browserCommand = new ArrayList<>() - private final Endpoint endpoint = new Endpoint(); + private final Endpoint endpoint = new Endpoint() /** * Whether Grails answers on the application's port with a progress page until the embedded web * server takes the port over. {@code null} means development mode decides. */ - public Boolean getEnabled() { - return enabled; + Boolean getEnabled() { + return enabled } - public void setEnabled(Boolean enabled) { - this.enabled = enabled; + void setEnabled(Boolean enabled) { + this.enabled = enabled } /** * The path, below the context path, that the progress page polls for the progress of the start. Once the * application is ready, a poll there is told so, so the path is the application's no longer. */ - public String getStatusPath() { - return statusPath; + String getStatusPath() { + return statusPath } - public void setStatusPath(String statusPath) { - this.statusPath = statusPath; + void setStatusPath(String statusPath) { + this.statusPath = statusPath } /** @@ -81,12 +83,12 @@ public class StartupProgressProperties { * exception when startup fails, to a browser signed in with the address the application logs. * {@code null} means development mode decides. */ - public Boolean getShowDetails() { - return showDetails; + Boolean getShowDetails() { + return showDetails } - public void setShowDetails(Boolean showDetails) { - this.showDetails = showDetails; + void setShowDetails(Boolean showDetails) { + this.showDetails = showDetails } /** @@ -94,12 +96,12 @@ public class StartupProgressProperties { * served, or on the application once it is ready when the page is not served. A browser is opened once * per address for the life of the JVM, so a restart by Spring Boot DevTools does not open another. */ - public boolean isOpenBrowser() { - return openBrowser; + boolean isOpenBrowser() { + return openBrowser } - public void setOpenBrowser(boolean openBrowser) { - this.openBrowser = openBrowser; + void setOpenBrowser(boolean openBrowser) { + this.openBrowser = openBrowser } /** @@ -107,61 +109,65 @@ public class StartupProgressProperties { * the operating system's own is used: {@code open} on macOS, {@code xdg-open} elsewhere on Unix, and * {@code rundll32 url.dll,FileProtocolHandler} on Windows. */ - public List<String> getBrowserCommand() { - return browserCommand; + List<String> getBrowserCommand() { + return browserCommand } - public void setBrowserCommand(List<String> browserCommand) { - this.browserCommand = browserCommand; + void setBrowserCommand(List<String> browserCommand) { + this.browserCommand = browserCommand } /** The startup report the application serves once it has started. */ - public Endpoint getEndpoint() { - return endpoint; + Endpoint getEndpoint() { + return endpoint } + @PackageScope boolean isEnabledOrDefault() { - return enabled != null ? enabled : Environment.isDevelopmentMode(); + return enabled != null ? enabled : Environment.isDevelopmentMode() } + @PackageScope boolean isShowDetailsOrDefault() { - return showDetails != null ? showDetails : Environment.isDevelopmentMode(); + return showDetails != null ? showDetails : Environment.isDevelopmentMode() } /** * Where, and whether, the application serves a report of how it started once it is running: the time * each stage took and the slowest beans, as a page or, to a client asking for JSON, as data. */ - public static class Endpoint { + static class Endpoint { - static final String DEFAULT_PATH = "/__grails/startup"; + @PackageScope + static final String DEFAULT_PATH = '/__grails/startup' - private Boolean enabled; + private Boolean enabled - private String path = DEFAULT_PATH; + private String path = DEFAULT_PATH /** * Whether the application serves the startup report. {@code null} means development mode decides. */ - public Boolean getEnabled() { - return enabled; + Boolean getEnabled() { + return enabled } - public void setEnabled(Boolean enabled) { - this.enabled = enabled; + void setEnabled(Boolean enabled) { + this.enabled = enabled } /** The path of the startup report, below the context path. */ - public String getPath() { - return path; + String getPath() { + return path } - public void setPath(String path) { - this.path = path; + void setPath(String path) { + this.path = path } + @PackageScope boolean isEnabledOrDefault() { - return enabled != null ? enabled : Environment.isDevelopmentMode(); + return enabled != null ? enabled : Environment.isDevelopmentMode() } } } diff --git a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressResponder.groovy b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressResponder.groovy index b48b24cf3b..bd31799e37 100644 --- a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressResponder.groovy +++ b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressResponder.groovy @@ -16,11 +16,12 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.grails.startup; +package org.apache.grails.startup -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; +import java.nio.charset.StandardCharsets + +import groovy.transform.CompileStatic +import groovy.transform.PackageScope /** * Decides how the startup progress answers a request, and answers it, for both of the servers that answer @@ -45,6 +46,7 @@ import java.util.List; * {@code 503} for anything else</li> * </ul> */ +@CompileStatic final class StartupProgressResponder { /** Which requests a server takes, beyond the startup progress's own paths. */ @@ -63,94 +65,96 @@ final class StartupProgressResponder { /** A request and its response, as a server that answers for the startup progress hands them over. */ interface Exchange { - String method(); + String method() /** The path asked for, undecoded, with the context path. */ - String path(); + String path() /** The query, undecoded, or {@code null} when there is none. */ - String query(); + String query() - String header(String name); + String header(String name) - List<String> headers(String name); + List<String> headers(String name) - void setHeader(String name, String value); + void setHeader(String name, String value) /** * Sends the status, headers and body, all of it before returning. * * @param contentType the type of the body, or {@code null} when there is no body */ - void send(int status, String contentType, byte[] body) throws IOException; + void send(int status, String contentType, byte[] body) throws IOException } - private static final byte[] NO_BODY = new byte[0]; + private static final byte[] NO_BODY = new byte[0] - private final StartupProgress progress; + private final StartupProgress progress - private final StartupProgressPage page; + private final StartupProgressPage page - private final StartupAccess access; + private final StartupAccess access - private final String statusPath; + private final String statusPath - private final String reportPath; + private final String reportPath /** * @param statusPath the full path the progress page polls * @param reportPath the full path of the startup report, or {@code null} when it is not served */ + @PackageScope StartupProgressResponder(StartupProgress progress, StartupProgressPage page, StartupAccess access, String statusPath, String reportPath) { - this.progress = progress; - this.page = page; - this.access = access; - this.statusPath = statusPath; - this.reportPath = reportPath; + this.progress = progress + this.page = page + this.access = access + this.statusPath = statusPath + this.reportPath = reportPath } /** * Answers the request if the server takes it, and says whether it did. A request left unanswered is the * application's. */ + @PackageScope boolean respond(Exchange exchange, Takes takes) throws IOException { - String path = exchange.path(); - boolean starting = progress.isReporting(); - boolean status = path.equals(statusPath); - boolean report = path.equals(reportPath); + String path = exchange.path() + boolean starting = progress.isReporting() + boolean status = path.equals(statusPath) + boolean report = path.equals(reportPath) if (status && !starting) { // a page still polling once the application is ready is told so, rather than the poll reaching an // application that has no such path and logs every request it cannot map - sendReady(exchange); - return true; + sendReady(exchange) + return true } - boolean everyRequest = takes == Takes.EVERY_REQUEST; + boolean everyRequest = takes == Takes.EVERY_REQUEST if ((everyRequest || starting || report) && signIn(exchange)) { - return true; + return true } - boolean pageLoad = isPageLoad(exchange); + boolean pageLoad = isPageLoad(exchange) if (!everyRequest && !report && !(starting && (status || takes == Takes.PAGE_LOADS && pageLoad))) { - return false; + return false } - boolean showDetails = access.showsDetails(exchange.headers("Cookie")); - boolean signInForDetails = access.isSignInRequired() && !showDetails; + boolean showDetails = access.showsDetails(exchange.headers('Cookie')) + boolean signInForDetails = access.isSignInRequired() && !showDetails if (status) { - StartupProgress.Status current = progress.report(showDetails, signInForDetails); - exchange.setHeader(StartupProgress.PHASE_HEADER, current.phase().name()); - send(exchange, 200, "application/json", current.json()); - progress.delivered(current); + StartupProgress.Status current = progress.report(showDetails, signInForDetails) + exchange.setHeader(StartupProgress.PHASE_HEADER, current.phase().name()) + send(exchange, 200, 'application/json', current.json()) + progress.delivered(current) } - else if (report && StartupProgressPage.wantsJson(exchange.header("Accept"), exchange.query())) { - send(exchange, 200, "application/json", progress.snapshot(showDetails, signInForDetails).json()); + else if (report && StartupProgressPage.wantsJson(exchange.header('Accept'), exchange.query())) { + send(exchange, 200, 'application/json', progress.snapshot(showDetails, signInForDetails).json()) } else if (report && !starting) { - setPageHeaders(exchange); - send(exchange, 200, "text/html", page.renderReport(progress.snapshot(showDetails, signInForDetails).json(), showDetails, signInForDetails)); + setPageHeaders(exchange) + send(exchange, 200, 'text/html', page.renderReport(progress.snapshot(showDetails, signInForDetails).json(), showDetails, signInForDetails)) } else { - sendStarting(exchange, pageLoad, showDetails, signInForDetails); + sendStarting(exchange, pageLoad, showDetails, signInForDetails) } - return true; + return true } /** @@ -161,31 +165,31 @@ final class StartupProgressResponder { * code, is never mistaken for one. */ private static boolean isPageLoad(Exchange exchange) { - String mode = exchange.header("Sec-Fetch-Mode"); + String mode = exchange.header('Sec-Fetch-Mode') if (mode != null) { - return "navigate".equals(mode) && "document".equals(exchange.header("Sec-Fetch-Dest")); + return 'navigate'.equals(mode) && 'document'.equals(exchange.header('Sec-Fetch-Dest')) } - return "1".equals(exchange.header("Upgrade-Insecure-Requests")); + return '1'.equals(exchange.header('Upgrade-Insecure-Requests')) } /** Signs a browser in when its request carries the token from the log, and says whether it did. */ private boolean signIn(Exchange exchange) throws IOException { - String method = exchange.method(); - String signedIn = "GET".equals(method) || "HEAD".equals(method) ? access.signInRedirect(exchange.path(), exchange.query()) : null; + String method = exchange.method() + String signedIn = 'GET'.equals(method) || 'HEAD'.equals(method) ? access.signInRedirect(exchange.path(), exchange.query()) : null if (signedIn == null) { - return false; + return false } - exchange.setHeader("Cache-Control", "no-store"); - exchange.setHeader("Referrer-Policy", "no-referrer"); - exchange.setHeader("Set-Cookie", access.signInCookie()); - exchange.setHeader("Location", signedIn); - exchange.send(302, null, NO_BODY); - return true; + exchange.setHeader('Cache-Control', 'no-store') + exchange.setHeader('Referrer-Policy', 'no-referrer') + exchange.setHeader('Set-Cookie', access.signInCookie()) + exchange.setHeader('Location', signedIn) + exchange.send(302, null, NO_BODY) + return true } private static void sendReady(Exchange exchange) throws IOException { - exchange.setHeader(StartupProgress.PHASE_HEADER, StartupProgress.Phase.READY.name()); - send(exchange, 200, "application/json", "{\"phase\":\"READY\"}"); + exchange.setHeader(StartupProgress.PHASE_HEADER, StartupProgress.Phase.READY.name()) + send(exchange, 200, 'application/json', '{"phase":"READY"}') } /** @@ -193,26 +197,26 @@ final class StartupProgressResponder { * address once the application is ready, and anything else a plain answer to try again. */ private void sendStarting(Exchange exchange, boolean pageLoad, boolean showDetails, boolean signInForDetails) throws IOException { - exchange.setHeader(StartupProgress.PHASE_HEADER, progress.getPhase().name()); - exchange.setHeader("Retry-After", StartupProgressPage.RETRY_AFTER_SECONDS); - String accept = exchange.header("Accept"); - if (pageLoad || accept != null && accept.contains("text/html")) { - setPageHeaders(exchange); - send(exchange, 503, "text/html", page.render(exchange.method(), showDetails, signInForDetails)); + exchange.setHeader(StartupProgress.PHASE_HEADER, progress.getPhase().name()) + exchange.setHeader('Retry-After', StartupProgressPage.RETRY_AFTER_SECONDS) + String accept = exchange.header('Accept') + if (pageLoad || accept != null && accept.contains('text/html')) { + setPageHeaders(exchange) + send(exchange, 503, 'text/html', page.render(exchange.method(), showDetails, signInForDetails)) } else { - send(exchange, 503, "text/plain", page.plainText()); + send(exchange, 503, 'text/plain', page.plainText()) } } private static void setPageHeaders(Exchange exchange) { - exchange.setHeader("Content-Security-Policy", StartupProgressPage.CONTENT_SECURITY_POLICY); - exchange.setHeader("Referrer-Policy", "no-referrer"); + exchange.setHeader('Content-Security-Policy', StartupProgressPage.CONTENT_SECURITY_POLICY) + exchange.setHeader('Referrer-Policy', 'no-referrer') } private static void send(Exchange exchange, int status, String contentType, String content) throws IOException { - exchange.setHeader("Cache-Control", "no-store"); - exchange.setHeader("X-Content-Type-Options", "nosniff"); - exchange.send(status, contentType + ";charset=utf-8", content.getBytes(StandardCharsets.UTF_8)); + exchange.setHeader('Cache-Control', 'no-store') + exchange.setHeader('X-Content-Type-Options', 'nosniff') + exchange.send(status, contentType + ';charset=utf-8', content.getBytes(StandardCharsets.UTF_8)) } } diff --git a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressRunListener.groovy b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressRunListener.groovy index ac234bc181..bb3a161144 100644 --- a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressRunListener.groovy +++ b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressRunListener.groovy @@ -16,31 +16,28 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.grails.startup; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.time.Duration; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.SpringApplicationRunListener; -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.boot.web.server.context.WebServerApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.DefaultLifecycleProcessor; -import org.springframework.core.SpringProperties; -import org.springframework.util.StringUtils; - -import grails.util.Environment; +package org.apache.grails.startup + +import java.time.Duration + +import groovy.transform.CompileStatic + +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory +import org.springframework.boot.SpringApplication +import org.springframework.boot.SpringApplicationRunListener +import org.springframework.boot.WebApplicationType +import org.springframework.boot.context.properties.bind.Bindable +import org.springframework.boot.context.properties.bind.Binder +import org.springframework.boot.web.server.context.WebServerApplicationContext +import org.springframework.context.ConfigurableApplicationContext +import org.springframework.context.support.DefaultLifecycleProcessor +import org.springframework.core.SpringProperties +import org.springframework.util.StringUtils + +import grails.util.Environment /** * Serves a progress page on the application's port from the moment the application context is @@ -69,126 +66,129 @@ import grails.util.Environment; * * @since 8.1 */ -public class StartupProgressRunListener implements SpringApplicationRunListener { +@CompileStatic +class StartupProgressRunListener implements SpringApplicationRunListener { + + private static final Logger LOG = LoggerFactory.getLogger(StartupProgressRunListener) - private static final Logger LOG = LoggerFactory.getLogger(StartupProgressRunListener.class); + private static final String PROPERTIES_PREFIX = 'grails.startup.progress' - private static final String PROPERTIES_PREFIX = "grails.startup.progress"; + private static final int DEFAULT_PORT = 8080 - private static final int DEFAULT_PORT = 8080; + private static final char SLASH = '/' /** How long a failed start waits for a watching page to be told why, before it carries on failing. */ - private static final long FAILURE_DELIVERY_TIMEOUT_MILLIS = 2000; + private static final long FAILURE_DELIVERY_TIMEOUT_MILLIS = 2000 - private final SpringApplication application; + private final SpringApplication application /** When the run of the application began, which the times in the report are measured from. */ - private final long runStartNanos = System.nanoTime(); + private final long runStartNanos = System.nanoTime() - private StartupProgress progress; + private StartupProgress progress - private StartupAccess access; + private StartupAccess access /** The full path of the startup report, while it is served. */ - private String reportPath; + private String reportPath - private StartupProgressServer server; + private StartupProgressServer server - private InetAddress address; + private InetAddress address - private String contextPath = ""; + private String contextPath = '' - private boolean ssl; + private boolean ssl /** The command that opens a browser, while one is still to be opened for this start. */ - private List<String> browserCommand; + private List<String> browserCommand - public StartupProgressRunListener(SpringApplication application, String[] args) { - this.application = application; + StartupProgressRunListener(SpringApplication application, String[] args) { + this.application = application } @Override - public void contextPrepared(ConfigurableApplicationContext context) { + void contextPrepared(ConfigurableApplicationContext context) { if (application.getWebApplicationType() != WebApplicationType.SERVLET || !(context instanceof WebServerApplicationContext) || !StartupProgressFilter.startsEmbeddedServer(context)) { - return; + return } - Binder binder = Binder.get(context.getEnvironment()); - StartupProgressProperties properties; + Binder binder = Binder.get(context.getEnvironment()) + StartupProgressProperties properties try { - properties = binder.bindOrCreate(PROPERTIES_PREFIX, StartupProgressProperties.class); + properties = binder.bindOrCreate(PROPERTIES_PREFIX, StartupProgressProperties) } catch (RuntimeException ex) { // nothing else reads these settings, so a mistake in them is said here or not at all - LOG.warn("Not serving startup progress: the {} settings could not be read: {}", PROPERTIES_PREFIX, ex.getMessage()); - return; + LOG.warn('Not serving startup progress: the {} settings could not be read: {}', PROPERTIES_PREFIX, ex.getMessage()) + return } - int port; + int port try { - port = binder.bind("server.port", Integer.class).orElse(DEFAULT_PORT); - address = binder.bind("server.address", InetAddress.class).orElse(null); - contextPath = contextPath(binder.bind("server.servlet.context-path", String.class).orElse("")); - ssl = isSslEnabled(binder); + port = binder.bind('server.port', Integer).orElse(DEFAULT_PORT) + address = binder.bind('server.address', InetAddress).orElse(null) + contextPath = contextPath(binder.bind('server.servlet.context-path', String).orElse('')) + ssl = isSslEnabled(binder) } catch (RuntimeException ex) { // the web server reports a bad server.* setting far more usefully than this page could - LOG.debug("Not serving startup progress: the server settings could not be read", ex); - return; + LOG.debug('Not serving startup progress: the server settings could not be read', ex) + return } if (properties.isOpenBrowser()) { - browserCommand = properties.getBrowserCommand(); + browserCommand = properties.getBrowserCommand() } - boolean pageEnabled = properties.isEnabledOrDefault(); - boolean reportEnabled = properties.getEndpoint().isEnabledOrDefault(); + boolean pageEnabled = properties.isEnabledOrDefault() + boolean reportEnabled = properties.getEndpoint().isEnabledOrDefault() if (!pageEnabled && !reportEnabled) { - return; + return } - String applicationName = applicationName(binder); - StartupProgress startupProgress = new StartupProgress(applicationName, Environment.getGrailsVersion(), runStartNanos); - StartupAccess startupAccess = new StartupAccess(properties.isShowDetailsOrDefault(), port); - String statusPath = path(properties.getStatusPath(), StartupProgressProperties.DEFAULT_STATUS_PATH, "startup progress status"); - StartupProgressPage page = new StartupProgressPage(applicationName, statusPath, Environment.getGrailsVersion()); - reportPath = reportEnabled ? path(properties.getEndpoint().getPath(), StartupProgressProperties.Endpoint.DEFAULT_PATH, "startup report") : null; + String name = applicationName(binder) + StartupProgress startupProgress = new StartupProgress(name, Environment.getGrailsVersion(), runStartNanos) + StartupAccess startupAccess = new StartupAccess(properties.isShowDetailsOrDefault(), port) + String statusPath = path(properties.getStatusPath(), StartupProgressProperties.DEFAULT_STATUS_PATH, 'startup progress status') + StartupProgressPage page = new StartupProgressPage(name, statusPath, Environment.getGrailsVersion()) + reportPath = reportEnabled ? path(properties.getEndpoint().getPath(), StartupProgressProperties.Endpoint.DEFAULT_PATH, 'startup report') : null if (statusPath.equals(reportPath)) { // a page polling there would take the report for the application answering, and reload without end - LOG.warn("Not serving the startup report at {}: it is the path the startup progress page polls", reportPath); - reportPath = null; - reportEnabled = false; + LOG.warn('Not serving the startup report at {}: it is the path the startup progress page polls', reportPath) + reportPath = null + reportEnabled = false } - StartupProgressResponder responder = new StartupProgressResponder(startupProgress, page, startupAccess, statusPath, reportPath); - boolean servingPage = pageEnabled && servePage(responder, port); + StartupProgressResponder responder = new StartupProgressResponder(startupProgress, page, startupAccess, statusPath, reportPath) + boolean servingPage = pageEnabled && servePage(responder, port) if (!servingPage && !reportEnabled) { - reportPath = null; - return; + reportPath = null + return } - progress = startupProgress; - access = startupAccess; + progress = startupProgress + access = startupAccess - context.setApplicationStartup(StartupProgressApplicationStartup.create(context.getApplicationStartup(), startupProgress, context.getBeanFactory())); - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + context.setApplicationStartup(StartupProgressApplicationStartup.create(context.getApplicationStartup(), startupProgress, context.getBeanFactory())) + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory() // the lifecycle beans live as long as the context, so they hold what they act on rather than this listener - StartupProgressServer pageServer = server; - WebServerApplicationContext webContext = (WebServerApplicationContext) context; - beanFactory.registerSingleton("grailsStartupProgressHandOff", StartupProgressLifecycle.beforeWebServer(() -> { - startupProgress.startingWebServer(); + StartupProgressServer pageServer = server + WebServerApplicationContext webContext = (WebServerApplicationContext) context + beanFactory.registerSingleton('grailsStartupProgressHandOff', StartupProgressLifecycle.beforeWebServer(() -> { + startupProgress.startingWebServer() if (pageServer != null) { - pageServer.stop(); + pageServer.stop() } - })); - beanFactory.registerSingleton("grailsStartupProgressInitializing", StartupProgressLifecycle.afterWebServer(() -> { - startupProgress.initializing(); + })) + beanFactory.registerSingleton('grailsStartupProgressInitializing', StartupProgressLifecycle.afterWebServer(() -> { + startupProgress.initializing() if (webContext.getWebServer() != null) { // a random port is only known now, and names the cookie that signs a browser in to the report - startupAccess.usePort(webContext.getWebServer().getPort()); + startupAccess.usePort(webContext.getWebServer().getPort()) } - })); - beanFactory.registerSingleton("grailsStartupProgressFilter", - StartupProgressFilter.registration(responder, servingPage)); + })) + beanFactory.registerSingleton('grailsStartupProgressFilter', + StartupProgressFilter.registration(responder, servingPage)) if (servingPage) { - LOG.info("Startup progress is shown at {} until the application is ready", uri("http", port, "/", signInQuery())); - openBrowser("http", port, signInQuery()); + LOG.info('Startup progress is shown at {} until the application is ready', uri('http', port, '/', signInQuery())) + openBrowser('http', port, signInQuery()) } } @@ -197,134 +197,135 @@ public class StartupProgressRunListener implements SpringApplicationRunListener */ private boolean servePage(StartupProgressResponder responder, int port) { if (port <= 0) { - LOG.debug("Not serving startup progress: server.port {} is not a fixed port", port); - return false; + LOG.debug('Not serving startup progress: server.port {} is not a fixed port', port) + return false } if (ssl) { - LOG.debug("Not serving startup progress: the web server uses SSL"); - return false; + LOG.debug('Not serving startup progress: the web server uses SSL') + return false } if (isCheckpointOnRefresh()) { // the checkpoint is taken before any lifecycle bean starts, so before the port would be handed over, // and a checkpoint fails on an open socket - LOG.debug("Not serving startup progress: a checkpoint is taken on refresh"); - return false; + LOG.debug('Not serving startup progress: a checkpoint is taken on refresh') + return false } - StartupProgressServer progressServer = new StartupProgressServer(address, port, responder); + StartupProgressServer progressServer = new StartupProgressServer(address, port, responder) try { - progressServer.start(); + progressServer.start() } catch (IOException ex) { - LOG.debug("Not serving startup progress: port {} could not be bound", port, ex); - return false; + LOG.debug('Not serving startup progress: port {} could not be bound', port, ex) + return false } - server = progressServer; - return true; + server = progressServer + return true } @Override - public void started(ConfigurableApplicationContext context, Duration timeTaken) { + void started(ConfigurableApplicationContext context, Duration timeTaken) { if (progress != null) { - progress.started(); + progress.started() } - stopServer(); + stopServer() } @Override - public void ready(ConfigurableApplicationContext context, Duration timeTaken) { + void ready(ConfigurableApplicationContext context, Duration timeTaken) { if (progress != null) { - progress.ready(); + progress.ready() } - stopServer(); - if (context instanceof WebServerApplicationContext webContext && webContext.getWebServer() != null) { - String scheme = ssl ? "https" : "http"; - int port = webContext.getWebServer().getPort(); + stopServer() + if (context instanceof WebServerApplicationContext && ((WebServerApplicationContext) context).getWebServer() != null) { + WebServerApplicationContext webContext = (WebServerApplicationContext) context + String scheme = ssl ? 'https' : 'http' + int port = webContext.getWebServer().getPort() if (reportPath != null) { // the details of the start are for whoever can read this log, so the address carries the token that shows them - LOG.info("Startup report is at {}", uri(scheme, port, reportPath.substring(contextPath.length()), signInQuery())); + LOG.info('Startup report is at {}', uri(scheme, port, reportPath.substring(contextPath.length()), signInQuery())) } // a browser not opened on the progress page opens on the application itself - openBrowser(scheme, port, null); + openBrowser(scheme, port, null) } } @Override - public void failed(ConfigurableApplicationContext context, Throwable exception) { + void failed(ConfigurableApplicationContext context, Throwable exception) { if (progress == null) { - return; + return } - StartupProgress.Phase reached = progress.getPhase(); - progress.failed(exception); + StartupProgress.Phase reached = progress.getPhase() + progress.failed(exception) if (server == null) { // only the report was served, which nobody watches while the application starts - return; + return } - boolean answering = server.isRunning(); + boolean answering = server.isRunning() if (!answering && (reached == StartupProgress.Phase.STARTING_WEB_SERVER || reached == StartupProgress.Phase.INITIALIZING)) { // a refresh that fails as the web server starts, or once it is up, stops the web server before run // listeners hear of it, so take the port back to say why; if the port is still held once the web server // is up, the failure came after the refresh and the web server's own filter is answering - answering = restartServer() || reached == StartupProgress.Phase.INITIALIZING; + answering = restartServer() || reached == StartupProgress.Phase.INITIALIZING } if (answering) { - progress.awaitFailureDelivery(FAILURE_DELIVERY_TIMEOUT_MILLIS); + progress.awaitFailureDelivery(FAILURE_DELIVERY_TIMEOUT_MILLIS) } - stopServer(); + stopServer() } private boolean restartServer() { try { - server.start(); - return true; + server.start() + return true } catch (IOException ex) { - LOG.debug("Could not take the port back to report the failed start", ex); - return false; + LOG.debug('Could not take the port back to report the failed start', ex) + return false } } private void openBrowser(String scheme, int port, String query) { - List<String> command = browserCommand; + List<String> command = browserCommand if (command == null || port <= 0) { - return; + return } - browserCommand = null; - URI uri = uri(scheme, port, "/", query); - if (uri != null) { - StartupBrowser.open(uri, command); + browserCommand = null + URI target = uri(scheme, port, '/', query) + if (target != null) { + StartupBrowser.open(target, command) } } /** The query that signs a browser in from the log, when there are details it would see by signing in. */ private String signInQuery() { - return access.isSignInRequired() ? access.signInQuery() : null; + return access.isSignInRequired() ? access.signInQuery() : null } private URI uri(String scheme, int port, String path, String query) { - String host = address == null || address.isAnyLocalAddress() ? "localhost" : address.getHostAddress(); + String host = address == null || address.isAnyLocalAddress() ? 'localhost' : address.getHostAddress() try { - return new URI(scheme, null, host, port, contextPath + path, query, null); + return new URI(scheme, null, host, port, contextPath + path, query, null) } catch (URISyntaxException ex) { - LOG.debug("No address to open a browser on for context path {}", contextPath, ex); - return null; + LOG.debug('No address to open a browser on for context path {}', contextPath, ex) + return null } } private void stopServer() { if (server != null) { - server.stop(); + server.stop() } } /** Whether Spring is to take a CRaC checkpoint when the context refreshes, as {@code -Dspring.context.checkpoint=onRefresh} asks. */ private static boolean isCheckpointOnRefresh() { - return DefaultLifecycleProcessor.ON_REFRESH_VALUE.equalsIgnoreCase(SpringProperties.getProperty(DefaultLifecycleProcessor.CHECKPOINT_PROPERTY_NAME)); + return DefaultLifecycleProcessor.ON_REFRESH_VALUE.equalsIgnoreCase(SpringProperties.getProperty(DefaultLifecycleProcessor.CHECKPOINT_PROPERTY_NAME)) } private static boolean isSslEnabled(Binder binder) { - boolean configured = binder.bind("server.ssl", Bindable.mapOf(String.class, Object.class)).map(ssl -> !ssl.isEmpty()).orElse(false); - return configured && binder.bind("server.ssl.enabled", Boolean.class).orElse(true); + boolean configured = binder.bind('server.ssl', Bindable.mapOf(String, Object)).map((Map<String, Object> ssl) -> !ssl.isEmpty()).orElse(false) + return configured && binder.bind('server.ssl.enabled', Boolean).orElse(true) } /** @@ -332,21 +333,21 @@ public class StartupProgressRunListener implements SpringApplicationRunListener * would take the place of the application's own root falls back to the default. */ private String path(String configured, String defaultPath, String servedThere) { - String path = contextPath(configured == null ? "" : configured); + String path = contextPath(configured == null ? '' : configured) if (path.isEmpty()) { - LOG.warn("Serving the {} at {} rather than at the application's root", servedThere, defaultPath); - path = defaultPath; + LOG.warn('Serving the {} at {} rather than at the application\'s root', servedThere, defaultPath) + path = defaultPath } - return contextPath + path; + return contextPath + path } private static String contextPath(String configured) { - String path = StringUtils.trimTrailingCharacter(configured.trim(), '/'); - return path.isEmpty() || path.startsWith("/") ? path : "/" + path; + String path = StringUtils.trimTrailingCharacter(configured.trim(), SLASH) + return path.isEmpty() || path.startsWith('/') ? path : '/' + path } private static String applicationName(Binder binder) { - return binder.bind("spring.application.name", String.class) - .orElseGet(() -> binder.bind("info.app.name", String.class).orElse("Grails application")); + return binder.bind('spring.application.name', String) + .orElseGet(() -> binder.bind('info.app.name', String).orElse('Grails application')) } } diff --git a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressServer.groovy b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressServer.groovy index b2b98ded1e..f1eaa1a6ef 100644 --- a/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressServer.groovy +++ b/grails-startup-progress/src/main/groovy/org/apache/grails/startup/StartupProgressServer.groovy @@ -16,41 +16,40 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.grails.startup; +package org.apache.grails.startup -import java.io.IOException; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.FutureTask; +import java.util.concurrent.ExecutionException +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.FutureTask -import com.sun.net.httpserver.HttpExchange; -import com.sun.net.httpserver.HttpServer; +import com.sun.net.httpserver.HttpExchange +import com.sun.net.httpserver.HttpServer +import groovy.transform.CompileStatic +import groovy.transform.PackageScope /** * Holds the application's port until the embedded web server is about to take it over, answering every * request on it with the {@link StartupProgressResponder}: the progress page for a browser, the status * the page polls for, and a plain {@code 503} for anything else. */ +@CompileStatic final class StartupProgressServer { - private final InetSocketAddress address; + private final InetSocketAddress address - private final StartupProgressResponder responder; + private final StartupProgressResponder responder - private HttpServer server; + private HttpServer server - private ExecutorService executor; + private ExecutorService executor - private volatile boolean running; + private volatile boolean running + @PackageScope StartupProgressServer(InetAddress address, int port, StartupProgressResponder responder) { - this.address = new InetSocketAddress(address, port); - this.responder = responder; + this.address = new InetSocketAddress(address, port) + this.responder = responder } /** @@ -63,22 +62,23 @@ final class StartupProgressServer { * * @throws IOException when the port cannot be bound, typically because something else holds it */ + @PackageScope void start() throws IOException { if (running) { - return; + return } - HttpServer httpServer = HttpServer.create(address, 0); + HttpServer httpServer = HttpServer.create(address, 0) ExecutorService pool = Executors.newFixedThreadPool(2, runnable -> { - Thread thread = new Thread(runnable, "grails-startup-progress"); - thread.setDaemon(true); - return thread; - }); - httpServer.createContext("/", this::handle); - httpServer.setExecutor(pool); - startFromDaemonThread(httpServer); - server = httpServer; - executor = pool; - running = true; + Thread thread = new Thread(runnable, 'grails-startup-progress') + thread.setDaemon(true) + return thread + }) + httpServer.createContext('/', (HttpExchange request) -> handle(request)) + httpServer.setExecutor(pool) + startFromDaemonThread(httpServer) + server = httpServer + executor = pool + running = true } /** @@ -86,53 +86,55 @@ final class StartupProgressServer { * daemon status of the thread that calls {@code start()}, and nothing else makes it a daemon. */ private static void startFromDaemonThread(HttpServer httpServer) throws IOException { - FutureTask<Void> start = new FutureTask<>(httpServer::start, null); - Thread starter = new Thread(start, "grails-startup-progress-start"); - starter.setDaemon(true); - starter.start(); - boolean interrupted = false; + FutureTask<Void> start = new FutureTask<Void>(() -> httpServer.start(), null) + Thread starter = new Thread(start, 'grails-startup-progress-start') + starter.setDaemon(true) + starter.start() + boolean interrupted = false try { while (true) { try { - start.get(); - return; + start.get() + return } - catch (InterruptedException ex) { + catch (InterruptedException ignored) { // the server is starting whether or not this thread is interrupted, so wait for it either way - interrupted = true; + interrupted = true } catch (ExecutionException ex) { - throw new IOException("The startup progress server could not be started", ex.getCause()); + throw new IOException('The startup progress server could not be started', ex.getCause()) } } } finally { if (interrupted) { - Thread.currentThread().interrupt(); + Thread.currentThread().interrupt() } } } + @PackageScope boolean isRunning() { - return running; + return running } /** * Closes the listening socket and returns once it is released, so the web server can bind the port * straight after. */ + @PackageScope void stop() { if (!running) { - return; + return } - running = false; - server.stop(0); - executor.shutdownNow(); + running = false + server.stop(0) + executor.shutdownNow() } private void handle(HttpExchange exchange) throws IOException { - try (exchange) { - responder.respond(new JdkExchange(exchange), StartupProgressResponder.Takes.EVERY_REQUEST); + try (HttpExchange closeable = exchange) { + responder.respond(new JdkExchange(closeable), StartupProgressResponder.Takes.EVERY_REQUEST) } } @@ -140,48 +142,48 @@ final class StartupProgressServer { private record JdkExchange(HttpExchange exchange) implements StartupProgressResponder.Exchange { @Override - public String method() { - return exchange.getRequestMethod(); + String method() { + return exchange.getRequestMethod() } @Override - public String path() { - return exchange.getRequestURI().getRawPath(); + String path() { + return exchange.getRequestURI().getRawPath() } @Override - public String query() { - return exchange.getRequestURI().getRawQuery(); + String query() { + return exchange.getRequestURI().getRawQuery() } @Override - public String header(String name) { - return exchange.getRequestHeaders().getFirst(name); + String header(String name) { + return exchange.getRequestHeaders().getFirst(name) } @Override - public List<String> headers(String name) { - List<String> values = exchange.getRequestHeaders().get(name); - return values != null ? values : List.of(); + List<String> headers(String name) { + List<String> values = exchange.getRequestHeaders().get(name) + return values != null ? values : List.of() } @Override - public void setHeader(String name, String value) { - exchange.getResponseHeaders().set(name, value); + void setHeader(String name, String value) { + exchange.getResponseHeaders().set(name, value) } @Override - public void send(int status, String contentType, byte[] body) throws IOException { + void send(int status, String contentType, byte[] body) throws IOException { if (contentType != null) { - exchange.getResponseHeaders().set("Content-Type", contentType); + exchange.getResponseHeaders().set('Content-Type', contentType) } - if (body.length == 0 || "HEAD".equals(exchange.getRequestMethod())) { - exchange.sendResponseHeaders(status, -1); - return; + if (body.length == 0 || 'HEAD'.equals(exchange.getRequestMethod())) { + exchange.sendResponseHeaders(status, -1) + return } - exchange.sendResponseHeaders(status, body.length); + exchange.sendResponseHeaders(status, body.length) try (OutputStream out = exchange.getResponseBody()) { - out.write(body); + out.write(body) } } }
