Difference between revisions of "I2Rpc EN"

From i2Rest
Jump to: navigation, search
(Секция session)
(Секция stateless)
Line 116: Line 116:
 
* '''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
 
* '''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
  
===Секция stateless===
+
===Section stateless===
* '''job, user, profile''' - имя работы, пользователя и профайл запускаемыx stateless сессий.
+
* '''job, user, profile''' - name of the job, user and profile of the submitted stateless sessions
: Если что-то не указано, по умолчанию используются параметры из серверного задания. То есть, если что-то из job, user, profile не указаны, и например запущенное задание данного сервера i2Rpc - 123456/I2RUSER/I2RPCG, работает под профилем I2RPRF, то stateless сессии  будут запускаться под профилем I2RPRF, и будут иметь имя NNNNNN/I2RUSER/I2RPCG
+
: 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''' - команда запуска stateless сессии.
+
* '''submit''' - command to submit a stateless session
: Указывается шаблон команды SBMJOB, которую сервер будет использовать для запуска новых stateless сессий. Можно указать любые параметры команды SBMJOB, за исключением параметра CMD. Параметр CMD формируется сервером самостоятельно
+
: 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.link}             
 
:* ${gateway.debugLevel}         
 
:* ${gateway.debugLevel}         
Line 137: Line 137:
 
:* ${stateless.profile}
 
:* ${stateless.profile}
 
:* ${stateless.init}
 
:* ${stateless.init}
: По умолчанию используется значение:
+
: The default value is:
 
:<code>SBMJOB JOB(${stateless.job}) USER(${stateless.user})</code>
 
:<code>SBMJOB JOB(${stateless.job}) USER(${stateless.user})</code>
* '''init''' - команда инициализации задания сессии. Будет выполнена первой командой в сессии, сразу после запуска задания
+
* '''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
: По умолчанию *NONE - команда инициализации не выполняется
+
: Default is *NONE - the initialization command is not executed
* '''submitTimeout''' - время ожидания готовности задания сессии на стороне сервера (мкс).
+
* '''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
: По умолчанию = 5000000, (5 секунд)
+
: Default = 5000000, (5 seconds)
* '''jobTimeout''' - время неактивности (мкс).
+
* '''jobTimeout''' - inactivity time (µs)  
: Если сессия не получает запросов в течение указанного времени, она будет завершена
+
: If the session does not receive requests within the specified time, it will be terminated
: По умолчанию = 600000000 (10 минут)
+
: Default = 600000000 (10 minutes)
* '''minJobs''' - минимальное количество stateless сессий.
+
* '''minJobs''' - minimum number of stateless sessions
: Указанное количество запускается при старте сервера, и далее количество stateless сессий не опускается ниже данного значения. В подсчет количества сессий принимаются также запущенные но еще не подключившиеся к серверу задания, у которых не истекло время submitTimeout
+
: 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
: По умолчанию 0
+
: Default 0
* '''maxJobs''' - максимальное количество stateless сессий, 0 - не ограничено
+
* '''maxJobs''' - maximum number of stateless sessions, 0 - unlimited
: По умолчанию 0 - не ограничено
+
: Default 0 - unlimited
* '''watermark''' - пороговый уровень запуска stateless сессий
+
* '''watermark''' - threshold level for launching stateless sessions
: Пока количество клиентов, ожидающих обработки своего запроса, не превысит указанное значение, сервер не будет запускать новые stateless сессии
+
: The server will not start new stateless sessions, until the number of clients waiting for their request to be processed exceeds the specified value
: По умолчанию 0, то есть новая stateless сессия будет запускаться каждый раз при поступлении нового коннекта от stateless клиента
+
: 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''' - количество запросов от одного клиента, которые может обработать сессия без переключения на другого stateless клиента.
+
* '''batchCalls''' - the number of requests from one client that a session can process without switching to another stateless client
: Если от клиента поступило меньше чем batchCalls запросов, сессия ждет batchCallTimeout и переключается на следующего клиента
+
: If there are less than batchCalls requests received from a client, the session waits for batchCallTimeout and switches to the next client
: По умолчанию 0, то есть сессия переключается на следующего клиента сразу после обработки очередного запроса
+
: By default, 0, i.e. the session switches to the next client immediately after processing the request
* '''batchCallTimeout''' - используется совместно с параметром batchCalls
+
* '''batchCallTimeout''' - used in conjunction with the batchCalls parameter (µs)
: Определяет время ожидания очередного запроса от одного и того же клиента в рамках обработки batchCalls запросов
+
: Defines the time to wait for another request from the same client within the batchCalls request processing
: Если от клиента поступило меньше чем batchCalls запросов, но с момента последнего запроса прошло больше чем batchCallTimeout микросекунд, сессия возвращается в пул свободный сессий и может быть использована для обработки запросов другого клиента
+
: 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
: По умолчанию 0
+
: Default 0
* '''sendTimeout''' - время, в течение которого клиент ожидает отправки сообщения в сессию
+
* '''sendTimeout''' - the time the client waits for a message to be sent to the session (µs)
: Если клиент не указал параметр sendTimeout при вызове RPC процедуры, то по умолчанию используется данное значение. i2RpcAPI ожидает завершения отправки указанное количество микросекунд, и если отправка не завершена - клиент получит сообщение об ошибке I2RC031
+
: 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
: По умолчанию 5000000 (5 секунд)
+
: Default 5000000 (5 seconds)
* '''receiveTimeout''' - время, в течение которого клиент ожидает приема сообщения от сессии
+
* '''receiveTimeout''' - the time the client waits to receive a message from the session (µs)
: Используется аналогично sendTimeout, для ограничения времени, затрачиваемого на прием ответа от сессии. Если прием ответа от сессии не будет завершен в течение receiveTimeout микросекунд после отправки - клиент получит сообщение об ошибке I2RC032
+
: 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
: По умолчанию 5000000 (5 секунд)
+
: Default 5000000 (5 seconds)
* '''contextSetExit''' - имя user exit программы, вызываемой в сессии перед вызовом программы, если [[#I2RC000005 изменение контекста вызова|контекст сессии был изменен]]
+
* '''contextSetExit''' - the name of the user exit program called in the session if [[#I2RC000005|the session context has been changed]]
  
 
===Секция statefull===
 
===Секция statefull===

Revision as of 12:50, 30 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

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:

  1. Download i2Rpc_Install.ZIP
  2. Copy downloaded file to IBMi IFS folder
  3. Open a terminal emulator session and run the command
    1. CHGCURDIR <Folder where i2Rpc_Install.ZIP was copied>
      The system will display the message "Current directory changed."
    2. QSH CMD('jar xMvf i2Rpc_Install.ZIP')
      This command will unpack SAVF from the archive, the message "inflated: I2RPCINST.SAVF" will be displayed.
    3. CRTSAVF FILE(QTEMP/I2RPCINST)
      File I2RPCINST created in library QTEMP.
    4. CPYFRMSTMF FROMSTMF(I2RPCINST.SAVF) TOMBR('/qsys.lib/qtemp.lib/I2RPCINST.file') MBROPT(*REPLACE)
      "Stream file copied to object."
    5. RSTLICPGM LICPGM(0AI2R11) DEV(*SAVF) SAVF(QTEMP/I2RPCINST)
      *PGM objects for product 0AI2R11 option *BASE release *FIRST restored.
  4. Check the i2Rpc installed:
    1. WRKLICINF PRDID(0AI2R11)
      Information about the installed licensed product i2Rpc will be displayed.
    2. 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)

Секция statefull

  • job, user - имя работы и пользователя запускаемыx statefull сессий.
Если что-то не указано, по умолчанию используются параметры из клиентского задания. То есть, если что-то из job или user не указаны, и например запущенное задание данного клиента i2Rpc - 123456/I2RUSER/I2RPCC, запущено под профилем I2RPRF, то statefull сессии, запускаемые для данного клиента, будут запускаться под профилем I2RPRF, и будут иметь имя NNNNNN/I2RUSER/I2RPCC
  • submit - команда запуска statefull сессии.
Указывается шаблон команды SBMJOB, которую сервер будет использовать для запуска новых statefull сессий. Можно указать любые параметры команды SBMJOB, за исключением параметра CMD. Параметр CMD формируется сервером самостоятельно
В шаблоне команды можно использовать следующие макроподстановки - при формировании команды данные макроподстановки будут заменены на соответствующие параметры конфигурации
  • ${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} - этот параметр определяется на основе наименования профайла, под которым работает исходное клиентское задание
  • ${statefull.system} - этот параметр содержит имя системы, в которой запущено исходное клиентское задание
По умолчанию используется значение:
SBMJOB JOB(${statefull.job}) USER(${statefull.user})
  • init - команда инициализации задания сессии. Будет выполнена первой командой в сессии, сразу после запуска задания
По умолчанию *NONE - команда инициализации не выполняется
  • submitTimeout - время ожидания готовности задания сессии на стороне сервера (мкс).
Если после запуска сессии прошло указанное время, но сессия не подключилась к серверу, то считается что сессия не стартовала, клиент получит сообщение об ошибке I2RC005 "Unable to get i2Rpc connection. Session submit timed out"
  • jobTimeout - время неактивности (мкс).
Если сессия не получает запросов в течение указанного времени, она будет завершена
По умолчанию = 5000000, (5 секунд)
  • maxJobs - максимальное количество statefull сессий, 0 - не ограничено
По умолчанию 0 - не ограничено
  • sendTimeout - время, в течение которого клиент ожидает отправки сообщения в сессию
Если клиент не указал параметр sendTimeout при вызове RPC процедуры, то по умолчанию используется данное значение. i2RpcAPI ожидает завершения отправки указанное количество микросекунд, и если отправка не завершена - клиент получит сообщение об ошибке I2RC031
По умолчанию 5000000 (5 секунд)
  • receiveTimeout - время, в течение которого клиент ожидает приема сообщения от сессии
Используется аналогично sendTimeout, для ограничения времени, затрачиваемого на прием ответа от сессии. Если прием ответа от сессии не будет завершен в течение receiveTimeout микросекунд после отправки - клиент получит сообщение об ошибке I2RC032
По умолчанию 5000000 (5 секунд)

Секция logger

Данная секция предназначена для настройки параметров протоколирования вызовов RPC прикладной программой трассировки (см. Логирование и трассировка)

Протоколирование параметров вызовов RPC внешней user exit программой - достаточно нагруженная процедура, поэтому в целях оптимизации вычислительных ресурсов задача протоколирования может быть отделена от основного задания сервера i2Rpc и вынесена в изолированное задание. То есть можно говорить об использовании встроенного и внешнего протоколирования вызовов RPC. За это отвечает параметр embedded.

Сервер протоколирования (встроенный или внешний) - это многопоточный сервер, в котором организована внутренняя очередь сообщений, подлежащих передаче в user exit программу протоколирования. Для передачи сообщений от сессий в сервер протоколирования используется отдельный unix сокет (файл на файловой системе IFS), который определяется в настройках сервера

  • embedded - Признак использования встроенного в gateway прикладного трассировщика
Если embedded=false, для логирования вызовов можно запустить отдельное задание логирования
Задание имеет те же параметры, что и основное задание gateway, только вместо CALL I2RPCG должен быть сделан CALL I2RPCL
  • listenerThreads - количество потоков сервера протоколирования. При использовании встроенного сервера протоколирования, данные потоки запускаются параллельно с остальными потоками сервера i2Rpc
  • link - линк (сокет), который используется для передачи сообщений серверу протоколирования
По умолчанию формируется в виде /tmp/I2R@<port>_log.do_not_delete, где port - номер порта gateway
Сервер протоколирования и сессии должны иметь доступ к указанному ресурсу
Удаление линка в момент работы сервера ЗАПРЕЩЕНО
  • program - имя программы, которая выполняет прикладное протоколирование вызовов RPC
  • events - какие сообщения подлежат протоколированию. Возможные варианты:
  • output - сохраняются только ответные сообщения
  • input - сохраняются только входящие запросы
  • both/inputoutput - сохраняются входящие запросы и ответные сообщения
  • none - протоколирование не выполняется

Запуск сервера

Для старта экземпляра сервера i2RPC необходимо запустить новое пакетное задание, в котором должна быть выполнена команда вызова основной программы сервера i2RPC:

SBMJOB CMD(CALL PGM(I2RPCG) PARM(<Параметры командной строки>)) ALWMLTTHD(*YES)

Параметры команды SBMJOB могут быть любыми, однако:

  • ALWMLTTHD(*YES) - обязательный параметр
  • Программа I2RPCG должна присутствовать в списке библиотек

TODO: Требуемая авторизация пользователя, который запускает I2RPCG

Параметры командной строки

Параметры конфигурации экземпляра сервера i2RPC указываются в параметрах вызова программы I2RPCG, в формате:

--parameter=value или

--parameter value или

--parameter - если параметр представляет собой некий признак, и не предусматривает указания значения

Пример:

SBMJOB CMD(CALL PGM(I2RPCG) PARM('--config=/home/i2rpc/config.json' '--stateless.minJobs' '1')) ALWMLTTHD(*YES)

Параметр --config, если указан, определяет имя файла, содержащего параметры конфигурации экземпляра сервера. Файл должен иметь кодировку 1208 (utf-8), и содержать валидный json объект с атрибутами, соответствующими параметрам конфигурации сервера.

Если какой-то из параметров конфигурации сервера содержится и в командной строке, и в файле конфигурации, то значение параметра из командной строки имеет преимущество

Встроенный и внешний сервер трассировки

Как отмечено в разделе Логирование и трассировка, для сохранения отладочных сведений о выполнении пользовательских программ, используется специальная user exit программа. Для уменьшения влияния производительности данной user exit программы на совокупную производительность сервера i2Rpc, все процедуры, связанные с трассировкой, вынесены в отдельный сервер трассировки. Сервер представляет собой поток(и), которые ожидают трассировочные сообщения от обработчиков и вызывают user exit программу протоколирования. Сервер может быть запущен как в составе основного задания сервера i2RpcG, так и в отдельном задании.

Для использования встроенного в i2RpcG сервера трассировки, необходимо указать следующие параметры конфигурации сервера:

  • logger.embedded = true
  • logger.listenerThreads - значение больше нуля. Определяет количество потоков сервера трассировки, которые будут запущены в составе сервера i2RpcG

Для запуска внешнего сервера протоколирования, необходимо:

  • Указать в logger.embedded=false, logger.listenerThreads - ненулевое значение
  • Запустить внешний сервер протоколирования командой, аналогичной команде запуска основного сервера i2RpcG, используя имя программы I2RPCL вместо I2RPCG, например:
SBMJOB CMD(CALL PGM(I2RPCL) PARM('--config=/home/i2rpc/config.json' '--stateless.minJobs' '1')) ALWMLTTHD(*YES)

Использование i2RpcAPI

Параметры вызова i2RpcAPI

Для взаимодействия клиентского ПО с сервером i2Rpc, используется программа I2RPCAPI

Прототипы:

#include <QUSEC.h>   
#pragma linkage(I2RPCAPI,OS)
void I2RPCAPI(char *format, void *apiData, ... /* Qus_EC_t *error */ );
D/COPY QSYSINC/QRPGLESRC,QUSEC
 * Основной модуль i2Rpc API
 * Параметры:
 *   format  - определяет команду i2Rpc API и формат ее параметров
 *   ApiData - параметры вызова i2RpcAPI, структура зависит от Format
 *   error   - (не обязательно) - структура для возврата кода ошибки 
 *            
D i2RpcAPI        PR                  EXTPGM('I2RPCAPI')
D  format                       10A   Const
D  apiData                   99999A   Options(*Varsize)
D  error                              Likeds(QUSEC) Options(*NOPASS)


Формальный список параметров программы i2RpcAPI:

  • format - команда i2Rpc, определяет команду i2Rpc и формат ее параметров. Одно из:
    • I2RC000001
    • I2RC000002
    • I2RC000003
    • I2RC000004
    • I2RC000005
  • apiData - cтруктура, содержащая параметры вызова данной команды
  • error (не обязательно) cтандартная структура для обмена информацией об ошибках, в стандартном формате API IBMi QUSEC ERRC0100

Если параметр ошибки не передан, то в случае возникновения ошибок, i2RpcAPI сгенерирует прерывающее escape сообщение. Если параметр ошибки передан, то после вызова i2RpcAPI в нем будет содержаться код ошибки и сопровождающая ошибку информация

I2RC000001 подключение к серверу

Команда I2RC000001 используется для получения хендлера соединения к серверу i2Rpc. Структура параметров команды I2RC000001:

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

Параметры:

  • gateway адрес сервера i2Rpc (IP адрес или сетевое имя, или имя файла на файловой системе, если сервер запущен на unix-сокете)
  • port порт сервера i2Rpc. Должно равняться 0, если используется unix-сокет
  • statefull если = 1, то для данного соединения будет запущено персональное задание, и все RPC вызовы будут адресованы в это задание. Если = 0, то сервер i2Rpc будет использовать любое доступное задание для RPC вызовов в рамках данного соединения
  • connectTimeout таймаут установки соединения. Если=0, по умолчанию используется 5с.
  • contextLength длина параметра contextData
  • contextData указатель на данные контекста
  • connection handler соединения
  • system, number, user, id имя задания, запущенного на сервере i2Rpc для обслуживания данного соединения (только для statefull=1)
Если statefull=0, то данные параметры в ответе не заполняются

I2RC000002 RPC вызов программ

Формат I2RC000002 используется для удаленного вызова программ при помощи i2Rpc

Структура параметров

// 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)

Описание параметров:

  • connection полученный ранее handler соединения
  • lib/pgm input - имя вызываемой программы. В lib можно использовать *LIBL. Программа должна быть "видна" в списке библиотек целевого задания
output - если параметр returnResolvedName=1, то в данных полях возвращается реальное имя библиотеки и программы, использованной при удаленном вызове
  • argc количество параметров программы
  • argv массив из argc элементов - указателей на параметры программы
  • argl массив длин параметров программы. Каждый элемент массива определяет длину соответствующего элемента массива argv
  • sendTimeout таймаут (мкс) отправки сообщения в сессию
Если отправка не завершится за указанное время, то i2RpcAPI вернет ошибку I2RC031
если = 0, то используется соответствующий параметр конфигурации сервера
  • recvTimeout таймаут (мкс) приема сообщения от сессии
Если ответное сообщение от сессии не поступит в течение указанного времени после отправки, то i2RpcAPI вернет ошибку I2RC032
если = 0, то используется соответствующий параметр конфигурации сервера
  • traceIn 0/1
Если = 1, то в job log сессии будет распечатан массив входных параметров программы в hex формате
  • traceOut 0/1
Если = 1, то в job log сессии будет распечатан массив выходных параметров программы в hex формате
  • withJobLog 0/1
Если = 1, то сервер вернет клиенту содержимое job log сессии, сформированное в процессе вызова программы.
Для приема joblog необходимо передать в параметре joblog указатель на область памяти, где должен быть размещен текст протокола задания, и указать в параметре joblogProvided длину данной области
  • withJobLogOnError 0/1
Аналогично предыдущему параметру, но job log будет возвращен только в случаях критических сбоев вызова программы
  • returnResolvedName 0/1
Если = 1, то после вызова API в переменных lib/pgm будет возвращено реальное значение использованных при вызове библиотеки и программы
  • logging I/O/B/N/D
Указывает что передается в трассировку:
  • I - входной PLIST перед вызовом программы
  • O - выходной PLIST после вызова программы
  • B - PLIST до и после вызова программы
  • N - Трассировка не выполняется
  • D или пробел - Трассировка определяется на основе настроек сервера
Параметры игнорируются, если на сервере отключена трассировка (нет потоков обработки трассировочных сообщений)
  • joblogProvided - количество байт, доступных в переменной joblog для приема возвращаемого joblog программы
  • joblog указатель на область памяти длиной joblogProvided, куда будет размещен joblog вызванной программы

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

<snap id="I2RC000005"/>

I2RC000005 изменение контекста вызова

Команда 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