Compare commits
128 Commits
@ -1,43 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" output="target/classes" path="src/main/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="test" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="test" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" path="target/generated-sources">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
</classpath>
|
@ -0,0 +1,4 @@
|
||||
/target/
|
||||
/.classpath
|
||||
/bin/
|
||||
/bin/
|
@ -0,0 +1,3 @@
|
||||
/org.eclipse.core.resources.prefs
|
||||
/org.eclipse.jdt.core.prefs
|
||||
/org.eclipse.m2e.core.prefs
|
@ -0,0 +1,155 @@
|
||||
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
# Changelog for Common Smartgears
|
||||
|
||||
## [v4.0.0-SNAPSHOT]
|
||||
|
||||
- porting to keycloak
|
||||
|
||||
|
||||
## [v3.2.0-SNAPSHOT]
|
||||
|
||||
- Added SecretManagerProvider thread local from authorization-utils [#22871]
|
||||
- Added Linux distribution version [#22933]
|
||||
|
||||
## [v3.1.3] - 2022-03-21
|
||||
|
||||
- fixed bug on policies
|
||||
|
||||
|
||||
## [v3.1.2] - 2022-01-19
|
||||
|
||||
- enabled policy check on smartgears
|
||||
- container configuration for test added
|
||||
|
||||
## [v3.1.1] - 2021-09-29
|
||||
|
||||
- minimal privilege granted also on empty resource_access in JWT token
|
||||
|
||||
## [v3.1.0] - 2021-05-14
|
||||
|
||||
- use of AccessTokenProvider
|
||||
- use gcube-jackson instead of minimal-json for access token parsing [#21097]
|
||||
|
||||
|
||||
## [v3.0.2] - 2020-03-01
|
||||
|
||||
- check if response is already committed on error
|
||||
|
||||
|
||||
## [v3.0.1] - 2020-11-18
|
||||
|
||||
- new Uma Token integration
|
||||
|
||||
## [v3.0.0] - 2020-10-20
|
||||
|
||||
- Switched container JSON management to gcube-jackson [#19283]
|
||||
|
||||
## [v.2.2.0] - 2020-01-23
|
||||
|
||||
- Multiple token are generated in the same call in place of one per call
|
||||
|
||||
|
||||
## [v.2.1.9] - 2019-11-08
|
||||
|
||||
- Project adapted to be build with Jenkins
|
||||
|
||||
|
||||
## [v.2.1.8] - 2019-05-27
|
||||
|
||||
- Support oauth2 protocol accepting token in the auhtorization header field
|
||||
|
||||
|
||||
## [v.2.1.7] - 2019-02-26
|
||||
|
||||
- Added Proxy Address to Application Configuration
|
||||
- Added protocol to Container Configuration (http by default)
|
||||
- Changed the logs in accounting handler to log error or success and eventually error code
|
||||
|
||||
|
||||
## [v.2.1.5] - 2017-09-19
|
||||
|
||||
- Added ThreadLocal InnerMethodName to set method name from application
|
||||
|
||||
|
||||
## [v.2.1.4] - 2017-07-25
|
||||
|
||||
- Validation handler for application split in 2 different handlers: - ContextRetriever that set Token and Scope - RequestValidation that does all the required checks
|
||||
|
||||
|
||||
## [v.2.1.3] - 2017-06-06
|
||||
|
||||
- Added gcube bom dependency
|
||||
- Search for handlers in the root classpath
|
||||
|
||||
|
||||
## [v.2.1.2] - 2017-05-02
|
||||
|
||||
- Modified the Authorization filter to accept also children scope when authorizeChildrenContext is enabled on ContianerConfiguration
|
||||
- Shutdown of Accounting thread added
|
||||
|
||||
|
||||
## [v.2.1.1] - 2017-03-16
|
||||
|
||||
- Minor issue on filter exclusion fixed
|
||||
|
||||
|
||||
## [v.2.0.1] - 2016-12-15
|
||||
|
||||
- Proxy configuration added
|
||||
- Solved a bug in events registration for ProfileManager
|
||||
- Added a scheduler for period update of GCoreEnpoints
|
||||
- Exclude modified to support exclude for sub-group of handlers
|
||||
|
||||
|
||||
## [v.2.0.0] - 2016-11-07
|
||||
|
||||
- Integration with Authorization 2.0
|
||||
|
||||
|
||||
## [v.1.2.7] - 2016-05-18
|
||||
|
||||
- Removed commons-io dependency [#2355]
|
||||
|
||||
## [v.1.2.6] - 2016-04-08
|
||||
|
||||
- Added missing class for service loader of org.gcube.smartgears.handlers.container.ContainerHandler [#2474]
|
||||
- Added flush of accounting data [#1353]
|
||||
|
||||
|
||||
## [v.1.2.5] - 2016-02-08
|
||||
|
||||
- Enhanced accounting version
|
||||
|
||||
|
||||
## [v.1.2.4] - 2015-12-09
|
||||
|
||||
- Transparent accounting added on service calls
|
||||
|
||||
|
||||
## [v.1.2.3] - 2015-07-27
|
||||
|
||||
- Authorization token control added
|
||||
- Added support to HTTP Basic authorization
|
||||
|
||||
|
||||
## [v.1.2.2] - 2015-04-27
|
||||
|
||||
- Fixed available space information on ghn profile
|
||||
|
||||
|
||||
## [v.1.2.1] - 2014-02-13
|
||||
|
||||
- Scopes can be removed from container
|
||||
- Node profile set to static
|
||||
- Internal adjustments for move to Java 7
|
||||
- Wildcard allowed in exclude directives
|
||||
- Domain corrected derived in gHN profile
|
||||
- Cleaner shutdown
|
||||
- Further improvement in shutdown handling
|
||||
|
||||
|
||||
## [v.1.0.0] - 2013-10-24
|
||||
|
||||
- First Release
|
||||
|
@ -0,0 +1,79 @@
|
||||
# Common Smartgears
|
||||
|
||||
A core gCube library which empower a servlet container (e.g. tomcat) with a set of functionality such as:
|
||||
|
||||
- node and application infrastructure registration
|
||||
- authorization
|
||||
- accounting
|
||||
|
||||
|
||||
## Built With
|
||||
|
||||
* [OpenJDK](https://openjdk.java.net/) - The JDK used
|
||||
* [Maven](https://maven.apache.org/) - Dependency Management
|
||||
|
||||
## Documentation
|
||||
|
||||
[SmartGears](https://wiki.gcube-system.org/gcube/SmartGears)
|
||||
|
||||
## Change log
|
||||
|
||||
See [Releases](https://code-repo.d4science.org/gCubeSystem/common-smartgears/releases).
|
||||
|
||||
## Authors
|
||||
|
||||
* **Luca Frosini** ([ORCID](https://orcid.org/0000-0003-3183-2291)) - [ISTI-CNR Infrascience Group](http://nemis.isti.cnr.it/groups/infrascience)
|
||||
* **Lucio Lelii** - [ISTI-CNR Infrascience Group](http://nemis.isti.cnr.it/groups/infrascience)
|
||||
* **Fabio Simeoni** - FAO of the UN, Italy
|
||||
|
||||
|
||||
## How to Cite this Software
|
||||
|
||||
Tell people how to cite this software.
|
||||
* Cite an associated paper?
|
||||
* Use a specific BibTeX entry for the software?
|
||||
|
||||
|
||||
@Manual{,
|
||||
title = {Common Smartgears},
|
||||
author = {{Frosini, Luca}, {Lelii, Lucio}, {Simeoni, Fabio}},
|
||||
organization = {{ISTI - CNR}, {FAO}},
|
||||
address = {{Pisa, Italy}, {Roma, Italy}},
|
||||
year = 2019,
|
||||
url = {http://www.gcube-system.org/}
|
||||
}
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the EUPL V.1.1 License - see the [LICENSE.md](LICENSE.md) file for details.
|
||||
|
||||
|
||||
## About the gCube Framework
|
||||
This software is part of the [gCubeFramework](https://www.gcube-system.org/ "gCubeFramework"): an
|
||||
open-source software toolkit used for building and operating Hybrid Data
|
||||
Infrastructures enabling the dynamic deployment of Virtual Research Environments
|
||||
by favouring the realisation of reuse oriented policies.
|
||||
|
||||
The projects leading to this software have received funding from a series of European Union programmes including:
|
||||
|
||||
- the Sixth Framework Programme for Research and Technological Development
|
||||
- DILIGENT (grant no. 004260).
|
||||
- the Seventh Framework Programme for research, technological development and demonstration
|
||||
- D4Science (grant no. 212488);
|
||||
- D4Science-II (grant no.239019);
|
||||
- ENVRI (grant no. 283465);
|
||||
- iMarine(grant no. 283644);
|
||||
- EUBrazilOpenBio (grant no. 288754).
|
||||
- the H2020 research and innovation programme
|
||||
- SoBigData (grant no. 654024);
|
||||
- PARTHENOS (grant no. 654119);
|
||||
- EGIEngage (grant no. 654142);
|
||||
- ENVRIplus (grant no. 654182);
|
||||
- BlueBRIDGE (grant no. 675680);
|
||||
- PerformFish (grant no. 727610);
|
||||
- AGINFRAplus (grant no. 731001);
|
||||
- DESIRA (grant no. 818194);
|
||||
- ARIADNEplus (grant no. 823914);
|
||||
- RISIS2 (grant no. 824091);
|
||||
|
||||
|
@ -1,4 +0,0 @@
|
||||
gCube System - License
|
||||
------------------------------------------------------------
|
||||
|
||||
${gcube.license}
|
@ -1,70 +0,0 @@
|
||||
The gCube System - ${name}
|
||||
--------------------------------------------------
|
||||
|
||||
${description}
|
||||
|
||||
|
||||
${gcube.description}
|
||||
|
||||
${gcube.funding}
|
||||
|
||||
|
||||
Version
|
||||
--------------------------------------------------
|
||||
|
||||
${version} (${buildDate})
|
||||
|
||||
Please see the file named "changelog.xml" in this directory for the release notes.
|
||||
|
||||
|
||||
Authors
|
||||
--------------------------------------------------
|
||||
|
||||
* Fabio Simeoni (fabio.simeoni@fao.org), FAO of the UN, Italy
|
||||
* Luca Frosini (luca.frosini@isti.cnr.it), CNR, Italy
|
||||
* Lucio Lelii (lucio.lelii@isti.cnr.it), CNT, Italy
|
||||
|
||||
|
||||
Maintainers
|
||||
-----------
|
||||
|
||||
* Luca Frosini (luca.frosini@isti.cnr.it), CNR, Italy
|
||||
* Lucio Lelii (lucio.lelii@isti.cnr.it), CNT, Italy
|
||||
|
||||
|
||||
Download information
|
||||
--------------------------------------------------
|
||||
|
||||
Source code is available from SVN:
|
||||
${scm.url}
|
||||
|
||||
Binaries can be downloaded from the gCube website:
|
||||
${gcube.website}
|
||||
|
||||
|
||||
Installation
|
||||
--------------------------------------------------
|
||||
|
||||
Installation documentation is available on-line in the gCube Wiki:
|
||||
${gcube.wikiRoot}/Smartgears
|
||||
|
||||
|
||||
Documentation
|
||||
--------------------------------------------------
|
||||
|
||||
Documentation is available on-line in the gCube Wiki:
|
||||
${gcube.wikiRoot}/Smartgears
|
||||
|
||||
|
||||
Support
|
||||
--------------------------------------------------
|
||||
|
||||
Bugs and support requests can be reported in the gCube issue tracking tool:
|
||||
${gcube.issueTracking}
|
||||
|
||||
|
||||
Licensing
|
||||
--------------------------------------------------
|
||||
|
||||
This software is licensed under the terms you may find in the file named "LICENSE" in this directory.
|
||||
|
@ -1,68 +0,0 @@
|
||||
<ReleaseNotes>
|
||||
<Changeset component="common-smartgears-2.1.9" date="2019-03-21">
|
||||
<Change>Support oauth2 protocol accepting token in the auhtorization header field</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-2.1.7" date="2017-01-16">
|
||||
<Change>Added Proxy Address to Application Configuration</Change>
|
||||
<Change>Added protocol to Container Configuration (http by default)</Change>
|
||||
<Change>Changed the logs in accounting handler to log error or success and eventually error code</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-2.1.5" date="2017-07-18">
|
||||
<Change>Added ThreadLocal InnerMethodName to set method name from application</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-2.1.4" date="2017-05-30">
|
||||
<Change>Validation handler for application split in 2 different handlers:
|
||||
- ContextRetriever that set Token and Scope
|
||||
- RequestValidation that does all the required checks
|
||||
</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-2.1.3" date="2017-05-12">
|
||||
<Change>Added gcube bom dependency</Change>
|
||||
<Change>Search for handlers in the root classpath</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-2.1.2" date="2017-03-22">
|
||||
<Change>Modified the Authorization filter to accept also children
|
||||
scope when authorizeChildrenContext is enabled on ContianerConfiguration</Change>
|
||||
<Change>Shutdown of Accounting thread added</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-2.1.1" date="2017-01-25">
|
||||
<Change>Minor issue on filter exclusion fixed</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-2.1.0" date="2016-10-24">
|
||||
<Change>proxy configuration added</Change>
|
||||
<Change>solved a bug in events registration for ProfileManager</Change>
|
||||
<Change>added a scheduler for period update of GCoreEnpoints</Change>
|
||||
<Change>Exclude modified to support exclude for sub-group of handlers</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-2.0.0" date="2016-03-10">
|
||||
<Change>integration with Authorization 2.0</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-1.2.6" date="2015-12-22">
|
||||
<Change>Added flush of accounting data</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-1.2.5" date="2015-12-22">
|
||||
<Change>Changed accounting version</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-1.2.4" date="2015-10-06">
|
||||
<Change>Transparent accounting added on service calls</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-1.2.3" date="2015-07-27">
|
||||
<Change>Authorization token control added</Change>
|
||||
<Change>Added support to HTTP Basic authorization</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-1.2.2" date="2015-04-27">
|
||||
<Change>Fixed available space information on ghn profile</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-1.2.1" date="2014-02-13">
|
||||
<Change>scopes can be removed from container</Change>
|
||||
<Change>node profile set to static</Change>
|
||||
<Change>internal adjustments for move to Java 7</Change>
|
||||
<Change>wildcard allowed in exclude directives</Change>
|
||||
<Change>domain corrected derived in gHN profile</Change>
|
||||
<Change>cleaner shutdown</Change>
|
||||
<Change>further improvement in shutdown handling</Change>
|
||||
</Changeset>
|
||||
<Changeset component="common-smartgears-1.0.0" date="2013-10-24">
|
||||
<Change>First Release</Change>
|
||||
</Changeset>
|
||||
</ReleaseNotes>
|
@ -1,31 +0,0 @@
|
||||
<assembly
|
||||
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
|
||||
<id>servicearchive</id>
|
||||
<formats>
|
||||
<format>tar.gz</format>
|
||||
</formats>
|
||||
<baseDirectory>/</baseDirectory>
|
||||
<fileSets>
|
||||
<fileSet>
|
||||
<directory>${distroDirectory}</directory>
|
||||
<outputDirectory>${file.separator}</outputDirectory>
|
||||
<useDefaultExcludes>true</useDefaultExcludes>
|
||||
<includes>
|
||||
<include>README</include>
|
||||
<include>LICENSE</include>
|
||||
<include>changelog.xml</include>
|
||||
<include>profile.xml</include>
|
||||
</includes>
|
||||
<fileMode>755</fileMode>
|
||||
<filtered>true</filtered>
|
||||
</fileSet>
|
||||
</fileSets>
|
||||
<files>
|
||||
<file>
|
||||
<source>target${file.separator}${build.finalName}.${project.packaging}</source>
|
||||
<outputDirectory>${file.separator}${artifactId}</outputDirectory>
|
||||
</file>
|
||||
</files>
|
||||
</assembly>
|
@ -1,29 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE xml>
|
||||
<Resource>
|
||||
<ID />
|
||||
<Type>Service</Type>
|
||||
<Profile>
|
||||
<Description>${description}</Description>
|
||||
<Class>${serviceClass}</Class>
|
||||
<Name>${artifactId}</Name>
|
||||
<Version>1.0.0</Version>
|
||||
<Packages>
|
||||
<Software>
|
||||
<Description>${description}</Description>
|
||||
<Name>${artifactId}</Name>
|
||||
<Version>${version}</Version>
|
||||
<MavenCoordinates>
|
||||
<groupId>${groupId}</groupId>
|
||||
<artifactId>${artifactId}</artifactId>
|
||||
<version>${version}</version>
|
||||
</MavenCoordinates>
|
||||
<Type>Library</Type>
|
||||
<Files>
|
||||
<File>${build.finalName}.${project.packaging}</File>
|
||||
</Files>
|
||||
</Software>
|
||||
</Packages>
|
||||
</Profile>
|
||||
</Resource>
|
||||
|
@ -1,2 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<smartgears version="${project.version}" />
|
Binary file not shown.
@ -0,0 +1,2 @@
|
||||
[smartgears]
|
||||
version = ${project.version}
|
@ -0,0 +1,37 @@
|
||||
package org.gcube.smartgears.configuration;
|
||||
|
||||
import org.gcube.common.security.credentials.Credentials;
|
||||
import org.gcube.common.validator.annotations.IsValid;
|
||||
import org.gcube.common.validator.annotations.NotNull;
|
||||
import org.gcube.smartgears.security.AuthorizationProviderFactory;
|
||||
|
||||
public class AuthorizationProviderConfiguration {
|
||||
|
||||
@NotNull
|
||||
AuthorizationProviderFactory<?> authProviderFactory;
|
||||
|
||||
@NotNull @IsValid
|
||||
Credentials credentials;
|
||||
|
||||
public AuthorizationProviderConfiguration(AuthorizationProviderFactory<?> authProviderFactory,
|
||||
Credentials credentials) {
|
||||
super();
|
||||
this.authProviderFactory = authProviderFactory;
|
||||
this.credentials = credentials;
|
||||
}
|
||||
|
||||
public AuthorizationProviderFactory<?> getAuthProviderFactory() {
|
||||
return authProviderFactory;
|
||||
}
|
||||
|
||||
public Credentials getCredentials() {
|
||||
return credentials;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "AuthorizationProviderConfiguration [authProviderFactory=" + authProviderFactory.getClass() + "]";
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package org.gcube.smartgears.configuration;
|
||||
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonTypeInfo.As;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
|
||||
|
||||
@JsonTypeInfo(include=As.PROPERTY, use=Id.CLASS, property= "className")
|
||||
public interface ComponentConfiguration {
|
||||
|
||||
String getLocation();
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
package org.gcube.smartgears.configuration;
|
||||
|
||||
public interface Configurable {
|
||||
|
||||
void configure(ComponentConfiguration configuration);
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package org.gcube.smartgears.configuration;
|
||||
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface ConfiguredWith {
|
||||
|
||||
public Class<? extends ComponentConfiguration> value();
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package org.gcube.smartgears.configuration;
|
||||
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import org.gcube.common.validator.annotations.IsValid;
|
||||
import org.gcube.common.validator.annotations.NotNull;
|
||||
import org.gcube.smartgears.persistence.PersistenceWriter;
|
||||
|
||||
@JsonInclude(value = Include.NON_NULL)
|
||||
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
|
||||
public class PersistenceConfiguration {
|
||||
|
||||
@NotNull
|
||||
private Class<? extends PersistenceWriter> implementationClass;
|
||||
|
||||
@IsValid
|
||||
private ComponentConfiguration writerConfiguration;
|
||||
|
||||
protected PersistenceConfiguration() {}
|
||||
|
||||
public <T extends ComponentConfiguration> PersistenceConfiguration(Class<? extends PersistenceWriter> implementationClass, T writerConfiguration) {
|
||||
super();
|
||||
this.implementationClass = implementationClass;
|
||||
this.writerConfiguration = writerConfiguration;
|
||||
}
|
||||
|
||||
public Class<? extends PersistenceWriter> getImplementationClass() {
|
||||
return this.implementationClass;
|
||||
}
|
||||
|
||||
public ComponentConfiguration getWriterConfiguration() {
|
||||
return writerConfiguration;
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package org.gcube.smartgears.configuration;
|
||||
|
||||
public class SmartgearsConfiguration {
|
||||
|
||||
private String version;
|
||||
|
||||
public SmartgearsConfiguration(String version) {
|
||||
super();
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public String getVersion() {
|
||||
return version;
|
||||
}
|
||||
}
|
@ -1,167 +1,182 @@
|
||||
package org.gcube.smartgears.configuration.application;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
import org.gcube.smartgears.configuration.Mode;
|
||||
import org.gcube.smartgears.persistence.Persistence;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonProperty;
|
||||
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;
|
||||
import org.gcube.common.validator.annotations.NotNull;
|
||||
import org.gcube.smartgears.configuration.PersistenceConfiguration;
|
||||
|
||||
/**
|
||||
* The configuration of the application.
|
||||
*
|
||||
* @author Fabio Simeoni
|
||||
* The configuration of a managed app.
|
||||
* <p>
|
||||
* Includes the list of its client services.
|
||||
*
|
||||
* @author Lucio Lelii
|
||||
*
|
||||
*/
|
||||
public interface ApplicationConfiguration {
|
||||
@JsonInclude(value = Include.NON_NULL)
|
||||
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
|
||||
public class 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
|
||||
*/
|
||||
String context();
|
||||
|
||||
boolean proxied();
|
||||
|
||||
/**
|
||||
* Sets the context path of the application
|
||||
* @param context the context path
|
||||
* @return this configuration
|
||||
*/
|
||||
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
|
||||
*/
|
||||
String name();
|
||||
|
||||
|
||||
/**
|
||||
* Sets the name of the application.
|
||||
* @param name the name
|
||||
* @return this configuration
|
||||
*/
|
||||
ApplicationConfiguration name(String name);
|
||||
|
||||
/**
|
||||
* Returns the class of the application
|
||||
* @return the class
|
||||
*/
|
||||
String serviceClass();
|
||||
|
||||
/**
|
||||
* Sets the class of the application.
|
||||
* @param serviceClass the class
|
||||
* @return this configuration
|
||||
*/
|
||||
ApplicationConfiguration serviceClass(String serviceClass);
|
||||
|
||||
/**
|
||||
* Returns the version of the application.
|
||||
* @return the version
|
||||
*/
|
||||
String version();
|
||||
|
||||
/**
|
||||
* Sets the version of the application.
|
||||
* @param version the version
|
||||
* @return this configuration
|
||||
*/
|
||||
ApplicationConfiguration version(String version);
|
||||
@NotNull
|
||||
String name;
|
||||
|
||||
/**
|
||||
* Returns the description of the application.
|
||||
* @return the description
|
||||
*/
|
||||
String description();
|
||||
@NotNull
|
||||
String group;
|
||||
|
||||
/**
|
||||
* Sets the description of the application.
|
||||
* @param description the description
|
||||
* @return this configuration
|
||||
*/
|
||||
ApplicationConfiguration description(String description);
|
||||
|
||||
ProxyAddress proxyAddress();
|
||||
|
||||
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();
|
||||
|
||||
@NotNull
|
||||
String version;
|
||||
|
||||
String description="";
|
||||
|
||||
@JsonIgnore
|
||||
String context;
|
||||
|
||||
private boolean proxable = true;
|
||||
|
||||
Set<GCubeExclude> excludes= new HashSet<>();
|
||||
|
||||
Set<GCubeInclude> includes= new HashSet<>();
|
||||
|
||||
@NotEmpty @JsonProperty("persistence")
|
||||
PersistenceConfiguration persistenceConfiguration;
|
||||
|
||||
public Set<GCubeExclude> excludes() {
|
||||
return excludes;
|
||||
}
|
||||
|
||||
public Set<GCubeInclude> includes() {
|
||||
return includes;
|
||||
}
|
||||
|
||||
public ApplicationConfiguration() {}
|
||||
|
||||
public String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String context() {
|
||||
return context;
|
||||
}
|
||||
|
||||
public ApplicationConfiguration excludes(GCubeExclude ... excludes) {
|
||||
this.excludes=new HashSet<GCubeExclude>(Arrays.asList(excludes));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ApplicationConfiguration includes(GCubeInclude... includes) {
|
||||
this.includes=new HashSet<GCubeInclude>(Arrays.asList(includes));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ApplicationConfiguration context(String context) {
|
||||
this.context = context;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ApplicationConfiguration name(String name) {
|
||||
this.name=name;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ApplicationConfiguration persistenceConfiguration(PersistenceConfiguration configuration) {
|
||||
this.persistenceConfiguration = configuration;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ApplicationConfiguration proxable(boolean proxable) {
|
||||
this.proxable = proxable;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String group() {
|
||||
return group;
|
||||
}
|
||||
|
||||
|
||||
public ApplicationConfiguration group(String group) {
|
||||
this.group=group;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String version() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public ApplicationConfiguration version(String version) {
|
||||
this.version=version;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public String description() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public ApplicationConfiguration description(String description) {
|
||||
this.description=description;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean proxable() {
|
||||
return proxable;
|
||||
}
|
||||
|
||||
public PersistenceConfiguration persistenceConfiguration() {
|
||||
return persistenceConfiguration;
|
||||
}
|
||||
|
||||
public void validate() {
|
||||
|
||||
List<String> msgs = new ArrayList<String>();
|
||||
|
||||
Validator validator = ValidatorFactory.validator();
|
||||
|
||||
for (ValidationError error : validator.validate(this))
|
||||
msgs.add(error.toString());
|
||||
|
||||
if (!this.excludes().isEmpty() && !this.includes().isEmpty())
|
||||
msgs.add("exclude tags and includes tags are mutually exclusive");
|
||||
|
||||
if (!msgs.isEmpty())
|
||||
throw new IllegalStateException("invalid configuration: "+msgs);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(description, excludes, group, includes, name, proxable, version);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
ApplicationConfiguration other = (ApplicationConfiguration) obj;
|
||||
return Objects.equals(description, other.description)
|
||||
&& Objects.equals(excludes, other.excludes) && Objects.equals(group, other.group)
|
||||
&& Objects.equals(includes, other.includes) && Objects.equals(name, other.name)
|
||||
&& proxable == other.proxable && Objects.equals(version, other.version);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a set of request paths that should not be subjected to request management.
|
||||
* @return the set of exclude paths.
|
||||
*/
|
||||
Set<Exclude> excludes();
|
||||
|
||||
/**
|
||||
* Returns a set of request paths that should be subjected to request management.
|
||||
* @return the set of exclude paths.
|
||||
*/
|
||||
Set<Include> includes();
|
||||
|
||||
|
||||
/**
|
||||
* Sets the persistence manager of the application.
|
||||
* @param manager the manager
|
||||
* @return this configuration
|
||||
*/
|
||||
ApplicationConfiguration persistence(Persistence manager);
|
||||
|
||||
|
||||
/**
|
||||
* Validates this configuration.
|
||||
*
|
||||
* @throws IllegalStateException if the configuration is not valid
|
||||
*/
|
||||
void validate();
|
||||
|
||||
|
||||
/**
|
||||
* Merges this configuration with another configuration
|
||||
* @param config the other configuration
|
||||
*/
|
||||
void merge(ApplicationConfiguration config);
|
||||
|
||||
ApplicationConfiguration excludes(Exclude ... excludes);
|
||||
|
||||
ApplicationConfiguration includes(Include ... includes);
|
||||
|
||||
|
||||
|
||||
}
|
@ -1,75 +0,0 @@
|
||||
package org.gcube.smartgears.configuration.application;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import javax.xml.bind.Unmarshaller;
|
||||
import javax.xml.bind.annotation.XmlAnyElement;
|
||||
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.IsValid;
|
||||
import org.gcube.smartgears.extensions.ApplicationExtension;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* The {@link ApplicationExtension}s that manage the application.
|
||||
*
|
||||
* @author Fabio Simeoni
|
||||
*
|
||||
*/
|
||||
@XmlRootElement(name="extensions")
|
||||
public class ApplicationExtensions {
|
||||
|
||||
@XmlAnyElement(lax=true) @IsValid
|
||||
List<ApplicationExtension> extensions = new ArrayList<ApplicationExtension>();
|
||||
|
||||
public ApplicationExtensions() {}
|
||||
|
||||
/**
|
||||
* Returns the extensions for the application.
|
||||
* @return the extensions
|
||||
*/
|
||||
public List<ApplicationExtension> extensions() {
|
||||
return extensions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the extensions for the application.
|
||||
* @param extensions the extensions
|
||||
* @return this configuration
|
||||
*/
|
||||
public ApplicationExtensions set(ApplicationExtension ... extensions) {
|
||||
this.extensions = Arrays.asList(extensions);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return extensions.toString();
|
||||
}
|
||||
|
||||
public void validate() {
|
||||
|
||||
List<String> msgs = new ArrayList<String>();
|
||||
|
||||
Validator validator = ValidatorFactory.validator();
|
||||
|
||||
for (ValidationError error : validator.validate(this))
|
||||
msgs.add(error.toString());
|
||||
|
||||
if (!msgs.isEmpty())
|
||||
throw new IllegalStateException("invalid configuration: "+msgs);
|
||||
|
||||
}
|
||||
|
||||
//since we use @AnyElement, after deserialisation, we check there are no DOM elements
|
||||
void afterUnmarshal(Unmarshaller u, Object parent) {
|
||||
for (Object o : extensions)
|
||||
if (o instanceof Element)
|
||||
throw new RuntimeException("invalid extensions detected: "+Element.class.cast(o).getLocalName());
|
||||
}
|
||||
|
||||
}
|
@ -1,167 +0,0 @@
|
||||
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.container.ContainerConfiguration;
|
||||
import org.gcube.smartgears.persistence.DefaultPersistence;
|
||||
import org.gcube.smartgears.persistence.Persistence;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Fabio Simeoni
|
||||
* @author Luca Frosini (ISTI - CNR) http://www.lucafrosini.com/
|
||||
*/
|
||||
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(new DefaultPersistence(location));
|
||||
|
||||
log.trace("setting persistence location for {} @ {}",application.name(), dir.getAbsolutePath());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public ApplicationConfiguration inner() {
|
||||
return application;
|
||||
}
|
||||
|
||||
public Mode mode() {
|
||||
return container.mode()==offline?offline:application.mode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String context() {
|
||||
return application.context();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration context(String context) {
|
||||
return application.context(context);
|
||||
}
|
||||
|
||||
public String name() {
|
||||
return application.name();
|
||||
}
|
||||
|
||||
public ApplicationConfiguration name(String name) {
|
||||
return application.name(name);
|
||||
}
|
||||
|
||||
public String serviceClass() {
|
||||
return application.serviceClass();
|
||||
}
|
||||
|
||||
public ApplicationConfiguration serviceClass(String group) {
|
||||
return application.serviceClass(group);
|
||||
}
|
||||
|
||||
public String version() {
|
||||
return application.version();
|
||||
}
|
||||
|
||||
public ApplicationConfiguration version(String version) {
|
||||
return application.version(version);
|
||||
}
|
||||
|
||||
public String description() {
|
||||
return application.description();
|
||||
}
|
||||
|
||||
public ProxyAddress proxyAddress() {
|
||||
return application.proxyAddress();
|
||||
}
|
||||
|
||||
public ApplicationConfiguration description(String description) {
|
||||
return application.description(description);
|
||||
}
|
||||
|
||||
public Persistence persistence() {
|
||||
return application.persistence();
|
||||
}
|
||||
|
||||
public ApplicationConfiguration persistence(Persistence manager) {
|
||||
return application.persistence(manager);
|
||||
}
|
||||
|
||||
public ApplicationConfiguration mode(Mode mode) {
|
||||
return application.mode(mode);
|
||||
}
|
||||
|
||||
public void validate() {
|
||||
|
||||
application.validate();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Exclude> excludes() {
|
||||
return application.excludes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Include> includes() {
|
||||
return application.includes();
|
||||
}
|
||||
|
||||
@Override
|
||||
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() {
|
||||
return application.proxied();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration excludes(Exclude ... excludes) {
|
||||
return application.excludes(excludes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration includes(Include... includes) {
|
||||
return application.includes(includes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration proxyAddress(ProxyAddress proxyaddress) {
|
||||
return application.proxyAddress(proxyaddress);
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,237 +0,0 @@
|
||||
package org.gcube.smartgears.configuration.application;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
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;
|
||||
|
||||
/**
|
||||
* The configuration of a managed app.
|
||||
* <p>
|
||||
* Includes the list of its client services.
|
||||
*
|
||||
* @author Fabio Simeoni
|
||||
* @author Luca Frosini (ISTI - CNR) http://www.lucafrosini.com/
|
||||
*
|
||||
*/
|
||||
@XmlRootElement(name="application")
|
||||
public class DefaultApplicationConfiguration implements ApplicationConfiguration {
|
||||
|
||||
|
||||
@XmlAttribute
|
||||
private Mode mode = Mode.online;
|
||||
|
||||
@XmlAttribute(name="context")
|
||||
String context;
|
||||
|
||||
@XmlElement(name="name" , required=true)
|
||||
@NotNull
|
||||
String name;
|
||||
|
||||
@XmlElement(name="group", required=true)
|
||||
@NotNull
|
||||
String group;
|
||||
|
||||
@XmlElement(name="version", required=true)
|
||||
@NotNull
|
||||
String version;
|
||||
|
||||
@XmlTransient
|
||||
Set<String> tokens = new HashSet<String>();
|
||||
|
||||
@XmlElement(name="description")
|
||||
String description="";
|
||||
|
||||
@XmlElementRef
|
||||
@IsValid
|
||||
ProxyAddress proxyAddress;
|
||||
|
||||
@XmlElementRef
|
||||
Set<Exclude> excludes= new LinkedHashSet<Exclude>();
|
||||
|
||||
@XmlElementRef
|
||||
Set<Include> includes= new LinkedHashSet<Include>();
|
||||
|
||||
@XmlElementRef(type=DefaultPersistence.class)
|
||||
@NotNull @IsValid
|
||||
private Persistence persistenceManager;
|
||||
|
||||
@Override
|
||||
public Set<Exclude> excludes() {
|
||||
return excludes;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Set<Include> includes() {
|
||||
return includes;
|
||||
}
|
||||
|
||||
public DefaultApplicationConfiguration() {}
|
||||
|
||||
@Override
|
||||
public Mode mode() {
|
||||
return mode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String context() {
|
||||
return context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration context(String context) {
|
||||
this.context=context;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ProxyAddress proxyAddress() {
|
||||
return proxyAddress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration excludes(Exclude ... excludes) {
|
||||
this.excludes=new HashSet<Exclude>(Arrays.asList(excludes));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration includes(Include... includes) {
|
||||
this.includes=new HashSet<Include>(Arrays.asList(includes));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration name(String name) {
|
||||
this.name=name;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serviceClass() {
|
||||
return group;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration serviceClass(String group) {
|
||||
this.group=group;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String version() {
|
||||
return version;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration version(String version) {
|
||||
this.version=version;
|
||||
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() {
|
||||
return description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration description(String description) {
|
||||
this.description=description;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean proxied() {
|
||||
return proxyAddress!=null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Persistence persistence() {
|
||||
return persistenceManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration persistence(Persistence manager) {
|
||||
this.persistenceManager=manager;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration proxyAddress(ProxyAddress proxyaddress) {
|
||||
this.proxyAddress = proxyaddress;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationConfiguration mode(Mode mode) {
|
||||
this.mode=mode;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate() {
|
||||
|
||||
List<String> msgs = new ArrayList<String>();
|
||||
|
||||
Validator validator = ValidatorFactory.validator();
|
||||
|
||||
for (ValidationError error : validator.validate(this))
|
||||
msgs.add(error.toString());
|
||||
|
||||
if (!this.excludes().isEmpty() && !this.includes().isEmpty())
|
||||
msgs.add("exclude tags and includes tags are mutually exclusive");
|
||||
|
||||
if (!msgs.isEmpty())
|
||||
throw new IllegalStateException("invalid configuration: "+msgs);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void merge(ApplicationConfiguration config) {
|
||||
|
||||
mode(config.mode());
|
||||
|
||||
if (config.persistence()!=null)
|
||||
persistence(config.persistence());
|
||||
|
||||
//scopes.addAll(config.startScopes());
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,99 @@
|
||||
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
|
||||
+ "]";
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
@ -1,50 +0,0 @@
|
||||
package org.gcube.smartgears.configuration.container;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAnyElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
import org.gcube.smartgears.handlers.container.ContainerHandler;
|
||||
|
||||
/**
|
||||
* The {@link ContainerHandler}s that manage the application.
|
||||
*
|
||||
* @author Fabio Simeoni
|
||||
*
|
||||
*/
|
||||
@XmlRootElement(name="handlers")
|
||||
public class ContainerHandlers {
|
||||
|
||||
@XmlAnyElement(lax=true)
|
||||
List<ContainerHandler> handlers = new ArrayList<ContainerHandler>();
|
||||
|
||||
public ContainerHandlers() {}
|
||||
|
||||
/**
|
||||
* Returns the {@link ContainerHandler}s for the service.
|
||||
* @return the lifecycle handlers
|
||||
*/
|
||||
public List<ContainerHandler> get() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link ContainerHandler}s for the service.
|
||||
* @param handlers the lifecycle handlers
|
||||
* @return this configuration
|
||||
*/
|
||||
public ContainerHandlers set(ContainerHandler ... handlers) {
|
||||
this.handlers = Arrays.asList(handlers);
|
||||
return this;
|
||||
}
|
||||
|
||||
public void mergeWith(ContainerHandlers other){
|
||||
List<ContainerHandler> handlers = other.get();
|
||||
for (ContainerHandler handler : handlers)
|
||||
if (!this.get().contains(handler))
|
||||
this.get().add(handler);
|
||||
}
|
||||
}
|
@ -1,79 +0,0 @@
|
||||
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
|
||||
private String version;
|
||||
|
||||
public SmartGearsConfiguration(){
|
||||
}
|
||||
|
||||
public String version() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public SmartGearsConfiguration version(String version) {
|
||||
this.version=version;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Validates this configuration
|
||||
*
|
||||
* @throws IllegalStateException if the configuration is invalid
|
||||
*/
|
||||
public void validate() {
|
||||
|
||||
List<String> msgs = new ArrayList<String>();
|
||||
|
||||
Validator validator = ValidatorFactory.validator();
|
||||
|
||||
for (ValidationError error : validator.validate(this))
|
||||
msgs.add(error.toString());
|
||||
|
||||
if (!msgs.isEmpty())
|
||||
throw new IllegalStateException("invalid configuration: "+msgs);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((version == null) ? 0 : version.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;
|
||||
SmartGearsConfiguration other = (SmartGearsConfiguration) obj;
|
||||
if (version == null) {
|
||||
if (other.version != null)
|
||||
return false;
|
||||
} else if (!version.equals(other.version))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
package org.gcube.smartgears.configuration.library;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.JAXBException;
|
||||
|
||||
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
|
||||
import org.gcube.smartgears.utils.Utils;
|
||||
|
||||
/**
|
||||
* Binds {@link ContainerConfiguration}s to and from XML serialisations.
|
||||
*
|
||||
* @author Fabio Simeoni
|
||||
*
|
||||
*/
|
||||
public class SmartGearsConfigurationBinder {
|
||||
|
||||
/**
|
||||
* Returns a {@link ContainerConfiguration} from its XML serialisation.
|
||||
*
|
||||
* @param stream the serialisation
|
||||
* @return the configuration
|
||||
* @throws RuntimeException if the serialisation is invalid
|
||||
*/
|
||||
public SmartGearsConfiguration bind(InputStream stream) {
|
||||
|
||||
try {
|
||||
|
||||
JAXBContext ctx = JAXBContext.newInstance(SmartGearsConfiguration.class);
|
||||
|
||||
SmartGearsConfiguration config = (SmartGearsConfiguration) ctx.createUnmarshaller().unmarshal(stream);
|
||||
|
||||
return config;
|
||||
|
||||
} catch (JAXBException e) {
|
||||
|
||||
throw new RuntimeException("invalid library configuration", e);
|
||||
|
||||
}
|
||||
finally {
|
||||
|
||||
Utils.closeSafely(stream);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,105 @@
|
||||
package org.gcube.smartgears.extensions.resource;
|
||||
|
||||
import static org.gcube.smartgears.Constants.application_json;
|
||||
import static org.gcube.smartgears.extensions.HttpExtension.Method.GET;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Set;
|
||||
import java.util.Timer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.gcube.common.health.api.HealthCheck;
|
||||
import org.gcube.common.health.api.ReadinessChecker;
|
||||
import org.gcube.smartgears.context.application.ApplicationContext;
|
||||
import org.gcube.smartgears.extensions.ApiResource;
|
||||
import org.gcube.smartgears.extensions.ApiSignature;
|
||||
import org.gcube.smartgears.health.HealthManager;
|
||||
import org.gcube.smartgears.health.HealthResponse;
|
||||
import org.gcube.smartgears.health.HealthTask;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import io.github.classgraph.ClassGraph;
|
||||
import io.github.classgraph.ClassInfo;
|
||||
import io.github.classgraph.ClassInfoList;
|
||||
import io.github.classgraph.ScanResult;
|
||||
|
||||
public class HealthResource extends ApiResource {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(HealthResource.class);
|
||||
|
||||
public static final String mapping = "/health";
|
||||
|
||||
private static final ApiSignature signature = handles(mapping).with(method(GET).produces(application_json));
|
||||
|
||||
private HealthManager manager;
|
||||
|
||||
private HealthTask task;
|
||||
|
||||
private Timer timer;
|
||||
|
||||
HealthResource() {
|
||||
super(signature);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(ApplicationContext context) throws Exception {
|
||||
Set<Class<?>> annotatedReadiness;
|
||||
|
||||
try (ScanResult result = new ClassGraph().enableClassInfo().enableAnnotationInfo().scan()) {
|
||||
|
||||
ClassInfoList classInfos = result.getClassesWithAnnotation(ReadinessChecker.class.getName());
|
||||
|
||||
annotatedReadiness = classInfos.stream().map(ClassInfo::loadClass)
|
||||
.filter(c -> HealthCheck.class.isAssignableFrom(c)).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
manager = new HealthManager();
|
||||
for (Class<?> readnessClass : annotatedReadiness)
|
||||
try {
|
||||
manager.register((HealthCheck) readnessClass.getDeclaredConstructor().newInstance());
|
||||
log.info("added class {} to health manager", readnessClass.getCanonicalName());
|
||||
} catch (Throwable e) {
|
||||
log.error("healthChecker class {} cannot be instantiated", readnessClass.getCanonicalName(), e);
|
||||
}
|
||||
|
||||
task = new HealthTask(manager);
|
||||
|
||||
timer = new Timer(true);
|
||||
|
||||
timer.scheduleAtFixedRate(task, 10000, 60000);
|
||||
|
||||
super.init(context);
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
if (timer!=null)
|
||||
timer.cancel();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
||||
PrintWriter out = resp.getWriter();
|
||||
resp.setContentType("application/json");
|
||||
resp.setCharacterEncoding("UTF-8");
|
||||
HealthResponse response = readiness();
|
||||
|
||||
new ObjectMapper().writeValue(out, response);
|
||||
|
||||
out.flush();
|
||||
}
|
||||
|
||||
public HealthResponse readiness() {
|
||||
return task.getResponse();
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
package org.gcube.smartgears.extensions.resource;
|
||||
|
||||
import static org.gcube.smartgears.Constants.plain_text;
|
||||
import static org.gcube.smartgears.extensions.HttpExtension.Method.GET;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.gcube.smartgears.extensions.ApiResource;
|
||||
import org.gcube.smartgears.extensions.ApiSignature;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.prometheus.PrometheusMeterRegistry;
|
||||
|
||||
public class MetricsResource extends ApiResource {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static final String mapping = "/metrics";
|
||||
|
||||
private static final ApiSignature signature = handles(mapping).with(method(GET).produces(plain_text));
|
||||
|
||||
|
||||
MetricsResource() {
|
||||
super(signature);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
||||
PrometheusMeterRegistry registry = (PrometheusMeterRegistry) Metrics.globalRegistry.getRegistries().stream().findFirst().get();
|
||||
registry.scrape(resp.getWriter());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package org.gcube.smartgears.handlers;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public class OfflineProfilePublisher implements ProfilePublisher {
|
||||
|
||||
@Override
|
||||
public void addTo(Collection<String> tokens) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addToAll() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeFrom(Collection<String> tokens) {
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package org.gcube.smartgears.handlers;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public interface ProfilePublisher {
|
||||
|
||||
void addTo(Collection<String> contexts);
|
||||
|
||||
void addToAll();
|
||||
|
||||
void update();
|
||||
|
||||
void removeFrom(Collection<String> contexts);
|
||||
|
||||
|
||||
}
|
@ -1,74 +0,0 @@
|
||||
package org.gcube.smartgears.handlers.application.lifecycle;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.Calendar;
|
||||
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;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class ProfileBuilder {
|
||||
|
||||
private static List<String> servletExcludes = Arrays.asList("default","jsp");
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ProfileBuilder.class);
|
||||
|
||||
private ApplicationContext context;
|
||||
|
||||
public ProfileBuilder(ApplicationContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public void fill(GCoreEndpoint endpoint) {
|
||||
|
||||
|
||||
ApplicationConfiguration configuration = context.configuration();
|
||||
ContainerConfiguration container = context.container().configuration();
|
||||
|
||||
|
||||
endpoint.profile()
|
||||
.description(configuration.description())
|
||||
.serviceName(configuration.name())
|
||||
.serviceClass(configuration.serviceClass())
|
||||
.version(configuration.version())
|
||||
.serviceId(configuration.name() + configuration.serviceClass() + configuration.version())
|
||||
.ghnId(context.container().profile(HostingNode.class).id());
|
||||
|
||||
endpoint.profile().newDeploymentData()
|
||||
.activationTime(Calendar.getInstance())
|
||||
.status((context.lifecycle().state().remoteForm()));
|
||||
|
||||
endpoint.profile().endpoints().clear();
|
||||
|
||||
String baseAddress;
|
||||
if (configuration.proxied()){
|
||||
String protocol = configuration.proxyAddress().protocol();
|
||||
String port = configuration.proxyAddress().port()!=null?":"+configuration.proxyAddress().port():"";
|
||||
|
||||
baseAddress=String.format("%s://%s%s%s", protocol , configuration.proxyAddress().hostname(), port,context.application().getContextPath());
|
||||
} else {
|
||||
String protocol = container.protocol();
|
||||
int port = container.port();
|
||||
|
||||
baseAddress=String.format("%s://%s:%d%s", protocol , container.hostname(), port,context.application().getContextPath());
|
||||
}
|
||||
|
||||
for (ServletRegistration servlet : context.application().getServletRegistrations().values())
|
||||
if (!servletExcludes.contains(servlet.getName()))
|
||||
for (String mapping : servlet.getMappings()) {
|
||||
String address = baseAddress+(mapping.endsWith("*")?mapping.substring(0,mapping.length()-2):mapping);
|
||||
endpoint.profile().endpoints().add().nameAndAddress(servlet.getName(),URI.create(address));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,215 +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.client.proxy.AuthorizationProxy;
|
||||
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
|
||||
import org.gcube.common.resources.gcore.GCoreEndpoint;
|
||||
import org.gcube.informationsystem.publisher.ScopedPublisher;
|
||||
import org.gcube.smartgears.context.application.ApplicationContext;
|
||||
import org.gcube.smartgears.provider.ProviderFactory;
|
||||
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 ProfilePublisher {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ProfilePublisher.class);
|
||||
|
||||
//the underlying IS publisher
|
||||
private final ScopedPublisher publisher;
|
||||
|
||||
private final ApplicationContext context;
|
||||
|
||||
private AuthorizationProxy authProxy ;
|
||||
|
||||
/**
|
||||
* Creates an instance for a given application.
|
||||
* @param context the context of the application
|
||||
*/
|
||||
public ProfilePublisher(ApplicationContext context) {
|
||||
this.context = context;
|
||||
this.publisher=ProviderFactory.provider().publisherFor(context);
|
||||
this.authProxy = ProviderFactory.provider().authorizationProxy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds for the first time the current resource profile of the application in one or more scopes.
|
||||
* @param scopes the scopes
|
||||
*/
|
||||
public void addTo(Collection<String> tokens) {
|
||||
|
||||
notEmpty("tokens",tokens);
|
||||
|
||||
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();
|
||||
|
||||
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]);
|
||||
Thread.currentThread().setContextClassLoader(ProfilePublisher.class.getClassLoader());
|
||||
profile = publisher.create(profile, resolveScopesFromTokens(tokens));
|
||||
|
||||
} catch (Exception e) {
|
||||
rethrowUnchecked(e);
|
||||
} finally{
|
||||
SecurityTokenProvider.instance.set(previousToken);
|
||||
Thread.currentThread().setContextClassLoader(contextCL);
|
||||
}
|
||||
|
||||
sharePublished(profile);
|
||||
log.debug("shared profile with scopes {}", profile.scopes().asCollection());
|
||||
}
|
||||
|
||||
public void addToAll() {
|
||||
this.addTo(context.configuration().startTokens());
|
||||
}
|
||||
|
||||
|
||||
public void update() {
|
||||
|
||||
|
||||
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();
|
||||
|
||||
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]);
|
||||
|
||||
Thread.currentThread().setContextClassLoader(ProfilePublisher.class.getClassLoader());
|
||||
profile = publisher.update(profile);
|
||||
|
||||
} catch (Exception e) {
|
||||
rethrowUnchecked(e);
|
||||
} finally{
|
||||
SecurityTokenProvider.instance.set(previousToken);
|
||||
Thread.currentThread().setContextClassLoader(contextCL);
|
||||
}
|
||||
|
||||
sharePublished(profile);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Removes the application from one or more scopes.
|
||||
* @param scopes the scopes
|
||||
*/
|
||||
public void removeFrom(Collection<String> tokens) {
|
||||
|
||||
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();
|
||||
|
||||
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]);
|
||||
Thread.currentThread().setContextClassLoader(ProfilePublisher.class.getClassLoader());
|
||||
profile = publisher.remove(profile, resolveScopesFromTokens(tokens));
|
||||
|
||||
} catch (Exception e) {
|
||||
rethrowUnchecked(e);
|
||||
} finally{
|
||||
SecurityTokenProvider.instance.set(previousToken);
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
@ -1,92 +0,0 @@
|
||||
package org.gcube.smartgears.handlers.application.request;
|
||||
|
||||
import static org.gcube.common.authorization.client.Constants.authorizationService;
|
||||
import static org.gcube.smartgears.Constants.scope_header;
|
||||
import static org.gcube.smartgears.Constants.token_header;
|
||||
import static org.gcube.smartgears.handlers.application.request.RequestError.internal_server_error;
|
||||
import static org.gcube.smartgears.handlers.application.request.RequestError.invalid_request_error;
|
||||
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
import org.gcube.common.authorization.client.exceptions.ObjectNotFound;
|
||||
import org.gcube.common.authorization.library.AuthorizationEntry;
|
||||
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
|
||||
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
|
||||
import org.gcube.common.authorization.library.utils.Caller;
|
||||
import org.gcube.common.scope.api.ScopeProvider;
|
||||
import org.gcube.smartgears.Constants;
|
||||
import org.gcube.smartgears.handlers.application.RequestEvent;
|
||||
import org.gcube.smartgears.handlers.application.RequestHandler;
|
||||
import org.gcube.smartgears.handlers.application.ResponseEvent;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@XmlRootElement(name = Constants.request_context_retriever)
|
||||
public class RequestContextRetriever extends RequestHandler {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(RequestContextRetriever.class);
|
||||
|
||||
private static final String BEARER_AUTH_PREFIX ="Bearer";
|
||||
private static final String BASIC_AUTH_PREFIX ="Basic";
|
||||
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return Constants.request_context_retriever;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleRequest(RequestEvent call) {
|
||||
String token = call.request().getParameter(token_header)==null? call.request().getHeader(token_header):call.request().getParameter(token_header);
|
||||
String scope = call.request().getParameter(scope_header)==null? call.request().getHeader(scope_header):call.request().getParameter(scope_header);
|
||||
|
||||
if (token==null && call.request().getHeader(Constants.authorization_header)!=null){
|
||||
|
||||
String authorization = call.request().getHeader(Constants.authorization_header);
|
||||
|
||||
if (authorization.contains(BASIC_AUTH_PREFIX)) {
|
||||
String base64Credentials = authorization.substring(BASIC_AUTH_PREFIX.length()).trim();
|
||||
String credentials = new String(DatatypeConverter.parseBase64Binary(base64Credentials));
|
||||
// credentials = username:password
|
||||
final String[] values = credentials.split(":",2);
|
||||
token = values[1];
|
||||
} else if (authorization.contains(BEARER_AUTH_PREFIX))
|
||||
token = authorization.substring(BEARER_AUTH_PREFIX.length()).trim();
|
||||
}
|
||||
|
||||
//Gives priority to the token
|
||||
if (token!=null)
|
||||
this.retreiveAndSetInfo(token, call);
|
||||
else if (scope!=null)
|
||||
ScopeProvider.instance.set(scope);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleResponse(ResponseEvent e) {
|
||||
SecurityTokenProvider.instance.reset();
|
||||
AuthorizationProvider.instance.reset();
|
||||
ScopeProvider.instance.reset();
|
||||
log.debug("resetting all the Thread local for this call.");
|
||||
}
|
||||
|
||||
private void retreiveAndSetInfo(String token, RequestEvent call){
|
||||
log.info("retrieving context using token {} ", token);
|
||||
AuthorizationEntry authEntry = null;
|
||||
try{
|
||||
authEntry = authorizationService().get(token);
|
||||
}catch(ObjectNotFound onf){
|
||||
log.warn("rejecting call to {}, invalid token {}",call.context().name(),token);
|
||||
invalid_request_error.fire(call.context().name()+" invalid token : "+token);
|
||||
}catch(Exception e){
|
||||
log.error("error contacting authorization service",e);
|
||||
internal_server_error.fire("error contacting authorization service");
|
||||
}
|
||||
|
||||
AuthorizationProvider.instance.set(new Caller(authEntry.getClientInfo(), authEntry.getQualifier()));
|
||||
SecurityTokenProvider.instance.set(token);
|
||||
ScopeProvider.instance.set(authEntry.getContext());
|
||||
log.info("retrieved request authorization info {} in scope {} ", AuthorizationProvider.instance.get(), authEntry.getContext());
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package org.gcube.smartgears.handlers.application.request;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import org.gcube.smartgears.Constants;
|
||||
import org.gcube.smartgears.handlers.application.RequestEvent;
|
||||
import org.gcube.smartgears.handlers.application.RequestHandler;
|
||||
import org.gcube.smartgears.handlers.application.ResponseEvent;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
|
||||
public class RequestMetrics extends RequestHandler {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(RequestMetrics.class);
|
||||
|
||||
private static ThreadLocal<Long> startCallThreadLocal = new ThreadLocal<Long>();
|
||||
|
||||
private static final String HTTP_REQUEST_METRICS_NAME = "http.server.requests";
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return Constants.request_metrics;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnfiltrable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleRequest(RequestEvent e) {
|
||||
startCallThreadLocal.set(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleResponse(ResponseEvent e) {
|
||||
try {
|
||||
String statusCode = Integer.toString(e.response().getStatus());
|
||||
Metrics.timer(HTTP_REQUEST_METRICS_NAME, "status", statusCode).record(Duration.ofMillis(System.currentTimeMillis() - startCallThreadLocal.get()));
|
||||
startCallThreadLocal.remove();
|
||||
}catch(Throwable t) {
|
||||
log.warn("error setting Metrics",t);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,218 @@
|
||||
package org.gcube.smartgears.handlers.container.lifecycle;
|
||||
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
import static org.gcube.common.events.Observes.Kind.critical;
|
||||
import static org.gcube.common.events.Observes.Kind.resilient;
|
||||
import static org.gcube.smartgears.Constants.profile_management;
|
||||
import static org.gcube.smartgears.handlers.ProfileEvents.changed;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.activation;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.failure;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.part_activation;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.shutdown;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.stop;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerState.active;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
|
||||
import org.gcube.common.events.Observes;
|
||||
import org.gcube.smartgears.configuration.Mode;
|
||||
import org.gcube.smartgears.context.Property;
|
||||
import org.gcube.smartgears.context.container.ContainerContext;
|
||||
import org.gcube.smartgears.handlers.container.ContainerHandler;
|
||||
import org.gcube.smartgears.handlers.container.ContainerLifecycleEvent;
|
||||
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
|
||||
import org.gcube.smartgears.lifecycle.container.ContainerState;
|
||||
import org.gcube.smartgears.managers.ContextEvents;
|
||||
import org.gcube.smartgears.provider.ProviderFactory;
|
||||
import org.gcube.smartgears.publishing.Publisher;
|
||||
import org.gcube.smartgears.utils.Utils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
* Manages the resource profile of the application.
|
||||
* <p>
|
||||
*
|
||||
* The manager:
|
||||
*
|
||||
* <ul>
|
||||
* <li>creates the profile when the application starts for the first time;
|
||||
* <li>loads the profile when the application restarts;
|
||||
* <li>publishes the profile when the application becomes active, and at any
|
||||
* lifecycle change thereafter;
|
||||
* <li>stores the profile locally after each publication;
|
||||
* </ul>
|
||||
*
|
||||
* @author Fabio Simeoni
|
||||
* @see ProfileBuilder
|
||||
* @see ProfilePublisherImpl
|
||||
*/
|
||||
public class ContainerProfileManager extends ContainerHandler {
|
||||
|
||||
Logger log = LoggerFactory.getLogger(ContainerProfileManager.class);
|
||||
|
||||
private ContainerContext context;
|
||||
private ScheduledFuture<?> periodicUpdates;
|
||||
private static final String PUBLISHED_PROP = "published";
|
||||
private List<Publisher> publishers;
|
||||
|
||||
@Override
|
||||
public void onStart(ContainerLifecycleEvent.Start e) {
|
||||
|
||||
context = e.context();
|
||||
|
||||
activated();
|
||||
|
||||
// note we don't fire profile events, but wait for the final startup
|
||||
// outcome which
|
||||
// will result in a state change. only then we publish and store the
|
||||
// profile
|
||||
// this avoids the redundancy and performance penalty of storing and
|
||||
// publishing multiple
|
||||
// times in rapid succession (which would be correct). Revise if proves
|
||||
// problematic in corner
|
||||
// cases.
|
||||
|
||||
}
|
||||
|
||||
private void activated() {
|
||||
publishers = context.configuration().mode() != Mode.offline ? ProviderFactory.provider().publishers()
|
||||
: Collections.emptyList();
|
||||
registerObservers();
|
||||
schedulePeriodicUpdates();
|
||||
}
|
||||
|
||||
private void registerObservers() {
|
||||
context.events().subscribe(new Object() {
|
||||
@Observes({ activation, part_activation, shutdown, stop, failure })
|
||||
void onChanged(ContainerLifecycle lc) {
|
||||
|
||||
// since we do not know the observers, they will deal with failures and their
|
||||
// consequences
|
||||
// any that comes back will be logged in this event thread
|
||||
context.events().fire(context, changed);
|
||||
}
|
||||
|
||||
@Observes(value = changed, kind = critical)
|
||||
void publishAfterChange(ContainerContext context) {
|
||||
log.info("Publish after profile Change event called -- contains published prop? {}",context.properties().contains(PUBLISHED_PROP));
|
||||
// if we've failed before first publication do not try to publish
|
||||
// (we may well have failed there)
|
||||
if (context.lifecycle().state() != ContainerState.failed) {
|
||||
if (!context.properties().contains(PUBLISHED_PROP)) {
|
||||
context.properties().add(new Property(PUBLISHED_PROP, true));
|
||||
log.info("publishing container for the first time");
|
||||
|
||||
publishers.parallelStream().forEach(p -> {
|
||||
try {
|
||||
p.create(context, context.authorizationProvider().getContexts());
|
||||
} catch (Throwable e) {
|
||||
log.error(
|
||||
"cannot publish container for first time with publisher type {} (see details)",
|
||||
p.getClass().getCanonicalName(), e);
|
||||
}
|
||||
});
|
||||
} else
|
||||
publishers.parallelStream().forEach(p -> {
|
||||
try {
|
||||
p.update(context);
|
||||
} catch (Throwable e) {
|
||||
log.error("cannot publish container with publisher type {} (see details)",
|
||||
p.getClass().getCanonicalName(), e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Observes(value = ContextEvents.ADD_CONTEXT_TO_CONTAINER)
|
||||
void addTo(String scope) {
|
||||
log.info("add_to_context event arrived in container");
|
||||
for (Publisher publisher : publishers)
|
||||
try {
|
||||
log.trace("publishing container within new scope");
|
||||
publisher.create(context, Collections.singleton(scope));
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
log.error("cannot add container to {} with publisher type {} (see details)", scope,
|
||||
publisher.getClass().getCanonicalName(), e);
|
||||
|
||||
// since we've failed no published event is fired and profile
|
||||
// will not be stored.
|
||||
// we do it manually to ensure we leave some local trace of the
|
||||
// changed profile.
|
||||
// TODO: CHECK --- store(profile);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Observes(value = ContextEvents.REMOVE_CONTEXT_FROM_CONTAINER)
|
||||
void removeFrom(String scope) {
|
||||
log.info("remove_from_context event arrived in container");
|
||||
for (Publisher publisher : publishers)
|
||||
try {
|
||||
log.trace("unpublishing container from context {}", scope);
|
||||
publisher.remove(context, Collections.singleton(scope));
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
log.error("cannot remove container from {} with publisher type {} (see details)", scope,
|
||||
publisher.getClass().getCanonicalName(), e);
|
||||
|
||||
// since we've failed no published event is fired and profile
|
||||
// will not be stored.
|
||||
// we do it manually to ensure we leave some local trace of the
|
||||
// changed profile.
|
||||
// TODO: CHECK --- store(profile);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void schedulePeriodicUpdates() {
|
||||
// register to cancel updates
|
||||
context.events().subscribe(new Object() {
|
||||
// we register it in response to lifecycle events so that we can stop and resume
|
||||
// along with application
|
||||
@Observes(value = { activation, part_activation }, kind = resilient)
|
||||
synchronized void restartPeriodicUpdates(ContainerLifecycle lc) {
|
||||
// already running
|
||||
if (periodicUpdates != null)
|
||||
return;
|
||||
if (lc.state() == active)
|
||||
log.info("scheduling periodic updates of container profile");
|
||||
else
|
||||
log.info("resuming periodic updates of container profile");
|
||||
final Runnable updateTask = new Runnable() {
|
||||
public void run() {
|
||||
context.events().fire(context, changed);
|
||||
}
|
||||
};
|
||||
periodicUpdates = Utils.scheduledServicePool.scheduleAtFixedRate(updateTask, 3,
|
||||
context.configuration().publicationFrequency(), SECONDS);
|
||||
}
|
||||
|
||||
@Observes(value = { stop, failure, shutdown }, kind = resilient)
|
||||
synchronized void cancelPeriodicUpdates(ContainerLifecycle ignore) {
|
||||
if (periodicUpdates != null) {
|
||||
log.trace("stopping periodic updates of container profile");
|
||||
try {
|
||||
periodicUpdates.cancel(true);
|
||||
periodicUpdates = null;
|
||||
} catch (Exception e) {
|
||||
log.warn("could not stop periodic updates of container profile", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return profile_management;
|
||||
}
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
package org.gcube.smartgears.handlers.container.lifecycle;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* @author Luca Frosini (ISTI-CNR)
|
||||
*/
|
||||
public class LinuxDistributionInfo {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(LinuxDistributionInfo.class);
|
||||
|
||||
public static final String LSB_RELEASE_COMMAND = "lsb_release -a";
|
||||
public static final String OS_RELEASE_FILE_PATH = "/etc/os-release";
|
||||
|
||||
protected Map<String, String> info;
|
||||
|
||||
protected Map<String, String> getInfoViaLsbReleaseCommand() throws IOException {
|
||||
logger.trace("Going to exec {}", LSB_RELEASE_COMMAND);
|
||||
Process process = Runtime.getRuntime().exec(LSB_RELEASE_COMMAND);
|
||||
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
Map<String, String> map = parseBufferedReader(bufferedReader);
|
||||
bufferedReader.close();
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, String> parseBufferedReader(BufferedReader bufferedReader) throws IOException {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
String line = "";
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
String[] nameValue = parseLine(line);
|
||||
map.put(nameValue[0], nameValue[1]);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private String[] parseLine(String line) {
|
||||
String[] splitted = line.split("=");
|
||||
if (splitted.length < 2) {
|
||||
splitted = line.split(":");
|
||||
}
|
||||
String[] ret = new String[2];
|
||||
ret[0] = splitted[0].trim();
|
||||
ret[1] = splitted[1].trim().replace("\"", "");
|
||||
return ret;
|
||||
}
|
||||
|
||||
private Map<String, String> getInfoViaFile(File file) throws IOException {
|
||||
logger.trace("Going to read file {}", file.getAbsolutePath());
|
||||
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
|
||||
Map<String, String> map = parseBufferedReader(bufferedReader);
|
||||
bufferedReader.close();
|
||||
return map;
|
||||
|
||||
}
|
||||
|
||||
protected Map<String, String> getInfoViaOsReleaseFile() throws IOException {
|
||||
File osReleaseFile = new File(OS_RELEASE_FILE_PATH);
|
||||
return getInfoViaFile(osReleaseFile);
|
||||
}
|
||||
|
||||
private Map<String, String> retriveInfo() {
|
||||
try {
|
||||
return getInfoViaLsbReleaseCommand();
|
||||
} catch (IOException e) {
|
||||
|
||||
}
|
||||
|
||||
try {
|
||||
return getInfoViaOsReleaseFile();
|
||||
}catch (IOException e) {
|
||||
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public Map<String, String> getInfo() {
|
||||
if (info == null) {
|
||||
info = retriveInfo();
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
}
|
@ -1,366 +0,0 @@
|
||||
package org.gcube.smartgears.handlers.container.lifecycle;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
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;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.gcube.common.resources.gcore.HostingNode;
|
||||
import org.gcube.common.resources.gcore.HostingNode.Profile.NodeDescription.GHNType;
|
||||
import org.gcube.common.resources.gcore.HostingNode.Profile.NodeDescription.Processor;
|
||||
import org.gcube.common.resources.gcore.HostingNode.Profile.NodeDescription.Variable;
|
||||
import org.gcube.common.resources.gcore.utils.Group;
|
||||
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
|
||||
import org.gcube.smartgears.configuration.library.SmartGearsConfiguration;
|
||||
import org.gcube.smartgears.context.container.ContainerContext;
|
||||
import org.gcube.smartgears.provider.ProviderFactory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* @author Fabio Simeoni
|
||||
* @author Luca Frosini (ISTI - CNR) http://www.lucafrosini.com/
|
||||
*
|
||||
*/
|
||||
public class ProfileBuilder {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(ProfileBuilder.class);
|
||||
|
||||
private ContainerContext context;
|
||||
|
||||
public ProfileBuilder(ContainerContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public HostingNode create() {
|
||||
|
||||
HostingNode node = new HostingNode();
|
||||
|
||||
ContainerConfiguration cfg = context.configuration();
|
||||
|
||||
node.newProfile().infrastructure(cfg.infrastructure());
|
||||
|
||||
addSiteTo(node);
|
||||
|
||||
String ip = "not resolved";
|
||||
try {
|
||||
ip = InetAddress.getLocalHost().getHostAddress();
|
||||
} catch (UnknownHostException e) {
|
||||
log.warn("unable to detect the IP address of the host");
|
||||
}
|
||||
|
||||
node.profile().newDescription().activationTime(Calendar.getInstance()).name(cfg.hostname() + ":" + cfg.port());
|
||||
|
||||
node.profile().description().networkAdapters().add().mtu(0).name("local-adapter").ipAddress(ip).inboundIP("")
|
||||
.outboundIP("");
|
||||
|
||||
node.profile().description().newOperatingSystem().name(System.getProperty("os.name"))
|
||||
.version(System.getProperty("os.version")).release("");
|
||||
|
||||
node.profile().description().newArchitecture().platformType(System.getProperty("os.arch")).smpSize(0)
|
||||
.smtSize(0);
|
||||
|
||||
ArrayList<HashMap<String, String>> info = cpuInfo();
|
||||
|
||||
Group<Processor> processors = node.profile().description().processors();
|
||||
|
||||
for (HashMap<String, String> map : info)
|
||||
|
||||
processors.add().bogomips(new BigDecimal(map.get("bogomips")))
|
||||
.clockSpeedMhz(new BigDecimal(map.get("cpu_MHz"))).family(map.get("cpu_family"))
|
||||
.modelName(map.get("model_name")).model(map.get("model")).vendor(map.get("vendor_id"))
|
||||
.cacheL1(new Integer(map.get("cache_size"))).cacheL1D(0).cacheL1I(0).cacheL2(0);
|
||||
|
||||
addVariablesTo(node);
|
||||
|
||||
update(node,false);
|
||||
|
||||
node.profile().description().type(GHNType.Static);
|
||||
// String type = (String) context.getProperty(GHNContext.GHN_TYPE, false);
|
||||
// if (type.compareToIgnoreCase(Type.DYNAMIC.toString()) == 0) description.setType(Description.Type.Dynamic);
|
||||
// else if (type.compareToIgnoreCase(Type.STATIC.toString()) == 0) description.setType(Description.Type.Static);
|
||||
// else if (type.compareToIgnoreCase(Type.SELFCLEANING.toString()) == 0)
|
||||
// description.setType(Description.Type.Selfcleaning);
|
||||
//
|
||||
// file system
|
||||
node.profile().description().localFileSystems().add().name("").type("").readOnly(false)
|
||||
.root(cfg.persistence().location());
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
@SuppressWarnings("all")
|
||||
private ArrayList<HashMap<String, String>> cpuInfo() {
|
||||
|
||||
ArrayList<HashMap<String, String>> map = new ArrayList<HashMap<String, String>>();
|
||||
|
||||
File file = new File("/proc/cpuinfo");
|
||||
|
||||
if (!file.exists()) {
|
||||
log.warn("cannot acquire CPU info (no /proc/cpuinfo)");
|
||||
return map;
|
||||
}
|
||||
|
||||
BufferedReader input = null;
|
||||
|
||||
try {
|
||||
input = new BufferedReader(new FileReader(file));
|
||||
|
||||
String line = null;
|
||||
|
||||
HashMap<String, String> currentProcessor = null;
|
||||
|
||||
while ((line = input.readLine()) != null) {
|
||||
|
||||
if ((line.startsWith("processor"))) { // add the current processor to the map
|
||||
|
||||
if (currentProcessor != null)
|
||||
map.add((HashMap) currentProcessor.clone());
|
||||
|
||||
currentProcessor = new HashMap<String, String>();
|
||||
}
|
||||
|
||||
try {
|
||||
if (line.contains("vendor_id"))
|
||||
currentProcessor.put("vendor_id", line.split(":")[1].trim());
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
try {
|
||||
if (line.contains("cpu family"))
|
||||
currentProcessor.put("cpu_family", line.split(":")[1].trim());
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
try {
|
||||
if ((line.contains("model\t")) || (line.contains("model\b")))
|
||||
currentProcessor.put("model", line.split(":")[1].trim());
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
try {
|
||||
if (line.contains("model name"))
|
||||
currentProcessor.put("model_name", line.split(":")[1].trim());
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
try {
|
||||
if (line.contains("cpu MHz"))
|
||||
currentProcessor.put("cpu_MHz", line.split(":")[1].trim());
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
try {
|
||||
if (line.contains("cache size"))
|
||||
currentProcessor.put("cache_size", line.split(":")[1].trim().split(" ")[0]);
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
try {
|
||||
if (line.contains("bogomips"))
|
||||
currentProcessor.put("bogomips", line.split(":")[1].trim());
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
}
|
||||
|
||||
if (currentProcessor != null)
|
||||
map.add(currentProcessor);
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
log.warn("unable to acquire CPU info", e);
|
||||
|
||||
} finally {
|
||||
|
||||
if (input != null)
|
||||
try {
|
||||
input.close();
|
||||
} catch (IOException e) {
|
||||
log.warn("unable to close stream", e);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private long getFreeSpace() {
|
||||
long free = 0;
|
||||
try {
|
||||
free = Files.getFileStore(Paths.get(context.configuration().persistence().location())).getUsableSpace()/1024;
|
||||
} catch (IOException ioe) {
|
||||
log.warn("unable to detect the free space on the disk", ioe);
|
||||
}
|
||||
return free;
|
||||
}
|
||||
|
||||
public void update(HostingNode node,boolean onLoad) {
|
||||
|
||||
ContainerConfiguration cfg = context.configuration();
|
||||
|
||||
if (onLoad) {
|
||||
|
||||
log.info("updating ghn profile");
|
||||
|
||||
node.profile().description().activationTime(Calendar.getInstance()).name(cfg.hostname() + ":" + cfg.port());
|
||||
|
||||
addVariablesTo(node);
|
||||
|
||||
addSiteTo(node);
|
||||
|
||||
}
|
||||
|
||||
node.profile().description().status(context.lifecycle().state().remoteForm());
|
||||
|
||||
Map<String, Long> mem = memoryUsage();
|
||||
|
||||
node.profile().description().newMainMemory().ramAvailable(mem.get("MemoryAvailable"))
|
||||
.ramSize(mem.get("MemoryTotalSize")).virtualAvailable(mem.get("VirtualAvailable"))
|
||||
.virtualSize(mem.get("VirtualSize"));
|
||||
|
||||
node.profile().description().localAvailableSpace(getFreeSpace());
|
||||
|
||||
node.profile().description().uptime(uptime());
|
||||
|
||||
node.profile().description().lastUpdate(Calendar.getInstance());
|
||||
|
||||
Map<String, Double> loads = loadStatistics();
|
||||
|
||||
node.profile().description().newLoad().lastMin(loads.get("1min") == null ? 0 : loads.get("1min"))
|
||||
.last5Mins(loads.get("5mins") == null ? 0 : loads.get("5mins"))
|
||||
.last15Mins(loads.get("15mins") == null ? 0 : loads.get("15mins"));
|
||||
|
||||
}
|
||||
|
||||
private void addSiteTo(HostingNode node) {
|
||||
|
||||
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()));
|
||||
}
|
||||
|
||||
private void addVariablesTo(HostingNode node) {
|
||||
|
||||
ContainerConfiguration cfg = context.configuration();
|
||||
|
||||
Group<Variable> variables = node.profile().description().environmentVariables();
|
||||
|
||||
// Cleaning variables to avoid duplicates
|
||||
variables.removeAll(node.profile().description().environmentVariables());
|
||||
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
map.putAll(cfg.properties());
|
||||
map.putAll(System.getenv());
|
||||
|
||||
for (Map.Entry<String, String> entry : map.entrySet()) {
|
||||
String varname = entry.getKey();
|
||||
if ((varname.compareToIgnoreCase("CLASSPATH") == 0) || (varname.compareToIgnoreCase("PATH") == 0)
|
||||
|| (varname.contains("SSH")) || (varname.contains("MAIL"))
|
||||
|| (varname.compareToIgnoreCase("LS_COLORS") == 0))
|
||||
continue;
|
||||
variables.add().keyAndValue(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
/* The following code is useless can be removed
|
||||
Map<String, String> envvars = new HashMap<String, String>();
|
||||
for (String varname : envvars.keySet()) {
|
||||
|
||||
// a bit of filtering
|
||||
if ((varname.compareToIgnoreCase("CLASSPATH") == 0) || (varname.compareToIgnoreCase("PATH") == 0)
|
||||
|| (varname.contains("SSH")) || (varname.contains("MAIL"))
|
||||
|| (varname.compareToIgnoreCase("LS_COLORS") == 0))
|
||||
continue;
|
||||
|
||||
variables.add().keyAndValue(varname, envvars.get(varname));
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
variables.add().keyAndValue("Java", System.getProperty("java.version"));
|
||||
|
||||
SmartGearsConfiguration config = ProviderFactory.provider().smartgearsConfiguration();
|
||||
variables.add().keyAndValue("SmartGears",config.version());
|
||||
|
||||
variables.add().keyAndValue("ghn-update-interval-in-secs", String.valueOf(cfg.publicationFrequency()));
|
||||
|
||||
}
|
||||
|
||||
public String uptime() {
|
||||
String lines = "", linetemp = null;
|
||||
try {
|
||||
Process p = Runtime.getRuntime().exec("uptime");
|
||||
p.waitFor();
|
||||
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
|
||||
while ((linetemp = input.readLine()) != null)
|
||||
lines += linetemp;
|
||||
input.close();
|
||||
p.destroy();
|
||||
lines = lines.split(",")[0].split("up")[1].trim();
|
||||
} catch (Exception e) {
|
||||
log.warn("unable to detect the uptime of this machine", e);
|
||||
lines = "unable to detect";
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
public Map<String, Double> loadStatistics() {
|
||||
|
||||
Map<String, Double> result = new HashMap<String, Double>();
|
||||
try {
|
||||
File loadadv = new File("/proc/loadavg");
|
||||
if (loadadv.exists()) {
|
||||
Reader reader = new FileReader(loadadv);
|
||||
int c;
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((c = reader.read()) != -1)
|
||||
content.append((char) c);
|
||||
reader.close();
|
||||
Pattern p = Pattern.compile("^(.*?)\\s{1}(.*?)\\s{1}(.*?)\\s{1}(.*)$");
|
||||
Matcher matcher = p.matcher(content.toString());
|
||||
if ((matcher.matches()) && (matcher.groupCount() > 3)) {
|
||||
result.put("1min", new Double(matcher.group(1)));
|
||||
result.put("5mins", new Double(matcher.group(2)));
|
||||
result.put("15mins", new Double(matcher.group(3).split("\\s")[0]));
|
||||
}
|
||||
}
|
||||
} catch (Exception ioe) {
|
||||
log.warn("unable to detect the load values of this machine", ioe);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@SuppressWarnings("all")
|
||||
public Map<String, Long> memoryUsage() {
|
||||
Map<String, Long> map = new HashMap<String, Long>();
|
||||
java.lang.management.OperatingSystemMXBean mxbean = java.lang.management.ManagementFactory
|
||||
.getOperatingSystemMXBean();
|
||||
com.sun.management.OperatingSystemMXBean sunmxbean = (com.sun.management.OperatingSystemMXBean) mxbean;
|
||||
long freeMemory = sunmxbean.getFreePhysicalMemorySize() / 1048576; // in MB
|
||||
long availableMemory = sunmxbean.getTotalPhysicalMemorySize() / 1048576; // in MB
|
||||
map.put("MemoryAvailable", freeMemory);
|
||||
map.put("MemoryTotalSize", availableMemory);
|
||||
long ramVirtualAvailable = Runtime.getRuntime().freeMemory() / 1048576; // in MB
|
||||
long ramVirtualSize = Runtime.getRuntime().totalMemory() / 1048576; // in MB
|
||||
map.put("VirtualAvailable", ramVirtualAvailable);
|
||||
map.put("VirtualSize", ramVirtualSize);
|
||||
return map;
|
||||
}
|
||||
|
||||
private String domainIn(String hostname) {
|
||||
Pattern pattern = Pattern.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})");
|
||||
java.util.regex.Matcher regexMatcher = pattern.matcher(hostname);
|
||||
if (regexMatcher.matches()) //it's an IP address, nothing to trim
|
||||
return hostname;
|
||||
String[] tokens = hostname.split("\\.");
|
||||
if (tokens.length < 2)
|
||||
return hostname;
|
||||
else
|
||||
return tokens[tokens.length-2]+ "." + tokens[tokens.length-1];
|
||||
}
|
||||
}
|
@ -1,289 +0,0 @@
|
||||
package org.gcube.smartgears.handlers.container.lifecycle;
|
||||
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
import static org.gcube.common.events.Observes.Kind.critical;
|
||||
import static org.gcube.common.events.Observes.Kind.resilient;
|
||||
import static org.gcube.smartgears.Constants.container_profile_property;
|
||||
import static org.gcube.smartgears.Constants.profile_management;
|
||||
import static org.gcube.smartgears.handlers.ProfileEvents.addToContext;
|
||||
import static org.gcube.smartgears.handlers.ProfileEvents.changed;
|
||||
import static org.gcube.smartgears.handlers.ProfileEvents.published;
|
||||
import static org.gcube.smartgears.handlers.ProfileEvents.removeFromContext;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.activation;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.failure;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.part_activation;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.shutdown;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerLifecycle.stop;
|
||||
import static org.gcube.smartgears.lifecycle.container.ContainerState.active;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
import org.gcube.common.events.Observes;
|
||||
import org.gcube.common.resources.gcore.HostingNode;
|
||||
import org.gcube.smartgears.context.Property;
|
||||
import org.gcube.smartgears.context.container.ContainerContext;
|
||||
import org.gcube.smartgears.handlers.container.ContainerHandler;
|
||||
import org.gcube.smartgears.handlers.container.ContainerLifecycleEvent.Start;
|
||||
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
|
||||
import org.gcube.smartgears.utils.Utils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
* Manages the resource profile of the container.
|
||||
* <p>
|
||||
*
|
||||
* The manager:
|
||||
*
|
||||
* <ul>
|
||||
* <li>creates the profile when the container starts for the first time;
|
||||
* <li>loads the profile when the container restarts;
|
||||
* <li>publishes the profile when the container becomes active, and at any lifecycle change thereafter;
|
||||
* <li>stores the profile locally after each publication;
|
||||
* </ul>
|
||||
*
|
||||
* @author Fabio Simeoni
|
||||
* @see ProfileBuilder
|
||||
*/
|
||||
@XmlRootElement(name = profile_management)
|
||||
public class ProfileManager extends ContainerHandler {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(ProfileManager.class);
|
||||
|
||||
private ContainerContext context;
|
||||
|
||||
private ProfileBuilder builder;
|
||||
private ProfilePublisher publisher;
|
||||
|
||||
|
||||
private ScheduledFuture<?> periodicUpdates;
|
||||
|
||||
@Override
|
||||
public void onStart(Start e) {
|
||||
|
||||
context = e.context();
|
||||
builder = new ProfileBuilder(context);
|
||||
|
||||
activated();
|
||||
|
||||
// note we don't fire profile events, but wait for the final startup response which
|
||||
// will result in a state change. only then we publish and store the profile
|
||||
// this avoids the redundancy and performance penalty of storing and publishing multiple
|
||||
// times in rapid succession (which would be correct). Revise if proves problematic in corner
|
||||
// cases.
|
||||
|
||||
}
|
||||
|
||||
private void activated(){
|
||||
HostingNode profile = loadOrCreateProfile();
|
||||
|
||||
share(profile);
|
||||
|
||||
publisher = new ProfilePublisher(context);
|
||||
|
||||
registerObservers();
|
||||
|
||||
schedulePeriodicUpdates();
|
||||
}
|
||||
|
||||
private void registerObservers() {
|
||||
|
||||
context.events().subscribe(new Object() {
|
||||
|
||||
@Observes({ activation, part_activation, shutdown, stop, failure })
|
||||
void onChanged(ContainerLifecycle lc) {
|
||||
|
||||
HostingNode profile = context.profile(HostingNode.class);
|
||||
|
||||
profile.profile().description().status(lc.state().remoteForm());
|
||||
|
||||
// since we do not know the observers, they will deal with failures and their consequences
|
||||
// any that comes back will be logged in this event thread
|
||||
context.events().fire(profile, changed);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Observes(value = published)
|
||||
void shareAfterPublish(HostingNode profile) {
|
||||
|
||||
share(profile); // publish may produce a new profile instance
|
||||
|
||||
}
|
||||
|
||||
@Observes(value = changed, kind = critical)
|
||||
void publishAfterChange(HostingNode profile) {
|
||||
log.info("Publish after profile Change event called");
|
||||
publish(profile); // if successful, triggers share and store.
|
||||
|
||||
}
|
||||
|
||||
@Observes(value = addToContext)
|
||||
void addTo(String token) {
|
||||
try {
|
||||
log.trace("publishing container with new token");
|
||||
publisher.addTo(Collections.singleton(token));
|
||||
publisher.update();
|
||||
}catch (Exception e) {
|
||||
|
||||
log.error("cannot add token {} (see details)",token, e);
|
||||
|
||||
// since we've failed no published event is fired and profile
|
||||
// will not be stored.
|
||||
// we do it manually to ensure we leave some local trace of the
|
||||
// changed profile.
|
||||
//TODO: CHECK --- store(profile);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Observes(value = removeFromContext)
|
||||
void removeFrom(String token) {
|
||||
try {
|
||||
log.trace("unpublishing container with new token");
|
||||
publisher.removeFrom(Collections.singleton(token));
|
||||
publisher.update();
|
||||
}catch (Exception e) {
|
||||
|
||||
log.error("cannot remove token {} (see details)",token, e);
|
||||
|
||||
// since we've failed no published event is fired and profile
|
||||
// will not be stored.
|
||||
// we do it manually to ensure we leave some local trace of the
|
||||
// changed profile.
|
||||
//TODO: CHECK --- store(profile);
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private HostingNode loadOrCreateProfile() {
|
||||
|
||||
return createProfile();
|
||||
|
||||
}
|
||||
|
||||
private void share(HostingNode profile) {
|
||||
|
||||
log.trace("sharing container profile");
|
||||
context.properties().add(new Property(container_profile_property, profile));
|
||||
}
|
||||
|
||||
private HostingNode createProfile() {
|
||||
|
||||
log.info("creating container profile");
|
||||
|
||||
try {
|
||||
HostingNode node = builder.create();
|
||||
node.setId(context.id());
|
||||
return node;
|
||||
} catch (Throwable e) {
|
||||
|
||||
// this is a critical startup failure: it will fail the application
|
||||
throw new RuntimeException("cannot create container profile", e);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void publish(HostingNode profile) {
|
||||
|
||||
//ContainerConfiguration configuration = context.configuration();
|
||||
|
||||
// first-publication vs. routine publication: when we delete scopes let's make sure there is
|
||||
// at least one left of it will be re-triggered
|
||||
boolean firstPublication = profile.scopes().isEmpty();
|
||||
|
||||
try {
|
||||
|
||||
if (firstPublication)
|
||||
publisher.addToAll();
|
||||
else
|
||||
publisher.update();
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
log.error("cannot publish container (see details)", e);
|
||||
|
||||
// since we've failed no published event is fired and profile will not be stored.
|
||||
// we do it manually to ensure we leave some local trace of the changed profile.
|
||||
//store(profile);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void schedulePeriodicUpdates() {
|
||||
|
||||
// register to cancel updates
|
||||
context.events().subscribe(
|
||||
|
||||
new Object() {
|
||||
|
||||
// we register it in response to lifecycle events so that we can stop and resume along with application
|
||||
@Observes(value = { activation, part_activation }, kind = resilient)
|
||||
synchronized void restartPeriodicUpdates(ContainerLifecycle lc) {
|
||||
|
||||
//already running
|
||||
if (periodicUpdates!=null)
|
||||
return;
|
||||
|
||||
if (lc.state()==active)
|
||||
log.info("scheduling periodic updates of container profile");
|
||||
|
||||
else
|
||||
log.info("resuming periodic updates of container profile");
|
||||
|
||||
final Runnable updateTask = new Runnable() {
|
||||
public void run() {
|
||||
HostingNode profile = context.profile(HostingNode.class);
|
||||
|
||||
try {
|
||||
builder.update(profile, false);
|
||||
}
|
||||
catch(Exception e) {
|
||||
//we may fail in the update of the profile
|
||||
log.error("cannot complete periodic update of container profile",e);
|
||||
}
|
||||
|
||||
//if handling of event generates failures these will be reported
|
||||
//for resilience we do not fail the application
|
||||
log.trace("firing change event on container profile");
|
||||
context.events().fire(profile,changed);
|
||||
}
|
||||
};
|
||||
|
||||
periodicUpdates = Utils.scheduledServicePool.scheduleAtFixedRate(updateTask, 3, context.configuration()
|
||||
.publicationFrequency(), SECONDS);
|
||||
|
||||
}
|
||||
|
||||
@Observes(value = { stop, failure, shutdown }, kind = resilient)
|
||||
synchronized void cancelPeriodicUpdates(ContainerLifecycle ignore) {
|
||||
|
||||
if (periodicUpdates != null){
|
||||
log.trace("stopping periodic updates of container profile");
|
||||
|
||||
try {
|
||||
periodicUpdates.cancel(true);
|
||||
periodicUpdates=null;
|
||||
}
|
||||
catch(Exception e) {
|
||||
log.warn("could not stop periodic updates of container profile",e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return profile_management;
|
||||
}
|
||||
}
|
@ -1,233 +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.context.container.ContainerContext;
|
||||
import org.gcube.smartgears.handlers.ProfileEvents;
|
||||
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 ProfilePublisher {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ProfilePublisher.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 ProfilePublisher(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();
|
||||
|
||||
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]);
|
||||
Thread.currentThread().setContextClassLoader(ProfilePublisher.class.getClassLoader());
|
||||
profile = publisher.create(profile, resolveScopesFromTokens(tokens));
|
||||
} catch (Exception e) {
|
||||
rethrowUnchecked(e);
|
||||
} finally {
|
||||
SecurityTokenProvider.instance.set(previousToken);
|
||||
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();
|
||||
|
||||
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]);
|
||||
|
||||
Thread.currentThread().setContextClassLoader(ProfilePublisher.class.getClassLoader());
|
||||
profile = publisher.update(profile);
|
||||
} catch (Exception e) {
|
||||
rethrowUnchecked(e);
|
||||
} finally {
|
||||
SecurityTokenProvider.instance.set(previousToken);
|
||||
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();
|
||||
|
||||
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]);
|
||||
Thread.currentThread().setContextClassLoader(ProfilePublisher.class.getClassLoader());
|
||||
profile = publisher.remove(profile, resolveScopesFromTokens(tokens));
|
||||
} catch (Exception e) {
|
||||
rethrowUnchecked(e);
|
||||
} finally {
|
||||
SecurityTokenProvider.instance.set(previousToken);
|
||||
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;
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package org.gcube.smartgears.health;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import org.gcube.common.health.api.HealthCheck;
|
||||
|
||||
public class HealthManager {
|
||||
|
||||
private List<HealthCheck> checks = new LinkedList<>();
|
||||
|
||||
public void register(HealthCheck check){
|
||||
checks.add(check);
|
||||
}
|
||||
|
||||
public List<HealthCheck> getChecks() {
|
||||
return checks;
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package org.gcube.smartgears.health;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import org.gcube.com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import org.gcube.common.health.api.Status;
|
||||
import org.gcube.common.health.api.response.HealthCheckResponse;
|
||||
import org.gcube.common.validator.annotations.NotNull;
|
||||
|
||||
@JsonInclude(Include.NON_NULL)
|
||||
public class HealthResponse {
|
||||
|
||||
@NotNull
|
||||
private Status status;
|
||||
|
||||
private List<HealthCheckResponse> checks;
|
||||
|
||||
|
||||
|
||||
public HealthResponse(Status status, List<HealthCheckResponse> checks) {
|
||||
super();
|
||||
this.status = status;
|
||||
this.checks = checks;
|
||||
}
|
||||
|
||||
public Status getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public List<HealthCheckResponse> getChecks() {
|
||||
return checks;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package org.gcube.smartgears.health;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.TimerTask;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.gcube.common.health.api.HealthCheck;
|
||||
import org.gcube.common.health.api.Status;
|
||||
import org.gcube.common.health.api.response.HealthCheckResponse;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class HealthTask extends TimerTask{
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(HealthTask.class);
|
||||
|
||||
private HealthResponse response;
|
||||
|
||||
private HealthManager healthManager;
|
||||
|
||||
public HealthTask(HealthManager healthManager) {
|
||||
this.healthManager = healthManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
List<HealthCheck> checks = healthManager.getChecks();
|
||||
|
||||
List<HealthCheckResponse> responses = checks.stream().map(c -> this.wrap(c)).collect(Collectors.toList());
|
||||
Status totalStatus = responses.stream().anyMatch(r -> r.getStatus().equals(Status.DOWN)) ? Status.DOWN : Status.UP;
|
||||
|
||||
this.response = new HealthResponse(totalStatus, responses);
|
||||
log.trace("health task executed with total status {}",totalStatus);
|
||||
}
|
||||
|
||||
public HealthResponse getResponse() {
|
||||
return response;
|
||||
}
|
||||
|
||||
private HealthCheckResponse wrap(HealthCheck check){
|
||||
try {
|
||||
return check.check();
|
||||
}catch (Throwable t) {
|
||||
return HealthCheckResponse.builder(check.getName()).down().error(t.getMessage()).build();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package org.gcube.smartgears.health;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import org.gcube.common.health.api.HealthCheck;
|
||||
import org.gcube.common.health.api.ReadinessChecker;
|
||||
import org.gcube.common.health.api.response.HealthCheckResponse;
|
||||
import org.gcube.smartgears.provider.ProviderFactory;
|
||||
|
||||
@ReadinessChecker
|
||||
public class KeyCloakHealthCheck implements HealthCheck{
|
||||
|
||||
private static final String CHECK_NAME = "authorization-check" ;
|
||||
|
||||
public String getName(){
|
||||
return CHECK_NAME;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HealthCheckResponse check() {
|
||||
try {
|
||||
Set<String> contexts = ProviderFactory.provider().containerContext().authorizationProvider().getContexts();
|
||||
if (contexts.isEmpty())
|
||||
return HealthCheckResponse.builder(CHECK_NAME).down().error("no contexts are defined for the client id provided").build();
|
||||
return HealthCheckResponse.builder(CHECK_NAME).up().info(String.format("running contexts are %s", contexts)).build();
|
||||
}catch (Exception e) {
|
||||
return HealthCheckResponse.builder(CHECK_NAME).down().error(e.getMessage()).build();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
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 java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.gcube.smartgears.configuration.ComponentConfiguration;
|
||||
import org.gcube.smartgears.configuration.ConfiguredWith;
|
||||
|
||||
@ConfiguredWith(LocalWriterConfiguration.class)
|
||||
public class LocalWriter implements PersistenceWriter {
|
||||
|
||||
private String location;
|
||||
|
||||
@Override
|
||||
public void configure(ComponentConfiguration configuration) {
|
||||
this.location = ((LocalWriterConfiguration) configuration).getLocation();
|
||||
|
||||
}
|
||||
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
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 long getFreeSpace() {
|
||||
try {
|
||||
return Files.getFileStore(Paths.get(location)).getUsableSpace();
|
||||
}catch (Exception e) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package org.gcube.smartgears.persistence;
|
||||
|
||||
import org.gcube.common.validator.annotations.NotEmpty;
|
||||
import org.gcube.common.validator.annotations.NotNull;
|
||||
import org.gcube.smartgears.configuration.ComponentConfiguration;
|
||||
|
||||
public class LocalWriterConfiguration implements ComponentConfiguration{
|
||||
|
||||
@NotEmpty @NotNull
|
||||
private String location;
|
||||
|
||||
protected LocalWriterConfiguration() {}
|
||||
|
||||
public LocalWriterConfiguration(String location) {
|
||||
super();
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return location;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,13 +0,0 @@
|
||||
package org.gcube.smartgears.persistence;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public interface Persistence {
|
||||
|
||||
String location();
|
||||
|
||||
File file(String path);
|
||||
|
||||
File writefile(String path);
|
||||
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package org.gcube.smartgears.persistence;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.gcube.smartgears.configuration.Configurable;
|
||||
|
||||
public interface PersistenceWriter extends Configurable{
|
||||
|
||||
File file(String path);
|
||||
|
||||
File writefile(String path);
|
||||
|
||||
long getFreeSpace();
|
||||
|
||||
String getLocation();
|
||||
|
||||
}
|
@ -1,56 +0,0 @@
|
||||
package org.gcube.smartgears.provider;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
import org.gcube.common.resources.gcore.Resource;
|
||||
import org.gcube.informationsystem.publisher.ScopedPublisher;
|
||||
import org.gcube.informationsystem.publisher.exception.RegistryNotFoundException;
|
||||
import org.gcube.smartgears.configuration.Mode;
|
||||
|
||||
/**
|
||||
* An implementation of {@link ScopedPublisher} that simulates remote publication.
|
||||
* <p>
|
||||
* Used for applications and or containers that operate in {@link Mode#offline}.
|
||||
*
|
||||
* @author Fabio Simeoni
|
||||
*
|
||||
*/
|
||||
public class OfflinePublisher implements ScopedPublisher {
|
||||
|
||||
@Override
|
||||
public <T extends Resource> T update(T resource){
|
||||
// do nothing
|
||||
return resource;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Resource> T create(T resource, List<String> scopes)
|
||||
throws RegistryNotFoundException {
|
||||
// fragile! bypass restrictions reflectively and set new scope
|
||||
for (String scope : scopes)
|
||||
try {
|
||||
Method m = resource.getClass().getSuperclass().getDeclaredMethod("addScope", String.class);
|
||||
m.setAccessible(true);
|
||||
m.invoke(resource, scope);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("could not simulate publication in scope " + scope, e);
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Resource> T remove(T resource, List<String> scopes)
|
||||
throws RegistryNotFoundException {
|
||||
for (String scope : scopes)
|
||||
try {
|
||||
Method m = resource.getClass().getSuperclass().getDeclaredMethod("removeScope", String.class);
|
||||
m.setAccessible(true);
|
||||
m.invoke(resource, scope);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("could not simulate publication remove from scope " + scope, e);
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
package org.gcube.smartgears.publishing;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import org.gcube.smartgears.context.application.ApplicationContext;
|
||||
import org.gcube.smartgears.context.container.ContainerContext;
|
||||
|
||||
public interface Publisher {
|
||||
|
||||
/**
|
||||
* creates the container resource in the context
|
||||
*
|
||||
* @param container
|
||||
* @param contexts the new contexts where the resource must be created
|
||||
* @return
|
||||
*/
|
||||
boolean create(ContainerContext container, Set<String> contexts);
|
||||
|
||||
/**
|
||||
* creates the application resource in the contexts
|
||||
*
|
||||
* @param application
|
||||
* @param contexts the new contexts where the resource must be created
|
||||
* @return
|
||||
*/
|
||||
boolean create(ApplicationContext application, Set<String> contexts);
|
||||
|
||||
|
||||
/**
|
||||
* updates the application resource
|
||||
*
|
||||
* @param application
|
||||
* @return
|
||||
*/
|
||||
boolean update(ApplicationContext application);
|
||||
|
||||
/**
|
||||
* updates the container resource
|
||||
*
|
||||
* @param container
|
||||
* @return
|
||||
*/
|
||||
boolean update(ContainerContext container);
|
||||
|
||||
|
||||
/**
|
||||
* removes the application resource from the contexts
|
||||
*
|
||||
* @param application
|
||||
* @param contexts the contexts from where the resource must be removed
|
||||
* @return
|
||||
*/
|
||||
boolean remove(ApplicationContext application, Set<String> contexts);
|
||||
|
||||
|
||||
/**
|
||||
* removes the container resource from the contexts
|
||||
* @param application
|
||||
* @param contexts the contexts from where the resource must be removed
|
||||
* @return
|
||||
*/
|
||||
boolean remove(ContainerContext application, Set<String> contexts);
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package org.gcube.smartgears.publishing;
|
||||
|
||||
public @interface SmartgearsProfilePublisher {
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package org.gcube.smartgears.security;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import org.gcube.common.security.credentials.Credentials;
|
||||
import org.gcube.common.security.secrets.Secret;
|
||||
|
||||
public interface AuthorizationProvider {
|
||||
|
||||
Set<String> getContexts();
|
||||
|
||||
Secret getSecretForContext(String context);
|
||||
|
||||
Credentials getCredentials();
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package org.gcube.smartgears.security;
|
||||
|
||||
import org.gcube.common.security.credentials.Credentials;
|
||||
|
||||
public interface AuthorizationProviderFactory<T extends AuthorizationProvider> {
|
||||
|
||||
T connect(Credentials credentials);
|
||||
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package org.gcube.smartgears.security;
|
||||
|
||||
import org.gcube.common.security.credentials.Credentials;
|
||||
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 + "]";
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
package org.gcube.smartgears.security.defaults;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.gcube.common.keycloak.KeycloakClient;
|
||||
import org.gcube.common.keycloak.KeycloakClientFactory;
|
||||
import org.gcube.common.keycloak.model.AccessToken.Access;
|
||||
import org.gcube.common.keycloak.model.ModelUtils;
|
||||
import org.gcube.common.keycloak.model.TokenResponse;
|
||||
import org.gcube.common.security.ContextBean;
|
||||
import org.gcube.common.security.secrets.Secret;
|
||||
import org.gcube.common.security.secrets.UmaTokenSecret;
|
||||
import org.gcube.smartgears.security.AuthorizationProvider;
|
||||
import org.gcube.smartgears.security.SimpleCredentials;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class DefaultAuthorizationProvider implements AuthorizationProvider {
|
||||
|
||||
private static Logger LOG = LoggerFactory.getLogger(DefaultAuthorizationProvider.class);
|
||||
|
||||
private KeycloakClient client = KeycloakClientFactory.newInstance();
|
||||
|
||||
private SimpleCredentials credentials;
|
||||
|
||||
private String endpoint;
|
||||
|
||||
public DefaultAuthorizationProvider(SimpleCredentials credentials, String endpoint) {
|
||||
this.credentials = credentials;
|
||||
this.endpoint = endpoint;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getContexts() {
|
||||
Set<String> contexts = new HashSet<String>();
|
||||
try {
|
||||
TokenResponse response = client.queryOIDCToken(new URL(this.endpoint), credentials.getClientID(), credentials.getSecret());
|
||||
Map<String, Access> resourceAccess = ModelUtils.getAccessTokenFrom(response).getResourceAccess();
|
||||
for (String context : resourceAccess.keySet()) {
|
||||
try {
|
||||
ContextBean scope = new ContextBean(context.replaceAll("%2F", "/"));
|
||||
contexts.add(scope.toString());
|
||||
LOG.debug("found context {}",context);
|
||||
}catch (IllegalArgumentException e) {
|
||||
LOG.debug("invalid context found in token: {}", context);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.error("error getting OIDToken from keycloak",e);
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return contexts;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Secret getSecretForContext(String context) {
|
||||
try {
|
||||
TokenResponse response = client.queryUMAToken(new URL(this.endpoint), credentials.getClientID(), credentials.getSecret(), context, null);
|
||||
return new UmaTokenSecret(response.getAccessToken());
|
||||
|
||||
} catch (Exception e) {
|
||||
LOG.error("error getting OIDToken from keycloak",e);
|
||||
throw new RuntimeException("error getting access token for context "+context, e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public SimpleCredentials getCredentials() {
|
||||
return credentials;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue