Implementing connector

This commit is contained in:
Luca Frosini 2022-06-29 09:11:29 +02:00
parent f12f541b11
commit f9f3217cb8
7 changed files with 246 additions and 674 deletions

44
pom.xml
View File

@ -38,14 +38,48 @@
</dependencyManagement>
<dependencies>
<!-- <dependency> -->
<!-- <groupId>org.gcube.information-system</groupId> -->
<!-- <artifactId>information-system-model</artifactId> -->
<!-- </dependency> -->
<!-- <dependency> -->
<!-- <groupId>org.gcube.resource-management</groupId> -->
<!-- <artifactId>gcube-model</artifactId> -->
<!-- </dependency> -->
<!-- <dependency> -->
<!-- <groupId>org.gcube.information-system</groupId> -->
<!-- <artifactId>resource-registry-publisher</artifactId> -->
<!-- </dependency> -->
<!-- <dependency> -->
<!-- <groupId>org.gcube.information-system</groupId> -->
<!-- <artifactId>resource-registry-client</artifactId> -->
<!-- </dependency> -->
<!-- Facets Based Resource Model related dependencies -->
<dependency>
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry-publisher</artifactId>
<artifactId>information-system-model</artifactId>
<version>[5.0.0-SNAPSHOT,6.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>org.gcube.resource-management</groupId>
<artifactId>gcube-model</artifactId>
<version>[4.0.0-SNAPSHOT,5.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry-client</artifactId>
<version>[4.1.0,5.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>org.gcube.information-system</groupId>
<artifactId>resource-registry-publisher</artifactId>
<version>[4.1.0,5.0.0-SNAPSHOT)</version>
</dependency>
<!-- END Facets Based Resource Model related dependencies -->
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-smartgears</artifactId>
@ -54,14 +88,6 @@
<groupId>org.gcube.core</groupId>
<artifactId>common-events</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.information-system</groupId>
<artifactId>information-system-model</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.resource-management</groupId>
<artifactId>gcube-model</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>

View File

@ -1,16 +1,9 @@
package org.gcube.smartgears.handler.resourceregistry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.UUID;
import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.smartgears.provider.ProviderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -21,67 +14,10 @@ public class ContextUtility {
private static Logger logger = LoggerFactory.getLogger(ContextUtility.class);
private static AuthorizationProxy authorizationProxy;
static {
authorizationProxy = ProviderFactory.provider().authorizationProxy();
}
public static void resetContex() {
SecurityTokenProvider.instance.reset();
ScopeProvider.instance.reset();
}
public static void setContextFromToken(String token) {
if (token == null || token.compareTo("") == 0) {
resetContex();
} else {
SecurityTokenProvider.instance.set(token);
String scope = getContextName(token);
ScopeProvider.instance.set(scope);
}
}
public static String getCurrentContextName() {
String token = SecurityTokenProvider.instance.get();
return getContextName(token);
}
public static UUID getContextUUID(String token) throws ResourceRegistryException {
public static UUID getContextUUID(String contextFullName) throws ResourceRegistryException {
ContextCache contextCache = ContextCache.getInstance();
String contextFullName = getContextName(token);
UUID contextUUID = contextCache.getUUIDByFullName(contextFullName);
return contextUUID;
}
public static String getContextName(String token) {
try {
return authorizationProxy.get(token).getContext();
} catch (Exception e) {
logger.error("Error retrieving context form token {}, it should never happen", token, e);
return null;
}
}
public static SortedSet<String> getContextFullNamesFromTokens(Set<String> tokens){
SortedSet<String> contextFullNames = new TreeSet<>();
for(String token : tokens) {
String contextFullName = getContextName(token);
contextFullNames.add(contextFullName);
}
return contextFullNames;
}
public static SortedSet<UUID> getContextUUIDFromTokens(Set<String> tokens) throws ResourceRegistryException {
SortedSet<UUID> contextsUUID = new TreeSet<>();
ContextCache contextCache = ContextCache.getInstance();
for(String token : tokens) {
String contextFullName = getContextName(token);
UUID contextUUID = contextCache.getUUIDByFullName(contextFullName);
contextsUUID.add(contextUUID);
}
return contextsUUID;
}
}

View File

@ -1,275 +0,0 @@
package org.gcube.smartgears.handler.resourceregistry;
import static org.gcube.common.events.Observes.Kind.resilient;
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.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
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.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.resourcemanagement.model.reference.entities.facets.StateFacet;
import org.gcube.resourcemanagement.model.reference.entities.resources.EService;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.handler.resourceregistry.resourcemanager.EServiceManager;
import org.gcube.smartgears.handlers.application.ApplicationLifecycleEvent.Start;
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 StateFacet} when the application becomes active,
* and at any lifecycle change thereafter;</li>
* </ul>
* </p>
*
* @author Luca Frosini (ISTI-CNR)
*/
public class EServiceHandler {
private static final Logger logger = LoggerFactory.getLogger(EServiceHandler.class);
private ApplicationContext applicationContext;
private ScheduledFuture<?> periodicUpdates;
protected EServiceManager eServiceManager;
public EServiceHandler() {
super();
}
public void onStart(Start event) {
try {
logger.info("{} onStart started", this.getClass().getSimpleName());
this.applicationContext = event.context();
init();
registerObservers();
schedulePeriodicUpdates();
logger.info("{} onStart terminated", this.getClass().getSimpleName());
} catch (Throwable re) {
logger.error("onStart failed", re);
}
}
protected void removeResourceFromOldContexts(Set<UUID> startContexts, Set<UUID> resourceContexts) {
Set<UUID> contextsToRemove = new HashSet<>(resourceContexts);
contextsToRemove.removeAll(startContexts);
for(UUID contextToRemove : contextsToRemove) {
try {
eServiceManager.removeFromContext(contextToRemove);
}catch (Exception e) {
try {
String contextFullName = ContextCache.getInstance().getContextFullNameByUUID(contextToRemove);
logger.warn("Unable to remove {} from Context {} UUID {}", EService.NAME, contextFullName, contextsToRemove, e);
}catch (Exception ex) {
logger.warn("Unable to remove {} from Context with UUID {}.", EService.NAME, contextsToRemove, e);
}
}
}
}
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();
String firstToken = startTokens.iterator().next();
ContextUtility.setContextFromToken(firstToken);
eServiceManager = new EServiceManager(applicationContext);
Set<UUID> startContextsUUID = new HashSet<>();
for (String token : startTokens) {
UUID contextUUID = ContextUtility.getContextUUID(token);
startContextsUUID.add(contextUUID);
if (create) {
eServiceManager.createEService();
create = false;
} else {
eServiceManager.addToContext(contextUUID);
}
}
Set<UUID> resourceContextsUUID = eServiceManager.getContextsUUID().keySet();
removeResourceFromOldContexts(startContextsUUID, resourceContextsUUID);
} 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 })
void onChanged(ApplicationLifecycle lc) {
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
String previousToken = SecurityTokenProvider.instance.get();
try {
Thread.currentThread().setContextClassLoader(EServiceHandler.class.getClassLoader());
if(previousToken==null) {
String token = applicationContext.configuration().startTokens().iterator().next();
ContextUtility.setContextFromToken(token);
}
eServiceManager.updateFacets();
} catch (Exception e) {
logger.error("Failed to update {} State", EService.NAME, e);
} finally {
ContextUtility.setContextFromToken(previousToken);
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);
UUID contextUUID = ContextUtility.getContextUUID(token);
eServiceManager.addToContext(contextUUID);
} catch (Exception e) {
logger.error("Failed to add {} to current context ({})", EService.NAME,
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());
eServiceManager.removeFromCurrentContext();
} catch (Exception e) {
logger.error("Failed to remove {} from current context ({})",
EService.NAME, 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;
}
String applicationName = applicationContext.name();
if (lc.state() == ApplicationState.active) {
logger.info("Scheduling periodic updates of {} for application {}",
EService.NAME, applicationName);
} else {
logger.info("Resuming periodic updates of {} for application {}",
EService.NAME, applicationName);
}
final Runnable updateTask = new Runnable() {
public void run() {
String previousToken = SecurityTokenProvider.instance.get();
if (previousToken == null) {
String token = applicationContext.configuration().startTokens().iterator().next();
ContextUtility.setContextFromToken(token);
}
try {
eServiceManager.updateFacets();
} catch (Exception e) {
logger.error("Cannot complete periodic update of {} for application {}", EService.NAME, applicationName, e);
} finally {
ContextUtility.setContextFromToken(previousToken);
}
}
};
periodicUpdates = Utils.scheduledServicePool.scheduleAtFixedRate(updateTask,
Constants.application_republish_frequency_in_minutes,
Constants.application_republish_frequency_in_minutes, TimeUnit.MINUTES);
/*
* The following line is used for testing purposes during development.
* If you uncomment this, you need to comment the line above
*/
// periodicUpdates = Utils.scheduledServicePool.scheduleAtFixedRate(updateTask, 120, 120, TimeUnit.SECONDS);
}
@Observes(value = { stop, failure }, kind = resilient)
synchronized void cancelPeriodicUpdates(ContainerLifecycle ignore) {
if (periodicUpdates != null) {
String applicationName = applicationContext.name();
logger.trace("Stopping periodic updates of {} for application {} ",
EService.NAME, applicationName);
try {
periodicUpdates.cancel(true);
periodicUpdates = null;
} catch (Exception e) {
logger.warn("Could not stop periodic updates of {} for application {}",
EService.NAME, applicationName, e);
}
}
}
});
}
@Override
public String toString() {
return Constants.RESOURCE_MANAGEMENT;
}
}

View File

@ -1,263 +0,0 @@
package org.gcube.smartgears.handler.resourceregistry;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.gcube.common.events.Observes.Kind.resilient;
import static org.gcube.smartgears.handlers.ProfileEvents.addToContext;
import static org.gcube.smartgears.handlers.ProfileEvents.removeFromContext;
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.activation;
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.failure;
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.part_activation;
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.shutdown;
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.stop;
import static org.gcube.smartgears.lifecycle.container.ContainerState.active;
import static org.gcube.smartgears.utils.Utils.rethrowUnchecked;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
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.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.resourcemanagement.model.reference.entities.facets.StateFacet;
import org.gcube.resourcemanagement.model.reference.entities.resources.HostingNode;
import org.gcube.smartgears.context.Property;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.handler.resourceregistry.resourcemanager.HostingNodeManager;
import org.gcube.smartgears.handlers.container.ContainerHandler;
import org.gcube.smartgears.handlers.container.ContainerLifecycleEvent.Start;
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
import org.gcube.smartgears.lifecycle.container.ContainerState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Manages the {@link HostingNode} {@link Resource} of the application.
* <p>
* The manager:
* <ul>
* <li>creates the {@link HostingNode} {@link Resource} and the facets it
* {@link ConsistsOf} when the container starts for the first time;</li>
* <li>update the {@link StateFacet} when the application becomes
* active, and at any lifecycle change thereafter;</li>
* <li>schedule a periodic update of {@link Facet}s containing variables
* information.</li>
* </ul>
* </p>
*
* @author Luca Frosini (ISTI-CNR)
*/
public class HostingNodeHandler {
private static Logger logger = LoggerFactory.getLogger(HostingNodeHandler.class);
private ContainerContext containerContext;
private ScheduledFuture<?> periodicUpdates;
protected HostingNodeManager hostingNodeManager;
public HostingNodeHandler() {
super();
}
public void onStart(Start event) {
try {
logger.info("{} onStart started", this.getClass().getSimpleName());
this.containerContext = event.context();
init();
registerObservers();
schedulePeriodicUpdates();
logger.info("{} onStart terminated", this.getClass().getSimpleName());
} catch (Throwable re) {
logger.error("onStart failed", re);
}
}
protected void removeResourceFromOldContexts(Set<UUID> startContexts, Set<UUID> resourceContexts) throws ResourceRegistryException {
Set<UUID> contextsToRemove = new HashSet<>(resourceContexts);
contextsToRemove.removeAll(startContexts);
for(UUID contextToRemove : contextsToRemove) {
hostingNodeManager.removeFromContext(contextToRemove);
}
}
private void init() {
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
String previousToken = SecurityTokenProvider.instance.get();
try {
Thread.currentThread().setContextClassLoader(HostingNodeHandler.class.getClassLoader());
boolean create = true;
List<String> startTokens = containerContext.configuration().startTokens();
String firstToken = startTokens.iterator().next();
ContextUtility.setContextFromToken(firstToken);
hostingNodeManager = new HostingNodeManager(containerContext);
Set<UUID> startContextsUUID = new HashSet<>();
for (String token : startTokens) {
UUID contextUUID = ContextUtility.getContextUUID(token);
startContextsUUID.add(contextUUID);
if (create) {
hostingNodeManager.createHostingNode();
containerContext.properties().add(new Property(Constants.HOSTING_NODE_MANAGER_PROPERTY, hostingNodeManager));
create = false;
} else {
hostingNodeManager.addToContext(contextUUID);
}
}
Set<UUID> resourceContextsUUID = hostingNodeManager.getContextsUUID().keySet();
removeResourceFromOldContexts(startContextsUUID, resourceContextsUUID);
} catch (Throwable e) {
rethrowUnchecked(e);
} finally {
ContextUtility.setContextFromToken(previousToken);
Thread.currentThread().setContextClassLoader(contextCL);
}
logger.info("{} init() terminated", this.getClass().getSimpleName());
}
private void registerObservers() {
containerContext.events().subscribe(new Object() {
@Observes({ activation, part_activation, shutdown, stop, failure })
void onChanged(ContainerLifecycle cl) {
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
String previousToken = SecurityTokenProvider.instance.get();
try {
Thread.currentThread().setContextClassLoader(HostingNodeHandler.class.getClassLoader());
if (previousToken == null) {
String token = containerContext.configuration().startTokens().iterator().next();
ContextUtility.setContextFromToken(token);
}
hostingNodeManager.updateFacets();
} catch (Exception e) {
logger.error("Failed to update {} State", HostingNode.NAME, e);
} finally {
ContextUtility.setContextFromToken(previousToken);
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(HostingNodeHandler.class.getClassLoader());
ContextUtility.setContextFromToken(token);
UUID contextUUID = ContextUtility.getContextUUID(token);
hostingNodeManager.addToContext(contextUUID);
} catch (Exception e) {
logger.error("Failed to update Service State", 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(HostingNodeHandler.class.getClassLoader());
ContextUtility.setContextFromToken(token);
UUID contextUUID = ContextUtility.getContextUUID(token);
hostingNodeManager.removeFromContext(contextUUID);
} catch (Exception e) {
logger.error("Failed to update Service State", e);
} finally {
ContextUtility.setContextFromToken(previousToken);
Thread.currentThread().setContextClassLoader(contextCL);
}
}
});
}
private void schedulePeriodicUpdates() {
// register to cancel updates
containerContext.events().subscribe(
new Object() {
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 cl) {
// already running
if (periodicUpdates != null) {
return;
}
if (cl.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() {
String previousToken = SecurityTokenProvider.instance.get();
if (previousToken == null) {
String token = containerContext.configuration().startTokens().iterator().next();
ContextUtility.setContextFromToken(token);
}
try {
hostingNodeManager.updateFacets();
} catch (Exception e) {
logger.error("Cannot complete periodic update of {}", HostingNode.NAME, e);
}finally {
ContextUtility.setContextFromToken(previousToken);
}
}
};
periodicUpdates = service.scheduleAtFixedRate(updateTask, 3,
containerContext.configuration().publicationFrequency(), SECONDS);
}
@Observes(value = { stop, failure, shutdown }, kind = resilient)
synchronized void cancelPeriodicUpdates(ContainerLifecycle cl) {
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);
}
}
}
});
}
@Override
public String toString() {
return Constants.RESOURCE_MANAGEMENT;
}
}

View File

@ -12,7 +12,8 @@ import java.util.UUID;
import javax.servlet.ServletRegistration;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.informationsystem.model.impl.properties.HeaderImpl;
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
import org.gcube.informationsystem.model.reference.entities.Facet;
@ -58,6 +59,7 @@ import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.handler.resourceregistry.Constants;
import org.gcube.smartgears.handler.resourceregistry.ContextUtility;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -82,98 +84,101 @@ public class EServiceManager {
}
public void addEServiceToCurrentContext() throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
String currentToken = SecurityTokenProvider.instance.get();
UUID contextUUID = ContextUtility.getContextUUID(currentToken);
Secret secret = SecretManagerProvider.instance.get();
String context = secret.getContext();
UUID contextUUID = ContextUtility.getContextUUID(context);
/* Trying to get a context which is not the current to properly invoke the addToContext without forcing the operation using addResourceToCurrentContext */
AuthorizationProvider authorizationProvider = applicationContext.container().configuration().authorizationProvider();
Set<String> contexts = authorizationProvider.getContexts();
boolean anotherContextSet = false;
Set<String> startTokens = applicationContext.configuration().startTokens();
for (String token : startTokens) {
UUID anotherContextUUID = ContextUtility.getContextUUID(token);
if(anotherContextUUID.compareTo(contextUUID)!=0) {
ContextUtility.setContextFromToken(token);
for (String c : contexts) {
if(c.compareTo(context)!=0) {
Secret s = authorizationProvider.getSecretForContext(c);
SecretManagerProvider.instance.set(s);
anotherContextSet = true;
break;
}
}
UUID uuid = UUID.fromString(applicationContext.id());
UUID uuid = UUID.fromString(applicationContext.id());
try {
if(anotherContextSet) {
resourceRegistryPublisher.addResourceToContext(EService.NAME, uuid, contextUUID, false);
}else {
resourceRegistryPublisher.addResourceToCurrentContext(HostingNode.NAME, uuid, false);
resourceRegistryPublisher.addResourceToCurrentContext(EService.NAME, uuid, false);
}
logger.info("{} with UUID {} successfully added to context ({})", EService.NAME, uuid, ContextUtility.getCurrentContextName());
logger.info("{} with UUID {} successfully added to context ({})", EService.NAME, uuid, context);
} catch (Exception e) {
logger.error("Unable to add {} with UUID {} to context ({})", EService.NAME, uuid, ContextUtility.getCurrentContextName(), e);
}finally {
ContextUtility.setContextFromToken(currentToken);
logger.error("Unable to add {} with UUID {} to context ({})", EService.NAME, uuid, context, e);
}
}
public void addHostingNodeToCurrentContext() throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
String currentToken = SecurityTokenProvider.instance.get();
UUID contextUUID = ContextUtility.getContextUUID(currentToken);
Secret secret = SecretManagerProvider.instance.get();
String context = secret.getContext();
UUID contextUUID = ContextUtility.getContextUUID(context);
/* Trying to get a context which is not the current to properly invoke the addToContext without forcing the operation using addResourceToCurrentContext */
AuthorizationProvider authorizationProvider = applicationContext.container().configuration().authorizationProvider();
Set<String> contexts = authorizationProvider.getContexts();
boolean anotherContextSet = false;
Set<String> startTokens = applicationContext.configuration().startTokens();
for (String token : startTokens) {
UUID anotherContextUUID = ContextUtility.getContextUUID(token);
if(anotherContextUUID.compareTo(contextUUID)!=0) {
ContextUtility.setContextFromToken(token);
for (String c : contexts) {
if(c.compareTo(context)!=0) {
Secret s = authorizationProvider.getSecretForContext(c);
SecretManagerProvider.instance.set(s);
anotherContextSet = true;
break;
}
}
UUID uuid = UUID.fromString(applicationContext.container().id());
UUID uuid = UUID.fromString(applicationContext.container().id());
try {
if(anotherContextSet) {
resourceRegistryPublisher.addResourceToContext(HostingNode.NAME, uuid, contextUUID, false);
resourceRegistryPublisher.addToContext(HostingNode.NAME, uuid, contextUUID, false);
}else {
resourceRegistryPublisher.addResourceToCurrentContext(HostingNode.NAME, uuid, false);
}
logger.info("{} with UUID {} successfully added to context ({})", HostingNode.NAME, uuid, ContextUtility.getCurrentContextName());
logger.info("{} with UUID {} successfully added to context ({})", HostingNode.NAME, uuid, context);
} catch (Exception e) {
logger.error("Unable to add {} with UUID {} to context ({})", HostingNode.NAME, uuid, ContextUtility.getCurrentContextName(), e);
}finally {
ContextUtility.setContextFromToken(currentToken);
logger.error("Unable to add {} with UUID {} to context ({})", HostingNode.NAME, uuid, context, e);
}
}
public void addToContext(UUID contextUUID) throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
String context = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
UUID uuid = UUID.fromString(applicationContext.container().id());
try {
resourceRegistryPublisher.addToContext(HostingNode.NAME, uuid, contextUUID, false);
logger.info("{} with UUID {} successfully added to context ({})", HostingNode.NAME, uuid, ContextUtility.getCurrentContextName());
logger.info("{} with UUID {} successfully added to context ({})", HostingNode.NAME, uuid, context);
} catch (Exception e) {
logger.error("Unable to add {} with UUID {} to context ({})", HostingNode.NAME, uuid, ContextUtility.getCurrentContextName(), e);
logger.error("Unable to add {} with UUID {} to context ({})", HostingNode.NAME, uuid, context, e);
}
}
public void removeFromCurrentContext()
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
Secret secret = SecretManagerProvider.instance.get();
String context = secret.getContext();
UUID uuid = UUID.fromString(applicationContext.container().id());
try {
resourceRegistryPublisher.removeResourceFromCurrentContext(HostingNode.NAME, uuid, false);
logger.info("{} with UUID {} successfully removed from context ({})", HostingNode.NAME, uuid,
ContextUtility.getCurrentContextName());
logger.info("{} with UUID {} successfully removed from context ({})", HostingNode.NAME, uuid, context);
} catch (Exception e) {
logger.error("Unable to remove {} with UUID {} from context ({})", HostingNode.NAME, uuid, ContextUtility.getCurrentContextName(), e);
logger.error("Unable to remove {} with UUID {} from context ({})", HostingNode.NAME, uuid, context, e);
}
}
public void removeFromContext(UUID contextUUID)
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
String contextFullName = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
String context = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
UUID uuid = UUID.fromString(applicationContext.container().id());
try {
resourceRegistryPublisher.removeResourceFromContext(HostingNode.NAME, uuid, contextUUID, false);
logger.info("{} with UUID {} successfully removed from context ({})", HostingNode.NAME, uuid, contextFullName);
logger.info("{} with UUID {} successfully removed from context ({})", HostingNode.NAME, uuid, context);
} catch (Exception e) {
logger.error("Unable to remove {} from context ({})", HostingNode.NAME, uuid, contextFullName, e);
logger.error("Unable to remove {} from context ({})", HostingNode.NAME, uuid, context, e);
}
}
@ -181,11 +186,11 @@ public class EServiceManager {
ApplicationConfiguration configuration = applicationContext.configuration();
ContainerConfiguration container = applicationContext.container().configuration();
String baseAddress;
if (configuration.proxied()) {
String protocol = configuration.proxyAddress().protocol();
String port = configuration.proxyAddress().port() != null ? ":" + configuration.proxyAddress().port() : "";
if (configuration.proxable()) {
String protocol = configuration.proxyAddress().getProtocol();
String port = configuration.proxyAddress().getPort() != null ? ":" + configuration.proxyAddress().getPort() : "";
baseAddress = String.format("%s://%s%s%s", protocol, configuration.proxyAddress().hostname(), port,
baseAddress = String.format("%s://%s%s%s", protocol, configuration.proxyAddress().getHostname(), port,
applicationContext.application().getContextPath());
} else {
String protocol = container.protocol();

View File

@ -33,7 +33,8 @@ import javax.management.ObjectName;
import javax.management.ReflectionException;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.informationsystem.model.impl.properties.HeaderImpl;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
@ -82,6 +83,7 @@ import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.handler.resourceregistry.ContextUtility;
import org.gcube.smartgears.lifecycle.container.ContainerState;
import org.gcube.smartgears.provider.ProviderFactory;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -113,16 +115,18 @@ public class HostingNodeManager {
}
public void addToCurrentContext() throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
String currentToken = SecurityTokenProvider.instance.get();
UUID contextUUID = ContextUtility.getContextUUID(currentToken);
Secret secret = SecretManagerProvider.instance.get();
String context = secret.getContext();
UUID contextUUID = ContextUtility.getContextUUID(context);
/* Trying to get a context which is not the current to properly invoke the addToContext without forcing the operation using addResourceToCurrentContext */
AuthorizationProvider authorizationProvider = containerContext.configuration().authorizationProvider();
Set<String> contexts = authorizationProvider.getContexts();
boolean anotherContextSet = false;
List<String> startTokens = containerContext.configuration().startTokens();
for (String token : startTokens) {
UUID anotherContextUUID = ContextUtility.getContextUUID(token);
if(anotherContextUUID.compareTo(contextUUID)!=0) {
ContextUtility.setContextFromToken(token);
for (String c : contexts) {
if(c.compareTo(context)!=0) {
Secret s = authorizationProvider.getSecretForContext(c);
SecretManagerProvider.instance.set(s);
anotherContextSet = true;
break;
}
@ -135,43 +139,45 @@ public class HostingNodeManager {
}else {
resourceRegistryPublisher.addResourceToCurrentContext(HostingNode.NAME, uuid, false);
}
logger.info("{} with UUID {} successfully added to context ({})", HostingNode.NAME, uuid, ContextUtility.getCurrentContextName());
logger.info("{} with UUID {} successfully added to context ({})", HostingNode.NAME, uuid, context);
} catch (Exception e) {
logger.error("Unable to add {} with UUID {} to context ({})", HostingNode.NAME, uuid, ContextUtility.getCurrentContextName(), e);
logger.error("Unable to add {} with UUID {} to context ({})", HostingNode.NAME, uuid, context, e);
}
}
public void addToContext(UUID contextUUID) throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
String context = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
UUID uuid = UUID.fromString(containerContext.id());
try {
resourceRegistryPublisher.addToContext(HostingNode.NAME, uuid, contextUUID, false);
logger.info("{} with UUID {} successfully added to context ({})", HostingNode.NAME, uuid, ContextUtility.getCurrentContextName());
logger.info("{} with UUID {} successfully added to context ({})", HostingNode.NAME, uuid, context);
} catch (Exception e) {
logger.error("Unable to add {} with UUID {} to context ({})", HostingNode.NAME, uuid, ContextUtility.getCurrentContextName(), e);
logger.error("Unable to add {} with UUID {} to context ({})", HostingNode.NAME, uuid, context, e);
}
}
public void removeFromCurrentContext()
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
Secret secret = SecretManagerProvider.instance.get();
String context = secret.getContext();
UUID uuid = UUID.fromString(containerContext.id());
try {
resourceRegistryPublisher.removeResourceFromCurrentContext(HostingNode.NAME, uuid, false);
logger.info("{} with UUID {} successfully removed from context ({})", HostingNode.NAME, uuid,
ContextUtility.getCurrentContextName());
logger.info("{} with UUID {} successfully removed from context ({})", HostingNode.NAME, uuid, context);
} catch (Exception e) {
logger.error("Unable to remove {} with UUID {} from context ({})", HostingNode.NAME, uuid, ContextUtility.getCurrentContextName(), e);
logger.error("Unable to remove {} with UUID {} from context ({})", HostingNode.NAME, uuid, context, e);
}
}
public void removeFromContext(UUID contextUUID)
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
String contextFullName = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
String context = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
UUID uuid = UUID.fromString(containerContext.id());
try {
resourceRegistryPublisher.removeResourceFromContext(HostingNode.NAME, uuid, contextUUID, false);
logger.info("{} with UUID {} successfully removed from context ({})", HostingNode.NAME, uuid, contextFullName);
logger.info("{} with UUID {} successfully removed from context ({})", HostingNode.NAME, uuid, context);
} catch (Exception e) {
logger.error("Unable to remove {} from context ({})", HostingNode.NAME, uuid, contextFullName, e);
logger.error("Unable to remove {} from context ({})", HostingNode.NAME, uuid, context, e);
}
}
@ -374,10 +380,10 @@ public class HostingNodeManager {
LocationFacet locationFacet = new LocationFacetImpl();
Site site = containerConfiguration.site();
locationFacet.setCountry(site.country());
locationFacet.setLocation(site.location());
locationFacet.setLatitude(site.latitude());
locationFacet.setLongitude(site.longitude());
locationFacet.setCountry(site.getCountry());
locationFacet.setLocation(site.getLocation());
locationFacet.setLatitude(site.getLatitude());
locationFacet.setLongitude(site.getLongitude());
hostingNode.addFacet(locationFacet);
logger.info("{} with UUID {} instantiated", HostingNode.NAME, uuid);
@ -434,7 +440,7 @@ public class HostingNodeManager {
long total = 0;
try {
FileStore fileStore = Files
.getFileStore(Paths.get(containerContext.configuration().persistence().location()));
.getFileStore(Paths.get(containerContext.configuration().persistence().getLocation()));
free = fileStore.getUsableSpace() / 1048576; // 1048576 = 1024*1024
// user to convert
// bytes in MByte

View File

@ -0,0 +1,137 @@
package org.gcube.smartgears.publisher.resourceregistry;
import java.util.Set;
import java.util.UUID;
import org.gcube.common.clients.config.Property;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.handler.resourceregistry.Constants;
import org.gcube.smartgears.handler.resourceregistry.ContextUtility;
import org.gcube.smartgears.handler.resourceregistry.resourcemanager.HostingNodeManager;
import org.gcube.smartgears.publishing.Publisher;
import org.gcube.smartgears.publishing.SmartgearsProfilePublisher;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SmartgearsProfilePublisher
public class FacetBasedPublisher implements Publisher {
private static Logger logger = LoggerFactory.getLogger(FacetBasedPublisher.class);
@Override
public boolean create(ContainerContext containerContext, Set<String> contexts) {
// Used at startup and in add to context
HostingNodeManager hostingNodeManager = new HostingNodeManager(containerContext);
AuthorizationProvider authorizationProvider = containerContext.configuration().authorizationProvider();
boolean first = true;
for (String context : contexts) {
UUID contextUUID = ContextUtility.getContextUUID(context);
if(first) {
hostingNodeManager.createHostingNode();
containerContext.properties().add(new Property(Constants.HOSTING_NODE_MANAGER_PROPERTY, hostingNodeManager));
first = false;
}else {
}
}
return true;
}
@Override
public boolean create(ApplicationContext applicationContext, Set<String> contexts) {
// Used at startup and in add to context
return false;
}
@Override
public boolean remove(ApplicationContext applicationContext, Set<String> contexts) {
// Remove from contexts
return false;
}
@Override
public boolean remove(ContainerContext containerContext, Set<String> contexts) {
// Remove from contexts
return false;
}
@Override
public boolean update(ApplicationContext applicationContext) {
// Periodic updates
return false;
}
@Override
public boolean update(ContainerContext containerContext) {
// Periodic updates
return false;
}
// @Override
// public boolean publishContainer(ContainerContext containerContext, Set<String> contexts) {
// HostingNodeManager hostingNodeManager = new HostingNodeManager(containerContext);
//
// AuthorizationProvider authorizationProvider = containerContext.configuration().authorizationProvider();
// Set<String> authorizedContexts = authorizationProvider.getContexts();
// for (String context : authorizedContexts) {
//
// }
// return true;
// }
//
// @Override
// public boolean publishApplication(ApplicationContext applicationContext, Set<String> contexts) {
// EServiceManager eServiceManager = new EServiceManager(applicationContext);
//
// AuthorizationProvider provider = applicationContext.container().configuration().authorizationProvider();
//
// for (String context : provider.getContexts())
// try {
// logger.info("publishing application in context {}", context);
// AuthorizedTasks.executeSafely(new Runnable() {
//
// @Override
// public void run() {
// try {
// logger.info("(inside task)publishing application in context {}", context);
// String resource = toXml(enpoint);
// registry.getStubs().create(resource, enpoint.type().toString());
// logger.debug("publisher resource in context {} : {}",context, resource);
// }catch (Exception e) {
// logger.error("erro publishing application", e);
// throw new RuntimeException(e);
// }
//
// }
// }, provider.getSecretForContext(context));
// }catch (Throwable e) {
// logger.error("error publisshing application profile in context {}", context, e);
// }
//
// return true;
// }
//
// @Override
// public boolean unpublishContainer(ContainerContext container, Set<String> contexts) {
// // TODO Auto-generated method stub
// return false;
// }
//
// @Override
// public boolean unpublishApplication(ApplicationContext application, Set<String> contexts) {
// // TODO Auto-generated method stub
// return false;
// }
//
// private String toXml(Resource resource){
// StringWriter writer = new StringWriter();
// Resources.marshal(resource, writer);
// return writer.toString();
// }
}