Многопроцессорность и отладка

Как и любое другое программное средство, фреймворк FCF поддерживает средства отладки, как на стороне сервера, так и на стороне клиента.

Отладка на стороне клиента.

По умолчанию все JS файлы, которые передаются на сторону клиента через штатный контроллер чтения файлов fcf:NServer/NControllers/File.js проходят упрощенное сжатие (удаляются лишние пробельные символы и комментарии с сохранением количества строк), отключить сжатие для текущего клиента можно используя панель управления разработки fcfManagement. (http://localhost:8080/fcfpackages/fcfManagement/development)

или выполнить следующие Javascript инструкции для включения отладочного режима в консоли браузера.

> fcf.getContext().debug = true; > fcf.saveContext();

После этого все файлы получаемые клиентом не будут подвергаться упрощенному сжатию.

Теперь можно приступать к отладке. Можете самостоятельно ознакомиться с отладкой шаблонов.

Многопроцессорная работа приложения FCF и перезапуск NODEJS процессов.

Прежде чем приступить к описанию отладки на стороне сервера, нужно пояснить как устроена многопроцессорная работа приложений FCF. Встроенная программа fcfserver запускает N количество процессов NODEJS. Количество процессов определяется параметром конфигурации "processes" fcfserver-а в файле server.json. Принимая запросы от клиента fcfserver распределяет запросы отдельным процессам NODEJS. Так же, fcfserver наблюдает за состоянием запущенных процессов и при необходимости производит перезапуск. Перезапуск процесса осуществляется в 4-х случаях:

  1. При явном запросе перезапуска. Используя панель fcfManagement (http://localhost:8080/fcfpackages/fcfManagement/system):

    Или используя отправку системного сообщения.

  2. При обновлении Javascript файлов или файлов конфигурации.
  3. При нештатном завершении процесса.
  4. При превышении лимита памяти. Данный лимит задается параметром конфигурации "maxMemory" в конфигурационном файле server.json приложения fcfserver. По умолчанию он достаточно мал и составляет 150Mb, поэтому при необходимости его следует изменить.

Перезапуск процесса происходит по следующей схеме. На каждый активный процесс NODEJS имеется пара конфигураций запуска процессов и при перезапуске происходит поочередное переключение между этими конфигурациями.

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

Отладка на стороне сервера.

Для выполнения отладки на стороне сервера необходимо изменить параметры конфигурации fcfserver. Необходимо задать параметры запуска NODEJS процессов для запуска в режиме отладки. Это делается редактированием параметра конфигурации "nodeOptions" в файле server.json. Данный параметр содержит массив, который содержит массив строк параметров запуска NODEJS процессов. Каждый элемент данного массива соответствует отдельной конфигурации запуска процесса. То есть, первые два элемента массива соответствуют первой паре активных взаимно сменяемых процессов, вторая второй и так далее. Таким образом если параметр "processes" равен 2, то размер массива nodeOptions должен быть равен 4.

И так, зададим конфигурацию fcfserver для отладки, отредактировав файл server.json. Добавим опцию --inspect с портом отладки.

Файл :server.json

{ // Server name "serverName": "main", // Main server name "mainServer": "main", // Server array // If there is only one element in the array (main server), then the port is not listened on. "servers": [ { // Server name "name": "main", // Server address "address": "127.0.0.1", // Server port "port": 3778 } ], // Number of the local server management port (int) // If 0 is specified, then a random free port is used "innerControlPort": 0, // Prefix of the log file path (string) "logFile": "log/server-log-", // The logging level (enum:[err|wrn|log|trc]) "logLevel": "log", // The life time of the log file of the server (days) "logLifeTime": 30, // User under which FCF processes are started. If the field is an empty string, then the process is executed from the current user. "user": "", // User password. Used only for Windows systems "password": "", // Length of the request queue "listenQueue": 128, // The value of keep-alive http requests "keepAliveTimeout": 5, // Maximum waiting time for receiving and sending a client packet (sec) "clientSocketTimeout": 5, // Maximum waiting time for receiving a request from the client (sec) "maxRequestTimeout": 300, // Maximum waiting time for receiving and sending a server packet (sec) "serverSocketTimeout": 5, // Maximum time to wait for a request to be sent from the server (sec) "maxResponseTimeout": 300, // Maximum time to wait for a child process to start (sec) "startTimeout": 600, // Maximum waiting time for a child process to stop (sec) "stopTimeout": 30, // Size of the intermediate data transfer buffer. This buffer is used // when receiving a request to transfer data to the client or in the case of a reboot // process when sending data to the client, in order to quickly release the process. // If the data size exceeds the set limit, then it is saved to disk. "transmissionBufferSize": 1000000, // The configuration of endpoints "endpoints": [ { // User under which FCF processes are started //"user": "www-data", // Used only for Windows systems //"password": "", // Length of the request queue //"listenQueue": 128, // Maximum waiting time for receiving and sending a client packet (sec) //"clientSocketTimeout": 5, // Maximum waiting time for receiving a request from the client (sec) //"maxRequestTimeout": 300, // Maximum waiting time for receiving and sending a server packet (sec) //"serverSocketTimeout": 5, // Maximum time to wait for a request to be sent from the server (sec) //"maxRequestTimeout": 300, // Maximum time to wait for a child process to start (sec) //"startTimeout": 600, // Maximum waiting time for a child process to stop (sec) //"stopTimeout": 30, // Size of the intermediate data transfer buffer. This buffer is used // when receiving a request to transfer data to the client or in the case of a reboot // process when sending data to the client, in order to quickly release the process. // If the data size exceeds the set limit, then it is saved to disk. //"transmissionBufferSize": 1000000, // The server interface address for IPv4, if omitted, must contain the value "none" (string) "bind4": "", // The server interface address for IPv6, if omitted, must contain the value "none" (string) "bind6": "::", // Number of the listening port (int) "port": 8080, // Handler parameters "handlers": [{ // Handler name "name": "application", // Maximum time to wait for a child process to start (sec) //"startTimeout": 30, // Maximum waiting time for a child process to stop (sec) //"stopTimeout": 30, // The host specified in the HTTP request that the handler will respond to. If omitted, it must contain an empty string. (string) "host": "", // URL the path specified in the HTTP request that the handler will respond to. If omitted, it must contain an empty string. (string) "path": "", // The number of concurrently running processes of handlers of constant work // without protection of memory leaks. The minimum value 2 (int) "processes": 1, // The FCF app. JavaScript script to run (string) "script": "fcf-example-moving-containers.js", // An array of arrays containing arrays of NDOEJS options for each process "nodeOptions": [["--inspect=17000"], ["--inspect=17001"]], // Maximum allowable memory size used by a handler process for processes with memory leak protection "maxMemory": 150, // Array of control message transmission ports. // The array is automatically filled up to the size specified in (process + processesLeakProtection) * 2, // applying an increment if at least one port is specified. // If the array is empty, then random free ports are used. "dataPorts": [] }] } ] }

Теперь откроем браузер chrome на странице настройки отладки chrome://inspect.

Добавьте в конфигурацию два наших соединения для отладки (кнопка configure).

Теперь перезапустите fcfserver. И на панели отладки chrome появится наш запущенный процесс.