smart-executor/src/main/java/org/gcube/vremanagement/executor/ispublisher/GCoreISPublisher.java

252 lines
9.8 KiB
Java

package org.gcube.vremanagement.executor.ispublisher;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import org.gcube.common.resources.gcore.Resource;
import org.gcube.common.resources.gcore.Resources;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.Profile;
import org.gcube.common.resources.gcore.ServiceEndpoint.Property;
import org.gcube.common.resources.gcore.ServiceEndpoint.Runtime;
import org.gcube.common.resources.gcore.common.Platform;
import org.gcube.common.resources.gcore.utils.Group;
import org.gcube.informationsystem.publisher.RegistryPublisher;
import org.gcube.informationsystem.publisher.RegistryPublisherFactory;
import org.gcube.informationsystem.publisher.exception.RegistryNotFoundException;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.resources.discovery.icclient.ICFactory;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.vremanagement.executor.ContextUtility;
import org.gcube.vremanagement.executor.exception.ExecutorException;
import org.gcube.vremanagement.executor.exception.PluginNotFoundException;
import org.gcube.vremanagement.executor.plugin.Plugin;
import org.gcube.vremanagement.executor.pluginmanager.PluginManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GCoreISPublisher extends ISPublisher {
private static Logger logger = LoggerFactory.getLogger(GCoreISPublisher.class);
public GCoreISPublisher(ApplicationContext applicationContext) {
super(applicationContext);
}
/**
* Publish the provided resource on all Service Scopes retrieved from
* Context
* @param resource to be published
* @throws RegistryNotFoundException if the Registry is not found so the
* resource has not be published
*/
private void publishResource(Resource resource) throws Exception {
StringWriter stringWriter = new StringWriter();
Resources.marshal(resource, stringWriter);
RegistryPublisher registryPublisher = RegistryPublisherFactory.create();
try {
logger.debug("Trying to publish to {}:\n{}", ContextUtility.getCurrentScope(), stringWriter);
registryPublisher.create(resource);
} catch(Exception e) {
logger.error("The resource was not published", e);
throw e;
}
}
/**
* Remove the resource from IS
* @param resource to be unpublished
* @throws RegistryNotFoundException if the Registry is not found so the
* resource has not be published
*/
private void unPublishResource(Resource resource) throws Exception {
//StringWriter stringWriter = new StringWriter();
//Resources.marshal(resource, stringWriter);
RegistryPublisher registryPublisher = RegistryPublisherFactory.create();
String id = resource.id();
logger.debug("Trying to remove {} with ID {} from {}", resource.getClass().getSimpleName(), id,
ContextUtility.getCurrentScope());
registryPublisher.remove(resource);
logger.debug("{} with ID {} removed successfully", resource.getClass().getSimpleName(), id);
}
/**
* Return the parsed version string as array of short.
* @param version the version as String
* @param wantedLenght if the length is equals to dot (.) separated
* number in the string. Otherwise the version is padded or truncated to
* the required version
* @return the parsed version as array of short. If on slicing some of the
* version cannot be parsed as short 1 is used for the first number, 0 is
* used instead or for padding
*/
private short[] getVersionSlice(String version, int wantedLenght) {
logger.trace("Trying to parse {}", version);
short[] versionSlices = new short[wantedLenght];
for(int j = 0; j < wantedLenght; j++) {
versionSlices[j] = (short) (j == 0 ? 1 : 0);
}
try {
String[] stringSlices = version.split("[.-]");
for(int i = 0; i < stringSlices.length; i++) {
logger.trace("Parsing version slice n. {} wich is '{}'", i, stringSlices[i]);
if(i >= wantedLenght) {
break;
}
try {
short n = Short.parseShort(stringSlices[i]);
versionSlices[i] = n;
logger.trace("Version slice n. {} wich is '{}' parsed as short {}", i, stringSlices[i], n);
} catch(NumberFormatException nfe) {
logger.trace("Version slice n. {} wich is '{}' failed to parse. The default value {} will be used",
i, stringSlices[i], versionSlices[i]);
}
}
} catch(Exception e) {
logger.trace("Error parsing the supplied version the default will be used", versionSlices);
}
logger.trace("Version {} parsed as {}", version, versionSlices);
return versionSlices;
}
private static String getRunningOn(ContainerConfiguration containerConfiguration) {
return String.format("%s:%s", containerConfiguration.hostname(), containerConfiguration.port());
}
/**
* Create the Service Endpoint using information related to discovered
* available plugins and their own discovered capabilities
* @return the created {@link ServiceEndpoint}
* @throws ExecutorException
* @throws PluginNotFoundException
*/
protected ServiceEndpoint createServiceEndpoint(Map<String,Class<? extends Plugin>> availablePlugins) throws PluginNotFoundException, ExecutorException {
logger.debug(
"Creating ServiceEndpoint to publish on IS available plugins and their own supported capabilities");
ApplicationConfiguration applicationConfiguration = applicationContext.configuration();
ServiceEndpoint serviceEndpoint = new ServiceEndpoint();
Profile profile = serviceEndpoint.newProfile();
profile.category(applicationConfiguration.serviceClass());
profile.name(applicationConfiguration.name());
String version = applicationConfiguration.version();
profile.version(version);
profile.description(applicationConfiguration.description());
String runningOn = getRunningOn(applicationContext.container().configuration());
Platform platform = profile.newPlatform();
platform.name(runningOn);
short[] versionSlices = getVersionSlice(version, 4);
platform.version(versionSlices[0]);
platform.minorVersion(versionSlices[1]);
platform.buildVersion(versionSlices[2]);
platform.revisionVersion(versionSlices[3]);
Runtime runtime = profile.newRuntime();
runtime.hostedOn(runningOn);
runtime.status(applicationConfiguration.mode().toString());
Group<AccessPoint> accessPoints = profile.accessPoints();
PluginManager pluginManager = PluginManager.getInstance();
for(String pluginName : availablePlugins.keySet()) {
AccessPoint accessPointElement = new AccessPoint();
accessPointElement.name(pluginName);
Plugin pluginDeclaration = pluginManager.getPlugin(pluginName);
accessPointElement.description(pluginDeclaration.getDescription());
Group<Property> properties = accessPointElement.properties();
Property propertyVersionElement = new Property();
propertyVersionElement.nameAndValue("Version", pluginDeclaration.getVersion());
properties.add(propertyVersionElement);
Map<String,String> pluginCapabilities = pluginDeclaration.getSupportedCapabilities();
if(pluginCapabilities!=null) {
for(String capabilityName : pluginCapabilities.keySet()) {
Property propertyElement = new Property();
propertyElement.nameAndValue(capabilityName, pluginCapabilities.get(capabilityName));
properties.add(propertyElement);
}
}
accessPoints.add(accessPointElement);
}
StringWriter stringWriter = new StringWriter();
Resources.marshal(serviceEndpoint, stringWriter);
logger.debug("The created ServiceEndpoint profile is\n{}", stringWriter.toString());
return serviceEndpoint;
}
protected void cleanServiceEndpoints() {
try {
ApplicationConfiguration applicationConfiguration = applicationContext.configuration();
ContainerContext containerContext = applicationContext.container();
SimpleQuery query = ICFactory.queryFor(ServiceEndpoint.class)
.addCondition(String.format("$resource/Profile/Category/text() eq '%s'",
applicationConfiguration.serviceClass()))
.addCondition(String.format("$resource/Profile/Name/text() eq '%s'",
applicationConfiguration.name()))
.addCondition(String.format("$resource/Profile/RunTime/HostedOn/text() eq '%s'",
getRunningOn(containerContext.configuration())))
.setResult("$resource");
DiscoveryClient<ServiceEndpoint> client = ICFactory.clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> serviceEndpoints = client.submit(query);
for(ServiceEndpoint serviceEndpoint : serviceEndpoints) {
try {
logger.debug("Trying to unpublish the old ServiceEndpoint with ID {} from scope {}",
serviceEndpoint.id(), ContextUtility.getCurrentScope());
unPublishResource(serviceEndpoint);
} catch(Exception e) {
logger.debug("Exception tryng to unpublish the old ServiceEndpoint with ID {} from scope {}",
serviceEndpoint.id(), ContextUtility.getCurrentScope(), e);
}
}
} catch(Exception e) {
logger.debug("An Exception occur while checking and/or unpublishing old ServiceEndpoint", e);
}
}
@Override
public void publishPlugins(Map<String,Class<? extends Plugin>> availablePlugins) {
try {
ServiceEndpoint serviceEndpoint = createServiceEndpoint(availablePlugins);
cleanServiceEndpoints();
publishResource(serviceEndpoint);
} catch(Exception e) {
logger.error("Unable to Create ServiceEndpoint for scope {}. The Service will be aborted",
ContextUtility.getCurrentScope(), e);
throw new RuntimeException(e);
}
}
@Override
public void unpublishPlugins(boolean force) throws Exception {
cleanServiceEndpoints();
}
}