Skip to content

Commit

Permalink
Match logic and signature for computeExternalURL
Browse files Browse the repository at this point in the history
Signed-off-by: Sven Nebel <[email protected]>
  • Loading branch information
snebel29 committed Sep 8, 2019
1 parent 67a8809 commit 515249d
Show file tree
Hide file tree
Showing 32 changed files with 63 additions and 8,396 deletions.
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ require (
github.com/prometheus/client_golang v1.0.0
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90
github.com/prometheus/common v0.6.0
github.com/stretchr/testify v1.3.0
golang.org/x/crypto v0.0.0-20190617133340-57b3e21c3d56 // indirect
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980
golang.org/x/sync v0.0.0-20190423024810-112230192c58 // indirect
Expand Down
63 changes: 32 additions & 31 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,24 +224,21 @@ func run() int {
level.Info(logger).Log("msg", "Loaded config file")

// Infer or set Blackbox exporter externalURL
beURL, err := extURL(logger, os.Hostname, *listenAddress, *externalURL)
beURL, err := computeExternalURL(*externalURL, *listenAddress)
if err != nil {
level.Error(logger).Log("msg", "failed to determine external URL", "err", err)
return 1
}
level.Debug(logger).Log("externalURL", beURL.String())

// Make routePrefix default to externalURL path if empty string.
// Default -web.route-prefix to path of -web.external-url.
if *routePrefix == "" {
*routePrefix = beURL.Path
}
// RoutePrefix must always be at least '/'.
*routePrefix = "/" + strings.Trim(*routePrefix, "/")
level.Debug(logger).Log("routePrefix", *routePrefix)

if *routePrefix == "/" {
*routePrefix = ""
}

hup := make(chan os.Signal, 1)
reloadCh := make(chan chan error)
signal.Notify(hup, syscall.SIGHUP)
Expand All @@ -266,7 +263,7 @@ func run() int {
}
}()

http.HandleFunc(fmt.Sprintf("%s/-/reload", *routePrefix),
http.HandleFunc(*routePrefix+"-/reload",
func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
Expand All @@ -280,24 +277,24 @@ func run() int {
http.Error(w, fmt.Sprintf("failed to reload config: %s", err), http.StatusInternalServerError)
}
})
http.Handle(fmt.Sprintf("%s/metrics", *routePrefix), promhttp.Handler())
http.HandleFunc(fmt.Sprintf("%s/probe", *routePrefix), func(w http.ResponseWriter, r *http.Request) {
http.Handle(*routePrefix+"metrics", promhttp.Handler())
http.HandleFunc(*routePrefix+"probe", func(w http.ResponseWriter, r *http.Request) {
sc.Lock()
conf := sc.C
sc.Unlock()
probeHandler(w, r, conf, logger, rh)
})
http.HandleFunc(fmt.Sprintf("%s/", *routePrefix), func(w http.ResponseWriter, r *http.Request) {
http.HandleFunc(*routePrefix, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte("<html>\n"))
w.Write([]byte(" <head><title>Blackbox Exporter</title></head>\n"))
w.Write([]byte(" <body>\n"))
w.Write([]byte(" <h1>Blackbox Exporter</h1>\n"))

w.Write([]byte(fmt.Sprintf(" <p><a href=\"%s/probe?target=prometheus.io&module=http_2xx\">Probe prometheus.io for http_2xx</a></p>\n", *routePrefix)))
w.Write([]byte(fmt.Sprintf(" <p><a href=\"%s/probe?target=prometheus.io&module=http_2xx&debug=true\">Debug probe prometheus.io for http_2xx</a></p>\n", *routePrefix)))
w.Write([]byte(fmt.Sprintf(" <p><a href=\"%s/metrics\">Metrics</a></p>\n", *routePrefix)))
w.Write([]byte(fmt.Sprintf(" <p><a href=\"%s/config\">Configuration</a></p>\n", *routePrefix)))
w.Write([]byte(" <p><a href=\"" + *routePrefix + "probe?target=prometheus.io&module=http_2xx\">Probe prometheus.io for http_2xx</a></p>\n"))
w.Write([]byte(" <p><a href=\"" + *routePrefix + "probe?target=prometheus.io&module=http_2xx&debug=true\">Debug probe prometheus.io for http_2xx</a></p>\n"))
w.Write([]byte(" <p><a href=\"" + *routePrefix + "metrics\">Metrics</a></p>\n"))
w.Write([]byte(" <p><a href=\"" + *routePrefix + "config\">Configuration</a></p>\n"))

w.Write([]byte(" <h2>Recent Probes</h2>\n"))
w.Write([]byte(" <table border='1'><tr><th>Module</th><th>Target</th><th>Result</th><th>Debug</th>\n"))
Expand All @@ -318,7 +315,7 @@ func run() int {
</html>`))
})

http.HandleFunc(fmt.Sprintf("%s/logs", *routePrefix), func(w http.ResponseWriter, r *http.Request) {
http.HandleFunc(*routePrefix+"logs", func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
if err != nil {
http.Error(w, "Invalid probe id", 500)
Expand All @@ -333,7 +330,7 @@ func run() int {
w.Write([]byte(result.debugOutput))
})

http.HandleFunc(fmt.Sprintf("%s/config", *routePrefix), func(w http.ResponseWriter, r *http.Request) {
http.HandleFunc(*routePrefix+"config", func(w http.ResponseWriter, r *http.Request) {
sc.RLock()
c, err := yaml.Marshal(sc.C)
sc.RUnlock()
Expand Down Expand Up @@ -394,36 +391,40 @@ func getTimeout(r *http.Request, module config.Module, offset float64) (timeoutS
return timeoutSeconds, nil
}

func extURL(logger log.Logger, hostnamef func() (string, error), listen, external string) (*url.URL, error) {
if external == "" {
hostname, err := hostnamef()
func startsOrEndsWithQuote(s string) bool {
return strings.HasPrefix(s, "\"") || strings.HasPrefix(s, "'") ||
strings.HasSuffix(s, "\"") || strings.HasSuffix(s, "'")
}

// computeExternalURL computes a sanitized external URL from a raw input. It infers unset
// URL parts from the OS and the given listen address.
func computeExternalURL(u, listenAddr string) (*url.URL, error) {
if u == "" {
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
_, port, err := net.SplitHostPort(listen)
_, port, err := net.SplitHostPort(listenAddr)
if err != nil {
return nil, err
}
if port == "" {
level.Warn(logger).Log("msg", "no port found for listen address", "address", listen)
}
u = fmt.Sprintf("http://%s:%s/", hostname, port)
}

external = fmt.Sprintf("http://%s:%s/", hostname, port)
if startsOrEndsWithQuote(u) {
return nil, errors.New("URL must not begin or end with quotes")
}

u, err := url.Parse(external)
eu, err := url.Parse(u)
if err != nil {
return nil, err
}
if u.Scheme != "http" && u.Scheme != "https" {
return nil, errors.Errorf("%q: invalid %q scheme, only 'http' and 'https' are supported", u.String(), u.Scheme)
}

ppref := strings.TrimRight(u.Path, "/")
ppref := strings.TrimRight(eu.Path, "/")
if ppref != "" && !strings.HasPrefix(ppref, "/") {
ppref = "/" + ppref
}
u.Path = ppref
eu.Path = ppref

return u, nil
return eu, nil
}
88 changes: 31 additions & 57 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,12 @@ package main

import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/stretchr/testify/require"

"github.com/go-kit/kit/log"
"github.com/prometheus/client_golang/prometheus"
pconfig "github.com/prometheus/common/config"
Expand Down Expand Up @@ -141,78 +138,55 @@ func TestTimeoutIsSetCorrectly(t *testing.T) {
}
}

func TestExternalURL(t *testing.T) {
hostname := "foo"
for _, tc := range []struct {
hostnameResolver func() (string, error)
external string
listen string

expURL string
err bool
func TestComputeExternalURL(t *testing.T) {
tests := []struct {
input string
valid bool
}{
{
listen: ":9093",
expURL: "http://" + hostname + ":9093",
},
{
listen: "localhost:9093",
expURL: "http://" + hostname + ":9093",
},
{
listen: "localhost:",
expURL: "http://" + hostname + ":",
},
{
external: "https://host.example.com",
expURL: "https://host.example.com",
},
{
external: "https://host.example.com/",
expURL: "https://host.example.com",
input: "",
valid: true,
},
{
external: "http://host.example.com/alertmanager",
expURL: "http://host.example.com/alertmanager",
input: "http://proxy.com/prometheus",
valid: true,
},
{
external: "http://host.example.com/alertmanager/",
expURL: "http://host.example.com/alertmanager",
input: "'https://url/prometheus'",
valid: false,
},
{
external: "http://host.example.com/////alertmanager//",
expURL: "http://host.example.com/////alertmanager",
input: "'relative/path/with/quotes'",
valid: false,
},
{
err: true,
input: "http://alertmanager.company.com",
valid: true,
},
{
hostnameResolver: func() (string, error) { return "", fmt.Errorf("some error") },
err: true,
input: "https://double--dash.de",
valid: true,
},
{
external: "://broken url string",
err: true,
input: "'http://starts/with/quote",
valid: false,
},
{
external: "host.example.com:8080",
err: true,
input: "ends/with/quote\"",
valid: false,
},
} {
tc := tc
if tc.hostnameResolver == nil {
tc.hostnameResolver = func() (string, error) {
return hostname, nil
}

for _, test := range tests {
_, err := computeExternalURL(test.input, "0.0.0.0:9090")
if test.valid {
if err != nil {
t.Errorf("unexpected error %v", err)
}
}
t.Run(fmt.Sprintf("external=%q,listen=%q", tc.external, tc.listen), func(t *testing.T) {
u, err := extURL(log.NewNopLogger(), tc.hostnameResolver, tc.listen, tc.external)
if tc.err {
require.Error(t, err)
return
} else {
if err == nil {
t.Errorf("expected error computing %s got none", test.input)
}
require.NoError(t, err)
require.Equal(t, tc.expURL, u.String())
})
}
}
}
15 changes: 0 additions & 15 deletions vendor/github.com/davecgh/go-spew/LICENSE

This file was deleted.

Loading

0 comments on commit 515249d

Please sign in to comment.