PGC
PGC
PGC
January 2009
Tuxedo Programming an Oracle Tuxedo ATMI Application Using C, 10g Release 3 (10.3) Copyright 1996, 2009, Oracle and/or its affiliates. All rights reserved. This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this software or related documentation is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable: U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065. This software is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications which may create a risk of personal injury. If you use this software in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe use of this software. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software in dangerous applications. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. This software and documentation may provide access to or information on content, products and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services.
Contents
2. Programming Environment
Updating the UBBCONFIG Configuration File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1 Setting Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5 Including the Required Header Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9 Starting and Stopping the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
iii
Setting Environment Variables for a VIEW Typed Buffer . . . . . . . . . . . . . . . . . . 3-18 Creating a View Description File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-19 Executing the VIEW Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-22 Using an FML Typed Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-23 Setting Environment Variables for an FML Typed Buffer . . . . . . . . . . . . . . . . . . 3-23 Creating a Field Table File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-24 Creating an FML Header File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-25 Using an XML Typed Buffer and the Apache Xerces C++ Parser . . . . . . . . . . . . . . . 3-26 About the XML Typed Buffer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-27 About the Apache Xerces C++ Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-28 XML Parser Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-28 XML Parser Support for ICU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-29 XML Parser Sample Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-29 Xerces Schema Sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-29 Converting XML Data To and From FML/FML32 Buffers . . . . . . . . . . . . . . . . . 3-29 Using On-Demand Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-30 Using Automatic Conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-31 Mapping XML To and From FML/FML32 Field Types . . . . . . . . . . . . . . . . 3-34 Conversion Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-38 Using an MBSTRING Typed Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-40 Multibyte Character Encoding Control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-42 Enabling MBSTRING to be Self-describing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-46 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-46 Safe/Unsafe Encoding Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-46 Multibyte Character Support Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-47 Multibyte Character Encoding Support for libiconv. . . . . . . . . . . . . . . . . . . . . . . 3-47 Customizing a Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-49 Defining Your Own Buffer Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-51
iv Programming an Oracle Tuxedo ATMI Application Using C
Coding Switch Element Routines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-59 Adding a New Buffer Type to tm_typesw . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-60 Compiling and Linking Your New tm_typesw . . . . . . . . . . . . . . . . . . . . . . . 3-61 Compiling and Linking Your New tm_typesw for a 16-bit Windows Platform . . 3-62 Data Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-63
4. Writing Clients
Joining an Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1 Using Features of the TPINIT Typed Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4 Client Naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4 Unsolicited Notification Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5 System Access Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7 Resource Manager Association . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7 Client Authentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7 Leaving the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8 Building Clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8 See Also. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10 Client Process Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10
5. Writing Servers
Oracle Tuxedo System main( ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1 System-Supplied Server and Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3 System-Supplied Server: AUTHSVR( ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3 System-Supplied Services: tpsvrinit( ) Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4 Receiving Command-line Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4 Opening a Resource Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5 System-Supplied Services: tpsvrdone( ) Function. . . . . . . . . . . . . . . . . . . . . . . . . . 5-7 Guidelines for Writing Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8
Programming an Oracle Tuxedo ATMI Application Using C v
Defining a Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9 Example: Checking the Buffer Type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13 Example: Checking the Priority of the Service Request. . . . . . . . . . . . . . . . . . . . 5-14 Terminating a Service Routine. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16 Sending Replies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16 Invalidating Descriptors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-23 Forwarding Requests. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-24 Advertising and Unadvertising Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-28 Advertising Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-28 Unadvertising Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-29 Example: Dynamic Advertising and Unadvertising of a Service . . . . . . . . . . . . . 5-29 Building Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-30 See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-32 Using a C++ Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-32 Declaring Service Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-32 Using Constructors and Destructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-33
vi
Example: Sending an Asynchronous Message with TPNOTRAN | TPNOREPLY 6-13 Example: Sending Asynchronous Requests . . . . . . . . . . . . . . . . . . . . . . . . . . 6-14 Getting an Asynchronous Reply . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-15 Setting and Getting Message Priorities. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16 Setting a Message Priority. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16 Getting a Message Priority . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-18
Programming Interface for the EventBroker . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4 Defining the Unsolicited Message Handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-5 Sending Unsolicited Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-5 Broadcasting Messages by Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-6 Broadcasting Messages by Identifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7 Checking for Unsolicited Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-8 Subscribing to Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-8 Notification via Unsolicited Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-10 Notification via Service Call or Reliable Queue . . . . . . . . . . . . . . . . . . . . . . 8-10 Unsubscribing from Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-11 Posting Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-12 Example of Event Subscription . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-14
viii
Implicitly Defining a Transaction in a Service Routine . . . . . . . . . . . . . . . . . . . . 9-15 Defining Global Transactions for an XA-Compliant Server Group. . . . . . . . . . . . . . . 9-16 Testing Whether a Transaction Has Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-16 See Also. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-18
ix
How Multithreading and Multicontexting Work in Application-Created Threads of an ATMI Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-18 Start-Up Phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-18 Work Phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-19 Completion Phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-19 See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-20 Design Considerations for a Multithreaded and Multicontexted ATMI Application . . 10-20 Environment Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-20 Design Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-21 Interoperability Restrictions for Workstation Clients . . . . . . . . . . . . . . . . . 10-23 Implementing a Multithreaded/ Multicontexted ATMI Application . . . . . . . . . . . . . 10-24 Preliminary Guidelines for Programming a Multithreaded/Multicontexted ATMI Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-24 Prerequisites for a Multithreaded ATMI Application . . . . . . . . . . . . . . . . . 10-25 General Multithreaded Programming Considerations . . . . . . . . . . . . . . . . . 10-25 Concurrency Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-25 Writing Code to Enable Multicontexting in an ATMI Client . . . . . . . . . . . . . . . 10-27 Context Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-27 Setting Up Multicontexting at Initialization . . . . . . . . . . . . . . . . . . . . . . . . 10-28 Implementing Security for a Multicontexted ATMI Client . . . . . . . . . . . . . 10-29 Synchronizing Threads Before an ATMI Client Termination . . . . . . . . . . . 10-29 Switching Contexts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-30 Handling Unsolicited Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-33 Coding Rules for Transactions in a Multithreaded/Multicontexted ATMI Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-33 Writing Code to Enable Server-Dispatched Multicontexting and Multithreading Threads in an ATMI Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-34
Context Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-34 Coding Rules for Server-Dispatched Threads in Multicontexted ATMI Server . . 10-34 Initializing and Terminating ATMI Servers and Server Threads . . . . . . . . . 10-35 See Also. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-36 Writing Code to Enable Multicontexting in Application-Created Threads of an ATMI Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-36 Creating Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-36 Associating Application Threads with a Context. . . . . . . . . . . . . . . . . . . . . 10-36 Associating Application Threads with an Existing Server-Dispatched Context . . 10-37 Sample Code for Associating Application Thread with an Existing Server-Dispatched Context in a Multicontexted Server . . . . . . . . . . . . 10-37 Associating Application Threads with Application-Created Context . . . . . 10-39 Sample Code for Associating Application Thread with Application-created server Context in a Multicontexted Server . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-40 Writing a Multithreaded ATMI Client. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-42 Coding Rules for a Multithreaded ATMI Client . . . . . . . . . . . . . . . . . . . . . 10-42 Initializing an ATMI Client to Multiple Contexts . . . . . . . . . . . . . . . . . . . . 10-43 Context State Changes for an ATMI Client Thread . . . . . . . . . . . . . . . . . . . 10-44 Getting Replies in a Multithreaded Environment. . . . . . . . . . . . . . . . . . . . . 10-45 Using Environment Variables in a Multithreaded and/or Multicontexted Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-46 Using Per-context Functions and Data Structures in a Multithreaded ATMI Client. . . 10-48 Using Per-process Functions and Data Structures in a Multithreaded ATMI Client. . . 10-50 Using Per-thread Functions and Data Structures in a Multithreaded ATMI Client10-51
xi
Sample Code for a Multithreaded ATMI Client . . . . . . . . . . . . . . . . . . . . . . . . . 10-51 Writing a Multithreaded ATMI Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-54 Compiling Code for a Multithreaded/Multicontexted ATMI Application . . . . . 10-54 Testing a Multithreaded/Multicontexted ATMI Application. . . . . . . . . . . . . . . . . . . 10-55 Testing Recommendations for a Multithreaded/Multicontexted ATMI Application . . 10-55 Troubleshooting a Multithreaded/Multicontexted ATMI Application . . . . . . . . 10-55 Improper Use of the TPMULTICONTEXTS Flag to tpinit( ) . . . . . . . . . . . 10-55 Calls to tpinit( ) Without TPMULTICONTEXTS . . . . . . . . . . . . . . . . . . . . 10-55 Insufficient Thread Stack Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-56 Error Handling for a Multithreaded/Multicontexted ATMI Application . . . . . . 10-56
xii
Permission Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-16 Protocol Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-17 Queuing Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-18 Release Compatibility Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-19 Resource Manager Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-20 Timeout Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-21 Transaction Errors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-22 Typed Buffer Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-23 Application Errors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-23 Handling Errors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-23 Transaction Considerations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-28 Communication Etiquette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-29 Transaction Errors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-31 Non-fatal Transaction Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-31 Fatal Transaction Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-32 Heuristic Decision Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-33 Transaction Timeouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-34 Effect on the tpcommit() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-34 Effect on the TPNOTRAN Flag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-34 tpreturn( ) and tpforward( ) Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-35 tpterm( ) Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-36 Resource Managers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-37 Sample Transaction Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-38 Called Service in Same Transaction as Caller. . . . . . . . . . . . . . . . . . . . . . . . . . . 11-38 Called Service in Different Transaction with AUTOTRAN Set . . . . . . . . . . . . . 11-38 Called Service That Starts a New Explicit Transaction. . . . . . . . . . . . . . . . . . . . 11-39 Oracle TUXEDO System-supplied Subroutines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-41 Central Event Log. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-41
Programming an Oracle Tuxedo ATMI Application Using C xiii
Log Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-42 Log Entry Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-42 Writing to the Event Log. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-43 Debugging Application Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-44 Debugging Application Processes on UNIX Platforms . . . . . . . . . . . . . . . . . . . 11-44 Debugging Application Processes on Windows 2003 Platforms . . . . . . . . . . . . 11-45 Comprehensive Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-46
xiv
CHAPTER
This topic includes the following sections: Oracle Tuxedo Distributed Application Programming Communication Paradigms Oracle Tuxedo Clients Oracle Tuxedo Servers Oracle Tuxedo API: ATMI
1-1
The task of checking an account balance, for example, can be performed simply by logging on and selecting an option from a menu. Behind the scenes, the local software module communicates with the remote software module using special application programming interface (API) functions. The Oracle Tuxedo distributed application programming environment provides the API functions necessary to enable secure, reliable communication between the distributed software modules. This API is referred to as the Application-to-Transaction Monitor Interface (ATMI). The ATMI enables you to: Send and receive messages between clients and servers, possibly across a network of heterogeneous machines Establish and use client naming and security features Define and manage transactions in which data may be stored in several locations Generically open and close a resource manager such as a Database Management System (DBMS) Manage the flow of service requests and the availability of servers to process them
Communication Paradigms
The following table describes the Oracle Tuxedo ATMI communication paradigms available to application developers.
1-2
C o m mu ni c a ti o n P ar a dig m s
Description
Request/response communication enables one software module to send a request to a second software module and wait for a response. Can be synchronous (processing waits until the requester receives the response) or asynchronous (processing continues while the requester waits for the response). This mode is also referred to as client/server interaction. The first software module assumes the role of the client; the second, of the server. Refer to Writing Request/Response Clients and Servers on page 6-1 for more information on this paradigm.
Conversational communication
Conversational communication is similar to request/response communication, except that multiple requests and/or responses need to take place before the conversation is terminated. With conversational communication, both the client and the server maintain state information until the conversation is disconnected. The application protocol that you are using governs how messages are communicated between the client and server. Conversational communication is commonly used to buffer portions of a lengthy response from a server to a client. Refer to Writing Conversational Clients and Servers on page 7-1 for more information on this paradigm.
1-3
Description
Application queue-based communication supports deferred or time-independent communication, enabling a client and server to communicate using an application queue. The Oracle Tuxedo/Q facility allows messages to be queued to persistent storage (disk) or to non-persistent storage (memory) for later processing or retrieval. For example, application queue-based communication is useful for enqueuing requests when a system goes offline for maintenance, or for buffering communications if the client and server systems are operating at different speeds. Refer to Using the ATMI /Q Component for more information on the /Q facility.
Event-based communication
Event-based communication allows a client or server to notify a client when a specific situation (event) occurs. Events are reported in one of two ways: Unsolicited events are unexpected situations that are reported by clients and/or servers directly to clients. Brokered events are unexpected situations or predictable occurrences with unpredictable timeframes that are reported by servers to clients indirectly, through an anonymous broker program that receives and distributes messages.
Event-based communication is based on the Oracle Tuxedo EventBroker facility. Refer to Writing Event-based Clients and Servers on page 8-1 for more information on this paradigm.
1-4
The client calls the ATMI termination routine to leave the application and notify the Oracle Tuxedo system that it (the client) no longer needs to be tracked. Consequently, Oracle Tuxedo application resources are made available for other operations. The operation of a basic client process can be summarized by the pseudo-code shown in the following listing. Listing 1-1 Pseudo-code for a Request/Response Client
main() { allocate a TPINIT buffer place initial client identification in buffer enroll as a client of the BEA Tuxedo application allocate buffer do while true { place user input in buffer send service request receive reply pass reply to the user } leave application }
Most of the actions described in the above listing are implemented with ATMI functions. Othersplacing the user input in a buffer and passing the reply to the userare implemented with C language functions. During the allocate buffer phase, the client program allocates a memory area, called a typed buffer, from the Oracle Tuxedo run-time system. A typed buffer is simply a memory buffer with an associated format, for example, a C structure. An ATMI client may send and receive any number of service requests before leaving the application. The client may send these requests as a series of request/response calls or, if it is important to carry state information from one call to the next, by establishing a connection to a conversational server. In both cases, the logic in the client program is similar, but different ATMI functions are required for these two approaches.
1-5
Before you can execute an ATMI client, you must run the buildclient command to compile it and link it with the Oracle Tuxedo ATMI and required libraries. Refer to Writing Clients on page 4-1 for information on the buildclient command.
1-6
After initialization, an ATMI server allocates a buffer, waits until a request message is delivered to its message queue, dequeues the request, and dispatches it to a service subroutine for processing. If a reply is required, the reply is considered part of request processing. The conversational paradigm is somewhat different from request/response, as illustrated by the pseudo-code in the following figure.
1-7
The Oracle Tuxedo system-supplied main() process contains the code needed to enroll a process as an ATMI server, advertise services, allocate buffers, and dequeue requests. ATMI functions are used in service subroutines that process requests. When you are ready to compile and test your service subroutines, you must link edit them with the server main() and generate an executable server. To do so, run the buildserver command.
Servers as Requesters
If a client requests several services, or several iterations of the same service, a subset of the services might be transferred to another server for execution. In this case, the server assumes the role of a client, or requester. Both clients and servers can be requesters; a client, however, can only be a requester. This coding model is easily accomplished using the Oracle Tuxedo ATMI functions. Note: A request/response server can also forward a request to another server. In this case, the server does not assume the role of client (requester) because the reply is expected by the original client, not by the server forwarding the request.
under the control of the Oracle Tuxedo system transaction monitor, including all the associated resources you need. The ATMI is a reasonably compact set of functions used to open and close resources, begin and end transactions, allocate and free buffers, and support communication between clients and servers. The following table summarizes the ATMI functions. Each function is described in the Oracle Tuxedo ATMI C Function Reference. Table 1-2 Using the ATMI Function For a Task Related to . . .
Buffer management
To . . .
Create a message buffer Resize a message buffer Get a message type and subtype Free a message buffer Check whether authentication is required Join an application Leave an application Retrieve an identifier for the current threads context Set the current threads context in a multicontexted process
tpfree()
Client membership
tpchkauth()
tpinit() tpterm()
tpgetctxt(3c)
tpsetctxt(3c)
1-9
To . . .
Initialize a server Terminate a server Initialize an individual server thread Termination code for an individual server thread End a service function Forward a request Advertise a service name Unadvertise a service name Get the priority of the last request Set the priority of the next request Initiate a synchronous request/response to a service Initiate an asynchronous request Receive an asynchronous response Cancel an asynchronous request
tpsvrthrdone()
tpreturn() tpforward()
tpsprio()
Request/response communications
tpcall()
Writing Servers on page 5-1 Writing Request/Response Clients and Servers on page 6-1
tpacall()
tpgetrply()
tpcancel()
1-10
To . . .
Begin a conversation with a service Abnormally terminate a conversation Send a message in a conversation Receive a message in a conversation Enqueue a message to a message queue Dequeue a message from a message queue Send an unsolicited message to a client Send messages to several clients Set unsolicited message call-back Check the arrival of unsolicited messages Post an event message Subscribe to event messages Unsubscribe to event messages
tpdiscon()
tpsend()
tprecv()
Reliable queuing
tpenqueue(3c)
tpdequeue(3c)
Event-based communications
tpnotify()
tpbroadcast()
tpsetunsol()
tpchkunsol()
tppost() tpsubscribe()
tpunsubscribe()
1-11
To . . .
Begin a transaction Commit the current transaction Roll back the current transaction Check whether in transaction mode Suspend the current transaction Resume a transaction Open a resource manager Close a resource manager Get blocktime value Set blocktime value in seconds
tpabort()
tpgetlev()
tpsuspend()
tpresume()
1-12
To . . .
Open a key handle for digital signature generation, message encryption, or message decryption Get information associated with a key handle Set optional attributes associated with a key handle Close a previously opened handle Mark a typed message buffer for generation of a digital signature Mark a typed message buffer for generation of an encryption envelope Access the digital signature and recipient information associated with a typed message buffer Convert a typed message buffer into an exportable, machine-independent (externalized) string representation Convert an externalized string representation back into a typed message buffer
tpkey_getinfo(3c)
tpkey_setinfo(3c)
tpkey_close(3c)
tpsign(3c)
tpseal(3c)
tpenvelope(3c)
tpexport(3c)
tpimport(3c)
1-13
1-14
CHAPTER
Programming Environment
This topic includes the following sections: Updating the UBBCONFIG Configuration File Setting Environment Variables Including the Required Header Files Starting and Stopping the Application
2-1
Set the UID and GID parameters so that you are the owner of the configuration. Review the documentation. The configuration file is described in UBBCONFIG(5) in the File Formats, Data Descriptions, MIBs, and System Processes Reference. The following table summarizes the UBBCONFIG configuration file parameters that affect the programming environment. Parameters are listed by functional category. Table 2-1 Programming-related UBBCONFIG Parameters by Functional Category Functional Category
Global resource limits
Parameter
MAXSERVERS
Section
RESOURCES
Description
Specifies the maximum number of servers in the configuration. When setting this value, you need to consider the MAX values for all servers. Specifies the maximum total number of services in the configuration. List of types and subtypes of data buffers for which the specified routing entry is valid. Sets the minimum encryption level that a process accepts. Sets the maximum encryption level that a process accepts.
MAXSERVICES
RESOURCES
Data-dependent routing
BUFTYPE
ROUTING
Link-level encryption
MINENCRYPTBITS
NETWORK
MAXENCRYPTBITS
NETWORK
2-2
Table 2-1 Programming-related UBBCONFIG Parameters by Functional Category (Continued) Functional Category
Load balancing
Parameter
LDBAL
Section
RESOURCES
Description
Flag for specifying whether or not load balancing is enabled. If enabled, the Oracle Tuxedo system attempts to balance requests across the network. Numeric value that is added to the load factor of services that are remote from the invoking client, providing a bias for choosing a local server over a remote server. Load balancing must be enabled (that is, LDBAL must be set to Y). Relative load factor associated with a service instance. The default is 50. Specifies the name of an application authentication service that is invoked by the system for each client joining the system. Specifies the type of application security to be enforced.
NETLOAD
MACHINES
LOAD
SERVICES
Security
AUTHSVC
RESOURCES
SECURITY
RESOURCES
2-3
Table 2-1 Programming-related UBBCONFIG Parameters by Functional Category (Continued) Functional Category
Conversational communication
Parameter
MAXCONV
Section
RESOURCES
Description
Sets the maximum number of simultaneous conversations for a single machine. You can specify a value between 0 and 32,767. The default is 64 if any conversational servers are defined in the SERVERS section; otherwise, the default is 1. The specified value can be overriden for each machine in the MACHINES section. Specifies whether or not conversational communication is supported. If this parameter is set to N or unspecified, a tpconnect() call to a service fails. Specifies the minimum and maximum number of occurrences of the server to be started by tmboot(1). If not specified, MIN defaults to 1 and MAX defaults to MIN. The same parameters are available for use with request/response servers. However, conversational servers are automatically spawned as needed. So if you set MIN=1 and MAX=10, for example, tmboot starts one server initially. When a tpconnect() call is made to a service offered by that server, the system starts a second copy of a server. As each copy is called, a new one is spawned, up to a limit of 10.
CONV
SERVERS
MIN/MAX
SERVERS
2-4
S e t ti ng En v i r o n m e nt V ar i a bl e s
Table 2-1 Programming-related UBBCONFIG Parameters by Functional Category (Continued) Functional Category
Transaction management
Parameter
AUTOTRAN
Section
SERVICES
Description
Controls whether a service routine is placed in transaction mode. If you set this parameter to Y, a transaction in the service subroutine is automatically started whenever a request message is received from another process.
MAXTRANTIME
RESOURCES
Specifies in seconds the maximum timeout allowed for transactions started in or received by this Oracle Tuxedo application.
Specifies the maximum number of concurrently dispatched threads that each server process may spawn. Specifies the number of server dispatch threads started on initial server boot.
Multithreaded servers
MAXDISPATCHTHREADS
SERVERS
MINDISPATCHTHREADS
SERVERS
The configuration file is an operating system text file. To make it usable by the system, you must execute the tmloadcf(1) command to convert the file to a binary file.
See Also
Setting Up an Oracle Tuxedo Application
UBBCONFIG(5) in the File Formats, Data Descriptions, MIBs, and System Processes
Reference
For the client and server routines in your application, you can update existing environment variables or create new ones. The following table summarizes the most commonly used environment variables. The variables are listed by functional category. Table 2-2 Programming-related Environment Variables by Functional Category Functional Category
Global
Environment Variable
TUXDIR
Defines the . . .
Location of the Oracle Tuxedo system binary files. Location of the Oracle Tuxedo configuration file. Command that invokes the C compiler. Default is cc. Link edit flags to be passed to the C compiler. Link edit flags are optional. Level of compression (between 1 and 9).
Used by . . .
Oracle Tuxedo application programs.
Configuration
TUXCONFIG
Compilation
CC
CFLAGS
Data compression
TMCMPPRFM
Oracle Tuxedo application programs that perform data compression. Oracle Tuxedo application programs that perform load balancing.
Load balancing
TMNETLOAD
Numeric value that is added to the load value for remote queues, making the remote queues appear to have more work than they actually do. As a result, even if load balancing is enabled, local requests are sent to local queues more often than to remote queues.
2-6
S e t ti ng En v i r o n m e nt V ar i a bl e s
Table 2-2 Programming-related Environment Variables by Functional Category (Continued) Functional Category
Buffer management
Environment Variable
FIELDTBLS or FIELDTBLS32
Defines the . . .
Comma-separated list of field table filenames for FML and FML32 typed buffers, respectively. Required only for FML and VIEW types. Colon-separated list of directories to be searched for the field table files for FML and FML32, respectively. For Windows 2003, a semicolon-separated list is used. Comma-separated list of allowable filenames for VIEW and VIEW32 typed buffers, respectively. Colon-separated list of directories to be searched for VIEW and VIEW32 files, respectively. For Windows 2003, a semicolon-separated list is used.
Used by . . .
FML and FML32 typed buffers and FML VIEWs
FLDTBLDIR or FLDTBLDIR32
VIEWFILES or VIEWFILES32
VIEWDIR or VIEWDIR32
2-7
Table 2-2 Programming-related Environment Variables by Functional Category (Continued) Functional Category
Code-set encoding conversion
Environment Variable
TPMBENC
Defines the . . .
Code-set encoding name to be included in an MBSTRING typed buffer or in an FLD_MBSTRING field in an FML32 typed buffer. Non-Null or Null value that determines whether the encoding of the MBSTRING data or the FLD_MBSTRING field data in an FML32 typed buffer is converted when received by the destination process. Flag to turn caching on/off for externally referenced files (DTD, Schemas, and entity reference.) Absolute path of the directory to store the cached files. If the URLENTITYCACHING flag is turned on and no path is specified, the current working directory is used to store the cached files (provided appropriate permissions are set.). Absolute path to a file containing pairs of XercesDOMParser class attributes and settings.
Used by . . .
MBSTRING and FML32 typed buffers
TPMBACONV
URLENTITYCACHING
URLENTITYCACHEDIR
TPXARSFILE
Oracle Tuxedo application programs that automatically parse XML data to and from FML/FML32 data.
2-8
If operating in a UNIX environment, add $TUXDIR/bin to your environment PATH to ensure that your application can locate the executables for the Oracle Tuxedo system commands. For more information on setting up the environment, see Setting Up an Oracle Tuxedo Application.
See Also
Setting Up an Oracle Tuxedo Application Setting Up Your Environment for FML and VIEWS in Programming Oracle Tuxedo ATMI Applications Using FML
2-9
See Also
tmboot(1) and tmshutdown(1) in the Oracle Tuxedo Command Reference
2-10
CHAPTER
This topic includes the following sections: Overview of Typed Buffers Allocating a Typed Buffer Putting Data in a Buffer Resizing a Typed Buffer Checking for Buffer Type Freeing a Typed Buffer Using a VIEW Typed Buffer Using an FML Typed Buffer Using an XML Typed Buffer and the Apache Xerces C++ Parser Using an MBSTRING Typed Buffer Customizing a Buffer
3-1
associated with it. Typed buffers make up one of the fundamental features of the distributed programming environment supported by the Oracle Tuxedo system. Why typed? In a distributed environment, an application may be installed on heterogeneous systems that communicate across multiple networks using different protocols. Different types of buffers require different routines to initialize, send and receive messages, and encode and decode data. Each buffer is designated as a specific type so that the appropriate routines can be called automatically without programmer intervention. The following table lists the typed buffers supported by the Oracle Tuxedo system and indicates whether or not: The buffer is self-describing; in other words, the buffer data type and length can be determined simply by (a) knowing the type and subtype, and (b) looking at the data. The buffer requires a subtype. The system supports data-dependent routing for the typed buffer. The system supports encoding and decoding for the typed buffer. If any routing functions are required, the application programmer must provide them as part of the application.
3-2
Subtype
DataDependent Routing
No
Encoding/ Decoding
No
CARRAY
Undefined array of characters, any of which can be NULL. This typed buffer is used to handle the data opaquely, as the Oracle Tuxedo system does not interpret the semantics of the array. Because a CARRAY is not self-describing, the length must always be provided during transmission. Encoding and decoding are not supported for messages sent between machines because the bytes are not interpreted by the system. Proprietary Oracle Tuxedo system type of self-describing buffer in which each data field carries its own identifier, an occurrence number, and possibly a length indicator. Because all data manipulation is done via FML function calls rather than native C statements, the FML buffer offers data-independence and greater flexibility at the expense of some processing overhead. The FML buffer uses 16 bits for field identifiers and lengths of fields. For more information about the FML buffer, see Using an FML Typed Buffer on page 3-23.
No
Yes
No
Yes
Yes
3-3
Subtype
DataDependent Routing
Yes
Encoding/ Decoding
Yes
FML32
Equivalent to FML but uses 32 bits for field identifiers and lengths of fields, which allows for larger and more fields and, consequently, larger overall buffers. For more information about the FML32 buffer, see Using an FML Typed Buffer on page 3-23.
No
STRING
Array of characters that terminates with a NULL character. The STRING buffer is self-describing, so the Oracle Tuxedo system can convert data automatically when data is exchanged by machines with different character sets. C structure defined by the application. VIEW types must have subtypes that designate individual data structures. A view description file, in which the fields and types that appear in the data structure are defined, must be available to client and server processes that use a data structure described in a VIEW typed buffer. Encoding and decoding are performed automatically if the buffer is passed between machines of different types. VIEW does not support mbstring type buffers. For more information about the VIEW buffer, see Using a VIEW Typed Buffer on page 3-17.
Yes
No
No
No
VIEW
No
Yes
Yes
Yes
3-4
Subtype
DataDependent Routing
Yes
Encoding/ Decoding
Yes
VIEW32
Equivalent to VIEW but uses 32 bits for length and count fields, which allows for larger and more fields and, consequently, larger overall buffers. VIEW32 supports mbstring type buffers and treat mbstring data in the same manner as carray. For more information about the VIEW32 buffer, see Using a VIEW Typed Buffer on page 3-17.
Yes
X_C_TYPE X_COMMON
Equivalent to VIEW. Equivalent to VIEW, but used for compatibility between COBOL and C programs. Field types should be limited to short, long, and string.
No No
Yes Yes
Yes Yes
Yes Yes
3-5
Subtype
DataDependent Routing
Yes
Encoding/ Decoding
No
XML
An XML document that consists of: Text, in the form of a sequence of encoded characters A description of the logical structure of the document and information about that structure
No
The routing of an XML document can be based on element content, or on element type and an attribute value. The XML parser, such as the Apache Xerces C++ Version 2.5 parser available in Oracle Tuxedo 9.x, determines the character encoding being used; if the encoding differs from the native character sets (US-ASCII or EBCDIC) used in the Oracle Tuxedo configuration files (UBBCONFIG(5) and DMCONFIG(5)), the element and attribute names are converted to US-ASCII or EBCDIC. For more information about the XML buffer and the Xerces C++ parser, see Using an XML Typed Buffer and the Apache Xerces C++ Parser on page 3-26. X_OCTET MBSTRING Equivalent to CARRAY. Character array for multibyte charactersavailable in Oracle Tuxedo 8.1. For more information about the MBSTRING buffer, see Using an MBSTRING Typed Buffer on page 3-40. No No No No No No No No
3-6
All buffer types are defined in a file called tmtypesw.c in the $TUXDIR/lib directory. Only buffer types defined in tmtypesw.c are known to your client and server programs. You can edit the tmtypesw.c file to add or remove buffer types. In addition, you can use the BUFTYPE parameter (in UBBCONFIG) to restrict the types and subtypes that can be processed by a given service. The tmtypesw.c file is used to build a shared object or dynamic link library. This object is dynamically loaded by both Oracle Tuxedo administrative servers, and application clients and servers.
See Also
Using a VIEW Typed Buffer on page 3-17 Using an FML Typed Buffer on page 3-23 Using an XML Typed Buffer and the Apache Xerces C++ Parser on page 3-26 Using an MBSTRING Typed Buffer on page 3-40
tuxtypes(5) in Oracle Tuxedo File Formats, Data Descriptions, MIBs, and System Processes Reference UBBCONFIG(5) in Oracle Tuxedo File Formats, Data Descriptions, MIBs, and System Processes Reference
3-7
Description
Pointer to a valid typed buffer. Pointer to the name of a subtype being specified (in the view description file) for a VIEW, VIEW32, or X_COMMON typed buffer. In the cases where a subtype is not relevant, assign the NULL value to this argument.
size
Size of the buffer. The Oracle Tuxedo system automatically associates a default buffer size with all typed buffers except CARRAY, X_OCTET, and XML, which require that you specify a size, so that the end of the buffer can be identified. For all typed buffers other than CARRAY, X_OCTET, and XML, if you specify a value of zero, the Oracle Tuxedo system uses the default associated with that typed buffer. If you specify a size, the Oracle Tuxedo system assigns the larger of the following two values: the specified size or the default size associated with that typed buffer. The default size for all typed buffers other than STRING, CARRAY, X_OCTET, and XML is 1024 bytes. The default size for STRING typed buffers is 512 bytes. There is no default value for CARRAY, X_OCTET, and XML; for these typed buffers you must specify a size value greater than zero. If you do not specify a size, the argument defaults to 0. As a result, the tpalloc() function returns a NULL pointer and sets tperrno to TPEINVAL.
The VIEW, VIEW32, X_C_TYPE, and X_COMMON typed buffers require the subtype argument, as shown in the following example. Listing 3-1 Allocating a VIEW Typed Buffer
struct aud *audv; /* pointer to aud view structure */ . . . audv = (struct aud *) tpalloc("VIEW", "aud", sizeof(struct aud)); . . .
3-8
The following example shows how to allocate an FML typed buffer. Note that a value of NULL is assigned to the subtype argument. Listing 3-2 Allocating an FML Typed Buffer
FBFR *fbfr; /* pointer to an FML buffer structure */ . . . fbfr = (FBFR *)tpalloc("FML", NULL, Fneeded(f, v)) . . .
The following example shows how to allocate a CARRAY typed buffer, which requires that a size value be specified. Listing 3-3 Allocating a CARRAY Typed Buffer
char *cptr; long casize; . . . casize = 1024; cptr = tpalloc("CARRAY", NULL, casize); . . .
Upon success, the tpalloc() function returns a pointer of type char. For types other than STRING and CARRAY, you should cast the pointer to the proper C structure or FML pointer. If the tpalloc() function encounters an error, it returns the NULL pointer. The following list provides examples of error conditions: Failure to specify a size value for a CARRAY, X_OCTET, or XML typed buffer Failure to specify a type (or subtype in the case of VIEW) Specifying a type that is not known to the system Failure to join the application before attempting allocation
3-9
For a complete list of error codes and explanations of them, refer to tpalloc(3c) in the Oracle Tuxedo ATMI C Function Reference. The following listing shows how to allocate a STRING typed buffer. In this example, the associated default size is used as the value of the size argument to tpalloc(). Listing 3-4 Allocating a STRING Buffer
char *cptr; . . . cptr = tpalloc("STRING", NULL, 0); . . .
See Also
Putting Data in a Buffer on page 3-10 Resizing a Typed Buffer on page 3-12
tpalloc(3c) in Oracle Tuxedo ATMI C Function Reference
3-10
P ut ti ng D at a i n a B u f fe r
/* Prepare aud structure */ audv->b_id = q_branchid; audv->balance = 0.0; (void)strcpy(audv->ermsg, ""); ...
When audit is used to query the total bank balance, the total balance at each site is obtained by a call to the BAL server. To run a query on each site, a representative branch identifier is specified. Representative branch identifiers are stored in an array named sitelist[]. Hence, the aud structure is set up as shown in the following example. Listing 3-6 Placing Data in a Message Buffer - Example 2
... /* Prepare aud structure */ audv->b_id = sitelist[i];/* routing done on this field */ audv->balance = 0.0; (void)strcpy(audv->ermsg, ""); ...
The process of putting data into a STRING buffer is illustrated in the listing titled Resizing a Buffer on page 3-13.
See Also
Allocating a Typed Buffer on page 3-7 Resizing a Typed Buffer on page 3-12
tpalloc(3c) in Oracle Tuxedo ATMI C Function Reference
3-11
The following table describes the arguments to the tprealloc() function. Table 3-3 tprealloc() Function Arguments Argument
ptr
Description
Pointer to the buffer that is to be resized. This pointer must have been allocated originally by a call to tpalloc(). If it was not, the call fails and tperrno(5) is set to TPEINVAL to signify that invalid arguments have been passed to the function. Long integer specifying the new size of the buffer.
size
The pointer returned by tprealloc() points to a buffer of the same type as the original buffer. You must use the returned pointer to reference the resized buffer because the location of the buffer may have changed. When you call the tprealloc() function to increase the size of the buffer, the Oracle Tuxedo system makes new space available to the buffer. When you call the tprealloc() function to make a buffer smaller, the system does not actually resize the buffer; instead, it renders the space beyond the specified size unusable. The actual content of the typed buffer remains unchanged. If you want to free up unused space, it is recommended that you copy the data into a buffer of the desired size and then free the larger buffer. On error, the tprealloc() function returns the NULL pointer and sets tperrno to an appropriate value. Refer to tpalloc(3c) in Oracle Tuxedo ATMI C Function Reference for information on error codes. WARNING: If the tprealloc() function returns the NULL pointer, the contents of the buffer passed to it may have been altered and may be no longer valid. The following example shows how to reallocate space for a STRING buffer.
3-12
s2len = (long)strlen(instr)+1; /* determine its length */ if ((s2ptr = tprealloc(s1ptr, s2len)) == NULL) { fprintf(stderr, tprealloc failed for echo of: %s\n, instr); free s1ptr's buffer leave application exit(1); } (void)strcpy(s2ptr, instr); make communication call with buffer pointed to by s2ptr . . .
3-13
The following example (an expanded version of the previous example) shows how to check for occurrences of all possible error codes. Listing 3-8 Error Checking for tprealloc()
. . . if ((s2ptr=tprealloc(s1ptr, s2len)) == NULL) switch(tperrno) { case TPEINVAL: fprintf(stderr, "given invalid arguments\n"); fprintf(stderr, "will do tpalloc instead\n"); tpfree(s1ptr); if ((s2ptr=tpalloc("STRING", NULL, s2len)) == NULL) { fprintf(stderr, "tpalloc failed for echo of: %s\n", instr); leave application exit(1); } break; case TPEPROTO: fprintf(stderr, "tried to tprealloc before tpinit;\n"); fprintf(stderr, "program error; contact product support\n"); leave application exit(1); case TPESYSTEM: fprintf(stderr, "BEA Tuxedo error occurred; consult today's userlog file\n"); leave application exit(1); case TPEOS: fprintf(stderr, "Operating System error %d occurred\n",Uunixerr); leave application exit(1); default: fprintf(stderr,
3-14
See Also
Allocating a Typed Buffer on page 3-7 Putting Data in a Buffer on page 3-10
tprealloc(3c) in Oracle Tuxedo ATMI C Function Reference
The following table describes the arguments to the tptypes() function. Table 3-4 tptypes() Function Arguments Argument
ptr
Description
Pointer to a data buffer. This pointer must have been originally allocated by a call to tpalloc() or tprealloc(), it may not be NULL, and it must be cast as a character type; otherwise, the tptypes() function reports an invalid argument error. Pointer to the type of the data buffer. type is of character type. Pointer to the subtype of the data buffer, if one exists. subtype is of character type. For all types other than VIEW, VIEW32, X_C_TYPE, and X_COMMON, upon return the subtype parameter points to a character array containing the NULL string.
type subtype
Upon success, the tptypes() function returns the length of the buffer in the form of a long integer.
Programming an Oracle Tuxedo ATMI Application Using C 3-15
In the event of an error, tptypes() returns a value of -1 and sets tperrno(5) to the appropriate error code. For a list of these error codes, refer to the Introduction to the C Language Application-to-Transaction Monitor Interface and tpalloc(3c) in the Oracle Tuxedo ATMI C Function Reference. You can use the size value returned by tptypes() upon success to determine whether the default buffer size is large enough to hold your data, as shown in the following example. Listing 3-9 Getting Buffer Size
. . . iptr = (FBFR *)tpalloc("FML", NULL, 0); ilen = tptypes(iptr, NULL, NULL); . . . if (ilen < mydatasize) iptr=tprealloc(iptr, mydatasize);
See Also
Allocating a Typed Buffer on page 3-7
tptypes(3c) in Oracle Tuxedo ATMI C Function Reference
The tpfree() function takes only one argument, ptr, which is described in the following table.
3-16
Description
Pointer to a data buffer. This pointer must have been allocated originally by a call to tpalloc() or tprealloc(), it may not be NULL, and it must be cast as a character type; otherwise, the function returns without freeing anything or reporting an error condition.
When freeing an FML32 buffer using tpfree(), the routine recursively frees all embedded buffers to prevent memory leaks. In order to preserve the embedded buffers, you should assign the associated pointer to NULL before issuing the tpfree() routine. When ptr is NULL, no action occurs. The following example shows how to use the tpfree() function to free a buffer. Listing 3-10 Freeing a Buffer
struct aud *audv; /* pointer to aud view structure */ . . . audv = (struct aud *)tpalloc("VIEW", "aud", sizeof(struct aud)); . . . tpfree((char *)audv);
See Also
Allocating a Typed Buffer on page 3-7 Resizing a Typed Buffer on page 3-12
tpfree(3c) in Oracle Tuxedo ATMI C Function Reference
3-17
The reason for converting FML buffers into C structures and back again (and the purpose of the FML VIEW typed buffers) is that while FML buffers provide data-independence and convenience, they incur processing overhead because they must be manipulated using FML function calls. C structures, while not providing flexibility, offer the performance required for lengthy manipulations of buffer data. If you need to perform a significant amount of data manipulation, you can improve performance by transferring fielded buffer data to C structures, operating on the data using normal C functions, and then converting the data back to the FML buffer for storage or message transmission. For more information on the FML typed buffer and FML file conversion, refer to the Oracle Tuxedo ATMI FML Function Reference. To use VIEW typed buffers, you must perform the following steps: Set the appropriate environment variables. Describe each structure in view description files. Compile the view description files using viewc, the Oracle Tuxedo view compiler. Specify the resulting header file in the #include statement for your application program.
Description
Comma-separated list of field table filenames for FML or FML32 typed buffers. Required only for FML VIEW types. Colon-separated list of directories to search for the field table files for FML and FML32 typed buffers. For Microsoft Windows, use a semicolon-separated list. Required only for FML VIEW types. Comma-separated list of allowable filenames for VIEW or VIEW32 description files. Colon-separated list of directories to search for VIEW or VIEW32 files. For Microsoft Windows, use a semicolon-separated list.
3-18
count
flag
size
null
The following table describes the fields that must be specified in the view description file for each C structure. Table 3-7 View Description File Fields Field
type
Description
Data type of the field. Can be set to short, long, float, double, char, string, or carray. Note: mbstring data type is supported by the VIEW32 typed buffer only .
cname fbname
Name of the field as it appears in the C structure. If you will be using the FML-to-VIEW or VIEW-to-FML conversion functions, this field must be included to indicate the corresponding FML name. This field name must also appear in the FML field table file. This field is not required for FML-independent VIEWs. Number of times field occurs. Specifies any of the following optional flag settings:
Pchange the interpretation of the NULL value Sone-way mapping from fielded buffer to structure Fone-way mapping from structure to fielded buffer Nzero-way mapping Cgenerate additional field for associated count member (ACM) Lhold number of bytes transferred for STRING, CARRAY, and MBSTRING
count flag
Note: The view32 command automatically adds the L option flag for MBSTRING typed buffers
3-19
Description
For STRING and CARRAY buffer types, specifies the maximum length of the value. This field is ignored for all other buffer types. User-specified NULL value, or minus sign (-) to indicate the default value for a field. NULL values are used in VIEW typed buffers to indicate empty C structure members. The default NULL value for all numeric types is 0 (0.0 for dec_t). For character types, the default NULL value is \0. For STRING, CARRAY, and MBSTRING types, the default NULL value is . Constants used, by convention, as escape characters can also be used to specify a NULL value. The view compiler recognizes the following escape constants: \ddd (where d is an octal digit), \0, \n, \t, \v, \r, \f, \\, \, and \. You may enclose STRING, CARRAY, MBSTRING, and char NULL values in double or single quotes. The view compiler does not accept unescaped quotes within a user-specified NULL value. You can also specify the keyword NONE in the NULL field of a view member description, which means that there is no NULL value for the member. The maximum size of default values for string and character array members is 2660 characters. For more information, see Oracle Tuxedo ATMI FML Function Reference.
null
You can include a comment line by prefixing it with the # or $ character. Lines prefixed by a $ sign are included in the .h file. The following listing is an excerpt from an example view description file based on an FML buffer. In this case, the fbname field must be specified and match that which appears in the corresponding field table file. Note that the CARRAY1 field includes an occurrence count of 2 and sets the C flag to indicate that an additional count element should be created. In addition, the L flag is set to establish a length element that indicates the number of characters with which the application populates the CARRAY1 field. Listing 3-11 View Description File for FML VIEW
$ /* View structure */ VIEW MYVIEW #type cname fbname count flag size null
3-20
float double long short int dec_t char string carray END
1 1 1 1 1 1 1 1 2
CL
9,16 20 20
The following listing illustrates the same view description file for an independent VIEW. Listing 3-12 View Description File for an Independent View
$ /* View data structure */ VIEW MYVIEW #type float double long short int dec_t char string carray END cname float1 fbname count 1 1 1 1 1 1 1 1 2 flag CL size 9,16 20 20 null -
string1 carray1 -
Note that the format is similar to the FML-dependent view, except that the fbname and null fields are not relevant and are ignored by the viewc compiler. You must include a value (for example, a dash) as a placeholder in these fields.
3-21
Note: To compile a VIEW32 typed buffer, run the viewc32 command. For an independent VIEW, use the -n option on the command line, as follows:
viewc -n myview.v
The output of the viewc command includes: One or more COBOL COPY files; for example, MYVIEW.cbl Header file containing a structure definition that may be used by application programs Binary version of the source description file; for example, myview.V Note: On case-insensitive platforms (for example, Microsoft Windows), the extension used for the names of such files is vv; for example, myview.vv. The following listing provides an example of the header file created by viewc. Listing 3-13 Header File Created Using the VIEW Compiler
struct MYVIEW { float float1; double long short int dec_t char char double1; long1; short1; int1; dec1; char1; string1[20]; /* length array of carray1 */ /* count of carray1 */
3-22
U s i ng a n F ML T y pe d B u f fe r
char };
carray1[2][20];
The same header file is created for FML-dependent and independent VIEWs. In order to use a VIEW typed buffer in client programs or service subroutines, you must specify the header file in the application #include statements.
See Also
Using an FML Typed Buffer on page 3-23 Using an XML Typed Buffer and the Apache Xerces C++ Parser on page 3-26 Using an MBSTRING Typed Buffer on page 3-40
viewc, viewc32(1) in Oracle Tuxedo Command Reference
to C structures and vice versa. By using these functions, you can access and update data values without having to know how data is structured and stored. For more information on FML functions, see Oracle Tuxedo ATMI FML Function Reference.
3-23
Description
Comma-separated list of field table filenames for FML or FML32 typed buffers, respectively. Colon-separated list of directories to search for the field table files for FML and FML32, respectively. For Microsoft Windows, use a semicolon-separated list.
The following table describes the fields that must be specified in the FML field table file for each FML field. Table 3-9 Field Table File Fields Field
*base value
Description
Specifies a base for offsetting subsequent field numbers, providing an easy way to group and renumber sets of related fields. The *base option allows field numbers to be reused. For a 16-bit buffer, the base plus the relevant number must be greater than or equal to 100 and less than 8191. This field is optional. Note: The Oracle Tuxedo system reserves field numbers 1-100 and 6000-7000 for internal use. Field numbers 101-8191 are available for application-defined fields with FML; field numbers 101-33, 554, and 431, for FML32.
name
Identifier for the field. The value must be a string of up to 256 characters, consisting of alphanumeric and underscore characters only.
3-24
U s i ng a n F ML T y pe d B u f fe r
Description
Relative numeric value of the field. This value is added to the current base, if specified, to calculate the field number. Type of the field. This value can be any of the following: char, string, short, long, float, double, or carray. Reserved for future use. A dash (-) should be included as a placeholder. Optional comment.
type
flag comment
All fields are optional, and may be included more than once. The following example illustrates a field table file that may be used with the FML-dependent VIEW example. Listing 3-14 Field Table File for FML VIEW
# name FLOAT1 DOUBLE1 LONG1 SHORT1 INT1 DEC1 CHAR1 STRING1 CARRAY1 number 110 111 112 113 114 115 116 117 118 type float double long short long string char string carray flags comments -
3-25
For FML32 typed buffers, use the mkfldhdr32 command. The following listing shows the myview.flds.h header file that is created by the mkfldhdr command. Listing 3-15 myview.flds.h Header File
/* /* #define #define #define #define #define #define #define #define #define fname ----FLOAT1 DOUBLE1 LONG1 SHORT1 INT1 DEC1 CHAR1 STRING1 CARRAY1 fldid ----((FLDID)24686) ((FLDID)32879) ((FLDID)8304) ((FLDID)113) ((FLDID)8306) ((FLDID)41075) ((FLDID)16500) ((FLDID)41077) ((FLDID)49270) */ */ /* /* /* /* /* /* /* /* /* number: number: number: number: number: number: number: number: number: 110 111 112 113 114 115 116 117 118 type: type: type: type: type: type: type: type: type: float double long short long string char string carray */ */ */ */ */ */ */ */ */
Specify the new header file in the #include statement of your application. Once the header file is included, you can refer to fields by their symbolic names.
See Also
Using a VIEW Typed Buffer on page 3-17 Using an XML Typed Buffer and the Apache Xerces C++ Parser on page 3-26 Using an MBSTRING Typed Buffer on page 3-40
mkfldhdr, mkfldhdr32(1) in Oracle Tuxedo Command Reference
Using an XML Typed Buffer and the Apache Xerces C++ Parser
As XML continues to gain acceptance as a data standard, Oracle Tuxedo customers are increasingly using XML typed buffers in their applications. To assist customers in this effort, Oracle has integrated the Apache Xerces C++ Version 2.5 parser into the Oracle Tuxedo software distribution.
3-26 Programming an Oracle Tuxedo ATMI Application Using C
Using an XML Typed Buffer and the Apache Xerces C++ Parser
This section introduces the following topics: About the XML Typed Buffer About the Apache Xerces C++ Parser Converting XML Data To and From FML/FML32 Buffers
3-27
Attributes configured for routing must be included in an XML document. If an attribute is configured as a routing criteria but it is not included in the XML document, routing processing fails. The content of an element and the value of an attribute must conform to the syntax and semantics required for a routing field value. The user must also specify the type of the routing field value. XML supports only character data. If a range field is numeric, the content or value of that field is converted to a numeric value during routing processing.
Programmatically by using four ATMI functions that specify particular Xerces parser class methods:
getURLEntityCaching() setURLEntityCaching() getURLEntityCacheDir() setURLEntityCacheDir()
Note: These four methods are Oracle Tuxedo enhancements to the Apache Xerces-C++ parser. They are used exclusively in conjunction with the following two Xerces objects :
XercesDOMParser
3-28
Using an XML Typed Buffer and the Apache Xerces C++ Parser
SAXParser
See Also
getURLEntityCacheDir(3c), setURLEntityCacheDir(3c), getURLEntityCaching(3c), setURLEntityCaching(3c), Xerces API parser on-line documentation.
3-29
Automatic conversion For application administrators, automatic conversion of XML to and from FML/FML32 buffers features a new BUFTYPECONV parameter in the SERVICES section of the UBBCONFIG configuration file initiates conversion when the server is booted. For more information, see Using Automatic Conversion. Regardless of the method used for conversion, the FML/FML32 field types are mapped to XML in a particular manner. For information on conversion mapping, see Mapping XML To and From FML/FML32 Field Types. Note: XML to and from FML/FML32 conversion uses third-party libraries (for example, libticudata.so) that may be substantial in size. Increasing the size of shared libraries may cause running Tuxedo application processes (that directly or indirectly depend on those libraries) to consume increased amounts of memory which, in turn, can impact performance. XML to and from FML/FML32 conversion should not be used by a Tuxedo system process. For other known issues or limitations regarding conversion between XML and FML/FML32 buffers using the Xerces parser, see Conversion Limitations.
For a detailed description of these functions and their arguments, see Oracle Tuxedo ATMI C Function Reference.
3-30
Using an XML Typed Buffer and the Apache Xerces C++ Parser
Set the appropriate environment variables Determine the conversion ATMI function you want to use Use the rtag argument to specify the input/output XML root tag for the buffer type conversion in the function call (optional) Set the flag argument to select Xerces parser options (optional)
3-31
Automatic XML to FML/FML32 buffers conversion only takes action on input XML data. All other input buffers are not converted even if specified in BUFTYPECONV. XML, FML, and FML32 input/output service data is converted only if the service acts as a server. In other words, if a client or other service makes a request to the service using the BUFTYPECONV parameter. If a service using the BUFTYPECONV parameter acts as a client, conversion does not take place. For example, a service with the BUFTYPECONV parameter using tpcall() on another service. In /Q messaging mode, TMQFORWARD uses tpcall() to call a service. If the called service uses the BUFTYPECONV parameter, automatic conversion will take place. During automatic conversion, the input XML root element name cannot be saved, so the output XML root tag uses the default root tag <FML Type="FML"> or <FML Type="FML32">.
3-32
Using an XML Typed Buffer and the Apache Xerces C++ Parser
The TPXPARSFILE environment variable designates the fully qualified path to a text file that contains the XercesDOMParser class attribute settings you want to modify. Each attribute in the text file is written on a separate line in the following format:
<parser attribute>=<setting>
The <parser attribute> can be any or all of the 14 parser attributes in the following table, where (D) denotes the default setting. Note: For a detailed description of these attributes, see Xerces parser 2.5.0 documentation. Parser Attribute
CacheGrammarFromParse DoNameSpaces DoSchema ExternalSchemaLocation ExitOnFirstFatalError IncludeIgnorableWhiteSpace LoadGrammar NoNamespaceSchemaLocation StandardUriConformant UseCachedGrammarInParse UseScanner ValidationConstraintFatal ValidationScheme ValidationSchemaFullChecking
Setting
True or False (D) True or False (D) True or False (D) Fully qualified path to file_name.xsd True or False (D) True or False (D) Fully qualified name of validating file Fully qualified path to file_name.xsd True or False (D) True or False (D) WF, DG, SG, or IG (D) True or False (D) Val_Never, Val_Always, or Val_Auto (D) True or False (D)
The following listing is a sample input plain text file for the TPXPARSFILE environment variable.
3-33
3-34
Using an XML Typed Buffer and the Apache Xerces C++ Parser
Field Type
SHORT LONG CHAR FLOAT DOUBLE STRING
Conversion Mapping
The FLD_SHORT, FLD_LONG, FLD_CHAR, FLD_FLOAT, FLD_DOUBLE, and FLD_STRING fields are simple conversions to and from the XML string values. Formatting of type values will follow the style, where possible, that has been used in Ftypcvt().
Example
FML:AMOUNT=10.00 XML:<AMOUNT>10.00</AMOUNT>
CARRAY
During FLD_CARRAY field conversion, FML: BEA=TUXEDO XML:<BEA>54555845444F</BEA> the XML byte stream value is converted from two alphanumeric characters in XML to one byte value in Tuxedo. That is, each XML pair of characters represents a hex byte value. During conversion to XML, the FLD_PTR fieldname points to one of the following valid Tuxedo buffer types: STRING, MBSTRING, CARRAY, FML, FML32, and VIEW32 and ignores any invalid buffer types. When the buffer content is converted to XML, the BUFTYPE attribute is included in the buffer type tag (see example 1).
Example 1 - XML Conversion:
<stringptr BUFTYPE=STRING>teststringptr </stringptr>
PTR
During conversion to FML32, the BUFTYPE attribute must be included in the buffer type tag. The only valid values are Tuxedo buffer types: STRING, MBSTRING, CARRAY, FML, FML32, and VIEW32. If the BUFTYPE attribute is not specified or an invalid value is used, the element is ignored in FML32.
3-35
Field Type
FML32
Conversion Mapping The FLD_FML32 fieldname is supported with the opening and closing tags based upon the FML field name. This XML document includes
multiple descriptions of <fieldname>value</fieldname>
Example The first example below includes an encoding attribute and the second example is an FML32 definition for a BANK field containing an embedded FML32 field named ID.
Example 1: <ACCT Tpmbenc="EUC"><NM>Smith</NM><T RAN>OPEN</TRAN></ACCT> Example 2: <BANK><BID>001</BID><ID><NM>Jo nes</NM><AC>001</AC></ID> </BANK>
for each field contained in the buffer. Embedded FML32 is allowed so hierarchal XML descriptions are permitted.
Note: An optional attribute, Tpmbenc, can be used to
specify the encoding for the entire MBSTRING field of FML32 buffers during XML to FML32 conversion
3-36
Using an XML Typed Buffer and the Apache Xerces C++ Parser
Field Type
VIEW32
Conversion Mapping
The FLD_VIEW32 fieldname is supported, and therefore, the FLD_INT and FLD_DECIMAL fields are also recognized. FLD_INT is treated like FLD_LONG. The start and end tag is based on the FLD_VIEW32 field name. It will take a Vname attribute for specifying the view name to use. This XML document includes multiple descriptions of
<fbname> value </fbname>
Example
<CURR Vname="Myview"> <FB1>001</FB1><FB1>002</FB1><F B2>7.50</FB2><FB3>Y</FB3> </CURR>
3-37
Field Type
MBSTRING
Conversion Mapping
The FLD_MBSTRING field conversion uses the Encoding attribute and the field data to describe the FML32 field. This conversion is similar to Fmbpack32 usage. Please note the following conditions: 1. If the Encoding attribute is present and the value is specified, the data values are used to create the FLD_MBSTRING value. 2. If the Encoding attribute is not present and Tpmbenc has been set for the full FML32 buffer, then the FLD_MBSTRING adopts the Tpmbenc value. 3. If the Encoding attribute is not present and Tpmbenc is not specified, then an attempt is made to get the process environment TPMBENC (all caps) and use that encoding as the FLD_MBSTRING value in place of the attribute definition. 4. If all three of the previous conditions are not met, Tuxedo ignores those elements and no conversion takes place. Data is treated in the same manner as a FLD_CARRAY field.
Example
<MBIN Encoding="SJIS">C7E8D9CAB3</MB IN>
Conversion Limitations
The following limitations exist for conversion of XML data to and from FML/FML32 buffers using the Xerces 2.5.0 parser delivered with Tuxedo. XML documents are treated as a constrained XML message set, and not as a flexible XML grammar. This constraint is based upon the definitions specified in the FML/FML32 header file.
3-38
Using an XML Typed Buffer and the Apache Xerces C++ Parser
Digitally signed XML, FML or FML32 buffers fail signature checking when using automatic conversion. The tpenvelope() function for digital signatures can only be used during on-demand conversion. Parsing limitations are those inherited from the Xerces library. The Xerces parser does not support output XML DTD/Schema validation. Conversion between XML and FML/FML32 buffers does not necessarily create the exact same XML document as which you started. Tuxedo FML/FML32 buffers group equivalent field types within a buffer and bases output order on that grouping; therefore, specific element ordering based on input XML is lost. The Xerces parser cannot track FML/FML32 field input order, or control FML/FML32 field output order. Please note the following: All input format structure is lost during XML conversion. You can input a partial listing of view32 members to XML, However, when XML is converted to FML32, the FML32 output will include all view32 members defined in the view definition file. During automatic conversion, input XML root tag names are not saved and the default output root tag <FML Type="FML"> or <FML Type="FML32"> is used.
See Also
Tutorial for xmlstockapp, a C and C++ XML Parser Application in Tutorials for Developing Oracle Tuxedo ATMI Applications
tpfml32toxml(3c), tpfmltoxml(3c), tpxmltofml32(3c), and tpxmltofml(3c) in
and System Processes Reference Using a VIEW Typed Buffer on page 3-17 Using an FML Typed Buffer on page 3-23 Using an MBSTRING Typed Buffer on page 3-40
3-39
3-40
Workstation
/WS Client
/WS Handler
App Server
Client Request
...
Japanese SJIS-encoded data
...
Length ...
SJIS
MBSTRING
MBSTRING Data
MBSTRING Header
Server Reply
...
MBSTRING EUCJP Length ... Japanese EUCJP-encoded data
...
MBSTRING Header
MBSTRING Data
As indicated in the example, the MBSTRING typed buffer is capable of carrying information identifying the code-set character encoding, or simply encoding, of its user data. In the example, the client-request MBSTRING buffer holds Japanese user data represented by the Shift-JIS (SJIS) encoding, while the server-reply MBSTRING buffer holds Japanese user data represented by the Extended UNIX Code (EUC) encoding. The multibyte character encoding feature reads environment variables TPMBENC and TPMBACONV to determine the source encoding, the target encoding, and the state (on or off) of automatic encoding conversion.
Programming an Oracle Tuxedo ATMI Application Using C 3-41
The encoding conversion capability enables the underlying Tuxedo system software to convert the encoding representation of an incoming message to an encoding representation supported by the machine on which the receiving process is running. The conversion is neither a conversion between character code sets nor a translation between languages, but rather a conversion between different character encodings for the same language.
3-42
Application client process calls tpalloc() to get an MBSTRING buffer. Tuxedo system allocates memory for buffer. Tuxedo system calls internal function (similar to tuxgetmbenc()) to get code-set encoding name defined in environment variable TPMBENC. Is
TPMBENC
No
set ? Yes Tuxedo system adds codeset encoding name to buffer. Client process puts multibyte data in MBSTRING buffer and calls tpsend(), tpcall(), . . . to send buffer.
Tuxedo system returns error message to client process and logs error message in local ULOG.
End
3-43
Start
Tuxedo system, acting on behalf of application server process, receives MBSTRING buffer destined for server process. Tuxedo system calls internal function (similar to tuxgetmbaconv()) to get value defined in environment variable TPMBACONV. Tuxedo system delivers multibyte data in MBSTRING buffer to server process as is (no encoding conversion).
Is
TPMBACONV
No
set ? Yes Tuxedo system calls internal function (similar to tuxgetmbenc()) to get code-set encoding name defined in environment variable TPMBENC.
Is
TPMBENC
No
set ? Yes
Tuxedo system returns error message to sending process and logs error message in local ULOG.
To Sheet 2
To Sheet 2
3-44
Tuxedo system calls internal function (similar to tpgetmbenc()) to get code-set encoding name in MBSTRING buffer.
Tuxedo system compares code-set encoding name in MBSTRING buffer to code-set encoding name defined in TPMBENC. Tuxedo system delivers multibyte data in MBSTRING buffer to server process as is (no encoding conversion).
Yes
No (different) Tuxedo system calls _mbsconv() to convert multibyte data in MBSTRING buffer from source encoding (encoding name in MBSTRING buffer) to target encoding (encoding name defined in TPMBENC) and delivers converted data to server process.
End
3-45
capability for the buffer to determine its own length if the user does not provide it. This self-describing behavior is triggered when an application sets the sendlen argument of a Tuxedo function call (for example, tpcall()) to zero.
Implementation
This self-describing behavior is implemented by adding the following:
_mbspresend() function to the MBSTRING typeswitch function list
A protective file, $TUXDIR/udataobj/sendlen0_unsafe_tpmbenc, containing the names of the codeset encoding names which are considered unsafe to use with the feature. The _mbspresend() addition requires any user who customizes Tuxedo buffers to rebuild their applications.
3-46
European languages ASCII, ISO-8859-{1,2,3,4,5,7,9,10,13,14,15,16}, KOI8-R, KOI8-U, KOI8-RU, CP{1250,1251,1252,1253,1254,1257}, CP{850,866}, Mac{Roman,CentralEurope,Iceland,Croatian,Romania}, Mac{Cyrillic,Ukraine,Greek,Turkish}, Macintosh Semitic languages ISO-8859-{6,8}, CP{1255,1256}, CP862, Mac{Hebrew,Arabic} Japanese
3-47
EUC-JP, SHIFT-JIS, CP932, ISO-2022-JP, ISO-2022-JP-2, ISO-2022-JP-1 Chinese EUC-CN, HZ, GBK, GB18030, EUC-TW, BIG5, CP950, BIG5-HKSCS, ISO-2022-CN, ISO-2022-CN-EXT Korean EUC-KR, CP949, ISO-2022-KR, JOHAB Armenian ARMSCII-8 Georgian Georgian-Academy, Georgian-PS Thai TIS-620, CP874, MacThai Laotian MuleLao-1, CP1133 Vietnamese VISCII, TCVN, CP1258 Platform specifics HP-ROMAN8, NEXTSTEP Full Unicode UTF-8 UCS-2, UCS-2BE, UCS-2LE UCS-4, UCS-4BE, UCS-4LE UTF-16, UTF-16BE, UTF-16LE UTF-32, UTF-32BE, UTF-32LE UTF-7 JAVA
3-48
Customizing a Buffer
Full Unicode, in terms of `uint16_t' or `uint32_t' (with machine-dependent endianness and alignment) UCS-2-INTERNAL, UCS-4-INTERNAL Locale dependent, in terms of `char' or `wchar_t' (with machine-dependent endianness and alignment, and with OS and locale dependent semantics) char, wchar_t
See Also
For more information about multibyte character encoding, see the following documents:
buffer(3c), tpmbconv(3c), tpgetmbenc(3c), tpsetmbenc(3c), tuxgetmbenc(3c), and tuxsetmbenc(3c), tuxgetmbaconv(3c), and tuxsetmbaconv(3c) in Oracle
Programming an Oracle Tuxedo ATMI Application Using FML Oracle Tuxedo ATMI FML Function Reference
Customizing a Buffer
You may find that the buffer types supplied by the Oracle Tuxedo system do not meet your needs.
For example, perhaps your application uses a data structure that is not flat, but has pointers to other data structures, such as a parse tree for an SQL database query. To accommodate unique application requirements, the Oracle Tuxedo system supports customized buffers. To customize a buffer, you need to identify the following characteristics.
3-49
Description
Name of the buffer type, specified by a string of up to eight characters. Name of the buffer subtype, specified by a string of up to 16 characters. The system uses a subtype to identify different processing requirements for buffers of a given type. When the wildcard character (*) is specified as the subtype value, all buffers of a given type can be processed using the same generic routine. Any buffers for which a subtype is defined must appear before the wildcard in the list, in order to be processed correctly. Minimum size of the associated buffer type that can be allocated or reallocated. For buffer types that have a value greater than zero and that are sized appropriately, you can specify a buffer size of zero when allocating or reallocating a buffer to use this default size.
Default size
The following table defines the list of routines that you may need to specify for each buffer type. If a particular routine is not applicable, you can simply provide a NULL pointer; the Oracle Tuxedo system uses default processing, as necessary. Table 3-11 Custom Buffer Type Routines Routine
Buffer initialization Buffer reinitialization
Description
Initializes a newly allocated typed buffer. Reinitializes a typed buffer. This routine is called after a buffer has been reallocated (that is, assigned a new size). Uninitializes a typed buffer. This routine is called just before a typed buffer is freed. Prepares the typed buffer for sending. This routine is called before a typed buffer is sent as a message to another client or server. It returns the length of the data to be transmitted. Returns the typed buffer to its original state. This routine is called after the message is sent. Prepares the typed buffer once it has been received by the application. It returns the length of the application data.
Buffer uninitialization
Buffer presend
Buffer postsend
Buffer postreceive
3-50
Customizing a Buffer
Description
Performs all the encoding and decoding necessary for the buffer type. A request to encode or decode is passed to the routine, along with input and output buffers and lengths. The format used for encoding is determined by the application and, as with the other routines, it may be dependent on the buffer type. Specifies the routing information. This routine is called with a typed buffer, the length of the data for that buffer, a logical routing name configured by an administrator, and a target service. Based on this information, the application must select the server group to which the message should be sent or indicate that the message is not needed. Specifies filter information. This routine is called to evaluate an expression against a typed buffer and to return a match if it finds one. If the typed buffer is VIEW or FML, the FML Boolean expressions are used. This routine is used by the EventBroker to evaluate matches for events. Specifies a printable string for a typed buffer.
Routing
Filter
Format
3-51
The rest of the sections in this topic address the steps listed in the preceding procedure to define a new buffer type in a shared-object or DLL environment. First, however, lets look at the buffer switch that is delivered with the Oracle Tuxedo system software. The following listing shows the switch delivered with the system. Listing 3-17 Default Buffer Type Switch
#include <stdio.h> #include <tmtypes.h> /* * Initialization of the buffer type switch. */ struct tmtype_sw_t tm_typesw[] = { { "CARRAY", "*", 0 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }, { "STRING", "*", 512, NULL, NULL, /* type */ /* subtype */ /* dfltsize */ /* initbuf */ /* reinitbuf */ /* type */ /* subtype */ /* dfltsize */ /* initbuf */ /* reinitbuf */ /* uninitbuf */ /* presend */ /* postsend */ /* postrecv */ /* encdec */ /* route */ /* filter */ /* format */ /* presend2 */ /* multibyte code-set encoding conversion */
3-52
Customizing a Buffer
NULL, _strpresend, NULL, NULL, _strencdec, NULL, _sfilter, _sformat, NULL, NULL }, { "FML", "*", 1024, _finit, _freinit, _funinit, _fpresend, _fpostsend, _fpostrecv, _fencdec, _froute, _ffilter, _fformat, NULL, NULL }, { "VIEW", "*", 1024, _vinit, _vreinit, NULL, _vpresend, NULL, NULL,
/* uninitbuf */ /* presend */ /* postsend */ /* postrecv */ /* encdec */ /* route */ /* filter */ /* format */ /* presend2 */ /* multibyte code-set encoding conversion */
/* type */ /* subtype */ /* dfltsize */ /* initbuf */ /* reinitbuf */ /* uninitbuf */ /* presend */ /* postsend */ /* postrecv */ /* encdec */ /* route */ /* filter */ /* format */ /* presend2 */ /* multibyte code-set encoding conversion */
3-53
/* XATMI - identical to CARRAY */ "X_OCTET", "*", 0 }, { /* XATMI - identical to VIEW */ {'X','_','C','_','T','Y','P','E'}, "*", 1024, _vinit, _vreinit, NULL, _vpresend, NULL, NULL, _vencdec, _vroute, _vfilter, _vformat, NULL, NULL }, { /* XATMI - identical to VIEW */ {'X','_','C','O','M','M','O','N'}, "*", /* subtype */ 1024, _vinit, _vreinit, NULL, /* dfltsize */ /* initbuf */ /* reinitbuf */ /* uninitbuf */ /* type */ /* subtype */ /* dfltsize */ /* initbuf */ /* reinitbuf */ /* uninitbuf */ /* presend */ /* postsend */ /* postrecv */ /* encdec */ /* route */ /* filter */ /* format */ /* presend2 */ /* multibyte code-set encoding conversion */ /* type */ /* type */ /* subtype */ /* dfltsize */
3-54
Customizing a Buffer
_vpresend, NULL, NULL, _vencdec, _vroute, _vfilter, _vformat, NULL, NULL }, { "FML32", "*", 1024, _finit32, _freinit32, _funinit32, _fpresend32, _fpostsend32, _fpostrecv32, _fencdec32, _froute32, _ffilter32, _fformat32, _fpresend232, _fmbconv32 }, { "VIEW32", "*", 1024, _vinit32, _vreinit32, NULL, _vpresend32, NULL, NULL, _vencdec32,
/* presend */ /* postsend */ /* postrecv */ /* encdec */ /* route */ /* filter */ /* format */ /* presend2 */ /* multibyte code-set encoding conversion */
/* type */ /* subtype */ /* dfltsize */ /* initbuf */ /* reinitbuf */ /* uninitbuf */ /* presend */ /* postsend */ /* postrecv */ /* encdec */ /* route */ /* filter */ /* format */ /* presend2 */ /* multibyte code-set encoding conversion */
/* type */ /* subtype */ /* dfltsize */ /* initbuf */ /* reinitbuf */ /* uninitbuf */ /* presend */ /* postsend */ /* postrecv */ /* encdec */
3-55
_vroute32, _vfilter32, _vformat32, NULL, _vmbconv32, }, { "XML", "*", 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, _xroute, NULL, NULL, NULL, NULL }, { "MBSTRING", "*", 0, _mbsinit, NULL, NULL, _mbspresend, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
/* type */ /* subtype */ /* dfltsize */ /* initbuf */ /* reinitbuf */ /* uninitbuf */ /* presend */ /* postsend */ /* postrecv */ /* encdec */ /* route */ /* filter */ /* format */ /* presend2 */ /* multibyte code-set encoding conversion */
/* type */ /* subtype */ /* dfltsize */ /* initbuf */ /* reinitbuf */ /* uninitbuf */ /* presend */ /* postsend */ /* postrecv */ /* encdec */ /* route */ /* filter */ /* format */ /* presend2 */
3-56
Customizing a Buffer
_mbsconv }, { "" } };
For a better understanding of the preceding listing, consider the declaration of the buffer type structure that is shown in the following listing. Listing 3-18 Buffer Type Structure
/* * The following definitions are in $TUXDIR/include/tmtypes.h */ #define TMTYPELEN ED_TYPELEN #define TMSTYPELEN ED_STYPELEN struct tmtype_sw_t { char type[TMTYPELEN]; /* type of buffer */ char subtype[TMSTYPELEN]; /* subtype of buffer */ long dfltsize; /* default size of buffer */ /* buffer initialization function pointer */ int (_TMDLLENTRY *initbuf) _((char _TM_FAR *, long)); /* buffer reinitialization function pointer */ int (_TMDLLENTRY *reinitbuf) _((char _TM_FAR *, long)); /* buffer un-initialization function pointer */ int (_TMDLLENTRY *uninitbuf) _((char _TM_FAR *, long)); /* pre-send buffer manipulation func pointer */ long (_TMDLLENTRY *presend) _((char _TM_FAR *, long, long));
3-57
/* post-send buffer manipulation func pointer */ void (_TMDLLENTRY *postsend) _((char _TM_FAR *, long, long)); /* post-receive buffer manipulation func pointer*/ long (_TMDLLENTRY *postrecv) _((char _TM_FAR *, long, long)); /* XDR encode/decode function pointer */ long (_TMDLLENTRY *encdec) _((int, char _TM_FAR *, long, char _TM_FAR *, long)); /* routing function pointer */ int (_TMDLLENTRY *route) _((char _TM_FAR *, char _TM_FAR *, char _TM_FAR *, long, char _TM_FAR *)); /* buffer filtering function pointer */ int (_TMDLLENTRY *filter) _((char _TM_FAR *, long, char _TM_FAR *, long)); /* buffer formatting function pointer */ int (_TMDLLENTRY *format) _((char _TM_FAR *, long, char _TM_FAR *, char _TM_FAR *, long)); /* process buffer before sending, possibly generating copy */ long (_TMDLLENTRY *presend2) _((char _TM_FAR *, long, long, char _TM_FAR *, long, long _TM_FAR *)); /* Multibyte code-set encoding conversion function pointer*/ long (_TMDLLENTRY *mbconv) _((char _TM_FAR *, long, char _TM_FAR *, char _TM_FAR *, long, long _TM_FAR *));
/* this space reserved for future expansion */ void (_TMDLLENTRY *reserved[8]) _((void)); }; /* * application types switch pointer * always use this pointer when accessing the table */ extern struct tmtype_sw_t *tm_typeswp;
The listing for the default buffer type switch shows the initialization of the buffer type switch. The nine default buffer types are shown, followed by a field for naming a subtype. Except for the VIEW (and equivalently X_C_TYPE and X_COMMON) type, subtype is NULL. The subtype for VIEW is given as ``*'', which means that the default VIEW type puts no constraints on subtypes; all subtypes of type VIEW are processed in the same manner.
3-58
Customizing a Buffer
The next field gives the default (minimum) size of the buffer. For the CARRAY (and equivalently X_OCTET) type this is given as 0, which means that the routine that uses a CARRAY buffer type must tpalloc() enough space for the expected CARRAY. For the other types, the Oracle Tuxedo system allocates (with a tpalloc() call) the space shown in the dfltsize field of the entry (unless the size argument of tpalloc() specifies a larger size). The remaining eight fields of entries in the buffer type switch contain the names of switch element routines. These routines are described in the buffer(3c) page in the Oracle Tuxedo C Function Reference. The name of a routine provides a clue to the purpose of the routine. For example, _fpresend on the FML type is a pointer to a routine that manipulates the buffer before sending it. If no presend manipulation is needed, a NULL pointer may be specified. NULL means no special handling is required; the default action should be taken. See buffer(3c) for details. It is particularly important that you notice the NULL entry at the end of the switch. Any changes that are made must always leave the NULL entry at the end of the array.
ptr is a pointer to the application data buffer. dlen is the length of the data as passed into the routine. mdlen is the size of the buffer in which the data resides.
3-59
The data compression that takes place within your presend routine is the responsibility of the system programmer for your application. On completion the routine should return the new, hopefully shorter length of the data to be sent (in the same buffer), or a -1 to indicate failure. The name given to your version of the presend routine can be any identifier accepted by the C compiler. For example, suppose we name it _mypresend. If you use our _mypresend compression routine, you will probably also need a corresponding _mypostrecv routine to decompress the data at the receiving end. Follow the template shown in the buffer(3c) entry in the Oracle Tuxedo C Function Reference.
3-60
Customizing a Buffer
{ "FML", "", 1024, _finit, _freinit, _funinit, _fpresend, _fpostsend, _fpostrecv, _fencdec, _froute, _ffilter, _fformat }, { "" } };
/* /* /* /* /* /* /* /* /* /* /* /* /*
type */ subtype */ dfltsize */ initbuf */ reinitbuf */ uninitbuf */ presend */ postsend */ postrecv */ encdec */ route */ filter */ format */
In the previous listing, we added a new type: SOUND. We also removed the entries for VIEW, X_OCTET, X_COMMON, and X_C_TYPE, to demonstrate that you can remove any entries that are not needed in the default switch. Note that the array still ends with the NULL entry. An alternative to defining a new buffer type is to redefine an existing type. Suppose, for the sake of argument, that the data compression for which you defined the buffer type MYTYPE was performed on strings. You could substitute your new switch element routines, _mypresend and _mypostrecv, for the two _dfltblen routines in type STRING.
3-61
1. Copy and modify $TUXDIR/lib/tmtypesw.c, as described in Adding a New Buffer Type to tm_typesw on page 3-60. If additional functions are required, store them in either tmtypesw.c or a separate C source file. 2. Compile tmtypesw.c with the flags required for shared objects. 3. Link together all object files to produce a shared object. 4. Copy libbuft.so.71 from the current directory to a directory in which it will be visible to applications, and processed before the default shared object supplied by the Oracle Tuxedo system. We recommend using one of the following directories: $APPDIR, $TUXDIR/lib, or $TUXDIR/bin (on a Windows 2003 platform). Different platforms assign different names to the buffer type switch shared object, to conform to operating system conventions. Table 3-12 OS-specific Names for the Buffer Type Switch Shared Object On This Platform . . .
UNIX System (most SVR4) HP-UX Sun OS Windows (16-bit) Windows (32-bit) OS/2 (16-bit) OS/2 (32-bit)
Please refer to the software development documentation for your platform for instructions on building a shared object library. As an alternative, it is possible to statically link a new buffer type switch in every client and server process, but doing so is more error-prone and not as efficient as building a shared object library.
Compiling and Linking Your New tm_typesw for a 16-bit Windows Platform
If you have modified tmtypesw.c on a Windows platform, as described in Compiling and Linking Your New tm_typesw on page 3-61, then you can use the commands shown in the
3-62 Programming an Oracle Tuxedo ATMI Application Using C
Customizing a Buffer
following sample code listing to make the modified buffer type switch available to your application. Listing 3-21 Sample Code in Microsoft Visual C++
CL -AL -I..\e\|sysinclu -I..\e\|include -Aw -G2swx -Zp -D_TM_WIN -D_TMDLL -Od -c TMTYPESW.C LINK /CO /ALIGN:16 TMTYPESW.OBJ, WBUFT.DLL, NUL, WTUXWS /SE:250 /NOD /NOE LIBW LDLLCEW, WBUFT.DEF RC /30 /T /K WBUFT.DLL
Data Conversion
The purpose of the TYPE parameter in the MACHINES section of the configuration file is to group together machines that have the same form of data representation (and use the same compiler) so that data conversion is done on messages going between machines of different TYPEs. For the default buffer types, data conversion between unlike machines is transparent to the user (and to the administrator and programmer, for that matter). If your application defines new buffer types for messages that move between machines with different data representation schemes, you must also write new encode/decode routines to be incorporated into the buffer type switch. When writing your own data conversion routines, keep the following guidelines in mind: You should use the semantics of the _tmencdec routine shown on reference page buffer(3c) in Oracle Tuxedo ATMI C Function Reference; that is, you should code your routine so that it uses the same arguments and returns the same values on success or failure as the _tmencdec routine. When defining new buffer types, follow the procedure provided in Defining Your Own Buffer Types on page 3-51 for building servers with services that will use your new buffer type. The encode/decode routines are called only when the Oracle Tuxedo system determines that data is being sent between two machines that are not of the same TYPE.
3-63
3-64
CHAPTER
Writing Clients
This topic includes the following sections: Joining an Application Using Features of the TPINIT Typed Buffer Leaving the Application Building Clients Client Process Examples
Joining an Application
Before an ATMI client can perform any service request, it must join the Oracle Tuxedo ATMI application, either explicitly or implicitly. Once the client has joined the application, it can initiate requests and receive replies. A client joins an application explicitly by calling the tpinit(3c) function with the following signature:
int tpinit (TPINIT *tpinfo)
A client joins an application implicitly by issuing a service request (or any ATMI function) without first calling the tpinit()function. In this case, the tpinit() function is called by the Oracle Tuxedo system on behalf of the client with the tpinfo argument set to NULL. The
4-1
tpinfo argument points to a typed buffer with a TPINIT type and NULL subtype. The TPINIT typed buffer is defined in the atmi.h header file and includes the following information: char usrname[MAXTIDENT+2]; char cltname[MAXTIDENT+2]; char passwd[MAXTIDENT+2]; char grpname[MAXTIDENT+2]; long flags; long datalen; long data;
The following table summarizes the TPINIT data structure fields. Table 4-1 TPINIT Data Structure Fields Field
usrname
Description
Name representing the client; used for both broadcast notification and administrative statistics retrieval. The client assigns a value to usrname during the call to the tpinit() function. The value is a string of up to MAXTIDENT characters (which defaults to 30 and is configurable by the administrator), and must be terminated by NULL. Client name with application-defined semantics: a 30-character NULL-terminated string used for both broadcast notification and administrative statistics retrieval. The client assigns a value to cltname during the call to the tpinit() function. The value is a string of up to MAXTIDENT characters (which defaults to 30 and is configurable by the administrator), and must be terminated by NULL. Note: The value sysclient is reserved for the cltname field.
cltname
passwd
Application password in unencrypted format. Used for user authentication. The value is a string of up to 30 characters. Associates client with resource manager group. If set to a 0-length string, the client is not associated with a resource manager and is in the default client group. The value of grpname must be the NULL string (0-length string) for Workstation clients. Refer to Using the ATMI Workstation Component for more information on Workstation clients.
grpname
4-2
Description
Indicates both the client-specific notification mechanism and the mode of system access. Controls both multicontext and single-context modes. Refer to Unsolicited Notification Handling on page 4-5 or tpinit() in the Oracle Tuxedo ATMI C Function Reference for more information on flags. Length of the application-specific data. The buffer type switch entry for the TPINIT typed buffer sets this field based on the total size passed in for the typed buffer. The size of the application data is the total size less the size of the TPINIT structure itself plus the size of the data placeholder as defined in the structure. Placeholder for variable length data that is forwarded to an application-defined authentication service.
datalen
data
Before it can join the application, the client program must call tpalloc() to allocate the TPINIT buffer. The following example shows how to allocate a TPINIT buffer that will be used to pass eight bytes of application-specific data to the tpinit() function. Listing 4-1 Allocating a TPINIT Typed Buffer
. . . TPINIT *tpinfo; . . . if ((tpinfo = (TPINIT *)tpalloc("TPINIT",(char *)NULL, TPINITNEED(8))) == (TPINIT *)NULL){ Error Routine }
4-3
Refer to tpinit() in the Oracle Tuxedo ATMI C Function Reference for more information on the TPINIT typed buffer.
See Also
tpinit(3c) in the Oracle Tuxedo ATMI C Function Reference
Client Naming
When an ATMI client joins an application, the Oracle Tuxedo system assigns a unique client identifier to it. The identifier is passed to each service called by the client. It can also be used for unsolicited notification. You can also assign unique client and usernames of up to 30 characters each, by passing them to the tpinit() function via the tpinfo buffer argument. The Oracle Tuxedo system establishes a unique identifier for each process by combining the client and usernames associated with it, with the logical machine identifier (LMID) of the machine on which the process is running. You may choose a method for acquiring the values for these fields. Note: If a process is executing outside the administrative domain of the application (that is, if it is running on a workstation connected to the administrative domain), the LMID of the machine used by the Workstation client to access the application is assigned. Once a unique identifier for a client process is created: Client authentication can be implemented.
4-4
Unsolicited messages can be sent to a specific client or to groups of clients via tpnotify() and tpbroadcast(). Detailed statistical information can be gathered via tmadmin(1). Refer to Writing Event-based Clients and Servers on page 8-1 for information on sending and receiving unsolicited messages, and the Oracle Tuxedo ATMI C Function Reference for more information on tmadmin(1). The following figure shows how names might be associated with clients accessing an application. In the example, the application uses the cltname field to indicate a job function. Figure 4-1 Client Naming
Does not interrupt the current processing As some time may elapse between dip-ins, the application can call the tpchkunsol() function to check for any waiting unsolicited messages. Refer to Writing Event-based Clients and Servers on page 8-1 for more information on the tpchkunsol()function. When a client joins an application using the tpinit() function, it can control how to handle unsolicited notification messages by defining flags. For client notification, the possible values for flags are defined in the following table. Table 4-2 Client Notification Flags in a TPINIT Typed Buffer Flag
TPU_SIG
Description
Select unsolicited notification by signals. This flag should be used only with single-threaded, single-context applications. The advantage of using this mode is immediate notification. The disadvantages include: The calling process must have the same UID as the sending process when you are running a native client. (Workstation clients do not have this limitation.)
TPU_SIG is not available on all platforms (specifically, it is not available on MS-DOS workstations).
If you specify this flag but do not meet the system or environmental requirements, the flag is set to TPU_DIP and the event is logged.
TPU_DIP (default)
Select unsolicited notification by dip-in. In this case, the client can specify the name of the message handling function using the tpsetunsol() function, and check for waiting unsolicited messages using the tpchkunsol() function. Select THREAD notification in a separate thread. This flag is allowed only on platforms that support multithreading. If TPU_THREAD is specified on a platform that does not support multithreading, it is considered an invalid argument. As a result, an error is returned and tperrno(5) is set to TPEINVAL. Ignore unsolicited notification.
TPU_THREAD
TPU_IGN
Refer to tpinit(3c) in the Oracle Tuxedo ATMI C Function Reference for more information on the TPINIT typed buffer flags.
4-6
Description
Allows ATMI calls within an application to access the Oracle Tuxedo system internal tables via shared memory, but protects shared memory against access by application code outside of the Oracle Tuxedo system libraries. Overrides the value in UBBCONFIG, except when NO_OVERRIDE is specified. Refer to Setting Up an Oracle Tuxedo Application for more information on UBBCONFIG. Allows ATMI calls within application code access to Oracle Tuxedo system internals via shared memory. Does not protect shared memory against access by application code outside of the Oracle Tuxedo system libraries. Overrides the value of UBBCONFIG except when NO_OVERRIDE is specified. Refer to Setting Up an Oracle Tuxedo Application for more information on UBBCONFIG.
Fastpath (default)
Client Authentication
The Oracle Tuxedo system provides security at incremental levels, including operating system security, application password, user authentication, optional access control lists, mandatory access control lists, and link-level encryption. Refer to Setting Up an Oracle Tuxedo Application for information on setting security levels. The application password security level requires every client to provide an application password when it joins the application. The administrator can set or change the application password and must provide it to valid users.
Programming an Oracle Tuxedo ATMI Application Using C 4-7
If this level of security is used, Oracle Tuxedo system-supplied client programs, such as ud(), prompt for the application password. (Refer to Administering an Oracle Tuxedo Application at Run Time for more information on ud, wud(1).) In turn, application-specific client programs must include code for obtaining the password from a user. The unencrypted password is placed in the TPINIT buffer and evaluated when the client calls tpinit() to join the application. Note: The password should not be displayed on the screen. You can use the tpchkauth(3c) function to determine: Whether the application requires any authentication If the application requires authentication, which of the following types of authentication is needed: System authentication based on an application password Application authentication based on an application password and user-specific information Typically, a client should call the tpchkauth() function before tpinit() to identify any additional security information that must be provided during initialization. Refer to Using Security in CORBA Applications for more information on security programming techniques.
Building Clients
To build an executable ATMI client, compile your application with the Oracle Tuxedo system libraries and all other referenced files using the buildclient(1) command. Use the following syntax for the buildclient command:
buildclient filename.c -o filename -f filenames -l filenames
4-8
-l filenames
-r
Note: The Oracle Tuxedo libraries are linked in automatically; you do not need to specify any Oracle Tuxedo libraries on the command line. The order in which you specify the library files to be link edited is significant: it depends on the order in which functions are called in the code, and which libraries contain references to those functions. By default, the buildclient command invokes the UNIX cc command. You can set the CC and CFLAGS environment variables to specify an alternative compile command, and to set flags for the compile and link-edit phases, respectively. For more information, refer to Setting Environment Variables on page 2-5.
buildclient -C -o audit -f audit.o
The following example command line compiles a C program called audit.c and generates an executable file named audit.
4-9
See Also
Building Servers on page 5-30
buildclient(1) in the Oracle Tuxedo Command Reference
4-10
error routine; } }
On error, -1 is returned and the application sets the external global variable, tperrno, to a value that indicates the nature of the error. tperrno is defined in the atmi.h header file and documented in tperrno(5) in the File Formats, Data Descriptions, MIBs, and System Processes Reference. Programmers typically assign an error code to this global variable that reflects the type of error encountered. There is a discussion of the values of tperrno in System Errors on page 11-1. See Introduction to the C Language Application-to-Transaction Monitor Interface in the Oracle Tuxedo ATMI C Function Reference for a complete list of error codes that can be returned for each of the ATMI functions. The following example illustrates how to use the tpinit() and tpterm() functions. This example is borrowed from, bankapp, the sample banking application that is provided with the Oracle Tuxedo system. Listing 4-3 Joining and Leaving an Application
#include <stdio.h> #include <string.h> #include <fml.h> #include <atmi.h> #include <Uunix.h> #include <userlog.h> #include "bank.h" #include "aud.h" ... main(argc, argv) int argc; char *argv[]; { ... /* UNIX */ /* UNIX */ /* BEA Tuxedo System */ /* BEA Tuxedo System */ /* BEA Tuxedo System */ /* BEA Tuxedo System */ /* BANKING #defines */ /* BANKING view defines */
4-11
if (strrchr(argv[0],'/') != NULL) proc_name = strrchr(argv[0],'/')+1; else proc_name = argv[0]; ... /* Join application */ if (tpinit((TPINIT *) NULL) == -1) { (void)userlog("%s: failed to join application\n", proc_name); exit(1); } ... /* Leave application */ if (tpterm() == -1) { (void)userlog("%s: failed to leave application\n", proc_name); exit(1); } }
The previous example shows the client process attempting to join the application with a call to tpinit(). If the process encounters an error (that is, if the return code is 1), the process writes a descriptive message to the central event log via a call to userlog(), which takes arguments similar to the printf() C program statement. Refer to userlog(3c) in the Oracle Tuxedo ATMI C Function Reference for more information. Similarly, when tpterm() is called, if an error is encountered, the process writes a descriptive message to the central event log.
4-12
CHAPTER
Writing Servers
This topic includes the following sections: Oracle Tuxedo System main( ) System-Supplied Server and Services Guidelines for Writing Servers Defining a Service Example: Checking the Buffer Type Example: Checking the Priority of the Service Request Terminating a Service Routine Advertising and Unadvertising Services Building ServersUsing a C++ Compiler
5-1
In addition to joining and exiting from an application, the predefined main() routine accomplishes the following tasks on behalf of the server. Executes the process ignoring any hangups (that is, it ignores the SIGHUP signal). Initiates the cleanup process on receipt of the standard operating system software termination signal (SIGTERM). The server is shut down and must be rebooted if needed again. Attaches to shared memory for bulletin board services. Creates a message queue for the process. Advertises the initial services to be offered by the server. The initial services are either all the services link edited with the predefined main(), or a subset specified by the Oracle Tuxedo system administrator in the configuration file. Processes command-line arguments up to the double dash (--), which indicates the end of system-recognized arguments. Calls the function tpsvrinit() to process any command-line arguments listed after the double dash (--) and optionally to open the resource manager. These command-line arguments are used for application-specific initialization. Until ordered to halt, checks its request queue for service request messages. When a service request message arrives on the request queue, main() performs the following tasks until ordered to halt: If the -r option is specified, records the starting time of the service request. Updates the bulletin board to indicate that the server is BUSY. Allocates a buffer for the request message and dispatches the service; that is, calls the service subroutine. When the service returns from processing its input, main() performs the following tasks until ordered to halt: If the -r option is specified, records the ending time of the service request. Updates statistics. Updates the bulletin board to indicate that the server is IDLE; that is, that the server is ready for work. Checks its queue for the next service request.
5-2
When the server is required to halt, calls tpsvrdone() to perform any required shutdown operations. As indicated above, the main() routine handles all of the details associated with joining and exiting from an application, managing buffers and transactions, and handling communication. Note: Because the system-supplied main() accomplishes the work of joining and leaving the application, you should not include calls to the tpinit() or tpterm() function in your code. If you do, the function encounters an error and returns TPEPROTO in tperrno. For more information on the tpinit() or tpterm() function, refer to Writing Clients on page 4-1.
5-3
When called by a Workstation client, tpinit() encrypts the data before sending it across the network.
initialization phase, before handling any service requests. If an application does not provide a custom version of this function within the server, the system uses the default function provided by main(), which opens the resource manager and logs an entry in the central event log indicating that the server has successfully started. The central user log is an automatically generated file to which processes can write messages by calling the userlog(3c) function. Refer to Managing Errors on page 11-1 for more information on the central event log. You can use the tpsvrinit() function for any initialization processes that might be required by an application, such as the following: Receiving command-line options Opening a database The following sections provide code samples showing how these initialization tasks are performed through calls to tpsvrinit(). Although it is not illustrated in the following examples, message exchanges can also be performed within this routine. However, tpsvrinit() fails if it returns with asynchronous replies pending. In this case, the replies are ignored by the Oracle Tuxedo system, and the server exits gracefully. You can also use the tpsvrinit() function to start and complete transactions, as described in Managing Errors on page 11-1. Use the following signature to call the tpsvrinit() function:
int tpsvrinit(int argc, char **argv)
The following code example shows how the tpsvrinit() function is used to receive command-line options. Listing 5-1 Receiving Command-line Options in tpsvrinit( )
tpsvrinit(argc, argv) int argc; char **argv; { int c; extern char *optarg; extern int optind; . . . while((c = getopt(argc, argv, "f:x:")) != EOF) switch(c){ . . . } . . . }
When main() calls tpsvrinit(), it picks up any arguments that follow the double dash (--) on the command line. In the example above, options f and x each takes an argument, as indicated by the colon. optarg points to the beginning of the option argument. The switch statement logic is omitted.
and tx_close(3c). Applications that use these functions to open and close their resource managers are portable in this respect. They work by accessing the resource manager instance-specific information that is available in the configuration file. Note: If writing a multithreaded server, you must use the tpsvrthrinit() function to open a resource manager, as described in Programming a Multithreaded and Multicontexted ATMI Application on page 10-1. These function calls are optional and can be used in place of the resource manager specific calls that are sometimes part of the Data Manipulation Language (DML) if the resource manager is a database. Note the use of the userlog(3c) function to write to the central event log. Note: To create an initialization function that both receives command-line options and opens a database, combine the following example with the previous example. Listing 5-2 Opening a Resource Manager in tpsvrinit( )
tpsvrinit() { /* Open database */ if (tpopen() == -1) { (void)userlog("tpsvrinit: failed to open database: "); switch (tperrno) { case TPESYSTEM: (void)userlog("System error\n"); break; case TPEOS: (void)userlog("Unix error %d\n",Uunixerr); break; case TPEPROTO: (void)userlog("Called in improper context\n"); break; case TPERMERR: (void)userlog("RM failure\n"); break; } return(-1); /* causes the server to exit */
5-6
} return(0); }
To guard against errors that may occur during initialization, tpsvrinit() can be coded to allow the server to exit gracefully before starting to process service requests.
The tpsvrdone() function requires no arguments. If an application does not define a closing routine for tpsvrdone(), the Oracle Tuxedo system calls the default routine supplied by main(). This routine calls tx_close() and userlog() to close the resource manager and write to the central event log, respectively. The message sent to the log indicates that the server is about to exit.
tpsvrdone() is called after the server has finished processing service requests but before it exits. Because the server is still part of the system, further communication and transactions can take place within the routine, as long as certain rules are followed. These rules are covered in Managing Errors on page 11-1.
The following example illustrates how to use the tpsvrdone() function to close a resource manager and exit gracefully. Listing 5-3 Closing a Resource Manager with tpsvrdone( )
void tpsvrdone() {
5-7
/* Close the database */ if(tpclose() == -1) (void)userlog("tpsvrdone: failed to close database: "); switch (tperrno) { case TPESYSTEM: (void)userlog("BEA TUXEDO error\n"); break; case TPEOS: (void)userlog("Unix error %d\n",Uunixerr); break; case TPEPROTO: (void)userlog("Called in improper context\n"); break; case TPERMERR: (void)userlog("RM failure\n"); break; } return; } return; }
5-8
after they finish executing, control returns to the Oracle Tuxedo systems main() instead of the calling function. When communicating with another server via tpacall(), the initiating service must either wait for all outstanding replies or invalidate them with tpcancel() before calling tpreturn() or tpforward(). Service routines are invoked with one argument, svcinfo, which is a pointer to a service information structure (TPSVCINFO).
Defining a Service
You must define every service routine as a function that receives one argument consisting of a pointer to a TPSVCINFO structure. The TPSVCINFO structure is defined in the atmi.h header file and includes the following information:
char long char long int int CLIENTID name[32]; flags; *data; len; cd; appkey; cltid;
5-9
Description
Specifies, to the service routine, the name used by the requesting process to invoke the service. Notifies the service if it is in transaction mode or if the caller is expecting a reply. The various ways in which a service can be placed in transaction mode are discussed in Writing Global Transactions on page 9-1. The TPTRAN flag indicates that the service is in transaction mode. When a service is invoked through a call to tpcall() or tpacall() with the flags parameter set to TPNOTRAN, the service cannot participate in the current transaction. However, it is still possible for the service to be executed in transaction mode. That is, even when the caller sets the TPNOTRAN communication flag, it is possible for TPTRAN to be set in svcinfo->flags. For an example of such a situation, refer to Writing Global Transactions on page 9-1. The flags member is set to TPNOREPLY if the service is called by tpacall() with the TPNOREPLY communication flag set. If a called service is part of the same transaction as the calling process, it must return a reply to the caller.
flags
data
Pointer to a buffer that was previously allocated by tpalloc() within the main(). This buffer is used to receive request messages. However, it is recommended that you also use this buffer to send back reply messages or forward request messages. Contains the length of the request data that is in the buffer referenced by the data field. For conversational communication, specifies the connection descriptor.
len
cd
5-10
Description
Reserved for use by the application. If application-specific authentication is part of your design, the application-specific authentication server, which is called when a client joins the application, should return a client authentication key as well as an indication of success or failure. The Oracle Tuxedo system holds the appkey on behalf of the client and passes the information to subsequent service requests in this field. By the time the appkey is passed to a service, the client has already been authenticated. However, the appkey field can be used within a service to identify the user invoking the service or some other parameters associated with the user. If this field is not used, the system assigns it a default value of -1.
cltid
Structure of type CLIENTID used by the system to carry the identification of the client. You should not modify this structure.
When the data field in the TPSVCINFO structure is being accessed by a process, the following buffer types must agree: Type of the request buffer passed by the calling process Type of the corresponding buffer code defined within the called service Type of the associated buffer type defined for the called service in the configuration file The following example illustrates a typical service definition. This code is borrowed from the
ABAL (account balance) service routine that is part of the banking application provided with the
Oracle Tuxedo software. ABAL is part of the BAL server. Listing 5-4 Typical Service Definition
#include <stdio.h> #include <atmi.h> #include <sqlcode.h> #include "bank.flds.h" #include "aud.h" /* UNIX */ /* BEA Tuxedo System */ /* BEA Tuxedo System */ /* bankdb fields */ /* BANKING view defines */
5-11
/* balance */
EXEC SQL end declare section; /* * Service to find sum of the account balances at a SITE */ void #ifdef __STDC__ ABAL(TPSVCINFO *transb) #else ABAL(transb) TPSVCINFO *transb; #endif { struct aud *transv; /* view of decoded message */
/* Set pointer to TPSVCINFO data buffer */ transv = (struct aud *)transb->data; set the consistency level of the transaction /* Get branch id from message, do query */ EXEC SQL declare acur cursor for select SUM(BALANCE) from ACCOUNT; EXEC SQL open acur; /* open */ EXEC SQL fetch acur into :bal; /* fetch */ if (SQLCODE != SQL_OK) { /* nothing found */ (void)strcpy (transv->ermsg,"abal failed in sql aggregation"); EXEC SQL close acur; tpreturn(TPFAIL, 0, transb->data, sizeof(struct aud), 0); } EXEC SQL close acur;
5-12
In the preceding example, the application allocates a request buffer on the client side by a call to tpalloc() with the type parameter set to VIEW and the subtype set to aud. The ABAL service is defined as supporting the VIEW typed buffer. The BUFTYPE parameter is not specified for ABAL and defaults to ALL. The ABAL service allocates a buffer of the type VIEW and assigns the data member of the TPSVCINFO structure that was passed to the ABAL subroutine to the buffer pointer. The ABAL server retrieves the appropriate data buffer by accessing the corresponding data member, as illustrated in the preceding example. Note: After the buffer is retrieved, but before the first attempt is made to access the database, the service must specify the consistency level of the transaction. Refer to Writing Global Transactions on page 9-1 for more details on transaction consistency levels.
5-13
TPSVCINFO *transb; { struct aud *transv; /* view message */ FBFR *transf; /* fielded buffer message */ int repc; /* tpgetrply return code */ char typ[TMTYPELEN+1], subtyp[TMSTYPELEN+1]; /* type, subtype of message */ char *retstr; /* return string if tptypes fails */ /* find out what type of buffer sent */ if (tptypes((char *)transb->data, typ, subtyp) == -1) { retstr=tpalloc("STRING", NULL, 100); (void)sprintf(retstr, "Message garbled; tptypes cannot tell what type message\n"); tpreturn(TPFAIL, TMTYPERR, retstr, 100, 0); } /* Determine method of processing service request based on type */ if (strcmp(typ, "FML") == 0) { transf = (FBFR *)transb->data; ... code to do abal service for fielded buffer ... tpreturn succeeds and sends FML buffer in reply } else if (strcmp(typ, "VIEW") == 0 && strcmp(subtyp, "aud") == 0) { transv = (struct aud *)transb->data; ... code to do abal service for aud struct ... tpreturn succeeds and sends aud view buffer in reply } else { retstr=tpalloc("STRING", NULL, 100); (void)sprintf(retstr, "Message garbled; is neither FML buffer nor aud view\n"); tpreturn(TPFAIL, INVALMTY, retstr, 100, 0); } }
The application queries pbuf>flags to determine whether a reply is expected. If so, it returns the name of the destination printer to the client. For more information on the tpreturn() function, refer to Terminating a Service Routine on page 5-16. Listing 5-6 Checking the Priority of a Received Request
#include <stdio.h> #include "atmi.h" char *roundrobin(); PRINTER(pbuf) TPSVCINFO *pbuf; /* print buffer */
/* /* /* /*
printer name, output command */ return buffer length */ priority of request */ pipe file pointer */
prio=tpgprio(); if (prio <= 20) (void)strcpy(prname,"bigjobs"); /* send low priority (verbose) jobs to big comp. center laser printer where operator sorts output and puts it in a bin */ else if (prio <= 60) (void)strcpy(prname,roundrobin()); /* assign printer on a rotating basis to one of many local small laser printers where output can be picked up immediately; roundrobin() cycles through list of printers */ else (void)strcpy(prname,"hispeed"); /* assign job to high-speed laser printer; reserved for those who need verbose output on a daily, frequent basis */ (void)sprintf(ocmd, "lp -d%s", prname); lp_pipe = popen(ocmd, "w"); (void)fprintf(lp_pipe, "%s", pbuf->data); (void)pclose(lp_pipe); /* /* /* /* output lp(1) command */ create pipe to command */ print output there */ close pipe */
5-15
if ((pbuf->flags & TPNOREPLY)) tpreturn(TPSUCCESS, 0, NULL, 0, 0); rlen = strlen(prname) + 1; pbuf->data = tprealloc(pbuf->data, rlen); /* ensure enough space for name */ (void)strcpy(pbuf->data, prname); tpreturn(TPSUCCESS, 0, pbuf->data, rlen, 0); char * roundrobin() { static char *printers[] = {"printer1", "printer2", "printer3", "printer4"}; static int p = 0; if (p > 3) p=0; return(printers[p++]); }
Sending Replies
The tpreturn(3c) function marks the end of the service routine and sends a message to the requester. Use the following signature to call the tpreturn() function:
void tpreturn(int rval, int rcode, char *data, long len, long flags)
5-16
Description
Indicates whether or not the service has completed successfully on an application-level. The value is an integer that is represented by a symbolic name. Valid settings include:
TPSUCCESSthe calling function succeeded. The function stores the reply message in the callers buffer. If there is a reply message, it is in the callers buffer. TPFAIL (default)the service terminated unsuccessfully. The function reports an error message to the client process waiting for the reply. In this case, the clients tpcall() or tpgetrply() function call fails and the system sets the tperrno(5) variable to TPESVCFAIL to indicate an application-defined failure. If a reply message was expected, it is available in the callers buffer. TPEXITthe service terminated unsuccessfully. The function reports an error message to the client process waiting for the reply, and exits.
For a description of the effect that the value of this argument has on global transactions, refer to Writing Global Transactions on page 9-1.
rcode
Returns an application-defined return code to the caller. The client can access the value returned in rcode by querying the tpurcode(5) global variable. The function returns this code regardless of success or failure.
5-17
Description
Pointer to the reply message that is returned to the client process. The message buffer must have been allocated previously by tpalloc(). If you use the same buffer that was passed to the service in the SVCINFO structure, you need not be concerned with buffer allocation or disposition because both are handled by the system-supplied main(). You cannot free this buffer using the tpfree() command; any attempt to do so quietly fails. You can resize the buffer using the tprealloc() function. If you use another buffer (that is, a buffer other than the one passed to the service routine) to return the message, it is your responsibility to allocate it. The system frees the buffer automatically when the application calls the tpreturn() function. If no reply message needs to be returned, set this argument to the NULL pointer. Note: If no reply is expected by the client (that is, if TPNOREPLY was set), the tpreturn() function ignores the data and len arguments and returns control to main().
len
Length of the reply buffer. The application accesses the value of this argument through the olen parameter of the tpcall() function or the len parameter of the tpgetrply() function. Acting as the client, the process can use this returned value to determine whether the reply buffer has grown. If a reply is expected by the client and there is no data in the reply buffer (that is, if the data argument is set to the NULL pointer), the function sends a reply with zero length, without modifying the clients buffer. The system ignores the value of this argument if the data argument is not specified.
flag
The primary function of a service routine is to process a request and return a reply to a client process. It is not necessary, however, for a single service to do all the work required to perform the requested function. A service can act as a requester and pass a request call to another service the same way a client issues the original request: through calls to tpcall() or tpacall(). Note: The tpcall() and tpacall() functions are described in detail in Writing Request/Response Clients and Servers on page 6-1.
5-18 Programming an Oracle Tuxedo ATMI Application Using C
When tpreturn() is called, control always returns to main(). If a service has sent requests with asynchronous replies, it must receive all expected replies or invalidate them with tpcancel() before returning control to main(). Otherwise, the outstanding replies are automatically dropped when they are received by the Oracle Tuxedo system main(), and an error is returned to the caller. If the client invokes the service with tpcall(), after a successful call to tpreturn(), the reply message is available in the buffer referenced by *odata. If tpacall() is used to send the request, and tpreturn() returns successfully, the reply message is available in the tpgetrply() buffer that is referenced by *data. If a reply is expected and tpreturn() encounters errors while processing its arguments, it sends a failed message to the calling process. The caller detects the error by checking the value placed in tperrno. In the case of failed messages, the system sets tperrno to TPESVCERR. This situation takes precedence over the value of the tpurcode global variable. If this type of error occurs, no reply data is returned, and both the contents and length of the callers output buffer remain unchanged. If tpreturn() returns a message in a buffer of an unknown type or a buffer that is not allowed by the caller (that is, if the call is made with flags set to TPNOCHANGE), the system returns TPEOTYPE in tperrno(5). In this case, application success or failure cannot be determined, and the contents and length of the output buffer remain unchanged. The value returned in the tpurcode(5) global variable is not relevant if the tpreturn() function is invoked and a timeout occurs for the call waiting for the reply. This situation takes precedence over all others in determining the value that is returned in tperrno(5). In this case, tperrno(5) is set to TPETIME and the reply data is not sent, leaving the contents and length of the callers reply buffer unchanged. There are two types of timeouts in the Oracle Tuxedo system: blocking and transaction timeouts (discussed in Writing Global Transactions on page 9-1). The example code in this section shows the TRANSFER service that is part of the XFER server. Basically, the TRANSFER service makes synchronous calls to the WITHDRAWAL and DEPOSIT services. It allocates a separate buffer for the reply message since it must use the request buffer for the calls to both the WITHDRAWAL and the DEPOSIT services. If the call to WITHDRAWAL fails, the service writes the message cannot withdraw on the status line of the form, frees the reply buffer, and sets the rval argument of the tpreturn() function to TPFAIL. If the call succeeds, the debit balance is retrieved from the reply buffer. Note: In the following example, the application moves the identifier for the destination account (which is retrieved from the cr_id variable) to the zeroth occurrence of the ACCOUNT_ID field in the transf fielded buffer. This move is necessary because this
5-19
occurrence of the field in an FML buffer is used for data-dependent routing. Refer to Setting Up an Oracle Tuxedo Application for more information. A similar scenario is followed for the call to DEPOSIT. On success, the service frees the reply buffer that was allocated in the service routine and sets the rval argument to TPSUCCESS, returning the pertinent account information to the status line. Listing 5-7 tpreturn( ) Function
#include #include #include #include #include #include #include #include <stdio.h> <string.h> "fml.h" "atmi.h" "Usysflds.h" "userlog.h" "bank.h" "bank.flds.h" /* /* /* /* /* /* /* /* UNIX */ UNIX */ BEA Tuxedo System */ BEA Tuxedo System */ BEA Tuxedo System */ BEA Tuxedo System */ BANKING #defines */ bankdb fields */
/* * Service to transfer an amount from a debit account to a credit * account */ void #ifdef __STDC__ TRANSFER(TPSVCINFO *transb) #else TRANSFER(transb) TPSVCINFO *transb; #endif { FBFR *transf; long db_id, cr_id; float db_bal, cr_bal; float tamt; FBFR *reqfb; int reqlen; char t_amts[BALSTR]; char db_amts[BALSTR]; char cr_amts[BALSTR]; /* /* /* /* /* /* /* /* /* fielded buffer of decoded message */ from/to account ids */ from/to account balances */ amount of the transfer */ fielded buffer for request message*/ length of fielded buffer */ string for transfer amount */ string for debit account balance */ string for credit account balance */
5-20
transf = (FBFR *)transb->data; /* Get debit (db_id) and credit (cr_id) account IDs */ /* must have valid debit account number */ if (((db_id = Fvall(transf, ACCOUNT_ID, 0)) < MINACCT) || (db_id > MAXACCT)) { (void)Fchg(transf, STATLIN, 0,"Invalid debit account number",(FLDLEN)0); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } /* must have valid credit account number */ if ((cr_id = Fvall(transf, ACCOUNT_ID, 1)) < MINACCT || cr_id > MAXACCT) { (void)Fchg(transf,STATLIN, 0,"Invalid credit account number",(FLDLEN)0); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } /* get amount to be withdrawn */ if (Fget(transf, SAMOUNT, 0, t_amts, < 0) 0 || strcmp(t_amts,"") == 0) { (void)Fchg(transf, STATLIN, 0, "Invalid amount",(FLDLEN)0); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } (void)sscanf(t_amts,"%f",tamt); /* must have valid amount to transfer */ if (tamt = 0.0) { (void)Fchg(transf, STATLIN, 0, "Transfer amount must be greater than $0.00",(FLDLEN)0); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } /* make withdraw request buffer */ if ((reqfb = (FBFR *)tpalloc("FML",NULL,transb->len)) == (FBFR *)NULL) { (void)userlog("tpalloc failed in transfer\n"); (void)Fchg(transf, STATLIN, 0, "unable to allocate request buffer", (FLDLEN)0); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } reqlen = Fsizeof(reqfb); /* put ID in request buffer */ (void)Fchg(reqfb,ACCOUNT_ID,0,(char *)&db_id, (FLDLEN)0); /* put amount in request buffer */ (void)Fchg(reqfb,SAMOUNT,0,t_amts, (FLDLEN)0); /* increase the priority of withdraw call */ if (tpsprio(PRIORITY, 0L) == -1) (void)userlog("Unable to increase priority of withdraw\n"); if (tpcall("WITHDRAWAL", (char *)reqfb,0, (char **)&reqfb,
5-21
(long *)&reqlen,TPSIGRSTRT) == -1) { (void)Fchg(transf, STATLIN, 0, "Cannot withdraw from debit account", (FLDLEN)0); tpfree((char *)reqfb); tpreturn(TPFAIL, 0,transb->data, 0L, 0); } /* get "debit" balance from return buffer */ (void)strcpy(db_amts, Fvals((FBFR *)reqfb,SBALANCE,0)); void)sscanf(db_amts,"%f",db_bal); if ((db_amts == NULL) || (db_bal < 0.0)) { (void)Fchg(transf, STATLIN, 0, "illegal debit account balance", (FLDLEN)0); tpfree((char *)reqfb); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } /* put deposit account ID in request buffer */ (void)Fchg(reqfb,ACCOUNT_ID,0,(char *)&cr_id, (FLDLEN)0); /* put transfer amount in request buffer */ (void)Fchg(reqfb,SAMOUNT,0,t_amts, (FLDLEN)0); /* Up the priority of deposit call */ if (tpsprio(PRIORITY, 0L) == -1) (void)userlog("Unable to increase priority of deposit\n"); /* Do a tpcall to deposit to second account */ if (tpcall("DEPOSIT", (char *)reqfb, 0, (char **)&reqfb, (long *)&reqlen, TPSIGRSTRT) == -1) { (void)Fchg(transf, STATLIN, 0, "Cannot deposit into credit account", (FLDLEN)0); tpfree((char *)reqfb); tpreturn(TPFAIL, 0,transb->data, 0L, 0); } /* get "credit" balance from return buffer */ (void)strcpy(cr_amts, Fvals((FBFR *)reqfb,SBALANCE,0)); (void)sscanf(cr_amts,"%f",&cr_bal); if ((cr_amts == NULL) || (cr_bal 0.0)) { (void)Fchg(transf, STATLIN, 0, "Illegal credit account balance", (FLDLEN)0); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } /* set buffer for successful return */ (void)Fchg(transf, FORMNAM, 0, "CTRANSFER", (FLDLEN)0);
5-22
(void)Fchg(transf, SAMOUNT, 0, Fvals(reqfb,SAMOUNT,0), (FLDLEN)0); (void)Fchg(transf, STATLIN, 0, "", (FLDLEN)0); (void)Fchg(transf, SBALANCE, 0, db_amts, (FLDLEN)0); (void)Fchg(transf, SBALANCE, 1, cr_amts, (FLDLEN)0); tpfree((char *)reqfb); tpreturn(TPSUCCESS, 0,transb->data, 0L, 0); }
Invalidating Descriptors
If a service calling tpgetrply() (described in detail in Writing Request/Response Clients and Servers on page 6-1) fails with TPETIME and decides to cancel the request, it can invalidate the descriptor with a call to tpcancel(3c). If a reply subsequently arrives, it is silently discarded. Use the following signature to call the tpcancel() function:
void tpcancel(int cd)
The cd (call descriptor) argument identifies the process you want to cancel.
tpcancel() cannot be used for transaction replies (that is, for replies to requests made without
the TPNOTRAN flag set). Within a transaction, tpabort(3c) does the same job of invalidating the transaction call descriptor. The following example shows how to invalidate a reply after timing out. Listing 5-8 Invalidating a Reply After Timing Out
int cd1; . . . if ((cd1=tpacall(sname, (char *)audv, sizeof(struct aud), TPNOTRAN)) == -1) { . . . } if (tpgetrply(cd1, (char **)&audv,&audrl, 0) == -1) {
5-23
Forwarding Requests
The tpforward(3c) function allows a service to forward a request to another service for further processing. Use the following signature to call the tpforward() function:
void tpforward(char *svc, char *data, long len, long flags)
5-24
Description
Character pointer to the name of the service to which the request is to be forwarded. Pointer to the reply message that is returned to the client process. The message buffer must have been allocated previously by tpalloc(). If you use the same buffer that was passed to the service in the SVCINFO structure, you need not be concerned with buffer allocation or disposition because both are handled by the system-supplied main(). You cannot free this buffer using the tpfree() command; any attempt to do so quietly fails. You can resize the buffer using the tprealloc() function. If you use another buffer (that is, a buffer other than the one that is passed to the service routine) to return the message, it is your responsibility to allocate it. The system frees the buffer automatically when the application calls the tpreturn() function. If no reply message needs to be returned, set this argument to the NULL pointer. Note: If no reply is expected by the client (that is, if TPNOREPLY was set), the tpreturn() function ignores the data and len arguments and returns control to main().
data
len
Length of the reply buffer. The application accesses the value of this argument through the olen parameter of the tpcall() function or the len parameter of the tpgetrply() function. Acting as the client, the process can use this returned value to determine whether the reply buffer has grown. If a reply is expected by the client and there is no data in the reply buffer (that is, if the data argument is set to the NULL pointer), the function sends a reply with zero length, without modifying the clients buffer. The system ignores the value of this argument if the data argument is not specified.
flag
The functionality of tpforward() differs from a service call: a service that forwards a request does not expect a reply. The responsibility for providing the reply is passed to the service to which the request has been forwarded. The latter service sends the reply to the process that originated
Programming an Oracle Tuxedo ATMI Application Using C 5-25
the request. It becomes the responsibility of the last server in the forward chain to send the reply to the originating client by invoking tpreturn(). The following figure shows one possible sequence of events when a request is forwarded from one service to another. Here a client initiates a request using the tpcall() function and the last service in the chain (SVC_C) provides a reply using the tpreturn() function. Figure 5-1 Forwarding a Request
Service routines can forward requests at specified priorities in the same manner that client processes send requests, by using the tpsprio() function. When a process calls tpforward(), the system-supplied main() regains control, and the server process is free to do more work. Note: If a server process is acting as a client and a reply is expected, the server is not allowed to request services from itself. If the only available instance of the desired service is offered by the server process making the request, the call fails, indicating that a recursive call cannot be made. However, if a service routine sends a request (to itself) with the TPNOREPLY communication flag set, or if it forwards the request, the call does not fail because the service is not waiting for itself. Calling tpforward() can be used to indicate success up to that point in processing the request. If no application errors have been detected, you can invoke tpforward(), otherwise, you can call tpreturn() with rval set to TPFAIL.
5-26
The following example is borrowed from the OPEN_ACCT service routine which is part of the ACCT server. This example illustrates how the service sends its data buffer to the DEPOSIT service by calling tpforward(). The code shows how to test the SQLCODE to determine whether the account insertion is successful. If the new account is added successfully, the branch record is updated to reflect the new account, and the data buffer is forwarded to the DEPOSIT service. On failure, tpreturn() is called with rval set to TPFAIL and the failure is reported on the status line of the form. Listing 5-9 tpforward( ) Function
... /* set pointer to TPSVCINFO data buffer */ transf = (FBFR *)transb->data; ... /* Insert new account record into ACCOUNT*/ account_id = ++last_acct; /* get new account number */ tlr_bal = 0.0; /* temporary balance of 0 */ EXEC SQL insert into ACCOUNT (ACCOUNT_ID, BRANCH_ID, BALANCE, ACCT_TYPE, LAST_NAME, FIRST_NAME, MID_INIT, ADDRESS, PHONE) values (:account_id, :branch_id, :tlr_bal, :acct_type, :last_name, :first_name, :mid_init, :address, :phone); if (SQLCODE != SQL_OK) { /* Failure to insert */ (void)Fchg(transf, STATLIN, 0, "Cannot update ACCOUNT", (FLDLEN)0); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } /* Update branch record with new LAST_ACCT */ EXEC SQL update BRANCH set LAST_ACCT = :last_acct where BRANCH_ID = :branch_id; if (SQLCODE != SQL_OK) { /* Failure to update */ (void)Fchg(transf, STATLIN, 0, "Cannot update BRANCH", (FLDLEN)0); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } /* up the priority of the deposit call */ if (tpsprio(PRIORITY, 0L) == -1) (void)userlog("Unable to increase priority of deposit\n"); /* tpforward same buffer to deposit service to add initial balance */ tpforward("DEPOSIT", transb->data, 0L, 0);
5-27
Advertising Services
Use the following signature to call the tpadvertise(3c) function:
int tpadvertise(char *svcname, void *func)
5-28
A dv e r ti s i ng a nd U na dv e r ti s i n g S e r v i c e s
Description
Pointer to the name of the service to be advertised. The service name must be a character string of up to 15 characters. Names longer than 15 characters are truncated. The NULL string is not a valid value. If it is specified, an error (TPEINVAL) results. Pointer to the address of an Oracle Tuxedo system function that is called to perform a service. Frequently, this name is the same as the name of the service. The NULL string is not a valid value. If it is specified, an error results.
func
Unadvertising Services
The tpunadvertise(3c) function removes the name of a service from the service table of the bulletin board so that the service is no longer advertised. Use the following signature for the tpunadvertise() function:
tpunadvertise(char *svcname) char *svcname;
The tpunadvertise() function contains one argument, which is described in the following table. Table 5-5 tpunadvertise( ) FunctionArguments Argument
svcname
Description
Pointer to the name of the service to be advertised. The service name must be a character string of up to 15 characters. Names longer than 15 characters are truncated. The NULL string is not a valid value. If it is specified, an error (TPEINVAL) results.
5-29
initialization, TLR_INIT advertises two services called DEPOSIT and WITHDRAW. Both are performed by the tlr_funcs function, and both are built into the TLR server. After advertising DEPOSIT and WITHDRAW, TLR_INIT unadvertises itself. Listing 5-10 Dynamic Advertising and Unadvertising
extern void tlr_funcs() . . . if (tpadvertise("DEPOSIT", (tlr_funcs)(TPSVCINFO *)) == -1) check for errors; if (tpadvertise("WITHDRAW", (tlr_funcs)(TPSVCINFO *)) == -1) check for errors; if (tpunadvertise("TLR_INIT") == -1) check for errors; tpreturn(TPSUCCESS, 0, transb->data,0L, 0);
Building Servers
To build an executable ATMI server, compile your application service subroutines with the Oracle Tuxedo system server adaptor and all other referenced files using the buildserver(1) command. Note: The Oracle Tuxedo server adaptor accepts messages, dispatches work, and manages transactions (if transactions are enabled). Use the following syntax for the buildserver command:
buildserver -o filename -f filenames -l filenames -s -v
5-30
Bu i l d i n g S e rv er s
-l filenames
-r filenames
-s [service:]function
-t
Specifies that the server is coded in a thread-safe manner and may be booted as multithreaded if specified as such in the configuration file.
Note: The Oracle Tuxedo libraries are linked in automatically. You do not need to specify the Oracle Tuxedo library names on the command line.
Programming an Oracle Tuxedo ATMI Application Using C 5-31
The order in which you specify the library files to be link edited is significant: it depends on the order in which functions are called and which libraries contain references to those functions. By default, the buildserver command invokes the UNIX cc command. You can specify an alternative compile command and set your own flags for the compile and link-edit phases, however, by setting the CC and CFLAGS environment variables, respectively. For more information, refer to Setting Environment Variables on page 2-5. The following command processes the acct.o application file and creates a server called ACCT that contains two services: NEW_ACCT, which calls the OPEN_ACCT function, and CLOSE_ACCT, which calls a function of the same name.
buildserver o ACCT f acct.o s NEW_ACCT:OPEN_ACCT s CLOSE_ACCT
See Also
Building Clients on page 4-8
buildclient(1) in the Oracle Tuxedo Command Reference
By declaring the name of your service with C linkage, you ensure that the C++ compiler will not modify the name. Many C++ compilers change the function name to include type information for the parameters and function return.
5-32
This declaration also allows you to: Link both C and C++ service routines into a single server without indicating the type of each routine. Use dynamic service advertisement, which requires accessing the symbol table of the executable to find the function name.
options that you want to include on the C++ command line by setting the CFLAGS environment variable. For more information, refer to Setting Environment Variables on page 2-5.
5-34
CHAPTER
This topic includes the following sections: Overview of Request/Response Communication Sending Synchronous Messages Sending Asynchronous Messages Setting and Getting Message Priorities
6-1
Once a client process has joined an application, allocated a buffer, and placed a request for input into that buffer, it can then send the request message to a service subroutine for processing and receive a reply message.
The following table describes the arguments to the tpcall() function. Table 6-1 tpcall( ) Function Arguments Argument
svc idata
Description
Pointer to the name of the service offered by your application. Pointer that contains the address of the data portion of the request. The pointer must reference a typed buffer that was allocated by a prior call to tpalloc(). Note that the type (and optionally the subtype) of idata must match the type (and optionally the subtype) expected by the service routine. If the types do not match, the system sets tperrno to TPEITYPE and the function call fails. If the request requires no data, set idata to the NULL pointer. This setting means that the parameter can be ignored. If no data is being sent with the request, you do not need to allocate a buffer for idata.
6-2
Description
Length of the request data in the buffer referenced by idata. If the buffer is a self-defining type, that is, an FML, FML32, VIEW, VIEW32, X_COMMON, X_C_TYPE, or STRING buffer, you can set this argument to zero to indicate that the argument should be ignored. Address of a pointer to the output buffer that receives the reply. You must allocate the output buffer using the tpalloc() function. If the reply message contains no data, upon successful return from tpcall(), the system sets *olen to zero, and the pointer and the contents of the output buffer remain unchanged. You can use the same buffer for both the request and reply messages. If you do, you must set *odata to the address of the pointer returned when you allocate the input buffer. It is an error for this parameter to point to NULL.
*odata
olen
Pointer to the length of the reply data. It is an error for this parameter to point to NULL. Flag options. You can OR a series of flags together. If you set this value to zero, the communication is conducted in the default manner. For a list of valid flags and the defaults, refer to tpcall(3c) in the Oracle Tuxedo ATMI C Function Reference.
flags
Note: Calling the tpcall() function is logically the same as calling the tpacall() function immediately followed by tpgetrply(), as described in Sending Asynchronous Messages on page 6-11. The request carries the priority set by the system for the specified service (svc) unless a different priority has been explicitly set by a call to the tpsprio() function (described in Setting and Getting Message Priorities on page 6-16).
tpcall() returns an integer. On failure, the value of this integer is -1 and the value of tperrno(5) is set to a value that reflects the type of error that occurred. For information on valid error codes, refer to tpcall(3c) in the Oracle Tuxedo ATMI C Function Reference.
Note: Communication calls may fail for a variety of reasons, many of which can be corrected at the application level. Possible causes of failure include: application defined errors (TPESVCFAIL), errors in processing return arguments (TPESVCERR), typed buffer errors
Programming an Oracle Tuxedo ATMI Application Using C 6-3
(TPEITYPE, TPEOTYPE), timeout errors (TPETIME), and protocol errors (TPEPROTO), among others. For a detailed discussion of errors, refer to Managing Errors on page 11-1. For a complete list of possible errors, refer to tpcall(3c) in the Oracle Tuxedo ATMI C Function Reference. The Oracle Tuxedo system automatically adjusts a buffer used for receiving a message if the received message is too large for the allocated buffer. You should test for whether or not the reply buffers have been resized. To access the new size of the buffer, use the address returned in the *olen parameter. To determine whether a reply buffer has changed in size, compare the size of the reply buffer before the call to tpcall() with the value of *olen after its return. If *olen is larger than the original size, the buffer has grown. If not, the buffer size has not changed. You should reference the output buffer by the value returned in odata after the call because the output buffer may change for reasons other than an increase in buffer size. You do not need to verify the size of request buffers because the request data is not adjusted once it has been allocated. Note: If you use the same buffer for the request and reply message, and the pointer to the reply buffer has changed because the system adjusted the size of the buffer, then the input buffer pointer no longer references a valid address.
Example: Using the Same Buffer for Request and Reply Messages
The following example shows how the client program, audit.c, makes a synchronous call using the same buffer for both the request and reply messages. In this case, using the same buffer is appropriate because the *audv message buffer has been set up to accommodate both request and reply information. The following actions are taken in this code: 1. The service queries the b_id field, but does not overwrite it. 2. The application initializes the bal and ermsg fields to zero and the NULL string, respectively, in preparation for the values to be returned by the service. 3. The svc_name and hdr_type variables represent the service name and the balance type requested, respectively. In this example, these variables represent account and teller, respectively.
6-4
Listing 6-1 Using the Same Buffer for Request and Reply Messages
. . . /* Create buffer and set data pointer */ audv = (struct aud *)tpalloc("VIEW", "aud", sizeof(struct aud)); /* Prepare aud structure */ audv->b_id = q_branchid; audv->balance = 0.0; (void)strcpy(audv->ermsg, ""); /* Do tpcall */ if (tpcall(svc_name,(char *)audv,sizeof(struct aud), (char **)&audv,(long *)&audrl,0)== -1){ (void)fprintf (stderr, "%s service failed\n %s: %s\n", svc_name, svc_name, audv->ermsg); retc = -1; } else (void)printf ("Branch %ld %s balance is $%.2f\n", audv->b_id, hdr_type, audv->balance); . . .
6-5
. . . if (idata = tpalloc("STRING", NULL, 0) == NULL) error if (odata = tpalloc("STRING", NULL, 0) == NULL) error place string value into idata buffer ilen = olen = strlen(idata)+1; . . . bef_len = olen; if (tpcall(svc, idata, ilen, &odata, &olen, flags) == -1) error aft_len = olen; if (aft_len > bef_len){ /* message buffer has grown */
6-6
6-7
start transaction if (tpcall("REPORT", rbuf, r1len, &rbuf, &r2len, 0) == -1) error routine &r3len, TPNOTRAN) == -1) error routine rbuf); terminate transaction free buffer leave application } /* get report print stream */
6-8
Note: In the preceding example, the term error routine indicates that the following tasks are performed: an error message is printed, the transaction is aborted, allocated buffers are freed, the client leaves the application, and the program is exited.
/* report buffer */ /* report reply buffer */ /* buffer lengths of send and reply buffers for report */
6-9
if (tpinit((TPINIT *) tpinfo) == -1) fprintf(stderr, "%s: failed to join application\n", argv[0]); if (rbuf = tpalloc("STRING", NULL, 0) == NULL) { /* allocate space for report */ tpterm(); exit(1); } /* allocate space for return buffer */ if (rrbuf = (struct rview1 *)tpalloc("VIEW", "rview1", sizeof(struct rview1)) \ == NULL{ tpfree(rbuf); tpterm(); exit(1); } (void)strcpy(rbuf, "REPORT=accrcv DBNAME=accounts FORMAT=rview1"); rlen = strlen(rbuf)+1; /* length of request */ /* get report in rview1 struct */
if (tpcall("REPORT", rbuf, rlen, (char **)&rrbuf, &rrlen, TPNOCHANGE) == -1) { fprintf(stderr, "accounts receivable report failed in service call\n"); if (tperrno == TPEOTYPE) fprintf(stderr, "report returned has wrong view type\n"); tpfree(rbuf); tpfree(rrbuf); tpterm(); exit(1); } (void)printf("Total accounts receivable %6d\n", rrbuf->total); (void)printf("Largest three outstanding %-20s %6d\n", rrbuf->name1, rrbuf->amt1); (void)printf("%-20s %6d\n", rrbuf->name2, rrbuf->amt2); (void)printf("%-20s %6d\n", rrbuf->name3, rrbuf->amt3); tpfree(rbuf); tpfree(rrbuf); tpterm(); }
6-10
6-11
Description
Pointer to the name of the service offered by your application. Pointer that contains the address of the data portion of the request. The pointer must reference a typed buffer that was allocated by a prior call to tpalloc(). Note that the type (and optionally the subtype) of idata must match the type (and optionally the subtype) expected by the service routine. If the types do not match, the system sets tperrno to TPEITYPE and the function call fails. If the request requires no data, set data to the NULL pointer. This setting means that the parameter can be ignored. If no data is being sent with the request, you do not need to allocate a buffer for data.
len
Length of the request data in the buffer referenced by data. If the buffer is a self-defining type, that is, an FML, FML32, VIEW, VIEW32, X_COMMON, X_C_TYPE, or STRING buffer, you can set this argument to zero, indicating that the argument should be ignored. Flag options. You can list a group of flags by using the logical OR operator. If you set this value to zero, the communication is conducted in the default manner. For a list of valid flags and defaults, refer to tpacall(3c) in the Oracle Tuxedo ATMI C Function Reference.
flags
The tpacall() function sends a request message to the service named in the svc parameter and immediately returns from the call. Upon successful completion of the call, the tpacall() function returns an integer that serves as a descriptor used to access the correct reply for the relevant request. While tpacall() is in transaction mode (as described in Writing Global Transactions on page 9-1) there may not be any outstanding replies when the transaction commits; that is, within a given transaction, for each request for which a reply is expected, a corresponding reply must eventually be received. If the value TPNOREPLY is assigned to the flags parameter, the parameter signals to tpacall() that a reply is not expected. When this flag is set, on success tpacall() returns a value of 0 as the reply descriptor. If subsequently passed to the tpgetrply() function, this value becomes invalid. Guidelines for using this flag value correctly when a process is in transaction mode are discussed in Writing Global Transactions on page 9-1. On error, tpacall() returns -1 and sets tperrno(5) to a value that reflects the nature of the error. tpacall() returns many of the same error codes as tpcall(). The differences between
6-12 Programming an Oracle Tuxedo ATMI Application Using C
the error codes for these functions are based on the fact that one call is synchronous and the other, asynchronous. These errors are discussed at length in Managing Errors on page 11-1.
6-13
error if (tpacall("PRINTER", rbuf, rrlen, TPNOTRAN|TPNOREPLY) == -1) /* send report to printer */ error . . . commit transaction free buffer leave application }
6-14
(void)fprintf (stderr, "%s: %s service request failed for site rep %ld\n", pgmname, sname, sitelist[i]); tpfree((char *)audv); return(-1); } }
The following table describes the arguments to the tpgetrply() function. Table 6-3 tpgetrply( ) Function Arguments Argument
cd *data
Description
Pointer to the call descriptor returned by the tpacall() function. Address of a pointer to the output buffer that receives the reply. You must allocate the output buffer using the tpalloc() function. If the reply message contains no data, upon successful return from tpcall(), the system sets *data to zero. The pointer and the contents of the output buffer remain unchanged. You can use the same buffer for both the request and reply messages. If you do, then you must set odata to the address of the pointer returned when you allocated the input buffer. It is an error for this parameter to point to NULL.
6-15
Description
Pointer to the length of the reply data. It is an error for this parameter to point to NULL. Flag options. You can list a group of flags using the logical OR operator. If you set this value to zero, the communication is conducted in the default manner. For a list of valid flags and defaults, refer to tpcall(3c)) in the Oracle Tuxedo ATMI C Function Reference.
flags
By default, the function waits for the arrival of the reply that corresponds to the value referenced by the cd parameter. During this waiting interval, a blocking timeout may occur. A time-out occurs when tpgetrply() fails and tperrno(5) is set to TPETIME (unless the flags parameter is set to TPNOTIME).
6-16
Description
Integer indicating a new priority value. The effect of this argument is controlled by the flags parameter. If flags is set to 0, prio specifies a relative value and the sign accompanying the value indicates whether the current priority is incremented or decremented. Otherwise, the value specified indicates an absolute value and prio must be set to a value between 0 and 100. If you do not specify a value within this range, the system sets the value to 50. Flag indicating whether the value of prio is treated as a relative value (0, the default) or an absolute value (TPABSOLUTE).
flags
The following sample code is an excerpt from the TRANSFER service. In this example, the TRANSFER service acts as a client by sending a synchronous request, via tpcall(), to the WITHDRAWAL service. TRANSFER also invokes tpsprio() to increase the priority of its request message to WITHDRAWAL, and to prevent the request from being queued for the WITHDRAWAL service (and later the DEPOSIT service) after waiting on the TRANSFER queue. Listing 6-8 Setting the Priority of a Request Message
/* increase the priority of withdraw call */ if (tpsprio(PRIORITY, 0L) == -1) (void)userlog("Unable to increase priority of withdraw\n"); if (tpcall("WITHDRAWAL", (char *)reqfb,0, (char **)&reqfb, (long *) \ &reqlen,TPSIGRSTRT) == -1) { (void)Fchg(transf, STATLIN, 0, "Cannot withdraw from debit account", \ (FLDLEN)0); tpfree((char *)reqfb); tpreturn(TPFAIL, 0,transb->data, 0L, 0); }
6-17
A requester can call the tpgprio() function after invoking the tpcall() or tpacall() function to retrieve the priority of the request message. If a requester calls the function but no request is sent, the function fails, returning -1 and setting tperrno(5) to TPENOENT. Upon success, tpgprio() returns an integer value in the range of 1 to 100 (where the highest priority value is 100). If a priority has not been explicitly set using the tpsprio() function, the system sets the message priority to that of the service routine that handles the request. Within an application, the priority of the request-handling service is assigned a default value of 50 unless a system administrator overrides this value. The following example shows how to determine the priority of a message that was sent in an asynchronous call. Listing 6-9 Determining the Priority of a Request After It Is Sent
#include <stdio.h> #include "atmi.h" main () { int cd1, cd2; int pr1, pr2; char *buf1, *buf2; long buf1len, buf2len; join application if (buf1=tpalloc("FML", NULL, 0) == NULL) error if (buf2=tpalloc("FML", NULL, 0) == NULL) /* call descriptors */ /* priorities to two calls */ /* buffers */ /* buffer lengths */
6-18
error populate FML buffers with send request if ((cd1 = tpacall("service1", buf1, 0, 0)) == -1) error if ((pr1 = tpgprio()) == -1) error if ((cd2 = tpacall("service2", buf2, 0, 0)) == -1) error if ((pr2 = tpgprio()) == -1)\ error if (pr1 >= pr2) { /* base the order of tpgetrplys on priority of calls */
if (tpgetrply(&cd1, &buf1, &buf1len, 0) == -1) error if (tpgetrply(&cd2, &buf2, &buf2len, 0) == -1) error } else { if (tpgetrply(&cd2, &buf2, &buf2len, 0) == -1) error if (tpgetrply(&cd1, &buf1, &buf1len, 0) == -1) error } . . . }
6-19
6-20
CHAPTER
This topic includes the following sections: Overview of Conversational Communication Joining an Application Establishing a Connection Sending and Receiving Messages Ending a Conversation Building Conversational Clients and Servers Understanding Conversational Communication Events
7-1
subordinate. The process that has control can send messages; the process that does not have control can only receive messages. To understand how conversational communication works in an Oracle Tuxedo ATMI application, consider the following example from an online banking application. In this example, a bank customer requests checking account statements for the past two months. Figure 7-1 Example of Conversational Communication in an Online Banking Application
1. The customer requests the checking account statements for the past two months. 2. The Account Records Storage System responds by sending the first months checking account statement followed by a More prompt for accessing the remaining months statement. 3. The customer requests the second months account statement by selecting the More prompt. Note: The Account Records Storage System must maintain state information so it knows which account statement to return when the customer selects the More prompt. 4. The Account Records Storage System sends the remaining months account statement. As with request/response communication, the Oracle Tuxedo system passes data using typed buffers. The buffer types must be recognized by the application. For more information on buffer types, refer to Overview of Typed Buffers on page 3-1. Conversational clients and servers have the following characteristics: The logical connection between them remains active until terminated. Any number of messages can be transmitted across a connection between them. Both clients and servers use the tpsend() and tprecv() routines to send and receive data in conversations. Conversational communication differs from request/response communication in the following ways:
7-2 Programming an Oracle Tuxedo ATMI Application Using C
A conversational client initiates a request for service using tpconnect() rather than tpcall() or tpacall(). A conversational client sends a service request to a conversational server. The configuration file reserves part of the conversational server for addressing conversational services. Conversational servers are prohibited from making calls using tpforward().
Joining an Application
A conversational client must join an application via a call to tpinit() before attempting to establish a connection to a service. For more information, refer to Writing Clients on page 4-1.
Establishing a Connection
The tpconnect(3c) function sets up a conversation: Use the following signature to call the tpconnect() function.
int tpconnect(char *name, char *data, long len, long flags)
7-3
Description
Character pointer to a conversational service name. If you do not specify name as a pointer to a conversational service, the call fails with a value of -1 and tperrno is set to the error code TPENOENT. Pointer to a data buffer. When establishing the connection, you can send data simultaneously by setting the data argument to point to a buffer previously allocated by tpalloc(). The type and subtype of the buffer must be types recognized by the service being called. You can set the value of data to NULL to specify that no data is to be sent. The conversational service being called receives the data and len pointers via the TPSVCINFO data structure passed to it by main() when the service is invoked. (A request/response service receives the data and len pointers in the same way.) For more information on the TPSVCINFO data structure, refer to Defining a Service on page 5-9.
data
len
Length of the data buffer. If the buffer is self-defining (for example, an FML buffer), you can set len to 0. Specifies the flag settings. For a complete list of valid flag settings, refer to tpconnect(3c) in the Oracle Tuxedo ATMI C Function Reference. The system notifies the called service through the flag members of the TPSVCINFO structure.
flag
The Oracle Tuxedo system returns a connection descriptor (cd) when a connection is established with tpconnect(). The cd is used to identify subsequent message transmissions with a particular conversation. A client or conversational service can participate in more than one conversation simultaneously. The maximum number of simultaneous conversations is 64. In the event of a failure, the tpconnect() function returns a value of -1 and sets tperrno to the appropriate error condition. For a list of possible error codes, refer to tpconnect(3c) in the Oracle Tuxedo ATMI C Function Reference. The following example shows how to use the tpconnect() function.
7-4
Sending Messages
To send a message, use the tpsend(3c) function with the following signature:
int tpsend(int cd, char *data, long len, long flags, long *revent)
7-5
Description
Specifies the connection descriptor returned by the tpconnect() function identifying the connection over which the data is sent. Pointer to a data buffer. When establishing the connection, you can send data simultaneously by setting the data argument to point to a buffer previously allocated by tpalloc(). The type and subtype of the buffer must be types recognized by the service being called. You can set the value of data to NULL to specify that no data is to be sent. The conversational service being called receives the data and len pointers via the TPSVCINFO data structure passed to it by main() when the service is invoked. (A request/response server receives the data and len pointers in the same way.) For more information on the TPSVCINFO data structure, refer to Defining a Service on page 5-9.
data
len
Length of the data buffer. If the buffer is self-defining (for example, an FML buffer), you can set len to 0. If you do not specify a value for data, this argument is ignored. Pointer to event value set when an error is encountered (that is, when tperrno(5) is set to TPEEVENT). For a list of valid event values, refer to tpsend(3c) in the Oracle Tuxedo ATMI C Function Reference. Specifies the flag settings. For a list of valid flag settings, refer to tpsend(3c) in the Oracle Tuxedo ATMI C Function Reference.
revent
flag
In the event of a failure, the tpsend() function returns a value of -1 and sets tperrno(5) to the appropriate error condition. For a list of possible error codes, refer to tpsend(3c) in the Oracle Tuxedo ATMI C Function Reference. You are not required to pass control each time you issue the tpsend() function. In some applications, the process authorized to issue tpsend() calls can execute as many calls as required by the current task before turning over control to the other process. In other applications, however, the logic of the program may require the same process to maintain control of the connection throughout the life of the conversation. The following example shows how to invoke the tpsend() function.
7-6
Listing 7-2
if (tpsend(cd,line,0,TPRECVONLY,revent) == -1) { (void)userlog(%s: tpsend failed tperrno %d, argv[0],tperrno); (void)tpabort(0); (void)tpterm(); exit(1); }
Receiving Messages
To receive data sent over an open connection, use the tprecv(3c) function with the following signature:
int tprecv(int cd, char **data, long *len, long flags, long *revent)
Argument
cd
Description
Specifies the connection descriptor. If a subordinate program issues the call, the cd argument should be set to the value specified in the TPSVCINFO structure for the program. If the originator program issues the call, the cd argument should be set to the value returned by the tpconnect() function. Pointer to a data buffer. The data argument must point to a buffer previously allocated by tpalloc(). The type and subtype of the buffer must be types recognized by the service being called. This value cannot be NULL; if it is, the call fails and tperrno(5) is set to TPEINVAL. The conversational service being called receives the data and len pointers via the TPSVCINFO data structure passed to it by main() when the service is invoked. (A request/response service receives the data and len pointers in the same way.) For more information on the TPSVCINFO data structure, refer to Defining a Service on page 5-9.
data
7-7
Argument
len
Description
Length of the data buffer. If the buffer is self-defining (for example, an FML buffer), you can set len to 0. This value cannot be NULL; if it is, the call fails and tperrno(5) is set to TPEINVAL. Pointer to event value set when an error is encountered (that is, when tperrno is set to TPEEVENT). Refer to tprecv(3c) in the Oracle Tuxedo ATMI C Function Reference for a list of valid event values. Specifies the flag settings. Refer to tprecv(3c) in the Oracle Tuxedo ATMI C Function Reference for a list of valid flags.
revent
flag
Upon success, the *data argument points to the data received and len contains the size of the buffer. If len is greater than the total size of the buffer before the call to tprecv(), the buffer size has changed and len indicates the new size. A value of 0 for the len argument indicates that no data was received. The following example shows how to use the tprecv() function. Listing 7-3 Receiving Data in Conversation
if (tprecv(cd,line,len,TPNOCHANGE,revent) != -1) { (void)userlog(%s: tprecv failed tperrno %d revent %ld, argv[0],tperrno,revent); (void)tpabort(0); (void)tpterm(); exit(1); }
Ending a Conversation
A connection can be taken down gracefully and a conversation ended normally through: A successful call to tpreturn() in a simple conversation. A series of successful calls to tpreturn() in a complex conversation based on a hierarchy of connections.
7-8 Programming an Oracle Tuxedo ATMI Application Using C
En di ng a Conv er sat io n
Global transactions, as described in Writing Global Transactions on page 9-1. Note: The tpreturn() function is described in detail in Writing Request/Response Clients and Servers on page 6-1. The following sections describe two scenarios for gracefully terminating conversations that do not include global transactions in which the tpreturn() function is used. The first example shows how to terminate a simple conversation between two components. The second example illustrates a more complex scenario, with a hierarchical set of conversations. If you end a conversation with connections still open, the system returns an error. In this case, either tpcommit() or tpreturn() fails in a disorderly manner.
The program flow is as follows: 1. A sets up the connection by calling tpconnect() with the TPSENDONLY flag set, indicating that process B is on the receiving end of the conversation. 2. A turns control of the connection over to B by calling tpsend() with the TPRECVONLY flag set, resulting in the generation of a TPEV_SENDONLY event. 3. The next call by B to tprecv() returns a value of -1, sets tperrno(5) to TPEEVENT, and returns TPEV_SENDONLY in the revent argument, indicating that control has passed to B. 4. B calls tpreturn() with rval set to TPSUCCESS. This call generates a TPEV_SVCSUCC event for A and gracefully brings down the connection.
7-9
5. A calls tprecv(), learns of the event, and recognizes that the conversation has been terminated. Data can be received on this call to tprecv() even if the event is set to TPEV_SVCFAIL. Note: In this example, A can be either a client or a server, but B must be a server.
In the preceding example, service B is a member of a conversation that has initiated a connection to a second service called C. In other words, there are two active connections: A-to-B and B-to-C. If B is in control of both connections, a call to tpreturn() has the following effect: the call fails, a TPEV_SVCERR event is posted on all open connections, and the connections are closed in a disorderly manner. In order to terminate both connections normally, an application must execute the following sequence:
7-10
B ui l din g C o nv e r s at i o na l C l i e nt s a nd S e r v e r s
1. B calls tpsend() with the TPRECVONLY flag set on the connection to C, transferring control of the B-to-C connection to C. 2. C calls tpreturn() with rval set to TPSUCCESS, TPFAIL, or TPEXIT, as appropriate. 3. B can then call tpreturn(), posting an event (either TPEV_SVCSUCC or TPEV_SVCFAIL) for A. Note: It is legal for a conversational service to make request/response calls if it needs to do so to communicate with another service. Therefore, in the preceding example, the calls from B to C may be executed using tpcall() or tpacall() instead of tpconnect(). Conversational services are not permitted to make calls to tpforward().
The cd argument specifies the connection descriptor returned by the tpconnect() function when the connection is established. The tpdiscon() function generates a TPEV_DISCONIMM event for the service at the other end of the connection, rendering the cd invalid. If a transaction is in progress, the system aborts it and data may be lost. If tpdiscon() is called from a service that was not the originator of the connection identified by cd, the function fails with an error code of TPEBADDESC. For a list and descriptions of all event and error codes, refer to tpdiscon(3c) in the Oracle Tuxedo ATMI C Function Reference.
7-11
For conversational and request/response services, you cannot: Build both in the same server Assign the same name to both
Received By
tprecv()
Description
Control of the connection has been passed; this process can now call tpsend(). The connection has been torn down and no further communication is possible. The tpdiscon() function posts this event in the originator of the connection, and sends it to all open connections when tpreturn() is called, as long as connections to subordinate services remain open. Connections are closed in a disorderly fashion. If a transaction exists, it is aborted. Received by the originator of the connection, usually indicating that the subordinate program issued a tpreturn() without having control of the connection. Received by the originator of the connection, indicating that the subordinate program issued a tpreturn() with TPSUCCESS or TPFAIL and a valid data buffer, but an error occurred that prevented the call from completing.
TPEV_DISCONIMM
TPEV_SVCERR
tpsend()
tprecv()
7-12
Received By
tpsend()
Description
Received by the originator of the connection, indicating that the subordinate program issued a tpreturn() without having control of the connection, and tpreturn() was called with TPFAIL or TPEXIT and no data. Received by the originator of the connection, indicating that the subordinate service finished unsuccessfully (tpreturn() was called with TPFAIL or TPEXIT). Received by the originator of the connection, indicating that the subordinate service finished successfully; that is, it called tpreturn() with TPSUCCESS.
tprecv()
TPEV_SVCSUCC
tprecv()
7-13
7-14
CHAPTER
This topic includes the following sections: Overview of Events Defining the Unsolicited Message Handler Sending Unsolicited Messages Checking for Unsolicited Messages Subscribing to Events Unsubscribing from Events Posting Events Example of Event Subscription
Overview of Events
Event-based communication provides a method for an Oracle Tuxedo system process to be notified when a specific situation (event) occurs. The Oracle Tuxedo system supports two types of event-based communication: Unsolicited events Brokered events
8-1
Unsolicited Events
Unsolicited events are messages used to communicate with client programs that are not waiting for and/or expecting a message.
Brokered Events
Brokered events enable a client and a server to communicate transparently with one another via an anonymous broker that receives and distributes messages. Such brokering is another client/server communication paradigm that is fundamental to the Oracle Tuxedo system. The EventBroker is an Oracle Tuxedo subsystem that receives and filters event posting messages, and distributes them to subscribers. A poster is an Oracle Tuxedo system process that detects when a specific event has occurred and reports (posts) it to the EventBroker. A subscriber is an Oracle Tuxedo system process with a standing request to be notified whenever a specific event has been posted. The Oracle Tuxedo system does not impose a fixed ratio of service requesters to service providers; an arbitrary number of posters can post a message buffer for an arbitrary number of subscribers. The posters simply post events, without knowing which processes receive the information or how the information is handled. Subscribers are notified of specified events, without knowing who posted the information. In this way, the EventBroker provides complete location transparency. Typically, EventBroker applications are designed to handle exception events. An application designer must decide which events in the application constitute exception events and need to be monitored. In a banking application, for example, it might be useful to post an event whenever an unusually large amount of money is withdrawn, but it would not be particularly useful to post an event for every withdrawal transaction. In addition, not all users would need to subscribe to that event; perhaps only the branch manager would need to be notified.
Notification Actions
The EventBroker may be configured such that whenever an event is posted, the EventBroker invokes one or more notification actions for clients and/or servers that have subscribed. The following table lists the types of notification actions that the EventBroker can take.
8-2
Description
Clients may receive event notification messages in their unsolicited message handling routine, just as if they were sent by the tpnotify() function. Servers may receive event notification messages as input to service routines, just as if they were sent by the tpacall() function. Event notification messages may be stored in an Oracle Tuxedo system reliable queue, using the tpenqueue(3c) function. Event notification buffers are stored until requests for buffer contents are issued. An Oracle Tuxedo system client or server process may call the tpdequeue(3c) function to retrieve these notification buffers, or alternately TMQFORWARD(5) may be configured to automatically dispatch an Oracle Tuxedo system service routine that retrieves a notification buffer. For more information on /Q, see Using the ATMI /Q Component.
Service call
Reliable queue
In addition, the application administrator may create an EVENT_MIB(5) entry (by using the Oracle Tuxedo administrative API) that performs the following notification actions: Invokes a system command Writes a message to the systems log file on disk Note: Only the Oracle Tuxedo application administrator is allowed to create an EVENT_MIB(5) entry. For information on the EVENT_MIB(5), refer to the File Formats, Data Descriptions, MIBs, and System Processes Reference.
EventBroker Servers
TMUSREVT is the Oracle Tuxedo system-supplied server that acts as an EventBroker for user
events. TMUSREVT processes event report message buffers, and then filters and distributes them. The Oracle Tuxedo application administrator must boot one or more of these servers to activate event brokering.
TMSYSEVT is the Oracle Tuxedo system-supplied server that acts as an EventBroker for system-defined events. TMSYSEVT and TMUSREVT are similar, but separate servers are provided to allow the application administrator the ability to have different replication strategies for
8-3
processing notifications of these two types of events. Refer to Setting Up an Oracle Tuxedo Application for additional information.
System-defined Events
The Oracle Tuxedo system itself detects and posts certain predefined events related to system warnings and failures. These tasks are performed by the EventBroker. For example, system-defined events include configuration changes, state changes, connection failures, and machine partitioning. For a complete list of system-defined events detected by the EventBroker, see EVENTS(5) in the File Formats, Data Descriptions, MIBs, and System Processes Reference. System-defined events are defined in advance by the Oracle Tuxedo system code and do not require posting. The name of a system-defined event, unlike that of an application-defined event, always begins with a dot (.). Names of application-defined events may not begin with a leading dot. Clients and servers can subscribe to system-defined events. These events, however, should be used mainly by application administrators, not by every client in the application. When incorporating the EventBroker into your application, remember that it is not intended to provide a mechanism for high-volume distribution to many subscribers. Do not attempt to post an event for every activity that occurs, and do not expect all clients and servers to subscribe. If you overload the EventBroker, system performance may be adversely affected and notifications may be dropped. To minimize the possibility of overload, the application administrator should carefully tune the operating system IPC resources, as explained in Installing the Oracle Tuxedo System.
8-4
If you are running on Windows-based operating systems you must declare unsolicited message handler functions as:
void _TMDLLENTRY CustomerUnsolFunc(char *data, long len, long flags)
The _TMDLLENTRY macro is required for Windows-based operating systems to obtain the proper calling conventions between the Tuxedo libaries and your code. On Unix systems, the _TMDLLENTRY macro is not required because it expands to the null string. The following table describes the single argument that can be passed to the tpsetunsol() function. Table 8-2 tpsetunsol( ) Function Argument Argument
myfunc
Description
Pointer to a function that conforms to the prototype of a call-back function. In order to conform, the function must accept the following three parameters:
datapoints to the typed buffer that contains the unsolicited message lenlength of the buffer flagscurrently not used
When a client receives an unsolicited notification, the system dispatches the call-back function with the message. To minimize task disruption, you should code the unsolicited message handler function to perform only minimal processing tasks, so it can return quickly to the waiting process.
8-5
Unsolicited messages can be sent to client processes by name, using tpbroadcast(3c), or by an identifier received with a previously processed message, using tpnotify(3c). Messages sent via tpbroadcast() can originate either in a service or in another client. Messages sent via tpnotify() can originate only in a service.
The following table describes the arguments to the tpbroadcast() function. Table 8-3 tpbroadcast( ) Function Arguments Argument
lmid
Description
Pointer to the logical machine identifier for the client. A value of NULL acts as a wildcard, so that a message can be directed to groups of clients. Pointer to the username of the client process, if one exists. A value of NULL acts as a wildcard, so that a message can be directed to groups of clients. Pointer to the client name of the client process, if one exists. A value of NULL acts as a wildcard, so that a message can be directed to groups of clients. Pointer to the content of a message. Size of the message buffer. If data points to a self-defining buffer type, for example, FML, then len can be set to 0. Flag options. Refer to tpbroadcast(3c) in the Oracle Tuxedo ATMI C Function Reference for information on available flags.
usrname
cltname
data len
flags
The following example illustrates a call to tpbroadcast() for which all clients are targeted. The message to be sent is contained in a STRING buffer.
8-6
The following table describes the arguments to the tpnotify() function. Table 8-4 tpnotify( ) Function Arguments Argument
clientid
Description
Pointer to a CLIENTID structure that is saved from the TPSVCINFO structure that accompanied the request to this service. Pointer to the content of the message. Size of the message buffer. If data points to a self-defining buffer type, for example, FML, then len can be set to 0. Flag options. Refer to tpnotify(3c) in the Oracle Tuxedo ATMI C Function Reference for information on available flags.
data len
flags
8-7
The function takes no arguments. If any messages are pending, the system invokes the unsolicited message handling function that was specified using tpsetunsol(). Upon completion, the function returns either the number of unsolicited messages that were processed or -1 on error. If you issue this function when the client is running in SIGNAL-based, thread-based notification mode, or is ignoring unsolicited messages, the function has no impact and returns immediately.
Subscribing to Events
The tpsubscribe(3c) function enables an Oracle Tuxedo system ATMI client or server to subscribe to an event. A subscriber can be notified through an unsolicited notification message, a service call, a reliable queue, or other notification methods configured by the application administrator. (For information about configuring alternative notification methods, refer to Setting Up an Oracle Tuxedo Application.) Use the following signature to call the tpsubscribe() function:
long handle tpsubscribe (char *eventexpr, char *filter, TPEVCTL *ctl, long flags)
8-8
Description
Pointer to a set of one or more events to which a process can subscribe. Consists of a NULL-terminated string of up to 255 characters containing a regular expression. Regular expressions are of the form specified in tpsubscribe(3c), as described in the Oracle Tuxedo ATMI C Function Reference). For example, if eventexpr is set to:
"\\..*"the caller is subscribing to all system-defined events. "\\.SysServer.*"the caller is subscribing to all system-defined events related to servers. "[A-Z].*"the caller is subscribing to all user events starting with any uppercase letter between A and Z. ".*(ERR|err).*"the caller is subscribing to all user events with names that contain either err or ERR, such as the account_error and ERROR_STATE events, respectively.
filter
Pointer to a string containing a Boolean filter rule that must be evaluated successfully before the EventBroker posts the event. Upon receiving an event to be posted, the EventBroker applies the filter rule, if one exists, to the posted events data. If the data passes the filter rule, the EventBroker invokes the notification method specified; otherwise, the EventBroker ignores the notification method. The caller can subscribe to the same event multiple times with different filter rules. By using the event-filtering capability, subscribers can discriminate among the events about which they are notified. For example, a poster can post an event for withdrawals greater than $10,000, but a subscriber may want to specify a higher threshold for being notified, such as $50,000. Or, a subscriber may want to be notified of large withdrawals made by specific customers. Filter rules are specific to the typed buffers to which they are applied. For more information on filter rules, refer to tpsubscribe(3c) in the Oracle Tuxedo ATMI C Function Reference.
8-9
Description
Pointer to a flag for controlling how a subscriber is notified of an event. Valid values include: NULLsends unsolicited messages. Refer to Notification via Unsolicited Message on page 8-10 for more information. Pointer to a valid TPEVCTL structuresends information based on the TPEVCTL structure. Refer to Notification via Service Call or Reliable Queue on page 8-10 for more information.
flags
Flag options. For more information on available flag options, refer to tpsubscribe(3c) in the Oracle Tuxedo ATMI C Function Reference.
You can subscribe to both system- and application-defined events using the tpsubscribe() function. For purposes of subscriptions (and for MIB updates), service routines executed in an Oracle Tuxedo system server process are considered to be trusted code.
8-10
reliable queue ensures that event data is not lost. It also provides the subscriber the flexibility of retrieving the event data at any time. If the subscriber (either a client or a server process) wants event notifications sent to service routines or to stable-storage queues, then the ctl parameter of tpsubscribe() must point to a valid TPEVCTL structure. The TPEVCTL structure contains the following elements:
long char char flags; name1[32]; name2[32];
TPQCTL qctl;
The following table summarizes the TPEVCTL typed buffer data structure. Table 8-6 TPEVCTL Typed Buffer Format Field
flags
Description
Flag options. For more information on flags, refer to tpsubscribe(3c) in the Oracle Tuxedo ATMI C Function Reference. Character string of 32 characters or fewer. Character string of 32 characters or fewer.
TPQCTL structure. For more information, refer to tpsubscribe(3c) in the Oracle Tuxedo ATMI C Function Reference.
8-11
Description
Subscription handle returned by a call to tpsubscribe(). Flag options. For more information on available flag options, refer to tpunsubscribe(3c) in the Oracle Tuxedo ATMI C Function Reference.
Posting Events
The tppost(3c) function enables an Oracle Tuxedo ATMI client or server to post an event. Use the following signature to call the tppost() function:
tppost(char *eventname, char *data, long len, long flags)
The following table describes the arguments to the tppost() function. Table 8-8 tppost( ) Function Arguments Argument
eventname
Description
Pointer to an event name containing up to 31 characters plus NULL. The first character cannot be a dot (.) because the dot is reserved as the first character in names of Oracle Tuxedo system-defined events. When defining event names, keep in mind that subscribers can use wildcard capabilities to subscribe to multiple events with a single function call. Using the same prefix for a category of related event names can be helpful. Pointer to a buffer previously allocated using the tpalloc() function. Size of data buffer that should be posted with the event. If data points to a buffer of a type that does not require a length to be specified (for example, an FML fielded buffer) or if you set it to NULL, the len argument is ignored and the event is posted with no data. Flag options. For more information on available flag options, refer to tppost(3c) in the Oracle Tuxedo ATMI C Function Reference.
data len
flags
The following example illustrates an event posting taken from the Oracle Tuxedo system sample application bankapp. This example is part of the WITHDRAWAL service. One of the functions of
8-12 Programming an Oracle Tuxedo ATMI Application Using C
P ost in g Eve nt s
the WITHDRAWAL service is checking for withdrawals greater than $10,000 and posting an event called BANK_TLR_WITHDRAWAL. Listing 8-2 Posting an Event with tppost( )
. . . /* Event logic related */ static float evt_thresh = 10000.00 ; /* default for event threshold */ static char emsg[200] ; /* used by event posting logic */ . . . /* Post a BANK_TLR_WITHDRAWAL event ? */ if (amt < evt_thresh) { /* no event to post */ tpreturn(TPSUCCESS, 0,transb->data , 0L, 0); } /* prepare to post the event */ if ((Fchg (transf, EVENT_NAME, 0, "BANK_TLR_WITHDRAWAL", (FLDLEN)0) == -1) || (Fchg (transf, EVENT_TIME, 0, gettime(), (FLDLEN)0) == -1) || (Fchg (transf, AMOUNT, 0, (char *)&amt, (FLDLEN)0) == -1)) { (void)sprintf (emsg, "Fchg failed for event fields: %s", Fstrerror(Ferror)) ; } /* post the event */ else if (tppost ("BANK_TLR_WITHDRAWAL", /* event name */ (char *)transf, /* data */ 0L, /* len */ TPNOTRAN | TPSIGRSTRT) == -1) { /* If event broker is not reachable, ignore the error */ if (tperrno != TPENOENT) (void)sprintf (emsg, "tppost failed: %s", tpstrerror (tperrno)); }
This example simply posts the event to the EventBroker to indicate a noteworthy occurrence in the application. Subscription to the event by interested clients, who can then take action as required, is done independently.
8-13
8-14
E x amp l e o f E v e nt Su bs c r i pt i o n
/* * Service called when a BANK_TLR_.* event is posted. */ void #if defined(__STDC__) || defined(__cplusplus) WATCHDOG(TPSVCINFO *transb) #else WATCHDOG(transb) TPSVCINFO *transb; #endif { FBFR *transf; /* fielded buffer of decoded message */ /* Set pointr to TPSVCINFO data buffer */ transf = (FBFR *)transb->data; /* Print the log entry to stdout */ (void)fprintf (stdout, "%20s|%28s|%8ld|%10.2f\n", Fvals (transf, EVENT_NAME, 0), Fvals (transf, EVENT_TIME, 0), Fvall (transf, ACCOUNT_ID, 0), *( (float *)CFfind (transf, AMOUNT, 0, NULL, FLD_FLOAT)) ); /* No data should be returned by the event subscriber's svc routine */ tpreturn(TPSUCCESS, 0,NULL, 0L, 0); }
8-15
8-16
CHAPTER
This topic includes the following sections: What Is a Global Transaction? Starting the Transaction Suspending and Resuming a Transaction Terminating the Transaction Implicitly Defining a Global Transaction Defining Global Transactions for an XA-Compliant Server Group Testing Whether a Transaction Has Started
9-1
A global transaction may be composed of several local transactions, each accessing the same resource manager. The resource manager is responsible for performing concurrency control and atomicity of updates. A given local transaction may be either successful or unsuccessful in completing its access; it cannot be partially successful. A maximum of 16 server groups can participate in a single transaction. The Oracle Tuxedo system manages a global transaction in conjunction with the participating resource managers and treats it as a specific sequence of operations that is characterized by atomicity, consistency, isolation, and durability. In other words, a global transaction is a logical unit of work in which: All portions either succeed or have no effect. Operations are performed that correctly transform resources from one consistent state to another. Intermediate results are not accessible to other transactions, although some processes in a transaction may access the data associated with another process. Once a sequence is complete, its results cannot be altered by any kind of failure. The Oracle Tuxedo system tracks the status of each global transaction and determines whether it should be committed or rolled back. Note: If a transaction includes calls to tpcall(), tpacall(), or tpconnect() for which the flags parameter is explicitly set to TPNOTRAN, the operations performed by the called service do not become part of that transaction. In this case, the calling process does not invite the called service to be a participant in the current transaction. As a result, services performed by the called process are not affected by the outcome of the current transaction. If TPNOTRAN is set for a call that is directed to a service in an XA-compliant server group, the call may be executed outside of transaction mode or in a separate transaction, depending on how the service is configured and coded. For more information, refer to Implicitly Defining a Global Transaction on page 9-15.
9-2
S ta r tin g th e T ra ns ac t i o n
Description
Specifies the amount of time, in seconds, a transaction can execute before timing out. You can set this value to the maximum number of seconds allowed by the system, by specifying a value of 0. In other words, you can set timeout to the maximum value for an unsigned long as defined by the system. The use of 0 or an unrealistically large value for the timeout parameter delays system detection and reporting of errors. The system uses the timeout parameter to ensure that responses to service requests are sent within a reasonable time, and to terminate transactions that encounter problems such as network failures before executing a commit. For a transaction in which a person is waiting for a response, you should set this parameter to a small value: if possible, less than 30 seconds. In a production system, you should set timeout to a value large enough to accommodate expected delays due to system load and database contention. A small multiple of the expected average response time is often an appropriate choice. Note: The value assigned to the timeout parameter should be consistent with that of the SCANUNIT parameter set by the Oracle Tuxedo application administrator in the configuration file. The SCANUNIT parameter specifies the frequency with which the system checks, or scans, for timed-out transactions and blocked calls in service requests. The value of this parameter represents the interval of time between these periodic scans, referred to as the scanning unit. You should set the timeout parameter to a value that is greater than the scanning unit. If you set the timeout parameter to a value smaller than the scanning unit, there will be a discrepancy between the time at which a transaction times out and the time at which this timeout is discovered by the system. The default value for SCANUNIT is 10 seconds. You may need to discuss the setting of the timeout parameter with your application administrator to make sure the value you assign to the timeout parameter is compatible with the values assigned to your system parameters.
flags
9-3
Any process may call tpbegin() unless the process is already in transaction mode or is waiting for outstanding replies. If tpbegin() is called in transaction mode, the call fails due to a protocol error and tperrno(5) is set to TPEPROTO. If the process is in transaction mode, the transaction is unaffected by the failure. The following example provides a high-level view of how a global transaction is defined. Listing 9-1 Defining a Global Transaction - High-level View
. . . if (tpbegin(timeout,flags) == -1) error routine program statements . . . if (tpcommit(flags) == -1) error routine
The following example provides a more detailed view of how to define a transaction. This example is excerpted from audit.c, a client program included in bankapp, the sample banking application delivered with the Oracle Tuxedo system. Listing 9-2 Defining a Global Transaction - Detailed View
#include #include #include #include #include #include #include <stdio.h> <string.h> <atmi.h> <Uunix.h> <userlog.h> "bank.h" "aud.h" /* /* /* /* /* /* /* UNIX */ UNIX */ BEA Tuxedo System */ BEA Tuxedo System */ BEA Tuxedo System */ BANKING #defines */ BANKING view defines */
#define INVI 0 #define ACCT 1 #define TELL 2 static static static static
int sum_bal _((char *, char *)); long sitelist[NSITE] = SITEREP; /* list of machines to audit */ char pgmname[STATLEN]; /* program name = argv[0] */ char result_str[STATLEN]; /* string to hold results of query */
9-4
S ta r tin g th e T ra ns ac t i o n
main(argc, argv) int argc; char *argv[]; { int aud_type=INVI; int clarg; int c; int cflgs=0; int aflgs=0; int nbl=0; char svc_name[NAMELEN]; char hdr_type[NAMELEN]; int retc; struct aud *audv; int audrl=0; long q_branchid; . . .
/* audit type -- invalid unless specified */ /* command line arg index from optind */ /* Option character */ /* Commit flags, currently unused */ /* Abort flags, currently unused */ /* count of branch list entries */ /* service name */ /* heading to appear on output */ /* return value of sum_bal() */ /* pointer to audit buf struct */ /* audit return length */ /* branch_id to query */
/* Join application */ if (tpinit((TPINIT *) NULL) == -1) { (void)userlog("%s: failed to join application\n", pgmname); exit(1); } /* Start global transaction */ if (tpbegin(30, 0) == -1) { (void)userlog("%s: failed to begin transaction\n", pgmname); (void)tpterm(); exit(1); } if (nbl == 0) { /* no branch id specified so do a global sum */ retc = sum_bal(svc_name, hdr_type); /* sum_bal routine not shown */ } else { /* Create buffer and set data pointer */ if ((audv = (struct aud *)tpalloc("VIEW", "aud", sizeof(struct aud))) == (struct aud *)NULL) { (void)userlog("audit: unable to allocate space for VIEW\n"); exit(1); } /* Prepare aud structure */
9-5
audv->b_id = q_branchid; audv->balance = 0.0; audv->ermsg[0] = '\0'; /* Do tpcall */ if (tpcall(svc_name,(char *)audv,sizeof(struct aud), (char **)audv,(long *)audrl,0) == -1){ (void)fprintf (stderr,"%s service failed\n%s: svc_name, svc_name, audv->ermsg); retc = -1; }else { (void)sprintf(result_str,"Branch %ld %s balance is $%.2f\n", audv->b_id, hdr_type, audv->balance); } tpfree((char *)audv); } /* Commit global transaction */ if (retc < 0) /* sum_bal failed so abort */ (void) tpabort(aflgs); else { if (tpcommit(cflgs) == -1) { (void)userlog("%s: failed to commit transaction\n", pgmname); (void)tpterm(); exit(1); } /*print out results only when transaction has committed successfully*/ (void)printf("%s",result_str); } /* Leave application */ if (tpterm() == -1) { (void)userlog("%s: failed to leave application\n", pgmname); exit(1); }
%s\n",
If a transaction times out, a call to tpcommit() causes the transaction to be aborted. As a result, tpcommit() fails and sets tperrno(5) to TPEABORT.
9-6
Su s p e nd i n g a nd R e s um i n g a T ra ns ac t i o n
The following example shows how to test for a transaction timeout. Note that the value of timeout is set to 30 seconds. Listing 9-3 Testing for Transaction Timeout
if (tpbegin(30, 0) == -1) { (void)userlog("%s: failed to begin transaction\n", argv[0]); tpterm(); exit(1); } . . . communication calls . . . if (tperrno == TPETIME){ if (tpabort(0) == -1) { check for errors; } else if (tpcommit(0) == -1){ check for errors; } . . .
Note: When a process is in transaction mode and makes a communication call with flags set to TPNOTRAN, it prohibits the called service from becoming a participant in the current transaction. Whether the service request succeeds or fails has no impact on the outcome of the transaction. The transaction can still timeout while waiting for a reply that is due from a service, whether it is part of the transaction or not. Refer to Managing Errors on page 11-1 for more information on the effects of the TPNOTRAN flag.
9-7
The Oracle Tuxedo system provides two functions that allow a client or server to suspend and resume a transaction in such situations: tpsuspend(3c) and tpresume(3c). Using these functions, a process can: 1. Temporarily suspend the current transaction by calling tpsuspend(). 2. Start a separate transaction. (In the preceding example, the server writes an entry to the event log.) 3. Commit the transaction started in step 2. 4. Resume the original transaction by calling tpresume().
Suspending a Transaction
Use the tpsuspend(3c) function to suspend the current transaction. Use the following signature to call the tpsuspend() function:
int tpsuspend(TPTRANID *t_id,long flags)
The following table describes the arguments to the tpsuspend() function. Table 9-2 tpsuspend( ) Function Arguments Field
*t_id flags
Description
Pointer to the transaction identifier. Currently not used. Reserved for future use.
You cannot suspend a transaction with outstanding asynchronous events. When a transaction is suspended, all modifications previously performed are preserved in a pending state until the transaction is committed, aborted, or timed out.
Resuming a Transaction
To resume the current transaction, use the tpresume(3c) function with the following signature.
int tpresume(TPTRANID *t_id,long flags)
9-8
Su s p e nd i n g a nd R e s um i n g a T ra ns ac t i o n
Description
Pointer to the transaction identifier. Currently not used. Reserved for future use.
It is possible to resume a transaction from a process other than the one that suspended it, subject to certain restrictions. For a list of these restrictions, refer to tpsuspend(3c) and tpresume(3c) in the Oracle Tuxedo ATMI C Function Reference.
tpbegin(30,TPNOFLAGS); /* begin separate transaction */ Perform work in the separate transaction. tpcommit(TPNOFLAGS); /* commit separate transaction */ tpresume(&t,TPNOFLAGS); . . . tpreturn(. . . ); } /* resume invoking transaction*/
9-9
Although the flags argument is not used currently, you must set it to zero to ensure compatibility with future releases.
transaction, returns -1, and sets tperrno(5) to TPEABORT. The results are the same if tpcommit() is called for a transaction that has already timed out: tpcommit() returns -1 and sets tperrno() to TPEABORT. Refer to Managing Errors on page 11-1 for more information on transaction errors.
By default, CMTRET is set to COMPLETE. If you later want to override the setting in the configuration file, you can do so by calling the
tpscmt() function with its flags argument set to either TP_CMT_LOGGED or TP_CMT_COMPLETE.
Although the flags argument is not used currently, you must set it to zero to ensure compatibility with future releases.
9-12
The connection hierarchy is created through the following process: 1. A client (process A) initiates a connection in transaction mode by calling tpbegin() and tpconnect(). 2. The client calls subsidiary services, which are executed. 3. As each subordinate service completes, it sends a reply indicating success or failure (TPEV_SVCSUCC or TPEV_SVCFAIL, respectively) back up through the hierarchy to the process that initiated the transaction. In this example the process that initiated the transaction is the client (process A). When a subordinate service has completed sending replies (that is, when no more replies are outstanding), it must call tpreturn(). 4. The client (process A) determines whether all subordinate services have returned successfully. If so, the client commits the changes made by those services, by calling tpcommit(), and completes the transaction.
9-13
If not, the client calls tpabort(), since it knows that tpcommit() could not be successful.
9-14
035 036 037 038 039 040 041 042 043 044 045 046 047 048
break; } if (tpabort(0) == -1){ check for errors; } } else if (tpcommit(0) == -1) fprintf(stderr, "Transaction failed at commit time\n"); tpfree(rbuf); tpfree(sbuf); tpterm(); exit(0); }
9-15
If the flags argument is not set to TPNOTRAN, then the system places the called process in transaction mode through the rule of propagation. The system does not check the AUTOTRAN parameter. If the flags argument is set to TPNOTRAN, the services performed by the called process are not included in the current transaction (that is, the propagation rule is suppressed). The system checks the AUTOTRAN parameter. If AUTOTRAN is set to N (or if it is not set), the system does not place the called process in transaction mode. If AUTOTRAN is set to Y, the system places the called process in transaction mode, but treats it as a new transaction. Note: Because a service can be placed in transaction mode automatically, it is possible for a service with the TPNOTRAN flag set to call services that have the AUTOTRAN parameter set. If such a service requests another service, the flags member of the service information structure returns TPTRAN when queried. For example, if the call is made with the communication flags member set to TPNOTRAN | TPNOREPLY, and the service automatically starts a transaction when called, the flags member of the information structure is set to TPTRAN | TPNOREPLY.
9-16
It is important to know whether or not a process is in transaction mode in order to avoid and interpret certain error conditions. For example, it is an error for a process already in transaction mode to call tpbegin(). When tpbegin() is called by such a process, it fails and sets tperrno(5) to TPEPROTO to indicate that it was invoked while the caller was already participating in a transaction. The transaction is not affected. You can design a service subroutine so that it tests whether it is in transaction mode before invoking tpbegin(). You can test the transaction level by either of the following methods: Querying the flags field of the service information structure that is passed to the service routine. The service is in transaction mode if the value is set to TPTRAN. Calling the tpgetlev(3c) function. Use the following signature to call the tpgetlev() function:
int tpgetlev() /* Get current transaction level */
The tpgetlev() function requires no arguments. It returns 0 if the caller is not in a transaction, and 1 if it is. The following code sample is a variation of the OPEN_ACCT servicethat shows how to test for transaction level using the tpgetlev() function (line 12). If the process is not already in transaction mode, the application starts a transaction (line 14). If tpbegin() fails, a message is returned to the status line (line 16) and the rcode argument of tpreturn() is set to a code that can be retrieved in the global variable tpurcode(5) (lines 1 and 17). Listing 9-6 Testing Transaction Level
001 #define BEGFAIL 002 void 003 OPEN_ACCT(transb) 004 TPSVCINFO *transb; 005 { ... other declarations ... 006 FBFR *transf; /* fielded buffer of decoded message */ 007 int dotran; /* checks whether service tpbegin/tpcommit/tpaborts */ 008 /* set pointer to TPSVCINFO data buffer */ 3 /* tpurcode setting for return if tpbegin fails */
9-17
009 transf = (FBFR *)transb->data; 010 /* Test if transaction exists; initiate if no, check if yes */ 011 dotran = 0; 012 if (tpgetlev() == 0) { 013 dotran = 1; 014 if (tpbegin(30, 0) == -1) { 015 Fchg(transf, STATLIN, 0, 016 "Attempt to tpbegin within service routine failed\n"); 017 tpreturn(TPFAIL, BEGFAIL, transb->data, 0, 0); 018 } 019 } . . .
If the AUTOTRAN parameter is set to Y, you do not need to call the tpbegin(), and tpcommit() or tpabort() transaction functions explicitly. As a result, you can avoid the overhead of testing for transaction level. In addition, you can set the TRANTIME parameter to specify the time-out interval: the amount of time that may elapse after a transaction for a service begins, and before it is rolled back if not completed. For example, suppose you are revising the OPEN_ACCT service shown in the preceding code listing. Currently, OPEN_ACCT defines the transaction explicitly and then tests for its existence (see lines 7 and 10-19). To reduce the overhead introduced by these tasks, you can eliminate them from the code. Therefore, you need to require that whenever OPEN_ACCT is called, it is called in transaction mode. To specify this requirement, enable the AUTOTRAN and TRANTIME system parameters in the configuration file.
See Also
Description of the AUTOTRAN configuration parameter in the section Implicitly Defining a Global Transaction on page 9-15 in Setting Up an Oracle Tuxedo Application.
TRANTIME configuration parameter in Setting Up an Oracle Tuxedo Application.
Using Tuxedo with Oracle Real Application Clusters (RAC) in Setting Up an Oracle Tuxedo Application.
9-18
C H A P T E R 10
This topic includes the following sections: Support for Programming a Multithreaded/Multicontexted ATMI Application Planning and Designing a Multithreaded/Multicontexted ATMI Application Implementing a Multithreaded/ Multicontexted ATMI Application Testing a Multithreaded/Multicontexted ATMI Application
10-1
See Also
What Are Multithreading and Multicontexting? on page 10-3 Advantages and Disadvantages of a Multithreaded/Multicontexted ATMI Application on page 10-7 How Multithreading and Multicontexting Work in a Client on page 10-9 How Multithreading and Multicontexting Work in Server-Dispatched Threads an on ATMI Server on page 10-14 How Multithreading and Multicontexting Work in Application-Created Threads of an ATMI Server on page 10-18
10-2 Programming an Oracle Tuxedo ATMI Application Using C
What Is Multithreading?
Multithreading is the inclusion of more than one unit of execution in a single process. In a multithreaded application, multiple simultaneous calls can be made from the same process. For example, an individual process is not limited to one outstanding tpcall(). In a server, multithreading requires multicontexting except when application-created threads are used in a singled-context server. The only way to create a multithreaded, single-context application is to use application-created threads. The Oracle Tuxedo system supports multithreaded applications written in C. It does not support multithreaded COBOL applications.
Programming an Oracle Tuxedo ATMI Application Using C 10-3
The following diagram shows how a multithreaded client can issue calls to three servers simultaneously. Figure 10-1 Sample Multithreaded Process
SERVER A
tpcall() tpcall()
SERVER B
THREAD 1
THREAD 2
tpcall()
SERVER C
In a multithreaded application, multiple service-dispatched threads are available in the same server, which means that fewer servers need to be started for that application. The following diagram shows how a server process can dispatch multiple threads to different clients simultaneously.
10-4
CLIENT A
CLIENT B
SERVER PROCESS
CLIENT C
What Is Multicontexting?
A context is an association to a domain. Multicontexting is the ability of a single process to have one of the following: More than one connection within a domain Connections to more than one domain Multicontexting can be used in both clients and servers. When used in servers, multicontexting implies the use of multithreading, as well.
10-5
For a more complete list of the characteristics of a context, see Context Attributes in one of the following sections: Writing Code to Enable Multicontexting in an ATMI Client on page 10-27 Writing Code to Enable Server-Dispatched Multicontexting and Multithreading Threads in an ATMI Server on page 10-34 The Oracle Tuxedo system supports multicontexted applications written in either C or COBOL. Multithreaded applications, however, are supported only in C. The following diagram shows how a multicontexted client process works within a domain. Each arrow represents an outstanding call to a server. Figure 10-3 Multicontexted Process in Two Domains
CLIENT PROCESS
Oracle Tuxedo Application A Context 1 Context 2
Server 1 Server 2
Context 3
10-6
See Also
Advantages and Disadvantages of a Multithreaded/Multicontexted ATMI Application on page 10-7 How Multithreading and Multicontexting Work in a Client on page 10-9 How Multithreading and Multicontexting Work in Server-Dispatched Threads an on ATMI Server on page 10-14 How Multithreading and Multicontexting Work in Application-Created Threads of an ATMI Server on page 10-18
In some applications it is easier to code different remote procedure calls and conversations in separate threads than to manage them from the same thread. Simultaneous access to multiple applications Your Oracle Tuxedo clients can be connected to more than one application at a time. Reduced number of required servers Because one server can dispatch multiple service threads, the number of servers to start for your application is reduced. This capability for multiple dispatched threads is especially useful for conversational servers, which otherwise must be dedicated to one client for the entire duration of a conversation. For applications in which client threads are created by the Microsoft Internet Information Server API or the Netscape Enterprise Server interface (that is, the NSAPI), the use of multiple threads is essential if you want to obtain the full benefits afforded by these tools. This may be true of other tools, as well.
10-8
Existing code often requires significant re-architecting to take advantage of multithreading and multicontexting. Programmers need to: Remove static variables Replace any function calls that are not thread-safe Replace any other code that is not thread-safe Because the completed port must be tested and retested, the work required to port a multithreaded and/or multicontexted application is substantial.
See Also
What Are Multithreading and Multicontexting? on page 10-3 How Multithreading and Multicontexting Work in a Client on page 10-9 How Multithreading and Multicontexting Work in Server-Dispatched Threads an on ATMI Server on page 10-14 How Multithreading and Multicontexting Work in Application-Created Threads of an ATMI Server on page 10-18 Design Considerations for a Multithreaded and Multicontexted ATMI Application on page 10-20
Start-up Phase
In the start-up phase the following events occur: Some client threads join one or more Oracle Tuxedo applications by calling tpinit(). Other client threads share the contexts created by the first set of threads by calling tpsetctxt(3c).
Programming an Oracle Tuxedo ATMI Application Using C 10-9
Some client threads join multiple contexts. Some client threads switch to an existing context. Note: There may also be threads that work independently of the Oracle Tuxedo system. We do not consider such threads in this documentation.
10-10
Once the second thread is associated with the desired context, it is available to perform tasks executed by ATMI functions that operate on a per-context basis. For details, see Using Per-context Functions and Data Structures in a Multithreaded ATMI Client on page 10-48.
Work Phase
In this phase each thread performs a task. The following is a list of sample tasks: A thread issues a request for a service. A thread gets the reply to a service request. A thread initiates and/or participates in a conversation. A thread begins, commits, or rolls back a transaction.
Service Requests
A thread sends a request to a server by calling either tpcall() for a synchronous request or tpacall() for an asynchronous request. If the request is sent with tpcall(), then the reply is received without further action by any thread.
Transactions
If one thread starts a transaction, then all threads that share the context of that thread also share the transaction. Many threads in a context may work on a transaction, but only one thread may commit or abort it. The thread that commits or aborts the transaction can be any thread working on the transaction; it is not necessarily the same thread that started the transaction. Threaded applications are responsible for providing appropriate synchronization so that the normal rules of transactions are followed. (For example, there can be no outstanding RPC calls or conversations when a transaction is committed, and no stray calls are allowed after a transaction has been committed or aborted.) A process may be part of at most one transaction for each of its application associations. If one thread of an application calls tpcommit() concurrently with an RPC or conversational call in another thread of the application, the system acts as if the calls were issued in some serial order. An application context may temporarily suspend work on a transaction by calling tpsuspend()
Programming an Oracle Tuxedo ATMI Application Using C 10-11
and then start another transaction subject to the same restrictions that exist for single-threaded and single-context programs.
Unsolicited Messages
For each context in a multithreaded or multicontexted application, you may choose one of three methods for handling unsolicited messages.
A context may . . .
Ignore unsolicited messages Use dip-in notification Use dedicated thread notification. (available only for C applications)
By setting . . .
TPU_IGN TPU_DIP TPU_THREAD
The following caveats apply: SIGNAL-based notification is not allowed in multithreaded or multicontexted processes. If your application runs on a platform that supports multicontexting but not multithreading, then you cannot use the TPU_THREAD unsolicited notification method. As a result, you cannot receive immediate notification of events. If receiving immediate notification of events is important to your application, then you should carefully consider whether to use a multicontexted approach on this platform. Dedicated thread notification is available only: For applications written in C On multithreaded platforms supported by the Oracle Tuxedo system When dedicated thread notification is chosen, the system dedicates a separate thread to receive unsolicited messages and dispatch the unsolicited message handler. Only one copy of the unsolicited message handler can run at any one time in a given context. If tpinit() is called on a platform for which the Oracle Tuxedo system does not support threads, with parameters indicating that TPU_THREAD notification is being requested on a platform that does not support threads, tpinit() returns -1 and sets tperrno to TPEINVAL. If the UBBCONFIG(5) default NOTIFY option is set to THREAD but threads are not available on a particular machine, the default behavior for that machine is downgraded to DIPIN. The difference between these two behaviors allows an administrator to specify a default for all machines in a
10-12 Programming an Oracle Tuxedo ATMI Application Using C
mixed configurationa configuration that includes some machines that support threads and some that do notbut it does not allow a client to explicitly request a behavior that is not available on its machine. If tpsetunsol() is called from a thread that is not associated with a context, a per-process default unsolicited message handler for all new tpinit() contexts created is established. A specific context may change the unsolicited message handler for that context by calling tpsetunsol() again when the context is active. The per-process default unsolicited message handler may be changed by again calling tpsetunsol() in a thread not currently associated with a context. If a process has multiple associations with the same application, then each association is assigned a different CLIENTID so that it is possible to send an unsolicited message to a specific application association. If a process has multiple associations with the same application, then any tpbroadcast() is sent separately to each of the application associations that meet the broadcast criteria. When performing a dip-in check for receiving unsolicited messages, an application checks for only those messages sent to the current application association. In addition to the ATMI functions permitted in unsolicited message handlers, it is permissible to call tpgetctxt(3c) within an unsolicited message handler. This functionality allows an unsolicited message handler to create another thread to perform any more substantial ATMI work required within the same context.
Placeholders are printed in the thread_ID and context_ID fields of entries for non-threaded platforms and single-contexted applications. The TM_MIB(5) supports this functionality in the TA_THREADID and TA_CONTEXTID fields in the T_ULOG class.
Completion Phase
In this phase, when the client process is about to exit, on behalf of the current context and all associated threads, a thread ends its application association by calling tpterm(). Like other ATMI functions, tpterm() operates on the current context. It affects all threads for which the context is set to the terminated context, and terminates any commonality of context among these threads.
10-13
A well-designed application normally waits for all work in a particular context to complete before it calls tpterm(). Be sure that all threads are synchronized before your application calls tpterm().
See Also
What Are Multithreading and Multicontexting? on page 10-3 Design Considerations for a Multithreaded and Multicontexted ATMI Application on page 10-20 Writing Code to Enable Multicontexting in an ATMI Client on page 10-27 Writing a Multithreaded ATMI Client on page 10-42 Synchronizing Threads Before an ATMI Client Termination on page 10-29
Start-up Phase
What happens during the start-up phase depends on the value of the MINDISPATCHTHREADS and MAXDISPATCHTHREADS parameters in the configuration file.
10-14
If the value of
MINDISPATCHTHREADS
Then . . .
is . . .
0
is . . .
>1 1. The Oracle Tuxedo system creates a thread dispatcher. 2. The dispatcher calls tpsvrinit() to join the application.
>0
>1
1. The Oracle Tuxedo system creates a thread dispatcher. 2. The dispatcher calls tpsvrinit() to join the application. 3. The Oracle Tuxedo system creates additional threads for handling service requests, and a context for each new thread. 4. Each new system-created thread calls tpsvrthrinit(3c) to join the application.
Work Phase
In this phase, the following activities occur: Multiple client requests to one server are handled concurrently in multiple contexts. The system allocates a separate thread for each request. If necessary, additional threads (up to the number indicated by MAXDISPATCHTHREADS) are created. The system keeps statistics on server threads.
This functionality is controlled by the following parameters in the SERVERS section of the UBBCONFIG(5) file and the TM_MIB(5).
UBBCONFIG Parameter
MINDISPATCHTHREADS MAXDISPATCHTHREADS THREADSTACKSIZE
MIB Parameter
TA_MINDISPATCHTHREADS TA_MAXDISPATCHTHREADS TA_THREADSTACKSIZE
Default
0 1 0 (representing the OS default)
Each dispatched thread is created with the stack size specified by THREADSTACKSIZE (or TA_THREADSTACKSIZE). If this parameter is not specified or has a value of 0, the operating system default is used. On a few operating systems on which the default is too small to be used by the Oracle Tuxedo system, a larger default is used. If the value of this parameter is not specified or is 0, or if the operating system does not support setting a THREADSTACKSIZE, then the operating system default is used.
MINDISPATCHTHREADS (or TA_MINDISPATCHTHREADS) must be less than or equal to MAXDISPATCHTHREADS (or TA_MAXDISPATCHTHREADS).
If MAXDISPATCHTHREADS (or TA_MAXDISPATCHTHREADS) is 1, then the dispatcher thread and the service function thread are the same thread. If MAXDISPATCHTHREADS (or TA_MAXDISPATCHTHREADS) is greater than 1, any separate thread used for dispatching other threads does not count toward the limit of dispatched threads. Initially, the system boots MINDISPATCHTHREADS (or TA_MINDISPATCHTHREADS) server threads. The system never boots more than MAXDISPATCHTHREADS (or TA_MAXDISPATCHTHREADS) server threads.
10-16
The BBL also sends a message to any process or thread that has been waiting longer than its timeout value to receive a message. The blocking message receive call then returns an error indicating a timeout.
Placeholders are printed in the thread_ID and context_ID fields of entries for non-threaded platforms and single-contexted applications. The TM_MIB(5) supports this functionality in the TA_THREADID and TA_CONTEXTID fields in the T_ULOG class.
Completion Phase
When the application is shut down, tpsvrthrdone(3c) and tpsvrdone(3c) are called to perform any termination processing that is necessary, such as closing a resource manager.
See Also
What Are Multithreading and Multicontexting? on page 10-3 Design Considerations for a Multithreaded and Multicontexted ATMI Application on page 10-20 Writing Code to Enable Server-Dispatched Multicontexting and Multithreading Threads in an ATMI Server on page 10-34 Writing a Multithreaded ATMI Server on page 10-54
Programming an Oracle Tuxedo ATMI Application Using C 10-17
Start-Up Phase
An application-created server thread creates a Tuxedo context and associates itself with this context by calling tpappthrinit(3c). The context created by tpappthrinit(3c) connects to the domain that the application server is in.
10-18
If necessary, after successfully calling tpappthrinit(3c), the application-created thread within an ATMI server may call tpgetctxt(3c) and pass the handle that is returned (the value of which is the current context) to a second application thread within the same process.
Work Phase
Each application-created server thread performs the following tasks: An application-created thread issues a request for a service. An application-created thread gets the reply to service request. An application-created thread initiates and/or participates in a conversation. An application-created thread begins, commits, or rolls back a transaction. These tasks performed in an application-created server thread share the same characteristics as in a client program. For more information, see How Multithreading and Multicontexting Work in a Client. Notes: An application-created server thread cannot call either tpreturn() or tpforward(). Application-created server thread may send, but cannot receive unsolicited messages.
Completion Phase
When an application-created server thread has finished its work, the thread calls tpappthrterm(3c) to terminate the current context.
tpappthrterm(3c) affects all application-created server threads that are currently working on the same context. Avoid calling tpappthrterm(3c) while other application threads are still
working on the terminated context. A well-designed application normally waits for all work in a particular context to complete before it calls tpappthrterm(3c). Be sure that all application threads are synchronized before your application thread calls tpappthrterm(3c).
10-19
See Also
How Multithreading and Multicontexting Work in a Client Design Considerations for a Multithreaded and Multicontexted ATMI Application Writing Code to Enable Multicontexting in Application-Created Threads of an ATMI Server Writing Code to Enable Server-Dispatched Multicontexting and Multithreading Threads in an ATMI Server Writing a Multithreaded ATMI Client
Environment Requirements
When considering the development of multithreaded and/or multicontexted applications, examine the following aspects of your development and run-time environments: Do you have an experienced team of programmers capable of writing and debugging multithreaded and multicontexted programs that successfully manage concurrency and synchronization? Are the multithreading features of the Oracle Tuxedo system supported on the platform on which you are developing your application? These features are supported only on platforms with an OS-provided threads package, providing an appropriate level of functionality. Do the resource managers (RMs) used by your servers support multithreading? If so, consider the following issues, as well: Do you need to set any parameters required by your RM to enable multithreaded access by your servers? For example, if you use an Oracle database with a multithreaded application, you must set the THREADS=true parameter as part of the OPENINFO string
10-20 Programming an Oracle Tuxedo ATMI Application Using C
passed to Oracle. By doing so, you make it possible for individual threads to operate as separate Oracle associations. Does your RM support a mixed mode of operation? A mixed-mode operation is a form of access such that multiple threads in a process can map to one RM association while other threads in the same process simultaneously map to different RM associations. Within one process, for example, Threads A and B map to RM Association X, while Thread C maps to RM Association Y. Not all RMs support mixed-mode operation. Some require all threads in a given process to map to the same RM association. If you are designing an application that will make use of transactional RM access within application-created threads, make sure your RM supports mixed-mode operation.
Design Requirements
When designing a multithreaded and/or multicontexted application, you should consider the following design questions: Is the Task of Your Application Suitable for Multithreading and/or Multicontexting? How Many Applications and Connections Do You Want? What Synchronization Issues Need to Be Addressed? Will You Need to Port Your Application? Which Threads Model Is Best for You?
10-21
Multicontexting.
Multithreading. By allocating one thread per context, you can simplify your code. Multithreading.
Does your client perform two or more tasks that can be executed independently for a long time such that the performance gains from concurrent execution outweigh the costs and complexities of threads synchronization? Do you want one server to process multiple concurrent requests?
Multithreading. Assign a value greater than 1 to MAXDISPATCHTHREADS. This value enables multiple clients, each in its own thread, for the server. Multithreading. Application-created server thread creates a separate Tuxedo context and associates itself with the context by calling tpappthrinit(3c) (This feature is available from Tuxedo 10g Release 3 (10.3)) Not using multithreading.
If your client or server had multiple threads, would it be necessary to synchronize them after each thread had performed only a little work?
10-22
If you want more than one connection to an application, then we recommend a multithreaded, multicontexted application. If you want only one connection to one application, then we recommend one of the following: Multithreaded, single-contexted clients Single-threaded, single-contexted clients In both cases, multithreaded, multicontexted servers may be used.
10-23
The client is multicontexted. The client is multithreaded and each thread is in a different context. An Oracle Tuxedo Release 7.1 Workstation client with multiple threads in a single context cannot interoperate with a pre-7.1 release of the Oracle Tuxedo system.
See Also
Advantages and Disadvantages of a Multithreaded/Multicontexted ATMI Application on page 10-7 Preliminary Guidelines for Programming a Multithreaded/Multicontexted ATMI Application on page 10-24
Concurrency Considerations
Multithreading enables different threads of an application to perform concurrent operations on the same conversation. We do not recommend this approach, but the Oracle Tuxedo system does not forbid it. If different threads perform concurrent operations on the same conversation, the system acts as if the concurrent calls were issued in some arbitrary order.
10-25
When programming with multiple threads, you must manage the concurrency among them by using mutexes or other concurrency-control functions. Here are three examples of the need for concurrency control: When multithreaded threads are operating on the same context, the programmer must ensure that functions are being executed in the required serial order. For example, all RPC calls and conversations must be invoked before tpcommit() can be called. If tpcommit() is called from a thread other than the thread from which all these RPC or conversational calls are made, some concurrency control is probably required in the application. Similarly, it is permissible to call tpacall() in one thread and tpgetrply() in another, but the application must either: Ensure that tpacall() is called before tpgetrply(), or Manage the consequences if tpacall() is not called before tpgetrply() Multiple threads may operate on the same conversation but application programmers must realize that if different threads issue tpsend() at approximately the same time, the system acts as though these tpsend() calls have been issued in an arbitrary order. For most applications, the best strategy is to code all the operations for one conversation in one thread. The second best strategy is to serialize these operations using concurrency control.
10-26
See Also
Design Considerations for a Multithreaded and Multicontexted ATMI Application on page 10-20 Writing Code to Enable Multicontexting in an ATMI Client on page 10-27 Writing Code to Enable Server-Dispatched Multicontexting and Multithreading Threads in an ATMI Server on page 10-34 Writing Code to Enable Multicontexting in Application-Created Threads of an ATMI Server on page 10-36 Writing a Multithreaded ATMI Client on page 10-42 Writing a Multithreaded ATMI Server on page 10-54
Context Attributes
When writing your code, keep in mind the following considerations about contexts:
Programming an Oracle Tuxedo ATMI Application Using C 10-27
If an application-created server thread which is currently associated with a server-disptached context exits without changing context before the original dispatched thread exits, then tpreturn() or tpforward() fails. The execution of a thread exit does not automatically trigger a call to tpsetctxt(3c) to change the context to TPNULLCONTEXT. For all contexts in a process, the same buffer type switch must be used. As with any other type of data structure, a multithreaded application must properly make use of Oracle Tuxedo buffers, that is, buffers should not be used concurrently in two calls when one of the following may be true: Both calls may use the buffer Both calls may free the buffer One call may use the buffer and one call may free the buffer If you call tpinit() more than once, either to join multiple applications or to make multiple connections to a single application, keep in mind that on each tpinit() you must accommodate whatever security mechanisms have been established.
10-28
A new application association is created and assigned to the Oracle Tuxedo domain specified in the TUXCONFIG or WSENVFILE/WSNADDR environment variable. Note: In any one process, either all calls to tpinit() must include the TPMULTICONTEXTS flag or else no call to tpinit() may include this flag. The only exception to this rule is that if all of a clients application associations are terminated by successful calls to tpterm(), then the process is restored to a state in which the inclusion of the TPMULTICONTEXTS flag in the next call to tpinit() is optional.
invalid context state, most ATMI functions are disallowed. A thread may exit from the invalid context state by calling tpsetctxt(3c) or tpterm(). Most well designed applications never have to deal with the invalid context state. Note: The Oracle Tuxedo system does not support multithreading in COBOL applications.
Switching Contexts
The following is a summary of the coding steps that might be made by a client that calls services from two contexts. 1. Set the TUXCONFIG environment variable to the value required by firstapp. 2. Join the first application by calling tpinit() with the TPMULTICONTEXTS flag set. 3. Obtain a handle to the current context by calling tpgetctxt(3c). 4. Switch the value of the TUXCONFIG environment variable to the value required by the secondapp context, by calling tuxputenv(). 5. Join the second application by calling tpinit() with the TPMULTICONTEXTS flag set. 6. Get a handle to the current context by calling tpgetctxt(3c). 7. Beginning with the firstapp context, start toggling between contexts by calling tpsetctxt(3c). 8. Call firstapp services. 9. Switch the client to the secondapp context (by calling tpsetctxt(3c)) and call secondapp services. 10. Switch the client to the firstapp context (by calling tpsetctxt(3c)) and call firstapp services. 11. Terminate the firstapp context by calling tpterm(). 12. Switch the client to the secondapp context (by calling tpsetctxt(3c)) and call secondapp services. 13. Terminate the secondapp context by calling tpterm(). The following sample code provides an example of these steps. Note: In order to simplify the sample, error checking code is not included.
10-30
10-31
* Get a handle to the context of secondapp. */ tpgetctxt(&secondapp_contextID, 0); /* * Now you can alternate between the two contexts * using tpsetctxt and the handles you obtained from * tpgetctxt. You begin with firstapp. */ tpsetctxt(firstapp_contextID, 0); /* * You call services offered by firstapp and then switch * to secondapp. */ tpsetctxt(secondapp_contextID, 0); /* * You call services offered by secondapp. * Then you switch back to firstapp. */ tpsetctxt(firstapp_contextID, 0); /* * You call services offered by firstapp. When you have * finished, you terminate the context for firstapp. */ tpterm(); /* * Then you switch back to secondapp. */ tpsetctxt(secondapp_contextID, 0); /* * You call services offered by secondapp. When you have finished, you terminate the context for secondapp and end your program. */ tpterm(); return(0); }
10-32
See Also
How Multithreading and Multicontexting Work in a Client on page 10-9 Writing a Multithreaded ATMI Client on page 10-42
Programming an Oracle Tuxedo ATMI Application Using C 10-33
Writing Code to Enable Server-Dispatched Multicontexting and Multithreading Threads in an ATMI Server
This topic includes the following sections: Context Attributes Coding Rules for Server-Dispatched Threads in Multicontexted ATMI Server Initializing and Terminating ATMI Servers and Server Threads Note: The instructions and sample code provided in this section refer to the C library functions provided by the Oracle Tuxedo system. (See the Oracle Tuxedo C Function Reference for details.) Equivalent COBOL routines are not available because multithreading (which is required to create a multicontexted server) is not supported for COBOL applications.
Context Attributes
When writing your code, keep in mind the following considerations about contexts: If an application-created server thread which is currently associated with a server-disptached context exits without changing context before the original dispatched thread exits, then tpreturn() or tpforward() fails. The execution of a thread exit does not automatically trigger a call to tpsetctxt(3c) to change the context to TPNULLCONTEXT. For all contexts in a process, the same buffer type switch must be used. As with any other type of data structure, a multithreaded application must properly make use of Oracle Tuxedo buffers, that is, buffers should not be used concurrently in two calls when one of the following may be true: Both calls may use the buffer. Both calls may free the buffer. One call may use the buffer and one call may free the buffer.
10-34
A server is prohibited from calling tpinit() . If a server process calls tpinit(), tpinit() returns -1 and sets tperrno(5) to TPEPROTO. Only a server-dispatched thread may call tpreturn() or tpforward(). A server cannot execute a tpreturn() or tpforward() if any application-created thread is still associated with any application context. Therefore, before a server-dispatched thread calls tpreturn(), each application-created thread associated with that context must call tpsetctxt(3c) with the context set to either TPNULLCONTEXT or another valid context. If this rule is violated, then tpreturn() or tpforward() writes a message to the user log, indicates TPESVCERR to the caller, and returns control to the main server dispatch loop. The threads that had been in the context where the invalid tpreturn() was done are placed in an invalid context. If there are outstanding ATMI calls, RPC calls, or conversations when tpreturn() or tpforward() is called, tpreturn() or tpforward() writes a message to the user log, indicates TPESVCERR to the caller, and returns control to the main server dispatch loop. A server-dispatched thread may not call tpsetctxt(3c). Unlike single-contexted servers, it is permissible for a multicontexted server thread to call a service that is offered only by that same server process.
10-35
See Also
How Multithreading and Multicontexting Work in Server-Dispatched Threads an on ATMI Server on page 10-14
Creating Threads
You can create additional threads within a Tuxedo application server by using OS threads functions. These new application threads may operate independently of the Tuxedo system, or they may operate in the same context as one of the server-dispatched threads. Application-created server threads may also operate in separate context created via tpappthrinit(3c).
10-36
Associate itself with a separated context created via tpappthrinit(3c) (This feature is available from Tuxedo 10g Release 3 (10.3))
Sample Code for Associating Application Thread with an Existing Server-Dispatched Context in a Multicontexted Server
For those applications that need to create an application thread in a server, Listing 10-3 shows a multicontexted server example where a service creates another thread to help perform its work in the same server-dispatched context. Operating system (OS) threads functions differ from one OS to another. In this sample POSIX and ATMI functions are used. Note: In order to simplify the example, error checking code is not included. Also, an example of a multicontexted server using only threads dispatched by the Oracle Tuxedo system is not included because such a server is coded in exactly the same way as a single-contexted server, as long as thread-safe programming practices are used. Listing 10-3 Code Sample for Application-Created Server Thread Working in Server-Dispatched Context
#include <pthread.h> #include <atmi.h>
10-37
tpgetctxt(&transferdata.ctxt, 0); transferdata.svcinfoptr = svcinfo; pthread_create( &withdrawalthreadid, NULL, withdrawalthread, &transferdata ); tpcall("DEPOSIT", ...); pthread_join(withdrawalthreadid, NULL); tpreturn(TPSUCCESS, ...); }
10-38
Context Attributes
The context created via tpappthrinit(3c) is independent from any server-dispatched context. It connects to the domain that the application server is in. The context created via tpappthrinit(3c) must be terminated by calling tpappthrterm(3c) after the application-created server thread has finished its work on that context. Depending on the type of security mechanism used in your application, user authentication information can be associated with the context when invoking tpappthrinit(3c). Each application association of an application-created context requires a separate security validation.
10-39
It should be avoided calling tpappthrterm() on an application-created context while other application threads are still working on that context. Handles and call descriptors are portable within the same context in the same process, but not between contexts or processes. Handles and call descriptors can be used only in the application context in which they are originally assigned. Once a conversation has been started, any thread in the same context within the same process can work on that conversation. Any application thread operating in the same context within the same server process can invoke tpgetrply() to receive a response to an earlier call to tpacall(), regardless of whether or not that application thread originally called tpacall(). A transaction can be committed or aborted by only one application thread in the same context within the same process, which may or may not be the same application thread that started it.
tpbegin() cannot be issued for a context that is already in transaction mode.
If the application server is in a group that is configured with XA transaction, tpopen() must be invoked before performing any transaction activities, such as tpbegin() and SQL operations. When transaction operations are finished, tpclose() should be called. Application-created server thread may send, but cannot receive unsolicited messages.
Sample Code for Associating Application Thread with Application-created server Context in a Multicontexted Server
For those applications with a need to create an application thread in a server, Listing 10-4 shows a multicontexted server example where a service creates another thread, and this application-created server thread operates in a separated context. Operating system (OS) threads functions differ from one OS to another. In this example, POSIX and ATMI functions are used. Note: In order to simplify the example, error checking code is not included. Listing 10-4 Code Sample for Application-Created Server Thread Working in Application-Created Context
#include <pthread.h> #include <atmi.h>
10-40
pthread_create( &withdrawalthreadid, NULL, withdrawalthread, ); tpcall("DEPOSIT", ...); pthread_join(withdrawalthreadid, NULL); tpreturn(TPSUCCESS, ...); }
void * withdrawalthread(void *arg) { tpappthrinit(NULL); tpopen(); tpcall("WITHDRAWAL", ...); tpclose(); tpappthrterm(); return(NULL); }
10-41
See Also
How Multithreading and Multicontexting Work in Application-Created Threads of an ATMI Server How Multithreading and Multicontexting Work in Server-Dispatched Threads an on ATMI Server
10-42
All RPC calls and all conversations must be completed before an attempt is made to commit the transaction. If an application calls tpcommit() while RPC calls or conversations are outstanding, tpcommit() aborts the transaction, returns -1, and sets tperrno(5) to TPEABORT. Functions such as tpcall(), tpacall(), tpgetrply(), tpconnect(), tpsend(), tprecv(), and tpdiscon() should not be called in transaction mode unless you are sure that the transaction is not already committing or aborting. Two tpbegin() calls cannot be made simultaneously for the same context.
tpbegin() cannot be issued for a context that is already in transaction mode.
If you are using a client and you want to connect to more than one domain, you must manually change the value of TUXCONFIG or WSNADDR before calling tpinit(). You must synchronize the setting of the environment variable and the tpinit() call if multiple threads may be performing such an action. All application associations in a client must obey the following rules: All associations must be made to the same release of the Oracle Tuxedo system. Either every application association in a particular client must be made as a native client, or every application association must be made as a Workstation client. To join an application, a multithreaded Workstation client must always call tpinit() with the TPMULTICONTEXTS flag set, even if the client is running in single-context mode.
On failure, tpinit() leaves the calling thread in its original context (that is, in the context state in which it was operating before the call to tpinit()). Do not call tpterm() from a given context if any of the threads in that context are still working. See the table labeled Multicontext State Transitions on page 10-44 for a description of the context states that result from calling tpterm() under these and other circumstances.
NULL CONTEXT
tpterm()
SINGLE CONTEXT
tpterm() or tpsetctxt()
MULTICONTEXT
INVALID CONTEXT
tpsetctxt()
10-44
Note: When tpterm() is called by a thread running in the multicontext state (TPMULTICONTEXTS), the calling thread is placed in the null context state (TPNULLCONTEXT). All other threads associated with the terminated context are switched to the invalid context state (TPINVALIDCONTEXT). The following table lists all possible context state changes produced by calling tpinit(), tpsetctxt(3c), and tpterm(). Table 10-2 Context State Changes for a Client Thread When this function is executed . . .
tpinit() without TPMULTICONTEXTS tpinit() with TPMULTICONTEXTS tpsetctxt(3c) to TPNULLCONTEXT tpsetctxt(3c) to context 0 tpsetctxt(3c) to context > 0
Single Context
Single context Error Error Single context
Multicontext
Error Multicontext Null Error
Invalid Context
Error Error Null Error
Multicontext
Error
Multicontext
Multicontext
Implicit tpinit()
tpterm() in this thread tpterm() in a different thread of this context
N/A Null
N/A Null
Error Null
N/A
Null
Invalid
N/A
10-45
tpgetrply() operates in only one context, which is the context in which it is called. Therefore, when you call tpgetrply() with the TPGETANY flag, only handles generated in the same context are considered. Similarly, a handle generated in one context may not be used in another context, but the handle may be used in any thread operating within the same context.
When tpgetrply() is called in a multithreaded environment, the following restrictions apply: If a thread calls tpgetrply() for a specific handle while another thread in the same context is already waiting in tpgetrply() for the same handle, tpgetrply() returns -1 and sets tperrno to TPEPROTO. If a thread calls tpgetrply() for a specific handle while another thread in the same context is already waiting in tpgetrply() with the TPGETANY flag, the call returns -1 and sets tperrno(5) to TPEPROTO. The same behavior occurs if a thread calls tpgetrply() with the TPGETANY flag while another thread in the same context is already waiting in tpgetrply() for a specific handle. These restrictions protect a thread that is waiting on a specific handle from having its reply taken by a thread waiting on any handle. At any given time, only one thread in a particular context can wait in tpgetrply() with the TPGETANY flag set. If a second thread in the same context invokes tpgetrply() with the TPGETANY flag while a similar call is outstanding, this second call returns -1 and sets tperrno(5) to TPEPROTO.
10-46
Caching is done on a . . .
Per-context basis
Per-process basis
The tuxputenv(3c) function affects the environment for the entire process. When you call the tuxreadenv(3c) function, it reads a file containing environment variables and adds them to the environment for the entire process. The tuxgetenv(3c) function returns the current value of the requested environment variable in the current context. Initially, all contexts have the same environment, but the use of environment files specific to a particular context can cause different contexts to have different environment settings. If a client intends to initialize to more than one domain, the client must change the value of the TUXCONFIG, WSNADDR, or WSENVFILE environment variable to the proper value before each call to tpinit(). If such an application is multithreaded, a mutex or other application-defined concurrency control will probably be needed to ensure that: The appropriate environment variable is reset. The call to tpinit() is made without the environment variable being reset by any other thread.
Programming an Oracle Tuxedo ATMI Application Using C 10-47
When a client initializes to the system, the WSENVFILE and/or machine environment file is read and affects the environment in that context only. The previous environment for the process as a whole remains for that context to the extent that it is not overridden within the environment file(s).
10-48
tprecv() tpresume() tpreturn() tpscmt(3c) tpsend() tpservice(3c) tpsetunsol() tpsubscribe() tpsuspend() tpterm() tpunsubscribe() tx_begin(3c) tx_close(3c) tx_commit(3c) tx_info(3c) tx_open(3c) tx_rollback(3c) tx_set_commit_return(3c) tx_set_transaction_control(3c) tx_set_transaction_timeout(3c) userlog(3c)
Note: For tpbroadcast(), the broadcast message is identified as having come from a particular application association. For tpnotify(3c), the notification is identified as having come from a particular application association. See Using Per-process Functions and Data Structures in a Multithreaded Client for notes about tpinit(). If tpsetunsol() is called from a thread that is not associated with a context, a per-process default unsolicited message handler for all new tpinit() contexts created is established. A specific context may change the unsolicited message handler for that context by calling tpsetunsol() again when the context is active. The per-process default unsolicited message handler may be changed by again calling tpsetunsol() in a thread not currently associated with a context.
10-49
The CLIENTID, client name, username, transaction ID, and the contents of the TPSVCINFO data structure may differ from context to context within the same process. Asynchronous call handles and connection descriptors are valid in the contexts in which they are created. The unsolicited notification type is specific per-context. Although signal-based notification may not be used with multiple contexts, each context may choose one of three options: Ignoring unsolicited messages Using dip-in notification Using dedicated thread notification
10-50
The determination of single-context mode, multicontext mode, or uninitialized mode affects an entire process. The buffer type switch, the view cache, and environment variable values are also per-process functions.
The Ferror, Ferror32(5), tperrno(5), tpurcode(5), and Uunix_err variables are specific to each thread. The identity of the current context is specific to each thread.
10-51
TPINIT * tpinitbuf; int timeout=60; pthread_t withdrawalthreadid, stockthreadid; TPCONTEXT_T ctxt; void * stackthread(void *); void * withdrawalthread(void *); main() { tpinitbuf = tpalloc(TPINIT, NULL, TPINITNEED(0)); /* * This code will perform a transfer, using separate threads for the * withdrawal and deposit. It will also get the current * price of Oracle stock from a separate application, and calculate how * many shares the transferred amount can buy. */ tpinitbuf->flags = TPMULTICONTEXTS; /* Fill in the rest of tpinitbuf. tpinit(tpinitbuf); */
tpgetctxt(&ctxt, 0); tpbegin(timeout, 0); pthread_create(&withdrawalthreadid, NULL, withdrawalthread, NULL); tpcall("DEPOSIT", ...); /* Wait for the withdrawal thread to complete. */ pthread_join(withdrawalthreadid, NULL); tpcommit(0); tpterm(); /* Wait for the stock thread to complete. */ pthread_join(stockthreadid, NULL); /* Print the results. */ printf("$%9.2f has been transferred \ from your savings account to your checking account.\n", ...); printf("At the current Oracle stock price of $%8.3f, \ you could purchase %d shares.\n", ...); exit(0); }
void *
10-52
stockthread(void *arg) { /* The other threads have now called tpinit(), so resetting TUXCONFIG can * no longer adversely affect them. */ tuxputenv("TUXCONFIG=/home/users/xyz/stockconf"); tpinitbuf->flags = TPMULTICONTEXTS; /* Fill in the rest of tpinitbuf. */ tpinit(tpinitbuf); tpcall("GETSTOCKPRICE", ...); /* Save the stock price in a variable that can also be accessed in main(). */ tpterm(); return(NULL); }
void * withdrawalthread(void *arg) { /* Create a separate thread to get stock prices from a different * application. */
See Also
How Multithreading and Multicontexting Work in a Client on page 10-9 Preliminary Guidelines for Programming a Multithreaded/Multicontexted ATMI Application on page 10-24 Writing Code to Enable Multicontexting in an ATMI Client on page 10-27
10-53
time and later try to boot the new server with a configuration file in which the value of MAXDISPATCHTHREADS is greater than 1, a warning message is recorded in the user log and the server reverts to single-threaded operation. To identify any operating system-specific compiler parameters that are required when you compile .c files into .o files in a multithreaded environment, run buildclient(1) or buildserver(1) with the -v option set on a test file.
See Also
Writing Code to Enable Multicontexting in an ATMI Client on page 10-27 Writing Code to Enable Server-Dispatched Multicontexting and Multithreading Threads in an ATMI Server on page 10-34 Writing Code to Enable Multicontexting in Application-Created Threads of an ATMI Server on page 10-36 Writing a Multithreaded ATMI Client on page 10-42
10-54
If a client has not joined an application and tpinit() is called implicitly (as a result of a call to another function that calls tpinit()), then the Oracle Tuxedo system interprets the action as a call to tpinit() without the TPMULTICONTEXTS flag for purposes of determining which flags may be used in subsequent calls to tpinit(). For most ATMI functions, if a function is invoked by a thread that is not associated with a context in a process already operating in multicontext mode, the ATMI function fails with tperrno(5)=TPEPROTO.
See Also
How Multithreading and Multicontexting Work in a Client on page 10-9
10-56 Programming an Oracle Tuxedo ATMI Application Using C
How Multithreading and Multicontexting Work in Server-Dispatched Threads an on ATMI Server on page 10-14 How Multithreading and Multicontexting Work in Application-Created Threads of an ATMI Server on page 10-18 Preliminary Guidelines for Programming a Multithreaded/Multicontexted ATMI Application on page 10-24
10-57
10-58
C H A P T E R 11
Managing Errors
This topic includes the following sections: System Errors Application Errors Handling Errors Transaction Considerations Central Event Log Debugging Application Processes Comprehensive Example
System Errors
The Oracle Tuxedo system uses the tperrno(5) variable to supply information to a process when a function fails. All ATMI functions that normally return an integer or pointer return -1 or NULL, respectively, on error and set tperrno() to a value that describes the nature of the error. When a function does not return to its caller, as in the case of tpreturn() or tpforward(), which are used to terminate a service routine, the only way the system can communicate success or failure is through the variable tperrno() in the requester. The tperrordetail(3c) and tpstrerrordetail(3c) functions can be used to obtain additional detail about an error in the most recent Oracle Tuxedo system call on the current thread. tperrordetail() returns an integer (with an associated symbolic name) which is then
11-1
used as an argument to tpstrerrordetail() to retrieve a pointer to a string that contains the error message. The pointer can then be used as an argument to userlog(3c) or fprintf(). For a list of the symbolic names that can be returned, refer to tperrordetail(3c) in the Oracle Tuxedo ATMI C Function Reference.
tpurcode(5) is used to communicate user-defined conditions only. The system sets the value of tpurcode to the value of the rcode argument of tpreturn(). The system sets tpurcode,
regardless of the value of the rval argument of tpreturn(), unless an error is encountered by
tpreturn() or a transaction timeout occurs.
The codes returned in tperrno(5) represent categories of errors, which are listed in the following table. Table 11-1 tperrno Error Categories Error Category
Abort Oracle Tuxedo system1 Call descriptor Conversational Duplicate operation General communication
tperrno Values
TPEABORT2 TPESYSTEM TPELIMIT and TPEBADDESC TPEVENT TPEMATCH TPESVCFAIL, TPESVCERR, TPEBLOCK, and TPGOTSIG TPEHAZARD2 and TPEHEURISTIC2 TPEINVAL TPEMIB TPENOENT TPEOS TPEPERM TPEPROTO
Heuristic decision Invalid argument1 MIB No entry Operating system1 Permission Protocol1
11-2
S ys te m E rror s
tperrno Values
TPEDIAGNOSTIC TPERELEASE TPERMERR TPETIME TPETRAN2 TPEITYPE and TPEOTYPE
1. Applicable to all ATMI functions for which failure is reported by the value returned in tperrno(5). 2. Refer to Fatal Transaction Errors on page 11-32 for more information on this error category.
As footnote 1 shows, four categories of errors are reported by tperrno(5) and are applicable to all ATMI functions. The remaining categories are used only for specific ATMI functions.The following sections describe some error categories in detail.
11-3
Abort Errors
For information on the errors that lead to abort, refer to Fatal Transaction Errors on page 11-32.
11-4
C al l D e s c r i pt o r E rr o r s
Limit Errors
The system allows up to 50 outstanding call descriptors (replies) per context (or Oracle Tuxedo application association). This limit is enforced by the system; it cannot be redefined by your application. The limit for call descriptors for simultaneous conversational connections is more flexible than the limit for replies. The application administrator defines the limit in the configuration file. When the application is not running, the administrator can modify the MAXCONV parameter in the RESOURCES section of the configuration file. When the application is running, the administrator can modify the MACHINES section dynamically. Refer to tmconfig, wtmconfig(1) in the Oracle Tuxedo Command Reference for more information.
11-5
When the application calls tpabort() or tpcommit() and transaction replies (sent without the TPNOTRAN flag) remain to be retrieved. A transaction times out. When the timeout is reported by a call to tpgetrply(), no message is retrieved using the specified descriptor and the descriptor becomes stale.
11-6
C o nv e r s at i o na l E rr o r s
Conversational Errors
When an unknown descriptor is specified for conversational services, the tpsend(), tprecv(), and tpdiscon() functions return TPEBADDESC. When tpsend() and tprecv() fail with a TPEEVENT error after a conversational connection is established, an event has occurred. Data may or may not be sent by tpsend(), depending on the event. The system returns TPEEVENT in the revent parameter passed to the function call and the course of action is dictated by the particular event. For a complete description of conversational events, refer to Understanding Conversational Communication Events on page 7-12.
11-7
Function
tpadvertise
Cause
The svcname specified is already advertised for the server but with a function other than func. Although the function fails, svcname remains advertised with its current function (that is, func does not replace the current function name). The tranid points to a transaction identifier that another process has already resumed. In this case, the callers state with respect to the transaction is not changed. The specified subscription information has already been listed with the EventBroker.
tpresume
tpsubscribe
For more information on these functions, refer to the Oracle Tuxedo ATMI C Function Reference
11-8
G e ner al C o m m un i c a t i o n C al l E rr o r s
11-9
The system returns TPEBLOCK for tpgetrply() when a call is made with flags set to TPNOBLOCK and a blocking condition is encountered while tpgetrply() is awaiting the reply. This may occur, for example, if a message is not currently available. The TPGOTSIG error indicates an interruption of a system call by a signal; this situation is not actually an error condition. If the flags parameter for the communication functions is set to TPSIGRSTRT, the calls do not fail and the system does not return the TPGOTSIG error code in tperrno(5).
11-10
I nv al i d A rg um e nt E rr o r s
11-11
MIB Error
The tpadmcall(3c) function returns TPEMIB in tperrno(5) in the event an administrative request fails. outbuf is updated and returned to the caller with FML32 fields indicating the cause of the error. For more information on the cause of the error, refer to MIB(5) and TM_MIB(5) in File Formats, Data Descriptions, MIBs, and System Processes Reference.
11-12
N o En tr y E rr o r s
No Entry Errors
No entry errors result from a lack of entries in the system tables or the data structure used to identify buffer types. The meaning of the no entry type error, TPENOENT, depends on the function that is returning it. The following table lists the functions that return this error and describes various causes of error. Table 11-2 No Entry Errors Function
tpalloc()
Cause
The system does not know about the type of buffer requested. For a buffer type and/or subtype to be known, there must be an entry for it in a type switch data structure that is defined in the Oracle Tuxedo system libraries. Refer to tuxtypes(5) and typesw(5) in the File Formats, Data Descriptions, MIBs, and System Processes Reference for more information. On an application level, ensure that you have referenced a known type; otherwise, check with the system administrator.
tpinit()
The calling process cannot join the application because there is no space left in the bulletin board to make an entry for it. Check with the system administrator. The calling process references a service called that is not known to the system since there is no entry for it in the bulletin board. On an application level, ensure that you have referenced the service correctly; otherwise, check with the system administrator. The system cannot connect to the specified name because the service named does not exist or it is not a conversational service. The calling process seeks a request priority when no request has been made. This is an application-level error. The system cannot unadvertise the service name because the name is not currently advertised by the calling process.
tpcall() tpacall()
tpconnect()
tpgprio()
tpunadvertise()
11-13
Cause
The system cannot access the queue space because the associated TMQUEUE(5)server is not available. Refer to the File Formats, Data Descriptions, MIBs, and System Processes Reference for more information. The system cannot access the Oracle Tuxedo system Event Broker. Refer to Writing Event-based Clients and Servers on page 8-1 for more information.
11-14
11-15
Permission Errors
If a calling process does not have the correct permissions to join the application, the tpinit() call fails, returning TPEPERM in tperrno(5). Permissions are set in the configuration file, outside of the application. If you encounter this error, check with the application administrator to make sure the necessary permissions are set in the configuration file.
11-16
Protoco l Errors
Protocol Errors
Protocol errors occur when an ATMI function is invoked, either in the wrong order or using an incorrect process. For example, a client may try to begin communicating with a server before joining the application. Or tpcommit() may be called by a transaction participant instead of the initiator. You can correct a protocol error at the application level by enforcing the rules of order and proper usage of ATMI calls. To determine the cause of a protocol error, answer the following questions: Is the call being made in the correct order? Is the call being made by the correct process? Protocol errors return the TPEPROTO value in tperrno(5). Refer to Introduction to the C Application-Transaction Monitor Interface in the Oracle Tuxedo ATMI C Function Reference for more information.
11-17
Queuing Error
The tpenqueue(3c) or tpdequeue(3c) function returns TPEDIAGNOSTIC in tperrno(5) if the enqueuing or dequeuing on a specified queue fails. The reason for failure can be determined by the diagnostic returned via the ctl buffer. For a list of valid ctl flags, refer to tpenqueue(3c) or tpdequeue(3c) in the Oracle Tuxedo ATMI C Function Reference
11-18
11-19
11-20
T i m e o ut E rr o r s
Timeout Errors
The Oracle Tuxedo system supports timeout errors to establish a limit on the amount of time that the application waits for a service request or transaction. The Oracle Tuxedo system supports two types of configurable timeout mechanisms: blocking and transaction. A blocking timeout specifies the maximum amount of time that an application waits for a reply to a service request. The application administrator defines the blocking timeout for the system in the configuration file. A transaction timeout defines the duration of a transaction, which may involve several service requests. To define the transaction timeout for an application, pass the timeout argument to tpbegin(). The system may return timeout errors on communication calls for either blocking or transaction timeouts, and on tpcommit() for transaction timeouts only. In each case, if a process is in transaction mode and the system returns TPETIME on a failed call, a transaction timeout has occurred. By default, if a process is not in transaction mode, the system performs blocking timeouts. When you set the flags parameter of a communication call to TPNOTIME, the flag setting applies to blocking timeouts only. If a process is in transaction mode, blocking timeouts are not performed and the TPNOTIME flag setting is not relevant. If a process is not in transaction mode and a blocking timeout occurs on an asynchronous call, the communication call that blocked fails, but the call descriptor is still valid and may be used on a reissued call. Other communication is not affected. When a transaction timeout occurs, the call descriptor to an asynchronous transaction reply (specified without the TPNOTRAN flag) becomes stale and may no longer be referenced.
TPETIME indicates a blocking timeout on a communication call if the call was not made in
transaction mode or if the flags parameter was not set to TPNOBLOCK. Note: If you set the TPNOBLOCK flag, a blocking timeout cannot occur because the call returns immediately if a blocking condition exists. For additional information on handling timeout errors, refer to Transaction Considerations on page 11-28.
11-21
Transaction Errors
For information on transactions and the non-fatal and fatal errors that can occur, refer to Transaction Considerations on page 11-28.
11-22
Application Errors
Within an application, you can pass information about user-defined errors to calling programs using the rcode argument of tpreturn(). Also, the system sets the value of tpurcode to the value of the rcode argument of tpreturn(). For more information about tpreturn(3c) or tpurcode(5), refer to the Oracle Tuxedo ATMI C Function Reference and the File Formats, Data Descriptions, MIBs, and System Processes Reference, respectively.
Handling Errors
Your application logic should test for error conditions for the calls that have return values, and take appropriate action when an error occurs. Specifically, you should: Test to determine whether a -1 or NULL value has been returned (depending on the function call).
Programming an Oracle Tuxedo ATMI Application Using C 11-23
Invoke code that contains a switch statement that tests for specific values of tperrno(5) and performs the appropriate application logic. The ATMI supports three functions, tpstrerrordetail(3c), tpstrerror(3c), and Fstrerror, Fstrerror32(3fml), for retrieving the text of an error message from the message catalogs for the Oracle Tuxedo system and FML. The functions return pointers to the appropriate error messages. Your program can use a pointer to direct the referenced text to userlog(3c) or to another destination. For details, refer to tpstrerrordetail(3c) and tpstrerror(3c) in the Oracle Tuxedo ATMI C Function Reference, and Fstrerror, Fstrerror32(3fml) in the Oracle Tuxedo ATMI FML Function Reference. The following example shows a typical method of handling errors. The atmicall() function in this example represents a generic ATMI call. Note the code after the switch statement (line 21): it shows how tpurcode can be used to interpret an application-defined return code. Listing 11-1 Handling Errors
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 if (rtnval == -1) { switch(tperrno) { allocate any buffers, make atmi calls check return value rtnval = atmicall(); main() { int rtnval; if (tpinit((TPINIT *) NULL) == -1) error message, exit program; if (tpbegin(30, 0) == -1) error message, tpterm, exit program; #include <stdio.h> #include "atmi.h"
11-24
H an dl i ng E rr o r s
022 023 024 025 026 027 028 029 030 page. 032 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 }
case TPEINVAL: fprintf(stderr, "Invalid arguments were given to atmicall\n"); fprintf(stderr, "e.g., service name was null or flags wrong\n"); break; case ...: fprintf(stderr, ". . ."); break; Include all error cases described in the atmicall(3) reference 031 Other return codes are not possible, so there should be no 033 default
within the switch statement. if (tpabort(0) == -1) { char *p; fprintf(stderr, "abort was attempted but failed\n"); p = tpstrerror(tperrno); userlog("%s", p); } else if (tpcommit(0) == -1) fprintf(stderr, "REPORT program failed at commit time\n"); The following code fragment shows how an application-specific return code can be examined. . . . **)&rcvbuf,
051 ret = tpcall("servicename", (char*)sendbuf, 0, (char &rcvlen, \ 052 053 054 055 056 057 058 (long)0); . . .
11-25
The values of tperrno(5) provide details about the nature of each problem and suggest the level at which it can be corrected. If your application defines a list of error conditions specific to your processing, the same can be said for the values of tpurcode. The following example shows how to use the tpstrerrordetail(3c) function to obtain additional detail when an error is encountered. Listing 11-2 Handling Errors Using tpstrerrordetail( )
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 } /* Attach to BEA Tuxedo System as a Client Process */ if (tpinit((TPINIT *) NULL) == -1) { #include <stdio.h> #include <string.h> #include <atmi.h>/* BEA Tuxedo #define LOOP_ITER 100 #if defined(__STDC__) || defined(__cplusplus) main(int argc, char *argv[]) #else main(argc, argv) int argc; char *argv[]; #endif { char *sendbuf, *rcvbuf; long sendlen, rcvlen; int ret; int i; if(argc != 2) { (void) fprintf(stderr, "Usage: simpcl string\n"); exit(1); Header File */
11-26
H an dl i ng E rr o r s
023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 TOUPPER\n"); 051 052 053 054 055 056 } } }
(void) fprintf(stderr, "Tpinit failed\n"); exit(1); sendlen = strlen(argv[1]); /* Allocate STRING buffers for the request and the reply */ if((sendbuf = (char *) tpalloc("STRING", NULL, sendlen+1)) == NULL) { (void) fprintf(stderr,"Error allocating send buffer\n"); tpterm(); exit(1);
if((rcvbuf = (char *) tpalloc("STRING", NULL, sendlen+1)) == NULL) { (void) fprintf(stderr,"Error allocating receive buffer\n"); tpfree(sendbuf); tpterm(); exit(1);
for( i=0; i<LOOP_ITER; i++) { (void) strcpy(sendbuf, argv[1]); /* Request the service TOUPPER, waiting for a reply */ ret = tpcall("TOUPPER", (char *)sendbuf, 0, (char **)&rcvbuf,
&rcvlen, (long)0); if(ret == -1) { (void) fprintf(stderr, "Can't send request to service (void) fprintf(stderr, "Tperrno = %d, %s\n", tperrno,
tpstrerror(tperrno)); ret = tperrordetail(0); if(ret == -1) { (void) fprintf(stderr, "tperrodetail() failed!\n"); (void) fprintf(stderr, "Tperrno = %d, %s\n", tperrno,
tpstrerror(tperrno));
11-27
057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 } }
} else if (ret != 0) { (void) fprintf( stderr, "errordetail:%s\n", tpstrerrordetail( ret, 0)); } tpfree(sendbuf); tpfree(rcvbuf); tpterm(); exit(1); (void) fprintf(stdout, "Returned string is: %s\n", rcvbuf); } /* Free Buffers & Detach from System/T */ tpfree(sendbuf); tpfree(rcvbuf); tpterm(); return(0);
Transaction Considerations
The following sections describe how various programming features work when used in transaction mode. The first section provides rules of basic communication etiquette that should be observed in code written for transaction mode.
11-28
Communication Etiquette
When writing code to be run in transaction mode, you must observe the following rules of basic communication etiquette: Processes that are participants in the same transaction must require replies for all requests. To include a request that requires no reply, set the flags parameter of tpacall() to TPNOTRAN or TPNOREPLY. A service must retrieve all asynchronous transaction replies before calling tpreturn() or tpforward(). This rule must be observed regardless of whether the code is running in transaction mode. The initiator must retrieve all asynchronous transaction replies (made without the TPNOTRAN flag) before calling tpcommit(). Replies must be retrieved for asynchronous calls that expect replies from non-participants of the transaction, that is, replies to requests made with tpacall() in which the transaction, but not the reply, is suppressed. If a transaction has not timed out but is marked abort-only, any further communication should be performed with the TPNOTRAN flag set so that the results of the communication are preserved after the transaction is rolled back. If a transaction has timed out: The descriptor for the timed-out call becomes stale and any further reference to it returns TPEBADDESC. Further calls to tpgetrply() or tprecv() for any outstanding descriptors return a global state of transaction timeout; the system sets tperrno(5) to TPETIME. Asynchronous calls can be made with the flags parameter of tpacall() set to TPNOREPLY, TPNOBLOCK, or TPNOTRAN. Once a transaction has been marked abort-only for reasons other than timeout, a call to tpgetrply() returns whatever value represents the local state of the call; that is, it returns either success or an error code that reflects the local condition. Once a descriptor is used with tpgetrply() to retrieve a reply, or with tpsend() or tprecv() to report an error condition, it becomes invalid and any further reference to it returns TPEBADDESC. This rule is always observed, regardless of whether the code is running in transaction mode.
11-29
Once a transaction is aborted, all outstanding transaction call descriptors (made without the TPNOTRAN flag) become stale, and any further references to them return TPEBADDESC.
11-30
Transaction Errors
Transaction Errors
The following sections describe transaction-related errors.
Cause
Usually caused by a transient system error that occur during an attempt to start the transaction. The problem may clear up with a repeated call. The function was called for a transaction reply after a request was made without the TPNOTRAN flag. The Oracle Tuxedo system is unable to resume a global transaction because the caller is currently participating in work outside the global transaction with one or more resource managers. All such work must be completed before the global transaction can be resumed. The callers state with respect to the local transaction is unchanged. A call was made in transaction mode to a service that does not support transactions. Some services belong to server groups that access a database management system (DBMS) that, in turn, support transactions. Other services, however, do not belong to such groups. In addition, some services that support transactions may require interoperation with software that does not. For example, a service that prints a form may work with a printer that does not support transactions. Services that do not support transactions may not function as participants in a transaction. The grouping of services into servers and server groups is an administrative task. In order to determine which services support transactions, check with your application administrator. You can correct transaction-level errors at the application level by enabling the TPNOTRAN flag or by accessing the service for which an error was returned outside of the transaction.
tpcancel()
tpresume()
11-31
The only protocol error that is fatal to transactions is calling tpcommit() from the wrong participant in a transaction. This error can be corrected in the application during the development phase. If tpcommit() is called after an initiator/participant failure or transaction timeout, the result is an implicit abort error. Then, because the commit failed, the transaction should be aborted. If the system returns TPESVCERR, TPESVCFAIL, TPEOTYPE, or TPETIME for any communication call, the transaction should be aborted explicitly with a call to tpabort(). You need not wait for outstanding call descriptors before explicitly aborting the transaction. However, because these descriptors are considered stale after the call is aborted, any attempt to access them after the transaction is terminated returns TPEBADDESC. In the case of TPESVCERR, TPESVCFAIL, and TPEOTYPE, communication calls continue to be allowed as long as the transaction has not timed out. When these errors are returned, the transaction is marked abort-only. To preserve the results of any further work, you should call any communication functions with the flags parameter set to TPNOTRAN. By setting this flag, you ensure that the work performed for the transaction marked abort-only will not be rolled back when the transaction is aborted. When a transaction timeout occurs, communication can continue, but communication requests cannot:
11-32 Programming an Oracle Tuxedo ATMI Application Using C
Transaction Errors
Require replies Block Be performed on behalf of the callers transaction Therefore, to make asynchronous calls, you must set the flags parameter to TPNOREPLY, TPNOBLOCK, or TPNOTRAN.
resource manager is involved in the transaction and it returns a heuristic decision or a hazard indication during a one-phase commit. If you set TP_COMMIT_CONTROL to TP_CMT_COMPLETE, then the system returns TPEHEURISTIC if any resource manager reports a heuristic decision, and TPEHAZARD if any resource manager reports a hazard. TPEHAZARD specifies that a participant failed during the second phase of commit (or during a one-phase commit) and that it is not known whether a transaction completed successfully.
11-33
Transaction Timeouts
As described in Transaction Errors on page 11-31, two types of timeouts can occur in an Oracle Tuxedo application: blocking and transaction. The following sections describe how various programming features are affected by transaction timeouts. Refer to Transaction Errors on page 11-31 for more information on timeouts.
11-34
t pr e t ur n ( ) a nd t pf o r w a rd ( ) F un c t i o n s
11-35
tpterm( ) Function
Use the tpterm() function to remove a client context from an application. If the client context is in transaction mode, the call fails with TPEPROTO returned in tperrno(5), and the client context remains part of the application and in transaction mode. When the call is successful, the client context is allowed no further communication or participation in transactions because the current thread of execution is no longer part of the application.
11-36
Resource Managers
Resource Managers
When you use an ATMI function to define transactions, the Oracle Tuxedo system executes an internal call to pass any global transaction information to each resource manager participating in the transaction. When you call tpcommit() or tpabort(), for example, the system makes internal calls to direct each resource manager to commit or abort the work it did on behalf of the callers global transaction. When a global transaction has been initiated, either explicitly or implicitly, you should not make explicit calls to the resource managers transaction functions in your application code. Failure to follow this transaction rule causes indeterminate results. You can use the tpgetlev() function to determine whether a process is already in a global transaction before calling the resource managers transaction function. Some resource managers allow programmers to configure certain parameters (such as the transaction consistency level) by specifying options available in the interface to the resource managers themselves. Such options are made available in two forms: Resource manager-specific function calls that can be used by programmers of distributed applications to configure options. Hard-coded options incorporated in the transaction interface supplied by the provider of the resource manager. Consult the documentation for your resource managers for additional information. The method of setting options varies for each resource manager. In the Oracle Tuxedo System SQL resource manager, for example, the set transaction statement is used to negotiate specific options (consistency level and access mode) for a transaction that has already been started by the Oracle Tuxedo system.
11-37
The success or failure of the called process affects the current transaction. If any fatal transaction errors are encountered by the participant, the current transaction is marked abort-only. Whether or not the tasks performed by a successful participant are applied depends on the fate of the transaction. In other words, if the transaction is aborted, the work of all participants is reversed. The TPNOREPLY flag cannot be used when calling another service to participate in the current transaction.
11-38
Because it is in transaction mode, tpreturn() is vulnerable to the failure of any participant in the transaction, as well as to transaction timeouts. In this scenario, the system is more likely to return a failed message. The state of the callers transaction is not affected by any failed messages or application failures returned to the caller. The callers own transaction may timeout as the caller waits for a reply. If no reply is expected, the callers transaction cannot be affected in any way by the communication call. Figure 11-1 Transaction Roles of tpforward( ) and tpreturn() with AUTOTRAN
11-39
Typically, the system returns processing errors, buffer type errors, or application failure, and follows the normal rules for TPESVCFAIL, TPEITYPE/TPEOTYPE, and TPESVCERR. The state of the callers transaction is not affected by any failed messages or application failures returned to the caller. The caller is vulnerable to the possibility that its own transaction may time out as it waits for its reply. If no reply is expected, the callers transaction cannot be affected in any way by the communication call.
11-40
O r acl e T U X ED O S y s t e m - s u pp l i e d S ub ro ut i n e s
11-41
Log Name
The application administrator defines (in the configuration file) the absolute pathname that is used as the prefix of the name of the userlog(3c) error message file on each machine. The userlog(3c) function creates a datein the form mmddyy, representing the month, day, and yearand adds this date to the pathname prefix, forming the full filename of the central event log. A new file is created daily. Thus, if a process sends messages to the central event log on succeeding days, the messages are written into different files.
In this example, the process ID for security is 23451, and the variable usrnm contains the value abc. If the preceding message was generated by the Oracle Tuxedo system (rather than by the application), it might appear as follows:
162214.mach1!security.23451: LIBSEC_CAT: 999: Unknown User abc
11-42
Ce nt r al Eve nt L o g
In this case, the message catalog name is LIBSEC_CAT and the message number is 999. If the message is sent to the central event log while the process is in transaction mode, other components are added to the tag in the user log entry. These components consist of the literal string gtrid followed by three long hexadecimal integers. The integers uniquely identify the global transaction and make up what is referred to as the global transaction identifier, that is, the gtrid. This identifier is used mainly for administrative purposes, but it also appears in the tag that prefixes the messages in the central event log. If the system writes the message to the central event log in transaction mode, the resulting log entry appears as follows:
162214.mach1!security.23451: gtrid x2 x24e1b803 x239: Unknown User abc
In this example, the message is sent to the central event log if tpopen(3c) returns -1. The userlog(3c) signature is similar to that of the UNIX System printf(3S) function. The format portion of both functions can contain literal strings and/or conversion specifications for a variable number of arguments.
11-43
To execute a client process: 1. Set any desired breakpoints in the code. 2. Enter the dbx command. 3. At the dbx prompt (*), type the run subcommand (r) and any options you want to pass to the client programs main(). The task of debugging server programs is more complicated. Normally a server is started using the tmboot command, which starts the server on the correct machine with the correct options. When using dbx, it is necessary to run a server directly rather than through the tmboot command. To run a server directly, enter the r (short for run) subcommand after the prompt displayed by the dbx command. The Oracle Tuxedo tmboot(1) command passes undocumented command-line options to the servers predefined main(). To run a server directly, you must pass these options, manually, to the r subcommand. To find out which options need to be specified, run tmboot with the -n and -d 1 options. The -n option instructs tmboot not to execute a boot; -d 1 instructs it to display level 1 debugging statements. By default, the -d 1 option returns information about all processes. If you want information about only one process, you can specify your request accordingly with additional options. For more information, refer to the Oracle Tuxedo Command Reference. The output of tmboot -n -d 1 includes a list of the command-line options passed by tmboot to the servers main(), as shown in the following example:
11-44 Programming an Oracle Tuxedo ATMI Application Using C
Once you have the list of required command-line options, you are ready to run the server program directly, with the r subcommand of dbx(1). The following command line is an example:
*r -g 1 -i 1 -u sfmax -U /tuxdir/appdir/ULOG -m 0 -A
You may not use dbx(1) to run a server that is already running as part of the configuration. If you try to do so, the server exits gracefully, indicating a duplicate server in the central event log.
Note: For versions of the Microsoft Visual C++ debugger that are earlier than 5.0, enter the start command as follows:
start msdev -p process_id
To invoke the debugger and automatically enter a process, specify the process name and arguments on the start command line, as follows:
start msdev filename argument
For example, to invoke the debugger and enter the simpcl.exe process with the ConvertThisString argument, enter the following command:
start msdev simpcl.exe ConvertThisString
When a user-mode exception occurs, you are prompted to invoke the default system debugger to examine the location of the program failure and the state of the registers, stacks, and so on. By default, Dr. Watson is used in the Windows 2003 environment uses as the default debugger for user-mode exception failures, while the kernel debugger is used in the Win32 SDK environment. To modify the default debugger used by the Windows 2003 system for user-mode exception failures, perform the following steps: 1. Run regedit or regedt32.
11-45
3. Double-click on the Debugger key to advance into the registry string editor. 4. Modify the existing string to specify the debugger of your choice. For example, to request the debugger supplied with the Microsoft Visual C++ environment, enter the following command:
msdev.exe -p %ld -e %ld
Note: For versions of the Microsoft Visual C++ debugger that are earlier than 5.0, enter the following command:
msvc.exe -p %ld -e %ld
Comprehensive Example
Transaction integrity, message communication, and resource access are the major requirements of an Online-Transaction-Processing (OLTP) application. This section provides a code sample that illustrates the ATMI transaction, buffer management, and communication routines operating together with SQL statements that access a resource manager. The example is borrowed from the ACCT server that is part of the Oracle Tuxedo banking application (bankapp) and illustrates the CLOSE_ACCT service. The example shows how the set transaction statement (line 49) is used to set the consistency level and access mode of the transaction before the first SQL statement that accesses the database. (When read/write access is specified, the consistency level defaults to high consistency.) The SQL query determines the amount to be withdrawn in order to close the account based on the value of the ACCOUNT_ID (lines 50-58).
tpalloc() allocates a buffer for the request message to the WITHDRAWAL service, and the ACCOUNT_ID and the amount to be withdrawn are placed in the buffer (lines 62-74). Next, a request is sent to the WITHDRAWAL service via a tpcall() call (line 79). An SQL delete statement then updates the database by removing the account in question (line 86).
If all is successful, the buffer allocated in the service is freed (line 98) and the TPSVCINFO data buffer that was sent to the service is updated to indicate the successful completion of the transaction (line 99). Then, if the service was the initiator, the transaction is automatically committed. tpreturn() returns TPSUCCESS, along with the updated buffer, to the client process that requested the closing of the account. Finally, the successful completion of the requested service is reported on the status line of the form.
11-46
C o m p re hen s i v e E x amp l e
After each function call, success or failure is determined. If a failure occurs, the buffer allocated in the service is freed, any transaction begun in the service is aborted, and the TPSVCINFO buffer is updated to show the cause of failure (lines 80-83). Finally, tpreturn() returns TPFAIL and the message in the updated buffer is reported on the status line of the form. Note: When specifying the consistency level of a global transaction in a service routine, take care to define the level in the same way for all service routines that may participate in the same transaction. Listing 11-3 ACCT Server
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 #include #include #include #include #include #include #include #include #include #include <stdio.h> <string.h> <fml.h> <atmi.h> <Usysflds.h> <sqlcode.h> <userlog.h> "bank.h" "bank.flds.h" "event.flds.h" /* /* /* /* /* /* /* /* /* /* UNIX */ UNIX */ BEA Tuxedo System */ BEA Tuxedo System */ BEA Tuxedo System */ BEA Tuxedo System */ BEA Tuxedo System */ BANKING #defines */ bankdb fields */ event fields */
EXEC SQL begin declare section; static long account_id; static long branch_id; static float bal, tlr_bal; static char acct_type; static char last_name[20], first_name[20]; static char mid_init; static char address[60]; static char phone[14]; static long last_acct; EXEC SQL end declare section; static FBFR *reqfb; static long reqlen; static char amts[BALSTR]; code for OPEN_ACCT service /* * Service to close an account */
/* /* /* /* /* /* /* /* /*
account id */ branch id */ BALANCE */ account type*/ last name, first name */ middle initial */ address */ telephone */ last account branch gave */
/* fielded buffer for request message */ /* length of request buffer */ /* string representation of float */
11-47
031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069
void #ifdef __STDC__ LOSE_ACCT(TPSVCINFO *transb) #else CLOSE_ACCT(transb) TPSVCINFO *transb; #endif { FBFR *transf; /* fielded buffer of decoded message */
/* set pointer to TPSVCINFO data buffer */ transf = (FBFR *)transb->data; /* must have valid account number */ if (((account_id = Fvall(transf, ACCOUNT_ID, 0)) < MINACCT) || (account_id > MAXACCT)) { (void)Fchg(transf, STATLIN, 0, "Invalid account number", (FLDLEN)0); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } /* Set transaction level */ EXEC SQL set transaction read write; /* Retrieve AMOUNT to be deleted */ EXEC SQL declare ccur cursor for select BALANCE from ACCOUNT where ACCOUNT_ID = :account_id; EXEC SQL open ccur; EXEC SQL fetch ccur into :bal; if (SQLCODE != SQL_OK) { /* nothing found */ (void)Fchg(transf, STATLIN, 0, getstr("account",SQLCODE), (FLDLEN)0); EXEC SQL close ccur; tpreturn(TPFAIL, 0, transb->data, 0L, 0); } /* Do final withdrawal */ /* make withdraw request buffer */ if ((reqfb = (FBFR *)tpalloc("FML",NULL,transb->len)) == (FBFR *)NULL) { (void)userlog("tpalloc failed in close_acct\n"); (void)Fchg(transf, STATLIN, 0, "Unable to allocate request buffer", (FLDLEN)0); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } reqlen = Fsizeof(reqfb); (void)Finit(reqfb,reqlen);
11-48
C o m p re hen s i v e E x amp l e
070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100
/* put ID in request buffer */ (void)Fchg(reqfb,ACCOUNT_ID,0,(char *)&account_id, (FLDLEN)0); /* put amount into request buffer */ (void)sprintf(amts,"%.2f",bal); (void)Fchg(reqfb,SAMOUNT,0,amts, (FLDLEN)0); /* increase the priority of this withdraw */ if (tpsprio(PRIORITY, 0L) == -1) (void)userlog("Unable to increase priority of withdraw"); /* tpcall to withdraw service to remove remaining balance */ if (tpcall("WITHDRAWAL", (char *)reqfb, 0L, (char **)&reqfb, (long *)&reqlen,TPSIGRSTRT) == -1) { (void)Fchg(transf, STATLIN, 0,"Cannot make withdrawal", (FLDLEN)0); tpfree((char *)reqfb); tpreturn(TPFAIL, 0,transb->data, 0L, 0); } /* Delete account record */ EXEC SQL delete from ACCOUNT where current of ccur; if (SQLCODE != SQL_OK) { /* Failure to delete */ (void)Fchg(transf, STATLIN, 0,"Cannot close account", (FLDLEN)0); EXEC SQL close ccur; tpfree((char *)reqfb); tpreturn(TPFAIL, 0, transb->data, 0L, 0); } EXEC SQL close ccur; /* prepare buffer for successful return */ (void)Fchg(transf, SBALANCE, 0, Fvals(reqfb,SAMOUNT,0), (FLDLEN)0); (void)Fchg(transf, FORMNAM, 0, "CCLOSE", (FLDLEN)0); (void)Fchg(transf, STATLIN, 0, " ", (FLDLEN)0); tpfree((char *)reqfb); tpreturn(TPSUCCESS, 0, transb->data, 0L, 0); }
11-49
11-50