├── .dockerignore ├── SECURITY.md ├── metrics.go ├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── Dockerfile ├── go.mod ├── server.go ├── client.go ├── README.md ├── main.go ├── go.sum ├── client_test.go └── LICENSE /.dockerignore: -------------------------------------------------------------------------------- 1 | # More info: https://docs.docker.com/engine/reference/builder/#dockerignore-file 2 | # Ignore all files which are not go type 3 | !**/*.go 4 | !**/*.mod 5 | !**/*.sum 6 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | 4 | ## Reporting a Vulnerability 5 | 6 | If you find a security vulnerability or any security related issues, please DO NOT file a public issue. Do not create a Github issue. Instead, send your report privately to cloud@snapp.cab. Security reports are greatly appreciated and we will publicly thank you for it. 7 | -------------------------------------------------------------------------------- /metrics.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "github.com/prometheus/client_golang/prometheus" 4 | 5 | var scrapeDurations = prometheus.NewHistogramVec( 6 | prometheus.HistogramOpts{ 7 | Name: "thanosfederateproxy_scrape_duration", 8 | Help: "Duration of scrape requests with response code", 9 | Buckets: []float64{0.01, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 30, 50}, 10 | }, 11 | []string{"status_code", "match_query"}, 12 | ) 13 | 14 | func init() { 15 | prometheus.MustRegister(scrapeDurations) 16 | } 17 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" # See documentation for possible values 4 | directory: "/" # Location of package manifests 5 | schedule: 6 | interval: "monthly" 7 | - package-ecosystem: "gomod" # See documentation for possible values 8 | directory: "/" # Location of package manifests 9 | schedule: 10 | interval: "monthly" 11 | - package-ecosystem: "docker" 12 | directory: "/" 13 | schedule: 14 | interval: "monthly" 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Binaries for programs and plugins 3 | *.exe 4 | *.exe~ 5 | *.dll 6 | *.so 7 | *.dylib 8 | bin 9 | testbin/* 10 | thanos-federate-proxy 11 | 12 | # Test binary, build with `go test -c` 13 | *.test 14 | 15 | # Output of the go coverage tool, specifically when used with LiteIDE 16 | *.out 17 | 18 | # Kubernetes Generated files - skip generated files, except for vendored files 19 | 20 | !vendor/**/zz_generated.* 21 | 22 | # editor and IDE paraphernalia 23 | .idea 24 | *.swp 25 | *.swo 26 | *~ 27 | 28 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | #build stage 2 | FROM golang:1.23-bullseye AS builder 3 | WORKDIR /go/src/app 4 | 5 | COPY go.sum go.mod /go/src/app/ 6 | RUN go mod download 7 | 8 | COPY . /go/src/app 9 | RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-w -s" -o prom_query_federate 10 | 11 | #final stage 12 | FROM debian:bullseye-slim 13 | 14 | ENV TZ=UTC \ 15 | PATH="/app:${PATH}" 16 | 17 | RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get install -y --no-install-recommends \ 18 | ca-certificates && \ 19 | apt-get clean && \ 20 | rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* 21 | 22 | WORKDIR /app 23 | 24 | COPY --from=builder /go/src/app/prom_query_federate /app/prom_query_federate 25 | ENTRYPOINT ["/app/prom_query_federate"] 26 | LABEL Name=prom_query_federate Version=1.0.0 27 | 28 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/snapp-incubator/thanos-federate-proxy 2 | 3 | go 1.22 4 | 5 | require ( 6 | github.com/prometheus/client_golang v1.20.5 7 | github.com/prometheus/common v0.60.1 8 | k8s.io/klog/v2 v2.130.1 9 | ) 10 | 11 | require ( 12 | github.com/beorn7/perks v1.0.1 // indirect 13 | github.com/cespare/xxhash/v2 v2.3.0 // indirect 14 | github.com/go-logr/logr v1.4.2 // indirect 15 | github.com/json-iterator/go v1.1.12 // indirect 16 | github.com/klauspost/compress v1.17.9 // indirect 17 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 18 | github.com/modern-go/reflect2 v1.0.2 // indirect 19 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect 20 | github.com/prometheus/client_model v0.6.1 // indirect 21 | github.com/prometheus/procfs v0.15.1 // indirect 22 | golang.org/x/sys v0.25.0 // indirect 23 | google.golang.org/protobuf v1.34.2 // indirect 24 | ) 25 | -------------------------------------------------------------------------------- /server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "net/http" 6 | "os" 7 | "os/signal" 8 | "syscall" 9 | "time" 10 | 11 | "k8s.io/klog/v2" 12 | ) 13 | 14 | func startServer(listen string, mux *http.ServeMux, cancel context.CancelFunc) { 15 | srv := &http.Server{ 16 | Addr: listen, 17 | Handler: mux, 18 | } 19 | 20 | sigCh := make(chan os.Signal, 1) 21 | signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) 22 | 23 | go func() { 24 | klog.Infof("Listening on port %s ...\n", listen) 25 | if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { 26 | klog.Fatalf("listen:%+s\n", err) 27 | } 28 | }() 29 | 30 | <-sigCh 31 | cancel() 32 | 33 | timeoutCtx, cancelTimeout := context.WithTimeout(context.Background(), time.Second*5) 34 | defer cancelTimeout() 35 | 36 | if err := srv.Shutdown(timeoutCtx); err != nil { 37 | klog.Infof("HTTP server Shutdown: %v", err) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: ci 3 | on: 4 | push: 5 | branches: [ main ] 6 | tags: [ v* ] 7 | pull_request: 8 | branches: [ main ] 9 | 10 | jobs: 11 | lint: 12 | name: lint 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: actions/setup-go@v5 17 | with: 18 | go-version-file: "go.mod" 19 | - name: golangci-lint 20 | uses: golangci/golangci-lint-action@v6 21 | with: 22 | version: latest 23 | args: --timeout=30m 24 | 25 | test: 26 | name: test 27 | runs-on: ubuntu-latest 28 | steps: 29 | - uses: actions/checkout@v4 30 | - uses: actions/setup-go@v5 31 | with: 32 | go-version-file: "go.mod" 33 | - run: go test -v ./... -covermode=atomic -coverprofile=coverage.out 34 | - uses: codecov/codecov-action@v5.0.7 35 | with: 36 | files: coverage.out 37 | token: ${{ secrets.CODECOV_TOKEN }} 38 | slug: snapp-incubator/thanos-federate-proxy 39 | 40 | docker: 41 | name: docker 42 | runs-on: ubuntu-latest 43 | needs: 44 | - lint 45 | - test 46 | steps: 47 | - uses: actions/checkout@v4 48 | - uses: docker/setup-qemu-action@v3 49 | - uses: docker/setup-buildx-action@v3 50 | - uses: docker/login-action@v3 51 | with: 52 | registry: ghcr.io 53 | username: ${{ github.repository_owner }} 54 | password: ${{ secrets.GITHUB_TOKEN }} 55 | - uses: docker/metadata-action@v5 56 | id: meta 57 | with: 58 | images: ghcr.io/${{ github.repository }} 59 | tags: | 60 | type=ref,event=branch 61 | type=ref,event=pr 62 | type=semver,pattern={{version}} 63 | type=semver,pattern={{major}}.{{minor}} 64 | - uses: docker/build-push-action@v6 65 | with: 66 | file: "Dockerfile" 67 | context: . 68 | platforms: linux/amd64 69 | push: true 70 | tags: ${{ steps.meta.outputs.tags }} 71 | labels: ${{ steps.meta.outputs.labels }} 72 | -------------------------------------------------------------------------------- /client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "context" 6 | "fmt" 7 | "io" 8 | "io/fs" 9 | "net/http" 10 | "net/url" 11 | "strings" 12 | 13 | "github.com/prometheus/client_golang/api" 14 | ) 15 | 16 | // ClientConfigError returned when the token file is empty or invalid 17 | type ClientConfigError string 18 | 19 | // Error implements error 20 | func (err ClientConfigError) Error() string { 21 | return string(err) 22 | } 23 | 24 | const ( 25 | EmptyBearerFileError = ClientConfigError("First line of bearer token file is empty") 26 | InvalidBearerTokenError = ClientConfigError("Bearer token must be ASCII") 27 | NilOptionError = ClientConfigError("configOption cannot be nil") 28 | ) 29 | 30 | // Client wraps prometheus api.Client to add custom headers to every request 31 | type client struct { 32 | api.Client 33 | authz string // Authorization header 34 | asGet bool // True to reject POST requests 35 | } 36 | 37 | type paramKey int 38 | 39 | // addValues inserts the provided request params in context 40 | func addValues(ctx context.Context, params url.Values) context.Context { 41 | return context.WithValue(ctx, paramKey(0), params) 42 | } 43 | 44 | // getValues extracts from context the params provided by addParams 45 | func getValues(ctx context.Context) (url.Values, bool) { 46 | if ctxValue := ctx.Value(paramKey(0)); ctxValue != nil { 47 | if params, ok := ctxValue.(url.Values); ok { 48 | return params, true 49 | } 50 | } 51 | return nil, false 52 | } 53 | 54 | // Do implements api.Client 55 | func (c client) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { 56 | if c.asGet && req.Method == http.MethodPost { 57 | // If response to POST is http.StatusMethodNotAllowed, 58 | // Prometheus api library will failover to GET. 59 | return &http.Response{ 60 | Status: "Method Not Allowed", 61 | StatusCode: http.StatusMethodNotAllowed, 62 | Proto: req.Proto, 63 | ProtoMajor: req.ProtoMajor, 64 | ProtoMinor: req.ProtoMinor, 65 | Body: io.NopCloser(nil), 66 | ContentLength: 0, 67 | Request: req, 68 | Header: make(http.Header, 0), 69 | }, nil, nil 70 | } 71 | // If context includes URL parameters, append them to the query 72 | if params, ok := getValues(ctx); ok { 73 | reqParams := req.URL.Query() 74 | for name, values := range params { 75 | for _, value := range values { 76 | reqParams.Add(name, value) 77 | } 78 | } 79 | req.URL.RawQuery = reqParams.Encode() 80 | } 81 | if c.authz != "" { 82 | if req.Header == nil { 83 | req.Header = make(http.Header) 84 | } 85 | req.Header.Set("Authorization", c.authz) 86 | } 87 | return c.Client.Do(ctx, req) 88 | } 89 | 90 | // readBearerToken from given FS and fileName. 91 | // Takes sys.FS instead of path for easier testing. 92 | func readBearerToken(fsys fs.FS, fileName string) (string, error) { 93 | bearerFile, err := fsys.Open(fileName) 94 | if err != nil { 95 | return "", err 96 | } 97 | defer bearerFile.Close() 98 | scanner := bufio.NewScanner(bearerFile) 99 | if !scanner.Scan() { 100 | if err := scanner.Err(); err != nil { 101 | return "", err 102 | } 103 | return "", EmptyBearerFileError 104 | } 105 | return scanner.Text(), nil 106 | } 107 | 108 | // IsAscii checks if string consists only of ascii characters 109 | func isAscii(str string) bool { 110 | for _, b := range str { 111 | if b <= 0 || b > 127 { 112 | return false 113 | } 114 | } 115 | return true 116 | } 117 | 118 | // clientOption implements functional options pattern for client 119 | type clientOption func(c *client) error 120 | 121 | // newClient wraps an api.Client adding the given options 122 | func newClient(c api.Client, opts ...clientOption) (client, error) { 123 | result := client{Client: c} 124 | if len(opts) > 0 { 125 | for _, opt := range opts { 126 | // catch wrong calls to newClient(c, nil) 127 | if opt == nil { 128 | return client{}, NilOptionError 129 | } 130 | if err := opt(&result); err != nil { 131 | return client{}, err 132 | } 133 | } 134 | } 135 | return result, nil 136 | } 137 | 138 | // withToken adds Authz bearer token to all requests 139 | func withToken(bearer string) clientOption { 140 | return func(c *client) error { 141 | bearer = strings.TrimSpace(bearer) 142 | if bearer == "" || !isAscii(bearer) { 143 | return InvalidBearerTokenError 144 | } 145 | c.authz = fmt.Sprintf("Bearer %s", bearer) 146 | return nil 147 | } 148 | } 149 | 150 | // withGet only allows GET queries 151 | func withGet(c *client) error { 152 | c.asGet = true 153 | return nil 154 | } 155 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Thanos Federate Proxy 2 | 3 | A proxy to convert `/federate` queries to `/v1/api/query` and respond in open metrics format. 4 | 5 | The most common use case for this proxy is to be used as a side car with [Thanos](https://github.com/thanos-io/thanos), to provide `/federate` api for thanos (currently Thanos does not support it). So this way you can add Thanos as a federation source in another prometheus. Also Thanos does not support remote write (Note that being able to write metrics remotely from thanos to another prometheus is a different concept than thanos receiver component). 6 | 7 | ## Usage 8 | 9 | ### Docker 10 | 11 | ```bash 12 | sudo docker run -p 9099:9099 ghcr.io/snapp-incubator/thanos-federate-proxy:main -insecure-listen-address="0.0.0.0:9099" 13 | ``` 14 | 15 | ### Binary releases 16 | 17 | ```bash 18 | export VERSION=0.1.0 19 | wget https://github.com/snapp-incubator/thanos-federate-proxy/releases/download/v${VERSION}/thanos-federate-proxy-${VERSION}.linux-amd64.tar.gz 20 | tar xvzf thanos-federate-proxy-${VERSION}.linux-amd64.tar.gz thanos-federate-proxy-${VERSION}.linux-amd64/thanos-federate-proxy 21 | ``` 22 | 23 | ### From source 24 | 25 | ```sh 26 | git clone https://github.com/snapp-incubator/thanos-federate-proxy 27 | cd thanos-federate-proxy && go build 28 | ./thanos-federate-proxy 29 | ``` 30 | 31 | ## Configuration 32 | 33 | Flags: 34 | 35 | ```text 36 | -insecure-listen-address string 37 | The address which proxy listens on (default "127.0.0.1:9099") 38 | -tlsSkipVerify 39 | Skip TLS Verfication (default false) 40 | -upstream string 41 | The upstream thanos URL (default "http://127.0.0.1:9090") 42 | -bearer-file string 43 | Path to file containing Authorization bearer token, if needed. 44 | -force-get 45 | Force prometheus api.Client to use GET requests instead of POST (default false) 46 | ``` 47 | 48 | Sample k8s deployment (as a side car with thanos or prometheus): 49 | 50 | ```yml 51 | containers: 52 | ... 53 | - name: thanos-federate-proxy 54 | image: ghcr.io/snapp-incubator/thanos-federate-proxy:main 55 | args: 56 | - -insecure-listen-address=0.0.0.0:9099 57 | - -upstream=http://127.0.0.1:9090 58 | ports: 59 | - containerPort: 9099 60 | name: fedproxy 61 | protocol: TCP 62 | ``` 63 | 64 | Sample prometheus config for federation: 65 | 66 | ```yml 67 | scrape_configs: 68 | - job_name: 'thanos-federate' 69 | scrape_timeout: 1m 70 | metrics_path: '/federate' 71 | params: 72 | 'match[]': 73 | - 'up{namespace=~"perfix.*"}' 74 | static_configs: 75 | - targets: 76 | - 'thanos.svc.cluster:9099' 77 | ``` 78 | 79 | ## Limitations 80 | 81 | The following limitations will be addressed in future releases (see [Roadmap](#roadmap)): 82 | 83 | - You can not pass empty matcher to prometheus for scraping all the metrics (see [this prometheus issue](https://github.com/prometheus/prometheus/issues/2162)). A workaround is to use the following matcher: 84 | 85 | ```yml 86 | 'match[]': 87 | - '{__name__=~".+"}' 88 | ``` 89 | 90 | Note that `{__name__=~".*"}` won't also work and you should use `".+"` instead of `".*"`. 91 | 92 | ## Roadmap 93 | 94 | - [x] test federation 95 | - [x] tlsSkipVerify flag 96 | - [x] Dockerfile 97 | - [x] Github actions 98 | - [x] metrics 99 | - [x] support multiple matchers 100 | - [ ] support empty matchers 101 | - [ ] support store-API for better performance 102 | - [ ] return error message instead of only logging it (??) 103 | - [ ] remove space after comma in metrics (causing no issues) 104 | - [ ] make query timeouts configurable 105 | - [ ] add markdown lint to CI 106 | 107 | ## Metrics 108 | 109 | | Metric | Notes | 110 | | -------------------------------------------------- | ---------------------------------------------------------------- | 111 | | thanosfederateproxy_scrape_duration_seconds_count | Total number of scrape requests with response code | 112 | | thanosfederateproxy_scrape_duration_seconds_sum | Duration of scrape requests with response code | 113 | | thanosfederateproxy_scrape_duration_seconds_bucket | Count of scrape requests per bucket (for calculating percentile) | 114 | 115 | ## Changelog 116 | 117 | See [CHANGELOG.md](./CHANGELOG.md) 118 | 119 | ## Security 120 | 121 | ### Reporting security vulnerabilities 122 | 123 | If you find a security vulnerability or any security related issues, please DO NOT file a public issue, instead send your report privately to cloud@snapp.cab. Security reports are greatly appreciated and we will publicly thank you for it. 124 | 125 | ## License 126 | 127 | Apache-2.0 License, see [LICENSE](LICENSE). 128 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "flag" 7 | "fmt" 8 | "net" 9 | "net/http" 10 | "os" 11 | "path/filepath" 12 | "time" 13 | 14 | "github.com/prometheus/client_golang/api" 15 | v1 "github.com/prometheus/client_golang/api/prometheus/v1" 16 | "github.com/prometheus/client_golang/prometheus" 17 | "github.com/prometheus/client_golang/prometheus/promhttp" 18 | "github.com/prometheus/common/model" 19 | "k8s.io/klog/v2" 20 | ) 21 | 22 | var ( 23 | insecureListenAddress string 24 | upstream string 25 | tlsSkipVerify bool 26 | bearerFile string 27 | forceGet bool 28 | ) 29 | 30 | func parseFlag() { 31 | flag.StringVar(&insecureListenAddress, "insecure-listen-address", "127.0.0.1:9099", "The address which proxy listens on") 32 | flag.StringVar(&upstream, "upstream", "http://127.0.0.1:9090", "The upstream thanos URL") 33 | flag.BoolVar(&tlsSkipVerify, "tlsSkipVerify", false, "Skip TLS Verification") 34 | flag.StringVar(&bearerFile, "bearer-file", "", "File containing bearer token for API requests") 35 | flag.BoolVar(&forceGet, "force-get", false, "Force api.Client to use GET by rejecting POST requests") 36 | flag.Parse() 37 | } 38 | 39 | func main() { 40 | parseFlag() 41 | ctx, cancel := context.WithCancel(context.Background()) 42 | defer cancel() 43 | 44 | // DefaultRoundTripper is used if no RoundTripper is set in Config. 45 | var roundTripper http.RoundTripper = &http.Transport{ 46 | Proxy: http.ProxyFromEnvironment, 47 | DialContext: (&net.Dialer{ 48 | Timeout: 30 * time.Second, 49 | KeepAlive: 30 * time.Second, 50 | }).DialContext, 51 | TLSHandshakeTimeout: 10 * time.Second, 52 | TLSClientConfig: &tls.Config{ 53 | InsecureSkipVerify: tlsSkipVerify, 54 | }, 55 | } 56 | // Create a new client. 57 | c, err := api.NewClient(api.Config{ 58 | Address: upstream, 59 | RoundTripper: roundTripper, 60 | }) 61 | if err != nil { 62 | klog.Fatalf("error creating API client: %s", err) 63 | } 64 | // Collect client options 65 | options := []clientOption{} 66 | if bearerFile != "" { 67 | fullPath, err := filepath.Abs(bearerFile) 68 | if err != nil { 69 | klog.Fatalf("error locating bearer file: %s", err) 70 | } 71 | dirName, fileName := filepath.Split(fullPath) 72 | bearer, err := readBearerToken(os.DirFS(dirName), fileName) 73 | if err != nil { 74 | klog.Fatalf("error reading bearer file: %s", err) 75 | } 76 | options = append(options, withToken(bearer)) 77 | } 78 | if forceGet { 79 | klog.Infof("Forcing api,Client to use GET requests") 80 | options = append(options, withGet) 81 | } 82 | if c, err = newClient(c, options...); err != nil { 83 | klog.Fatalf("error building custom API client: %s", err) 84 | } 85 | apiClient := v1.NewAPI(c) 86 | 87 | // server mux 88 | mux := http.NewServeMux() 89 | mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { 90 | w.WriteHeader(http.StatusOK) 91 | }) 92 | mux.Handle("/metrics", promhttp.Handler()) 93 | mux.HandleFunc("/federate", func(w http.ResponseWriter, r *http.Request) { 94 | federate(ctx, w, r, apiClient) 95 | }) 96 | startServer(insecureListenAddress, mux, cancel) 97 | } 98 | 99 | func federate(_ context.Context, w http.ResponseWriter, r *http.Request, apiClient v1.API) { 100 | params := r.URL.Query() 101 | matchQueries := params["match[]"] 102 | 103 | nctx, ncancel := context.WithTimeout(r.Context(), 2*time.Minute) 104 | defer ncancel() 105 | if params.Del("match[]"); len(params) > 0 { 106 | nctx = addValues(nctx, params) 107 | } 108 | for _, matchQuery := range matchQueries { 109 | start := time.Now() 110 | // Ignoring warnings for now. 111 | val, _, err := apiClient.Query(nctx, matchQuery, start) 112 | responseTime := time.Since(start).Seconds() 113 | 114 | if err != nil { 115 | klog.Errorf("query failed: %s", err) 116 | 117 | scrapeDurations.With(prometheus.Labels{ 118 | "match_query": matchQuery, 119 | "status_code": "500", 120 | }).Observe(responseTime) 121 | w.WriteHeader(http.StatusInternalServerError) 122 | ncancel() 123 | return 124 | } 125 | if val.Type() != model.ValVector { 126 | klog.Errorf("query result is not a vector: %v", val.Type()) 127 | scrapeDurations.With(prometheus.Labels{ 128 | "match_query": matchQuery, 129 | "status_code": "502", 130 | }).Observe(responseTime) 131 | // TODO: should we continue to the next query? 132 | w.WriteHeader(http.StatusInternalServerError) 133 | ncancel() 134 | return 135 | } 136 | scrapeDurations.With(prometheus.Labels{ 137 | "match_query": matchQuery, 138 | "status_code": "200", 139 | }).Observe(responseTime) 140 | printVector(w, val) 141 | } 142 | } 143 | 144 | func printVector(w http.ResponseWriter, v model.Value) { 145 | vec := v.(model.Vector) 146 | for _, sample := range vec { 147 | fmt.Fprintf(w, "%v %v %v\n", sample.Metric, sample.Value, int(sample.Timestamp)) 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= 2 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= 3 | github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= 4 | github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 5 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 7 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 8 | github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= 9 | github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= 10 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 11 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 12 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 13 | github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA= 14 | github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= 15 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 16 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 17 | github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= 18 | github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= 19 | github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= 20 | github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= 21 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 22 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 23 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 24 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 25 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 26 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= 27 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= 28 | github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+SVif2QVs3tOP0zanoHgBEVAwHxUSIzRqU= 29 | github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= 30 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 31 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 32 | github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y= 33 | github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= 34 | github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= 35 | github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= 36 | github.com/prometheus/common v0.60.1 h1:FUas6GcOw66yB/73KC+BOZoFJmbo/1pojoILArPAaSc= 37 | github.com/prometheus/common v0.60.1/go.mod h1:h0LYf1R1deLSKtD4Vdg8gy4RuOvENW2J/h19V5NADQw= 38 | github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= 39 | github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= 40 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 41 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 42 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 43 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 44 | golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= 45 | golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= 46 | golang.org/x/oauth2 v0.23.0 h1:PbgcYx2W7i4LvjJWEbf0ngHV6qJYr86PkAV3bXdLEbs= 47 | golang.org/x/oauth2 v0.23.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= 48 | golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= 49 | golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 50 | golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= 51 | golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= 52 | google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= 53 | google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= 54 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 55 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 56 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 57 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 58 | k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= 59 | k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= 60 | -------------------------------------------------------------------------------- /client_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "errors" 7 | "io" 8 | "net/http" 9 | "net/url" 10 | "reflect" 11 | "testing" 12 | "testing/fstest" 13 | 14 | "github.com/prometheus/client_golang/api" 15 | ) 16 | 17 | const ( 18 | validBearerToken = "Any Regular ASCII string" 19 | validBearerHeader = "Bearer " + validBearerToken 20 | ) 21 | 22 | // mockClient does a poor job at mocking prometheus api.Client 23 | type mockClient struct { 24 | header http.Header 25 | reqURL *url.URL 26 | } 27 | 28 | // URL implements api.Client 29 | func (m *mockClient) URL(ep string, args map[string]string) *url.URL { 30 | return nil 31 | } 32 | 33 | // Do implements api.Client 34 | func (m *mockClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { 35 | m.header = req.Header 36 | m.reqURL = req.URL 37 | return nil, nil, nil 38 | } 39 | 40 | // TestBearerToken validates bearer token reading and insertion 41 | func TestBearerToken(t *testing.T) { 42 | fsys := fstest.MapFS{ 43 | "empty_bearer": { 44 | Data: []byte{}, 45 | }, 46 | "empty_first_line_bearer": { 47 | Data: []byte("\nFirst line cannot be emtpy"), 48 | }, 49 | "invalid_bearer": { 50 | Data: []byte("bearer must be ascii: áéíóú"), 51 | }, 52 | "valid_bearer": { 53 | Data: []byte(validBearerToken), 54 | }, 55 | "valid_bearer_with_whitespace": { 56 | Data: []byte(" " + validBearerToken + " "), 57 | }, 58 | } 59 | 60 | read := func(fileName string) (*mockClient, api.Client, error) { 61 | m := &mockClient{} 62 | b, err := readBearerToken(fsys, fileName) 63 | if err != nil { 64 | return m, nil, err 65 | } 66 | c, err := newClient(m, withToken(b)) 67 | return m, c, err 68 | } 69 | 70 | // Check invalid files raise proper errors 71 | invalid := map[string]error{ 72 | "empty_bearer": EmptyBearerFileError, 73 | "empty_first_line_bearer": InvalidBearerTokenError, 74 | "invalid_bearer": InvalidBearerTokenError, 75 | } 76 | for fileName, expectedErr := range invalid { 77 | t.Run("Read bearer from "+fileName, func(t *testing.T) { 78 | _, _, err := read(fileName) 79 | if !errors.Is(err, expectedErr) { 80 | t.Fatalf("Expected error %v, got %v", expectedErr, err) 81 | } 82 | }) 83 | } 84 | 85 | // Check valid files send proper token 86 | valid := []string{ 87 | "valid_bearer", 88 | "valid_bearer_with_whitespace", 89 | } 90 | for _, fileName := range valid { 91 | t.Run("Read bearer from "+fileName, func(t *testing.T) { 92 | m, c, err := read(fileName) 93 | if err != nil { 94 | t.Fatalf("Expected no error, got %v", err) 95 | } 96 | req, _ := http.NewRequest(http.MethodGet, "http://localhost/test", nil) 97 | _, _, err = c.Do(context.TODO(), req) 98 | if err != nil { 99 | t.Fatal("Error:", err) 100 | } 101 | if m.header == nil || len(m.header) <= 0 { 102 | t.Fatal("Empty headers in request") 103 | } 104 | if authz := m.header.Get("Authorization"); authz != validBearerHeader { 105 | t.Fatalf("Expected Authorization header '%s', got '%s'", validBearerHeader, authz) 106 | } 107 | }) 108 | } 109 | } 110 | 111 | // TestWithGet validates GET request filtering 112 | func TestWithGet(t *testing.T) { 113 | post := func(t *testing.T, opts ...clientOption) *http.Response { 114 | c, err := newClient(&mockClient{}, opts...) 115 | if err != nil { 116 | t.Fatalf("Expected no error, got %v", err) 117 | } 118 | req, _ := http.NewRequest(http.MethodPost, "http://localhost/test", io.NopCloser(bytes.NewReader([]byte{}))) 119 | req.Header.Add("Content-Type", "application/x-www-form-urlencoded") 120 | res, _, err := c.Do(context.TODO(), req) 121 | if err != nil { 122 | t.Fatalf("Expected no error, got %v", err) 123 | } 124 | return res 125 | } 126 | 127 | t.Run("regular client permits POST", func(t *testing.T) { 128 | if res := post(t); res != nil { 129 | t.Fatalf("Expected nil response (from mock), got %v", res) 130 | } 131 | }) 132 | 133 | t.Run("withGet client rejects POST", func(t *testing.T) { 134 | res := post(t, withGet) 135 | if res == nil { 136 | t.Fatal("Expected not-nil response") 137 | } 138 | if res.StatusCode != http.StatusMethodNotAllowed { 139 | t.Fatalf("Expected status code %d, got %v", http.StatusMethodNotAllowed, res) 140 | } 141 | }) 142 | } 143 | 144 | // TestWithValues validates params passing through context 145 | func TestWithValues(t *testing.T) { 146 | m := mockClient{} 147 | c, err := newClient(&m) 148 | if err != nil { 149 | t.Fatalf("Expected no error, got %v", err) 150 | } 151 | v, _ := url.ParseQuery("key1=val1&key2=val2") 152 | ctx := addValues(context.TODO(), v) 153 | req, _ := http.NewRequest(http.MethodGet, "http://localhost/test", nil) 154 | if _, _, err := c.Do(ctx, req); err != nil { 155 | t.Fatalf("Expected no error, got %v", err) 156 | } 157 | urlQuery := m.reqURL.Query() 158 | if !reflect.DeepEqual(v, urlQuery) { 159 | t.Fatalf("Expected query parameters %v, got %v", v, urlQuery) 160 | } 161 | } 162 | 163 | // TestNilOption makes sure config doesn't panic if a nil option is passed 164 | func TestNilOption(t *testing.T) { 165 | if _, err := newClient(&mockClient{}, nil); !errors.Is(err, NilOptionError) { 166 | t.Fatalf("Expected error %v, got %v", NilOptionError, err) 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------