betslus1 / bestbot

конкурс ТИ
Apache License 2.0
21 stars 5 forks source link

Вылетает из-за нехватки памяти #3

Closed Slona closed 2 years ago

Slona commented 2 years ago

Пробовал на 2 Гб, 4 Гб, 8 Гб, результат один:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory                             ║| # | c     | h     | l     | o     | time        | v   ║
 1: 0xb02930 node::Abort() [node]                                                                                                    ║--------------------------------------------------------║
 2: 0xa18149 node::FatalError(char const*, char const*) [node]                                                                       ║| 0 | 48.8  | 48.98 | 48.28 | 48.37 | 17.08 23:37 | 2493║
 3: 0xcdd16e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node]                                           ║| 1 | 49.5  | 49.85 | 48.75 | 48.75 | 17.08 23:38 | 5676║
 4: 0xcdd4e7 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]                             ║| 2 | 49.1  | 49.57 | 48.7  | 49.45 | 17.08 23:39 | 1240║
 5: 0xe94b55  [node]                                                                                                                 ║| 3 | 49.25 | 49.29 | 48.9  | 49.14 | 17.08 23:40 | 9024║
 6: 0xe95636  [node]                                                                                                                 ║| 4 | 49.02 | 49.16 | 49    | 49.16 | 17.08 23:41 | 9450║
 7: 0xea3b5e  [node]                                                                                                                 ║| 5 | 49.1  | 49.12 | 49    | 49.1  | 17.08 23:42 | 1101║
 8: 0xea45a0 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node] | 49.34 | 48.95 | 49.08 | 17.08 23:43 | 7932║
 9: 0xea751e v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]8 23:44 | 1286║
10: 0xe68a5a v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [node]  ║| 8 | 49.13 | 49.33 | 49.02 | 49.12 | 17.08 23:45 | 7596║
11: 0x11e18fc v8::internal::Runtime_AllocateInOldGeneration(int, unsigned long*, v8::internal::Isolate*) [node]                      ║| 9 | 48.83 | 49.2  | 48.66 | 49.2  | 17.08 23:46 | 4600║
12: 0x15d5439  [node]                                                                                                                ║--------------------------------------------------------║
Aborted                                 
Slona commented 2 years ago

ПРобовал вот это, не помогло:

export NODE_OPTIONS="--max-old-space-size=8192" # Increase to 8 GB

betslus1 commented 2 years ago

Ему столько не надо, дело не в памяти

Скорее всего из за того что папка node_modules скомпилирована под другую версию чего-то

Напишите все версии, что сейчас установлено: Название и версию ОС Версию nodejs Версию npm

PS. ошибку посмотрю PPS. По уму мне может стоит удалить вообще этот несчастный sqlite3, он там используется только для хранения сделок и по факту он там не нужен. Вообще когда отправлял репозиторий тестировал на Debian последнем, Windows 10, и MacOS

betslus1 commented 2 years ago

И на всякий случай напишите options.js (без секретных токенов), и какой инструмент запустили. Веб версия работает?

Сразу после запуска ошибка? ./data/db.sqlite появился?

Slona commented 2 years ago

Ух, поехали:

Description:    Debian GNU/Linux 11 (bullseye)
Release:        11
Codename:       bullseye

node: v16.17.0


npm: 8.15.0


Веб-версия работает, пытался ковыряться в песочнице, но недолго, в промежутке от 2 до 15 минут апп ложится с ошибкой выше.


./data/db.sqlite присутствует


options.js правил не полностью, вот содержимое:

