Compare commits

..

10 Commits

Author SHA1 Message Date
lucio a8284cd9d4 update for ContextManager interface change 2024-05-08 10:54:56 +02:00
lucio 5e9492da8e fixed add and remove of a context using the conductor 2024-03-06 16:47:18 +01:00
lucio 8069bdae44 package updated 2024-01-25 13:35:44 +01:00
lucio 8f2a7b33d6 moved to REST interface 2024-01-25 13:27:13 +01:00
lucio 6bd96ecee2 modified 2024-01-24 16:28:38 +01:00
lucio 000b6e49fc updated with configuration for smartgears 4 2024-01-24 16:25:09 +01:00
Lucio Lelii 08ccc15f63 updated for the latest modification of smartgears 2023-01-23 15:52:13 +01:00
Lucio Lelii 25e5321e6f import fixed 2022-07-27 09:32:08 +02:00
Lucio Lelii b9ca6eab87 added call to Keycloak to add and remove contexts 2022-06-24 15:55:42 +02:00
Lucio Lelii 570b010506 porting to smartgears 4 2022-06-10 18:33:29 +02:00
26 changed files with 554 additions and 354 deletions

View File

@ -1,28 +1,13 @@
<?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"/>
</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"/>
<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.7">
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
@ -32,5 +17,24 @@
<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"/>
<attribute name="optional" value="true"/>
</attributes>
</classpathentry>
<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 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 kind="output" path="target/classes"/>
</classpath>

View File

@ -15,6 +15,11 @@
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
@ -22,8 +27,11 @@
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>

13
.settings/.jsdtscope Normal file
View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<classpathentry excluding="**/node_modules/*|**/*.min.js|**/bower_components/*" kind="src" path="target/m2e-wtp/web-resources"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>

View File

@ -1,8 +1,8 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.targetPlatform=11
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.compliance=11
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
@ -10,6 +10,6 @@ org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8
org.eclipse.jdt.core.compiler.source=11

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="whn-manager">
<wb-resource deploy-path="/WEB-INF/web.xml" source-path="/src/main/webapp/WEB-INF/web.xml"/>
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/java"/>
<dependent-module archiveName="common-smartgears-app-3.0.1-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/common-smartgears-app/common-smartgears-app">
<dependency-type>uses</dependency-type>
</dependent-module>
<property name="context-root" value="whn-manager"/>
<property name="java-output-path" value="/Whn-Manager/target/classes"/>
</wb-module>
</project-modules>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="java" version="11"/>
<installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="jst.web" version="4.0"/>
</faceted-project>

View File

@ -0,0 +1 @@
org.eclipse.wst.jsdt.launching.baseBrowserLibrary

View File

@ -0,0 +1 @@
Window

View File

@ -0,0 +1,2 @@
disabled=06target
eclipse.preferences.version=1

View File

@ -1,9 +1,8 @@
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
# Changelog for WhnManager Distribution
# Changelog for Test WhnManager
## [v2.0.1] - 2022-11-29
## [v3.0.0-SNAPSHOT] - 2022-06-10
- First Release with git
- added exclude authorization on gcube-apps.xml
- porting to smartgears 4

View File

@ -1,10 +1,6 @@
# WHNManager Service
# WHN Manager
A set of gCube library which empower a servlet container (e.g. tomcat) with a set of functionality such as:
- node and application infrastructure registration
- authorization
- accounting
An Application to add monitoring to all smartgears node
## Built With
@ -12,31 +8,16 @@ A set of gCube library which empower a servlet container (e.g. tomcat) with a se
* [OpenJDK](https://openjdk.java.net/) - The JDK used
* [Maven](https://maven.apache.org/) - Dependency Management
## Documentation
## Change log
See [Releases](https://code-repo.d4science.org/gCubeSystem/whnmanager/releases).
See [Releases](https://code-repo.d4science.org/gCubeSystem/whn-manager/releases).
## Authors
* **Lucio Lelii** - [ISTI-CNR Infrascience Group](http://nemis.isti.cnr.it/groups/infrascience)
* Roberto Cirillo (roberto.cirillo@isti.cnr.it), ISTI-CNR.
## 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 = {whnManager},
author = {{Cirillo, Roberto}},
organization = {{ISTI - CNR}, {FAO}},
address = {{Pisa, Italy}, {Roma, Italy}},
year = 2019,
url = {http://www.gcube-system.org/}
}
## License
@ -70,3 +51,5 @@ The projects leading to this software have received funding from a series of Eur
- DESIRA (grant no. 818194);
- ARIADNEplus (grant no. 823914);
- RISIS2 (grant no. 824091);

View File

@ -1,11 +0,0 @@
<application mode='online'>
<name>WhnManager</name>
<group>VREManagement</group>
<version>${version}</version>
<description>Web Hosting Node Service</description>
<local-persistence location='target' />
<exclude handlers='request-validation'>/*</exclude>
</application>

View File

@ -0,0 +1,5 @@
name: WhnManager
group: VREManagement
version: ${version}
description: Web Hosting Node Service
proxable: false

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>org.gcube.resourcemanagement.whnmanager.WHNManager</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>org.gcube.resourcemanagement.whnmanager.WHNManager</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

166
pom.xml
View File

@ -3,37 +3,26 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maven-parent</artifactId>
<groupId>org.gcube.tools</groupId>
<version>1.1.0</version>
<relativePath />
<artifactId>maven-parent</artifactId>
<version>1.2.0</version>
</parent>
<groupId>org.gcube.resourcemanagement</groupId>
<artifactId>whn-manager</artifactId>
<version>2.0.1</version>
<version>3.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<scm>
<connection>scm:git:https://code-repo.d4science.org/gCubeSystem/${project.artifactId}.git</connection>
<developerConnection>scm:git:https://code-repo.d4science.org/gCubeSystem/${project.artifactId}.git</developerConnection>
<url>https://code-repo.d4science.org/gCubeSystem/${project.artifactId}</url>
</scm>
<properties>
<webappDirectory>${project.basedir}/src/main/webapp/WEB-INF</webappDirectory>
<distroDirectory>${project.basedir}/distro</distroDirectory>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-smartgears-bom</artifactId>
<version>2.2.0</version>
<version>3.0.1-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -41,136 +30,81 @@
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<!-- smartgears -->
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-smartgears</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-smartgears-app</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.ws/jaxws-rt -->
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.inject/jersey-cdi2-se -->
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.3.2</version>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-cdi2-se</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.istack/istack-commons-runtime -->
<!-- <dependency>
<groupId>com.sun.istack</groupId>
<artifactId>istack-commons-runtime</artifactId>
<version>3.0.8</version>
</dependency> -->
<!-- jersey -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
</dependency>
<!-- add jackson as json provider -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet-core</artifactId>
<version>2.0.4.Final</version>
<exclusions>
<exclusion>
<artifactId>jboss-el-api_3.0_spec</artifactId>
<groupId>org.jboss.spec.javax.el</groupId>
</exclusion>
</exclusions>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<artifactId>jboss-el-api_3.0_spec</artifactId>
<groupId>org.jboss.spec.javax.el</groupId>
<version>1.0.0.Alpha1</version>
<scope>provided</scope>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core</artifactId>
<version>2.0.4.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.gcube.resourcemanagement</groupId>
<artifactId>whnmanager-api</artifactId>
<version>[2.0.0-SNAPSHOT, 3.0.0-SNAPSHOT)</version>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>gxHTTP</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>event-publisher-library</artifactId>
<version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- interpolates profiles and copies from distribution location to configuration
location, where it is need for embedding into stub artifact, gar generation,
and service archive. -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-profile</id>
<goals>
<goal>copy-resources</goal>
</goals>
<phase>process-resources</phase>
<configuration>
<outputDirectory>${webappDirectory}</outputDirectory>
<resources>
<resource>
<directory>${distroDirectory}</directory>
<includes>
<include>gcube-app.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<!-- <packagingExcludes>WEB-INF/lib/jaxws-rt-2.1.7.jar,WEB-INF/lib/jaxws-api-2.1.jar,WEB-INF/lib/jaxb-impl-2.1.11.jar,WEB-INF/lib/jaxb-api-2.1.jar</packagingExcludes> -->
<warName>whn-manager</warName>
<webXml>src\main\webapp\WEB-INF\web.xml</webXml>
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
</project>

View File

@ -0,0 +1,182 @@
package org.gcube.resourcemanagement.whnmanager;
import java.net.URL;
import java.security.InvalidParameterException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import org.gcube.common.keycloak.KeycloakClient;
import org.gcube.common.keycloak.KeycloakClientFactory;
import org.gcube.common.keycloak.model.ModelUtils;
import org.gcube.common.keycloak.model.TokenResponse;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.event.publisher.AbstractHTTPWithJWTTokenAuthEventSender;
import org.gcube.event.publisher.Event;
import org.gcube.event.publisher.EventStatus.Status;
import org.gcube.oidc.rest.JWTToken;
import org.gcube.oidc.rest.OpenIdConnectRESTHelperException;
import org.gcube.resourcemanagement.whnmanager.utils.ValidationUtils;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.managers.ContextEvents;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.gcube.smartgears.security.SimpleCredentials;
import org.gcube.smartgears.utils.InnerMethodName;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/contexts")
public class ContextManager {
private static Logger logger = LoggerFactory.getLogger(ContextManager.class);
private static final String CONDUCTOR_URI = "https://conductor.cloud-dev.d4science.org/api/workflow/";
// private static final String REQUEST_PATH ="workflow";
private static final String ADD_CONTEXT_TASK = "ghn_client_add_to_context";
private static final String REMOVE_CONTEXT_TASK = "ghn_client_remove_from_context";
private enum TaskType {
ADD(ADD_CONTEXT_TASK), REMOVE(REMOVE_CONTEXT_TASK);
private String taskName;
TaskType(String contextName) {
this.taskName = contextName;
}
}
private static final int READ_TIMEOUT = 40000;
private static final int CONNECTION_TIMEOUT = 40000;
@PUT
@Path("")
public Response add(final @FormParam("context") String context) {
InnerMethodName.set("addContext");
Secret secret = SecretManagerProvider.get();
logger.debug(
"WHNManager: addToContext method invokation with parameters context :{} and caller: {} curentContext: {}",
context, secret.getOwner().getId(), secret.getContext());
try {
executeTask(l -> l.contains(context), TaskType.ADD, context);
ApplicationContext appContext = ContextProvider.get();
appContext.container().events().fire(context, ContextEvents.ADD_CONTEXT_TO_CONTAINER);
return Response.ok().build();
} catch (InvalidParameterException ip) {
logger.warn("clientId already contains {}", context);
return Response.noContent().build();
} catch (IllegalArgumentException ia) {
logger.warn("null context passed",ia);
return Response.status(400, "context parameter is null").build();
} catch (Throwable t) {
logger.error("error adding context", t);
throw new WebApplicationException(t);
}
}
@DELETE
@Path("")
public Response remove(final @FormParam("context") String context) {
InnerMethodName.set("removeContext");
Secret secret = SecretManagerProvider.get();
logger.debug(
"WHNManager: removeFromContext method invokation with parameters context :{} and caller: {} curentContext: {}",
context, secret.getOwner().getId(), secret.getContext());
try {
executeTask(l -> !l.contains(context), TaskType.REMOVE, context);
ApplicationContext appContext = ContextProvider.get();
appContext.container().events().fire(context, ContextEvents.REMOVE_CONTEXT_FROM_CONTAINER);
return Response.ok().build();
} catch (Throwable t) {
logger.error("error removing context", t);
throw new WebApplicationException(t);
}
}
private Status executeTask(Predicate<Set<String>> notModifiablePredicate, TaskType type, String inputContext ) throws Throwable {
ValidationUtils.valid("context", inputContext);
ApplicationContext appContext = ContextProvider.get();
AuthorizationProvider authProvider = appContext.container().authorizationProvider();
SimpleCredentials credentials = (SimpleCredentials) authProvider.getCredentials();
logger.debug("contexts already present in the container are {} executing task {}",authProvider.getContexts(), type.taskName);
if (notModifiablePredicate.test(authProvider.getContexts()))
throw new InvalidParameterException();
Map<String, String> inputs = new HashMap<String, String>();
inputs.put("client_id", credentials.getClientID());
inputs.put("context", inputContext);
Event event = new Event(type.taskName, type.taskName, appContext.name(), inputs);
Status result = checkEventResult(credentials, event);
logger.debug("{} exectured with result {}", type.taskName, result);
if (result != Status.COMPLETED) {
throw new Exception("error executing the workflow retuned with status " + result);
}
return result;
}
private Status checkEventResult(SimpleCredentials credentials, Event event) throws Throwable {
Secret secret = SecretManagerProvider.get();
AbstractHTTPWithJWTTokenAuthEventSender eventRequest = getAuthEventSender(credentials, secret);
String result = eventRequest.sendAndGetResult(event);
JSONObject eventResult;
do {
Thread.sleep(5000);
eventResult = eventRequest.retrive(result);
} while (Status.RUNNING == Status.valueOf((String) eventResult.get("status")));
return Status.valueOf((String) eventResult.get("status"));
}
@GET
@Path("")
@Produces(MediaType.APPLICATION_JSON)
public String[] get() {
InnerMethodName.set("getContext");
ApplicationContext appContext = ContextProvider.get();
Set<String> contexts = appContext.authorizationProvider().getContexts();
return contexts.stream().toArray(String[]::new);
}
private AbstractHTTPWithJWTTokenAuthEventSender getAuthEventSender(SimpleCredentials credentials, Secret secret)
throws Throwable {
KeycloakClient client = KeycloakClientFactory.newInstance();
TokenResponse tokenResponse = client.queryOIDCToken(secret.getContext(), credentials.getClientID(),
credentials.getSecret());
AbstractHTTPWithJWTTokenAuthEventSender eventSender = new AbstractHTTPWithJWTTokenAuthEventSender(
new URL(CONDUCTOR_URI), credentials.getClientID(), credentials.getSecret(), null) {
protected JWTToken getAuthorizationToken() throws OpenIdConnectRESTHelperException {
return JWTToken.fromString(ModelUtils.toJSONString(tokenResponse));
}
};
eventSender.setConnectionTimeout(CONNECTION_TIMEOUT);
eventSender.setReadTimeout(READ_TIMEOUT);
return eventSender;
}
}

View File

@ -0,0 +1,20 @@
package org.gcube.resourcemanagement.whnmanager;
import java.util.HashSet;
import java.util.Set;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Application;
@Path("/")
public class WHNManager extends Application{
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(ContextManager.class);
return classes;
}
}

View File

@ -1,4 +1,4 @@
package org.gcube.vremanagement.whnmanager.utils;
package org.gcube.resourcemanagement.whnmanager.utils;
import java.util.Iterator;

View File

@ -1,103 +0,0 @@
package org.gcube.vremanagement.whnmanager.jaxws.ws;
import static org.gcube.smartgears.provider.ProviderFactory.provider;
import javax.jws.WebService;
import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.ContainerInfo;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.resourcemanagement.whnmanager.api.WhnManager;
import org.gcube.resourcemanagement.whnmanager.api.exception.GCUBEUnrecoverableException;
import org.gcube.resourcemanagement.whnmanager.api.exception.GCUBEUnrecoverableExceptionInfo;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.managers.ContextEvents;
import org.gcube.vremanagement.whnmanager.utils.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import org.gcube.common.calls.jaxws.Constants;
@WebService(portName = "WhnManagerIOPort",
serviceName = WhnManager.SERVICE_NAME,
targetNamespace = WhnManager.TNS,
endpointInterface = "org.gcube.resourcemanagement.whnmanager.api.WhnManager" )
//@Singleton
public class WhnManagerImpl implements WhnManager{
private static Logger logger=LoggerFactory.getLogger(WhnManagerImpl.class);
//public static final String TOKEN_HEADER_ENTRY = "gcube-token";
/**
* Add a scope to the ghn profile and publish it on IS
*/
public boolean addToContext(String context) throws GCUBEUnrecoverableException{
logger.trace("WHNManager: addToContext method invokation with parameters context :{} and caller: {} curentContext: {}",context, AuthorizationProvider.instance.get(), ScopeProvider.instance.get() );
ValidationUtils.valid("context", context);
ApplicationContext appContext = ContextProvider.get();
if(context!=null){
if(!appContext.container().configuration().allowedContexts().contains(context)){
if (new ScopeBean(context).enclosingScope().toString().equals(ScopeProvider.instance.get())){
AuthorizationProxy proxy = provider().authorizationProxy();
try {
String token = proxy.requestActivation(new ContainerInfo(appContext.container().configuration().hostname(), appContext.container().configuration().port()), context);
logger.trace("generated token is {}",token);
appContext.events().fire(token, ContextEvents.ADD_TOKEN_TO_CONTAINER);
} catch (Exception e) {
logger.error("error contacting authorization service",e);
throw new GCUBEUnrecoverableException(new GCUBEUnrecoverableExceptionInfo("error contacting authorization service"));
}
} else {
logger.error("the selected context {} is not enclosed in the context passed via token : authorization denied ", context);
return false;
}
}else{
logger.warn("the context {} is already present ", context);
return false;
}
}else{
logger.error("context is null");
return false;
}
return true;
}
/**
* Remove a scope from ghn profile and publish the new profile on IS
*/
public boolean removeFromContext(String context) throws GCUBEUnrecoverableException {
logger.trace("WHNManager: removeFromContext method invokation with parameters context :{} and caller: {} curentContext: {}",context, AuthorizationProvider.instance.get(), ScopeProvider.instance.get() );
ValidationUtils.valid("context", context);
ApplicationContext appContext = ContextProvider.get();
if(context!=null){
logger.trace("allowed container in context are {} ",appContext.container().configuration().allowedContexts());
if(appContext.container().configuration().allowedContexts().contains(context)){
if (new ScopeBean(context).enclosingScope().toString().equals(ScopeProvider.instance.get())){
AuthorizationProxy proxy = provider().authorizationProxy();
try {
String token = proxy.requestActivation(new ContainerInfo(appContext.container().configuration().hostname(), appContext.container().configuration().port()), context);
logger.trace("token to remove is {}",token);
appContext.events().fire(token, ContextEvents.REMOVE_TOKEN_FROM_CONTAINER);
} catch (Exception e) {
logger.error("error contacting authorization service",e);
throw new GCUBEUnrecoverableException(new GCUBEUnrecoverableExceptionInfo("error contacting authorization service"));
}
} else {
logger.error("the selected context {} is not enclosed in the context passed via token : authorization denied ", context);
return false;
}
}else{
logger.warn("the context {} is not present ", context);
return false;
}
}else{
logger.error("context is null");
return false;
}
return true;
}
}

View File

@ -1,11 +0,0 @@
<application mode='online'>
<name>WhnManager</name>
<group>VREManagement</group>
<version>2.0.1-SNAPSHOT</version>
<description>Web Hosting Node Service</description>
<local-persistence location='target' />
<exclude>/*</exclude>
</application>

View File

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<endpoints
xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
version="2.0">
<endpoint
name="whnmanager"
implementation="org.gcube.vremanagement.whnmanager.jaxws.ws.WhnManagerImpl"
url-pattern="/gcube/vremanagement/ws/whnmanager"/>
</endpoints>

View File

@ -1,43 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<!--
<listener>
<listener-class>org.gcube.data.analysis.tabulardata.context.MyContext</listener-class>
</listener>
<listener>
<listener-class>org.gcube.common.ghn.service.ApplicationListener</listener-class>
</listener>
-->
<servlet>
<servlet-name>whnmanager</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>whnmanager</servlet-name>
<url-pattern>/gcube/vremanagement/ws/whnmanager</url-pattern>
</servlet-mapping>
<!--
<filter>
<filter-name>scopeFilter</filter-name>
<filter-class>org.gcube.data.analysis.tabulardata.context.MySoapFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>scopeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>-->
</web-app>

View File

@ -0,0 +1,148 @@
package org.gcube.resourcemanagement.whnmanager;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import jakarta.servlet.ServletContext;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import org.gcube.common.events.Hub;
import org.gcube.common.security.credentials.Credentials;
import org.gcube.common.security.secrets.Secret;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.context.Properties;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.persistence.PersistenceWriter;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.gcube.smartgears.security.secrets.SecretFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.BeforeClass;
import org.junit.Test;
public class ContextManagerIntegrationTest extends JerseyTest {
@Override
protected Application configure() {
return new ResourceConfig(ContextManager.class);
}
@BeforeClass
public static void init() {
ContextProvider.set(new ApplicationContext() {
@Override
public Properties properties() {
// TODO Auto-generated method stub
return null;
}
@Override
public PersistenceWriter persistence() {
// TODO Auto-generated method stub
return null;
}
@Override
public String name() {
// TODO Auto-generated method stub
return null;
}
@Override
public ApplicationLifecycle lifecycle() {
// TODO Auto-generated method stub
return null;
}
@Override
public String id() {
// TODO Auto-generated method stub
return null;
}
@Override
public Hub events() {
// TODO Auto-generated method stub
return null;
}
@Override
public ContainerContext container() {
// TODO Auto-generated method stub
return null;
}
@Override
public ApplicationConfiguration configuration() {
// TODO Auto-generated method stub
return null;
}
@Override
public AuthorizationProvider authorizationProvider() {
return new AuthorizationProvider() {
@Override
public Set<String> getContexts() {
return Collections.singleton("/test/context");
}
@Override
public Secret getSecretForContext(String context) {
// TODO Auto-generated method stub
return null;
}
@Override
public Credentials getCredentials() {
// TODO Auto-generated method stub
return null;
}
};
}
@Override
public ServletContext application() {
// TODO Auto-generated method stub
return null;
}
@Override
public Path appSpecificConfigurationFolder() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<SecretFactory<? extends Secret>> allowedSecretFactories() {
// TODO Auto-generated method stub
return null;
}
});
}
@Test
public void gettingContexts() {
Response response = target("/contexts").request()
.get();
assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus());
assertEquals("Http Content-Type should be: ", MediaType.APPLICATION_JSON, response.getHeaderString(HttpHeaders.CONTENT_TYPE));
String[] content = response.readEntity(String[].class);
assertArrayEquals(content, new String[]{"/test/context"});
}
}

Binary file not shown.

View File

@ -1,9 +0,0 @@
log4j.rootCategory = WARN,ROOT
log4j.appender.ROOT=org.apache.log4j.ConsoleAppender
log4j.appender.ROOT.layout=org.apache.log4j.PatternLayout
log4j.appender.ROOT.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p %c{2} [%t,%M:%L] %m%n
log4j.category.org.gcube = TRACE,ROOT
log4j.additivity.org.gcube=false

View File

@ -0,0 +1,13 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="TRACE">
<appender-ref ref="STDOUT"/>
</root>
<logger name="org.gcube.resourcemanagement.whnmanager" level="TRACE"/>
</configuration>