The omniORB version 4.3
Users’ Guide

Duncan Grisby
(dgrisby@apasphere.com)

Contents

Chapter 1 Introduction

omniORB is an Object Request Broker (ORB) that implements version 2.6 of the Common Object Request Broker Architecture (CORBA) [] specification. Where possible, backward compatibility has been maintained back to specification 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 applications. 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:

1.1.1 Multithreading

omniORB is fully multithreaded. To achieve low call overhead, unnecessary call multiplexing is eliminated. With the default policies, there is at most one call in-flight in each communication channel between two address spaces at any one time. To do this without limiting the level of concurrency, new channels connecting the two address spaces are created on demand and cached when there are concurrent calls in progress. Each channel is served by a dedicated thread. This arrangement provides maximal concurrency and eliminates any thread switching in either of the address spaces to process a call. Furthermore, to maximise the throughput in processing large call arguments, large data elements are sent as soon as they are processed while the other arguments are being marshalled. With GIOP 1.2, large messages are fragmented, so the marshaller can start transmission before it knows how large the entire message will be.

omniORB also supports a flexible thread pool policy, and supports sending multiple interleaved calls on a single connection. This policy leads to a small amount of additional call overhead, compared to the default thread per connection model, but allows omniORB to scale to extremely large numbers of concurrent clients.

1.1.2 Portability

omniORB runs on many flavours of Unix, Windows, several embedded operating systems, and relatively obscure systems such as OpenVMS and Fujitsu-Siemens BS2000. It is designed to be easy to port to new platforms. The IDL to C++ mapping for all target platforms is the same.

omniORB uses real C++ exceptions and nested classes. It keeps to the CORBA specification’s standard mapping as much as possible and does not use the alternative mappings for C++ dialects. The only small exception is the mapping of IDL modules, which can use either namespaces according to the standard, or nested classes for truly ancient C++ compilers without namespace support.

omniORB relies on native thread libraries to provide multithreading capability. A small class library (omnithread []) is used to encapsulate the APIs of the native thread libraries. In application code, it is recommended but not mandatory to use this class library for thread management. It should be easy to port omnithread to any platform that either supports the POSIX thread standard or has a thread package that supports similar capabilities.

Partly for historical reasons, and partly to support users with archaic compilers, omniORB does not use the C++ standard library.

The omniORB IDL compiler, omniidl, requires Python version 3.5 or later or, for people stuck in the past, version 2.7.

1.1.3 Missing features

omniORB is not a complete implementation of the CORBA 2.6 core. The following is a list of the most significant missing features.

1.2 Setting up your environment

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 according to your required setup. The configuration can be set with a configuration file, environment variables, command-line arguments or, on Windows, the Windows registry.

omniORB has a large number of parameters than can be configured. See chapter ?? for full details. The files sample.cfg and sample.reg contain an example configuration file and set of registry entries respectively.

To get all the omniORB examples running, the main thing you need to configure is the Naming service, omniNames. To do that, the configuration file or registry should contain an entry of the form

  InitRef = NameService=corbaname::my.host.name

See section ?? for full details of corbaname URIs.

1.3 Platform specific variables

To compile omniORB programs correctly, several C++ preprocessor defines must be specified to identify the target platform. On Unix platforms where omniORB was configured with Autoconf, the omniconfig.h file sets these for you. On other platforms, and Unix platforms when Autoconf is not used, you must specify the following defines:

PlatformCPP defines
Windows__x86__ __NT__ __OSVERSION__=4 __WIN32__
Windows NT 3.5__x86__ __NT__ __OSVERSION__=3 __WIN32__
Sun Solaris 2.5__sparc__ __sunos__ __OSVERSION__=5
HPUX 10.x__hppa__ __hpux__ __OSVERSION__=10
HPUX 11.x__hppa__ __hpux__ __OSVERSION__=11
IBM AIX 4.x__aix__ __powerpc__ __OSVERSION__=4
Digital Unix 3.2__alpha__ __osf1__ __OSVERSION__=3
Linux 2.x (x86)__x86__ __linux__ __OSVERSION__=2
Linux 2.x (powerpc)__powerpc__ __linux__ __OSVERSION__=2
OpenVMS 6.x (alpha)__alpha__ __vms __OSVERSION__=6
OpenVMS 6.x (vax)__vax__ __vms __OSVERSION__=6
SGI Irix 6.x__mips__ __irix__ __OSVERSION__=6
Reliant Unix 5.43__mips__ __SINIX__ __OSVERSION__=5
ATMos 4.0__arm__ __atmos__ __OSVERSION__=4
NextStep 3.x__m68k__ __nextstep__ __OSVERSION__=3
Unixware 7__x86__ __uw7__ __OSVERSION__=5

The preprocessor defines for new platform ports not listed above can be found in the corresponding platform configuration files. 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

In this chapter, we go through three examples to illustrate the practical steps to use omniORB. By going through the source code of each example, the essential concepts and APIs are introduced. If you have no previous experience with using CORBA, you should study this chapter in detail. There are pointers to other essential documents you should be familiar with.

If you have experience with using other ORBs, you should still go through this chapter because it provides important information about the features and APIs that are necessarily omniORB specific. With the Portable Object Adapter, there are very few omniORB specific details.

2.1 The Echo Object Example

Our example is an object which has only one method. The method simply echos the argument string. We have to:

  1. define the object interface in IDL
  2. use the IDL compiler to generate the stub code, which provides the object mapping as defined in the CORBA specification
  3. provide the servant object implementation
  4. write the client code.

