Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Quarkus initialization thread-safe in BaseFunction #23801

Merged
merged 3 commits into from
Feb 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,13 @@ public class BaseFunction {

private static final int BUFFER_SIZE = 8096;

protected static void initQuarkus() {
protected static void ensureQuarkusInitialized() {
// The following will atomically call initQuarkus if this hasn't been done before,
// and therefore make sure that deploymentStatus, started and bootstrapError are all set as necessary
QuarkusInitializer.ensureQuarkusInitialized();
}

private static void initQuarkus() {
StringWriter error = new StringWriter();
PrintWriter errorWriter = new PrintWriter(error, true);
if (Application.currentApplication() == null) { // were we already bootstrapped? Needed for mock azure unit testing.
Expand All @@ -55,6 +61,7 @@ protected static void initQuarkus() {
bootstrapError = true;
errorWriter.println("Quarkus bootstrap failed.");
ex.printStackTrace(errorWriter);
log.error("Quarkus bootstrap failed.", ex);
}
} else {
errorWriter.println("Quarkus bootstrapped successfully.");
Expand Down Expand Up @@ -174,4 +181,19 @@ public void close() {
future.completeExceptionally(new RuntimeException("Connection closed"));
}
}

private static final class QuarkusInitializer {

static {
// Using an initializer block ensures that initQuarkus is called exactly once,
// and is called atomically, thereby making it thread-safe.

initQuarkus();
}

private static void ensureQuarkusInitialized() {
// No code needed; the static initializer block will take care of the initialization.
// This method exists to ensure that this class is loaded, and therefore Quarkus is initialized.
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ public class Function extends BaseFunction {
public HttpResponseMessage run(
@HttpTrigger(name = "req") HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
if (!started && !bootstrapError) {
initQuarkus();
}

ensureQuarkusInitialized();

if (bootstrapError) {
HttpResponseMessage.Builder responseBuilder = request
.createResponseBuilder(HttpStatus.valueOf(500)).body(
Expand Down