├── .github ├── dependabot.yml └── workflows │ ├── integration.yaml │ ├── release.yml │ └── test.yaml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── contrib ├── README.md ├── unbound-cert-setup.sh └── unbound_exporter.service ├── docker-compose.yml ├── droplist.zone ├── go.mod ├── go.sum ├── integration_test.go ├── nfpm.yaml ├── unbound-example.conf ├── unbound_exporter.go └── unbound_exporter_test.go /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "go" 4 | directory: "/" 5 | schedule: 6 | interval: "monthly" 7 | - package-ecosystem: "github-actions" 8 | directory: "/" 9 | schedule: 10 | interval: "monthly" 11 | -------------------------------------------------------------------------------- /.github/workflows/integration.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | name: integration 3 | 4 | on: 5 | push: 6 | branches: 7 | - main 8 | pull_request: 9 | workflow_dispatch: 10 | 11 | jobs: 12 | integration: 13 | runs-on: [ubuntu-latest] 14 | steps: 15 | - name: Install Go 16 | uses: actions/setup-go@v4 17 | with: 18 | go-version: "1.21.x" 19 | - name: checkout 20 | uses: actions/checkout@v4 21 | - name: Start containers 22 | run: docker compose up --build --detach 23 | - name: run integration test 24 | run: go test -v --tags=integration 25 | - name: Stop containers 26 | if: always() 27 | run: docker compose down 28 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Build and release 2 | on: 3 | # Runs automatically when a tag beginning with 'v' (i.e. a versioned release) is pushed. 4 | push: 5 | tags: 6 | - v* 7 | branches: [main] 8 | pull_request: 9 | branches: [main] 10 | 11 | jobs: 12 | build-release: 13 | runs-on: ubuntu-20.04 14 | permissions: 15 | contents: read 16 | steps: 17 | - uses: actions/setup-go@v4 18 | with: 19 | go-version: '1.21.4' 20 | 21 | - uses: actions/checkout@v4 22 | with: 23 | persist-credentials: false 24 | 25 | - name: build binary 26 | run: go build 27 | 28 | - name: install nfpm 29 | run: go install github.com/goreleaser/nfpm/v2/cmd/nfpm@v2.15.1 30 | 31 | - name: build deb 32 | run: nfpm package -p deb -t unbound_exporter.deb 33 | 34 | - name: upload deb 35 | uses: actions/upload-artifact@v3 36 | with: 37 | name: unbound_exporter deb artifact 38 | path: unbound_exporter.deb 39 | 40 | push-release: 41 | if: github.event_name == 'push' && contains(github.ref, 'refs/tags/') 42 | needs: build-release 43 | runs-on: ubuntu-20.04 44 | # Overrides the org default of 'read'. This allows us to upload and post the 45 | # resulting package file as part of a release. 46 | permissions: 47 | contents: write 48 | steps: 49 | - uses: actions/checkout@v2 50 | with: 51 | persist-credentials: false 52 | 53 | - name: Download release artifact 54 | uses: actions/download-artifact@v3 55 | with: 56 | name: unbound_exporter deb artifact 57 | 58 | - name: rename 59 | run: mv unbound_exporter.deb unbound_exporter-${GITHUB_REF_NAME}.x86_64.deb 60 | 61 | - name: push release 62 | env: 63 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 64 | # https://cli.github.com/manual/gh_release_create 65 | run: gh release create "${GITHUB_REF_NAME}" unbound_exporter-${GITHUB_REF_NAME}.x86_64.deb 66 | -------------------------------------------------------------------------------- /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - master 8 | pull_request: 9 | workflow_dispatch: 10 | 11 | env: 12 | GO111MODULE: "auto" 13 | 14 | jobs: 15 | test: 16 | strategy: 17 | matrix: 18 | go-version: 19 | - 1.20.x 20 | - 1.21.x 21 | os: [ubuntu-latest] 22 | runs-on: ${{ matrix.os }} 23 | steps: 24 | - name: Install Go 25 | uses: actions/setup-go@v4 26 | with: 27 | go-version: ${{ matrix.go-version }} 28 | - name: Checkout code 29 | uses: actions/checkout@v4 30 | - name: golangci-lint 31 | uses: golangci/golangci-lint-action@v2 32 | with: 33 | version: latest 34 | - name: go coverage 35 | run: | 36 | go test -mod=readonly -v -race -covermode=atomic -coverprofile=coverage.out ./... 37 | - uses: codecov/codecov-action@v3 38 | if: success() 39 | with: 40 | file: ./coverage.out 41 | flags: unbound_exporter_tests 42 | name: unbound_exporter tests 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | unbound_exporter 2 | .idea/ 3 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM --platform=$BUILDPLATFORM docker.io/library/golang:1.21.4-bookworm AS build 2 | 3 | WORKDIR /go/src/app 4 | 5 | COPY go.mod . 6 | COPY go.sum . 7 | 8 | RUN go mod download 9 | 10 | COPY *.go . 11 | 12 | ENV CGO_ENABLED=0 13 | 14 | RUN GOOS=$TARGETOS GOARCH=$TARGETPLATFORM go build -v -o /go/bin/unbound_exporter ./... 15 | 16 | FROM gcr.io/distroless/static-debian12 17 | 18 | COPY --from=build /go/bin/unbound_exporter / 19 | 20 | ENTRYPOINT ["/unbound_exporter"] 21 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Prometheus Unbound exporter 2 | 3 | This repository provides code for a simple Prometheus metrics exporter 4 | for [the Unbound DNS resolver](https://unbound.net/). This exporter 5 | connects to Unbounds TLS control socket and sends the `stats_noreset` 6 | command, causing Unbound to return metrics as key-value pairs. The 7 | metrics exporter converts Unbound metric names to Prometheus metric 8 | names and labels by using a set of regular expressions. 9 | 10 | - - - - 11 | 12 | # Prerequisites 13 | 14 | Go 1.20 or above is required. 15 | 16 | # Installation 17 | 18 | go install github.com/letsencrypt/unbound_exporter@latest 19 | 20 | This will install the binary in `$GOBIN`, or `$HOME/go/bin` if 21 | `$GOBIN` is unset. 22 | 23 | # Updating dependencies 24 | 25 | ``` 26 | go get -u 27 | go mod tidy 28 | ``` 29 | 30 | - - - - 31 | 32 | # Usage - Unix socket 33 | 34 | The simplest way to run unbound_exporter is on the same machine as your Unbound instance, connecting via a Unix socket. First, make sure you have this in your unbound.conf: 35 | 36 | remote-control: 37 | control-enable: yes 38 | control-interface: /run/unbound.ctl 39 | 40 | Then, arrange to run this on the same machine: 41 | 42 | unbound_exporter -unbound.ca "" -unbound.cert "" -unbound.host "unix:///run/unbound.ctl" 43 | 44 | Metrics will be exported under /metrics, on port 9167, on all interfaces. 45 | 46 | $ curl 127.0.0.1:9167/metrics | grep '^unbound_up' 47 | unbound_up 1 48 | 49 | # Usage - TLS 50 | 51 | The more complicated way to run unbound_exporter is to configure unbound's control-interface with a TLS certificate from a private CA, and run unbound_exporter on a separate host. This is more of a hassle because you have to keep the certificate up to date and distribute the private CA to the host that unbound_exporter runs on. 52 | 53 | See https://unbound.docs.nlnetlabs.nl/en/latest/getting-started/configuration.html#set-up-remote-control for instructions on setting up the certificates and keys for remote-control via TLS. On the unbound_exporter side you will need to set the `-unbound.ca`, `-unbound.cert`, and `-unbound.key` flags to point to valid files that will trust the Unbound server's certificate and be trusted by Unbound in return. 54 | 55 | # Extended statistics 56 | 57 | From the Unbound [statistics doc](https://www.nlnetlabs.nl/documentation/unbound/howto-statistics/): Unbound has an option to enable extended statistics collection. If enabled, more statistics are collected, for example what types of queries are sent to the resolver. Otherwise, only the total number of queries is collected. Add the following to your `unbound.conf`. 58 | 59 | server: 60 | extended-statistics: yes 61 | 62 | -------------------------------------------------------------------------------- /contrib/README.md: -------------------------------------------------------------------------------- 1 | # Contrib 2 | This collection of scripts and files helps us further configure our unbounds and unbound_exporters. 3 | 4 | ## unbound-control-setup.sh 5 | 6 | From [Golang 1.15 docs:](https://golang.google.cn/doc/go1.15#commonname) 7 | > X.509 CommonName deprecation 8 | > The deprecated, legacy behavior of treating the CommonName field on X.509 certificates as a host name when no Subject Alternative Names are present is now disabled by default. It can be temporarily re-enabled by adding the value x509ignoreCN=0 to the GODEBUG environment variable. 9 | > Note that if the CommonName is an invalid host name, it's always ignored, regardless of GODEBUG settings. Invalid names include those with any characters other than letters, digits, hyphens and underscores, and those with empty labels or trailing dots. 10 | 11 | Unbound still ships with an `unbound-control-setup` that generates a problematic keypair. This script will generate a keypair that satisfies newer versions of Golang. 12 | 13 | Generate the new keypair 14 | ``` 15 | $ bash unbound-control-setup.sh 16 | ``` 17 | 18 | You'll then want to configure `/etc/unbound/unbound.conf` with the following stanza 19 | 20 | ``` 21 | $ cat /etc/unbound/unbound.conf 22 | ... 23 | remote-control: 24 | control-enable: yes 25 | control-use-cert: yes 26 | server-key-file: "/etc/unbound/unbound_server_ec.key" 27 | server-cert-file: "/etc/unbound/unbound_server_ec.pem" 28 | control-key-file: "/etc/unbound/unbound_control_ec.key" 29 | control-cert-file: "/etc/unbound/unbound_control_ec.pem" 30 | ``` 31 | 32 | Test that you can still communicate with unbound via `unbound_control`. You should be able to see metrics. 33 | ``` 34 | $ unbound-control stats_noreset 35 | thread0.num.queries=35 36 | thread0.num.queries_ip_ratelimited=0 37 | thread0.num.cachehits=25 38 | thread0.num.cachemiss=10 39 | thread0.num.prefetch=0 40 | thread0.num.expired=0 41 | ... 42 | 43 | ``` 44 | 45 | To reconfigure `unbound_exporter` as a systemd service, see [this file](unbound_exporter.service). 46 | -------------------------------------------------------------------------------- /contrib/unbound-cert-setup.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Generally based on /usr/sbin/unbound-control-setup but adapted to catch 4 | # up to ~2010. You know, x509v3, secp384r1, AKIs, stuff like that. 5 | 6 | # directory for files 7 | DESTDIR="${UNBOUND_CONFIG_DIR:-/etc/unbound}" 8 | 9 | # validity period for certificates 10 | DAYS="${UNBOUND_CERT_LIFETIME:-397}" 11 | 12 | # hash algorithm 13 | HASH=sha256 14 | 15 | # base name for unbound CA keys 16 | CA_BASE=unbound_ca_ec 17 | 18 | # base name for unbound server keys 19 | SVR_BASE=unbound_server_ec 20 | 21 | # base name for unbound-control keys 22 | CTL_BASE=unbound_control_ec 23 | 24 | # we want -rw-r----- access (say you run this as root: grp=yes (server), all=no). 25 | umask 0027 26 | 27 | # end of options 28 | 29 | # functions: 30 | error ( ) { 31 | echo "$0 fatal error: ${1}" 32 | exit 1 33 | } 34 | 35 | # go!: 36 | echo "setup in directory ${DESTDIR}" 37 | cd "${DESTDIR}" || error "could not cd to ${DESTDIR}" 38 | 39 | # create certificate keys; do not recreate if they already exist. 40 | if test -f "${CA_BASE}.key"; then 41 | echo "${CA_BASE}.key exists" 42 | else 43 | echo "generating ${CA_BASE}.key" 44 | openssl ecparam -genkey -name secp384r1 > ${CA_BASE}.key || error "could not gen ecdsa" 45 | fi 46 | if test -f "${SVR_BASE}.key"; then 47 | echo "${SVR_BASE}.key exists" 48 | else 49 | echo "generating ${SVR_BASE}.key" 50 | openssl ecparam -genkey -name secp384r1 > ${SVR_BASE}.key || error "could not gen ecdsa" 51 | fi 52 | if test -f "${CTL_BASE}.key"; then 53 | echo "${CTL_BASE}.key exists" 54 | else 55 | echo "generating ${CTL_BASE}.key" 56 | openssl ecparam -genkey -name secp384r1 > ${CTL_BASE}.key || error "could not gen ecdsa" 57 | fi 58 | 59 | # create self-signed cert CSR for server 60 | cat > ca_request.cfg < server_request.cfg < server_exts.cfg < client_request.cfg < client_exts.cfg <> "${SVR_BASE}.pem" 146 | 147 | echo "Setup success. Certificates created." 148 | -------------------------------------------------------------------------------- /contrib/unbound_exporter.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Prometheus exporter for Unbound metrics, written in Go with pluggable metric collectors. The metrics exporter converts Unbound metric names to Prometheus metric names and labels by using a set of regular expressions. 3 | Documentation=https://github.com/letsencrypt/unbound_exporter 4 | After=network.target 5 | 6 | [Service] 7 | Type=simple 8 | ExecStart=/bin/unbound_exporter \ 9 | -unbound.ca "/etc/unbound/unbound_ca_ec.pem" \ 10 | -unbound.cert "/etc/unbound/unbound_control_ec.pem" \ 11 | -unbound.key "/etc/unbound/unbound_control_ec.key" \ 12 | -unbound.host "tcp://localhost:8953" 13 | 14 | [Install] 15 | WantedBy=multi-user.target 16 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | unbound_exporter: 3 | build: . 4 | command: [ "-unbound.host=unix:///var/run/socket/unbound.ctl" ] 5 | volumes: 6 | - socket:/var/run/socket:ro 7 | ports: 8 | - "9167:9167" 9 | depends_on: 10 | unbound: 11 | condition: service_started 12 | unbound: 13 | image: "mvance/unbound:1.18.0" 14 | volumes: 15 | - socket:/var/run/socket:rw 16 | - ./unbound-example.conf:/opt/unbound/etc/unbound/unbound.conf 17 | - ./droplist.zone:/opt/unbound/etc/unbound/droplist.zone 18 | ports: 19 | - "1053:1053/udp" 20 | - "1053:1053/tcp" 21 | volumes: 22 | socket: 23 | -------------------------------------------------------------------------------- /droplist.zone: -------------------------------------------------------------------------------- 1 | *.example.com IN A 127.0.0.1 2 | *.example.net IN A 127.0.0.1 3 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/letsencrypt/unbound_exporter 2 | 3 | go 1.20 4 | 5 | require ( 6 | github.com/go-kit/log v0.2.1 7 | github.com/prometheus/client_golang v1.17.0 8 | github.com/prometheus/common v0.45.0 9 | ) 10 | 11 | require ( 12 | github.com/beorn7/perks v1.0.1 // indirect 13 | github.com/cespare/xxhash/v2 v2.2.0 // indirect 14 | github.com/go-logfmt/logfmt v0.6.0 // indirect 15 | github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect 16 | github.com/prometheus/client_model v0.5.0 // indirect 17 | github.com/prometheus/procfs v0.12.0 // indirect 18 | golang.org/x/sys v0.14.0 // indirect 19 | google.golang.org/protobuf v1.33.0 // indirect 20 | ) 21 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= 2 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= 3 | github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= 4 | github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 5 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 6 | github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU= 7 | github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= 8 | github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= 9 | github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= 10 | github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= 11 | github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 h1:jWpvCLoY8Z/e3VKvlsiIGKtc+UG6U5vzxaoagmhXfyg= 12 | github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0/go.mod h1:QUyp042oQthUoa9bqDv0ER0wrtXnBruoNd7aNjkbP+k= 13 | github.com/prometheus/client_golang v1.17.0 h1:rl2sfwZMtSthVU752MqfjQozy7blglC+1SOtjMAMh+Q= 14 | github.com/prometheus/client_golang v1.17.0/go.mod h1:VeL+gMmOAxkS2IqfCq0ZmHSL+LjWfWDUmp1mBz9JgUY= 15 | github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw= 16 | github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= 17 | github.com/prometheus/common v0.45.0 h1:2BGz0eBc2hdMDLnO/8n0jeB3oPrt2D08CekT0lneoxM= 18 | github.com/prometheus/common v0.45.0/go.mod h1:YJmSTw9BoKxJplESWWxlbyttQR4uaEcGyv9MZjVOJsY= 19 | github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= 20 | github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= 21 | golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q= 22 | golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 23 | google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= 24 | google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= 25 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 26 | -------------------------------------------------------------------------------- /integration_test.go: -------------------------------------------------------------------------------- 1 | //go:build integration 2 | 3 | package main 4 | 5 | import ( 6 | "net/http" 7 | "testing" 8 | 9 | "github.com/prometheus/common/expfmt" 10 | ) 11 | 12 | // TestIntegration checks that unbound_exporter is running, successfully 13 | // scraping and exporting metrics. 14 | // 15 | // It assumes unbound_exporter is available on localhost:9167, and Unbound on 16 | // localhost:1053, as is set up in the docker-compose.yml file. 17 | // 18 | // A typical invocation of this test would look like 19 | // 20 | // docker compose up --build -d 21 | // go test --tags=integration 22 | // docker compose down 23 | func TestIntegration(t *testing.T) { 24 | resp, err := http.Get("http://localhost:9167/metrics") 25 | if err != nil { 26 | t.Fatalf("Failed to fetch metrics from unbound_exporter: %v", err) 27 | } 28 | defer resp.Body.Close() 29 | 30 | if resp.StatusCode != http.StatusOK { 31 | t.Fatalf("Expected a 200 OK from unbound_exporter, got: %v", resp.StatusCode) 32 | } 33 | 34 | parser := expfmt.TextParser{} 35 | metrics, err := parser.TextToMetricFamilies(resp.Body) 36 | if err != nil { 37 | t.Fatalf("Failed to parse metrics from unbound_exporter: %v", err) 38 | } 39 | 40 | // unbound_up is 1 if we've successfully scraped metrics from it 41 | unbound_up := metrics["unbound_up"].Metric[0].Gauge.GetValue() 42 | if unbound_up != 1 { 43 | t.Errorf("Expected unbound_up to be 1, not: %v", unbound_up) 44 | } 45 | 46 | // Check some expected metrics are present 47 | for _, metric := range []string{ 48 | "go_info", 49 | "unbound_queries_total", 50 | "unbound_response_time_seconds", 51 | "unbound_cache_hits_total", 52 | "unbound_query_https_total", 53 | "unbound_memory_doh_bytes", 54 | } { 55 | if _, ok := metrics[metric]; !ok { 56 | t.Errorf("Expected metric is missing: %s", metric) 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /nfpm.yaml: -------------------------------------------------------------------------------- 1 | name: "unbound_exporter" 2 | arch: "amd64" 3 | platform: "linux" 4 | version: "${GITHUB_REF_NAME}" 5 | description: "Prometheus exporter for Unbound recursive DNS resolver" 6 | vendor: "ISRG" 7 | maintainer: "ISRG Team " 8 | homepage: "https://github.com/letsencrypt/unbound_exporter" 9 | license: "Apache 2.0" 10 | contents: 11 | - src: unbound_exporter 12 | dst: /usr/bin/unbound_exporter 13 | -------------------------------------------------------------------------------- /unbound-example.conf: -------------------------------------------------------------------------------- 1 | ## This is an example Unbound configuration file 2 | ## This is needed to use unbound_exporter 3 | remote-control: 4 | control-enable: yes 5 | control-interface: /var/run/socket/unbound.ctl 6 | 7 | # The rest of this file is standard Unbound configuration 8 | # There's nothing special here. 9 | server: 10 | module-config: "respip validator iterator" 11 | extended-statistics: yes 12 | cache-max-ttl: 86400 13 | cache-min-ttl: 300 14 | directory: "/opt/unbound/etc/unbound" 15 | do-ip4: yes 16 | do-ip6: no 17 | do-tcp: yes 18 | do-udp: yes 19 | edns-buffer-size: 1232 20 | interface: 0.0.0.0 21 | port: 1053 22 | prefer-ip6: no 23 | rrset-roundrobin: yes 24 | username: "_unbound" 25 | log-local-actions: no 26 | log-queries: no 27 | log-replies: no 28 | log-servfail: yes 29 | logfile: /opt/unbound/etc/unbound/unbound.log 30 | verbosity: 2 31 | infra-cache-slabs: 4 32 | incoming-num-tcp: 10 33 | key-cache-slabs: 4 34 | msg-cache-size: 142768128 35 | msg-cache-slabs: 4 36 | num-queries-per-thread: 4096 37 | num-threads: 3 38 | outgoing-range: 8192 39 | rrset-cache-size: 285536256 40 | rrset-cache-slabs: 4 41 | minimal-responses: yes 42 | prefetch: yes 43 | prefetch-key: yes 44 | serve-expired: yes 45 | so-reuseport: yes 46 | aggressive-nsec: yes 47 | delay-close: 10000 48 | do-daemonize: no 49 | do-not-query-localhost: no 50 | neg-cache-size: 4M 51 | qname-minimisation: yes 52 | access-control: 127.0.0.1/32 allow 53 | access-control: 192.168.0.0/16 allow 54 | access-control: 172.16.0.0/12 allow 55 | access-control: 10.0.0.0/8 allow 56 | access-control: fc00::/7 allow 57 | access-control: ::1/128 allow 58 | auto-trust-anchor-file: "/opt/unbound/etc/unbound/var/root.key" 59 | chroot: "" 60 | deny-any: yes 61 | harden-algo-downgrade: yes 62 | harden-below-nxdomain: yes 63 | harden-dnssec-stripped: yes 64 | harden-glue: yes 65 | harden-large-queries: yes 66 | harden-referral-path: no 67 | harden-short-bufsize: yes 68 | hide-http-user-agent: no 69 | hide-identity: yes 70 | hide-version: no 71 | http-user-agent: "DNS" 72 | identity: "DNS" 73 | private-address: 10.0.0.0/8 74 | private-address: 172.16.0.0/12 75 | private-address: 192.168.0.0/16 76 | private-address: 169.254.0.0/16 77 | private-address: fd00::/8 78 | private-address: fe80::/10 79 | private-address: ::ffff:0:0/96 80 | ratelimit: 1000 81 | tls-cert-bundle: /etc/ssl/certs/ca-certificates.crt 82 | unwanted-reply-threshold: 10000 83 | use-caps-for-id: yes 84 | val-clean-additional: yes 85 | include: /opt/unbound/etc/unbound/a-records.conf 86 | include: /opt/unbound/etc/unbound/srv-records.conf 87 | 88 | rpz: 89 | name: unbound_exporter_cloak 90 | zonefile: /opt/unbound/etc/unbound/droplist.zone 91 | rpz-log: yes 92 | rpz-log-name: unbound_exporter_cloak 93 | rpz-action-override: nxdomain 94 | -------------------------------------------------------------------------------- /unbound_exporter.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Kumina, https://kumina.nl/ 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package main 15 | 16 | import ( 17 | "bufio" 18 | "crypto/tls" 19 | "crypto/x509" 20 | "flag" 21 | "fmt" 22 | "io" 23 | "net" 24 | "net/http" 25 | "net/url" 26 | "os" 27 | "regexp" 28 | "strconv" 29 | "strings" 30 | 31 | "sort" 32 | 33 | "github.com/go-kit/log/level" 34 | "github.com/prometheus/client_golang/prometheus" 35 | "github.com/prometheus/client_golang/prometheus/promhttp" 36 | "github.com/prometheus/common/promlog" 37 | ) 38 | 39 | var ( 40 | log = promlog.New(&promlog.Config{}) 41 | 42 | unboundUpDesc = prometheus.NewDesc( 43 | prometheus.BuildFQName("unbound", "", "up"), 44 | "Whether scraping Unbound's metrics was successful.", 45 | nil, nil) 46 | 47 | unboundHistogram = prometheus.NewDesc( 48 | prometheus.BuildFQName("unbound", "", "response_time_seconds"), 49 | "Query response time in seconds.", 50 | nil, nil) 51 | 52 | unboundMetrics = []*unboundMetric{ 53 | newUnboundMetric( 54 | "answer_rcodes_total", 55 | "Total number of answers to queries, from cache or from recursion, by response code.", 56 | prometheus.CounterValue, 57 | []string{"rcode"}, 58 | "^num\\.answer\\.rcode\\.(\\w+)$"), 59 | newUnboundMetric( 60 | "answers_bogus", 61 | "Total number of answers that were bogus.", 62 | prometheus.CounterValue, 63 | nil, 64 | "^num\\.answer\\.bogus$"), 65 | newUnboundMetric( 66 | "answers_secure_total", 67 | "Total number of answers that were secure.", 68 | prometheus.CounterValue, 69 | nil, 70 | "^num\\.answer\\.secure$"), 71 | newUnboundMetric( 72 | "cache_hits_total", 73 | "Total number of queries that were successfully answered using a cache lookup.", 74 | prometheus.CounterValue, 75 | []string{"thread"}, 76 | "^thread(\\d+)\\.num\\.cachehits$"), 77 | newUnboundMetric( 78 | "cache_misses_total", 79 | "Total number of cache queries that needed recursive processing.", 80 | prometheus.CounterValue, 81 | []string{"thread"}, 82 | "^thread(\\d+)\\.num\\.cachemiss$"), 83 | newUnboundMetric( 84 | "queries_cookie_client_total", 85 | "Total number of queries with a client cookie.", 86 | prometheus.CounterValue, 87 | []string{"thread"}, 88 | "^thread(\\d+)\\.num\\.queries_cookie_client$"), 89 | newUnboundMetric( 90 | "queries_cookie_invalid_total", 91 | "Total number of queries with a invalid cookie.", 92 | prometheus.CounterValue, 93 | []string{"thread"}, 94 | "^thread(\\d+)\\.num\\.queries_invalid_client$"), 95 | newUnboundMetric( 96 | "queries_cookie_valid_total", 97 | "Total number of queries with a valid cookie.", 98 | prometheus.CounterValue, 99 | []string{"thread"}, 100 | "^thread(\\d+)\\.num\\.queries_cookie_valid$"), 101 | newUnboundMetric( 102 | "memory_caches_bytes", 103 | "Memory in bytes in use by caches.", 104 | prometheus.GaugeValue, 105 | []string{"cache"}, 106 | "^mem\\.cache\\.(\\w+)$"), 107 | newUnboundMetric( 108 | "memory_modules_bytes", 109 | "Memory in bytes in use by modules.", 110 | prometheus.GaugeValue, 111 | []string{"module"}, 112 | "^mem\\.mod\\.(\\w+)$"), 113 | newUnboundMetric( 114 | "memory_sbrk_bytes", 115 | "Memory in bytes allocated through sbrk.", 116 | prometheus.GaugeValue, 117 | nil, 118 | "^mem\\.total\\.sbrk$"), 119 | newUnboundMetric( 120 | "prefetches_total", 121 | "Total number of cache prefetches performed.", 122 | prometheus.CounterValue, 123 | []string{"thread"}, 124 | "^thread(\\d+)\\.num\\.prefetch$"), 125 | newUnboundMetric( 126 | "queries_total", 127 | "Total number of queries received.", 128 | prometheus.CounterValue, 129 | []string{"thread"}, 130 | "^thread(\\d+)\\.num\\.queries$"), 131 | newUnboundMetric( 132 | "expired_total", 133 | "Total number of expired entries served.", 134 | prometheus.CounterValue, 135 | []string{"thread"}, 136 | "^thread(\\d+)\\.num\\.expired$"), 137 | newUnboundMetric( 138 | "query_classes_total", 139 | "Total number of queries with a given query class.", 140 | prometheus.CounterValue, 141 | []string{"class"}, 142 | "^num\\.query\\.class\\.([\\w]+)$"), 143 | newUnboundMetric( 144 | "query_flags_total", 145 | "Total number of queries that had a given flag set in the header.", 146 | prometheus.CounterValue, 147 | []string{"flag"}, 148 | "^num\\.query\\.flags\\.([\\w]+)$"), 149 | newUnboundMetric( 150 | "query_ipv6_total", 151 | "Total number of queries that were made using IPv6 towards the Unbound server.", 152 | prometheus.CounterValue, 153 | nil, 154 | "^num\\.query\\.ipv6$"), 155 | newUnboundMetric( 156 | "query_opcodes_total", 157 | "Total number of queries with a given query opcode.", 158 | prometheus.CounterValue, 159 | []string{"opcode"}, 160 | "^num\\.query\\.opcode\\.([\\w]+)$"), 161 | newUnboundMetric( 162 | "query_edns_DO_total", 163 | "Total number of queries that had an EDNS OPT record with the DO (DNSSEC OK) bit set present.", 164 | prometheus.CounterValue, 165 | nil, 166 | "^num\\.query\\.edns\\.DO$"), 167 | newUnboundMetric( 168 | "query_edns_present_total", 169 | "Total number of queries that had an EDNS OPT record present.", 170 | prometheus.CounterValue, 171 | nil, 172 | "^num\\.query\\.edns\\.present$"), 173 | newUnboundMetric( 174 | "query_tcp_total", 175 | "Total number of queries that were made using TCP towards the Unbound server, including DoT and DoH queries.", 176 | prometheus.CounterValue, 177 | nil, 178 | "^num\\.query\\.tcp$"), 179 | newUnboundMetric( 180 | "query_tcpout_total", 181 | "Total number of queries that the Unbound server made using TCP outgoing towards other servers.", 182 | prometheus.CounterValue, 183 | nil, 184 | "^num\\.query\\.tcpout$"), 185 | newUnboundMetric( 186 | "query_tls_total", 187 | "Total number of queries that were made using TCP TLS towards the Unbound server, including DoT and DoH queries.", 188 | prometheus.CounterValue, 189 | nil, 190 | "^num\\.query\\.tls$"), 191 | newUnboundMetric( 192 | "query_tls_resume_total", 193 | "Total number of queries that were made using TCP TLS Resume towards the Unbound server.", 194 | prometheus.CounterValue, 195 | nil, 196 | "^num\\.query\\.tls\\.resume$"), 197 | newUnboundMetric( 198 | "query_https_total", 199 | "Total number of DoH queries that were made towards the Unbound server.", 200 | prometheus.CounterValue, 201 | nil, 202 | "^num\\.query\\.https$"), 203 | newUnboundMetric( 204 | "query_types_total", 205 | "Total number of queries with a given query type.", 206 | prometheus.CounterValue, 207 | []string{"type"}, 208 | "^num\\.query\\.type\\.([\\w]+)$"), 209 | newUnboundMetric( 210 | "query_udpout_total", 211 | "Total number of queries that the Unbound server made using UDP outgoing towardsother servers.", 212 | prometheus.CounterValue, 213 | nil, 214 | "^num\\.query\\.udpout$"), 215 | newUnboundMetric( 216 | "query_aggressive_nsec", 217 | "Total number of queries that the Unbound server generated response using Aggressive NSEC.", 218 | prometheus.CounterValue, 219 | []string{"rcode"}, 220 | "^num\\.query\\.aggressive\\.(\\w+)$"), 221 | newUnboundMetric( 222 | "request_list_current_all", 223 | "Current size of the request list, including internally generated queries.", 224 | prometheus.GaugeValue, 225 | []string{"thread"}, 226 | "^thread([0-9]+)\\.requestlist\\.current\\.all$"), 227 | newUnboundMetric( 228 | "request_list_current_user", 229 | "Current size of the request list, only counting the requests from client queries.", 230 | prometheus.GaugeValue, 231 | []string{"thread"}, 232 | "^thread([0-9]+)\\.requestlist\\.current\\.user$"), 233 | newUnboundMetric( 234 | "request_list_exceeded_total", 235 | "Number of queries that were dropped because the request list was full.", 236 | prometheus.CounterValue, 237 | []string{"thread"}, 238 | "^thread([0-9]+)\\.requestlist\\.exceeded$"), 239 | newUnboundMetric( 240 | "request_list_overwritten_total", 241 | "Total number of requests in the request list that were overwritten by newer entries.", 242 | prometheus.CounterValue, 243 | []string{"thread"}, 244 | "^thread([0-9]+)\\.requestlist\\.overwritten$"), 245 | newUnboundMetric( 246 | "recursive_replies_total", 247 | "Total number of replies sent to queries that needed recursive processing.", 248 | prometheus.CounterValue, 249 | []string{"thread"}, 250 | "^thread(\\d+)\\.num\\.recursivereplies$"), 251 | newUnboundMetric( 252 | "rrset_bogus_total", 253 | "Total number of rrsets marked bogus by the validator.", 254 | prometheus.CounterValue, 255 | nil, 256 | "^num\\.rrset\\.bogus$"), 257 | newUnboundMetric( 258 | "rrset_cache_max_collisions_total", 259 | "Total number of rrset cache hashtable collisions.", 260 | prometheus.CounterValue, 261 | nil, 262 | "^rrset\\.cache\\.max_collisions$"), 263 | newUnboundMetric( 264 | "time_elapsed_seconds", 265 | "Time since last statistics printout in seconds.", 266 | prometheus.CounterValue, 267 | nil, 268 | "^time\\.elapsed$"), 269 | newUnboundMetric( 270 | "time_now_seconds", 271 | "Current time in seconds since 1970.", 272 | prometheus.GaugeValue, 273 | nil, 274 | "^time\\.now$"), 275 | newUnboundMetric( 276 | "time_up_seconds_total", 277 | "Uptime since server boot in seconds.", 278 | prometheus.CounterValue, 279 | nil, 280 | "^time\\.up$"), 281 | newUnboundMetric( 282 | "unwanted_queries_total", 283 | "Total number of queries that were refused or dropped because they failed the access control settings.", 284 | prometheus.CounterValue, 285 | nil, 286 | "^unwanted\\.queries$"), 287 | newUnboundMetric( 288 | "unwanted_replies_total", 289 | "Total number of replies that were unwanted or unsolicited.", 290 | prometheus.CounterValue, 291 | nil, 292 | "^unwanted\\.replies$"), 293 | newUnboundMetric( 294 | "recursion_time_seconds_avg", 295 | "Average time it took to answer queries that needed recursive processing (does not include in-cache requests).", 296 | prometheus.GaugeValue, 297 | nil, 298 | "^total\\.recursion\\.time\\.avg$"), 299 | newUnboundMetric( 300 | "recursion_time_seconds_median", 301 | "The median of the time it took to answer queries that needed recursive processing.", 302 | prometheus.GaugeValue, 303 | nil, 304 | "^total\\.recursion\\.time\\.median$"), 305 | newUnboundMetric( 306 | "msg_cache_count", 307 | "The Number of Messages cached", 308 | prometheus.GaugeValue, 309 | nil, 310 | "^msg\\.cache\\.count$"), 311 | newUnboundMetric( 312 | "msg_cache_max_collisions_total", 313 | "Total number of msg cache hashtable collisions.", 314 | prometheus.CounterValue, 315 | nil, 316 | "^msg\\.cache\\.max_collisions$"), 317 | newUnboundMetric( 318 | "rrset_cache_count", 319 | "The Number of rrset cached", 320 | prometheus.GaugeValue, 321 | nil, 322 | "^rrset\\.cache\\.count$"), 323 | newUnboundMetric( 324 | "rpz_action_count", 325 | "Total number of triggered Response Policy Zone actions, by type.", 326 | prometheus.CounterValue, 327 | []string{"type"}, 328 | "^num\\.rpz\\.action\\.rpz-([\\w-]+)$"), 329 | newUnboundMetric( 330 | "memory_doh_bytes", 331 | "Memory used by DoH buffers, in bytes.", 332 | prometheus.GaugeValue, 333 | []string{"buffer"}, 334 | "^mem\\.http\\.(\\w+)$"), 335 | } 336 | ) 337 | 338 | type unboundMetric struct { 339 | desc *prometheus.Desc 340 | valueType prometheus.ValueType 341 | pattern *regexp.Regexp 342 | } 343 | 344 | func newUnboundMetric(name string, description string, valueType prometheus.ValueType, labels []string, pattern string) *unboundMetric { 345 | return &unboundMetric{ 346 | desc: prometheus.NewDesc( 347 | prometheus.BuildFQName("unbound", "", name), 348 | description, 349 | labels, 350 | nil), 351 | valueType: valueType, 352 | pattern: regexp.MustCompile(pattern), 353 | } 354 | } 355 | 356 | func CollectFromReader(file io.Reader, ch chan<- prometheus.Metric) error { 357 | scanner := bufio.NewScanner(file) 358 | scanner.Split(bufio.ScanLines) 359 | histogramPattern := regexp.MustCompile(`^histogram\.\d+\.\d+\.to\.(\d+\.\d+)$`) 360 | 361 | histogramCount := uint64(0) 362 | histogramAvg := float64(0) 363 | histogramBuckets := make(map[float64]uint64) 364 | 365 | for scanner.Scan() { 366 | fields := strings.Split(scanner.Text(), "=") 367 | if len(fields) != 2 { 368 | return fmt.Errorf( 369 | "%q is not a valid key-value pair", 370 | scanner.Text()) 371 | } 372 | 373 | for _, metric := range unboundMetrics { 374 | if matches := metric.pattern.FindStringSubmatch(fields[0]); matches != nil { 375 | value, err := strconv.ParseFloat(fields[1], 64) 376 | 377 | if err != nil { 378 | return err 379 | } 380 | ch <- prometheus.MustNewConstMetric( 381 | metric.desc, 382 | metric.valueType, 383 | value, 384 | matches[1:]...) 385 | 386 | break 387 | } 388 | } 389 | 390 | if matches := histogramPattern.FindStringSubmatch(fields[0]); matches != nil { 391 | end, err := strconv.ParseFloat(matches[1], 64) 392 | if err != nil { 393 | return err 394 | } 395 | value, err := strconv.ParseUint(fields[1], 10, 64) 396 | 397 | if err != nil { 398 | return err 399 | } 400 | histogramBuckets[end] = value 401 | histogramCount += value 402 | } else if fields[0] == "total.recursion.time.avg" { 403 | value, err := strconv.ParseFloat(fields[1], 64) 404 | if err != nil { 405 | return err 406 | } 407 | histogramAvg = value 408 | } 409 | } 410 | 411 | // Convert the metrics to a cumulative Prometheus histogram. 412 | // Reconstruct the sum of all samples from the average value 413 | // provided by Unbound. Hopefully this does not break 414 | // monotonicity. 415 | keys := []float64{} 416 | for k := range histogramBuckets { 417 | keys = append(keys, k) 418 | } 419 | sort.Float64s(keys) 420 | prev := uint64(0) 421 | for _, i := range keys { 422 | histogramBuckets[i] += prev 423 | prev = histogramBuckets[i] 424 | } 425 | ch <- prometheus.MustNewConstHistogram( 426 | unboundHistogram, 427 | histogramCount, 428 | histogramAvg*float64(histogramCount), 429 | histogramBuckets) 430 | 431 | return scanner.Err() 432 | } 433 | 434 | func CollectFromSocket(socketFamily string, host string, tlsConfig *tls.Config, ch chan<- prometheus.Metric) error { 435 | var ( 436 | conn net.Conn 437 | err error 438 | ) 439 | 440 | if socketFamily == "unix" || tlsConfig == nil { 441 | conn, err = net.Dial(socketFamily, host) 442 | } else { 443 | conn, err = tls.Dial(socketFamily, host, tlsConfig) 444 | } 445 | if err != nil { 446 | return err 447 | } 448 | defer conn.Close() 449 | _, err = conn.Write([]byte("UBCT1 stats_noreset\n")) 450 | if err != nil { 451 | return err 452 | } 453 | return CollectFromReader(conn, ch) 454 | } 455 | 456 | type UnboundExporter struct { 457 | socketFamily string 458 | host string 459 | tlsConfig *tls.Config 460 | } 461 | 462 | func NewUnboundExporter(host string, ca string, cert string, key string) (*UnboundExporter, error) { 463 | u, err := url.Parse(host) 464 | if err != nil { 465 | return &UnboundExporter{}, err 466 | } 467 | 468 | if u.Scheme == "unix" { 469 | return &UnboundExporter{ 470 | socketFamily: u.Scheme, 471 | host: u.Path, 472 | }, nil 473 | } 474 | 475 | if ca == "" && cert == "" { 476 | return &UnboundExporter{ 477 | socketFamily: u.Scheme, 478 | host: u.Host, 479 | }, nil 480 | } 481 | 482 | /* Server authentication. */ 483 | caData, err := os.ReadFile(ca) 484 | if err != nil { 485 | return &UnboundExporter{}, err 486 | } 487 | roots := x509.NewCertPool() 488 | if !roots.AppendCertsFromPEM(caData) { 489 | return &UnboundExporter{}, fmt.Errorf("Failed to parse CA") 490 | } 491 | 492 | /* Client authentication. */ 493 | certData, err := os.ReadFile(cert) 494 | if err != nil { 495 | return &UnboundExporter{}, err 496 | } 497 | keyData, err := os.ReadFile(key) 498 | if err != nil { 499 | return &UnboundExporter{}, err 500 | } 501 | keyPair, err := tls.X509KeyPair(certData, keyData) 502 | if err != nil { 503 | return &UnboundExporter{}, err 504 | } 505 | 506 | return &UnboundExporter{ 507 | socketFamily: u.Scheme, 508 | host: u.Host, 509 | tlsConfig: &tls.Config{ 510 | Certificates: []tls.Certificate{keyPair}, 511 | RootCAs: roots, 512 | ServerName: "unbound", 513 | }, 514 | }, nil 515 | } 516 | 517 | func (e *UnboundExporter) Describe(ch chan<- *prometheus.Desc) { 518 | ch <- unboundUpDesc 519 | for _, metric := range unboundMetrics { 520 | ch <- metric.desc 521 | } 522 | } 523 | 524 | func (e *UnboundExporter) Collect(ch chan<- prometheus.Metric) { 525 | err := CollectFromSocket(e.socketFamily, e.host, e.tlsConfig, ch) 526 | if err == nil { 527 | ch <- prometheus.MustNewConstMetric( 528 | unboundUpDesc, 529 | prometheus.GaugeValue, 530 | 1.0) 531 | } else { 532 | _ = level.Error(log).Log("Failed to scrape socket: ", err) 533 | ch <- prometheus.MustNewConstMetric( 534 | unboundUpDesc, 535 | prometheus.GaugeValue, 536 | 0.0) 537 | } 538 | } 539 | 540 | func main() { 541 | var ( 542 | listenAddress = flag.String("web.listen-address", ":9167", "Address to listen on for web interface and telemetry.") 543 | metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.") 544 | unboundHost = flag.String("unbound.host", "tcp://localhost:8953", "Unix or TCP address of Unbound control socket.") 545 | unboundCa = flag.String("unbound.ca", "/etc/unbound/unbound_server.pem", "Unbound server certificate.") 546 | unboundCert = flag.String("unbound.cert", "/etc/unbound/unbound_control.pem", "Unbound client certificate.") 547 | unboundKey = flag.String("unbound.key", "/etc/unbound/unbound_control.key", "Unbound client key.") 548 | ) 549 | flag.Parse() 550 | 551 | _ = level.Info(log).Log("Starting unbound_exporter") 552 | exporter, err := NewUnboundExporter(*unboundHost, *unboundCa, *unboundCert, *unboundKey) 553 | if err != nil { 554 | panic(err) 555 | } 556 | prometheus.MustRegister(exporter) 557 | 558 | http.Handle(*metricsPath, promhttp.Handler()) 559 | http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 560 | _, _ = w.Write([]byte(` 561 | 562 | Unbound Exporter 563 | 564 |

Unbound Exporter

565 |

Metrics

566 | 567 | `)) 568 | }) 569 | _ = level.Info(log).Log("Listening on address:port => ", *listenAddress) 570 | _ = level.Error(log).Log(http.ListenAndServe(*listenAddress, nil)) 571 | os.Exit(1) 572 | } 573 | -------------------------------------------------------------------------------- /unbound_exporter_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func TestStub(t *testing.T) { 6 | if 1 != 1 { //nolint 7 | t.Fatal("Math is a lie. We should never have taught computers to think.") 8 | } 9 | } 10 | --------------------------------------------------------------------------------