These examples are in the src/examples/echo directory of the omniORB distribution; there are several other examples in src/examples.

2.2 Specifying the Echo interface in IDL

We define an object interface, called Echo, as follows:

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 []. 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. Therefore, 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.

2.3 Generating the C++ stubs

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:

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 ?? 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

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 ??.

2.4 Object References and Servants

We contact a CORBA object through an object reference. The actual implementation of a CORBA object is termed a servant.

Object references and servants are quite separate entities, and it is important not to confuse the two. Client code deals purely with object references, so there can be no confusion; object implementation code must deal with both object references and servants. omniORB uses distinct C++ types for object references and servants, so the C++ compiler will complain if you use a servant when an object reference is expected, or vice-versa.

2.5 A quick look at the C++ mapping

The C++ stubs conform to the standard mapping defined in the CORBA specification []. Sadly, since it pre-dates the C++ standard library, the C++ language mapping is quite hard to use, especially because it has complex memory 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.

2.5.1 Mapping overview

For interface Echo, omniidl generates four things of note:

2.5.2 Interface scope type

A C++ class Echo is defined to hold a number of static functions and type definitions. It looks like this:

class Echo { public: typedef Echo_ptr _ptr_type; typedef Echo_var _var_type; static _ptr_type _duplicate(_ptr_type); static _ptr_type _narrow(CORBA::Object_ptr); static _ptr_type _nil(); };

The _ptr_type and _var_type typedefs are there to facilitate template programming. The static functions are described below.

2.5.3 Object reference pointer type

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); }; typedef something Echo_ptr;

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 omniORB, it is not—the object reference type is distinct from class Echo.

2.5.3.1 Nil object reference

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.

2.5.3.2 Object reference lifecycle

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 interface. 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 };

Once you have called CORBA::release() on an object reference, you may no longer use that reference. This is because the associated resources may have been deallocated. Remember that we are referring to the resources associated with the object reference and not the servant object. Servant objects are not affected by the lifetimes of object references. In particular, servants are not deleted when all references to them have been released—CORBA does not perform distributed garbage collection.

Nil object references are not reference counted, so there is no need to call _duplicate() and release() with them, although it does no harm.

Since object references must be released explicitly, their usage is prone to error and can lead to memory leaks or invalid memory accesses. The mapping defines the object reference variable type Echo_var to make life somewhat easier.

The Echo_var is more convenient to use because it automatically releases its object reference when it goes out of scope or when assigned a new object reference. For many operations, mixing data of type Echo_var and Echo_ptr is possible without any explicit operations or casting. For instance, the echoString() operation can be called using the arrow (‘->’) on a Echo_var, as one can do with a Echo_ptr.

The usage of Echo_var is illustrated below:

Echo_var a; Echo_ptr p = ... // somehow obtain an object reference a = p; // a assumes ownership of p, must not use p any more Echo_var b = a; // implicit _duplicate p = ... // somehow obtain another object reference a = Echo::_duplicate(p); // release old object reference // a now holds a copy of p.

The mappings of many other IDL data types include _var types with similar semantics.

2.5.3.3 Object reference inheritance

All CORBA objects inherit from the generic object CORBA::Object. CORBA::Object_ptr is the object reference type for base CORBA::Object. Object references 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

An object reference such as Echo_ptr can be used in places where a CORBA::Object_ptr is expected. Conversely, the Echo::_narrow() function takes an argument of type CORBA::Object_ptr and returns a new object reference of the Echo interface. If the actual (runtime) type of the argument object reference can be narrowed to Echo_ptr, _narrow() will return a valid object reference. Otherwise it will return a nil object reference. Note that _narrow() performs an implicit duplication of the object reference, so the result must be released. Note also that _narrow() may involve a remote call to check the type of the object, so it may throw CORBA system exceptions such as TRANSIENT or OBJECT_NOT_EXIST.

2.5.3.4 Object reference equivalence

As described above, the equality operator== should not be used on object references. 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

_is_equivalent() does not contact the object to check for equivalence—it uses purely local knowledge, meaning that it is possible to construct situations in which two object references refer to the same object, but _is_equivalent() does not consider them equivalent. If you need a strong sense of object identity, you must implement it with explicit IDL operations.

2.5.4 Servant Object Implementation

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(); virtual char * echoString(const char* mesg) = 0; };

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 signature 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 object 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 deallocated via CORBA::release(). See section ?? for an example of how this function is used.

2.6 Writing the servant implementation

You define a class to provide the servant implementation. There is little constraint on how you design your implementation class except that it has to inherit from the skeleton class1 and to implement all the abstract functions defined in the skeleton class. Each of these abstract functions corresponds to an operation 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); }; char* Echo_i::echoString(const char* mesg) { return CORBA::string_dup(mesg); }

There are four points to note here:

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 object 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 implementation 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.

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.

2.7 Writing the client

Here is an example of how an Echo_ptr object reference is used.

1void 2hello(CORBA::Object_ptr obj) 3{ 4 Echo_var e = Echo::_narrow(obj); 5 6 if (CORBA::is_nil(e)) { 7 cerr << "cannot invoke on a nil object reference." 8 << endl; 9 return; 10 } 11 12 CORBA::String_var src = (const char*) "Hello!"; 13 CORBA::String_var dest; 14 15 dest = e->echoString(src); 16 17 cout << "I said, \"" << src << "\"." 18 << " The Object said,\"" << dest <<"\"" << endl; 19}

