├── .gitignore ├── Dockerfile ├── go.mod ├── Makefile ├── CHANGELOG.md ├── README.md ├── go.sum ├── internal ├── puppetdb │ └── puppetdb.go └── exporter │ └── exporter.go ├── main.go └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | prometheus-puppetdb-exporter 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.12 as builder 2 | WORKDIR /go/src/github.com/camptocamp/prometheus-puppetdb-exporter 3 | COPY . . 4 | RUN make prometheus-puppetdb-exporter 5 | 6 | FROM scratch 7 | COPY --from=builder /go/src/github.com/camptocamp/prometheus-puppetdb-exporter/prometheus-puppetdb-exporter / 8 | ENTRYPOINT ["/prometheus-puppetdb-exporter"] 9 | CMD [""] 10 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/camptocamp/prometheus-puppetdb-exporter 2 | 3 | go 1.15 4 | 5 | require ( 6 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 // indirect 7 | github.com/golang/protobuf v1.2.0 // indirect 8 | github.com/jessevdk/go-flags v1.4.0 9 | github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect 10 | github.com/prometheus/client_golang v0.8.0 11 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 // indirect 12 | github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e // indirect 13 | github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273 // indirect 14 | github.com/sirupsen/logrus v1.3.0 15 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 // indirect 16 | golang.org/x/sync v0.0.0-20190423024810-112230192c58 // indirect 17 | ) 18 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | DEPS = $(wildcard */*.go) 2 | VERSION = $(shell git describe --always --dirty) 3 | COMMIT_SHA1 = $(shell git rev-parse HEAD) 4 | BUILD_DATE = $(shell date +%Y-%m-%d) 5 | GOOS = linux 6 | ARCH = amd64 7 | 8 | all: lint vet prometheus-puppetdb-exporter 9 | 10 | prometheus-puppetdb-exporter: main.go $(DEPS) 11 | GO111MODULE=on CGO_ENABLED=0 GOOS=$(GOOS) \ 12 | go build -a \ 13 | -ldflags="-X main.version=$(VERSION) -X main.commitSha1=$(COMMIT_SHA1) -X main.buildDate=$(BUILD_DATE)" \ 14 | -installsuffix cgo -o $@ $< 15 | strip $@ 16 | 17 | release: prometheus-puppetdb-exporter-$(VERSION).$(GOOS)-$(ARCH).tar.gz 18 | 19 | %.tar.gz: prometheus-puppetdb-exporter LICENSE 20 | tar cvzf $@ --transform 's,^,$*/,' $^ 21 | 22 | clean: 23 | rm -f prometheus-puppetdb-exporter 24 | 25 | lint: 26 | @GO111MODULE=off go get -v golang.org/x/lint/golint 27 | @for file in $$(git ls-files '*.go' | grep -v '_workspace/'); do \ 28 | export output="$$(golint $${file} | grep -v 'type name will be used as docker.DockerInfo')"; \ 29 | [ -n "$${output}" ] && echo "$${output}" && export status=1; \ 30 | done; \ 31 | exit $${status:-0} 32 | 33 | vet: main.go 34 | go vet $< 35 | 36 | .PHONY: all lint vet clean 37 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [1.1.0](https://github.com/camptocamp/prometheus-puppetdb-exporter/tree/1.1.0) (2020-12-03) 4 | 5 | [Full Changelog](https://github.com/camptocamp/prometheus-puppetdb-exporter/compare/1.0.0...1.1.0) 6 | 7 | **Closed issues:** 8 | 9 | - Deactivated nodes still appear [\#8](https://github.com/camptocamp/prometheus-puppetdb-exporter/issues/8) 10 | 11 | **Improvements:** 12 | 13 | - Remove legacy `vendor/` directory 14 | 15 | ## [1.0.0](https://github.com/camptocamp/prometheus-puppetdb-exporter/tree/1.0.0) (2020-06-09) 16 | 17 | [Full Changelog](https://github.com/camptocamp/prometheus-puppetdb-exporter/compare/0.1.0...1.0.0) 18 | 19 | **Breaking changes:** 20 | 21 | - Switch port to 9635 [\#5](https://github.com/camptocamp/prometheus-puppetdb-exporter/pull/5) ([bastelfreak](https://github.com/bastelfreak)) 22 | 23 | ## [0.1.0](https://github.com/camptocamp/prometheus-puppetdb-exporter/tree/0.1.0) (2020-06-08) 24 | 25 | [Full Changelog](https://github.com/camptocamp/prometheus-puppetdb-exporter/compare/8499b362f2f346f1ce58a60d5299d0de628556aa...0.1.0) 26 | 27 | **Closed issues:** 28 | 29 | - No nodes exist? [\#3](https://github.com/camptocamp/prometheus-puppetdb-exporter/issues/3) 30 | - Report nodes as "unreported" if last report is more that 2 hours old [\#1](https://github.com/camptocamp/prometheus-puppetdb-exporter/issues/1) 31 | 32 | **Merged pull requests:** 33 | 34 | - Allow to select report metrics categories to scrape [\#2](https://github.com/camptocamp/prometheus-puppetdb-exporter/pull/2) ([mcanevet](https://github.com/mcanevet)) 35 | 36 | 37 | 38 | \* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)* 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Prometheus PuppetDB exporter 2 | ============================ 3 | 4 | ## Usage 5 | 6 | ``` 7 | Usage: 8 | prometheus-puppetdb-exporter [OPTIONS] 9 | 10 | Application Options: 11 | --version Show version. 12 | -u, --puppetdb-url= PuppetDB base URL. (default: https://puppetdb:8081/pdb/query) [$PUPPETDB_URL] 13 | --cert-file= A PEM encoded certificate file. [$PUPPETDB_CERT_FILE] 14 | --key-file= A PEM encoded private key file. [$PUPPETDB_KEY_FILE] 15 | --ca-file= A PEM encoded CA's certificate. [$PUPPETDB_CA_FILE] 16 | --ssl-skip-verify Skip SSL verification. [$PUPPETDB_SSL_SKIP_VERIFY] 17 | --scrape-interval= Duration between two scrapes. (default: 5s) [$PUPPETDB_SCRAPE_INTERVAL] 18 | --listen-address= Address to listen on for web interface and telemetry. (default: 0.0.0.0:9635) 19 | [$PUPPETDB_LISTEN_ADDRESS] 20 | --metric-path= Path under which to expose metrics. (default: /metrics) [$PUPPETDB_METRIC_PATH] 21 | --verbose Enable debug mode [$PUPPETDB_VERBOSE] 22 | --unreported-node= Tag nodes as unreported if the latest report is older than the defined duration. 23 | (default: 2h) [$PUPPETDB_UNREPORTED_NODE] 24 | --categories= Report metrics categories to scrape. (default: resources,time,changes,events) 25 | [$REPORT_METRICS_CATEGORIES] 26 | 27 | Help Options: 28 | -h, --help Show this help message 29 | ``` 30 | 31 | ## Metrics 32 | 33 | ``` 34 | # HELP puppetdb_exporter_build_info puppetdb exporter build informations 35 | # TYPE puppetdb_exporter_build_info gauge 36 | puppetdb_exporter_build_info{build_date="2019-02-18",commit_sha="XXXXXXXXXX",golang_version="go1.11.4",version="1.0.0"} 1 37 | # HELP puppetdb_node_report_status_count Total count of reports status by type 38 | # TYPE puppetdb_node_report_status_count gauge 39 | puppetdb_node_report_status_count{status="changed"} 1 40 | puppetdb_node_report_status_count{status="failed"} 1 41 | puppetdb_node_report_status_count{status="unchanged"} 1 42 | ``` 43 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLMYoU8P317H5OQ+Via4RmuPwCS0= 2 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 3 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 4 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= 6 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 7 | github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA= 8 | github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= 9 | github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= 10 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 11 | github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= 12 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 13 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 14 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 15 | github.com/prometheus/client_golang v0.8.0 h1:1921Yw9Gc3iSc4VQh3PIoOqgPCZS7G/4xQNVUp8Mda8= 16 | github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= 17 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 h1:idejC8f05m9MGOsuEi1ATq9shN03HrxNkD/luQvxCv8= 18 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 19 | github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e h1:n/3MEhJQjQxrOUCzh1Y3Re6aJUUWRp2M9+Oc3eVn/54= 20 | github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= 21 | github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273 h1:agujYaXJSxSo18YNX3jzl+4G6Bstwt+kqv47GS12uL0= 22 | github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 23 | github.com/sirupsen/logrus v1.3.0 h1:hI/7Q+DtNZ2kINb6qt/lS+IyXnHQe9e90POfeewL/ME= 24 | github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= 25 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 26 | github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= 27 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 28 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 29 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 30 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8= 31 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 32 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 33 | golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU= 34 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 35 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 36 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 37 | golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI= 38 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 39 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 40 | -------------------------------------------------------------------------------- /internal/puppetdb/puppetdb.go: -------------------------------------------------------------------------------- 1 | package puppetdb 2 | 3 | import ( 4 | "crypto/tls" 5 | "crypto/x509" 6 | "encoding/json" 7 | "fmt" 8 | "io/ioutil" 9 | "net/http" 10 | "net/url" 11 | "strings" 12 | ) 13 | 14 | // PuppetDB stores informations used to connect to a PuppetDB 15 | type PuppetDB struct { 16 | options *Options 17 | client *http.Client 18 | } 19 | 20 | // Options contains the options used to connect to a PuppetDB 21 | type Options struct { 22 | URL string 23 | CertPath string 24 | CACertPath string 25 | KeyPath string 26 | SSLVerify bool 27 | } 28 | 29 | // Node is a structure returned by a PuppetDB 30 | type Node struct { 31 | Certname string `json:"certname"` 32 | Deactivated string `json:"deactivated"` 33 | LatestReportStatus string `json:"latest_report_status"` 34 | ReportEnvironment string `json:"report_environment"` 35 | ReportTimestamp string `json:"report_timestamp"` 36 | LatestReportHash string `json:"latest_report_hash"` 37 | } 38 | 39 | // ReportMetric is a structure returned by a PuppetDB 40 | type ReportMetric struct { 41 | Name string `json:"name"` 42 | Value float64 `json:"value"` 43 | Category string `json:"category"` 44 | } 45 | 46 | // NewClient creates a new PuppetDB client 47 | func NewClient(options *Options) (p *PuppetDB, err error) { 48 | var transport *http.Transport 49 | 50 | puppetdbURL, err := url.Parse(options.URL) 51 | if err != nil { 52 | err = fmt.Errorf("failed to parse PuppetDB URL: %v", err) 53 | return 54 | } 55 | 56 | if puppetdbURL.Scheme != "http" && puppetdbURL.Scheme != "https" { 57 | err = fmt.Errorf("%s is not a valid http scheme", puppetdbURL.Scheme) 58 | return 59 | } 60 | 61 | if puppetdbURL.Scheme == "https" { 62 | // Load client cert 63 | cert, err := tls.LoadX509KeyPair(options.CertPath, options.KeyPath) 64 | if err != nil { 65 | err = fmt.Errorf("failed to load keypair: %s", err) 66 | return nil, err 67 | } 68 | 69 | // Load CA cert 70 | caCert, err := ioutil.ReadFile(options.CACertPath) 71 | if err != nil { 72 | err = fmt.Errorf("failed to load ca certificate: %s", err) 73 | return nil, err 74 | } 75 | caCertPool := x509.NewCertPool() 76 | caCertPool.AppendCertsFromPEM(caCert) 77 | 78 | // Setup HTTPS client 79 | tlsConfig := &tls.Config{ 80 | Certificates: []tls.Certificate{cert}, 81 | RootCAs: caCertPool, 82 | InsecureSkipVerify: !options.SSLVerify, 83 | } 84 | tlsConfig.BuildNameToCertificate() 85 | transport = &http.Transport{TLSClientConfig: tlsConfig} 86 | } else { 87 | transport = &http.Transport{} 88 | } 89 | 90 | p = &PuppetDB{ 91 | client: &http.Client{Transport: transport}, 92 | options: options, 93 | } 94 | return 95 | } 96 | 97 | // Nodes returns the list of nodes 98 | func (p *PuppetDB) Nodes() (nodes []Node, err error) { 99 | err = p.get("nodes", "[\"or\", [\"=\", [\"node\", \"active\"], false], [\"=\", [\"node\", \"active\"], true]]", &nodes) 100 | if err != nil { 101 | err = fmt.Errorf("failed to get nodes: %s", err) 102 | return 103 | } 104 | return 105 | } 106 | 107 | // ReportMetrics returns the list of reportMetrics 108 | func (p *PuppetDB) ReportMetrics(reportHash string) (reportMetrics []ReportMetric, err error) { 109 | err = p.get(fmt.Sprintf("reports/%s/metrics", reportHash), "", &reportMetrics) 110 | if err != nil { 111 | err = fmt.Errorf("failed to get reports: %s", err) 112 | return 113 | } 114 | return 115 | } 116 | 117 | func (p *PuppetDB) get(endpoint string, query string, object interface{}) (err error) { 118 | base := strings.TrimRight(p.options.URL, "/") 119 | var myurl string 120 | if query == "" { 121 | myurl = fmt.Sprintf("%s/v4/%s", base, endpoint) 122 | } else { 123 | myurl = fmt.Sprintf("%s/v4/%s?query=%s", base, endpoint, url.QueryEscape(query)) 124 | } 125 | req, err := http.NewRequest("GET", myurl, strings.NewReader("")) 126 | if err != nil { 127 | err = fmt.Errorf("failed to build request: %s", err) 128 | return 129 | } 130 | resp, err := p.client.Do(req) 131 | if err != nil { 132 | err = fmt.Errorf("failed to call API: %s", err) 133 | return 134 | } 135 | defer resp.Body.Close() 136 | 137 | body, err := ioutil.ReadAll(resp.Body) 138 | if err != nil { 139 | err = fmt.Errorf("failed to read response: %s", err) 140 | return 141 | } 142 | err = json.Unmarshal(body, object) 143 | if err != nil { 144 | err = fmt.Errorf("failed to unmarshal: %s", err) 145 | return 146 | } 147 | return 148 | } 149 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | "os" 6 | "runtime" 7 | "strings" 8 | "time" 9 | 10 | "github.com/jessevdk/go-flags" 11 | "github.com/prometheus/client_golang/prometheus" 12 | "github.com/prometheus/client_golang/prometheus/promhttp" 13 | log "github.com/sirupsen/logrus" 14 | 15 | "github.com/camptocamp/prometheus-puppetdb-exporter/internal/exporter" 16 | ) 17 | 18 | // Config stores handler's configuration 19 | type Config struct { 20 | Version bool `long:"version" description:"Show version."` 21 | PuppetDBUrl string `short:"u" long:"puppetdb-url" description:"PuppetDB base URL." env:"PUPPETDB_URL" required:"true" default:"https://puppetdb:8081/pdb/query"` 22 | CertFile string `long:"cert-file" description:"A PEM encoded certificate file." env:"PUPPETDB_CERT_FILE"` 23 | KeyFile string `long:"key-file" description:"A PEM encoded private key file." env:"PUPPETDB_KEY_FILE"` 24 | CACertFile string `long:"ca-file" description:"A PEM encoded CA's certificate." env:"PUPPETDB_CA_FILE"` 25 | SSLSkipVerify bool `long:"ssl-skip-verify" description:"Skip SSL verification." env:"PUPPETDB_SSL_SKIP_VERIFY"` 26 | ScrapeInterval string `long:"scrape-interval" description:"Duration between two scrapes." env:"PUPPETDB_SCRAPE_INTERVAL" default:"5s"` 27 | ListenAddress string `long:"listen-address" description:"Address to listen on for web interface and telemetry." env:"PUPPETDB_LISTEN_ADDRESS" default:"0.0.0.0:9635"` 28 | MetricPath string `long:"metric-path" description:"Path under which to expose metrics." env:"PUPPETDB_METRIC_PATH" default:"/metrics"` 29 | Verbose bool `long:"verbose" description:"Enable debug mode" env:"PUPPETDB_VERBOSE"` 30 | UnreportedNode string `long:"unreported-node" description:"Tag nodes as unreported if the latest report is older than the defined duration." env:"PUPPETDB_UNREPORTED_NODE" default:"2h"` 31 | Categories string `long:"categories" description:"Report metrics categories to scrape." env:"REPORT_METRICS_CATEGORIES" default:"resources,time,changes,events"` 32 | } 33 | 34 | var ( 35 | // VERSION, BUILD_DATE, GIT_COMMIT are filled in by the build script 36 | version = "<<< filled in by build >>>" 37 | buildDate = "<<< filled in by build >>>" 38 | commitSha1 = "<<< filled in by build >>>" 39 | ) 40 | 41 | func main() { 42 | var c Config 43 | parser := flags.NewParser(&c, flags.Default) 44 | if _, err := parser.Parse(); err != nil { 45 | if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp { 46 | os.Exit(0) 47 | } else { 48 | os.Exit(1) 49 | } 50 | } 51 | 52 | log.Printf("PuppetDB Metrics Exporter %s build date: %s sha1: %s Go: %s", 53 | version, buildDate, commitSha1, 54 | runtime.Version(), 55 | ) 56 | if c.Verbose { 57 | log.SetLevel(log.DebugLevel) 58 | log.Debugln("Enabling debug output") 59 | } else { 60 | log.SetLevel(log.InfoLevel) 61 | } 62 | 63 | if c.Version { 64 | return 65 | } 66 | 67 | interval, err := time.ParseDuration(c.ScrapeInterval) 68 | if err != nil { 69 | log.Fatalf("failed to parse scrape interval duration: %s", err) 70 | } 71 | 72 | // Create a map[string]struct{} of categories to provide an efficient way to 73 | // find if a category exists in the list of categories. 74 | cats := strings.Split(c.Categories, ",") 75 | categories := make(map[string]struct{}, len(cats)) 76 | for _, category := range cats { 77 | categories[category] = struct{}{} 78 | } 79 | exp, err := exporter.NewPuppetDBExporter(c.PuppetDBUrl, c.CertFile, c.CACertFile, c.KeyFile, c.SSLSkipVerify, categories) 80 | if err != nil { 81 | log.Fatalf("failed to initialize exporter: %s", err) 82 | } 83 | 84 | go exp.Scrape(interval, c.UnreportedNode, categories) 85 | 86 | buildInfo := prometheus.NewGaugeVec(prometheus.GaugeOpts{ 87 | Name: "puppetdb_exporter_build_info", 88 | Help: "puppetdb exporter build informations", 89 | }, []string{"version", "commit_sha", "build_date", "golang_version"}) 90 | buildInfo.WithLabelValues(version, commitSha1, buildDate, runtime.Version()).Set(1) 91 | prometheus.MustRegister(buildInfo) 92 | 93 | http.Handle(c.MetricPath, promhttp.Handler()) 94 | http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 95 | w.Write([]byte(` 96 | 97 | Prometheus PuppetDB Exporter v` + version + ` 98 | 99 |

Prometheus PuppetDB Exporter ` + version + `

100 |

Metrics

101 | 102 | 103 | `)) 104 | }) 105 | 106 | log.Infof("Providing metrics at %s%s", c.ListenAddress, c.MetricPath) 107 | log.Fatal(http.ListenAndServe(c.ListenAddress, nil)) 108 | } 109 | -------------------------------------------------------------------------------- /internal/exporter/exporter.go: -------------------------------------------------------------------------------- 1 | package exporter 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "time" 7 | 8 | "github.com/prometheus/client_golang/prometheus" 9 | log "github.com/sirupsen/logrus" 10 | 11 | "github.com/camptocamp/prometheus-puppetdb-exporter/internal/puppetdb" 12 | ) 13 | 14 | // Exporter implements the prometheus.Exporter interface, and exports PuppetDB metrics 15 | type Exporter struct { 16 | client *puppetdb.PuppetDB 17 | namespace string 18 | metrics map[string]*prometheus.GaugeVec 19 | } 20 | 21 | var ( 22 | metricMap = map[string]string{ 23 | "node_status_count": "node_status_count", 24 | } 25 | ) 26 | 27 | // NewPuppetDBExporter returns a new exporter of PuppetDB metrics. 28 | func NewPuppetDBExporter(url, certPath, caPath, keyPath string, sslSkipVerify bool, categories map[string]struct{}) (e *Exporter, err error) { 29 | e = &Exporter{ 30 | namespace: "puppetdb", 31 | } 32 | 33 | opts := &puppetdb.Options{ 34 | URL: url, 35 | CertPath: certPath, 36 | CACertPath: caPath, 37 | KeyPath: keyPath, 38 | SSLVerify: sslSkipVerify, 39 | } 40 | 41 | e.client, err = puppetdb.NewClient(opts) 42 | if err != nil { 43 | log.Fatalf("failed to create new client: %s", err) 44 | return 45 | } 46 | 47 | e.initGauges(categories) 48 | 49 | return 50 | } 51 | 52 | // Describe outputs PuppetDB metric descriptions 53 | func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { 54 | for _, m := range e.metrics { 55 | m.Describe(ch) 56 | } 57 | } 58 | 59 | // Collect fetches new metrics from the PuppetDB and updates the appropriate metrics 60 | func (e *Exporter) Collect(ch chan<- prometheus.Metric) { 61 | for _, m := range e.metrics { 62 | m.Collect(ch) 63 | } 64 | } 65 | 66 | // Scrape scrapes PuppetDB and update metrics 67 | func (e *Exporter) Scrape(interval time.Duration, unreportedNode string, categories map[string]struct{}) { 68 | var statuses map[string]int 69 | 70 | unreportedDuration, err := time.ParseDuration(unreportedNode) 71 | if err != nil { 72 | log.Errorf("failed to parse unreported duration: %s", err) 73 | return 74 | } 75 | 76 | for { 77 | statuses = make(map[string]int) 78 | 79 | nodes, err := e.client.Nodes() 80 | if err != nil { 81 | log.Errorf("failed to get nodes: %s", err) 82 | } 83 | 84 | e.metrics["report"].Reset() 85 | e.metrics["node_report_status_count"].Reset() 86 | 87 | for _, node := range nodes { 88 | var deactivated string 89 | if node.Deactivated == "" { 90 | deactivated = "false" 91 | } else { 92 | deactivated = "true" 93 | } 94 | 95 | if node.ReportTimestamp == "" { 96 | if deactivated == "false" { 97 | statuses["unreported"]++ 98 | } 99 | continue 100 | } 101 | latestReport, err := time.Parse("2006-01-02T15:04:05Z", node.ReportTimestamp) 102 | if err != nil { 103 | if deactivated == "false" { 104 | statuses["unreported"]++ 105 | } 106 | log.Errorf("failed to parse report timestamp: %s", err) 107 | continue 108 | } 109 | e.metrics["report"].With(prometheus.Labels{"environment": node.ReportEnvironment, "host": node.Certname, "deactivated": deactivated}).Set(float64(latestReport.Unix())) 110 | 111 | if deactivated == "false" { 112 | if latestReport.Add(unreportedDuration).Before(time.Now()) { 113 | statuses["unreported"]++ 114 | } else if node.LatestReportStatus == "" { 115 | statuses["unreported"]++ 116 | } else { 117 | statuses[node.LatestReportStatus]++ 118 | } 119 | } 120 | 121 | if node.LatestReportHash != "" { 122 | reportMetrics, _ := e.client.ReportMetrics(node.LatestReportHash) 123 | for _, reportMetric := range reportMetrics { 124 | _, ok := categories[reportMetric.Category] 125 | if ok { 126 | category := fmt.Sprintf("report_%s", reportMetric.Category) 127 | e.metrics[category].With(prometheus.Labels{"name": strings.ReplaceAll(strings.Title(reportMetric.Name), "_", " "), "environment": node.ReportEnvironment, "host": node.Certname}).Set(reportMetric.Value) 128 | } 129 | } 130 | } 131 | } 132 | 133 | for statusName, statusValue := range statuses { 134 | e.metrics["node_report_status_count"].With(prometheus.Labels{"status": statusName}).Set(float64(statusValue)) 135 | } 136 | 137 | time.Sleep(interval) 138 | } 139 | } 140 | 141 | func (e *Exporter) initGauges(categories map[string]struct{}) { 142 | e.metrics = map[string]*prometheus.GaugeVec{} 143 | 144 | e.metrics["node_report_status_count"] = prometheus.NewGaugeVec(prometheus.GaugeOpts{ 145 | Namespace: e.namespace, 146 | Name: "node_report_status_count", 147 | Help: "Total count of reports status by type", 148 | }, []string{"status"}) 149 | 150 | for category := range categories { 151 | metricName := fmt.Sprintf("report_%s", category) 152 | e.metrics[metricName] = prometheus.NewGaugeVec(prometheus.GaugeOpts{ 153 | Namespace: "puppet", 154 | Name: metricName, 155 | Help: fmt.Sprintf("Total count of %s per status", category), 156 | }, []string{"name", "environment", "host"}) 157 | 158 | } 159 | 160 | e.metrics["report"] = prometheus.NewGaugeVec(prometheus.GaugeOpts{ 161 | Namespace: "puppet", 162 | Name: "report", 163 | Help: "Timestamp of latest report", 164 | }, []string{"environment", "host", "deactivated"}) 165 | 166 | for _, m := range e.metrics { 167 | prometheus.MustRegister(m) 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------