AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / server / 问题

Perguntas[haproxy](server)

Martin Hope
hack4mer
Asked: 2025-01-04 14:10:20 +0800 CST

O limite de conexão HAProxy por servidor backend é limitado a port_range

  • 5

Estou executando um balanceador de carga HAProxy para um servidor WebSocket.

Se eu colocar um servidor backend

backend pieproxy
  option http-keep-alive
  timeout tunnel 0ms

  balance leastconn

  server s1 IP:3001

O HAproy pode lidar apenas com 28.000 conexões estabelecidas.

Consigo contornar isso e fazer mais conexões adicionando outro servidor.

backend pieproxy
  option http-keep-alive
  timeout tunnel 0ms

  balance leastconn

  server s1 IP:3001
  server s2 IP:3001

Agora o HAproxy pode fazer o dobro desse número de conexões.

Quando reduzo o valor de

sysctl net.ipv4.ip_local_port_range

O HAproxy é capaz de fazer conexões máximas de até

number of backend server * ip_local_port_range

Por favor me ajude. Estou esquecendo de alguma coisa?

Como posso fazer com que um servidor backend atenda mais conexões que o valor de ip_local_port_range

haproxy
  • 2 respostas
  • 47 Views
Martin Hope
Gábor Major
Asked: 2024-02-29 01:13:39 +0800 CST

HAProxy sempre retorna 502 Bad Gateway, mas o backend responde

  • 5

Eu tenho um HAProxy 2.8.4 que é usado para fazer proxy de vários serviços HTTPS em vários caminhos de URL e vários back-ends diferentes, e também um cluster PostgreSQL sobre TCP. Esta é a saída completa do haproxy -vvv:

HAProxy version 2.8.4-a4ebf9d 2023/11/17 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2028.
Known bugs: http://www.haproxy.org/bugs/bugs-2.8.4.html
Running on: Linux 4.18.0-513.5.1.el8_9.x86_64 #1 SMP Fri Sep 29 05:21:10 EDT 2023 x86_64
Build options :
  TARGET  = linux-glibc
  CPU     = generic
  CC      = cc
  CFLAGS  = -O2 -g -Wall -Wextra -Wundef -Wdeclaration-after-statement -Wfatal-errors -Wtype-limits -Wshift-negative-value -Wshift-overflow=2 -Wduplicated-cond -Wnull-dereference -fwrapv -Wno-address-of-packed-member -Wno-unused-label -Wno-sign-compare -Wno-unused-parameter -Wno-clobbered -Wno-missing-field-initializers -Wno-cast-function-type -Wno-string-plus-int -Wno-atomic-alignment
  OPTIONS = USE_THREAD=1 USE_LINUX_TPROXY=1 USE_OPENSSL=1 USE_LUA=1 USE_ZLIB=1 USE_TFO=1 USE_NS=1 USE_SYSTEMD=1 USE_PCRE=1 USE_PCRE_JIT=1
  DEBUG   = -DDEBUG_STRICT -DDEBUG_MEMORY_POOLS

Feature list : -51DEGREES +ACCEPT4 +BACKTRACE -CLOSEFROM +CPU_AFFINITY +CRYPT_H -DEVICEATLAS +DL -ENGINE +EPOLL -EVPORTS +GETADDRINFO -KQUEUE -LIBATOMIC +LIBCRYPT +LINUX_CAP +LINUX_SPLICE +LINUX_TPROXY +LUA +MATH -MEMORY_PROFILING +NETFILTER +NS -OBSOLETE_LINKER +OPENSSL -OPENSSL_WOLFSSL -OT +PCRE -PCRE2 -PCRE2_JIT +PCRE_JIT +POLL +PRCTL -PROCCTL -PROMEX -PTHREAD_EMULATION -QUIC -QUIC_OPENSSL_COMPAT +RT +SHM_OPEN -SLZ +SSL -STATIC_PCRE -STATIC_PCRE2 +SYSTEMD +TFO +THREAD +THREAD_DUMP +TPROXY -WURFL +ZLIB

Default settings :
  bufsize = 16384, maxrewrite = 1024, maxpollevents = 200

Built with multi-threading support (MAX_TGROUPS=16, MAX_THREADS=256, default=2).
Built with OpenSSL version : OpenSSL 1.1.1k  FIPS 25 Mar 2021
Running on OpenSSL version : OpenSSL 1.1.1k  FIPS 25 Mar 2021
OpenSSL library supports TLS extensions : yes
OpenSSL library supports SNI : yes
OpenSSL library supports : TLSv1.0 TLSv1.1 TLSv1.2 TLSv1.3
Built with Lua version : Lua 5.4.4
Built with network namespace support.
Built with zlib version : 1.2.11
Running on zlib version : 1.2.11
Compression algorithms supported : identity("identity"), deflate("deflate"), raw-deflate("deflate"), gzip("gzip")
Built with transparent proxy support using: IP_TRANSPARENT IPV6_TRANSPARENT IP_FREEBIND
Built with PCRE version : 8.42 2018-03-20
Running on PCRE version : 8.42 2018-03-20
PCRE library supports JIT : yes
Encrypted password support via crypt(3): yes
Built with gcc compiler version 8.5.0 20210514 (Red Hat 8.5.0-20)

Available polling systems :
      epoll : pref=300,  test result OK
       poll : pref=200,  test result OK
     select : pref=150,  test result OK
Total: 3 (3 usable), will use epoll.

Available multiplexer protocols :
(protocols marked as <default> cannot be specified using 'proto' keyword)
         h2 : mode=HTTP  side=FE|BE  mux=H2    flags=HTX|HOL_RISK|NO_UPG
       fcgi : mode=HTTP  side=BE     mux=FCGI  flags=HTX|HOL_RISK|NO_UPG
  <default> : mode=HTTP  side=FE|BE  mux=H1    flags=HTX
         h1 : mode=HTTP  side=FE|BE  mux=H1    flags=HTX|NO_UPG
  <default> : mode=TCP   side=FE|BE  mux=PASS  flags=
       none : mode=TCP   side=FE|BE  mux=PASS  flags=NO_UPG

Available services : none

Available filters :
        [BWLIM] bwlim-in
        [BWLIM] bwlim-out
        [CACHE] cache
        [COMP] compression
        [FCGI] fcgi-app
        [SPOE] spoe
        [TRACE] trace

Esta é a minha configuração, com o material não relacionado do Postgre e outros caminhos de URL HTTPS omitidos:

lobal
    log 127.0.0.1 local0
    log 127.0.0.1 local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/haproxy.sock mode 600 level admin
    pidfile /var/run/haproxy.pid
    stats timeout 30s
    user haproxy
    group haproxy
    daemon

defaults
    log     global
    mode    http
    option  dontlognull
    retries 2
    timeout connect 4s
    timeout client  30m
    timeout server  30m
    timeout check   5s

# Temporary detailed logging
   log-format "Client IP:port = [%ci:%cp], Start Time = [%tr], Frontend Name = [%ft], Backend Name = [%b], Backend Server = [%s], Time to receive full request = [%TR ms], Response time = [%Tr ms], Status Code = [%ST], Bytes Read = [%B], Request = [%{+Q}r], Request Body = [%[capture.req.hdr(0)]]"

    errorfile 400 /etc/haproxy/errors/400.http
    errorfile 403 /etc/haproxy/errors/403.http
    errorfile 408 /etc/haproxy/errors/408.http
    errorfile 500 /etc/haproxy/errors/500.http
    errorfile 502 /etc/haproxy/errors/502.http
    errorfile 503 /etc/haproxy/errors/503.http
    errorfile 504 /etc/haproxy/errors/504.http

frontend main
    timeout client 86400000
    bind :443 ssl crt /etc/haproxy/haproxy.crt

    option http-buffer-request
    declare capture request len 40000
    http-request capture req.body id 0

    capture request header origin len 128

    # Many other URL mappings and other use_backend directives omitted here

    acl url_apigee path_beg -i /apigee-connector
    use_backend voda-apigee-conn-be if url_apigee

    default_backend deny_be

# Many other backend definitions omitted here

backend voda-apigee-conn-be
    balance roundrobin

    option httpchk
    http-check send meth GET uri /actuator/health

    server api1 x.x.x.x:8002 check inter 10s fall 3 rise 2 ssl verify none
    server api2 y.y.y.y:8002 check inter 10s fall 3 rise 2 ssl verify none

backend deny_be
    http-request deny

Quando chamo o back-end diretamente com cURL, recebo uma resposta HTTP 200, e ele também faz internamente o que é esperado:

curl -vvv -k -w "@curl-format.txt" -X POST -H "X-API-Key: my-api-key-1" -H "Content-Type: application/json" -d @apigee-conn-email3.json https://x.x.x.x:8002/apigee-connector/outbound-communication
Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying x.x.x.x...
* TCP_NODELAY set
* Connected to x.x.x.x (x.x.x.x) port 8002 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, [no content] (0):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, [no content] (0):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: <omitted>
*  start date: Dec  8 07:51:33 2023 GMT
*  expire date: Dec  7 07:51:32 2025 GMT
*  issuer: <omitted>
*  SSL certificate verify result: self signed certificate in certificate chain (19), continuing anyway.
* TLSv1.3 (OUT), TLS app data, [no content] (0):
> POST /apigee-connector/outbound-communication HTTP/1.1
> Host: x.x.x.x:8002
> User-Agent: curl/7.61.1
> Accept: */*
> X-API-Key: my-api-key-1
> Content-Type: application/json
> Content-Length: 344
>
* upload completely sent off: 344 out of 344 bytes
* TLSv1.3 (IN), TLS handshake, [no content] (0):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS app data, [no content] (0):
< HTTP/1.1 200
< Server: nginx
< Date: Wed, 28 Feb 2024 16:38:26 GMT
< Transfer-Encoding: chunked
< Connection: keep-alive
< Expires: 0
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Set-Cookie: JSESSIONID=YWLvqrZAAMHBgbOLK9Q-nz2vrxhs9mKw_Yt92lQ5.cgwcsmfuatapp1; path=/; secure; HttpOnly
< X-XSS-Protection: 1; mode=block
< Pragma: no-cache
< X-Frame-Options: DENY
< X-Content-Type-Options: nosniff
< Strict-Transport-Security: max-age=31536000 ; includeSubDomains
< RequestId: 59d32aad-4294-4811-a385-a4e65d68065f
< Quota-Reset: 1709139600925
< Quota-Allowed: 10000
< Quota-Available: 9998
< Content-Type: application/json
< Transfer-Encoding: chunked
<
* TLSv1.3 (IN), TLS app data, [no content] (0):
* Connection #0 to host x.x.x.x left intact
{"id":"94440760","attachment":{"id":{"value":"DOC-20240228-173826-WNHPC"}}}

     time_namelookup:  0.000076s
        time_connect:  0.000414s
     time_appconnect:  0.026246s
    time_pretransfer:  0.026375s
       time_redirect:  0.000000s
  time_starttransfer:  2.132503s
                     ----------
          time_total:  2.133572s

Quando chamo o mesmo através do HAProxy:

curl -vvv -k -w "@curl-format.txt" -X POST -H "X-API-Key: my-api-key-1" -H "Content-Type: application/json" -d @apigee-conn-email3.json https://z.z.z.z/apigee-connector/outbound-communication
Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying z.z.z.z...
* TCP_NODELAY set
* Connected to z.z.z.z (z.z.z.z) port 443 (#0)
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, [no content] (0):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, [no content] (0):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, [no content] (0):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, [no content] (0):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, [no content] (0):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN, server accepted to use h2
* Server certificate:
*  subject: <omitted>
*  start date: Jan 31 20:50:09 2024 GMT
*  expire date: Jan 30 20:50:08 2026 GMT
*  issuer: <omitted>
*  SSL certificate verify result: self signed certificate in certificate chain (19), continuing anyway.
* TLSv1.3 (OUT), TLS app data, [no content] (0):
> POST /apigee-connector/outbound-communication HTTP/1.1
> Host: z.z.z.z
> User-Agent: curl/7.61.1
> Accept: */*
> X-API-Key: my-api-key-1
> Content-Type: application/json
> Content-Length: 344
>
* upload completely sent off: 344 out of 344 bytes
* TLSv1.3 (IN), TLS handshake, [no content] (0):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS handshake, [no content] (0):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS app data, [no content] (0):
* HTTP 1.0, assume close after body
< HTTP/1.0 502 Bad Gateway
< cache-control: no-cache
< content-type: text/html
<
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>

* TLSv1.3 (IN), TLS alert, [no content] (0):
* TLSv1.3 (IN), TLS alert, close notify (256):
* Closing connection 0
* TLSv1.3 (OUT), TLS alert, [no content] (0):
* TLSv1.3 (OUT), TLS alert, close notify (256):

     time_namelookup:  0.000073s
        time_connect:  0.001454s
     time_appconnect:  0.023841s
    time_pretransfer:  0.023926s
       time_redirect:  0.000000s
  time_starttransfer:  2.589714s
                     ----------
          time_total:  2.589899s

Registro HAProxy:

Feb 28 18:01:38 localhost haproxy[3223599]: Client IP:port = [a.a.a.a:34660], Start Time = [28/Feb/2024:18:01:36.068], Frontend Name = [main~], Backend Name = [voda-apigee-conn-be], Backend Server = [api2], Time to receive full request = [0 ms], Response time = [-1 ms], Status Code = [502], Bytes Read = [208], Request = ["POST https://z.z.z.z/apigee-connector/outbound-communication HTTP/2.0"], Request Body = [<JSON body omitted>]

Sempre recebo 502 Bad Gateway, no entanto, o back-end ainda executa totalmente a solicitação conforme o esperado e diz que gerou uma resposta... pelo menos vejo exatamente as mesmas mensagens de log no nível do aplicativo em ambos os casos.

Percebi que o HAProxy muda para HTTP/2, tentei forçar o HTTP 1.1 na configuração do HAProxy com a diretiva alpn e também na linha de comando cURL com o sinalizador --http1.1, então era HTTP 1.1, mas ainda 502 Bad Gateway .

Oque pode estar errado aqui?

----- ATUALIZAR -----