The hello() function accepts a generic object reference. The object reference (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 allocate data items on the heap, it is a good practice to use the T_var types to manage the heap storage.

2.8 Example 1 — Colocated Client and Servant

Having introduced the client and the object implementation, we can now describe 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:

1int 2main(int argc, char **argv) 3{ 4 CORBA::ORB_ptr orb = CORBA::ORB_init(argc, argv, "omniORB4"); 5 6 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); 7 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj); 8 9 PortableServer::Servant_var<Echo_i> myecho = new Echo_i(); 10 PortableServer::ObjectId_var myechoid = poa->activate_object(myecho); 11 12 Echo_var myechoref = myecho->_this(); 13 14 PortableServer::POAManager_var pman = poa->the_POAManager(); 15 pman->activate(); 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:

2.8.1 ORB initialisation

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 processes 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 arguments, or an invalid configuration file, the CORBA::INITIALIZE system exception is raised.

2.8.2 Obtaining the Root POA

Lines 6–7

To activate our servant object and make it available to clients, we must register it with a POA. In this example, we use the Root POA, rather than creating 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[] for details of all the POA policies which are available.

2.8.3 Object initialisation

Line 9

An instance of the Echo servant is initialised using the new operator. The PortableServer::Servant_var<> template 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 references 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.

2.8.4 Activating the POA

Lines 14–15

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!

2.8.5 Performing a call

Line 17

At long last, we can call hello() with this object reference. The argument is widened implicitly to the generic object reference CORBA::Object_ptr.

2.8.6 ORB destruction

Line 19

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.

2.9 Example 2 — Different Address Spaces

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.

2.9.1 Making a Stringified Object Reference

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.

1int main(int argc, char** argv) 2{ 3 CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); 4 5 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); 6 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj); 7 8 PortableServer::Servant_var<Echo_i> myecho = new Echo_i(); 9 10 PortableServer::ObjectId_var myechoid = poa->activate_object(myecho); 11 12 obj = myecho->_this(); 13 CORBA::String_var sior(orb->object_to_string(obj)); 14 cerr << sior << endl; 15 16 PortableServer::POAManager_var pman = poa->the_POAManager(); 17 pman->activate(); 18 19 orb->run(); 20 orb->destroy(); 21 return 0; 22}

The stringified object reference is obtained by calling the ORB’s object_to_string() function (line 13). This results in a string starting with the signature ‘IOR:’ and followed by quite a lot of hexadecimal digits. All CORBA compliant ORBs are able to convert the string into its internal representation of a so-called Interoperable Object Reference (IOR). The IOR contains the location information and a key to uniquely identify the object implementation in its own address space. From the IOR, an object reference can be constructed.

2.9.2 Client: Using a Stringified Object Reference

The stringified object reference is passed to the client as a command-line argument. The client uses the ORB’s string_to_object() function to convert the string into a generic object reference (CORBA::Object_ptr). The relevant section of the code is reproduced below. The full listing (eg2_clt.cc) can be found at the end of this chapter.

