From 0924549efdecf5d32e2e91686fcef3ed3ab5952e Mon Sep 17 00:00:00 2001 From: Nuno Diegues Date: Wed, 28 Jul 2021 09:27:05 +0100 Subject: [PATCH] TUN-4811: Publish quick tunnels' hostname in /metrics under `userHostname` for backwards-compatibility --- cmd/cloudflared/tunnel/quick_tunnel.go | 8 +++++++- connection/observer.go | 7 +++++++ connection/observer_test.go | 19 +++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/cmd/cloudflared/tunnel/quick_tunnel.go b/cmd/cloudflared/tunnel/quick_tunnel.go index db76d212..9c0f1491 100644 --- a/cmd/cloudflared/tunnel/quick_tunnel.go +++ b/cmd/cloudflared/tunnel/quick_tunnel.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "net/http" + "strings" "time" "github.com/google/uuid" @@ -51,9 +52,14 @@ func RunQuickTunnel(sc *subcommandContext) error { TunnelName: data.Result.Name, } + url := data.Result.Hostname + if !strings.HasPrefix(url, "https://") { + url = "https://" + url + } + for _, line := range connection.AsciiBox([]string{ "Your Quick Tunnel has been created! Visit it at:", - data.Result.Hostname, + url, }, 2) { sc.log.Info().Msg(line) } diff --git a/connection/observer.go b/connection/observer.go index bb0887a5..57efaf70 100644 --- a/connection/observer.go +++ b/connection/observer.go @@ -111,6 +111,13 @@ func (o *Observer) sendConnectedEvent(connIndex uint8, location string) { func (o *Observer) sendURL(url string) { o.sendEvent(Event{EventType: SetURL, URL: url}) + + if !strings.HasPrefix(url, "https://") { + // We add https:// in the prefix for backwards compatibility as we used to do that with the old free tunnels + // and some tools (like `wrangler tail`) are regexp-ing for that specifically. + url = "https://" + url + } + o.metrics.userHostnamesCounts.WithLabelValues(url).Inc() } func (o *Observer) SendReconnect(connIndex uint8) { diff --git a/connection/observer_test.go b/connection/observer_test.go index cc7f1798..b4a271c0 100644 --- a/connection/observer_test.go +++ b/connection/observer_test.go @@ -6,9 +6,28 @@ import ( "testing" "time" + "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" "github.com/stretchr/testify/assert" ) +func TestSendUrl(t *testing.T) { + observer := NewObserver(&log, &log, false) + + observer.sendURL("my-url.com") + assert.Equal(t, 1.0, getCounterValue(t, observer.metrics.userHostnamesCounts, "https://my-url.com")) + + observer.sendURL("https://another-long-one.com") + assert.Equal(t, 1.0, getCounterValue(t, observer.metrics.userHostnamesCounts, "https://another-long-one.com")) +} + +func getCounterValue(t *testing.T, metric *prometheus.CounterVec, val string) float64 { + var m = &dto.Metric{} + err := metric.WithLabelValues(val).Write(m) + assert.NoError(t, err) + return m.Counter.GetValue() +} + func TestRegisterServerLocation(t *testing.T) { m := newTunnelMetrics() tunnels := 20