RPC::XML::Server - A server base-class for XML-RPC |
RPC::XML::Server - A server base-class for XML-RPC
use RPC::XML::Server;
... $srv = RPC::XML::Server->new(port => 9000); # Several of these, most likely: $srv->add_method(...); ... $srv->server_loop; # Never returns
This is both a base-class for developing XML-RPC servers, and a working server class in its own right. It is built upon the RPC::XML data classes, and defaults to using HTTP::Daemon for the communication layer.
Use of the RPC::XML::Server is based on an object model. A server is instantiated from the class, methods (subroutines) are made public by adding them through the object interface, and then the server object is responsible for dispatching requests (and possibly for the HTTP listening, as well).
These methods are static to the package, and are used to provide external access to internal settings:
NAME/VERSION
consistent with other applications such as Apache and
LWP. It is provided here as part of the compatibility with HTTP::Daemon
that is required for effective integration with Net::Server.
The following are object (non-static) methods. Unless otherwise explicitly noted, all methods return the invoking object reference upon success, and a non-reference error string upon failure.
See Content Compression below for details of how the server class manages gzip-based compression and expansion of messages.
new(OPTIONS)
true
value, prevents the creation and storage of the
HTTP::Daemon object. This allows for deployment of a server object in other
environments. Note that if this is set, the server_loop method described
below will silently attempt to use the Net::Server module.
true
value, prevents the loading of the default procedures
provided with the RPC::XML distribution. These may be later loaded using
the add_default_methods interface described later. The procedures themselves
are described below (see The Default Procedures Provided).
UNLINK
set,
so once it is freed the disk space is immediately freed.
tmpdir
method from the File::Spec package is used, instead.
Note that this value is not applied to any faults specified via the next
option, fault_table
. It is assumed that the developer has already applied
any offset to those codes.
Any other keys in the options hash not explicitly used by the constructor are
copied over verbatim onto the object, for the benefit of sub-classing this
class. All internal keys are prefixed with __
to avoid confusion. Feel
free to use this prefix only if you wish to re-introduce confusion.
undef
.
new
method) creates and stores an instance of
HTTP::Response, which is then used by the HTTP::Daemon or Net::Server
processing loops in constructing the response to clients. The response object
has all common headers pre-set for efficiency. This method returns a reference
to that object.
started([BOOL])
time2iso8601
routine exported by the RPC::XML package.
timeout(INT)
If passed as a hash reference, the following keys are expected:
true
value, then the method should be hidden
from any introspection API implementations. This parameter is optional, the
default behavior being to make the method publically-visible.
If a file is passed, then it is expected to be in the XML-based format, described in the RPC::XML::Procedure page (see RPC::XML::Procedure). If the name passed is not an absolute pathname, then the file will be searched for in any directories specified when the object was instantiated, then in the directory into which this module was installed, and finally in the current working directory. If the operation fails, the return value will be a non-reference, an error message. Otherwise, the return value is the object reference.
The add_method, add_function and add_procedure calls are essentialy identical unless called with hash references. Both files and objects contain the information that defines the type (method vs. procedure) of the funtionality to be added to the server. If add_method is called with a file that describes a procedure, the resulting addition to the server object will be a RPC::XML::Procedure object, not a method object.
For more on the creation and manipulation of procedures and methods as objects, see RPC::XML::Procedure.
delete_method(NAME)
delete_procedure(NAME)
delete_function(NAME)
The delete_procedure and delete_function calls are identical, supplied for the sake of symmetry. All calls return the matched object regardless of its underlying type.
The list_procedures and list_functions calls are provided for symmetry. All calls list all published routines on the calling server object, regardless of underlying type.
xpl_path([LISTREF])
*.xpl
files (files that
specify methods) that are specified in calls to add_method, above. If a
list reference is passed, it is installed as the new path (each element of the
list being one directory name to search). Regardless of argument, the current
path is returned as a list reference. When a file is passed to add_method,
the elements of this path are searched first, in order, before the
installation directory or the current working directory are searched.
get_method(NAME)
get_procedure(NAME)
get_function(NAME)
undef
is returned. Note that this is a referent to the object as stored
on the server object itself, and thus changes to it could affect the behavior
of the server.
The get_procedure and get_function calls are provided for symmetry. All will return the same object for NAME, regardless of the underlying type.
server_loop(HASH)
accept()
-based loop of HTTP::Daemon if the object was created with
an instance of that class as a part. Otherwise, this enters the run-loop of
the Net::Server class. It listens for requests, and marshalls them out via
the dispatch
method described below. It answers HTTP-HEAD requests
immediately (without counting them on the server statistics) and efficiently
by using a cached HTTP::Response object.
Because infinite loops requiring a HUP
or KILL
signal to terminate are
generally in poor taste, the HTTP::Daemon side of this sets up a localized
signal handler which causes an exit when triggered. By default, this is
attached to the INT
signal. If the Net::Server module is being used
instead, it provides its own signal management.
The arguments, if passed, are interpreted as a hash of key/value options (not a hash reference, please note). For HTTP::Daemon, only one is recognized:
false
value) or the
string NONE
, then the signal handler will not be installed, and the
loop may only be broken out of by killing the running process (unless other
arrangements are made within the application).
The options that Net::Server responds to are detailed in the manual pages
for that package. All options passed to server_loop
in this situation are
passed unaltered to the run()
method in Net::Server.
dispatch(REQUEST)
The dispatched method may communicate error in several ways. First, any
non-reference return value is presumed to be an error string, and is encoded
and returned as an RPC::XML::fault response. The method is run under an
eval()
, so errors conveyed by $@
are similarly encoded and returned. As
a special case, a method may explicitly die()
with a fault response, which
is passed on unmodified.
add_default_methods([DETAILS])
*.xpl
extension, and are installed into the same directory as this
Server.pm file. The set of default methods are described below (see
The Default Methods Provided).
If any names are passed as a list of arguments to this call, then only those
methods specified are actually loaded. If the *.xpl
extension is absent on
any of these names, then it is silently added for testing purposes. Note that
the methods shipped with this package have file names without the leading
status.
part of the method name. If the very first element of the list of
arguments is except
(or -except
), then the rest of the list is
treated as a set of names to not load, while all others do get read. The
Apache::RPC::Server module uses this to prevent the loading of the default
system.status
method while still loading all the rest of the defaults. (It
then provides a more Apache-centric status method.)
Note that there are no symmetric calls in this case. The provided API is implemented as methods, and thus only this interface is provided.
*.xpl
files. In fact, the
add_default_methods routine simply calls this routine with the installation
directory as the first argument. The definition of the additional arguments is
the same as above.
add_procedures_in_dir and add_functions_in_dir are provided for symmetry.
Alternately, one or more of the name parameters passed to this call may be
regular-expression objects (the result of the qr operator). Any of these
detected are applied against the list of all available methods known to the
source server. All matching ones are inserted into the list (the list is pared
for redundancies in any case). This allows for easier addition of whole
classes such as those in the system.*
name space (via qr/^system[.]/
),
for example. There is no substring matching provided. Names listed in the
parameters to this routine must be either complete strings or regular
expressions.
The share_procedures and share_functions calls are provided for symmetry.
clone()
method
from that class. Thus, while the calling object has the same methods
available, and is re-using existing code in the Perl runtime, the method
objects (and hence the statistics and such) are kept separate. As with the
above, an error is flagged if one or more are not found.
This routine also accepts regular-expression objects with the same behavior and limitations. Again, copy_procedures and copy_functions are provided for symmetry.
Specifying the methods themselves can be a tricky undertaking. Some packages (in other languages) delegate a specific class to handling incoming requests. This works well, but it can lead to routines not intended for public availability to in fact be available. There are also issues around the access that the methods would then have to other resources within the same running system.
The approach taken by RPC::XML::Server (and the Apache::RPC::Server subclass of it) require that remote procedures be explicitly published in one of the several ways provided. Procedures may be added directly within code by using add_procedure/add_method/add_function as described above, with full data provided for the code reference, signature list, etc. The add_* technique can also be used with a file that conforms to a specific XML-based format (detailed in the manual page for the RPC::XML::Procedure class, see RPC::XML::Procedure). Entire directories of files may be added using add_methods_in_dir, which merely reads the given directory for files that appear to be method definitions.
There are three types of procedures that RPC::XML::Server marshalls calls to. All are provided by the RPC::XML::Procedure module. You should not need to load or reference this module directly, as loading RPC::XML::Server (or a derivative) makes it available. The three types are:
There is (currently) no version that is called like a method but ignores signatures like a function.
When a routine is called via the server dispatcher, it is called with the arguments that the client request passed. Depending on whether the routine is considered a ``function'', a ``procedure'' or a ``method'', there may be an extra argument at the head of the list. The extra argument is present when the routine being dispatched is part of a RPC::XML::Method object. The extra argument is a reference to a RPC::XML::Server object (or a subclass thereof). This is derived from a hash reference, and will include these special keys:
peerhost
, it is readily
available in both this server environment and the Apache::RPC::Server
environment and thus included for convenience.
x.x.x.x
(dotted-quad) format. If you wish to look up the clients host-name, you
can use this to do so or utilize the encoded structure above directly.
X-Forwarded-For
for your access checks, for
example).
Those keys should only be referenced within method code itself, as they are not set on the server object outside of that context.
Note that by passing the server object reference first, method-classed routines are essentially expected to behave as actual methods of the server class, as opposed to ordinary functions. Of course, they can also discard the initial argument completely.
The routines should not make (excessive) use of global variables, for obvious
reasons. When the routines are loaded from XPL files, the code is created as a
closure that forces execution in the RPC::XML::Procedure package (unless the
XPL specifies a namespace, see RPC::XML::Procedure). If
the code element of a procedure/method is passed in as a direct code reference
by one of the other syntaxes allowed by the constructor, the package may well
be different. Thus, routines should strive to be as localized as possible,
independent of specific namespaces. If a group of routines are expected to work
in close concert, each should explicitly set the namespace with a package
declaration as the first statement within the routines themselves.
The following methods are provided with this package, and are the ones installed on newly-created server objects unless told not to. These are identified by their published names, as they are compiled internally as anonymous subroutines and thus cannot be called directly:
method(s)
have no
help text, the string will be null.
methodName
member, which provides the name of the method to call. If
there is also a params
member, it refers to an array of the parameters
that should be passed to the call.
In addition, each of these has an accompanying help file in the methods
sub-directory of the distribution.
These methods are installed as *.xpl
files, which are generated from files
in the methods
directory of the distribution using the make_method tool
(see make_method). The files there provide the Perl code that
implements these, their help files and other information.
The RPC::XML::Server class now supports compressed messages, both incoming and outgoing. If a client indicates that it can understand compressed content, the server will use the Compress::Zlib (available from CPAN) module, if available, to compress any outgoing messages above a certain threshhold in size (the default threshhold is set to 4096 bytes). The following methods are all related to the compression support within the server class:
compress_thresh([MIN_LIMIT])
If the server anticipates handling large out-bound messages (for example, if
the hosted code returns large Base64 values pre-encoded from file handles),
the message_file_thresh
and message_temp_dir
settings may be used in a
manner similar to RPC::XML::Client. Specifically, the threshhold is used to
determine when a message should be spooled to a filehandle rather than made
into an in-memory string (the RPC::XML::base64 type can use a filehandle,
thus eliminating the need for the data to ever be completely in memory). An
anonymous temporary file is used for these operations.
Note that the message size is checked before compression is applied, since the size of the compressed output cannot be known until the full message is examined. It is possible that a message will be spooled even if its compressed size is below the threshhold, if the uncompressed size exceeds the threshhold.
new
method.
Previous versions of this library had a very loosely-organized set of fault codes that a server might return in certain (non-fatal) error circumstances. This has been replaced by a more configurable, adjustable system to allow users to better integrate the server-defined faults with any that their application may produce. It also allows for the definition of additional fault types so that the same mechanism for formatting the pre-defined faults can be used within sub-classes and user applications.
The server method server_fault is used to generate RPC::XML::fault objects for these situations. It takes one or two arguments, the first being the name of the type of fault to create and the second being the specific message. If a fault is defined with a static message, the second argument may be skipped (and will be ignored if passed).
In addition to defining their own faults, a user may override the definition of any of the server's pre-defined faults.
The user may define their own faults using the fault_table
argument to the
constructor of the server class being instantiated. They may also override
any of the pre-defined faults (detailed in the next section) by providing a
new definition for the name.
The value of the fault_table
argument is a hash reference whose keys are
the names of the faults and whose values are one of two types:
%s
,
this will be replaced with the message argument (the second parameter) passed
to server_fault. If that sequence is not in the string, then the fault
message is considered static and the message argument is ignored.
An example of defining faults:
my $server = RPC::XML::Server->new( ... fault_table => { limitexceeded => [ 500 => 'Call limit exceeded' ], accessdenied => [ 600 => 'Access denied: %s' ], serviceclosed => 700 }, ... );
In this example, the fault-type ``limitexceeded'' is defined as having a fault
code of 500 and a static message of Call limit exceeded
. The next fault
defined is ``accessdenied'', which has a code of 600 and message that starts
with Access denied:
and incorporates whatever message was passed in to the
fault creation. The last example defines a fault called serviceclosed
that
has a code of 700 and uses any passed-in message unaltered.
The RPC::XML::Server class defines the following faults and uses them
internally. You can override the codes and messages for these by including them
in the table passed as a fault_table
argument. The faults fall into three
groups:
The faults, and the phases they apply to, are:
The code is 100
, and the message is of the form, XML parse error: %s
.
The specific error from the XML parser is included in the message.
The code is 200
, and the message is of the form, Method lookup error: %s
.
The name of the method and other information is included in the message.
The code is 201
, and the message is of the form, Method signature error:
%s
. The name of the method and the signature of the arguments is included in
the message.
$@
is used in the message of the fault that gets generated.
The code is 300
, and the message is of the form, Code execution error:
%s
. The actual text of the exception thrown is included in the message.
There is one special server-fault whose code and message cannot be overridden.
If a call is made to server_fault for an unknown type of fault, the
returned object will have a code of -1
and a message stating that the
fault-type is unknown. The message will include both the requested type-name
and any message (if any) that was passed in.
If you just want to ``move'' the range of codes that the server uses out of the
way of your application's own faults, this can be done with the
fault_code_base
parameter when constructing the server object. The value
of the parameter must be an integer, and it is added to the value of all
existing fault codes. For example, a value of 10000
would make the code
for the badxml
fault be 10100
, the code for badmethod
be 10200
,
etc.
This is applied before any user-defined faults are merged in, so their code values will not be affected by this value.
Unless explicitly stated otherwise, all methods return some type of reference on success, or an error string on failure. Non-reference return values should always be interpreted as errors unless otherwise noted.
Please report any bugs or feature requests to
bug-rpc-xml at rt.cpan.org
, or through the web interface at
http://rt.cpan.org/NoAuth/ReportBug.html. I will be
notified, and then you'll automatically be notified of progress on
your bug as I make changes.
This file and the code within are copyright (c) 2011 by Randy J. Ray.
Copying and distribution are permitted under the terms of the Artistic License 2.0 (http://www.opensource.org/licenses/artistic-license-2.0.php) or the GNU LGPL 2.1 (http://www.opensource.org/licenses/lgpl-2.1.php).
The XML-RPC standard is Copyright (c) 1998-2001, UserLand Software, Inc. See <http://www.xmlrpc.com> for more information about the XML-RPC specification.
RPC::XML, RPC::XML::Client, RPC::XML::ParserFactory
Randy J. Ray <rjray@blackperl.com>
RPC::XML::Server - A server base-class for XML-RPC |