developing distributed object - vanderbilt universityschmidt/pdf/corba4.pdf · siemens scr, siemens...
TRANSCRIPT
Developing Distributed ObjectComputing Applications with CORBA
Douglas C. SchmidtProfessor Department of [email protected] Vanderbilt Universitywww.cs.wustl.edu/�schmidt/ (615) 343-8197
SponsorsNSF, DARPA, ATD, BAE Systems, BBN, Boeing, Cisco, Comverse, GDIS, Experian,Global MT, Hughes, Kodak, Krones, Lockheed, Lucent, Microsoft, Mitre, Motorola,
NASA, Nokia, Nortel, OCI, Oresis, OTI, Qualcomm, Raytheon, SAIC, SAVVIS,Siemens SCR, Siemens MED, Siemens ZT, Sprint, Telcordia, USENIX
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Motivation: the Distributed Software Crisis
Symptoms
� Hardware gets smaller, faster, cheaper
� Software gets larger, slower, moreexpensive
Culprits
� Inherent and accidental complexity
Solution Approach
� Components, Frameworks, Patterns,& Architecture
Vanderbilt University 1
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Techniques for Improving Software
NETWORKING
DATABASE
GUI
EVENT
LOOP
APPLICATION-SPECIFIC
FUNCTIONALITY
EVENT
LOOP
EVENT
LOOP
CALL
BACKSINVOKES
(A) CLASS LIBRARY ARCHITECTURE
(B) FRAMEWORK ARCHITECTURE
DATABASE
CLASSES
NETWORK
IPCCLASSES
MATH
CLASSES
ADTCLASSES
GUICLASSES
APPLICATION-SPECIFIC
FUNCTIONALITY
EVENT
LOOP
GLUE
CODE
LOCAL
INVOCATIONS
ADTCLASSES
MATH
CLASSES
Proven solutions !
� Components– Self-contained, “pluggable”
ADTs
� Frameworks– Reusable, “semi-complete”
applications
� Patterns– Problem/solution/context
� Architecture– Families of related patterns
and components
Vanderbilt University 2
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of CORBA Middleware Architecture
INTERFACEREPOSITORY
IMPLEMENTATIONREPOSITORY
IDLCOMPILER
DII ORBINTERFACE
ORB CORE GIOP/IIOP/ESIOPS
IDLSTUBS
operation()in args
out args + return valueCLIENT
OBJECT(SERVANT)
OBJREF
STANDARD INTERFACE STANDARD LANGUAGE MAPPING
ORB-SPECIFIC INTERFACE STANDARD PROTOCOL
INTERFACEREPOSITORY
IMPLEMENTATIONREPOSITORY
IDLCOMPILER
IDLSKELETON
DSI
OBJECTADAPTER
www.cs.wustl.edu/�schmidt/corba.html
Goals of CORBA
� Simplifydistribution byautomating
– Object location &activation
– Parametermarshaling
– Demultiplexing– Error handling
� Providefoundation forhigher-levelservices
Vanderbilt University 3
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Key CORBA Concepts
� Object reference: A strongly-typedopaque handle that identifies anobject’s location
� Client: Makes requests on anobject via one of its references
� Server: Computational context(e.g., process) for objects/servants
– Client and server are “roles” - aprogram can play both roles
� Stub: A proxy that converts methodcalls into messages
� Skeleton: An adapter that convertsmessages back into method calls
� Object: A CORBAprogramming entity with anidentity, an interface, and animplementation
� Servant: A programminglanguage entity thatimplements requests on oneor more objects
� POA: A container forobjects/servants in a server
� ORB Core:Message-passinginfrastructure
Vanderbilt University 4 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
CO
RB
ATw
oway
Pro
cess
ing
Ste
ps
IMP
LE
ME
NTA
TIO
NR
EP
OS
ITO
RY
OR
B
CO
RE
IDL
ST
UB
S
op
era
tio
n()
in
arg
s
ou
t a
rgs
+ r
etu
rn
va
lue
CL
IEN
TO
BJ
EC
T(S
ER
VA
NT)
OB
JR
EF
IMP
LE
ME
NTA
TIO
NR
EP
OS
ITO
RY O
BJ
EC
TA
DA
PT
ER
1c 2c
3c
4c
1s
3s ID
LS
KE
LE
TO
N
2s
4s
Clie
ntpr
oces
sing
step
s
1cLo
cate
targ
etob
ject
2cS
entr
eque
stm
essa
geto
serv
er3c
Wai
tfor
requ
estt
oco
mpl
ete
4cR
etur
nco
ntro
lto
clie
nt
Ser
ver
proc
essi
ngst
eps
1sA
ctiv
ate
serv
er(if
nece
ssar
y)2s
Act
ivat
eob
ject
’sse
rvan
t(if
nece
ssar
y)3s
Pro
cess
requ
est
4sR
etur
nre
sult
orex
cept
ion
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Applying CORBA to Medical Imaging
DIAGNOSTIC STATIONSDIAGNOSTIC STATIONS
ATMATMMANMAN
ATM
LAN
ATM
LAN
MODALITIES
(CT, MR, CR) CENTRAL
BLOB STORE
CLUSTER
BLOB
STORE
DX
BLOB
STORE
� Domain Challenges
– Large volume of “Blob” data
� e.g., 10 to 40 Mbps– “Lossy compression” isn’t
viable– Prioritization of requests
� URLs
– �schmidt/PDF/COOTS-96.pdf
–
�schmidt/PDF/av chapter.pdf– �schmidt/NMVC.html
Vanderbilt University 6
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Applying CORBA to Real-time Avionics
REPLICATION
SERVICE
OBJECT REQUEST BROKER
1: SENSORS
GENERATE
DATA
FLIRGPS IFF
3:PUSH (EVENTS)
2: SENSOR PROXIES DEMARSHAL DATA
& PASS TO EVENT CHANNEL
3:PUSH (EVENTS)
EVENT
CHANNEL
HUD NavAir
FrameWTS
4: PULL(DATA)
� Domain Challenges
– Real-time periodicprocessing
– Complexdependencies
– Very low latency
� URLs
– �schmidt/PDF/JSAC-98.pdf
– �schmidt/TAO-boeing.html
Vanderbilt University 7
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Applying CORBA to Global PCS
WIDE AREANETWORK
SATELLITESTRACKINGSTATIONPEERS
STATUS INFO
COMMANDS BULK DATA
TRANSFER
LOCAL AREA NETWORK
GROUNDSTATIONPEERS
GATEWAY
� Domain Challenges
– Long latency satellite links– High reliability– Prioritization
� URL
– �schmidt/PDF/TAPOS-00.pdf
Vanderbilt University 8
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Tutorial Outline
� Motivation
� Example CORBA Applications
� Using CORBA to Cope with Changing Requirements
� Detailed Overview of CORBA Architecture and Features
� Evaluations and Recommendations
Vanderbilt University 9
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Motivation for COTS Middleware
� It is hard to develop distributed applications whose componentscollaborate efficiently, reliably, transparently, and scalably
� To help address this challenge, the Object Management Group(OMG) is specifying the Common Object Request BrokerArchitecture (CORBA)
� OMG is a consortium of �800 companies
– Sun, HP, DEC, IBM, IONA, Borland, Cisco, Motorola, Boeing, etc.
� The latest version of the CORBA spec is available online
– www.omg.org/technology/documents/formal/
Vanderbilt University 10
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Sources of Complexity for Distributed ApplicationsPRINTER
FILESYSTEM
PRINTER FILE SYSTEM
COMPUTER
(1) STAND-ALONE APPLICATION ARCHITECTURE
(2) DISTRIBUTED APPLICATION ARCHITECTURE
CD ROM
CD ROM
NETWORKFI LE
SERVICE
CYCLE
SERVICE
DISPLAY
SERVICE
SERVICE
NAME
SERVICE
TIME
SERVICE
� Inherent complexity
– Latency– Reliability– Partitioning– Ordering– Security
� Accidental Complexity
– Low-level APIs– Poor debugging tools– Algorithmic
decomposition– Continuous re-invention
Vanderbilt University 11
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Sources of Inherent Complexity
� Inherent complexity results from fundamental challenges in thedistributed application domain
� Key challenges of distributed computing include
– Addressing the impact of latency– Detecting and recovering from partial failures of networks and
hosts– Load balancing and service partitioning– Consistent ordering of distributed events
Vanderbilt University 12
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Sources of Accidental Complexity
� Accidental complexity results from limitations with tools andtechniques used to develop distributed applications
� In practice, key limitations of distributed computing include
– Lack of type-safe, portable, re-entrant, and extensible system callinterfaces and component libraries
– Inadequate debugging support– Widespread use of algorithmic decomposition– Continuous rediscovery and reinvention of core concepts and
components
Vanderbilt University 13
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Motivation for CORBA
� Simplifies application interworking
– Higher level integration than untyped TCP bytestreams
� Supports heterogeneity
– e.g., middleware enables applications to be independent oftransports, OS, hardware, language, location, and implementationdetails
� Benefits for distributed programming similar to OO languages
– e.g., encapsulation, interface inheritance, polymorphism, andexception handling
� Provides a foundation for higher-level distributed object collaboration
– e.g., CCM, J2EE, and CORBAServices
Vanderbilt University 14
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
CORBA Quoter Example
int main (void){
// Use a factory to bind// to a Quoter.Quoter_var quoter =
resolve_quoter_service ();
const char *name ="ACME ORB Inc.";
CORBA::Long value =quoter->get_quote (name);
cout << name << " = "<< value << endl;
}
� Ideally, a distributedservice should look justlike a non-distributedservice
� Unfortunately, life isharder when errorsoccur...
Vanderbilt University 15
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
CORBA Quoter Interface
// IDL interface is like a C++// class or Java interface.interface Quoter{
exception Invalid_Stock {};
long get_quote(in string stock_name)raises (Invalid_Stock);
};
� We write an OMGIDL interface forour Quoter
– Used by bothclients andservers
Using OMG IDL promotes language/platform independence, locationtransparency, modularity, and robustness
Vanderbilt University 16
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of OMG Interfaces
� OMG interfaces are similar toC++ abstract classes or Javainterfaces
– They define object types– Can be passed as (reference)
parameters– Can raise exceptions and– Can be forward declared
� There are several differences,however, since they
– Cannot define datamembers
– Cannot have private orprotected access controlsections
– Must designate theirparameter directions
� Only CORBA objects defined with interfaces can be accessedremotely
– However, locality constrained CORBA objects can’t be accessedremotely
Vanderbilt University 17
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of OMG Operations
� Each operation in an OMG interface must have
– A name– A return type (can be void )– Zero or more parameters
� An operation can optionally have
– A raises clause, which indicates the exceptions(s) the operationcan throw
– A oneway qualifier, which indicates the caller doesn’t expect anyresults
– A context clause, which is deprecated and non-portable...
� Due to limitations with certain programming language mappings,operations cannot be overloaded in IDL interfaces
Vanderbilt University 18 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Usi
ngan
OM
GID
LC
ompi
ler
for
C++
CLIE
NTST
UBBO
DY
CLIE
NTST
UBHE
ADER
SERV
ERSK
ELET
ONHE
ADER
SERV
ERSK
ELET
ONBO
DY
IDL
CO
MPI
LER
IDL
FILE
C++
CO
MPI
LER
C++
CO
MPI
LER
CLIE
NTSO
URCE
CODE
CLIE
NTSO
URCE
CODE
CLIE
NTSO
URCE
CODE
CLI
ENT
APPL
ICAT
ION
SERV
ERSO
URCE
CODE
SERV
ERSO
URCE
CODE
SERV
ERSO
URCE
CODE
SER
VER
APPL
ICAT
ION
CO
RB
AR
UN
-TIM
ELI
BR
AR
IES
inte
rfac
e Q
uo
ter
{
lon
g
get
_qu
ote
(in
str
ing
nam
e);
};
CLI
ENT
DEV
ELO
PER
SER
VER
DEV
ELO
PER
�
Diff
eren
tID
Lco
mpi
lers
gene
rate
diffe
rent
files
and
prov
ide
diffe
rent
optio
ns
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
OMG IDL-to-C++ Mapping Rules (1/2)
� There are mappings from OMG IDL to various programminglanguages standardized by CORBA
� Mapping OMG IDL to C++ can be classified into
– Basic C++ mapping for basic and structured types– Client-side mapping of IDL interfaces into C++ to support client
applications– Server-side C++ mapping of IDL interfaces into C++ to support
server developers– Pseudo-object C++ mapping of certain CORBA types, e.g.,
Object , ORB, and PortableServer::POA
� Memory management in C++ mapping can be tricky
Vanderbilt University 20
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
OMG IDL-to-C++ Mapping Rules (2/2)
� Sample mapping OMG IDL to C++
– Each module is mapped to a namespace (or class)– Each interface is mapped to a class– Each operation is mapped to a C++ method with appropriate
parameters– Each read/write attribute is mapped to a pair of get/set methods– An Environment is defined to carry exceptions in languages
that lack this feature
� We’ll discuss the various mapping issues as we go along
� See Henning and Vinoski for all details of IDL-to-C++ mapping
Vanderbilt University 21
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Usi
ngan
IDL
Com
pile
rfo
rC
++&
Java
CLIE
NTST
UBBO
DY
CLIE
NTST
UBHE
ADER
SERV
ERSK
ELET
ONHE
ADER
SERV
ERSK
ELET
ONBO
DY
IDL-
TO-J
AVA
CO
MPI
LERID
L FI
LE
C++
CO
MPI
LER
JAVA
CO
MPI
LER
CLIE
NTSO
URCE
CODE
CLIE
NTSO
URCE
CODE
CLIE
NTSO
URCE
CODE
CLI
ENT
APPL
ICAT
ION
SERV
ERSO
URCE
CODE
SERV
ERSO
URCE
CODE
SERV
ERSO
URCE
CODE
SER
VER
APPL
ICAT
ION
CO
RB
AR
UN
-TIM
ELI
BR
AR
IES
inte
rfac
e Q
uo
ter
{
lon
g
get
_qu
ote
(in
str
ing
nam
e);
};
CLI
ENT
DEV
ELO
PER
SER
VER
DEV
ELO
PER
IDL-
TO-C
++ C
OM
PILE
R
�
CO
RB
Am
akes
itst
raig
htfo
rwar
dto
exch
ange
data
betw
een
diffe
rent
prog
ram
min
gla
ngua
ges
indi
ffere
ntad
dres
ssp
aces
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Software Bus
:: NETWORK NETWORK
TIMETIME
:: LOCATION LOCATION
BROKERBROKER
:: TRADING TRADING
RULESRULES
:: HEARTBEAT HEARTBEAT
MONITORMONITOR
: STOCK
QUOTER: PRINTER
: AUTHEN-TICATOR
: STOCK
TRADER
: STOCK
QUOTER
SOFTWARE BUS
:: STOCK STOCK
QUOTERQUOTER
� CORBA provides a communication infrastructure for aheterogeneous, distributed collection of collaborating objects
� Analogous to “hardware bus”
Vanderbilt University 23
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
CO
RB
AO
bjec
tCol
labo
ratio
n :: NA
ME
NA
ME
SE
RV
ICE
SE
RV
ICE
:: QU
OT
E Q
UO
TE
SE
RV
ICE
SE
RV
ICE
:: AU
TH
EN
AU
TH
EN--
TIC
AT
ION
TIC
AT
ION
1:
reso
lve (
"Q
uote
r"
)1:
reso
lve (
"Q
uote
r"
):: B
RO
KE
R B
RO
KE
R
2:
au
then
ticate
(b
rok
er)
2:
au
then
ticate
(b
rok
er)
3:
tim
est
am
p()
3:
tim
est
am
p()
4:
get
_q
uote
("
AC
ME
OR
B, In
c."
)4:
get
_q
uote
("
AC
ME
OR
B, In
c."
)
:: NE
TW
OR
K N
ET
WO
RK
TIM
ET
IME
�
Col
labo
ratin
gob
ject
sca
nbe
eith
erre
mot
eor
loca
l
–i.e
.,di
strib
uted
orco
lloca
ted
�
For
this
tow
ork
tran
spar
ently
the
OR
Bsh
ould
supp
ortn
este
dup
calls
and
collo
catio
nop
timiz
atio
ns
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Communication Features of CORBA
� CORBA supports reliable,uni-cast communication
– i.e., oneway, twoway, deferredsynchronous, andasynchronous
� CORBA objects can alsocollaborate in a client/server,peer-to-peer, orpublish/subscribe manner
– e.g., COS Event & NotificationServices define a publish &subscribe communicationparadigm
operation(args)
response
requestCLIENT
TARGET
OBJECT4
POLLINGPOLLING
CLIENTCLIENT
PPOOLLLLEERR
operation(args)operation(args)
1: request
3: response
2: poller
4: get
TARGETTARGET
OBJECTOBJECT44
CALLBACKCALLBACK
CLIENTCLIENT
1: request
2: response
TARGETTARGET
OBJECTOBJECT44
3: upcall
operation(callback, args)operation(callback, args)
Vanderbilt University 25
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Fundamental CORBA Design Principles
� Separation of interface and implementation
– Clients depend on interfaces, not implementations
� Location transparency
– Service use is orthogonal to service location
� Access transparency
– Invoke operations on objects
� Typed interfaces
– Object references are typed by interfaces
� Support of multiple inheritance of interfaces
– Inheritance extends, evolves, and specializes behavior
Vanderbilt University 26
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Related Work (1/4)� Traditional Client/Server RPC (e.g., DCE)
– Servers offer a service and wait for clients to invoke remoteprocedure calls (RPCs)
– When a client invokes an RPC the server performs the requestedprocedure and returns a result
� Problems with Client/Server RPC
– Only supports “procedural” integration of application services– Doesn’t provide object abstractions, e.g., polymorphism,
inheritance of interfaces, etc.– Doesn’t support async message passing, or dynamic invocation
Vanderbilt University 27
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Related Work (2/4)
� Windows COM/DCOM/COM+
– A component model for Windows that support binary-levelintegration and reuse of components
� Problems with Windows COM/DCOM/COM+
– Largely limited to desktop applications– Does not address heterogeneous distributed computing
Vanderbilt University 28
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Related Work (3/4)
� SOAP
– A simple XML-based protocol that allows applications toexchange structured and typed information on the Web usingHTTP and MIME
– Widely implemented
� Problems with SOAP
– Considerable time/space overhead
Vanderbilt University 29
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Related Work (4/4)
� Java RMI
– Limited to Java only
� Can be extended into other languages, such as C or C++, byusing a bridge across the Java Native Interface (JNI)
– Well-suited for all-Java applications because of its tight integrationwith the Java virtual machine
� e.g., can pass both object data and code by value– However, many challenging issues remain unresolved
� e.g., security, robustness, and versioning
� J2EE and .NET
– Higher-level distributed component frameworks– Widely used in business/enterprise domains
Vanderbilt University 30
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
CORBA Stock Quoter Application Example
FDDI
OS/2 - PowerPC
SunOS - SPARC
HP/UX - HPPA
Windows NT - Alpha
Gateway/Router
MVS - IBM
WIDE AREAWIDE AREA
NETWORKNETWORK
ETHERNETETHERNET
ATMATM
LANLAN
BROKERSBROKERS
BROKERSBROKERS
QUOTEQUOTE
SERVERSSERVERS
Windows- Pentium
� The quote server(s)maintains thecurrent stock prices
� Brokers access thequote server(s) viaCORBA
� Note all theheterogeneity!
� We use this exampleto explore manyfeatures of CORBA
Vanderbilt University 31
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Sim
ple
OM
GID
LQ
uote
rD
efini
tion
module
Sto
ck{
//E
xceptio
ns
are
sim
ilar
tost
ruct
s.exc
eptio
nIn
valid
_S
tock
{};
exc
eptio
nIn
valid
_F
act
ory
{};
//In
terf
ace
issi
mila
rto
aC
++
class
.in
terf
ace
Quote
r{
long
get_
quote
(in
string
stock
_nam
e)
rais
es
(Inva
lid_S
tock
);}; //
Afa
ctory
that
create
sQ
uote
robje
cts.
inte
rface
Quote
r_F
act
ory
{//
Fact
ory
Meth
od
that
retu
rns
anew
Quote
r//
sele
cted
by
nam
ee.g
.,"D
ow
Jones,
"//
"Reute
rs,"
,etc
.Q
uote
rcr
eate
_quote
r(in
string
quote
r_se
rvic
e)
rais
es
(Inva
lid_F
act
ory
);};
}; Not
eth
eus
eof
the
Fact
ory
Met
hod
patte
rn
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of IDL Parameter Passing (1/2)
� Operation parameters in OMG IDL must be designated to have oneof the following directions:
– in , which means that the parameter is passed from the client tothe server
– out , which means that the parameter is returned from the serverto the client
– inout , which means that the parameter is passed from the clientto the server and then returned from the server to the client,overwriting the original value
� Parameter passing modes are used in CORBA to optimize the dataexchanged between client and server
Vanderbilt University 33
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of IDL Parameter Passing (2/2)
� The C++ mapping for parameter passing depend on both the typeand the direction
– Built-in in params (e.g., char and long ) passed by value– User defined in params (e.g., structs ) passed by const
reference– Strings are passed as pointers (e.g., const char *)– inout params are passed by reference– Fixed-size out params are passed by reference– Variable-size out params are allocated dynamically– Fixed-size return values are passed by value– Variable-size return values are allocated dynamically– Object reference out params and return values are duplicated
� As usual, applications can be shielded from most of these details byusing _var types
Vanderbilt University 34
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Object References (1/3)� An object reference is a strongly-typed opaque handle to one
instance of an interface that identifies the object’s location
� An object reference is an ORB-specific entity that can contain
– A repository ID, which identifies its interface type– Transport address information, e.g., a server’s TCP/IP host/port
address(es)– An object key that identifies which object in the server the request
is destined for
� An object reference similar to a C++ “pointer on steriods” that’s beenenhanced to identify objects in remote address spaces
– e.g., it can be NULL and it can reference non-existent objects
Vanderbilt University 35
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Object References (2/3)
� Object references can be passed among processes on separatehosts
– The underlying CORBA ORB will correctly convert objectreferences into a form that can be transmitted over the network
– The object stays where it is, however, and its reference is passedby value
� The ORB provides the receiver with a pointer to a proxy in its ownaddress space
– This proxy refers to the remote object implementation
� Object references are a powerful feature of CORBA
– e.g., they support peer-to-peer interactions and distributedcallbacks
Vanderbilt University 36
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Object References (3/3)
� The following is a transient object reference
– The timestamp helps ensure uniqueness across process lifetimes
iiop:1.0//pachanga:10015/P353bccdb00094ae8/firstPOA/myservant
ObjectAdapter Id
Protocol Id
CommunicationEndpoint
Time Stamp Object Id
� Persistent object references omit the timestamp to help ensureconsistency across process lifetimes
– There’s also a requirement to keep port numbers and IPaddresses consistent...
Vanderbilt University 37
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of OMG Modules
� OMG modules are similar to C++ namespaces or Java packages
– i.e., they define scopes and can be nested
� OMG modules can be reopened to enable incremental definitions,e.g.:
module Stock {interface Quoter { /* ... */ };
};// ...module Stock {
interface Quoter_Factory { /* ... */ };};
� Reopening of modules is particular useful for mutually dependentinterfaces that require forward definitions
Vanderbilt University 38
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of OMG Exceptions� Two types of exceptions in OMG IDL inherit from
CORBA::Exception :
– System exceptions (e.g., CORBA::OBJECT_NOT_EXIST), whichare predefined by the CORBA spec and must not appear in araises clause
– User exceptions (e.g., Stock::Invalid_Stock ), which canbe defined by user applications and can appear in a raisesclause
� There are various restrictions on exceptions in CORBA
– e.g., they can’t be nested or inherited and can’t be members ofother data types
Vanderbilt University 39
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Rev
ised
OM
GID
LQ
uote
rD
efini
tion
App
lyth
eC
OR
BA
Life
cycl
eS
ervi
ce
module
Sto
ck{
exc
eptio
nIn
valid
_S
tock
{};
inte
rface
Quote
r:
CosL
ifeC
ycle
::Life
Cyc
leO
bje
ct{
long
get_
quote
(in
string
stock
_nam
e)
rais
es
(Inva
lid_S
tock
);//
Inherits
://
void
rem
ove
()ra
ises
(NotR
em
ova
ble
);}; //
Manage
the
lifecy
cle
of
aQ
uote
robje
ct.
inte
rface
Quote
r_F
act
ory
:C
osL
ifeC
ycle
::G
enericF
act
ory
{//
Retu
rns
anew
Quote
rse
lect
ed
by
nam
e//
e.g
.,"D
ow
Jones,
""R
eute
rs,"
,etc
.//
Inherits
://
Obje
ctcr
eate
_obje
ct(in
Key
k,//
inC
rite
ria
crite
ria)
//ra
ises
(NoF
act
ory
,In
valid
Crite
ria,
//C
annotM
eetC
rite
ria);
};}; V
ande
rbilt
Uni
vers
ity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of OMG Object
� The CosLifeCycle::GenericFactory::create_object()factory method returns an object reference to an instance that’sderived from the CORBA::Object interface
� Since all objects implicitly inherit from CORBA::Object , all objectreferences support the following operations:
interface Object {// Reference counting methodsObject duplicate ();void release ();// Checks for existence and reference identity & relationshipsboolean is_nil ();boolean non_existent ();boolean is_equivalent (in Object another_object);boolean is_a (in string repository_id);// ...
Vanderbilt University 41
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Fixed- and Variable-size TypesCertain types are variable-size:
� Bounded or unbounded strings(as shown in theStock::Quoter example)
� Bounded or unboundedsequences
� Object references
� Type any
Other types can be variable- orfixed-size:
� structs , unions , and arraysare fixed-size if they contain onlyfixed-size fields (recursively)
� structs , unions , and arraysare variable-size if they containany variable-size fields(recursively)
� Variable-size types require the sender to dynamically allocateinstances and the receiver to deallocate instances
� Again, use _var types to simplify programming
Vanderbilt University 42 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
RP
C-
vs.
Obj
ect-
styl
eD
esig
ns
QU
OT
E
SE
RV
ER
: R
eute
rs:
Reu
ters
Qu
ote
rQ
uote
r
: D
ow
Jon
es:
Dow
Jon
esQ
uote
rQ
uote
r
: Q
uote
r:
Qu
ote
rF
act
ory
Fact
ory
QU
OT
E
CL
IEN
T
: D
ow
Jon
es:
Dow
Jon
esQ
uote
rQ
uote
rP
roxy
Pro
xy
: Q
uote
r:
Qu
ote
rF
act
ory
Fact
ory
Pro
xy
Pro
xy
get
_q
uote
()get
_q
uote
()
rem
ove(
)re
move(
)
crea
te_ob
ject
()cr
eate
_ob
ject
()
nam
en
am
e
valu
evalu
e
nam
en
am
e
Qu
ote
rQ
uote
r
: R
eute
rs:
Reu
ters
Qu
ote
rQ
uote
rP
roxy
Pro
xy
QU
OT
E C
LIE
NT
QU
OT
E S
ER
VE
R
: Q
uote
r:
Qu
ote
rP
roxy
Pro
xy
: Q
uote
r:
Qu
ote
r
get
_q
uote
()get
_q
uote
()
nam
en
am
e
valu
evalu
e
RPC RPC---STYLE STYLE OBJECT OBJECT---STYLE STYLE
: Q
uote
r:
Qu
ote
rP
roxy
Pro
xy
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Results of Compiling the Stock.idl File
Running the Stock module through the IDL compiler generates stubsand skeletons
� Each (twoway) stub is a proxy that
1. Ensures a connection to theserver is established
2. Marshals the requestparameters
3. Sends the request4. Waits to get the reply5. Demarshals the reply
parameters6. Returns to the client caller
� Each skeleton is an adapterthat
1. Demarshals the requestparameters
2. Performs an upcall on thedesignated servantmethod
3. Marshals the replyparameters
4. Sends the reply back tothe client
Vanderbilt University 44 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Ove
rvie
wof
Gen
erat
edC
lient
Stu
bs
//N
ote
C+
+m
appin
gof
IDL
module
type
nam
esp
ace
Sto
ck{
//N
ote
C+
+m
appin
gof
IDL
inte
rface
type
class
Quote
r//
Quote
rals
oIS
-AC
OR
BA
::O
bje
ct.
:public
virt
ual
CosL
ifeC
ycle
::Life
Cyc
leO
bje
ct{
public
://
Note
C+
+m
appin
gof
IDL
long
and
string
types
CO
RB
A::Long
get_
quote
(const
char
*sto
ck_nam
e);
//...
}; class
Quote
r_F
act
ory
:public
virt
ual
CosL
ifeC
ycle
::G
enericF
act
ory
{public
://
Fact
ory
meth
od
for
creatio
nth
at
inherits
://
CO
RB
A::O
bje
ct_ptr
create
_obje
ct//
(const
CosL
ifeC
ycle
::K
ey
&fa
ctory
_ke
y,//
const
CosL
ifeC
ycle
::C
rite
ria
&cr
iteria)
//N
ote
C+
+m
appin
gof
Key
and
Crite
ria
stru
cts.
//...
};}; N
ote
that
you
neve
rin
stan
tiate
ast
ubcl
ass
dire
ctly
,bu
talw
ays
via
afa
ctor
y
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
OMG Object and POA IDL Mappings
MyMyQuoterQuoterFactoryFactory
create_object()
ServantServantBaseBaseA
CORBA::CORBA::ObjectObject
A
Stock::Stock::QuoterQuoterFactoryFactory
CLIENTCLIENT--SIDESIDE
MAPPINGMAPPING
SERVERSERVER--SIDESIDE
MAPPINGMAPPING
POA_CosLifeCycle::POA_CosLifeCycle::GenericFactoryGenericFactory
A
create_object() = 0
POA_Stock::POA_Stock::Quoter_FactoryQuoter_Factory
A
create_object() = 0
CosLifeCycle::CosLifeCycle::GenericFactoryGenericFactory
create_object() = 0
create_object() = 0
A
A
Stock::Stock::QuoterQuoter
Factory_varFactory_varcreate_object()
� The OMG client mapping inherits allproxy interfaces from the Objectinterface
– Moreover, proxy classes mirrorthe IDL inheritance hierarchy, soreferences to derived interfacesare compatible with references tobase interfaces via widening andpolymorphism
� The IDL server C++ mappinginherits all Servants fromServantBase
Vanderbilt University 46
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Generated Server Skeletons� Skeleton classes provide the server counterpart to the client stub
class proxies
– There’s a C++ virtual method in the skeleton class for eachoperation defined in the IDL interface
� CORBA associates a user-defined servant class to a generated IDLskeleton class using either
1. The Class form of the Adapter pattern (inheritance)POA_Stock::Quoter
2. The Object form of the Adapter pattern (object composition, i.e.,TIE)template <class Impl> class POA_Stock::Quoter_tie
Vanderbilt University 47
CORBA Tutorial Douglas C. Schmidt
The Class Form of the Adapter Pattern
clientclient
QuoterQuoterFactoryFactory
A
create_object() = 0
ServantServantBaseBaseA
CosLifeCycleCosLifeCycleGenericFactoryGenericFactory
A
create_object() = 0
MyMyQuoterQuoterFactoryFactory
create_object()
1: create_object()
Vanderbilt University
CO
RB
ATutorial
Douglas
C.S
chmidt&
Bala
Natarajan
Defining
aS
ervantUsing
Inheritance
�
Servantclasses
caninheritfrom
theirskeleton
directly:cla
ssM
y_Q
uote
r_F
acto
ry:
public
virtual
PO
A_S
tock::Q
uote
r_F
acto
ry{
public:
My_
Quote
r_F
acto
ry(co
nst
char
*facto
ry=
"my
quote
rfa
ctory");
virtual
CO
RB
A::O
bje
ct_ptr
//F
acto
rym
eth
od
for
creatio
n.
create
_obje
ct(co
nst
CosL
ifeC
ycle::K
ey
&fa
ctory_
key,
const
CosL
ifeC
ycle::C
riteria
&th
e_crite
ria)
thro
w(C
OR
BA
::Syste
mE
xceptio
n,
Quote
rFacto
ry::NoF
acto
ry);priva
te:
std::m
ap<
std::strin
g,
CO
RB
A::O
bje
ct_va
r>objre
f_list_
;};
�
How
ever,thisapproach
cancreate
a“brittle”
hierarchyand
make
ithard
tointegrate
with
legacycode
( e.g.,when
distributinga
stand-aloneapplication)
�
Moreover,virtualinheritance
issom
etimes
implem
entedpoorly
byC
++
compilers
VanderbiltU
niversity49
CORBA Tutorial Douglas C. Schmidt
PortableServer::ServantBase
� PortableServer::ServantBaseimplements reference counting for servantclasses via two methods:
– _add_ref() increments reference count(initial count is 1)
– _remove_ref() decrements referencecount by 1 and deletes servant when value is0
� Servant classes implicitly inherit fromPortableServer::ServantBase
� Developers should create the servant usingoperator new
� When ever any method is called that returns aservant object (e.g., id_to_servant() ,reference_to_servant() , _this() ),_add_ref() is called automatically toincrement the ref count by 1
Vanderbilt University
CORBA Tutorial Douglas C. Schmidt
The Object Form of the Adapter Pattern
clientclient
QuoterQuoterFactory_tieFactory_tie
create_object()
MyMyQuoterQuoterFactoryFactory
create_object()2: create_object()
1: create_quoter ()
My_QuoterMy_Quoter
FactoryFactory
QuoterQuoterFactoryFactory
A
create_object() = 0
ServantServantBaseBaseA
CosLifeCycleCosLifeCycleGenericFactoryGenericFactory
A
create_object() = 0
Vanderbilt University
CO
RB
ATutorial
Douglas
C.S
chmidt&
Bala
Natarajan
AT
IE-based
Implem
entationcla
ssM
y_Q
uote
r_F
acto
ry{
public:
My_
Quote
r_F
acto
ry(co
nst
char
*nam
e=
"my
quote
rfa
ctory");
//F
acto
rym
eth
od
for
creatio
n.
CO
RB
A::O
bje
ct_ptr
create
_obje
ct(co
nst
CosL
ifeC
ycle::K
ey
&fa
ctory_
key,
const
CosL
ifeC
ycle::C
riteria
&th
e_crite
ria)
thro
w(C
OR
BA
::Syste
mE
xceptio
n,
Quote
rFacto
ry::NoF
acto
ry);priva
te:
//...
};TIE
allows
classesto
become
distributedeven
iftheyw
eren’tdeveloped
with
priorknow
ledgeofC
OR
BA
�
There
isno
useofinheritance
andoperations
neednotbe
virtual!
�
How
ever,lifecycleissues
for“tie”
and“tied”
objectsare
tricky...
VanderbiltU
niversity52
CO
RB
ATutorial
Douglas
C.S
chmidt&
Bala
Natarajan
Defining
aS
ervantUsing
TIE
nam
esp
ace
PO
A_S
tock
{te
mpla
te<
class
Impl>
class
Quote
r_F
acto
ry_tie
:public
Quote
r_F
acto
ry{
/*...
*/};
//...
We
generatea
typedefanda
servantthatplacesan
implem
entationpointer
objectwithin
theT
IEclass:
typedef
PO
A_S
tock::Q
uote
r_F
acto
ry_tie
<M
y_Q
uote
r_F
acto
ry>M
Y_Q
UO
TE
R_F
AC
TO
RY
;
MY
_Q
UO
TE
R_F
AC
TO
RY
*facto
ry=
new
MY
_Q
UO
TE
R_F
AC
TO
RY
(new
My_
Quote
r_F
acto
ry);
Alloperation
callsvia
theT
IEclass
arethen
delegatedto
theim
plementation
object
VanderbiltU
niversity53
CORBA Tutorial Douglas C. Schmidt
Implementing My Quoter Factory
The following code is identical regardless of whichform of Adapter pattern is used for servant classes
CORBA::Object_ptrMy_Quoter_Factory::create_object
(const CosLifeCycle::Key &factory_key,const CosLifeCycle::Criteria &the_criteria)
{POA_Stock::Quoter *quoter;PortableServer::ServantBase_var xfer;
// Factory method selects quoter.if (strcmp (factory_key.id,
"my quoter") == 0) {xfer = quoter = new My_Quoter;
}else if (strcmp (factory_key.id,
"dow jones") == 0) {xfer = quoter = new Dow_Jones_Quoter;
} else // Raise an exception.throw Quoter_Factory::NoFactory ();
// Create a Stock::Quoter_ptr, register// the servant with the default_POA, and// return the new Object Reference.return quoter->_this ();
};
Vanderbilt University
CORBA Tutorial Douglas C. Schmidt
Another create object()Implementation
Preventing multiple servant activations for thesame key
CORBA::Object_ptrMy_Quoter_Factory::create_object
(/* args omitted */){
CORBA::Object_var objref;if (objref_list_.find (factory_key.id,
objref) == 0)return objref._retn ();
// Declarations...// Factory method selects quoter.if (strcmp (factory_key.id,
"my quoter") == 0) {xfer = quoter = new My_Quoter;
}// Create a Stock::Quoter_ptr, register// the servant with the default_POA, and// return the new Object Reference.objref = quoter->_this ();
// operator=() defined in CORBA::Object_var// duplicates references.objref_list_.bind (factory_key.id,
objref);return objref._retn ();
};
Vanderbilt University
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Implicit Activation and this()
� Each generated skeleton class contains a _this() method, e.g.:
class POA_Stock::Quoter: public virtual CosLifeCycle::LifeCycleObject {
public:Quoter_ptr _this ();
};
� Depending on the POA policy, the _this() method can be used toactivate a servant and return the corresponding object reference
� Internally, _this() duplicates the object reference, so it must bedecremented at some point to avoid memory leaks
� If you use _this() for a servant in a non-Root POA, make sure tooverride the servant’s _default_POA() method...
Vanderbilt University 56 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Ref
eren
ceC
ount
ing
Ser
vant
sP
rope
rly
�
Whe
na
serv
antt
hati
nher
itsfr
omP
ort
able
Serv
er:
:Serv
antB
ase
iscr
eate
dits
refc
ount
isse
tto
1
�
Whe
nit’
sac
tivite
dw
ithth
eP
OA
itsre
fcou
ntis
incr
emen
ted
to2
�
Whe
nP
ort
able
Serv
er:
:PO
A::
deact
ivate
_obje
ct()
isca
lled
late
rth
ere
fco
unti
sde
rem
ente
dby
1
–B
utth
ese
rvan
tis
only
dest
roye
dw
hen
itsre
fco
unti
s0
�
Toen
sure
the
serv
anti
sde
stro
yed
prop
erly
,use
Port
able
Serv
er:
:Serv
antB
ase
_va
rto
hold
the
new
lyal
loca
ted
serv
antp
oint
ersi
nce
itsde
stru
ctor
calls
_re
move
_re
f()
auto
mat
ical
ly
–T
his
appr
oach
isal
soex
cept
ion-
safe
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Implementing the My Quoter InterfaceImplementation of the Quoter IDL interface
class My_Quoter : virtual public POA_Stock::Quoter{public:
My_Quoter (void *state); // Constructor.
// Returns the current stock value.long get_quote (const char *stock_name)
throw (CORBA::SystemException, Quoter::InvalidStock);
// Deactivate quoter instance.void remove (void)
throw (CORBA::SystemException,CosLifeCycle::LifeCycleObject::NotRemovable);
private:// ...
};
Vanderbilt University 58
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Throwing Exceptions� To throw an exception, simply instantiate the exception class and
throw it, i.e., throw Quoter_Factory::NoFactory()
– The process is slightly more baroque using emulated exceptions
� Servant code should generally try to throw user exceptions
– Avoid throwing system exceptions since they convey lessinformation to clients
– When you do throw a system exception, set its completion statusto indicate what state the operation was in
� Use C++ try blocks to protect scopes where operations may throwexceptions and always use _var and/or std::auto_ptr<> typesappropriately
Vanderbilt University 59
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Memory Management Tips (1/3)
� Memory management is straightforward for basic/fixed types, butmore complicated for variable-sized types
� Rule of thumb: Caller owns all storage
� Use _var to manage memory automatically
– But never declare method signatures using _var ; use _ptrinstead...
Quoter_ptr factory (CORBA::Object_ptr arg); // OkQuoter_var factory (CORBA::Object_var arg); // Wrong
� Remember _var owns the memory
– Unless _retn() is used
� Not obeying the rules can cause crashes (if you’re lucky) or memoryleaks/corruption (if you’re not)
Vanderbilt University 60
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Memory Management Tips (2/3)
� Server-side implementations of operations should
– Object references must be duplicated before being stored toprevent premature deletion
– Operations receiving variable-sized data types should perform adeep copy of the incoming data to safely use them later
� Caching pointers to the parameter will not help– Allocate memory for out and return parameters of variable-sized
types
� Clients handle this by using _var types– Servants automatically give up ownership of memory allocated for
out and return parameters.
� Call _duplicate() or equivalent operation if servants need toretain ownership.
– Use PortableServer::ServantBase_var and
Vanderbilt University 61
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
std::auto_ptr<> to prevent memory leaks when exceptionsoccur
Vanderbilt University 62
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Memory Management Tips (3/3)� Frequently Made Mistakes (FMM’s)
1. Storing strings within sequences and structs2. Not handling the return reference from an operation, but passing it
to another operation3. Not activating the POA manager4. Not setting length() of sequence properly5. Not duplicating object references properly6. Not using ServantBase_var properly
� We’ll show how to avoid these mistakes in subsequent slides
Vanderbilt University 63
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Motivation for the CORBA Naming Service
� Clients access Quoter objects returned by My_Quoter_Factory
– But how do clients find My_Quoter_Factory ?!
� One approach is to use CORBA::ORBhelper operations to convertan object reference to a string and vice versainterface ORB {
// ...string object_to_string (in Object o);Object string_to_object (in string s);
};
� Stringified object references can be written to and read from a file,passed between ORBs, and/or stored in a database
� A more effective and scalable approach, however, is often to use theCORBA Naming Service
Vanderbilt University 64
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of the CORBA Naming Service
SERVERSERVER
1: bind()1: bind()
2: resolve()2: resolve()
NNAMINGAMING
SERVICESERVICE
3: create_object()3: create_object()4: get_quote()4: get_quote()
CLIENTCLIENT
� Purpose
– Maps sequences ofstrings to objectreferences
� Capabilities
– A Naming Contextcan be a hierarchicallynested graph
– Naming Contextscan also be federated
Vanderbilt University 65
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Reg
iste
ring
My
Quote
rF
act
ory
with
the
Nam
ing
Ser
vice
ext
ern
CosN
am
ing::N
am
ingC
onte
xtE
xt_ptr
nam
e_co
nte
xt;
My_
Quote
r_F
act
ory
::M
y_Q
uote
r_F
act
ory
(const
char
*fact
ory
_nam
e)
{ch
ar
tmp[]
="o
bje
ctim
pl"
;C
OR
BA
::S
trin
gS
eq
sseq
(2);
sseq.le
ngth
(2);
sseq[0
]=
fact
ory
_nam
e;
sseq[1
]=
tmp;
//F
MM
1//
FM
M:
ass
ignm
ent
from
const
char
*duplic
ate
s//
the
string
but
anon-c
onst
char
doesn
’t.C
osN
am
ing::N
am
enam
e;
nam
e.le
ngth
(1);
nam
e[0
].id
=ss
eq[0
];nam
e[0
].ki
nd
=ss
eq[1
];
//O
bta
inobjref
and
regis
ter
with
PO
A.
Quote
r_F
act
ory
_va
rqf
=th
is->
_th
is()
;
//E
xport
objref
tonam
ing
conte
xt.
nam
e_co
nte
xt->
bin
d(n
am
e,
qf.in
());
//F
MM
2is
todo
the
follo
win
g.
//nam
e_co
nte
xt->
bin
d(n
am
e,
this
->_th
is()
);}; R
ealc
ode
shou
ldha
ndle
exce
ptio
ns...
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Programming with Object References (1/3)� An IDL compiler generates two different object reference types for
each interface :
– <interface>_ptr ! C++ pointer to object reference
� An “unmanaged type” that requires programmers to manipulatereference ownership via <proxy>::_duplicate() andCORBA::release()
– <interface>_var ! “Smart pointer” to object reference
� Manages reference lifetime by assuming ownership ofdynamically allocated memory and deallocating it when the_var goes out of scope
� operator->() delegates to the underlying pointer value
� _var types are essential for writing exception-safe code
Vanderbilt University 67
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Programming with Object References (2/3)
� You should use _var types as often as possible since theyautomate most of the error-prone reference counting, e.g.:// When ORB returns object reference its proxy has// a reference count of 1Quoter_ptr quoter = resolve_quoter_service ();CORBA::Long value = quoter->get_quote ("ACME ORB Inc.");CORBA::release (quoter);// release() decrements the reference count by one,// which causes deallocate when the count reaches 0
versusQuoter_var quoter = resolve_quoter_service ();CORBA::Long value = quoter->get_quote ("ACME ORB Inc.");// quoter automatically releases object reference.
� Calls to _duplicate() and CORBA::release() only affect thelocal proxy, not the remote object!!!
Vanderbilt University 68
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Programming with Object References (3/3)
� To handle broken C++ compilers, you may need to use specialhelper methods generated by the IDL compiler to workaroundproblems with implicit type conversions from _var to the underlyingpointer
– in() passes the _var as an in parameter– inout() passes the _var as an inout parameter– out() passes the _var as an out parameter
� Variable-size _var types have a _retn() method that transfersownership of the returned pointer
– This method is important for writing exception-safe code
Vanderbilt University 69
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
The
Mai
nS
erve
rP
rogr
am
Use
spe
rsis
tent
activ
atio
nm
ode
int
main
(int
arg
c,ch
ar
*arg
v[])
{O
RB
_M
anager
orb
_m
anager
(arg
c,arg
v);
const
char
*fact
ory
_nam
e=
"my
quote
rfa
ctory
";
//C
reate
the
serv
ant,
whic
hre
gis
ters
with
//th
ero
otP
OA
and
Nam
ing
Serv
ice
implic
itly.
My_
Quote
r_F
act
ory
*fact
ory
=new
My_
Quote
r_F
act
ory
(fact
ory
_nam
e);
//T
ransf
er
ow
ners
hip
tosm
art
poin
ter.
Port
able
Serv
er:
:Serv
antB
ase
_va
rxf
er
(fact
ory
);
//B
lock
indefin
itely
waiti
ng
for
inco
min
g//
invo
catio
ns
and
dis
patc
hupca
lls.
retu
rnorb
_m
anager.
run
();
//A
fter
run()
retu
rns,
the
OR
Bhas
shutd
ow
n.
} Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Motivation for ORB Manager� Like many CORBA servers, our stock quoter server is initialized via
the following steps:
1. We call CORBA::ORB_init() to obtain the locality constrainedobject reference to the ORB pseudo-object
2. We use the ORB object reference to obtain the Root POA3. We then instantiate the quoter factory servant and activate it to
obtain its object reference4. We next make the object reference for the quoter factory available
to clients via the Naming Service5. Finally, we activate the Root POA’s manager and run the ORB’s
event loop
� To automate many of these steps, we define the ORB_Managerwrapper facade class
Vanderbilt University 71
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Ove
rvie
wof
OR
BM
anag
er
class
OR
B_M
anager
{public
://
Initi
aliz
eth
eO
RB
manager.
OR
B_M
anager
(int
arg
c,ch
ar
*arg
v[])
{orb
_=
CO
RB
A::O
RB
_in
it(a
rgc,
arg
v,0);
CO
RB
A::O
bje
ct_va
robj
=orb
_->
reso
lve_in
itial_
refe
rence
s("
RootP
OA
");
poa_
=P
ort
able
Serv
er:
:PO
A::_narr
ow
(obj.i
n()
);poa_m
anager_
=poa_->
the_P
OA
Manager
();
} //O
RB
Acc
ess
or.
CO
RB
A::O
RB
_ptr
orb
(void
){
retu
rnorb
_;
}
//R
un
the
main
OR
Beve
nt
loop.
int
run
(void
){
poa_m
anager_
->act
ivate
();
//F
MM
3re
turn
orb
_->
run
();
} //C
leanup
the
OR
Band
PO
A.
˜OR
B_M
anager
(){
orb
_->
dest
roy
();
}priva
te:
CO
RB
A::O
RB
_va
rorb
_;
Port
able
Serv
er:
:PO
A_va
rpoa_;
Port
able
Serv
er:
:PO
A_M
anager_
var
poa_m
anager_
;}; V
ande
rbilt
Uni
vers
ity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Pseudo-objects and Locality Constraints
� The CORBA::ORBand PortableServer::POA interfaces define“pseudo-objects,” i.e.:
orb_ = CORBA::ORB_init (argc, argv, 0);CORBA::Object_var obj =
orb_->resolve_initial_references ("RootPOA");poa_ =
PortableServer::POA::_narrow (obj.in ());
� Pseudo-objects have IDL interfaces but are implemented in theORB’s runtime library, rather than by using generatedstubs/skeletons
� Pseudo-objects are “locality constrained,” which means that theirobject references can’t be passed to remote address spaces
Vanderbilt University 73
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of narrow() Conversion Operators
� The IDL compiler generates static method _narrow() for eachproxy that behaves like the C++ dynamic_cast operator
– i.e., it returns a non-nil reference if the argument to the method isthe right type, else nil
� Note that _narrow() implicitly calls _duplicate() , whichincrements the reference countclass Quoter : public virtual CosLifeCycle::LifeCycleObject {public:
static Quoter_ptr _narrow (CORBA::Object_ptr arg);// ...
class Stat_Quoter : public virtual Quoter {public:
static Stat_Quoter_ptr _narrow (CORBA::Object_ptr arg);// ...
Vanderbilt University 74
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of ORB Shutdown� The following two operations shutdown the ORB gracefully:
interface ORB {void shutdown (in boolean wait_for_completion);void destroy ();
};
� These operations do the following:
– Stop the ORB from accepting new requests– Allow existing requests to complete and– Destroy all POAs associated with the ORB
� The wait_for_completion boolean allows the caller to decidewhether to wait for the ORB to finish shutting down before returning
– This is important for multi-threaded ORB implementations...
Vanderbilt University 75
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Recap of the Stock Quoter Server
� In our stock quoterserver, we (i.e., theapplicationdevelopers) simplywrite
1. The IDL interfaces2. The servant classes3. Code to initialize
the server eventloop
� The ORB and associated tools (e.g., IDLcompiler) provides the rest:
1. Generated skeleton classes thatconnect the ORB with theapplication-defined servant classes
2. (De)marshaling code3. Management of object references4. The ORB runtime libraries that handle
connection management, GIOP datatransfer, endpoint and requestdemuxing, and concurrency control
Vanderbilt University 76
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
How a Client Accesses a CORBA Object
� Several steps:
1. Client uses resolve_initial_references() and“Interoperable Naming Service” to obtain a NamingContext– This is the standard ORB “bootstrapping” mechanism
2. Client then uses NamingContext to obtain desired objectreference
3. The client then invokes operations via object reference
� Object references can be passed as parameters to other remoteobjects
– This design supports various types of “factory” patterns
Vanderbilt University 77
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Stock Quoter Client Program (1/3)
int main (int argc, char *argv[]) {CORBA::ORB_var orb = CORBA::ORB_init (argc, argv, 0);
CORBA::Object_var obj =orb->resolve_initial_references ("NameService");
CosNaming::NamingContextExt_var name_context =CosNaming::NamingContextExt::_narrow (obj.in ());
Stock::Quoter_var quoter; // Manages refcounts.char *stock_name = 0;
Vanderbilt University 78
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Stock Quoter Client Program (2/3)try { // Use a factory to resolve any quoter.
Stock::Quoter_Factory_var qf =resolve_service<Stock::Quoter_Factory>
("my quoter factory", name_context.in ());if (CORBA::is_nil (qf.in ())) return 0;
CosLifeCycle::Key key; key.length (1);key[0].id = "my quoter";
// Find a quoter and invoke the call.CORBA::Object_var obj = qf->create_object (key);quoter = Stock::Quoter::_narrow (obj);
stock_name = CORBA::string_dup ("ACME ORB Inc.");CORBA::Long value = quoter->get_quote (stock_name);
Vanderbilt University 79
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Stock Quoter Client Program (3/3)
cout << stock_name << " = " << value << endl;// Destructors of *_var release memory.
}catch (Stock::Invalid_Stock &){
cerr << stock_name << " not valid" << endl;} catch (...) { /* Handle exception... */ }
CORBA::string_free (const_cast <char *> (stock_name));
quoter->remove (); // Shut down server object}
Vanderbilt University 80
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Memory Management for OMG Strings
� CORBA provides the following methods that must be used tomanage the memory of dynamically allocated strings
namespace CORBA {char *string_dup (const char *ostr);void string_free (char *nstr);char *string_alloc (ULong len); // Allocates len + 1 chars// ... Similar methods for wstrings ...
}
� These methods are necessary for platforms such as Windows thathave constraints on heap allocation/deallocation
� In the Stock Quoter client example above we could have avoided theuse of dynamic string allocations by simply using the following
const char *stock_name = "ACME ORB Inc.";
Vanderbilt University 81
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Obtaining an Object Reference
template <class T>typename T::_ptr_type /* trait */resolve_service (const char *n,
CosNaming::NamingContextExt_ptr name_context) {CosNaming::Name svc_name;svc_name.length (1); svc_name[0].id = n;svc_name[0].kind = "object impl";
// Find object reference in the name service.obj = name_context->resolve (svc_name);
// Can also use// obj = name_context->resolve_str (n);
// Narrow to the T interface and away we go!
Vanderbilt University 82
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
return T::_narrow (obj);}
Vanderbilt University 83
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Coping with Changing Requirements
� New Quoter features
– Format changes to extend functionality– New interfaces and operations
� Improving existing Quoter features
– Batch requests
� Leveraging other ORB features
– Asynchronous Method Invocations (AMI)– Passing object references to implement a publisher/subscriber
architecture
Vanderbilt University 84
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
New FormatsFor example, percentage that stock increased or decreased since startof trading day, volume of trades, etc.
module Stock{
// ...
interface Quoter{
long get_quote (in string stock_name,out double percent_change,out long trading_volume)
raises (Invalid_Stock);};
};
Note that even making this simple change would involve a great deal ofwork for a sockets-based solution...
Vanderbilt University 85
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Adding Features Unobtrusively
� Interface inheritance allows new features to be added withoutbreaking existing interfacesmodule Stock {
// No change to Quoter interface!!interface Quoter { /* ... */ };
interface Stat_Quoter : Quoter // a Stat_Quoter IS-A Quoter {// Note OMG IDL’s inability to support overloading!long get_stats (in string stock_name,
out double percent_change,out long volume) raises (Invalid_Stock);
// ...
� Applications can pass a Stat_Quoter whereever a Quoter isexpected
– Clients can use _narrow() to determine actual type
Vanderbilt University 86
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
New Interfaces and OperationsFor example, adding a trading interface
module Stock {// Interface Quoter_Factory and Quoter same as before.interface Trader {
void buy (in string name,inout long num_shares,in long max_value) raises (Invalid_Stock);
// sell() operation is similar...};interface Trader_Factory { /* ... */ };
};
Multiple inheritance is also useful to define a full service broker:
interface Full_Service_Broker : Stat_Quoter, Trader {};
Note that you can’t inherit the same operation from more than oneinterface
Vanderbilt University 87
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Batch RequestsImprove performance for multiple queries or trades
interface Batch_Quoter : Stat_Quoter{ // Batch_Quoter IS-A Stat_Quoter
typedef sequence<string> Names;struct Stock_Info {
// Acts like String_var initialized to empty string.string name;long value;double change;long volume;
};typedef sequence<Stock_Info> Info;exception No_Such_Stock { Names stock; };
// Note problems with exception design...void batch_quote (in Names stock_names,
out Info stock_info) raises (No_Such_Stock);};
Vanderbilt University 88
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of OMG Structs
� IDL structs are similar to C++ structs
– i.e., they contain one or more fields of arbitrary types
� However, IDL structs must be named and have one or more fields
� The C++ mapping rules are different for fixed- and variable-sizestructs
– i.e., variable-size structs must be dynamically allocated bysender and deallocated by receiver
� Using the IDL-generated _var helper types minimize the differencesbetween fixed- and variable-sized structs in C++ mapping
Vanderbilt University 89
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of OMG Sequences (1/2)
� IDL sequences are variable-length vectors of size >= 0
� They can be bounded or unbounded
– Bounded sequences have a max number of elements– Unbounded sequences can grow to any (reasonable) length
� Sequences can contain other sequences
typedef sequence<octet> Octet_Sequence;typedef sequence<Octet_Sequence> Octet_Argv;
� Sequences can be also used to define recursive data structures forstructs and unions
struct Node {sequence<Node> Children;// ...
};
Vanderbilt University 90
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of OMG Sequences (2/2)� Each IDL sequence type maps to a distinct C++ class
� The length() accessor returns # elements in sequence
� The length() mutator can change # elements in sequence
� Each C++ class defines pair of overloaded subscript operators(operator[] )
� Although it’s illegal to access beyond the current length, you can usethe length() mutator to grow the sequence length at its tail
� FMM 4: Using the sequence to store data without setting thelength() can cause undefined behaviors
� The copying semantics of sequences depend on the types of itselements
Vanderbilt University 91
CORBA Tutorial Douglas C. Schmidt
Motivation for AsynchronousMethod Invocations (AMI)
� Early versions of CORBA lacked support forasynchronous two-way invocations
� This omission yielded the following drawbacks
1. Increase the number of client threads– e.g., due to synchronous two-way
communication2. Increase the end-to-end latency for multiple
requests– e.g., due to blocking on certain long-delay
operations3. Decrease OS/network resource utilization
– e.g., inefficient support for bulk datatransfers
Vanderbilt University
CORBA Tutorial Douglas C. Schmidt
Limitations with Workarounds forCORBA’s Lack of Asynchrony
� Synchronous method invocation (SMI)multi-threading
– Often non-portable, non-scalable, andinefficient
� Oneway operations
– Best-effort semantics are unreliable– Requires callback objects– Applications must match callbacks with
requests
� Deferred synchronous
– Uses DII, thus very hard to program– Not type-safe
Vanderbilt University
CO
RB
ATutorial
Douglas
C.S
chmidt&
Bala
Natarajan
OM
GS
olution
!
CO
RB
AM
essagingS
pecification
�
Defines
QoS
Policies
forthe
OR
B
–T
imeouts
–P
riority–
Reliable
one-ways
�
Specifies
two
asynchronousm
ethodinvocation
(AM
I)m
odels
1.P
ollerm
odel2.
Callback
model
�
Standardizes
time-independent
invocation(T
II)m
odel
–U
sedfor
store/forward
routers
PO
LL
ING
PO
LL
ING
CL
IEN
TC
LIE
NT
PPOOLLLLEERR
op
eratio
n(a
rgs)
op
eratio
n(a
rgs)
1: request
3: response
2: poller
4: get
TA
RG
ET
TA
RG
ET
OB
JE
CT
OB
JE
CT
44
CA
LL
BA
CK
CA
LL
BA
CK
CL
IEN
TC
LIE
NT
1: request
2: response
TA
RG
ET
TA
RG
ET
OB
JE
CT
OB
JE
CT
44
3: upcall
op
eratio
n(ca
llback
, arg
s)op
eratio
n(ca
llback
, arg
s)
VanderbiltU
niversity94
CO
RB
ATutorial
Douglas
C.S
chmidt&
Bala
Natarajan
AM
ICallback
Overview
get_qu
ote ("IB
M"
)
value
stock_name
QU
OT
E
CL
IEN
T
ST
OC
K
QU
OT
ER
4
Quoter
IDL
Interface:m
od
ule
Sto
ck{
inte
rface
Qu
ote
r{
//T
wo
-wa
yo
pe
ratio
nto
//g
et
curre
nt
stock
valu
e.
lon
gg
et_
qu
ote
(instrin
gsto
ck_n
am
e);
};//...
}
Implied-ID
Lfor
client:m
od
ule
Sto
ck{
//R
ep
lyHa
nd
ler.
inte
rface
AM
I_Q
uo
terH
an
dle
r:
Me
ssag
ing
::Re
plyH
an
dle
r{
//C
allb
ack
me
tho
d.
void
ge
t_q
uo
te(in
lon
gre
turn
_va
lue
);};
inte
rface
Qu
ote
r{
//T
wo
-wa
ysyn
chro
no
us
op
era
tion
.lo
ng
ge
t_q
uo
te(in
string
stock_
na
me
);
//T
wo
-wa
ya
synch
ron
ou
so
pe
ratio
n.
void
sen
dc_
ge
t_q
uo
te(in
AM
I_Q
uo
terH
an
dle
rh
an
dle
r,in
string
stock);
};};
VanderbiltU
niversity95
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Example: Synchronous Client
get_quote ("IBM")
value
stock_name
QUOTE
CLIENT
STOCK
QUOTER 4
IDL-generated stub:CORBA::ULongStock::Quoter::get_quote
(const char *name){
// 1. Setup connection// 2. Marshal// 3. Send request & wait// 4. Get reply// 5. Demarshal// 6. Return
};
Application:// NASDAQ abbreviations for ORB vendors.static const char *stocks[] ={
"IONA" // IONA Orbix"BEAS" // BEA Systems WLE"IBM" // IBM Component Broker
}// Set the max number of ORB stocks.static const int MAX_STOCKS = 3;
// Make synchronous two-way calls.for (int i = 0; i < MAX_STOCKS; i++) {
CORBA::Long value =quoter_ref->get_quote (stocks[i]);
cout << "Current value of "<< stocks[i] << " stock: "<< value << endl;
}
Vanderbilt University 96
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Example: AMI Callback Client (1/2)CALLBACK
QUOTE
CLIENT
2: value
STOCK
QUOTER 4sendc_get_quote(handler, "IBM")
handler3:upcall 1: stock_name
Asynchronous stub:voidStock::Quoter::sendc_get_quote
(AMI_QuoterHandler_ptr,const char *name)
{// 1. Setup connection// 2. Store reply handler// in ORB// 3. Marshal// 4. Send request// 5. Return
};
Reply Handler Servant:class My_Async_Stock_Handler
: public POA_Stock::AMI_QuoterHandler {public:
My_Async_Stock_Handler (const char *s): stock_ (s)
{ }˜My_Async_Stock_Handler (void) { }
// Callback method.virtual void get_quote
(CORBA::Long ami_return_val) {cout << stock_.in () << " stock: "
<< ami_return_val << endl;// Decrement global reply count.reply_count--;
}private:
CORBA::String_var stock_;};
Vanderbilt University 97
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Example: AMI Callback Client (2/2)// Global reply countint reply_count = MAX_STOCKS;
// Servants.My_Async_Stock_Handler *
handlers[MAX_STOCKS];
// Objrefs.Stock::AMI_QuoterHandler_var
handler_refs[MAX_STOCKS];
int i;
// Initialize ReplyHandler// servants.for (i = 0; i < MAX_STOCKS; i++)
handlers[i] = newMy_Async_Stock_Handler (stocks[i]);
// Initialize ReplyHandler object refs.for (i = 0; i < MAX_STOCKS; i++)
handler_refs[i] =handlers[i]->_this ();
// Make asynchronous two-way calls// using the callback model.for (i = 0; i < MAX_STOCKS; i++)
quoter_ref->sendc_get_quote(handler_refs[i].in (),
stocks[i]);
// ... activate POA manager ...
// Event loop to receive all replies.while (reply_count > 0)
if (orb->work_pending ())orb->perform_work ();
else...
Vanderbilt University 98
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Additional Information on AMI� Messaging specification is integrated into CORBA spec.
– www.omg.org
� See Vinoski’s CACM article on CORBA 3.0 for more info.
– www.cs.wustl.edu/�schmidt/vinoski-98.pdf
� See our papers on AMI
– www.cs.wustl.edu/�schmidt/report-doc.html– www.cs.wustl.edu/�schmidt/PDF/ami1.pdf– www.cs.wustl.edu/�schmidt/PDF/ami2.pdf
� See TAO release to experiment with working AMI examples
– $TAO_ROOT/tests/AMI/
Vanderbilt University 99
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Motivation for a Publisher/Subscriber Architecture
� To this point, our stock quoter service has required the client to “poll”the server periodically to receive the latest quote value
– However, this design is inefficient since the client keepscontacting the server, even if nothing has changed!
� A more scalable approach may be to use the Publisher/Subscriberarchitectural pattern
– This pattern decouples the publishers who produce quote eventsfrom subscribers who consume them
� We’ll redesign our stock quoter application to implement thePublisher/Subscriber pattern using object references
Vanderbilt University 100 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
AP
ublis
her/
Sub
scrib
erS
tock
Quo
ter
Arc
hite
ctur
e
: N
oti
fier
: N
oti
fier
NE
TW
OR
K
CO
NSU
ME
RC
ON
SU
ME
R
AA
CO
NSU
ME
RC
ON
SU
ME
R
BB
Co
nC
on
Ob
jRef
Ob
jRef
BB
Co
nC
on
Ob
jRef
Ob
jRef
AA1:
sub
scri
be
(Ob
jRef
1:
sub
scri
be
(Ob
jRef
AA))
B :
B :
Co
nsu
mer
Con
sum
er
4:
pu
sh (
even
t)4
: p
ush
(ev
ent)
2: s
ubsc
ribe
(ObjR
ef
2: s
ubsc
ribe
(ObjR
efBB))
4: p
ush
(ev
ent)
4: p
ush
(ev
ent)
NO
TIF
IER
NO
TIF
IER
Noti
fier
Noti
fier
Ob
jRef
Ob
jRef
3: push
(event)
3: push
(event)
Noti
fier
No
tifi
erO
bjR
efO
bjR
ef
A :
A :
Co
nsu
mer
Co
nsu
mer
No
tifi
erN
oti
fier
Ob
jRef
Ob
jRef
SU
PP
LIE
RS
UP
PL
IER
Not
eth
eus
eof
the
Pub
lishe
r/S
ubsc
riber
patte
rn
Van
derb
iltU
nive
rsity
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Eve
ntTy
pe
�
We
defin
ean
Eve
nt
stru
ctth
atco
ntai
nsa
string
and
anany
:
stru
ctE
vent
{st
ring
topic
_;
//U
sed
for
filte
ring.
any
valu
e_;
//E
vent
conte
nts
.};
�
Thi
sm
aps
toth
efo
llow
ing
C+
+cl
ass
stru
ctE
vent
{T
AO
::S
trin
g_m
gr
topic
_;
CO
RB
A::A
ny
valu
e_;
};
�
The
TA
O::S
trin
g_m
gr
beha
ves
like
aS
trin
g_va
rth
at’s
initi
aliz
edto
the
empt
yst
ring
–D
ono
tuse
the
TA
O::S
trin
g_m
gr
inyo
urap
plic
atio
nco
desi
nce
it’s
expl
icitl
yde
sign
edto
beO
RB
-spe
cific
!!!
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of the CORBA Any Type (1/2)� OMG IDL defines type any for use with applications that can only
determine the types of their data at runtime
� This type contains the following pair of fields:
– The TypeCode that describes the type of the value in the any inorder to ensure typesafety
– The current value of the any
� The client ORB stores the TypeCode before the value so that theserver ORB can properly decode and interpret the value
Vanderbilt University 103
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of the CORBA Any Type (2/2)
� IDL any maps to the C++ class CORBA::Any :class Any {public:
Any (); // Constructs an Any that contains no value.Any (const Any &); // Deep copy semanticsAny &operator= (const Any &); // Deep copy semantics// ...
� Built-in types are inserted and extracted using overloadedoperator<<= and operator>>= , respectively
– The insertion operators copies the value and sets the typecode– The extract operators return true iff the extraction succeeds, i.e., if
the typecodes match!
� The IDL compiler generates these overloaded operators foruser-defined types, as shown later in a DII example
Vanderbilt University 104 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Eve
ntR
ecei
ver
Inte
rfac
e
inte
rface
Consu
mer
{//
Info
rmth
eC
onsu
mer
//eve
nt
has
occ
urr
ed.
onew
ay
void
push
(in
Eve
nt
eve
nt)
;
//D
isco
nnect
the
Consu
mer
//fr
om
the
Notif
ier.
void
dis
connect
(in
string
reaso
n);
}; AC
onsu
mer
isca
lled
back
byth
eN
otifi
er
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Oneway Operations
� The push() operations in Consumer and Notifier interfaces areoneway
– They must therefore have void return type, only in parameters,and no raises clause
� By default, oneway operations have “best effort” semantics
– i.e., there is no guarantee they will be delivered in the order sentor that they’ll even be delivered at all!
� Later versions of CORBA define so-called “reliable oneways,” whichaddress some of these issues via the SyncScope policy
– e.g., SYNC NONE, SYNC WITH TRANSPORT, SYNC WITH SERVER,and SYNC WITH TARGET
Vanderbilt University 106 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Not
ifier
Inte
rfac
e
inte
rface
Notif
ier
{//
=F
or
Consu
mers
.//
Subsc
ribe
aco
nsu
mer
tore
ceiv
e//
eve
nts
that
matc
hfil
tering_cr
iteria
//applie
dby
notif
ier.
Retu
rns
consu
mer
long
subsc
ribe
(in
Consu
mer
consu
mer,
inst
ring
filte
ring_cr
iteria);
//R
em
ove
apart
icula
rco
nsu
mer.
void
unsu
bsc
ribe
(in
long
consu
mer_
id);
//=
For
Supplie
rs.
//P
ush
the
eve
nt
toall
the
consu
mers
//w
ho
have
subsc
ribed
and
who
matc
h//
the
filte
ring
crite
ria.
onew
ay
void
push
(in
Eve
nt
eve
nt)
;}; A
Not
ifier
publ
ishe
sE
vents
tosu
bscr
ibed
Con
sum
ers
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Limitations of Object References
� Note that the Notifier::subscribe() operation returns aconsumer ID that the unsubscribe() operation uses to removethe subscription of a particular consumer
� We need this ID since it’s invalid to compare objects for equalitydirectly using object references, i.e.:
– Object references only indicate location, not object identity– Object::is_equivalent() is a local operation that tests
object reference identity, not object identity!!
� Other invalid operations on object references include
– Using C++ dynamic_cast rather than _narrow()– Testing for NULL rather than using CORBA::is_nil()
Vanderbilt University 108
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Notifier Implementationclass My_Notifier { // C++ pseudo-code, error checking omitted...public:
CORBA::Long subscribe (Consumer_ptr con, const char *fc) {// Not using _duplicate is FMM 5consumer_set_.bind (fc, Consumer::_duplicate (con));return consumer_id;
}void unsubscribe (CORBA::Long con_id) {
Consumer_var con;// FMM 5 is to use _ptr; _var needed since _ptr’s in map.consumer_set_.unbind (fc, con);remove <con_id> from <consumer_set_>.
}void push (const Event &event) {
foreach <consumer> in <consumer_set_>if (event.topic_ matches <consumer>.filter_criteria)
<consumer>.push (event);}
private: // e.g., use an STL map.std::map <string, Consumer_ptr> consumer_set_;
};
Vanderbilt University 109
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
CO
RB
AO
RB
Arc
hite
ctur
e
NE
TW
OR
KN
ET
WO
RK
DII
DII
OR
BO
RB
INT
ER
FA
CE
INT
ER
FA
CE
OR
BO
RB
CO
RE
CO
RE
op
erati
on
()op
erati
on
()
IDL
IDL
ST
UB
SS
TU
BS
OB
JE
CT
OB
JE
CT
AD
AP
TE
RA
DA
PT
ER
IDL
IDL
SK
EL
ET
ON
SK
EL
ET
ON
DS
ID
SI
in args
in args
ou
t a
rgs
+ r
etu
rn
valu
eou
t a
rgs
+ r
etu
rn
valu
e
CL
IEN
TC
LIE
NT
INT
ER
FA
CE
INT
ER
FA
CE
RE
PO
SIT
OR
YR
EP
OS
ITO
RY
IMP
LE
ME
NT
AT
ION
IMP
LE
ME
NT
AT
ION
RE
PO
SIT
OR
YR
EP
OS
ITO
RY
IDL
IDL
CO
MP
ILE
RC
OM
PIL
ER
NA
MIN
GN
AM
ING
SE
RV
ICE
SE
RV
ICE
GIO
PG
IOP//I
IOP
IIO
P
OB
JE
CT
OB
JE
CT
((SE
RV
AN
TS
ER
VA
NT))
OS
K
ER
NE
LO
S K
ER
NE
L
OS
I
OS
I//
O
SU
BS
YS
TE
MO
S
UB
SY
ST
EM
NE
TW
OR
K IN
TE
RF
AC
ES
NE
TW
OR
K IN
TE
RF
AC
ES
OS
K
ER
NE
LO
S K
ER
NE
L
OS
I
OS
I//
O
SU
BS
YS
TE
MO
S
UB
SY
ST
EM
NE
TW
OR
K IN
TE
RF
AC
ES
NE
TW
OR
K IN
TE
RF
AC
ES
Van
derb
iltU
nive
rsity
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Ove
rvie
wof
CO
RB
AC
ompo
nent
s
�
The
CO
RB
Asp
ecifi
catio
nco
ntai
nsth
efo
llow
ing
maj
orco
mpo
nent
s:
–O
bjec
tReq
uest
Bro
ker
(OR
B)
Cor
e–
Inte
rope
rabi
lity
Spe
c(G
IOP
and
IIOP
)–
Inte
rfac
eD
efini
tion
Lang
uage
(ID
L)–
Pro
gram
min
gla
ngua
gem
appi
ngs
for
IDL
–S
tatic
Invo
catio
nIn
terf
ace
(SII)
–D
ynam
icIn
voca
tion
Inte
rfac
e(D
II)–
Sta
ticS
kele
ton
Inte
rfac
e(S
SI)
–D
ynam
icS
kele
ton
Inte
rfac
e(D
SI)
–P
orta
ble
Obj
ectA
dapt
er(P
OA
)–
Impl
emen
tatio
nR
epos
itory
–In
terf
ace
Rep
osito
ry
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
OMA Reference Model Interface Categories
OBJECT REQUEST BROKEROBJECT REQUEST BROKER
OBJECTOBJECT
SERVICESSERVICES
APPLICATIONAPPLICATION
INTERFACESINTERFACES
DOMAINDOMAIN
INTERFACESINTERFACES
COMMONCOMMON
FACILITIESFACILITIES
The Object Management Architecture (OMA) Reference Modeldescribes the interactions between various CORBA components andlayers
Vanderbilt University 112
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of the ORB Core
OBJECT ADAPTER
I/O SUBSYSTEM
ORB CORE
GIOP TRANSPORT PROTOCOLSIIOP/TCP/IP ATM RTP ISIS
ENDPOINT DEMULTIPLEXER
Features
� Connection/memorymanagement
� Request transfer
� Endpoint demuxing� Concurrency control
Vanderbilt University 113
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Tracing a Request Through a CORBA ORB
Leader/Followers
Connection Cache Memory Pool
ConnectorReactor
A BCV2
A
POA
S
CV1
Client ORB
B S
Connection Cache Memory Pool
AcceptorReactor
A B
A
C
Server ORB
B C
1, 3
2
4
5
6
9
10
11
12, 14, 16
13
15
19
7, 8, 17
18, 20
Request invocation phases
1. Client ORB connectionmanagement
2. Server ORB connectionmanagement
3. Client invocation for twowaycalls
4. Server processing fortwoway calls
5. Client reply handling fortwoway calls
Vanderbilt University 114
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Client ORB Connection Management
The following are the activities a client ORB performs to create aconnection actively when a client application invokes an operation onan object reference to a target server object:
1. Query the client ORB’s connection cache for an existing connectionto the server designated in the object reference on which theoperation is invoked
2. If the cache doesn’t contain a connection to the server, use aconnector factory to create a new connection S
3. Add the newly established connection S to the connection cache
4. Also add connection S to the client ORB’s reactor since S isbi-directional and the server may send requests to the client using S
Vanderbilt University 115
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Server ORB Connection Management
The server ORB activities for accepting a connection passively include:
5. Use an acceptor factory to accept the new connection C from theclient
6. Add C to the server ORB’s connection cache since C isbi-directional and the server can use it to send requests to the client
7. Also add connection C to the server ORB’s reactor so the server isnotified when a request arrives from the client
8. Wait in the reactor’s event loop for new connection and data events
Vanderbilt University 116
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Client Invocation of Synchronous Twoway Operation
We now describe the steps involved when a client invokes asynchronous two-way request to a server:
9. Allocate a buffer from a memory pool to marshal the parameters inthe operation invocation
10. Send the marshaled data to the server using connection S.Connection S is locked for the duration of the transfer
11. Use the leader/followers manager to wait for a reply from the server.Assuming that a leader thread is already available, the client threadwaits as a follower on a condition variable or semaphore.1
1The leader thread may actually be a server thread waiting for incoming requests or another clientthread waiting for its reply
Vanderbilt University 117
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Server Processing for Twoway OperationThe server ORB activities for processing a request are describedbelow:
12. Read the header of the request arriving on connection C todetermine the size of the request
13. Allocate a buffer from a memory pool to hold the request
14. Read the request data into the buffer
15. Demultiplex the request to find the target portable object adapter(POA), servant, and skeleton – then dispatch the designated upcallto the servant after demarshaling the request parameters
16. Send the reply (if any) to the client on connection C, connection C islocked for the duration of the transfer
17. Wait in the reactor’s event loop for new connection and data events
Vanderbilt University 118
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Client Reply Handling for Twoway Operation
Finally, the client ORB performs the following activities to process areply from the server:
18. The leader thread reads the reply from the server on connection S
19. After identifying that the reply belongs to the follower thread, theleader thread hands off the reply to the follower thread by signalingthe condition variable used by the follower thread
20. The follower thread demarshals the parameters and returns controlto the client application, which processes the reply
Vanderbilt University 119
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
CO
RB
AIn
tero
pera
bilit
yP
roto
cols
OR
B M
ES
SA
GIN
G
CO
MP
ON
EN
T
OR
B T
RA
NS
PO
RT
AD
AP
TE
R
CO
MP
ON
EN
T
TR
AN
SP
OR
T
LA
YE
R
NE
TW
OR
K
LA
YE
R
GIO
P
IIO
P
TC
P
IP
VM
E
DR
IVE
R
AA
L5
AT
M
GIO
PL
ITE
VM
E-I
OP
ES
IOP
AT
M-I
OP
RE
LIA
BLE
SE
QU
EN
CE
D
PR
OT
OC
OL
CO
NF
IGU
RA
TIO
NS
ST
AN
DA
RD
C
OR
BA
P
RO
GR
AM
MIN
G
AP
I
�
GIO
P
–E
nabl
esO
RB
-to-
OR
Bin
tero
pera
bilit
y
�
IIOP
–W
orks
dire
ctly
over
TC
P/IP
,no
RP
C
�
ES
IOP
s
–e.
g.,D
CE
,DC
OM
,wire
less
,etc
.
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of GIOP and IIOP
� Common Data Representation (CDR)
– Transfer syntax mapping OMG-IDL data types into a bi-canonicallow-level representation
� Supports variable byte ordering and aligned primitive types
� Message transfer
– Request multiplexing, i.e., shared connections– Ordering constraints are minimal, i.e., can be asynchronous
� Message formats
– Client: Request , CancelRequest , LocateRequest– Server: Reply , LocateReply , CloseConnection– Both: MessageError
� IIOP is a mapping of GIOP over TCP/IP
Vanderbilt University 121
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Exa
mpl
eG
IOP
For
mat
module
GIO
P{
enum
Msg
Typ
e{
Request
,R
eply
,C
ance
lRequest
,Loca
teR
equest
,Loca
teR
eply
,C
lose
Connect
ion,
Mess
ageE
rror
}; stru
ctM
ess
ageH
eader
{ch
ar
magic
[4];
Vers
ion
GIO
P_ve
rsio
n;
oct
et
byt
e_ord
er;
//F
ragm
ent
bit
in1.1
.oct
et
mess
age_ty
pe;
unsi
gned
long
mess
age_si
ze;
}; stru
ctR
equest
Header
{IO
P::S
erv
iceC
onte
xtLis
tse
rvic
e_co
nte
xt;
unsi
gned
long
request
_id
;//
Relia
ble
one-w
ay
bits
in1.2
boole
an
resp
onse
_re
quest
ed;
sequence
<oct
et>
obje
ct_ke
y;st
ring
opera
tion;
Princi
pal
request
ing_princi
pal;
}; //...
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Interface Definition Languages (IDLs)� Motivation
– Developing flexible distributed applications on heterogeneousplatforms requires
� An interface contract between client and server that definespermissible operations and types
� Strict separation of interface from implementation(s)
� Benefits of using an IDL
– Ensure platform independence ! e.g., Windows NT to UNIX– Enforce modularity ! e.g., separate concerns– Increase robustness ! e.g., eliminate common network
programming errors– Enable language independence ! e.g., COBOL, C, C++, Java,
etc.
Vanderbilt University 123
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Example IDLs
� Many IDLs are currently available, e.g.,
– OSI ASN.1– OSI GDMO– SNMP SMI– DCE IDL– Microsoft’s IDL (MIDL)– OMG IDL– ONC’s XDR
� However, many of these are procedural IDLs
– These are more complicated to extend and reuse since they don’tsupport inheritance
Vanderbilt University 124
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of OMG IDL (1/2)
� OMG IDL is an object-oriented interface definition language
– Used to specify interfaces containing operations and attributes– OMG IDL support interface inheritance (both single and multiple
inheritance)
� OMG IDL is designed to map onto multiple programming languages
– e.g., C, C++, C#, Java, Smalltalk, COBOL, Perl, etc.
� All data exchanged between clients and servers must be definedusing OMG IDL
Vanderbilt University 125
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of OMG IDL (2/2)
� OMG IDL is similar to Java interfaces or C++ abstract classes
– i.e., it defines the interface and type “contracts” that clients andservers must agree upon to exchange data correctly andefficiently
� OMG IDL is not a complete programming language, however
– e.g., it is purely declarative and can not be used to define objectstate or perform computations
� IDL source files must end with the .idl suffix
Vanderbilt University 126
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
OMG IDL Features� OMG IDL is similar to C++ and Java
– e.g., comment styles, identifiers, built-in types, etc.
� OMG IDL supports the following features:
– modules and interfaces– Operations and Attributes– Single and multiple inheritance– Fixed-size basic types (e.g., double , long , char , octet , etc).– Arrays and sequence– struct, enum, union, typedef– consts– exceptions
Vanderbilt University 127
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
OMG IDL Differences from C++ and Java
� Case-insensitive
� No control constructs
� No data members (cfvaluetypes)
� No pointers (cf valuetypes)
� No constructors or destructors
� No overloaded operations
� No int data type
� Contains parameter passingmodes
� Unions require a tag
� Different String type
� Different Sequence type
� Different exception interface
� No templates
� oneway call semantics
� readonly keyword
� any type
Vanderbilt University 128
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Using OMG IDL Interfaces Effectively
� The CORBA specification and services are defined using IDL
� Interfaces described using OMG IDL can also be application-specific
– e.g., databases, spreadsheets, spell checkers, networkmanagers, air traffic control systems, documents, medicalimaging systems, etc.
� Objects may be defined at any level of granularity
– e.g., from fine-grained GUI objects to multi-megabyte multimedia“Blobs”
� It’s essential to remember that distributed objects will incur higherlatency than collocated objects
– Interfaces designed for purely stand-alone applications maytherefore require reengineering
Vanderbilt University 129
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Static Invocation Interface (SII)
// Get object reference.Quoter_var quoter = // ...
const char *name ="ACME ORB Inc.";
CORBA::Long value =quoter->get_quote (name);
cout << name << " = "<< value << endl;
� The common way to use OMG IDL isthe “Static Invocation Interface” (SII)
� All operations are specified inadvance and are known to client viastubs
– Stubs marshal operation calls intorequest messages
� The advantages of SII are simplicity, typesafety, and efficiency
� The disadvantage of SII is its inflexibility (and potentially its footprint)
Vanderbilt University 130 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
SII
Stu
bsus
eth
eP
roxy
Pat
tern
NE
TW
OR
K
CL
IEN
T
SE
RV
ER
2: F
OR
WA
RD
RE
QU
ES
T3:
RE
SP
ON
SE
1: M
ET
HO
D C
AL
L
4: M
ET
HO
D R
ET
UR
N
: QU
OTE
R
PR
OX
Y
: BR
OK
ER
get
_qu
ote
()
get
_qu
ote
()
: QU
OTE
R S
KE
LETO
N
: QU
OTE
R
Inte
nt:
prov
ide
asu
rrog
ate
for
anot
her
obje
ctth
atco
ntro
lsac
cess
toit
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Dynamic Invocation Interface (DII)
� A less common programming API is the “Dynamic InvocationInterface” (DII)
– Enables clients to invoke operations on objects that aren’t knownuntil run-time
� e.g., MIB browsers– Allows clients to “push” arguments onto a request stack and
identify operations via an ASCII name
� Type-checking via meta-info in “Interface Repository”
� The DII is more flexible than the SMI SII
– e.g., it supports deferred synchronous invocation and enablesdynamic dispatching of operations
� However, the DII is also more complicated, less typesafe, andinefficient
Vanderbilt University 132 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
An
Exa
mpl
eD
IIC
lient
//G
et
Quote
rre
fere
nce
.S
tock
::Q
uote
r_va
rquote
r_re
f=
//...
CO
RB
A::Long
valu
e;
//C
reate
request
obje
ct.
CO
RB
A::R
equest
_va
rre
quest
=quote
r_re
f->
_re
quest
("get_
quote
");
//A
dd
para
mete
rusi
ng
inse
rtio
nopera
tion,
//w
hic
hm
ake
sa
‘‘deep
copy’
’and
sets
//ty
peco
de
to‘‘u
nbounded
string.’’
request
->add_in
_arg
()<
<=
"IO
NA
Y";
request
->se
t_re
turn
_ty
pe
(CO
RB
A::_tc
_lo
ng);
request
->in
voke
();
//C
all
meth
od.
//R
etr
ieve
valu
eusi
ng
ext
ract
ion
//opera
tor,
whic
hm
ake
sa
‘‘shallo
wco
py.
’’if
(request
->re
turn
_va
lue
()>
>=
valu
e)
cout
<<
"Curr
ent
valu
eof
ION
Ast
ock
:"
<<
valu
e<
<endl;
�
The
DII
exam
ple
abov
eis
mor
eco
mpl
icat
edan
din
effic
ient
than
the
earli
erS
IIex
ampl
e
�
ww
w.c
s.w
ustl.
edu/
�
schm
idt/r
epor
t-do
c.ht
mlh
asm
ore
info
rmat
ion
onD
II
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Static and Dynamic Skeleton Interface
� The Static Skeleton Interface (SSI) is generated automatically by theIDL compiler
– The SII performs the operation demuxing/dispatching andparameter demarshaling
� The Dynamic Skeleton Interface (DSI) provides analogousfunctionality for the server that the DII provides on the client
– It is defined primarily to build ORB “Bridges”– The DSI lets server code handle arbitrary invocations on CORBA
objects– The DSI requires the use of certain POA features
Vanderbilt University 134
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Advanced CORBA Features
HOSTINFRASTRUCTURE
MIDDLEWARE LAYER
Container
… …
Container
… …
Object Adapter
ORB CORE
OS/KERNEL
DISTRIBUTIONMIDDLEWARE
LAYER
COMPONENTMIDDLEWARE
LAYER
Client
OBJREF
DII IDLSTUBS ORB
INTERFACE
in argsoperation()
out args +return
IDLSKEL
Component(Servant)
NETWORKPROTOCOLS
NETWORKINTERFACE
OS/KERNELNETWORK
PROTOCOLS
NETWORKINTERFACE
NETWORK
Services
www.cs.wustl.edu/�schmidt/corba.html
Features
� Portable ObjectAdapter
� Multi-threading
� ImplementationRepository
� CORBAComponent Model
Vanderbilt University 135
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of the Portable Object Adapter (POA)
OBJECTOBJECT ADAPTERADAPTER
II//OO SUBSYSTEMSUBSYSTEM
ORB CORB COREORE
SERVANTSSERVANTS
SERVANTSSERVANTS
RootRootPOAPOA
ACTIVEACTIVE OBJECTOBJECT MAPMAP
SERVANTSSERVANTS
OOBJECTBJECT IDID
OOBJECTBJECT IDID
OOBJECTBJECT IDID
PERSISTENTPERSISTENT
POAPOA
OBJECT ID
OBJECT ID
SERVANTS
SERVANTS
PortableServer interfaces
� POA
� POAManager
� Servant
� POA Polices
� Servant activators and servantlocators
� POACurrent
� AdapterActivator
Vanderbilt University 136
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Design Goals of the Portable Object Adapter
� Servants that are portable between ORBs
� Objects with persistent & transient identities
� Transient objects with minimal programming effort and overhead
� Transparent activation & deactivation of servants
� Implicit and explicit servant activation
� A single servant can support multiple object identities
� Multiple (nested) instances of the POA in a server process
� POA behavior is dictated by creation policies
� Servants can inherit from skeletons or use DSI
Vanderbilt University 137
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
The
PO
AA
rchi
tect
ure
PO
A M
anag
er
Obj
ect I
dO
bjec
t Id
Obj
ect I
dO
bjec
t Id
Act
ive
Obj
ect M
ap
defa
ult s
erva
nt
PO
A A
Act
ive
Obj
ect M
ap
PO
A B
adap
ter
activ
ator
Obj
ect I
dO
bjec
t Id
Obj
ect I
d
PO
A C
Act
ive
Obj
ect M
ap
Roo
tPO
A
Obj
ect I
d
SE
RV
AN
T
SE
RV
AN
T
SE
RV
AN
T
SE
RV
AN
TS
ER
VA
NT
SE
RV
AN
T
SE
RV
AN
T
Ser
vant
Act
ivat
or
PO
A M
anag
er
Use
r de
fined
obje
ct
PO
A o
bjec
t
Poi
nter
Obj
ect
refe
renc
e
Lege
nd
Ada
pter
Act
ivat
or
serv
ant
loca
tor
serv
ant
activ
ator
Ser
vant
Loca
tor
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Object Lifecycle for a POA
Vanderbilt University 139
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Object IDs
� Object IDs are the value used by the POA and by the ORBimplementation to identify particular CORBA objects
– Object ID values may be assigned by the POA or by theapplication
– Object ID values are encapsulated by references and hidden fromclients
– Object ID have no standard form; they are managed by the POAas uninterpreted octet sequences
� An object reference encapsulates an object Id, a POA identity, andtransport profiles
Vanderbilt University 140
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of POAs
� POAs form a hierarchical namespace for objects in servers
– i.e., a namespace for object ids and child POAs
� Each servant belongs to one POA, but a POA can contain manyservants
� A POA is a manager for object lifecycles, e.g.:
– A factory for creating object refs– Activates and deactivates objects– Etherealizes and incarnates servants
� A POA maps client requests to servants
� POA policies specify the characteristics of a child POA when it iscreated
Vanderbilt University 141
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
PO
AA
rchi
tect
ure
inU
ML
CO
RB
A::P
olic
yLis
t(f
rom
CO
RB
A C
ore)
: CO
RB
A::P
olic
y
CO
RB
A::C
urre
nt(f
rom
CO
RB
A C
ore)
Port
able
Serv
er::C
ooki
e
Port
able
Serv
er::C
urre
nt(f
rom
Por
tabl
eSer
ver)
get_
obje
ct_i
d()
(fro
m P
orta
bleS
erve
r)Po
rtab
leSe
rver
::Ser
vant
(fro
m C
OR
BA
Cor
e)C
OR
BA
::Pol
icy
(fro
m P
orta
bleS
erve
r)
Port
able
Serv
er::P
OA
Man
ager
(fro
m P
orta
bleS
erve
r)
activ
ate(
)
disc
ard_
requ
ests
()
get_
POA
()
Port
able
Serv
er::A
dapt
erA
ctiv
ator
(fro
m P
orta
bleS
erve
r)
unkn
own_
adap
ter(
)
Port
able
Serv
er::O
bjec
tId
(fro
m P
orta
bleS
erve
r)
the_
pare
nt
the_
serv
ant_
man
ager
the_
activ
ator
copy
()
the_
man
ager
dest
roy(
)
hold
_req
uest
s()
deac
tivat
e()
Port
able
Serv
er::S
erva
ntM
anag
er(f
rom
Por
tabl
eSer
ver)
Port
able
Serv
er::S
erva
ntL
ocat
orPo
rtab
leSe
rver
::Ser
vant
Act
ivat
or(f
rom
Por
tabl
eSer
ver)
(fro
m P
orta
bleS
erve
r)
prei
nvok
e()
post
invo
ke()
inca
rnat
e()
ethe
real
ize(
)
0..n
0..n
1..n
1..n
0..1
Port
able
Serv
er::P
OA
(fro
m P
orta
bleS
erve
r)
the_
nam
e : s
trin
gth
e_pa
rent
: Po
rtab
leSe
rver
::PO
Ath
e_m
anag
er: P
orta
bleS
erve
r::P
OA
Man
ager
the_
activ
ator
: Por
tabl
eSer
ver:
:Ada
pter
Act
ivat
orth
e_se
rvan
t_m
anag
er: P
orta
bleS
erve
r::S
erva
ntM
anag
er
crea
te_P
OA
()fi
nd_P
OA
()de
stro
y()
crea
te_t
hrea
d_po
licy(
)cr
eate
_lif
espa
n_po
licy(
)cr
eate
_id_
uniq
uene
ss_p
olic
y()
crea
te_i
d_as
sign
men
t_po
licy(
)cr
eate
_im
plic
it_ac
tivat
ion_
polic
y()
crea
te_s
erva
nt_r
eten
tion_
polic
y()
crea
te_r
eque
st_p
roce
ssin
g_po
licy(
)ge
t_in
stan
ce_m
anag
er()
set_
inst
ance
_man
ager
()ge
t_se
rvan
t()
set_
serv
ant(
)ac
tivat
e_ob
ject
()ac
tivat
e_ob
ject
_with
_id(
)de
activ
ate_
obje
ct()
crea
te_r
efer
ence
()cr
eate
_ref
eren
ce_w
ith_i
d()
serv
ant_
to_i
d()
serv
ant_
to_r
efer
ence
()re
fere
nce_
to_s
erva
nt()
refe
renc
e_to
_id(
)id
_to_
serv
ant(
)id
_to_
refe
renc
e()
0..n
1..1
0..n
0..1
1..1
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of the POA Manager
activate
discard_requests
Inactive
Active Discarding
discard_requests
deactivate
create_POA
hold_requests
hold_requestsactivate
deactivatedeactivate
destroy
Holding
� Encapsulates the processingstate of associated POAs
� Can dispatch, hold, or discardrequests for the associatedPOAs and deactivate POA(s)
– The default state is “holding”
� A POA manager is associatedwith a POA at creation time andcannot be changed aftercreation
Vanderbilt University 143
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of POA Policies
� When a POA is created, its behavior can be controlled by up toseven policies
– i.e., lifespan, ID assignment, ID uniqueness, implicit activation,request processing, servant retention, and thread policies
� These policies all inherit from the CORBA::Policy interfacemodule CORBA {
typedef unsigned long PolicyType;interface Policy {
readonly attribute PolicyType policy_type;Policy copy ();void destroy ();
};typedef sequence<Policy> PolicyList;// ...
� The POA interface defines a factory method to create each policy
Vanderbilt University 144 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Ove
rvie
wof
the
Act
ive
Obj
ectM
ap
�
By
defa
ult,
aP
OA
cont
ains
anac
tive
obje
ctm
ap(A
OM
)
�
The
obje
ctID
inth
eob
ject
key
sent
byth
ecl
ient
isth
ein
dex
into
the
AO
M
SK
EL
1
SE
RV
AN
T 1
SE
RV
AN
T N
SE
RV
AN
T 2
OB
JEC
T ID
1O
BJE
CT
ID2
OB
JEC
T ID
N..
.
/RootPOA/POA1/objectid1
OPERATION1
OPERATION2
OPERATIONK
... ..
.P
OA
1
OR
B
CO
RE
RO
OT
P
OA
PO
A2
PO
AN
...
SK
EL
2SK
EL N
OR
BL
AY
ER
SE
RV
AN
TS
AC
TIV
E O
BJ
EC
T M
AP
OBJECT KEY
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of the Root POA
� The Root POA has a preordained set of policies that cannot bechanged:
– The lifespan policy is transient– The ID assignment policy uses system IDs– The ID uniqueness policy uses unique IDs– The implicit activation policy is enabled (not default)– The request processing policy uses an active object map– The servant retention policy retains servants– The thread policy gives the ORB control
� If these policies are inappropriate, you can create your own childPOAs via the PortableServer::POA::create_POA() factory
Vanderbilt University 146
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Canonical Steps to Obtain the Root POA
// ORB is ‘‘locality constrained’’CORBA::ORB_var orb = CORBA::ORB_init (argc, argv);
// Root POA is the default POA (locality constrained)CORBA::Object_var obj =
orb->resolve_initial_references ("RootPOA");
// Type-safe downcast.PortableServer::POA_var root_poa
= PortableServer::POA::_narrow (obj.in ());
// Activate the POA.PortableServer::POA_Manager_var poa_manager =
root_poa->the_POAManager ();poa_manager->activate ();// FMM 2// root_poa->the_POAManager ()->activate ();
Vanderbilt University 147
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Implicit Activation Policy
� This policy controls whether a servant can be activated implicitly orexplicitly
enum ImplicitActivationPolicyValue {IMPLICIT_ACTIVATION,NO_IMPLICIT_ACTIVATION /* DEFAULT */ };
interface ImplicitActivationPolicy : CORBA::Policy {readonly attribute ImplicitActivationPolicyValue value;
}
� When the IMPLICIT_ACTIVATION policy value is used withRETAIN and SYSTEM_IDpolicy values servants are added to theAOM by calling _this()
� The NO_IMPLICIT_ACTIVATION policy value requires servants tobe activated via one of the POA::activate_object*() calls
Vanderbilt University 148 CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Impl
ictA
ctiv
atio
nw
ithS
yste
mID
s
Thi
sex
ampl
eill
ustr
ates
_th
is()
:
inte
rface
Quote
r{
//...
IDL
long
get_
quote
(in
string
stock
_nam
e)
rais
es
(Inva
lid_S
tock
);}; //
Auto
-genera
ted
for
use
by
serv
ants
.cl
ass
My_
Quote
r:
public
virt
ual
PO
A_S
tock
::Q
uote
r{ public
://
...
CO
RB
A::Long
get_
quote
(const
char
*sto
ck_nam
e);
}; My_
Quote
r*q
uote
r=
new
My_
Quote
r;
//F
MM
6--
not
transf
ering
the
ow
ners
hip
to//
Port
able
Serv
er:
:Serv
antB
ase
_va
r//
Implic
itact
ivatio
nw
ithsy
stem
IDC
OR
BA
::O
bje
ct_va
robjref
=quote
r->
_th
is()
;
Port
able
Serv
er:
:PO
A_M
anager_
var
poa_m
anager
=ro
ot_
poa->
the_P
OA
Manager
();
poa_m
anager-
>act
ivate
();
orb
->ru
n()
;
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of ID Assignment Policy
� This policy controls whether object IDs are created by the ORB orby an application
enum IdAssignmentPolicyValue {USER_ID,SYSTEM_ID /* DEFAULT */
};
interface IdAssignmentPolicy : CORBA::Policy {readonly attribute IdAssignmentPolicyValue value;
}
� The USER_ID policy value works best with theNO_IMPLICIT_ACTIVATION and PERSISTENTpolicy values
� The SYSTEM_IDpolicy value works best with theIMPLICIT_ACTIVATION and TRANSIENTpolicy values
Vanderbilt University 150
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Lifespan Policy� This policy controls whether object references are transcient or
persistent
enum LifespanPolicyValue {PERSISTENT,TRANSIENT /* DEFAULT */
};
interface LifespanPolicy : CORBA::Policy {readonly attribute LifespanPolicyValue value;
}
� The PERSISTENTpolicy value works best with theNO_IMPLICIT_ACTIVATION and USER_ID policy values
� The TRANSIENTpolicy value works best with theIMPLICIT_ACTIVATION and SYSTEM_IDpolicy values
Vanderbilt University 151
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Creating a Child POAWe use the PortableServer::POA::create_POA() operation tocreate a new POA with the USER_ID and PERSISTENTpolicies
// FMM 4: Not calling length() is a mistake!CORBA::PolicyList policies (2); policies.length (2);
policies[0] = root_poa->create_id_assignment_policy(PortableServer::IdAssignmentPolicy::USER_ID);
policies[1] = root_poa->create_lifespan_policy(PortableServer::LifespanPolicy::PERSISTENT);
PortableServer::POA_var child_poa =root_poa->create_POA
("child_poa", // New POA namePortableServer::POAManager::_nil (), // Non-shared POA managerpolicies); // New POA policies
for (CORBA::ULong i = 0; i != policies.length (); ++i)policies[i]->destroy ();
Vanderbilt University 152
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Explicit Activation with User IDsThis example illustrates POA::activate_object_with_id() :
// Create a new servant instance.My_Quoter *quoter = new My_Quoter;
// Create a new user-defined object ID for the object.PortableServer::ObjectId_var oid =
PortableServer::string_to_ObjectId ("my quoter");
// Activate the object with the new object IDchild_poa->activate_object_with_id (oid.in (), quoter);PortableServer::POA_Manager_var poa_manager =
child_poa->the_POAManager ();poa_manager ()->activate ();// Run the ORB’s event loop.orb->run ();
Vanderbilt University 153
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Deactivating Objects
� There are certain steps to follow when deactivating objects
void My_Quoter::remove (void)throw (CORBA::SystemException,
CosLifeCycle::LifeCycleObject::NotRemovable);{
PortableServer::POA_var poa = this->_default_POA ();PortableServer::ObjectId_var oid = poa->servant_to_id (this);// POA calls _remove_ref() on servant once all// operations are completedpoa->deactivate_object (oid.in ());
}
� Calling _remove_ref() from the application could destroy theservant, but the POA has no knowledge of this and could potentiallydispatch calls to the same servant since object entries in the activeobject map are still active and they haven’t been invalidated
Vanderbilt University 154
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
The Servant Retention Policy� This policy controls whether a POA has an active object map.
enum ServantRetentionPolicyValue{ NON_RETAIN, RETAIN /* DEFAULT */ };
interface ServantRetentionPolicy : CORBA::Policy {readonly attribute ServantRetentionPolicyValue value;
}
� The NON_RETAINpolicy value must be used in conjunction with therequest processing policy of either
– USE_DEFAULT_SERVANT, in which case the POA delegatesincoming requests to a default servant (used for DSI)
– USE_SERVANT_MANAGER, in which case the POA uses theInterceptor pattern to determine how to associate a servant withthe request
Vanderbilt University 155
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
POA Policies for Lazy Object AllocationThe following example illustrates how to create references without firstactivating objects:
PortableServer::ObjectId_var oid =PortableServer::string_to_ObjectId ("my quoter");
CORBA::Object_var obj =child_poa->create_reference_with_id
(oid.in (),"IDL:Stock/Quoter:1.0"); // Repository ID.
// Insert into a name context.name_context->bind (svc_name, obj.in ());
// Later the following steps happen:// 1. A new My_Quoter servant is created// 2. This object is activated in the child_poa
Vanderbilt University 156
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Repository IDs
� An IDL compiler generates a unique repository ID for each identifierin an IDL file
module Stock { // IDL:Stock:1.0interface Quoter { // IDL:Stock/Quoter:1.0
long get_quote (in string stock_name);// IDL:Stock/Quoter/get_quote:1.0
};
� You can use #pragma prefix to ensure the uniqueness ofrepository IDs
#pragma prefix "wallstreet.com"module Stock { // IDL:wallstreet.com/Stock:1.0
interface Quoter { // IDL:wallstreet.com/Stock/Quoter:1.0long get_quote (in string stock_name);// IDL:wallstreet.com/Stock/Quoter/get_quote:1.0
};
� You can use #pragma version to change the version number
Vanderbilt University 157
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Servant Managers
� The POA defines servant managers to support the lazy objectallocation approach described above
� A servant manager is an interceptor that incarnates andetherealizes servants on-demand
� Two types of servant managers are supported
– ServantActivator , which allocates a servant the first time it’saccessed
– ServantLocator , which allocates and deallocates a servant oneach request
� Naturally, each type of servant manager can be selected via POApolicies
Vanderbilt University 158
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
The Request Processing Policy� This policy controls whether a POA uses an AOM, a default servant,
or “faults in” servants on-demand
enum RequestProcessingPolicyValue {USE_ACTIVE_OBJECT_MAP_ONLY /* DEFAULT */,USE_DEFAULT_SERVANT,USE_SERVANT_MANAGER
};
interface RequestProcessingPolicy : CORBA::Policy {readonly attribute RequestProcessingPolicyValue value;
}
� The USE_ACTIVE_OBJECT_MAP_ONLYpolicy value must be usedin conjunction with the RETAIN servant retention policy
� The USE_DEFAULT_SERVANTpolicy value must be used inconjunction with the MULTIPLE_ID ID uniqueness policy
Vanderbilt University 159
CORBA Tutorial Douglas C. Schmidt
Servant Activator DefinitionA POA created with RETAIN servant retentionpolicy and the USE_SERVANT_MANAGERrequestprocessing policy uses the servant activator to“fault in” servants into the POA
typedef ServantBase *Servant;
// Skeleton classnamespace POA_PortableServer{
class ServantActivator :public virtual ServantManager
{// Destructor.virtual ˜ServantActivator (void);
// Create a new servant for <id>.virtual Servant incarnate
(const ObjectId &id,POA_ptr poa) = 0;
// <servant> is no longer active in <poa>.virtual void etherealize
(const ObjectId &,POA_ptr poa,Servant servant,Boolean remaining_activations) = 0;
};}
Vanderbilt University
CORBA Tutorial Douglas C. Schmidt
Custom ServantActivatorDefinition and Creation
// Implementation class.class My_Quoter_Servant_Activator :
public POA_PortableServer::ServantActivator{
Servant incarnate (const ObjectId &oid,POA_ptr poa) {
String_var s =PortableServer::ObjectId_to_string (oid);
if (strcmp (s.in (), "my quoter") == 0)return new My_Quoter;
elsethrow CORBA::OBJECT_NOT_EXIST ();
}
void etherealize(const ObjectId &oid,
POA_ptr poa,Servant servant,Boolean remaining_activations) {
if (remaining_activations == 0)servant->_remove_ref ();
}};
Vanderbilt University
CORBA Tutorial Douglas C. Schmidt
Overview of the String var Class
String_var is a “smart pointer” class
class String_var {public:
// Initialization and termination methods.String_var (char *); // Assumes ownership.String_var (const char *); // CORBA::string_dup().// ... (assignment operators are similar)˜String_var (); // Deletes the string.
// Indexing operators.char &operator[] (CORBA::ULong index);char operator[] (CORBA::ULong index) const;
// Workarounds for broken C++ compilers.const char *in () const;char *&inout ();char *&out ();
// Relinquishes ownership.char *_retn ();
};
istream &operator >> (istream, CORBA::String_var &);ostream &operator << (ostream,
const CORBA::String_var);
Vanderbilt University
CORBA Tutorial Douglas C. Schmidt
Servant Locator Definition
A POA created with NON_RETAINservant retentionpolicy and the USE_SERVANT_MANAGERrequestprocessing policy uses the servant locator tocreate/destroy a servant for each request
namespace POA_PortableServer{
class ServantLocator :public virtual ServantManager {// Destructor.virtual ˜ServantLocator (void);
// Create a new servant for <id>.virtual PortableServer::Servant preinvoke
(const PortableServer::ObjectId &id,PortableServer::POA_ptr poa,const char *operation,PortableServer::Cookie &cookie) = 0;
// <servant> is no longer active in <poa>.virtual void postinvoke
(const PortableServer::ObjectId &id,PortableServer::POA_ptr poa,const char *operation,PortableServer::Cookie cookie,PortableServer::Servant servant) = 0;
};}
Vanderbilt University
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
Cus
tom
Ser
vant
Loca
tor
Defi
nitio
nan
dC
reat
ion
//Im
ple
menta
tion
class
.cl
ass
My_
Quote
r_S
erv
ant_
Loca
tor
:public
PO
A_P
ort
able
Serv
er:
:Serv
antL
oca
tor
{S
erv
ant
pre
invo
ke(c
onst
Port
able
Serv
er:
:Obje
ctId
&oid
,P
ort
able
Serv
er:
:PO
A_ptr
poa,
const
char
*opera
tion,
Port
able
Serv
er:
:Cooki
e&
cooki
e)
{C
OR
BA
::S
trin
g_va
rke
y=
Port
able
Serv
er:
:Obje
ctId
_to
_st
ring
(oid
);O
bje
ct_S
tate
state
;if
(data
base
_lo
oku
p(k
ey,
state
)=
=-1
)th
row
CO
RB
A::O
BJE
CT
_N
OT
_E
XIS
T()
;re
turn
new
My_
Quote
r(&
state
);} vo
idpost
invo
ke(c
onst
Port
able
Serv
er:
:Obje
ctId
&id
,P
ort
able
Serv
er:
:PO
A_ptr
poa,
const
char
*opera
tion,
Port
able
Serv
er:
:Cooki
eco
oki
e,
Port
able
Serv
er:
:Serv
ant
serv
ant)
{data
base
_update
(serv
ant)
;se
rvant-
>_re
move
_re
f()
;}
}; Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Registering Servant LocatorsPortableServer::ObjectId_var oid =
PortableServer::string_to_ObjectId ("my quoter");CORBA::Object_var obj =
poa->create_reference_with_id (oid.in (),"IDL:Quoter:1.0");
// Insert into a name context.name_context->bind (svc_name, obj.in ());
My_Quoter_Servant_Locator *quoter_locator =new My_Quoter_Servant_Locator;
// Locality constrained.ServantLocator_var locator = quoter_locator->_this ();poa->set_servant_manager (locator.in ());PortableServer::POA_Manager_var poa_manager =
poa->the_POAManager ();poa_manager ()->activate ();orb->run ();
Vanderbilt University 165
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of Adapter Activators
� Adapter Activator: Callback object used when a request is receivedfor a child POA that does not exist currently
– The adapter activator can then create the required POA ondemand
Vanderbilt University 166
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Additional Information on the POA� See OMG POA specification for some examples:
– One Servant for all Objects– Single Servant, many objects and types, using DSI
� See Vinoski/Henning book for even more examples
� See Schmidt/Vinoski C++ Report columns
– www.cs.wustl.edu/�schmidt/report-doc.html
� See TAO release to experiment with working POA examples
– $TAO_ROOT/tests/POA/– $TAO_ROOT/examples/POA/
Vanderbilt University 167
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Motivation for Concurrency in CORBA
SERVER
WORK
REQUEST
WORK
REQUEST
WORK
REQUEST
WORK
REQUEST
CLIENT
CLIENT
CLIENT CLIENT
(2) CONCURRENT SERVER
maxfdp1
read_fds
WORK
REQUEST
SERVER
CLIENT
WORK
REQUEST
WORK
REQUEST
WORK
REQUESTCLIENT
CLIENT CLIENT
(1) ITERATIVE SERVER
� Leverage hardware/software
– e.g., multi-processors and OSthread support
� Increase performance
– e.g., overlap computation andcommunication
� Improve response-time
– e.g., GUIs and network servers
� Simplify program structure
– e.g., sync vs. async
Vanderbilt University 168
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Overview of the Thread Policy
� This policy controls whether requests are dispatched serially (i.e.,single-threaded) or whether they are dispatched using anORB-defined threading modelenum ThreadPolicyValue{ SINGLE_THREAD_MODEL, ORB_CTRL_MODEL /* DEFAULT */ };
interface ThreadPolicy : CORBA::Policy {readonly attribute ThreadPolicyValue value;
}
� The SINGLE_THREAD_MODELpolicy value serializes all requestswithin a particular POA (but not between POAs, so beware of“servant sharing”...)
� The ORB_CTRL_MODELcan be used to allow the ORB to select thetype of threading model and synchronization for a particular POA(which is not very portable, of course...)
Vanderbilt University 169
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Threading in TAO
� An application can choose to ignore threads and if it creates none, itneed not be thread-safe
� TAO can be configured with various concurrency strategies:
– Reactive (default)– Thread-per-Connection– Thread Pool– Thread-per-Endpoint
� TAO also provides many locking strategies
– TAO doesn’t automatically synchronize access to applicationobjects
– Therefore, applications must synchronize access to their ownobjects
Vanderbilt University 170
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
TAO Multi-threading Examples� Each example implements a concurrent CORBA stock quote service
– Show how threads can be used on the server
� The server is implemented in two different ways:
1. Thread-per-Connection ! Every client connection causes a newthread to be spawned to process it
2. Thread Pool ! A fixed number of threads are generated in theserver at start-up to service all incoming requests
� Note that clients are unaware which concurrency model is beingused...
Vanderbilt University 171
CO
RB
ATu
toria
lD
ougl
asC
.Sch
mid
t
TAO
’sT
hrea
d-pe
r-C
onne
ctio
nC
oncu
rren
cyA
rchi
tect
ure
Clie
nt
OB
JR
EF
Obj
ect
(Ser
vant
)in
arg
sop
erat
ion(
)ou
t arg
s +
retu
rn
IDL
SK
EL Obj
ect A
dapt
er
OR
B C
OR
E
IDL
ST
UB
Sor
b->r
un()
Pro
s
�
Sim
ple
toim
plem
enta
ndef
ficie
ntfo
rlo
ng-d
urat
ion
requ
ests
Con
s
�
Exc
essi
veov
erhe
adfo
rsh
ort-
dura
tion
requ
ests
�
Per
mits
unbo
unde
dnu
mbe
rof
conc
urre
ntre
ques
ts
Van
derb
iltU
nive
rsity
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Thread-per-Connection Main ProgramServer creates a Quoter_Factory and waits in ORB’s event loop
int main (void) {ORB_Manager orb_manager (argc, argv);
const char *factory_name = "my quoter factory";
// Create servant (registers with rootPOA and Naming Service).My_Quoter_Factory *factory =
new My_Quoter_Factory (factory_name);// Transfer ownership to smart pointer.PortableServer::ServantBase_var xfer (factory);
// Block indefinitely dispatching upcalls.orb_manager.run ();// After run() returns, the ORB has shutdown.
}
The ORB’s svc.conf file
static Advanced_Resource_Factory "-ORBReactorType select_mt"static Server_Strategy_Factory "-ORBConcurrency thread-per-connection"
Vanderbilt University 173
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Thread-per-Connection Quoter InterfaceImplementation of the Quoter IDL interface
typedef u_long COUNTER; // Maintain request count.
class My_Quoter : virtual public POA_Stock::Quoter{public:
My_Quoter (void *state); // Constructor.
// Returns the current stock value.long get_quote (const char *stock_name)
throw (CORBA::SystemException, Quoter::InvalidStock);
void remove (void)throw (CORBA::SystemException,
CosLifeCycle::LifeCycleObject::NotRemovable);private:
ACE_Thread_Mutex lock_; // Serialize access to database.static COUNTER req_count_; // Maintain request count.CORBA::String_var last_quote_; // The last symbol looked up.
};
Vanderbilt University 174
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Thread-per-Connection Quoter ImplementationImplementation of multi-threaded Quoter callback invoked by theCORBA skeleton
long My_Quoter::get_quote (const char *stock_name) {ACE_GUARD_RETURN (ACE_Thread_Mutex, g, lock_, -1);
++My_Quoter::req_count_; // Increment the request count.
// Obtain stock price (beware...).long value =
Quote_Database::instance ()->lookup_stock_price (stock_name);
if (value == -1)throw Stock::Invalid_Stock (); // Skeleton handles exceptions.
last_quote_ = stock_name;return value;
}
Vanderbilt University 175
CO
RB
ATutorial
Douglas
C.S
chmidt&
Bala
Natarajan
Thread
Pool
�
This
approachcreates
athread
pooltoam
ortizethe
costofdynam
icallycreating
threads
�
Inthis
scheme,before
waiting
forinputthe
servercode
createsthe
following:
1.A
Quote
r_F
acto
ry(as
before)2.
Apoolofthreads
basedupon
thecom
mand
lineinput
�
Note
theuse
oftheA
CE
_T
hre
ad_M
anager::sp
aw
n_
n()
method
tospaw
nm
ultiplepoolthreads
VanderbiltU
niversity176
CORBA Tutorial Douglas C. Schmidt
TAO’s Thread PoolConcurrency Architecture
Client
OBJREF
Object(Servant)
out args +return
IDLSKEL
Object Adapter
ORB CORE
IDLSTUBS
in argsoperation()
orb->run() orb->run() orb->run()
Pros
� Bounds the number of concurrentrequests
� Scales nicely for multi-processorplatforms, e.g., permits load balancing
Cons
� MayDeadlock
Vanderbilt University
CORBA Tutorial Douglas C. Schmidt
Thread Pool Main Program
int main (int argc, char *argv[]) {try {
ORB_Manager orb_manager (argc, argv);
const char *factory_name = "my quoter factory";
// Create the servant, which registers with// the rootPOA and Naming Service implicitly.My_Quoter_Factory *factory =
new My_Quoter_Factory (factory_name);// Transfer ownership to smart pointer.PortableServer::ServantBase_var xfer (factory);
int pool_size = // ...
// Create a thread pool.ACE_Thread_Manager::instance ()->spawn_n
(pool_size,&run_orb,(void *) orb_manager.orb ());
// Block indefinitely waiting for other// threads to exit.ACE_Thread_Manager::instance ()->wait ();
// After run() returns, the ORB has shutdown.} catch (...) { /* handle exception ... */ }
}
Vanderbilt University
CORBA Tutorial Douglas C. Schmidt
Thread Pool Configuration
The run_orb() adapter function
void run_orb (void *arg){
try {CORBA::ORB_ptr orb =
ACE_static_cast (CORBA::ORB_ptr, arg);
// Block indefinitely waiting for incoming// invocations and dispatch upcalls.orb->run ();
// After run() returns, the ORB has shutdown.} catch (...) { /* handle exception ... */ }
}
The ORB’s svc.conf file
static Resource_Factory "-ORBReactorType tp"
Vanderbilt University
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Additional Information on CORBA Threading
� See Real-time CORBA 1.0 specification
– Now adopted as part of CORBA specifications
� See our papers on CORBA Threading
– www.cs.wustl.edu/�schmidt/PDF/CACM-arch.pdf– www.cs.wustl.edu/�schmidt/PDF/RTAS-02.pdf– www.cs.wustl.edu/�schmidt/PDF/RT-perf.pdf– www.cs.wustl.edu/�schmidt/PDF/COOTS-99.pdf– www.cs.wustl.edu/�schmidt/PDF/orc.pdf– www.cs.wustl.edu/�schmidt/report-doc.html
� See TAO release to experiment with working threading examples
– $TAO_ROOT/tests/
Vanderbilt University 180
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Implementation Repository
� Allows the ORB to activate servers to process operation invocations
� Store management information associated with objects
– e.g., resource allocation, security, administrative control, serveractivation modes, etc.
� Primarily designed to work with persistent object references
� From client’s perspective, behavior is portable, but administrativedetails are highly specific to an ORB/OS environment
– i.e., not generally portable
� www.cs.wustl.edu/�schmidt/PDF/binding.pdf
Vanderbilt University 181
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Typical Implementation Repository Use-case
Client ImR (ringil:5000)
Server (ringil:5500)
1. some_request
4. LOCATION_FORWARD
2. ping3. is_running
5. some_request
6. some_response
iiop ://ringil:5000/poa_name/object_name
ringil:4500plane.exe airplane_poa
server.exepoa_name
ringil:4500plane.exe airplane_poa
server.exepoa_name ringil:5500
2.1 start
iiop ://ringil:5500/poa_name/object_name
Vanderbilt University 182
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Server Activation via Implementation Repository� If the server isn’t running when a client invokes an operation on an
object it manages, the Implementation Repository automaticallystarts the server
� Servers can register with the Implementation Repository
– e.g., in TAO% tao_imr add airplane_poa -c "plane.exe"
� Server(s) may be installed on any machine
� Clients may bind to an object in a server by using the NamingService or by explicitly identifying the server
Vanderbilt University 183
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Server Activation Modes
� An idle server will be automatically launched when one of its objectsis invoked
� TAO’s Implementation Repository supports four types of activation
1. Normal ! one server, started if needed but not running2. Manual ! one server, will not be started on client request, i.e.,
pre-launched3. Per-client call ! one server activated for each request to the
Implementation Repository4. Automatic ! like normal, except will also be launched when the
Implementation Repository starts
Vanderbilt University 184
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
The CORBA Component ModelCallback
COMPONENTCORBA
Container
Callback
COMPONENTCORBA
Interfaces
External
Home
InterfacesInternal
Container
Interfaces
POA
External
Home
InterfacesInternal
Interfaces
Persistent
Interfaces
POA
ORB
NotificationSecurity
Transactions
�schmidt/PDF/CBSE.pdf
� Features
– Navigation amonginterfaces supported bycomponents
– Standardizedsystem-componentinteraction
– Standardized componentlife-cycle management
– Componentinterconnections
– Standardized componentconfiguration
– Standardized ORBservices interfaces
Vanderbilt University 185
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Evaluating CORBA
INTERFACEREPOSITORY
IMPLEMENTATIONREPOSITORY
IDLCOMPILER
DII ORBINTERFACE
ORB CORE GIOP/IIOP/ESIOPS
IDLSTUBS
operation()in args
out args + return valueCLIENT
OBJECT(SERVANT)
OBJREF
STANDARD INTERFACE STANDARD LANGUAGE MAPPING
ORB-SPECIFIC INTERFACE STANDARD PROTOCOL
INTERFACEREPOSITORY
IMPLEMENTATIONREPOSITORY
IDLCOMPILER
IDLSKELETON
DSI
OBJECTADAPTER
www.cs.wustl.edu/�schmidt/corba.html
Criteria
� Learning curve
� Interoperability
� Portability
� FeatureLimitations
� Performance
Vanderbilt University 186
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Learning Curve� CORBA introduces the following:
1. New concepts– e.g., object references, proxies, and object adapters
2. New components and tools– e.g., interface definition languages, IDL compilers, and
object-request brokers3. New features
– e.g., exception handling and interface inheritance
� Time spent learning this must be amortized over many projects
Vanderbilt University 187
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Interoperability
� The first CORBA 1 spec was woefully incomplete with respect tointeroperability
– The solution was to use ORBs provided by a single supplier
� CORBA 2.x defines a useful interoperability specification
– Later extensions deal with portability issues for server
� i.e., the POA spec
� Most ORB implementations now support IIOP or GIOP robustly...
– However, higher-level CORBA services aren’t covered by ORBinteroperability spec...
Vanderbilt University 188
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Portability
� To improve portability, the latest CORBA specification standardizes
– IDL-to-C++ language mapping– Naming service, event service, lifecycle service– ORB initialization service– Portable Object Adapter API– Servant mapping– Server thread pools (Real-time CORBA)
� Porting applications from ORB-to-ORB is greatly simplified bycorbaconf
– http://corbaconf.kiev.ua
Vanderbilt University 189
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Feature Limitations (1/3)
� Standard CORBA doesn’t yet address all the “inherent” complexitiesof distributed computing, e.g.,
– Latency– Causal ordering– Deadlock
� It does address
– Service partitioning– Fault tolerance– Security
Vanderbilt University 190
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Feature Limitations (2/3)� All ORBs support the following semantics:
– Object references are passed by-reference
� However, all operations are routed to the originator– C-style structures and discriminated unions may be passed
by-value
� However, these structures and unions do not contain anymethods
� Older ORBs didn’t support passing objects-by-value (OBV)
– However, CORBA 2.3 OBV spec. defines a solution for this andmany ORBs now implement it
� If OBV is not available, objects can be passed by value usinghand-crafted “factories” (tedious)
Vanderbilt University 191
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Feature Limitations (3/3)
� Many ORBs do not yet support AMI and/or standard CORBAtimeouts
– However, these capabilities are defined in the OMG Messagingand are implemented by ORBs like TAO and Orbix 2000Specification
� Most ORBs do not yet support fault tolerance
– This was standardized by the OMG recently, however– www.omg.org/techprocess/meetings/schedule/Fault Tolerance RFP.html
� Versioning is supported in IDL via pragmas
– Unlike Sun RPC or DCE, which include in language
Vanderbilt University 192
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Performance Limitations
� Performance may not be as good as hand-crafted code for someapplications due to
– Additional remote invocations for naming– Marshaling/demarshaling overhead– Data copying and memory management– Endpoint and request demultiplexing– Context switching and synchronization overhead
� Typical trade-off between extensibility, robustness, maintainability !
micro-level efficiency
� Note that a well-crafted ORB may be able to automatically optimizemacro-level efficiency
Vanderbilt University 193
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
CORBA Implementations
� Many ORBs are now available
– Orbix2000 and ORBacus from IONA– VisiBroker from Borland– BEA Web Logic Enterprise– Component Broker from IBM– e*ORB from PrismTech and ORB Express from OIS– Open-source ORBs ! TAO, JacORB, omniORB, and MICO
� In theory, CORBA facilitates vendor-independent andplatform-independent application collaboration
– In practice, heterogeneous ORB interoperability and portabilitystill an issue...
Vanderbilt University 194
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
CORBA Services� Other OMG documents (e.g., COSS) specify higher level services
– Naming service
� Mapping of convenient object names to object references– Event service
� Enables decoupled, asynchronous communication betweenobjects
– Lifecycle service
� Enables flexible creation, copy, move, and deletion operationsvia factories
� Other CORBA services include transactions, trading, relationship,security, concurrency, property, A/V streaming, etc.
Vanderbilt University 195
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Summary of CORBA Features
� CORBA specifies the following functions to support an ObjectRequest Broker (ORB)
– Interface Definition Language (IDL)– A mapping from IDL onto C++, Java, C, COBOL, etc.– A Static Invocation Interface, used to compose operation requests
via proxies– A Dynamic Invocation Interface, used to compose operation
requests at run-time– Interface and Implementation Repositories containing meta-data
queried at run-time– The Portable Object Adapter (POA), allows service programmers
to interface their code with an ORB
Vanderbilt University 196
CORBA Tutorial Douglas C. Schmidt & Bala Natarajan
Concluding Remarks
� Additional information about CORBA is available on-line at thefollowing WWW URLs
– Doug Schmidt’s CORBA page
� www.cs.wustl.edu/�schmidt/corba.html– OMG’s WWW Page
� www.omg.org/corba/– CETUS CORBA Page
� www.cetus-links.org/oo corba.html
Vanderbilt University 197