module.exports = {
        'login'            : 'xxxxx', //имя от веб версии
        'password'         : 'xxxxxxxx', //пароль от веб версии
        'appname'      : 'bestbot-slona', //Служебный параметр для идентификации SDK на стороне брокера (для статистики), желательно не менять если используете стандартную конфигурацию
        'workmode'     : 'sandbox', //real, sandbox, backtest
        'port'         : 333, //Номер порта для веб версии интерфейса
        'token'        : 'xxxxx' || process.argv[2], //Токен либо первый аргумент "node app.js <token>"
        'tradeAccount' : xxxxxxx, //Номер счета, посмотреть можно в брокреском отчете или методом getAccounts()
        'sandboxAccountId' : 'xxxxxx', //account_id для песочницы по умолчанию
        'strategy'     : 'rsi',//Имя стратегии по умолчанию
        'instrument'   : 'BBG004S68598', //'BBG000B9XRY4', //Figi инструмента по умолчанию
        'candleHistoryLenght': 60,      //Количество свечей передаваемых в стратегию
        'isLog'        :        { //Отображать или скрывать в общем логе данные типы сообщений
                'ordersSync'      : false,
                'balanceSync'     : false,
                'loadInstruments' : true,
                'loadHistory'     : true,
                'operationsSync'  : true,
        },
        'comission'    : 0.04/100, //Размер комиссии брокера
        'telegramKey'  : 'xxxxxxxxxxx', //Создается через бота @botFather в телеграм
        'chatId'           : 129531676, //смотрим через бота (отправить боту в телеграме /start и запустить приложение, потом вписать сюда ID вашего чата), - не менял пока что
        'maxCountError': 100, //Количество ошибок в час для автоматической аварийной остановки
        'minMoneyBalance' : -10000,
        'limit'       : { //rpm
                'marketData' : 30,
                'orders'     : 30,
                'operations' : 30,
        }
}
Slona commented 2 years ago

а, ну и вопрос не по теме заодно: бот только с рублями работает? в песочнице например добавляются только рубли.

betslus1 commented 2 years ago

Запустил на 15 минут с этим конфигом. Alert'ы не приходили в телеграм какие - нибудь? Каких то действий перед падением не делалось? Память переполняется медленно или резко?

а, ну и вопрос не по теме заодно: бот только с рублями работает?

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

в песочнице например добавляются только рубли.

Можно поменять валюту в файле web.js метод webApp.get('/sandboxPayIn', async function (req, res) { или сделать аналогичный свой метод, тут полет для фантазии.

Slona commented 2 years ago

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

betslus1 commented 2 years ago

Попробуйте токен телеграмма добавить, там 2 минуты через @botFather, туда могут ошибки приходить какие - то от программы. Я запустил, единсветнное в вашем конфиге второй figi раскоментировал (там APPLE) чтобы стакан шевелился хоть немного в веб и консоль версии. Вроде нормально все.

Возможно какое -то конкретное действие вызывает зависание.

Slona commented 2 years ago

Подключил бота, запустил апп. Открыл веб-морду песочницы, загрузил тикер ENDP, спустя две минуты апп снова упал. Более ничего не делал, просто смотрел errrrr

Slona commented 2 years ago

Плюс в консоли регулярно спамится вот эта надпись, это нормально? Skip

UPD: вот сейчас запустилл апп и ВООБЩЕ ничего не делал, даже веб-морду не открывал. Сдох спустя 2 минуты. errrrrrr

betslus1 commented 2 years ago

Возможно все таки надо правильно собрать и скомпилировать SQLite и другие модули через npm, сложно так удалённо что-то сказать.

Или нужно дебажить и смотреть в каком модуле течёт память.

Могу попробовать в докер собрать как вариант, хотя по мне это не очень удобно, ибо она рассматривалась как шаблон для разработки.

как я писал, сборка стабильно работала в виндовс,Линукс и на маке. Сейчас я ее также выгрузил с гитхаба и запустил.

Slona commented 2 years ago

Ок, щас еще раз откачусь на чистую ось и попробую по инструкции собрать. Какие пререквизиты должны быть на оси? кроме node.js надо чтото ставить?

betslus1 commented 2 years ago

Ничего не нужно, я для разработки так же использовал debian 11 x64, nodejs актуальный на тот момент v16.10

Ставил с оф источника https://github.com/nodesource/distributions/blob/master/README.md

Using Debian, as root

curl -fsSL https://deb.nodesource.com/setup_lts.x | bash -
apt-get install -y nodejs

Если вдруг не получится, и эта виртуалка в которой ничего нет секретного, могу зайти подебажить, самому уже интересно.

Slona commented 2 years ago

Ну в общем все тоже самое при компиляции:

slona@inv-bot:~/bestbot$ npm i
npm WARN deprecated to-iso-string@0.0.2: to-iso-string has been deprecated, use @segment/to-iso-string instead.
npm WARN deprecated request-promise@4.2.6: request-promise has been deprecated because it extends the now deprecated request package, see https://github.com/request/request/issues/3142
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated node-pre-gyp@0.11.0: Please upgrade to @mapbox/node-pre-gyp: the non-scoped node-pre-gyp package is deprecated and only the @mapbox scoped package will recieve updates in the future
npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated mkdirp@0.3.0: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
npm WARN deprecated mkdirp@0.5.1: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
npm WARN deprecated jade@0.26.3: Jade has been renamed to pug, please install the latest version of pug instead of jade
npm notice
npm notice New minor version of npm available! 8.15.0 -> 8.18.0
npm notice Changelog: https://github.com/npm/cli/releases/tag/v8.18.0
npm notice Run npm install -g npm@8.18.0 to update!
npm notice
npm ERR! code 1
npm ERR! path /home/slona/bestbot/node_modules/sqlite3
npm ERR! command failed
npm ERR! command sh /tmp/install-b0dc0c0b.sh
npm ERR! Failed to execute '/usr/bin/node /usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/home/slona/bestbot/node_modules/sqlite3/lib/binding/node-v108-linux-x64/node_sqlite3.node --module_name=node_sqlite3 --module_path=/home/slona/bestbot/node_modules/sqlite3/lib/binding/node-v108-linux-x64 --napi_version=8 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v108' (1)
npm ERR! node-pre-gyp info it worked if it ends with ok
npm ERR! node-pre-gyp info using node-pre-gyp@0.11.0
npm ERR! node-pre-gyp info using node@18.7.0 | linux | x64
npm ERR! node-pre-gyp WARN Using request for node-pre-gyp https download
npm ERR! node-pre-gyp info check checked for "/home/slona/bestbot/node_modules/sqlite3/lib/binding/node-v108-linux-x64/node_sqlite3.node" (not found)
npm ERR! node-pre-gyp http GET https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v4.2.0/node-v108-linux-x64.tar.gz
npm ERR! node-pre-gyp http 403 https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v4.2.0/node-v108-linux-x64.tar.gz
npm ERR! node-pre-gyp WARN Tried to download(403): https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v4.2.0/node-v108-linux-x64.tar.gz
npm ERR! node-pre-gyp WARN Pre-built binaries not found for sqlite3@4.2.0 and node@18.7.0 (node-v108 ABI, glibc) (falling back to source compile with node-gyp)
npm ERR! node-pre-gyp http 403 status code downloading tarball https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v4.2.0/node-v108-linux-x64.tar.gz
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.0.0
npm ERR! gyp info using node@18.7.0 | linux | x64
npm ERR! gyp info ok
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.0.0
npm ERR! gyp info using node@18.7.0 | linux | x64
npm ERR! gyp info find Python using Python version 3.9.2 found at "/usr/bin/python3"
npm ERR! gyp http GET https://nodejs.org/download/release/v18.7.0/node-v18.7.0-headers.tar.gz
npm ERR! gyp http 200 https://nodejs.org/download/release/v18.7.0/node-v18.7.0-headers.tar.gz
npm ERR! gyp http GET https://nodejs.org/download/release/v18.7.0/SHASUMS256.txt
npm ERR! gyp http 200 https://nodejs.org/download/release/v18.7.0/SHASUMS256.txt
npm ERR! gyp info spawn /usr/bin/python3
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/home/slona/bestbot/node_modules/sqlite3/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/home/slona/.cache/node-gyp/18.7.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/home/slona/.cache/node-gyp/18.7.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/usr/lib/node_modules/npm/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/home/slona/.cache/node-gyp/18.7.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/home/slona/bestbot/node_modules/sqlite3',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp info ok
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.0.0
npm ERR! gyp info using node@18.7.0 | linux | x64
npm ERR! gyp ERR! build error
npm ERR! gyp ERR! stack Error: not found: make
npm ERR! gyp ERR! stack     at getNotFoundError (/usr/lib/node_modules/npm/node_modules/which/which.js:10:17)
npm ERR! gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/which/which.js:57:18
npm ERR! gyp ERR! stack     at new Promise (<anonymous>)
npm ERR! gyp ERR! stack     at step (/usr/lib/node_modules/npm/node_modules/which/which.js:54:21)
npm ERR! gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/which/which.js:71:22
npm ERR! gyp ERR! stack     at new Promise (<anonymous>)
npm ERR! gyp ERR! stack     at subStep (/usr/lib/node_modules/npm/node_modules/which/which.js:69:33)
npm ERR! gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/which/which.js:80:22
npm ERR! gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/isexe/index.js:42:5
npm ERR! gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/isexe/mode.js:8:5
npm ERR! gyp ERR! System Linux 5.10.0-17-amd64
npm ERR! gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "build" "--fallback-to-build" "--module=/home/slona/bestbot/node_modules/sqlite3/lib/binding/node-v108-linux-x64/node_sqlite3.node" "--module_name=node_sqlite3" "--module_path=/home/slona/bestbot/node_modules/sqlite3/lib/binding/node-v108-linux-x64" "--napi_version=8" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v108"
npm ERR! gyp ERR! cwd /home/slona/bestbot/node_modules/sqlite3
npm ERR! gyp ERR! node -v v18.7.0
npm ERR! gyp ERR! node-gyp -v v9.0.0
npm ERR! gyp ERR! not ok
npm ERR! node-pre-gyp ERR! build error
npm ERR! node-pre-gyp ERR! stack Error: Failed to execute '/usr/bin/node /usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/home/slona/bestbot/node_modules/sqlite3/lib/binding/node-v108-linux-x64/node_sqlite3.node --module_name=node_sqlite3 --module_path=/home/slona/bestbot/node_modules/sqlite3/lib/binding/node-v108-linux-x64 --napi_version=8 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v108' (1)
npm ERR! node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/home/slona/bestbot/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
npm ERR! node-pre-gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
npm ERR! node-pre-gyp ERR! stack     at maybeClose (node:internal/child_process:1091:16)
npm ERR! node-pre-gyp ERR! stack     at ChildProcess._handle.onexit (node:internal/child_process:302:5)
npm ERR! node-pre-gyp ERR! System Linux 5.10.0-17-amd64
npm ERR! node-pre-gyp ERR! command "/usr/bin/node" "/home/slona/bestbot/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
npm ERR! node-pre-gyp ERR! cwd /home/slona/bestbot/node_modules/sqlite3
npm ERR! node-pre-gyp ERR! node -v v18.7.0
npm ERR! node-pre-gyp ERR! node-pre-gyp -v v0.11.0
npm ERR! node-pre-gyp ERR! not ok

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/slona/.npm/_logs/2022-08-18T19_43_38_701Z-debug-0.log
slona@inv-bot:~/bestbot$
betslus1 commented 2 years ago

попробуйте под root, если не получится, киньте в телеграм (@betslus) доступ, попробую сам.

betslus1 commented 2 years ago

stack Error: not found: make

Должно вылечиться

sudo apt-get install build-essential

Slona commented 2 years ago

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

curl -sL https://deb.nodesource.com/setup_14.x | sudo bash -
sudo apt-get install -y nodejs
sudo apt-get install gcc g++ make
sudo apt-get install build-essential
sudo apt install sqlite3
sudo apt-get install python

После этого все отлично скомпилировалось. Однако проблему с вылетом по памяти это не решило. Также без каких-либо действий через 2 минуты вылет (скрин). Заметил также, что после запуска аппа кулер на ПК постепенно начинает разгоняться, видать где-то идет лик и нагрузка. rerererer

PS: если мыслей по прежнему никаких, то тогда завтра прокину порты и дам доступ в виртуалку в телеге

betslus1 commented 2 years ago

Спасибо, добавлю в инструкцию про зависимости.

PS: если мыслей по прежнему никаких, то тогда завтра прокину порты и дам доступ в виртуалку в телеге Пока никаких, наверное быстрее всего пообрубать по одному модули и посмотреть какой из них приводит к утечке. Гляну завтра.

Slona commented 2 years ago

Приветствую снова! Был небольшой перерыв, сегодня попробовал снова, как раз во время торгов. Проблема остается, также вылет через 2 минуты. SSH на виртуалку настроил. Маякните, когда можно будет в телегу стучать.

betslus1 commented 2 years ago

Да, я на месте, пока не сильно занят

betslus1 commented 2 years ago

Исравил ошибку, fix залил в репозиторий. Была проблема с лотностью и чрезмерной нагрузкой от operations.