File exporter_exporter-0.4.0.obscpio of Package golang-github-QubitProducts-exporter_exporter

07070100000000000081A4000003E800000064000000015EB2C5B300000015000000000000000000000000000000000000002600000000exporter_exporter-0.4.0/.dockerignorepromu
github-release
07070100000001000081A4000003E800000064000000015EB2C5B30000013F000000000000000000000000000000000000002000000000exporter_exporter-0.4.0/AUTHORSBrian Brazil <brian.brazil@robustperception.io>
Brian Candler <b.candler@pobox.com>
Dan Poltawski <dan.poltawski@tnp.net.uk>
Kirill Shestakov <freyr.sh@gmail.com>
Laurie Clark-Michalek <laurie@qubit.com>
Linas <linas@daneliukas.eu>
Thomas Frössman <thomasf@jossystem.se>
Tristan Colgate-McFarlane <tcolgate@gmail.com>
07070100000002000081A4000003E800000064000000015EB2C5B3000000E6000000000000000000000000000000000000002300000000exporter_exporter-0.4.0/DockerfileFROM golang:1.14.2-alpine AS build
RUN mkdir /src
WORKDIR /src
COPY *.go go.mod go.sum /src/
RUN apk add git
RUN go build .

FROM alpine
COPY --from=build /src/exporter_exporter /usr/bin/
ENTRYPOINT ["/usr/bin/exporter_exporter"]
07070100000003000081A4000003E800000064000000015EB2C5B300002C5D000000000000000000000000000000000000002000000000exporter_exporter-0.4.0/LICENSE                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
07070100000004000081A4000003E800000064000000015EB2C5B3000011B6000000000000000000000000000000000000002100000000exporter_exporter-0.4.0/MakefileGITHUB_ORG  = QubitProducts
GITHUB_REPO = exporter_exporter
VERSION      = 0.4.0

DOCKER_REGISTRY     = qubitproducts
DOCKER_NAME         = exporter_exporter
DOCKER_IMAGE        = $(DOCKER_REGISTRY)/$(DOCKER_NAME):$(VERSION)
DOCKER_IMAGE_LATEST = $(DOCKER_REGISTRY)/$(DOCKER_NAME):latest

SHELL        := /usr/bin/env bash
GO           := go
FIRST_GOPATH := $(firstword $(subst :, ,$(GOPATH)))
FILES         = $(shell find . -name '*.go' | grep -v vendor)
PREFIX       ?= $(shell pwd)
BIN_DIR      ?= $(shell pwd)

PACKAGE_TARGET     = deb
PACKAGE_NAME       = expexp
PACKAGE_VERSION    = $(VERSION)
PACKAGE_REVISION   = 3
PACKAGE_ARCH       = amd64
PACKAGE_MAINTAINER = tristan@qubit.com
PACKAGE_FILE       = $(PACKAGE_NAME)_$(PACKAGE_VERSION)-$(PACKAGE_REVISION)_$(PACKAGE_ARCH).$(PACKAGE_TARGET)
BINNAME            = exporter_exporter

PWD := $(shell pwd)

all: package
clean:
	rm -f $(PACKAGE_FILE)
	rm -rf dist
	rm -rf build

.PHONY: test
test:
	echo ">> running short tests"
	$(GO) test -short $(pkgs)

.PHONY: test-static
test-static:
	echo ">> running static tests"
	$(GO) vet $(pkgs)
	[[ "$(shell gofmt -l $(files))" == "" ]] || (echo "gofmt check failed"; exit 1)

.PHONY: format
format:
	echo ">> formatting code"
	$(GO) fmt $(pkgs)

.PHONY: vet
vet:
	echo ">> vetting code"
	$(GO) vet $(pkgs)

.PHONY: prepare-package clean-package package
prepare-package: clean-package build/$(BINNAME)-$(VERSION).linux-amd64/$(BINNAME)
	mkdir -p dist/usr/local/bin
	mkdir -p dist/etc/init
	mkdir -p dist/etc/default
	mkdir -p dist/etc/exporter_exporter.d/
	install -m755 build/$(BINNAME)-$(VERSION).linux-amd64/$(BINNAME) dist/usr/local/bin/$(BINNAME)
	install -m644 $(BINNAME).conf dist/etc/init/$(BINNAME).conf
	install -m644 $(BINNAME).defaults dist/etc/default/$(BINNAME)
	install -m644 expexp.yaml dist/etc/exporter_exporter.yaml
	touch dist/etc/exporter_exporter.d/.dir

clean-package:
	rm -rf dist

.PHONY: AUTHORS
AUTHORS:
	# There's only so much credit I need.
	git log --format='%aN <%aE>' | grep -v Tristan\ Colgate\  | sort -u > AUTHORS

$(PACKAGE_FILE): prepare-package
	cd dist && \
	  fpm \
	  -t $(PACKAGE_TARGET) \
	  -m $(PACKAGE_MAINTAINER) \
	  -n $(PACKAGE_NAME) \
	  -a $(PACKAGE_ARCH) \
	  -v $(PACKAGE_VERSION) \
	  --iteration $(PACKAGE_REVISION) \
	  --config-files /etc/$(BINNAME).yaml \
	  --config-files /etc/init/$(BINNAME).conf \
	  --config-files /etc/default/$(BINNAME) \
	  -s dir \
	  -p ../$(PACKAGE_FILE) \
	  .

.PHONY: build-docker release-docker
build-docker: 
	docker build -t $(DOCKER_IMAGE) .

release-docker: build-docker
	docker push $(DOCKER_IMAGE)
	docker tag $(DOCKER_IMAGE) $(DOCKER_IMAGE_LATEST)
	docker push $(DOCKER_IMAGE_LATEST)

LDFLAGS = -X main.Version=$(VERSION) \
					-X main.Branch=$(BRANCH) \
					-X main.Revision=$(REVISION) \
					-X main.BuildUser=$(BUILDUSER) \
					-X main.BuildDate=$(BUILDDATE)

build/$(BINNAME)-$(VERSION).windows-amd64/$(BINNAME).exe: $(SRCS)
	GOOS=$* GOARCH=amd64 $(GO) build \
	 -ldflags "$(LDFLAGS)" \
	 -o $@ \
	 .
build/$(BINNAME)-$(VERSION).windows-amd64.zip: build/expoter_exporter-$(VERSION).windows-amd64/$(BINNAME).exe
	zip $@ $<

build/$(BINNAME)-$(VERSION).%-amd64/$(BINNAME): $(SRCS)
	GOOS=$* GOARCH=amd64 $(GO) build \
	 -ldflags  "$(LDFLAGS)" \
	 -o $@ \
	 .

build/$(BINNAME)-$(VERSION).%-amd64.tar.gz: build/$(BINNAME)-$(VERSION).%-amd64/$(BINNAME)
	cd build && \
		tar cfzv $(BINNAME)-$(VERSION).$*-amd64.tar.gz $(BINNAME)-$(VERSION).$*-amd64


package: $(PACKAGE_FILE)

package-release: $(PACKAGE_FILE)
	go run github.com/aktau/github-release upload \
	  -u $(GITHUB_ORG) \
	 	-r $(GITHUB_REPO) \
	 	--tag v$(VERSION) \
		--name $(PACKAGE_FILE) \
		--file $(PACKAGE_FILE)

release-windows: build/exporter_exporter-$(VERSION).windows-amd64.zip
	go run github.com/aktau/github-release upload \
		-u $(GITHUB_ORG) \
		-r $(GITHUB_REPO) \
		--tag v$(VERSION) \
		--name exporter_exporter-$(VERSION).windows-amd64.zip \
		-f ./build/exporter_exporter-$(VERSION).windows-amd64.zip

release-%: build/exporter_exporter-$(VERSION).%-amd64.tar.gz
	go run github.com/aktau/github-release upload \
		-u $(GITHUB_ORG) \
		-r $(GITHUB_REPO) \
		--tag v$(VERSION) \
		--name exporter_exporter-$(VERSION).$*-amd64.tar.gz \
		-f ./build/exporter_exporter-$(VERSION).$*-amd64.tar.gz

release: 
	git tag v$(VERSION)
	git push origin v$(VERSION)
	go run github.com/aktau/github-release release \
		-u $(GITHUB_ORG) \
		-r $(GITHUB_REPO) \
		--tag v$(VERSION) \
		--name v$(VERSION)
	make release-darwin release-linux release-windows package-release
07070100000005000081A4000003E800000064000000015EB2C5B30000002C000000000000000000000000000000000000001F00000000exporter_exporter-0.4.0/NOTICEexporter_exporter
Copyright 2016 Qubit Ltd.
07070100000006000081A4000003E800000064000000015EB2C5B300001B2B000000000000000000000000000000000000002200000000exporter_exporter-0.4.0/README.md# Exporter Exporter - prometheus exporter proxy

```   "you mean apache/nginx" - bbrazil ```

This provides a simple reverse proxy for prometheus exporters. It is intended as a
single binary alternative to nginx/apache for use in environments where opening multiple
TCP ports to all servers might be difficult (technically or politically)

The advantages are:

- A single port can be used to query multiple exporters (to ease firewall configuration concerns).
- Can provide TLS with optional client certificate authentication.
- Provides verification that the target is serving prometheus metrics.
- Can be used to execute scripts that produce prometheus metrics.
- _up_ behaviour is the same as for querying individual collectors.
- Small code size, minimal external depedencies, easily auditable.

The exporter has three endpoints.

- /: displays a list of all exporters with links to their metrics.
  - Returns JSON if the header "Accept: application/json" is passed

- /proxy: which takes the following parameters:
  - module: the name of the module from the configuration to execute.
  - args (optional): arguments to pass to the module.
  - params (optional): named parameter to pass to the module (either as CLI args, or http parameters).

- /metrics: this exposes the metrics for the collector itself.

Features that will NOT be included:

- merging of module outputs into one query (this would break _up_ behaviour)

## Installation

You can build directly using a plain ```go get github.com/QubitProducts/exporter_exporter```.
The provided Makefile is primarily used for releases.

Pre-built binaries and a debian package are available on the [GitHub release page](https://github.com/QubitProducts/exporter_exporter/releases).

An ansible recipe as also [available](https://github.com/umanit/ansible-prometheus_exporter_exporter) (kindly provided by one of our users).

TODO:

- Config reload on HUP (or POST, or config file change?)
- route to a docker/rocket container by name

### Windows Service

The binary can be installed as a Windows service by supplying the `-winsvc install` arg.
All other arguments passed along with `-winsvc install` will be added to the service startup 
and can only be changed by uninstalling/installing it again (or modifying the Windows registry directly).

## Configuration

In expexp.yaml list each exporter listening on localhost with its known port.

```
modules:
  node:
    method: http
    http:
       port: 9100

  mtail:
    method: http
    http:
       port: 3903
       headers:
          foo: bar

  cadvisor:
    verify: false
    method: http
    http:
       port: 4194
  
  netdata:
    method: http
    http:
       port: 19999
       path: '/api/v1/allmetrics?format=prometheus'

  somescript:
    method: exec
    timeout: 1s
    exec:
      command: /tmp/myscript.sh
      args:
        - "myarg1"
        - "myarg2"
      env:
        THING: "1"
        THING2: "2"
```

In your prometheus configuration

```
scrape_configs:
  - job_name: 'expexp_metrics'
    scrape_interval: 1s
    static_configs:
      - targets: ['host:9999']
  - job_name: 'cadvisor'
    scrape_interval: 5s
    metrics_path: /proxy
    params:
      module:
        - cadvisor
    static_configs:
      - targets: ['host:9999']
  - job_name: 'mtail'
    scrape_interval: 5s
    metrics_path: /proxy
    params:
      module:
        - mtail
    static_configs:
      - targets: ['host:9999']
  - job_name: 'somescript'
    scrape_interval: 5s
    metrics_path: /proxy
    params:
      module:
        - somescript
    static_configs:
      - targets: ['host:9999']
```

## Directory-based configuration

You can also specify `-config.dirs` to break the configuration into separate
files.  The module name is taken from the name of the file (minus the
yml/yaml extension), and the configuration for that module goes in at the
top level.

```
==> expexp.yaml <==
modules: {}

==> expexp.d/node.yaml <==
method: http
http:
   port: 9100

==> expexp.d/mtail.yaml <==
method: http
http:
   port: 3903
```

## TLS configuration

You can use exporter_exporter with TLS to encrypt the traffic, and at the
same time enforce strong mutual authentication between the nodes and the
prometheus server.

Note that `-web.tls.verify` will accept *any* certificate signed by the
`-web.tls.ca`, so you need to create a separate CA for this purpose - or use
a self-signed certificate, which acts as its own CA.

Here is a simple configuration example, using one key/cert for the
prometheus server and one key/cert shared between all the remote nodes.
Firstly, create the keys and certs:

```
openssl req -x509 -newkey rsa:1024 -keyout prom_node_key.pem -out prom_node_cert.pem -days 29220 -nodes -subj /commonName=prom_node/
openssl req -x509 -newkey rsa:1024 -keyout prometheus_key.pem -out prometheus_cert.pem -days 29220 -nodes -subj /commonName=prometheus/
```

Create an `/etc/prometheus/ssl/` directory on the prometheus server and all
the remote nodes.  Install both cert.pem files everywhere.  It is safe for
them to be world-readable.

Install `prom_node_key.pem` only on the nodes, and set file permissions to
protect it so that only exporter_exporter can read it.  Similarly, install
`prometheus_key.pem` only on the prometheus server, and set permissions so
that only the prometheus process can read it.

Configuration for exporter_exporter on the nodes (here it also disables
plain HTTP):

```
EXPEXP_FLAGS='-web.listen-address= -web.tls.listen-address=:9998
 -web.tls.cert=/etc/prometheus/ssl/prom_node_cert.pem
 -web.tls.key=/etc/prometheus/ssl/prom_node_key.pem
 -web.tls.ca=/etc/prometheus/ssl/prometheus_cert.pem
 -web.tls.verify'
```

To test, use `curl` to make a scrape, replacing x.x.x.x with the IP address
of the target:

```
curl --cert /etc/prometheus/ssl/prometheus_cert.pem \
     --key /etc/prometheus/ssl/prometheus_key.pem \
     --cacert /etc/prometheus/ssl/prom_node_cert.pem \
     --resolve prom_node:9998:x.x.x.x \
     -v https://prom_node:9998/proxy?module=node
```

When this is working, configure your prometheus server to use https. Example:

```
  - job_name: node
    scrape_interval: 1m
    scrape_timeout: 50s
    file_sd_configs:
      - files:
        - /etc/prometheus/targets.d/node_targets.yml
    scheme: https
    tls_config:
      # Verifying remote identity
      ca_file: /etc/prometheus/ssl/prom_node_cert.pem
      server_name: prom_node
      # Asserting our identity
      cert_file: /etc/prometheus/ssl/prometheus_cert.pem
      key_file: /etc/prometheus/ssl/prometheus_key.pem
    metrics_path: /proxy
    params:
      module: [ node ]
    relabel_configs:
      - source_labels: [__address__]
        target_label: instance
      - source_labels: [__address__]
        regex: '[^:]+'
        target_label: __address__
        replacement: '${1}:9998'
```

Example `/etc/prometheus/targets.d/node_targets.yml`:

```
- labels: []
  targets:
  - 192.0.2.1
  - 192.0.2.2
```
07070100000007000081A4000003E800000064000000015EB2C5B300001580000000000000000000000000000000000000002200000000exporter_exporter-0.4.0/config.go// Copyright 2016 Qubit Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"bytes"
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httputil"
	"time"

	yaml "gopkg.in/yaml.v2"
)

type config struct {
	Global struct {
	}
	Modules map[string]*moduleConfig
	XXX     map[string]interface{} `yaml:",inline"`

	bearerToken   string
	proxyPath     string
	telemetryPath string
}

type moduleConfig struct {
	Method  string                 `yaml:"method"`
	Timeout time.Duration          `yaml:"timeout"`
	XXX     map[string]interface{} `yaml:",inline"`

	Exec execConfig `yaml:"exec"`
	HTTP httpConfig `yaml:"http"`

	name string
}

type httpConfig struct {
	Verify                *bool                  `yaml:"verify"`                   // no default
	TLSInsecureSkipVerify bool                   `yaml:"tls_insecure_skip_verify"` // false
	TLSCertFile           *string                `yaml:"tls_cert_file"`            // no default
	TLSKeyFile            *string                `yaml:"tls_key_file"`             // no default
	TLSCACertFile         *string                `yaml:"tls_ca_cert_file"`         // no default
	Port                  int                    `yaml:"port"`                     // no default
	Path                  string                 `yaml:"path"`                     // /metrics
	Scheme                string                 `yaml:"scheme"`                   // http
	Address               string                 `yaml:"address"`                  // 127.0.0.1
	Headers               map[string]string      `yaml:"headers"`                  // no default
	XXX                   map[string]interface{} `yaml:",inline"`

	tlsConfig              *tls.Config
	mcfg                   *moduleConfig
	*httputil.ReverseProxy `json:"-"`
}

type execConfig struct {
	Command string                 `yaml:"command"`
	Args    []string               `yaml:"args"`
	Env     map[string]string      `yaml:"env"`
	XXX     map[string]interface{} `yaml:",inline"`

	mcfg *moduleConfig
}

func readConfig(r io.Reader) (*config, error) {
	buf := bytes.Buffer{}
	io.Copy(&buf, r)
	cfg := config{}

	err := yaml.Unmarshal(buf.Bytes(), &cfg)

	if len(cfg.XXX) != 0 {
		return nil, fmt.Errorf("Unknown configuration fields: %v", cfg.XXX)
	}

	for s := range cfg.Modules {
		if err := checkModuleConfig(s, cfg.Modules[s]); err != nil {
			return nil, fmt.Errorf("bad config for module %s, %w", s, err)
		}
	}

	return &cfg, err
}

func readModuleConfig(name string, r io.Reader) (*moduleConfig, error) {
	buf := bytes.Buffer{}
	io.Copy(&buf, r)
	cfg := moduleConfig{}

	err := yaml.Unmarshal(buf.Bytes(), &cfg)
	if err != nil {
		return nil, err
	}

	if err = checkModuleConfig(name, &cfg); err != nil {
		return nil, err
	}

	return &cfg, nil
}

func checkModuleConfig(name string, cfg *moduleConfig) error {
	if len(cfg.XXX) != 0 {
		return fmt.Errorf("unknown module configuration fields: %v", cfg.XXX)
	}

	cfg.name = name

	switch cfg.Method {
	case "http":
		if len(cfg.HTTP.XXX) != 0 {
			return fmt.Errorf("Unknown http module configuration fields: %v", cfg.HTTP.XXX)
		}

		if cfg.HTTP.Port == 0 {
			return fmt.Errorf("module %v must have a non-zero port set", name)
		}
		if cfg.HTTP.Verify == nil {
			v := true
			cfg.HTTP.Verify = &v
		}
		if cfg.HTTP.Scheme == "" {
			cfg.HTTP.Scheme = "http"
		}
		if cfg.HTTP.Path == "" {
			cfg.HTTP.Path = "/metrics"
		}
		if cfg.HTTP.Address == "" {
			cfg.HTTP.Address = "localhost"
		}

		tlsConfig, err := cfg.HTTP.getTLSConfig()
		if err != nil {
			return fmt.Errorf("could not create tls config, %w", err)
		}

		dirFunc, err := cfg.getReverseProxyDirectorFunc()
		if err != nil {
			return err
		}

		cfg.HTTP.tlsConfig = tlsConfig
		cfg.HTTP.ReverseProxy = &httputil.ReverseProxy{
			Transport:    &http.Transport{TLSClientConfig: tlsConfig},
			Director:     dirFunc,
			ErrorHandler: cfg.getReverseProxyErrorHandlerFunc(),
		}
		if *cfg.HTTP.Verify {
			cfg.HTTP.ReverseProxy.ModifyResponse = cfg.getReverseProxyModifyResponseFunc()
		}
	case "exec":
		if len(cfg.Exec.XXX) != 0 {
			return fmt.Errorf("Unknown exec module configuration fields: %v", cfg.Exec.XXX)
		}
	default:
		return fmt.Errorf("Unknown module method: %v", cfg.Method)
	}

	return nil
}

func (c httpConfig) getTLSConfig() (*tls.Config, error) {
	config := &tls.Config{
		InsecureSkipVerify: c.TLSInsecureSkipVerify,
		MinVersion:         tls.VersionTLS12,
	}
	if c.TLSCACertFile != nil {
		caCert, err := ioutil.ReadFile(*c.TLSCACertFile)
		if err != nil {
			return nil, fmt.Errorf("could not read ca from %v, %w", *c.TLSCACertFile, err)
		}

		config.ClientCAs = x509.NewCertPool()
		config.ClientCAs.AppendCertsFromPEM(caCert)
	}
	if c.TLSCertFile != nil && c.TLSKeyFile != nil {
		cert, err := tls.LoadX509KeyPair(*c.TLSCertFile, *c.TLSKeyFile)
		if err != nil {
			return nil, fmt.Errorf("failed reading TLS credentials, %w", err)
		}
		config.Certificates = []tls.Certificate{cert}
	}

	return config, nil
}
07070100000008000081A4000003E800000064000000015EB2C5B300000AAC000000000000000000000000000000000000002000000000exporter_exporter-0.4.0/exec.go// Copyright 2016 Qubit Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"bytes"
	"context"
	"fmt"
	"net/http"
	"os"
	"os/exec"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	dto "github.com/prometheus/client_model/go"
	"github.com/prometheus/common/expfmt"
	log "github.com/sirupsen/logrus"
)

var (
	cmdStartsCount = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "expexp_command_starts_total",
			Help: "Counts of command starts",
		},
		[]string{"module"},
	)
	cmdFailsCount = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "expexp_command_fails_total",
			Help: "Count of commands with non-zero exits",
		},
		[]string{"module"},
	)
)

func (c execConfig) GatherWithContext(ctx context.Context, r *http.Request) prometheus.GathererFunc {
	return func() ([]*dto.MetricFamily, error) {
		var out bytes.Buffer

		cmd := exec.CommandContext(ctx, c.Command)
		cmd.Args = append(cmd.Args, c.Args...)
		uargs, ok := r.URL.Query()["args"]
		if ok {
			cmd.Args = append(cmd.Args, uargs...)
		}

		for k, v := range c.Env {
			cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
		}

		cmd.Stdout = &out
		cmd.Stderr = os.Stderr

		errc := make(chan error, 1)
		go func() {
			cmdStartsCount.WithLabelValues(c.mcfg.name).Inc()
			errc <- cmd.Run()
			close(errc)
		}()

		var err error
		select {
		case err = <-errc:
		case <-ctx.Done():
			err = ctx.Err()
		}

		if err != nil {
			log.Warnf("Command module %v failed %+v", c.mcfg.name, err)
			cmdFailsCount.WithLabelValues(c.mcfg.name).Inc()
			if err == context.DeadlineExceeded {
				proxyTimeoutCount.WithLabelValues(c.mcfg.name).Inc()
			}
			return nil, err
		}
		var prsr expfmt.TextParser

		var result []*dto.MetricFamily
		mfs, err := prsr.TextToMetricFamilies(&out)
		if err != nil {
			proxyMalformedCount.WithLabelValues(c.mcfg.name).Inc()
			return nil, err
		}
		for _, mf := range mfs {
			result = append(result, mf)
		}
		return result, nil
	}
}

