- RTNETLINK answers: Cannot assign requested address
- Nginx 99: Cannot assign requested address to upstream
- Введение
- Причины возникновения
- Диагностирование
- Решение
- Тюнинг ядра
- Изменение адреса назначения
- Настройка keepalive
- Тюнинг ядра. Ещё раз [2]
- Заключение
- Starting nginx: [emerg]: bind() to IP failed (99: Cannot assign requested address)
- 6 комментариев к записи “ Starting nginx: [emerg]: bind() to IP failed (99: Cannot assign requested address) ”
- net/http: cannot assign requested address #16012
- Comments
- pierrre commented Jun 8, 2016 •
- pierrre commented Jun 8, 2016
- ianlancetaylor commented Jun 8, 2016
- pierrre commented Jun 9, 2016 •
- ianlancetaylor commented Jun 9, 2016
- Cannot assign requested address (99 #1039
- Comments
- teaglebuilt commented May 10, 2020 •
- Problem
- Stacktrace
- To Reproduce
- Test Script Below
- Environment
- Suggestions
- References
- Previous attempts
- selenium-assistant bot commented May 10, 2020
- selenium-assistant bot commented May 10, 2020
- Shikaka commented May 14, 2020
- Akkarine commented May 24, 2020
- diemol commented May 24, 2020
- Akkarine commented May 24, 2020 •
- diemol commented May 24, 2020
- Akkarine commented May 27, 2020
- okainov commented Jun 14, 2020
- LukasRypl commented Jul 28, 2020 •
- danonorato commented Jul 29, 2020
- JoshuaGarrison27 commented Aug 11, 2021
- scamposd commented Aug 20, 2021
- github-actions bot commented Sep 20, 2021
RTNETLINK answers: Cannot assign requested address
Проблема такая: перестали работать один за другим два сетевых интерфейса. При попытке поднятия выдают следующее:
Подскажите, пожалуйста, куда копать. Нагуглились только проблемы с dhcp, но отключение dhcp на этих интерфейсах ничего не изменило.
попробуй просто повесить ИП на инт — ifconfig eth0 1.2.3.4 up
Возможно, подрались из-за адресов. Покажи ip ad && ip ro
# ifconfig eth3 172.16.4.4 up
SIOCSIFFLAGS: Cannot assign requested address
SIOCSIFFLAGS: Cannot assign requested address
а вобще что говорит ifconfig eth0 ?
Да вроде порядок или я где-то туплю:
# ip ad && ip ro
1: lo: mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 brd 127.255.255.255 scope host lo
inet 127.0.0.2/8 brd 127.255.255.255 scope host secondary lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0:
mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 90:e6:ba:6a:31:ae brd ff:ff:ff:ff:ff:ff
inet 172.16.1.1/24 brd 172.16.1.255 scope global eth0
3: eth1:
mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 90:e6:ba:6a:31:af brd ff:ff:ff:ff:ff:ff
inet 172.16.2.1/24 brd 172.16.2.255 scope global eth1
4: eth2:
mtu 1500 qdisc noop state DOWN qlen 1000
link/ether 00:00:00:00:00:00 brd ff:ff:ff:ff:ff:ff
5: eth3:
mtu 1500 qdisc noop state DOWN qlen 1000
link/ether 00:00:00:00:00:00 brd ff:ff:ff:ff:ff:ff
inet 192.168.200.22/24 brd 192.168.200.255 scope global eth3
8: dsl0:
mtu 1492 qdisc pfifo_fast state UNKNOWN qlen 3
link/ppp
inet 10.248.73.21 peer 10.248.1.1/32 scope global dsl0
10.248.1.1 dev dsl0 proto kernel scope link src 10.248.73.21
172.16.2.0/24 dev eth1 proto kernel scope link src 172.16.2.1
172.16.1.0/24 dev eth0 proto kernel scope link src 172.16.1.1
169.254.0.0/16 dev eth0 scope link
127.0.0.0/8 dev lo scope link
default dev dsl0 scope link
сначала сделай UP, потом адрес назначь. Вдруг поможет.
Ну, после выполненной команды:
# ifconfig eth3
eth3 Link encap:Ethernet HWaddr 00:00:00:00:00:00
inet addr:172.16.4.4 Bcast:172.16.255.255 Mask:255.255.0.0
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)
Interrupt:17
Но по факту интерфейс не работает.
Так и было задумано? в /var/log/messages что-нибудь есть?
Источник
Nginx 99: Cannot assign requested address to upstream
Введение
В данной статье описаны причины возникновения и решения проблемы с Nginx, когда периодически возникает ошибка вида [crit] 12889#0: *32401195 connect() to 127.0.0.1:80 failed (99: Cannot assign requested address) while connecting to upstream.
В моем случае сложности добавляло следующее: используется Nginx Ingress Controller в kubernetes, был установлен сложный релиз с множеством нового функционала и маршрутизацией для микросервисов. Поэтому было не сразу понятно, в чем проблема и куда смотреть, и прежде чем я пришёл к решению проблемы, было перелопачено много access-логов и конфигов в k8s, т.к. основными симптомами являлись периодические 502 ошибки в одной из частей приложения, а основная часть работала без проблем.
Причины возникновения
Перед тем, как рассказать о решении проблемы, необходимо иметь минимальный багаж знаний о работе TCP. В частности, как происходит сеанс установки TCP-соединения (в данной статье описывается лишь частично в рамках исследуемой проблемы):
- На стороне клиента создается сокет
- По аналогии сокет создается и на сервере, к которому обращается клиент
- Оба сокета соединяются для создания пары сокетов, которая называется quadruplet
- quadruplet состоит из локального IP-адреса и порта, а также удаленного IP-адреса и порта клиента. В RFC quadruplet описывается так: и по сути представляет собой кортеж из значений IP и портов.
Чтобы сразу понимать, как это выглядит в Linux, можно запустить команду netstat или ss для просмотра сетевых соединений на порту, который прослушивает Nginx:
Из команды выше адрес 10.89.108.137 – клиент, а 1879 – порт, связанный с клиентом только на время соединения и поэтому называется эфемерным . Когда соединение будет разорвано, временный порт будет доступен для повторного использования уже в рамках другого соединения.
Клиентский порт назначается автоматически из определенного диапазона, который указан в ядре по пути:
По умолчанию размер диапазона составляет 60999-32768=28231 (в моем случае на RHEL 7), что не так уж и много для высоконагруженных систем с большим количеством клиентов.
Диагностирование
Итак, определившись с текущим объемом ip_local_port_range – 28231, необходимо диагностировать, сколько соединений используется. Для этого можно воспользоваться также netstat или ss:
В примере выше, общее кол-во соединений составляет 47773. Соединений в состоянии established не так и много, а вот на соединения timewait стоит обратить внимание, т.к. они являются активными потребителями диапазона в данном случае (к тому же их кол-во постоянно меняется). Можно сразу смотреть их кол-во без лишнего вывода:
netstat в моём случае отработал быстрее, а ss с ощутимой задержкой
И вот она проблема – почти 37 тысяч соединений, а в лимите разрешено всего 28231. У такой проблемы есть даже название “Ephemeral Port Exhaustion”, т.е. эфемерное истощение портов, если перевести дословно.
Решение
Тюнинг ядра
Первым делом можно сразу же увеличить лимит по умолчанию – это будет самым простым и верным решением. Для этого:
Главное помнить, что лимит не резиновый и не стоит ставить меньше 4096 (порты для системных нужд) и выше 65000 + на различных портах могут слушать различные демоны прикладного ПО. Я выставил 49000 для начала. Хотя допустимо минимальным значением диапазона выставить 1024, но нужно помнить, что могут быть проблемы с другими службами и фаерволом, если сделать бездумно.
Изменение адреса назначения
Помните, что каждое соединение состоит из 4 частей (называемых quadruplet) с исходным IP и исходным портом, целевым IP и целевым портом? Так вот если нет возможности изменить исходный порт или IP-адрес, можно изменить IP-адреса назначения и тем самым избежать ограничений по лимиту из ip_local_port_range.
Наглядно это будет выглядеть так: например, конечный endpoint слушает на всех портах сетевых интерфейсов, т.е. на 0.0.0.0. А значит к нему можно обратиться по разным адресам – локальному, внешнему, loopback или добавить алиасы на интерфейс. Для этого создается апстрим с именем backend:
И далее можно проксировать трафик в вышеописанный upstream:
Тем самым будет достигнута экономия локальных портов из диапазона ip_local_port_range, т.к. вместо одного адреса уже будет два или более – в зависимости от настроек.
Настройка keepalive
Есть ещё одно решение – это настройка keepalive между Nginx и серверами в upstream. Keepalive-соединение будет поддерживаться открытым, а потому его можно использовать повторно уже другими клиентами, не создавая новых и опять же не расходуя лимиты ip_local_port_range.
Для настройки нужно указать директиву keepalive и её значение в блоке upstream:
При использовании keepalive, необходимо также использовать следующие директивы:
proxy_http_version 1.1;
proxy_set_header Connection «»;
И учитывать, что для протокола WebSocket это может быть критично.
Тюнинг ядра. Ещё раз [2]
После того, как лимиты в ip_local_port_range увеличены, количество соединений всё равно может увеличиваться. Особенно это актуально для веб-сервера, к которому происходят множественные обращения. Как правило, основным потребителем являются соединения в состоянии TIME_WAIT, и занимают большую часть диапазона ip_local_port_range. В таком случае ошибка Cannot assign requested address может снова повториться.
Сгладить ситуацию поможет параметр ядра net.ipv4.tcp_tw_reuse=1. Как видно из названия, он позволяет использовать повторно соединения TW, не создавая новых. Проблем с применением этого параметра на работающем сервере быть не должно.
Есть также другой параметр tcp_tw_recycle, который позволяет сократить время нахождения соединения в TIME-WAIT, но известно, что при его использовании могут быть проблемы у клиентов за NAT. Не рекомендуется использовать данный параметр, а в новых версиях ядра он вообще удален.
Заключение
В итоге получилось, что для решения ошибки Nginx Cannot assign requested address while connecting to upstream можно использовать целый комплекс мер – увеличить лимиты в ядре, настроить keepalive и сконфигурировать upstream. Но также не стоит забывать, что нужно искать проблему не там, где кажется на первый взгляд, т.к. могут получаться такие совпадения, связанные с выкаткой нового функционала. Грешил на одно, а проблема оказалась в итоге совсем в другом месте. В идеале же нужно применять всё в зависимости от ситуации, а также не могу не упомянуть про мониторинг.
В моем случае после решения данной проблемы, я настроил в Zabbix простой мониторинг кол-ва TCP-соединений через netstat -nt для 80 и 443 на нужном мне порту, где запущен Nginx Ingress Controller, чтобы понимать динамику загрузки и оперативно принять меры.
Для более глубокого понимания проблемы рекомендую изучить ссылки в используемых источниках ниже, особенно из блога Nginx.
Источник
Starting nginx: [emerg]: bind() to IP failed (99: Cannot assign requested address)
Такая ошибка возникает при попытке назначить для прослушивания IP, который в данный момент недоступен (например, при наличии виртуального IP, назначаемого с помощью keepalived или vrrpd).
Для того, чтобы nginx не ругался на несуществующий IP, нужно разрешить бинд нелокальных адресов. Для этого в файле /etc/sysctl.conf прописываем:
После чего перезагружаем конфиг sysctl:
6 комментариев к записи “ Starting nginx: [emerg]: bind() to IP failed (99: Cannot assign requested address) ”
Спустя три года от этого коммента я говорю тебе спасибо:) в полвторого ночи, после внезапной остановки nginx!
Да не за что 🙂
Виртуальный айпишник перешел на другой сервер?)
сертификаты Lets Enscrypt отвалились 🙂 и за ними nginx
Спасибо большое, уфф, я уже весь инет перерыл
Первая ссылка в Google выдаёт тот же совет но с ipv6. Добавил в конфиг обе строки. Но у меня, естественно, ipv4. Так что первая статья не помогла.
Забавно так. Перезагружаешь сервак. Все такие: упали, отжались, поднялись. А nginx такой: «не-не-не, ты чет там нахимичил, возвращай, как было.» А я такой в ТП: «Вы чет там нахимичили, возвращайте как было.» А ТП такая: «без проблем, плати 15 евро.» А я такой, не-не-не. «Ок Google! Там что-то нахимичили, как быть?». И тут вы со своим советом)
Источник
net/http: cannot assign requested address #16012
Comments
pierrre commented Jun 8, 2016 •
|
Run this benchmark:
With: go test -bench=. -benchmem -benchtime=10s
- What did you expect to see?
- What did you see instead?
It takes a long time and crashes:
During the benchmark, the value displayed by watch «ss -a | wc -l» increases really quickly (around 30-40k).
The text was updated successfully, but these errors were encountered:
pierrre commented Jun 8, 2016
If I write the benchmark without concurrency:
It works (no crash).
And the value displayed by watch «ss -a | wc -l» is low and stable (around 700).
ianlancetaylor commented Jun 8, 2016
I suspect you are exceeding the number of local socket connections permitted by your OS.
pierrre commented Jun 9, 2016 •
I suspect you are exceeding the number of local socket connections permitted by your OS.
You are probably right, but I can’t explain why.
I’ve performed the test again, with differents GOMAXPROCS values, and I displayed the number of network connection:
Most connections are in the TIME-WAIT state.
Should I configure something on my system or fix my code?
ianlancetaylor commented Jun 9, 2016
The point of a parallel benchmark is to run as many iterations of the function, in parallel, as will complete in 1 second. The benchmark will keep ramping up the number of iterations until it finds the answer. On your system, it seems that the answer is: more than the system can handle.
I would suggest that you put a limit in your code on the number of simultaneous open connections.
I’m going to close this issue because at this point I don’t see anything to be fixed in Go.
Источник
Cannot assign requested address (99 #1039
Comments
teaglebuilt commented May 10, 2020 •
Problem
I am launching seleniumgrid with mobbrowserproxy in a docker bridged network. The remote driver proxy settings are configured correctly but i cannot connect to the proxy server from the chrome driver. I have looked at all the issues and i cannot find a solution.
Below is the error which shows the driver desired capabilities/options.
Stacktrace
I believe the key point of this stacktrace is right here
To Reproduce
To reproduce this error. If you simple launch the containers and login to chromenode and use the chromedriver cli, you should see the same error in the terminal. Again the target of this issue is connecting the proxy container via chromedriver proxy settings.
As you can see in the trace above. the desired capabilities and options are all there. What I am trying to find out is why the chrome driver is getting this error with the proxy settings above.
My test is failing when looking for the first element on the login page. I am not sure if you need the test scripts and the ability to execute the test scripts to try to reproduce this or if this is something that can be pointed out. I can add this repo to github if needed.
Test Script Below
Environment
This is on a MacOs Mojave.
Suggestions
I think the most important part of this script is the variables connecting to the hub and the mob browser proxy containers
This script just shows you how I am setting the preferences that you already see here in the stacktrace on the chrome node.
References
These are the issues i have already found online
One
Two — at the bottom of this issue it was resolved with adding, and as you can see above. I have already tried this.
Three this guy solved this problem by adding ipv6 to his docker config. But i am using a bridged network in docker compose so i dont see why this option would matter.
Previous attempts
I am not sure if this is an issue with chromedriver or docker. To go through a couple of things i have already tried.
- I tried logging in to the chrome container and using the chromedriver cli. I also get the same error
comment on issue 2
I did try to use the image that included chromedriver 74 as the next comment suggested
next comment on issue 2
The text was updated successfully, but these errors were encountered:
selenium-assistant bot commented May 10, 2020
👋 Hi there! Thank you for creating this issue.
I am the Selenium Assistant Bot 🤖 , I triage issues in this repository. If I can’t do it, I label it to help maintainers identify issues that need triaging.
I am an Open Source project 🙌 , post bugs or ideas here!
selenium-assistant bot commented May 10, 2020
❗️ It seems this issue is not using any of the supported templates
💡 Supported issue types are (they start with):
- 🐛 Bug Report (bugs found in a recent release)
- 🚀 Feature Proposal (a useful feature you would like to propose)
- 💥 Regression Report (a supported feature is not working anymore)
Issue templates help this project to stay in shape, please use them and fill them out completely. By doing that you are helping the project because the community and maintainers can provide prompt feedback, and potentially solve the issue.
If you are asking a question, a better way to address this is:
- 📫 Send questions and support requests to the Selenium user group
- 📮 Post them to StackOverflow
- 🗣 Join us in the IRC/Slack channel where the community can help you as well
If you think this is incorrect, please feel free to open a new issue.
Thank you for your contributions.
Shikaka commented May 14, 2020
Same problem in docker.
Akkarine commented May 24, 2020
Also having this issue with standalone configuration. Simplyfied info:
Part of docker-compose for selenium:
Using it in python tests:
diemol commented May 24, 2020
What is the issue? Are tests no passing due to this?
We have seen this message in the logs but this normally doesn’t affect tests.
Akkarine commented May 24, 2020 •
What is the issue? Are tests no passing due to this?
We have seen this message in the logs but this normally doesn’t affect tests.
Django tests are not passing. Thought, that this error could be the cause. Log from one of tests, that locally pass with latest chromedriver:
whitescreen at screenshots.
diemol commented May 24, 2020
It could be a waiting issue or something similar. If the screen was not actually assigned, the browser would not even start and the test would crash when the session is created.
Akkarine commented May 27, 2020
It could be a waiting issue or something similar. If the screen was not actually assigned, the browser would not even start and the test would crash when the session is created.
You were right, the test errors were not related to this message.
okainov commented Jun 14, 2020
Having the same issue with Hub-node configuration in Docker-compose. Is there a way to pass additional options to chromedriver when using selenium/node-chrome image. Folks around are suggesting to pass -whitelisted-ips , but I don’t see a way how can I do that from this image.
LukasRypl commented Jul 28, 2020 •
I had the same issue . I was desperately trying different things (version of selenium, standalone, debug, with hub, manually running driver, replacing capybara, . lot of nice exercises that helped me to understand what is inside 🙂 )
In my case, I had nearly full disk space allocated in docker for desktop. It did not display any errors that may indicate that this is the root cause. Even building and running some other docker images was OK .
This is the place where you can check:
Some first aid to remove the largest images from CLI:
danonorato commented Jul 29, 2020
I see the bind Error as well, but in my env its seems to be benign. the grid and nodes function as expected.
JoshuaGarrison27 commented Aug 11, 2021
Did anyone find a solution for this? I am having this issue as well.
scamposd commented Aug 20, 2021
I am having this issue as well.
selenium-hub | 19:43:48.878 INFO [RequestHandler.process] — Got a request to create a new session: Capabilities
selenium-hub | 19:43:48.883 INFO [TestSlot.getNewSession] — Trying to create a new session on test slot
chrome_1 | 19:43:48.900 INFO [ActiveSessionFactory.apply] — Capabilities are: <
chrome_1 | «browserName»: «chrome»,
chrome_1 | «goog:chromeOptions»: <
chrome_1 | «args»: [
chrome_1 | «—verbose»
chrome_1 | ],
chrome_1 | «extensions»: [
chrome_1 | ]
chrome_1 | >
chrome_1 | >
chrome_1 | 19:43:48.901 INFO [ActiveSessionFactory.lambda$apply$11] — Matched factory org.openqa.selenium.grid.session.remote.ServicedSession$Factory (provider: org.ope
nqa.selenium.chrome.ChromeDriverService)
chrome_1 | Starting ChromeDriver 92.0.4515.107 (87a818b10553a07434ea9e2b6dccf3cbe7895134-refs/branch-heads/4515@<#1634>) on port 13373
chrome_1 | Only local connections are allowed[.
chrome_1 | Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
chrome_1 | ChromeDriver was started successfully.
chrome_1 | 1629488628.917][SEVERE]: bind() failed: Cannot assign requested address (99)
chrome_1 | 19:43:49.433 INFO [ProtocolHandshake.createSession] — Detected dialect: W3C
chrome_1 | 19:43:49.434 INFO [RemoteSession$Factory.lambda$performHandshake$0] — Started new session 9c120334dae2bb5fc6b961497bf089cb (org.openqa.selenium.chrome.Chrome
DriverService)
chrome_1 | 19:44:04.013 INFO [ActiveSessions$1.onStop] — Removing session 9c120334dae2bb5fc6b961497bf089cb (org.openqa.selenium.chrome.ChromeDriverService)
github-actions bot commented Sep 20, 2021
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник