Difference between revisions of "I2Rpc EN"
(→I2RC000001 подключение к серверу) |
(→I2RC000002 RPC вызов программ) |
||
Line 358: | Line 358: | ||
:If statefull=0, then these parameters are not filled in the response | :If statefull=0, then these parameters are not filled in the response | ||
− | ==I2RC000002 RPC | + | ==I2RC000002 RPC program call== |
− | + | The I2RC000002 format is used to call programs remotely using i2Rpc | |
− | + | Parameters structure | |
// I2RC000002 - Run program | // I2RC000002 - Run program | ||
Line 405: | Line 405: | ||
D joblog * O (withJobLog*+joblogProvided) | D joblog * O (withJobLog*+joblogProvided) | ||
− | + | Parameters: | |
− | * '''connection''' | + | * '''connection''' previously obtained connection handler |
− | * '''lib/pgm''' input - | + | * '''lib/pgm''' input - the name of the program to be called. *LIBL can be used in lib. The program must be "visible" in the list of libraries of the target job |
− | : output - | + | : output - if the parameter returnResolvedName=1, then the real name of the library and program used in the remote call is returned in these fields |
− | * '''argc''' | + | * '''argc''' number of program parameters |
− | * '''argv''' | + | * '''argv''' array of argc elements - pointers to program parameters |
− | * '''argl''' | + | * '''argl''' array of program parameter lengths. Each array element defines the length of the corresponding element of the argv array |
− | * '''sendTimeout''' | + | * '''sendTimeout''' timeout (µs) for sending a message to a session |
− | : | + | : If the sending does not complete within the specified time, i2RpcAPI will return the error I2RC031 |
− | : | + | : if = 0, then the corresponding server configuration parameter is used |
− | * '''recvTimeout''' | + | * '''recvTimeout''' timeout (µs) for receiving a message from a session |
− | : | + | : If a response message from the session is not received within the specified time after sending, i2RpcAPI will return the error I2RC032 |
− | : | + | : if = 0, then the corresponding server configuration parameter is used |
* '''traceIn''' 0/1 | * '''traceIn''' 0/1 | ||
− | : | + | : If = 1, then the program input parameters array will be printed in hex format in the session's job log |
* '''traceOut''' 0/1 | * '''traceOut''' 0/1 | ||
− | : | + | : If = 1, then the program output parameters array will be printed in hex format in the session's job log |
* '''withJobLog''' 0/1 | * '''withJobLog''' 0/1 | ||
− | : | + | : If = 1, the server will return to the client the contents of the session's job log generated during the program call |
− | : | + | : To receive joblog, you must pass in the joblog parameter a pointer to the memory area where the text of the job log should be placed, and specify the length of this area in the joblogProvided parameter |
* '''withJobLogOnError''' 0/1 | * '''withJobLogOnError''' 0/1 | ||
− | : | + | : Similar to the previous parameter, but the job log will be returned only in cases of critical program call failures |
* '''returnResolvedName''' 0/1 | * '''returnResolvedName''' 0/1 | ||
− | : | + | : If = 1, then after calling the API, the real value of the library and program used when calling will be returned to the lib/pgm variables |
* '''logging''' I/O/B/N/D | * '''logging''' I/O/B/N/D | ||
− | : | + | : Specifies what is passed to the trace: |
− | :* I - | + | :* I - input PLIST before calling the program |
− | :* O - | + | :* O - output PLIST after program call |
− | :* B - | + | :* B - PLISTs before and after calling the program |
− | :* N - | + | :* N - No tracing performed |
− | :* D | + | :* D or space - Trace is determined based on server settings |
− | :: | + | :: The parameters are ignored if tracing is disabled on the server (there are no threads processing trace messages) |
− | * '''joblogProvided''' - | + | * '''joblogProvided''' - the number of bytes available in the joblog variable to receive the program's returned joblog |
− | * '''joblog''' | + | * '''joblog''' - pointer to a memory area of length joblogProvided where the called program's joblog will be placed |
==I2RC000003 печать joblog== | ==I2RC000003 печать joblog== |
Latest revision as of 16:46, 31 July 2025
i2Rpc is a tool for remotely calling programs on the IBMi platform. Allows you to call programs in a separate job, both locally and on a remote IBMi server
Contents
Solution architecture
i2Rpc Server
The i2Rpc server instance located on the IBMi server is a multi-threaded server that receives and processes requests to perform remote program calls from i2Rpc Clients. The server communicates with i2Rpc Clients via a proprietary protocol built on top of the TCP/IP protocol. The server processes client connection requests and connects clients to sessions that service remote program calls.
To serve i2Rpc clients, the server starts a listener for incoming TCP/IP or UNIX connections. The port number or UNIX socket address of incoming requests is defined in the server configuration parameters. If a TCP/IP port is used, the server can accept requests from clients located on other IBMi servers that have access to this server. Using UNIX connections allows you to limit the scope of the i2Rpc server instance to this IBMi server only.
To connect sessions, the i2Rpc server opens a UNIX connection listener on a local UNIX socket. The server starts sessions with the SBMJOB command, and the session job is notified of the address that the server listener listens to for processing connections with sessions. After starting, the session connects to the server and starts for waiting for tasks to process client RPC requests.
i2Rpc clients
An i2Rpc client can be any IBMi program that requires remote execution of another program on an IBMi server running an instance of the i2Rpc server. To interact with the i2Rpc server, the client is provided with a special API implemented by the program i2RpcAPI. i2RpcAPI has several commands, which are defined in the first parameter of the i2RpcAPI program. The most notable commands are:
- I2RC000001 - used to connect to i2Rpc server and get connection handler
- I2RC000002 - remote program call within this connection
- I2RC000004 - close connection to i2Rpc server, release resources
Depending on the command, the client program must pass the corresponding data structures containing the parameters of a particular command to i2RpcAPI.
In particular, the parameters of the I2RC000002 action are designed in such a way as to minimize program modifications when switching from a local call to a remote one. In fact, instead of passing a list of parameters during a local call, the same list of parameters must be passed to RPC, and accompanied by a formal description of this list - specify the number of parameters and their sizes
i2Rpc sessions
Direct execution of remote program calls occurs in i2Rpc Sessions. A Session is a separate single-threaded job that connects to the i2Rpc Server and receives from the server a connection to the client, from which the RPC call request was arrived.
Sessions monitor the server state. If a server job is stopped in one way or another, all sessions connected to this server will also terminate their work. During work, sessions inform the server about the results of processing client RPC requests.
There are two types of i2Rpc sessions:
- statefull session (SF session) - a job within which requests of only one client are executed. In the job, all properties of the call environment generated by the client are saved unchanged - library list, activation groups, object and record locks, objects in QTEMP, etc. When a client connects to the i2Rpc server in SF mode, the server starts a separate job in which all RPC calls from this client are executed. During the first RPC call, the server passes the client connection descriptor to the session job, and further interaction of the client with i2Rpc occurs directly between the client and the session, without involving the i2Rpc server. The server monitors the activity of the client connection and session. In case of disconnection of the client connection, the SF session will be automatically stopped. And vice versa - if the session job is terminated in one way or another, the server will close the connection with the client
- stateless session (SL session) is a job that can serve RPC calls from several clients. The i2Rpc server does not guarantee that calls from a specific client to an SL session will be executed within the same session job. When a client calls an SL session, the server determines a available session job from the pool of SL jobs, submits a new SL session job if necessary, and passes it a client connection descriptor. The SL session, after completing processing the RPC request (requests) of this client, returns to the pool of available SL sessions, and can be used in the future to process requests from other clients. The size of the SL session pool - the minimum and maximum number of jobs - can be defined in the i2Rpc server settings. The server automatically maintains the specified pool width, monitoring the completion of jobs and starting new jobs as needed.
Session context
The session context is a small amount of client data that is transferred to the session with each remote program call. The client API has an interface that allows you to set/change the contents of the session context. In turn, the contents of the session context are analyzed on the session side immediately before calling user programs. If the session context has changed after the previous call, then before calling the program, a special user exit program will be called, which can form/change a new user environment (for example, change the list of libraries or the contents of objects in the QTEMP library). For stateless and statefull sessions, you can set your own user exit program name - it is specified in the server configuration parameters --stateless.contextSetExit
or --statefull.contextSetExit
Logging and tracing
In the context of this project, the concepts of Logging and Tracing are distinguished.
Logging is the recording of events that occur during the operation of the server and sessions. To register such events, the job's log, its spool file QPRINT, or the syslog server can be used.
Tracing - is logging of RPC call parameters, which is performed by a separate user exit program. This user exit program can be called before and/or after the call of the RPC program by the session. In essence, tracing is application logging of RPC procedure calls, performed by the user user exit.
Logging and tracing parameters are configured in the i2Rpc server configuration file, or can be passed to the server on the server startup command line.
To perform tracing, it is necessary to create a special user exit tracing program and set up the appropriate tracing parameters in the server configuration.
The call of user exit tracing can be performed both within the i2Rpc server job itself and within a separate tracer job. The corresponding server configuration parameter is responsible for the method of calling user exit tracing
i2Rpc installation
The i2Rpc server is installed as licensed software. To install. To install i2Rpc:
- Download i2Rpc_Install.ZIP
- Copy downloaded file to IBMi IFS folder
- Open a terminal emulator session and run the command
CHGCURDIR <Folder where i2Rpc_Install.ZIP was copied>
- The system will display the message "Current directory changed."
QSH CMD('jar xMvf i2Rpc_Install.ZIP')
- This command will unpack SAVF from the archive, the message "inflated: I2RPCINST.SAVF" will be displayed.
CRTSAVF FILE(QTEMP/I2RPCINST)
- File I2RPCINST created in library QTEMP.
CPYFRMSTMF FROMSTMF(I2RPCINST.SAVF) TOMBR('/qsys.lib/qtemp.lib/I2RPCINST.file') MBROPT(*REPLACE)
- "Stream file copied to object."
RSTLICPGM LICPGM(0AI2R11) DEV(*SAVF) SAVF(QTEMP/I2RPCINST)
- *PGM objects for product 0AI2R11 option *BASE release *FIRST restored.
- Check the i2Rpc installed:
WRKLICINF PRDID(0AI2R11)
- Information about the installed licensed product i2Rpc will be displayed.
WRKOBJPDM I2RPCPROD
- A list of objects in the I2RPCPROD product library will appear
Server setup
The i2Rpc server configuration parameters are set in the configuration file, which has the JSON format. The file name is specified in the server startup parameters. The server parameters which set in the json file can be redefined directly in the startup command line. For example:
call i2rpcg parm('--config=config.json' '--stateless.minJobs=1' '--stateless.maxJobs=1')
In this server startup command, the configuration parameters are set in the config.json file, with the stateless.minJobs and stateless.maxJobs parameters overridden at the command line level
The contents of the server configuration file is utf-8 encoded text, which is a json object. The text may contain C-like comments, such as
// This is line-comment
/* This is block-comment */
Full list of server parameters
All configuration parameters are divided into separate sections:
- gateway - general server parameters, such as logging parameters, server listener address, etc
- session - general session parameters
- stateless - stateless session settings
- statefull - statefull session settings
- logger - custom tracing settings
Gateway section
- debugIdentity - logging identifier specified in syslog protocols, default is I2RPCG
- debugLevel - logging level. Possible values are EMERG, ALERT, CRIT, ERR, ERROR, WARNING, NOTICE, INFO, DEBUG, default is ERROR
- debugFacility - syslog message source identifier. Possible values are ERN, USER, MAIL, DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7, default - LOCAL0
- debugProtocol - logging protocol. Determines the method of logging messages by the server. Possible values - UDP, TCP (sending messages to the syslog server UDP or TCP), STDOUT, STDERR (printing to the spool file), JOBLOG (output to the job log of the task). Default - UDP
- syslogHost, syslogPort - logging server parameters if UDP or TCP protocol is used. By default "syslog" and "514" respectively
- link - the name of the file on the IFS file system, which is used as a unix socket on which the server listener "listens" for i2Rpc client requests. Not used together with the port parameter. Defaults to ""
- port - the port number on which the server listener "listens" for i2Rpc client requests via TCP. Not used together with the link parameter. Required if the link parameter is not specified. If the port parameter is specified, the i2Rpc listener "listens" for client requests at the address 0.0.0.0:<port>
- maxDescriptors - the maximum number of file descriptors available to an i2Rpc server job. The IBMi operating system by default limits the number of file descriptors available to a job to 200. The i2Rpc server requires a minimum of 2 file descriptors for each connected client, and 2 descriptors for each connected session. It is recommended to specify a maxDescriptors value that is sufficient to service the planned number of clients and sessions.
Session section
- debugIdentity, debugLevel, debugFacility, debugProtocol, syslogHost, syslogPort - logging parameters similar to those described above in the gateway section
- link - a link (unix socket) through which the server and sessions communicate. By default, it is formed as
/tmp/I2R@<port>.do_not_delete
, where port is the gateway port number. The server and sessions must have access to the specified resource. Removing a link while the server is running is PROHIBITED - maxLoggerQueueSize - Maximum length of the queue for sending messages to the tracer (the total length of all messages not sent by the session, in bytes). If exceeded, session will pause sending messages to the tracer
Section stateless
- job, user, profile - name of the job, user and profile of the submitted stateless sessions
- If something is not specified, the parameters from the server job are used by default. That is, for example, if something from job, user, profile are not specified, and i2Rpc server runs under I2RPRF in job named 123456/I2RUSER/I2RPCG, then stateless sessions will be launched under the I2RPRF profile, and will have the name NNNNNN/I2RUSER/I2RPCG
- submit - command to submit a stateless session
- Specifies the template of the SBMJOB command that the server will use to start new stateless sessions. You can specify any parameters of the SBMJOB command, except for the CMD parameter. The CMD parameter is prepared by the server itself
- The following macro substitutions can be used in the command template - when forming a command, these macro substitutions will be replaced with the corresponding configuration/runtime parameters
- ${gateway.link}
- ${gateway.debugLevel}
- ${gateway.debugFacility}
- ${gateway.debugProtocol}
- ${gateway.syslogHost}
- ${gateway.syslogPort}
- ${session.debugLevel}
- ${session.debugFacility}
- ${session.debugProtocol}
- ${session.syslogHost}
- ${session.syslogPort}
- ${stateless.job}
- ${stateless.user}
- ${stateless.profile}
- ${stateless.init}
- The default value is:
SBMJOB JOB(${stateless.job}) USER(${stateless.user})
- init - the command to initialize the session job. It will be executed by the first command in the session, immediately after the job is started
- Default is *NONE - the initialization command is not executed
- submitTimeout - the time to wait for the session job to be ready on the server side (µs)
- If the specified time has passed after the session has started, but the session job has not connected to the server, then it is considered that the session has not started
- Default = 5000000, (5 seconds)
- jobTimeout - inactivity time (µs)
- If the session does not receive requests within the specified time, it will be terminated
- Default = 600000000 (10 minutes)
- minJobs - minimum number of stateless sessions
- The specified number is submitted when the server starts, and then the number of stateless sessions does not fall below this value. The number of sessions also includes jobs that have been submitted but have not yet connected to the server and whose submitTimeout has not expired
- Default 0
- maxJobs - maximum number of stateless sessions, 0 - unlimited
- Default 0 - unlimited
- watermark - threshold level for launching stateless sessions
- The server will not start new stateless sessions, until the number of clients waiting for their request to be processed exceeds the specified value
- By default 0, that is, a new stateless session will be started every time a new connection request is received from a stateless client
- batchCalls - the number of requests from one client that a session can process without switching to another stateless client
- If there are less than batchCalls requests received from a client, the session waits for batchCallTimeout and switches to the next client
- By default, 0, i.e. the session switches to the next client immediately after processing the request
- batchCallTimeout - used in conjunction with the batchCalls parameter (µs)
- Defines the time to wait for another request from the same client within the batchCalls request processing
- If there are fewer than batchCalls requests from a client, but more than batchCallTimeout microseconds have passed since the last request, the session is returned to the free session pool and can be used to process requests from another client
- Default 0
- sendTimeout - the time the client waits for a message to be sent to the session (µs)
- If the client does not specify the sendTimeout parameter when calling the RPC procedure, then this value is used by default. i2RpcAPI waits for the specified number of microseconds to complete sending, and if sending is not completed, the client will receive an error message I2RC031
- Default 5000000 (5 seconds)
- receiveTimeout - the time the client waits to receive a message from the session (µs)
- Used similarly to sendTimeout, to limit the time spent on receiving a response from the session. If the response from the session is not completed within receiveTimeout microseconds after sending, the client will receive an error message I2RC032
- Default 5000000 (5 seconds)
- contextSetExit - the name of the user exit program called in the session if the session context has been changed
Section statefull
- job, user - name of the job and user of the submitted statefull sessions
- If something is not specified, the parameters from the client job are used by default. That is, if something from job or user is not specified, and for example the job of this i2Rpc client is 123456/I2RUSER/I2RPCC, running under the I2RPRF profile, then statefull sessions submitted for this client will be run under the I2RPRF profile, and will have the name NNNNNN/I2RUSER/I2RPCC
- submit - command to submit a statefull session
- Specifies the template of the SBMJOB command that the server will use to start new statefull sessions. You can specify any parameters of the SBMJOB command, except for the CMD parameter. The CMD parameter is generated by the server itself
- The following macro substitutions can be used in the command template - when forming a command, these macro substitutions will be replaced with the corresponding configuration parameters
- ${gateway.link}
- ${gateway.debugLevel}
- ${gateway.debugFacility}
- ${gateway.debugProtocol}
- ${gateway.syslogHost}
- ${gateway.syslogPort}
- ${session.debugLevel}
- ${session.debugFacility}
- ${session.debugProtocol}
- ${session.syslogHost}
- ${session.syslogPort}
- ${statefull.job}
- ${statefull.user}
- ${statefull.init}
- ${statefull.profile} - this parameter is determined based on the name of the profile under which the original client job is running
- ${statefull.system} - this parameter contains the name of the system on which the original client job is running
- The default value is:
SBMJOB JOB(${statefull.job}) USER(${statefull.user})
- init - the command to initialize the session job. It will be executed by the first command in the session, immediately after the job is started
- Default is *NONE - the initialization command is not executed
- submitTimeout - the time to wait for the session job to be ready (µs)
- If session has started and the specified time has passed, but the session has not connected to the server, then it is considered that the session has not started, the client will receive the error message I2RC005 "Unable to get i2Rpc connection. Session submit timed out"
- jobTimeout - inactivity time (µs)
- If the session does not receive requests within the specified time, it will be terminated
- Default = 5000000, (5 seconds)
- maxJobs - maximum number of statefull sessions, 0 - unlimited
- Default 0 - unlimited
- sendTimeout - the time the client waits for a message to be sent to the session
- If the client does not specify the sendTimeout parameter when calling the RPC procedure, then this value is used by default. i2RpcAPI waits for the specified number of microseconds to complete sending, and if sending is not completed, the client will receive an error message I2RC031
- Default 5000000 (5 seconds)
- receiveTimeout - the time during which the client waits to receive a message from the session
- Used similarly to sendTimeout, to limit the time spent on receiving a response from the session. If the response from the session is not completed within receiveTimeout microseconds after sending, the client will receive an error message I2RC032
- Default 5000000 (5 seconds)
- contextSetExit - the name of the user exit program called in the session before calling the program if the session context has been changed
Section logger
This section is intended for configuring the parameters for logging RPC calls by the tracing application (see Logging and Tracing)
Logging of RPC call parameters by an external user exit program is a fairly loaded procedure, therefore, in order to optimize resources, the logging job can be separated from the main job of the i2Rpc server and moved to an isolated job. That is, we are talking about using built-in and external logging of RPC calls. The embedded parameter is responsible for this
The logging server (embedded or external) is a multi-threaded server that has an internal queue of messages to be transferred to the user exit logging program. A separate UUNIX socket (file link on the IFS file system) is used to transfer messages from sessions to the logging server. The link is defined in the server settings
- embedded - Flag for using the gateway's built-in application logger
- If embedded=false, a separate logging job can be started to log calls
- The job has the same parameters as the main gateway job, only
CALL I2RPCL
must be specified instead ofCALL I2RPCG
- listenerThreads - the number of logging server threads. When using the built-in logging server, these threads are started in parallel with the other i2Rpc server threads
- link - a link (socket) that is used to transmit messages to the logging server
- By default, it is generated in the form
/tmp/I2R@<port>_log.do_not_delete
, where port is the gateway port number - The logging server and sessions must have access to the specified resource
- Removing a link while the server is running is PROHIBITED
- program - the name of the program that performs application logging of RPC calls
- events - which messages are subject to logging. Possible options:
- input - only incoming requests (before-PLISTs) are logged
- output - only responses (after-PLISTs) are logged
- both/inputoutput - incoming requests and responses are logged
- none - no application logging is performed
Starting the server
To start an instance of the i2Rpc server, you need to start a new batch job, in which the command to call the main program of the i2Rpc server must be executed:
SBMJOB CMD(CALL PGM(I2RPCG) PARM(<startup parameters>)) ALWMLTTHD(*YES)
The parameters of the SBMJOB command can be anything, however:
- ALWMLTTHD(*YES) - mandatory parameter
- The I2RPCG program must be presented in the library list
Startup parameters
The i2Rpc server instance configuration parameters are specified in the I2RPCG program call parameters, in the following format:
--parameter=value
or
--parameter value
or
--parameter
- if the parameter is a certain flag and does not require specifying a value
Example:
SBMJOB CMD(CALL PGM(I2RPCG) PARM('--config=/home/i2rpc/config.json' '--stateless.minJobs' '1')) ALWMLTTHD(*YES)
The --config parameter, if entered, specifies the name of the file containing the server instance configuration parameters. The file must be encoded as 1208 (utf-8), and contain a valid json object with attributes corresponding to the server configuration parameters
If any of the server configuration parameters are contained both on the command line and in the configuration file, the value of the parameter from the command line takes precedence
Embedded and external tracing server
As noted in the Logging and Tracing, a special user exit program is used to save debug information about the execution of user programs. To reduce the impact of the performance of this user exit program on the overall performance of the i2Rpc server, all procedures associated with tracing are moved to a separate tracing server. The server is a thread(s) that wait for tracing messages from sessions and call the user exit logging program. The server can be launched either as part of the main i2RpcG server job or as a separate job
To use the embedded i2RpcG tracing server, you must specify the following server configuration parameters:
- logger.embedded = true
- logger.listenerThreads - value greater than zero. Defines the number of trace server threads that will be started as part of the i2RpcG server
To start an external logging server, you need to:
- Specify logger.embedded=false, logger.listenerThreads - non-zero value
- Submit job of the external logging server with a command similar to the command to start the main i2RpcG server, using the program name I2RPCL instead of I2RPCG, for example:
SBMJOB CMD(CALL PGM(I2RPCL) PARM('--config=/home/i2rpc/config.json' '--stateless.minJobs' '1')) ALWMLTTHD(*YES)
How to use i2RpcAPI
i2RpcAPI Call Parameters
For interaction between the client software and the i2Rpc server, the I2RPCAPI program is used
Prototypes:
#include <QUSEC.h> #pragma linkage(I2RPCAPI,OS) void I2RPCAPI(char *format, void *apiData, ... /* Qus_EC_t *error */ );
D/COPY QSYSINC/QRPGLESRC,QUSEC * i2Rpc API * Parameters: * format - defines the i2Rpc API command and the format of its parameters * ApiData - i2RpcAPI call parameters, structure depends on Format * error - (optional) - structure for returning error code * D i2RpcAPI PR EXTPGM('I2RPCAPI') D format 10A Const D apiData 99999A Options(*Varsize) D error Likeds(QUSEC) Options(*NOPASS)
Formal list of parameters of the i2RpcAPI program:
- format - i2Rpc command, defines the i2Rpc command and the format of its parameters. One of:
- I2RC000001
- I2RC000002
- I2RC000003
- I2RC000004
- I2RC000005
- apiData - a structure containing the parameters for calling this command
- error (optional) standard structure for exchanging error information, in standard IBMi API QUSEC API IBMi QUSEC ERRC0100
If the error parameter is not passed, then in case of errors, i2RpcAPI will generate an escape message. If the error parameter is passed, then after calling i2RpcAPI it will contain the error code and information accompanying the error
I2RC000001 connect to server
The I2RC000001 command is used to obtain a connection handler to the i2Rpc server. The structure of the I2RC000001 command parameters:
// I2RC000001 - Connect typedef struct i2R_Connect_t { // Input char gateway[256]; int port; char statefull; // 0/1 int connectTimeout; int contextLength; char *contextData; // Output void *connection; char system[8]; char number[6]; char user[10]; char id[10]; } i2R_Connect_t;
D i2RConnect DS Qualified Inz * Input D gateway 256A D port 10I 0 D statefull 3I 0 1/0 D connect... D Timeout 10I 0 D contextLength 10I 0 D contextData * * Output D connection * D system 8A System D number 6A Job number D user 10A Job user D id 10A Job id
Parameters:
- gateway address of the i2Rpc server (IP address or network name, or file name on the file system if the server is listening on a unix socket)
- port i2Rpc server port. Should be 0 if unix socket is used
- statefull if = 1, then a private job will be submitted for this connection, and all RPC calls will be addressed to this job. If = 0, then the i2Rpc server will use any available stateless job for RPC calls within this connection
- connectTimeout connection timeout. If=0, default is 5s
- contextLength length of the contextData parameter
- contextData pointer to context data
- connection (output) connection handler
- system, number, user, id (output) - name of the job running on the i2Rpc server to service this connection (only for statefull=1)
- If statefull=0, then these parameters are not filled in the response
I2RC000002 RPC program call
The I2RC000002 format is used to call programs remotely using i2Rpc
Parameters structure
// I2RC000002 - Run program typedef struct i2R_RunProgram_t { void *connection; char lib[10]; char pgm[10]; int argc; char **argv; int *argl; int sendTimeout; int recvTimeout; char traceIn; char traceOut; char withJobLog; char withJobLogOnError; char returnResolvedName; char logging; int jobLogProvided; char *jobLog; } i2R_RunProgram_t;
D i2RCallProgram DS Qualified Inz D connection * D lib 10A I/O (returnResolvedName) D pgm 10A I/O (returnResolvedName) D argc 10I 0 D argv * Input/Output D argl * D sendTimeout 10I 0 I D recvTimeout 10I 0 I D traceIn 3I 0 1/0 D traceOut 3I 0 1/0 D withJobLog 3I 0 1/0 D withJobLog... D OnError 3I 0 1/0 D return... D Resolved... D Name 3I 0 1/0 D logging 1A I/O/B/D/N D joblog... D Provided 10I 0 D joblog * O (withJobLog*+joblogProvided)
Parameters:
- connection previously obtained connection handler
- lib/pgm input - the name of the program to be called. *LIBL can be used in lib. The program must be "visible" in the list of libraries of the target job
- output - if the parameter returnResolvedName=1, then the real name of the library and program used in the remote call is returned in these fields
- argc number of program parameters
- argv array of argc elements - pointers to program parameters
- argl array of program parameter lengths. Each array element defines the length of the corresponding element of the argv array
- sendTimeout timeout (µs) for sending a message to a session
- If the sending does not complete within the specified time, i2RpcAPI will return the error I2RC031
- if = 0, then the corresponding server configuration parameter is used
- recvTimeout timeout (µs) for receiving a message from a session
- If a response message from the session is not received within the specified time after sending, i2RpcAPI will return the error I2RC032
- if = 0, then the corresponding server configuration parameter is used
- traceIn 0/1
- If = 1, then the program input parameters array will be printed in hex format in the session's job log
- traceOut 0/1
- If = 1, then the program output parameters array will be printed in hex format in the session's job log
- withJobLog 0/1
- If = 1, the server will return to the client the contents of the session's job log generated during the program call
- To receive joblog, you must pass in the joblog parameter a pointer to the memory area where the text of the job log should be placed, and specify the length of this area in the joblogProvided parameter
- withJobLogOnError 0/1
- Similar to the previous parameter, but the job log will be returned only in cases of critical program call failures
- returnResolvedName 0/1
- If = 1, then after calling the API, the real value of the library and program used when calling will be returned to the lib/pgm variables
- logging I/O/B/N/D
- Specifies what is passed to the trace:
- I - input PLIST before calling the program
- O - output PLIST after program call
- B - PLISTs before and after calling the program
- N - No tracing performed
- D or space - Trace is determined based on server settings
- The parameters are ignored if tracing is disabled on the server (there are no threads processing trace messages)
- joblogProvided - the number of bytes available in the joblog variable to receive the program's returned joblog
- joblog - pointer to a memory area of length joblogProvided where the called program's joblog will be placed
I2RC000003 печать joblog
Данная команда API i2RpcAPI служит для печати содержимого joblog, полученного при вызове программы при помощи I2RC000002. Job log представляет собой текстовую строку, содержащую разделители (cr+lf), которая заканчивается нулевым символом (x'00'). Функция печати I2RC000003 разбивает полученный job log на отдельные строки и выполняет их вывод в job log клиентского задания, используя функцию Qp0zLprintf.
Структура параметров:
// I2RC000003 - Print job log typedef struct i2R_PrintJobLog_t { int jobLogProvided; char *jobLog; } i2R_PrintJobLog_t;
D i2RJobLog DS Qualified Inz D jobLog... D Provided 10I 0 D jobLog *
Описание параметров:
- jobLogProvided длина параметра joblog
- jobLog указатель на содержимое joblog, полученное при вызове i2RpcAPI в режиме I2RC000002
I2RC000004 отключение от сервера
Если в клиентском соединении более нет необходимости, клиент может выполнить отключение от сервера командой I2RC000004. Этот вызов освободит на стороне сервера ресурсы, зарезервированные для обслуживания соединения с данным клиентом, а также (для statefull сессии) - завершит сессионное задание данного клиента.
Сервер i2Rpc отслеживает завершение клиентских заданий, и если клиент не выполнил предварительно вызов команды I2RC000004, то серверные ресурсы, относящиеся к данному заданию, будут освобождены автоматически. Тем не менее, хорошей практикой является контролируемое отключение клиентского соединения по инициативе самого клиента.
Структура параметров
// I2RC000004 - Disconnect typedef struct i2R_Disconnect_t { void *connection; } i2R_Disconnect_t;
D i2RDisconnect DS Qualified Inz D connection *
Параметры
- connection указатель на хэндлер соединения, полученный ранее командой I2RC000001
I2RC000005 Set/update client context
Команда I2RC000005 позволяет клиенту выполнить установку/изменение клиентского контекста сессии. Данный вызов сохраняет/заменяет содержимое области данных клиентского контекста, эти данные передаются серверу i2Rpc при всех последующих вызовах программ командой I2RC000002.
Вызов команды I2RC000005 не изменяет непосредственно окружение в клиентской сессии. При этом вызове только сохраняется новое содержимое области данных контекста сессии, и если это содержимое будет отличаться от того, которое было использовано ранее при вызове программы в сессии (команда I2RC000002), то перед следующим вызовом программы будет предварительно вызван вызван user exit, указанный в параметре конфигурации state{full|less}.contextSetExit
Структура параметров
// I2RC000005 - SetContext typedef struct i2R_SetContext_t { // Input void *connection; int contextLength; char *contextData; } i2R_SetContext_t;
D i2RSetContext DS Qualified Inz D connection * D contextLength 10I 0 D contextData *
Описание параметров
- connection полученный ранее handler соединения
- contextLength длина параметра contextData
- contextData указатель на данные контекста
User Exits
logger.program - Трассировка RPC вызовов
Как описано в разделе Логирование и трассировка, трассировка вызовов пользовательских программ выполняется в специальной user exit программе. Сессии i2Rpc до и/или после вызовов rpc программ, могут выполнять вызов user exit, которому передается информация о параметрах вызова RPC программ. Имя данного user exit указывается в параметрах конфигурации сервера
Прототип user exit
typedef struct i2RpcJobIdentity { // Идентификатор задания void *reserved; char *number; // номер задания char *user; // идентификатор пользователя задания сhar *id; // имя задания char *profile; // профайл, под которым выполняется задание. Может отличаться от идентификатора пользователя сhar *system; // наименование системы, на которой запущено задание char *fullName; // полное наименование задания в формате система:номер/пользователь/имя задания } i2RpcJobIdentity; typedef struct i2RpcParam { // Параметр в PLIST void *reserved; int length; // формальная длина параметра void *data; // указатель на значение параметра. Может быть NULL int dataSize; // фактическая длина параметра. Может быть 0 } i2RpcParam; typedef struct i2RpcPlist { // PLIST - массив параметров программы int length; // количество параметров i2RpcParam *params; // массив параметров } i2RpcPlist; typedef struct i2RpcProgramCallRequest { // Детали трассировки до вызова RPC программы void *reserved; i2RpcJobIdentity *clientJob; // Идентификатор клиентского задания char *libName; // Библиотека и имя программы для RPC вызова char *pgmName; i2RpcPlist plist; // Значения параметров программы до вызова char traceInput; // Флажки (передаются с клиентской стороны): печатать входные параметры в job log 0/1 char traceOutput; // печатать выходные параметры в job log 0/1 int withJobLog; // Длина переменной, в которой нужно вернуть job log int withJobLogOnError; // Длина переменной, в которой нужно вернуть job log (только в случае ошибок) char returnResolvedName; // Возвращать фактическое имя программы 0/1 int traceOption; // В каких точках вызывать трассировку I/O/B/N void *contextData; // Контекст вызова int contextDataSize; // Длина контекста } i2RpcProgramCallRequest; typedef struct i2RpcProgramCallResponse { // Детали трассировки до вызова RPC программы void *reserved; i2RpcJobIdentity *clientJob; // Идентификатор клиентского задания i2RpcJobIdentity *sessionJob; // Идентификатор задания сессии, в котором сделан вызов RPC char *libName; // Библиотека и имя программы, уточненные если returnResolvedName=1 char *pgmName; i2RpcPlist plist; // Значения параметров программы после вызова char *jobLog; // job log (если withJobLog или withJobLogOnError не равны 0) int programCallResult; // код ошибки: // 0 - нет ошибки // -1 - не найдена программа libName/pgmName // -2 - вызов программы libName/pgmName завершен с ошибкой // -4 - не найдена программа contextSetExit // -5 - ошибка вызова программы contextSetExit } i2RpcProgramCallResponse;
User exit трассировки вызовов принимает на вход два параметра:
- Код точки вызова, строка из одного символа:
- I - до вызова RPC программы
- O - после вызова RPC программы
- Данные для трассировки. В зависимости от кода точки вызова, это может быть структура i2RpcProgramCallRequest или i2RpcProgramCallResponse
Особые указания
- User exit трассировки должен быть спроектирован с учетом использования в составе высоконагруженного мультипоточного приложения. User exit вызывается в контексте основного задания сервера I2RPCG или в задании внешнего логгера I2RPCL, в зависимости от параметра конфигурации logger.embedded
- Недопустимо использование не threadsafe функций, и любых не threadsafe конструкций, например глобальных переменных, не защищенных блокировками - см. Thread safety
- Недопустимо изменение значений любого из полученных параметров
- Любой указатель на какую-либо переменную валиден только в момент вызова user exit. Использование этих значений после выхода из user exit недопустимо. При необходимости в user exit можно сделать копии значений для последующего использования
- Все строковые переменные завершаются нулевым символом
state{full|less}.contextSetExit - установка контекста сессии
Данный user exit вызывается в сессии i2Rpc, если в момент вызова RPC программы обнаруживается, что контекст сессии был изменен с момента предыдущего вызова. Имя RPC программы не имеет значения, т.е. если после вызова некой программы с контекстом A, происходит вызов любой программы контекстом B, то до вызова программы сессия i2Rpc выполнит вызов user exit contextSetExit.
Эта опция предоставляет возможность оперативной смены окружения, что особенно ценно в случае использования stateless режима. Однако, если очевидно, что смена контекста является достаточно частым явлением, вероятно имеет смысл перейти к использованию statefull режима. В этом режиме сессия обслуживает персонально одного выделенного ей клиента, поэтому можно использовать одно и то же окружение повторно.
В параметрах конфигурации сервера можно настроить отдельные имена user exit программ - stateless.contextSetExit и statefull.contextSetExit
User exit смены контекста вызывается с одним параметром - это указатель на копию данных, которые были переданы клиентом при вызове API I2RC000005 в параметре contextData.
Особые указания
- User exit contextSetExit вызывается в контексте однопоточного задания сессии, и должен быть спроектирован с учетом использования в составе высоконагруженного приложения
- Недопустимо изменение значения полученного контекста сессии
Примеры клиентского ПО
Клиент на языке C
// Пример вызова программы *LIBL/ECHO при помощи i2Rpc // Тестовая программа *LIBL/ECHO принимает на вход три параметра, 10, 20 и 30 символов длиной #include <STDIO.h> #include <STDLIB.h> #include <qp0ztrc.h> #include <mih/mattod.h> #define NOW(t) (mattod((void *)&(t)),(t)>>=12,(t)) #include "i2RpcAPI.h" int main(int argc, char *argv[]) { i2R_Connect_t connect; i2R_RunProgram_t runProgram; i2R_Disconnect_t disconnect; char p1[10], p2[20], p3[30]; int arg_l[] = {10, 20, 30}; char *arg_v[] = {p1, p2, p3}; unsigned long long start; unsigned long long end; NOW(start); // Получаем handler соединения memset(&connect, ' ', sizeof(connect)); memcpy(connect.gateway, "0.0.0.0", 7); connect.port = 22088; // сервер запущен на порту 22088 connect.statefull = 1; // используем statefull соединение i2RpcAPI("I2RC000001", &connect); // RPC вызов программы memset(p1, ' ', sizeof(p1)); p1[0]='1'; memset(p2, ' ', sizeof(p2)); p2[0]='2'; memset(p3, ' ', sizeof(p3)); p3[0]='3';
memset(&runProgram, ' ', sizeof(runProgram)); runProgram.connection = connect.connection; memcpy(runProgram.pgm, "ECHO", 4); memcpy(runProgram.lib, "*LIBL", 5); runProgram.argc = 3; runProgram.argl = arg_l; runProgram.argv = arg_v; i2RpcAPI("I2RC000002", &runProgram); // Отключаемся от сессии memset(&disconnect, ' ', sizeof(disconnect)); disconnect.connection = connect.connection; i2RpcAPI("I2RC000004", &disconnect); NOW(end); Qp0zLprintf("Time elapsed = %llu.%llu\n", (end - start) / (unsigned long long)1000000, (end - start) % (unsigned long long)1000000); return 0; }
Клиент на RPGLE
TODO
Пример user exit трассировки вызовов
TODO
Пример user exit contextSetExit
TODO