This commit is contained in:
Lucio Lelii 2017-10-16 16:22:44 +00:00
parent f7ca18fd79
commit 66011345b5
2 changed files with 227 additions and 208 deletions

View File

@ -97,7 +97,7 @@ public class EServiceManager extends ApplicationLifecycleHandler {
private ScheduledFuture<?> periodicUpdates;
private static List<String> servletExcludes = Arrays.asList("default","jsp");
public EServiceManager() {
super();
this.authorizationProxy = ProviderFactory.provider()
@ -118,13 +118,19 @@ public class EServiceManager extends ApplicationLifecycleHandler {
@Override
public void onStart(ApplicationLifecycleEvent.Start e) {
this.applicationContext = e.context();
init();
registerObservers();
schedulePeriodicUpdates();
try{
logger.info("onStart started");
this.applicationContext = e.context();
init();
registerObservers();
schedulePeriodicUpdates();
logger.info("onStart finished");
}catch(Throwable re){
logger.error("onStart failed", re);
}
}
private void init() {
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
String previousToken = SecurityTokenProvider.instance.get();
@ -133,7 +139,7 @@ public class EServiceManager extends ApplicationLifecycleHandler {
EServiceManager.class.getClassLoader());
EService eService = null;
Set<String> startTokens = applicationContext.configuration().startTokens();
for (String token : startTokens) {
setContextFromToken(token);
@ -144,14 +150,15 @@ public class EServiceManager extends ApplicationLifecycleHandler {
eService= getEService();
share(eService);
}
} catch (Exception e) {
} catch (Throwable e) {
rethrowUnchecked(e);
} finally {
setContextFromToken(previousToken);
Thread.currentThread().setContextClassLoader(contextCL);
}
logger.info("init for EService executed");
}
private void share(EService eService) {
logger.trace("sharing EService for {}", applicationContext.name());
applicationContext.properties().add(
@ -167,14 +174,14 @@ public class EServiceManager extends ApplicationLifecycleHandler {
void onChanged(ApplicationLifecycle lc) {
String state = getState(lc);
logger.debug("Moving app {} to {}", applicationContext.name(), state);
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
String previousToken = SecurityTokenProvider.instance.get();
if(previousToken==null){
if(previousToken==null)
previousToken = applicationContext.configuration().startTokens().iterator().next();
setContextFromToken(previousToken);
}
setContextFromToken(previousToken);
try {
Thread.currentThread().setContextClassLoader(EServiceManager.class.getClassLoader());
createOrUpdateServiceStateFacet(state);
@ -183,7 +190,7 @@ public class EServiceManager extends ApplicationLifecycleHandler {
} finally {
Thread.currentThread().setContextClassLoader(contextCL);
}
}
@Observes(value = addToContext)
@ -193,10 +200,10 @@ public class EServiceManager extends ApplicationLifecycleHandler {
try {
Thread.currentThread().setContextClassLoader(EServiceManager.class.getClassLoader());
setContextFromToken(token);
ResourceRegistryPublisher resourceRegistryPublisher = ResourceRegistryPublisherFactory.create();
addToContext(resourceRegistryPublisher);
} catch (Exception e) {
logger.error("Failed to add HostingNode to current context ({})", getCurrentContextName(), e);
} finally {
@ -212,110 +219,110 @@ public class EServiceManager extends ApplicationLifecycleHandler {
try {
Thread.currentThread().setContextClassLoader(EServiceManager.class.getClassLoader());
setContextFromToken(token);
ResourceRegistryPublisher resourceRegistryPublisher = ResourceRegistryPublisherFactory.create();
removeFromContext(resourceRegistryPublisher);
} catch (Exception e) {
logger.error("Failed to remove HostingNode from current context ({})", getCurrentContextName(), e);
} finally {
setContextFromToken(previousToken);
Thread.currentThread().setContextClassLoader(contextCL);
}
}
});
}
private String getState(ApplicationLifecycle lc){
return lc.state().remoteForm().toLowerCase();
}
private void schedulePeriodicUpdates() {
// register to cancel updates
applicationContext.events().subscribe(
new Object() {
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) {
// 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;
}
// 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());
}
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 state = getState(lc);
createOrUpdateServiceStateFacet(state);
} catch (Exception e) {
logger.error("Cannot complete periodic update of EService", e);
final Runnable updateTask = new Runnable() {
public void run() {
try {
String state = getState(lc);
createOrUpdateServiceStateFacet(state);
} 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 {} EService",
applicationContext.name(), 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 {} EService",
applicationContext.name(), e);
}
}
}
});
});
}
private Hosts<HostingNode, EService> createHostsRelation(EService eService,
ResourceRegistryPublisher resourceRegistryPublisher) throws ResourceRegistryException{
HostingNode hostingNode = applicationContext.container().properties().lookup(Constants.HOSTING_NODE_PROPERTY).value(HostingNode.class);
addToContext(resourceRegistryPublisher);
PropagationConstraint propagationConstraint = new PropagationConstraintImpl();
propagationConstraint.setRemoveConstraint(RemoveConstraint.cascade);
propagationConstraint.setAddConstraint(AddConstraint.propagate);
Hosts<HostingNode, EService> hosts = new HostsImpl<>(hostingNode, eService, propagationConstraint);
try {
hosts = resourceRegistryPublisher.createIsRelatedTo(hosts);
} catch (ResourceNotFoundException e) {
@ -325,14 +332,14 @@ public class EServiceManager extends ApplicationLifecycleHandler {
logger.error("Error while creating {}", hosts, e);
throw e;
}
hostingNode.attachResource(hosts);
shareHostingNode(hostingNode);
return hosts;
}
private EService getEService() throws ResourceRegistryException {
EService eService = null;
ResourceRegistryClient resourceRegistryClient = ResourceRegistryClientFactory.create();
@ -352,21 +359,21 @@ public class EServiceManager extends ApplicationLifecycleHandler {
}
return eService;
}
private void shareHostingNode(HostingNode hostingNode) {
logger.trace("sharing {} {}", HostingNode.NAME, Resource.NAME);
applicationContext.container().properties().add(
new Property(Constants.HOSTING_NODE_PROPERTY, hostingNode));
}
private String getCurrentContextName() {
String token = SecurityTokenProvider.instance.get();
return getContextName(token);
}
private String getContextName(String token) {
try {
return this.authorizationProxy.get(token).getContext();
@ -375,7 +382,7 @@ public class EServiceManager extends ApplicationLifecycleHandler {
return null;
}
}
private void addToContext(ResourceRegistryPublisher resourceRegistryPublisher) throws ResourceRegistryException {
HostingNode hostingNode = applicationContext.container().properties().lookup(Constants.HOSTING_NODE_PROPERTY).value(HostingNode.class);
resourceRegistryPublisher.addResourceToContext(hostingNode);
@ -383,25 +390,25 @@ public class EServiceManager extends ApplicationLifecycleHandler {
hostingNode, getCurrentContextName());
shareHostingNode(hostingNode);
}
private void removeFromContext(ResourceRegistryPublisher resourceRegistryPublisher) throws ResourceRegistryException {
HostingNode hostingNode = applicationContext.container().properties().lookup(Constants.HOSTING_NODE_PROPERTY).value(HostingNode.class);
resourceRegistryPublisher.removeResourceFromContext(hostingNode);
logger.info("{} successfully removed from current context ({})", hostingNode, getCurrentContextName());
shareHostingNode(hostingNode);
}
private void createOrUpdateServiceStateFacet(String state) throws ResourceRegistryException {
ResourceRegistryClient resourceRegistryClient= ResourceRegistryClientFactory
.create();
ResourceRegistryPublisher resourceRegistryPublisher = ResourceRegistryPublisherFactory
.create();
String selectedToken = applicationContext.configuration().startTokens().toArray(new String[0])[0];
setContextFromToken(selectedToken);
EService eService = getEService();
ServiceStateFacet serviceStateFacet = null;
@ -410,7 +417,7 @@ public class EServiceManager extends ApplicationLifecycleHandler {
serviceStateFacet = serviceStateFacets.get(0);
serviceStateFacet.setValue(state);
serviceStateFacet = resourceRegistryPublisher.updateFacet(serviceStateFacet);
for(int i=1; i<serviceStateFacets.size(); i++){
try {
logger.warn("You should not be here. There are more than one {}. Anyway deleting it : {}", ServiceStateFacet.class.getSimpleName(), serviceStateFacets.get(i));
@ -419,41 +426,40 @@ public class EServiceManager extends ApplicationLifecycleHandler {
logger.warn("Unable to delete {} which should not exists : {}", ServiceStateFacet.class.getSimpleName(), serviceStateFacets.get(i));
}
}
}else {
serviceStateFacet = new ServiceStateFacetImpl();
serviceStateFacet.setValue(state);
serviceStateFacet = resourceRegistryPublisher.createFacet(serviceStateFacet);
ConsistsOf<EService, ServiceStateFacet> consistsOf = new ConsistsOfImpl<EService, ServiceStateFacet>(
eService, serviceStateFacet, null);
consistsOf = resourceRegistryPublisher.createConsistsOf(consistsOf);
// Newly created ServiceStateFacet must be added to all context
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
String previousToken = SecurityTokenProvider.instance.get();
try {
Thread.currentThread().setContextClassLoader(
EServiceManager.class.getClassLoader());
Set<String> startTokens = applicationContext.configuration().startTokens();
for (String token : startTokens) {
setContextFromToken(token);
addToContext(resourceRegistryPublisher);
}
} catch (ResourceRegistryException e) {
throw e;
} finally {
setContextFromToken(previousToken);
Thread.currentThread().setContextClassLoader(contextCL);
}
}
UUID eServiceUUID = eService.getHeader().getUUID();
eService = resourceRegistryClient.getInstance(EService.class, eServiceUUID);
// Newly created ServiceStateFacet must be added to all context
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(
EServiceManager.class.getClassLoader());
Set<String> startTokens = applicationContext.configuration().startTokens();
for (String token : startTokens) {
setContextFromToken(token);
addToContext(resourceRegistryPublisher);
}
} catch (ResourceRegistryException e) {
throw e;
} finally {
setContextFromToken(null);
Thread.currentThread().setContextClassLoader(contextCL);
}
//UUID eServiceUUID = eService.getHeader().getUUID();
//eService = resourceRegistryClient.getInstance(EService.class, eServiceUUID);
share(eService);
}
@ -475,7 +481,7 @@ public class EServiceManager extends ApplicationLifecycleHandler {
}
return baseAddress;
}
private EService instantiateEService(UUID uuid) {
logger.info("Creating EService for {}", applicationContext.name());
@ -501,9 +507,9 @@ public class EServiceManager extends ApplicationLifecycleHandler {
.getServletRegistrations().values()) {
if (!servletExcludes.contains(servlet.getName())) {
for (String mapping : servlet.getMappings()) {
String address = baseAddress+(mapping.endsWith("*")?mapping.substring(0,mapping.length()-2):mapping);
AccessPointFacet accessPointFacet = new AccessPointFacetImpl();
accessPointFacet.setEntryName(servlet.getName());
accessPointFacet.setEndpoint(URI.create(address));

View File

@ -70,6 +70,7 @@ import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegis
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAlreadyPresentException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.entity.resource.ResourceNotFoundException;
import org.gcube.informationsystem.resourceregistry.api.exceptions.relation.RelationAvailableInAnotherContextException;
import org.gcube.informationsystem.resourceregistry.client.ResourceRegistryClient;
import org.gcube.informationsystem.resourceregistry.client.ResourceRegistryClientFactory;
import org.gcube.informationsystem.resourceregistry.publisher.ResourceRegistryPublisher;
@ -142,11 +143,17 @@ public class HostingNodeManager extends ContainerHandler {
@Override
public void onStart(Start e) {
context = e.context();
HostingNode hostingNode = instantiateHostingNode();
hostingNode = publishHostingNode(hostingNode);
registerObservers();
schedulePeriodicUpdates();
try{
logger.info("onStart started");
context = e.context();
HostingNode hostingNode = instantiateHostingNode();
hostingNode = publishHostingNode(hostingNode);
registerObservers();
schedulePeriodicUpdates();
logger.info("onStart finished");
}catch(Throwable re){
logger.error("onStart failed",re);
}
}
private void share(HostingNode hostingNode) {
@ -185,67 +192,67 @@ public class HostingNodeManager extends ContainerHandler {
// register to cancel updates
context.events().subscribe(
new Object() {
new Object() {
final ScheduledExecutorService service = Executors
.newScheduledThreadPool(1);
final ScheduledExecutorService service = Executors
.newScheduledThreadPool(1);
// we register it in response to lifecycle events so that we can
// stop and resume along with application
@Observes(value = { activation, part_activation }, kind = resilient)
synchronized void restartPeriodicUpdates(ContainerLifecycle lc) {
// we register it in response to lifecycle events so that we can
// stop and resume along with application
@Observes(value = { activation, part_activation }, kind = resilient)
synchronized void restartPeriodicUpdates(ContainerLifecycle lc) {
// already running
if (periodicUpdates != null) {
return;
}
// already running
if (periodicUpdates != null) {
return;
}
if (lc.state() == active) {
logger.info("scheduling periodic updates of {}",
HostingNode.NAME);
} else {
logger.info("resuming periodic updates of {}",
HostingNode.NAME);
}
if (lc.state() == active) {
logger.info("scheduling periodic updates of {}",
HostingNode.NAME);
} else {
logger.info("resuming periodic updates of {}",
HostingNode.NAME);
}
final Runnable updateTask = new Runnable() {
public void run() {
HostingNode hostingNode = context.properties().lookup(Constants.HOSTING_NODE_PROPERTY).value(HostingNode.class);
try {
updateHostingNode(hostingNode);
} catch (Exception e) {
logger.error(
"cannot complete periodic update of {}",
HostingNode.NAME, e);
final Runnable updateTask = new Runnable() {
public void run() {
HostingNode hostingNode = context.properties().lookup(Constants.HOSTING_NODE_PROPERTY).value(HostingNode.class);
try {
updateHostingNode(hostingNode);
} catch (Exception e) {
logger.error(
"cannot complete periodic update of {}",
HostingNode.NAME, e);
}
}
};
periodicUpdates = service
.scheduleAtFixedRate(updateTask, 3, context
.configuration().publicationFrequency(),
SECONDS);
}
@Observes(value = { stop, failure, shutdown }, kind = resilient)
synchronized void cancelPeriodicUpdates(ContainerLifecycle ignore) {
if (periodicUpdates != null) {
logger.trace("stopping periodic updates of {}",
HostingNode.NAME);
try {
periodicUpdates.cancel(true);
service.shutdownNow();
periodicUpdates = null;
} catch (Exception e) {
logger.warn("could not stop periodic updates of {}",
HostingNode.NAME, e);
}
}
}
};
periodicUpdates = service
.scheduleAtFixedRate(updateTask, 3, context
.configuration().publicationFrequency(),
SECONDS);
}
@Observes(value = { stop, failure, shutdown }, kind = resilient)
synchronized void cancelPeriodicUpdates(ContainerLifecycle ignore) {
if (periodicUpdates != null) {
logger.trace("stopping periodic updates of {}",
HostingNode.NAME);
try {
periodicUpdates.cancel(true);
service.shutdownNow();
periodicUpdates = null;
} catch (Exception e) {
logger.warn("could not stop periodic updates of {}",
HostingNode.NAME, e);
}
}
}
});
});
}
@ -265,14 +272,14 @@ public class HostingNodeManager extends ContainerHandler {
try {
ResourceRegistryPublisher resourceRegistryPublisher = ResourceRegistryPublisherFactory
.create();
if (create) {
try {
hostingNode = resourceRegistryPublisher
.createResource(hostingNode);
share(hostingNode);
// TODO Add a Reference to Site
/*
* node.profile().newSite().country(cfg.site().country
@ -288,7 +295,7 @@ public class HostingNodeManager extends ContainerHandler {
.create();
hostingNode = registryClient.getInstance(
HostingNode.class, hostingNode.getHeader()
.getUUID());
.getUUID());
updateHostingNode(hostingNode);
} catch (ResourceAvailableInAnotherContextException e) {
addToContext(hostingNode, token);
@ -299,7 +306,7 @@ public class HostingNodeManager extends ContainerHandler {
} else {
addToContext(hostingNode, token);
}
} catch (Exception e) {
logger.error("Unable to add {} to current context ({})",
hostingNode, getCurrentContextName(token), e);
@ -307,12 +314,13 @@ public class HostingNodeManager extends ContainerHandler {
}
} catch (Exception e) {
} catch (Throwable e) {
rethrowUnchecked(e);
} finally {
setContextFromToken(previousToken);
Thread.currentThread().setContextClassLoader(contextCL);
}
logger.info("hosting node published");
return hostingNode;
}
@ -428,7 +436,7 @@ public class HostingNodeManager extends ContainerHandler {
ResourceRegistryPublisher resourceRegistryPublisher = ResourceRegistryPublisherFactory
.create();
ContainerStateFacet containerStateFacet = null;
MemoryFacet ramFacet = null;
MemoryFacet jvmMemoryFacet = null;
@ -475,7 +483,7 @@ public class HostingNodeManager extends ContainerHandler {
// Resource Update has effect only on specified facet.
// Removing the one that have not to be changed
consistsOfList.removeAll(consistsOfToRemove);
try {
hostingNode = resourceRegistryPublisher.updateResource(hostingNode);
} catch (ResourceNotFoundException e) {
@ -483,6 +491,11 @@ public class HostingNodeManager extends ContainerHandler {
// ReAdding the removed relations to recreate all
consistsOfList.addAll(consistsOfToRemove);
hostingNode = resourceRegistryPublisher.createResource(hostingNode);
} catch (ResourceAvailableInAnotherContextException | RelationAvailableInAnotherContextException e) {
addToContext(hostingNode, SecurityTokenProvider.instance.get());
hostingNode = resourceRegistryPublisher.updateResource(hostingNode);
} catch (ResourceRegistryException e) {
logger.error("error trying to publish hosting node",e);
}
return hostingNode;
@ -538,21 +551,21 @@ public class HostingNodeManager extends ContainerHandler {
HasVolatileMemory<HostingNode, MemoryFacet> hasVolatileRAMMemory = new HasVolatileMemoryImpl<HostingNode, MemoryFacet>(
hostingNode, ramFacet, null);
hasVolatileRAMMemory
.setAdditionalProperty(MEMORY_TYPE, MEMORY_TYPE_RAM);
.setAdditionalProperty(MEMORY_TYPE, MEMORY_TYPE_RAM);
hostingNode.addFacet(hasVolatileRAMMemory);
MemoryFacet jvmMemoryFacet = getJVMMemoryInfo(null);
HasVolatileMemory<HostingNode, MemoryFacet> hasVolatileJVMMemory = new HasVolatileMemoryImpl<HostingNode, MemoryFacet>(
hostingNode, jvmMemoryFacet, null);
hasVolatileJVMMemory
.setAdditionalProperty(MEMORY_TYPE, MEMORY_TYPE_JVM);
.setAdditionalProperty(MEMORY_TYPE, MEMORY_TYPE_JVM);
hostingNode.addFacet(hasVolatileJVMMemory);
MemoryFacet diskFacet = getDiskSpace(null);
HasPersistentMemory<HostingNode, MemoryFacet> hasPersistentMemory = new HasPersistentMemoryImpl<HostingNode, MemoryFacet>(
hostingNode, diskFacet, null);
hostingNode.addFacet(hasPersistentMemory);
logger.info("hostingNode instanciated");
return hostingNode;
}
@ -576,11 +589,11 @@ public class HostingNodeManager extends ContainerHandler {
FileStore fileStore = Files.getFileStore(Paths.get(context
.configuration().persistence().location()));
free = fileStore.getUsableSpace() / 1048576; // 1048576 = 1024*1024
// user to convert
// bytes in MByte
// user to convert
// bytes in MByte
total = fileStore.getTotalSpace() / 1048576; // 1048576 = 1024*1024
// user to convert
// bytes in MByte
// user to convert
// bytes in MByte
} catch (IOException ioe) {
logger.warn("Unable to detect disk space information", ioe);
memoryFacet.setAdditionalProperty(MESSAGE,
@ -604,9 +617,9 @@ public class HostingNodeManager extends ContainerHandler {
.getOperatingSystemMXBean();
com.sun.management.OperatingSystemMXBean sunmxbean = (com.sun.management.OperatingSystemMXBean) mxbean;
long freeMemory = sunmxbean.getFreePhysicalMemorySize() / 1048576; // in
// MB
// MB
long totalMemory = sunmxbean.getTotalPhysicalMemorySize() / 1048576; // in
// MB
// MB
memoryFacet.setUnit(MemoryUnit.MB);
memoryFacet.setSize(totalMemory);
@ -723,7 +736,7 @@ public class HostingNodeManager extends ContainerHandler {
while ((line = input.readLine()) != null) {
if ((line.startsWith(CPU_PROCESSOR))) { // add the current
// processor to the map
// processor to the map
cpuFacet = new CPUFacetImpl();
cpuFacets.add(cpuFacet);
}