Difference between revisions of "Refining the implementation"
(→Logging it!) |
(→Service Logs) |
||
Line 187: | Line 187: | ||
</pre> | </pre> | ||
− | Typically, loggers are defined as static or instance members of implementation components. Static loggers are more memory-efficient but also less flexible in the presence of inheritance | + | Typically, loggers are defined as static or instance members of implementation components. Static loggers are more memory-efficient but also less flexible in the presence of inheritance. For example, the following instance-level logger: |
<pre> | <pre> | ||
Line 197: | Line 197: | ||
</pre> | </pre> | ||
− | logs on behalf of the class of the object denoted by <code>this</code>, not necessarily <code>MyClass<code> but potentially one of its subclasses. gCF uses instance-level loggers to log on behalf of its subclasses. | + | logs on behalf of the class of the object denoted by <code>this</code>, not necessarily <code>MyClass</code> but potentially one of its subclasses. gCF uses instance-level loggers to log on behalf of its subclasses. |
A common strategy to easily recognise service-specific entries in the container's log is to log on behalf of the service context, either at the point of creation of the logger or at any point of its lifetime, e.g.: | A common strategy to easily recognise service-specific entries in the container's log is to log on behalf of the service context, either at the point of creation of the logger or at any point of its lifetime, e.g.: | ||
Line 213: | Line 213: | ||
</pre> | </pre> | ||
− | For a | + | As [[The Development Cycle#Starting the gHN|already noticed]], the base logging level of a <code>GCUBELog</code> is configured in the <code>$GLOBUS_LOCATION/container-log4j.properties</code>. As an example, the default gCore configuration: |
+ | |||
+ | <pre> | ||
+ | log4j.category.org.globus=WARN | ||
+ | log4j.category.org.gcube=DEBUG | ||
+ | </pre> | ||
+ | |||
+ | is to the effect that loggers for classes 'under' <code>org.globus</code> will emit only warnings and errors, whereas loggers for classes 'under' <code>org.gcube</code> will emit all messages and excludes only traces. | ||
+ | |||
+ | For a (rather artificial) example of logging in context, here's a version of our port-type implementation with leaves a trace of some of its actions: | ||
<pre> | <pre> |
Revision as of 23:58, 16 April 2008
Now that we have exemplified the tasks which comprise the development cycle of a gCube service, we can progressively inject more structure and functionality into the implementation of SampleService
. We do so incrementally, of course, tackling first a number of issues which are common to all service implementations and yet do not imply big changes to the internal structure of our SampleService
.
Contents
A Faultful PortType
Things not always go according to plans. Unpredictable circumstances at runtime may cause deviations form the control flow we expect within our service implementation. Some of these deviations are the result of genuine programming errors which we hope to capture as early as possible during testing. Others are more exceptional and we cannot blame our code for them, rather a malformed client request or simply a local or remote environment which does not satisfy normal expectations. When this happens and there is a client waiting for a response, all we can do is return a fault which explains the problem and may induce a client to react in some useful way.
Faults & Exceptions
Simply put, a fault is an exception which escapes the service implementation. More precisely, it wraps such an exception in a way which is suitable for it to travel over the network and back to clients. By default, the gHN wraps exceptions which escape the service boundary in a generic SOAP fault. There is no much a client can do with it, beside desisting gracefully from doing whatever it was trying to do. However, we can define our own fault types as specialisations of the generic one.
gCF offer three pre-defined fault specialisations. They model prototypical fault causes, still generic but informative enough for clients to react more usefully than by giving up:
-
GCUBERetrySameFault
, which basically means: couldn't do it now, but try again later I might make it then. -
GCUBERetryEquivalentFault
which basically means: couldn't do it myself, but other Running Instances they might. -
GCUBEUnrecoverableFault
, which basically means: couldn't do it now, won't do it later, and there is no point asking someone else. Just forget about it.
A client presented with either one of the first two fault types can try to recover accordingly, while a client presented with the last knows that there is little point in insisting, neither later nor elsewhere. Of course, when or which of these faults should be returned depends on the precise semantics of our service.
So, how about our SampleService
? Well, at the moment our Stateless
port-type can hardly go wrong, because if its single about()
method completes successfully once, it is very likely that it will complete successfully all the time. At the very best, we could play safe and declare that we might return a GCUBEUnrecoverableFault
, in the assumption that if something goes wrong then there aren't many chances it will ever go right. In fact, a modicum of testing could immediately eliminate this possibility: either the service does not activate properly within the gHN or, if it does, it will behave correctly.
So, to illustrate fully the case of 'faultful' port-types, we are going to introduce artificially the possibility of a wider range of faults into the interface and implementation of the about()
method.
Before we do that, however, a final observation. Faults are 'heavyweight' exceptions and are best raised and caught at the ‘edge’ of a service implementations, i.e. in the code directly invoked by clients and in the code which directly call the methods of other services. Accordingly, gCF mirrors gCube faults with equivalent but 'lightweight' exception for use inside the service implementation:
-
GCUBERetrySameException
~ GCUBERetrySameFault -
GCUBERetryEquivalentException
~ GCUBERetryEquivalentFault -
GCUBEUnrecoverableException
~ GCUBEUnrecoverableFault
gCube exceptions and gCube faults are freely convertible. Typically, a gCube exception raised within the service should be converted into a gCube fault before it escapes the service. Similary, a gCube fault received from interacting with another service ought to be converted into a gCube exception before it perculates up backwords the call stack.
Note: gCube exceptions complement but do not replace all the other Java exceptions, of course. The code which observes a failure may or may not be aware of its implications in the broader context of the request process. If it does, then it should raise a gCube exception. If it does not (e.g. is a generic routine), then it should raise whatever Java exception seems most appropriate.
Note: All gCube faults share a common root GCUBEFault
, both as interface elements and implementation objects. Similary, all gCube exceptions derive GCUBEException
. As we shall see, these roots are mostly useful in the implementation, where they simplify exception handling.
A Faultful Interface
First of all, let us declare the possibility of failures in the port-type interface:
<?xml version="1.0" encoding="UTF-8"?> <definitions name="Stateless" targetNamespace="http://acme.org/sample" xmlns:tns="http://acme.org/sample" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:corefaults="http://gcube-system.org/namespaces/common/core/faults"> <import namespace="http://gcube-system.org/namespaces/common/core/faults" location="../gcube/common/core/faults/GCUBEFaults.wsdl"/> <types> <xsd:schema targetNamespace="http://acme.org/sample"> <xsd:element name="about" type="xsd:string" /> <xsd:element name="aboutResponse" type="xsd:string" /> </xsd:schema> </types> <message name="aboutInputMessage"> <part name="request" element="tns:about"/> </message> <message name="aboutOutputMessage"> <part name="response" element="tns:aboutResponse"/> </message> <portType name="StatelessPortType"> <operation name="about"> <input message="tns:aboutInputMessage"/> <output message="tns:aboutOutputMessage"/> <fault name="unrecoverablefault" message="corefaults:GCUBEUnrecoverableFaultMessage"/> <fault name="retrysamefault" message="corefaults:GCUBERetrySameFaultMessage"/> <fault name="retryequivalentfault" message="corefaults:GCUBERetryEquivalentFaultMessage" /> </operation> </portType> </definitions>
The thing to notice here is that we import pre-defined fault messages from a standard gCore WSDL:
<import namespace="http://gcube-system.org/namespaces/common/core/faults" location="../gcube/common/core/faults/GCUBEFaults.wsdl"/>
and then use them in the declartion of the about()
operation:
<operation name="about"> <input message="tns:aboutInputMessage"/> <output message="tns:aboutOutputMessage"/> <fault name="unrecoverablefault" message="corefaults:GCUBEUnrecoverableFaultMessage"/> <fault name="retrysamefault" message="corefaults:GCUBERetrySameFaultMessage"/> <fault name="retryequivalentfault" message="corefaults:GCUBERetryEquivalentFaultMessage" /> </operation>
Note: The location
makes sense with respect to the temporary build
used by our buildfile and will succeed because the buildfile will copy all the the pre-defined gCore WSDL in that folder at the point of building. You do not need to worry about it, just make sure you are copying this correctly.
That's all for the interface of Stateless
. This is the right time to rebuild the stubs though.
A Faultful Implementation
Now the implementation of the port-type and the simulation of failure we promised:
package org.acme.sample.stateless; import ... public class Stateless extends GCUBEStartupPortType { /** {@inheritDoc} */ protected GCUBEServiceContext getServiceContext() {return ServiceContext.getContext();} protected static void simulateRequestProcessing() throws Exception { if (Math.random()<.60) { //simulating an error switch ((int) (Math.random()*4+1)) {//randomly choosing error type case 1 : throw new GCUBEUnrecoverableException("just give up"); case 2 : throw new GCUBERetryEquivalentException("maybe someone else?"); case 3: throw new GCUBERetrySameException("maybe in a bit?"); case 4: throw new Exception("some problem with unclear semantics"); }}} public String about(String name) throws GCUBEFault,GCUBERetryEquivalentFault,GCUBERetrySameFault,GCUBEUnrecoverableFault { try { simulateRequestProcessing(); return ("Hello " + name + ", you have invoked service ")+this.getServiceContext().getName() + " ("+this.getServiceContext().getServiceClass() + ")"; } catch(GCUBEException e) {throw e.toFault();} catch(Exception e) {throw sctx.getDefaultException("Problem of unknown semantics", e).toFault();} } }
A few things to comment upon here:
- the method
simulatRequestProcessing()
emulates an arbitrarily complex process which may fail in more than one different way. In a real scenario, the process would be likely distributed among many implementation components, and it would probably reach very 'deeply' within the call stack. Here we use a 'flat' method in which we throw a die and simulate a failure in 60% of the outcomes. When we do so, we throw another 4-faced die to simulate the different types of failures which may occur inside a gCube Service: the three types of gCube exceptions gCube plus a fourth type of generic failure.
- the method
about()
invokessimulatRequestProcessing()
and catches potential exceptions. All gCube exceptions are converted to the corresponding gCube fault. Any other Java exception is embedded into the type of gCube exception set as default before being also converted to a gCube fault.
-
getDefaultException()
is a method whichServiceContext
inherits fromGCUBEServiceContext
. If not overridden, the method will wrap any exception into aGCUBERetryEquivalentException
, but it may be overridden to reflect more optimistic or less optimistic assumptions.
Note: about()
must declare explicitly all the gCube faults it may throw. If it did not, specific faults would arrive at the client as generic gCube faults, so defeating their purpose. This is unfortunately one limitation of the technologies underlying the current implementation of gCore. In addition, about()
must declare to throw the generic gCube fault because the method toFault()
of gCube exceptions returns it.
After having rebuilt and redeployed SampleService
, adapt our StatelessClient
to catch faults of the different types and then test it.
Logging it!
We gave earlier a first look at the gHN's log, and observed the logs which gCF produces at startup on behalf of SampleService
. Surely enough you would like to log the activities of your code, not only the gCF code from which yours inherits. In fact, you would probably want to log both from within code which runs within the gHN (and thus into container.log
), as well as from within client code which runs outside a gHN. After all, configurable and multi-level log entries are much more informative and flexible than hand-made println()
statements could possibly be.
Logging in gCF is discussed in somewhat more detail here. For a usage perspective, it is sufficient to recall that:
- logging messages are produced by invoking the methods of a logger object.
- logging messages can be assigned any one of 6 different levels. In order of increasing 'severity':
TRACE
,DEBUG
,INFO
,WARN
,ERROR
,FATAL
. - logging messages can be complemented with stacktrace information.
- logging messages at any one level appear in the log only if the logger which emits them is configured to display messages at that level.
This is a summary of the logger interface:
logger.fatal(Object message); logger.fatal(Object message, Throwable t); logger.error(Object message); logger.error(Object message, Throwable t); logger.warn(Object message); logger.warn(Object message, Throwable t); logger.info(Object message); logger.info(Object message, Throwable t); logger.debug(Object message); logger.debug(Object message, Throwable t); logger.trace(Object message); logger.trace(Object message, Throwable t);
gCF offers two types of loggers for use within and outside the gHN, respectively. Both use log4j implementations of a simple JCL interface. The log4j implementations can be configured to log only at or above a certain level of security, towards specific outputs, and using specific templates.
Service Logs
Within the service implementation, you can use instantiate a GCUBELog
with either the object or class on behalf of which you wish to log. For example, if myObject
denotes an object of class MyClass
, then the following idioms are equivalent:
GCUBELog logger = new GCUBELog(myObject); GCUBELog logger = new GCUBELog(myObject.getClass()); GCUBELog logger = new GCUBELog(MyClass.class);
Typically, loggers are defined as static or instance members of implementation components. Static loggers are more memory-efficient but also less flexible in the presence of inheritance. For example, the following instance-level logger:
public class MyClass { .... GCUBELog logger = new GCUBELog(this); ... }
logs on behalf of the class of the object denoted by this
, not necessarily MyClass
but potentially one of its subclasses. gCF uses instance-level loggers to log on behalf of its subclasses.
A common strategy to easily recognise service-specific entries in the container's log is to log on behalf of the service context, either at the point of creation of the logger or at any point of its lifetime, e.g.:
GCUBELog logger = new GCUBELog(ServiceContext.getContext());
or:
logger.setContext(ServiceContext.getContext());
In fact, any log prefix can be dynamically associated with a logger:
logger.setPrefix("someprefix")
As already noticed, the base logging level of a GCUBELog
is configured in the $GLOBUS_LOCATION/container-log4j.properties
. As an example, the default gCore configuration:
log4j.category.org.globus=WARN log4j.category.org.gcube=DEBUG
is to the effect that loggers for classes 'under' org.globus
will emit only warnings and errors, whereas loggers for classes 'under' org.gcube
will emit all messages and excludes only traces.
For a (rather artificial) example of logging in context, here's a version of our port-type implementation with leaves a trace of some of its actions:
package org.acme.sample.stateless; import ... public class Stateless extends GCUBEStartupPortType { private GCUBELog logger = new GCUBELog(this); /** {@inheritDoc} */ protected GCUBEServiceContext getServiceContext() {return ServiceContext.getContext();} protected static void simulateRequestProcessing() throws Exception { if (Math.random()<.60) { //simulating an error switch ((int) (Math.random()*4+1)) {//randomly choosing error type case 1 : throw new GCUBEUnrecoverableException("just give up"); case 2 : throw new GCUBERetryEquivalentException("maybe someone else?"); case 3: throw new GCUBERetrySameException("maybe in a bit?"); case 4: throw new Exception("some problem with unclear semantics"); }}} public String about(String name) throws GCUBEFault,GCUBERetryEquivalentFault,GCUBERetrySameFault,GCUBEUnrecoverableFault { logger.debug("Received a call from "+name); try { simulateRequestProcessing(); return ("Hello " + name + ", you have invoked service ")+this.getServiceContext().getName() + " ("+this.getServiceContext().getServiceClass() + ")"; } catch(GCUBEException e) { logger.error("gCube Exception'',e); throw e.toFault(); } catch(Exception e) { logger.error("Problem of unknown semantics",e); throw sctx.getDefaultException("Problem of unknown semantics", e).toFault();} } }