Difference between revisions of "I2Rpc EN"

From i2Rest
Jump to: navigation, search
(Контекст сессии)
(I2RC000002 RPC вызов программ)
 
(18 intermediate revisions by the same user not shown)
Line 42: Line 42:
 
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_config|server configuration parameters]] <code>--stateless.contextSetExit</code> or <code>--statefull.contextSetExit</code>
 
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_config|server configuration parameters]] <code>--stateless.contextSetExit</code> or <code>--statefull.contextSetExit</code>
  
==Логирование и трассировка==
+
==Logging and tracing==
<span id="logging_and_tracing"/>В контексте данного проекта, разделяются понятия Логирование и Трассировка.
+
<span id="logging_and_tracing"/>In the context of this project, the concepts of Logging and Tracing are distinguished.
  
'''Логированием''' называется протоколирование событий, возникающих в процессе работы сервера и сессий. Для регистрации таких событий может быть использован job log задания, его spool файл QPRINT, или сервер syslog, запущенный на локальном сервере IBMi или на удаленной машине.  
+
'''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.
  
'''Трассировка''' - это протоколирование параметров RPC вызовов, которое выполняется отдельной user exit программой. Данная user exit программа может быть вызвана до и/или после непосредственного вызова сессией программы, обрабатывающей RPC запрос. По сути трассировка - это прикладное протоколирование вызовов RPC процедур, выполняемое пользовательским user exit.
+
'''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.
  
Параметры логирования и трассировки настраиваются в файле конфигурации сервера i2Rpc, либо могут передаваться серверу в командной строке запуска сервера.
+
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.
  
Для выполнения трассировки требуется создание специальной user exit программы трассировки, и настройки соответствующих параметров трассировке в конфигурации сервера.
+
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.
  
Непосредственный вызов user exit трассировки может выполняться как в рамках самого задания сервера i2Rpc, так и в рамках отдельного задания. За способ вызова user exit трассировки отвечает соответствующий [[#embedded_logger|параметр конфигурации сервера]]
+
The call of user exit tracing can be performed both within the i2Rpc server job itself and within a separate tracer job. The corresponding [[#embedded_logger|server configuration parameter]] is responsible for the method of calling user exit tracing
  
=Установка i2Rpc=
+
=i2Rpc installation=
Сервер i2Rpc устанавливается как лицензионое программное обеспечение.
+
The i2Rpc server is installed as licensed software. To install.
Для установки:
+
To install i2Rpc:
# Загрузите файл [https://nexus3.btc.info/#browse/browse:files.public:i2Rpc i2Rpc_Install.ZIP]
+
# Download [https://nexus3.btc.info/#browse/browse:files.public:i2Rpc i2Rpc_Install.ZIP]
# Скопируйте файл в папку на IFS сервера IBMi
+
# Copy downloaded file to IBMi IFS folder
# Откройте сессию эмулятора терминала и выполните команду
+
# Open a terminal emulator session and run the command
##<code>CHGCURDIR <Папка куда скопирован файл i2Rpc_Install.ZIP></code>
+
##<code>CHGCURDIR <Folder where i2Rpc_Install.ZIP was copied></code>
##:<small>Система выдаст сообщение "Current directory changed."</small>
+
##:<small>The system will display the message "Current directory changed."</small>
 
##<code>QSH CMD('jar xMvf i2Rpc_Install.ZIP')</code>
 
##<code>QSH CMD('jar xMvf i2Rpc_Install.ZIP')</code>
##:<small>Данная команда распакует SAVF из архива, будет выдано сообщение "inflated: I2RPCINST.SAVF"</small>
+
##:<small>This command will unpack SAVF from the archive, the message "inflated: I2RPCINST.SAVF" will be displayed.</small>
 
##<code>CRTSAVF FILE(QTEMP/I2RPCINST)</code>
 
##<code>CRTSAVF FILE(QTEMP/I2RPCINST)</code>
 
##:<small>File I2RPCINST created in library QTEMP.</small>
 
##:<small>File I2RPCINST created in library QTEMP.</small>
Line 71: Line 71:
 
##<code>RSTLICPGM LICPGM(0AI2R11) DEV(*SAVF) SAVF(QTEMP/I2RPCINST)</code>
 
##<code>RSTLICPGM LICPGM(0AI2R11) DEV(*SAVF) SAVF(QTEMP/I2RPCINST)</code>
 
##:<small>*PGM objects for product 0AI2R11 option *BASE release *FIRST restored.</small>
 
##:<small>*PGM objects for product 0AI2R11 option *BASE release *FIRST restored.</small>
# Проверьте установку продукта i2Rpc:
+
# Check the i2Rpc installed:
 
##<code>WRKLICINF PRDID(0AI2R11)</code>
 
##<code>WRKLICINF PRDID(0AI2R11)</code>
##:<small>Будут отображены сведения об установленном лицензионном продукте i2Rpc</small>
+
##:<small>Information about the installed licensed product i2Rpc will be displayed.</small>
 
##<code>WRKOBJPDM I2RPCPROD</code>
 
##<code>WRKOBJPDM I2RPCPROD</code>
##:<small>Появится список объектов в библиотеке продукта I2RPCPROD</small>
+
##:<small>A list of objects in the I2RPCPROD product library will appear</small>
  
 
<span id="server_config"/>
 
<span id="server_config"/>
=Настройка сервера=
+
 
Параметры функционирования сервера i2Rpc задаются в конфигурационном файле, имеющем формат JSON. Имя файла указывается в параметрах старта сервера. Параметры сервера, заданные в json файле, могут быть переопределены непосредственно в командной строке запуска. Например:
+
=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:
  
 
<code>
 
<code>
Line 85: Line 86:
 
</code>
 
</code>
  
В этой команде запуска сервера параметры конфигурации заданы в файле config.json, при этом параметры stateless.minJobs и stateless.maxJobs переопределены на уровне командной строки
+
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
  
Содержимое файла конфигурации сервера - текст в кодировке utf-8, представляющий собой json объект. Текст может содержать C-образные комментарии, например
+
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
  
<code>// Это комментарий, действует до конца строки</code>
+
<code>// This is line-comment</code>
  
<code>/* Это комментарий, действует пока не закрыт */</code>
+
<code>/* This is block-comment */</code>
  
==Полный перечень параметров сервера==
+
==Full list of server parameters==
Все параметры конфигурации разбиты на отдельные секции:
+
All configuration parameters are divided into separate sections:
* '''gateway''' - общие параметры сервера, такие как параметры логирования, адрес листенера сервера и прочие
+
* '''gateway''' - general server parameters, such as logging parameters, server listener address, etc
* '''session''' - общие параметры сессий
+
* '''session''' - general session parameters
* '''stateless''' - параметры настройки stateless сессий
+
* '''stateless''' - stateless session settings
* '''statefull''' - параметры настройки statefull сессий
+
* '''statefull''' - statefull session settings
* '''logger''' - параметры настройки пользовательской трассировки
+
* '''logger''' - custom tracing settings
===Секция gateway===
+
===Gateway section===
* '''debugIdentity''' - идентификатор логирования, указываемый в протоколах syslog, по умолчанию - I2RPCG
+
* '''debugIdentity''' - logging identifier specified in syslog protocols, default is I2RPCG
* '''debugLevel''' - уровень логирования. Возможные значения EMERG, ALERT, CRIT, ERR, ERROR, WARNING, NOTICE, INFO, DEBUG, по умолчанию ERROR
+
* '''debugLevel''' - logging level. Possible values are EMERG, ALERT, CRIT, ERR, ERROR, WARNING, NOTICE, INFO, DEBUG, default is ERROR
* '''debugFacility''' - идентификатор источника сообщений в syslog. Возможные значения ERN, USER, MAIL, DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7, по умолчанию - LOCAL0
+
* '''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''' - протокол логирования. Определяет способ логирования сообщений сервером. Возможные значения - UDP, TCP (отправка сообщений на syslog сервер UDP или TCP), STDOUT, STDERR (печать в spool файл), JOBLOG (вывод в job log задания). По умолчанию - UDP
+
* '''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''' - параметры сервера логирования, если используется протокол UDP или TCP. По умолчанию "syslog" и "514" соответственно
+
* '''syslogHost''', '''syslogPort''' - logging server parameters if UDP or TCP protocol is used. By default "syslog" and "514" respectively
* '''link''' - имя файла на файловой системе IFS, которое используется в качестве unix сокета, на котором листенер сервера "слушает" обращения клиентов i2Rpc. Не используется совместно с параметром port. По умолчанию - ""
+
* '''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''' - номер порта, на котором листенер сервера "слушает" обращения клиентов i2Rpc по протоколу TCP. Не используется совместно с параметром link. Обязательно для заполнения, если не указан параметр link. Если указан параметр port, листенер i2Rpc "слушает" обращения клиентов по адресу 0.0.0.0:<port>
+
* '''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''' - максимальное количество файловых дескрипторов, доступных серверному заданию i2Rpc. Операционная система IBMi по умолчанию ограничивает количество файловых дескрипторов, доступных заданию, значением 200. Серверу i2Rpc требуется минимум 2 файловых дескриптора на каждого подключенного клиента, и по 2 дескриптора на каждую подключенную сессию. Рекомендуется указывать значение maxDescriptors, которое будет достаточным для обслуживания планируемого количества клиентов и сессий.
+
* '''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===
 
* '''debugIdentity, debugLevel, debugFacility, debugProtocol, syslogHost, syslogPort''' - параметры логирования, аналогичные описанным выше в секции gateway
 
* '''link''' - линк (unix сокет), через который общаются сервер и сессии. По умолчанию формируется в виде <code>/tmp/I2R@<port>.do_not_delete</code>, где port - номер порта gateway. Сервер и сессии должны иметь доступ к указанному ресурсу. Удаление линка в момент работы сервера ЗАПРЕЩЕНО
 
* '''maxLoggerQueueSize''' - Максимальная длина очереди отправки сообщений в прикладную трассировку (общая длина всех неотправленных сессией сообщений, в байтах). При превышении отправка сообщений в трассировщик останавливается
 
  
===Секция stateless===
+
===Session section===
* '''job, user, profile''' - имя работы, пользователя и профайл запускаемыx stateless сессий.
+
* '''debugIdentity, debugLevel, debugFacility, debugProtocol, syslogHost, syslogPort''' - logging parameters similar to those described above in the gateway section
: Если что-то не указано, по умолчанию используются параметры из серверного задания. То есть, если что-то из job, user, profile не указаны, и например запущенное задание данного сервера i2Rpc - 123456/I2RUSER/I2RPCG, работает под профилем I2RPRF, то stateless сессии  будут запускаться под профилем I2RPRF, и будут иметь имя NNNNNN/I2RUSER/I2RPCG
+
* '''link''' -  a link (unix socket) through which the server and sessions communicate. By default, it is formed as <code>/tmp/I2R@<port>.do_not_delete</code>, 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
* '''submit''' - команда запуска stateless сессии.
+
* '''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
: Указывается шаблон команды SBMJOB, которую сервер будет использовать для запуска новых stateless сессий. Можно указать любые параметры команды SBMJOB, за исключением параметра CMD. Параметр CMD формируется сервером самостоятельно
+
 
: В шаблоне команды можно использовать следующие макроподстановки - при формировании команды данные макроподстановки будут заменены на соответствующие параметры конфигурации
+
===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.link}             
 
:* ${gateway.debugLevel}         
 
:* ${gateway.debugLevel}         
Line 135: 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===
+
===Section statefull===
* '''job, user''' - имя работы и пользователя запускаемыx statefull сессий.
+
* '''job, user''' - name of the job and user of the submitted statefull sessions
: Если что-то не указано, по умолчанию используются параметры из клиентского задания. То есть, если что-то из job или user не указаны, и например запущенное задание данного клиента i2Rpc - 123456/I2RUSER/I2RPCC, запущено под профилем I2RPRF, то statefull сессии, запускаемые для данного клиента, будут запускаться под профилем I2RPRF, и будут иметь имя NNNNNN/I2RUSER/I2RPCC
+
: 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''' - команда запуска statefull сессии.
+
* '''submit''' - command to submit a statefull session
: Указывается шаблон команды SBMJOB, которую сервер будет использовать для запуска новых statefull сессий. Можно указать любые параметры команды SBMJOB, за исключением параметра CMD. Параметр CMD формируется сервером самостоятельно
+
: 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.link}             
 
:* ${gateway.debugLevel}         
 
:* ${gateway.debugLevel}         
Line 188: Line 190:
 
:* ${statefull.user}
 
:* ${statefull.user}
 
:* ${statefull.init}
 
:* ${statefull.init}
:* ${statefull.profile} - этот параметр определяется на основе наименования профайла, под которым работает исходное клиентское задание
+
:* ${statefull.profile} - this parameter is determined based on the name of the profile under which the original client job is running
:* ${statefull.system} - этот параметр содержит имя системы, в которой запущено исходное клиентское задание
+
:* ${statefull.system} - this parameter contains the name of the system on which the original client job is running
: По умолчанию используется значение:
+
: The default value is:
 
:<code>SBMJOB JOB(${statefull.job}) USER(${statefull.user})</code>
 
:<code>SBMJOB JOB(${statefull.job}) USER(${statefull.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 (µs)  
: Если после запуска сессии прошло указанное время, но сессия не подключилась к серверу, то считается что сессия не стартовала, клиент получит сообщение об ошибке I2RC005 "Unable to get i2Rpc connection. Session submit timed out"
+
: 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''' - время неактивности (мкс).
+
* '''jobTimeout''' - inactivity time (µs)  
: Если сессия не получает запросов в течение указанного времени, она будет завершена
+
: If the session does not receive requests within the specified time, it will be terminated
: По умолчанию = 5000000, (5 секунд)
+
: Default = 5000000, (5 seconds)
* '''maxJobs''' - максимальное количество statefull сессий, 0 - не ограничено
+
* '''maxJobs''' - maximum number of statefull sessions, 0 - unlimited
: По умолчанию 0 - не ограничено
+
: Default 0 - unlimited
* '''sendTimeout''' - время, в течение которого клиент ожидает отправки сообщения в сессию
+
* '''sendTimeout''' - the time the client waits for a message to be sent to the session
: Если клиент не указал параметр 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 during which the client waits to receive a message from the session
: Используется аналогично 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 before calling the program if the session [[#I2RC000005|context has been changed]]
  
===Секция logger===
+
===Section logger===
Данная секция предназначена для настройки параметров протоколирования вызовов RPC прикладной программой трассировки (см. [[#Логирование и трассировка|Логирование и трассировка]])
+
This section is intended for configuring the parameters for logging RPC calls by the tracing application (see [[#Logging and Tracing|Logging and Tracing]])
  
Протоколирование параметров вызовов RPC внешней user exit программой - достаточно нагруженная процедура, поэтому в целях оптимизации вычислительных ресурсов задача протоколирования может быть отделена от основного задания сервера i2Rpc и вынесена в изолированное задание. То есть можно говорить об использовании встроенного и внешнего протоколирования вызовов RPC. За это отвечает параметр '''embedded'''.
+
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
  
Сервер протоколирования (встроенный или внешний) - это многопоточный сервер, в котором организована внутренняя очередь сообщений, подлежащих передаче в user exit программу протоколирования. Для передачи сообщений от сессий в сервер протоколирования используется отдельный unix сокет (файл на файловой системе IFS), который определяется в настройках сервера
+
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
* <span id="embedded_logger">'''embedded''' - Признак использования встроенного в gateway прикладного трассировщика
 
: Если embedded=false, для логирования  вызовов можно запустить отдельное задание логирования
 
: Задание имеет те же параметры, что и основное задание gateway, только вместо <code>CALL I2RPCG</code> должен быть сделан <code>CALL I2RPCL</code>
 
* '''listenerThreads''' - количество потоков сервера протоколирования. При использовании встроенного сервера протоколирования, данные потоки запускаются параллельно с остальными потоками сервера i2Rpc
 
* '''link''' - линк (сокет), который используется для передачи сообщений серверу протоколирования
 
: По умолчанию формируется в виде <code>/tmp/I2R@<port>_log.do_not_delete</code>, где port - номер порта gateway
 
: Сервер протоколирования и сессии должны иметь доступ к указанному ресурсу
 
: Удаление линка в момент работы сервера ЗАПРЕЩЕНО
 
* <span id="embedded_logger_program">'''program''' - имя программы, которая выполняет прикладное протоколирование вызовов RPC
 
* '''events''' - какие сообщения подлежат протоколированию. Возможные варианты:
 
:* '''output''' - сохраняются только ответные сообщения
 
:* '''input''' - сохраняются только входящие запросы
 
:* '''both/inputoutput''' - сохраняются входящие запросы и ответные сообщения
 
:* '''none''' - протоколирование не выполняется
 
  
=Запуск сервера=
+
* <span id="embedded_logger">'''embedded''' - Flag for using the gateway's built-in application logger
Для старта экземпляра сервера i2RPC необходимо запустить новое пакетное задание, в котором должна быть выполнена команда вызова основной программы сервера i2RPC:
+
: 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 <code>CALL I2RPCL</code> must be specified instead of <code>CALL I2RPCG</code>
 +
* '''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 <code>/tmp/I2R@<port>_log.do_not_delete</code>, 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
 +
* <span id="embedded_logger_program">'''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
  
<code>SBMJOB CMD(CALL PGM(I2RPCG) PARM(<Параметры командной строки>)) ALWMLTTHD(*YES)</code>
+
=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 могут быть любыми, однако:
+
<code>SBMJOB CMD(CALL PGM(I2RPCG) PARM(<startup parameters>)) ALWMLTTHD(*YES)</code>
* ALWMLTTHD(*YES) - обязательный параметр
 
* Программа I2RPCG должна присутствовать в списке библиотек
 
  
'''''TODO:''''' Требуемая авторизация пользователя, который запускает I2RPCG
+
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==
Параметры конфигурации экземпляра сервера i2RPC указываются в параметрах вызова программы I2RPCG, в формате:
+
The i2Rpc server instance configuration parameters are specified in the I2RPCG program call parameters, in the following format:
  
<code>--parameter=value</code> или
+
<code>--parameter=value</code> or
  
<code>--parameter value</code> или
+
<code>--parameter value</code> or
  
<code>--parameter</code> - если параметр представляет собой некий признак, и не предусматривает указания значения
+
<code>--parameter</code> - if the parameter is a certain flag and does not require specifying a value
  
Пример:
+
Example:
  
 
<code>SBMJOB CMD(CALL PGM(I2RPCG) PARM('--config=/home/i2rpc/config.json' '--stateless.minJobs' '1')) ALWMLTTHD(*YES)</code>
 
<code>SBMJOB CMD(CALL PGM(I2RPCG) PARM('--config=/home/i2rpc/config.json' '--stateless.minJobs' '1')) ALWMLTTHD(*YES)</code>
  
Параметр --config, если указан, определяет имя файла, содержащего параметры конфигурации экземпляра сервера. Файл должен иметь кодировку 1208 (utf-8), и содержать валидный json объект с атрибутами, соответствующими параметрам конфигурации сервера.
+
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==
Как отмечено в разделе [[#logging_and_tracing|Логирование и трассировка]], для сохранения отладочных сведений о выполнении пользовательских программ, используется специальная user exit программа. Для уменьшения влияния производительности данной user exit программы на совокупную производительность сервера i2Rpc, все процедуры, связанные с трассировкой, вынесены в отдельный сервер трассировки. Сервер представляет собой поток(и), которые ожидают трассировочные сообщения от обработчиков и вызывают user exit программу протоколирования. Сервер может быть запущен как в составе основного задания сервера i2RpcG, так и в отдельном задании.
+
As noted in the [[#logging_and_tracing|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
  
Для использования встроенного в i2RpcG сервера трассировки, необходимо указать следующие параметры конфигурации сервера:
+
To use the embedded i2RpcG tracing server, you must specify the following server configuration parameters:
 
* '''logger.embedded''' = true
 
* '''logger.embedded''' = true
* '''logger.listenerThreads''' - значение больше нуля. Определяет количество потоков сервера трассировки, которые будут запущены в составе сервера i2RpcG
+
* '''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:
* Указать в '''logger.embedded'''=false, '''logger.listenerThreads''' - ненулевое значение
+
* Specify '''logger.embedded'''=false, '''logger.listenerThreads''' - non-zero value
* Запустить внешний сервер протоколирования командой, аналогичной команде запуска основного сервера i2RpcG, используя имя программы I2RPCL вместо I2RPCG, например:
+
* 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:
 
:<code>SBMJOB CMD(CALL PGM(<b>I2RPCL</b>) PARM('--config=/home/i2rpc/config.json' '--stateless.minJobs' '1')) ALWMLTTHD(*YES)</code>
 
:<code>SBMJOB CMD(CALL PGM(<b>I2RPCL</b>) PARM('--config=/home/i2rpc/config.json' '--stateless.minJobs' '1')) ALWMLTTHD(*YES)</code>
  
 
<span id="I2RPCAPI/>
 
<span id="I2RPCAPI/>
=Использование i2RpcAPI=
 
==Параметры вызова i2RpcAPI==
 
Для взаимодействия клиентского ПО с сервером i2Rpc, используется программа I2RPCAPI
 
  
Прототипы:
+
=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>   
 
  #include <QUSEC.h>   
Line 282: Line 284:
  
 
  D/COPY QSYSINC/QRPGLESRC,QUSEC
 
  D/COPY QSYSINC/QRPGLESRC,QUSEC
   * Основной модуль i2Rpc API
+
   * i2Rpc API
   * Параметры:
+
   * Parameters:
   *  format  - определяет команду i2Rpc API и формат ее параметров
+
   *  format  - defines the i2Rpc API command and the format of its parameters
   *  ApiData - параметры вызова i2RpcAPI, структура зависит от Format
+
   *  ApiData - i2RpcAPI call parameters, structure depends on Format
   *  error  - (не обязательно) - структура для возврата кода ошибки
+
   *  error  - (optional) - structure for returning error code
 
   *             
 
   *             
 
  D i2RpcAPI        PR                  EXTPGM('I2RPCAPI')
 
  D i2RpcAPI        PR                  EXTPGM('I2RPCAPI')
Line 294: Line 296:
  
  
Формальный список параметров программы i2RpcAPI:
+
Formal list of parameters of the i2RpcAPI program:
* '''format''' - команда i2Rpc, определяет команду i2Rpc и формат ее параметров. Одно из:
+
* '''format''' - i2Rpc command, defines the i2Rpc command and the format of its parameters. One of:
 
** I2RC000001
 
** I2RC000001
 
** I2RC000002
 
** I2RC000002
Line 301: Line 303:
 
** I2RC000004
 
** I2RC000004
 
** I2RC000005
 
** I2RC000005
* '''apiData''' - cтруктура, содержащая параметры вызова данной команды
+
* '''apiData''' - a structure containing the parameters for calling this command
* '''error''' (не обязательно) cтандартная структура для обмена информацией об ошибках, в стандартном формате API IBMi QUSEC [https://www.ibm.com/docs/en/ssw_ibm_i_74/apiref/errorcodeformat.htm ERRC0100]
+
* '''error''' (optional) standard structure for exchanging error information, in standard IBMi API QUSEC API IBMi QUSEC [https://www.ibm.com/docs/en/ssw_ibm_i_74/apiref/errorcodeformat.htm ERRC0100]
  
Если параметр ошибки не передан, то в случае возникновения ошибок, i2RpcAPI сгенерирует прерывающее escape сообщение. Если параметр ошибки передан, то после вызова i2RpcAPI в нем будет содержаться код ошибки и сопровождающая ошибку информация
+
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 подключение к серверу==
+
==I2RC000001 connect to server==
Команда I2RC000001 используется для получения хендлера соединения к серверу i2Rpc. Структура параметров команды I2RC000001:
+
The I2RC000001 command is used to obtain a connection handler to the i2Rpc server. The structure of the I2RC000001 command parameters:
  
 
  // I2RC000001 - Connect
 
  // I2RC000001 - Connect
Line 345: Line 347:
 
  D  id                          10A                                        Job id
 
  D  id                          10A                                        Job id
  
Параметры:
+
Parameters:
* '''gateway''' адрес сервера i2Rpc (IP адрес или сетевое имя, или имя файла на файловой системе, если сервер запущен на unix-сокете)
+
* '''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. Должно равняться 0, если используется unix-сокет
+
* '''port''' i2Rpc server port. Should be 0 if unix socket is used
* '''statefull''' если = 1, то для данного соединения будет запущено персональное задание, и все RPC вызовы будут адресованы в это задание. Если = 0, то сервер i2Rpc будет использовать любое доступное задание для RPC вызовов в рамках данного соединения
+
* '''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''' таймаут установки соединения. Если=0, по умолчанию используется 5с.
+
* '''connectTimeout''' connection timeout. If=0, default is 5s
* '''contextLength''' длина параметра contextData  
+
* '''contextLength''' length of the contextData parameter
* '''contextData''' указатель на данные контекста
+
* '''contextData''' pointer to context data
* '''connection''' handler соединения
+
* '''connection''' (output) connection handler
* '''system''', '''number''', '''user''', '''id''' имя задания, запущенного на сервере i2Rpc для обслуживания данного соединения (только для statefull=1)
+
* '''system''', '''number''', '''user''', '''id''' (output) - name of the job running on the i2Rpc server to service this connection (only for statefull=1)
:Если statefull=0, то данные параметры в ответе не заполняются
+
:If statefull=0, then these parameters are not filled in the response
  
==I2RC000002 RPC вызов программ==
+
==I2RC000002 RPC program call==
Формат I2RC000002 используется для удаленного вызова программ при помощи i2Rpc
+
The I2RC000002 format is used to call programs remotely using i2Rpc
  
Структура параметров
+
Parameters structure
  
 
  // I2RC000002 - Run program
 
  // I2RC000002 - Run program
Line 403: Line 405:
 
  D  joblog                        *                                        O (withJobLog*+joblogProvided)
 
  D  joblog                        *                                        O (withJobLog*+joblogProvided)
  
Описание параметров:
+
Parameters:
  
* '''connection''' полученный ранее handler соединения
+
* '''connection''' previously obtained connection handler
* '''lib/pgm'''  input - имя вызываемой программы. В lib можно использовать *LIBL. Программа должна быть "видна" в списке библиотек целевого задания
+
* '''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 - если параметр returnResolvedName=1, то в данных полях возвращается реальное имя библиотеки и программы, использованной при удаленном вызове
+
: 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''' массив из argc элементов - указателей на параметры программы
+
* '''argv''' array of argc elements - pointers to program parameters
* '''argl''' массив длин параметров программы. Каждый элемент массива определяет длину соответствующего элемента массива argv
+
* '''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
: Если отправка не завершится за указанное время, то i2RpcAPI вернет ошибку I2RC031
+
: If the sending does not complete within the specified time, i2RpcAPI will return the error I2RC031
: если = 0, то используется соответствующий параметр конфигурации сервера
+
: if = 0, then the corresponding server configuration parameter is used
* '''recvTimeout''' таймаут (мкс) приема сообщения от сессии
+
* '''recvTimeout''' timeout (µs) for receiving a message from a session
: Если ответное сообщение от сессии не поступит в течение указанного времени после отправки, то i2RpcAPI вернет ошибку I2RC032
+
: If a response message from the session is not received within the specified time after sending, i2RpcAPI will return the error I2RC032
: если = 0, то используется соответствующий параметр конфигурации сервера
+
: if = 0, then the corresponding server configuration parameter is used
 
* '''traceIn''' 0/1
 
* '''traceIn''' 0/1
: Если = 1, то в job log сессии будет распечатан массив входных параметров программы в hex формате
+
: 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
: Если = 1, то в job log сессии будет распечатан массив выходных параметров программы в hex формате
+
: 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
: Если = 1, то сервер вернет клиенту содержимое job log сессии, сформированное в процессе вызова программы.
+
: If = 1, the server will return to the client the contents of the session's job log generated during the program call
: Для приема joblog необходимо передать в параметре joblog указатель на область памяти, где должен быть размещен текст протокола задания, и указать в параметре joblogProvided длину данной области
+
: 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
: Аналогично предыдущему параметру, но job log будет возвращен только в случаях критических сбоев вызова программы
+
: 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
: Если = 1, то после вызова API в переменных lib/pgm будет возвращено реальное значение использованных при вызове библиотеки и программы
+
: 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 - входной PLIST перед вызовом программы
+
:* I - input PLIST before calling the program
:* O - выходной PLIST после вызова программы
+
:* O - output PLIST after program call
:* B - PLIST до и после вызова программы
+
:* 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''' - количество байт, доступных в переменной joblog для приема возвращаемого joblog программы
+
* '''joblogProvided''' - the number of bytes available in the joblog variable to receive the program's returned joblog
* '''joblog''' указатель на область памяти длиной joblogProvided, куда будет размещен joblog вызванной программы
+
* '''joblog''' - pointer to a memory area of length joblogProvided where the called program's joblog will be placed
  
 
==I2RC000003 печать joblog==
 
==I2RC000003 печать joblog==
Line 478: Line 480:
 
* '''connection''' указатель на хэндлер соединения, полученный ранее командой I2RC000001
 
* '''connection''' указатель на хэндлер соединения, полученный ранее командой I2RC000001
  
<snap id="I2RC000005"/>
+
<span id="I2RC000005"/>
==I2RC000005 изменение контекста вызова==
+
 
 +
==I2RC000005 Set/update client context==
 
Команда I2RC000005 позволяет клиенту выполнить установку/изменение клиентского [[#session_context|контекста сессии]]. Данный вызов сохраняет/заменяет содержимое области данных клиентского контекста, эти данные передаются серверу i2Rpc при всех последующих вызовах программ командой I2RC000002.  
 
Команда I2RC000005 позволяет клиенту выполнить установку/изменение клиентского [[#session_context|контекста сессии]]. Данный вызов сохраняет/заменяет содержимое области данных клиентского контекста, эти данные передаются серверу i2Rpc при всех последующих вызовах программ командой I2RC000002.  
  

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

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)

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 of CALL 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