try { CORBA::Object_var obj = orb->string_to_object(argv[1]); hello(obj); } catch (CORBA::TRANSIENT&) { ... // code to handle transient exception... }

2.9.3 Catching System Exceptions

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 fragment, shown in section ??, 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.

2.9.4 Lifetime of a CORBA object

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 active 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 chapter ?? 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 path names to the object references. CORBA defines a standard naming service, which is a component of the Common Object Services (COS) [], that can be used for this purpose. The next section describes an example of how to use the COS Naming Service.

2.10 Example 3 — Using the Naming Service

In this example, the object implementation uses the Naming Service [] 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 implementation (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 components. 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 naming contexts. 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. However, 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.

2.10.1 Obtaining the Root Context Object Reference

The initial contact with the Naming Service can be established via the root context. The object reference to the root context is provided by the ORB and can be obtained by calling resolve_initial_references(). The following code fragment shows how it is used:

CORBA::ORB_ptr orb = CORBA::ORB_init(argc,argv); CORBA::Object_var obj = orb->resolve_initial_references("NameService"); CosNaming::NamingContext_var rootContext; rootContext = CosNaming::NamingContext::_narrow(obj);

Remember from section ??, omniORB constructs its internal list of initial references at initialisation time using the information provided in the configuration 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.

2.10.2 The Naming Service Interface

It is beyond the scope of this chapter to describe in detail the Naming Service interface. You should consult the CORBA services specification [] (chapter 3). The code listed in eg3_impl.cc and eg3_clt.cc are good examples of how the service can be used.

2.11 Example 4 — Using tie implementation templates

omniORB supports tie implementation templates as an alternative way of providing servant classes. If you use the -Wbtp option to omniidl, it generates an extra template class for each interface. This template class can be used to tie a C++ class to the skeleton class of the interface.

The source code in eg3_tieimpl.cc at the end of this chapter illustrates how the template class can be used. The code is almost identical to eg3_impl.cc with only a few changes.

Firstly, the servant class Echo_i does not inherit from any skeleton classes. This is the main benefit of using the template class because there are applications in which it is difficult to require every servant class to derive from CORBA classes.

Secondly, the instantiation of a CORBA object now involves creating an instance of the implementation class and an instance of the template. Here is the relevant code fragment:

class Echo_i { ... }; Echo_i *myimpl = new Echo_i(); POA_Echo_tie<Echo_i> myecho(myimpl); PortableServer::ObjectId_var myechoid = poa->activate_object(&myecho);

For interface Echo, the name of its tie implementation template is POA_Echo_tie. The template parameter is the servant class that contains an implementation 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 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.

2.12 Source Listings

2.12.1 eg1.cc

// eg1.cc - This is the source code of example 1 used in Chapter 2 // "The Basics" of the omniORB user guide. // // In this example, both the object implementation and the // client are in the same process. // // Usage: eg1 // #include <echo.hh> #include <iostream> using namespace std; // This is the object implementation. class Echo_i : public POA_Echo { public: inline Echo_i() {} virtual ~Echo_i() {} virtual char* echoString(const char* mesg); }; char* Echo_i::echoString(const char* mesg) { // Memory management rules say we must return a newly allocated // string. return CORBA::string_dup(mesg); } ////////////////////////////////////////////////////////////////////// // This function acts as a client to the object. static void hello(Echo_ptr e) { if( CORBA::is_nil(e) ) { cerr << "hello: The object reference is nil!" << endl; return; } CORBA::String_var src = (const char*) "Hello!"; // String literals are (char*) rather than (const char*) on some // old compilers. Thus it is essential to cast to (const char*) // here to ensure that the string is copied, so that the // CORBA::String_var does not attempt to 'delete' the string // literal. CORBA::String_var dest = e->echoString(src); cout << "I said, \"" << (char*)src << "\"." << endl << "The Echo object replied, \"" << (char*)dest <<"\"." << endl; } ////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { try { // Initialise the ORB. CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); // Obtain a reference to the root POA. CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); PortableServer::POA_var poa = PortableServer::POA::_narrow(obj); // We allocate the servant (implementation object) on the heap. // The servant is reference counted. We start out holding a // reference, and when the object is activated, the POA holds // another reference. The PortableServer::Servant_var<> template // automatically releases our reference when it goes out of scope. PortableServer::Servant_var<Echo_i> myecho = new Echo_i(); // Activate the object. This tells the POA that this object is // ready to accept requests. PortableServer::ObjectId_var myechoid = poa->activate_object(myecho); // Obtain a reference to the object. Echo_var myechoref = myecho->_this(); // Obtain a POAManager, and tell the POA to start accepting // requests on its objects. PortableServer::POAManager_var pman = poa->the_POAManager(); pman->activate(); // Do the client-side call. hello(myechoref); // Clean up all the resources. orb->destroy(); } catch (CORBA::SystemException& ex) { cerr << "Caught CORBA::" << ex._name() << endl; } catch (CORBA::Exception& ex) { cerr << "Caught CORBA::Exception: " << ex._name() << endl; } return 0; }

2.12.2 eg2_impl.cc

// eg2_impl.cc - This is the source code of example 2 used in Chapter 2 // "The Basics" of the omniORB user guide. // // This is the object implementation. // // Usage: eg2_impl // // On startup, the object reference is printed to cout as a // stringified IOR. This string should be used as the argument to // eg2_clt. // #include <echo.hh> #include <iostream> using namespace std; class Echo_i : public POA_Echo { public: inline Echo_i() {} virtual ~Echo_i() {} virtual char* echoString(const char* mesg); }; char* Echo_i::echoString(const char* mesg) { cout << "Upcall: " << mesg << endl; return CORBA::string_dup(mesg); } ////////////////////////////////////////////////////////////////////// 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); PortableServer::Servant_var<Echo_i> myecho = new Echo_i(); PortableServer::ObjectId_var myechoid = poa->activate_object(myecho); // Obtain a reference to the object, and print it out as a // stringified IOR. obj = myecho->_this(); CORBA::String_var sior(orb->object_to_string(obj)); cout << sior << endl; PortableServer::POAManager_var pman = poa->the_POAManager(); pman->activate(); // Block until the ORB is shut down. 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; }

2.12.3 eg2_clt.cc

// eg2_clt.cc - This is the source code of example 2 used in Chapter 2 // "The Basics" of the omniORB user guide. // // This is the client. The object reference is given as a // stringified IOR on the command line. // // Usage: eg2_clt <object reference> // #include <echo.hh> #include <iostream> using namespace std; static void hello(Echo_ptr e) { CORBA::String_var src = (const char*) "Hello!"; CORBA::String_var dest = e->echoString(src); cout << "I said, \"" << (char*)src << "\"." << endl << "The Echo object replied, \"" << (char*)dest <<"\"." << endl; } ////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { try { CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); if (argc != 2) { cerr << "usage: eg2_clt <object reference>" << endl; return 1; } CORBA::Object_var obj = orb->string_to_object(argv[1]); Echo_var echoref = Echo::_narrow(obj); if (CORBA::is_nil(echoref)) { cerr << "Can't narrow reference to type Echo (or it was nil)." << endl; return 1; } for (CORBA::ULong count=0; count<10; count++) hello(echoref); 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; }

2.12.4 eg3_impl.cc

// eg3_impl.cc - This is the source code of example 3 used in Chapter 2 // "The Basics" of the omniORB user guide. // // This is the object implementation. // // Usage: eg3_impl // // On startup, the object reference is registered with the // COS naming service. The client uses the naming service to // locate this object. // // The name which the object is bound to is as follows: // root [context] // | // test [context] kind [my_context] // | // Echo [object] kind [Object] // #include <echo.hh> #include <iostream> using namespace std; static CORBA::Boolean bindObjectToName(CORBA::ORB_ptr, CORBA::Object_ptr); class Echo_i : public POA_Echo { public: inline Echo_i() {} virtual ~Echo_i() {} virtual char* echoString(const char* mesg); }; char* Echo_i::echoString(const char* mesg) { return CORBA::string_dup(mesg); } ////////////////////////////////////////////////////////////////////// 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); PortableServer::Servant_var<Echo_i> myecho = new Echo_i(); PortableServer::ObjectId_var myechoid = poa->activate_object(myecho); // Obtain a reference to the object, and register it in // the naming service. obj = myecho->_this(); CORBA::String_var sior(orb->object_to_string(obj)); cout << sior << endl; if (!bindObjectToName(orb, obj)) return 1; PortableServer::POAManager_var pman = poa->the_POAManager(); pman->activate(); 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: CORBA::Object_var obj = orb->resolve_initial_references("NameService"); // Narrow the reference returned. rootContext = CosNaming::NamingContext::_narrow(obj); if (CORBA::is_nil(rootContext)) { cerr << "Failed to narrow the root naming context." << endl; return 0; } } catch (CORBA::NO_RESOURCES&) { cerr << "Caught NO_RESOURCES exception. You must configure omniORB " << "with the location" << endl << "of the naming service." << endl; return 0; } catch (CORBA::ORB::InvalidName&) { // This should not happen! cerr << "Service required is invalid [does not exist]." << endl; return 0; } 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 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; } } // Bind objref with name Echo to the testContext: CosNaming::Name objectName; objectName.length(1); objectName[0].id = (const char*) "Echo"; // string copied objectName[0].kind = (const char*) "Object"; // string copied 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; }

2.12.5 eg3_clt.cc

// eg3_clt.cc - This is the source code of example 3 used in Chapter 2 // "The Basics" of the omniORB user guide. // // This is the client. It uses the COS naming service // to obtain the object reference. // // Usage: eg3_clt // // // On startup, the client lookup the object reference from the // COS naming service. // // The name which the object is bound to is as follows: // root [context] // | // text [context] kind [my_context] // | // Echo [object] kind [Object] // #include <echo.hh> #include <iostream> using namespace std; static void hello(Echo_ptr e) { if (CORBA::is_nil(e)) { cerr << "hello: The object reference is nil!\n" << endl; return; } CORBA::String_var src = (const char*) "Hello!"; CORBA::String_var dest = e->echoString(src); cerr << "I said, \"" << (char*)src << "\"." << endl << "The Echo object replied, \"" << (char*)dest <<"\"." << endl; } ////////////////////////////////////////////////////////////////////// int main (int argc, char **argv) { try { CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); // We use a corbaname URI to resolve the name const char* uri = "corbaname:rir:#test.my_context/Echo.Object"; CORBA::Object_var obj = orb->string_to_object(uri); Echo_var echoref = Echo::_narrow(obj); for (CORBA::ULong count=0; count < 10; count++) hello(echoref); orb->destroy(); return 0; } catch (CORBA::TRANSIENT&) { cerr << "Caught system exception TRANSIENT -- unable to contact the " << "server." << endl; } catch (CORBA::NO_RESOURCES&) { cerr << "Caught NO_RESOURCES exception." << endl << "You must configure omniORB with the location of the naming service." << endl; } catch (CORBA::BAD_PARAM&) { cerr << "Caught BAD_PARAM exception." << endl << "The object is not registered in the naming service." << endl; } catch (CORBA::SystemException& ex) { cerr << "Caught a CORBA::" << ex._name() << endl; } catch (CORBA::Exception& ex) { cerr << "Caught CORBA::Exception: " << ex._name() << endl; } return 1; }

2.12.6 eg3_tieimpl.cc

// eg3_tieimpl.cc - This example is similar to eg3_impl.cc except that // the tie implementation skeleton is used. // // This is the object implementation. // // Usage: eg3_tieimpl // // On startup, the object reference is registered with the // COS naming service. The client uses the naming service to // locate this object. // // The name which the object is bound to is as follows: // root [context] // | // test [context] kind [my_context] // | // Echo [object] kind [Object] // #include <echo.hh> #include <iostream> using namespace std; static CORBA::Boolean bindObjectToName(CORBA::ORB_ptr, CORBA::Object_ptr); // This is the object implementation. Notice that it does not inherit // from any skeleton class, and notice that the echoString() member // function does not have to be virtual. class Echo_i { public: inline Echo_i() {} inline ~Echo_i() {} char* echoString(const char* mesg); }; char* Echo_i::echoString(const char* mesg) { return CORBA::string_dup(mesg); } ////////////////////////////////////////////////////////////////////// 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); // Note that the <myecho> tie object is constructed on the stack // here. It will delete its implementation (myimpl) when it it // itself destroyed (when it goes out of scope). It is essential // however to ensure that such servants are not deleted whilst // still activated. // // Tie objects can of course be allocated on the heap using new, // in which case they are deleted when their reference count // becomes zero, as with any other servant object. Echo_i* myimpl = new Echo_i(); POA_Echo_tie<Echo_i> myecho(myimpl); PortableServer::ObjectId_var myechoid = poa->activate_object(&myecho); // Obtain a reference to the object, and register it in // the naming service. obj = myecho._this(); if (!bindObjectToName(orb, obj)) return 1; PortableServer::POAManager_var pman = poa->the_POAManager(); pman->activate(); 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: CORBA::Object_var obj = orb->resolve_initial_references("NameService"); // Narrow the reference returned. rootContext = CosNaming::NamingContext::_narrow(obj); if (CORBA::is_nil(rootContext)) { cerr << "Failed to narrow the root naming context." << endl; return 0; } } catch (CORBA::NO_RESOURCES&) { cerr << "Caught NO_RESOURCES exception. You must configure omniORB " << "with the location" << endl << "of the naming service." << endl; return 0; } catch (CORBA::ORB::InvalidName&) { // This should not happen! cerr << "Service required is invalid [does not exist]." << endl; return 0; } 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 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; } } // Bind objref with name Echo to the testContext: CosNaming::Name objectName; objectName.length(1); objectName[0].id = (const char*) "Echo"; // string copied objectName[0].kind = (const char*) "Object"; // string copied 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; }

1
Rather than deriving from the skeleton class, an alternative is to use a tie template, described in section ??.
2
In the previous 1.0 version of the C++ mapping, servant reference counting was optional, chosen by inheriting from a mixin class named RefCountServantBase. That has been deprecated in the 1.1 version of the C++ mapping, but the class is still available as an empty struct, so existing code that inherits from RefCountServantBase will continue to work.
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.
5
For backwards compatibility, the ORB identifiers ‘omniORB2’ and ‘omniORB3’ are also accepted.
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.
8
There are escaping rules to cope with id and kind fields which contain ‘.’ and ‘/’ characters. See chapter ?? of this manual, and chapter 3 of the CORBA services specification, as updated for the Interoperable Naming Service [].

Chapter 3 C++ language mapping

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 []. 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++’ [] includes many example code fragments to illustrate how to use the C++ mapping.

3.1 omniORB 2 BOA compatibility

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 specification rectifies that. For compatibility, omniORB 4 still supports the old omniORB 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 specification 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.

3.2 omniORB 3.0 compatibility

omniORB 4 is almost completely source-code compatible with omniORB 3.0. There are two main cases where code may have to change. The first is code that uses the omniORB API, some aspects of which have changed. The omniORB configuration file also has a new format. See the next chapter for details of the new API and configuration file.

The second case of code that may have to change is code using the Dynamic Any interfaces. The standard changed quite significantly between CORBA 2.2 and CORBA 2.3; omniORB 3.0 supported the old CORBA 2.2 interfaces; omniORB 4 uses the new mapping. The changes are largely syntax changes, rather than semantic differences.

3.3 omniORB 4.0 compatibility

omniORB 4.3 is source-code compatible with omniORB 4.0, with four exceptions:

  1. As required by the 1.1 version of the CORBA C++ mapping specification, the RefCountServantBase class has been deprecated, and the reference counting functionality moved into ServantBase. For backwards compatibility, RefCountServantBase still exists, but is now defined as an empty struct. Most code will continue to work unchanged, but code that explicitly calls RefCountServantBase::_add_ref() or _remove_ref() will no longer compile.
  2. omniORB 4.0 had an option for Any extraction semantics that was compatible with omniORB 2.7, where ownership of extracted values was not maintained by the Any. That option is no longer available.
  3. The members of the clientSendRequest interceptor have been changed, replacing all the separate variables with a single member of type GIOP_C. All the values previously available can be accessed through the GIOP_C instance.
  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 immediately marshalled into the Any’s internal buffer, and the sequence was deleted. Since 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 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.

3.4 omniORB 4.1 compatibility

omniORB 4.3 is source-code compatible with omniORB 4.1 with two exceptions:

  1. When omniORB 4.1 and earlier detected a timeout condition, they would throw the CORBA::TRANSIENT system exception. omniORB 4.2 and later support the CORBA::TIMEOUT system exception that was introduced with the CORBA Messaging specification. Application code that caught CORBA::TRANSIENT to handle timeouts should be changed to catch CORBA::TIMEOUT instead. Alternatively, to avoid code changes, omniORB can be configured to throw CORBA::TRANSIENT for timeouts, by setting the throwTransientOnTimeOut parameter to 1. See section ??.
  2. sslContext has moved to the omni namespace.

3.5 omniORB 4.2 compatibility

omniORB 4.3 is source-code compatible with omniORB 4.2, with one exception:

  1. sslContext has moved to the omni namespace.

3.6 Interoperability

In general, all versions of omniORB interoperate with each other, and with other CORBA implementations. There are a number of configuration options that can be set to work around interoperability with other CORBA implementations, described in section ??.

3.6.1 Exceptions in Anys

Normally, exceptions—both system exceptions and user-defined exceptions—are thrown by server operations and caught by clients. When that occurs, the GIOP protocol is completely clear that the exception is marshalled as the exception’s repository id, followed by the exception’s data members.

It is not permitted to specify an Exception as a normal operation parameter or within a constructed IDL type, but it is permitted to insert an Exception into an Any, and transmit that in an operation parameter. In that case, when the Any is marshalled, first the TypeCode is sent, and then the data value. It is somewhat ambiguous in the GIOP specification whether the value part of an Exception sent this way should contain the repository id, or not — the id is contained in the TypeCode, so sending it as part of the value too is redundant.

Versions of omniORB for C++ prior to 4.3 did not send the Exception repository id in the value part of an Any. All versions of omniORBpy do send it, as do some other CORBA implementations. For interoperability, omniORB 4.3 has changed to send the repository id. This means that it is compatible with omniORBpy and other ORBs, but that it is incompatible with previous versions of omniORB for C++. The exceptionIdInAny configuration parameter can be set to false to revert to the prior behaviour if interoperability with earlier omniORB versions is required.

Chapter 4 omniORB configuration and API

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 configuration parameters, and how they are used.

4.1 Setting parameters

When CORBA::ORB_init() is called, the value for each configuration parameter is searched for in the following order:

  1. Command line arguments
  2. ORB_init() options
  3. Environment variables
  4. Configuration file / Windows registry
  5. Built-in defaults

4.1.1 Command line arguments

Command line arguments take the form ‘-ORBparameter’, and usually expect another argument. An example is ‘-ORBtraceLevel 10’.

4.1.2 ORB_init() parameter

ORB_init()’s extra argument accepts an array of two-dimensional string arrays, like this:

const char* options[][2] = { { "traceLevel", "1" }, { 0, 0 } }; orb = CORBA::ORB_init(argc,argv,"omniORB4",options);

4.1.3 Environment variables

Environment variables consist of the parameter name prefixed with ‘ORB’. Using bash, for example

export ORBtraceLevel=10

4.1.4 Configuration file

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
Command line arguments and environment variables prefix parameter names with ‘-ORB’ and ‘ORB’ respectively, but the configuration file and the extra argument to ORB_init() do not use a prefix.

4.1.5 Windows registry

On Windows, configuration parameters can be stored in the registry, under the key HKEY_LOCAL_MACHINE\SOFTWARE\omniORB.

The file sample.reg shows the settings that can be made. It can be edited and then imported into regedit.

4.2 Tracing options

The following options control debugging trace output.

traceLevel    default = 1

omniORB can output tracing and diagnostic messages to the standard error stream. The following levels are defined:

 
level 0critical errors only
level 1informational messages only
level 2configuration information and warnings
level 5notifications when server threads are created and communication endpoints are shutdown
level 10execution and exception traces
level 25trace each send or receive of a GIOP message
level 30dump up to 128 bytes of each GIOP message
level 40dump complete contents of each GIOP message

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 invocations are logged, in addition to any logging that may have been selected with traceLevel.

traceInvocationReturns    default = 0

If the traceInvocationReturns parameter is set true, a log message is output as an operation invocation returns. In conjunction with traceInvocations and traceTime (described below), this provides a simple way of timing CORBA calls within your application.

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-threaded code, but it adds overhead to the logging so it can be disabled.

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 =

omniORB’s tracing is normally sent to stderr. If traceFile it set, the specified file name is used for trace messages.

4.2.1 Tracing API

The tracing parameters can be modified at runtime by assigning to the following variables

namespace omniORB { CORBA::ULong traceLevel; CORBA::Boolean traceExceptions; CORBA::Boolean traceInvocations; CORBA::Boolean traceInvocationReturns; CORBA::Boolean traceThreadId; CORBA::Boolean traceTime; };

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 infinite recursion as outputting a log message caused other log messages to be generated, and so on.

4.3 Miscellaneous global options

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.

scanGranularity    default = 5

As explained in chapter ??, omniORB regularly scans incoming and outgoing connections, so it can close unused ones. This value is the granularity in seconds at which the ORB performs its scans. A value of zero turns off the scanning altogether.

nativeCharCodeSet    default = ISO-8859-1

The native code set the application is using for char and string. See chapter ??.

nativeWCharCodeSet    default = UTF-16

The native code set the application is using for wchar and wstring. See chapter ??.

defaultCharCodeSet    default = none

The default code set used for char and string if the server does not specify it in its IORs. See chapter ??.

defaultWCharCodeSet    default = none

The default code set used for wchar and wstring if the server does not specify it in its IORs. See chapter ??.

copyValuesInLocalCalls    default = 1

Determines whether valuetype parameters in local calls are copied or not. See chapter ??.

abortOnInternalError    default = 0

If this is set true, internal fatal errors will abort immediately, rather than throwing the omniORB::fatalException exception. This can be helpful for tracking down bugs, since it leaves the call stack intact.

abortOnNativeException    default = 0

On Windows, ‘native’ exceptions such as segmentation faults and divide by zero appear as C++ exceptions that can be caught with catch (...). Setting this parameter to true causes such exceptions to abort the process instead.

maxSocketSend
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.

socketSendBuffer    default = -1 or 16384

On Windows, there is a kernel buffer used during send operations. A bug in Windows means that if a send uses the entire kernel buffer, a select() on the socket blocks until all the data has been acknowledged by the receiver, resulting in dreadful performance. This parameter modifies the socket send buffer from its default (8192 bytes on Windows) to the value specified. If this parameter is set to -1, the socket send buffer is left at the system default.

On Windows, the default value of this parameter is 16384 bytes; on all other platforms the default is -1.

validateUTF8    default = 0

When transmitting a string that is supposed to be UTF-8, omniORB usually passes it directly, assuming that it is valid. With this parameter set true, omniORB checks that all UTF-8 strings are valid, and throws DATA_CONVERSION if not.

4.4 Client side options

These options control aspects of client-side behaviour.

InitRef    default = none

Specify objects available from ORB::resolve_initial_references(). The arguments take the form <key>=<uri>, where key is the name given to resolve_initial_references() and uri is a valid CORBA object reference URI, as detailed in chapter ??.

DefaultInitRef    default = none

Specify the default URI prefix for resolve_initial_references(). See chapter ??.

clientTransportRule    default = * unix,tcp,ssl

Used to specify the way the client contacts a server, depending on the server’s address. See section ?? 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 ?? 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 ?? 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 performance 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 and later support 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.

outConScanPeriod    default = 120

Idle timeout in seconds for outgoing (i.e. client initiated) connections. If a connection has been idle for this amount of time, the ORB closes it. See section ??.

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 parameter. 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 maxGIOPConnectionPerServer. With this parameter set to false, the ORB will allow concurrent calls on a single connection. This saves connection resources, but requires 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

The maximum number of calls that can be interleaved on a connection. If more concurrent calls are made, they are queued.

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 ??.

diiThrowsSysExceptions    default = 0

If this is true, DII functions throw system exceptions; if it is false, system exceptions that occur are passed through the Environment object.

verifyObjectExistsAndType    default = 1

By default, omniORB uses the GIOP LOCATE_REQUEST message to verify the existence 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 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 parameter 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 according to the client transport rules (after resolving names if resolveNamesForTransportRules 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.

bootstrapAgentHostname    default = none

If set, this parameter indicates the hostname to use for look-ups using the obsolete Sun bootstrap agent. This mechanism is superseded by the interoperable naming service.

bootstrapAgentPort    default = 900

The port number for the obsolete Sun bootstrap agent.

principal    default = none

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.

4.5 Server side options

These parameters affect server-side operations.

endPoint             default = giop:tcp::
endPointPublish
endPointNoPublish
These options determine the end-points the ORB should listen on, and the details that should be published in IORs. See chapter ?? for details.

serverTransportRule    default = * unix,tcp,ssl

Configure the rules about whether a server should accept an incoming connection from a client. See section ?? 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.

inConScanPeriod    default = 180

Idle timeout in seconds for incoming connections. If a connection has been idle for this amount of time, the ORB closes it. See section ??.

threadPerConnectionPolicy    default = 1

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.

maxServerThreadPerConnection    default = 100

If the client multiplexes several concurrent requests on a single connection, omniORB uses extra threads to service them. This parameter specifies the maximum number of threads that are allowed to service a single connection at any one time.

maxServerThreadPoolSize    default = 100

The maximum number of threads the server will allocate to do various tasks, including dispatching calls in the thread pool mode. This number does not include threads dispatched under the thread per connection server mode.

threadPerConnectionUpperLimit    default = 10000

If the threadPerConnectionPolicy parameter is true, the ORB can automatically transition to thread pool mode if too many connections arrive. This parameter sets the number of connections at which thread pooling is started. The default of 10000 is designed to mean that it never happens.

threadPerConnectionLowerLimit    default = 9000

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 performed 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 ??.

connectionWatchPeriod    default = 50000

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

When a thread handles an incoming call, it unmarshals the arguments then marks the connection as watchable by the connection watching thread, in case the client sends a concurrent call on the same connection. If this parameter is set to the default false, the connection is not actually watched until the next connection watch period (determined by the connectionWatchPeriod parameter). If this parameter is set true, the connection watching thread is immediately signalled to watch the connection. That leads to faster interactive response to clients that multiplex calls, but adds significant overhead along the call chain.

Note that this setting has no effect on Windows, since it has no mechanism for signalling the connection watching thread.

acceptBiDirectionalGIOP    default = 0

Determines whether a server will ever accept clients’ offers of bidirectional GIOP connections. See section ??.

unixTransportDirectory    default = /tmp/omni-%u

(Unix platforms only). Selects the location used to store Unix domain sockets. The ‘%u’ is expanded to the user name.

unixTransportPermission    default = 0777

(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

omniORB supports the PortableServer::Current interface to provide thread context information to servants. Supporting current has a small but noticeable run-time overhead due to accessing thread specific storage, so this option allows it to be turned off.

objectTableSize    default = 0

Hash table size of the Active Object Map. If this is zero, the ORB uses a dynamically 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

If set true, servers support the Sun bootstrap agent protocol.

4.5.1 Main thread selection

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 default, 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 with it (i.e. it must have been created by omnithread, or omni_thread::create_dummy() must have been called). If it does not, the function throws CORBA::INITIALIZE.

Note that calls are only actually dispatched to the ‘main’ thread if ORB::run() or ORB::perform_work() is called from that thread.

4.6 GIOP and interoperability options

These options control omniORB’s use of GIOP, and cover some areas where omniORB can work around buggy behaviour by other ORBs.

maxGIOPVersion    default = 1.2

Choose the maximum GIOP version the ORB should support. Valid values are 1.0, 1.1 and 1.2.

giopMaxMsgSize    default = 2097152

The largest message, in bytes, that the ORB will send or receive, to avoid resource starvation. If the limit is exceeded, a MARSHAL exception is thrown. The size must be >= 8192.

giopBufferSize    default = 8192

When transmitting data, it is marshalled into a buffer, and flushed across the network when the buffer is full. If there is a large amount of data to transmit, using a relatively small buffer allows some of the data to be in transit across the network while later marshalling activity happens in parallel. However, in some circumstances it may be beneficial to use larger buffers, and so make it more likely that the complete request/response body fits in a single buffer.

giopDirectReceiveCutOff    default = 1024

Some values, such as sequences of base integer types and strings that do not require codeset conversion, have an in-memory representation that is identical to the GIOP marshalled form. When receiving such data, if the marshalled value is larger than the direct receive cut-off, omniORB directly receives from the network into the application data structure, rather than first copying it to the GIOP buffer.

giopDirectSendCutOff    default = 16384

Some values, such as sequences of base integer types and strings that do not require codeset conversion, have an in-memory representation that is identical to the GIOP marshalled form. When sending such data, if the marshalled value is larger than the direct send cut-off, omniORB directly sends it from the application data structure, rather than first copying it to the GIOP buffer.

giopMinChunkBeforeDirectSend    default = 1024

When directly sending GIOP data (due to giopDirectSendCutOff), omniO