new features for configuration file type changing

master
Lucio Lelii 2 years ago
parent cf3c134953
commit 08b3cd590a

@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<smartgears version="${project.version}" />

@ -28,8 +28,8 @@
<properties>
<distroDirectory>distro</distroDirectory>
<tomcat.version>7.0.42</tomcat.version>
<jersey.version>1.17.1</jersey.version>
<tomcat.version>8.0.42</tomcat.version>
<jersey.version>2.25.1</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@ -154,9 +154,8 @@
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
@ -227,6 +226,20 @@
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<property>
<name>projectVersion</name>
<value>${project.version}</value>
</property>
</systemPropertyVariables>
</configuration>
</plugin>
<!-- include probe in attached war -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -280,9 +293,6 @@
<resources>
<resource>
<directory>${distroDirectory}</directory>
<includes>
<include>smartgears-config.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>

@ -90,7 +90,7 @@ public class Bootstrap implements ServletContainerInitializer {
* using gcube facilities annotation based
* ( i.e org.gcube.common.validator.annotations)
*/
//context.configuration().validate();
context.configuration().validate();
} catch (RuntimeException e) {

@ -115,6 +115,9 @@ public interface ApplicationConfiguration {
*/
ApplicationConfiguration persistence(PersistenceWriter manager);
void authorizedContexts(Set<String> authorizedContexts);
Set<String> authorizedContexts();
/**
* Validates this configuration.

@ -134,5 +134,16 @@ public class BridgedApplicationConfiguration implements ApplicationConfiguration
return application.proxyAddress(proxyaddress);
}
@Override
public void authorizedContexts(Set<String> authorizedContexts) {
application.authorizedContexts(authorizedContexts);
}
@Override
public Set<String> authorizedContexts() {
return application.authorizedContexts();
}
}

@ -57,6 +57,7 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
@XmlElementRef
Set<Include> includes= new LinkedHashSet<Include>();
Set<String> authorizedContexts;
@NotNull @IsValid
private PersistenceWriter persistenceManager;
@ -169,6 +170,16 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
return this;
}
@Override
public void authorizedContexts(Set<String> authorizedContexts) {
this.authorizedContexts = authorizedContexts;
}
@Override
public Set<String> authorizedContexts() {
return this.authorizedContexts;
}
@Override
public void validate() {
@ -197,5 +208,6 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
}
}

@ -16,14 +16,10 @@ public class Site {
@NotNull
String location;
@NotNull
String latitude;
@NotNull
String longitude;
public String getCountry() {
return country;
}

@ -3,18 +3,14 @@ package org.gcube.smartgears.configuration.library;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.gcube.common.validator.ValidationError;
import org.gcube.common.validator.Validator;
import org.gcube.common.validator.ValidatorFactory;
import org.gcube.common.validator.annotations.NotEmpty;
@XmlRootElement(name="smartgears")
public class SmartGearsConfiguration {
@XmlAttribute @NotEmpty
@NotEmpty
private String version;
public SmartGearsConfiguration(){

@ -3,6 +3,7 @@ package org.gcube.smartgears.context.application;
import javax.servlet.ServletContext;
import org.gcube.common.events.Hub;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.context.Properties;
import org.gcube.smartgears.context.container.ContainerContext;
@ -35,7 +36,7 @@ public interface ApplicationContext {
ApplicationConfiguration configuration();
<T> T profile(Class<T> type);
GCoreEndpoint profile();
/**
* Returns the lifecycle of the application.
@ -79,4 +80,5 @@ public interface ApplicationContext {
*/
Properties properties();
}

@ -66,13 +66,8 @@ public class DefaultApplicationContext implements ApplicationContext {
}
@Override
@SuppressWarnings("all")
public <T> T profile(Class<T> type) {
if (type==GCoreEndpoint.class)
return (T) properties().lookup(profile_property).value(GCoreEndpoint.class);
throw new IllegalArgumentException("unsupported profile type: "+type);
public GCoreEndpoint profile() {
return properties().lookup(profile_property).value(GCoreEndpoint.class);
}
@Override

@ -1,6 +1,7 @@
package org.gcube.smartgears.context.container;
import org.gcube.common.events.Hub;
import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.context.Properties;
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
@ -25,7 +26,7 @@ public interface ContainerContext {
* Returns the resource profile of a given type of the container.
* @return the profile
*/
<T> T profile(Class<T> type);
HostingNode profile();
/**
* Returns the lifecycle of the container

@ -38,13 +38,8 @@ public class DefaultContainerContext implements ContainerContext {
this.properties=properties;
}
@SuppressWarnings("all")
public <T> T profile(Class<T> type) {
if (type==HostingNode.class)
return (T) properties().lookup(container_profile_property).value(HostingNode.class);
throw new IllegalArgumentException("unsupported profile type: "+type);
public HostingNode profile() {
return properties().lookup(container_profile_property).value(HostingNode.class);
};
@Override

@ -23,7 +23,6 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.smartgears.extensions.ApiResource;
import org.gcube.smartgears.extensions.ApiSignature;
@ -95,7 +94,7 @@ public class FrontPageResource extends ApiResource {
String infrastructure = context().container().configuration().infrastructure();
StringBuilder voValue = new StringBuilder();
Collection<String> scopes = context().profile(GCoreEndpoint.class).scopes().asCollection();
Collection<String> scopes = context().profile().scopes().asCollection();
Set<String> vos = new HashSet<String>();
//pre-process

@ -9,7 +9,6 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.resources.gcore.Resources;
import org.gcube.smartgears.extensions.ApiResource;
import org.gcube.smartgears.extensions.ApiSignature;
@ -36,7 +35,7 @@ public class ProfileResource extends ApiResource {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Resources.marshal(context().profile(GCoreEndpoint.class),resp.getWriter());
Resources.marshal(context().profile(),resp.getWriter());
}
}

@ -0,0 +1,138 @@
package org.gcube.smartgears.handlers;
import static org.gcube.smartgears.utils.Utils.notEmpty;
import static org.gcube.smartgears.utils.Utils.rethrowUnchecked;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.resources.gcore.Resource;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.smartgears.provider.ProviderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractProfilePublisher<P extends Resource> implements ProfilePublisher {
private static final Logger log = LoggerFactory.getLogger(AbstractProfilePublisher.class);
//the underlying IS publisher
private final ScopedPublisher publisher;
//private AuthorizationProvider authProvider ;
public AbstractProfilePublisher() {
this.publisher=ProviderFactory.provider().publisher();
//this.authProvider = ProviderFactory.provider().authorizationProvider();
}
protected abstract P getProfile();
protected abstract boolean isRoot();
protected abstract void sharePublished(P profile);
protected abstract Set<String> getAllowedContexts();
/**
* Removes the application from one or more scopes.
* @param scopes the scopes
*/
public void removeFrom(Collection<String> contexts) {
P profile = getProfile();
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get();
String previousScope = ScopeProvider.instance.get();
try{//This classloader set is needed for the jaxb context
if (previousToken!=null)
SecurityTokenProvider.instance.reset();
if (isRoot())
Thread.currentThread().setContextClassLoader(AbstractProfilePublisher.class.getClassLoader());
profile = publisher.remove(profile, new ArrayList<String>(contexts));
} catch (Exception e) {
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
ScopeProvider.instance.set(previousScope);
if (isRoot())
Thread.currentThread().setContextClassLoader(contextCL);
}
log.debug("after remove application profile contains scopes {}",profile.scopes().asCollection());
sharePublished(profile);
}
public void addToAll(){
this.addTo(getAllowedContexts());
}
/**
* Adds for the first time the current resource profile of the application in one or more scopes.
* @param contexts the contexts
*/
public void addTo(Collection<String> contexts) {
notEmpty("contexts",contexts);
P profile = getProfile();
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get();
String previousScope = ScopeProvider.instance.get();
try{//This classloader set is needed for the jaxb context
if (previousToken!=null)
SecurityTokenProvider.instance.reset();;
if (isRoot()) Thread.currentThread().setContextClassLoader(AbstractProfilePublisher.class.getClassLoader());
ScopeProvider.instance.set(contexts.stream().findFirst().get());
profile = publisher.create(profile, new ArrayList<String>(contexts));
} catch (Exception e) {
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
ScopeProvider.instance.set(previousScope);
if (isRoot()) Thread.currentThread().setContextClassLoader(contextCL);
}
sharePublished(profile);
log.debug("shared profile with scopes {}", profile.scopes().asCollection());
}
public void update() {
P profile = getProfile();
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get();
String previousScope = ScopeProvider.instance.get();
try{//This classloader set is needed for the jaxb context
if (previousToken!=null)
SecurityTokenProvider.instance.reset();
if (isRoot())
Thread.currentThread().setContextClassLoader(AbstractProfilePublisher.class.getClassLoader());
profile = publisher.update(profile);
} catch (Exception e) {
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
ScopeProvider.instance.set(previousScope);
if (isRoot())
Thread.currentThread().setContextClassLoader(contextCL);
}
sharePublished(profile);
}
}

@ -3,21 +3,14 @@ package org.gcube.smartgears.handlers;
import java.util.Collection;
public interface ProfilePublisher {
/**
* Adds for the first time the current resource profile of the application in one or more scopes.
* @param scopes the scopes
*/
void addTo(Collection<String> tokens);
void addTo(Collection<String> contexts);
void addToAll();
void update();
/**
* Removes the application from one or more scopes.
* @param scopes the scopes
*/
void removeFrom(Collection<String> tokens);
void removeFrom(Collection<String> contexts);
}
}

@ -8,7 +8,6 @@ import java.util.List;
import javax.servlet.ServletRegistration;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.context.application.ApplicationContext;
@ -38,7 +37,7 @@ public class ProfileBuilder {
.serviceClass(configuration.serviceClass())
.version(configuration.version())
.serviceId(configuration.name() + configuration.serviceClass() + configuration.version())
.ghnId(context.container().profile(HostingNode.class).id());
.ghnId(context.container().profile().id());
endpoint.profile().newDeploymentData()
.activationTime(Calendar.getInstance())

@ -94,7 +94,7 @@ public class ProfileManager extends ApplicationLifecycleHandler {
share(profile);
publisher = context.container().configuration().mode()!=Mode.offline?
new ProfilePublisherImpl(context):
new ServicePublisher(context):
new OfflineProfilePublisher();
@ -109,7 +109,7 @@ public class ProfileManager extends ApplicationLifecycleHandler {
@Observes({ activation, stop, failure })
void onChanged(ApplicationLifecycle lc) {
GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
GCoreEndpoint profile = context.profile();
profile.profile().deploymentData().status(lc.state().remoteForm());
@ -270,7 +270,7 @@ public class ProfileManager extends ApplicationLifecycleHandler {
final Runnable updateTask = new Runnable() {
public void run() {
GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
GCoreEndpoint profile = context.profile();
//if handling of event generates failures these will be reported
//for resilience we do not fail the application

@ -1,201 +0,0 @@
package org.gcube.smartgears.handlers.application.lifecycle;
import static org.gcube.smartgears.handlers.ProfileEvents.published;
import static org.gcube.smartgears.utils.Utils.notEmpty;
import static org.gcube.smartgears.utils.Utils.rethrowUnchecked;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.handlers.ProfilePublisher;
import org.gcube.smartgears.provider.ProviderFactory;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Publishes the current resource profile of the application.
* <p>
*Distinguishes publication in new scopes ({@link #addTo(List)} from publication updates in existing scopes ({@link #update()}.
*
*
* @author Fabio Simeoni
*
*/
public class ProfilePublisherImpl implements ProfilePublisher {
private static final Logger log = LoggerFactory.getLogger(ProfilePublisherImpl.class);
//the underlying IS publisher
private final ScopedPublisher publisher;
private final ApplicationContext context;
private AuthorizationProvider authProxy ;
/**
* Creates an instance for a given application.
* @param context the context of the application
*/
public ProfilePublisherImpl(ApplicationContext context) {
this.context = context;
this.publisher=ProviderFactory.provider().publisherFor(context);
this.authProxy = context.container().configuration().authorizationProvider();
}
/**
* Adds for the first time the current resource profile of the application in one or more scopes.
* @param scopes the scopes
*/
@Override
public void addTo(Collection<String> contexts) {
notEmpty("tokens",contexts);
GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
/* TODO: reintroduce it when scope will be removed
//TODO: remove when move to new IS
Collection<String> retainedContexts = new ArrayList<String>(context.container().configuration().allowedContexts());
retainedContexts.removeAll(profile.scopes().asCollection());
profile.scopes().asCollection().addAll(retainedContexts);
String previousToken = SecurityTokenProvider.instance.get();
try {
for (String token: tokens){
log.info("creating profile with token {}", token);
SecurityTokenProvider.instance.set(token);
profile = publisher.create(profile);
SecurityTokenProvider.instance.reset();
}
}catch (Exception e) {
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
}
*/
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get();
String previousScope = ScopeProvider.instance.get();
try{//This classloader set is needed for the jaxb context
if (previousToken!=null)
SecurityTokenProvider.instance.reset();;
if (context.container().configuration().mode()!=Mode.root) Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
ScopeProvider.instance.set(contexts.stream().findFirst().get());
profile = publisher.create(profile, new ArrayList<String>(contexts));
} catch (Exception e) {
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
ScopeProvider.instance.set(previousScope);
if (context.container().configuration().mode()!=Mode.root) Thread.currentThread().setContextClassLoader(contextCL);
}
sharePublished(profile);
log.debug("shared profile with scopes {}", profile.scopes().asCollection());
}
@Override
public void addToAll() {
this.addTo(context.configuration().allowedContexts());
}
@Override
public void update() {
GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get();
String previousScope = ScopeProvider.instance.get();
try{//This classloader set is needed for the jaxb context
if (previousToken!=null)
SecurityTokenProvider.instance.reset();
if (context.container().configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
profile = publisher.update(profile);
} catch (Exception e) {
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
ScopeProvider.instance.set(previousScope);
if (context.container().configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(contextCL);
}
sharePublished(profile);
}
/**
* Removes the application from one or more scopes.
* @param scopes the scopes
*/
@Override
public void removeFrom(Collection<String> contexts) {
GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get();
String previousScope = ScopeProvider.instance.get();
try{//This classloader set is needed for the jaxb context
if (previousToken!=null)
SecurityTokenProvider.instance.reset();
if (context.container().configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
profile = publisher.remove(profile, contexts);
} catch (Exception e) {
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
ScopeProvider.instance.set(previousScope);
if (context.container().configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(contextCL);
}
log.debug("after remove application profile contains scopes {}",profile.scopes().asCollection());
sharePublished(profile);
}
private void sharePublished(GCoreEndpoint profile) {
context.events().fire(profile,published);
}
private List<String> resolveScopesFromTokens(Collection<String> tokens){
List<String> scopes = new ArrayList<String>(tokens.size());
for (String token: tokens)
try{
scopes.add(this.authProxy.get(token).getContext());
}catch (Exception e) {
log.warn("error retrieving token {} , it should never happen",token);
}
return scopes;
}
}

@ -0,0 +1,62 @@
package org.gcube.smartgears.handlers.application.lifecycle;
import java.util.List;
import java.util.Set;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.handlers.AbstractProfilePublisher;
import org.gcube.smartgears.handlers.ProfileEvents;
/**
* Publishes the current resource profile of the application.
* <p>
*Distinguishes publication in new scopes ({@link #addTo(List)} from publication updates in existing scopes ({@link #update()}.
*
*
* @author Fabio Simeoni
*
*/
public class ServicePublisher extends AbstractProfilePublisher<GCoreEndpoint> {
private final ApplicationContext context;
public ServicePublisher(ApplicationContext context) {
super();
this.context = context;
}
protected void sharePublished(HostingNode profile) {
context.events().fire(profile,ProfileEvents.published);
}
@Override
protected GCoreEndpoint getProfile() {
return context.profile();
}
@Override
protected boolean isRoot() {
return context.container().configuration().mode()!=Mode.root;
}
@Override
protected void sharePublished(GCoreEndpoint profile) {
context.events().fire(profile,ProfileEvents.published);
}
@Override
protected Set<String> getAllowedContexts() {
// TODO Auto-generated method stub
return null;
}
}

@ -0,0 +1,55 @@
package org.gcube.smartgears.handlers.container.lifecycle;
import java.util.List;
import java.util.Set;
import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.handlers.AbstractProfilePublisher;
import org.gcube.smartgears.handlers.ProfileEvents;
/**
* Publishes the resource profile of the container.
* <p>
* Distinguishes publication in new scopes ({@link #addTo(List)} from publication updates in existing scopes ({@link #update(List)}.
*
* @author Fabio Simeoni
*
*/
public class ContainerPublisher extends AbstractProfilePublisher<HostingNode> {
private final ContainerContext context;
public ContainerPublisher(ContainerContext context) {
super();
this.context = context;
}
protected void sharePublished(HostingNode profile) {
context.events().fire(profile,ProfileEvents.published);
}
@Override
protected HostingNode getProfile() {
return context.profile();
}
@Override
protected boolean isRoot() {
return context.configuration().mode()!=Mode.root;
}
@Override
protected Set<String> getAllowedContexts() {
// TODO Auto-generated method stub
return null;
}
}

@ -9,8 +9,6 @@ import java.io.Reader;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
@ -193,7 +191,7 @@ public class ProfileBuilder {
long free = 0;
try {
free = context.configuration().persistence().getFreeSpace()/1024;
} catch (IOException ioe) {
} catch (Exception ioe) {
log.warn("unable to detect the free space on the disk", ioe);
}
return free;
@ -241,8 +239,8 @@ public class ProfileBuilder {
ContainerConfiguration cfg = context.configuration();
node.profile().newSite().country(cfg.site().country()).location(cfg.site().location())
.latitude(cfg.site().latitude()).longitude(cfg.site().longitude()).domain(domainIn(cfg.hostname()));
node.profile().newSite().country(cfg.site().getCountry()).location(cfg.site().getLocation())
.latitude(cfg.site().getLatitude()).longitude(cfg.site().getLongitude()).domain(domainIn(cfg.hostname()));
}
private void addVariablesTo(HostingNode node) {

@ -87,7 +87,7 @@ public class ProfileManager extends ContainerHandler {
share(profile);
publisher = context.configuration().mode()!=Mode.offline?
new ProfilePublisherImpl(context):
new ContainerPublisher(context):
new OfflineProfilePublisher();
registerObservers();
@ -102,7 +102,7 @@ public class ProfileManager extends ContainerHandler {
@Observes({ activation, part_activation, shutdown, stop, failure })
void onChanged(ContainerLifecycle lc) {
HostingNode profile = context.profile(HostingNode.class);
HostingNode profile = context.profile();
profile.profile().description().status(lc.state().remoteForm());
@ -245,7 +245,7 @@ public class ProfileManager extends ContainerHandler {
final Runnable updateTask = new Runnable() {
public void run() {
HostingNode profile = context.profile(HostingNode.class);
HostingNode profile = context.profile();
try {
builder.update(profile, false);

@ -1,241 +0,0 @@
package org.gcube.smartgears.handlers.container.lifecycle;
import static org.gcube.smartgears.utils.Utils.notEmpty;
import static org.gcube.smartgears.utils.Utils.rethrowUnchecked;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.handlers.ProfileEvents;
import org.gcube.smartgears.handlers.ProfilePublisher;
import org.gcube.smartgears.provider.ProviderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Publishes the resource profile of the container.
* <p>
* Distinguishes publication in new scopes ({@link #addTo(List)} from publication updates in existing scopes ({@link #update(List)}.
*
* @author Fabio Simeoni
*
*/
public class ProfilePublisherImpl implements ProfilePublisher {
private static final Logger log = LoggerFactory.getLogger(ProfilePublisherImpl.class);
//the underlying IS publisher
private final ScopedPublisher publisher;
//private final AuthorizationProvider authorization;
private final ContainerContext context;
private AuthorizationProxy authProxy ;
/**
* Creates an instance for the container.
* @param context the context of the application
*/
public ProfilePublisherImpl(ContainerContext context) {
this.context = context;
this.publisher=ProviderFactory.provider().publisherFor(context);
this.authProxy = ProviderFactory.provider().authorizationProxy();
}
/**
* Adds the current resource profile of the application in one or more
* scopes. The scopes are retrieved from tokens
* @param tokens the tokens
*/
public void addTo(Collection<String> tokens) {
notEmpty("tokens",tokens);
log.info("publishing container with tokens {}", tokens);
HostingNode profile = context.profile(HostingNode.class);
/* TODO: reintroduce it when scope will be removed
//TODO: remove when move to new IS
Collection<String> retainedContexts = new ArrayList<String>(context.configuration().allowedContexts());
retainedContexts.removeAll(profile.scopes().asCollection());
profile.scopes().asCollection().addAll(retainedContexts);
log.trace("profile scopes on create are {} ",profile.scopes().asCollection());
String previousToken = SecurityTokenProvider.instance.get();
try {
for (String token: tokens){
log.info("creating profile with token {}", token);
SecurityTokenProvider.instance.set(token);
profile = publisher.create(profile);
SecurityTokenProvider.instance.reset();
}
update();
} catch (Exception e) {
log.warn("error adding scopes",e);
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
}*/
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get();
try{//This classloader set is needed for the jaxb context
if (previousToken==null)
SecurityTokenProvider.instance.set((String)tokens.toArray()[0]);
if (context.configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
profile = publisher.create(profile, resolveScopesFromTokens(tokens));
} catch (Exception e) {
rethrowUnchecked(e);
} finally {
SecurityTokenProvider.instance.set(previousToken);
if (context.configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(contextCL);
}
sharePublished(profile);
}
/**
* Adds the current resource profile of the application in one or more scopes.
*/
public void addToAll() {
addTo(context.configuration().startTokens());
}
/**
* Updates the current resource profile of the application in its current scopes.
*/
public void update() {
HostingNode profile = context.profile(HostingNode.class);
/* TODO: reintroduce it when scope will be removed
Collection<String> tokens = context.configuration().startTokens();
log.info("updating container with tokens {}", tokens);
String previousToken = SecurityTokenProvider.instance.get();
try {
for (String token: tokens){
SecurityTokenProvider.instance.set(token);
profile = publisher.update(profile);
SecurityTokenProvider.instance.reset();
}
sharePublished(profile);
}
catch (Exception e) {
log.warn("error updating container",e);
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
}*/
log.debug("[update] resource scopes are : {} ",profile.scopes().asCollection());
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get();
try{//This classloader set is needed for the jaxb context
if (previousToken==null)
SecurityTokenProvider.instance.set((String)context.configuration().startTokens().toArray()[0]);
if (context.configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
profile = publisher.update(profile);
} catch (Exception e) {
rethrowUnchecked(e);
} finally {
SecurityTokenProvider.instance.set(previousToken);
if (context.configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(contextCL);
}
sharePublished(profile);
}
/**
* Removes the container from one or more scopes.
* @param tokens the tokens
*/
public void removeFrom(Collection<String> tokens) {
HostingNode profile = context.profile(HostingNode.class);
log.info("removing container with tokens {}", tokens);
/* TODO: reintroduce it when scope will be removed
String previousToken = SecurityTokenProvider.instance.get();
try {
for (String token: tokens){
SecurityTokenProvider.instance.set(token);
profile = publisher.remove(profile);
SecurityTokenProvider.instance.reset();
}
update();
}
catch (Exception e) {
log.warn("error removing scopes",e);
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
} */
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get();
try{//This classloader set is needed for the jaxb context
if (previousToken==null)
SecurityTokenProvider.instance.set((String)tokens.toArray()[0]);
if (context.configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
profile = publisher.remove(profile, resolveScopesFromTokens(tokens));
} catch (Exception e) {
rethrowUnchecked(e);
} finally {
SecurityTokenProvider.instance.set(previousToken);
if (context.configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(contextCL);
}
log.debug("after remove container profile contains scopes {}",profile.scopes().asCollection());
sharePublished(profile);
}
private void sharePublished(HostingNode profile) {
context.events().fire(profile,ProfileEvents.published);
}
private List<String> resolveScopesFromTokens(Collection<String> tokens){
List<String> scopes = new ArrayList<String>(tokens.size());
for (String token: tokens)
try{
scopes.add(this.authProxy.get(token).getContext());
}catch (Exception e) {
log.warn("error retrieving token {} , it should never happen",token);
}
return scopes;
}
}

@ -15,7 +15,6 @@ import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
@ -69,18 +68,11 @@ public class ApplicationManager {
for (Entry<String,? extends ServletRegistration> servlet : application.getServletRegistrations().entrySet())
log.trace("servlet {} : {} {} ", application.getServletContextName(),servlet.getKey(), servlet.getValue().getMappings());
/* if (context.configuration().secure() &&
container.configuration().securePort()==null)
throw new IllegalStateException(
String.format("Application %s cannot be managed because is declared as secure without a secure connector port declared in the container", context.application().getContextPath()));
*/
if (context.container().configuration().mode()!=Mode.offline) {
context.configuration().startTokens(generateTokensForApplication(container).stream().collect(Collectors.toSet()));
context.configuration().authorizedContexts(context.container().configuration().allowedContexts());
context.configuration().validate();
//TODO take information from container to configure application
}
saveApplicationState();
@ -93,8 +85,6 @@ public class ApplicationManager {
ApplicationHandlers handlers = provider().handlersFor(context);
handlers.validate();
ApplicationExtensions extensions = provider().extensionsFor(context);
extensions.validate();

@ -10,29 +10,21 @@ import static org.gcube.smartgears.provider.ProviderFactory.provider;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.gcube.common.authorization.client.exceptions.ObjectNotFound;
import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.ClientInfo;
import org.gcube.common.authorization.library.provider.ContainerInfo;
import org.gcube.common.events.Observes;
import org.gcube.common.events.Observes.Kind;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.container.ContainerHandlers;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.handlers.ProfileEvents;
import org.gcube.smartgears.handlers.container.ContainerHandler;
import org.gcube.smartgears.handlers.container.ContainerLifecycleEvent;
import org.gcube.smartgears.handlers.container.ContainerPipeline;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.lifecycle.container.ContainerState;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.gcube.smartgears.security.Credentials;
import org.gcube.smartgears.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -49,8 +41,6 @@ public class ContainerManager {
public static ContainerManager instance = new ContainerManager();
private AuthorizationProvider authProvider = provider().authorizationProxy();
private ContainerContext context;
private ContainerPipeline pipeline;
@ -113,57 +103,26 @@ public class ContainerManager {
private void validateContainer(ContainerContext context) {
//List<String> tokensToRemove = new ArrayList<String>();
context.configuration().validate();
Set<String> foundContexts= new HashSet<String>();
Credentials credential = context.configuration().credentials();
Set<String> foundContexts;
try {
List<AuthorizationEntry> entries = authProvider.get(context.configuration().startTokens());
log.info("requesting auth on {} tokens returned {} entries", context.configuration().startTokens().size(),entries.size());
for (AuthorizationEntry entry : entries ) {
log.info("the container will be started in context {}",entry.getContext());
foundContexts.add(entry.getContext());
}
foundContexts = context.configuration().allowedContexts();
} catch (Exception e) {
log.error("error contacting auth service on container",e);
log.error("error authorizing container",e);
throw new RuntimeException("error authorizing container, moving the container to failed",e);
}
if (foundContexts.isEmpty()){
log.error("no valid starting token are specified, moving the container to failed");
throw new RuntimeException("no valid starting token are specified");
log.error("no valid contexts found, moving the container to failed");
throw new RuntimeException("no valid contexts found, moving the container to failed");
}
//context.configuration().startTokens().removeAll(tokensToRemove);
context.configuration().allowedContexts(foundContexts);
}
private String resolveTokenForAdd(Set<String> alreadyAddedContext, String token){
try {
AuthorizationEntry entry = authProvider.get(token);
ClientInfo info = entry.getClientInfo();
log.info("resolved authorization entry for container {}",entry);
if (alreadyAddedContext.contains(entry.getContext())){
log.warn("the token {} cannot be used, another token with the same context {} found ", entry.getContext());
} else if(!entry.getContext().startsWith("/"+context.configuration().infrastructure())){
log.warn("the token {} cannot be used, is not in the infrastructure {} of the container ", token,context.configuration().infrastructure());
}else if (!(info instanceof ContainerInfo)){
log.warn("the token {} cannot be used, is not for a container token ", token);
} else if (!((ContainerInfo)info).getHost().equals(context.configuration().hostname())
|| context.configuration().port()!=((ContainerInfo)info).getPort()){
log.warn("the token {} cannot be used, the client id {} resolved with the token is not the same of the one specified in this container ", token, info.getId());
} else
return entry.getContext();
}catch(ObjectNotFound onf){
log.error("token {} not valid", token);
} catch (Exception e) {
log.error("error contacting authorization for token {}",token,e);
}
return null;
}
public void manage(ApplicationContext app) {
app.events().subscribe(this);
@ -175,40 +134,15 @@ public class ContainerManager {
context.lifecycle().tryMoveTo(ContainerState.partActive);
}
@Observes(value=ContextEvents.ADD_TOKEN_TO_CONTAINER,kind=Kind.critical)
void addToken(String token) {
log.trace("adding token {} to container", token);
String newContext;
if ((newContext = resolveTokenForAdd(context.configuration().allowedContexts(), token))!=null) {
context.configuration().startTokens().add(token);
context.configuration().allowedContexts().add(newContext);
saveContainerState();
//loadKeyForToken(Arrays.asList(token));
context.events().fire(token, ContextEvents.ADD_TOKEN_TO_APPLICATION);
context.events().fire(token, ProfileEvents.addToContext);
log.trace("token added and event fired");
} else log.warn("trying to add an invalid token");
@Observes(value=ContextEvents.ADD_CONTEXT_TO_CONTAINER,kind=Kind.critical)
void addContext(String context) {
log.trace("adding context {} to container", context);
}
@Observes(value=ContextEvents.REMOVE_TOKEN_FROM_CONTAINER,kind=Kind.critical)
void removeToken(String token) {
log.trace("removing token {} from container", token);
AuthorizationEntry entry;
try {
entry = authProvider.get(token);
} catch (Exception e) {
log.error("error resolving token to remove");
return;
}
if (context.configuration().startTokens().contains(token)) {
context.configuration().startTokens().remove(token);
context.configuration().allowedContexts().remove(entry.getContext());
saveContainerState();
context.events().fire(token, ContextEvents.REMOVE_TOKEN_FROM_APPLICATION);
context.events().fire(token, ProfileEvents.removeFromContext);
log.trace("token removed and event fired");
} else log.warn("cannot remove token, it is not present in the container");
@Observes(value=ContextEvents.REMOVE_CONTEXT_FROM_CONTAINER,kind=Kind.critical)
void removeContext(String context) {
log.trace("removing context {} from container", context);
}
/**

@ -5,6 +5,8 @@ import static org.gcube.smartgears.utils.Utils.fileAt;
import static org.gcube.smartgears.utils.Utils.notNull;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull;
@ -50,10 +52,7 @@ public class LocalPersistence implements PersistenceWriter {
return fileAt(new File(location, path).getAbsolutePath()).toRead();
}
void initialize(){
}
public void validate() {
File locationDir = new File(location);
@ -61,5 +60,14 @@ public class LocalPersistence implements PersistenceWriter {
throw new IllegalStateException("invalid node configuration: home "+location+" does not exist or is not a directory or cannot be accessed in read/write mode");
}
@Override
public long getFreeSpace() {
try {
return Files.getFileStore(Paths.get(location)).getUsableSpace();
}catch (Exception e) {
return -1;
}
}
}

@ -1,10 +1,9 @@
package org.gcube.smartgears.provider;
import static org.gcube.common.authorization.client.Constants.authorizationService;
import static org.gcube.smartgears.Constants.application_handlers_file_name;
import static org.gcube.smartgears.Constants.configuration_file_path;
import static org.gcube.smartgears.Constants.container_configuraton_file_path;
import static org.gcube.smartgears.Constants.container_handlers_file_name;
import static org.gcube.smartgears.Constants.application_handlers_file_name;
import static org.gcube.smartgears.Constants.container_handlers_file_path;
import static org.gcube.smartgears.Constants.container_profile_file_path;
import static org.gcube.smartgears.Constants.default_extensions_file_path;
@ -25,11 +24,10 @@ import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletContext;
import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
import org.gcube.common.events.Hub;
import org.gcube.common.events.impl.DefaultHub;
import org.gcube.common.scan.ClasspathScanner;
@ -56,7 +54,7 @@ import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.context.container.DefaultContainerContext;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
import org.gcube.smartgears.persistence.DefaultPersistence;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.gcube.smartgears.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -74,24 +72,33 @@ public class DefaultProvider implements Provider {
private ContainerContext containerContext;
//TODO: do the same with applicationContext (with a map)
private File configFile = null;
protected DefaultProvider(File configFile) {
this.configFile = configFile;
}
protected DefaultProvider(){};
@SuppressWarnings("unchecked")
@Override
public ContainerContext containerContext() {
if(containerContext==null){
ContainerConfiguration configuration = containerConfiguration();
/*
if (configuration.persistence()==null) {
String location = Utils.home()+"/state";
File dir = new File(location);
if (!dir.exists())
dir.mkdirs();
configuration.persistence(new DefaultPersistence(location));
configuration.persistence(new LocalPersistence(location));
log.trace("setting persistence location for container @ {}",dir.getAbsolutePath());
}
}*/
Hub hub = new DefaultHub();
@ -100,12 +107,10 @@ public class DefaultProvider implements Provider {
File file = configuration.persistence().file(container_profile_file_path);
String id = null;
List<String> tokens = null;
if (file.exists()){
log.info("loading persisted state for container");
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))){
id = (String)ois.readObject();
tokens = (List<String>) ois.readObject();
}catch(Exception e){
log.error("error loading persisted state, creating new uuid",e);
}
@ -117,9 +122,6 @@ public class DefaultProvider implements Provider {
}
if (tokens!=null)
configuration.startTokens(tokens);
containerContext = new DefaultContainerContext(id, configuration, hub, lifecycle, new Properties());
}
return containerContext;
@ -137,14 +139,14 @@ public class DefaultProvider implements Provider {
ContainerConfigurationBinder binder = new ContainerConfigurationBinder();
ContainerHandlers defaultHandlers = binder.bindHandlers(config);
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
if (currentClassLoader.getParent()!=null && !currentClassLoader.getParent().equals(ClassLoader.getSystemClassLoader())){
log.trace("probably i'm in a webapp classloader");
currentClassLoader = currentClassLoader.getParent();
}
try{
if (currentClassLoader instanceof URLClassLoader){
URL[] urls = ((URLClassLoader) currentClassLoader).getURLs() ;
@ -152,13 +154,13 @@ public class DefaultProvider implements Provider {
if (urls!=null && urls.length>0){
ClasspathScanner scanner = ClasspathScannerFactory.scanner(new HashSet<URL>(Arrays.asList(urls)));
Collection<ClasspathResource> resources = scanner.scan(new NameMatcher(container_handlers_file_name));
for (URL url: urls)
log.trace("URL: "+ url.toString());
if (resources==null || resources.isEmpty())
log.info("no custom container handlers found in the classpath");
for (ClasspathResource res : resources){
try{
ContainerHandlers customHandlers= binder.bindHandlers(res.stream());
@ -190,8 +192,6 @@ public class DefaultProvider implements Provider {
ApplicationConfiguration embedded = configurationFor(application);
ApplicationConfiguration external = context.configuration().app(application.getContextPath());
//shouldn't happen: management shouldn't have started at all
if (embedded==null && external==null)
throw new AssertionError("application @ "+application.getContextPath()+" is not distributed with "
@ -259,15 +259,15 @@ public class DefaultProvider implements Provider {
ApplicationConfigurationBinder binder = new ApplicationConfigurationBinder();
ApplicationHandlers defaultHandlers = binder.bindHandlers(defaultHandlersStream);
//searching for smartegars related application handlers in the common classloader
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
if (currentClassLoader.getParent()!=null && !currentClassLoader.getParent().equals(ClassLoader.getSystemClassLoader())){
log.trace("probably i'm in a webapp classloader");
currentClassLoader = currentClassLoader.getParent();
}
try{
if (currentClassLoader instanceof URLClassLoader){
URL[] urls = ((URLClassLoader) currentClassLoader).getURLs() ;
@ -277,7 +277,7 @@ public class DefaultProvider implements Provider {
Collection<ClasspathResource> resources = scanner.scan(new NameMatcher(application_handlers_file_name));
if (resources==null || resources.isEmpty())
log.info("no custom smartgears related application handlers found in the classpath");
for (ClasspathResource res : resources){
try{
ApplicationHandlers customHandlers= binder.bindHandlers(res.stream());
@ -292,9 +292,9 @@ public class DefaultProvider implements Provider {
}catch(Exception e){
log.warn("cannot load smartgears related handlers for application from the root classloader",e);
}
InputStream appSpecificHandlersStream = context.application().getResourceAsStream(handlers_file_path);
if (appSpecificHandlersStream !=null ){
defaultHandlers.mergeWith(binder.bindHandlers(appSpecificHandlersStream));
log.trace("{} uses default lifecycle with app spceific handler as it includes {}", context.name(), handlers_file_path);
@ -349,15 +349,9 @@ public class DefaultProvider implements Provider {
try {
InputStream config = getClass().getResourceAsStream(library_configuration_file_path);
if (config == null)
throw new IllegalStateException("invalid distribution: cannot find " + library_configuration_file_path);
SmartGearsConfigurationBinder binder = new SmartGearsConfigurationBinder();
SmartGearsConfiguration configuration = binder.bind(config);
SmartGearsConfiguration configuration = new SmartGearsConfiguration();
configuration.version(System.getProperty("projectVersion"));
configuration.validate();
return configuration;
@ -371,7 +365,6 @@ public class DefaultProvider implements Provider {
}
// helpers
private ApplicationConfiguration configurationFor(ServletContext application) {
try {
@ -394,76 +387,48 @@ public class DefaultProvider implements Provider {
private ContainerConfiguration containerConfiguration() {
String home = Utils.home();
if (home == null)
throw new IllegalStateException("invalid node configuration: the environment variable " + ghn_home_env
+ " or the system property " + ghn_home_property + " must be defined");
File homeDir = new File(home);
if (!(homeDir.exists() && homeDir.isDirectory() && homeDir.canRead() && homeDir.canWrite()))
throw new IllegalStateException("invalid node configuration: home "+home+" does not exist or is not a directory or cannot be accessed in read/write mode");
File config = new File(homeDir,container_configuraton_file_path);
if (!(config.exists() && config.canRead()))
throw new IllegalStateException("invalid node configuration: file "+config.getAbsolutePath()+" does not exist or cannot be accessed");
log.trace("reading container configuration @ {} ", config.getAbsolutePath());
if (configFile==null) {
String home = Utils.home();
if (home == null)
throw new IllegalStateException("invalid node configuration: the environment variable " + ghn_home_env
+ " or the system property " + ghn_home_property + " must be defined");
ContainerConfigurationBinder binder = new ContainerConfigurationBinder();
File homeDir = new File(home);
FileInputStream stream = null;
try {
if (!(homeDir.exists() && homeDir.isDirectory() && homeDir.canRead() && homeDir.canWrite()))
throw new IllegalStateException("invalid node configuration: home "+home+" does not exist or is not a directory or cannot be accessed in read/write mode");
stream = new FileInputStream(config);
configFile = new File(homeDir,container_configuraton_file_path);
}
catch(Exception e) {
throw new RuntimeException("unexpected exception reading container configuration file see cause)",e);
log.trace("reading container configuration @ {} ", configFile.getAbsolutePath());
}
ContainerConfiguration configuration = binder.bind(stream);
if (!(configFile.exists() && configFile.canRead()))
throw new IllegalStateException("invalid node configuration: file "+configFile.getAbsolutePath()+" does not exist or cannot be accessed");
try {
stream.close();
ContainerConfiguration configuration;
try (InputStream stream = new FileInputStream(configFile)){
configuration= ContainerConfiguration.load(stream);
}catch (Exception e) {
throw new IllegalStateException("invalid node configuration: file "+configFile.getAbsolutePath()+" is invalid");
}
catch(Exception e) {
log.warn("could not close stream when reading container configuration @ "+config.getAbsolutePath()+" (see cause)",e);
}
return configuration;
}
/*
@Override
public RegistryPublisher publisherFor(ContainerContext context) {
return context.configuration().mode()==Mode.online?
RegistryPublisherFactory.create(): new OfflinePublisher();
}
@Override
public RegistryPublisher publisherFor(ApplicationContext context) {
return context.configuration().mode()==Mode.online?
RegistryPublisherFactory.create(): new OfflinePublisher();
}*/
@Override
public ScopedPublisher publisherFor(ContainerContext context) {
return context.configuration().mode()==Mode.online? RegistryPublisherFactory.scopedPublisher()
public ScopedPublisher publisher() {
return containerContext.configuration().mode()==Mode.online? RegistryPublisherFactory.scopedPublisher()
: new OfflinePublisher();
}
@Override
public ScopedPublisher publisherFor(ApplicationContext context) {
return context.configuration().mode()==Mode.online? RegistryPublisherFactory.scopedPublisher()
: new OfflinePublisher();
}
@Override
public AuthorizationProxy authorizationProxy() {
return authorizationService();
public AuthorizationProvider authorizationProvider() {
return containerContext.configuration().authorizationProvider();
}
}

@ -2,7 +2,6 @@ package org.gcube.smartgears.provider;
import javax.servlet.ServletContext;
import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.smartgears.configuration.application.ApplicationExtensions;
import org.gcube.smartgears.configuration.application.ApplicationHandlers;
@ -43,10 +42,9 @@ public interface Provider {
/**
* Returns an implementation of the IS publisher for the container
* @param application the context of the container
* @return the publisher implementation
*/
ScopedPublisher publisherFor(ContainerContext application);
ScopedPublisher publisher();
//application-level dependencies
@ -72,19 +70,11 @@ public interface Provider {
* @return the extensions
*/
ApplicationExtensions extensionsFor(ApplicationContext application);
/**
* Returns an implementation of the IS publisher for a given application
* @param application the context of the application
* @return the publisher implementation
*/
ScopedPublisher publisherFor(ApplicationContext application);
/**
* Returns an implementation of the IS publisher for a given application
* @param application the context of the application
* @return the publisher implementation
* Returns the authorization provider for this node
* @return the AuthorizationProvider implementation
*/
AuthorizationProvider authorizationProxy();
AuthorizationProvider authorizationProvider();
}

@ -1,10 +1,10 @@
package org.gcube.smartgears.security;
import java.util.Collection;
import java.util.Set;
public interface AuthorizationProvider {
void connect(Credentials credentials) throws Exception;
Collection<String> getAllowedContexts();
Set<String> getAllowedContexts();
}

@ -1,6 +1,6 @@
package org.gcube.smartgears.security;
import java.util.Set;
public class DefaultAuthorizationProvider implements AuthorizationProvider {
@ -11,4 +11,9 @@ public class DefaultAuthorizationProvider implements AuthorizationProvider {
this.credentials = (SimpleCredentials)credentials;
}
@Override
public Set<String> getAllowedContexts() {
return null;
}
}

@ -1,41 +1,38 @@
package app;
import static com.sun.jersey.api.client.Client.create;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.gcube.smartgears.Constants.scope_header;
import static org.gcube.smartgears.extensions.HttpExtension.Method.DELETE;
import static org.gcube.smartgears.extensions.HttpExtension.Method.GET;
import static utils.TestUtils.context_root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation.Builder;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.UserInfo;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.smartgears.extensions.HttpExtension.Method;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientResponse;
import org.glassfish.jersey.logging.LoggingFeature;
import utils.TestUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.core.header.OutBoundHeaders;
public class Request {
private String path="";
private String scope = TestUtils.scope;
private OutBoundHeaders headers = new OutBoundHeaders();
private Method method = GET;
//private OutBoundHeaders headers = new OutBoundHeaders();
private String method = HttpMethod.GET;
private String body = null;
private boolean logged = false;
Map<String, List<Object>> headers = new HashMap<>();
public static Request request() {
return new Request();
@ -66,11 +63,11 @@ public class Request {
}
public Request with(String name, String value) {
this.headers.add(name, value);
this.headers.put(name, value);
return this;
}
public Request using(Method method) {
public Request using(String method) {
this.method=method;
return this;
}
@ -83,7 +80,7 @@ public class Request {
return body;
}
public Method method() {
public String method() {
return method;
}
@ -101,7 +98,7 @@ public class Request {
class Box {
volatile UniformInterfaceException failure;
volatile Exception failure;
volatile ClientResponse response;
}
@ -116,35 +113,43 @@ public class Request {
try {
Client client = create();
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient();
if (logged)
client.addFilter(new LoggingFilter(System.err));
client.register(new LoggingFeature(Logger.getLogger(getClass().getName())));
Builder builder = client.target(address(path,port)).request();
builder.header("gcube-scope", scope);
Builder builder = client.resource(address(path,port))
.entity(body).header(scope_header, scope);
for (Entry<String,List<Object>> header : headers.entrySet())
for (Object value : header.getValue())
builder.header(header.getKey(), value);
if (method==DELETE)
if (method.equals(HttpMethod.DELETE))
builder.delete();
else {
System.err.println("making request @ "+address(path,port));
ClientResponse response = builder.method(method.name(),ClientResponse.class);
ClientResponse response = builder.method(method,ClientResponse.class);
//throws an exception if there response has error status
if (response.getStatus()>300)
throw new UniformInterfaceException(response);
throw new Exception(response.getStatus());
box.response=response;
}
} catch (UniformInterfaceException t) {
} catch (Exception t) {
box.failure=t;
}
@ -154,7 +159,7 @@ public class Request {
try {
if (!latch.await(2000, MILLISECONDS))
if (!latch.await(2000, TimeUnit.MILLISECONDS))
throw new RuntimeException("application has not responded in time");
} catch (InterruptedException e) {

@ -65,7 +65,7 @@ public class SomeApp {
private ApplicationConfiguration configuration;
private ApplicationHandlers handlers = new ApplicationHandlers();
private ApplicationExtensions extensions = new ApplicationExtensions();
private TestProvider provider = new TestProvider();
private TestProvider provider = new TestProvider(new File("src/test/resources/test-configuration.ini"));
private boolean deployHandlers = true;
private boolean deployExtensions = true;
private boolean deployConfiguration = true;

@ -1,37 +0,0 @@
package test;
import static junit.framework.Assert.*;
import java.io.ByteArrayInputStream;
import org.gcube.smartgears.configuration.library.SmartGearsConfiguration;
import org.gcube.smartgears.configuration.library.SmartGearsConfigurationBinder;
import org.junit.Test;
public class SmartgearsConfigurationTest {
@Test
public void configurationBinds() throws Exception {
String xml = "<smartgears version='1.0.0-SNAPSHOT'/>";
SmartGearsConfigurationBinder binder = new SmartGearsConfigurationBinder();
SmartGearsConfiguration bound = binder.bind(new ByteArrayInputStream(xml.getBytes()));
bound.validate();
String version = bound.version();
assertEquals("1.0.0-SNAPSHOT",version);
assertEquals(sampleSmartgearsConfiguration(),bound);
}
private SmartGearsConfiguration sampleSmartgearsConfiguration() {
return new SmartGearsConfiguration().version("1.0.0-SNAPSHOT");
}
}

@ -33,7 +33,7 @@ public class ProfileManagementTest {
@Test
public void createsStoresAndPublishesAValidProfile() throws Exception {
GCoreEndpoint profile = ctx.profile(GCoreEndpoint.class);
GCoreEndpoint profile = ctx.profile();
assertNotNull(profile);
@ -64,7 +64,7 @@ public class ProfileManagementTest {
ApplicationContext ctx = runtwice.start();
GCoreEndpoint profile = ctx.profile(GCoreEndpoint.class);
GCoreEndpoint profile = ctx.profile();
assertNotNull(profile);

@ -81,8 +81,8 @@ public class RemoteResourceTest {
GCoreEndpoint profile = Resources.unmarshal(GCoreEndpoint.class, new StringReader(outcome));
assertEquals(context.profile(GCoreEndpoint.class).id(), profile.id());
assertEquals(context.profile(GCoreEndpoint.class).profile().deploymentData().status(), profile.profile().deploymentData().status());
assertEquals(context.profile().id(), profile.id());
assertEquals(context.profile().profile().deploymentData().status(), profile.profile().deploymentData().status());
}

@ -27,7 +27,7 @@ import org.gcube.smartgears.handlers.application.ApplicationEvent;
import org.gcube.smartgears.handlers.application.ApplicationLifecycleEvent.Start;
import org.gcube.smartgears.handlers.application.ApplicationLifecycleHandler;
import org.gcube.smartgears.handlers.application.RequestHandler;
import org.gcube.smartgears.persistence.DefaultPersistence;
import org.gcube.smartgears.persistence.LocalPersistence;
import org.junit.After;
import org.junit.Test;
import org.mockito.Matchers;
@ -162,7 +162,7 @@ public class StartupTest {
public void canUseMergedConfiguration() {
ApplicationConfiguration config = new DefaultApplicationConfiguration();
config.persistence(new DefaultPersistence(new File(".").getAbsolutePath()));
config.persistence(new LocalPersistence(new File(".").getAbsolutePath()));
ApplicationContext context = app.start();

@ -35,7 +35,6 @@ public class ConfigurationTest {
StringWriter sw = new StringWriter();
ini.store(sw);
System.out.println(sw.toString());
}
}

@ -24,7 +24,7 @@ public class ProfileManagementTest {
ContainerContext ctx = startAppAndGetContainerContext();
HostingNode node = ctx.profile(HostingNode.class);
HostingNode node = ctx.profile();
assertNotNull(node);
@ -49,9 +49,9 @@ public class ProfileManagementTest {
ContainerContext ctx = runtwice.start().container();
assertNotNull(ctx.profile(HostingNode.class));
assertNotNull(ctx.profile());
HostingNode node = ctx.profile(HostingNode.class);
HostingNode node = ctx.profile();
Resources.validate(node);
}
@ -62,7 +62,7 @@ public class ProfileManagementTest {
SomeApp app = new SomeApp();
app.containerConfiguration().publicationFrequency(1);
//app.containerConfiguration().publicationFrequency(1);
ContainerContext ctx = app.start().container();

@ -43,7 +43,7 @@ public class StartupTest {
@Test(expected=RuntimeException.class)
public void failsIfConfigurationIsInvalid() {
app.containerConfiguration().hostname(null);
//app.containerConfiguration().hostname(null);
app.start();

@ -1,4 +1,4 @@
package test.container;
package utils;
import java.io.File;
@ -13,12 +13,12 @@ public class PersistenceWriterTest implements PersistenceWriter{
@Override
public File file(String path) {
return null;
return new File(location+"/"+path);
}
@Override
public File writefile(String path) {
return null;
return new File(location+"/"+path);
}
public String getLocation() {
@ -28,5 +28,10 @@ public class PersistenceWriterTest implements PersistenceWriter{
public void setLocation(String location) {
this.location = location;
}
@Override
public long getFreeSpace() {
return 0;
}
}

@ -1,17 +1,24 @@
package utils;
import java.io.File;
import javax.servlet.ServletContext;
import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.application.ApplicationExtensions;
import org.gcube.smartgears.configuration.application.ApplicationHandlers;
import org.gcube.smartgears.configuration.library.SmartGearsConfiguration;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.provider.DefaultProvider;
public class TestProvider extends DefaultProvider {
public TestProvider(File configFile) {
super(configFile);
}
public ApplicationContext context;
public ApplicationConfiguration configuration;
public ApplicationHandlers handlers;
@ -34,9 +41,18 @@ public class TestProvider extends DefaultProvider {
this.extensions=extensions;
}
@Override
public SmartGearsConfiguration smartgearsConfiguration() {
SmartGearsConfiguration conf = new SmartGearsConfiguration();
conf.version("0.0.1-TEST");
return conf ;
}
@Override
public ScopedPublisher publisherFor(ApplicationContext context) {
return publisher==null?super.publisherFor(context):publisher;
public ScopedPublisher publisher() {
return publisher==null?super.publisher():publisher;
}
@Override

@ -1,6 +1,6 @@
[node]
; mandatory
; optional fields: mode (online), publication-frequency-seconds (=60), authorizeChildrenContext (=false)
; optional fields: mode (=online), publication-frequency-seconds (=60), authorizeChildrenContext (=false)
mode = offline
hostname = localhost
protocol= https
@ -16,10 +16,9 @@ SmartGearsDistributionBundle = UnBundled
[site]
; mandatory
; optional fields: latitude, logitude
country = it
location = rome
latitude = 41.9000
longitude = 12.5000
[proxy]
; not mandatory
@ -29,7 +28,7 @@ port = 80
[authorization]
; mandatory
; optional fields: provider (org.gcube.smartgears.security.DefaultAuthorizationProvider)
; optional fields: provider (=org.gcube.smartgears.security.DefaultAuthorizationProvider)
provider = org.gcube.smartgears.security.DefaultAuthorizationProvider
credentials.class = org.gcube.smartgears.security.SimpleCredentials
credentials.clientID = testClient
@ -37,5 +36,5 @@ credentials.secret = testSecret
[persistence]
; not mandatory (default is LocalPersistence writing in the ghn home)
class = test.container.PersistenceWriterTest
location = /state
class = utils.PersistenceWriterTest
location = /tmp

Loading…
Cancel
Save