Skip to content

Instantly share code, notes, and snippets.

@rah003
Last active June 21, 2018 07:54
Show Gist options
  • Save rah003/7f9eec77929918756d5894d8d3325e4f to your computer and use it in GitHub Desktop.
Save rah003/7f9eec77929918756d5894d8d3325e4f to your computer and use it in GitHub Desktop.
package aws.servlet.heartbeat;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import info.magnolia.objectfactory.Components;
import info.magnolia.module.ModuleManager;
import info.magnolia.cms.beans.config.ConfigLoader;
import info.magnolia.cms.beans.config.VersionConfig;
import info.magnolia.cms.beans.config.ServerConfiguration;
import info.magnolia.publishing.PublishingCoreModule;
// deploy under "/.magnolia/awsHeartbeat"
public class AWSHeartbeatServlet extends HttpServlet {
private boolean provisioned = false;
private long lastProvisioningRequest = Long.MIN_VALUE;
private boolean publicsAreReady = false;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (provisioned && selfReady() && isPublicProfile() {
// public instance is ready when provisioned, installed and reachable by http
response.setStatus(200);
if (provisioned && selfReady() && !isPublicProfile && publicsAreReady)) {
// author instance is ready when provisioned, installed and all it's publics are reachable by http
response.setStatus(200);
} else {
response.setStatus(503);
long now = new Date().getTime();
// wait for 5 minutes before asking public directly (might want to make this configurable)
if (now - lastProvisioningRequest > 300) {
lastProvisioningRequest = now;
publicsAreReady = true;
try {
for (Receiver receiver: Components.getComponent(PublishingCoreModule.class).getReceivers()) {
String url = receiver.getUrl() + "/.magnolia/awsHeartbeat"
URL url = new URL(url);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
publicsAreReady &= (http.getResponseCode() == 200);
}
} catch (Exception e) {
publicsAreReady = false;
}
}
}
}
protected boolean isPublicProfile() {
return Components.getComponent(ServerConfiguration.class).isAdmin();
}
protected boolean selfReady() {
boolean ready = true;
try {
ready = MgnlContext.hasInstance();
moduleManager = Components.getComponent(ModuleManager.class);
configLoader = Components.getComponent(ConfigLoader.class);
} catch (Exception e) {
ready = false;
}
return ready && !mm.getStatus().needsUpdateOrInstall();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// got notified by AWS that provisioning is finished
provisioned = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment