1// Copyright (c) The Thanos Authors.
2// Licensed under the Apache License 2.0.
3
4package e2ethanos
5
6import (
7	"net/http"
8	"net/http/httputil"
9	"net/url"
10	"os/exec"
11	"strings"
12	"testing"
13
14	"github.com/cortexproject/cortex/integration/e2e"
15
16	"github.com/thanos-io/thanos/pkg/testutil"
17)
18
19func CleanScenario(t testing.TB, s *e2e.Scenario) func() {
20	return func() {
21		// Make sure Clean can properly delete everything.
22		testutil.Ok(t, exec.Command("chmod", "-R", "777", s.SharedDir()).Run())
23		s.Close()
24	}
25}
26
27func singleJoiningSlash(a, b string) string {
28	aslash := strings.HasSuffix(a, "/")
29	bslash := strings.HasPrefix(b, "/")
30	switch {
31	case aslash && bslash:
32		return a + b[1:]
33	case !aslash && !bslash:
34		return a + "/" + b
35	}
36	return a + b
37}
38
39// NewSingleHostReverseProxy is almost same as httputil.NewSingleHostReverseProxy
40// but it performs a url path rewrite.
41func NewSingleHostReverseProxy(target *url.URL, externalPrefix string) *httputil.ReverseProxy {
42	targetQuery := target.RawQuery
43	director := func(req *http.Request) {
44		req.URL.Scheme = target.Scheme
45		req.URL.Host = target.Host
46		req.URL.Path = singleJoiningSlash(target.Path, strings.TrimPrefix(req.URL.Path, "/"+externalPrefix))
47
48		if targetQuery == "" || req.URL.RawQuery == "" {
49			req.URL.RawQuery = targetQuery + req.URL.RawQuery
50		} else {
51			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
52		}
53	}
54	return &httputil.ReverseProxy{Director: director}
55}
56