Após o comentário de AlexD, modifiquei meu log, basicamente adicionei todos os parâmetros% Tx que pude encontrar, apenas adicionei nomes legíveis por humanos porque nunca aprenderei o que é Tr e TR e Th etc:

log-format "Client IP:port = [%ci:%cp], Start Time = [%tr], Frontend Name = [%ft], Backend Name = [%b], Backend Server = [%s], Active time of the request = [%Ta ms], Time to establish TCP connection to the server = [%Tc ms], SSL handshake time = [%Th ms], Idle time before the HTTP request = [%Ti ms], Time to get the client's request = [%Tq ms], Time to receive full request = [%TR ms], Response time = [%Tr ms], Total session duration time = [%Tt ms], Status Code = [%ST], Bytes Read = [%B], Termination state = [%ts], Request = [%{+Q}r], Request Body = [%[capture.req.hdr(0)]]"

Novo log depois disso:

Feb 29 08:46:33 localhost haproxy[3388761]: Client IP:port = [10.215.30.29:37666], Start Time = [29/Feb/2024:08:46:31.067], Frontend Name = [main~], Backend Name = [voda-apigee-conn-be], Backend Server = [api1], Active time of the request = [2092 ms], Time to establish TCP connection to the server = [8 ms], SSL handshake time = [20 ms], Idle time before the HTTP request = [0 ms], Time to get the client's request = [20 ms], Time to receive full request = [0 ms], Response time = [-1 ms], Total session duration time = [2112 ms], Status Code = [502], Bytes Read = [208], Termination state = [PH], Request = ["POST /apigee-connector/outbound-communication HTTP/1.1"], Request Body = [<omitted>]

Esta parece ser uma informação útil. O estado de encerramento é "PH", o que parece significar que a resposta foi bloqueada durante o processamento do cabeçalho. O que é estranho, não acho que nosso aplicativo de back-end retorne nenhum cabeçalho inválido. Você pode ver a resposta direta da solicitação cURL acima. Tentei desativar o modo estrito de resposta http em meu front-end, mas isso não mudou o comportamento. Também não encontrei muitas informações adicionais sobre esse estado de terminação "PH".

----- ATUALIZAÇÃO 2 -----

Consegui ativar o soquete de administrador chamando systemctl reload haproxy, não sei por que isso era necessário. Mas depois de consultar "mostrar erros", é isso que mostra:

[admin@ccaas1t-postgres-t1 ~]$ echo "show errors" | sudo socat stdio /run/haproxy/haproxy.sock
Total events captured on [29/Feb/2024:11:24:00.722] : 1

[29/Feb/2024:11:23:53.236] backend voda-apigee-conn-be (#13): invalid response
  frontend main (#5), server api1 (#1), event #0, src x.x.x.x:60930
  buffer starts at 0 (including 0 out), 15627 free,
  len 757, wraps at 16336, error at position 665
  H1 connection flags 0x80000000, H1 stream flags 0x00004810
  H1 msg state MSG_HDR_L2_LWS(24), H1 msg flags 0x00011654
  H1 chunk len 0 bytes, H1 body len 0 bytes :

  00000  HTTP/1.1 200 \r\n
  00015  Server: nginx\r\n
  00030  Date: Thu, 29 Feb 2024 10:23:53 GMT\r\n
  00067  Transfer-Encoding: chunked\r\n
  00095  Connection: keep-alive\r\n
  00119  Expires: 0\r\n
  00131  Cache-Control: no-cache, no-store, max-age=0, must-revalidate\r\n
  00194  Set-Cookie: JSESSIONID=nGfILjPozmcVahj831vf21a6BXIxgqElGlE8zxqA.cgwcsm
  00264+ fuatapp1; path=/; secure; HttpOnly\r\n
  00300  X-XSS-Protection: 1; mode=block\r\n
  00333  Pragma: no-cache\r\n
  00351  X-Frame-Options: DENY\r\n
  00374  X-Content-Type-Options: nosniff\r\n
  00407  Strict-Transport-Security: max-age=31536000 ; includeSubDomains\r\n
  00472  VFHU-RequestId: 20681405-102a-4eed-8eee-00ed8f3c37c8\r\n
  00526  VFHU-Quota-Reset: 1709204400244\r\n
  00559  VFHU-Quota-Allowed: 10000\r\n
  00586  VFHU-Quota-Available: 9999\r\n
  00614  Content-Type: application/json\r\n
  00646  Transfer-Encoding: chunked\r\n
  00674  \r\n
  00676  4b\r\n
  00680  {"id":"94464170","attachment":{"id":{"value":"DOC-20240229-112353-OTXV
  00750+ J"}}}\r\n

"erro na posição 665". A posição 665 são dois pontos (:) no cabeçalho "Transfer-Encoding: chunked". Parece bom para mim, o tamanho do pedaço é enviado como 4b hexadecimal, que é 75 decimal, que é o tamanho do JSON. Além disso, não estamos construindo essa resposta HTTP manualmente, ela é feita por uma biblioteca Java, então tenho certeza de que tudo ficará bem.

haproxy
  • 1 respostas
  • 34 Views
Martin Hope
EsseTi
Asked: 2024-02-09 07:58:36 +0800 CST

Django uwsgi por trás do haproxy: http ou http-socket?

  • 5

Eu tenho um aplicativo Django dentro de um arquivo que usa uwsgi. Como temos vários Dockers rodando em máquinas diferentes, temos o haproxy como balanceador de carga.

Minha pergunta é: devo usar uwsgi com httpou http-socket?

A partir daqui https://uwsgi-docs.readthedocs.io/en/latest/HTTP.html

Parecehttp

A opção http-socket fará com que o uWSGI fale HTTP nativamente. Se o seu servidor web não suporta o protocolo uwsgi, mas é capaz de se comunicar com proxies HTTP upstream, ou se você estiver usando um serviço como Webfaction ou Heroku para hospedar seu aplicativo, você pode usar o soquete http. Se você planeja expor seu aplicativo ao mundo apenas com uWSGI, use a opção http, pois o roteador/proxy/balanceador de carga será seu escudo.

A última parte sugere o httpque fazer se houver um balanceador de carga

Mas aqui https://uwsgi-docs.readthedocs.io/en/latest/ThingsToKnow.html

As opções de soquete http e http são feras totalmente diferentes. O primeiro gera um processo adicional que encaminha solicitações para uma série de trabalhadores (pense nisso como uma forma de escudo, no mesmo nível do Apache ou nginx), enquanto o segundo define os trabalhadores para falarem nativamente o protocolo http. TL/DR: se você planeja expor o uWSGI diretamente ao público, use --http, se quiser fazer proxy atrás de um servidor web falando http com backends, use --http-socket.

Parece inferir que http-socketse não for exposto diretamente ao público

Então, qual é a maneira de fazer isso com o haproxy?

haproxy
  • 1 respostas
  • 106 Views
Martin Hope
Michel
Asked: 2023-10-05 23:22:18 +0800 CST

O plugin Munin haproxy não está obtendo dados, embora munin-run show data e outros plugins funcionem bem

  • 5

Eu tenho um servidor Munin (2.72) monitorando muitos servidores corretamente.

Eu tenho um servidor haproxy com munin-node (2.0.73) funcionando bem para todos os plugins, exceto haproxy_* (haproxy_sessions_frontend, haproxy_bytes_frontend, haproxy_rate_frontend, etc.) que me fornece valores NaN.

Quando testo o plugin localmente no servidor haproxy, obtenho valores relevantes:

# Skipping systemd properties simulation due to required systemd version (999)
# Processing plugin configuration from /etc/munin/plugin-conf.d/00-default
# Processing plugin configuration from /etc/munin/plugin-conf.d/haproxy
# Processing plugin configuration from /etc/munin/plugin-conf.d/munin-node
# Setting /rgid/ruid/ to /982/0/
# Setting /egid/euid/ to /982 982/0/
# Setting up environment
# Environment frontend = https_front haproxy-monitoring fe-letsencrypt
# Environment url = http://127.0.0.1:8080/haproxy_stats;csv;norefresh
# Environment backend = app-main haproxy-monitoring letsencrypt-backend
# About to run '/etc/munin/plugins/haproxy_sessions_frontend'
scurea490f35148af7011c03b86177948440.value 3
smaxea490f35148af7011c03b86177948440.value 25
scur4dc7a8e588e9bb787fe6e39c1c96957a.value 1
smax4dc7a8e588e9bb787fe6e39c1c96957a.value 2
scura92191189150289a82c2c4464351178c.value 0
smaxa92191189150289a82c2c4464351178c.value 5

Quando me conecto remotamente do servidor Munin, é isso que recebo:

bash-4.4$ /usr/share/munin/munin-update --debug --nofork --host servxxx.domain.tld --service haproxy_session_frontend
2023/10/05 17:12:57 [DEBUG] Creating new lock file /var/run/munin/munin-update.lock
2023/10/05 17:12:57 [DEBUG] Creating lock : /var/run/munin/munin-update.lock succeeded
2023/10/05 17:12:57 [INFO]: Starting munin-update
2023/10/05 17:12:58 [DEBUG] Creating new lock file /var/run/munin/munin-datafile.lock
2023/10/05 17:12:58 [DEBUG] Creating lock : /var/run/munin/munin-datafile.lock succeeded
2023/10/05 17:12:58 [DEBUG] Writing state to /var/lib/munin/datafile.storable
2023/10/05 17:12:58 [DEBUG] about to write '/var/lib/munin/datafile.storable'
2023/10/05 17:12:58 [INFO]: Munin-update finished (1.47 sec)

Mas meus arquivos rrd são preenchidos com NaN e no munin-update.log recebo este aviso toda vez que Munin tenta atualizar dados do nó:

2023/10/05 17:15:13 [WARNING] 6 lines had errors while 0 lines were correct (100.00%) in data from 'fetch haproxy_sessions_frontend' on haproxy.captcha/x.x.x.x:4949

Eu tentei quase tudo nesta página https://guide.munin-monitoring.org/en/latest/tutorial/troubleshooting.html mas não tenho ideia. O mesmo plugin está funcionando bem em outro servidor haproxy. A principal diferença é que o outro servidor está rodando Rocky Linux 8 e aquele com problema está rodando Rocky Linux 9

O que posso fazer para que este plugin funcione?

haproxy
  • 1 respostas
  • 19 Views
Martin Hope
Guiomar Raissa
Asked: 2023-07-11 20:12:16 +0800 CST

Adicionando cabeçalhos personalizados em respostas de erro do haproxy

  • 7

Eu tenho a seguinte configuração haproxy que adiciona o access-control-allow-origincabeçalho em 200 solicitações bem-sucedidas com a configuração abaixo. Meu problema é que, quando atinjo o tempo limite ou o próprio haproxy (não meu servidor upstream), gera um erro por algum outro motivo, esse cabeçalho não é adicionado. Como eu adiciono este cabeçalho em, por exemplo, respostas 504 também?

global
        log /dev/log    local0
        log /dev/log    local1 notice
        chroot /var/lib/haproxy
        stats socket /run/haproxy/admin.sock mode 660 level admin
        stats timeout 30s
        user haproxy
        group haproxy
        daemon

        ca-base /etc/ssl/certs
        crt-base /etc/ssl/private

        ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA>
        ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
        ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        timeout connect 5s
        timeout client  30s
        timeout server  30s
        errorfile 400 /etc/haproxy/errors/400.http
        errorfile 403 /etc/haproxy/errors/403.http
        errorfile 408 /etc/haproxy/errors/408.http
        errorfile 500 /etc/haproxy/errors/500.http
        errorfile 502 /etc/haproxy/errors/502.http
        errorfile 503 /etc/haproxy/errors/503.http
        errorfile 504 /etc/haproxy/errors/504.http

frontend www-https
    bind *:80
    bind *:443 ssl crt /etc/ssl/cert.io.pem

    http-response add-header access-control-allow-origin "myCoolWebsite.com"

    redirect scheme https code 301 if !{ ssl_fc }
    mode http

    default_backend myBackend


backend myBackend
  server myServer 123.456.789.101:2345



Editar: Resolvi esse problema principalmente adicionando um arquivo de erro personalizado para 504, como abaixo. O único problema é que não consegui descobrir como definir dinamicamente access-control-allow-originapenas o domínio que está solicitando no momento, em vez de *. Isso é um problema, pois alguns navegadores têm problemas/problemas ao receber respostas com *. Alguma ideia de como posso fazer isso?

// 504.http
HTTP/1.0 504 Gateway Time-out
Cache-Control: no-cache
Connection: close
Content-Type: text/html
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods:\ GET,\ HEAD,\ OPTIONS,\ POST,\ PUT
Access-Control-Allow-Credentials:\ true
Access-Control-Allow-Headers:\ Origin,\ Accept,\ X-Requested-With,\ Content-Type,\ Access-Control-Request-Method,\ Access-Control-Request-Headers,\ Authorization

{
  "html": {
    "body": {
      "h1": "504 Gateway Time-out",
      "#text": "The server didn't respond in time."
    }
  }
}
haproxy
  • 1 respostas
  • 102 Views
Martin Hope
LinuxN00b
Asked: 2023-03-06 04:03:18 +0800 CST

HA Proxy falha na validação SSL

  • 5

Estamos usando um certificado curinga Godaddy em HA (Wildcard.pem) e certificados CA personalizados nos back-ends. A CA interna tem a confiança do HA e de todos os servidores. Posso acessar todos os servidores de back-end individualmente sem problemas, mas quando habilitamos a validação SSL, a verificação de integridade falha com o erro 503 quase imediatamente.

configurações HA

frontend api.qa.domain.com_esil_HTTPS_443_VS_172.20.25.69
    mode http
    bind 172.20.25.69:80
    bind 172.20.25.69:443 ssl crt /etc/hapee-2.4/ssl/Wildcard.pem ciphers ECDHE-RSA-AES128-CBC-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-CBC-SHA:AES128-SHA:AES256-SHA:ECDHE-ECDSA-AES128-SHA:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS ssl-min-ver TLSv1.2
    http-after-response replace-header set-cookie "^(my.session=.*)" "\1; SameSite=Strict" 
    http-request set-var(txn.path) path
    http-request set-var(req.backend) str(api.qa.domain.com_loggingservices_http_33313_POOL) if { path -i -m beg /loggingservice/ }
    
    use_backend %[var(req.backend)]

    backend api.qa.domain.com_loggingservice_http_333_POOL
    mode http
    http-request return status 503 content-type "text/html; charset=utf-8" lf-file /etc/hapee-2.4/apps/app_offline.htm if { nbsrv() le 0 }

    balance roundrobin
    dynamic-cookie-key Av3ryS3curek3y
    option httpchk GET /loggingservice/v1/_healthcheck HTTP/1.1
    http-check send hdr host api.qa.domain.com
    http-check expect status 200
    server QA_SERVER1_Node 10.133.20.24:333 check ssl verify none

Preciso mesclar nossos certificados de back-end que criamos usando nossa CA com o arquivo pem GoDaddy? se sim, qual seria a ordem correta?

haproxy
  • 1 respostas
  • 31 Views
Martin Hope
Lamboo
Asked: 2023-02-10 02:02:36 +0800 CST

A página Haproxy Stats não funciona com o modo TCP

  • 5

Especialistas em Haproxy,

Não consigo fazer com que a página de estatísticas haproxy funcione com o modo TCP para os back-ends.

global
    log         127.0.0.1 local2
    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon
    stats socket /var/lib/haproxy/stats

defaults
    mode                    tcp
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000
    stats enable
    stats hide-version
    stats refresh 30s
    stats show-node
    stats auth admin:xxxxxxxxxxxxxxxxx
    stats uri /haproxy?stats

frontend main
    listen stats
    bind *:5000
    mode tcp
    default_backend             app

backend app
    balance     roundrobin
#backends
    server   server1  xxx.xxx.xxx.xxx:10222 check
    server   server2  xxx.xxx.xxx.xxx:34013 check
haproxy
  • 1 respostas
  • 56 Views
Martin Hope
uozzyy
Asked: 2023-01-27 20:06:09 +0800 CST

HAProxy e postgres

  • 5

Minha configuração do haproxy é a seguinte, no back-end existe o cluster pg_autoctl, outra VM (bunty4) hospeda o monitor e o haproxy está instalado nele.

global
    maxconn 100

defaults
    log global
    mode tcp
    retries 2
    timeout client 30m
    timeout connect 4s
    timeout server 30m
    timeout check 5s

listen stats
    mode tcp
    bind *:7000
    stats enable
    stats uri /

listen ReadWrite
    bind *:5000
    option httpchk
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
    server bunty1 bunty1:6001 maxconn 100 check port 23267
    server bunty2 bunty2:6002 maxconn 100 check port 23267
    server bunty3 bunty3:6003 maxconn 100 check port 23267

listen ReadOnly
    bind *:5001
    option httpchk
    http-check expect status 206
    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
    server bunty1 bunty1:6001 maxconn 100 check port 23267
    server bunty2 bunty2:6002 maxconn 100 check port 23267
    server bunty3 bunty3:6003 maxconn 100 check port 23267

Isso funciona bem:

postgres@bunty4:~$ psql -h bunty2 -p 6002
psql (14.6 (Ubuntu 14.6-1.pgdg22.04+1))
Type "help" for help.

postgres=# \q
postgres@bunty4:~$ psql -h bunty1 -p 6001
psql (14.6 (Ubuntu 14.6-1.pgdg22.04+1))
Type "help" for help.

Quando tento conectar a porta frontend 7000 (através do pgadmin ou cli) dá um erro:

postgres@bunty4:~$ psql -h localhost -p 7000
psql: error: connection to server at "localhost" (127.0.0.1), port 7000 failed: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

psql -h 192.168.5.129 -p 7000   ## this also fails with same error.

Não sei por que, haproxy.log não vomita nada.

haproxy
  • 1 respostas
  • 59 Views
Martin Hope
Pavel Klimov
Asked: 2022-11-25 23:12:41 +0800 CST

Por que a instrução frontend "tcp-request content accept" é necessária para o roteamento adequado baseado em HAProxy SNI?

  • 6

Recentemente, tentei configurar o roteamento baseado em SNI no HAProxy para mongodb+srvconexão do protocolo mongodb.

Eu fiz funcionar, mas não foi até eu colocar

tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }

na minha configuração de frontend que começou a funcionar corretamente

Sem eles (ou com apenas um deles), continuei recebendo redefinições de conexão esporádicas em cerca de 70% das minhas solicitações. Observe que em algum momento a conexão conseguiu se estabelecer.

De acordo com http://cbonte.github.io/haproxy-dconv/2.0/configuration.html#4-tcp-request%20content

As regras baseadas em conteúdo são avaliadas em sua ordem de declaração exata. Se nenhuma regra corresponder ou se não houver regra, a ação padrão é aceitar o conteúdo. Não há limite específico para o número de regras que podem ser inseridas.

Portanto, deveria estar funcionando por padrão.

Ou estou perdendo algum conceito TCP fundamental ou algum detalhe específico da conexão do Mongo. Mas notei que quase todos têm a mesma regra definida quando vão para o roteamento baseado em SNI, então deve fazer sentido para a maioria das pessoas.

Configuração HAProxy de trabalho:

    frontend fe_mongo-nonprod
      bind :27017
      tcp-request inspect-delay 5s
      tcp-request content accept if { req_ssl_hello_type 1 }

      acl mongoAtlas-01 req_ssl_sni -i host1.mongodb.net
      acl mongoAtlas-02 req_ssl_sni -i host2.mongodb.net
      acl mongoAtlas-03 req_ssl_sni -i host3.mongodb.net
      use_backend be_mongo-nonprod if mongoAtlas-01 || mongoAtlas-02 || mongoAtlas-03

    backend be_mongo-nonprod
      mode tcp

      acl mongoAtlas-01 req_ssl_sni -i host1.mongodb.net
      acl mongoAtlas-02 req_ssl_sni -i host2.mongodb.net
      acl mongoAtlas-03 req_ssl_sni -i host3.mongodb.net

      use-server server-01 if mongoAtlas-01
      use-server server-02 if mongoAtlas-02
      use-server server-03 if mongoAtlas-03

      server server-01 host1.mongodb.net:27017
      server server-02 host2.mongodb.net:27017
      server server-03 host3.mongodb.net:27017

Também vale a pena mencionar que o HAProxy é implantado no Kubernetes (cluster gerenciado pelo Google no GCP), possui um istio-sidecar e é exposto por meio do serviço Internal LoadBalancer k8s.

Como afirmado, a configuração acima funciona perfeitamente bem. O que me interessa é por que tcp-request content accepté absolutamente necessário e a conexão nem sempre é aceita por padrão aqui.

haproxy
  • 1 respostas
  • 45 Views
Martin Hope
Diego
Asked: 2022-08-19 14:19:31 +0800 CST

A solicitação do Haproxy obtém tempo limite ao fazer ACL

  • 1

Eu criei um aplicativo simples e estou executando-o em 4 contêineres diferentes.

Consegui fazer proxy de todas as portas para o bind 9991, mas quando crio acl para usar backends diferentes não funciona, apenas o backend padrão.

Configuração:

frontend tests
  bind *:9991

  timeout client 60s
  mode http

  acl is_servers_2 path_end /app2
  use_backend servers_2 if is_servers_2

  acl is_servers_3 path_end /app3
  use_backend servers_3 if is_servers_3

  default_backend servers_2

backend servers_2
  timeout connect 10s
  timeout server 60s
  mode http
  server server3001 127.0.0.1:3001
  server server3002 127.0.0.1:3002

backend servers_3
  timeout connect 10s
  timeout server 60s
  mode http
  server server3003 127.0.0.1:3003
  server server3004 127.0.0.1:3004

versão haproxy: 2.4.4

Ubuntu: 18.04

haproxy
  • 0 respostas
  • 31 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Você pode passar usuário/passar para autenticação básica HTTP em parâmetros de URL?

    • 5 respostas
  • Marko Smith

    Ping uma porta específica

    • 18 respostas
  • Marko Smith

    Verifique se a porta está aberta ou fechada em um servidor Linux?

    • 7 respostas
  • Marko Smith

    Como automatizar o login SSH com senha?

    • 10 respostas
  • Marko Smith

    Como posso dizer ao Git para Windows onde encontrar minha chave RSA privada?

    • 30 respostas
  • Marko Smith

    Qual é o nome de usuário/senha de superusuário padrão para postgres após uma nova instalação?

    • 5 respostas
  • Marko Smith

    Qual porta o SFTP usa?

    • 6 respostas
  • Marko Smith

    Linha de comando para listar usuários em um grupo do Windows Active Directory?

    • 9 respostas
  • Marko Smith

    O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL?

    • 3 respostas
  • Marko Smith

    Como determinar se uma variável bash está vazia?

    • 15 respostas
  • Martin Hope
    Davie Ping uma porta específica 2009-10-09 01:57:50 +0800 CST
  • Martin Hope
    kernel O scp pode copiar diretórios recursivamente? 2011-04-29 20:24:45 +0800 CST
  • Martin Hope
    Robert ssh retorna "Proprietário incorreto ou permissões em ~/.ssh/config" 2011-03-30 10:15:48 +0800 CST
  • Martin Hope
    Eonil Como automatizar o login SSH com senha? 2011-03-02 03:07:12 +0800 CST
  • Martin Hope
    gunwin Como lidar com um servidor comprometido? 2011-01-03 13:31:27 +0800 CST
  • Martin Hope
    Tom Feiner Como posso classificar a saída du -h por tamanho 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent Como determinar se uma variável bash está vazia? 2009-05-13 09:54:48 +0800 CST

Hot tag

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve