moving smartgears to a .ini Configuration file type

This commit is contained in:
Lucio Lelii 2022-03-17 17:17:15 +01:00
parent 515891e083
commit cf3c134953
39 changed files with 732 additions and 1002 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
/target/
/.classpath
/bin/
/bin/

View File

@ -2,6 +2,12 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
# Changelog for Common Smartgears
## [v4.0.0-SNAPSHOT]
## [v3.2.0-SNAPSHOT]
- Added SecretManagerProvider thread local from authorization-utils [#22871]

10
pom.xml
View File

@ -11,7 +11,7 @@
<groupId>org.gcube.core</groupId>
<artifactId>common-smartgears</artifactId>
<version>3.2.0-SNAPSHOT</version>
<version>4.0.0-SNAPSHOT</version>
<name>SmartGears</name>
<dependencyManagement>
@ -66,7 +66,7 @@
<groupId>org.gcube.common</groupId>
<artifactId>common-authorization</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-utils</artifactId>
@ -97,6 +97,12 @@
<artifactId>common-gcore-resources</artifactId>
</dependency>
<dependency>
<groupId>org.ini4j</groupId>
<artifactId>ini4j</artifactId>
<version>0.5.4</version>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-validator</artifactId>

View File

@ -28,7 +28,7 @@ public class Constants {
/**
* The container configuration file path, relative to the container configuration directory.
*/
public static final String container_configuraton_file_path = "container.xml";
public static final String container_configuraton_file_path = "smartgears-node.ini";
/**

View File

@ -0,0 +1,42 @@
package org.gcube.smartgears.configuration;
import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull;
public class ProxyAddress {
@NotNull @NotEmpty
String protocol = "http";
@NotNull @NotEmpty
String hostname;
@NotNull
Integer port;
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
}

View File

@ -2,8 +2,8 @@ package org.gcube.smartgears.configuration.application;
import java.util.Set;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.persistence.Persistence;
import org.gcube.smartgears.configuration.ProxyAddress;
import org.gcube.smartgears.persistence.PersistenceWriter;
/**
* The configuration of the application.
@ -13,15 +13,7 @@ import org.gcube.smartgears.persistence.Persistence;
*/
public interface ApplicationConfiguration {
/**
* Returns the management mode of the application.
* @return the management mode
*/
Mode mode();
/**
* Returns the context path of the application
* @return the context path
@ -37,14 +29,7 @@ public interface ApplicationConfiguration {
*/
ApplicationConfiguration context(String context);
/**
* Sets the management mode of this application.
* @param the management mode
* @return this configuration
*/
ApplicationConfiguration mode(Mode mode);
/**
* Returns the name of the application.
* @return the name
@ -102,25 +87,12 @@ public interface ApplicationConfiguration {
ApplicationConfiguration proxyAddress(ProxyAddress proxyaddress);
/**
* Returns the tokens in which the application operates when it first starts.
* @return the tokens
*/
Set<String> startTokens();
/**
* Sets the tokens in which the application operates when it first starts.
* @param scopes the scopes
* @return this configuration
*/
ApplicationConfiguration startTokens(Set<String> tokens);
/**
* Returns the persistence manager of the application.
* @return the manager
*/
Persistence persistence();
PersistenceWriter persistence();
/**
@ -141,7 +113,7 @@ public interface ApplicationConfiguration {
* @param manager the manager
* @return this configuration
*/
ApplicationConfiguration persistence(Persistence manager);
ApplicationConfiguration persistence(PersistenceWriter manager);
/**

View File

@ -1,14 +1,10 @@
package org.gcube.smartgears.configuration.application;
import static org.gcube.smartgears.configuration.Mode.offline;
import java.io.File;
import java.util.Set;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.ProxyAddress;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.persistence.DefaultPersistence;
import org.gcube.smartgears.persistence.Persistence;
import org.gcube.smartgears.persistence.PersistenceWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -21,25 +17,18 @@ public class BridgedApplicationConfiguration implements ApplicationConfiguration
private static Logger log = LoggerFactory.getLogger(ApplicationConfiguration.class);
private final ContainerConfiguration container;
private final ApplicationConfiguration application;
public BridgedApplicationConfiguration(ContainerConfiguration container, ApplicationConfiguration config) {
this.container=container;
this.application=config;
if (application.persistence()==null) {
String location = container.persistence().location()+"/"+application.name();
File dir = new File(location);
if (!dir.exists())
dir.mkdirs();
application.persistence(container.persistence());
application.persistence(new DefaultPersistence(location));
log.trace("setting persistence location for {} @ {}",application.name(), dir.getAbsolutePath());
log.trace("setting persistence location for {} the same as the container persistence",application.name());
}
}
@ -47,10 +36,6 @@ public class BridgedApplicationConfiguration implements ApplicationConfiguration
public ApplicationConfiguration inner() {
return application;
}
public Mode mode() {
return container.mode()==offline?offline:application.mode();
}
@Override
public String context() {
@ -98,17 +83,14 @@ public class BridgedApplicationConfiguration implements ApplicationConfiguration
return application.description(description);
}
public Persistence persistence() {
public PersistenceWriter persistence() {
return application.persistence();
}
public ApplicationConfiguration persistence(Persistence manager) {
public ApplicationConfiguration persistence(PersistenceWriter manager) {
return application.persistence(manager);
}
public ApplicationConfiguration mode(Mode mode) {
return application.mode(mode);
}
public void validate() {
@ -130,18 +112,7 @@ public class BridgedApplicationConfiguration implements ApplicationConfiguration
public void merge(ApplicationConfiguration config) {
application.merge(config);
}
@Override
public Set<String> startTokens() {
return application.startTokens();
}
@Override
public ApplicationConfiguration startTokens(Set<String> tokens) {
return application.startTokens(tokens);
}
@Override
public boolean proxied() {

View File

@ -7,20 +7,17 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.gcube.common.validator.ValidationError;
import org.gcube.common.validator.Validator;
import org.gcube.common.validator.ValidatorFactory;
import org.gcube.common.validator.annotations.IsValid;
import org.gcube.common.validator.annotations.NotNull;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.persistence.DefaultPersistence;
import org.gcube.smartgears.persistence.Persistence;
import org.gcube.smartgears.configuration.ProxyAddress;
import org.gcube.smartgears.persistence.PersistenceWriter;
/**
* The configuration of a managed app.
@ -34,11 +31,6 @@ import org.gcube.smartgears.persistence.Persistence;
@XmlRootElement(name="application")
public class DefaultApplicationConfiguration implements ApplicationConfiguration {
@XmlAttribute
private Mode mode = Mode.online;
@XmlAttribute(name="context")
String context;
@XmlElement(name="name" , required=true)
@ -52,14 +44,10 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
@XmlElement(name="version", required=true)
@NotNull
String version;
@XmlTransient
Set<String> tokens = new HashSet<String>();
@XmlElement(name="description")
String description="";
@XmlElementRef
@IsValid
ProxyAddress proxyAddress;
@ -68,10 +56,10 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
@XmlElementRef
Set<Include> includes= new LinkedHashSet<Include>();
@XmlElementRef(type=DefaultPersistence.class)
@NotNull @IsValid
private Persistence persistenceManager;
private PersistenceWriter persistenceManager;
@Override
public Set<Exclude> excludes() {
@ -85,12 +73,7 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
}
public DefaultApplicationConfiguration() {}
@Override
public Mode mode() {
return mode;
}
@Override
public String name() {
return name;
@ -152,16 +135,6 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
return this;
}
@Override
public Set<String> startTokens() {
return tokens;
}
@Override
public ApplicationConfiguration startTokens(Set<String> tokens) {
this.tokens.addAll(tokens);
return this;
}
@Override
public String description() {
@ -180,12 +153,12 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
}
@Override
public Persistence persistence() {
public PersistenceWriter persistence() {
return persistenceManager;
}
@Override
public ApplicationConfiguration persistence(Persistence manager) {
public ApplicationConfiguration persistence(PersistenceWriter manager) {
this.persistenceManager=manager;
return this;
}
@ -196,12 +169,7 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
return this;
}
@Override
public ApplicationConfiguration mode(Mode mode) {
this.mode=mode;
return this;
}
@Override
public void validate() {
@ -223,13 +191,9 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
@Override
public void merge(ApplicationConfiguration config) {
mode(config.mode());
if (config.persistence()!=null)
persistence(config.persistence());
//scopes.addAll(config.startScopes());
}

View File

@ -1,97 +0,0 @@
package org.gcube.smartgears.configuration.application;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.gcube.common.validator.annotations.NotNull;
@XmlRootElement(name="proxy")
public class ProxyAddress {
@XmlAttribute
String protocol = "http";
@XmlElement
@NotNull
String hostname;
@XmlElement
Integer port;
public String hostname() {
return hostname;
}
public ProxyAddress hostname(String hostname) {
this.hostname = hostname;
return this;
}
public Integer port() {
return port;
}
public ProxyAddress port(int port) {
this.port = port;
return this;
}
public String protocol() {
return protocol;
}
public ProxyAddress protocol(String protocol) {
this.protocol = protocol;
return this;
}
@Override
public String toString() {
return "ProxyAddress [protocol=" + protocol + ", hostname=" + hostname + ", port=" + port + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((hostname == null) ? 0 : hostname.hashCode());
result = prime * result + ((port == null) ? 0 : port.hashCode());
result = prime * result + ((protocol == null) ? 0 : protocol.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProxyAddress other = (ProxyAddress) obj;
if (hostname == null) {
if (other.hostname != null)
return false;
} else if (!hostname.equals(other.hostname))
return false;
if (port == null) {
if (other.port != null)
return false;
} else if (!port.equals(other.port))
return false;
if (protocol == null) {
if (other.protocol != null)
return false;
} else if (!protocol.equals(other.protocol))
return false;
return true;
}
}

View File

@ -0,0 +1,101 @@
package org.gcube.smartgears.configuration.container;
import static org.gcube.smartgears.Constants.default_container_publication_frequency_in_seconds;
import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull;
import org.gcube.smartgears.configuration.Mode;
public class BaseConfiguration {
Mode mode = Mode.online;
@NotNull @NotEmpty
String hostname;
@NotNull
Integer port;
@NotNull @NotEmpty
String protocol="http";
boolean authorizeChildrenContext = false;
@NotNull @NotEmpty
String infrastructure;
long publicationFrequencyInSeconds = default_container_publication_frequency_in_seconds;
public Mode getMode() {
return mode;
}
public String getHostname() {
return hostname;
}
public Integer getPort() {
return port;
}
public String getProtocol() {
return protocol;
}
public boolean isAuthorizeChildrenContext() {
return authorizeChildrenContext;
}
public String getInfrastructure() {
return infrastructure;
}
public long getPublicationFrequencyInSeconds() {
return publicationFrequencyInSeconds;
}
public void setPublicationFrequencyInSeconds(long publicationFrequencyInSeconds) {
this.publicationFrequencyInSeconds = publicationFrequencyInSeconds;
}
public void setMode(Mode mode) {
this.mode = mode;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public void setPort(Integer port) {
this.port = port;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public void setAuthorizeChildrenContext(boolean authorizeChildrenContext) {
this.authorizeChildrenContext = authorizeChildrenContext;
}
public void setInfrastructure(String infrastructure) {
this.infrastructure = infrastructure;
}
@Override
public String toString() {
return "BaseConfiguration [mode=" + mode + ", hostname=" + hostname + ", port=" + port + ", protocol="
+ protocol + ", authorizeChildrenContext=" + authorizeChildrenContext + ", infrastructure="
+ infrastructure + ", publicationFrequency=" + publicationFrequencyInSeconds
+ "]";
}
}

View File

@ -1,19 +1,17 @@
package org.gcube.smartgears.configuration.container;
import static org.gcube.smartgears.Constants.default_container_publication_frequency_in_seconds;
import static org.gcube.smartgears.utils.Utils.notNull;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.gcube.common.validator.ValidationError;
@ -23,10 +21,16 @@ import org.gcube.common.validator.annotations.IsValid;
import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.ProxyAddress;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.application.DefaultApplicationConfiguration;
import org.gcube.smartgears.persistence.DefaultPersistence;
import org.gcube.smartgears.persistence.Persistence;
import org.gcube.smartgears.persistence.LocalPersistence;
import org.gcube.smartgears.persistence.PersistenceWriter;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.gcube.smartgears.security.Credentials;
import org.gcube.smartgears.security.DefaultAuthorizationProvider;
import org.gcube.smartgears.utils.Utils;
import org.ini4j.Ini;
import org.ini4j.Profile.Section;
/**
* The configuration of the container.
@ -34,78 +38,45 @@ import org.gcube.smartgears.persistence.Persistence;
* @author Fabio Simeoni
* @author Luca Frosini (ISTI - CNR)
*/
@XmlRootElement(name="container")
public class ContainerConfiguration {
@XmlAttribute
private Mode mode = Mode.online;
@XmlElement
@NotNull @IsValid
String hostname;
@XmlElement
@NotNull
Integer port;
@XmlElement(name ="authentication-endpoint")
String authenticationEnpoint = null;
@XmlElement(name ="protocol")
@NotNull @IsValid
String protocol="http";
@XmlElement
boolean authorizeChildrenContext = false;
@XmlElement
@NotNull@IsValid
String infrastructure;
@XmlElement
@NotNull @IsValid
Site site;
@XmlElement(name="token")
@NotNull @NotEmpty
List<String> tokens = new ArrayList<String>();
@NotNull @IsValid
private BaseConfiguration baseConfiguration;
@IsValid
private Map<String,String> properties = new HashMap<String, String>();
@NotNull @IsValid
private Site site;
@IsValid
private ProxyAddress proxy;
@NotEmpty @NotNull
private String accountingFallbackLocation;
@XmlTransient
Set<String> allowedContext = new HashSet<String>();
private Set<String> allowedContext = new HashSet<String>();
private List<ApplicationConfiguration> apps = new ArrayList<ApplicationConfiguration>();
@NotNull @IsValid
private PersistenceWriter persistenceManager;
@NotNull @IsValid
private AuthorizationProvider authorizationProvider;
@XmlElementRef(type=DefaultApplicationConfiguration.class)
List<ApplicationConfiguration> apps = new ArrayList<ApplicationConfiguration>();
@XmlElement(name="property")
@IsValid
List<Property> properties = new ArrayList<Property>();
@XmlElement(name="publication-frequency")
long publicationFrequency = default_container_publication_frequency_in_seconds;
@XmlElementRef(type=DefaultPersistence.class)
@IsValid
private Persistence persistenceManager;
/**
* Returns the management mode for the container.
* @return the management mode
*/
public Mode mode() {
return mode;
return baseConfiguration.getMode();
}
/**
* Sets the management mode for the container.
* @param mode the management mode
* @return this configuration
*/
public ContainerConfiguration mode(Mode mode) {
this.mode=mode;
return this;
}
/**
* Returns the application configurations included in this configuration.
* @return the application configurations
@ -113,21 +84,21 @@ public class ContainerConfiguration {
public List<ApplicationConfiguration> apps() {
return apps;
}
/**
* Returns the configuration of an application with a given context path.
* @param context the context path
* @return the application configuration
*/
public ApplicationConfiguration app(String context) {
for (ApplicationConfiguration app : apps)
if (context.equals(app.context()))
return app;
return null;
}
/**
* Adds the configuration of an application to this configuration.
* @param app the application configuration
@ -146,7 +117,7 @@ public class ContainerConfiguration {
apps.add(app);
return this;
}
/**
* Returns the geographical site of the container.
* @return the site
@ -155,186 +126,96 @@ public class ContainerConfiguration {
return site;
}
/**
* Sets the geographical site of the container.
* @param site the site
* @return this configuration
*/
public ContainerConfiguration site(Site site) {
this.site=site;
return this;
}
/**
* Returns the infrastructure in which the container is running.
* @return the infrastructure
*/
public String infrastructure() {
return infrastructure;
return baseConfiguration.getInfrastructure();
}
/**
* Sets the infrastructure in which the container is running.
* @param infrastructure the infrastructure
* @return this configuration
*/
public ContainerConfiguration infrastructure(String infrastructure) {
this.infrastructure=infrastructure;
return this;
}
/**
* Returns the host name of the container.
* @return the host name;
*/
public String hostname() {
return hostname;
return baseConfiguration.getHostname();
}
/**
* Sets the host name of the container.
* @param name the host name
* @return this configuration
*/
public ContainerConfiguration hostname(String name) {
this.hostname=name;
return this;
}
/**
* Returns the port at which the container is listening for requests.
* @return the port
*/
public int port() {
return port;
return baseConfiguration.getPort();
}
/**
* Returns the port at which the container is listening for requests.
* @return the port
*/
public String protocol() {
return protocol;
}
public String authenticationEnpoint() {
return authenticationEnpoint;
}
public ContainerConfiguration authenticationEnpoint(String endpoint) {
this.authenticationEnpoint = endpoint;
return this;
return baseConfiguration.getProtocol();
}
/**
* Sets the port at which the container is listening for requests.
* @param port the port
* @return this configuration
*/
public ContainerConfiguration port(int port) {
this.port=port;
return this;
}
public ContainerConfiguration protocol(String protocol) {
this.protocol=protocol;
return this;
}
public boolean authorizeChildrenContext() {
return authorizeChildrenContext;
}
public ContainerConfiguration authorizeChildrenContext(boolean authorizeChildrenContext) {
this.authorizeChildrenContext = authorizeChildrenContext;
return this;
return baseConfiguration.isAuthorizeChildrenContext();
}
/**
* Returns the VOs in which the container initially operates.
* @return the VOs
* Returns the credentials.
* @return the credentials
*/
public List<String> startTokens() {
return tokens;
public AuthorizationProvider authorizationProvider() {
return authorizationProvider;
}
/**
* Sets the VOs in which the container initially operates.
* @param vos the VOs
* @return this configuration
* Returns the proxy of the container.
* @return the proxy
*/
public ContainerConfiguration startTokens(List<String> tokens) {
notNull("start Tokens",tokens);
this.tokens = tokens;
return this;
public ProxyAddress proxy() {
return proxy;
}
/**
* Returns the persistence manager of the container.
* @return the manager
*/
public Persistence persistence() {
public PersistenceWriter persistence() {
return persistenceManager;
}
/**
* Sets the persistence manager of the container.
* @param manager the manager
* @return this configuration
* Returns the persistence manager of the container.
* @return the manager
*/
public ContainerConfiguration persistence(Persistence manager) {
this.persistenceManager=manager;
return this;
public String accountingFallbackLocation() {
return accountingFallbackLocation;
}
/**
* Returns the configuration properties of the container.
* @return the properties
*/
public Map<String,String> properties() {
Map<String,String> map = new HashMap<String, String>();
for (Property prop : properties)
map.put(prop.name, prop.value);
return map;
return Collections.unmodifiableMap(properties);
}
/**
* Adds a configuration property to the container.
* @param the name of the property
* @param the value of the property
* @return this configuration
*/
public ContainerConfiguration property(String name, String value) {
properties.add(new Property(name, value));
return this;
}
/**
* Returns the publication frequency for the container's profile.
* @return the frquency;
*/
public long publicationFrequency() {
return publicationFrequency;
return baseConfiguration.getPublicationFrequencyInSeconds();
}
/**
* Sets the publication frequency for the container's profile.
* @param frequency the frequency
* @return this configuration
*/
public ContainerConfiguration publicationFrequency(long frequency) {
this.publicationFrequency=frequency;
return this;
}
public Set<String> allowedContexts() {
return allowedContext;
}
@ -353,7 +234,7 @@ public class ContainerConfiguration {
List<String> msgs = new ArrayList<String>();
Validator validator = ValidatorFactory.validator();
for (ValidationError error : validator.validate(this))
msgs.add(error.toString());
@ -362,159 +243,116 @@ public class ContainerConfiguration {
}
public static ContainerConfiguration load(InputStream stream) {
try {
Ini configurator = new Ini(stream);
ContainerConfiguration conf = new ContainerConfiguration();
Section nodeSection = configurator.get("node");
if (nodeSection != null ) {
BaseConfiguration nodeConf = new BaseConfiguration();
nodeSection.to(nodeConf);
conf.baseConfiguration = nodeConf;
}
Section propertiesSection = configurator.get("properties");
if (propertiesSection!=null)
conf.properties = propertiesSection.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
Section siteSection = configurator.get("site");
if (siteSection != null) {
Site siteConf = new Site();
siteSection.to(siteConf);
conf.site = siteConf;
}
initAuthorizationPart(configurator, conf);
initPersistencePart(configurator, conf);
initProxyPart(configurator, conf);
//TODO: find a solution for this shit
String location = Utils.home()+"/state";
File dir = new File(location);
if (!dir.exists())
dir.mkdirs();
conf.accountingFallbackLocation = location;
// END Shit
return conf;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void initProxyPart(Ini configurator, ContainerConfiguration conf) throws Exception{
Section proxySection = configurator.get("proxy");
if (proxySection != null) {
ProxyAddress proxyConf = new ProxyAddress();
proxySection.to(proxyConf);
conf.proxy = proxyConf;
}
}
private static void initPersistencePart(Ini configurator, ContainerConfiguration conf) throws Exception{
Section persistenceSection = configurator.get("persistence");
if (persistenceSection != null) {
String type = persistenceSection.get("class");
if (type ==null)
throw new Exception("ini file error: type not found in \"persistence\" section");
PersistenceWriter persistenceWriter;
try {
Object persistenceImpl = Class.forName(type).newInstance();
persistenceWriter = PersistenceWriter.class.cast(persistenceImpl);
}catch (Exception e) {
throw new Exception("ini file error: invalid persistence type in \"persistence\" section", e);
}
persistenceSection.to(persistenceWriter);
conf.persistenceManager = persistenceWriter;
} else {
String location = Utils.home()+"/state";
File dir = new File(location);
if (!dir.exists())
dir.mkdirs();
conf.persistenceManager = new LocalPersistence(location);
}
}
static class Property {
@XmlAttribute @NotNull
String name;
@XmlAttribute @NotNull
String value;
Property() {}
Property(String key, String value) {
this.name=key;
this.value=value;
private static void initAuthorizationPart(Ini configurator, ContainerConfiguration conf) throws Exception{
Section authorizationSection = configurator.get("authorization");
if (authorizationSection != null) {
String provider = authorizationSection.get("provider");
AuthorizationProvider authProvider;
if (provider!=null) {
try {
Object authProviderImpl = Class.forName(provider).newInstance();
authProvider = AuthorizationProvider.class.cast(authProviderImpl);
}catch (Exception e) {
throw new Exception("ini file error: invalid provider type in \"authorization\" section", e);
}
} else
authProvider = new DefaultAuthorizationProvider();
String type = authorizationSection.get("credentials.class");
if (type ==null)
throw new Exception("ini file error: credentials type not found in \"authorization\" section");
Credentials credentials;
try {
Object credentialsImpl = Class.forName(type).newInstance();
credentials = Credentials.class.cast(credentialsImpl);
}catch (Exception e) {
throw new Exception("ini file error: invalid credentials type in \"authorization\" section", e);
}
authorizationSection.to(credentials, "credentials.");
authProvider.connect(credentials);
conf.authorizationProvider = authProvider;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Property other = (Property) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((allowedContext == null) ? 0 : allowedContext.hashCode());
result = prime * result + ((apps == null) ? 0 : apps.hashCode());
result = prime * result + ((authenticationEnpoint == null) ? 0 : authenticationEnpoint.hashCode());
result = prime * result + (authorizeChildrenContext ? 1231 : 1237);
result = prime * result + ((hostname == null) ? 0 : hostname.hashCode());
result = prime * result + ((infrastructure == null) ? 0 : infrastructure.hashCode());
result = prime * result + ((mode == null) ? 0 : mode.hashCode());
result = prime * result + ((persistenceManager == null) ? 0 : persistenceManager.hashCode());
result = prime * result + ((port == null) ? 0 : port.hashCode());
result = prime * result + ((properties == null) ? 0 : properties.hashCode());
result = prime * result + ((protocol == null) ? 0 : protocol.hashCode());
result = prime * result + (int) (publicationFrequency ^ (publicationFrequency >>> 32));
result = prime * result + ((site == null) ? 0 : site.hashCode());
result = prime * result + ((tokens == null) ? 0 : tokens.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ContainerConfiguration other = (ContainerConfiguration) obj;
if (allowedContext == null) {
if (other.allowedContext != null)
return false;
} else if (!allowedContext.equals(other.allowedContext))
return false;
if (apps == null) {
if (other.apps != null)
return false;
} else if (!apps.equals(other.apps))
return false;
if (authenticationEnpoint == null) {
if (other.authenticationEnpoint != null)
return false;
} else if (!authenticationEnpoint.equals(other.authenticationEnpoint))
return false;
if (authorizeChildrenContext != other.authorizeChildrenContext)
return false;
if (hostname == null) {
if (other.hostname != null)
return false;
} else if (!hostname.equals(other.hostname))
return false;
if (infrastructure == null) {
if (other.infrastructure != null)
return false;
} else if (!infrastructure.equals(other.infrastructure))
return false;
if (mode != other.mode)
return false;
if (persistenceManager == null) {
if (other.persistenceManager != null)
return false;
} else if (!persistenceManager.equals(other.persistenceManager))
return false;
if (port == null) {
if (other.port != null)
return false;
} else if (!port.equals(other.port))
return false;
if (properties == null) {
if (other.properties != null)
return false;
} else if (!properties.equals(other.properties))
return false;
if (protocol == null) {
if (other.protocol != null)
return false;
} else if (!protocol.equals(other.protocol))
return false;
if (publicationFrequency != other.publicationFrequency)
return false;
if (site == null) {
if (other.site != null)
return false;
} else if (!site.equals(other.site))
return false;
if (tokens == null) {
if (other.tokens != null)
return false;
} else if (!tokens.equals(other.tokens))
return false;
return true;
}
@Override
public String toString() {
return "ContainerConfiguration [mode=" + mode + ", hostname=" + hostname + ", port=" + port + ", authenticationEnpoint=" + authenticationEnpoint + ", protocol=" + protocol
+ ", authorizeChildrenContext=" + authorizeChildrenContext + ", infrastructure=" + infrastructure
+ ", site=" + site + ", tokens=" + tokens + ", allowedContext=" + allowedContext + ", apps=" + apps
+ ", properties=" + properties + ", publicationFrequency=" + publicationFrequency
+ ", persistenceManager=" + persistenceManager + "]";
}
}

View File

@ -1,8 +1,5 @@
package org.gcube.smartgears.configuration.container;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.gcube.common.validator.annotations.NotNull;
/**
@ -11,97 +8,52 @@ import org.gcube.common.validator.annotations.NotNull;
* @author Fabio Simeoni
*
*/
@XmlRootElement(name="site")
public class Site {
@XmlElement
@NotNull
String country;
@XmlElement
@NotNull
String location;
@XmlElement
@NotNull
String latitude;
@XmlElement
@NotNull
String longitude;
/**
* Returns the country.
* @return the country
*/
public String country() {
public String getCountry() {
return country;
}
/**
* Sets the country.
* @param the country
* @return this configuration
*/
public Site country(String country) {
this.country=country;
return this;
}
/**
* Returns the latitude.
* @return the latitude
*/
public String latitude() {
return latitude;
public void setCountry(String country) {
this.country = country;
}
/**
* Sets the latitude.
* @param the latitude
* @return this configuration
*/
public Site latitude(String latitude) {
this.latitude=latitude;
return this;
}
/**
* Returns the longitude.
* @return the longitude
*/
public String longitude() {
return longitude;
}
/**
* Sets the longitude.
* @param the longitude
* @return this configuration
*/
public Site longitude(String longitude) {
this.longitude=longitude;
return this;
}
/**
* Returns the location.
* @return the location
*/
public String location() {
public String getLocation() {
return location;
}
/**
* Sets the location.
* @param the location
* @return this location
*/
public Site location(String location) {
this.location=location;
return this;
public void setLocation(String location) {
this.location = location;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
@Override

View File

@ -7,7 +7,7 @@ import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.context.Properties;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.persistence.Persistence;
import org.gcube.smartgears.persistence.PersistenceWriter;
/**
* The management context of an application.
@ -56,7 +56,7 @@ public interface ApplicationContext {
*
* @return the manager
*/
Persistence persistence();
PersistenceWriter persistence();
/**
* Returns the servlet context of the application.

View File

@ -10,7 +10,7 @@ import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.context.Properties;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.persistence.Persistence;
import org.gcube.smartgears.persistence.PersistenceWriter;
/**
* Default {@link ApplicationContext} implementation.
@ -96,7 +96,7 @@ public class DefaultApplicationContext implements ApplicationContext {
}
@Override
public Persistence persistence() {
public PersistenceWriter persistence() {
return configuration.persistence();
}

View File

@ -4,7 +4,7 @@ import org.gcube.common.events.Hub;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.context.Properties;
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
import org.gcube.smartgears.persistence.Persistence;
import org.gcube.smartgears.persistence.PersistenceWriter;
/**
* The management context of the container.
@ -43,7 +43,7 @@ public interface ContainerContext {
* Returns the persistence manager of the container.
* @return the manager
*/
Persistence persistence();
PersistenceWriter persistence();
/**
* Returns the properties of the container.

View File

@ -1,12 +1,13 @@
package org.gcube.smartgears.context.container;
import static org.gcube.smartgears.Constants.*;
import static org.gcube.smartgears.Constants.container_profile_property;
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;
import org.gcube.smartgears.persistence.Persistence;
import org.gcube.smartgears.persistence.PersistenceWriter;
/**
* Default {@link ContainerContext} implementation.
@ -62,7 +63,7 @@ public class DefaultContainerContext implements ContainerContext {
}
@Override
public Persistence persistence() {
public PersistenceWriter persistence() {
return configuration.persistence();
}

View File

@ -48,10 +48,10 @@ public class ProfileBuilder {
String baseAddress;
if (configuration.proxied()){
String protocol = configuration.proxyAddress().protocol();
String port = configuration.proxyAddress().port()!=null?":"+configuration.proxyAddress().port():"";
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,context.application().getContextPath());
baseAddress=String.format("%s://%s%s%s", protocol , configuration.proxyAddress().getHostname(), port,context.application().getContextPath());
} else {
String protocol = container.protocol();
int port = container.port();

View File

@ -8,14 +8,15 @@ 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.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;
@ -37,7 +38,7 @@ public class ProfilePublisherImpl implements ProfilePublisher {
private final ApplicationContext context;
private AuthorizationProxy authProxy ;
private AuthorizationProvider authProxy ;
/**
* Creates an instance for a given application.
@ -46,7 +47,7 @@ public class ProfilePublisherImpl implements ProfilePublisher {
public ProfilePublisherImpl(ApplicationContext context) {
this.context = context;
this.publisher=ProviderFactory.provider().publisherFor(context);
this.authProxy = ProviderFactory.provider().authorizationProxy();
this.authProxy = context.container().configuration().authorizationProvider();
}
/**
@ -54,9 +55,9 @@ public class ProfilePublisherImpl implements ProfilePublisher {
* @param scopes the scopes
*/
@Override
public void addTo(Collection<String> tokens) {
public void addTo(Collection<String> contexts) {
notEmpty("tokens",tokens);
notEmpty("tokens",contexts);
GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
@ -87,16 +88,19 @@ public class ProfilePublisherImpl implements ProfilePublisher {
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.set((String)tokens.toArray()[0]);
if (previousToken!=null)
SecurityTokenProvider.instance.reset();;
if (context.container().configuration().mode()!=Mode.root) Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
profile = publisher.create(profile, resolveScopesFromTokens(tokens));
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);
}
@ -106,7 +110,7 @@ public class ProfilePublisherImpl implements ProfilePublisher {
@Override
public void addToAll() {
this.addTo(context.configuration().startTokens());
this.addTo(context.configuration().allowedContexts());
}
@ -115,33 +119,16 @@ public class ProfilePublisherImpl implements ProfilePublisher {
GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
/* TODO: reintroduce it when scope will be removed
String previousToken = SecurityTokenProvider.instance.get();
try {
for (String token: context.configuration().startTokens()){
SecurityTokenProvider.instance.set(token);
profile = publisher.update(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.set((String)context.configuration().startTokens().toArray()[0]);
if (previousToken!=null)
SecurityTokenProvider.instance.reset();
if (context.container().configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
@ -151,6 +138,7 @@ public class ProfilePublisherImpl implements ProfilePublisher {
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
ScopeProvider.instance.set(previousScope);
if (context.container().configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(contextCL);
}
@ -164,46 +152,28 @@ public class ProfilePublisherImpl implements ProfilePublisher {
* @param scopes the scopes
*/
@Override
public void removeFrom(Collection<String> tokens) {
public void removeFrom(Collection<String> contexts) {
GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
/* 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();
}
}
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.set((String)tokens.toArray()[0]);
if (previousToken!=null)
SecurityTokenProvider.instance.reset();
if (context.container().configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
profile = publisher.remove(profile, resolveScopesFromTokens(tokens));
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);
}

View File

@ -8,8 +8,8 @@ import org.gcube.accounting.datamodel.UsageRecord.OperationResult;
import org.gcube.accounting.datamodel.usagerecords.ServiceUsageRecord;
import org.gcube.accounting.persistence.AccountingPersistence;
import org.gcube.accounting.persistence.AccountingPersistenceFactory;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.smartgears.Constants;
import org.gcube.smartgears.configuration.Mode;
@ -46,7 +46,7 @@ public class RequestAccounting extends RequestHandler {
calledMethod= e.request().getMethod()+" "+calledMethod;
}
InnerMethodName.instance.set(calledMethod);
String caller = AuthorizationProvider.instance.get()!=null? AuthorizationProvider.instance.get().getClient().getId(): "UNKNOWN";
String caller = SecretManagerProvider.instance.get().getUser().getUsername();
startCallThreadLocal.set(System.currentTimeMillis());
log.info("REQUEST START ON {}:{}({}) CALLED FROM {}@{} IN SCOPE {} ",
context.configuration().name(),context.configuration().serviceClass(), InnerMethodName.instance.get(),
@ -65,8 +65,8 @@ public class RequestAccounting extends RequestHandler {
resetScope = true;
}
String caller = AuthorizationProvider.instance.get()!=null? AuthorizationProvider.instance.get().getClient().getId(): "UNKNOWN";
String callerQualifier = AuthorizationProvider.instance.get()!=null? AuthorizationProvider.instance.get().getTokenQualifier(): "UNKNOWN";
String caller = SecretManagerProvider.instance.get().getUser().getUsername();
String callerQualifier = "UNKNOWN";
//retieves caller Ip when there is a proxy
String callerIp = e.request().getHeader("x-forwarded-for");
if(callerIp==null)
@ -87,7 +87,7 @@ public class RequestAccounting extends RequestHandler {
}
void generateAccounting(String caller, String callerQualifier, String remoteHost, boolean success, ApplicationContext context){
AccountingPersistenceFactory.setFallbackLocation(context.container().persistence().location());
AccountingPersistenceFactory.setFallbackLocation(context.container().configuration().accountingFallbackLocation());
AccountingPersistence persistence = AccountingPersistenceFactory.getPersistence();
ServiceUsageRecord serviceUsageRecord = new ServiceUsageRecord();
try{

View File

@ -14,9 +14,9 @@ import org.gcube.common.authorization.library.PolicyUtils;
import org.gcube.common.authorization.library.policies.Policy;
import org.gcube.common.authorization.library.policies.User2ServicePolicy;
import org.gcube.common.authorization.library.policies.UserEntity;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.provider.ServiceIdentifier;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.scope.impl.ScopeBean.Type;
@ -39,7 +39,7 @@ public class RequestValidator extends RequestHandler {
private static Logger log = LoggerFactory.getLogger(RequestValidator.class);
private ApplicationContext context;
private ApplicationContext appContext;
@Override
public String getName() {
@ -51,13 +51,13 @@ public class RequestValidator extends RequestHandler {
log.trace("executing request validator ON REQUEST");
context = call.context();
appContext = call.context();
validateAgainstLifecycle(call);
rejectUnauthorizedCalls(call);
if (context.container().configuration().mode()!=Mode.offline) {
if (appContext.container().configuration().mode()!=Mode.offline) {
validateScopeCall();
validatePolicy(ScopeProvider.instance.get(), call);
}
@ -66,7 +66,7 @@ public class RequestValidator extends RequestHandler {
private void validateAgainstLifecycle(RequestEvent call) {
switch(context.lifecycle().state()) {
switch(appContext.lifecycle().state()) {
case stopped :
application_unavailable_error.fire(); break;
@ -86,28 +86,28 @@ public class RequestValidator extends RequestHandler {
String scope = ScopeProvider.instance.get();
if (scope == null) {
log.warn("rejecting unscoped call to {}",context.name());
log.warn("rejecting unscoped call to {}",appContext.name());
invalid_request_error.fire("call is unscoped");
}
ScopeBean bean = new ScopeBean(scope);
ContainerConfiguration conf = context.container().configuration();
ContainerConfiguration conf = appContext.container().configuration();
if (!conf.allowedContexts().contains(scope) &&
!(conf.authorizeChildrenContext() && bean.is(Type.VRE) && conf.allowedContexts().contains(bean.enclosingScope().toString()) ) ) {
log.warn("rejecting call to {} in invalid context {}, allowed context are {}",context.name(),scope,context.container().configuration().allowedContexts());
invalid_request_error.fire(context.name()+" cannot be called in scope "+scope);
log.warn("rejecting call to {} in invalid context {}, allowed context are {}",appContext.name(),scope,appContext.container().configuration().allowedContexts());
invalid_request_error.fire(appContext.name()+" cannot be called in scope "+scope);
}
}
private void rejectUnauthorizedCalls(RequestEvent call){
String token = SecurityTokenProvider.instance.get();
String scope = ScopeProvider.instance.get();
String context = SecretManagerProvider.instance.get().getContext();
if (token == null && scope==null){
log.warn("rejecting call to {}, authorization required",context.name(),token);
RequestError.request_not_authorized_error.fire(context.name()+": authorization required");
if (token == null && context==null){
log.warn("rejecting call to {}, authorization required",appContext.name(),token);
RequestError.request_not_authorized_error.fire(appContext.name()+": authorization required");
}
}
@ -121,7 +121,7 @@ public class RequestValidator extends RequestHandler {
ServiceIdentifier serviceIdentifier = Utils.getServiceInfo(call.context()).getServiceIdentifier();
String callerId = AuthorizationProvider.instance.get().getClient().getId();
String callerId = SecretManagerProvider.instance.get().getUser().getUsername();
List<Policy> policies = null;
try {
@ -142,8 +142,8 @@ public class RequestValidator extends RequestHandler {
toReject = true;
else toReject = !entity.getExcludes().contains(callerId);
if (toReject) {
log.error("rejecting call to {} : {} is not allowed to contact the service ",context.name(), callerId);
RequestError.request_not_authorized_error.fire("rejecting call to "+context.name()+" for polices: "+callerId+" is not allowed to contact the service: "+serviceIdentifier.getServiceName() );
log.error("rejecting call to {} : {} is not allowed to contact the service ",appContext.name(), callerId);
RequestError.request_not_authorized_error.fire("rejecting call to "+appContext.name()+" for polices: "+callerId+" is not allowed to contact the service: "+serviceIdentifier.getServiceName() );
}
}

View File

@ -97,7 +97,7 @@ public class ProfileBuilder {
//
// file system
node.profile().description().localFileSystems().add().name("").type("").readOnly(false)
.root(cfg.persistence().location());
.root("/");
return node;
}
@ -192,7 +192,7 @@ public class ProfileBuilder {
private long getFreeSpace() {
long free = 0;
try {
free = Files.getFileStore(Paths.get(context.configuration().persistence().location())).getUsableSpace()/1024;
free = context.configuration().persistence().getFreeSpace()/1024;
} catch (IOException ioe) {
log.warn("unable to detect the free space on the disk", ioe);
}

View File

@ -23,10 +23,7 @@ import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.events.Observes;
import org.gcube.smartgears.Constants;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.application.ApplicationExtensions;
import org.gcube.smartgears.configuration.application.ApplicationHandlers;
@ -34,14 +31,12 @@ import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.extensions.ApplicationExtension;
import org.gcube.smartgears.extensions.RequestExceptionBarrier;
import org.gcube.smartgears.handlers.ProfileEvents;
import org.gcube.smartgears.handlers.application.ApplicationLifecycleEvent;
import org.gcube.smartgears.handlers.application.ApplicationLifecycleHandler;
import org.gcube.smartgears.handlers.application.ApplicationPipeline;
import org.gcube.smartgears.handlers.application.RequestHandler;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
import org.gcube.smartgears.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -143,41 +138,6 @@ public class ApplicationManager {
}
private List<String> generateTokensForApplication(ContainerContext container){
log.info("generating token for app {}",context.configuration().name());
SecurityTokenProvider.instance.set(container.configuration().startTokens().get(0));
try {
AuthorizationProxy authProxy = provider().authorizationProxy();
try {
return authProxy.generateServiceToken(Utils.getServiceInfo(context), container.configuration().startTokens());
}catch (Exception e) {
log.error("error generating service token",e);
throw new RuntimeException(e);
}
} catch (Exception e) {
throw new RuntimeException("error contacting authorization service",e);
} finally{
SecurityTokenProvider.instance.reset();
}
}
private String generateApplicationToken(String containerToken, AuthorizationProxy authProxy){
SecurityTokenProvider.instance.set(containerToken);
try {
log.info("generating token for app {} with container token {} ",context.configuration().name(), containerToken);
return authProxy.generateServiceToken(Utils.getServiceInfo(context));
} catch (Exception e) {
throw new RuntimeException("error contacting authorization service",e);
} finally{
SecurityTokenProvider.instance.reset();
}
}
private void saveApplicationState() {
File file = context.configuration().persistence().file(profile_file_path);
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))){
@ -320,28 +280,6 @@ public class ApplicationManager {
log.warn("cannot stop {} after container has stopped", context.name());
}
@Observes(value = ContextEvents.ADD_TOKEN_TO_APPLICATION, kind = critical)
void onAddToken(String containerToken) {
log.trace("event add received with token {} ",containerToken);
String appToken = generateApplicationToken(containerToken, provider().authorizationProxy());
context.configuration().startTokens().add(appToken);
log.trace("app token created : {} ", appToken);
context.events().fire(appToken, ProfileEvents.addToContext);
context.events().fire(appToken, Constants.token_registered);
saveApplicationState();
}
@Observes(value = ContextEvents.REMOVE_TOKEN_FROM_APPLICATION, kind = critical)
void onRemoveToken(String containerToken) {
log.trace("event remove received with token {} ",containerToken);
String appToken = generateApplicationToken(containerToken, provider().authorizationProxy());
context.configuration().startTokens().remove(appToken);
log.trace("app token removed : {} ", appToken);
context.events().fire(appToken, ProfileEvents.removeFromContext);
context.events().fire(appToken, Constants.token_removed);
saveApplicationState();
}
};
context.container().events().subscribe(observer);

View File

@ -31,6 +31,8 @@ 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;
@ -47,7 +49,7 @@ public class ContainerManager {
public static ContainerManager instance = new ContainerManager();
private AuthorizationProxy authProvider = provider().authorizationProxy();
private AuthorizationProvider authProvider = provider().authorizationProxy();
private ContainerContext context;
@ -101,7 +103,6 @@ public class ContainerManager {
File file = context.configuration().persistence().file(container_profile_file_path);
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))){
oos.writeObject(context.id());
oos.writeObject(context.configuration().startTokens());
}catch (Exception e) {
log.error("error serializing cointainer state");
throw new RuntimeException(e);
@ -113,7 +114,9 @@ public class ContainerManager {
//List<String> tokensToRemove = new ArrayList<String>();
context.configuration().validate();
Set<String> foundContexts= new HashSet<String>();
Credentials credential = context.configuration().credentials();
try {
List<AuthorizationEntry> entries = authProvider.get(context.configuration().startTokens());

View File

@ -2,12 +2,9 @@ package org.gcube.smartgears.managers;
public class ContextEvents {
public static final String ADD_TOKEN_TO_CONTAINER ="AddTokenToContainer";
public static final String ADD_CONTEXT_TO_CONTAINER ="AddContextToContainer";
public static final String ADD_TOKEN_TO_APPLICATION ="AddTokenToApplication";
public static final String REMOVE_CONTEXT_FROM_CONTAINER ="RemoveContextFromContainer";
public static final String REMOVE_TOKEN_FROM_CONTAINER ="RemoveTokenFromContainer";
public static final String REMOVE_TOKEN_FROM_APPLICATION ="RemoveTokenFromApplication";
}

View File

@ -1,96 +0,0 @@
package org.gcube.smartgears.persistence;
import static org.gcube.smartgears.utils.Utils.*;
import java.io.File;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.gcube.common.validator.annotations.NotNull;
@XmlRootElement(name="persistence")
public class DefaultPersistence implements Persistence {
@XmlAttribute(name="location") @NotNull
private String location;
public DefaultPersistence() {}
public DefaultPersistence(String location) {
notNull("persistence location",location);
this.location=location;
validate();
}
@Override
public String location() {
return location;
}
@Override
public File writefile(String path) {
notNull("relative path", path);
return fileAt(new File(location, path).getAbsolutePath()).toWrite();
}
@Override
public File file(String path) {
notNull("relative path", path);
return fileAt(new File(location, path).getAbsolutePath()).toRead();
}
//called after JAXB unmarshalling to purge unavailable handlers
void afterUnmarshal(Unmarshaller u, Object parent) {
validate();
}
public void validate() {
File locationDir = new File(location);
if (!(locationDir.exists() && locationDir.isDirectory() && locationDir.canRead() && locationDir.canWrite()))
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 int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((location == null) ? 0 : location.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DefaultPersistence other = (DefaultPersistence) obj;
if (location == null) {
if (other.location != null)
return false;
} else if (!location.equals(other.location))
return false;
return true;
}
@Override
public String toString() {
return "local persistence in "+location;
}
}

View File

@ -0,0 +1,65 @@
package org.gcube.smartgears.persistence;
import static org.gcube.smartgears.utils.Utils.fileAt;
import static org.gcube.smartgears.utils.Utils.notNull;
import java.io.File;
import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull;
public class LocalPersistence implements PersistenceWriter {
@NotNull @NotEmpty
private String location;
protected LocalPersistence() {}
public LocalPersistence(String location) {
notNull("persistence location",location);
this.location=location;
validate();
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
@Override
public File writefile(String path) {
notNull("relative path", path);
return fileAt(new File(location, path).getAbsolutePath()).toWrite();
}
@Override
public File file(String path) {
notNull("relative path", path);
return fileAt(new File(location, path).getAbsolutePath()).toRead();
}
void initialize(){
}
public void validate() {
File locationDir = new File(location);
if (!(locationDir.exists() && locationDir.isDirectory() && locationDir.canRead() && locationDir.canWrite()))
throw new IllegalStateException("invalid node configuration: home "+location+" does not exist or is not a directory or cannot be accessed in read/write mode");
}
}

View File

@ -2,12 +2,12 @@ package org.gcube.smartgears.persistence;
import java.io.File;
public interface Persistence {
String location();
public interface PersistenceWriter {
File file(String path);
File writefile(String path);
long getFreeSpace();
}

View File

@ -221,7 +221,6 @@ public class DefaultProvider implements Provider {
}
}
// TODO we can check scopes here instead of in BridgedApplicationConfiguration constructor
ApplicationConfiguration bridgedConfiguration = new BridgedApplicationConfiguration(context.configuration(),
configuration);

View File

@ -10,6 +10,7 @@ import org.gcube.smartgears.configuration.container.ContainerHandlers;
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.security.AuthorizationProvider;
/**
* Provides dependencies for container and application management.
@ -84,6 +85,6 @@ public interface Provider {
* @param application the context of the application
* @return the publisher implementation
*/
AuthorizationProxy authorizationProxy();
AuthorizationProvider authorizationProxy();
}

View File

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

View File

@ -0,0 +1,5 @@
package org.gcube.smartgears.security;
public interface Credentials {
}

View File

@ -0,0 +1,14 @@
package org.gcube.smartgears.security;
public class DefaultAuthorizationProvider implements AuthorizationProvider {
SimpleCredentials credentials;
@Override
public void connect(Credentials credentials) {
this.credentials = (SimpleCredentials)credentials;
}
}

View File

@ -0,0 +1,67 @@
package org.gcube.smartgears.security;
import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull;
public class SimpleCredentials implements Credentials{
@NotNull @NotEmpty
String clientID;
@NotNull @NotEmpty
String secret;
public String getClientID() {
return clientID;
}
public void setClientID(String clientID) {
this.clientID = clientID;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((clientID == null) ? 0 : clientID.hashCode());
result = prime * result + ((secret == null) ? 0 : secret.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SimpleCredentials other = (SimpleCredentials) obj;
if (clientID == null) {
if (other.clientID != null)
return false;
} else if (!clientID.equals(other.clientID))
return false;
if (secret == null) {
if (other.secret != null)
return false;
} else if (!secret.equals(other.secret))
return false;
return true;
}
@Override
public String toString() {
return "SimpleCredentials [clientID=" + clientID + ", secret=" + secret + "]";
}
}

View File

@ -10,6 +10,7 @@ import static utils.TestUtils.location;
import static utils.TestUtils.servlet_name;
import java.io.File;
import java.io.InputStream;
import org.apache.catalina.Wrapper;
import org.apache.catalina.core.StandardContext;
@ -18,13 +19,11 @@ import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.scan.StandardJarScanner;
import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.smartgears.Constants;
import org.gcube.smartgears.configuration.Mode;
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.application.DefaultApplicationConfiguration;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.configuration.container.Site;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.managers.ContainerManager;
import org.gcube.smartgears.provider.ProviderFactory;
@ -249,8 +248,7 @@ public class SomeApp {
if (clean)
cleanupInstallation();
installContainerConfiguration();
if (deployConfiguration)
deployConfiguration();
@ -283,7 +281,7 @@ public class SomeApp {
webapp.setServlet(new TestServlet(test));
context.container().configuration().port(port());
//context.container().configuration().port(port());
containerConfiguration = context.container().configuration();
}
@ -343,14 +341,7 @@ public class SomeApp {
}
// helpers
/**
* Installs the container configuration.
*/
private void installContainerConfiguration() {
TestUtils.serialise(containerConfiguration(),containerConfigurationFile());
}
/**
* Includes the configuration in the application's WAR.
@ -411,17 +402,15 @@ public class SomeApp {
private ApplicationConfiguration defaultConfiguration() {
return new DefaultApplicationConfiguration().mode(Mode.offline).serviceClass("test-class").name("test-app").version("1.0");
return new DefaultApplicationConfiguration().serviceClass("test-class").name("test-app").version("1.0");
}
private ContainerConfiguration defaultContainerConfiguration() {
return new ContainerConfiguration().mode(Mode.offline).hostname("localhost").port(port()).infrastructure("gcube")
.site(new Site().country("it").location("rome").latitude("41.9000").longitude("12.5000"))
.property("test-prop1","foo")
.property("test-prop2","bar")
.publicationFrequency(5);
InputStream is = SomeApp.class.getResourceAsStream("/test-configuration.ini");
return ContainerConfiguration.load(is);
}

View File

@ -5,14 +5,13 @@ import static junit.framework.Assert.assertNotNull;
import java.io.ByteArrayInputStream;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.application.ApplicationConfigurationBinder;
import org.gcube.smartgears.configuration.application.ApplicationExtensions;
import org.gcube.smartgears.configuration.application.DefaultApplicationConfiguration;
import org.gcube.smartgears.configuration.application.Include;
import org.gcube.smartgears.extensions.ApplicationExtension;
import org.gcube.smartgears.persistence.DefaultPersistence;
import org.gcube.smartgears.persistence.LocalPersistence;
import org.junit.Test;
public class ConfigurationTest {
@ -99,14 +98,13 @@ public class ConfigurationTest {
return new DefaultApplicationConfiguration()
.mode(Mode.offline)
.context("ctx")
.name("name")
.serviceClass("class")
.includes(new Include("/pathBis"))
.version("version")
.description("desc")
.persistence(new DefaultPersistence("target"));
.persistence(new LocalPersistence("target"));
}

View File

@ -1,19 +1,10 @@
package test.container;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import java.io.StringWriter;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.List;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.application.DefaultApplicationConfiguration;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.configuration.container.ContainerConfigurationBinder;
import org.gcube.smartgears.configuration.container.Site;
import org.gcube.smartgears.persistence.DefaultPersistence;
import org.ini4j.Ini;
import org.ini4j.Profile.Section;
import org.junit.Test;
public class ConfigurationTest {
@ -21,51 +12,30 @@ public class ConfigurationTest {
@Test
public void containerConfigurationBinds() throws Exception {
String appXml = "<application mode='offline'>" + "<name>name</name>" + "<group>class</group>"
+ "<version>version</version>" + "<description>desc</description>" + "<persistence location='target'/>"
+ "</application>";
String xml = "<container mode='offline'>"
+ "<hostname>localhost</hostname>"
+ "<port>8080</port>"
+ "<infrastructure>gcube</infrastructure>"
+ "<authorizeChildrenContext>true</authorizeChildrenContext> "
+"<token>token1</token>" + "<token>token2</token>" + "<persistence location='target'/>" + appXml + "<site>"
+ "<country>it</country>" + "<location>rome</location>" + "<latitude>41.9000</latitude>"
+ "<longitude>12.5000</longitude>" + "</site>" + "<property name='prop1' value='val1' />"
+ "<property name='prop2' value='val2' />" + "<publication-frequency>30</publication-frequency>"
+ "</container>";
ContainerConfigurationBinder binder = new ContainerConfigurationBinder();
ContainerConfiguration bound = binder.bind(new ByteArrayInputStream(xml.getBytes()));
ContainerConfiguration bound = ContainerConfiguration
.load(ConfigurationTest.class.getResourceAsStream("/test-configuration.ini"));
bound.validate();
List<String> scopes = bound.startTokens();
assertTrue(scopes.contains("token1"));
assertTrue(scopes.contains("token2"));
assertEquals(sampleContainerConfiguration(), bound);
}
private ContainerConfiguration sampleContainerConfiguration() {
@Test
public void iniStore() throws Exception {
Ini ini = new Ini();
return new ContainerConfiguration().mode(Mode.offline).hostname("localhost").port(8080).infrastructure("gcube")
.startTokens(Arrays.asList("token1", "token2"))
.site(new Site().country("it").location("rome").latitude("41.9000").longitude("12.5000"))
.property("prop1", "val1").property("prop2", "val2").publicationFrequency(30)
.app(sampleAppConfiguration()).authorizeChildrenContext(true)
.persistence(new DefaultPersistence("target"));
}
private ApplicationConfiguration sampleAppConfiguration() {
return new DefaultApplicationConfiguration().mode(Mode.offline).name("name").serviceClass("class")
.version("version").description("desc").persistence(new DefaultPersistence("target"));
// lets add a section, it will create needed intermediate sections as well
ini.add("root/child/sub");
Section rsec = ini.get("root");
rsec.add("test", "team");
Section csec = rsec.getChild("child");
csec.add("testchild", "pappo");
Section ssec = csec.getChild("sub");
ssec.add("testSec", "pippo");
StringWriter sw = new StringWriter();
ini.store(sw);
System.out.println(sw.toString());
}
}

View File

@ -0,0 +1,32 @@
package test.container;
import java.io.File;
import org.gcube.common.validator.annotations.IsValid;
import org.gcube.common.validator.annotations.NotNull;
import org.gcube.smartgears.persistence.PersistenceWriter;
public class PersistenceWriterTest implements PersistenceWriter{
@IsValid @NotNull
String location;
@Override
public File file(String path) {
return null;
}
@Override
public File writefile(String path) {
return null;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}

View File

@ -1,7 +1,5 @@
package utils;
import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
@ -13,7 +11,6 @@ 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.application.DefaultApplicationConfiguration;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.extensions.ApplicationExtension;
import org.gcube.smartgears.handlers.application.ApplicationHandler;
@ -41,34 +38,7 @@ public class TestUtils {
}
/**
* Serialises a {@link ContainerConfiguration} to XML in a file.
*
* @param config the configuration
* @param the file
* @return the serialisation
* @throws RuntimeException if the configuration cannot be serialised
*/
public static void serialise(ContainerConfiguration config, File file) {
//serialises configuration
try {
JAXBContext ctx = JAXBContext.newInstance(ContainerConfiguration.class);
FileWriter writer = new FileWriter(file);
ctx.createMarshaller().marshal(config, writer);
writer.flush();
writer.close();
} catch (Exception e) {
throw new RuntimeException("invalid service configuration", e);
}
}
/**
* Serialises a {@link ApplicationConfiguration} to XML.
*

View File

@ -0,0 +1,41 @@
[node]
; mandatory
; optional fields: mode (online), publication-frequency-seconds (=60), authorizeChildrenContext (=false)
mode = offline
hostname = localhost
protocol= https
port = 8080
infrastructure = gcube
authorizeChildrenContext = true
publicationFrequencyInSeconds = 60
[properties]
; not mandatory
SmartGearsDistribution = 0.0.1
SmartGearsDistributionBundle = UnBundled
[site]
; mandatory
country = it
location = rome
latitude = 41.9000
longitude = 12.5000
[proxy]
; not mandatory
protocol = https
hostname = proxy
port = 80
[authorization]
; mandatory
; optional fields: provider (org.gcube.smartgears.security.DefaultAuthorizationProvider)
provider = org.gcube.smartgears.security.DefaultAuthorizationProvider
credentials.class = org.gcube.smartgears.security.SimpleCredentials
credentials.clientID = testClient
credentials.secret = testSecret
[persistence]
; not mandatory (default is LocalPersistence writing in the ghn home)
class = test.container.PersistenceWriterTest
location = /state