resource-registry-handlers/src/main/java/org/gcube/smartgears/handler/resourceregistry/EServiceHandler.java

268 lines
9.4 KiB
Java

package org.gcube.smartgears.handler.resourceregistry;
import static org.gcube.common.events.Observes.Kind.resilient;
import static org.gcube.smartgears.handler.resourceregistry.Constants.RESOURCE_MANAGEMENT;
import static org.gcube.smartgears.handlers.ProfileEvents.addToContext;
import static org.gcube.smartgears.handlers.ProfileEvents.removeFromContext;
import static org.gcube.smartgears.lifecycle.application.ApplicationLifecycle.activation;
import static org.gcube.smartgears.lifecycle.application.ApplicationLifecycle.failure;
import static org.gcube.smartgears.lifecycle.application.ApplicationLifecycle.stop;
import static org.gcube.smartgears.utils.Utils.rethrowUnchecked;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.xml.bind.annotation.XmlRootElement;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.events.Observes;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.resourcemanagement.model.reference.entities.facets.ServiceStateFacet;
import org.gcube.resourcemanagement.model.reference.entities.resources.EService;
import org.gcube.smartgears.context.Property;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.handler.resourceregistry.resourcemanager.EServiceManager;
import org.gcube.smartgears.handlers.application.ApplicationLifecycleEvent;
import org.gcube.smartgears.handlers.application.ApplicationLifecycleHandler;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.lifecycle.application.ApplicationState;
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
import org.gcube.smartgears.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Manages the {@link EService} {@link Resource} of the application.
* <p>
* The manager:
* <ul>
* <li>creates the {@link EService} {@link Resource} and the facets it
* {@link ConsistsOf} when the application starts for the first time;</li>
* <li>update the {@link ServiceStateFacet} when the application becomes active,
* and at any lifecycle change thereafter;</li>
* </ul>
* </p>
*
* @author Luca Frosini
*/
@XmlRootElement(name = RESOURCE_MANAGEMENT)
public class EServiceHandler extends ApplicationLifecycleHandler {
private static final Logger logger = LoggerFactory.getLogger(EServiceHandler.class);
private ApplicationContext applicationContext;
private ScheduledFuture<?> periodicUpdates;
protected EServiceManager eServiceManager;
public EServiceHandler() {
super();
}
@Override
public void onStart(ApplicationLifecycleEvent.Start e) {
try {
logger.info("{} onStart started", this.getClass().getSimpleName());
this.applicationContext = e.context();
init();
registerObservers();
schedulePeriodicUpdates();
logger.info("{} onStart finished", this.getClass().getSimpleName());
} catch (Throwable re) {
logger.error("onStart failed", re);
}
}
private void init() {
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
String previousToken = SecurityTokenProvider.instance.get();
try {
Thread.currentThread().setContextClassLoader(EServiceHandler.class.getClassLoader());
boolean create = true;
Set<String> startTokens = applicationContext.configuration().startTokens();
for (String token : startTokens) {
ContextUtility.setContextFromToken(token);
try {
if (create) {
eServiceManager = new EServiceManager();
eServiceManager.createEService(applicationContext);
applicationContext.properties()
.add(new Property(Constants.ESERVICE_MANAGER_PROPERTY, eServiceManager));
create = false;
} else {
eServiceManager.addToContext(applicationContext);
}
} catch (Exception e) {
logger.error("Unable to add {} to current context ({})", eServiceManager.geteService(),
ContextUtility.getContextName(token), e);
}
}
} catch (Throwable e) {
rethrowUnchecked(e);
} finally {
ContextUtility.setContextFromToken(previousToken);
Thread.currentThread().setContextClassLoader(contextCL);
}
logger.info("{} init() terminated", this.getClass().getSimpleName());
}
private void registerObservers() {
applicationContext.events().subscribe(new Object() {
// @Observes({ activation, stop, failure })
@Observes({ activation })
void onChanged(ApplicationLifecycle lc) {
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
String currentToken = SecurityTokenProvider.instance.get();
if (currentToken == null) {
currentToken = applicationContext.configuration().startTokens().iterator().next();
}
ContextUtility.setContextFromToken(currentToken);
try {
Thread.currentThread().setContextClassLoader(EServiceHandler.class.getClassLoader());
eServiceManager.updateServiceStateFacet(applicationContext);
} catch (Exception e) {
logger.error("Failed to update {} State", EService.NAME, e);
} finally {
Thread.currentThread().setContextClassLoader(contextCL);
}
}
@Observes({ stop, failure })
void onStop(ApplicationLifecycle lc) {
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
String currentToken = SecurityTokenProvider.instance.get();
if (currentToken == null) {
currentToken = applicationContext.configuration().startTokens().iterator().next();
}
ContextUtility.setContextFromToken(currentToken);
try {
Thread.currentThread().setContextClassLoader(EServiceHandler.class.getClassLoader());
eServiceManager.removeEService(applicationContext);
} catch (Exception e) {
logger.error("Failed to update Service State", e);
} finally {
Thread.currentThread().setContextClassLoader(contextCL);
}
}
@Observes(value = addToContext)
void addTo(String token) {
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
String previousToken = SecurityTokenProvider.instance.get();
try {
Thread.currentThread().setContextClassLoader(EServiceHandler.class.getClassLoader());
ContextUtility.setContextFromToken(token);
eServiceManager.addToContext(applicationContext);
} catch (Exception e) {
logger.error("Failed to add HostingNode to current context ({})",
ContextUtility.getCurrentContextName(), e);
} finally {
ContextUtility.setContextFromToken(previousToken);
Thread.currentThread().setContextClassLoader(contextCL);
}
}
@Observes(value = removeFromContext)
void removeFrom(String token) {
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
String previousToken = SecurityTokenProvider.instance.get();
try {
Thread.currentThread().setContextClassLoader(EServiceHandler.class.getClassLoader());
ContextUtility.setContextFromToken(token);
eServiceManager.removeFromContext();
} catch (Exception e) {
logger.error("Failed to remove HostingNode from current context ({})",
ContextUtility.getCurrentContextName(), e);
} finally {
ContextUtility.setContextFromToken(previousToken);
Thread.currentThread().setContextClassLoader(contextCL);
}
}
});
}
private void schedulePeriodicUpdates() {
// register to cancel updates
applicationContext.events().subscribe(
new Object() {
// we register it in response to lifecycle events so that we can
// stop and resume along with application
@Observes(value = { activation }, kind = resilient)
synchronized void restartPeriodicUpdates(final ApplicationLifecycle lc) {
// already running
if (periodicUpdates != null) {
return;
}
if (lc.state() == ApplicationState.active) {
logger.info("scheduling periodic updates of application {} EService",
applicationContext.name());
} else {
logger.info("resuming periodic updates of application {} EService",
applicationContext.name());
}
final Runnable updateTask = new Runnable() {
public void run() {
try {
String currentToken = SecurityTokenProvider.instance.get();
if (currentToken == null)
currentToken = applicationContext.configuration().startTokens().iterator()
.next();
ContextUtility.setContextFromToken(currentToken);
eServiceManager.updateServiceStateFacet(applicationContext);
} catch (Exception e) {
logger.error("Cannot complete periodic update of EService", e);
}
}
};
periodicUpdates = Utils.scheduledServicePool.scheduleAtFixedRate(updateTask,
Constants.application_republish_frequency_in_minutes,
Constants.application_republish_frequency_in_minutes, TimeUnit.MINUTES);
}
@Observes(value = { stop, failure }, kind = resilient)
synchronized void cancelPeriodicUpdates(ContainerLifecycle ignore) {
if (periodicUpdates != null) {
logger.trace("stopping periodic updates of application {} EService",
applicationContext.name());
try {
periodicUpdates.cancel(true);
periodicUpdates = null;
} catch (Exception e) {
logger.warn("could not stop periodic updates of application {}",
applicationContext.name(), e);
}
}
}
});
}
@Override
public String toString() {
return RESOURCE_MANAGEMENT;
}
}