Nextcloud onlyoffice при попытке соединения возникла ошибка

ONLYOFFICE имеет хорошую поддержку документов в формате Microsoft Office, поэтому выбор пал на него.

Технологический стек:

  • ONLYOFFICE Docs Community.
  • CentOS 9 под ONLYOFFICE.
  • NextCloud развёрнут в TrueNAS и работает в Jail, но у вас может работать на чём угодно.

Устанавливаем через snap – это просто и быстро.

Добавить репозиторий EPEL:

sudo yum install epel-release

Установить snap:

sudo yum install snapd

Включить системный модуль, который управляет основным сокетом связи snap:

sudo systemctl enable --now snapd.socket

Включить поддержку классической привязки, создав символическую ссылку между /var/lib/snapd/snap и /snap:

sudo ln -s /var/lib/snapd/snap /snap

Установить ONLYOFFICE:

sudo snap install onlyoffice-ds

Перезагрузить сервер:

sudo reboot -n

Настройка сети

Открыть порты, на которых работает ONLYOFFICE:

sudo firewall-cmd --permanent --zone=public --add-port=80/tcp
sudo firewall-cmd --permanent --zone=public --add-port=443/tcp
sudo firewall-cmd --reload

Вы уже можете заходить по адресу вашего сервера и наблюдать работу сервера ONLYOFFICE.

Настройка SSL и работа по HTTPS

Если у вас уже есть сертификат и ключ, чуть ниже читайте куда их поместить. Мы же сейчас разберём как создать самоподписанный сертификат для использования его на сервере ONLYOFFICE.

Перейти во временный каталог:

cd /tmp

Создать закрытый ключ:

openssl genrsa -out onlyoffice.key 2048

Создать запрос на подпись сертификата:

openssl req -new -key onlyoffice.key -out onlyoffice.csr

Подписать сертификат:

openssl x509 -req -days 365 -in onlyoffice.csr -signkey onlyoffice.key -out onlyoffice.crt

Для усиления безопасности сервера сгенерировать усиленный dhparam:

openssl dhparam -out dhparam.pem 2048

Скопировать созданные файлы в рабочий каталог ONLYOFFICE:

cp onlyoffice.key /var/snap/onlyoffice-ds/current/var/www/onlyoffice/Data/certs/
cp onlyoffice.crt /var/snap/onlyoffice-ds/current/var/www/onlyoffice/Data/certs/
cp dhparam.pem /var/snap/onlyoffice-ds/current/var/www/onlyoffice/Data/certs/

Разрешить серверу использовать самоподписанные сертификаты:

snap set onlyoffice-ds onlyoffice.use-unautorized-storage=true

Перезапустить ONLYOFFICE, чтобы он подхватил настройки и начал автоматически работать по HTTPS:

snap restart onlyoffice-ds

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

Дополнительные команды

Перейти на HTTP удалив сертификат и перезапустив ONLYOFFICE:

rm /var/snap/onlyoffice-ds/current/var/www/onlyoffice/Data/certs/onlyoffice.*
rm /var/snap/onlyoffice-ds/current/var/www/onlyoffice/Data/certs/dhparam.pem
snap restart onlyoffice-ds

Сменить HTTPS-порт:

snap set onlyoffice-ds onlyoffice.ds-ssl-port=8443

Сменить HTTP-порт:

snap set onlyoffice-ds onlyoffice.ds-port=8080

Включить примеры на сервере, чтобы проверить работу сервера без подключения к NextCloud:

snap set onlyoffice-ds onlyoffice.example-enabled=true

После выполнения команды на главной странице сервера жмите на кнопку и проверяйте работу сервера:

Кнопка

Если работает, то можно подключать к NextCloud. Не забудьте потом отключить:

snap set onlyoffice-ds onlyoffice.example-enabled=false

Получить секретный ключ

Необходимо узнать секретный ключ, который требуется указать в NextCloud, чтобы он мог подключаться к ONLYOFFICE. Для этого на сервере, где установлен ONLYOFFICE открываем файл /var/snap/onlyoffice-ds/current/etc/onlyoffice/documentserver/local.json

Ищем секцию secret и записываем секретный ключ:

Секретный ключ Onlyoffice

Он нам пригодится дальше.

Настройка интеграции ONLYOFFICE и NextCloud

Кстати, есть небольшие особенности при интеграции, поэтому не упускайте детали.

Идём в настройки NextCloud https://{IP-DOMEN}/settings/apps/files и включаем плагин ONLYOFFICE connector:

ONLYOFFICE connector

После включения идём в настройки плагина https://{IP-DOMEN}/settings/admin/onlyoffice

Настройки интеграции Onlyoffice и Nextcloud

(1) — указать домен сервера или IP-адрес доступный снаружи, на котором развёрнут ONLYOFFICE. Если указать IP вашей внутренней сети, то редактировать документы сможете только с внутренней сети, так как NextCloud при открытии документов на редактирование обращается по этому адресу к ONLYOFFICE с вашего устройства (проверьте). И понятно, что если этот адрес недоступен из внешнего мира, то вы не сможете работать с документами.

(2) — тут указываем секретный ключ, который записали ранее узнав его в секции secret.

(3) — тут указываете IP сервера ONLYOFFICE принадлежащий к вашей внутренней сети.

(4) — здесь я указал домен NextCloud, который доступен из внешней сети. По умолчанию он и подставляется сюда.

Далее я выставил следующие настройки, так как считаю их оптимальными для себя:

Настройки интеграции Onlyoffice и Nextcloud
Настройки интеграции Onlyoffice и Nextcloud

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

Особенности интеграции

  1. Первую особенность я озвучил выше, когда указывал какой IP прописывать, чтобы можно было документы править не только из локальной сети.
  2. Если время на сервере NextCloud отличается от времени на сервере ONLYOFFICE, то вы получите ошибку при сохранении настроек интеграции «При попытке соединения возникла ошибка (Возникла ошибка в службе документов: Error while downloading the document file to be converted.)». Устанавливайте одинаковое время и настройте синхронизацию серверов с каким-нибудь NTP сервером. У Google их четыре https://developers.google.com/time/guides
  3. Если при сохранении настроек синхронизации получаете ошибку «…Invalid Token», то скорее всего пока вы правили настройки NextCloud сбросил секретный ключ. Проверьте и снова внесите корректное значение.

Hi, I’m trying to integrate Onlyoffice with my Nextcloud 19 but I’m also getting this message, and since I’m new to Docker I cannot figure out what is wrong.

These are 2 separate servers. one has the Nextcloud parked on a Virtualmin Web Server and the OnlyOffice Workspace version is on a Ubuntu 20.04 server.
I’ve installed the ONO using the provided script, witwout the mail service.
I can find the ‘local.json’ file on the Docker containers, using ‘find’ command, and tried the ‘secret’ that is mentioned on them, but without any success.
The Docker is starting automatically but I’m not finding the starting service for it, yet.

Can you help figuring this out?
Thanks in advance.
JG

Добрый день! Нужна помощь. Не получается связать приложение Nextcloud с Onlyoffice.

Настраивал из docker контейнеров приложения Nextcloud и Onlyoffice. Отдельно приложения работают.
Работает на самоподписных ssl сертификатах. Перед Nextcloud-ом настроен реверс прокси. Проксирует имя example на 192.168.1.10:8088. Приложение открывает. При добавлении сервера из веб-браузера выходит ошибка «При попытке соединения возникла ошибка (Ошибка запроса или тайм-аута).

Поиск в интернете дает ответ, что ругается на самоподписные сертификаты. Но они поидее должны работать в локальной сети бех валидных сертов.
В какую сторону «копать» ?

Логи из сервера nextcloud:

{«reqId»:»8aTGtsuZtKwWXD9J75iU»,»level»:3,»time»:»2017-09-25 17:55:41″,»remoteAddr»:»172.17.0.1″,»user»:»nextcloud»,»app»:»onlyoffice»,»method»:»PUT»,»url»:»/apps/onlyoffice/ajax/settings»,»message»:»CommandRequest on check error: u041eu0448u0438u0431u043au0430 u0437u0430u043fu0440u043eu0441u0430 u0438u043bu0438 u0442u0430u0439u043cu0430u0443u0442″,»userAgent»:»Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36″,»version»:»12.0.3.3″}

Прикрепляю скрин добавления сервера из веб-интерфейса.
Заранее благодарен за любую помощь.
b8e9e9101dd44e84a39ff662fd2eaacd.jpg

Новую версию выкатили, а доку не обновили.

Если при добавлении Onlyoffice document server (сервера документов) в Nextcloud вы получаете ошибку от Nginx 403 Forbidden,(При выполнении соединения возникла ошибка (Client error Get бла бла бла resulted in a ‘403 Forbidden’ response: ), то вам следует проверить значение строки в следующих файлах :

  1. /documentserver/local.json , смотрим что в значении secretString
  2. /nginx/ds.conf , сморим что в строке secure_link_secret

Если значения различаются, то скорректируйте значения в файле ds.conf на значение из файла local.json и перезапустите Nginx.

systemctl restart nginx

Если в файле local.json нет параметра secretString, проверьте его значение в файле default.json

/documentserver/default.json

Остальное все по мануалам с сайта onlyoffice.

@axcairns

Если работает, то можно подключать к NextCloud. Не забудьте потом отключить:

snap set onlyoffice-ds onlyoffice.example-enabled=false

Получить секретный ключ

Необходимо узнать секретный ключ, который требуется указать в NextCloud, чтобы он мог подключаться к ONLYOFFICE. Для этого на сервере, где установлен ONLYOFFICE открываем файл /var/snap/onlyoffice-ds/current/etc/onlyoffice/documentserver/local.json

Ищем секцию secret и записываем секретный ключ:

Секретный ключ Onlyoffice

Он нам пригодится дальше.

Настройка интеграции ONLYOFFICE и NextCloud

Кстати, есть небольшие особенности при интеграции, поэтому не упускайте детали.

Идём в настройки NextCloud https://{IP-DOMEN}/settings/apps/files и включаем плагин ONLYOFFICE connector:

ONLYOFFICE connector

После включения идём в настройки плагина https://{IP-DOMEN}/settings/admin/onlyoffice

Настройки интеграции Onlyoffice и Nextcloud

(1) — указать домен сервера или IP-адрес доступный снаружи, на котором развёрнут ONLYOFFICE. Если указать IP вашей внутренней сети, то редактировать документы сможете только с внутренней сети, так как NextCloud при открытии документов на редактирование обращается по этому адресу к ONLYOFFICE с вашего устройства (проверьте). И понятно, что если этот адрес недоступен из внешнего мира, то вы не сможете работать с документами.

(2) — тут указываем секретный ключ, который записали ранее узнав его в секции secret.

(3) — тут указываете IP сервера ONLYOFFICE принадлежащий к вашей внутренней сети.

(4) — здесь я указал домен NextCloud, который доступен из внешней сети. По умолчанию он и подставляется сюда.

Далее я выставил следующие настройки, так как считаю их оптимальными для себя:

Настройки интеграции Onlyoffice и Nextcloud
Настройки интеграции Onlyoffice и Nextcloud

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

Особенности интеграции

  1. Первую особенность я озвучил выше, когда указывал какой IP прописывать, чтобы можно было документы править не только из локальной сети.
  2. Если время на сервере NextCloud отличается от времени на сервере ONLYOFFICE, то вы получите ошибку при сохранении настроек интеграции «При попытке соединения возникла ошибка (Возникла ошибка в службе документов: Error while downloading the document file to be converted.)». Устанавливайте одинаковое время и настройте синхронизацию серверов с каким-нибудь NTP сервером. У Google их четыре https://developers.google.com/time/guides
  3. Если при сохранении настроек синхронизации получаете ошибку «…Invalid Token», то скорее всего пока вы правили настройки NextCloud сбросил секретный ключ. Проверьте и снова внесите корректное значение.

Hi, I’m trying to integrate Onlyoffice with my Nextcloud 19 but I’m also getting this message, and since I’m new to Docker I cannot figure out what is wrong.

These are 2 separate servers. one has the Nextcloud parked on a Virtualmin Web Server and the OnlyOffice Workspace version is on a Ubuntu 20.04 server.
I’ve installed the ONO using the provided script, witwout the mail service.
I can find the ‘local.json’ file on the Docker containers, using ‘find’ command, and tried the ‘secret’ that is mentioned on them, but without any success.
The Docker is starting automatically but I’m not finding the starting service for it, yet.

Can you help figuring this out?
Thanks in advance.
JG

Добрый день! Нужна помощь. Не получается связать приложение Nextcloud с Onlyoffice.

Настраивал из docker контейнеров приложения Nextcloud и Onlyoffice. Отдельно приложения работают.
Работает на самоподписных ssl сертификатах. Перед Nextcloud-ом настроен реверс прокси. Проксирует имя example на 192.168.1.10:8088. Приложение открывает. При добавлении сервера из веб-браузера выходит ошибка «При попытке соединения возникла ошибка (Ошибка запроса или тайм-аута).

Поиск в интернете дает ответ, что ругается на самоподписные сертификаты. Но они поидее должны работать в локальной сети бех валидных сертов.
В какую сторону «копать» ?

Логи из сервера nextcloud:

{«reqId»:»8aTGtsuZtKwWXD9J75iU»,»level»:3,»time»:»2017-09-25 17:55:41″,»remoteAddr»:»172.17.0.1″,»user»:»nextcloud»,»app»:»onlyoffice»,»method»:»PUT»,»url»:»/apps/onlyoffice/ajax/settings»,»message»:»CommandRequest on check error: u041eu0448u0438u0431u043au0430 u0437u0430u043fu0440u043eu0441u0430 u0438u043bu0438 u0442u0430u0439u043cu0430u0443u0442″,»userAgent»:»Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36″,»version»:»12.0.3.3″}

Прикрепляю скрин добавления сервера из веб-интерфейса.
Заранее благодарен за любую помощь.
b8e9e9101dd44e84a39ff662fd2eaacd.jpg

Новую версию выкатили, а доку не обновили.

Если при добавлении Onlyoffice document server (сервера документов) в Nextcloud вы получаете ошибку от Nginx 403 Forbidden,(При выполнении соединения возникла ошибка (Client error Get бла бла бла resulted in a ‘403 Forbidden’ response: ), то вам следует проверить значение строки в следующих файлах :

  1. /documentserver/local.json , смотрим что в значении secretString
  2. /nginx/ds.conf , сморим что в строке secure_link_secret

Если значения различаются, то скорректируйте значения в файле ds.conf на значение из файла local.json и перезапустите Nginx.

systemctl restart nginx

Если в файле local.json нет параметра secretString, проверьте его значение в файле default.json

/documentserver/default.json

Остальное все по мануалам с сайта onlyoffice.

I have installed ONLYOFFICE 4.1.4 and Community Document Server 0.1.3 on Nextcloud 18.0.0 running in a Docker container (official image) on Ubuntu 19.10 x64.

When I go to the ONLYOFFICE settings the «Document Editing Service address» and «Server address for internal requests from the Document Editing Service» are prefilled with the address of my Nextcloud instance but the «Document Editing Service address for internal requests from the server» is empty.

If I hit save on the settings page I get an error toast with the message «Error when trying to connect (Bad healthcheck status)». There are no Onlyoffice options in either the create file menu or the file context menu.

@axcairns

Still not working with 0.1.5.

I noticed this in my Nextcloud logs (via settings > Logging) —

[PHP] Error: fclose(): supplied resource is not a valid stream resource at /var/www/html/custom_apps/documentserver_community/lib/Document/FontManager.php#66

GET /index.phpapps/update/documentserver_community
from 59.167.111.65 by allan at 2020-02-04T12:59:10+00:00

… and this in my docker logs for the nextcloud container —

[Tue Feb 04 20:59:38.166593 2020] [authz_core:error] [pid 125] [client 59.167.111.65:0] AH01630: client denied by server configuration: /var/www/html/config

@SenchoPoro42

@Wdavery

Stuck at this point too, also behind a nginx reverse proxy.

@klaask

Similar setup and healthcheck error on our side:
nginx reverse proxy & ssl termination (no docker)

To fix this error we added a different subdomain as «Document Editing Service address» and «Server address for internal requests from the Document Editing Service» and as trusted_domain in config.php.

@SenchoPoro42

I fixed my issue by letting removing the ONLYOFFICE application only, then installing it again. The correct server address was already filled in, but I just avoided pressing save on it and it then worked correctly and could connect.

@LordMort

The following fixed my issue on a NC 19.0.6 installation with OO 0.1.8 DSCE.

  1. In the OO-settings page I simply removed ALL server-entries and REFRAINED from clicking the safe-button.
  2. After that I switched to another settings page, the «Overview» in my case, and returned to the OO-settings without changing anything else.
  3. The OO-settings had been auto-filled with working entries, see below. Clicking on the safe-button at that time successfully enabled OO in my NC-installation.

The entry that had been auto-filled was:
https://<MY.DOMAIN.TLD>/index.php/apps/documentserver_community/

@TheSimu

@LordMort : Thanks! Your the hero of the day with that URL — did the trick on v.21 and current OO as of today…

@MaoMaoCake

The following fixed my issue on a NC 19.0.6 installation with OO 0.1.8 DSCE.

  1. In the OO-settings page I simply removed ALL server-entries and REFRAINED from clicking the safe-button.
  2. After that I switched to another settings page, the «Overview» in my case, and returned to the OO-settings without changing anything else.
  3. The OO-settings had been auto-filled with working entries, see below. Clicking on the safe-button at that time successfully enabled OO in my NC-installation.

The entry that had been auto-filled was: https://<MY.DOMAIN.TLD>/index.php/apps/documentserver_community/

if this dosent work try adding /index.php/apps/documentserver_community/ to the end of the url
for example your server is at https://<MY.DOMAIN.TLD>/ fill in https://<MY.DOMAIN.TLD>/index.php/apps/documentserver_community/

@iamhakeembey

The following fixed my issue on a NC 19.0.6 installation with OO 0.1.8 DSCE.

  1. In the OO-settings page I simply removed ALL server-entries and REFRAINED from clicking the safe-button.
  2. After that I switched to another settings page, the «Overview» in my case, and returned to the OO-settings without changing anything else.
  3. The OO-settings had been auto-filled with working entries, see below. Clicking on the safe-button at that time successfully enabled OO in my NC-installation.

The entry that had been auto-filled was: https://<MY.DOMAIN.TLD>/index.php/apps/documentserver_community/

In my case I had to click «Save», but simply changing the URL manually works the same. Just ensure that it includes the «index.php». Also, it’s important that both «Nextcloud Office» and «Collabora Online — Built-in CODE Server» are disabled. Otherwise, documents will be stalled at the loading screen as [at least one of] the two apps appear to interfere with ONLYOFFICE somehow. Once disabled, everything worked fine for me.

Comments

@w-le

I just had an instance of rest-api v1.17.11 get into this state:

  • api responses were OK for almost all requests made by backoffice (except ones that involve redis)
  • healthcheck was passing
  • However there must have been a redis connection issue — I believe the redis pod restarted on a different IP a few hours before this rest-api issue was reported (about 2021-03-15T23:00:00Z).
    redis pod previous status info is here:
terminated
Reason: Completed - exit code: 0
Started at: 2021-03-15T01:32:47Z
Finished at: 2021-03-15T10:02:06Z
  • api returns this error when attempting to list the Commands of any Module:
ERROR: Socket::ConnectError: Error connecting to 'redis-headless.redis:6379': Address not available (Redis::CannotConnectError)
  from app/lib/redis/src/redis/socket_wrapper.cr:10:5 in 'connect'
  from app/lib/redis-cluster/src/cluster/bootstrap.cr:47:7 in 'redis'
  from app/lib/redis-cluster/src/redis.cr:69:13 in 'connect!'
  from usr/share/crystal/src/indexable.cr:269:9 in '???'
  from app/lib/placeos-driver/src/placeos-driver/proxy/system.cr:44:5 in 'get__api_engine_v2_systems___sys_id_functions__module_slug'
  from usr/share/crystal/src/primitives.cr:255:3 in 'call'
  from usr/share/crystal/src/http/server/handler.cr:28:7 in 'call'
  from usr/share/crystal/src/http/server/handler.cr:28:7 in 'call'
  from usr/share/crystal/src/http/server/request_processor.cr:50:11 in 'process'
  from usr/share/crystal/src/http/server.cr:498:5 in '->'
  from usr/share/crystal/src/primitives.cr:255:3 in 'run'
  from ???

Recreating the api pod immediately resolved the issue.

Can we change the api healthcheck such that it fails if there is any current connection issue with Redis? OR, is that already the current healthcheck behaviour in the current version? This way kubernetes will auto restart api so that it connect to the new redis ip.

Alternatively, how often is the ip resolved for the redis hostname? if it’s currently resolved only once upon the first initialization redis cluster bootstrap, then perhaps changing this to resolve upon every cluster bootstrap would ensure the api pod never gets into this state and would not even need to be restarted to reconnect to redis.

@w-le

Copy link


Contributor

Author

Unfortunately the same issue occurred again today.

Interestingly Core had no issues reconnecting to Redis — hey @caspiano are there any differences between the implementation of the Redis client in core vs rest-api that may point to an easy change in rest-api such that it is able to reconnect to Redis seamlessly in cases where Redis is briefly unavailable?

@caspiano

There isn’t much difference, all interactions with redis are via the same PlaceOS::Driver::Storage interface or the underlying client of PlaceOS::Driver::Storage.

Looking into this.

@w-le

Copy link


Contributor

Author

More info that may or may not be helpful:

I was trying to reproduce the issue by restarting redis in a similar k8s environment (same client, uat instead of prod) but when doing this rest-api was able to reconnect without issues after redis was back up.

In this controlled test, during the brief redis downtime, rest-api will output this repeatedly as expected, and then connect fine afterwards
https://gist.github.com/w-le/8f424d1371fc7d9505789497967a41c9

So I’m not sure why the behaviour in this controlled test is different to that described in the OP. In fact we did not even see the same specific error type «Address not available (Redis::CannotConnectError)» outputted, even though that error was outputted both times when the issue occurred (Redis exits unexpected with code 0) in production.

@w-le

Copy link


Contributor

Author

unfortunately this happened again today, causing a third outage in the same prod instance.
Not yet sure why it can get stuck in this state while other times redis can restart and rest-api will reconnect to it just fine.

Maybe it’s related to the number of open redis connections/files within the api container exceeding a maximum or something? I have previously seen a redis error stating «too many connections» in this instance.

I’ll try something like this to increase max open files to see if it helps:https://stackoverflow.com/a/63700455
Will uat deploy today and prod deploy tonight.

evel=DEBUG time=2021-03-30T02:13:16Z source=place_os.api.session ws_request_id=1 sys_id=sys-GhPzxGRnmFJ module_name=Bookings index=1 name=bookings message=Session (bind)
level=WARN time=2021-03-30T02:13:16Z source=place_os.api.session sys_id=sys-GhPzxGRnmFJ module_name=Bookings index=1 name=bookings message=websocket binding could not find system
Socket::ConnectError: Error connecting to 'redis-headless.redis:6379': Address not available (Redis::CannotConnectError)
from app/lib/redis/src/redis/socket_wrapper.cr:10:5 in 'connect'
from app/lib/redis-cluster/src/cluster/bootstrap.cr:47:7 in 'redis'
from app/lib/redis-cluster/src/redis.cr:69:13 in 'connect!'
from usr/share/crystal/src/indexable.cr:269:9 in '???'
from app/lib/placeos-driver/src/placeos-driver/subscriptions/indirect_subscription.cr:44:5 in 'perform_subscribe'
from app/lib/placeos-driver/src/placeos-driver/subscriptions.cr:72:7 in 'bind'
from app/src/placeos-rest-api/session.cr:664:24 in '__send__'
from app/src/placeos-rest-api/session.cr:563:7 in '->'
from usr/share/crystal/src/primitives.cr:255:3 in 'run'
from app/src/placeos-rest-api/controllers/systems.cr:11:3 in '->'
from usr/share/crystal/src/primitives.cr:255:3 in 'process'
from usr/share/crystal/src/http/server.cr:498:5 in '->'
from usr/share/crystal/src/primitives.cr:255:3 in 'run'
from ???

@caspiano

I’ll add the healthcheck now.

We have had a file descriptor issue due to the creation of redis clients before.
@stakach could you investigate the redis connection issue?

@stakach

Comments

@w-le

I just had an instance of rest-api v1.17.11 get into this state:

  • api responses were OK for almost all requests made by backoffice (except ones that involve redis)
  • healthcheck was passing
  • However there must have been a redis connection issue — I believe the redis pod restarted on a different IP a few hours before this rest-api issue was reported (about 2021-03-15T23:00:00Z).
    redis pod previous status info is here:
terminated
Reason: Completed - exit code: 0
Started at: 2021-03-15T01:32:47Z
Finished at: 2021-03-15T10:02:06Z
  • api returns this error when attempting to list the Commands of any Module:
ERROR: Socket::ConnectError: Error connecting to 'redis-headless.redis:6379': Address not available (Redis::CannotConnectError)
  from app/lib/redis/src/redis/socket_wrapper.cr:10:5 in 'connect'
  from app/lib/redis-cluster/src/cluster/bootstrap.cr:47:7 in 'redis'
  from app/lib/redis-cluster/src/redis.cr:69:13 in 'connect!'
  from usr/share/crystal/src/indexable.cr:269:9 in '???'
  from app/lib/placeos-driver/src/placeos-driver/proxy/system.cr:44:5 in 'get__api_engine_v2_systems___sys_id_functions__module_slug'
  from usr/share/crystal/src/primitives.cr:255:3 in 'call'
  from usr/share/crystal/src/http/server/handler.cr:28:7 in 'call'
  from usr/share/crystal/src/http/server/handler.cr:28:7 in 'call'
  from usr/share/crystal/src/http/server/request_processor.cr:50:11 in 'process'
  from usr/share/crystal/src/http/server.cr:498:5 in '->'
  from usr/share/crystal/src/primitives.cr:255:3 in 'run'
  from ???

Recreating the api pod immediately resolved the issue.

Can we change the api healthcheck such that it fails if there is any current connection issue with Redis? OR, is that already the current healthcheck behaviour in the current version? This way kubernetes will auto restart api so that it connect to the new redis ip.

Alternatively, how often is the ip resolved for the redis hostname? if it’s currently resolved only once upon the first initialization redis cluster bootstrap, then perhaps changing this to resolve upon every cluster bootstrap would ensure the api pod never gets into this state and would not even need to be restarted to reconnect to redis.

@w-le

Copy link


Contributor

Author

Unfortunately the same issue occurred again today.

Interestingly Core had no issues reconnecting to Redis — hey @caspiano are there any differences between the implementation of the Redis client in core vs rest-api that may point to an easy change in rest-api such that it is able to reconnect to Redis seamlessly in cases where Redis is briefly unavailable?

@caspiano

There isn’t much difference, all interactions with redis are via the same PlaceOS::Driver::Storage interface or the underlying client of PlaceOS::Driver::Storage.

Looking into this.

@w-le

Copy link


Contributor

Author

More info that may or may not be helpful:

I was trying to reproduce the issue by restarting redis in a similar k8s environment (same client, uat instead of prod) but when doing this rest-api was able to reconnect without issues after redis was back up.

In this controlled test, during the brief redis downtime, rest-api will output this repeatedly as expected, and then connect fine afterwards
https://gist.github.com/w-le/8f424d1371fc7d9505789497967a41c9

So I’m not sure why the behaviour in this controlled test is different to that described in the OP. In fact we did not even see the same specific error type «Address not available (Redis::CannotConnectError)» outputted, even though that error was outputted both times when the issue occurred (Redis exits unexpected with code 0) in production.

@w-le

Copy link


Contributor

Author

unfortunately this happened again today, causing a third outage in the same prod instance.
Not yet sure why it can get stuck in this state while other times redis can restart and rest-api will reconnect to it just fine.

Maybe it’s related to the number of open redis connections/files within the api container exceeding a maximum or something? I have previously seen a redis error stating «too many connections» in this instance.

I’ll try something like this to increase max open files to see if it helps:https://stackoverflow.com/a/63700455
Will uat deploy today and prod deploy tonight.

evel=DEBUG time=2021-03-30T02:13:16Z source=place_os.api.session ws_request_id=1 sys_id=sys-GhPzxGRnmFJ module_name=Bookings index=1 name=bookings message=Session (bind)
level=WARN time=2021-03-30T02:13:16Z source=place_os.api.session sys_id=sys-GhPzxGRnmFJ module_name=Bookings index=1 name=bookings message=websocket binding could not find system
Socket::ConnectError: Error connecting to 'redis-headless.redis:6379': Address not available (Redis::CannotConnectError)
from app/lib/redis/src/redis/socket_wrapper.cr:10:5 in 'connect'
from app/lib/redis-cluster/src/cluster/bootstrap.cr:47:7 in 'redis'
from app/lib/redis-cluster/src/redis.cr:69:13 in 'connect!'
from usr/share/crystal/src/indexable.cr:269:9 in '???'
from app/lib/placeos-driver/src/placeos-driver/subscriptions/indirect_subscription.cr:44:5 in 'perform_subscribe'
from app/lib/placeos-driver/src/placeos-driver/subscriptions.cr:72:7 in 'bind'
from app/src/placeos-rest-api/session.cr:664:24 in '__send__'
from app/src/placeos-rest-api/session.cr:563:7 in '->'
from usr/share/crystal/src/primitives.cr:255:3 in 'run'
from app/src/placeos-rest-api/controllers/systems.cr:11:3 in '->'
from usr/share/crystal/src/primitives.cr:255:3 in 'process'
from usr/share/crystal/src/http/server.cr:498:5 in '->'
from usr/share/crystal/src/primitives.cr:255:3 in 'run'
from ???

@caspiano

I’ll add the healthcheck now.

We have had a file descriptor issue due to the creation of redis clients before.
@stakach could you investigate the redis connection issue?

@stakach

Nextcloud community

Loading

Do you want to request a feature or report a bug?
bug
Or maybe I’m being stupid.

What is the current behavior?
It connects without JWT, but this is obviously very insecure. After attempting to enable JWT in nextcloud by applying the configuration methods detailed here: ONLYOFFICE/onlyoffice-owncloud#45

Nextcloud will provide the error message «invalid token» upon every connection attempt. Like so:

«message»:»CommandRequest on check error: Error occurred in the document service: Invalid token»,»userAgent»:»Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36″,»version»:»13.0.1.1″}

Monitoring the loopback interface on the nginx proxy in front of the ONLYOFFICE docker container, I see this:

POST /coauthoring/CommandService.ashx HTTP/1.0
Connection: close
Host: 127.0.0.1:61209
Content-Length: 15
Content-type: application/json
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjoie1wiY1wiOlwidmVyc2lvblwifSJ9.TPCfco_w5xBfxKSm0LuEP82jHVre9fccVLiKAWqUs-U

{«c»:»version»}

This seems to indicate that the JWT request is being made and is being passed through by nginx.

Immediately following this, the response from the docker container is this:

HTTP/1.1 200 OK
Server: nginx
Date: Tue, 17 Apr 2018 23:03:25 GMT
Content-Type: application/json
Content-Length: 11
Connection: close
X-Powered-By: Express
ETag: W/»b-LRcxe7iSAJH5JBcNMVwY3YCaOwE»

{«error»:6}

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem.
New NC install + new ONLYOFFICE install on two different servers in two different places. On the document server, it has only the onlyoffice docker container connected behind NGINX local proxy. Nginx proxy is configured with SSL certs and forwarding to port 80 on the docker container. Docker is launched with port mapping to map the docker image port 80+443 to some random high ports. iptables is used to block all inbound connections except for port 443 and port 80. The only changes made to the docker container are to default.json as detailed above.

What is the expected behavior?
Works
Did this work in previous versions of DocumentServer?
Never used it before!
DocumentServer version:
5
Operating System:
Ubuntu 16

Возможно, вам также будет интересно:

  • Next rp ошибка cc23 как исправить
  • Next rp как исправить ошибку
  • Next rp вылетает с ошибкой
  • New world ошибка при запуске приложения 0xc0000005
  • New world ошибка unrecoverable error

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии