This commit is contained in:
Manuele Simi 2010-03-13 01:22:10 +00:00
parent a1349ba306
commit 48cc9ca0aa
76 changed files with 6475 additions and 0 deletions

14
.classpath Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="/Dependencies/SOFTWAREREPOSITORY/org.gcube.vremanagement.softwarerepository.stubs.jar"/>
<classpathentry kind="lib" path="/Dependencies/Deployer/org.gcube.common.vremanagement.deployer.stubs.jar"/>
<classpathentry kind="lib" path="/Dependencies/GHNManager/org.gcube.common.vremanagement.ghnmanager.stubs.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.USER_LIBRARY/GCORELIBS"/>
<classpathentry combineaccessrules="false" kind="src" path="/GCF.TRUNK"/>
<classpathentry kind="lib" path="/Dependencies/ResourceManager/org.gcube.vremanagement.resourcemanager.stubs.jar"/>
<classpathentry kind="lib" path="/Dependencies/XStream/xstream-1.3.1.jar"/>
<classpathentry kind="lib" path="/Dependencies/JUnit/junit.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

17
.project Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>VREManager_branched</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

15
CHANGELOG Normal file
View File

@ -0,0 +1,15 @@
v. 1.2.3 (20-11-2009)
* Porting on gCore 0.6.0
v. 1.2.0 (13-05-2009)
* Porting on gCore 0.5.0
* Fixing the loading sequence of the ScopeResource
* Dedicated ScopeResource per VO and Infrastructure
* State under persistent root folder
v. 1.1.0 (14-11-2008)
* Management of ScopeResource, improved reporting and management of any GCUBEResource
v. 1.0.0 (28-09-2008)
* First release

11
INSTALL Normal file
View File

@ -0,0 +1,11 @@
to compile:
ant garService
ant buildStubs
to deploy:
gcore-deploy-service org.gcube.vremanagement.resourcemanager.gar
cp org.gcube.vremanagement.resourcemanager.stubs.jar

6
LICENSE Normal file
View File

@ -0,0 +1,6 @@
gCube System - License
------------------------------------------------------------
The gCube/gCore software is licensed as Free Open Source software conveying to the EUPL (http://ec.europa.eu/idabc/eupl).
The software and documentation is provided by its authors/distributors "as is" and no expressed or
implied warranty is given for its use, quality or fitness for a particular case.

3
MAINTAINERS Normal file
View File

@ -0,0 +1,3 @@
* Manuele Simi (manuele.simi@isti.cnr.it), CNR Pisa,
Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo".

45
README Normal file
View File

@ -0,0 +1,45 @@
The gCube System - ResourceManager Service
------------------------------------------------------------
This work is partially funded by the European Commission in the
context of the D4Science project (www.d4science.eu), under the 1st call of FP7 IST priority.
Authors
-------
* Manuele Simi (manuele.simi@isti.cnr.it), CNR Pisa,
Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo".
Version and Release Date
------------------------
v. 1.0.0, 25/09/2008
Description
-----------
The ResourceManager...
Download information
--------------------
Source code is available from SVN:
http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/vre-management/ResourceManager
Binaries can be downloaded from:
Documentation
-------------
ResourceManager documentation is available on-line from the Projects Documentation Wiki:
https://technical.wiki.d4science.research-infrastructures.eu/documentation/index.php/VRE_Manager
Test-suite documentation is available on-line from the Projects Documentation Wiki:
https://technical.wiki.d4science.research-infrastructures.eu/documentation/index.php/VRE_Manager#The_test-suite
Licensing
---------
This software is licensed under the terms you may find in the file named "LICENSE" in this directory.

536
build.xml Normal file
View File

@ -0,0 +1,536 @@
<?xml version="1.0"?>
<!-- Ant buildfile for GCUBE Services
Version 0.5
INPUT PROPERTIES
This buildfile assumes that the following properties have or may have been defined in a "build.properties" file
in the configuration directory of the service (or else using the -D flag on the command line).
package: (mandatory) Root package of the service implementation: it should be the first package in the
implementation hierarchy which uniquely identifies the implementation.
lib.dir: (mandatory) Root directory where auxiliary jar files are located. Ideally outside ${base.dir} as not needed for remote build and dynamic deployment.
wsdl.<n>: (mandatory) Name of the <n>-th port-type of the service, as defined in the "name" attributed of the
"definitions" root element of the corresponding WSDL file.
The order imposed over port-type serves only to distinguish build properties and
and has no particular semantics otherwise.
This script supports by default up to 6 wsdls (wsdl.1, wsdl.2, wsdl.3,...).
Further wsdls require a simple script extension (see guidelines at end of script).
namespace.<n>: (mandatory) The <n>-th target namespace of a port-type WSSDL or of auxiliary XSD definition. Again, the over imposed over namespaces
serves only to distinguish build properties and has no particular semantics otherwise.
package.<n>: (optional) The package name of the stubs generated from WSDL and/or XSD elements in the <n>-th target namespace. If it is specified, it is
considered to be relative to ${package}.stubs. If it is omitted, WSLD and XSD elements are placed in $package}.stubs.
etics.build: (optional) Set to 'true', it indicates that build structures and procedures
should be optimised for remote builds in ETICS. If it is omitted, this buildfile will optimise build structures and procedures
for local builds.
full.stubs: (optional) Set to 'false', it excludes auxiliary stub code placed under ${package}/stubs when building the stub distribution.
It is intended to simplify realignment of auxiliary and standard stub in IDE environments in case the latter change in non backwards-compatible ways.
After re-alignment, the property is typically left to its default of 'true' to restore a joint build of all stub code.
-->
<project default="deployService" name="GCUBE Service Buildfile">
<!-- environment -->
<property environment="env" />
<!-- external environment -->
<echo message="container.dir ->${env.GLOBUS_LOCATION}" level="info"/>
<property name="container.dir" value="${env.GLOBUS_LOCATION}" />
<property name="container.schema.dir" location="${container.dir}/share/schema" />
<property name="build.packages" location="${container.dir}/share/gcore_tools/build-packages.xml" />
<property name="build.stubs" location="${container.dir}/share/gcore_tools/build-stubs.xml" />
<!-- load non-standard tasks -->
<taskdef resource="ise/antelope/tasks/antlib.xml">
<classpath>
<pathelement location="${container.dir}/lib/AntelopeTasks_3.4.2.jar"/>
</classpath>
</taskdef>
<!-- discriminate between local and remote build -->
<property name="etics.build" value="false" />
<!-- service-specific locations -->
<property name="service.dir" location="." />
<property name="schema.dir.name" value="schema" />
<property name="schema.dir" location="${service.dir}/${schema.dir.name}"/>
<property name="etc.dir.name" value="etc" />
<property name="etc.dir" value="${service.dir}/${etc.dir.name}" />
<property name="source.dir" value="${service.dir}/src" />
<!-- load input properties -->
<property file="${etc.dir}/build.properties" />
<stringutil property="package.dir" string="${package}"><!-- derive package.dir from ${package} -->
<replace regex="\." replacement="/"/>
</stringutil>
<!-- file defaults -->
<property name="garname" value="${package}"/>
<property name="garfile" value="${garname}.gar"/>
<property name="jarfile" value="${package}.jar" />
<property name="jarfile.stubs" value="${package}.stubs.jar" />
<if name="etics.build" value="true">
<property name="build.location" location="${service.dir}" />
<property name="lib.location" value="${build.location}/lib" />
<property name="gar.location" value="${lib.location}"/>
<else>
<property name="build.location" location="${env.BUILD_LOCATION}" />
<property name="lib.location" value="${build.location}/${lib.dir}" />
<property name="gar.location" value="${build.location}"/>
</else>
</if>
<property name="full.stubs" value="true"/>
<property name="stubs.package" value="${package}.${stubs.dir.name}"/>
<property name="stubs.dir.name" value="stubs" /> <!-- auxiliary stub classes -->
<property name="stubs.dir" value="${source.dir}/${package.dir}/${stubs.dir.name}" />
<available file="${stubs.dir}" property="stubs.dir.present"/>
<!-- temporary build locations -->
<property name="build.dir" location="${build.location}/build" />
<property name="build.class.dir" location="${build.dir}/classes" />
<property name="build.lib.dir" location="${build.dir}/lib" />
<property name="build.schema.dir" location="${build.dir}/schema" />
<property name="build.schema.service.dir" location="${build.schema.dir}/${package}" />
<property name="build.stubs.dir" location="${build.dir}/stubs-${package}" />
<property name="build.stubs.src.dir" location="${build.stubs.dir}/src" />
<property name="build.stubs.class.dir" location="${build.stubs.dir}/classes" />
<!-- misc defaults -->
<property name="java.debug" value="on" />
<property name="java.deprecation" value="off" />
<!-- common filesets -->
<fileset dir="${build.lib.dir}" id="garjars" />
<property name="garjars.id" value="garjars" />
<fileset dir="${build.schema.dir}" id="garschema">
<include name="${package}/**" />
</fileset>
<property name="garschema.id" value="garschema" />
<fileset dir="${etc.dir}" id="garetc" />
<property name="garetc.id" value="garetc" />
<!-- initialisation tasks -->
<target name="init" depends="clean" description="creates build structures">
<!-- input summary -->
<echo message="Root Package -> ${package}" level="info"/>
<echo message="Interfaces -> ${schema.dir}" level="info"/>
<echo message="Auxiliary Stubs -> ${stubs.dir}" level="info"/>
<echo message="Configuration -> ${etc.dir}" level="info"/>
<echo message="External dependencies -> ${lib.location}" level="info"/>
<!-- output summary -->
<echo message="Service Gar -> ${garfile}" level="info"/>
<echo message="Service Jar -> ${jarfile}" level="info"/>
<echo message="Stubs Jar -> ${jarfile.stubs}" level="info"/>
<!-- create dependency location, if it does not exist already -->
<mkdir dir="${lib.location}" />
<!-- create temporary build folders -->
<mkdir dir="${build.dir}" />
<mkdir dir="${build.class.dir}" />
<delete dir="${build.lib.dir}" />
<mkdir dir="${build.lib.dir}" />
<mkdir dir="${build.schema.service.dir}" />
<mkdir dir="${build.stubs.dir}" />
<mkdir dir="${build.stubs.src.dir}" />
<mkdir dir="${build.stubs.class.dir}"/>
<!-- Populates schema folder -->
<copy toDir="${build.schema.dir}">
<fileset dir="${container.schema.dir}" casesensitive="yes">
<include name="wsrf/**/*" />
<include name="ws/**/*" />
<include name="gcube/**/**/**/*" />
</fileset>
</copy>
<copy toDir="${build.schema.service.dir}">
<fileset dir="${schema.dir}"/>
</copy>
<!-- Populates library folder -->
<copy toDir="${build.lib.dir}">
<fileset dir="${lib.location}">
<exclude name="${jarfile.stubs}" />
</fileset>
</copy>
</target>
<!-- wsdl specific tasks. Clone for each additional wsdl, if required -->
<target name="processWSDL.1" depends="init" if="wsdl.1" description="Flattens wsdl and generate bindings">
<echo message="PROCESSING ${wsdl.1}'s WSDL:" level="debug"/>
<ant antfile="${build.stubs}" target="flatten">
<property name="source.flatten.dir" location="${build.schema.service.dir}" />
<property name="target.flatten.dir" location="${build.schema.service.dir}" />
<property name="wsdl.source" value="${wsdl.1}.wsdl" />
<property name="wsdl.target" value="${wsdl.1}_flattened.wsdl" />
<property name="wsdl.porttype" value="${wsdl.1}PortType" />
</ant>
<ant antfile="${build.stubs}" target="generateBinding">
<property name="source.binding.dir" value="${build.schema.service.dir}" />
<property name="target.binding.dir" value="${build.schema.service.dir}" />
<property name="porttype.wsdl" value="${wsdl.1}_flattened.wsdl" />
<property name="binding.root" value="${wsdl.1}" />
</ant>
</target>
<target name="processWSDL.2" depends="init" if="wsdl.2" description="Flattens wsdl and generate bindings">
<echo message="PROCESSING ${wsdl.2}'s WSDL:" level="debug"/>
<ant antfile="${build.stubs}" target="flatten">
<property name="source.flatten.dir" location="${build.schema.service.dir}" />
<property name="target.flatten.dir" location="${build.schema.service.dir}" />
<property name="wsdl.source" value="${wsdl.2}.wsdl" />
<property name="wsdl.target" value="${wsdl.2}_flattened.wsdl" />
<property name="wsdl.porttype" value="${wsdl.2}PortType" />
</ant>
<ant antfile="${build.stubs}" target="generateBinding">
<property name="source.binding.dir" value="${build.schema.service.dir}" />
<property name="target.binding.dir" value="${build.schema.service.dir}" />
<property name="porttype.wsdl" value="${wsdl.2}_flattened.wsdl" />
<property name="binding.root" value="${wsdl.2}" />
</ant>
</target>
<target name="processWSDL.3" depends="init" if="wsdl.3" description="Flattens wsdl and generate bindings">
<echo message="PROCESSING ${wsdl.3}'s WSDL:" level="debug"/>
<ant antfile="${build.stubs}" target="flatten">
<property name="source.flatten.dir" location="${build.schema.service.dir}" />
<property name="target.flatten.dir" location="${build.schema.service.dir}" />
<property name="wsdl.source" value="${wsdl.3}.wsdl" />
<property name="wsdl.target" value="${wsdl.3}_flattened.wsdl" />
<property name="wsdl.porttype" value="${wsdl.3}PortType" />
</ant>
<ant antfile="${build.stubs}" target="generateBinding">
<property name="source.binding.dir" value="${build.schema.service.dir}" />
<property name="target.binding.dir" value="${build.schema.service.dir}" />
<property name="porttype.wsdl" value="${wsdl.3}_flattened.wsdl" />
<property name="binding.root" value="${wsdl.3}" />
</ant>
</target>
<target name="processWSDL.4" depends="init" if="wsdl.4" description="Flattens wsdl and generate bindings">
<echo message="PROCESSING ${wsdl.4.name}'s WSDL:" level="debug"/>
<ant antfile="${build.stubs}" target="flatten">
<property name="source.flatten.dir" location="${build.schema.service.dir}" />
<property name="target.flatten.dir" location="${build.schema.service.dir}" />
<property name="wsdl.source" value="${wsdl.4}.wsdl" />
<property name="wsdl.target" value="${wsdl.4}_flattened.wsdl" />
<property name="wsdl.porttype" value="${wsdl.4}PortType" />
</ant>
<ant antfile="${build.stubs}" target="generateBinding">
<property name="source.binding.dir" value="${build.schema.service.dir}" />
<property name="target.binding.dir" value="${build.schema.service.dir}" />
<property name="porttype.wsdl" value="${wsdl.4}_flattened.wsdl" />
<property name="binding.root" value="${wsdl.4}" />
</ant>
</target>
<target name="processWSDL.5" depends="init" if="wsdl.5" description="Flattens wsdl and generate bindings">
<echo message="PROCESSING ${wsdl.5}'s WSDL:" level="debug"/>
<ant antfile="${build.stubs}" target="flatten">
<property name="source.flatten.dir" location="${build.schema.service.dir}" />
<property name="target.flatten.dir" location="${build.schema.service.dir}" />
<property name="wsdl.source" value="${wsdl.5}.wsdl" />
<property name="wsdl.target" value="${wsdl.5}_flattened.wsdl" />
<property name="wsdl.porttype" value="${wsdl.5}PortType" />
</ant>
<ant antfile="${build.stubs}" target="generateBinding">
<property name="source.binding.dir" value="${build.schema.service.dir}" />
<property name="target.binding.dir" value="${build.schema.service.dir}" />
<property name="porttype.wsdl" value="${wsdl.5}_flattened.wsdl" />
<property name="binding.root" value="${wsdl.5}" />
</ant>
</target>
<target name="processWSDL.6" depends="init" if="wsdl.6" description="Flattens wsdl and generate bindings">
<echo message="PROCESSING ${wsdl.6}'s WSDL:" level="debug"/>
<ant antfile="${build.stubs}" target="flatten">
<property name="source.flatten.dir" location="${build.schema.service.dir}" />
<property name="target.flatten.dir" location="${build.schema.service.dir}" />
<property name="wsdl.source" value="${wsdl.6}.wsdl" />
<property name="wsdl.target" value="${wsdl.6}_flattened.wsdl" />
<property name="wsdl.porttype" value="${wsdl.6}PortType" />
</ant>
<ant antfile="${build.stubs}" target="generateBinding">
<property name="source.binding.dir" value="${build.schema.service.dir}" />
<property name="target.binding.dir" value="${build.schema.service.dir}" />
<property name="porttype.wsdl" value="${wsdl.6}_flattened.wsdl" />
<property name="binding.root" value="${wsdl.6}" />
</ant>
</target>
<target name="generateStubs.1" if="wsdl.1" description="Generate wsdl stub classes">
<echo message="GENERATING ${wsdl.1}'s STUBS:" level="debug"/>
<ant antfile="${build.stubs}" target="generateStubs">
<property name="mappings" value="${mappings}"/>
<property name="source.stubs.dir" location="${build.schema.service.dir}" />
<property name="target.stubs.dir" location="${build.stubs.src.dir}" />
<property name="wsdl.file" value="${wsdl.1}_service.wsdl" />
</ant>
</target>
<target name="generateStubs.2" if="wsdl.2" description="Generate wsdl stub classes">
<echo message="GENERATING ${wsdl.2}'s STUBS:" level="debug"/>
<ant antfile="${build.stubs}" target="generateStubs">
<property name="mappings" value="${mappings}"/>
<property name="source.stubs.dir" location="${build.schema.service.dir}" />
<property name="target.stubs.dir" location="${build.stubs.src.dir}" />
<property name="wsdl.file" value="${wsdl.2}_service.wsdl" />
</ant>
</target>
<target name="generateStubs.3" if="wsdl.3" description="Generate wsdl stub classes">
<echo message="GENERATING ${wsdl.3}'s STUBS:" level="debug"/>
<ant antfile="${build.stubs}" target="generateStubs">
<property name="mappings" value="${mappings}"/>
<property name="source.stubs.dir" location="${build.schema.service.dir}" />
<property name="target.stubs.dir" location="${build.stubs.src.dir}" />
<property name="wsdl.file" value="${wsdl.3}_service.wsdl" />
</ant>
</target>
<target name="generateStubs.4" if="wsdl.4" description="Generate wsdl stub classes">
<echo message="GENERATING ${wsdl.4}'s STUBS:" level="debug"/>
<ant antfile="${build.stubs}" target="generateStubs">
<property name="mappings" value="${mappings}"/>
<property name="source.stubs.dir" location="${build.schema.service.dir}" />
<property name="target.stubs.dir" location="${build.stubs.src.dir}" />
<property name="wsdl.file" value="${wsdl.4}_service.wsdl" />
</ant>
</target>
<target name="generateStubs.5" if="wsdl.5" description="Generate wsdl stub classes">
<echo message="GENERATING ${wsdl.5}'s STUBS:" level="debug"/>
<ant antfile="${build.stubs}" target="generateStubs">
<property name="mappings" value="${mappings}"/>
<property name="source.stubs.dir" location="${build.schema.service.dir}" />
<property name="target.stubs.dir" location="${build.stubs.src.dir}" />
<property name="wsdl.file" value="${wsdl.5}_service.wsdl" />
</ant>
</target>
<target name="generateStubs.6" if="wsdl.6" description="Generate wsdl stub classes">
<echo message="GENERATING ${wsdl.6}'s STUBS:" level="debug"/>
<ant antfile="${build.stubs}" target="generateStubs">
<property name="mappings" value="${mappings}"/>
<property name="source.stubs.dir" location="${build.schema.service.dir}" />
<property name="target.stubs.dir" location="${build.stubs.src.dir}" />
<property name="wsdl.file" value="${wsdl.6}_service.wsdl" />
</ant>
</target>
<!-- Cross-wsdl tasks. Adds dependencies for each additional wsdl, if required -->
<target name="processWSDLs" depends="processWSDL.1,processWSDL.2,processWSDL.3,processWSDL.4,processWSDL.5,processWSDL.6" description="generate bindings for all porttypes" />
<target name="generateStubs" depends="generateMappings,generateStubs.1,generateStubs.2,generateStubs.3,generateStubs.4,generateStubs.5,generateStubs.6" description="generate stub classes for all porttypes" />
<target name="generateMappings">
<var name="mappings" value=""/>
<if name="namespace.1">
<if name="package.1">
<var name="package.1" value="${stubs.package}.${package.1}"/>
<else>
<var name="package.1" value="${stubs.package}"/></else>
</if>
<var name="mappings" value="${mappings} -N${namespace.1}=${package.1} -N${namespace.1}/service=${package.1}.service -N${namespace.1}/bindings=${package.1}.bindings"/>
</if>
<if name="namespace.2">
<if name="package.2">
<var name="package.2" value="${stubs.package}.${package.2}"/>
<else>
<var name="package.2" value="${stubs.package}"/></else>
</if>
<var name="mappings" value="${mappings} -N${namespace.2}=${package.2} -N${namespace.2}/service=${package.2}.service -N${namespace.2}/bindings=${package.2}.bindings"/>
</if>
<if name="namespace.3">
<if name="package.3">
<var name="package.3" value="${stubs.package}.${package.3}"/>
<else>
<var name="package.3" value="${stubs.package}"/></else>
</if>
<var name="mappings" value="${mappings} -N${namespace.3}=${package.3} -N${namespace.3}/service=${package.3}.service -N${namespace.3}/bindings=${package.3}.bindings"/>
</if>
<if name="namespace.4">
<if name="package.4">
<var name="package.4" value="${stubs.package}.${package.4}"/>
<else>
<var name="package.4" value="${stubs.package}"/></else>
</if>
<var name="mappings" value="${mappings} -N${namespace.4}=${package.4} -N${namespace.4}/service=${package.4}.service -N${namespace.4}/bindings=${package.4}.bindings"/>
</if>
<if name="namespace.5">
<if name="package.5">
<var name="package.5" value="${stubs.package}.${package.5}"/>
<else>
<var name="package.5" value="${stubs.package}"/></else>
</if>
<var name="mappings" value="${mappings} -N${namespace.5}=${package.5} -N${namespace.5}/service=${package.5}.service -N${namespace.5}/bindings=${package.5}.bindings"/>
</if>
<if name="namespace.6">
<if name="package.6">
<var name="package.6" value="${stubs.package}.${package.6}"/>
<else>
<var name="package.6" value="${stubs.package}"/></else>
</if>
<var name="mappings" value="${mappings} -N${namespace.6}=${package.6} -N${namespace.6}/service=${package.6}.service -N${namespace.6}/bindings=${package.6}.bindings"/>
</if>
</target>
<!-- Service tasks -->
<target name="deployService" depends="garService" description="deploy service gar">
<exec executable="${container.dir}/bin/gcore-deploy-service">
<arg value="${gar.location}/${package}.gar"/>
</exec>
</target>
<target name="buildService" depends="processWSDLs" description="compiles service implementation">
<javac srcdir="${source.dir}" destdir="${build.class.dir}" debug="${java.debug}" deprecation="${java.deprecation}">
<classpath>
<fileset dir="${lib.location}">
<include name="**/*.jar" />
</fileset>
<fileset dir="${container.dir}/lib">
<include name="*.jar" />
<exclude name="${jarfile}" />
</fileset>
</classpath>
</javac>
</target>
<target name="jarService" depends="buildService" description="jars service implementation">
<jar jarfile="${build.lib.dir}/${jarfile}" basedir="${build.class.dir}">
<include name="${package.dir}/**" />
</jar>
</target>
<target name="garService" depends="jarService" description="creates service gar">
<ant antfile="${build.packages}" target="makeGar">
<property name="garserverdeployment.file" value="${etc.dir}/deploy-server.wsdd" />
<property name="garserverdeployment_NOSEC.file" value="${etc.dir}/deploy-server.wsdd_NOSEC" />
<property name="garclientdeployment.file" value="${etc.dir}/deploy-client.wsdd" />
<property name="garclientserverdeployment.file" value="${etc.dir}/deploy-client-server.wsdd" />
<property name="garjndiconfigdeployment.file" value="${etc.dir}/deploy-jndi-config.xml" />
<property name="gar.id" value="${package}" />
<reference refid="${garjars.id}" />
<reference refid="${garschema.id}" />
<reference refid="${garetc.id}" />
</ant>
<delete dir="tmp" />
<move file="${garfile}" toDir="${gar.location}"/>
</target>
<!-- Stub Build tasks -->
<target name="buildStubs" depends="processWSDLs,generateStubs" description="build service stubs">
<if name="full.stubs" value="true">
<if name="stubs.dir.present">
<copy toDir="${build.stubs.src.dir}/${package.dir}/${stubs.dir.name}" overwrite="true">
<fileset dir="${stubs.dir}" casesensitive="yes">
<exclude name="**/*.class" />
</fileset>
</copy>
</if>
</if>
<javac srcdir="${build.stubs.src.dir}" destdir="${build.stubs.class.dir}" debug="${java.debug}" deprecation="${java.deprecation}" description="compile stub classes">
<include name="**/*.java" />
<classpath>
<fileset dir="${container.dir}/lib">
<include name="*.jar" />
<exclude name="${jarfile.stubs}" />
<exclude name="${jarfile}" />
</fileset>
<fileset dir="${lib.location}">
<include name="**/*.jar" />
<exclude name="**/${jarfile.stubs}" />
<exclude name="**/${jarfile}" />
</fileset>
</classpath>
</javac>
<copy toDir="${build.stubs.class.dir}/META-INF" overwrite="false"><!-- copy configuration info as well -->
<fileset dir="${etc.dir}" casesensitive="yes" />
</copy>
</target>
<target name="jarStubs" depends="buildStubs" description="jar stub classes">
<jar destfile="${build.lib.dir}/${jarfile.stubs}" basedir="${build.stubs.class.dir}" />
</target>
<target name="deployStubs" depends="jarStubs" description="deploy stub jar">
<copy file="${build.lib.dir}/${jarfile.stubs}" toDir="${lib.location}"/>
<if name="etics.build" value="false">
<copy file="${build.lib.dir}/${jarfile.stubs}" toDir="${container.dir}/lib"/>
</if>
</target>
<target name="stubs" depends="deployStubs" description="generates, builds, jars and deploy stubs"/>
<!-- undeployement tasks -->
<target name="undeployStubs" description="deploy stub jar">
<delete file="${container.dir}/lib/${jarfile.stubs}"/>
</target>
<target name="undeployService" description="undeploy service jar">
<exec executable="${container.dir}/bin/gcore-undeploy-service">
<arg value="${package}"/>
</exec>
</target>
<!-- javadoc tasks -->
<target name="doc">
<javadoc access="public" author="true" sourcepath="${source.dir}" packagenames="${package}.*"
destdir="doc/api" nodeprecated="false" nodeprecatedlist="false"
noindex="false" nonavbar="false" notree="false"
source="1.5"
splitindex="true"
use="true" version="true" failonerror="false">
<classpath>
<fileset dir="${lib.location}">
<include name="**/*.jar" />
<exclude name="**/${jarfile}" />
</fileset>
<fileset dir="${container.dir}/lib">
<include name="*.jar" />
</fileset>
</classpath>
</javadoc>
</target>
<target name="docstubs">
<javadoc access="public" author="true" destdir="doc/api" nodeprecated="false"
packagenames="${package}.${stubs.dir.name}.*"
nodeprecatedlist="false" noindex="false" nonavbar="false" notree="false"
source="1.5" sourcepath="${build.stubs.src.dir}"
splitindex="true" use="true" version="true"
failonerror="false">
<classpath>
<fileset dir="${lib.location}">
<include name="**/*.jar" />
<exclude name="**/${jarfile.stubs}" />
</fileset>
<fileset dir="${container.dir}/lib">
<include name="*.jar" />
</fileset>
</classpath>
</javadoc>
</target>
<target name="clean">
<delete dir="${build.dir}" quiet="true"/>
<delete dir="${service.dir}/tmp" quiet="true"/>
<delete file="${gar.location}/${garfile}" quiet="true"/>
</target>
</project>

9
etc/build.properties Executable file
View File

@ -0,0 +1,9 @@
package = org.gcube.vremanagement.resourcemanager
lib.dir = Dependencies/ResourceManager
wsdl.1 = ResourceManager
package.1 = resourcemanager
package.2 = common
namespace.1=http://gcube-system.org/namespaces/vremanagement/resourcemanager
namespace.2=http://gcube-system.org/common/vremanagement/types

View File

@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<jndiConfig xmlns="http://wsrf.globus.org/jndi/config">
<service name="gcube/vremanagement/ResourceManager/service">
<environment
name="configDir"
value="@config.dir@"
type="java.lang.String"
override="false" />
<environment
name="securityManagerClass"
value="org.gcube.common.core.security.GCUBESimpleServiceSecurityManager"
type="java.lang.String"
override="false" />
<environment
name="startScopes"
value="/gcube/devsec/CNR-VRE"
type="java.lang.String"
override="false" />
</service>
<service name="gcube/vremanagement/ResourceManager">
<environment
name="name"
value="VREManager"
type="java.lang.String"
override="false" />
<environment
name="RPDName"
value="VREManagerResourceProperties"
type="java.lang.String"
override="false"/>
<resource name="home" type="org.gcube.vremanagement.resourcemanager.impl.state.ResourceManagerHome">
<resourceParams>
<parameter>
<name>factory</name>
<value>org.globus.wsrf.jndi.BeanFactory</value>
</parameter>
<parameter>
<name>resourceClass</name>
<value>org.gcube.vremanagement.resourcemanager.impl.state.InstanceState</value>
</parameter>
</resourceParams>
</resource>
</service>
</jndiConfig>

17
etc/deploy-server.wsdd Normal file
View File

@ -0,0 +1,17 @@
<deployment name="defaultServerConfig"
xmlns="http://xml.apache.org/axis/wsdd/"
xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<service name="gcube/vremanagement/ResourceManager" provider="Handler" use="literal" style="document">
<parameter name="className" value="org.gcube.vremanagement.resourcemanager.impl.ResourceManager"/>
<wsdlFile>share/schema/org.gcube.vremanagement.resourcemanager/ResourceManager_service.wsdl</wsdlFile>
<parameter name="allowedMethods" value="*"/>
<parameter name="handlerClass" value="org.globus.axis.providers.RPCProvider"/>
<parameter name="scope" value="Application"/>
<parameter name="providers" value="GCUBEProvider GetCurrentMessageProvider"/>
<parameter name="loadOnStartup" value="true"/>
<parameter name="securityDescriptor" value="@config.dir@/security_descriptor.xml"/>
</service>
</deployment>

88
etc/profile.xml Normal file
View File

@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource>
<ID/>
<Type>Service</Type>
<Profile>
<Description>ResourceManager creates and manages a VRE context</Description>
<Class>VREManagement</Class>
<Name>ResourceManager</Name>
<Version>1.0.0</Version>
<Dependencies>
<Dependency>
<Class>VREManagement</Class>
<Name>SoftwareRepository</Name>
<Version>1.0.0</Version>
</Dependency>
<Dependency>
<Class>VREManagement</Class>
<Name>GHNManager</Name>
<Version>1.0.0</Version>
</Dependency>
<Dependency>
<Class>VREManagement</Class>
<Name>Deployer</Name>
<Version>1.0.0</Version>
</Dependency>
</Dependencies>
<Packages>
<Main deployable="true">
<Description>Service package for creating a ResourceManager instance: it provides an implementation of all ResourceManager operations</Description>
<Name>ResourceManager-service</Name>
<Version>2.0.0</Version>
<Mandatory level="VRE"/>
<Shareable level="NONE"/>
<GHNRequirements>
<Requirement category="Site" requirement="string" value="java1.5" operator="ge"/>
</GHNRequirements>
<Dependencies>
<Dependency>
<Service>
<Class>VREManagement</Class>
<Name>ResourceManager</Name>
<Version>1.00.00</Version>
</Service>
<Package>ResourceManager-stubs</Package>
<Version>1.01.00</Version>
<Scope level="GHN"/>
<Optional>false</Optional>
</Dependency>
</Dependencies>
<GARArchive>org.gcube.vremanagement.resourcemanager.gar</GARArchive>
<PortType>
<Name>gcube/vremanagement/ResourceManager</Name>
<Security/>
<WSDL/>
</PortType>
</Main>
<Software>
<Description>Stubs for ResourceManager: it provides facilities to interact with a ResourceManager instance</Description>
<Name>ResourceManager-stubs</Name>
<Version>2.0.0</Version>
<MultiVersion value="true"/>
<Mandatory level="GHN"/>
<Shareable level="VO"/>
<GHNRequirements>
<Requirement category="Site" operator="ge" requirement="string" value="java1.5"/>
</GHNRequirements>
<Type>library</Type>
<Files>
<File>org.gcube.vremanagement.resourcemanager.stubs.jar</File>
</Files>
</Software>
<Software>
<Description>Test-suite for ResourceManager: it provides sample usages of interaction with a ResourceManager instance</Description>
<Name>ResourceManager-test-suite</Name>
<Version>2.00.00</Version>
<MultiVersion value="true"/>
<Shareable level="VO"/>
<GHNRequirements>
<Requirement category="Site" operator="ge" requirement="string" value="java1.5"/>
</GHNRequirements>
<Type>application</Type>
<Files>
<File>lib/org.gcube.vremanagement.resourcemanager.testsuite.jar</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

1
etc/reports/readme.txt Executable file
View File

@ -0,0 +1 @@
This folder contains the resource reports.

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<securityConfig xmlns="http://www.globus.org" >
<authz value="none"/>
<method name="addResources">
<auth-method>
<none/>
</auth-method>
</method>
<method name="sendReport">
<auth-method>
<none/>
</auth-method>
</method>
<method name="setScopeOptions">
<auth-method>
<none/>
</auth-method>
</method>
<method name="getReport">
<auth-method>
<none/>
</auth-method>
</method>
<method name="removeResources">
<auth-method>
<none/>
</auth-method>
</method>
<method name="notifyGHNdeath">
<auth-method>
<none/>
</auth-method>
</method>
<method name="queryResourceProperties">
<auth-method>
<none/>
</auth-method>
</method>
<method name="subscribe">
<auth-method>
<none/>
</auth-method>
</method>
<method name="getCurrentMessage">
<auth-method>
<none/>
</auth-method>
</method>
<method name="getMultipleResourceProperties">
<auth-method>
<none/>
</auth-method>
</method>
</securityConfig>

261
schema/ResourceManager.wsdl Normal file
View File

@ -0,0 +1,261 @@
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="ResourceManager"
targetNamespace="http://gcube-system.org/namespaces/vremanagement/resourcemanager"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:tns="http://gcube-system.org/namespaces/vremanagement/resourcemanager"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:provider="http://gcube-system.org/namespaces/common/core/porttypes/GCUBEProvider"
xmlns:coretypes="http://gcube-system.org/namespaces/common/core/types"
xmlns:corefaults="http://gcube-system.org/namespaces/common/core/faults"
xmlns:vretypes="http://gcube-system.org/common/vremanagement/types"
xmlns:wsrlw="http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceLifetime-1.2-draft-01.wsdl"
xmlns:wsrp="http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceProperties-1.2-draft-01.xsd"
xmlns:wsntw="http://docs.oasis-open.org/wsn/2004/06/wsn-WS-BaseNotification-1.2-draft-01.wsdl"
xmlns:wsdlpp="http://www.globus.org/namespaces/2004/10/WSDLPreprocessor"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<import namespace="http://gcube-system.org/namespaces/common/core/porttypes/GCUBEProvider" location="../gcube/common/core/providers/GCUBEProvider.wsdl"/>
<import namespace="http://gcube-system.org/namespaces/common/core/faults" location="../gcube/common/core/faults/GCUBEFaults.wsdl"/>
<import namespace="http://gcube-system.org/common/vremanagement/types" location="VREManagementTypes.wsdl"/>
<!--============================================================
T Y P E S
============================================================-->
<types>
<xsd:schema targetNamespace="http://gcube-system.org/namespaces/vremanagement/resourcemanager"
xmlns:tns="http://gcube-system.org/namespaces/vremanagement/resourcemanager"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:import namespace="http://gcube-system.org/namespaces/common/core/types" schemaLocation="../gcube/common/core/types/GCUBETypes.xsd"/>
<xsd:import namespace="http://gcube-system.org/common/vremanagement/types" schemaLocation="VREManagementTypes.xsd"/>
<xsd:simpleType name="resourceID">
<xsd:restriction base="xsd:string" />
</xsd:simpleType>
<xsd:element name="VOID">
<xsd:complexType/>
</xsd:element>
<xsd:complexType name="CStoRun">
<xsd:sequence>
<xsd:element name="pre" type="tns:resourceID" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element name="post" type="tns:resourceID" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element name="delete" type="tns:resourceID" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="ServiceItem">
<xsd:sequence>
<xsd:element name="ServiceClass" type="xsd:string"/>
<xsd:element name="ServiceName" type="xsd:string"/>
<xsd:element name="ServiceVersion" type="xsd:string" minOccurs="0" maxOccurs="1"/>
<xsd:element name="GHN" type="tns:resourceID" minOccurs="0" maxOccurs="1"/>
<xsd:element name="CS" type="tns:CStoRun" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="ServiceList">
<xsd:sequence>
<xsd:element name="service" type="tns:ServiceItem" minOccurs="1" maxOccurs="unbounded"/>
<xsd:element name="GHN" type="tns:resourceID" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="ResourceItem">
<xsd:sequence>
<xsd:element name="ID" type="tns:resourceID"/>
<xsd:element name="Type" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="ResourceList">
<xsd:sequence>
<xsd:element name="resource" type="tns:ResourceItem" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="addResourcesParameters">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="services" type="tns:ServiceList" minOccurs="0" maxOccurs="1"/>
<xsd:element name="resources" type="tns:ResourceList" minOccurs="0" maxOccurs="1"/>
<xsd:element name="targetScope" type="xsd:string" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="removeResourcesParameters">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="resources" type="tns:ResourceList" minOccurs="0" maxOccurs="1"/>
<xsd:element name="targetScope" type="xsd:string" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="sendReportParameters">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="callbackID" type="xsd:string"/>
<xsd:element name="report" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="ScopeOption">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="value" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="optionsParameters">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="ScopeOptionList" type="tns:ScopeOption" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="disposeScopeParameters">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Name" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="createScopeParameters">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Name" type="xsd:string"/>
<xsd:element name="ScopeOptionList" type="tns:ScopeOption" minOccurs="1" maxOccurs="unbounded"/>
<xsd:element name="ServiceMap" type="xsd:string" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="GHN" type="tns:resourceID"/>
<xsd:element name="reportID" type="xsd:string"/>
<xsd:element name="report" type="xsd:string"/>
<!-- RESOURCE PROPERTIES -->
<xsd:element name="ManagedScope" type="xsd:string"/>
<xsd:element name="ResourceManagerResourceProperties">
<xsd:complexType>
<xsd:element ref="tns:ManagedScope" minOccurs="1" maxOccurs="1"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>
</types>
<!--============================================================
M E S S A G E S
============================================================-->
<message name="AddResourcesInputMessage">
<part name="request" element="tns:addResourcesParameters"/>
</message>
<message name="AddResourcesResponseMessage">
<part name="request" element="tns:reportID"/>
</message>
<message name="RemoveResourcesInputMessage">
<part name="request" element="tns:removeResourcesParameters"/>
</message>
<message name="RemoveResourcesResponseMessage">
<part name="request" element="tns:reportID"/>
</message>
<message name="SendReportInputMessage">
<part name="request" element="tns:sendReportParameters"/>
</message>
<message name="ChangeScopeOptionsInputMessage">
<part name="request" element="tns:optionsParameters"/>
</message>
<message name="DisposeScopeInputMessage">
<part name="request" element="tns:disposeScopeParameters"/>
</message>
<message name="CreateScopeInputMessage">
<part name="request" element="tns:createScopeParameters"/>
</message>
<message name="GetReportInputMessage">
<part name="request" element="tns:reportID"/>
</message>
<message name="GetReportResponseMessage">
<part name="request" element="tns:report"/>
</message>
<message name="VoidMessage">
<part name="response" element="tns:VOID"/>
</message>
<!--============================================================
P O R T T Y P E
============================================================-->
<portType name="ResourceManagerPortType"
wsdlpp:extends="provider:GCUBEProvider"
wsrp:ResourceProperties="tns:ResourceManagerResourceProperties">
<documentation>service version 1.0.2 </documentation>
<operation name="AddResources">
<input message="tns:AddResourcesInputMessage"/>
<output message="tns:AddResourcesResponseMessage"/>
<fault name="fault" message="corefaults:GCUBEFaultMessage"/>
</operation>
<operation name="RemoveResources">
<input message="tns:RemoveResourcesInputMessage"/>
<output message="tns:RemoveResourcesResponseMessage"/>
<fault name="fault" message="corefaults:GCUBEFaultMessage"/>
</operation>
<operation name="ChangeScopeOptions">
<input message="tns:ChangeScopeOptionsInputMessage"/>
<output message="tns:VoidMessage"/>
<fault name="fault" message="corefaults:GCUBEFaultMessage"/>
</operation>
<operation name="DisposeScope">
<input message="tns:DisposeScopeInputMessage"/>
<output message="tns:VoidMessage"/>
<fault name="fault" message="corefaults:GCUBEFaultMessage"/>
</operation>
<operation name="CreateScope">
<input message="tns:CreateScopeInputMessage"/>
<output message="tns:VoidMessage"/>
<fault name="fault" message="corefaults:GCUBEFaultMessage"/>
</operation>
<operation name="SendReport">
<input message="tns:SendReportInputMessage"/>
<output message="tns:VoidMessage"/>
<fault name="fault" message="corefaults:GCUBEFaultMessage"/>
</operation>
<operation name="GetReport">
<input message="tns:GetReportInputMessage"/>
<output message="tns:GetReportResponseMessage"/>
<fault name="fault" message="corefaults:GCUBEFaultMessage"/>
</operation>
</portType>
</definitions>

27
schema/VREManagementTypes.wsdl Executable file
View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="VREManagementTypes"
targetNamespace="http://gcube-system.org/common/vremanagement/types"
xmlns:tns="http://gcube-system.org/common/vremanagement/types"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/03/addressing"
elementFormDefault="qualified" attributeFormDefault="unqualified">
<!--============================================================
T Y P E S
============================================================-->
<types>
<xs:schema
targetNamespace="http://gcube-system.org/common/vremanagement/types"
xmlns:tns="http://gcube-system.org/common/vremanagement/types">
<!-- <xs:import namespace="http://schemas.xmlsoap.org/ws/2004/03/addressing" schemaLocation="../../../../ws/addressing/WS-Addressing.xsd" /> -->
<xs:import namespace="http://schemas.xmlsoap.org/ws/2004/03/addressing" schemaLocation="../ws/addressing/WS-Addressing.xsd" />
<xs:include schemaLocation="VREManagementTypes.xsd" />
</xs:schema>
</types>
</definitions>

80
schema/VREManagementTypes.xsd Executable file
View File

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://gcube-system.org/common/vremanagement/types"
xmlns:tns="http://gcube-system.org/common/vremanagement/types"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/03/addressing"
elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:complexType name="DeployInfoStatus">
<xs:sequence minOccurs="1" maxOccurs="1">
<xs:element name="ghnID" type="xs:string"/>
<xs:element name="packageInfo" type="tns:PackageInfoStatus"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DeployInfo">
<xs:sequence minOccurs="1" maxOccurs="1">
<xs:element name="ghnID" type="xs:string"/>
<xs:element name="packageInfo" type="tns:PackageInfo"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="Pair">
<xs:sequence minOccurs="1" maxOccurs="1">
<xs:element name="name" type="xs:string"/>
<xs:element name="value" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="PackageInfo">
<xs:sequence minOccurs="1" maxOccurs="1">
<xs:element name="serviceName" type="xs:string"/>
<xs:element name="serviceClass" type="xs:string"/>
<xs:element name="serviceVersion" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="version" type="xs:string"/>
<xs:element name="Options" type="tns:Pair" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="PackageInfoStatus">
<xs:sequence>
<xs:element name="package" type="tns:PackageInfo" />
<xs:element name="status" type="xs:string"/>
<xs:element name="message" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ServiceInfoStatus">
<xs:sequence minOccurs="1" maxOccurs="1">
<xs:element name="serviceName" type="xs:string"/>
<xs:element name="serviceClass" type="xs:string"/>
<xs:element name="ghnName" type="xs:string"/>
<xs:element name="status" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="deployMessage">
<xs:sequence>
<xs:element name="serviceName" type="xs:string"/>
<xs:element name="serviceClass" type="xs:string"/>
<xs:element name="ghnID" type="xs:string" />
<xs:element name="Scope" type="xs:string" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="feedbackMessage">
<xs:sequence>
<xs:element name="callbackID" type="xs:string" />
<xs:element name="log" type="xs:string" />
<xs:element name="type" type="xs:string" />
<xs:element name="runningInstanceIDsList" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="packageInfoStatus" type="tns:PackageInfoStatus" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

View File

@ -0,0 +1,236 @@
package org.gcube.vremanagement.resourcemanager.impl;
import org.apache.axis.components.uuid.UUIDGenFactory;
import org.gcube.common.core.contexts.GCUBEServiceContext;
import org.gcube.common.core.faults.GCUBEFault;
import org.gcube.common.core.porttypes.GCUBEPortType;
import org.gcube.common.core.resources.GCUBEResource;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.scope.GCUBEScopeManager.IllegalScopeException;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.impl.contexts.StatefulPortTypeContext;
import org.gcube.vremanagement.resourcemanager.impl.deployment.DeployerReport;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.AddResourcesParameters;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.CreateScopeParameters;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.DisposeScopeParameters;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.OptionsParameters;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.RemoveResourcesParameters;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ScopeOption;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.SendReportParameters;
import org.gcube.vremanagement.resourcemanager.impl.operators.AddResourcesOperator;
import org.gcube.vremanagement.resourcemanager.impl.operators.OperatorConfig;
import org.gcube.vremanagement.resourcemanager.impl.operators.RemoveResourcesOperator;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedRunningInstance;
import org.gcube.vremanagement.resourcemanager.impl.state.ResourceReport;
import org.gcube.vremanagement.resourcemanager.impl.state.PublishedScopeResource;
import org.gcube.vremanagement.resourcemanager.impl.state.InstanceState;
import org.gcube.vremanagement.resourcemanager.impl.state.PublishedScopeResource.UnknownScopeOptionException;
import org.globus.wsrf.NoSuchResourceException;
import org.globus.wsrf.ResourceException;
/**
* <em>ResourceManager</em> port-type implementation
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class ResourceManager extends GCUBEPortType {
/** Singleton resource name*/
public static final String SINGLETON_RESOURCE_KEY = "VREManagerState";
/**
* Object logger.
*/
protected final GCUBELog logger = new GCUBELog(this, ServiceContext.getContext());
@Override
protected GCUBEServiceContext getServiceContext() {
return ServiceContext.getContext();
}
/**
* Adds a new group of {@link GCUBEResource} to the PublishedScopeResource
*
* @param resourcesList the resources to join
* @return the ID assigned to the operation, it can be used to retrieve the resource report by invoking the {@link ResourceManager#getReport(String)} operation
* @throws GCUBEFault if the operation fails
*/
public String addResources(AddResourcesParameters resourceList) throws GCUBEFault {
logger.debug("AddResources operation invoked");
try {
//PublishedScopeResource resource = this.getResource().getPublishedScopeResource();
//resource.reload();
//checks the input scope
GCUBEScope targetScope = this.validateOperationScope(resourceList.getTargetScope());
ResourceReport report = new ResourceReport(UUIDGenFactory.getUUIDGen().nextUUID(), targetScope);
this.getResource().addReport(report);
new AddResourcesOperator(new OperatorConfig(report, this.getResource().getResourceList(), targetScope),resourceList).run();
//resource.publish();
//returns the report ID, it can be used to invoke the getReport operation
return report.getId();
} catch (IllegalScopeException ise){
logger.error("The target scope (" + resourceList.getTargetScope() + ") is not valid or null or not joined to this instance", ise);
throw ServiceContext.getContext().getDefaultException("The target scope (" + resourceList.getTargetScope() + ") is not valid or null or not joined to this instance", ise).toFault();
} catch (Exception e) {
logger.error("Unable to manage the input given resources(s) within the scope: " + e.getMessage(), e);
throw ServiceContext.getContext().getDefaultException("Unable to manage the input given resources(s) within the scope: " + e.getMessage(), e).toFault();
}
}
/**
* Removes a group of {@link GCUBEResource} from the PublishedScopeResource
*
* @param resourcesList the resources to remove from the PublishedScopeResource
* @throws GCUBEFault if the operation fails
*/
public String removeResources(RemoveResourcesParameters resourceList) throws GCUBEFault {
try {
//PublishedScopeResource resource = this.getResource().getPublishedScopeResource();
//resource.reload();
GCUBEScope targetScope = this.validateOperationScope(resourceList.getTargetScope());
ResourceReport report = new ResourceReport(UUIDGenFactory.getUUIDGen().nextUUID(), targetScope);
this.getResource().addReport(report);
new RemoveResourcesOperator(new OperatorConfig(report, this.getResource().getResourceList(), targetScope),resourceList).run();
//resource.publish();
//returns the report ID, it can be used to invoke the getReport operation
return report.getId();
} catch (IllegalScopeException ise){
logger.error("The target scope (" + resourceList.getTargetScope() + ") is not valid or null or not joined to this instance", ise);
throw ServiceContext.getContext().getDefaultException("The target scope (" + resourceList.getTargetScope() + ") is not valid or null or not joined to this instance", ise).toFault();
} catch (Exception e) {
logger.error("Unable to manage the input given resources(s) within the scope: " + e.getMessage(), e);
throw ServiceContext.getContext().getDefaultException("Unable to manage the input given resources(s) within the scope: " + e.getMessage(), e).toFault();
}
}
public void disposeScope(DisposeScopeParameters params) {
}
public void createScope(CreateScopeParameters params) {
}
/**
* Changes some options on the scope
*
* @param options the new options to change
* @throws GCUBEFault if any of the input options is not valid
*/
public void changeScopeOptions(OptionsParameters options) throws GCUBEFault {
PublishedScopeResource scoperesource = null;
try {
scoperesource = this.getResource().getPublishedScopeResource();
scoperesource.reload();
} catch (NoSuchResourceException e) {
logger.error("No resource found for this scope", e);
throw ServiceContext.getContext().getDefaultException("No resource found for this scope", e).toFault();
} catch (Exception e) {
logger.error("SetScopeOption: ", e);
throw ServiceContext.getContext().getDefaultException("ChangeScopeOption: ", e).toFault();
}
//add the new options
for (ScopeOption option : options.getScopeOptionList()) {
logger.trace("ScopeOption received: " + option.getName() +"="+ option.getValue());
try {
scoperesource.setOption(option.getName().trim(), option.getValue().trim());
} catch (UnknownScopeOptionException e) {
logger.warn("Unknown option: " + option.getName());
//throw ServiceContext.getContext().getDefaultException("Unknown option: " + option.getName(), e).toFault();
} catch (Exception e) {
logger.warn("Unable to read option: " + option.getName());
//throw ServiceContext.getContext().getDefaultException("Unable to manage option: " + option.getName() + " reason " +e.getMessage(), e).toFault();
}
}
//and publish the scope resource
try {
scoperesource.publish();
} catch (Exception e) {
logger.error("Unable to publish the ScopeResouce", e);
throw ServiceContext.getContext().getDefaultException("Unable to publish the ScopeResouce", e).toFault();
}
}
/**
* Receives a deployment report. It is called by the Deployer services on the GHNs contacted within the {@link #addResources(AddResourcesParameters)}
* operation
*
* @param report the resource report
* @throws GCUBEFault if the report does not have a valid serialization
*/
public void sendReport(SendReportParameters reportMessage) throws GCUBEFault {
logger.info("Received report for session " + reportMessage.getCallbackID());
logger.trace("Report content: \n" + reportMessage.getReport());
try {
ResourceReport report = this.getResource().getReport(reportMessage.getCallbackID());
DeployerReport dreport = new DeployerReport(reportMessage.getReport());
report.addGHNReport(dreport);
report.save();
PublishedScopeResource resource = this.getResource().getPublishedScopeResource();
resource.reload();
for (ScopedRunningInstance instance : dreport.getInstances()) {
logger.trace("Adding instance " + instance.getId() + " to PublishedScopeResource");
resource.addResource(instance);
}
resource.publish();
} catch (NoSuchResourceException e) {
logger.error("Unable to find ResourceManager resource", e);
throw ServiceContext.getContext().getDefaultException("Unable to find ResourceManager resource", e).toFault();
} catch (ResourceException e) {
logger.error("Unable to find ResourceManager resource", e);
throw ServiceContext.getContext().getDefaultException("Unable to find ResourceManager resource", e).toFault();
} catch (Exception e) {
throw ServiceContext.getContext().getDefaultException("Unable to parse or save the Deployer Report", e).toFault();
}
}
/**
* Gets a Resource Report
*
* @param ID the report identifier
* @return a string serialization of the report
* @throws GCUBEFault if the report is not found or does not have a valid serialization
*/
public String getReport(String ID) throws GCUBEFault {
try {
return this.getResource().getReport(ID).toXML();
} catch (Exception e) {
logger.error("Unable to retrieve the Resource Report for ID " + ID,e);
throw ServiceContext.getContext().getDefaultException("Unable to retrieve the Resource Report for ID " + ID, e).toFault();
}
}
/**
* Validates the input scope of each PublishedScopeResource operation
*
* @param inScope the scope to check
* @return the accepted scope
* @throws IllegalScopeException if the given scope has not been accepted
*/
private GCUBEScope validateOperationScope(String inScope) throws IllegalScopeException {
if ((inScope == null) || (inScope.compareToIgnoreCase("") == 0))
return ServiceContext.getContext().getScope(); // use the instance scope as default
else if (GCUBEScope.getScope(inScope.trim()).isEnclosedIn(ServiceContext.getContext().getScope()))
return GCUBEScope.getScope(inScope.trim());
else
throw new IllegalScopeException();
}
/**
* Gets the singleton resource
*
* @return the {@link InstanceState}
* @throws NoSuchResourceException
* @throws ResourceException
*/
private InstanceState getResource() throws NoSuchResourceException, ResourceException{
return (InstanceState) StatefulPortTypeContext.getContext().getWSHome().find(StatefulPortTypeContext.getContext().makeKey(SINGLETON_RESOURCE_KEY));
}
}

View File

@ -0,0 +1,116 @@
package org.gcube.vremanagement.resourcemanager.impl.contexts;
import java.io.File;
import org.gcube.common.core.contexts.GCUBEServiceContext;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.utils.handlers.GCUBEHandler;
import org.gcube.common.core.utils.handlers.GCUBEScheduledHandler;
import org.gcube.vremanagement.resourcemanager.impl.ResourceManager;
/**
* ResourceManager service context implementation
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class ServiceContext extends GCUBEServiceContext {
static ServiceContext cache = new ServiceContext();
/**
* Gets the current service context
* @return the service context
*/
public static ServiceContext getContext() {
return cache;
}
@Override protected String getJNDIName() {
return "gcube/vremanagement/ResourceManager/service";
}
/**
* {@inheritDoc}
*
*/
@SuppressWarnings("unchecked")
protected void onReady() throws Exception {
super.onReady();
// no more than one scope is allowed!
if (ServiceContext.getContext().getInstance().getScopes().values().size() != 1) {
logger.fatal("ResourceManager is misconfigured, cannot start the service in multiple scopes");
throw new IllegalServiceScopeException("ResourceManager has been configured to join more than one scope, while it can work only in ONE single scope");
}
//creates the stateful resource for the service with a short delay
HStateScheduler stateScheduler = new HStateScheduler(10, GCUBEScheduledHandler.Mode.LAZY);
stateScheduler.setScheduled(new HState());
stateScheduler.run();
}
/**
* Creates/updates the Deployer stateful resource
*
* @author Manuele Simi (ISTI-CNR)
*
*/
@SuppressWarnings("unchecked")
protected class HStateScheduler extends GCUBEScheduledHandler {
public HStateScheduler(long interval, Mode mode) {
super(interval, mode);
}
@Override
protected boolean repeat(Exception exception, int exceptionCount) {
if (exception!=null) {
logger.warn("Failed to create the vre manager resource (attempt "+exceptionCount+" out of 20)",exception);
if (exceptionCount >= 20) {
logger.error("Max attempts reached, no more chance to register the ResourceManager resource, the service startup failed");
ServiceContext.getContext().setStatus(GCUBEServiceContext.Status.FAILED);
return false;
} else
return true;
} else {
return false;
}
}
}
/** Tries to create the resource in all the instance scopes*/
protected class HState extends GCUBEHandler<Object> {
public HState() {}
public void run() throws Exception {
GCUBEScope scope = ServiceContext.getContext().getInstance().getScopes().values().iterator().next();
logger.trace("Adding ResourceManager resource to " + scope);
ServiceContext.getContext().setScope(scope);
StatefulPortTypeContext.getContext().getWSHome().create(StatefulPortTypeContext.getContext().makeKey(ResourceManager.SINGLETON_RESOURCE_KEY));
}
}
/**
* Given a relative path in the /etc folder of the service, returns its absolute path
*
* @param path a relative path to a configuration file or folder
* @return the absolute path of the file
*/
public String getConfigurationFileAbsolutePath(String relativepath) {
File file = super.getFile(relativepath, false);
//eventually creates the directory tree if needed
if (!file.exists() || file.isDirectory()) {file.mkdirs();}
return file.getAbsolutePath();
}
/** IllegalServiceScopeException exception */
public static class IllegalServiceScopeException extends Exception{
private static final long serialVersionUID = 1L;
public IllegalServiceScopeException(String message) {super(message);}};
}

View File

@ -0,0 +1,40 @@
package org.gcube.vremanagement.resourcemanager.impl.contexts;
import org.gcube.common.core.contexts.GCUBEServiceContext;
import org.gcube.common.core.contexts.GCUBEStatefulPortTypeContext;
/**
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class StatefulPortTypeContext extends GCUBEStatefulPortTypeContext {
static StatefulPortTypeContext cache = new StatefulPortTypeContext();
@Override
public String getJNDIName() {
return "gcube/vremanagement/ResourceManager";
}
@Override
public String getNamespace() {
return "http://gcube-system.org/namespaces/vremanagement/vremanager";
}
@Override
public GCUBEServiceContext getServiceContext() {
return ServiceContext.getContext();
}
/**
*
* @return the stateful context
*/
public static GCUBEStatefulPortTypeContext getContext() {
return cache;
}
}

View File

@ -0,0 +1,77 @@
package org.gcube.vremanagement.resourcemanager.impl.deployment;
import java.util.List;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ServiceItem;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ServiceList;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.ResolvedService;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.Service;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.VirtualNodeManager;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.VirtualNodeManager.NoGHNFoundException;
import org.gcube.vremanagement.resourcemanager.impl.operators.OperatorConfig;
import org.gcube.vremanagement.resourcemanager.impl.operators.Operator;
/**
* A Deployer Operator that contacts the Deployer Services on the target nodes asking for the package deployment
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class DeployServiceOperator implements Operator {
/** Object logger */
protected final GCUBELog logger=new GCUBELog(this);
private ServiceList services;
private OperatorConfig configuration;
public DeployServiceOperator(OperatorConfig configuration, ServiceList services) {
this.services = services;
this.configuration = configuration;
}
/* (non-Javadoc)
* @see org.gcube.vremanagement.resourcemanager.impl.deployment.VREOperator#run()
*/
public void run() throws Exception {
SoftwareRepositoryRequest request = new SoftwareRepositoryRequest();
//resolving the list of packages for each service
for (ServiceItem serviceitem : services.getService())
request.addService(Service.fromServiceItem(serviceitem));
List<ResolvedService> resolved = request.send();
this.configuration.report.save();
//sanity check: do we get the same list passed as input?
if ( (resolved == null) || (resolved.size() != services.getService().length)) {
logger.error("Unable to understand the list of deps for the given service(s): input services #" +services.getService().length + ", resolved services #" + resolved.size());
logger.trace("RESOLVED: " + resolved);
logger.trace("REQUESTED " + services.getService());
throw new Exception("invalid list of deps retrieved: input services #" +services.getService().length + ", resolved services #" + resolved.size());
}
//deploy the packages
VirtualNodeManager drequest = new VirtualNodeManager(this.configuration.report.getId(), this.configuration.scope);
drequest.setTargetGHNs(services.getGHN());
for (ResolvedService resolvedService : resolved) {
if (resolvedService.getMissingDependencies().size() > 0) {//ops, some deps are missing!
logger.debug("Missing dependencies for service " + resolvedService.toString());
resolvedService.setErrorMessage("The service cannot be deployed due to one or more missing dependencies");
} else {
try {
drequest.addService(resolvedService);
} catch (NoGHNFoundException e) {
logger.error("Unable to find a valid GHN to target for the deployment of this service: " + resolvedService.getName());
resolvedService.setErrorMessage("Unable to find a valid GHN to target for the deployment of this service");
}
}
this.configuration.report.addService(resolvedService);
}
drequest.send();
this.configuration.report.save();
}
}

View File

@ -0,0 +1,209 @@
package org.gcube.vremanagement.resourcemanager.impl.deployment;
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.DeployedDependency;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.Service;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedRunningInstance;
import org.gcube.vremanagement.resourcemanager.impl.state.ProfileDate;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;
/**
* Parser for the report sent back by the Deployer Service
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class DeployerReport {
private String report = "";
private String status = "";
private String id = "";
private String host = "";
private String type = "";
private Date lastUpdate;
private List<DeployedDependency> dependencies = new ArrayList<DeployedDependency>();
private Set<ScopedRunningInstance> instances = new HashSet<ScopedRunningInstance>();
/**
*
* @param report the string representation of the report as sent by a Deployer Service
*
*/
public DeployerReport(String report) throws Exception {
this.report = report;
try {
this.parse();
} catch (XmlPullParserException e) {
throw new Exception("invalid Deployer Report");
}
}
/**
* Gets the GHN ID
* @return the id
*
* @throws Exception if it is impossible to parse the Deployer Report or the GHNID element is not found
*/
public String getGHNID() {
//look for GHNID element
return this.id;
}
public String toString() {
return this.report;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @return the lastUpdate
*/
public Date getLastUpdate() {
return lastUpdate;
}
/**
* @return the dependencies
*/
public List<DeployedDependency> getDependencies() {
return dependencies;
}
/**
*
* @return the hostname from which the report was sent
*/
public String getHost() {
return this.host;
}
private void parse() throws Exception {
KXmlParser parser = new KXmlParser();
parser.setInput(new BufferedReader(new StringReader(report)));
loop: while (true) {
try {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("GHNID")) this.id = parser.nextText();
else if (parser.getName().equals("Type")) this.type = parser.nextText();
else if (parser.getName().equals("LastUpdate")) this.lastUpdate = ProfileDate.fromXMLDateAndTime( parser.nextText());
else if (parser.getName().equals("Status")) this.status = parser.nextText();
else if (parser.getName().equals("Packages")) this.parsePackages(parser);
else if (parser.getName().equals("NewInstances")) this.parseInstances(parser);
break;
case KXmlParser.END_DOCUMENT: break loop;
}
} catch (Exception e) {
throw new Exception ("Unable to parse the Deployer Report");
}
}
}
private void parseInstances(KXmlParser parser) throws Exception {
loop: while (true) {
try {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("NewInstance")) {
String id = "";
innerloop: while (true) {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("ID"))
id = parser.nextText();
else
parser.nextText();//just skip the text
break;
case KXmlParser.END_TAG: if (parser.getName().equals("NewInstance")){
this.instances.add(new ScopedRunningInstance(id, ServiceContext.getContext().getScope(), this.host));
break innerloop;
}
break;
case KXmlParser.END_DOCUMENT: throw new Exception ("Parsing failed at Package");
}
}
}
break;
case KXmlParser.END_TAG: if (parser.getName().equals("NewInstances")) break loop;
break;
case KXmlParser.END_DOCUMENT: throw new Exception ("Parsing failed at NewInstances");
}
} catch (Exception e) {
throw new Exception ("Unable to parse the Deployer Report");
}
}
}
private void parsePackages(KXmlParser parser) throws Exception {
loop: while (true) {
try {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("Package")) {
DeployedDependency dd = new DeployedDependency();
dd.setService(new Service());
innerloop: while (true) {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("ServiceClass")) {dd.getService().setClazz(parser.nextText());}
else if (parser.getName().equals("ServiceName")) {dd.getService().setName(parser.nextText());}
else if (parser.getName().equals("ServiceVersion")) {dd.getService().setVersion(parser.nextText());}
else if (parser.getName().equals("PackageName")) {dd.setName(parser.nextText());}
else if (parser.getName().equals("PackageVersion")) {dd.setVersion(parser.nextText());}
else if (parser.getName().equals("Status")) {dd.setStatus(parser.nextText());}
else if (parser.getName().equals("Host")) {dd.setHost(parser.nextText()); this.host = dd.getHost();}
else if (parser.getName().equals("Message")) {dd.setMessage(parser.nextText());}
else parser.nextText();
break;
case KXmlParser.END_TAG: if (parser.getName().equals("Package")){ this.dependencies.add(dd); break innerloop;}
break;
case KXmlParser.END_DOCUMENT: throw new Exception ("Parsing failed at Package");
}
}
}
break;
case KXmlParser.END_TAG: if (parser.getName().equals("Packages")) break loop;
break;
case KXmlParser.END_DOCUMENT: throw new Exception ("Parsing failed at Packages");
}
} catch (Exception e) {
throw new Exception ("Unable to parse the Deployer Report");
}
}
}
/**
* @return the status
*/
public String getStatus() {
return this.status;
}
/**
* @return the instances
*/
public Set<ScopedRunningInstance> getInstances() {
return this.instances;
}
}

View File

@ -0,0 +1,252 @@
package org.gcube.vremanagement.resourcemanager.impl.deployment;
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.gcube.common.core.contexts.GCUBERemotePortTypeContext;
import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.informationsystem.client.AtomicCondition;
import org.gcube.common.core.informationsystem.client.ISClient;
import org.gcube.common.core.informationsystem.client.queries.GCUBERIQuery;
import org.gcube.common.core.resources.GCUBERunningInstance;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.Dependency;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.ResolvedService;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.Service;
import org.gcube.vremanagement.softwarerepository.stubs.ListScopedPackagesByServiceDataMessage;
import org.gcube.vremanagement.softwarerepository.stubs.ListScopedPackagesByServiceDataMessageScope;
import org.gcube.vremanagement.softwarerepository.stubs.SoftwareRepositoryPortType;
import org.gcube.vremanagement.softwarerepository.stubs.service.SoftwareRepositoryServiceAddressingLocator;
import org.kxml2.io.KXmlParser;
/**
* Request for the Software Repository service to solve the service2package
* relationships
*
* @author Manuele Simi (ISTI-CNR)
*
*/
class SoftwareRepositoryRequest {
Map<Service, ListScopedPackagesByServiceDataMessage> requests = new HashMap<Service, ListScopedPackagesByServiceDataMessage>();
protected static final String RESOLVED_DEPS_KEY = "listResolvedDeps";
protected static final String MISSING_DEPS_KEY = "listMissingDeps";
/** Target port-type name. */
protected static final String REPOSITORY_ENDPOINT = "gcube/vremanagement/softwarerepository/SoftwareRepository";
/** Target service name. */
protected static final String REPOSITORY_NAME = "SoftwareRepository";
/** Target service class. */
protected static final String REPOSITORY_CLASS = "VREManagement";
/** Target service class. */
protected static final int TIMEOUT = 600000; //in milliseconds
/** Object logger */
protected final GCUBELog logger = new GCUBELog(this);
/**
* Adds a new service to the request
*
* @param service
*/
protected void addService(Service service) {
ListScopedPackagesByServiceDataMessage message = new ListScopedPackagesByServiceDataMessage();
message.setServiceClass(service.getClazz());
message.setServiceName(service.getName());
message.setServiceVersion(service.getVersion());
message.setScope(ListScopedPackagesByServiceDataMessageScope.GHN);// look for packages to co-deploy
requests.put(service, message);
}
/**
* Sends the request to the appropriate SR
*
* @throws Exception
*/
protected List<ResolvedService> send() throws Exception {
List<ResolvedService> service2package = new ArrayList<ResolvedService>();
Map<GCUBEScope, Set<EndpointReferenceType>> eprs = this.findInstances();
for (Service service : requests.keySet()) {
ListScopedPackagesByServiceDataMessage message = requests.get(service);
logger.trace("Checking deps for " + message.getServiceName());
//look for service deps in one of the instances found
inner: for (GCUBEScope scope : eprs.keySet()) {
for (EndpointReferenceType epr : eprs.get(scope)) {
try {
logger.trace("Trying Service Repository located at "+ epr);
SoftwareRepositoryPortType portType = new SoftwareRepositoryServiceAddressingLocator().getSoftwareRepositoryPortTypePort(epr);
String report = GCUBERemotePortTypeContext.getProxy(portType, scope, TIMEOUT, ServiceContext.getContext()).listScopedPackagesByServiceData(message);
service2package.add(parseDependenciesReport(service, report));
break inner;//no need for looping on the other instances, we just need that one satisfies the request
} catch (Exception e) {
logger.warn("Unable to check deps for " + message.getServiceName() + " from Service Repository in " + scope + ": "+ e.getMessage(), e);
}
}
// if we are here, no SR instance was able to resolve the dependencies
ResolvedService s = new ResolvedService(service);
s.setErrorMessage("Unable to check deps for this service in any of the Service Repository instance in scope");
service2package.add(s);
}
}
return service2package;
}
/**
* Parses the dependencies report
* @param report
* @return
*/
private ResolvedService parseDependenciesReport(Service service, String report) throws Exception {
ResolvedService depsMap = new ResolvedService(service);
KXmlParser parser = new KXmlParser();
parser.setInput(new BufferedReader(new StringReader(report)));
logger.trace("Parsing: " + report);
try {
loop: while (true) {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("ResolvedDependencies")) this.parseResolvedDependencies(parser, depsMap.getResolvedDependencies());
if (parser.getName().equals("MissingDependencies")) this.parseMissingDependencies(parser, depsMap.getMissingDependencies());
break;
case KXmlParser.END_DOCUMENT:
break loop;
}
}
} catch (Exception e) {
logger.error("Unable to parse the deployment report returned by the Software Repository", e);
}
return depsMap;
}
/**
* Parses the service section of a dependency
*
* @param parser the XML parser
* @param s the service to populate
* @throws Exception
*/
private void parseService(KXmlParser parser, Service s) throws Exception {
inloop: while (true) {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("Class"))
s.setClazz(parser.nextText());
if (parser.getName().equals("Name"))
s.setName(parser.nextText());
if (parser.getName().equals("Version"))
s.setVersion(parser.nextText());
break;
case KXmlParser.END_TAG:
if (parser.getName().equals("Service"))
break inloop;
break;
case KXmlParser.END_DOCUMENT:
throw new Exception("Parsing failed at Service");
}
}
}
/**
* Parses a generic dependency section (both missing and resolved)
*
* @param parser the XML parser
* @return the dependency
* @throws Exception
*/
private Dependency parseDependency(KXmlParser parser) throws Exception {
logger.trace("Parsing a resolved or missing dependency...");
Dependency p = new Dependency();
loop: while (true) {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("Service")) parseService(parser, p.getService());
if (parser.getName().equals("Package")) p.setName(parser.nextText());
if (parser.getName().equals("Version")) p.setVersion(parser.nextText());
break;
case KXmlParser.END_TAG:
if ((parser.getName().equals("Dependency")) || (parser.getName().equals("MissingDependency"))) break loop;
break;
case KXmlParser.END_DOCUMENT:
throw new Exception("Parsing failed at Dependency");
}
}
return p;
}
private void parseResolvedDependencies(KXmlParser parser, List<Dependency> listResolvedDeps) throws Exception {
logger.trace("Parsing resolved dependencies...");
loop: while (true) {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("Dependency")) listResolvedDeps.add(this.parseDependency(parser));
case KXmlParser.END_TAG:
if (parser.getName().equals("ResolvedDependencies")) break loop;
break;
case KXmlParser.END_DOCUMENT:
throw new Exception("Parsing failed at ResolvedDependencies");
}
}
}
private void parseMissingDependencies(KXmlParser parser, List<Dependency> listMissingDeps) throws Exception {
logger.trace("Parsing missing dependencies...");
loop: while (true) {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("MissingDependency")) listMissingDeps.add(this.parseDependency(parser));
case KXmlParser.END_TAG:
if (parser.getName().equals("MissingDependencies")) break loop;
break;
case KXmlParser.END_DOCUMENT:
throw new Exception("Parsing failed at MissingDependencies");
}
}
}
/**
* Finds instances of the Software Repository service in the current scope(s)
* @return the list of scopes and the EPR of the available SR
* @throws Exception
*/
protected Map<GCUBEScope, Set<EndpointReferenceType>> findInstances()throws Exception {
Map<GCUBEScope, Set<EndpointReferenceType>> scopeMap = new HashMap<GCUBEScope, Set<EndpointReferenceType>>();
logger.debug("Looking for SR instances...");
ISClient client = GHNContext.getImplementation(ISClient.class);
GCUBERIQuery lookupQuery = client.getQuery(GCUBERIQuery.class);
lookupQuery.addAtomicConditions(new AtomicCondition("//ServiceName",REPOSITORY_NAME));
lookupQuery.addAtomicConditions(new AtomicCondition("//ServiceClass",REPOSITORY_CLASS));
for (GCUBEScope scope : ServiceContext.getContext().getInstance().getScopes().values()) {
/*
* if (scope.isInfrastructure()) //TODO: deploy only in a PublishedScopeResource
* continue;
*/
logger.debug("Quering in scope " + scope);
List<GCUBERunningInstance> list = client.execute(lookupQuery, scope);
logger.debug("Found N." + list.size() + " instances");
for (GCUBERunningInstance instance : list) {
logger.trace("Found instance " + instance.toString());
EndpointReferenceType epr = instance.getAccessPoint().getEndpoint(REPOSITORY_ENDPOINT);
logger.trace("Found EPR " + epr.toString());
if (!scopeMap.keySet().contains(scope)) {
Set<EndpointReferenceType> l = new HashSet<EndpointReferenceType>();
scopeMap.put(scope, l);
}
scopeMap.get(scope).add(epr);
}
}
return scopeMap;
}
}

View File

@ -0,0 +1,29 @@
package org.gcube.vremanagement.resourcemanager.impl.deployment;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.vremanagement.resourcemanager.impl.operators.Operator;
import org.gcube.vremanagement.resourcemanager.impl.operators.OperatorConfig;
/**
*
* TODO: manuele, don't forget to comment this class
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class UndeployServiceOperator implements Operator {
protected final GCUBELog logger=new GCUBELog(this);
private OperatorConfig configuration;
public UndeployServiceOperator(OperatorConfig configuration) {
this.configuration = configuration;
}
public void run() throws Exception {
}
}

View File

@ -0,0 +1,100 @@
package org.gcube.vremanagement.resourcemanager.impl.deployment.resources;
public class Dependency {
protected Service service = new Service();
protected String name;
protected String version;
/**
* @return the service
*/
public Service getService() {
return service;
}
/**
* @param service the service to set
*/
public void setService(Service service) {
this.service = service;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the version
*/
public String getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion(String version) {
this.version = version;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((service == null) ? 0 : service.hashCode());
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Dependency other = (Dependency) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (service == null) {
if (other.service != null)
return false;
} else if (!service.equals(other.service))
return false;
if (version == null) {
if (other.version != null)
return false;
} else if (!version.equals(other.version))
return false;
return true;
}
@Override public String toString() {
return this.getName() + "," + this.getVersion() + " of service (" + this.getService() + ")";
}
}

View File

@ -0,0 +1,58 @@
package org.gcube.vremanagement.resourcemanager.impl.deployment.resources;
/**
* A package deployed by a Deployer service
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class DeployedDependency extends Dependency {
protected String host = "";
protected String status = "";
protected String message = "";
/**
* @return the host
*/
public String getHost() {
return host;
}
/**
* @param host the host to set
*/
public void setHost(String host) {
this.host = host;
}
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
}

View File

@ -0,0 +1,78 @@
package org.gcube.vremanagement.resourcemanager.impl.deployment.resources;
import java.util.ArrayList;
import java.util.List;
/**
* A {@link ResolvedService} is a {@link Service} whose dependencies have been already checked
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class ResolvedService extends Service {
protected List<Dependency> resolved = new ArrayList<Dependency>();
protected List<Dependency> missing = new ArrayList<Dependency>();
protected String deployedOn = "";
private String errorMessage = "";
/**
* @return the deployedOn
*/
public String getDeployedOn() {
return deployedOn;
}
/**
* @param deployedOn the deployedOn to set
*/
public void setDeployedOn(String deployedOn) {
this.deployedOn = deployedOn;
}
/**
*
* @param service the service used to check the dependecnies
*/
public ResolvedService(Service service) {
this.clazz = service.clazz;
this.name = service.name;
this.version = service.version;
this.GHN = service.GHN;
}
/**
* @return the resolved dependencies
*/
public List<Dependency> getResolvedDependencies() {
return resolved;
}
/**
* @return the missing dependencies
*/
public List<Dependency> getMissingDependencies() {
return missing;
}
/**
*
* @param message
*/
public void setErrorMessage(String message) {
this.errorMessage = message;
}
/**
* @return the errorMessage
*/
public String getErrorMessage() {
return errorMessage;
}
}

View File

@ -0,0 +1,134 @@
package org.gcube.vremanagement.resourcemanager.impl.deployment.resources;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ServiceItem;
/**
* A GCUBE service
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class Service {
protected String clazz;
protected String name;
protected String version;
/** the gHN on which the servie is expected to be deployed */
protected String GHN;
public static Service fromServiceItem(ServiceItem item) {
Service s = new Service();
s.setClazz(item.getServiceClass());
s.setName(item.getServiceName());
s.setVersion(item.getServiceVersion());
if ((item.getGHN() != null) && (item.getGHN().compareToIgnoreCase("")!=0))
s.setGHN(item.getGHN());
return s;
}
/**
* @return the clazz
*/
public String getClazz() {
return clazz;
}
/**
* @param clazz the class to set
*/
public void setClazz(String clazz) {
this.clazz = clazz;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the version
*/
public String getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion(String version) {
this.version = version;
}
/**
* @return the gHNID
*/
public String getGHN() {
return GHN;
}
/**
* @param ghn the gHN to set
*/
public void setGHN(String ghn) {
GHN = ghn;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((clazz == null) ? 0 : clazz.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Service other = (Service) obj;
if (clazz == null) {
if (other.clazz != null)
return false;
} else if (!clazz.equals(other.clazz))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (version == null) {
if (other.version != null)
return false;
} else if (!version.equals(other.version))
return false;
return true;
}
@Override public String toString() {
return this.getName() + "," + this.getClazz() + "," + this.getVersion() ;
}
}

View File

@ -0,0 +1,142 @@
package org.gcube.vremanagement.resourcemanager.impl.deployment.resources;
import java.util.Set;
import org.apache.axis.message.addressing.Address;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.gcube.common.core.contexts.GCUBERemotePortTypeContext;
import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.informationsystem.client.AtomicCondition;
import org.gcube.common.core.informationsystem.client.ISClient;
import org.gcube.common.core.informationsystem.client.queries.GCUBEGHNQuery;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.common.vremanagement.deployer.stubs.common.PackageInfo;
import org.gcube.common.vremanagement.deployer.stubs.deployer.DeployParameters;
import org.gcube.common.vremanagement.deployer.stubs.deployer.DeployerPortType;
import org.gcube.common.vremanagement.deployer.stubs.deployer.service.DeployerServiceAddressingLocator;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.VirtualNodeManager.NoGHNFoundException;
/**
* Models a node with its the packages
*
* @author Manuele Simi (ISTI-CNR)
*
*/
class VirtualNode {
/** Object logger */
protected final GCUBELog logger=new GCUBELog(this);
private String ID = "";
private String name = "";
private GCUBEScope scope = null;
Set<PackageInfo> packages = new java.util.HashSet<PackageInfo>();
protected VirtualNode(String ID, GCUBEScope scope, String ... name) throws NoGHNFoundException {
this.ID = ID;
this.scope = scope;
this.name = (name != null && name.length > 0)? name[0] : this.detectName();
}
private String detectName() throws NoGHNFoundException {
if (GHNContext.getContext().getGHNID().compareToIgnoreCase(this.ID) == 0)
throw new NoGHNFoundException ("cannot deploy on the same GHN (ID=" + this.ID + ") where the ResourceManager is deployed");
try {
ISClient client = GHNContext.getImplementation(ISClient.class);
GCUBEGHNQuery query = client.getQuery(GCUBEGHNQuery.class);
query.addAtomicConditions(new AtomicCondition("/ID/text()", this.ID));
return client.execute(query, this.scope).get(0).getNodeDescription().getName();
} catch (Exception e) {
logger.error("unable to find the target GHN (ID=" + this.ID + ")");
throw new NoGHNFoundException ("unable to find the target GHN (ID=" + this.ID + ")");
}
}
/**
* Adds new packages to the node
*
* @param packages the list of packages to add
*/
protected void addPackages(Set<PackageInfo> packages) {
for (PackageInfo p : packages)
this.packages.add(p);
}
/**
* Gets the packages available on this node
*
* @return the packages
*/
protected Set<PackageInfo> getPackages() {
return this.packages;
}
/**
* Checks if a list of packages is already on this node
*
* @param packages the list of packages to check
* @return true if all the packages are already on this node, false otherwise
*/
protected boolean hasPackages(Set<PackageInfo> packages) {
if (packages.size() == 0)
return false;
if (this.packages.size() == 0)
return false;
input: for (PackageInfo inputPackage : packages) {
for (PackageInfo nodePackage : this.packages) {
if ( (inputPackage.getServiceClass().compareToIgnoreCase(nodePackage.getServiceClass())==0) &&
(inputPackage.getServiceName().compareToIgnoreCase(nodePackage.getServiceName())==0) &&
(inputPackage.getServiceVersion().compareToIgnoreCase(nodePackage.getServiceVersion())==0) &&
(inputPackage.getName().compareToIgnoreCase(nodePackage.getName())==0) &&
(inputPackage.getVersion().compareToIgnoreCase(nodePackage.getVersion())==0))
continue input;
}
return false; //if we arrive here, no matching package has been found
}
return true;
}
/**
* Gets the node ID
*
* @return the node ID
*/
protected String getID() {
return this.ID;
}
/**
* Sends a request to the physical node to deploy the packages
*
* @param callbackID the callback identifier
* @param callbackEPR the callback {@link EndpointReferenceType}
* @throws Exception if the deployment fails
*/
protected void materialize(String callbackID, EndpointReferenceType callbackEPR) throws Exception {
DeployParameters param = new DeployParameters();
param.set_package(this.packages.toArray(new PackageInfo[0]));
param.setTargetScope(new String[] {this.scope.toString()});
param.setCallbackID(callbackID);
param.setEndpointReference(callbackEPR);
EndpointReferenceType nodeEPR = new EndpointReferenceType();
nodeEPR.setAddress(new Address("http://" + this.name+"/wsrf/services/gcube/common/vremanagement/Deployer"));
logger.trace("Deploying on " + nodeEPR.toString());
DeployerPortType pt = GCUBERemotePortTypeContext.getProxy(new DeployerServiceAddressingLocator().getDeployerPortTypePort(nodeEPR),
this.scope, ServiceContext.getContext());
pt.deploy(param);
}
}

View File

@ -0,0 +1,177 @@
package org.gcube.vremanagement.resourcemanager.impl.deployment.resources;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.List;
import java.util.Set;
import org.apache.axis.message.addressing.Address;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.axis.types.URI.MalformedURIException;
import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.common.vremanagement.deployer.stubs.common.PackageInfo;
import org.gcube.vremanagement.resourcemanager.impl.contexts.StatefulPortTypeContext;
/**
* Multiple Request for a Deployer service
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class VirtualNodeManager {
/** Object logger */
protected final GCUBELog logger=new GCUBELog(this);
protected String callbackID;
protected GCUBEScope target;
protected EndpointReferenceType callbackEPR = new EndpointReferenceType();
protected List<String> GHNs = new ArrayList<String>();
//used to apply a round robin assignment of the input GHNs
private int nodewalker = 0;
private static final String DEFAULTNODE = "";
public VirtualNodeManager(String callbackID, GCUBEScope target) throws MalformedURIException {
this.callbackID = callbackID;
this.target = target;
logger.trace("Using target: " + this.target);
this.callbackEPR.setAddress(new Address("http://"+ GHNContext.getContext().getHostnameAndPort() +"/wsrf/services/" + StatefulPortTypeContext.getContext().getJNDIName()));
}
/** ghn id to request map*/
Map<String, Set<PackageInfo>> requests = new HashMap<String, Set<PackageInfo>>();
Map<String, VirtualNode> virtualNodes = new HashMap<String, VirtualNode>();
public void addService(ResolvedService service, String ... GHN) throws NoGHNFoundException {
try {
//select the target GHN
/*
String nodeID = this.getTargetGHN(service);
String nodename = findNodeName(node);
if (! requests.containsKey(nodename))
requests.put(nodename, new HashSet<PackageInfo>());
Set<PackageInfo> packages = new HashSet<PackageInfo>();
service.setDeployedOn(node);
*/
Set<PackageInfo> packages = new HashSet<PackageInfo>();
//prepare the input list of packages for that GHN
List<Dependency> deps = service.getResolvedDependencies();
for (int i = 0; i < deps.size(); i++) {
PackageInfo p = new PackageInfo();
p.setServiceName(deps.get(i).getService().getName());
p.setServiceClass(deps.get(i).getService().getClazz());
p.setServiceVersion(deps.get(i).getService().getVersion());
p.setVersion(deps.get(i).getVersion());
p.setName(deps.get(i).getName()); //packageName
logger.trace("Adding Package to deployment request: " + deps.get(i));
packages.add(p);
}
//check if there is a node with all the packages already scheduled to be deployed
//if so, the service will be already activated there, therefore there is nothing to do
for (VirtualNode virtualNode : this.virtualNodes.values())
if (virtualNode.hasPackages(packages)) return;
VirtualNode node = this.getTargetGHN(service);
if (this.virtualNodes.containsKey(node.getID())) {
this.virtualNodes.get(node.getID()).addPackages(packages);
} else {
node.addPackages(packages);
this.virtualNodes.put(node.getID(), node);
}
service.setDeployedOn(node.getID());
} catch (NoGHNFoundException e) {
service.setDeployedOn("");
service.setErrorMessage("unable to deploy: " + e.getMessage());
}
}
/**
* Sends the request to the appropriate target Deployers
*/
public void send() {
for (VirtualNode virtualNode : this.virtualNodes.values())
try {
virtualNode.materialize(this.callbackID, this.callbackEPR);
} catch (Exception e) {
logger.error("Deployment failed at " + virtualNode.getID());
}
}
/**
* Looks for a GHN hostname given its ID
* @param id the GHN ID
* @return the GHN hostname, if found
*
* @throws Exception if the GHN does not exist
*/
/*private String findNodeName(String id) throws NoGHNFoundException {
try {
ISClient client = GHNContext.getImplementation(ISClient.class);
GCUBEGHNQuery query = client.getQuery(GCUBEGHNQuery.class);
query.addAtomicConditions(new AtomicCondition("/ID/text()", id));
return client.execute(query, this.target).get(0).getNodeDescription().getName();
} catch (Exception e) {
logger.error("unable to find the target GHN (ID=" + id + ")");
throw new NoGHNFoundException ("unable to find the target GHN (ID=" + id + ")");
}
}*/
/**
* Selects a target node for the deployment
*
* @param service the service to deploy
* @return the GHN ID
*/
private VirtualNode getTargetGHN(ResolvedService service) throws NoGHNFoundException {
if ( (service.getGHN() != null) && (service.getGHN().compareToIgnoreCase("") != 0)) {
//a specific GHN has been requested
return new VirtualNode(service.getGHN(),this.target);
} else if (this.GHNs.size() > 0) {
//a set of target GHNs has been requested, assign one of them with a round robin
return new VirtualNode(this.GHNs.get(nodewalker++ % GHNs.size()),this.target);
} else {
//no GHN has been specified as explicit target
return new VirtualNode(DEFAULTNODE,this.target);
}
// TODO: integration with the BMM here?
}
/**
* Sets the GHNs to use as target nodes
*
* @param ghns the list of GHN ID
*/
public void setTargetGHNs(String[] ghns) {
if (ghns == null)
return;
for (String ghn : ghns)
this.GHNs.add(ghn);
}
/** NoGHNFoundException exception */
public static class NoGHNFoundException extends Exception {
private static final long serialVersionUID = 1L;
public NoGHNFoundException(String message) {super(message);}
}
}

View File

@ -0,0 +1,72 @@
package org.gcube.vremanagement.resourcemanager.impl.operators;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.impl.deployment.DeployServiceOperator;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.AddResourcesParameters;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceList;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ServiceList;
import org.gcube.vremanagement.resourcemanager.impl.scopemanagement.ScopedResourceManagerOperator;
import org.gcube.vremanagement.resourcemanager.impl.scopemanagement.ScopedResourceManagerOperator.ACTION;
/**
* A Resources Operator that coordinates the adding of resources to the scope
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class AddResourcesOperator implements Operator {
protected final GCUBELog logger = new GCUBELog(this, ServiceContext.getContext());
private AddResourcesParameters resourceList;
private OperatorConfig configuration;
/**
* Creates a new operator to manage the input resource list
*
* @param resourceList
* @param target
* @param operationID
*/
public AddResourcesOperator(OperatorConfig configuration, AddResourcesParameters resourceList){
this.resourceList = resourceList;
this.configuration = configuration;
}
/**
* {@inheritDoc}
*/
public void run() throws Exception {
// deploy the services, if any
ServiceList services = resourceList.getServices();
if ((services == null) || (services.getService() == null) || (services.getService().length == 0)) {
logger.warn("The list of services to deploy is empty");
} else {
try {
new DeployServiceOperator(configuration, services).run();
} catch (Exception e) {
logger.error("Unable to activate the deployment of the given service(s)", e);
throw new Exception("Unable to activate the deployment of the given service(s)", e);
}
}
//add the resources to the PublishedScopeResource, if any
ResourceList resources = resourceList.getResources();
if ((resources == null) || (resources.getResource() == null) || (resources.getResource().length == 0))
logger.warn("The list of resource to add is empty");
else {
try {
new ScopedResourceManagerOperator(configuration, resources, ACTION.ADD).run();
}catch (Exception e) {
logger.error("Unable to manage the given resource(s)", e);
throw new Exception("Unable to manage the given resource(s)", e);
}
}
//save the report
this.configuration.report.save();
}
}

View File

@ -0,0 +1,14 @@
package org.gcube.vremanagement.resourcemanager.impl.operators;
/**
*
* Interface for service's operators
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public interface Operator {
public abstract void run() throws Exception;
}

View File

@ -0,0 +1,28 @@
package org.gcube.vremanagement.resourcemanager.impl.operators;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.impl.state.ResourceList;
import org.gcube.vremanagement.resourcemanager.impl.state.ResourceReport;
/**
* Basic configuration for every {@link Operator}
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class OperatorConfig {
public final ResourceReport report;
public final GCUBEScope scope;
public final ResourceList resourceList;
public OperatorConfig(ResourceReport report, ResourceList resourceList, GCUBEScope ... scope) {
this.report = report;
this.resourceList = resourceList;
this.scope = (scope!=null && scope.length >0)? scope[0] : ServiceContext.getContext().getScope();
}
}

View File

@ -0,0 +1,45 @@
package org.gcube.vremanagement.resourcemanager.impl.operators;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.RemoveResourcesParameters;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceList;
import org.gcube.vremanagement.resourcemanager.impl.scopemanagement.ScopedResourceManagerOperator;
import org.gcube.vremanagement.resourcemanager.impl.scopemanagement.ScopedResourceManagerOperator.ACTION;
/**
* A Resources Operator that coordinates the removal of resources from the scope
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class RemoveResourcesOperator implements Operator {
protected final GCUBELog logger = new GCUBELog(this, ServiceContext.getContext());
private OperatorConfig configuration;
private RemoveResourcesParameters resourceList;
public RemoveResourcesOperator(OperatorConfig configuration, RemoveResourcesParameters resourceList) {
this.configuration = configuration;
this.resourceList = resourceList;
}
public void run() throws Exception {
//removes the resources to the PublishedScopeResource, if any
ResourceList resources = resourceList.getResources();
if ((resources == null) || (resources.getResource().length == 0))
logger.warn("The list of resource to add is empty");
else {
try {
new ScopedResourceManagerOperator(configuration, resources, ACTION.REMOVE).run();
}catch (Exception e) {
logger.error("Unable to manage the given resource(s)", e);
throw new Exception("Unable to manage the given resource(s)", e);
}
}
}
}

View File

@ -0,0 +1,46 @@
package org.gcube.vremanagement.resourcemanager.impl.resources;
import java.util.HashSet;
import java.util.Set;
import org.gcube.common.core.resources.GCUBEService;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.DeployedDependency;
/**
*
* Models a scoped {@link GCUBEService}
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class ScopedDeployedService extends ScopedResource {
public static final String TYPE = GCUBEService.TYPE;
Set<DeployedDependency> deployedUnits = new HashSet<DeployedDependency>();
public ScopedDeployedService(String id, GCUBEScope scope) {
super(id, TYPE, scope);
}
@Override
public void find() throws Exception {}
@Override
protected void addToScope() throws Exception {
}
@Override
protected void removeFromScope() throws Exception {
}
}

View File

@ -0,0 +1,93 @@
package org.gcube.vremanagement.resourcemanager.impl.resources;
import org.apache.axis.message.addressing.Address;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.gcube.common.core.contexts.GCUBERemotePortTypeContext;
import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.informationsystem.client.AtomicCondition;
import org.gcube.common.core.informationsystem.client.ISClient;
import org.gcube.common.core.informationsystem.client.queries.GCUBEGHNQuery;
import org.gcube.common.core.resources.GCUBEHostingNode;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.vremanagement.ghnmanager.stubs.AddScopeInputParams;
import org.gcube.common.vremanagement.ghnmanager.stubs.GHNManagerPortType;
import org.gcube.common.vremanagement.ghnmanager.stubs.service.GHNManagerServiceAddressingLocator;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
/**
* Models a scoped {@link GCUBEHostingNode}
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class ScopedGHN extends ScopedResource {
public static final String TYPE = GCUBEHostingNode.TYPE;
private String nodename = "";
public ScopedGHN(String id, GCUBEScope scope) {
super(id, TYPE, scope);
}
@Override
protected void addToScope() throws Exception {
if (this.nodename.compareToIgnoreCase("") == 0)
this.find();
//contact the GHNManager to add the GHN to the given scope
EndpointReferenceType endpoint = new EndpointReferenceType();
try {
endpoint.setAddress(new Address("http://"+ this.nodename +"/wsrf/services/gcube/common/vremanagement/GHNManager"));
GHNManagerServiceAddressingLocator locator = new GHNManagerServiceAddressingLocator();
GHNManagerPortType pt = GCUBERemotePortTypeContext.getProxy(locator.getGHNManagerPortTypePort(endpoint),
ServiceContext.getContext().getScope().getEnclosingScope(), ServiceContext.getContext());
AddScopeInputParams params = new AddScopeInputParams();
params.setScope(this.scope.toString());
params.setMap(""); //eventually, set here the new Service Map
pt.addScope(params);
} catch (Exception e) {
logger.error("Failed to add GHN to scope " + scope.toString(), e);
throw new Exception("Failed to add GHN to scope " + scope.toString());
}
}
@Override
public void find() throws Exception {
try {
ISClient client = GHNContext.getImplementation(ISClient.class);
GCUBEGHNQuery query = client.getQuery(GCUBEGHNQuery.class);
query.addAtomicConditions(new AtomicCondition("/ID/text()", this.id));
this.nodename = client.execute(query, ServiceContext.getContext().getScope().getEnclosingScope()).get(0).getNodeDescription().getName();
this.hostedOn = nodename;
} catch (Exception e) {
logger.error("unable to find the target GHN (ID=" + this.id + ")", e);
throw new Exception("unable to find target GHN (ID=" + this.id + ")");
}
}
@Override
protected void removeFromScope() throws Exception {
if (this.nodename.compareToIgnoreCase("") == 0)
this.find();
EndpointReferenceType endpoint = new EndpointReferenceType();
try {
endpoint.setAddress(new Address("http://"+ this.nodename +"/wsrf/services/gcube/common/vremanagement/GHNManager"));
GHNManagerServiceAddressingLocator locator = new GHNManagerServiceAddressingLocator();
GHNManagerPortType pt = GCUBERemotePortTypeContext.getProxy(locator.getGHNManagerPortTypePort(endpoint),
ServiceContext.getContext().getScope().getEnclosingScope(), ServiceContext.getContext());
pt.removeScope(this.scope.toString());
} catch (Exception e) {
logger.error("Failed to remoce GHN from scope " + scope.toString(), e);
throw new Exception("Failed to remove GHN from scope " + scope.toString());
}
}
}

View File

@ -0,0 +1,117 @@
package org.gcube.vremanagement.resourcemanager.impl.resources;
import java.util.List;
import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.resources.GCUBECS;
import org.gcube.common.core.resources.GCUBECSInstance;
import org.gcube.common.core.resources.GCUBECollection;
import org.gcube.common.core.resources.GCUBEExternalRunningInstance;
import org.gcube.common.core.resources.GCUBEGenericResource;
import org.gcube.common.core.resources.GCUBEMCollection;
import org.gcube.common.core.resources.GCUBEResource;
import org.gcube.common.core.resources.GCUBEService;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.impl.scopemanagement.ScopedResourceManagerOperator.ACTION;
import org.gcube.common.core.informationsystem.client.AtomicCondition;
import org.gcube.common.core.informationsystem.client.ISClient;
import org.gcube.common.core.informationsystem.client.ISTemplateQuery;
import org.gcube.common.core.informationsystem.client.queries.GCUBECSInstanceQuery;
import org.gcube.common.core.informationsystem.client.queries.GCUBECSQuery;
import org.gcube.common.core.informationsystem.client.queries.GCUBECollectionQuery;
import org.gcube.common.core.informationsystem.client.queries.GCUBEExternalRIQuery;
import org.gcube.common.core.informationsystem.client.queries.GCUBEGenericResourceQuery;
import org.gcube.common.core.informationsystem.client.queries.GCUBEMCollectionQuery;
import org.gcube.common.core.informationsystem.client.queries.GCUBEServiceQuery;
import org.gcube.common.core.informationsystem.publisher.ISPublisher;
/**
*
* Models a generic scoped {@link GCUBEResource}
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class ScopedGenericResource extends ScopedResource {
GCUBEResource profile = null;
@SuppressWarnings("unchecked")
Class profileClass = null;
public ScopedGenericResource(String id, String type, GCUBEScope scope) {
super(id, type, scope);
}
/**
* Gets the profile of the Scoped Resource
*/
@SuppressWarnings({ "unchecked"})
@Override
public void find() throws Exception {
ISClient client = GHNContext.getImplementation(ISClient.class);
Class query = null;
try {
if (this.type.compareToIgnoreCase(GCUBECollection.TYPE) == 0) {query = GCUBECollectionQuery.class; profileClass = GCUBECollection.class;}
else if (this.type.compareToIgnoreCase(GCUBEMCollection.TYPE) == 0) {query = GCUBEMCollectionQuery.class; profileClass = GCUBEMCollection.class;}
else if (this.type.compareToIgnoreCase(GCUBEGenericResource.TYPE) == 0) {query = GCUBEGenericResourceQuery.class; profileClass = GCUBEGenericResource.class;}
else if (this.type.compareToIgnoreCase(GCUBEExternalRunningInstance.TYPE) == 0) {query = GCUBEExternalRIQuery.class; profileClass = GCUBEExternalRunningInstance.class;}
else if (this.type.compareToIgnoreCase(GCUBECS.TYPE) == 0) {query = GCUBECSQuery.class; profileClass = GCUBECS.class;}
else if (this.type.compareToIgnoreCase(GCUBECSInstance.TYPE) == 0) {query = GCUBECSInstanceQuery.class; profileClass = GCUBECSInstance.class;}
else if (this.type.compareToIgnoreCase(GCUBEService.TYPE) == 0) {query = GCUBEServiceQuery.class; profileClass = GCUBEService.class;}
else throw new Exception("Unknown resource type: " + this.type);
ISTemplateQuery realquery = (ISTemplateQuery) client.getQuery(query);
realquery.addAtomicConditions(new AtomicCondition("//ID",this.id));
List <GCUBEResource> profiles = client.execute(realquery, this.scope);
if ((profiles != null) && (profiles.size() > 0))
this.profile = profiles.get(0);
else
// obviously, in the case of adding, the resource is not in the current scope, therefore we look upstairs (the enclosing scope)
this.profile = (GCUBEResource) client.execute(realquery, this.scope.getEnclosingScope()).get(0);
} catch (Exception e) {
logger.error("unable to find the target resource (ID=" + id + ")", e);
throw new Exception("unable to find target resource (ID=" + id + "). Possible cause: " + e.getMessage());
}
}
@Override
protected void addToScope() throws Exception {
this.status = STATUS.ADDREQUESTED;
if (profile == null)
this.find();
profile.addScope(this.getScope());
//republish the resource
ISPublisher publisher = GHNContext.getImplementation(ISPublisher.class);
publisher.updateGCUBEResource(this.profile, ServiceContext.getContext().getScope(), ServiceContext.getContext());
//republish also in the infrastructure scope, if needed
if (ServiceContext.getContext().getScope().getType() == GCUBEScope.Type.VO) {
if (this.profile.getScopes().values().contains(ServiceContext.getContext().getScope().getEnclosingScope())) {
publisher.updateGCUBEResource(this.profile, ServiceContext.getContext().getScope().getEnclosingScope(), ServiceContext.getContext());
}
}
}
@Override
protected void removeFromScope() throws Exception {
this.status = STATUS.REMOVEREQUESTED;
if (profile == null)
this.find();
profile.removeScope(this.getScope());
//republish the resource
ISPublisher publisher = GHNContext.getImplementation(ISPublisher.class);
publisher.updateGCUBEResource(this.profile, ServiceContext.getContext().getScope(), ServiceContext.getContext());
//republish also in the infrastructure scope, if needed
if (ServiceContext.getContext().getScope().getType() == GCUBEScope.Type.VO) {
if (this.profile.getScopes().values().contains(ServiceContext.getContext().getScope().getEnclosingScope())) {
publisher.updateGCUBEResource(this.profile, ServiceContext.getContext().getScope().getEnclosingScope(), ServiceContext.getContext());
}
}
}
}

View File

@ -0,0 +1,233 @@
package org.gcube.vremanagement.resourcemanager.impl.resources;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.gcube.common.core.resources.GCUBEResource;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.vremanagement.resourcemanager.impl.scopemanagement.ScopedResourceManagerOperator.ACTION;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* An abstract model for a scoped {@link GCUBEResource}
*
* @author Manuele Simi (ISTI-CNR)
*
*/
@XStreamAlias("ScopedResource")
public abstract class ScopedResource {
/** Object logger */
protected final GCUBELog logger=new GCUBELog(this);
/** the resource identifier*/
@XStreamAlias("ResourceID")
protected String id;
/** the resource type */
@XStreamAlias("ResourceType")
protected String type;
/** where the resource is hosted on, it makes sense for RI, GHN*/
@XStreamAlias("HostedOn")
protected String hostedOn;
/** result of the last operation performed on the resource */
@XStreamAlias("LastOperationResult")
protected boolean success;
/** the error message, if any, from the last operation */
@XStreamAlias("LastOperationMessage")
protected String errorMessage = "";
@XStreamAlias("Scope")
protected GCUBEScope scope;
/** the last action performed on the resource*/
protected ACTION action;
/** Last modification time stamp*/
@XStreamAlias("LastModificationTime")
protected Date lastModificationTime;
@XStreamAlias("LastStatus")
protected STATUS status;
public static enum STATUS {
CREATED() {public List<STATUS> previous() {return Collections.emptyList();}},
ADDREQUESTED() {public List<STATUS> previous() {return Collections.unmodifiableList(Arrays.asList(CREATED));}},
ADDED() {public List<STATUS> previous() {return Collections.unmodifiableList(Arrays.asList(ADDREQUESTED));}},
PUBLISHED() {public List<STATUS> previous() {return Collections.unmodifiableList(Arrays.asList(ADDED));}},
REMOVEREQUESTED() {public List<STATUS> previous() {return Collections.unmodifiableList(Arrays.asList(ADDED, PUBLISHED));}},
REMOVED() {public List<STATUS> previous() {return Collections.unmodifiableList(Arrays.asList(REMOVEREQUESTED));}},
UNPUBLISHED () {public List<STATUS> previous() {return Collections.unmodifiableList(Arrays.asList(REMOVED));}},
LOST () {public List<STATUS> previous() {return Collections.unmodifiableList(Arrays.asList(REMOVED,REMOVEREQUESTED,ADDED,PUBLISHED,CREATED,UNPUBLISHED));}};
abstract public List<STATUS> previous();
}
public ScopedResource(String id, String type, GCUBEScope scope) {
this.id = id;
this.type = type;
this.scope = scope;
this.status = STATUS.CREATED;
this.setChanged();
}
/**
* Finds the resource in the infrastructure
*
* @throws Exception if it is impossible to locate the resource
*/
public abstract void find() throws Exception;;
public synchronized void doAction(ACTION action) throws Exception {
this.action = action;
switch (action) {
case ADD: this.addToScope(); this.success= true; break;
case REMOVE: this.removeFromScope(); this.success= true; break;
default: break;
}
this.setChanged();
}
/**
* Adds the resource to the scope
* @throws Exception if the operation fails
*/
protected abstract void addToScope() throws Exception;
/**
* Removes the resource from the scope
* @throws Exception if the operation fails
*/
protected abstract void removeFromScope() throws Exception;
/**
* @return the resource ID
*/
public String getId() {
return id;
}
/**
* @return the resource type
*/
public String getType() {
return type;
}
/**
* @return the scope
*/
public GCUBEScope getScope() {
return scope;
}
/**
* @return the action
*/
public ACTION getAction() {
return action;
}
/**
* @return the errorMessage
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* @param errorMessage the errorMessage to set
*/
public void setErrorMessage(String errorMessage) {
this.success = false;
this.errorMessage = errorMessage;
this.setChanged();
}
private void setChanged() {
this.setLastModificationTime(Calendar.getInstance().getTime());
}
/**
* @return the success
*/
public boolean isSuccess() {
return success;
}
/**
* @return the hostedOn
*/
public String getHostedOn() {
return hostedOn;
}
public Date getLastModificationTime() {
return lastModificationTime;
}
private void setLastModificationTime(Date lastModificationTime) {
this.lastModificationTime = lastModificationTime;
}
/**
* @return the status
*/
public STATUS getStatus() {
return status;
}
/**
* @param status the status to set
*/
public synchronized void setStatus(STATUS status) {
this.status = status;
this.setChanged();
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ScopedResource other = (ScopedResource) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}

View File

@ -0,0 +1,27 @@
package org.gcube.vremanagement.resourcemanager.impl.resources;
import org.gcube.common.core.resources.GCUBEHostingNode;
import org.gcube.common.core.resources.GCUBERunningInstance;
import org.gcube.common.core.resources.GCUBEService;
import org.gcube.common.core.scope.GCUBEScope;
public class ScopedResourceFactory {
public static ScopedResource newResource(String id, String type, GCUBEScope scope) {
ScopedResource sresource = null;
//FIXME: should I get the resource from the list, if any?
if (type.compareToIgnoreCase(GCUBEHostingNode.TYPE) == 0)
sresource = new ScopedGHN(id, scope);
else if (type.compareToIgnoreCase(GCUBERunningInstance.TYPE) == 0)
sresource = new ScopedRunningInstance(id, scope);
else if (type.compareToIgnoreCase(GCUBEService.TYPE) == 0)
sresource = new ScopedDeployedService(id, scope);
else
sresource = new ScopedGenericResource(id, type, scope);
return sresource;
}
}

View File

@ -0,0 +1,146 @@
package org.gcube.vremanagement.resourcemanager.impl.resources;
import java.util.List;
import org.apache.axis.message.addressing.Address;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.gcube.common.core.contexts.GCUBERemotePortTypeContext;
import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.informationsystem.client.AtomicCondition;
import org.gcube.common.core.informationsystem.client.ISClient;
import org.gcube.common.core.informationsystem.client.queries.GCUBEGHNQuery;
import org.gcube.common.core.informationsystem.client.queries.GCUBERIQuery;
import org.gcube.common.core.resources.GCUBERunningInstance;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.vremanagement.ghnmanager.stubs.GHNManagerPortType;
import org.gcube.common.vremanagement.ghnmanager.stubs.ScopeRIParams;
import org.gcube.common.vremanagement.ghnmanager.stubs.service.GHNManagerServiceAddressingLocator;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
/**
* Models a scoped {@link GCUBERunningInstance}
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class ScopedRunningInstance extends ScopedResource {
public static final String TYPE = GCUBERunningInstance.TYPE;
private String hostingNode = "";
GCUBERunningInstance ri;
public ScopedRunningInstance(String id, GCUBEScope scope, String ... hostedOn) {
super(id, TYPE, scope);
if ((hostedOn != null) && (hostedOn.length > 0))
this.hostedOn = hostedOn[0];
}
@Override
public void find() throws Exception {
//looks for the RI to manage
try {
ISClient client = GHNContext.getImplementation(ISClient.class);
GCUBERIQuery query = client.getQuery(GCUBERIQuery.class);
query.addAtomicConditions(new AtomicCondition("/ID/text()", id));
List<GCUBERunningInstance> ris = client.execute(query, ServiceContext.getContext().getScope());
if (ris == null || ris.size() == 0) {
ris = client.execute(query, ServiceContext.getContext().getScope().getEnclosingScope());
if (ris == null || ris.size() == 0)
throw new Exception("unable to find target RI (ID=" + id + ") on the IS");
}
this.ri = ris.get(0);
} catch (Exception e) {
logger.error("unable to find the target RI (ID=" + id + ")", e);
throw new Exception("unable to find target RI (ID=" + id + ")");
}
//looks for the GHN to contact
try {
ISClient client = GHNContext.getImplementation(ISClient.class);
GCUBEGHNQuery query = client.getQuery(GCUBEGHNQuery.class);
query.addAtomicConditions(new AtomicCondition("/ID/text()", ri.getGHNID()));
this.hostingNode = client.execute(query, ServiceContext.getContext().getScope()).get(0).getNodeDescription().getName();
this.hostedOn = hostingNode;
} catch (Exception e) {
logger.error("unable to find the target GHN (ID=" + ri.getGHNID() + ")", e);
throw new Exception("unable to find target GHN (ID=" + ri.getGHNID() + ")");
}
}
/**
* Adds the RI to the scope
*
* @throws Exception if it is not possible to add the resource
*/
@Override
protected void addToScope() throws Exception {
if (this.hostingNode.compareToIgnoreCase("") == 0)
this.find();
EndpointReferenceType endpoint = new EndpointReferenceType();
try {
endpoint.setAddress(new Address("http://"+ this.hostingNode +"/wsrf/services/gcube/common/vremanagement/GHNManager"));
GHNManagerServiceAddressingLocator locator = new GHNManagerServiceAddressingLocator();
GHNManagerPortType pt = GCUBERemotePortTypeContext.getProxy(locator.getGHNManagerPortTypePort(endpoint),
ServiceContext.getContext().getScope(), ServiceContext.getContext());
ScopeRIParams params = new ScopeRIParams();
params.setClazz(this.ri.getServiceClass());
params.setName(this.ri.getServiceName());
params.setScope(this.scope.toString());
pt.addRIToScope(params);
} catch (Exception e) {
logger.error("Failed to add RunningInstance to scope " + scope.toString(), e);
throw new Exception("Failed to add RunningInstance to scope " + scope.toString());
}
}
/**
* Removes the RI from the scope
*
* @throws Exception if it is not possible to remove the resource
*/
@Override
protected void removeFromScope() throws Exception {
if (this.hostingNode.compareToIgnoreCase("") == 0)
this.find();
if (this.ri.getScopes().values().size() == 1) {
this.undeploy();
return;
}
EndpointReferenceType endpoint = new EndpointReferenceType();
try {
endpoint.setAddress(new Address("http://"+ this.hostingNode +"/wsrf/services/gcube/common/vremanagement/GHNManager"));
GHNManagerServiceAddressingLocator locator = new GHNManagerServiceAddressingLocator();
GHNManagerPortType pt = GCUBERemotePortTypeContext.getProxy(locator.getGHNManagerPortTypePort(endpoint),
ServiceContext.getContext().getScope(), ServiceContext.getContext());
ScopeRIParams params = new ScopeRIParams();
params.setClazz(this.ri.getServiceClass());
params.setName(this.ri.getServiceName());
params.setScope(this.scope.toString());
pt.removeRIFromScope(params);
} catch (Exception e) {
logger.error("Failed to remove RunningInstance from scope " + scope.toString(), e);
throw new Exception("Failed to remove RunningInstance from scope " + scope.toString());
}
}
/**
* Undeploys the RI
*
* @throws Exception if an error occurs during the undeployment
*/
private void undeploy() throws Exception {
//list the packages belonging the RI... from where??
//TODO
//contact the target Deployer to remove them
}
}

View File

@ -0,0 +1,249 @@
package org.gcube.vremanagement.resourcemanager.impl.resources.types;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* A thread-safe Map with multiple keys allowing multiple values per key
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class MultiKeysMap<K1, K2, V> implements Iterable<V> {
private List<V> values = Collections.synchronizedList(new LinkedList<V>());
private List<WrappedValue> wrappedValues = Collections.synchronizedList(new LinkedList<WrappedValue>());
private Map<K1, HashSet<V>> k1values = Collections.synchronizedMap(new HashMap<K1, HashSet<V>>());
private Map<K2, HashSet<V>> k2values = Collections.synchronizedMap(new HashMap<K2, HashSet<V>>());
/**
* {@inheritDoc}
*/
public Iterator<V> iterator() {
return values.iterator();
}
/**
* Associates the specified value with the two keys
*
* @param key1 the value's primary key
* @param key2 the value's secondary key
* @param value the value
*/
public void put(K1 key1, K2 key2, V value) {
WrappedValue wrappedValue = this.new WrappedValue(value);
wrappedValue.addKey1(key1);
wrappedValue.addKey2(key2);
wrappedValues.add(wrappedValue);
values.add(value);
//add the value index to k1values
if (!k1values.containsKey(key1))
k1values.put(key1, new HashSet<V>());
k1values.get(key1).add(value);
//add the value index to k2values
if (!k2values.containsKey(key2))
k2values.put(key2, new HashSet<V>());
k2values.get(key2).add(value);
}
/**
* removes the given values and its keys from the map
* @param value
*/
public void removeValue(V value) {
values.remove(value);
WrappedValue wvalue = wrappedValues.get(this.wrappedIndexOf(value));
k1values.get(wvalue.key1).remove(value);
if (k1values.get(wvalue.key1).isEmpty())
k1values.remove(wvalue.key1);
k2values.get(wvalue.key2).remove(value);
if (k2values.get(wvalue.key2).isEmpty())
k2values.remove(wvalue.key2);
wrappedValues.remove(wvalue);
}
/**
* Removes all the values associated to the primary key
*
* @param key the key of type K1
*/
public void removeValuesByPrimaryKey(K1 key) {
Set<V> valuesToRemove = k1values.get(key);
if (valuesToRemove == null)
return;
Iterator<V> iterator = valuesToRemove.iterator();
while (iterator.hasNext()) {
V value = iterator.next();
values.remove(value);
if (value == null) {
return;
}
WrappedValue wvalue = wrappedValues.get(this.wrappedIndexOf(value));
k2values.get(wvalue.key2).remove(value);
if (k2values.get(wvalue.key2).isEmpty())
k2values.remove(wvalue.key2);
wrappedValues.remove(wvalue);
}
k1values.remove(key);
}
/**
* Removes all the values associated to the secondary key
*
* @param key the key of type K2
*/
public void removeValuesBySecondaryKey(K2 key) {
Set<V> valuesToRemove = k2values.get(key);
if (valuesToRemove == null)
return;
Iterator<V> iterator = valuesToRemove.iterator();
while (iterator.hasNext()) {
V value = iterator.next();
values.remove(value);
if (value == null) {
return;
}
WrappedValue wvalue = wrappedValues.get(this.wrappedIndexOf(value));
k1values.get(wvalue.key1).remove(value);
if (k1values.get(wvalue.key1).isEmpty())
k1values.remove(wvalue.key1);
wrappedValues.remove(wvalue);
}
k2values.remove(key);
}
private int wrappedIndexOf(V value) {
int index = 0;
if (value==null)
return -1;
for (WrappedValue wvalue : wrappedValues) {
if (wvalue.equals(value))
return index;
index++;
}
return -1;
}
/**
* Returns the values to which this map maps the specified primary key
*
* @param key key whose associated values are to be returned
* @return the values to which this map maps the specified primary key, or
* <tt>null</tt> if the map contains no mapping for this key
*/
public Set<V> getValuesByPrimaryKey(K1 key) {
return k1values.get(key);
}
/**
* Returns the values to which this map maps the specified primary key
* @param key key whose associated values are to be returned
* @return @return the values to which this map maps the specified secondary key, or
* <tt>null</tt> if the map contains no mapping for this key
*/
public Set<V> getValuesBySecondaryKey(K2 key) {
return k2values.get(key);
}
/**
* Returns a set view of the primary keys contained in this map
*
* @return a set view of the primary keys contained in this map
*/
public Set<K1> primaryKeySet() {
return k1values.keySet();
}
/**
* Returns a set view of the secondary keys contained in this map
*
* @return a set view of the secondary keys contained in this map
*/
public Set<K2> secondaryKeySet() {
return k2values.keySet();
}
/**
* Returns a collection view of the values contained in this map
*
* @return a collection view of the values contained in this map
*/
public Collection<V> values() {
return Collections.unmodifiableCollection(values);
}
/**
* Removes all mapping from this maps
*/
public void clean () {
values.clear();
wrappedValues.clear();
k1values.clear();
k2values.clear();
}
/**
*
* Internal Map objects, maps a value V to both its primary and secondary key
*
* @author Manuele Simi (ISTI-CNR)
*
*/
class WrappedValue {
V value;
K1 key1;
K2 key2;
WrappedValue(V value) { this.value = value;}
void addKey1(K1 key) {this.key1=key;}
void addKey2(K2 key) {this.key2=key;}
@Override
public int hashCode() {
return ((value == null) ? 0 : value.hashCode());
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() == obj.getClass()) {
WrappedValue other = (WrappedValue) obj;
if ((value == null) && (other.value == null)) {
return true;
} else if (value.equals(other.value))
return true;
} else { //check if obj is the wrapped object
if (value.equals(obj))
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,104 @@
package org.gcube.vremanagement.resourcemanager.impl.resources.types;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedGHN;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedRunningInstance;
import junit.framework.Assert;
import junit.framework.TestCase;
public class MultiKeysMapTest extends TestCase {
private MultiKeysMap<String, String, ScopedResource> map;
public MultiKeysMapTest(String name) {
super(name);
this.map = new MultiKeysMap<String, String, ScopedResource>();
}
protected void setUp() throws Exception {
System.out.println("Map before the method");
printMap();
}
protected void tearDown() throws Exception {
System.out.println("Map after the method");
printMap();
}
public void testPut() {
ScopedGHN ghn = new ScopedGHN("ID1", GCUBEScope.getScope("/gcube"));
map.put(ghn.getId(), ghn.getType(), ghn);
Assert.assertEquals(1, map.values().size());
ScopedGHN ghn2 = new ScopedGHN("ID2", GCUBEScope.getScope("/gcube"));
map.put(ghn2.getId(), ghn2.getType(), ghn2);
Assert.assertEquals(2, map.values().size());
ScopedRunningInstance ri = new ScopedRunningInstance("RI1", GCUBEScope.getScope("/gcube"), "");
map.put(ri.getId(), ri.getType(), ri);
Assert.assertEquals(3, map.values().size());
}
public void testRemoveValue() {
ScopedGHN ghn = new ScopedGHN("ID1", GCUBEScope.getScope("/gcube"));
map.removeValue(ghn);
}
public void testRemoveValuesByPrimaryKey() {
map.removeValuesByPrimaryKey("ID2");
}
public void testRemoveValuesBySecondaryKey() {
ScopedRunningInstance ri = new ScopedRunningInstance("RI1", GCUBEScope.getScope("/gcube"), "");
map.removeValuesBySecondaryKey(ri.getType());
}
public void testGetValuesByPrimaryKey() {
fail("Not yet implemented");
}
public void testGetValuesBySecondaryKey() {
fail("Not yet implemented");
}
public void testPrimaryKeySet() {
fail("Not yet implemented");
}
public void testSecondaryKeySet() {
fail("Not yet implemented");
}
public void testValues() {
for (ScopedResource resource : map.values()) {
System.out.println("Resource Value ID = " + resource.getId());
}
}
public void testClean() {
map.clean();
}
public void printMap() {
System.out.println("Values by KEY1:");
for (String key1 : map.primaryKeySet()) {
for (ScopedResource resource : map.getValuesByPrimaryKey(key1))
System.out.println( key1 + " ->" +resource.getId());
}
System.out.println("Values by KEY2:");
for (String key2 : map.secondaryKeySet()) {
for (ScopedResource resource : map.getValuesBySecondaryKey(key2))
System.out.println( key2 + " ->" +resource.getId());
}
System.out.println("Values:");
for (ScopedResource resource : map.values()) {
System.out.println(resource.getId());
}
}
}

View File

@ -0,0 +1,66 @@
package org.gcube.vremanagement.resourcemanager.impl.scopemanagement;
import java.util.HashSet;
import java.util.Set;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceItem;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceList;
import org.gcube.vremanagement.resourcemanager.impl.operators.OperatorConfig;
import org.gcube.vremanagement.resourcemanager.impl.operators.Operator;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResourceFactory;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource.STATUS;
/**
* Add and remove list of GCUBEResources to/from a given scope
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class ScopedResourceManagerOperator implements Operator {
protected final GCUBELog logger = new GCUBELog(this, ServiceContext.getContext());
private ResourceList resources;
private ACTION action;
private OperatorConfig configuration;
public enum ACTION {ADD,REMOVE}
public ScopedResourceManagerOperator(OperatorConfig configuration, ResourceList resources, ACTION action) {
this.configuration = configuration;
this.resources = resources;
this.action = action;
}
public void run() throws Exception {
Set<ScopedResource> toadd = new HashSet<ScopedResource>();
Set<ScopedResource> toremove = new HashSet<ScopedResource>();
ScopedResource sresource = null;
for (ResourceItem resource : this.resources.getResource()) {
sresource = ScopedResourceFactory.newResource(resource.getID(), resource.getType(), this.configuration.scope);
if (this.action == ACTION.ADD) {
logger.info("Adding resource " + sresource.getId() + " (" + sresource.getType() + ")");
toadd.add(sresource);
} else if (this.action == ACTION.REMOVE) {
logger.info("Removing resource " + sresource.getId() + " (" + sresource.getType() + ")");
toremove.add(sresource);
}
//add the resource item to the report
this.configuration.report.addResource(sresource);
}
if(toadd.size() > 0)
configuration.resourceList.addResources(toadd);
if(toremove.size() > 0)
configuration.resourceList.removeResources(toremove);
this.configuration.report.save();
}
}

View File

@ -0,0 +1,147 @@
package org.gcube.vremanagement.resourcemanager.impl.state;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.state.GCUBEWSResource;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource;
import org.gcube.vremanagement.resourcemanager.impl.state.observers.Executor;
import org.gcube.vremanagement.resourcemanager.impl.state.observers.Publisher;
import org.gcube.vremanagement.resourcemanager.impl.state.observers.Serializer;
import org.globus.wsrf.NoSuchResourceException;
/**
* The ResourceManager's stateful resource
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class InstanceState extends GCUBEWSResource {
protected static final String ManagedScopeRP="ManagedScope";
final static String[] RPNames = {ManagedScopeRP};
final protected GCUBEScope scope = ServiceContext.getContext().getInstance().getScopes().values().iterator().next();
protected ResourceList resourceList;
/** report id -> report map*/
static Map<String, ResourceReport> id2report = Collections.synchronizedMap(new HashMap<String, ResourceReport>());;
@Override
protected void initialise(Object... params) throws Exception {
this.setManagedScope(scope.toString());
try {
logger.info("Loading the instance state from the local file system...");
resourceList = Serializer.load(scope);
//synch IS list w/ resourceList
this.getPublishedScopeResource().loadFromLocalState(resourceList); //it's already done by the Publisher observer?
} catch (IOException io) {
logger.warn("The local serialized list of scoped resources is not available");
resourceList = new ResourceList(scope, scope.getName());
logger.info("Loading the instance state from the IS...");
if (this.getPublishedScopeResource().loaded()) {
logger.info("List of scoped resources harvested from the IS");
//synch resourceList w/ IS list
this.getPublishedScopeResource().to(resourceList);
} else
logger.info("Empty list of scoped resources created");
this.getPublishedScopeResource().loadFromLocalState(resourceList);
}
//register the observers
resourceList.addObserver(new Executor());
resourceList.addObserver(new Publisher());
resourceList.addObserver(new Serializer());
//let's notify the observers about the current list
resourceList.notifyObservers();
}
@Override
protected String[] getPropertyNames() {
return RPNames;
}
/**
* Gets the RP <em>ManagedScope</em>
*
* @return the scope managed by this instance
*/
synchronized public int getManagedScope () {
return (Integer) this.getResourcePropertySet().get(ManagedScopeRP).get(0);
}
/**
* Sets for the RP <em>ManagedScope</em>
* @param scope the scope managed by this instace
*
*/
synchronized public void setManagedScope (String scope) {
this.getResourcePropertySet().get(ManagedScopeRP).clear();
this.getResourcePropertySet().get(ManagedScopeRP).add(scope);
}
/**
* Gets the {@link ResourceReport}
*
* @param id the report ID
* @return the report
* @throws IOException
*/
public ResourceReport getReport(String id) throws IOException {
if (! id2report.containsKey(id))
id2report.put(id, ResourceReport.load(id));
return id2report.get(id);
}
/**
* Gets the string representation of a {@link ResourceReport}
*
* @param id the report ID
* @return the string representation of the report
* @throws IOException
*/
public String getReportAsString(String id) throws IOException {
return ResourceReport.loadAsString(id);
}
/**
* Adds a new {@link ResourceReport} to the service's state
*
* @param report the report to add
*/
public void addReport(ResourceReport report) {
id2report.put(report.getId(), report);
}
/**
* Gets the {@link PublishedScopeResource}
*
* @return the {@link PublishedScopeResource}
* @throws NoSuchResourceException
*/
public PublishedScopeResource getPublishedScopeResource() throws NoSuchResourceException {
try {
return PublishedScopeResource.getResource(this.scope);
} catch (Exception e) {
logger.warn("Unable to get the PublishedScopeResource", e);
throw new NoSuchResourceException();
}
}
/**
* Gets the list of {@link ScopedResource}s
* @return the list of scoped resources
*/
public ResourceList getResourceList() {
return resourceList;
}
}

View File

@ -0,0 +1,56 @@
package org.gcube.vremanagement.resourcemanager.impl.state;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
/**
* Transforms from {@link Date} to a valid string representation for the <em>xs:dateAndTime</em> XML Schema data type and vice versa.
* It can be used to write/read a {@link Date} object to/from a profile.
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public final class ProfileDate {
static final DateFormat dateAndTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
/**
* Transforms the input {@link Date} in a valid string representation for the <em>xs:dateAndTime</em> XML Schema data type
* @param date the {@link Date} object to tranform
* @return the {@link String} object
*/
public static synchronized String toXMLDateAndTime(Date date) {
String formatted = dateAndTime.format(date);
StringBuilder toXS = new StringBuilder();
toXS.append(formatted.substring(0, formatted.length()-2));
toXS.append(":");
toXS.append(formatted.substring(formatted.length()-2, formatted.length()));
return toXS.toString();
}
/**
* Transforms the input <em>xs:dateAndTime</em> representation in a {@link Date} object
* @param date the string representation of <em>xs:dateAndTime</em> (e.g. &quot 2009-05-12T16:46:03+02:00 &quot)
* @return the {@link Date} object
* @throws ParseException if the input date is not in an valid format
*/
public static synchronized Date fromXMLDateAndTime(String date) throws ParseException {
//the test is for backward compatibility, to read the old profiles that have no time zone in the dateAndTime fields
Pattern p = Pattern.compile("^.*T\\d{2}:\\d{2}:\\d{2}$"); //ends with 'T'HH:mm:ss
if (p.matcher(date).matches()) {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(date);
} else {
StringBuilder toDate = new StringBuilder();
toDate.append(date.substring(0, date.length()-3));
toDate.append(date.substring(date.length()-2, date.length()));
return dateAndTime.parse(toDate.toString());
}
}
}

View File

@ -0,0 +1,664 @@
package org.gcube.vremanagement.resourcemanager.impl.state;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedGHN;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedGenericResource;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedRunningInstance;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource.STATUS;
import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.informationsystem.client.AtomicCondition;
import org.gcube.common.core.informationsystem.client.ISClient;
import org.gcube.common.core.informationsystem.client.queries.GCUBEGenericResourceQuery;
import org.gcube.common.core.informationsystem.publisher.ISPublisher;
import org.gcube.common.core.resources.GCUBEGenericResource;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.scope.GCUBEScope.Type;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.kxml2.io.KXmlParser;
import org.kxml2.io.KXmlSerializer;
/**
* The scope resource published in the IS
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class PublishedScopeResource {
protected GCUBELog logger = new GCUBELog(this);
private GCUBEGenericResource resource;
private PublishedResourceList publishedResourceList;
private GCUBEScope scope;
private static final String NS ="";
private String creator = "", designer = "", service = "";
private Date startTime = null, endTime = null;
private boolean securityEnabled = false;
private boolean loaded = false;
private static Map<GCUBEScope,PublishedScopeResource> cache = new HashMap<GCUBEScope, PublishedScopeResource>();;
public void reload() throws Exception {
try {
publishedResourceList = new PublishedResourceList();
this.load();
//this.store();//to make sure we have locally the latest resource
} catch (Exception e) {
logger.error("Failed to reload the Scope Resource");
throw e;
}
}
// make it private to avoid explicit creation of VREscope objects
private PublishedScopeResource(GCUBEScope scope) throws Exception{
this.scope = scope;
publishedResourceList = new PublishedResourceList();
this.load();
//this.store();//to make sure we have locally the latest resource
}
/**
* Gets the current Scope Resource
* @param scope the scope of the resource to load
* @return the PublishedScopeResource
*/
public static PublishedScopeResource getResource(GCUBEScope scope) throws Exception {
if (! cache.containsKey(scope))
cache.put(scope, new PublishedScopeResource(scope));
return cache.get(scope);
}
/**
* Adds a resource to PublishedScopeResource
*
* @param resource
* @throws Exception
*/
public void addResource(ScopedResource resource) throws Exception {
this.publishedResourceList.add(resource.getId(), resource.getType(),resource.getLastModificationTime(), resource.getHostedOn());
resource.setStatus(STATUS.PUBLISHED);
}
/**
* Removes a resource from the PublishedScopeResource
*
* @param resource
* @throws Exception
*/
public void removeResource(ScopedResource resource) throws Exception {
this.publishedResourceList.remove(resource.getId(), resource.getType());
resource.setStatus(STATUS.UNPUBLISHED);
}
/**
* Returns a string representation of the PublishedScopeResource
* @throws IOException
*/
public String toString() {
try {
this.resource.setBody(this.prepareBody());
StringWriter ret = new StringWriter();
this.resource.store(ret);
return ret.toString();
} catch (Exception e) { logger.error("Invalid Scope Resource serialization",e); return "";}
}
/**
* @return the scope
*/
public GCUBEScope getScope() {
return scope;
}
/**
* Returns the type of the scope.
*
* @return the type.
*/
public Type getType() {
return scope.getType();
}
/**
* Sets a scope option
*
* @param name
* the option name
* @param value
* the option value
* @throws Exception
* @throws ParseException
*/
public void setOption(String name, String value)
throws Exception {
if (value == null)
return;
try {
if (name.compareToIgnoreCase("DESIGNER") == 0) {
// the designer's DN
this.designer = value;
} else if (name.compareToIgnoreCase("MANAGER") == 0) {
// the creator's DN
this.creator = value;
} else if (name.compareToIgnoreCase("ENDTIME") == 0) {
// the time at which the scope will be dismissed
this.endTime = ProfileDate.fromXMLDateAndTime(value);
} else if (name.compareToIgnoreCase("STARTTIME") == 0) {
// the time this scope was created
this.startTime = ProfileDate.fromXMLDateAndTime(value);
} else if (name.compareToIgnoreCase("DESCRIPTION") == 0) {
// the scope description
this.resource.setDescription(value);
} else if (name.compareToIgnoreCase("DISPLAYNAME") == 0) {
// the name to display (the unique name is the qualified scope)
this.resource.setName(value);
} else if (name.compareToIgnoreCase("SECURITYENABLED") == 0) {
// the name to display (the unique name is the qualified scope)
this.securityEnabled = Boolean.valueOf(value);
} else
throw new UnknownScopeOptionException();
} catch (ParseException e) {
throw new Exception ("Unable to parse option " + name);
}
}
/**
* Publishes the {@link PublishedScopeResource} into the IS
*/
public synchronized void publish() throws Exception {
this.resource.setBody(this.prepareBody());
logger.trace("Publishing Scope Resource: \n" + this.toString());
//this.store();
ISPublisher publisher = GHNContext.getImplementation(ISPublisher.class);
if (this.loaded) {
publisher.updateGCUBEResource(this.resource, this.scope, ServiceContext.getContext());
}
else {
publisher.registerGCUBEResource(this.resource, this.scope, ServiceContext.getContext());
this.loaded = true;
}
}
private String prepareBody() throws IOException {
StringWriter body = new StringWriter(); // serialises to a temporary writer first
KXmlSerializer serializer = new KXmlSerializer();
serializer.setOutput(body);
try {
serializer.startDocument("UTF-8", true);
serializer.startTag(NS,"Scope").text(scope.toString()).endTag(NS,"Scope");
serializer.startTag(NS,"Service").text(this.service).endTag(NS,"Service");
serializer.startTag(NS,"Creator").text(this.getManager()).endTag(NS,"Creator");
serializer.startTag(NS,"Designer").text(this.getDesigner()).endTag(NS,"Designer");
if (this.startTime == null)
this.startTime = Calendar.getInstance().getTime();
serializer.startTag(NS,"StartTime").text(ProfileDate.toXMLDateAndTime(this.startTime)).endTag(NS,"StartTime");
if (this.endTime != null)
serializer.startTag(NS,"EndTime").text(ProfileDate.toXMLDateAndTime(this.endTime)).endTag(NS,"EndTime");
serializer.startTag(NS,"SecurityEnabled").text(String.valueOf(this.securityEnabled)).endTag(NS,"SecurityEnabled");
publishedResourceList.store(serializer);
} catch (Exception e) {
logger.error("The Scope Resource does not have a valid serialisation", e);
throw new IOException("The Scope Resource does not have a valid serialisation");
}
finally {
body.close();
}
return body.toString();
}
/**
* @return the creator
*/
public String getManager() {
return creator;
}
/**
* @return the designer
*/
public String getDesigner() {
return designer;
}
/**
* @return the description
*/
public String getDescription() {
return this.resource.getDescription();
}
/**
* @return the display name
*/
public String getDisplayName() {
return this.resource.getName();
}
/**
* @return the startTime
*/
public Date getStartTime() {
return startTime;
}
/**
* @return the endTime
*/
public Date getEndTime() {
return endTime;
}
/**
* @return the securityEnabled
*/
public boolean isSecurityEnabled() {
return securityEnabled;
}
/**
* loads the PublishedScopeResource resource or creates a new one
*
* @throws Exception
*/
private void load() throws Exception {
//get the service EPR from the RI profile
this.service = ServiceContext.getContext().getInstance().getAccessPoint().getRunningInstanceInterfaces().getEndpoint().get(0).getValue();
// get the resource implementation
try {
this.resource = GHNContext.getImplementation(GCUBEGenericResource.class);
} catch (Exception e) {
throw new Exception("Unable to create Scope Resource for " + scope.toString());
}
// try to load the resource from the IS
if (this.loadFromIS()) return;
// try to load locally the resource
//if (this.loadFromFileSystem()) return;
// create the resource from scratch
/*logger.info("ResourceManager is going to create a new Scope Resource from scratch for " + this.scope.getName());
try {
//initialise some resource's fields
if (this.scope.getType() == Type.VRE) {
this.resource.setSecondaryType(GCUBEGenericResource.SECONDARYTYPE_VRE);
this.resource.setName("");
this.resource.setDescription("");
}
else if (this.scope.getType() == Type.VO) {
this.resource.setSecondaryType("VO");
this.resource.setName("VOResource");
this.resource.setDescription(this.scope.getName() + " VO");
}
else {
this.resource.setSecondaryType("INFRASTRUCTURE");
this.resource.setName("InfrastructureResource");
this.resource.setDescription(this.scope.getName() + " Infrastructure");
}
this.resource.addScope(this.scope);
this.toString(); // force first serialization of Body
} catch (Exception e) {
logger.error("Unable to create a new Scope Resource from scratch", e);
throw new Exception("Unable to to create a new Scope Resource from scratch");
}
*/
}
/**
* Loads from the <em>Body</em> element the resource information
* @param body the <em>Body</em> of the generic resource
* @throws Exception if the element is not valid or well formed
*/
private void parseBody(String body) throws Exception {
KXmlParser parser = new KXmlParser();
parser.setInput(new BufferedReader(new StringReader(body)));
loop: while (true) {
try {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("Creator")) this.creator = parser.nextText();
else if (parser.getName().equals("Designer")) this.designer = parser.nextText();
else if (parser.getName().equals("EndTime")) this.endTime = ProfileDate.fromXMLDateAndTime(parser.nextText());
else if (parser.getName().equals("StartTime")) this.startTime = ProfileDate.fromXMLDateAndTime(parser.nextText());
//else if (parser.getName().equals("DisplayName")) this.display = parser.nextText();
else if (parser.getName().equals("SecurityEnabled")) this.securityEnabled = Boolean.valueOf(parser.nextText());
else if (parser.getName().equals(PublishedResourceList.RESOURCES_ELEMENT)) publishedResourceList.load(parser);
else parser.nextText();//just skip the text
break;
case KXmlParser.END_DOCUMENT: break loop;
}
} catch (Exception e) {
throw new Exception ("Unable to parse the PublishedScopeResource body");
}
}
}
/**
* Loads the scope resource from the local file system
* @param resource the resource to load
*
* @return true if the resource is found and loaded, false otherwise
*/
/*private boolean loadFromFileSystem() {
// try to load locally the resource
try {
this.resource.load(new FileReader(serializedResource));
this.parseBody(this.resource.getBody());
this.loaded = true;
logger.debug("Scope Resource loaded from the file system");
return true;
} catch (Exception e) {logger.warn("Unable to locally load the PublishedScopeResource"); }
return false;
}*/
/**
* Loads the scope resource from the IS
* @param resource the resource to load
*
* @return true if the resource is found and loaded, false otherwise
*/
private boolean loadFromIS() {
try {
ISClient client = GHNContext.getImplementation(ISClient.class);
GCUBEGenericResourceQuery query = client.getQuery(GCUBEGenericResourceQuery.class);
query.addAtomicConditions(new AtomicCondition("//SecondaryType", determineSecondaryType()),
new AtomicCondition("//Body/Scope", scope.toString()));
logger.trace(query.toString());
List<GCUBEGenericResource> results = client.execute(query, scope);
if ((results != null) && (results.size() > 0)) {
this.resource = results.get(0);
this.parseBody(this.resource.getBody());
this.loaded = true;
return true;
} else
logger.warn("Unable to load the PublishedScopeResource for "+ this.scope.toString() + " from the IS");
} catch (Exception e) {logger.warn("PublishedScopeResource for "+ this.scope.toString()+ " does not exist on the IS yet", e);}
return false;
}
/*private void store() throws Exception{
this.resource.store(new FileWriter(serializedResource));
}/*
/**
* Determines the secondary type of the scope resource
*
* @return the secondary type
*/
private String determineSecondaryType() {
if (this.scope.getType() == Type.VRE)
return GCUBEGenericResource.SECONDARYTYPE_VRE;
else if (this.scope.getType() == Type.VO)
return GCUBEGenericResource.SECONDARYTYPE_VO;
else
return GCUBEGenericResource.SECONDARYTYPE_INFRASTRUCTURE;
}
public boolean loaded() {
return this.loaded;
}
/**
* Fills the input {@link ResourceList} with the actual content of the {@link PublishedResourceList}
*
* @param resourceList the list to fill
*/
public void to(ResourceList resourceList) {
resourceList.addResources(publishedResourceList.asScopedResouces());
resourceList.setDesigner(this.getDesigner());
resourceList.setManager(this.getManager());
resourceList.securityEnabled = this.isSecurityEnabled();
resourceList.changeDescription(this.getDescription());
resourceList.setEndTime(this.endTime);
resourceList.setStartTime(this.startTime);
resourceList.setName(this.getDisplayName());
}
/**
* Fills this {@link PublishedResourceList} with the content of the input {@link ResourceList}
*
* @param resourceList the list to load
* @throws Exception if the load fails
*/
public synchronized void loadFromLocalState(ResourceList resourceList) throws Exception {
publishedResourceList = new PublishedResourceList();//empty the resourceList
this.synchBasicInfo(resourceList);
for(ScopedResource resource : resourceList.getAllResources())
this.addResource(resource);
//initialise some resource's fields
if (this.scope.getType() == Type.VRE)
this.resource.setSecondaryType(GCUBEGenericResource.SECONDARYTYPE_VRE);
else if (this.scope.getType() == Type.VO)
this.resource.setSecondaryType("VO");
else
this.resource.setSecondaryType("INFRASTRUCTURE");
this.resource.addScope(this.scope);
// force the first serialization of Body
this.toString();
}
/**
* Synchronizes this {@link PublishedResourceList} with the content of the input {@link ResourceList}
*
* @param resourceList the list to synchronize with
* @throws Exception if the synchronization fails
*/
public synchronized void synchWithLocalState(ResourceList resourceList) throws Exception {
for(ScopedResource resource : resourceList.getAllResources()) {
switch (resource.getStatus()) {
case ADDED: this.addResource(resource); break;
case REMOVED: this.removeResource(resource); break;
//in the other statuses, the resource is just ignored
}
}
this.synchBasicInfo(resourceList);
}
private void synchBasicInfo(ResourceList resourceList) throws Exception {
this.setOption("MANAGER",resourceList.getManager());
this.setOption("DESIGNER",resourceList.getDesigner());
this.setOption("DESCRIPTION",resourceList.getDescription());
this.setOption("DISPLAYNAME",resourceList.getName());
//here we directly assign the values, don't want to format/unformat them via setOption()
this.endTime = resourceList.getEndTime();
this.startTime = resourceList.getStartTime();
this.securityEnabled = resourceList.isSecurityEnabled();
}
/** InvalidVREOption exception */
public static class UnknownScopeOptionException extends Exception {
private static final long serialVersionUID = 1L;
}
/**
* List of resources forming the {@link PublishedScopeResource}
*
* @author Manuele Simi (ISTI-CNR)
*
*/
class PublishedResourceList {
private Set<Item> resources = Collections.synchronizedSet(new HashSet<Item>());
private static final String RESOURCES_ELEMENT = "ScopedRescources";
private static final String RESOURCE_ELEMENT = "ScopedRescource";
class Item {
protected String id;
protected String type;
protected String hostedOn;
protected Date lastModificationTime;
protected Item(String id, String value, Date lastModificationTime, String ... hostedOn) {
this.id = id;
this.type = value;
this.lastModificationTime = lastModificationTime;
this.hostedOn = (hostedOn!=null && hostedOn.length>0) ? hostedOn[0] : null;
}
protected Item(String id, String value, String ... hostedOn) {
this(id, value, null, hostedOn);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((type == null) ? 0 : type.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;
final Item other = (Item) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
void add(String id, String type, Date time, String ... hostedOn) {resources.add(new Item(id, type, time, hostedOn));}
void remove(String id, String type) {resources.remove(new Item(id, type)); }
Set<ScopedResource> asScopedResouces() {
Set<ScopedResource> temp = new HashSet<ScopedResource>();
for (Item item : resources) {
ScopedResource resource;
if (item.type.compareToIgnoreCase(ScopedGHN.TYPE) == 0) {
resource = new ScopedGHN(item.id, scope);
} else if (item.type.compareToIgnoreCase(ScopedRunningInstance.TYPE) == 0) {
resource = new ScopedRunningInstance(item.id, scope, item.hostedOn);
} else {
resource = new ScopedGenericResource(item.id, item.type, scope);
}
temp.add(resource);
}
return temp;
}
int getSize() {return resources.size();}
/**
* Stores the resources in the given serializer
* @param serializer the serializer
* @throws IOException if the storage fails
*/
void store(KXmlSerializer serializer) throws IOException {
serializer.startTag(PublishedScopeResource.NS, RESOURCES_ELEMENT);
for (Item item : resources) {
serializer.startTag(PublishedScopeResource.NS, RESOURCE_ELEMENT);
serializer.startTag(PublishedScopeResource.NS, "ResourceID").text(item.id).endTag(PublishedScopeResource.NS, "ResourceID");
serializer.startTag(PublishedScopeResource.NS, "ResourceType").text(item.type).endTag(PublishedScopeResource.NS, "ResourceType");
if (item.hostedOn != null)
serializer.startTag(PublishedScopeResource.NS, "HostedOn").text(item.hostedOn).endTag(PublishedScopeResource.NS, "HostedOn");
serializer.startTag(PublishedScopeResource.NS, "LastModificationTime").text(ProfileDate.toXMLDateAndTime(item.lastModificationTime)).endTag(PublishedScopeResource.NS, "LastModificationTime");
serializer.endTag(PublishedScopeResource.NS, RESOURCE_ELEMENT);
}
serializer.endTag(PublishedScopeResource.NS, RESOURCES_ELEMENT);
}
/**
* Parses the <em>Resources</em> element
* @param parser the parser
* @throws Exception if the element is not valid or well formed
*/
void load(KXmlParser parser) throws Exception {
loop: while (true) {
try {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals(RESOURCE_ELEMENT)) {
String id=null, type=null, hostedOn=null;
Date time = null;
innerloop: while (true) {
switch (parser.next()) {
case KXmlParser.START_TAG:
if (parser.getName().equals("ResourceID")) id=parser.nextText();
else if (parser.getName().equals("ResourceType")) type=parser.nextText();
else if (parser.getName().equals("HostedOn")) hostedOn=parser.nextText();
else if (parser.getName().equals("LastModificationTime")) time=ProfileDate.fromXMLDateAndTime(parser.nextText());
else parser.nextText();
break;
case KXmlParser.END_TAG: if (parser.getName().equals(RESOURCE_ELEMENT)){this.add(id, type, time, hostedOn);break innerloop;}
break;
case KXmlParser.END_DOCUMENT: throw new Exception ("Parsing failed at " + RESOURCE_ELEMENT);
}
}
}
break;
case KXmlParser.END_TAG: if (parser.getName().equals(RESOURCES_ELEMENT)) break loop;
break;
case KXmlParser.END_DOCUMENT: throw new Exception ("Failed to parse at " + RESOURCES_ELEMENT);
}
} catch (Exception e) {
throw new Exception ("Failed to parse at Resources");
}
}
}
}
}

View File

@ -0,0 +1,260 @@
package org.gcube.vremanagement.resourcemanager.impl.state;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Observable;
import java.util.Set;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource.STATUS;
import org.gcube.vremanagement.resourcemanager.impl.resources.types.MultiKeysMap;
import org.gcube.vremanagement.resourcemanager.impl.scopemanagement.ScopedResourceManagerOperator;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
*
* A list of scoped resources
*
* @author Manuele Simi (ISTI-CNR)
*
*/
@XStreamAlias("ResourceList")
public class ResourceList extends Observable {
/** the scope this list belong to*/
@XStreamAlias("Scope")
protected GCUBEScope scope;
@XStreamAlias("Description")
protected String description = "";
@XStreamAlias("Name")
protected String name;
@XStreamAlias("Designer")
protected String designer;
@XStreamAlias("Manager")
protected String manager;
@XStreamAlias("StartTime")
protected Date startTime = null;
@XStreamAlias("StartTime")
protected Date endTime = null;
@XStreamAlias("Security")
protected boolean securityEnabled = false;
@XStreamAlias("Resources")
protected MultiKeysMap<String, String, ScopedResource> resources;
/** last operation performed on the list*/
@XStreamAlias("LastOperationPerformed")
protected OPERATION lastOperationPerformed;
public enum OPERATION {CREATED, LOADED, TOBEMANAGED, PUBLISHED, SERIALIZED, EXECUTED};
public ResourceList(GCUBEScope scope, String name, String ... description) {
this.resources = new MultiKeysMap<String, String, ScopedResource>();
this.scope = scope;
this.name = name;
this.lastOperationPerformed = OPERATION.CREATED;
if (this.startTime == null)
this.startTime = Calendar.getInstance().getTime();
if ((description != null) && (description.length > 0))
this.description = description[0];
}
/**
* Sets the scope manager identity
* @param manager the manager
*/
public synchronized void setManager(String manager) {
this.manager = manager;
this.notifyObservers();
}
/**
* Sets the scope designer identity
* @param manager the manager
*/
public synchronized void setDesigner(String designer) {
this.designer = designer;
this.notifyObservers();
}
/**
* Changes the scope description
*
* @param description the description
*/
public synchronized void changeDescription (String description) {
this.description = description;
this.notifyObservers();
}
/**
* Adds a new resources to the list
* @param newresources the resources to add
*/
public synchronized void addResources(Set<ScopedResource> newresources) {
for (ScopedResource resource : newresources) {
resource.setStatus(STATUS.ADDREQUESTED);
resources.put(resource.getId(), resource.getType(), resource);
}
this.setLastOperationPerformed(OPERATION.TOBEMANAGED);
this.notifyObservers();
}
/**
* Gets resources of the given type
*
* @param type the type to filter
* @return the collection of resources
*/
public Set<ScopedResource> getResourcesByType(String type) {
return resources.getValuesBySecondaryKey(type);
}
/**
* Removes all the resource of the given type
*
* @param type the type of resources to remove
*/
public synchronized void removeAllResourcesByType(String type) {
for (ScopedResource resource : resources.getValuesBySecondaryKey(type))
resource.setStatus(STATUS.REMOVEREQUESTED);
this.setLastOperationPerformed(OPERATION.TOBEMANAGED);
this.notifyObservers();
resources.removeValuesBySecondaryKey(type);
}
/**
* Removes the resources from the scope
*
* @param id the resources to remove
*
*/
public synchronized void removeResources(Set<ScopedResource> oldresources) {
for (ScopedResource resource : oldresources)
resource.setStatus(STATUS.REMOVEREQUESTED);
this.setLastOperationPerformed(OPERATION.TOBEMANAGED);
this.notifyObservers(); //let the obs do their work before to remove the resources
for (ScopedResource resource : oldresources) {
if (resource.getStatus() == STATUS.UNPUBLISHED)
resources.removeValuesByPrimaryKey(resource.getId());
}
}
/**
* Empty the list of resources
*/
protected synchronized void removeAllResources() {
for (ScopedResource resource : resources.values())
resource.setStatus(STATUS.REMOVEREQUESTED);
this.setLastOperationPerformed(OPERATION.TOBEMANAGED);
this.notifyObservers();
resources.clean();
}
/**
* Gets the resource's scope
*
* @return the scope
*/
public GCUBEScope getScope() {
return this.scope;
}
public void notifyObservers(Object whatschanged) {
// Otherwise it won't propagate changes:
setChanged();
super.notifyObservers(whatschanged);
}
public void notifyObservers() {
// Otherwise it won't propagate changes:
setChanged();
super.notifyObservers();
}
/**
* Gets all the {@link ScopedResource}s
*
* @return all the {@link ScopedResource}s
*/
public Collection<ScopedResource> getAllResources() {
return resources.values();
}
/**
* Gets the scope manager
* @return the scope manger
*/
public String getManager() {
return this.manager;
}
/**
* Gets the scope designer
* @return the scope designer
*/
public String getDesigner() {
return this.designer;
}
public String getDescription() {
return this.description;
}
public String getName() {
return this.name;
}
public Date getEndTime() {
return this.endTime;
}
public Date getStartTime() {
return this.startTime;
}
public boolean isSecurityEnabled() {
return this.securityEnabled;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
this.notifyObservers();
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
this.notifyObservers();
}
public void setName(String name) {
this.name = name;
this.notifyObservers();
}
/**
* @return the the last operation performed on the list
*/
public OPERATION getLastOperationPerformed() {
return lastOperationPerformed;
}
/**
* @param operation the last operation performed on the list
*/
public synchronized void setLastOperationPerformed(OPERATION operation) {
this.lastOperationPerformed = operation;
}
}

View File

@ -0,0 +1,21 @@
package org.gcube.vremanagement.resourcemanager.impl.state;
import org.gcube.common.core.contexts.GCUBEStatefulPortTypeContext;
import org.gcube.common.core.state.GCUBEWSHome;
import org.gcube.vremanagement.resourcemanager.impl.contexts.StatefulPortTypeContext;
/**
*
* Home for stateful resource
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class ResourceManagerHome extends GCUBEWSHome {
@Override
public GCUBEStatefulPortTypeContext getPortTypeContext() {
return StatefulPortTypeContext.getContext();
}
}

View File

@ -0,0 +1,309 @@
package org.gcube.vremanagement.resourcemanager.impl.state;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.impl.deployment.DeployerReport;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.Dependency;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.DeployedDependency;
import org.gcube.vremanagement.resourcemanager.impl.deployment.resources.ResolvedService;
import org.gcube.vremanagement.resourcemanager.impl.scopemanagement.ScopedResourceManagerOperator.ACTION;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource;
import org.kxml2.io.KXmlSerializer;
/**
* Integrated deployment report. It collects the report sent by the Deployer Service and build a single integrated report
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class ResourceReport implements Serializable, Observer {
protected final GCUBELog logger = new GCUBELog(this, ServiceContext.getContext());
final static String NS = "";
/** */
private static final long serialVersionUID = 1180822699138069365L;
private static final String reportDir = "reports";
/** report last update timestamp */
private Calendar lastUpdate = new GregorianCalendar();
private String id = "";
private GCUBEScope scope = null;
/** ghn id -> deployer report map*/
private Map<String, DeployerReport> node2report = Collections.synchronizedMap(new HashMap<String, DeployerReport>());
/** Status of a dependency resolver request */
public enum DEPSTATUS {SUCCESS, FAILED};
private Set<ResolvedService> services = Collections.synchronizedSet(new HashSet<ResolvedService>());
private Set<ScopedResource> resources = Collections.synchronizedSet(new HashSet<ScopedResource>());
/** internally used by {@link ResourceReport#loadAsString(String)}*/
private ResourceReport () {}
/**
* Builds a new empty report
* @param id the session ID assigned to the operation
*/
public ResourceReport(String id, GCUBEScope ... scope) {
this.id = id;
if ((scope == null)|| (scope[0] == null))
this.scope = ServiceContext.getContext().getInstance().getScopes().values().iterator().next();
else
this.scope = scope[0];
}
/**
* Adds a Deployer Report to the Resource Report
* @param report the string representation of the report, as sent by a Deployer service
* @throws Exception if a problem in the report parsing occurs
*/
synchronized public void addGHNReport(DeployerReport report) throws Exception {
node2report.put(report.getGHNID(), report);
this.lastUpdate = new GregorianCalendar();
}
synchronized public void addResource(ScopedResource resource) {
this.resources.add(resource);
this.lastUpdate = new GregorianCalendar();
}
synchronized public void addService(ResolvedService service) {
this.services.add(service);
this.lastUpdate = new GregorianCalendar();
}
/**
*
*/
public String toXML() throws IOException {
StringWriter report = new StringWriter(); // serialises to a temporary writer first
KXmlSerializer serializer = new KXmlSerializer();
serializer.setOutput(report);
//serializer.setProperty(XmlSerializer, "\t");
try {
serializer.startDocument("UTF-8", true);
serializer.startTag(NS,"ResourceReport");
serializer.startTag(NS,"ID").text(this.id).endTag(NS, "ID");
serializer.startTag(NS,"LastUpdate").text(ProfileDate.toXMLDateAndTime(this.lastUpdate.getTime())).endTag(NS,"LastUpdate");
serializer.startTag(NS,"TargetScope").text(this.scope.toString()).endTag(NS,"TargetScope");
//services section
serializer.startTag(NS,"Services");
for (ResolvedService service : this.services) {
serializer.startTag(NS,"Service");
serializer.startTag(NS,"Class").text(service.getClazz()).endTag(NS, "Class");
serializer.startTag(NS,"Name").text(service.getName()).endTag(NS, "Name");
serializer.startTag(NS,"Version").text(service.getVersion()).endTag(NS, "Version");
if ( (service.getMissingDependencies().size() > 0) || (service.getErrorMessage().length() > 0) ) {
serializer.startTag(NS,"DependenciesResolutionStatus").text(DEPSTATUS.FAILED.name()).endTag(NS, "DependenciesResolutionStatus");
serializer.startTag(NS,"DeployedOn").text("not deployed").endTag(NS, "DeployedOn");
serializer.startTag(NS,"ErrorDescription").text(service.getErrorMessage()).endTag(NS, "ErrorDescription");
}else {
serializer.startTag(NS,"DependenciesResolutionStatus").text(DEPSTATUS.SUCCESS.name()).endTag(NS, "DependenciesResolutionStatus");
serializer.startTag(NS,"DeployedOn").text(service.getDeployedOn()).endTag(NS, "DeployedOn");
serializer.startTag(NS,"ErrorDescription").text("-").endTag(NS, "ErrorDescription");
}
serializer.startTag(NS,"DependenciesResolution");
//resolved dependencies
serializer.startTag(NS,"ResolvedDependencies");
for (Dependency dep : service.getResolvedDependencies()) {
serializer.startTag(NS,"Dependency");
serializer.startTag(NS,"ServiceClass").text(dep.getService().getClazz()).endTag(NS, "ServiceClass");
serializer.startTag(NS,"ServiceName").text(dep.getService().getName()).endTag(NS, "ServiceName");
serializer.startTag(NS,"ServiceVersion").text(dep.getService().getVersion()).endTag(NS, "ServiceVersion");
serializer.startTag(NS,"PackageName").text(dep.getName()).endTag(NS, "PackageName");
serializer.startTag(NS,"PackageVersion").text(dep.getVersion()).endTag(NS, "PackageVersion");
serializer.endTag(NS,"Dependency");
}
serializer.endTag(NS,"ResolvedDependencies");
//missing dependencies
serializer.startTag(NS,"MissingDependencies");
for (Dependency dep : service.getMissingDependencies()) {
serializer.startTag(NS,"Dependency");
serializer.startTag(NS,"ServiceClass").text(dep.getService().getClazz()).endTag(NS, "ServiceClass");
serializer.startTag(NS,"ServiceName").text(dep.getService().getName()).endTag(NS, "ServiceName");
serializer.startTag(NS,"ServiceVersion").text(dep.getService().getVersion()).endTag(NS, "ServiceVersion");
serializer.startTag(NS,"PackageName").text(dep.getName()).endTag(NS, "PackageName");
serializer.startTag(NS,"PackageVersion").text(dep.getVersion()).endTag(NS, "PackageVersion");
serializer.endTag(NS,"Dependency");
}
serializer.endTag(NS,"MissingDependencies");
serializer.endTag(NS,"DependenciesResolution");
serializer.endTag(NS,"Service");
}
serializer.endTag(NS,"Services");
serializer.startTag(NS,"DeploymentActivity");
for (String ghnID : node2report.keySet()) {
serializer.startTag(NS,"GHN");
serializer.startTag(NS,"ID").text(ghnID).endTag(NS, "ID");
serializer.startTag(NS,"Host").text(node2report.get(ghnID).getHost()).endTag(NS,"Host");
serializer.startTag(NS,"LastReportReceivedOn").text(ProfileDate.toXMLDateAndTime(node2report.get(ghnID).getLastUpdate())).endTag(NS,"LastReportReceivedOn");
serializer.startTag(NS,"LastReportReceived");
serializer.startTag(NS,"Status").text(node2report.get(ghnID).getStatus()).endTag(NS, "Status");
this.addGHNReport(serializer, node2report.get(ghnID));
serializer.endTag(NS, "LastReportReceived");
serializer.endTag(NS,"GHN");
}
serializer.endTag(NS,"DeploymentActivity");
//resources section
serializer.startTag(NS,"Resources");
for (ScopedResource resource : resources) {
serializer.startTag(NS,"Resource");
serializer.startTag(NS,"ID").text(resource.getId()).endTag(NS,"ID");
serializer.startTag(NS,"Type").text(resource.getType()).endTag(NS,"Type");
if (resource.isSuccess()) {
if (resource.getAction().compareTo(ACTION.ADD) == 0)
serializer.startTag(NS,"Status").text("ADDED").endTag(NS,"Status");
else if (resource.getAction().compareTo(ACTION.REMOVE) == 0)
serializer.startTag(NS,"Status").text("REMOVED").endTag(NS,"Status");
serializer.startTag(NS,"ErrorDescription").text("-").endTag(NS,"ErrorDescription");
} else {
serializer.startTag(NS,"Status").text("FAILED").endTag(NS,"Status");
serializer.startTag(NS,"ErrorDescription").text(resource.getErrorMessage()).endTag(NS,"ErrorDescription");
}
serializer.endTag(NS,"Resource");
}
serializer.endTag(NS,"Resources");
serializer.endTag(NS,"ResourceReport");
serializer.endDocument();
}
catch (Exception e) {
logger.error("The Resource Report does not have a valid serialisation", e);
throw new IOException("The Resource Report does not have a valid serialisation");
}
finally {
report.close();
}
return report.toString();
}
/**
* @return the lastUpdate
*/
public Calendar getLastUpdate() {
return lastUpdate;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @return the scope
*/
public GCUBEScope getScope() {
return scope;
}
/**
* Saves the report on the local file system
*
* @throws IOException if the saving fails
*/
synchronized public void save() throws IOException {
FileWriter file = new FileWriter(getReportFile(this.id));
file.write(this.toXML());
file.close();
}
/**
* Loads the report from the file system
*
* @param id the report ID
* @return the report
* @throws IOException if the report does not have a valid serialization
*/
protected static ResourceReport load(String id) throws IOException {
ResourceReport report = new ResourceReport();
// load the report from its serialization
return report;
}
/**
* Loads the report from the file system
*
* @param id the report ID
* @return the string representation of the report
* @throws IOException if the report does not have a valid serialization
*/
protected static String loadAsString(String id) throws IOException {
// load the report serialization
File f = getReportFile(id);
if (! f.exists())
throw new IOException("Unable to find a serialized report with ID=" + id);
BufferedReader br = new BufferedReader(new FileReader(f));
StringBuilder report = new StringBuilder();
String s;
while((s = br.readLine()) != null) {
report.append(s);
}
br.close();
return report.toString();
}
private static File getReportFile(String id) throws IOException {
return new File(ServiceContext.getContext().getConfigurationFileAbsolutePath(reportDir) + File.separator + id + ".xml");
}
private void addGHNReport(KXmlSerializer serializer, DeployerReport report) throws Exception {
serializer.startTag(NS, "Packages");
for (DeployedDependency dep: report.getDependencies()) {
serializer.startTag(NS,"Package");
serializer.startTag(NS,"ServiceClass").text(dep.getService().getClazz()).endTag(NS, "ServiceClass");
serializer.startTag(NS,"ServiceName").text(dep.getService().getName()).endTag(NS, "ServiceName");
serializer.startTag(NS,"ServiceVersion").text(dep.getService().getVersion()).endTag(NS, "ServiceVersion");
serializer.startTag(NS,"PackageName").text(dep.getName()).endTag(NS, "PackageName");
serializer.startTag(NS,"PackageVersion").text(dep.getVersion()).endTag(NS, "PackageVersion");
serializer.startTag(NS,"Status").text(dep.getStatus()).endTag(NS, "Status");
serializer.startTag(NS,"Message").text(dep.getMessage()).endTag(NS, "Message");
serializer.endTag(NS,"Package");
}
serializer.endTag(NS, "Packages");
}
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,58 @@
package org.gcube.vremanagement.resourcemanager.impl.state.observers;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource.STATUS;
import org.gcube.vremanagement.resourcemanager.impl.scopemanagement.ScopedResourceManagerOperator.ACTION;
import org.gcube.vremanagement.resourcemanager.impl.state.ResourceList;
import org.gcube.vremanagement.resourcemanager.impl.state.ResourceList.OPERATION;
/**
*
* Performs operations on {@link ScopedResource}s
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class Executor extends ResourceListObserver {
@Override
protected void listChanged(ResourceList resourceList) {
if (resourceList.getLastOperationPerformed() == OPERATION.EXECUTED)
return; //nothing to manage
boolean managed = false;
for (ScopedResource resource : resourceList.getAllResources()) {
switch (resource.getStatus()) {
case ADDREQUESTED: this.addResourceToScope(resource); managed = true; break;
case REMOVEREQUESTED: this.removeResourceFromScope(resource); managed = true;break;
}
}
//notify the others for serialization and publication duties
if (managed) {
resourceList.setLastOperationPerformed(OPERATION.EXECUTED);
resourceList.notifyObservers();
}
}
private void addResourceToScope(ScopedResource resource) {
try {
resource.doAction(ACTION.ADD);
resource.setStatus(STATUS.ADDED);
} catch (Exception e) {
resource.setStatus(STATUS.LOST);
}
}
private void removeResourceFromScope(ScopedResource resource) {
try {
resource.doAction(ACTION.REMOVE);
resource.setStatus(STATUS.REMOVED);
} catch (Exception e) {
resource.setStatus(STATUS.LOST);
}
}
}

View File

@ -0,0 +1,40 @@
package org.gcube.vremanagement.resourcemanager.impl.state.observers;
import org.gcube.vremanagement.resourcemanager.impl.state.PublishedScopeResource;
import org.gcube.vremanagement.resourcemanager.impl.state.ResourceList;
import static org.gcube.vremanagement.resourcemanager.impl.state.ResourceList.OPERATION;
/**
*
* Synchronizes the resources' list with the IS
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class Publisher extends ResourceListObserver {
@Override
protected void listChanged(ResourceList resourceList) {
if (resourceList.getLastOperationPerformed() == OPERATION.PUBLISHED)
return; //no need to republish and loop on this
try {
PublishedScopeResource resource = PublishedScopeResource.getResource(resourceList.getScope());
try {
resource.synchWithLocalState(resourceList);
resource.publish();
resourceList.setLastOperationPerformed(OPERATION.PUBLISHED);
resourceList.notifyObservers();//force to serialize after publishing (not nice, thought)
} catch (Exception e) {
logger.fatal("Can't publish the Scope Resource in the IS");
throw e;
}
} catch (Exception e) {
logger.fatal("An error occured in the resource's publishing", e);
}
}
}

View File

@ -0,0 +1,41 @@
package org.gcube.vremanagement.resourcemanager.impl.state.observers;
import java.util.Observable;
import java.util.Observer;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.vremanagement.resourcemanager.impl.state.ResourceList;
/**
*
* Base observer for {@link ResourceList}
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public abstract class ResourceListObserver implements Observer {
protected GCUBELog logger = new GCUBELog(this.getClass());
public void update(Observable observed, Object arg) {
logger.debug(this.getClass().getSimpleName() + " Observer has been notified");
ResourceList resources;
if (ResourceList.class.isAssignableFrom(observed.getClass()))
resources = (ResourceList) observed;
else
throw new IllegalArgumentException("Can't manage the observed obj");
//notify subclasses
this.listChanged(resources);
}
/**
* Manages the modified resources list
*
* @param resourceList the new resources list
*/
protected abstract void listChanged(ResourceList resourceList);
}

View File

@ -0,0 +1,68 @@
package org.gcube.vremanagement.resourcemanager.impl.state.observers;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.vremanagement.resourcemanager.impl.contexts.ServiceContext;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource;
import org.gcube.vremanagement.resourcemanager.impl.state.ResourceList;
import com.thoughtworks.xstream.XStream;
/**
*
* Serializer for {@link ResourceList}
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class Serializer extends ResourceListObserver {
final public static File persistentList = ServiceContext.getContext().getPersistentFile("ScopedResourceList.xml", true);
/**
* Serializes the notified list on the file system
* @param resourceList the list to serialize
*/
@Override
protected synchronized void listChanged(final ResourceList resourceList) {
try {
store(resourceList);
//resourceList.setLastOperationPerformed(OPERATION.SERIALIZED); //if we record this, the others observer manage the list with no need
//we do not notify the others obs here, since the serialization does not imply any change in the list
} catch (IOException e) {
logger.fatal("Cannot serialize the resource's list", e);
}
}
public synchronized static void store(ResourceList resourceList) throws IOException {
XStream stream = new XStream();
stream.processAnnotations(ResourceList.class);
FileOutputStream fs = new FileOutputStream(persistentList);
stream.toXML(resourceList, fs);
fs.close();
}
/**
* Loads the list of {@link ScopedResource} from the local file system
* @param the actual scope
* @return the resource list, if any
* @throws IOException if the list was not found on the file system
*/
synchronized public static ResourceList load(GCUBEScope scope) throws IOException {
if (! persistentList.exists())
throw new IOException();
//try to load the local list of resources
XStream stream = new XStream();
stream.processAnnotations(ResourceList.class);
ResourceList list = (ResourceList) stream.fromXML(new FileInputStream((persistentList)));
//a bit of sanity checks....
if ((list == null) || (list.getScope() == null) || (list.getScope().getName().compareTo(scope.getName()) != 0))
throw new IOException();
return list;
}
}

View File

@ -0,0 +1,101 @@
package org.gcube.vremanagement.resourcemanager.stubs.testsuite;
import java.io.IOException;
import java.util.Properties;
import org.apache.axis.message.addressing.Address;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.gcube.common.core.contexts.GCUBERemotePortTypeContext;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.security.GCUBESecurityManagerImpl;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.AddResourcesParameters;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceItem;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceList;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ServiceItem;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ServiceList;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceManagerPortType;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.service.ResourceManagerServiceAddressingLocator;
/**
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class AddResourceTest {
protected static Properties resources = new Properties();
/**
* @param args
*/
public static void main(String[] args) {
if (args.length < 3)
AddResourceTest.printUsage();
try {
resources.load(AddResourceTest.class.getResourceAsStream("/" + args[2]));
} catch (IOException e1) {
e1.printStackTrace();
Runtime.getRuntime().exit(1);
}
EndpointReferenceType endpoint = new EndpointReferenceType();
try {
endpoint.setAddress(new Address("http://"+ args[0]+":"+ args[1] +"/wsrf/services/gcube/vremanagement/ResourceManager"));
ResourceManagerPortType pt;
GCUBESecurityManagerImpl managerSec = new GCUBESecurityManagerImpl() {
public boolean isSecurityEnabled() {return false;}};
pt = GCUBERemotePortTypeContext.getProxy(new ResourceManagerServiceAddressingLocator().getResourceManagerPortTypePort(endpoint),
GCUBEScope.getScope(resources.getProperty("callerScope").trim() ),managerSec);
AddResourcesParameters add = new AddResourcesParameters();
// prepare the list of service to ask to deploy
ServiceItem[] servicelist = new ServiceItem[new Integer(resources.getProperty("numOfServicesToAdd"))];
for (int i = 1 ; i < (servicelist.length +1); i++) {
servicelist[i-1] = new ServiceItem();
servicelist[i-1].setServiceClass(resources.getProperty("service." + i + ".class"));
servicelist[i-1].setServiceName(resources.getProperty("service." + i + ".name"));
servicelist[i-1].setServiceVersion(resources.getProperty("service." + i + ".version"));
if (resources.getProperty("service." + i + ".GHN") != null)
servicelist[i-1].setGHN(resources.getProperty("service." + i + ".GHN"));
}
ServiceList l = new ServiceList();
l.setService(servicelist);
//set the set of GHN, if any
if (resources.getProperty("GHNSet") != null) {
String[] ghns = resources.getProperty("GHNSet").split(",");
l.setGHN(ghns);
}
add.setServices(l);
ResourceItem[] resourcelist = new ResourceItem[new Integer(resources.getProperty("numOfResourcesToAdd"))];
for (int i = 1 ; i < (resourcelist.length +1); i++) {
resourcelist[i-1] = new ResourceItem();
resourcelist[i-1].setID(resources.getProperty("resource." + i + ".id"));
resourcelist[i-1].setType(resources.getProperty("resource." + i + ".type"));
}
ResourceList r = new ResourceList();
r.setResource(resourcelist);
add.setResources(r);
add.setTargetScope(resources.getProperty("targetScope"));
System.out.println ("Sending the Resource request....");
String reportID = pt.addResources(add);
System.out.println ("Returned report ID: " + reportID);
} catch (Exception e) {
e.printStackTrace();
}
}
static void printUsage() {
System.out.println("AddResourceTest <ResourceManager host> <ResourceManager port> <properties file>");
System.exit(1);
}
}

View File

@ -0,0 +1,52 @@
package org.gcube.vremanagement.resourcemanager.stubs.testsuite;
import java.util.Calendar;
import org.apache.axis.message.addressing.Address;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.gcube.common.core.contexts.GCUBERemotePortTypeContext;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.security.GCUBESecurityManagerImpl;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceManagerPortType;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.service.ResourceManagerServiceAddressingLocator;
public class GetReportTest {
/**
* @param args
*/
public static void main(String[] args) {
EndpointReferenceType endpoint = new EndpointReferenceType();
try {
endpoint.setAddress(new Address("http://"+ args[0]+":"+ args[1] +"/wsrf/services/gcube/vremanagement/ResourceManager"));
ResourceManagerPortType pt;
GCUBESecurityManagerImpl managerSec = new GCUBESecurityManagerImpl() {
public boolean isSecurityEnabled() {return false;}};
pt = GCUBERemotePortTypeContext.getProxy(new ResourceManagerServiceAddressingLocator().getResourceManagerPortTypePort(endpoint),
GCUBEScope.getScope(args[2]), 90000, managerSec);
System.out.println(Calendar.getInstance().getTime().toString());
String report = pt.getReport(args[3]);
System.out.println(Calendar.getInstance().getTime().toString());
System.out.println ("REPORT");
System.out.println ("************");
System.out.println (report);
System.out.println ("************");
} catch (Exception e) {
e.printStackTrace();
}
}
static void printUsage() {
System.out.println("GetReportTest <ResourceManager host> <ResourceManager port> <caller scope> <reportID>");
System.exit(1);
}
}

View File

@ -0,0 +1,77 @@
package org.gcube.vremanagement.resourcemanager.stubs.testsuite;
import java.io.IOException;
import java.util.Properties;
import org.apache.axis.message.addressing.Address;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.gcube.common.core.contexts.GCUBERemotePortTypeContext;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.security.GCUBESecurityManagerImpl;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.RemoveResourcesParameters;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceItem;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceList;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceManagerPortType;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.service.ResourceManagerServiceAddressingLocator;
public class RemoveResourceTest {
protected static Properties resources = new Properties();
/**
* @param args
*/
public static void main(String[] args) {
if (args.length < 3)
AddResourceTest.printUsage();
try {
resources.load(RemoveResourceTest.class.getResourceAsStream("/" + args[2]));
} catch (IOException e1) {
e1.printStackTrace();
Runtime.getRuntime().exit(1);
}
EndpointReferenceType endpoint = new EndpointReferenceType();
try {
endpoint.setAddress(new Address("http://"+ args[0]+":"+ args[1] +"/wsrf/services/gcube/vremanagement/ResourceManager"));
ResourceManagerPortType pt;
GCUBESecurityManagerImpl managerSec = new GCUBESecurityManagerImpl() {
public boolean isSecurityEnabled() {return false;}};
pt = GCUBERemotePortTypeContext.getProxy(new ResourceManagerServiceAddressingLocator().getResourceManagerPortTypePort(endpoint),
GCUBEScope.getScope(resources.getProperty("callerScope").trim() ),managerSec);
RemoveResourcesParameters params = new RemoveResourcesParameters();
ResourceItem[] resourcelist = new ResourceItem[new Integer(resources.getProperty("numOfResourcesToRemove"))];
for (int i = 1 ; i < (resourcelist.length +1); i++) {
resourcelist[i-1] = new ResourceItem();
resourcelist[i-1].setID(resources.getProperty("resource." + i + ".id"));
resourcelist[i-1].setType(resources.getProperty("resource." + i + ".type"));
}
ResourceList r = new ResourceList();
r.setResource(resourcelist);
params.setResources(r);
params.setTargetScope(resources.getProperty("targetScope").trim());
System.out.println ("Sending the Remove Resource request....");
String reportID = pt.removeResources(params);
System.out.println ("Returned report ID: " + reportID);
} catch (Exception e) {
e.printStackTrace();
}
}
static void printUsage() {
System.out.println("RemoveResourceTest <ResourceManager host> <ResourceManager port> <properties file>");
System.exit(1);
}
}

View File

@ -0,0 +1,75 @@
package org.gcube.vremanagement.resourcemanager.stubs.testsuite;
import java.io.IOException;
import java.util.Properties;
import org.apache.axis.message.addressing.Address;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.gcube.common.core.contexts.GCUBERemotePortTypeContext;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.security.GCUBESecurityManagerImpl;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.OptionsParameters;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ScopeOption;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceManagerPortType;
import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.service.ResourceManagerServiceAddressingLocator;
/**
*
* Tester for the <em>ChangeScopeOptionTest</em> operation
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class SetScopeOptionsTest {
protected static Properties resources = new Properties();
protected static String[] optionNames = new String[] {"creator", "designer", "endTime", "startTime",
"description", "displayName", "securityenabled"};
/**
* @param args
*/
public static void main(String[] args) {
if (args.length < 3)
SetScopeOptionsTest.printUsage();
try {
resources.load(SetScopeOptionsTest.class.getResourceAsStream("/" + args[2]));
} catch (IOException e1) {
e1.printStackTrace();
Runtime.getRuntime().exit(1);
}
EndpointReferenceType endpoint = new EndpointReferenceType();
try {
endpoint.setAddress(new Address("http://"+ args[0]+":"+ args[1] +"/wsrf/services/gcube/vremanagement/ResourceManager"));
ResourceManagerPortType pt;
GCUBESecurityManagerImpl managerSec = new GCUBESecurityManagerImpl() {
public boolean isSecurityEnabled() {return false;}};
pt = GCUBERemotePortTypeContext.getProxy(new ResourceManagerServiceAddressingLocator().getResourceManagerPortTypePort(endpoint),
GCUBEScope.getScope(resources.getProperty("callerScope")),managerSec);
OptionsParameters options = new OptionsParameters();
ScopeOption[] scopeOptionList = new ScopeOption[optionNames.length];
for (int i=0; i < optionNames.length; i++)
scopeOptionList[i] = new ScopeOption(optionNames[i], resources.getProperty(optionNames[i]));
options.setScopeOptionList(scopeOptionList);
pt.changeScopeOptions(options);
} catch (Exception e) {
e.printStackTrace();
}
}
static void printUsage() {
System.out.println("SetScopeOptionsTest <ResourceManager host> <ResourceManager port> <properties file>");
System.exit(1);
}
}

View File

@ -0,0 +1,67 @@
package org.gcube.vremanagement.resourcemanager.unit;
import java.util.Observable;
import java.util.Observer;
import junit.framework.TestCase;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedGHN;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedRunningInstance;
import org.gcube.vremanagement.resourcemanager.impl.resources.types.MultiKeysMap;
public class MultiKeysTester extends TestCase {
MultiKeysMap<String, String, ScopedResource> map;
public void createMap() {
this.map = new MultiKeysMap<String, String, ScopedResource>();
}
public void addObserver() {
this.createMap();
//map.addObserver(new CollectionWatcher());
}
public void populateMap() {
ScopedGHN ghn = new ScopedGHN("ID1", GCUBEScope.getScope("/gcube"));
map.put(ghn.getId(), ghn.getType(), ghn);
ScopedGHN ghn2 = new ScopedGHN("ID2", GCUBEScope.getScope("/gcube"));
map.put(ghn2.getId(), ghn2.getType(), ghn2);
ScopedRunningInstance ri = new ScopedRunningInstance("RI1", GCUBEScope.getScope("/gcube"), "");
map.put(ri.getId(), ri.getType(), ri);
printMap(map);
map.removeValuesBySecondaryKey(ri.getType());
printMap(map);
map.removeValue(ghn);
printMap(map);
}
public void printMap(MultiKeysMap<String, String, ScopedResource> map) {
System.out.println("Values by KEY1:");
for (String key1 : map.primaryKeySet()) {
for (ScopedResource resource : map.getValuesByPrimaryKey(key1))
System.out.println( key1 + " ->" +resource.getId());
}
System.out.println("Values by KEY2:");
for (String key2 : map.secondaryKeySet()) {
for (ScopedResource resource : map.getValuesBySecondaryKey(key2))
System.out.println( key2 + " ->" +resource.getId());
}
System.out.println("Values:");
for (ScopedResource resource : map.values()) {
System.out.println(resource.getId());
}
}
public class CollectionWatcher implements Observer {
public void update(Observable o, Object arg) {
System.out.println("Notified");
}
}
}

View File

@ -0,0 +1,98 @@
package org.gcube.vremanagement.resourcemanager.unit;
import java.util.HashSet;
import java.util.Set;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedGHN;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedResource;
import org.gcube.vremanagement.resourcemanager.impl.resources.ScopedRunningInstance;
import org.gcube.vremanagement.resourcemanager.impl.state.ResourceList;
import com.thoughtworks.xstream.XStream;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
*
* JUnit test class for {@link ResourceList}
*
* @author Manuele Simi (ISTI-CNR)
*
*/
public class ResourceListTest extends TestCase {
private static final String SCOPE = "/gcube/devsec";
private static final String NAME = "test-list";
private static final String DESCRIPTION = "This is a test for scoped resources";
private ResourceList list;
public ResourceListTest(String name) {
super(name);
list = new ResourceList(GCUBEScope.getScope(SCOPE), NAME, DESCRIPTION);
}
protected void setUp() throws Exception {
}
protected void tearDown() throws Exception {
XStream stream = new XStream();
stream.processAnnotations(ResourceList.class);
System.out.println(stream.toXML(list));
}
public void testAddResource() {
Set<ScopedResource> resourceToAdd = new HashSet<ScopedResource>();
ScopedGHN ghn = new ScopedGHN("ID1", GCUBEScope.getScope(SCOPE));
resourceToAdd.add(ghn);
list.addResources(resourceToAdd);
Assert.assertEquals(1, list.getResourcesByType(ghn.getType()).size());
ScopedGHN ghn2 = new ScopedGHN("ID2", GCUBEScope.getScope(SCOPE));
resourceToAdd.add(ghn2);
list.addResources(resourceToAdd);
Assert.assertEquals(2, list.getResourcesByType(ghn2.getType()).size());
ScopedRunningInstance ri = new ScopedRunningInstance("RI1", GCUBEScope.getScope(SCOPE), "node1.p:8080");
resourceToAdd.add(ri);
list.addResources(resourceToAdd);
Assert.assertEquals(3, list.getResourcesByType(ri.getType()).size());
}
public void testGetResourcesByType() {
fail("Not yet implemented");
}
public void testChangeDescription() {
list.changeDescription("This is a new description");
}
public void testRemoveAllResourcesByType() {
fail("Not yet implemented");
}
public void testRemoveResource() {
Set<ScopedResource> resourceToRemove = new HashSet<ScopedResource>();
ScopedGHN ghn = new ScopedGHN("ID1", GCUBEScope.getScope(SCOPE));
resourceToRemove.add(ghn);
list.removeResources(resourceToRemove);
}
public void testCleanList() {
//list.r
}
public void testAddObserver() {
fail("Not yet implemented");
}
public void testDeleteObserver() {
fail("Not yet implemented");
}
}

1
test-suite/addresource.sh Executable file
View File

@ -0,0 +1 @@
java -cp .:./lib/org.gcube.vremanagement.resourcemanager.testsuite.jar:$CLASSPATH org/gcube/vremanagement/resourcemanager/stubs/testsuite/AddResourceTest $1 $2 $3

1
test-suite/getreport.sh Executable file
View File

@ -0,0 +1 @@
java -cp .:./lib/org.gcube.vremanagement.resourcemanager.testsuite.jar:$CLASSPATH org/gcube/vremanagement/resourcemanager/stubs/testsuite/GetReportTest $1 $2 $3 $4

1
test-suite/removeresource.sh Executable file
View File

@ -0,0 +1 @@
java -cp .:./lib/org.gcube.vremanagement.resourcemanager.testsuite.jar:$CLASSPATH org/gcube/vremanagement/resourcemanager/stubs/testsuite/RemoveResourceTest $1 $2 $3

View File

@ -0,0 +1,21 @@
#global properties
numOfServicesToAdd=0
numOfResourcesToAdd=4
targetScope=/d4science.research-infrastructures.eu/EM/GCM
callerScope=/d4science.research-infrastructures.eu/EM/GCM
# resources' list
resource.1.id=7cb85930-01dd-11de-b2a2-bcdecbb76505
resource.1.type=GenericResource
resource.2.id=b57e3140-01dd-11de-b2a2-bcdecbb76505
resource.2.type=GenericResource
resource.3.id=69dbbef0-01de-11de-b2a2-bcdecbb76505
resource.3.type=GenericResource
resource.4.id=ec37cd10-0276-11de-89d4-a519d1390335
resource.4.type=GenericResource

View File

@ -0,0 +1,22 @@
#global properties
numOfServicesToAdd=3
numOfResourcesToAdd=0
targetScope=
callerScope=/gcube/devsec
# services' list
service.1.name=ContentManagementService
service.1.class=ContentManagement
service.1.version=1.00.00
service.1.GHN=2baac080-ce27-11dd-a523-acaef5fbd79f
service.2.name=StorageManagementService
service.2.class=ContentManagement
service.2.version=1.00.00
service.2.GHN=2baac080-ce27-11dd-a523-acaef5fbd79f
service.3.name=CollectionManagementService
service.3.class=ContentManagement
service.3.version=1.00.00
service.3.GHN=2baac080-ce27-11dd-a523-acaef5fbd79f

View File

@ -0,0 +1,14 @@
#global properties
numOfServicesToAdd=1
numOfResourcesToAdd=0
targetScope=/gcube/testing
callerScope=/gcube/testing
# service list
service.1.name=CredentialsRenewalService
service.1.class=DVOS
service.1.version=1.00.00
#GHNID on which the service will be deployed
service.1.GHN=4d6e3bc0-97a9-11dd-8a4d-ceae45834360

View File

@ -0,0 +1,14 @@
#global properties
numOfServicesToAdd=1
numOfResourcesToAdd=0
targetScope=/gcube/testing
callerScope=/gcube/testing
# service list
service.1.name=FullTextIndexManagement
service.1.class=Index
service.1.version=1.00.00
#GHNID on which the service will be deployed
service.1.GHN=31c9e960-b4d6-11dd-a51f-e0948ed0e306

View File

@ -0,0 +1,16 @@
#global properties
numOfServicesToAdd=1
numOfResourcesToAdd=0
targetScope=/gcube/devsec
callerScope=/gcube/devsec
# services' list
service.1.name=MetadataManager
service.1.class=MetadataManagement
service.1.version=1.00.00
#GHNID on which the service will be deployed
GHNSet=44361b70-7b8f-11de-a325-b01be4856265

View File

@ -0,0 +1,14 @@
#global properties
numOfServicesToAdd=1
numOfResourcesToAdd=0
targetScope=/gcube/testing
callerScope=/gcube/testing
# services' list
service.1.name=IS-Notifier
service.1.class=InformationSystem
service.1.version=1.00.00
#GHNID on which the service will be deployed
GHNSet=6ddbc120-bbc6-11dd-aa7e-d9f87371b7f5

View File

@ -0,0 +1,14 @@
#global properties
numOfServicesToAdd=1
numOfResourcesToAdd=0
targetScope=/gcube/testing
callerScope=/gcube/testing
# service list
service.1.name=UserManagementPortlet
service.1.class=Portal
service.1.version=1.00.00
#GHNID on which the service will be deployed
service.1.GHN=24f4ba20-cac1-11dd-a633-b8daa23bbeab

View File

@ -0,0 +1,13 @@
#global properties
numOfServicesToAdd=1
targetScope=/gcube/devsec
callerScope=/gcube/devsec
# service list
service.1.name=ISRegistry
service.1.class=InformationSystem
service.1.version=1.00.00
#GHNID on which the service will be deployed
service.1.GHN=a938b7d0-88ce-11dd-a38a-f9b09f00a04e

View File

@ -0,0 +1,13 @@
#global properties
numOfServicesToAdd=0
numOfResourcesToAdd=1
targetScope=/gcube/devsec/CNR-VRE
callerScope=/gcube/devsec/CNR-VRE
# resources' list
resource.1.id=9ad3ce60-27aa-11df-9df7-e0bf8afcd20f
resource.1.type=Collection

View File

@ -0,0 +1,13 @@
#global properties
numOfServicesToAdd=1
targetScope=/gcube/testing
callerScope=/gcube/testing
# service list
service.1.name=MetadataBroker
service.1.class=MetadataManagement
service.1.version=1.00.00
#GHNID on which the service will be deployed
service.1.GHN=c83d49b0-8a41-11dd-be58-8b0d49c88c26

View File

@ -0,0 +1,20 @@
#global properties
numOfServicesToAdd=2
numOfResourcesToAdd=0
targetScope=/gcube/devsec
callerScope=/gcube/devsec
# services' list
service.1.name=GeoIndexUpdater
service.1.class=Index
service.1.version=1.00.00
service.2.name=ForwardIndexUpdater
service.2.class=Index
service.2.version=1.00.00
#GHNID on which the service will be deployed
GHNSet=

View File

@ -0,0 +1,13 @@
#global properties
numOfServicesToAdd=0
numOfResourcesToRemove=1
targetScope=/gcube/devsec/CNR-VRE
callerScope=/gcube/devsec/CNR-VRE
# resources' list
resource.1.id=9ad3ce60-27aa-11df-9df7-e0bf8afcd20f
resource.1.type=Collection

View File

@ -0,0 +1,11 @@
callerScope=/gcube/devsec/FAO-VRE
# scope options
creator=CN=Manuele Simi, L=NMIS-ISTI, OU=Personal Certificate, O=INFN, C=IT
designer=CN=Manuele Simi, L=NMIS-ISTI, OU=Personal Certificate, O=INFN, C=IT
securityenabled=false
displayName=FAO-VRE
description=Sample VRE for FAO
#startTime=2008-11-27T16:58:12+01:00

1
test-suite/setscopeoptions.sh Executable file
View File

@ -0,0 +1 @@
java -cp .:./lib/org.gcube.resourcemanagement.manager.testsuite.jar:$CLASSPATH org/gcube/vremanagement/vremanager/stubs/testsuite/SetScopeOptionsTest $1 $2 $3