The Omniorb Version 4.2 Users' Guide: Duncan Grisby
The Omniorb Version 4.2 Users' Guide: Duncan Grisby
2
Users’ Guide
Duncan Grisby
([email protected])
Contents
1 Introduction 1
1.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.1 Multithreading . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.1.2 Portability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.1.3 Missing features . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Setting up your environment . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Platform specific variables . . . . . . . . . . . . . . . . . . . . . . . 4
2 The Basics 6
2.1 The Echo Object Example . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 Specifying the Echo interface in IDL . . . . . . . . . . . . . . . . . . 6
2.3 Generating the C++ stubs . . . . . . . . . . . . . . . . . . . . . . . 7
2.4 Object References and Servants . . . . . . . . . . . . . . . . . . . . 8
2.5 A quick look at the C++ mapping . . . . . . . . . . . . . . . . . . . 8
2.5.1 Mapping overview . . . . . . . . . . . . . . . . . . . . . . . . 8
2.5.2 Interface scope type . . . . . . . . . . . . . . . . . . . . . . . 8
2.5.3 Object reference pointer type . . . . . . . . . . . . . . . . . 9
2.5.3.1 Nil object reference . . . . . . . . . . . . . . . . . . 9
2.5.3.2 Object reference lifecycle . . . . . . . . . . . . . . . 10
2.5.3.3 Object reference inheritance . . . . . . . . . . . . . 11
2.5.3.4 Object reference equivalence . . . . . . . . . . . . 11
2.5.4 Servant Object Implementation . . . . . . . . . . . . . . . . 12
2.6 Writing the servant implementation . . . . . . . . . . . . . . . . . . 12
2.7 Writing the client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.8 Example 1 — Colocated Client and Servant . . . . . . . . . . . . . . 15
2.8.1 ORB initialisation . . . . . . . . . . . . . . . . . . . . . . . . 16
2.8.2 Obtaining the Root POA . . . . . . . . . . . . . . . . . . . . . 16
2.8.3 Object initialisation . . . . . . . . . . . . . . . . . . . . . . . 17
2.8.4 Activating the POA . . . . . . . . . . . . . . . . . . . . . . . . 18
2.8.5 Performing a call . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.8.6 ORB destruction . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.9 Example 2 — Different Address Spaces . . . . . . . . . . . . . . . . 18
ii
2.9.1 Making a Stringified Object Reference . . . . . . . . . . . . 19
2.9.2 Client: Using a Stringified Object Reference . . . . . . . . . 19
2.9.3 Catching System Exceptions . . . . . . . . . . . . . . . . . . 20
2.9.4 Lifetime of a CORBA object . . . . . . . . . . . . . . . . . . . 20
2.10 Example 3 — Using the Naming Service . . . . . . . . . . . . . . . 21
2.10.1 Obtaining the Root Context Object Reference . . . . . . . . 21
2.10.2 The Naming Service Interface . . . . . . . . . . . . . . . . . 22
2.11 Example 4 — Using tie implementation templates . . . . . . . . . . 22
2.12 Source Listings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.12.1 eg1.cc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.12.2 eg2_impl.cc . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.12.3 eg2_clt.cc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.12.4 eg3_impl.cc . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.12.5 eg3_clt.cc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.12.6 eg3_tieimpl.cc . . . . . . . . . . . . . . . . . . . . . . . . . . 39
9 Interceptors 102
9.1 Interceptor registration . . . . . . . . . . . . . . . . . . . . . . . . . 103
9.2 Available interceptors . . . . . . . . . . . . . . . . . . . . . . . . . . 103
9.3 Server-side call interceptor . . . . . . . . . . . . . . . . . . . . . . . 106
15 Resources 131
Chapter 1
Introduction
omniORB is an Object Request Broker (ORB) that implements version 2.6 of the
Common Object Request Broker Architecture (CORBA) [OMG01] specification.
Where possible, backward compatibility has been maintained back to specifica-
tion 2.0. It passed the Open Group CORBA compliant testsuite (for CORBA 2.1)
and was one of the three ORBs to be granted the CORBA brand in June 1999.
This user guide tells you how to use omniORB to develop CORBA applica-
tions. It assumes a basic understanding of CORBA.
In this chapter, we give an overview of the main features of omniORB and
what you need to do to set up your environment to run omniORB.
1.1 Features
omniORB is quite feature-rich, but it does not slavishly implement every last
part of the CORBA specification. The goal is to provide the most generally useful
parts of the specification in a clean and efficient manner. Highlights are:
• DynAny is supported.
1
CHAPTER 1. INTRODUCTION 2
• Many platforms are supported, including most Unix platforms and Win-
dows.
• It has been successfully tested for interoperability via IIOP with other
ORBs.
1.1.1 Multithreading
1.1.2 Portability
omniORB is not a complete implementation of the CORBA 2.6 core. The follow-
ing is a list of the most significant missing features.
• For some very dynamic uses of CORBA, you may need an Interface Repos-
itory. omniORB does not have its own one, but it can act as a client to an
IfR. The omniifr project (https://github.com/omniorb/omniifr) aims to
create an IfR for omniORB.
To get omniORB running, you first need to install omniORB according to the
instructions in the installation notes for your platform. See README.FIRST.txt
at the top of the omniORB tree for instructions. Most Unix platforms can use
the Autoconf configure script to automate the configuration process.
Once omniORB is installed in a suitable location, you must configure it ac-
cording to your required setup. The configuration can be set with a configura-
tion file, environment variables, command-line arguments or, on Windows, the
Windows registry.
CHAPTER 1. INTRODUCTION 4
• On Unix platforms, the omniORB runtime looks for the environment vari-
able OMNIORB_CONFIG. If this variable is defined, it contains the pathname
of the omniORB configuration file. If the variable is not set, omniORB will
use the compiled-in pathname to locate the file (by default /etc/omniORB.
cfg).
InitRef = NameService=corbaname::my.host.name
The preprocessor defines for new platform ports not listed above can be
found in the corresponding platform configuration files. For instance, the plat-
form configuration file for Sun Solaris 2.6 is in mk/platforms/sun4_sosV_5.6.
mk. The preprocessor defines to identify a platform are in the make variable
IMPORT_CPPFLAGS.
In a single source multi-target environment, you can put the preprocessor
defines as the command-line arguments for the compiler. If you are building for
a single platform, you can edit include/omniconfig.h to add the definitions.
Chapter 2
The Basics
Our example is an object which has only one method. The method simply echos
the argument string. We have to:
2. use the IDL compiler to generate the stub code, which provides the object
mapping as defined in the CORBA specification
6
CHAPTER 2. THE BASICS 7
interface Echo {
string echoString(in string mesg);
};
If you are new to IDL, you can learn about its syntax in Chapter 3 of the
CORBA 2.6 specification [OMG01]. For the moment, you only need to know that
the interface consists of a single operation, echoString(), which takes a string
as an input argument and returns a copy of the same string.
The interface is written in a file, called echo.idl. It is part of the CORBA
standard that all IDL files must have the extension ‘.idl’, although omniORB
does not enforce this. In the omniORB distribution, this file is in idl/echo.idl.
For simplicity, the interface is defined in the global IDL namespace. You
should normally avoid this practice for the sake of object reusability. If every
CORBA developer defines their interfaces in the global IDL namespace, there is
a danger of name clashes between two independently defined interfaces. There-
fore, it is better to qualify your interfaces by defining them inside module names.
Of course, this does not eliminate the chance of a name clash unless some form
of naming convention is agreed globally. Nevertheless, a well-chosen module
name can help a lot.
From the IDL file, we use the IDL compiler to produce the C++ mapping of the
interface. The IDL compiler for omniORB is called omniidl. Given the IDL file,
omniidl produces two stub files: a C++ header file and a C++ source file. For
example, from the file echo.idl, the following files are produced:
• echo.hh
• echoSK.cc
omniidl must be invoked with the -bcxx argument to tell it to generate C++
stubs. The following command line generates the stubs for echo.idl:
omniidl -bcxx echo.idl
Note that the names echo.hh and echoSK.cc are not defined in the C++
mapping standard. Other CORBA implementations may use different file names.
To aid migration omniidl from other implementations, omniidl has options to
override the default output file names. See section 5.2 for details.
If you are using our make environment, you don’t need to invoke omniidl
explicitly. In the example file dir.mk, we have the following line:
CORBA_INTERFACES = echo
CHAPTER 2. THE BASICS 8
That is all we need to instruct the build system to generate the stubs. You won’t
find the stubs in your working directory because all stubs are written into the
stub directory at the top level of your build tree.
The full arguments to omniidl are detailed in chapter 5.
The C++ stubs conform to the standard mapping defined in the CORBA speci-
fication [OMG03]. Sadly, since it pre-dates the C++ standard library, the C++
language mapping is quite hard to use, especially because it has complex mem-
ory management rules.
The best way to understand the mapping is to read either the specification
or, better, a book about using CORBA from C++. Reading the code generated
by omniidl is hard-going, and it is difficult to distinguish the parts you need to
know from the implementation details.
A C++ class Echo is defined to hold a number of static functions and type defi-
nitions. It looks like this:
CHAPTER 2. THE BASICS 9
class Echo {
public:
typedef Echo_ptr _ptr_type;
typedef Echo_var _var_type;
The _ptr_type and _var_type typedefs are there to facilitate template pro-
gramming. The static functions are described below.
For interface Echo, the mapping defines the object reference type Echo_ptr
which has pointer semantics. The _ptr type provides access to the interface’s
operations. The concrete type of an object reference is opaque, i.e. you must
not make any assumptions about how an object reference is implemented. You
can imagine it looks something like this:
class private_class : public some_base_class {
char* echoString(const char* mesg);
};
To use an object reference, you use the arrow operator ‘->’ to invoke its
operations, but you must not use it as a C++ pointer in any other respect. It is
non-compliant to convert it to void*, perform arithmetic or relational operations
including testing for equality using operator==.
In some CORBA implementations, Echo_ptr is a typedef to Echo*. In omni-
ORB, it is not—the object reference type is distinct from class Echo.
Object references can be nil. To obtain a nil object reference for interface Echo,
call Echo::_nil(). To test if an object reference is nil, use CORBA::_is_nil():
CORBA::Boolean true_result = CORBA::is_nil(Echo::_nil());
Echo::_nil() is the only compliant way to obtain a nil Echo reference, and
CORBA::is_nil() is the only compliant way to check if an object reference is
nil. You should not use the equality operator==. Many C++ ORBs use the null
pointer to represent a nil object reference, but omniORB does not.
CHAPTER 2. THE BASICS 10
Object references are reference counted. That is, the opaque C++ objects on the
client side that implement Echo_ptr are reference counted, so they are deleted
when the count goes to zero. The lifetime of an object reference has no bearing
at all on the lifetime of the CORBA object to which it is a reference—when an
object reference is deleted, it has no effect on the object in the server.
Reference counting for Echo object references is performed with Echo::
_duplicate() and CORBA::release().
The _duplicate() function returns a new object reference of the Echo inter-
face. The new object reference can be used interchangeably with the old object
reference to perform an operation on the same object.
To indicate that an object reference will no longer be accessed, you must call
the CORBA::release() operation. Its signature is as follows:
namespace CORBA {
void release(CORBA::Object_ptr obj);
... // other methods
};
The mappings of many other IDL data types include _var types with similar
semantics.
All CORBA objects inherit from the generic object CORBA::Object. CORBA::
Object_ptr is the object reference type for base CORBA::Object. Object ref-
erences can be implicitly widened to base interface types, so this is valid:
Echo_ptr echo_ref = // get reference from somewhere
CORBA::Object_ptr base_ref = echo_ref; // widen
As described above, the equality operator== should not be used on object ref-
erences. To test if two object references are equivalent, the member function
_is_equivalent() of the generic object CORBA::Object can be used. Here is
an example of its usage:
Echo_ptr a;
... // initialise a to a valid object reference
Echo_ptr b = a;
CORBA::Boolean true_result = a->_is_equivalent(a);
// Note: the above call is guaranteed to be true
does not consider them equivalent. If you need a strong sense of object identity,
you must implement it with explicit IDL operations.
For each object interface, a skeleton class is generated. In our example, the POA
specification says that the skeleton class for interface Echo is named POA_Echo.
A servant implementation can be written by creating an implementation class
that derives from the skeleton class.
The skeleton class POA_Echo is defined in echo.hh. The relevant section of
the code is reproduced below.
class POA_Echo :
public virtual PortableServer::ServantBase
{
public:
Echo_ptr _this();
The code fragment shows the only member functions that can be used in the
object implementation code. Other member functions are generated for internal
use only. As with the code generated for object references, other POA-based
ORBs will generate code which looks different, but is functionally equivalent to
this.
echoString()
It is through this abstract function that an implementation class provides
the implementation of the echoString() operation. Notice that its signa-
ture is the same as the echoString() function that can be invoked via the
Echo_ptr object reference. This will be the case most of the time, but ob-
ject reference operations for certain parameter types use special helper
classes to facilitate correct memory management.
_this()
The _this() function returns an object reference for the target object,
provided the POA policies permit it. The returned value must be deallo-
cated via CORBA::release(). See section 2.8 for an example of how this
function is used.
You define a class to provide the servant implementation. There is little con-
straint on how you design your implementation class except that it has to inherit
CHAPTER 2. THE BASICS 13
from the skeleton class1 and to implement all the abstract functions defined in
the skeleton class. Each of these abstract functions corresponds to an opera-
tion of the interface. They are the hooks for the ORB to perform upcalls to your
implementation. Here is a simple implementation of the Echo object.
class Echo_i : public POA_Echo
{
public:
inline Echo_i() {}
virtual ~Echo_i() {}
virtual char* echoString(const char* mesg);
};
Storage Responsibilities
String, which is used both as an in argument and the return value of
echoString(), is a variable sized data type. Other examples of variable
sized data types include sequences, type ‘any’, etc. For these data types,
you must be clear about whose responsibility it is to allocate and release
the associated storage. As a rule of thumb, the client (or the caller to the
implementation functions) owns the storage of all in arguments, the ob-
ject implementation (or the callee) must copy the data if it wants to retain
a copy. For out arguments and return values, the object implementation
allocates the storage and passes the ownership to the client. The client
must release the storage when the variables will no longer be used. For
details, see the C++ mapping specification.
Multi-threading
As omniORB is fully multithreaded, multiple threads may perform the same
upcall to your implementation concurrently. It is up to your implementa-
tion to synchronise the threads’ accesses to shared data. In our simple
example, we have no shared data to protect so no thread synchronisation
is necessary.
Alternatively, you can create a POA which has the SINGLE_THREAD_MODEL
Thread Policy. This guarantees that all calls to that POA are processed
sequentially.
1
Rather than deriving from the skeleton class, an alternative is to use a tie template, described
in section 2.11.
CHAPTER 2. THE BASICS 14
Reference Counting
All servant objects are reference counted. The base PortableServer::
ServantBase class from which all servant skeleton classes derive defines
member functions named _add_ref() and _remove_ref()2 . The reference
counting means that an Echo_i instance will be deleted when no more
references to it are held by application code or the POA itself. Note that
this is totally separate from the reference counting which is associated
with object references—a servant object is never deleted due to a CORBA
object reference being released.
Instantiation
Servants are usually instantiated on the heap, i.e. using the new operator.
However, they can also be created on the stack as automatic variables. If
you do that, it is vital to make sure that the servant has been deactivated,
and thus released by the POA, before the variable goes out of scope and is
destroyed.
6 if (CORBA::is_nil(e)) {
7 cerr << "cannot invoke on a nil object reference."
8 << endl;
9 return;
10 }
11
15 dest = e->echoString(src);
16
The hello() function accepts a generic object reference. The object refer-
ence (obj) is narrowed to Echo_ptr. If the object reference returned by Echo::
_narrow() is not nil, the operation echoString() is invoked. Finally, both the
argument to and the return value of echoString() are printed to cout.
The example also illustrates how T_var types are used. As was explained
in the previous section, T_var types take care of storage allocation and release
automatically when variables are reassigned or when the variables go out of
scope.
In line 4, the variable e takes over the storage responsibility of the object
reference returned by Echo::_narrow(). The object reference is released by
the destructor of e. It is called automatically when the function returns. Lines 6
and 15 show how a Echo_var variable is used. As explained earlier, the Echo_var
type can be used interchangeably with the Echo_ptr type.
The argument and the return value of echoString() are stored in CORBA::
String_var variables src and dest respectively. The strings managed by the
variables are deallocated by the destructor of CORBA::String_var. It is called
automatically when the variable goes out of scope (as the function returns). Line
15 shows how CORBA::String_var variables are used. They can be used in place
of a string (for which the mapping is char*)3 . As used in line 12, assigning a
constant string (const char*) to a CORBA::String_var causes the string to be
copied. On the other hand, assigning a char* to a CORBA::String_var, as used
in line 15, causes the latter to assume the ownership of the string4 .
Under the C++ mapping, T_var types are provided for all the non-basic data
types. One should use automatic variables whenever possible both to avoid
memory leaks and to maximise performance. However, when one has to allo-
cate data items on the heap, it is a good practice to use the T_var types to
manage the heap storage.
Having introduced the client and the object implementation, we can now de-
scribe how to link up the two via the ORB and POA. In this section, we describe
an example in which both the client and the object implementation are in the
same address space. In the next two sections, we shall describe the case where
the two are in different address spaces.
The code for this example is reproduced below:
1 int
2 main(int argc, char **argv)
3 {
3
A conversion operator of CORBA::String_var converts a CORBA::String_var to a char*.
4
Please refer to the C++ mapping specification for details of the String_var mapping.
CHAPTER 2. THE BASICS 16
17 hello(myechoref);
18
19 orb->destroy();
20 return 0;
21 }
The example illustrates several important interactions among the ORB, the
POA, the servant, and the client. Here are the details:
Line 4
The ORB is initialised by calling the CORBA::ORB_init() function. The
function uses the optional 3rd argument to determine which ORB should
be returned. Unless you are using omniORB specific features, it is usually
best to leave it out, and get the default ORB. To explicitly ask for omniORB
4.x, this argument must be ‘omniORB4’5 .
CORBA::ORB_init() takes the list of command line arguments and pro-
cesses any that start ‘-ORB’. It removes these arguments from the list, so
application code does not have to deal with them.
If any error occurs during ORB initialisation, such as invalid ORB argu-
ments, or an invalid configuration file, the CORBA::INITIALIZE system ex-
ception is raised.
Lines 6–7
To activate our servant object and make it available to clients, we must reg-
ister it with a POA. In this example, we use the Root POA, rather than cre-
5
For backwards compatibility, the ORB identifiers ‘omniORB2’ and ‘omniORB3’ are also ac-
cepted.
CHAPTER 2. THE BASICS 17
ating any child POAs. The Root POA is found with orb->resolve_initial_
references(), which returns a plain CORBA::Object. In line 7, we narrow
the reference to the right type for a POA.
A POA’s behaviour is governed by its policies. The Root POA has suitable
policies for many simple servers, and closely matches the ‘policies’ used by
omniORB 2’s BOA. See Chapter 11 of the CORBA 2.6 specification[OMG01]
for details of all the POA policies which are available.
Line 9
An instance of the Echo servant is initialised using the new operator. The
PortableServer::Servant_var<> template automatically is analogous to
the T_var types generated by the IDL compiler. It releases our reference
to the servant when it goes out of scope.
Line 10
The servant object is activated in the Root POA using poa->activate_
object(), which returns an object identifier (of type PortableServer::
ObjectId*). The object id must be passed back to various POA operations.
The caller is responsible for freeing the object id, so it is assigned to a _var
type.
Line 12
The object reference is obtained from the servant object by calling its
_this() method. Like all object references, the return value of _this()
must be released by CORBA::release() when it is no longer needed. In
this case, we assign it to a _var type, so the release is implicit at the end
of the function.
One of the important characteristics of an object reference is that it is
completely location transparent. A client can invoke on the object using
its object reference without any need to know whether the servant object
is colocated in the same address space or is in a different address space.
In the case of colocated client and servant, omniORB is able to short-circuit
the client calls so they do not involve IIOP. The calls still go through the
POA, however, so the various POA policies affect local calls in the same
way as remote ones. This optimisation is applicable not only to object ref-
erences returned by _this(), but to any object references that are passed
around within the same address space or received from other address
spaces via remote calls.
CHAPTER 2. THE BASICS 18
Lines 15–16
POAs are initially in the holding state, meaning that incoming requests are
blocked. Lines 15 and 16 acquire a reference to the POA’s POA manager,
and use it to put the POA into the active state. Incoming requests are
now served. Failing to activate the POA is one of the most common
programming mistakes. If your program appears deadlocked, make
sure you activated the POA!
Line 18
At long last, we can call hello() with this object reference. The argument
is widened implicitly to the generic object reference CORBA::Object_ptr.
Line 20
Shutdown the ORB permanently. This call causes the ORB to release all its
resources, e.g. internal threads, and also to deactivate any servant objects
which are currently active. When it deactivates the Echo_i instance, the
servant’s reference count drops to zero, so the servant is deleted.
This call is particularly important when writing a CORBA DLL on Windows
NT that is to be used from ActiveX. If this call is absent, the application
will hang when the CORBA DLL is unloaded.
In this example, the client and the object implementation reside in two different
address spaces. The code of this example is almost the same as the previous
example. The only difference is the extra work which needs to be done to pass
the object reference from the object implementation to the client.
The simplest (and quite primitive) way to pass an object reference between
two address spaces is to produce a stringified version of the object reference
and to pass this string to the client as a command-line argument. The string is
then converted by the client into a proper object reference. This method is used
in this example. In the next example, we shall introduce a better way of passing
the object reference using the CORBA Naming Service.
CHAPTER 2. THE BASICS 19
The main() function of the server side is reproduced below. The full listing
(eg2_impl.cc) can be found at the end of this chapter.
1 int main(int argc, char** argv)
2 {
3 CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);
4
12 obj = myecho->_this();
13 CORBA::String_var sior(orb->object_to_string(obj));
14 cerr << sior << endl;
15
19 orb->run();
20 orb->destroy();
21 return 0;
22 }
}
catch (CORBA::TRANSIENT&) {
... // code to handle transient exception...
}
When omniORB detects an error condition, it may raise a system exception. The
CORBA specification defines a series of exceptions covering most of the error
conditions that an ORB may encounter. The client may choose to catch these
exceptions and recover from the error condition6 . For instance, the code frag-
ment, shown in section 2.9.2, catches the TRANSIENT system exception which
indicates that the object could not be contacted at the time of the call, usually
meaning the server is not running.
All system exceptions inherit from CORBA::SystemException. Unless you
have a truly ancient C++ compiler, a single catch of CORBA::SystemException
will catch all the different system exceptions.
CORBA objects are either transient or persistent. The majority are transient,
meaning that the lifetime of the CORBA object (as contacted through an object
reference) is the same as the lifetime of its servant object. Persistent objects can
live beyond the destruction of their servant object, the POA they were created
in, and even their process. Persistent objects are, of course, only contactable
when their associated server processes are running, and their servants are ac-
tive or can be activated by their POA with a servant manager7 . A reference to
a persistent object can be published, and will remain valid even if the server
process is restarted.
To support persistent objects, the servants must be activated in their POA
with the same object identifier each time. Also, the server must be configured
with the same endpoint details so it is contactable in the same way as previous
invocations. See section 6.6 for details.
A POA’s Lifespan Policy determines whether objects created within it are
transient or persistent. The Root POA has the TRANSIENT policy.
An alternative to creating persistent objects is to register object references
in a naming service and bind them to fixed path names. Clients can bind to the
object implementations at run time by asking the naming service to resolve the
6
If a system exception is not caught, the C++ runtime will call the terminate() function. This
function is defaulted to abort the whole process and on some systems will cause a core file to be
produced.
7
The POA itself can be activated on demand with an adapter activator.
CHAPTER 2. THE BASICS 21
path names to the object references. CORBA defines a standard naming service,
which is a component of the Common Object Services (COS) [OMG98], that can
be used for this purpose. The next section describes an example of how to use
the COS Naming Service.
In this example, the object implementation uses the Naming Service [OMG98]
to pass on the object reference to the client. This method is often more practical
than using stringified object references. The full listing of the object implemen-
tation (eg3_impl.cc) and the client (eg3_clt.cc) can be found at the end of this
chapter.
The names used by the Naming service consist of a sequence of name com-
ponents. Each name component has an id and a kind field, both of which are
strings. All name components except the last one are bound to a naming context.
A naming context is analogous to a directory in a filing system: it can contain
names of object references or other naming contexts. The last name component
is bound to an object reference.
Sequences of name components can be represented as a flat string, using ‘.’
to separate the id and kind fields, and ‘/’ to separate name components from each
other8 . In our example, the Echo object reference is bound to the stringified
name ‘test.my_context/Echo.Object’.
The kind field is intended to describe the name in a syntax-independent way.
The naming service does not interpret, assign, or manage these values. How-
ever, both the name and the kind attribute must match for a name lookup to
succeed. In this example, the kind values for test and Echo are chosen to be
‘my_context’ and ‘Object’ respectively. This is an arbitrary choice as there is
no standardised set of kind values.
The initial contact with the Naming Service can be established via the root con-
text. The object reference to the root context is provided by the ORB and can be
obtained by calling resolve_initial_references(). The following code frag-
ment shows how it is used:
CORBA::ORB_ptr orb = CORBA::ORB_init(argc,argv);
CORBA::Object_var obj = orb->resolve_initial_references("NameService");
8
There are escaping rules to cope with id and kind fields which contain ‘.’ and ‘/’ characters.
See chapter 7 of this manual, and chapter 3 of the CORBA services specification, as updated for
the Interoperable Naming Service [OMG00].
CHAPTER 2. THE BASICS 22
CosNaming::NamingContext_var rootContext;
rootContext = CosNaming::NamingContext::_narrow(obj);
Remember from section 1.2, omniORB constructs its internal list of initial
references at initialisation time using the information provided in the configu-
ration file omniORB.cfg, or given on the command line. If this file is not present,
the internal list will be empty and resolve_initial_references() will raise a
CORBA::ORB::InvalidName exception.
It is beyond the scope of this chapter to describe in detail the Naming Service
interface. You should consult the CORBA services specification [OMG98] (chap-
ter 3). The code listed in eg3_impl.cc and eg3_clt.cc are good examples of
how the service can be used.
For interface Echo, the name of its tie implementation template is POA_Echo_
tie. The template parameter is the servant class that contains an implementa-
tion of each of the operations defined in the interface. As used above, the tie
template takes ownership of the Echo_i instance, and deletes it when the tie
CHAPTER 2. THE BASICS 23
object goes out of scope. The tie constructor has an optional boolean argument
(defaulted to true) which indicates whether or not it should delete the servant
object. For full details of using tie templates, see the CORBA C++ mapping
specification.
CHAPTER 2. THE BASICS 24
2.12.1 eg1.cc
#include <echo.hh>
#ifdef HAVE_STD
# include <iostream>
using namespace std;
#else
# include <iostream.h>
#endif
//////////////////////////////////////////////////////////////////////
if( CORBA::is_nil(e) ) {
cerr << "hello: The object reference is nil!" << endl;
return;
}
cout << "I said, \"" << (char*)src << "\"." << endl
<< "The Echo object replied, \"" << (char*)dest <<"\"." << endl;
}
//////////////////////////////////////////////////////////////////////
// Activate the object. This tells the POA that this object is
// ready to accept requests.
PortableServer::ObjectId_var myechoid = poa->activate_object(myecho);
pman->activate();
2.12.2 eg2_impl.cc
#include <echo.hh>
#ifdef HAVE_STD
# include <iostream>
using namespace std;
#else
# include <iostream.h>
#endif
//////////////////////////////////////////////////////////////////////
2.12.3 eg2_clt.cc
#include <echo.hh>
#ifdef HAVE_STD
# include <iostream>
using namespace std;
#else
# include <iostream.h>
#endif
cout << "I said, \"" << (char*)src << "\"." << endl
<< "The Echo object replied, \"" << (char*)dest <<"\"." << endl;
}
//////////////////////////////////////////////////////////////////////
if (argc != 2) {
cerr << "usage: eg2_clt <object reference>" << endl;
return 1;
}
if (CORBA::is_nil(echoref)) {
cerr << "Can’t narrow reference to type Echo (or it was nil)." << endl;
return 1;
}
orb->destroy();
}
catch (CORBA::TRANSIENT&) {
cerr << "Caught system exception TRANSIENT -- unable to contact the "
<< "server." << endl;
}
catch (CORBA::SystemException& ex) {
cerr << "Caught a CORBA::" << ex._name() << endl;
}
catch (CORBA::Exception& ex) {
cerr << "Caught CORBA::Exception: " << ex._name() << endl;
}
return 0;
}
CHAPTER 2. THE BASICS 31
2.12.4 eg3_impl.cc
#include <echo.hh>
#ifdef HAVE_STD
# include <iostream>
using namespace std;
#else
# include <iostream.h>
#endif
//////////////////////////////////////////////////////////////////////
int
main(int argc, char **argv)
{
try {
CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);
CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
CORBA::String_var sior(orb->object_to_string(obj));
cout << sior << endl;
if (!bindObjectToName(orb, obj))
return 1;
orb->run();
}
catch (CORBA::SystemException& ex) {
cerr << "Caught CORBA::" << ex._name() << endl;
}
catch (CORBA::Exception& ex) {
cerr << "Caught CORBA::Exception: " << ex._name() << endl;
}
return 0;
}
//////////////////////////////////////////////////////////////////////
static CORBA::Boolean
bindObjectToName(CORBA::ORB_ptr orb, CORBA::Object_ptr objref)
{
CosNaming::NamingContext_var rootContext;
try {
// Obtain a reference to the root context of the Name service:
CHAPTER 2. THE BASICS 33
try {
// Bind a context called "test" to the root context:
CosNaming::Name contextName;
contextName.length(1);
contextName[0].id = (const char*) "test"; // string copied
contextName[0].kind = (const char*) "my_context"; // string copied
// Note on kind: The kind field is used to indicate the type
// of the object. This is to avoid conventions such as that used
// by files (name.type -- e.g. test.ps = postscript etc.)
CosNaming::NamingContext_var testContext;
try {
// Bind the context to root.
testContext = rootContext->bind_new_context(contextName);
}
catch(CosNaming::NamingContext::AlreadyBound& ex) {
// If the context already exists, this exception will be raised.
// In this case, just resolve the name and assign testContext
// to the object returned:
CORBA::Object_var obj = rootContext->resolve(contextName);
testContext = CosNaming::NamingContext::_narrow(obj);
if (CORBA::is_nil(testContext)) {
cerr << "Failed to narrow naming context." << endl;
return 0;
}
CHAPTER 2. THE BASICS 34
try {
testContext->bind(objectName, objref);
}
catch(CosNaming::NamingContext::AlreadyBound& ex) {
testContext->rebind(objectName, objref);
}
// Note: Using rebind() will overwrite any Object previously bound
// to /test/Echo with obj.
// Alternatively, bind() can be used, which will raise a
// CosNaming::NamingContext::AlreadyBound exception if the name
// supplied is already bound to an object.
}
catch (CORBA::TRANSIENT& ex) {
cerr << "Caught system exception TRANSIENT -- unable to contact the "
<< "naming service." << endl
<< "Make sure the naming server is running and that omniORB is "
<< "configured correctly." << endl;
return 0;
}
catch (CORBA::SystemException& ex) {
cerr << "Caught a CORBA::" << ex._name()
<< " while using the naming service." << endl;
return 0;
}
return 1;
}
CHAPTER 2. THE BASICS 35
2.12.5 eg3_clt.cc
#include <echo.hh>
#ifdef HAVE_STD
# include <iostream>
using namespace std;
#else
# include <iostream.h>
#endif
cerr << "I said, \"" << (char*)src << "\"." << endl
<< "The Echo object replied, \"" << (char*)dest <<"\"." << endl;
}
CHAPTER 2. THE BASICS 36
//////////////////////////////////////////////////////////////////////
int
main (int argc, char **argv)
{
try {
CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);
orb->destroy();
}
catch (CORBA::TRANSIENT&) {
cerr << "Caught system exception TRANSIENT -- unable to contact the "
<< "server." << endl;
}
catch (CORBA::SystemException& ex) {
cerr << "Caught a CORBA::" << ex._name() << endl;
}
catch (CORBA::Exception& ex) {
cerr << "Caught CORBA::Exception: " << ex._name() << endl;
}
return 0;
}
//////////////////////////////////////////////////////////////////////
static CORBA::Object_ptr
getObjectReference(CORBA::ORB_ptr orb)
{
CosNaming::NamingContext_var rootContext;
try {
// Obtain a reference to the root context of the Name service:
CORBA::Object_var obj;
obj = orb->resolve_initial_references("NameService");
if (CORBA::is_nil(rootContext)) {
CHAPTER 2. THE BASICS 37
cerr << "Failed to narrow the root naming context." << endl;
return CORBA::Object::_nil();
}
}
catch (CORBA::NO_RESOURCES&) {
cerr << "Caught NO_RESOURCES exception. You must configure omniORB "
<< "with the location" << endl
<< "of the naming service." << endl;
return CORBA::Object::_nil();
}
catch (CORBA::ORB::InvalidName& ex) {
// This should not happen!
cerr << "Service required is invalid [does not exist]." << endl;
return CORBA::Object::_nil();
}
try {
// Resolve the name to an object reference.
return rootContext->resolve(name);
}
catch (CosNaming::NamingContext::NotFound& ex) {
// This exception is thrown if any of the components of the
// path [contexts or the object] aren’t found:
cerr << "Context not found." << endl;
}
catch (CORBA::TRANSIENT& ex) {
cerr << "Caught system exception TRANSIENT -- unable to contact the "
<< "naming service." << endl
<< "Make sure the naming server is running and that omniORB is "
<< "configured correctly." << endl;
}
catch (CORBA::SystemException& ex) {
cerr << "Caught a CORBA::" << ex._name()
<< " while using the naming service." << endl;
}
CHAPTER 2. THE BASICS 38
return CORBA::Object::_nil();
}
CHAPTER 2. THE BASICS 39
2.12.6 eg3_tieimpl.cc
#include <echo.hh>
#ifdef HAVE_STD
# include <iostream>
using namespace std;
#else
# include <iostream.h>
#endif
class Echo_i {
public:
inline Echo_i() {}
inline ~Echo_i() {}
char* echoString(const char* mesg);
};
return CORBA::string_dup(mesg);
}
//////////////////////////////////////////////////////////////////////
orb->run();
}
catch (CORBA::SystemException& ex) {
cerr << "Caught CORBA::" << ex._name() << endl;
}
catch (CORBA::Exception& ex) {
cerr << "Caught CORBA::Exception: " << ex._name() << endl;
}
return 0;
}
//////////////////////////////////////////////////////////////////////
CHAPTER 2. THE BASICS 41
static CORBA::Boolean
bindObjectToName(CORBA::ORB_ptr orb, CORBA::Object_ptr objref)
{
CosNaming::NamingContext_var rootContext;
try {
// Obtain a reference to the root context of the Name service:
CORBA::Object_var obj = orb->resolve_initial_references("NameService");
try {
// Bind a context called "test" to the root context:
CosNaming::Name contextName;
contextName.length(1);
contextName[0].id = (const char*) "test"; // string copied
contextName[0].kind = (const char*) "my_context"; // string copied
// Note on kind: The kind field is used to indicate the type
// of the object. This is to avoid conventions such as that used
// by files (name.type -- e.g. test.ps = postscript etc.)
CosNaming::NamingContext_var testContext;
try {
// Bind the context to root.
testContext = rootContext->bind_new_context(contextName);
}
catch(CosNaming::NamingContext::AlreadyBound& ex) {
// If the context already exists, this exception will be raised.
CHAPTER 2. THE BASICS 42
try {
testContext->bind(objectName, objref);
}
catch(CosNaming::NamingContext::AlreadyBound& ex) {
testContext->rebind(objectName, objref);
}
// Note: Using rebind() will overwrite any Object previously bound
// to /test/Echo with obj.
// Alternatively, bind() can be used, which will raise a
// CosNaming::NamingContext::AlreadyBound exception if the name
// supplied is already bound to an object.
}
catch (CORBA::TRANSIENT& ex) {
cerr << "Caught system exception TRANSIENT -- unable to contact the "
<< "naming service." << endl
<< "Make sure the naming server is running and that omniORB is "
<< "configured correctly." << endl;
return 0;
}
catch (CORBA::SystemException& ex) {
cerr << "Caught a CORBA::" << ex._name()
<< " while using the naming service." << endl;
return 0;
}
return 1;
}
Chapter 3
Now that you are familiar with the basics, it is important to familiarise yourself
with the standard IDL to C++ language mapping. The mapping is described
in detail in [OMG03]. If you have not done so, you should obtain a copy of the
document and use that as the programming guide to omniORB.
The specification is not an easy read. The alternative is to use one of the
books on CORBA programming. For instance, Henning and Vinoski’s ‘Advanced
CORBA Programming with C++’ [HV99] includes many example code fragments
to illustrate how to use the C++ mapping.
Before the Portable Object Adapter (POA) specification, many of the details of
how servant objects should be implemented and registered with the system were
unspecified, so server-side code was not portable between ORBs. The POA spec-
ification rectifies that. For compatibility, omniORB 4 still supports the old omni-
ORB 2.x BOA mapping, but you should always use the POA mapping for new
code. BOA code and POA code can coexist within a single program.
If you use the -WbBOA option to omniidl, it will generate skeleton code with
(nearly) the same interface as the old omniORB 2 BOA mapping, as well as code
to be used with the POA. Note that since the major problem with the BOA spec-
ification was that server code was not portable between ORBs, it is unlikely
that omniORB’s BOA compatibility will help you much if you are moving from a
different BOA-based ORB.
The BOA compatibility permits the majority of BOA code to compile without
difficulty. However, there are a number of constructs which relied on omniORB
2 implementation details which no longer work.
• omniORB 2 did not use distinct types for object references and servants,
and often accepted a pointer to a servant when the CORBA specification
43
CHAPTER 3. C++ LANGUAGE MAPPING 44
says it should only accept an object reference. Such code will not compile
under omniORB 4.
• It used to be the case that the skeleton class for interface I (_sk_I) was
derived from class I. This meant that the names of any types declared in
the interface were available in the scope of the skeleton class. This is no
longer true. If you have an interface:
interface I {
struct S {
long a,b;
};
S op();
};
omniORB 4.2 is source-code compatible with omniORB 4.0, with four exceptions:
2. omniORB 4.0 had an option for Any extraction semantics that was com-
patible with omniORB 2.7, where ownership of extracted values was not
maintained by the Any. That option is no longer available.
4. The C++ mapping contains Any insertion operators for sequence types
that are passed by pointer, which cause the Any to take ownership of the
inserted sequence. In omniORB 4.0 and earlier, the sequence was imme-
diately marshalled into the Any’s internal buffer, and the sequence was
deleted. In omniORB 4.1, the sequence pointer is stored by the Any, and
the sequence is deleted later when the Any is destroyed.
For most uses, this change is not visible to application code. However, if
a sequence is constructed using an application-supplied buffer with the
release flag set to false (meaning that the application continues to own
CHAPTER 3. C++ LANGUAGE MAPPING 46
the buffer), it is now important that the buffer is not deleted or modified
while the Any exists, since the Any continues to refer to the buffer contents.
This change means that code that worked with omniORB 4.0 may now fail
with 4.1, with the Any seeing modified data or the process crashing due
to accessing deleted data. To avoid this situation, use the alternative Any
insertion operator using a const reference, which copies the sequence.
omniORB 4.2 is source-code compatible with omniORB 4.1 with one exception:
1. When omniORB 4.1 and earlier detected a timeout condition, they would
throw the CORBA::TRANSIENT system exception. omniORB 4.2 supports the
CORBA::TIMEOUT system exception that was introduced with the CORBA
Messaging specification. Application code that caught CORBA::TRANSIENT
to handle timeout situations should be updated to catch CORBA::TIMEOUT
instead. Alternatively, to avoid code changes, omniORB can be configured
to throw CORBA::TRANSIENT for timeouts, by setting the throwTransient
OnTimeout parameter to 1. See section 4.4.
Chapter 4
omniORB has a wide range of parameters that can be configured. They can be
set in the configuration file / Windows registry, as environment variables, on the
command line, or within a proprietary extra argument to CORBA::ORB_init().
A few parameters can be configured at run time. This chapter lists all the con-
figuration parameters, and how they are used.
2. ORB_init() options
3. Environment variables
5. Built-in defaults
Command line arguments take the form ‘-ORBparameter’, and usually expect
another argument. An example is ‘-ORBtraceLevel 10’.
47
CHAPTER 4. OMNIORB CONFIGURATION AND API 48
Environment variables consist of the parameter name prefixed with ‘ORB’. Using
bash, for example
export ORBtraceLevel=10
The best way to understand the format of the configuration file is to look at the
sample.cfg file in the omniORB distribution. Each parameter is set on a single
line like
traceLevel = 10
Some parameters can have more than one value, in which case the parameter
name may be specified more than once, or you can leave it out:
InitRef = NameService=corbaname::host1.example.com
= InterfaceRepository=corbaloc::host2.example.com:1234/IfR
traceLevel default = 1
omniORB can output tracing and diagnostic messages to the standard error
stream. The following levels are defined:
The trace level is cumulative, so at level 40, all trace messages are output.
traceExceptions default = 0
If the traceExceptions parameter is set true, all system exceptions are logged
as they are thrown, along with details about where the exception is thrown from.
This parameter is enabled by default if the traceLevel is set to 10 or more.
traceInvocations default = 0
If the traceInvocations parameter is set true, all local and remote invoca-
tions are logged, in addition to any logging that may have been selected with
traceLevel.
traceInvocationReturns default = 0
traceThreadId default = 1
If traceThreadId is set true, all trace messages are prefixed with the id of the
thread outputting the message. This can be handy for making sense of multi-
CHAPTER 4. OMNIORB CONFIGURATION AND API 50
traceTime default = 1
If traceTime is set true, all trace messages are prefixed with the time. This is
useful, but on some platforms it adds a very large overhead, so it can be turned
off.
traceFile default =
Log messages can be sent somewhere other than stderr by registering a logging
function which is called with the text of each log message:
namespace omniORB {
typedef void (*logFunction)(const char*);
void setLogFunction(logFunction f);
};
The log function must not make any CORBA calls, since that could lead to in-
finite recursion as outputting a log message caused other log messages to be
generated, and so on.
These options control miscellaneous features that affect the whole ORB runtime.
dumpConfiguration default = 0
If set true, the ORB dumps the values of all configuration parameters at start-
up.
CHAPTER 4. OMNIORB CONFIGURATION AND API 51
scanGranularity default = 5
The native code set the application is using for char and string. See chapter 8.
The native code set the application is using for wchar and wstring. See chap-
ter 8.
The default code set used for char and string if the server does not specify it
in its IORs. See chapter 8.
The default code set used for wchar and wstring if the server does not specify
it in its IORs. See chapter 8.
copyValuesInLocalCalls default = 1
Determines whether valuetype parameters in local calls are copied or not. See
chapter 11.
abortOnInternalError default = 0
If this is set true, internal fatal errors will abort immediately, rather than throw-
ing the omniORB::fatalException exception. This can be helpful for tracking
down bugs, since it leaves the call stack intact.
abortOnNativeException default = 0
maxSocketSend
CHAPTER 4. OMNIORB CONFIGURATION AND API 52
maxSocketRecv
On some platforms, calls to send() and recv() have a limit on the buffer size that
can be used. These parameters set the limits in bytes that omniORB uses when
sending / receiving bulk data.
The default values are platform specific. It is unlikely that you will need to
change the values from the defaults.
The minimum valid limit is 1KB, 1024 bytes.
validateUTF8 default = 0
Used to specify the way the client contacts a server, depending on the server’s
address. See section 6.7.1 for details.
clientCallTimeOutPeriod default = 0
Call timeout in milliseconds for the client side. If a call takes longer than the
specified number of milliseconds, the ORB closes the connection to the server
and raises a TRANSIENT exception. A value of zero means no timeout; calls can
block for ever. See section 6.3.1 for more information about timeouts.
Note: omniORB 3 had timeouts specified in seconds; omniORB 4.0 and later use
milliseconds for timeouts.
clientConnectTimeOutPeriod default = 0
The timeout that is used in the case that a new network connection is established
to the server. A value of zero means that the normal call timeout is used. See
section 6.3.1 for more information about timeouts.
supportPerThreadTimeOut default = 0
If this parameter is set true, timeouts can be set on a per thread basis, as well
as globally and per object. Checking per-thread storage has a noticeable per-
formance impact, so it is turned off by default.
resetTimeoutOnRetries default = 0
If true, the call timeout is reset when an exception handler causes a call to be
retried. If false, the timeout is not reset, and therefore applies to the call as a
whole, rather than to each individual call attempt.
throwTransientOnTimeout default = 0
omniORB 4.2 supports the CORBA::TIMEOUT exception that is part of the CORBA
Messaging specification. By default, that is the exception thrown when timeouts
occur. Previous omniORB releases did not have the CORBA::TIMEOUT exception,
and instead used CORBA::TRANSIENT. If this parameter is set true, omniORB
follows the old behaviour of throwing CORBA::TRANSIENT when a timeout occurs.
Idle timeout in seconds for outgoing (i.e. client initiated) connections. If a con-
nection has been idle for this amount of time, the ORB closes it. See section 6.5.
maxGIOPConnectionPerServer default = 5
The maximum number of concurrent connections the ORB will open to a single
server. If multiple threads on the client call the same server, the ORB opens
additional connections to the server, up to the maximum specified by this pa-
rameter. If the maximum is reached, threads are blocked until a connection
becomes free for them to use.
oneCallPerConnection default = 1
When this parameter is set to true (the default), the ORB will only send a single
call on a connection at a time. If multiple client threads invoke on the same
server, multiple connections are opened, up to the limit specified by maxGIOP
ConnectionPerServer. With this parameter set to false, the ORB will allow
concurrent calls on a single connection. This saves connection resources, but re-
quires slightly more management work for both client and server. Some server-
side ORBs (including omniORB versions before 4.0) serialise all incoming calls
on a single connection.
maxInterleavedCallsPerConnection default = 5
offerBiDirectionalGIOP default = 0
If set true, the client will indicate to servers that it is willing to accept callbacks
on client-initiated connections using bidirectional GIOP, provided the relevant
POA policies are set. See section 6.8.
diiThrowsSysExceptions default = 0
verifyObjectExistsAndType default = 1
By default, omniORB uses the GIOP LOCATE_REQUEST message to verify the ex-
istence of an object prior to the first invocation. In the case that the full type
of the object is not known, it instead calls the _is_a() operation to check the
object’s type. Some ORBs have bugs that mean one or other of these operations
CHAPTER 4. OMNIORB CONFIGURATION AND API 55
fail. Setting this parameter false prevents omniORB from making these calls.
giopTargetAddressMode default = 0
GIOP 1.2 supports three addressing modes for contacting objects. This param-
eter selects the mode that omniORB uses. A value of 0 means GIOP::KeyAddr;
1 means GIOP::ProfileAddr; 2 means GIOP::ReferenceAddr.
immediateAddressSwitch default = 0
If true, the client will immediately switch to use a new address to contact an
object after a failure. If false (the default), the current address will be retried
in certain circumstances.
resolveNamesForTransportRules default = 1
If true, names in IORs will be resolved when evaluating client transport rules,
and remembered from then on; if false, names will not be resolved until connect
time. Client transport rules based on IP address will therefore not match, but
some platforms can use external knowledge to pick the best address to use if
given a name to connect to.
retainAddressOrder default = 1
For IORs with multiple addresses, determines how the address to connect to
is chosen. When first establishing a connection, the addresses are ordered ac-
cording to the client transport rules (after resolving names if resolveNamesFor
TransportRules is true), and the addresses are tried in priority order until one
connects successfully. For as long as there is at least one connection open to
the address, new connections continue to use the same address.
After a failure, or after all open connections have been scavenged and closed,
this parameter determines the address used to reconnect on the next call. If this
parameter is true (the default), the address order and chosen address within the
order is remembered; if false, a new connection attempt causes re-evaluation
of the order (in case name resolutions change), and the highest priority address
is tried first.
If set, this parameter indicates the hostname to use for look-ups using the obso-
lete Sun bootstrap agent. This mechanism is superseded by the interoperable
naming service.
CHAPTER 4. OMNIORB CONFIGURATION AND API 56
GIOP 1.0 and 1.1 have a request header field named ‘principal’, which contains
a sequence of octets. It was never defined what it should mean, and its use is
now deprecated; GIOP 1.2 has no such field. Some systems (e.g. Gnome) use
the principal field as a primitive authentication scheme. This parameter sets the
data omniORB uses in the principal field. The default is an empty sequence.
These options determine the end-points the ORB should listen on, and the details
that should be published in IORs. See chapter 6 for details.
Configure the rules about whether a server should accept an incoming connec-
tion from a client. See section 6.7.2 for details.
serverCallTimeOutPeriod default = 0
This timeout is used to catch the situation that the server starts receiving a
request, but the end of the request never comes. If a calls takes longer than
the specified number of milliseconds to arrive, the ORB shuts the connection. A
value of zero means never timeout.
Idle timeout in seconds for incoming connections. If a connection has been idle
for this amount of time, the ORB closes it. See section 6.5.
threadPerConnectionPolicy default = 1
CHAPTER 4. OMNIORB CONFIGURATION AND API 57
If true (the default), the ORB dedicates one server thread to each incoming
connection. Setting it false means the server should use a thread pool.
The maximum number of threads the server will allocate to do various tasks, in-
cluding dispatching calls in the thread pool mode. This number does not include
threads dispatched under the thread per connection server mode.
If thread pooling was started because the number of connections hit the upper
limit, this parameter determines when thread per connection should start again.
threadPoolWatchConnection default = 1
After dispatching an upcall in thread pool mode, the thread that has just per-
formed the call can watch the connection for a short time before returning to
the pool. This leads to less thread switching for a series of calls from a single
client, but is less fair if there are concurrent clients. The connection is watched
if the number of threads concurrently handling the connection is less than or
equal to the value of this parameter. i.e. if the parameter is zero, the connection
is never watched; if it is 1, the last thread managing a connection watches it; if
2, the connection is still watched if there is one other thread still in an upcall
for the connection, and so on. See section 6.4.2.
For each endpoint, the ORB allocates a thread to watch for new connections and
to monitor existing connections for calls that should be handed by the thread
pool. The thread blocks in select() or similar for a period, after which it re-
scans the lists of connections it should watch. This parameter is specified in
microseconds.
connectionWatchImmediate default = 0
acceptBiDirectionalGIOP default = 0
(Unix platforms only). Selects the location used to store Unix domain sockets.
The ‘%u’ is expanded to the user name.
(Unix platforms only). Determines the octal permission bits for Unix domain
sockets. By default, all users can connect to a server, just as with TCP.
supportCurrent default = 1
objectTableSize default = 0
CHAPTER 4. OMNIORB CONFIGURATION AND API 59
Hash table size of the Active Object Map. If this is zero, the ORB uses a dy-
namically resized open hash table. This is normally the best option, but it leads
to less predictable performance since any operation which adds or removes a
table entry may trigger a resize. If set to a non-zero value, the hash table has
the specified number of entries, and is never resized. Note that the hash table
is open, so this does not limit the number of active objects, just how efficiently
they can be located.
poaHoldRequestTimeout default = 0
If a POA is put in the HOLDING state, calls to it will be timed out after the specified
number of milliseconds, by raising a CORBA::TIMEOUT exception. Zero means no
timeout.
poaUniquePersistentSystemIds default = 1
The POA specification requires that object ids in POAs with the PERSISTENT
and SYSTEM_ID policies are unique between instantiations of the POA. Older
versions of omniORB did not comply with that, and reused object ids. With this
value true, the POA has the correct behaviour; with false, the POA uses the
old scheme for compatibility.
idleThreadTimeout default = 10
When a thread created by omniORB becomes idle, it is kept alive for a while, in
case a new thread is required. Once a thread has been idle for the number of
seconds specified in this parameter, it exits.
supportBootstrapAgent default = 0
There is one server-side parameter that must be set with an API function, rather
than a normal configuration parameter:
namespace omniORB {
void setMainThread();
};
POAs with the MAIN_THREAD policy dispatch calls on the ‘main’ thread. By de-
fault, omniORB assumes that the thread that initialised the omnithread library
is the ‘main’ thread. To choose a different thread, call this function from the
desired ‘main’ thread. The calling thread must have an omni_thread associated
CHAPTER 4. OMNIORB CONFIGURATION AND API 60
These options control omniORB’s use of GIOP, and cover some areas where omni-
ORB can work around buggy behaviour by other ORBs.
Choose the maximum GIOP version the ORB should support. Valid values are
1.0, 1.1 and 1.2.
The largest message, in bytes, that the ORB will send or receive, to avoid re-
source starvation. If the limit is exceeded, a MARSHAL exception is thrown. The
size must be >= 8192.
strictIIOP default = 1
lcdMode default = 0
If true, select ‘Lowest Common Denominator’ mode. This disables various IIOP
and GIOP features that are known to cause problems with some ORBs.
tcAliasExpand default = 0
This flag is used to indicate whether TypeCodes associated with Anys should
have aliases removed. This functionality is included because some ORBs will
not recognise an Any containing a TypeCode with aliases to be the same as the
actual type contained in the Any. There is a performance penalty when inserting
into an Any if tcAliasExpand is set to 1.
useTypeCodeIndirections default = 1
CHAPTER 4. OMNIORB CONFIGURATION AND API 61
TypeCode Indirections reduce the size of marshalled TypeCodes, and are essen-
tial for recursive types, but some old ORBs do not support them. Setting this
flag to false prevents the use of indirections (and, therefore, prevents the use
of recursive TypeCodes).
acceptMisalignedTcIndirections default = 0
By default, all system exceptions that are raised during an operation invoca-
tion, with the exception of some cases of CORBA::TRANSIENT, are propagated
to the application code. Some applications may prefer to trap these exceptions
within the proxy objects so that the application logic does not have to deal with
the error condition. For example, when a CORBA::COMM_FAILURE is received, an
application may just want to retry the invocation until it finally succeeds. This
approach is useful for objects that are persistent and have idempotent opera-
tions.
omniORB provides a set of functions to install exception handlers. Once
they are installed, proxy objects will call these handlers when the associated
system exceptions are raised by the ORB runtime. Handlers can be installed
for CORBA::TRANSIENT, CORBA::TIMEOUT, CORBA::COMM_FAILURE and CORBA::
SystemException. This last handler covers all system exceptions other than
the three specific ones covered by the first three handlers. An exception han-
dler can be installed for individual proxy objects, or it can be installed for all
proxy objects in the address space.
omniORB makes extensive use of exception minor codes to indicate the specific
circumstances surrounding a system exception. The file include/omniORB4/
minorCode.h contains definitions of all the minor codes used in omniORB, cov-
ering codes allocated in the CORBA specification, and ones specific to omni-
ORB. In compilers with namespace support, the minor code constants appear in
namespace omni; otherwise they are in the global scope.
Applications can use minor codes to adjust their behaviour according to the
condition, e.g.
CHAPTER 4. OMNIORB CONFIGURATION AND API 62
try {
...
}
catch (CORBA::TRANSIENT& ex) {
if (ex.minor() == omni::TRANSIENT_ConnectFailed) {
// retry with a different object reference...
}
else {
// print an error message...
}
}
3. The client caches the new location and retries to the new location.
4. Time passes...
5. The client tries to invoke on the object again, using the cached, forwarded
location.
7. The ORB runtime resets the location cache and throws a TRANSIENT excep-
tion with minor code TRANSIENT_FailedOnForwarded.
In this situation, the default TRANSIENT exception handler retries the call,
using the object’s original location. If the retry results in another LOCATION_
FORWARD, to the same or a different location, and that forwarded location fails
immediately, the TRANSIENT exception will occur again, and the pattern will re-
peat. With repeated exceptions, the handler starts adding delays before retries,
with exponential back-off.
In all other circumstances, the default TRANSIENT handler just passes the
exception on to the caller.
Applications can override the default behaviour by installing their own ex-
ception handler. The API to do so is summarised below:
CHAPTER 4. OMNIORB CONFIGURATION AND API 63
namespace omniORB {
typedef CORBA::Boolean
(*transientExceptionHandler_t)(void* cookie,
CORBA::ULong n_retries,
const CORBA::TRANSIENT& ex);
void
installTransientExceptionHandler(void* cookie,
transientExceptionHandler_t fn);
void
installTransientExceptionHandler(CORBA::Object_ptr obj,
void* cookie,
transientExceptionHandler_t fn);
}
void installhandlers()
{
omniORB::installTransientExceptionHandler(0, my_transient_handler1);
// All proxy objects will call my_transient_handler1 from now on.
omniORB::installTransientExceptionHandler(myobj, 0, my_transient_handler2);
// The proxy object of myobj will call my_transient_handler2 from now on.
}
4.7.3 CORBA::TIMEOUT
When a call timeout occurs, by default the ORB throws CORBA::TIMEOUT. The
default behaviour of the proxy objects is to propagate this exception to the ap-
plication. Applications can override the default behaviour by installing their own
exception handlers. The API to do so is summarised below:
typedef CORBA::Boolean
(*timeoutExceptionHandler_t)(void* cookie,
CORBA::ULong n_retries,
const CORBA::TIMEOUT& ex);
void
installTimeoutExceptionHandler(void* cookie,
timeoutExceptionHandler_t fn);
void
installTimeoutExceptionHandler(CORBA::Object_ptr obj,
void* cookie,
timeoutExceptionHandler_t fn);
4.7.4 CORBA::COMM_FAILURE
If the ORB has successfully contacted a server at some point, and access to it
subsequently fails (and the condition for TRANSIENT described above does not
occur), the ORB raises a CORBA::COMM_FAILURE exception.
The default behaviour of the proxy objects is to propagate this exception to
the application. Applications can override the default behaviour by installing
their own exception handlers. The API to do so is summarised below:
typedef CORBA::Boolean
(*commFailureExceptionHandler_t)(void* cookie,
CORBA::ULong n_retries,
const CORBA::COMM_FAILURE& ex);
void
installCommFailureExceptionHandler(void* cookie,
commFailureExceptionHandler_t fn);
void
installCommFailureExceptionHandler(CORBA::Object_ptr obj,
void* cookie,
commFailureExceptionHandler_t fn);
4.7.5 CORBA::SystemException
void
installSystemExceptionHandler(void* cookie,
systemExceptionHandler_t fn);
CHAPTER 4. OMNIORB CONFIGURATION AND API 66
void
installSystemExceptionHandler(CORBA::Object_ptr obj,
void* cookie,
systemExceptionHandler_t fn);
New in omniORB 4.2, each of the exception handlers described above also has an
‘extended’ form in which the exception handler takes two additional parameters,
the object reference being invoked upon, and a string containing the name of
the operation invoked. e.g.:
namespace omniORB {
typedef CORBA::Boolean
(*transientExceptionHandlerExt_t)(void* cookie,
CORBA::ULong n_retries,
const CORBA::TRANSIENT& ex,
CORBA::Object_ptr obj,
const char* op);
void
installTransientExceptionHandlerExt(void* cookie,
transientExceptionHandlerExt_t fn);
void
installTransientExceptionHandlerExt(CORBA::Object_ptr obj,
void* cookie,
transientExceptionHandlerExt_t fn);
}
Note that the operation parameter can sometimes be null. By default, omni-
ORB sends a LocateRequest message prior to the first operation invocation on
an object reference. That LocateRequest is subject to the same exception han-
dling mechanism as a normal operation invocation, but it is represented with
a null operation name. Exception handler code that uses the operation name
must correctly handle a null operation name pointer.
-bback-end Run the specified back-end. For the C++ ORB, use -bcxx.
-Dname[=value] Define name for the preprocessor.
-Uname Undefine name for the preprocessor.
-Idir Include dir in the preprocessor search path.
-E Only run the preprocessor, sending its output to stdout.
-Ycmd Use cmd as the preprocessor, rather than the normal C preprocessor.
-N Do not run the preprocessor.
-T Use a temporary file, not a pipe, for preprocessor output.
-Wparg[,arg. . . ] Send arguments to the preprocessor.
-Wbarg[,arg. . . ] Send arguments to the back-end.
-nf Do not warn about unresolved forward declarations.
-k Keep comments after declarations, to be used by some back-ends.
-K Keep comments before declarations, to be used by some back-ends.
-Cdir Change directory to dir before writing output files.
-d Dump the parsed IDL then exit, without running a back-end.
-pdir Use dir as a path to find omniidl back-ends.
-V Print version information then exit.
68
CHAPTER 5. THE IDL COMPILER 69
Most of these options are self explanatory, but some are not so obvious.
IDL is processed by the C preprocessor before omniidl parses it. omniidl always
uses the GNU C preprocessor (which it builds with the name omnicpp). The
-D, -U, and -I options are just sent to the preprocessor. Note that the current
directory is not on the include search path by default—use ‘-I.’ for that. The -Y
option can be used to specify a different preprocessor to omnicpp. Beware that
line directives inserted by other preprocessors are likely to confuse omniidl.
The output from the C preprocessor is normally fed to the omniidl parser through
a pipe. On some Windows 98 machines (but not all!) the pipe does not work,
and the preprocessor output is echoed to the screen. When this happens, the
omniidl parser sees an empty file, and produces useless stub files with strange
long names. To avoid the problem, use the ‘-T’ option to create a temporary file
between the two stages.
5.1.3 Comments
By default, omniidl discards comments in the input IDL. However, with the -k
and -K options, it preserves the comments for use by the back-ends. The C++
back-end ignores this information, but it is relatively easy to write new back-
ends which do make use of comments.
The two different options relate to how comments are attached to declara-
tions within the IDL. Given IDL like:
interface I {
void op1();
// A comment
void op2();
};
the -k flag will attach the comment to op1(); the -K flag will attach it to op2().
When you specify the C++ back-end (with -bcxx), the following -Wb options are
available. Note that the -Wb options must be specified after the -bcxx option,
so omniidl knows which back-end to give the arguments to.
By default, omniidl generates the minimum code required to provide all the IDL-
defined types and interfaces, which is sufficient for the majority of applications.
Additional code can also be generated, for various purposes:
To generate TypeCodes and Any insertion operators, give the -Wba option. See
chapter 10 for details.
By default, omniidl separates the normal stub and skeleton file (the SK.cc
file) from these ‘dynamic’ stubs (the DynSK.cc file), so applications that do not
need support for Any and TypeCode for a particular IDL file do not waste space
with unnecessary definitions. It is possible to output both the normal stubs and
the dynamic stubs to a single file, by simply specifying the same extension for
both files. This command places both the normal stubs and the dynamic stubs
in aSK.cc:
As described in section 2.11, tie templates can be used to provide servant im-
plementations, instead of using inheritance from the normal skeleton classes.
To generate tie templates, give the -Wbtp option to omniidl.
When using a pre-namespace C++ compiler, IDL modules are mapped to
C++ classes, which causes a problem with tie templates. The C++ mapping
says that for the interface M::I, the C++ tie template class should be named
POA_M::I_tie. However, since template classes cannot be declared inside other
classes, this naming scheme cannot be used if POA_M is a class.
The C++ mapping has an alternative option of ‘flattened’ tie class names, in
which the template class is declared at global scope with the name POA_M_I_tie.
i.e. all occurrences of ‘::’ are replaced by ‘_’. Generate the flattened ties using
the -Wbtf command line argument.
If you use the -Wbexample flag, omniidl will generate an example implementation
file as well as the stubs and skeletons. For IDL file foo.idl, the example code is
CHAPTER 5. THE IDL COMPILER 72
written to foo_i.cc. The example file contains class and method declarations
for the operations of all interfaces in the IDL file, along with a main() function
which creates an instance of each object. You still have to fill in the operation
implementations, of course.
IDL files regularly #include other files. By default, if file a.idl says #include
<b/c.idl> then the generated header a.hh has an include of the form #include
<c.idl>, and aSK.cc and aDynSK.cc contain only code corresponding to the
declarations in a.idl.
If the -Wbinline option is provided, all the #included declarations are gen-
erated in a.hh, aSK.cc and aDynSK.cc, meaning the application code should
only use that single set of files.
If -Wbuse-quotes is specified, then the directive in a.hh uses quotes rather
than angle brackets: #include "c.idl".
Normally any path details contained in the IDL #include directive are re-
moved, leaving just the base name. If -Wbkeep-inc-path is specified, the direc-
tive in a.hh is #include <b/c.idl>.
Some of the C++ mapping’s parameter passing rules are problematic in terms
of memory management. For example, if an IDL operation has a parameter of
type inout string, the standard mapping has a C++ parameter of type char*&.
If application code passes a String_var for the parameter, some C++ compil-
ers choose the wrong conversion operator and cause a violation of the memory
management rules1 .
To avoid this, omniORB uses some helper classes as the parameter types
in object reference operations, meaning that the correct memory management
rules are always followed. Normally, that is invisible to application code, but
occasionally it becomes problematic. One example is that if a local inter-
face is derived from a normal unconstrained interface, the C++ mapping of the
local interface derives from the object reference class, and so the base object
reference class must use the standard mapping rather than omniORB’s usual
enhanced mapping. To choose the standard ‘implementation mapping’, give the
-Wbimpl-mapping option to omniidl.
Similarly, omniidl usually uses non-virtual methods in its object reference
classes, since there is no usual need to override them. The local interface situa-
1
For this reason, the _var types define an inout() method that ensures use of the correct
conversion and thus avoids this kind of trouble.
CHAPTER 5. THE IDL COMPILER 73
5.3 Examples
This chapter describes how omniORB manages threads and network connec-
tions.
6.1 Background
In CORBA, the ORB is the ‘middleware’ that allows a client to invoke an opera-
tion on an object without regard to its implementation or location. In order to
invoke an operation on an object, a client needs to ‘bind’ to the object by acquir-
ing its object reference. Such a reference may be obtained as the result of an
operation on another object (such as a naming service or factory object) or by
conversion from a stringified representation. If the object is in a different ad-
dress space, the binding process involves the ORB building a proxy object in the
client’s address space. The ORB arranges for invocations on the proxy object
to be transparently mapped to equivalent invocations on the implementation
object.
For the sake of interoperability, CORBA mandates that all ORBs should sup-
port IIOP as the means to communicate remote invocations over a TCP/IP con-
nection. IIOP is usually1 asymmetric with respect to the roles of the parties at
the two ends of a connection. At one end is the client which can only initiate re-
mote invocations. At the other end is the server which can only receive remote
invocations.
Notice that in CORBA, as in most distributed systems, remote bindings are
established implicitly without application intervention. This provides the illusion
that all objects are local, a property known as ‘location transparency’. CORBA
does not specify when such bindings should be established or how they should
1
GIOP 1.2 supports ‘bidirectional GIOP’, which permits the rôles to be reversed.
75
CHAPTER 6. CONNECTION AND THREAD MANAGEMENT 76
be multiplexed over the underlying network connections. Instead, ORBs are free
to implement implicit binding by a variety of means.
The rest of this chapter describes how omniORB manages network connec-
tions and the programming interface to fine tune the management policy.
On the client side of a connection, the thread that invokes on a proxy object
drives the GIOP protocol directly and blocks on the connection to receive the
reply. The first time the client makes a call to a particular address space, the
ORB opens a suitable connection to the remote address space (based on the
client transport rule as described in section 6.7.1). After the reply has been
received, the ORB caches the open network connection, ready for use by another
call.
If two (or more) threads in a multi-threaded client attempt to contact the
same address space simultaneously, there are two different ways to proceed.
The default way is to open another network connection to the server. This means
that neither the client or server ORB has to perform any multiplexing on the net-
work connections—multiplexing is performed by the operating system, which
has to deal with multiplexing anyway. The second possibility is for the client
to multiplex the concurrent requests on a single network connection. This con-
serves operating system resources (network connections), but means that both
the client and server have to deal with multiplexing issues themselves.
In the default one call per connection mode, there is a limit to the number
of concurrent connections that are opened, set with the maxGIOPConnection
PerServer parameter. To tell the ORB that it may multiplex calls on a single con-
CHAPTER 6. CONNECTION AND THREAD MANAGEMENT 77
omniORB can associate a timeout with a call, meaning that if the call takes too
long a CORBA::TIMEOUT exception2 is thrown. Timeouts can be set for the whole
process, for a specific thread, or for a specific object reference.
Timeouts are set using this API:
namespace omniORB {
void setClientCallTimeout(CORBA::ULong millisecs);
void setClientCallTimeout(CORBA::Object_ptr obj, CORBA::ULong millisecs);
void setClientThreadCallTimeout(CORBA::ULong millisecs);
void setClientConnectTimeout(CORBA::ULong millisecs);
};
If the connect timeout is set to 20 seconds, then a call that establishes a new
connection will be permitted 20 seconds before it times out. Subsequent calls
using the same connection have the normal 10 second timeout. If establishing
the connection takes 8 seconds, then the call itself takes 5 seconds, the call suc-
ceeds despite having taken 13 seconds in total, longer than the usual timeout.
This kind of configuration is good when connections are slow to be estab-
lished.
If an object reference has multiple possible endpoints available, and connect-
ing to the first endpoint times out, only that one endpoint will have been tried
before an exception is raised. However, once the timeout has occurred, the ob-
ject reference will switch to use the next endpoint. If the application attempts
to make another call, it will use the next endpoint.
The server side has two primary modes of operation: thread per connection and
thread pooling. It is able to dynamically transition between the two modes, and
CHAPTER 6. CONNECTION AND THREAD MANAGEMENT 79
it supports a hybrid scheme that behaves mostly like thread pooling, but has the
same fast turn-around for sequences of calls as thread per connection.
In thread per connection mode (the default, and the only option in omniORB
versions before 4.0), each connection has a single thread dedicated to it. The
thread blocks waiting for a request. When it receives one, it unmarshals the
arguments, makes the up-call to the application code, marshals the reply, and
goes back to watching the connection. There is thus no thread switching along
the call chain, meaning the call is very efficient.
As explained above, a client can choose to multiplex multiple concurrent
calls on a single connection, so once the server has received the request, and
just before it makes the call into application code, it marks the connection as
‘selectable’, meaning that another thread should watch it to see if any other
requests arrive. If they do, extra threads are dispatched to handle the con-
current calls. GIOP 1.2 actually allows the argument data for multiple calls to
be interleaved on a connection, so the unmarshalling code has to handle that
too. As soon as any multiplexing occurs on the connection, the aim of remov-
ing thread switching cannot be met, and there is inevitable inefficiency due to
thread switching.
The maxServerThreadPerConnection parameter can be set to limit the num-
ber of threads that can be allocated to a single connection containing concurrent
calls. Setting the parameter to 1 mimics the behaviour of omniORB versions be-
fore 4.0, that did not support calls multiplexed on one connection.
a new call comes in during the watching period, the call is dispatched without
any thread switching, just as in thread per connection mode. Of course, if the
server is supporting a very large number of connections (more than the size of
the thread pool), this policy can delay a call coming from another connection. If
the threadPoolWatchConnection parameter is set to zero, connection watching
is disabled and threads return to the pool immediately after finishing a single
request.
In the face of multiplexed calls on a single connection, multiple threads from
the pool can be dispatched for one connection, just as in thread per connection
mode. With threadPoolWatchConnection set to the default value of 1, only
the last thread servicing a connection will watch it when it finishes a request.
Setting the parameter to a larger number allows the last n connections to watch
the connection.
It is wasteful to leave a connection open when it has been left unused for a
considerable time. Too many idle connections could block out new connections
when the system runs out of spare communication channels. For example, most
platforms have a limit on the number of file handles a process can open. Many
platforms have a very small default limit like 64. The value can often be in-
creased to a maximum of a thousand or more by changing the ‘ulimit’ in the
shell.
Every so often, a thread scans all open connections to see which are idle.
The scanning period (in seconds) is set with the scanGranularity parameter.
The default is 5 seconds.
Outgoing connections (initiated by clients) and incoming connections (ini-
tiated by servers) have separate idle timeouts. The timeouts are set with the
outConScanPeriod and inConScanPeriod parameters respectively. The values
are in seconds, and must be a multiple of the scan granularity.
Beware that setting outConScanPeriod or inConScanPeriod to be equal to
(or less than) scanGranularity means that connections are considered candi-
dates for closure immediately after they are opened. That can mean that the
connections are closed before any calls have been sent through them. If oneway
calls are used, such connection closure can result in silent loss of calls.
The IIOP specification allows both the client and the server to shutdown a con-
nection unilaterally. When one end is about to shutdown a connection, it should
send a CloseConnection message to the other end. It should also make sure
that the message will reach the other end before it proceeds to shutdown the
connection.
The client should distinguish between an orderly and an abnormal connec-
tion shutdown. When a client receives a CloseConnection message before the
connection is closed, the condition is an orderly shutdown. If the message is not
received, the condition is an abnormal shutdown. In an abnormal shutdown, the
ORB should raise a COMM_FAILURE exception whereas in an orderly shutdown,
the ORB should not raise an exception and should try to re-establish a new con-
nection transparently.
omniORB implements these semantics completely. However, it is known that
some ORBs are not (yet) able to distinguish between an orderly and an abnor-
mal shutdown. Usually this is manifested as the client in these ORBs seeing a
COMM_FAILURE occasionally when connected to an omniORB server. The work-
around is either to catch the exception in the application code and retry, or to
turn off the idle connection shutdown inside the omniORB server.
CHAPTER 6. CONNECTION AND THREAD MANAGEMENT 82
omniORB can support multiple network transports. All platforms (usually) have
a TCP transport available. Unix platforms support a Unix domain socket trans-
port. Platforms with the OpenSSL library available can support an SSL trans-
port.
Servers must be configured in two ways with regard to transports: the trans-
ports and interfaces on which they listen, and the details that are published in
IORs for clients to see. Usually the published details will be the same as the
listening details, but there are times when it is useful to publish different infor-
mation.
Details are selected with the endPoint family of parameters. The simplest is
plain endPoint, which chooses a transport and interface details, and publishes
the information in IORs. Endpoint parameters are in the form of URIs, with a
scheme name of ‘giop:’, followed by the transport name. Different transports
have different parameters following the transport.
TCP endpoints have the format:
giop:tcp:<host>:<port>
The host must be a valid host name or IP address for the server machine. It
determines the network interface on which the server listens. The port selects
the TCP port to listen on, which must be unoccupied. Either the host or port, or
both can be left empty. If the host is empty, the ORB publishes the IP address
of the first non-loopback network interface it can find (or the loopback if that
is the only interface), but listens on all network interfaces. If the port is empty,
the operating system chooses an ephemeral port.
Multiple TCP endpoints can be selected, either to specify multiple network
interfaces on which to listen, or (less usefully) to select multiple TCP ports on
which to listen.
If no endPoint parameters are set, the ORB assumes a single parameter of
giop:tcp::, meaning IORs contain the address of the first non-loopback net-
work interface, the ORB listens on all interfaces, and the OS chooses a port
number.
SSL endpoints have the same format as TCP ones, except ‘tcp’ is replaced
with ‘ssl’. Unix domain socket endpoints have the format:
giop:unix:<filename>
where the filename is the name of the socket within the filesystem. If the file-
name is left blank, the ORB chooses a name based on the process id and a times-
tamp.
CHAPTER 6. CONNECTION AND THREAD MANAGEMENT 83
giop:tcp::5000-5010
omniORB randomly chooses a port in the range. If it finds that the chosen
port is already occupied, it keeps trying different ports until it finds a free one.
If all the ports in the range are occupied, it throws CORBA::INITIALIZE.
6.6.2 IPv6
giop:tcp:0.0.0.0:
All IPv6 addresses contain colons, so the address portion in URIs must be con-
tained within [] characters. Therefore, to listen just for IPv6 connections on all
IPv6 interfaces, use the somewhat cryptic:
giop:tcp:[::]:
To listen for both IPv4 and IPv6 connections on Windows versions prior to Vista,
both endpoints must be explicitly provided.
CHAPTER 6. CONNECTION AND THREAD MANAGEMENT 84
In IPv6, all network interfaces are assigned a link local address, starting with
the digits fe80. The link local address is only valid on the same ‘link’ as the
interface, meaning directly connected to the interface, or possibly on the same
subnet, depending on how the network is switched. To connect to a server’s
link local address, a client has to know which of its network interfaces is on
the same link as the server. Since there is no way for omniORB to know which
local interface a remote link local address may be connected to, and in extreme
circumstances may even end up contacting the wrong server if it picks the wrong
interface, link local addresses are not considered valid. Servers do not publish
link local addresses in their IORs.
For clients to be able to connect to a server, the server publishes endpoint in-
formation in its IORs (Interoperable Object References). Normally, omniORB
publishes the first available address for each of the endpoints it is listening on.
The endpoint information to publish is determined by the endPointPublish
configuration parameter. It contains a comma-separated list of publish rules.
The rules are applied in turn to each of the configured endpoints; if a rule
matches an endpoint, it causes one or more endpoints to be published.
The following core rules are supported:
The core rules can be combined using the vertical bar operator to try several
rules in turn until one succeeds. e.g:
name|ipv6|ipv4 the name of the endpoint if it has one; failing that, its
first IPv6 address; failing that, its first IPv4 address.
Multiple rules can be combined using the comma operator to publish more than
one endpoint. e.g.
For endpoints with multiple addresses (e.g. TCP endpoints on multi-homed ma-
chines), the all() manipulator causes all addresses to be published. e.g.:
A specific endpoint can be published by giving its endpoint URI, even if the
server is not listening on that endpoint. e.g.:
giop:tcp:not.my.host:12345
giop:unix:/not/my/socket-
file
If the host or port number for a TCP or SSL URI are missed out, they are filled
in with the details from each listening TCP/SSL endpoint. This can be used to
publish a different name for a TCP/SSL endpoint that is using an ephemeral port,
for example.
omniORB 4.0 supported two options related to endpoint publishing that are
superseded by the endPointPublish parameter, and so are now deprecated.
Setting endPointPublishAllIFs to 1 is equivalent to setting endPointPublish
to ‘all(addr)’. The endPointNoListen parameter is equivalent to adding end-
point URIs to the endPointPublish parameter.
In the face of IORs containing details about multiple different endpoints, clients
have to know how to choose the one to use to connect a server. Similarly, servers
may wish to restrict which clients can connect to particular transports. This is
achieved with transport rules.
Server transport rules have the same format as client transport rules. Rather
than being used to select which of a set of ways to contact a machine, they are
used to determine whether or not to accept connections from particular clients.
In this example, we only allow connections from our intranet:
And in this one, we accept only SSL connections if the client is not on the in-
tranet:
In the absence of any explicit rules, the server uses the implicit rule of ‘* unix,
ssl,tcp’, meaning any kind of connection is accepted from any client.
• The client transport rule for the target server must contain the bidir ac-
tion.
• The POA containing the callback object (or objects) must have been cre-
ated with a BidirectionalPolicy value of BOTH.
• The server transport rule for the requesting client must contain the bidir
action.
• The POA hosting the object contacted by the client must have been created
with a BidirectionalPolicy value of BOTH.
echo 01 >demoCA/serial
touch demoCA/index.txt
Amongst other things, you now have a server key file in server_key.pem and a
certificate in server_cert.pem. To make a single file containing both the key
and the certificate, suitable for use in omniORB, concatenate the key and certifi-
cate files together. You can skip the human-readable(ish) text in the certificate
file before the -----BEGIN CERTIFICATE----- marker.
If need be, create more certificates for servers and clients in the same way.
6.10 ZIOP
This allows you to enable ZIOP for WAN links, but disable it for LAN communi-
cation, for example.
CHAPTER 6. CONNECTION AND THREAD MANAGEMENT 90
The fact that a server supports ZIOP is encoded in its IORs. This means that if
a client uses a corbaloc URI to reference an object, the object reference does
not contain ZIOP details, and thus the communication cannot use ZIOP. If a
client is absolutely certain that a server supports ZIOP, it can extend an object
reference with ZIOP details using omniZIOP::setServerPolicies(). Using the
new object reference, the client will be able to make ZIOP calls.
namespace omniZIOP {
CORBA::Object_ptr
setServerPolicies(CORBA::Object_ptr obj, const CORBA::PolicyList& policies);
};
void init();
CORBA::Object_ptr
makeRestrictedReference(CORBA::Object_ptr obj,
CORBA::ULong connection_id,
CORBA::ULong max_connections,
CORBA::ULong max_threads,
CORBA::Boolean data_batch,
CORBA::Boolean permit_interleaved,
CORBA::Boolean server_hold_open);
};
connection_id
This number identifies the private connection set. All object references with the
same connection_id will share the same set of GIOP connections. Object refer-
ences with different connection ids are guaranteed to use different connections
from each other, and from object references that have not been annotated with
makeRestrictedReference().
max_connections
data_batch
permit_interleaved
max_threads
server_hold_open
Normally, both clients and servers can decide to close a GIOP connection at any
time. When using normal two-way calls, this is no problem since if a server
closes a connection, the client is guaranteed to notice it when it waits for a
reply, and can retry the call if necessary. With oneway calls, however, if a server
closes a connection just as the client is sending a request, the client will not
know whether the oneway call was received or not, and the call will potentially
be lost. By setting the server_hold_open parameter to true, the server will
not close the connection, relying on the client to do so. In that case, oneway
calls will not be lost unless there is a network problem that breaks the GIOP
connection.
6.11.3 Usage
7.1.1 corbaloc
corbaloc URIs allow you to specify object references which can be contacted
by IIOP, or found through ORB::resolve_initial_references(). To specify an
IIOP object reference, you use a URI of the form:
corbaloc:iiop:<host>:<port>/<object key>
for example:
corbaloc:iiop:myhost.example.com:1234/MyObjectKey
corbaloc:iiop:myhost.example.com:1234/My%efObjectKey
denotes an object key with the value 239 (hex ef) in the third octet.
The protocol name ‘iiop’ can be abbreviated to the empty string, so the
original URI can be written:
93
CHAPTER 7. INTEROPERABLE NAMING SERVICE 94
corbaloc::myhost.example.com:1234/MyObjectKey
The IANA has assigned port number 28091 for use by corbaloc, so if the server
is listening on that port, you can leave the port number out. The following two
URIs refer to the same object:
corbaloc::myhost.example.com:2809/MyObjectKey
corbaloc::myhost.example.com/MyObjectKey
You can specify an object which is available at more than one location by sepa-
rating the locations with commas:
corbaloc::myhost.example.com,:localhost:1234/MyObjectKey
Note that you must restate the protocol for each address, hence the ‘:’ before
‘localhost’. It could equally have been written ‘iiop:localhost’.
You can also specify an IIOP version number:
corbaloc::[email protected]/MyObjectKey
Specifying IIOP versions above 1.0 is slightly risky since higher versions make
use of various information stored in IORs that is not present in a corbaloc URI.
It is generally best to contact initial corbaloc objects with IIOP 1.0, and rely on
higher versions for all other object references.
The only transport specified in the CORBA standard is iiop, but omniORB also
supports the following extensions:
ssliop
Equivalent semantics to iiop, but the server is contacted using SSL / TLS.
As with iiop, the address details are of the form host:port.
omniunix
The omniORB Unix domain socket transport. The address details are of
the form filename.
is identical in behaviour to
orb->resolve_initial_references("NameService");
1
Not 2089 as printed in [OMG00]!
CHAPTER 7. INTEROPERABLE NAMING SERVICE 95
7.1.4 corbaname
for example:
corbaname::myhost/NameService#project/example/echo.obj
corbaname:rir:/NameService#project/example/echo.obj
The object found with the corbaloc-style portion must be of type CosNaming::
NamingContext, or something derived from it. If the object key (or rir name) is
‘NameService’, it can be left out:
corbaname::myhost#project/example/echo.obj
corbaname:rir:#project/example/echo.obj
The stringified name portion can also be left out, in which case the URI denotes
the CosNaming::NamingContext which would have been used for a look-up:
corbaname::myhost.example.com
corbaname:rir:
The first of these examples is the easiest way of specifying the location of a
naming service.
The INS specifies two standard command line arguments which provide a portable
way of configuring ORB::resolve_initial_references():
7.2.1 ORBInitRef
-ORBInitRef NameService=corbaname::myhost.example.com
-ORBInitRef NameService=IOR:00ff...
CHAPTER 7. INTEROPERABLE NAMING SERVICE 96
7.2.2 ORBDefaultInitRef
-ORBDefaultInitRef corbaloc::myhost.example.com
-ORBDefaultInitRef corbaname::myhost.example.com#services
7.3 omniNames
7.3.1 NamingContextExt
To make it easy to use omniNames with corbaname URIs, it starts with the de-
fault port of 2809, and an object key of ‘NameService’ for the root naming con-
text.
7.4 omniMapper
omniMapper is a simple daemon which listens on port 2809 (or any other port),
and redirects IIOP requests for configured object keys to associated persistent
object references. It can be used to make a naming service (even an old non-
INS aware version of omniNames or other ORB’s naming service) appear on port
2809 with the object key ‘NameService’. The same goes for any other service
you may wish to specify, such as an interface repository. omniMapper is started
with a command line of:
The -port option allows you to choose a port other than 2809 to listen on. The -
config option specifies a location for the configuration file. The default name is
CHAPTER 7. INTEROPERABLE NAMING SERVICE 98
# Example omniMapper.cfg
NameService IOR:000f...
InterfaceRepository IOR:0100...
omniMapper can either be run on a single machine, in much the same way
as omniNames, or it can be run on every machine, with a common configuration
file. That way, each machine’s omniORB configuration file could contain the line:
ORBDefaultInitRef corbaloc::localhost
In normal use, omniORB creates object keys containing various information in-
cluding POA names and various non-ASCII characters. Since object keys are
supposed to be opaque, this is not usually a problem. The INS breaks this opac-
ity and requires servers to create objects with human-friendly keys.
If you wish to make your objects available with human-friendly URIs, there
are two options. The first is to use omniMapper as described above, in conjunc-
tion with a PERSISTENT POA. The second is to create objects with the required
keys yourself. You do this with a special POA with the name ‘omniINSPOA’, ac-
quired from resolve_initial_references(). This POA has the USER_ID and
PERSISTENT policies, and the special property that the object keys it creates
contain only the object ids given to the POA, and no other data. It is a normal
POA in all other respects, so you can activate/deactivate it, create children, and
so on, in the usual way.
Children of the omniINSPOA do not inherit its special properties of creating
simple object keys. If the omniINSPOA’s policies are not suitable for your appli-
cation, you cannot create a POA with different policies (such as single threading,
for example), and still generate simple object keys. Instead, you can activate a
servant in the omniINSPOA that uses location forwarding to redirect requests
to objects in a different POA.
Chapter 8
omniORB supports full code set negotiation, used to select and translate be-
tween different character code sets when transmitting chars, strings, wchars
and wstrings. The support is mostly transparent to application code, but there
are a number of options that can be selected. This chapter covers the options,
and also gives some pointers about how to implement your own code sets, in
case the ones that come with omniORB are not sufficient.
For the ORB to know how to handle strings and wstrings given to it by the appli-
cation, it must know what code set they are represented with, so it can properly
translate them if need be. The defaults are ISO 8859-1 (Latin 1) for char and
string, and UTF-16 for wchar and wstring. Different code sets can be chosen
at initialisation time with the nativeCharCodeSet and nativeWCharCodeSet pa-
rameters. The supported code sets are printed out at initialisation time if the
ORB traceLevel is 15 or greater.
For most applications, the defaults are fine. Some applications may need
to set the native char code set to UTF-8, allowing the full Unicode range to be
supported in strings.
Note that the default for wchar is always UTF-16, even on Unix platforms
where wchar is a 32-bit type. Select the UCS-4 code set to select characters
outside the first plane without having to use UTF-16 surrogates1 .
1
If you have no idea what this means, don’t worry—you’re better off not knowing unless you
really have to.
99
CHAPTER 8. CODE SET CONVERSION 100
The way code set conversion is meant to work in CORBA communication is that
each client and server has a native code set that it uses for character data in
application code, and supports a number of transmission code sets that is uses
for communication. When a client connects to a server, the client picks one of
the server’s transmission code sets to use for the interaction. For that to work,
the client plainly has to know the server’s supported transmission code sets.
Code set information from servers is embedded in IORs. A client with an
IOR from a server should therefore know what transmission code sets the server
supports. This approach can fail for two reasons:
1. A corbaloc URI (see chapter 7) does not contain any code set information.
The CORBA standard says that if a server has not specified transmission code
set information, clients must assume that they only support ISO-8859-1 for char
and string, and do not support wchar and wstring at all. The effect is that client
code receives DATA_CONVERSION or BAD_PARAM exceptions.
To avoid this issue, omniORB allows you to configure default code sets that
are used as a server’s transmission code sets if they are not otherwise known.
Set defaultCharCodeSet for char and string data, and defaultWCharCodeSet
for wchar and wstring data.
To save space in the main ORB core library, most of the code set implementa-
tions are in a separate library named omniCodeSets4. To use the extra code
sets, you must link your application with that library. On most platforms, if
you are using dynamic linking, specifying the omniCodeSets4 library in the link
command is sufficient to have it initialised, and for the code sets to be avail-
able. With static linking, or platforms with less intelligent dynamic linkers,
you must force the linker to initialise the library. You do that by including the
omniORB4/optionalFeatures.h header. By default, that header enables sev-
eral optional features. Look at the file contents to see how to turn off particular
features.
It is quite easy to implement new code sets, if you need support for code sets (or
marshalling formats) that do not come with the omniORB distribution. There are
CHAPTER 8. CODE SET CONVERSION 101
extensive comments in the headers and ORB code that explain how to implement
a code set; this section just serves to point you in the right direction.
The main definitions for the code set support are in include/omniORB4/
codeSets.h. That defines a set of base classes use to implement code sets, plus
some derived classes that use look-up tables to convert simple 8-bit and 16-bit
code sets to Unicode.
When sending or receiving string data, there are a total of four code sets in
action: a native char code set, a transmission char code set, a native wchar code
set, and a transmission wchar code set. The native code sets are as described
above; the transmission code sets are the ones selected to communicate with a
remote machine. They are responsible for understanding the GIOP marshalling
formats, as well as the code sets themselves. Each of the four code sets has an
object associated with it which contains methods for converting data.
There are two ways in which a string/wstring can be transmitted or received.
If the transmission code set in action knows how to deal directly with the na-
tive code set (the trivial case being that they are the same code set, but more
complex cases are possible too), the transmission code set object can directly
marshal or unmarshal the data into or out of the application buffer. If the trans-
mission code set does not know how to handle the native code set, it converts
the string/wstring into UTF-16, and passes that to the native code set object (or
vice-versa). All code set implementations must therefore know how to convert
to and from UTF-16.
With this explanation, the classes in codeSets.h should be easy to under-
stand. The next place to look is in the various existing code set implementa-
tions, which are files of the form cs-*.cc in the src/lib/omniORB/orbcore and
src/lib/omniORB/codesets. Note how all the 8-bit code sets (the ISO 8859-*
family) consist entirely of data and no code, since they are driven by look-up
tables.
Chapter 9
Interceptors
class info_T {
public:
GIOP_C& giop_c;
IOP::ServiceContextList service_contexts;
private:
info_T();
info_T(const info_T&);
info_T& operator=(const info_T&);
};
void add(interceptFunc);
void remove(interceptFunc);
};
...
102
CHAPTER 9. INTERCEPTORS 103
};
You can see that the interceptors themselves are functions that take the info_T
object as their argument and return boolean. Interceptors are called in the order
they are registered; normally, all interceptor functions return true, meaning
that processing should continue with subsequent interceptors. If an interceptor
returns false, later interceptors are not called. You should only do that if you
really know what you are doing.
Notice that the info_T contains references to omniORB internal data types.
The definitions of these types can be found in other header files within include/
omniORB4 and include/omniORB4/internal.
All the interceptor singletons are registered within another singleton object of
class omniInterceptors. You retrieve a pointer to the object with the omniORB::
getInterceptors() function, which must be called after the ORB has been ini-
tialised with CORBA::ORB_init(), but before the ORB is used. The code to reg-
ister an interceptor looks, for example, like:
omniInterceptors* interceptors = omniORB::getInterceptors();
interceptors->clientSendRequest.add(myInterceptorFunc);
encodeIOR
Called when encoding an IOR to represent an object reference. This in-
terception point allows the application to insert extra profile components
into IORs. Note that you must understand and adhere to the rules about
data stored in IORs, otherwise the IORs created may be invalid. omniORB
itself uses this interceptor to insert various items, so you can see an ex-
ample of its use in the insertSupportedComponents() function defined in
src/lib/omniORB/orbcore/ior.cc.
decodeIOR
Called when decoding an IOR. The application can use this to get out what-
ever information they put into IORs with encodeIOR. Again, see extract
SupportedComponents() in src/lib/omniORB/orbcore/ior.cc for an ex-
ample.
CHAPTER 9. INTERCEPTORS 104
clientOpenConnection
Called as a client opens a new connection to a server, after the connection
is opened but before it is used to send a request. The interceptor func-
tion can set the info_T’s reject member to true to cause the client to
immediately close the new connection and throw CORBA::TRANSIENT to
the calling code. In that case, the interceptor function can also set the why
member to provide a message that is logged.
clientSendRequest
Called just before a request header is sent over the network. The applica-
tion can use it to insert service contexts in the header. See the setCodeSet
ServiceContext() function in src/lib/omniORB/orbcore/cdrStream.cc
for an example of its use.
clientReceiveReply
Called as the client receives a reply, just after unmarshalling the reply
header. Called for normal replies and exceptions.
serverAcceptConnection
Called when a server accepts a new incoming connection, but before it
reads any data from it. The interceptor function can set the info_T’s re-
ject member to true to cause the server to immediately close the new
connection. In that case, the interceptor function can also set the why
member to provide a message that is logged.
serverReceiveRequest
Called when the server receives a request, just after unmarshalling the
request header. See the getCodeSetServiceContext() function in src/
lib/omniORB/orbcore/cdrStream.cc for an example.
serverSendReply
Called just before the server marshals a reply header.
serverSendException
Called just before the server marshals an exception reply header.
createRope
Called when the ORB is about to create a ‘rope’ that encapsulates a bundle
of connections (‘strands’) to a remote address space. It allows application
code to override omniORB’s normal connection management.
createIdentity
Called when the ORB is about to create an ‘identity’ object to represent
a CORBA object. It allows application code to provide its own identity
CHAPTER 9. INTERCEPTORS 105
createORBServer
Used internally by the ORB to register different kinds of server. At present,
only a GIOP server is registered. It is very unlikely that application code
will need to do this.
createThread
Called whenever the ORB creates a thread. The info_T class for this in-
terceptor is
class info_T {
public:
virtual void run() = 0;
virtual omni_thread* self() = 0;
};
The interceptor is called in the context of the newly created thread. The
function must call the info_T’s run() method, to pass control to the thread
body. run() returns just before the thread exits. This arrangement allows
the interceptor to initialise some per-thread state before the thread body
runs, then release it just before the thread exits.
The info_T’s self() method returns a pointer to the omni_thread object
for the thread, equivalent to calling omni_thread::self().
assignUpcallThread
The ORB maintains a general thread pool, from which threads are drawn
for various purposes. One purpose is for performing upcalls to application
code, in response to incoming CORBA calls. The assignUpcallThread in-
terceptor is called when a thread is assigned to perform upcalls. In the
thread per connection model, the thread stays assigned to performing
upcalls for the entire lifetime of the underlying network connection; in
the thread pool model, threads are assigned for upcalls on a per call ba-
sis, so this interceptor is triggered for every incoming call1 . As with the
createThread interceptor, the interceptor function must call the info_T’s
run() method to pass control to the upcall.
When a thread finishes its assignment of processing upcalls, it returns to
the pool (even in thread per connection mode), so the same thread can be
reassigned to perform more upcalls, or reused for a different purpose.
1
Except that with the threadPoolWatchConnection parameter set true, a thread can perform
multiple upcalls even when thread pool mode is active.
CHAPTER 9. INTERCEPTORS 106
assignAMIThread
Asynchronous Method Invocation (AMI) uses threads to perform outgoing
calls. The assignAMIThread interceptor is called when a thread is assigned
to perform AMI calls. As with the other thread interceptors, the interceptor
function must call the info_T’s run() method to pass control to the AMI
call.
Unlike the other interceptors, the interceptor functions for createThread,
assignUpcallThread and assignAMIThread have no return values. Inter-
ceptor chaining is performed by calls through the info_T::run() method,
rather than by visiting interceptor functions in turn.
Calls can be intercepted on the server just before the upcall into application
code. This interceptor is registered with omniORB’s callDescriptor class,
which is responsible for encapsulating the state of a call. Unlike the transport-
related serverReceiveRequest, serverSendReply and serverSendException
interceptors, the callDescriptor interceptor is invoked for all calls, even ones
from colocated clients in the same address space.
The types used for the call interceptor are defined in include/omniORB4/
callDescriptor.h. The interceptor takes the form of a bare function with two
parameters. The first parameter is a pointer to the callDescriptor; the sec-
ond is a pointer to omniServant, which is the base class of all servant classes.
The interceptor function must call the callDescriptor’s interceptedCall()
method to pass on the call.
This interception point allows access to various parts of omniORB’s call ma-
chinery. The callDescriptor includes access to the operation name and, if cast
to the concrete subclass defined by the IDL compiler, the call arguments and
return values too.
Chapter 10
The CORBA specification provides for a type that can hold the value of any OMG
IDL type. This type is known as type Any. The OMG also specifies a pseudo-
object, TypeCode, that can encode a description of any type specifiable in OMG
IDL.
In this chapter, an example demonstrating the use of type Any is presented.
The example code is in the src/examples/anyExample directory in the omniORB
distribution. The example is followed by sections describing the behaviour of
type Any and TypeCode in omniORB. For further information on type Any, refer
to the C++ Mapping specification., and for more information on TypeCode, refer
to the Interface Repository chapter in the CORBA core section of the CORBA
specification.
Before going through this example, you should make sure that you have read
and understood the examples in chapter 2.
Type Any allows one to delay the decision on the type used in an operation
until run-time. To use type any in IDL, use the keyword any, as in the following
example:
// IDL
interface anyExample {
any testOp(in any mesg);
};
The operation testOp() in this example can now take any value expressible in
OMG IDL as an argument, and can also return any type expressible in OMG IDL.
107
CHAPTER 10. TYPE ANY AND TYPECODE 108
Type Any is mapped into C++ as the type CORBA::Any. When passed as an
argument or as a result of an operation, the following rules apply:
The question now arises as to how values are inserted into and removed from
an Any. This is achieved using two overloaded operators: <<= and >>=.
To insert a value into an Any, the <<= operator is used, as in this example:
// C++
CORBA::Any an_any;
CORBA::Long l = 100;
an_any <<= l;
Note that the overloaded <<= operator has a return type of void.
To extract a value, the >>= operator is used, as in this example (where the
Any contains a long):
// C++
CORBA::Long l;
an_any >>= l;
if (an_any >>= l) {
cout << "Long: " << l << endl;
}
else if (an_any >>= d) {
cout << "Double: " << d << endl;
}
else if (an_any >>= str) {
cout << "String: " << str << endl;
// The storage of the extracted string is still owned by the any.
}
else {
cout << "Unknown value." << endl;
}
It is also possible to insert and extract constructed types and object references
from an Any. omniidl will generate insertion and extraction operators for the
constructed type. Note that it is necessary to specify the -Wba command-line
flag when running omniidl in order to generate these operators. The following
example illustrates the use of constructed types with type Any:
// IDL
struct testStruct {
long l;
short s;
};
interface anyExample {
any testOp(in any mesg);
};
Upon compiling the above IDL with omniidl -bcxx -Wba, the following over-
loaded operators are generated:
Operators of this form are generated for all constructed types, and for inter-
faces.
The first operator, (1), copies the constructed type, and inserts it into the
Any. The second operator, (2), inserts the constructed type into the Any, and
CHAPTER 10. TYPE ANY AND TYPECODE 110
then manages it. Note that if the second operator is used, the Any consumes
the constructed type, and the caller should not use the pointer to access the
data after insertion. The following is an example of how to insert a value into an
Any using operator (1):
// C++
CORBA::Any an_any;
testStruct t;
t.l = 456;
t.s = 8;
an_any <<= t;
The third operator, (3), is used to extract the constructed type from the Any,
and can be used as follows:
const testStruct* tp;
As with basic types, if an attempt is made to extract a type from an Any that
does not contain a value of that type, the extraction operator returns false.
If the Any does contain that type, the extraction operator returns true. If the
extraction is successful, the caller’s pointer will point to memory managed by the
Any. The caller must not delete or otherwise change this storage, and should not
use this storage after the contents of the Any are replaced (either by insertion
or assignment), or after the Any has been destroyed. In particular, management
of the pointer should not be assigned to a _var type.
If the extraction fails, the caller’s pointer will be set to point to null.
Note that there are special rules for inserting and extracting arrays (using
the _forany types), and for inserting and extracting bounded strings, booleans,
chars, and octets. Please refer to the C++ Mapping specification for further
information.
This section contains some notes on the use and behaviour of type Any in omni-
ORB.
CHAPTER 10. TYPE ANY AND TYPECODE 111
To generate type Any insertion and extraction operators for constructed types
and interfaces, the -Wba command line flag should be specified when running
omniidl.
When an attempt is made to extract a type from an Any, the TypeCode of the
type is checked for equivalence with the TypeCode of the type stored by the
Any. The equivalent() test in the TypeCode interface is used for this purpose.
For example:
// IDL 1
typedef double Double1;
struct Test1 {
Double1 a;
};
// IDL 2
typedef double Double2;
struct Test1 {
Double2 a;
};
If an attempt is made to extract the type Test1 defined in IDL 1 from an Any
containing the Test1 defined in IDL 2, this will succeed (and vice-versa), as the
two types differ only by an alias.
When a type is inserted into an Any, the Any stores both the value of the type
and the TypeCode for that type. However, in some cases, a top-level alias can
be lost due to the details of the C++ mapping. For example, consider these IDL
definitions:
// IDL 3
typedef sequence<double> seqDouble1;
typedef sequence<double> seqDouble2;
typedef seqDouble2 seqDouble3;
omniidl generates distinct types for seqDouble1 and seqDouble2, and there-
fore each has its own set of C++ operators for Any insertion and extraction.
That means inserting a seqDouble1 into an Any sets the Any’s TypeCode to in-
clude the alias ‘seqDouble1’, and inserting a seqDouble2 sets the TypeCode to
the alias ‘seqDouble2’.
CHAPTER 10. TYPE ANY AND TYPECODE 112
Some ORBs (such as old versions of Orbix) will not accept TypeCodes contain-
ing tk_alias TypeCodes. When using type Any while interoperating with these
ORBs, it is necessary to remove tk_alias TypeCodes from throughout the Type-
Code representing a constructed type.
To remove all tk_alias TypeCodes from TypeCodes transmitted in Anys,
supply the -ORBtcAliasExpand 1 command-line flag when running an omniORB
executable. There will be some (small) performance penalty when transmitting
Any values.
Note that the _tc_ TypeCodes generated for all constructed types will con-
tain the complete TypeCode for the type (including any tk_alias TypeCodes),
regardless of whether the -ORBtcAliasExpand flag is set to 1 or not. It is only
when Anys are transmitted that the aliases are stripped.
omniORB supports recursive TypeCodes. This means that types such as the
following can be inserted or extracted from an Any:
// IDL 4
struct Test4 {
sequence<Test4> a;
};
Inserting and extracting simultaneously from the same Any (in 2 threads) results
in undefined behaviour.
In versions of omniORB before 4.0, extracting simultaneously from the same
Any (in 2 or more different threads) also led to undefined behaviour. That is no
longer the case—Any extraction is now thread safe.
CHAPTER 10. TYPE ANY AND TYPECODE 113
This section contains some notes on the use and behaviour of TypeCode in omni-
ORB
When using TypeCodes in IDL, note that they are defined in the CORBA scope.
Therefore, CORBA::TypeCode should be used. Example:
// IDL 5
struct Test5 {
long length;
CORBA::TypeCode desc;
};
10.3.2 orb.idl
The CORBA specification says that IDL using CORBA::TypeCode must include
the file orb.idl. That is not required in omniORB, but a suitable orb.idl is
available.
omniORB 4.1 supports objects by value, declared with the valuetype keyword in
IDL, and both abstract and local interfaces. This chapter outlines some issues
to do with using these types in omniORB. You are assumed to have read the
relevant parts of the CORBA specification, specifically chapters 3, 4, 5 and 6
of the CORBA 2.6 specification, and sections 1.17, 1.18 and 1.35 of the C++
mapping specification, version 1.1.
11.1 Features
omniORB supports the complete objects by value specification, with the excep-
tion of custom valuetypes. All other valuetype features including value boxes,
value sharing semantics, abstract valuetypes, and abstract interfaces are sup-
ported. Local interfaces are supported, with a number of caveats outlined in
section 11.8.
Values are reference counted. This means that, as long as your application prop-
erly manages reference counts, values are usually automatically deleted when
they are no longer required. However, one of the features of valuetypes is that
they support the representation of cyclic graph structures. In that kind of situ-
ation, the reference counting garbage collection does not work, because refer-
ences internal to the graph prevent the reference counts ever becoming zero.
To avoid memory leaks, application code must explicitly break any reference
cycles in values it manipulates. This includes graphs of values received as pa-
rameters and return values from CORBA operations.
114
CHAPTER 11. OBJECTS BY VALUE, ETC. 115
When valuetypes are passed as parameters in CORBA calls (i.e. calls on CORBA
objects declared with interface in IDL), the structure of related values is main-
tained. Consider, for example, the following IDL definitions (which are from the
example code in src/examples/valuetype/simple:
module ValueTest {
valuetype One {
public string s;
public long l;
};
interface Test {
One op1(in One a, in One b);
};
};
If the client to the Test object passes the same value in both parameters,
just one value is transmitted, and the object implementation receives a copy of
the single value, with references to it in both parameters.
In the case that the object is remote from the client, there is obviously a
copying step involved. In the case that the object is in the same address space
as the client, the same copying semantics must be maintained so that the object
implementation can modify the values it receives without the client seeing the
modifications. To support that, omniORB must copy the entire parameter list in
one operation, in case there is sharing between different parameters. Such copy-
ing is a rather more time-consuming process than the parameter-by-parameter
copy that takes place in calls not involving valuetypes.
To avoid the overhead of copying parameters in this way, applications can
choose to relax the semantics of value copying in local calls, so values are not
copied at all, but are passed by reference. In that case, the client to a call will see
any modifications to the values it passes as parameters (and similarly, the object
implementation will see any changes the client makes to returned values). To
choose this option, set the copyValuesInLocalCalls configuration parameter
to zero.
With normal valuetypes, omniidl generates factory classes (with names ending
_init) as required by the C++ mapping specification. The application is re-
sponsible for registering the factories with the ORB.
Unfortunately, the C++ mapping makes no mention of factories for value
boxes. In omniORB, factories for value boxes are automatically registered with
CHAPTER 11. OBJECTS BY VALUE, ETC. 116
the ORB, and there are no application-visible factory classes generated for them.
Some other CORBA implementations generate application visible factories, and
the application does have to register the factories with the ORB.
As required by the C++ mapping, on C++ compilers that support covariant re-
turn types, omniidl generates code for the _copy_value() function that returns
the most derived type of the value. On older compilers, _copy_value() returns
CORBA::ValueBase.
If you write code that calls _copy_value(), and you need to support older
compilers, you should assign the result to a variable of type CORBA::ValueBase*
and downcast to the target type, rather than using the covariant return.
If you are overriding _copy_value(), you must correctly take account of the
OMNI_HAVE_COVARIANT_RETURNS preprocessor definition.
Valuetypes inserted into Anys cause a number of interesting issues. Even when
inside Anys, values are required to support complete sharing semantics. Take
this IDL for example:
module ValueTest {
valuetype One {
public string s;
public long l;
};
interface AnyTest {
void op1(in One v, in Any a);
};
};
obj->op1(v, a);
This is all very well in this kind of simple situation, but problems can arise if
truncatable valuetypes are used. Imagine this derived value:
module ValueTest {
valuetype Two : truncatable One {
public double d;
};
};
Now, suppose that the client shown above sends an instance of valuetype Two
in both parameters, and suppose that the server has not seen the definition of
valuetype Two. In this situation, as the first parameter is unmarshalled, it will be
truncated to valuetype One, as required. Now, when the Any is unmarshalled,
it refers to the same value, which has been truncated. So, even though the
TypeCode in the Any indicates that the value has type Two, the stored value
actually has type One. If the receiver of the Any tries to pass it on, transmission
will fail because the Any’s value does not match its TypeCode.
In the opposite situation, where an Any parameter comes before a valuetype
parameter, a different problem occurs. In that case, as the Any is unmarshalled,
there is no type information available for valuetype Two, so the value inside the
Any has an internal omniORB type used for unknown valuetypes. As the next
parameter is unmarshalled, omniORB sees that the shared value is unknown,
and is able to convert it to the target One valuetype with truncation. In this
case, the Any and the plain valuetype both have the correct types and values,
but the fact that both should have referred to the same value has been lost.
Because of these issues, it is best to avoid defining interfaces that mix value-
types and Anys in a single operation, and certainly to avoid trying to share plain
values with values inside Anys.
The sharing semantics of valuetypes can also cause difficulties for DynAny. The
CORBA 2.6 specification does not mention how shared values inside DynAnys
should be handled; the CORBA 3.x specification slightly clarifies the situation,
but it is still unclear. To write portable code it is best to avoid manipulating
DynAnys containing values that are shared.
CHAPTER 11. OBJECTS BY VALUE, ETC. 118
Local interfaces are somewhat under-specified in the C++ mapping. This sec-
tion outlines the way local interfaces are supported in omniORB, and details the
limitations and issues.
The IDL compiler generates an abstract base class Test::Example. The ap-
plication defines a class derived from it that implements the abstract hello()
member function. Instances of that class can then be used where the IDL spec-
ifies interface Example.
Note that, by default, local interface implementations have no reference
counting behaviour. If the local object should be deleted when the last reference
is released, the application must implement the _add_ref() and _remove_ref()
virtual member functions within the implementation class. Make sure that the
implementations are thread safe.
};
interface Receiver {
void setOne(in One a);
};
};
IDL like this leads to two issues to do with omniORB’s C++ mapping imple-
mentation.
First, an instance of local interface Two should be suitable to pass as the ar-
gument to the setOne() method of a Receiver object (as long as the object is in
the same address space as the caller). Therefore, the Two abstract base class has
to inherit from the internal class omniORB uses to map object references of type
One. For performance reasons, the class that implements One object references
normally has non-virtual member functions. That means that the application-
supplied problem() member function for the implementation of local interface
Two will not override the base class’s version. To overcome this, the IDL for the
base unconstrained interface must be compiled with the -Wbvirtual-objref
switch to omniidl. That makes the member functions of the mapping of One into
virtual functions, so they can be overridden.
The second problem is that, in some cases, omniORB uses a different map-
ping for object reference member functions than the mapping used in servant
classes. For example, in the problem() operation, it uses an internal type for
the inout string argument that avoids memory issues if the application uses a
String_var in the argument. This means that the abstract member function
declared in the Two class (and implemented by the application) has a different
signature to the member function in the base class. The application-supplied
class will therefore not properly override the base class method. In all likeli-
hood, the C++ compiler will also complain that the two member functions are
ambiguous. The solution to this problem is to use the implementation mapping
in the base object reference class, rather than the normal object reference map-
ping, using the -Wbimpl-mapping switch to omniidl. The consequence of this is
that some uses of _var types for inout arguments that are normally acceptable
in omniORB can now lead to memory management problems.
In summary, to use local interfaces derived from normal unconstrained in-
terfaces, you should compile all your IDL with the omniidl flags:
-Wbvirtual-objref -Wbimpl-mapping
local interface I {
void my_operation();
};
valuetype V supports I {
public string s;
};
omniidl accepts the IDL, but unfortunately the resulting C++ code does not
compile. The C++ mapping specification has a problem in that both the CORBA::
LocalObject and CORBA::ValueBase classes have _add_ref() and _remove_
ref() member functions defined. The classes generated for the valuetype in-
herit from both these base classes, and therefore have an ambiguity. Until the
C++ mapping resolves this conflict, valuetypes supporting local interfaces can-
not be used in omniORB.
Chapter 12
Asynchronous Method
Invocation
AMI works by defining some additional implied IDL for each interface in the
real IDL. The implied IDL contains type and operation definitions that enable
asynchronous calls.
As a guide to the implied IDL, there is a special ami back-end to omniidl that
outputs the implied IDL for the given input IDL. For example, given the Echo
example IDL:
// echo.idl
interface Echo {
string echoString(in string mesg);
};
121
CHAPTER 12. ASYNCHRONOUS METHOD INVOCATION 122
Alternatively, you can use the -Wbdump option to output an interleaved version
that shows the original IDL and the implied IDL together.
Note that the implied IDL output is for information only. You should not
compile it, but rather instruct the omniidl C++ back-end to generate the corre-
sponding C++ definitions.
To generate stub code including AMI types and operations, give the -Wbami com-
mand line option to omniidl’s cxx back-end:
That generates the normal C++ stubs and skeletons, plus all the definitions in
the implied IDL.
Example AMI clients for the Echo server can be found in src/examples/ami.
Chapter 13
This chapter describes the mechanism used by omniORB to ensure type safety
when object references are exchanged across the network. This mechanism is
handled completely within the ORB. There is no programming interface visible
at the application level. However, for the sake of diagnosing the problem when
there is a type violation, it is useful to understand the underlying mechanism in
order to interpret the error conditions reported by the ORB.
13.1 Introduction
123
CHAPTER 13. INTERFACE TYPE CHECKING 124
// C++
C_ptr server;
B_ptr objB;
A_ptr objA = objB;
server->op(objA); // Send B as A
When the ORB receives an IOR of interface type B when it expects the type to
be A, it must find out if B inherits from A. When the ORB has no local knowledge
of the type B, it must work out the type of B dynamically.
The CORBA specification defines an Interface Repository (IR) from which
IDL interfaces can be queried dynamically. In the above situation, the ORB
could contact the IR to find out the type of B. However, this approach assumes
that an IR is always available and contains the up-to-date information of all the
interfaces used in the domain. This assumption may not be valid in many appli-
cations.
An alternative is to use the _is_a() operation to work out the actual type
of an object. This approach is simpler and more robust than the previous one
because no 3rd party is involved, so this is what omniORB does.
class Object{
CORBA::Boolean _is_a(const char* type_id);
};
Notice that the _is_a() call is not performed when the IOR is unmarshalled.
It is performed just prior to the first application invocation on the object. This
leads to some interesting failure modes if B reports that it is not an A. Consider
the following example:
// IDL
interface A { ... };
interface B : A { ... };
interface D { ... };
interface C {
A op1();
Object op2();
};
1 // C++
2 C_ptr objC;
3 A_ptr objA;
4 CORBA::Object_ptr objR;
5
6 objA = objC->op1();
7 (void) objA->_non_existent();
8
9 objR = objC->op2();
10 objA = A::_narrow(objR);
Case 2 C::op1() and C::op2() return a D. This condition only occurs if the
runtime of the remote end is buggy. Even though the IDL definitions show
that D is not derived from A, omniORB gives it the benefit of the doubt,
in case it actually has a more derived interface that is derived from both
A and D. At line 7, the object is contacted to ask if it is an A. The answer
is no, so a CORBA::INV_OBJREF exception is raised. At line 10, the narrow
operation will fail, and objA will be set to nil.
Case 2 C::op1() and C::op2() return a D. This condition only occurs if the
runtime of the remote end is buggy. Line 6 completes and no exception is
raised. At line 7, the object is contacted to ask if it is an A. If the answer
CHAPTER 13. INTERFACE TYPE CHECKING 126
omniORB’s stubs can be packaged into shared libraries or DLLs. On Unix plat-
forms this is mostly painless, but on Windows things are slightly more tricky.
On Unix platforms, the linker figures out how to link the symbols exported by a
library in to the running program. On Windows, unfortunately, you have to tell
the linker where symbols are coming from. This causes all manner of difficulties.
To (statically) link with a DLL file in Windows, you link with a LIB file which
references the symbols exported from the DLL. To build the LIB and DLL files,
127
CHAPTER 14. PACKAGING STUBS INTO DLLS 128
the correct symbols must be exported. One way to do that is to decorate the
source code with magic tags that tell the compiler to export the symbols. The
alternative is to provide a DEF file that lists all the symbols to be exported.
omniORB uses a DEF file.
The question is, how do you create the DEF file? The answer is to use a
Python script named makedeffile.py that lives in the bin\scripts directory
in the omniORB distribution. makedeffile.py runs the dumpbin program that
comes with Visual C++, and processes its output to extract the necessary sym-
bols. Although it is designed for exporting the symbols from omniORB stub files,
it can actually be used for arbitrary C++ code. To use it to create a DLL from a
single source file, use the following steps:
2. Build a static library (It probably won’t work on its own due to the -MD
switch to cl, but we just need it to get the symbols out):
lib -out:foo_static.lib foo.o
Of course, you can link together many separate C++ files, rather than just
the one shown here.
As if exporting the symbols from a DLL was not complicated enough, any con-
stant values exported by a DLL have to be explicitly imported into the code using
them. omniORB’s stub files declare a number of such constants. This time, the
constant declarations in the generated header files are decorated in a way that
tells the compiler what to do. When the stub headers are #included, the correct
pre-processor defines must be set. If things are not set correctly, the code all
links without problems, but then mysteriously blows up at run time.
Depending on how complex your situation is, there are a range of solutions.
Starting with the simplest, here are some scenarios you may find yourself in:
1. All stub code, and all code that uses it is wrapped up in a single DLL.
Do nothing special.
CHAPTER 14. PACKAGING STUBS INTO DLLS 129
2. All stub code is in a single DLL. Code using it is in another DLL, or not in
a DLL at all.
#define USE_stub_in_nt_dll before #include of the stub headers.
3. The stubs for each IDL file are in separate DLLs, one DLL per IDL file.
In this case, if the IDL files #include each other, then when the stub files
are compiled, import declarations are needed so that references between
the separate DLLs work. To do this, first compile the IDL files with the
-Wbdll_stubs flag:
omniidl -bcxx -Wbdll_stubs example.idl
Then define the INCLUDED_stub_in_nt_dll pre-processor symbol when
compiling the stub files. As above, define USE_stub_in_nt_dll when in-
cluding the stub headers into application code.
4. Stubs and application code are packaged into multiple DLLs, but DLLs
contain the stubs for more than one IDL file.
This situation is handled by ‘annotating’ the IDL files to indicate which
DLLs they will be compiled into. The annotation takes the form of some
#ifdefs to be inserted in the stub headers. For example,
// one.idl
#include <two.idl>
module ModuleOne {
...
};
// two.idl
#include <three.idl>
...
CHAPTER 14. PACKAGING STUBS INTO DLLS 130
Resources
• The omniORB mailing list is the first port of call for questions that are not
answered in this document or in the FAQ. Subscription information and
archives are at https://www.omniorb.net/list.html
131
Bibliography
132