func (c execConfig) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	g := c.GatherWithContext(ctx, r)
	promhttp.HandlerFor(g, promhttp.HandlerOpts{}).ServeHTTP(w, r)
}
07070100000009000081A4000003E800000064000000015EB2C5B300000179000000000000000000000000000000000000002400000000exporter_exporter-0.4.0/expexp.yamlmodules:
  node:
    method: http
    http:
       port: 9100
       tls_ca_cert_file: nofile

  mtail:
    method: http
    http:
       port: 3903
       headers:
          foo: bar

  cadvisor:
    method: http
    http:
       port: 4194

  haproxy:
    method: http
    http:
       port: 9101

  blackbox:
    method: http
    http:
       port: 9115
       path: probe

0707010000000A000081A4000003E800000064000000015EB2C5B30000015A000000000000000000000000000000000000002F00000000exporter_exporter-0.4.0/exporter_exporter.conf# Ubuntu upstart file at /etc/init/exporter_exporter.conf

description "exporter_exporter"

start on (started networking)
stop on [!12345]

respawn
respawn limit 2 5

setuid root
setgid root

script
    . /etc/default/exporter_exporter
    exec /usr/local/bin/exporter_exporter -config.file /etc/exporter_exporter.yaml ${EXPEXP_FLAGS}
end script
0707010000000B000081A4000003E800000064000000015EB2C5B300000010000000000000000000000000000000000000003300000000exporter_exporter-0.4.0/exporter_exporter.defaultsEXPEXP_FLAGS=""
0707010000000C000081A4000003E800000064000000015EB2C5B300000422000000000000000000000000000000000000001F00000000exporter_exporter-0.4.0/go.modmodule github.com/QubitProducts/exporter_exporter

require (
	github.com/aktau/github-release v0.7.2
	github.com/dustin/go-humanize v1.0.0 // indirect
	github.com/golang/protobuf v1.3.1 // indirect
	github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
	github.com/kr/pretty v0.1.0 // indirect
	github.com/prometheus/client_golang v0.9.2
	github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90
	github.com/prometheus/common v0.2.0
	github.com/prometheus/procfs v0.0.0-20190322151404-55ae3d9d5573 // indirect
	github.com/sirupsen/logrus v1.4.0
	github.com/stretchr/testify v1.3.0 // indirect
	github.com/tomnomnom/linkheader v0.0.0-20180905144013-02ca5825eb80 // indirect
	github.com/voxelbrain/goptions v0.0.0-20180630082107-58cddc247ea2 // indirect
	golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c // indirect
	golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6
	golang.org/x/sys v0.0.0-20190322080309-f49334f85ddc
	gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
	gopkg.in/yaml.v2 v2.2.2
)

go 1.14
0707010000000D000081A4000003E800000064000000015EB2C5B300002038000000000000000000000000000000000000001F00000000exporter_exporter-0.4.0/go.sumgithub.com/aktau/github-release v0.7.2 h1:la7AnShr2MQPIlBEcRA9MPbI8av0YFmpFP9WM5EoqJs=
github.com/aktau/github-release v0.7.2/go.mod h1:cPkP83iRnV8pAJyQlQ4vjLJoC+JE+aT5sOrYz3sTsX0=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc h1:cAKDfWh5VpdgMhJosfJnn5/FoN2SRZ4p7fJNX58YPaU=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf h1:qet1QNfXsQxTZqLG4oE62mJzwPIB8+Tee4RNCL9ulrY=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLMYoU8P317H5OQ+Via4RmuPwCS0=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s=
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
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 v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.2 h1:awm861/B8OKDd2I/6o1dy3ra4BamzKhYOiGItCeZ740=
github.com/prometheus/client_golang v0.9.2/go.mod h1:OsXs2jCmiKlQ1lTBmv21f2mNfw4xf/QclQDMrYNZzcM=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90 h1:S/YWwWx/RA8rT8tKFRuGUZhuA90OyIBpPCXkcbwU8DE=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/common v0.2.0 h1:kUZDBDTdBVBYBj5Tmh2NZLlF60mfjA27rM34b+cVwNU=
github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20190322151404-55ae3d9d5573 h1:gAuD3LIrjkoOOPLlhGlZWZXztrQII9a9kT6HS5jFtSY=
github.com/prometheus/procfs v0.0.0-20190322151404-55ae3d9d5573/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.0 h1:yKenngtzGh+cUSSh6GWbxW2abRqhYUSR/t/6+2QqNvE=
github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/tomnomnom/linkheader v0.0.0-20180905144013-02ca5825eb80 h1:nrZ3ySNYwJbSpD6ce9duiP+QkD3JuLCcWkdaehUS/3Y=
github.com/tomnomnom/linkheader v0.0.0-20180905144013-02ca5825eb80/go.mod h1:iFyPdL66DjUD96XmzVL3ZntbzcflLnznH0fr99w5VqE=
github.com/voxelbrain/goptions v0.0.0-20180630082107-58cddc247ea2 h1:txplJASvd6b/hrE0s/Ixfpp2cuwH9IO9oZBAN9iYa4A=
github.com/voxelbrain/goptions v0.0.0-20180630082107-58cddc247ea2/go.mod h1:DGCIhurYgnLz8J9ga1fMV/fbLDyUvTyrWXVWUIyJon4=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c h1:Vj5n4GlwjmQteupaxJ9+0FNOmBrHfq7vN4btdGoDZgI=
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6 h1:bjcUS9ztw9kFmmIxJInhon/0Is3p+EHBKNgquIzo1OI=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190322080309-f49334f85ddc h1:4gbWbmmPFp4ySWICouJl6emP0MyS31yy9SrTlAGFT+g=
golang.org/x/sys v0.0.0-20190322080309-f49334f85ddc/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
0707010000000E000081A4000003E800000064000000015EB2C5B3000015F8000000000000000000000000000000000000002000000000exporter_exporter-0.4.0/http.go// Copyright 2016 Qubit Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"bytes"
	"compress/gzip"
	"context"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"strconv"
	"strings"

	dto "github.com/prometheus/client_model/go"
	"github.com/prometheus/common/expfmt"
	log "github.com/sirupsen/logrus"
)

const (
	// Msg to send in response body when verification of proxied server
	// response is failed
	VerificationErrorMsg = "Internal Server Error: " +
		"Response from proxied server failed verification. " +
		"See server logs for details"
)

type VerifyError struct {
	msg   string
	cause error
}

func (e *VerifyError) Error() string { return e.msg + ": " + e.cause.Error() }
func (e *VerifyError) Unwrap() error { return e.cause }

func (cfg moduleConfig) getReverseProxyDirectorFunc() (func(*http.Request), error) {
	base, err := url.Parse(cfg.HTTP.Path)
	if err != nil {
		return nil, fmt.Errorf("http configuration path should be a valid URL path with options, %w", err)
	}

	cvs := base.Query()

	return func(r *http.Request) {
		qvs := r.URL.Query()
		for k, vs := range cvs {
			for _, v := range vs {
				qvs.Add(k, v)
			}
		}
		qvs["module"] = qvs["module"][1:]

		r.URL.RawQuery = qvs.Encode()

		for k, v := range cfg.HTTP.Headers {
			r.Header.Add(k, v)
		}

		r.URL.Scheme = cfg.HTTP.Scheme
		r.URL.Host = net.JoinHostPort(cfg.HTTP.Address, strconv.Itoa(cfg.HTTP.Port))
		r.URL.Path = base.Path
	}, nil
}

func (cfg moduleConfig) getReverseProxyModifyResponseFunc() func(*http.Response) error {
	return func(resp *http.Response) error {
		if resp.StatusCode != 200 {
			return nil
		}

		var (
			err     error
			body    bytes.Buffer
			oldBody = resp.Body
		)
		defer oldBody.Close()

		if _, err = body.ReadFrom(oldBody); err != nil {
			return &VerifyError{"Failed to read body from proxied server", err}
		}

		resp.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))

		var bodyReader io.ReadCloser
		if resp.Header.Get("Content-Encoding") == "gzip" {
			bodyReader, err = gzip.NewReader(bytes.NewReader(body.Bytes()))
			if err != nil {
				return &VerifyError{"Failed to decode gzipped response", err}
			}
		} else {
			bodyReader = ioutil.NopCloser(bytes.NewReader(body.Bytes()))
		}
		defer bodyReader.Close()

		dec := expfmt.NewDecoder(bodyReader, expfmt.ResponseFormat(resp.Header))
		for {
			mf := dto.MetricFamily{}
			err := dec.Decode(&mf)
			if err == io.EOF {
				break
			}
			if err != nil {
				proxyMalformedCount.WithLabelValues(cfg.name).Inc()
				return &VerifyError{"Failed to decode metrics from proxied server", err}
			}
		}

		return nil
	}
}

func (cfg moduleConfig) getReverseProxyErrorHandlerFunc() func(http.ResponseWriter, *http.Request, error) {
	return func(w http.ResponseWriter, r *http.Request, err error) {
		var verifyError *VerifyError
		if errors.As(err, &verifyError) {
			log.Errorf("Verification for module '%s' failed: %v", cfg.name, err)
			http.Error(w, VerificationErrorMsg, http.StatusInternalServerError)
			return
		}

		if errors.Is(err, context.DeadlineExceeded) {
			log.Errorf("Request time out for module '%s'", cfg.name)
			http.Error(w, http.StatusText(http.StatusGatewayTimeout), http.StatusGatewayTimeout)
			return
		}

		log.Errorf("Proxy error for module '%s': %v", cfg.name, err)
		http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
	}
}

// BearerAuthMiddleware
type BearerAuthMiddleware struct {
	http.Handler
	Token string
}

func (b BearerAuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	authHeader := r.Header.Get("Authorization")
	if authHeader == "" {
		w.WriteHeader(http.StatusUnauthorized)
		_, _ = w.Write([]byte("Authorization header is missing"))
		return
	}
	ss := strings.SplitN(authHeader, " ", 2)
	if !(len(ss) == 2 && ss[0] == "Bearer") {
		w.WriteHeader(http.StatusUnauthorized)
		_, _ = w.Write([]byte("Authorization header not of Bearer type"))
		return
	}
	if ss[1] != b.Token {
		w.WriteHeader(http.StatusUnauthorized)
		_, _ = w.Write([]byte("Invalid Bearer Token"))
		return
	}
	b.Handler.ServeHTTP(w, r)
}

type IPAddressAuthMiddleware struct {
	http.Handler
	ACL []net.IPNet
}

func (m IPAddressAuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		log.Errorf("Failed to parse host form remote address '%s'", r.RemoteAddr)
		w.WriteHeader(http.StatusInternalServerError)
		_, _ = w.Write([]byte("Failed to determine client IP address"))
		return
	}

	addr := net.ParseIP(host)
	if addr == nil {
		log.Errorf(
			"Failed to determine client IP address from '%s' (originally '%s')",
			host, r.RemoteAddr,
		)
		w.WriteHeader(http.StatusInternalServerError)
		_, _ = w.Write([]byte("Failed to determine client IP address"))
		return
	}

	for _, network := range m.ACL {
		// client is in access list
		if network.Contains(addr) {
			m.Handler.ServeHTTP(w, r)
			return
		}
	}

	// client is not in access list
	log.Infof("Access forbidden for %q", addr)
	w.WriteHeader(http.StatusForbidden)
	_, _ = w.Write([]byte("Forbidden"))
}
0707010000000F000081A4000003E800000064000000015EB2C5B300000A98000000000000000000000000000000000000002500000000exporter_exporter-0.4.0/http_test.gopackage main

import (
	"bytes"
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strconv"
	"testing"
	"time"

	dto "github.com/prometheus/client_model/go"
	"github.com/prometheus/common/expfmt"
)

func BenchmarkReverseProxyHandler(b *testing.B) {
	body := genRandomMetricsResponse(10000, 10)

	test_exporter := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		reader := bytes.NewReader(body.Bytes())
		io.Copy(w, reader)
	}))
	defer test_exporter.Close()

	URL, _ := url.Parse(test_exporter.URL)
	verify := true
	port, _ := strconv.ParseInt(URL.Port(), 0, 0)
	modCfg := &moduleConfig{
		Method:  "http",
		Timeout: 5 * time.Second,
		HTTP: httpConfig{
			Verify:  &verify,
			Scheme:  URL.Scheme,
			Address: URL.Hostname(),
			Port:    int(port),
			Path:    "/",
		},
	}

	if err := checkModuleConfig("test", modCfg); err != nil {
		b.Fatalf("Failed to check module config: %v", err)
	}

	cfg := &config{
		Modules: map[string]*moduleConfig{
			"test": modCfg,
		},
	}

	req := httptest.NewRequest("GET", "/proxy?module=test", nil)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		rr := httptest.NewRecorder()
		cfg.doProxy(rr, req)
		if rr.Code != http.StatusOK {
			b.Fatalf("Bad response status %d", rr.Code)
		}
		if len(rr.Body.Bytes()) <= 0 {
			b.Fatal("Response body is absent")
		}
	}
}

// genRandomMetricsResponse generates http response body which contains random set of
// prometheus metrics. mf_num sets number of metric families in response which has
// metric names in format 'metric{random number}'. m_num controls number of metrics
// inside each metric family. Metrics inside metric families differ in values of
// label 'label'.
func genRandomMetricsResponse(mf_num int, m_num int) *bytes.Buffer {
	rand.Seed(time.Now().UnixNano())
	helpMsg := "help msg"
	labelName := "label"
	metricFamilies := make([]*dto.MetricFamily, mf_num)
	metricType := dto.MetricType_GAUGE
	for i, _ := range metricFamilies {
		metrics := make([]*dto.Metric, m_num)
		for i, _ := range metrics {
			labelValue := fmt.Sprint(rand.Int63())
			value := rand.Float64()
			ts := time.Now().UnixNano()
			metrics[i] = &dto.Metric{
				Label: []*dto.LabelPair{
					&dto.LabelPair{
						Name:  &labelName,
						Value: &labelValue,
					},
				},
				Gauge: &dto.Gauge{
					Value: &value,
				},
				TimestampMs: &ts,
			}
		}
		metricName := fmt.Sprintf("metric%d", rand.Int63())
		metricFamilies[i] = &dto.MetricFamily{
			Name:   &metricName,
			Help:   &helpMsg,
			Type:   &metricType,
			Metric: metrics,
		}
	}

	buf := &bytes.Buffer{}
	enc := expfmt.NewEncoder(buf, expfmt.FmtText)
	for _, mf := range metricFamilies {
		enc.Encode(mf)
	}

	return buf
}
07070100000010000081A4000003E800000064000000015EB2C5B3000039EC000000000000000000000000000000000000002000000000exporter_exporter-0.4.0/main.go// Copyright 2016 Qubit Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"html/template"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"regexp"
	"strings"
	"time"

	"golang.org/x/sync/errgroup"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	log "github.com/sirupsen/logrus"
)

var (
	printVersion = flag.Bool("version", false, "Print the version and exit")

	cfgFile  = flag.String("config.file", "expexp.yaml", "The path to the configuration file.")
	cfgDirs  StringSliceFlag
	skipDirs = flag.Bool("config.skip-dirs", false, "Skip non existent -config.dirs entries instead of terminating.")

	addr = flag.String("web.listen-address", ":9999", "The address to listen on for HTTP requests.")

	bearerToken     = flag.String("web.bearer.token", "", "Bearer authentication token.")
	bearerTokenFile = flag.String("web.bearer.token-file", "", "File containing the Bearer authentication token.")

	acl IPNetSliceFlag

	certPath  = flag.String("web.tls.cert", "cert.pem", "Path to cert")
	keyPath   = flag.String("web.tls.key", "key.pem", "Path to key")
	caPath    = flag.String("web.tls.ca", "ca.pem", "Path to CA to auth clients against")
	verify    = flag.Bool("web.tls.verify", false, "Enable client verification")
	certMatch = flag.String("web.tls.certmatch", "", "if set, this is used as a regexp that is matched against any certificate subject, dnsname or email address, only certs with a match are verified. web.tls.verify must also be set")
	tlsAddr   = flag.String("web.tls.listen-address", "", "The address to listen on for HTTPS requests.")

	tPath = flag.String("web.telemetry-path", "/metrics", "The address to listen on for HTTP requests.")
	pPath = flag.String("web.proxy-path", "/proxy", "The address to listen on for HTTP requests.")

	logLevel = LogLevelFlag(log.WarnLevel)
	logJson  = flag.Bool("log.json", false, "Serialize log messages in JSON")

	proxyDuration = prometheus.NewSummaryVec(
		prometheus.SummaryOpts{
			Name: "expexp_proxy_duration_seconds",
			Help: "Duration of proxying requests to configured exporters",
		},
		[]string{"module"},
	)
	proxyErrorCount = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "expexp_proxy_errors_total",
			Help: "Counts of errors",
		},
		[]string{"module"},
	)
	proxyTimeoutCount = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "expexp_proxy_timeout_errors_total",
			Help: "Counts of the number of times a proxy timeout occurred",
		},
		[]string{"module"},
	)

	proxyMalformedCount = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "expexp_malformed_content_errors_total",
			Help: "Counts of unparsable scrape content errors",
		},
		[]string{"module"},
	)
)

func init() {
	// register the collector metrics in the default
	// registry.
	prometheus.MustRegister(proxyDuration)
	prometheus.MustRegister(proxyTimeoutCount)
	prometheus.MustRegister(proxyErrorCount)
	prometheus.MustRegister(proxyMalformedCount)
	prometheus.MustRegister(cmdStartsCount)
	prometheus.MustRegister(cmdFailsCount)

	flag.Var(&cfgDirs, "config.dirs", "The path to directories of configuration files, can be specified multiple times.")
	flag.Var(&acl, "allow.net", "Allow connection from this network specified in CIDR notation. Can be specified multiple times.")
	flag.Var(&logLevel, "log.level", "Log level")
}

func setup() (*config, error) {
	cfg := &config{
		Modules: make(map[string]*moduleConfig),
		XXX:     make(map[string]interface{}),
	}
	if *cfgFile != "" {
		r, err := os.Open(*cfgFile)
		if err != nil {
			return nil, err
		}
		defer r.Close()

		cfg, err = readConfig(r)
		if err != nil {
			return nil, err
		}
		for mn, _ := range cfg.Modules {
			log.Debugf("read module config '%s' from: %s", mn, *cfgFile)
		}
	}

cfgDirs:
	for _, cfgDir := range cfgDirs {
		mfs, err := ioutil.ReadDir(cfgDir)
		if err != nil {
			if *skipDirs && os.IsNotExist(err) {
				log.Warnf("skipping non existent config.dirs entry '%s'", cfgDir)
				continue cfgDirs
			}
			return nil, fmt.Errorf("failed reading directory: %s, %v", cfgDir, err)
		}

		yamlSuffixes := map[string]bool{
			".yml":  true,
			".yaml": true,
		}
		for _, mf := range mfs {
			fullpath := filepath.Join(cfgDir, mf.Name())
			if mf.IsDir() || !yamlSuffixes[filepath.Ext(mf.Name())] {
				log.Warnf("skipping non-yaml file %v", fullpath)
				continue
			}

			mn := strings.TrimSuffix(mf.Name(), filepath.Ext(mf.Name()))
			if _, ok := cfg.Modules[mn]; ok {
				return nil, fmt.Errorf("module %s is already defined", mn)
			}
			r, err := os.Open(fullpath)
			if err != nil {
				return nil, fmt.Errorf("failed to open config file %s, %w", fullpath, err)
			}
			defer r.Close()

			mcfg, err := readModuleConfig(mn, r)
			if err != nil {
				return nil, fmt.Errorf("failed reading configs %s, %w", fullpath, err)
			}

			log.Debugf("read module config '%s' from: %s", mn, fullpath)
			cfg.Modules[mn] = mcfg
		}
	}
	if len(cfg.Modules) == 0 {
		log.Errorln("no modules loaded from any config file")
	}

	if *bearerToken != "" {
		cfg.bearerToken = *bearerToken
	}

	if *bearerTokenFile != "" {
		if *bearerToken != "" {
			return nil, errors.New(("web.bearer.token and web.bearer.token-file are mutually exclusive options"))
		}
		bs, err := ioutil.ReadFile(*bearerTokenFile)
		if err != nil {
			return nil, fmt.Errorf("failed reading bearer file %s, %w", *bearerTokenFile, err)
		}

		t := strings.TrimSpace(string(bs))
		if len(t) == 0 {
			return nil, errors.New("token file should not be empty")
		}
		cfg.bearerToken = t
	}

	cfg.proxyPath = path.Clean("/" + *pPath)
	cfg.telemetryPath = path.Clean("/" + *tPath)
	if cfg.proxyPath == cfg.telemetryPath {
		return nil, fmt.Errorf("flags -web.proxy-path and -web.telemetry-path can not be set to the same value")
	}
	return cfg, nil
}

func getClientValidator(r *regexp.Regexp, helloInfo *tls.ClientHelloInfo) func([][]byte, [][]*x509.Certificate) error {
	return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
		for _, c := range verifiedChains {
			leaf := c[0]

			if r.MatchString(leaf.Subject.CommonName) {
				return nil
			}

			for _, name := range leaf.DNSNames {
				if r.MatchString(name) {
					return nil
				}
			}

			for _, name := range leaf.EmailAddresses {
				if r.MatchString(name) {
					return nil
				}
			}
		}
		return errors.New("no client certificate subject or email address matched")
	}
}
func setupTLS() (*tls.Config, error) {
	var tlsConfig *tls.Config
	if *tlsAddr == "" {
		return nil, nil
	}

	cert, err := tls.LoadX509KeyPair(*certPath, *keyPath)
	if err != nil {
		return nil, fmt.Errorf("Could not parse key/cert, %w", err)
	}

	tlsConfig = &tls.Config{
		Certificates: []tls.Certificate{cert},
		MinVersion:   tls.VersionTLS12,
		CipherSuites: []uint16{
			tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
			tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
			tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
			tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
			tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
		},
	}
	tlsConfig.BuildNameToCertificate()

	if *verify {
		pool := x509.NewCertPool()
		cabs, err := ioutil.ReadFile(*caPath)
		if err != nil {
			return nil, fmt.Errorf("Could not open ca file, %w", err)
		}
		ok := pool.AppendCertsFromPEM(cabs)
		if !ok {
			return nil, errors.New("Failed loading ca certs")
		}
		tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
		tlsConfig.ClientCAs = pool

		if *certMatch != "" {
			rx, err := regexp.Compile(*certMatch)
			if err != nil {
				return nil, fmt.Errorf("tls.web.certmatch is not a valid regexp, %w", err)
			}
			tlsConfig.GetConfigForClient = func(hi *tls.ClientHelloInfo) (*tls.Config, error) {
				serverConf := tlsConfig.Clone()
				serverConf.VerifyPeerCertificate = getClientValidator(rx, hi)
				return serverConf, nil
			}
		}
	} else {
		if *certMatch != "" {
			return nil, errors.New("tls.web.verify must be set to use certificate matching")
		}
	}

	return tlsConfig, nil
}

func runListener(ctx context.Context, name string, lsnr net.Listener, handler http.Handler) error {
	srvr := http.Server{
		Handler: handler,
	}
	go func() {
		<-ctx.Done()
		srvr.Shutdown(context.Background())
	}()

	if err := srvr.Serve(lsnr); err != nil {
		return fmt.Errorf("listener %s stopped, %w", name, err)
	}
	return nil
}

func main() {
	var err error
	defer func() {
		if err != nil {
			log.Errorln(err.Error())
			os.Exit(1)
		}
	}()

	flag.Parse()
	manageService()

	if *printVersion {
		fmt.Fprintf(os.Stderr, "Version: %s\n", versionStr())
		return
	}

	cfg, err := setup()
	if err != nil {
		return
	}
	tlsConfig, err := setupTLS()
	if err != nil {
		return
	}

	if *addr == "" && *tlsAddr == "" {
		log.Info("No web addresses to listen on, nothing to do!")
		os.Exit(0)
	}

	var lsnr net.Listener
	if *addr != "" {
		lsnr, err = net.Listen("tcp", *addr)
		if err != nil {
			return
		}
	}

	var tlsLsnr net.Listener
	if *tlsAddr != "" {
		tlsLsnr, err = net.Listen("tcp", *tlsAddr)
		if err != nil {
			return
		}

		tlsLsnr = tls.NewListener(tlsLsnr, tlsConfig)
	}

	http.HandleFunc(cfg.proxyPath, cfg.doProxy)
	http.HandleFunc("/", cfg.listModules)
	http.Handle(cfg.telemetryPath, promhttp.Handler())

	handler := http.Handler(http.DefaultServeMux)

	if cfg.bearerToken != "" {
		handler = &BearerAuthMiddleware{handler, cfg.bearerToken}
	}

	if len(acl) > 0 {
		log.Infof("Allowing connections only from %v", acl)
		handler = &IPAddressAuthMiddleware{handler, acl}
	}

	log.SetLevel(log.Level(logLevel))
	if *logJson {
		log.SetFormatter(&log.JSONFormatter{})
	}
	handler = &AccessLogMiddleware{handler}

	eg, ctx := errgroup.WithContext(context.Background())

	if lsnr != nil {
		eg.Go(func() error {
			return runListener(ctx, "http", lsnr, handler)
		})
	}

	if tlsLsnr != nil {
		eg.Go(func() error {
			return runListener(ctx, "https", tlsLsnr, handler)
		})
	}

	err = eg.Wait()
}

type responseWriterWithStatus struct {
	http.ResponseWriter
	status int
}

func (w *responseWriterWithStatus) WriteHeader(status int) {
	w.status = status
	w.ResponseWriter.WriteHeader(status)
}

type AccessLogMiddleware struct {
	http.Handler
}

func (middleware AccessLogMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var (
		start        = time.Now()
		statusWriter = &responseWriterWithStatus{w, http.StatusOK}
	)
	defer func() {
		remoteHost, _, _ := net.SplitHostPort(r.RemoteAddr)
		log.Infof(
			"%s - %s \"%s\" %d %s (took %s)",
			remoteHost, r.Method, r.URL.RequestURI(), statusWriter.status,
			http.StatusText(statusWriter.status), time.Now().Sub(start),
		)
	}()
	middleware.Handler.ServeHTTP(statusWriter, r)
}

func (cfg *config) doProxy(w http.ResponseWriter, r *http.Request) {
	mod, ok := r.URL.Query()["module"]
	if !ok {
		log.Errorf("no module given")
		http.Error(w, fmt.Sprintf("require parameter module is missing%v\n", mod), http.StatusBadRequest)
		return
	}

	log.Debugf("running module %v\n", mod)

	var h http.Handler
	if m, ok := cfg.Modules[mod[0]]; !ok {
		proxyErrorCount.WithLabelValues("unknown").Inc()
		log.Warnf("unknown module requested  %v\n", mod)
		http.Error(w, fmt.Sprintf("unknown module %v\n", mod), http.StatusNotFound)
		return
	} else {
		h = m
	}

	h.ServeHTTP(w, r)
}

func (cfg *config) listModules(w http.ResponseWriter, r *http.Request) {
	switch r.Header.Get("Accept") {
	case "application/json":
		log.Debugf("Listing modules in json")
		moduleJSON, err := json.Marshal(cfg.Modules)
		if err != nil {
			log.Error(err)
			http.Error(w, "Failed to produce JSON", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.Write(moduleJSON)
	default:
		log.Debugf("Listing modules in html")
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		tmpl := template.Must(template.New("modules").Parse(`
			<h2>Exporters:</h2>
				<ul>
					{{range $name, $cfg := .Modules}}
						<li><a href="/proxy?module={{$name}}">{{$name}}</a></li>
					{{end}}
				</ul>`))
		err := tmpl.Execute(w, cfg)
		if err != nil {
			log.Error(err)
			http.Error(w, "Can't execute the template", http.StatusInternalServerError)
		}
	}
	return
}

func (m moduleConfig) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	st := time.Now()
	defer func() {
		proxyDuration.WithLabelValues(m.name).Observe(float64(time.Since(st)) / float64(time.Second))
	}()

	nr := r
	cancel := func() {}
	if m.Timeout != 0 {
		log.Debugf("setting module %v timeout to %v", m.name, m.Timeout)

		var ctx context.Context
		ctx, cancel = context.WithTimeout(r.Context(), m.Timeout)
		nr = r.WithContext(ctx)
	}
	defer cancel()

	switch m.Method {
	case "exec":
		m.Exec.mcfg = &m
		m.Exec.ServeHTTP(w, nr)
	case "http":
		m.HTTP.mcfg = &m
		m.HTTP.ServeHTTP(w, nr)
	default:
		log.Errorf("unknown module method  %v\n", m.Method)
		proxyErrorCount.WithLabelValues(m.name).Inc()
		http.Error(w, fmt.Sprintf("unknown module method %v\n", m.Method), http.StatusNotFound)
		return
	}
}

// StringSliceFlags collects multiple uses of a named flag into a slice.
type StringSliceFlag []string

func (s *StringSliceFlag) String() string {
	// Just some representation output, not actually used to parse the input,
	// the flag is instead supposed to be specified multiple times.
	return strings.Join(*s, ", ")
}

func (s *StringSliceFlag) Set(value string) error {
	*s = append(*s, value)
	return nil
}

// IPNetSliceFlag parses IP network in CIDR notation into net.IPNet. Can be set
// multiple times
type IPNetSliceFlag []net.IPNet

func (nets IPNetSliceFlag) String() string {
	netsStr := make([]string, len(nets))
	for i := range nets {
		netsStr[i] = fmt.Sprint(nets[i].String())
	}
	return strings.Join(netsStr, ", ")
}

func (nets *IPNetSliceFlag) Set(value string) error {
	if _, net, err := net.ParseCIDR(value); err != nil {
		return err
	} else {
		*nets = append(*nets, *net)
	}
	return nil
}

type LogLevelFlag log.Level

func (level LogLevelFlag) String() string {
	return log.Level(level).String()
}

func (level *LogLevelFlag) Set(value string) error {
	if lvl, err := log.ParseLevel(value); err != nil {
		return err
	} else {
		*level = LogLevelFlag(lvl)
	}
	return nil
}
07070100000011000081A4000003E800000064000000015EB2C5B30000007A000000000000000000000000000000000000002300000000exporter_exporter-0.4.0/service.go// nothing to see here, service control only applies to Windows
// +build !windows

package main

func manageService() {}
07070100000012000081A4000003E800000064000000015EB2C5B300001610000000000000000000000000000000000000002B00000000exporter_exporter-0.4.0/service_windows.gopackage main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/prometheus/common/log"
	"golang.org/x/sys/windows/svc"
	"golang.org/x/sys/windows/svc/eventlog"
	"golang.org/x/sys/windows/svc/mgr"
)

var (
	winSvcCmd     = flag.String("winsvc", "", "install, uninstall, start, stop a Windows service")
	winSvcRunning = false
)

func manageService() {
	const winSvcName = "exporter_exporter"

	var err error

	switch *winSvcCmd {
	case "start":
		err = startService(winSvcName)
	case "install":
		err = installService(winSvcName, "Reverse proxy for Prometheus exporters")
	case "uninstall":
		err = uninstallService(winSvcName)
	case "stop":
		err = controlService(winSvcName, svc.Stop, svc.Stopped)
	case "":
		isIntSess, err := svc.IsAnInteractiveSession()
		if err != nil {
			log.Fatalf("Failed to determine if we are running in an interactive session: %v", err)
		}
		if !isIntSess {
			go runService(winSvcName)
			for {
				time.Sleep(time.Millisecond * 200)
				if winSvcRunning {
					break
				}
			}
		}
		return
	default:
		log.Fatalf("Unknown command '%v' for -winsvc", *winSvcCmd)
	}
	if err != nil {
		log.Fatalf("Failed to %s %s: %v", *winSvcCmd, winSvcName, err)
	}
	os.Exit(0)
}

func exePath() (string, error) {
	prog := os.Args[0]
	p, err := filepath.Abs(prog)
	if err != nil {
		return "", err
	}
	fi, err := os.Stat(p)
	if err == nil {
		if !fi.Mode().IsDir() {
			return p, nil
		}
		err = fmt.Errorf("%s is directory", p)
	}
	if filepath.Ext(p) == "" {
		p += ".exe"
		fi, err := os.Stat(p)
		if err == nil {
			if !fi.Mode().IsDir() {
				return p, nil
			}
			err = fmt.Errorf("%s is directory", p)
		}
	}
	return "", err
}

func installService(name, desc string) error {
	exepath, err := exePath()
	if err != nil {
		return fmt.Errorf("Unable to determine path of exe: %v", err)
	}
	var serviceArgs []string
	flag.Visit(func(f *flag.Flag) {
		if f.Name != "winsvc" {
			serviceArgs = append(serviceArgs, fmt.Sprintf("-%s", f.Name))
			if f.Value.String() != "true" {
				serviceArgs = append(serviceArgs, f.Value.String())
			}
		}
	})
	if len(serviceArgs) <= 0 {
		serviceArgs = append(serviceArgs, "-config.file", fmt.Sprintf("%s\\expexp.yaml", filepath.Dir(exepath)))
	}
	m, err := mgr.Connect()
	if err != nil {
		return fmt.Errorf("Failed while connecting to service control manager: %v", err)
	}
	defer m.Disconnect()
	s, err := m.OpenService(name)
	if err == nil {
		s.Close()
		return fmt.Errorf("Service with the name '%s' already exists", name)
	}
	s, err = m.CreateService(name, exepath, mgr.Config{DisplayName: name,
		StartType:   mgr.StartAutomatic,
		Description: desc}, serviceArgs...,
	)
	if err != nil {
		return fmt.Errorf("Failed while creating a new service: %v", err)
	}
	defer s.Close()
	err = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info)
	if err != nil {
		s.Delete()
		return fmt.Errorf("Failed while creating eventlog source: %v", err)
	}
	log.Infof("Installed service %s with args: %v", name, serviceArgs)
	return nil
}

func uninstallService(name string) error {
	controlService(name, svc.Stop, svc.Stopped)
	m, err := mgr.Connect()
	if err != nil {
		return err
	}
	defer m.Disconnect()
	s, err := m.OpenService(name)
	if err != nil {
		return fmt.Errorf("Failed while retrieving access to the service: %v", err)
	}
	defer s.Close()
	err = s.Delete()
	if err != nil {
		return err
	}
	err = eventlog.Remove(name)
	if err != nil {
		return fmt.Errorf("Failed while removing eventlog source: %v", err)
	}
	return nil
}

func startService(name string) error {
	m, err := mgr.Connect()
	if err != nil {
		return err
	}
	defer m.Disconnect()
	s, err := m.OpenService(name)
	if err != nil {
		return fmt.Errorf("Failed while retrieving access to the service: %v", err)
	}
	defer s.Close()
	err = s.Start()
	if err != nil {
		return fmt.Errorf("Failed while trying to start the service: %v", err)
	}
	return nil
}

func controlService(name string, c svc.Cmd, to svc.State) error {
	m, err := mgr.Connect()
	if err != nil {
		return err
	}
	defer m.Disconnect()
	s, err := m.OpenService(name)
	if err != nil {
		return fmt.Errorf("Failed while retrieving access to the service: %v", err)
	}
	defer s.Close()
	status, err := s.Control(c)
	if err != nil {
		return fmt.Errorf("Failed while sending control %d: %v", c, err)
	}
	timeout := time.Now().Add(35 * time.Second)
	for status.State != to {
		if timeout.Before(time.Now()) {
			return fmt.Errorf("Failed while waiting for the service to change state to %d", to)
		}
		time.Sleep(300 * time.Millisecond)
		status, err = s.Query()
		if err != nil {
			return fmt.Errorf("Failed while attempting to retrieve service status: %v", err)
		}
	}
	return nil
}

type exporterExporterService struct {
}

func (s *exporterExporterService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
	const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
	changes <- svc.Status{State: svc.StartPending}
	changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
	winSvcRunning = true

loop:
	for c := range r {
		switch c.Cmd {
		case svc.Interrogate:
			changes <- c.CurrentStatus
		case svc.Stop, svc.Shutdown:
			break loop
		default:
			log.Errorf("Unexpected control request #%d", c)
		}
	}
	changes <- svc.Status{State: svc.StopPending}
	return
}

func runService(name string) {
	log.Infof("Starting service %s %s", name, Version)
	err := svc.Run(name, &exporterExporterService{})
	if err != nil {
		log.Errorf("%s service failed: %v", name, err)
		return
	}
	log.Infof("%s service stopped", name)
	os.Exit(0)
}
07070100000013000081A4000003E800000064000000015EB2C5B300000050000000000000000000000000000000000000002100000000exporter_exporter-0.4.0/tools.go// +build never

package tools

import (
	_ "github.com/aktau/github-release"
)
07070100000014000081A4000003E800000064000000015EB2C5B30000031E000000000000000000000000000000000000002300000000exporter_exporter-0.4.0/version.gopackage main

import (
	"fmt"
	"runtime"

	"github.com/prometheus/client_golang/prometheus"
)

var (
	Version   = "unset"
	Revision  = "unset"
	Branch    = "unset"
	BuildUser = "unset"
	BuildDate = "unset"
	GoVersion = runtime.Version()
)

var (
	buildInfo = prometheus.NewGaugeVec(
		prometheus.GaugeOpts{
			Name: "build_info",
			Help: "A metric with a constant '1' value labeled by version, revision, branch and goversion from which exporter_exporter was built.",
		},
		[]string{"version", "revision", "branch", "goversion"},
	)
)

func init() {
	prometheus.MustRegister(buildInfo)
	buildInfo.WithLabelValues(Version, Revision, Branch, GoVersion).Set(1)
}

func versionStr() string {
	return fmt.Sprintf("%s-%s (from %s, built by %s on %s)", Version, Revision, Branch, BuildUser, BuildDate)
}
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!147 blocks
openSUSE Build Service is sponsored by