Skip to content

Add proxy protocol v2 client-side support #979

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ Flags:
--nginx.ssl-client-cert=""
Path to the PEM encoded client certificate file to use when connecting to the server. ($SSL_CLIENT_CERT)
--nginx.ssl-client-key="" Path to the PEM encoded client certificate key file to use when connecting to the server. ($SSL_CLIENT_KEY)
--[no-]nginx.proxy-protocol
Pass proxy protocol payload to nginx listeners. ($PROXY_PROTOCOL)
--nginx.timeout=5s A timeout for scraping metrics from NGINX or NGINX Plus. ($TIMEOUT)
--prometheus.const-label=PROMETHEUS.CONST-LABEL ...
Label that will be used in every metric. Format is label=value. It can be repeated multiple times. ($CONST_LABELS)
Expand Down
55 changes: 53 additions & 2 deletions exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import (

"github.com/prometheus/exporter-toolkit/web"
"github.com/prometheus/exporter-toolkit/web/kingpinflag"

proxyproto "github.com/pires/go-proxyproto"
)

// positiveDuration is a wrapper of time.Duration to ensure only positive values are accepted.
Expand Down Expand Up @@ -90,6 +92,7 @@ var (
sslCaCert = kingpin.Flag("nginx.ssl-ca-cert", "Path to the PEM encoded CA certificate file used to validate the servers SSL certificate.").Default("").Envar("SSL_CA_CERT").String()
sslClientCert = kingpin.Flag("nginx.ssl-client-cert", "Path to the PEM encoded client certificate file to use when connecting to the server.").Default("").Envar("SSL_CLIENT_CERT").String()
sslClientKey = kingpin.Flag("nginx.ssl-client-key", "Path to the PEM encoded client certificate key file to use when connecting to the server.").Default("").Envar("SSL_CLIENT_KEY").String()
useProxyProto = kingpin.Flag("nginx.proxy-protocol", "Pass proxy protocol payload to nginx listeners.").Default("false").Envar("PROXY_PROTOCOL").Bool()

// Custom command-line flags.
timeout = createPositiveDurationFlag(kingpin.Flag("nginx.timeout", "A timeout for scraping metrics from NGINX or NGINX Plus.").Default("5s").Envar("TIMEOUT").HintOptions("5s", "10s", "30s", "1m", "5m"))
Expand Down Expand Up @@ -223,17 +226,65 @@ func main() {
func registerCollector(logger *slog.Logger, transport *http.Transport,
addr string, labels map[string]string,
) {
var socketPath string

if strings.HasPrefix(addr, "unix:") {
socketPath, requestPath, err := parseUnixSocketAddress(addr)
var err error
var requestPath string
socketPath, requestPath, err = parseUnixSocketAddress(addr)
if err != nil {
logger.Error("parsing unix domain socket scrape address failed", "uri", addr, "error", err.Error())
os.Exit(1)
}
addr = "http://unix" + requestPath
}

if !*useProxyProto && socketPath != "" {
transport.DialContext = func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", socketPath)
}
addr = "http://unix" + requestPath
}

if *useProxyProto {
transport.DialContext = func(_ context.Context, network, addr string) (net.Conn, error) {
if socketPath != "" {
network = "unix"
addr = socketPath
}

conn, err := (&net.Dialer{}).Dial(network, addr)
if err != nil {
return nil, fmt.Errorf("dialing %s %s: %w", network, addr, err)
}

localAddr := conn.LocalAddr()
remoteAddr := conn.RemoteAddr()
transportProtocol := proxyproto.TCPv4

switch addr := remoteAddr.(type) {
case *net.TCPAddr:
if addr.IP.To4() == nil {
Copy link
Preview

Copilot AI Aug 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The variable name 'addr' shadows the outer 'addr' parameter, which could lead to confusion. The switch should use a different variable name like 'tcpAddr' or 'remoteAddrTyped'.

Suggested change
if addr.IP.To4() == nil {
switch remoteAddrTyped := remoteAddr.(type) {
case *net.TCPAddr:
if remoteAddrTyped.IP.To4() == nil {

Copilot uses AI. Check for mistakes.

transportProtocol = proxyproto.TCPv6
}
case *net.UnixAddr:
transportProtocol = proxyproto.UnixStream
}

header := &proxyproto.Header{
Version: 2,
Command: proxyproto.PROXY,
TransportProtocol: transportProtocol,
SourceAddr: localAddr,
DestinationAddr: remoteAddr,
}

_, err = header.WriteTo(conn)
if err != nil {
return nil, fmt.Errorf("writing proxyproto header: %w", err)
}
Copy link
Preview

Copilot AI Aug 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The number of bytes written is being ignored. Consider logging or validating the bytes written to ensure the complete header was sent, or add a comment explaining why this return value is intentionally ignored.

Suggested change
}
n, err := header.WriteTo(conn)
if err != nil {
return nil, fmt.Errorf("writing proxyproto header: %w", err)
}
// Validate that the entire header was written
var buf bytes.Buffer
_, marshalErr := header.WriteTo(&buf)
if marshalErr != nil {
return nil, fmt.Errorf("marshalling proxyproto header for length check: %w", marshalErr)
}
expectedLen := buf.Len()
if n < expectedLen {
return nil, fmt.Errorf("proxyproto header: only %d of %d bytes written", n, expectedLen)
}

Copilot uses AI. Check for mistakes.


return conn, nil
}
}

userAgent := fmt.Sprintf("NGINX-Prometheus-Exporter/v%v", common_version.Version)
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.24.2
require (
github.com/alecthomas/kingpin/v2 v2.4.0
github.com/nginx/nginx-plus-go-client/v2 v2.4.0
github.com/pires/go-proxyproto v0.8.1
github.com/prometheus/client_golang v1.22.0
github.com/prometheus/common v0.65.0
github.com/prometheus/exporter-toolkit v0.14.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/nginx/nginx-plus-go-client/v2 v2.4.0 h1:4c7V57CLCZUOxQCUcS9G8a5MClzdmxByBm+f4zKMzAY=
github.com/nginx/nginx-plus-go-client/v2 v2.4.0/go.mod h1:P+dIP2oKYzFoyf/zlLWQa8Sf+fHb+CclOKzxAjxpvug=
github.com/pires/go-proxyproto v0.8.1 h1:9KEixbdJfhrbtjpz/ZwCdWDD2Xem0NZ38qMYaASJgp0=
github.com/pires/go-proxyproto v0.8.1/go.mod h1:ZKAAyp3cgy5Y5Mo4n9AlScrkCZwUy0g3Jf+slqQVcuU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q=
Expand Down