Full Code of google/dnsmasq_exporter for AI

main becb865b703c
21 files
55.0 KB
16.8k tokens
Repository: google/dnsmasq_exporter
Branch: main
Commit: becb865b703c
Files: 21
Total size: 55.0 KB

Directory structure:
gitextract_gu75wkps/

├── .github/
│   └── workflows/
│       └── go.yml
├── .gitignore
├── .promu.yml
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── README.md
├── collector/
│   ├── collector.go
│   ├── collector_test.go
│   └── testdata/
│       └── dnsmasq.leases
├── dnsmasq-mixin/
│   ├── Makefile
│   ├── README.md
│   ├── dnsmasq-overview.json
│   ├── go.mod
│   └── mixin.libsonnet
├── dnsmasq.go
├── dnsmasq_exporter.service
├── examples/
│   └── openwrt-init.d/
│       └── dnsmasq_exporter
├── go.mod
├── go.sum
└── travis/
    └── Dockerfile

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/workflows/go.yml
================================================
name: CI

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  tests:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2

    - name: Ensure all files were formatted as per gofmt
      run: |
        [ "$(gofmt -l $(find . -name '*.go') 2>&1)" = "" ]

    - name: install binaries
      run: go install github.com/google/dnsmasq_exporter

    - name: build tests
      run: go test -c ./collector

    - name: docker build
      run: docker build --pull --no-cache --rm -t=dns -f travis/Dockerfile .

    - name: run tests in docker
      run: docker run -v $PWD:/usr/src:ro -e TESTDATA_FILE_PATH=/usr/src/collector/testdata/dnsmasq.leases dns /bin/sh -c './collector.test -test.v'


================================================
FILE: .gitignore
================================================
build


================================================
FILE: .promu.yml
================================================
go:
    # Whenever the Go version is updated here,
    # .circle/config.yml should also be updated.
    version: 1.25
repository:
    path: github.com/google/dnsmasq_exporter
build:
    binaries:
        - name: dnsmasq_exporter
          path: ./
    flags: -a -tags netgo
    ldflags: |
        -X github.com/prometheus/common/version.Version={{.Version}}
        -X github.com/prometheus/common/version.Revision={{.Revision}}
        -X github.com/prometheus/common/version.Branch={{.Branch}}
        -X github.com/prometheus/common/version.BuildUser={{user}}@{{host}}
        -X github.com/prometheus/common/version.BuildDate={{date "20060102-15:04:05"}}


================================================
FILE: CONTRIBUTING.md
================================================
# How to Contribute

We'd love to accept your patches and contributions to this project. There are
just a few small guidelines you need to follow.

## Contributor License Agreement

Contributions to this project must be accompanied by a Contributor License
Agreement. You (or your employer) retain the copyright to your contribution,
this simply gives us permission to use and redistribute your contributions as
part of the project. Head over to <https://cla.developers.google.com/> to see
your current agreements on file or to sign a new one.

You generally only need to submit a CLA once, so if you've already submitted one
(even if it was for a different project), you probably don't need to do it
again.

## Code reviews

All submissions, including submissions by project members, require review. We
use GitHub pull requests for this purpose. Consult
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
information on using pull requests.


================================================
FILE: Dockerfile
================================================
# build stage
FROM golang:1.25.6-trixie AS build-env
ADD . /src
ENV CGO_ENABLED=0
WORKDIR /src
RUN go build -o dnsmasq_exporter

# final stage
FROM scratch
WORKDIR /app
COPY --from=build-env /src/dnsmasq_exporter /app/
USER 65534
ENTRYPOINT ["/app/dnsmasq_exporter"]


================================================
FILE: 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.


================================================
FILE: README.md
================================================
# dnsmasq exporter

[![Build Status](https://github.com/google/dnsmasq_exporter/actions/workflows/go.yml/badge.svg?branch=main)](https://github.com/google/dnsmasq_exporter/actions)

dnsmasq_exporter is an exporter for [Prometheus](https://prometheus.io/),
allowing you to monitor/alert on the number of DHCP leases and various DNS
statistics.

The minimum required version of dnsmasq is 2.69, which added support for
querying the statistics via DNS.

See also the “cache statistics” section in
https://manpages.debian.org/stretch/dnsmasq-base/dnsmasq.8.en.html#NOTES

This is not an official Google product.

## Installation

``` shell
go install github.com/google/dnsmasq_exporter@latest
```

## Usage

Place `dnsmasq_exporter.service` in
`/etc/systemd/system/dnsmasq_exporter.service`, then enable and start the
service using:

```shell
systemctl daemon-reload
systemctl enable --now dnsmasq_exporter
```

### Alternative usage

```shell
docker build -t dnsmasq_exporter .
docker run --restart=unless-stopped --net=host dnsmasq_exporter
```

Then, add the endpoint to your Prometheus configuration file:

```yaml
scrape_configs:
  - job_name: dnsmasq
    static_configs:
      - targets: ['localhost:9153']
```


================================================
FILE: collector/collector.go
================================================
// Copyright 2016 Google Inc. All Rights Reserved.
//
// 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 collector collects dnsmasq statistics as a Prometheus collector.
package collector

import (
	"bufio"
	"errors"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"

	"github.com/miekg/dns"
	"github.com/prometheus/client_golang/prometheus"
	"golang.org/x/sync/errgroup"
)

var (
	// floatMetrics contains prometheus Gauges, keyed by the stats DNS record
	// they correspond to.
	floatMetrics = map[string]*prometheus.Desc{
		"cachesize.bind.": prometheus.NewDesc(
			"dnsmasq_cachesize",
			"configured size of the DNS cache",
			nil, nil,
		),

		"insertions.bind.": prometheus.NewDesc(
			"dnsmasq_insertions",
			"DNS cache insertions",
			nil, nil,
		),

		"evictions.bind.": prometheus.NewDesc(
			"dnsmasq_evictions",
			"DNS cache exictions: numbers of entries which replaced an unexpired cache entry",
			nil, nil,
		),

		"misses.bind.": prometheus.NewDesc(
			"dnsmasq_misses",
			"DNS cache misses: queries which had to be forwarded",
			nil, nil,
		),

		"hits.bind.": prometheus.NewDesc(
			"dnsmasq_hits",
			"DNS queries answered locally (cache hits)",
			nil, nil,
		),

		"auth.bind.": prometheus.NewDesc(
			"dnsmasq_auth",
			"DNS queries for authoritative zones",
			nil, nil,
		),
	}

	serversMetrics = map[string]*prometheus.Desc{
		"queries": prometheus.NewDesc(
			"dnsmasq_servers_queries",
			"DNS queries on upstream server",
			[]string{"server"}, nil,
		),
		"queries_failed": prometheus.NewDesc(
			"dnsmasq_servers_queries_failed",
			"DNS queries failed on upstream server",
			[]string{"server"}, nil,
		),
	}

	// individual lease metrics have high cardinality and are thus disabled by
	// default, unless enabled with the -expose_leases flag
	leaseMetrics = prometheus.NewDesc(
		"dnsmasq_lease_expiry",
		"Expiry time for active DHCP leases",
		[]string{"mac_addr", "ip_addr", "computer_name", "client_id"},
		nil,
	)

	leases = prometheus.NewDesc(
		"dnsmasq_leases",
		"Number of DHCP leases handed out",
		nil, nil,
	)
)

// From https://manpages.debian.org/stretch/dnsmasq-base/dnsmasq.8.en.html:
// The cache statistics are also available in the DNS as answers to queries of
// class CHAOS and type TXT in domain bind. The domain names are cachesize.bind,
// insertions.bind, evictions.bind, misses.bind, hits.bind, auth.bind and
// servers.bind. An example command to query this, using the dig utility would
// be:
//     dig +short chaos txt cachesize.bind

// Config contains the configuration for the collector.
type Config struct {
	DnsClient    *dns.Client
	DnsmasqAddr  string
	LeasesPath   string
	ExposeLeases bool
}

// Collector implements prometheus.Collector and exposes dnsmasq metrics.
type Collector struct {
	cfg Config
}

type lease struct {
	expiry       uint64
	macAddress   string
	ipAddress    string
	computerName string
	clientId     string
}

// New creates a new Collector.
func New(cfg Config) *Collector {
	return &Collector{
		cfg: cfg,
	}
}

func (c *Collector) Describe(ch chan<- *prometheus.Desc) {
	for _, d := range floatMetrics {
		ch <- d
	}
	for _, d := range serversMetrics {
		ch <- d
	}
	ch <- leases
	ch <- leaseMetrics
}

func (c *Collector) Collect(ch chan<- prometheus.Metric) {
	var eg errgroup.Group

	eg.Go(func() error {
		questionBinds := []string{
			"cachesize.bind.",
			"insertions.bind.",
			"evictions.bind.",
			"misses.bind.",
			"hits.bind.",
			"auth.bind.",
			"servers.bind.",
		}

		for _, questionBind := range questionBinds {
			err := queryDnsmasq(questionBind, c, ch)

			if err != nil {
				return err
			}
		}

		return nil
	})

	eg.Go(func() error {
		activeLeases, err := readLeaseFile(c.cfg.LeasesPath)
		if err != nil {
			return err
		}
		ch <- prometheus.MustNewConstMetric(leases, prometheus.GaugeValue, float64(len(activeLeases)))

		if c.cfg.ExposeLeases {
			for _, activeLease := range activeLeases {
				ch <- prometheus.MustNewConstMetric(leaseMetrics, prometheus.GaugeValue, float64(activeLease.expiry),
					activeLease.macAddress, activeLease.ipAddress, activeLease.computerName, activeLease.clientId)
			}
		}
		return nil
	})

	if err := eg.Wait(); err != nil {
		log.Printf("could not complete scrape: %v", err)
	}
}

func queryDnsmasq(questionBind string, c *Collector, ch chan<- prometheus.Metric) error {
	msg := &dns.Msg{
		MsgHdr: dns.MsgHdr{
			Id:               dns.Id(),
			RecursionDesired: true,
		},
		Question: []dns.Question{
			question(questionBind),
		},
	}
	in, _, err := c.cfg.DnsClient.Exchange(msg, c.cfg.DnsmasqAddr)
	if err != nil {
		return err
	}
	for _, a := range in.Answer {
		txt, ok := a.(*dns.TXT)
		if !ok {
			continue
		}
		switch txt.Hdr.Name {
		case "servers.bind.":
			for _, str := range txt.Txt {
				arr := strings.Fields(str)
				if got, want := len(arr), 3; got != want {
					return fmt.Errorf("stats DNS record servers.bind.: unexpeced number of argument in record: got %d, want %d", got, want)
				}
				queries, err := strconv.ParseFloat(arr[1], 64)
				if err != nil {
					return err
				}
				failedQueries, err := strconv.ParseFloat(arr[2], 64)
				if err != nil {
					return err
				}
				ch <- prometheus.MustNewConstMetric(serversMetrics["queries"], prometheus.GaugeValue, queries, arr[0])
				ch <- prometheus.MustNewConstMetric(serversMetrics["queries_failed"], prometheus.GaugeValue, failedQueries, arr[0])
			}
		default:
			g, ok := floatMetrics[txt.Hdr.Name]
			if !ok {
				continue // ignore unexpected answer from dnsmasq
			}
			if got, want := len(txt.Txt), 1; got != want {
				return fmt.Errorf("stats DNS record %q: unexpected number of replies: got %d, want %d", txt.Hdr.Name, got, want)
			}
			f, err := strconv.ParseFloat(txt.Txt[0], 64)
			if err != nil {
				return err
			}
			ch <- prometheus.MustNewConstMetric(g, prometheus.GaugeValue, f)
		}
	}

	return nil
}

func question(name string) dns.Question {
	return dns.Question{
		Name:   name,
		Qtype:  dns.TypeTXT,
		Qclass: dns.ClassCHAOS,
	}
}

func parseLease(line string) (*lease, error) {
	if strings.TrimSpace(line) == "" {
		return nil, errSkipLease
	}
	if strings.HasPrefix(line, "duid ") || strings.HasPrefix(line, "vendorclass ") {
		return nil, errSkipLease
	}

	arr := strings.Fields(line)
	if got, want := len(arr), 5; got != want {
		return nil, fmt.Errorf("illegal lease: expected %d fields, got %d", want, got)
	}

	expires, err := strconv.ParseUint(arr[0], 10, 64)
	if err != nil {
		return nil, err
	}

	return &lease{
		expiry:       expires,
		macAddress:   arr[1],
		ipAddress:    arr[2],
		computerName: arr[3],
		clientId:     arr[4],
	}, nil
}

var errSkipLease = errors.New("skip lease line")

// Read the DHCP lease file with the given path and return a list of leases.
//
// The format of the DHCP lease file written by dnsmasq is not formally
// documented in the dnsmasq manual but the format has been described in the
// mailing list:
//
// - https://lists.thekelleys.org.uk/pipermail/dnsmasq-discuss/2006q2/000733.html
// - https://lists.thekelleys.org.uk/pipermail/dnsmasq-discuss/2016q2/010595.html
//
// The DHCP lease file is written to by lease_update_file() in
// src/lease.c, and is read by lease_init().
func readLeaseFile(path string) ([]lease, error) {
	f, err := os.Open(path)
	if err != nil {
		if os.IsNotExist(err) {
			// ignore
			return []lease{}, nil
		}

		return nil, err
	}

	defer f.Close()

	scanner := bufio.NewScanner(f)
	activeLeases := []lease{}
	for i := 1; scanner.Scan(); i++ {
		leaseLine := scanner.Text()
		activeLease, err := parseLease(leaseLine)
		if errors.Is(err, errSkipLease) {
			continue
		}
		if err == nil {
			activeLeases = append(activeLeases, *activeLease)
		} else {
			log.Printf("Error parsing lease (%d, %q): %s", i, leaseLine, err)
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return activeLeases, nil
}


================================================
FILE: collector/collector_test.go
================================================
// Copyright 2016 Google Inc. All Rights Reserved.
//
// 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 collector

import (
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"os/exec"
	"strings"
	"testing"
	"time"

	"github.com/miekg/dns"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func TestDnsmasqExporter(t *testing.T) {
	// NOTE(stapelberg): dnsmasq disables DNS operation upon --port=0 (as
	// opposed to picking a free port). Hence, we must pick one. This is
	// inherently prone to race conditions: another process could grab the port
	// between our ln.Close() and dnsmasq’s bind(). Ideally, dnsmasq would
	// support grabbing a free port and announcing it, or inheriting a listening
	// socket à la systemd socket activation.

	ln, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	_, port, err := net.SplitHostPort(ln.Addr().String())
	if err != nil {
		t.Fatal(err)
	}
	ln.Close()

	dnsmasq := exec.Command(
		"dnsmasq",
		"--port="+port,
		"--no-daemon",
		"--cache-size=666",
		"--bind-interfaces",
		"--interface=lo")
	dnsmasq.Stderr = os.Stderr
	fmt.Printf("starting %v\n", dnsmasq.Args)
	if err := dnsmasq.Start(); err != nil {
		t.Fatal(err)
	}
	defer dnsmasq.Process.Kill()

	// Wait until dnsmasq started up
	resolver := &dns.Client{}
	for {
		// Cause a cache miss (dnsmasq must forward this query)
		var m dns.Msg
		m.SetQuestion("localhost.", dns.TypeA)
		if _, _, err := resolver.Exchange(&m, "localhost:"+port); err == nil {
			break
		}
		time.Sleep(10 * time.Millisecond) // do not hog the CPU
	}

	testDataFilePath := os.Getenv("TESTDATA_FILE_PATH")
	if testDataFilePath == "" {
		testDataFilePath = "./testdata/dnsmasq.leases"
	}

	cfg := Config{
		DnsClient: &dns.Client{
			SingleInflight: true,
		},
		DnsmasqAddr:  "localhost:" + port,
		LeasesPath:   testDataFilePath,
		ExposeLeases: false,
	}

	c := New(cfg)

	t.Run("first", func(t *testing.T) {
		metrics := fetchMetrics(t, c)
		want := map[string]string{
			"dnsmasq_leases":    "2",
			"dnsmasq_cachesize": "666",
			"dnsmasq_hits":      "5",
			"dnsmasq_misses":    "0",
		}
		for key, val := range want {
			if got, want := metrics[key], val; got != want {
				t.Errorf("metric %q: got %q, want %q", key, got, want)
			}
		}
	})

	t.Run("second", func(t *testing.T) {
		metrics := fetchMetrics(t, c)
		want := map[string]string{
			"dnsmasq_leases":    "2",
			"dnsmasq_cachesize": "666",
			"dnsmasq_hits":      "12",
			"dnsmasq_misses":    "0",
		}
		for key, val := range want {
			if got, want := metrics[key], val; got != want {
				t.Errorf("metric %q: got %q, want %q", key, got, want)
			}
		}
	})

	// Cause a cache miss (dnsmasq must forward this query)
	var m dns.Msg
	m.SetQuestion("no.such.domain.invalid.", dns.TypeA)
	if _, _, err := resolver.Exchange(&m, "localhost:"+port); err != nil {
		t.Fatal(err)
	}

	t.Run("after query", func(t *testing.T) {
		metrics := fetchMetrics(t, c)
		want := map[string]string{
			"dnsmasq_leases":    "2",
			"dnsmasq_cachesize": "666",
			"dnsmasq_hits":      "19",
			"dnsmasq_misses":    "1",
		}
		for key, val := range want {
			if got, want := metrics[key], val; got != want {
				t.Errorf("metric %q: got %q, want %q", key, got, want)
			}
		}
	})

	t.Run("should not expose lease information when disabled", func(t *testing.T) {
		metrics := fetchMetrics(t, c)
		for key := range metrics {
			if strings.Contains(key, "dnsmasq_lease_expiry") {
				t.Errorf("lease information should not be exposed when disabled: %v", key)
			}
		}
	})

	c.cfg.ExposeLeases = true

	t.Run("with high-cardinality lease metrics enabled", func(t *testing.T) {
		metrics := fetchMetrics(t, c)
		want := map[string]string{
			"dnsmasq_leases":    "2",
			"dnsmasq_cachesize": "666",
			"dnsmasq_hits":      "33",
			"dnsmasq_misses":    "1",
			"dnsmasq_lease_expiry{client_id=\"00:00:00:00:00:00\",computer_name=\"host-1\",ip_addr=\"10.10.10.10\",mac_addr=\"00:00:00:00:00:00\"}": "1.625595932e+09",
			"dnsmasq_lease_expiry{client_id=\"00:00:00:00:00:01\",computer_name=\"host-2\",ip_addr=\"10.10.10.11\",mac_addr=\"00:00:00:00:00:01\"}": "0",
		}
		for key, val := range want {
			if got, want := metrics[key], val; got != want {
				t.Errorf("metric %q: got %q, want %q", key, got, want)
			}
		}
	})

	c.cfg.LeasesPath = "testdata/dnsmasq.leases.does.not.exists"

	t.Run("without leases file", func(t *testing.T) {
		metrics := fetchMetrics(t, c)
		want := map[string]string{
			"dnsmasq_leases":    "0",
			"dnsmasq_cachesize": "666",
			"dnsmasq_hits":      "40",
			"dnsmasq_misses":    "1",
		}
		for key, val := range want {
			if got, want := metrics[key], val; got != want {
				t.Errorf("metric %q: got %q, want %q", key, got, want)
			}
		}
	})

}

func fetchMetrics(t *testing.T, c *Collector) map[string]string {
	reg := prometheus.NewRegistry()
	reg.MustRegister(c)
	handler := promhttp.HandlerFor(reg, promhttp.HandlerOpts{})

	rec := httptest.NewRecorder()
	handler.ServeHTTP(rec, httptest.NewRequest("GET", "/metrics", nil))
	resp := rec.Result()
	if got, want := resp.StatusCode, http.StatusOK; got != want {
		b, _ := io.ReadAll(resp.Body)
		t.Fatalf("unexpected HTTP status: got %v (%v), want %v", resp.Status, string(b), want)
	}
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		t.Fatal(err)
	}
	metrics := make(map[string]string)
	for _, line := range strings.Split(strings.TrimSpace(string(body)), "\n") {
		if strings.HasPrefix(line, "#") {
			continue
		}
		parts := strings.Split(line, " ")
		if len(parts) < 2 {
			continue
		}
		if !strings.HasPrefix(parts[0], "dnsmasq_") {
			continue
		}
		metrics[parts[0]] = parts[1]
	}
	return metrics
}

func TestParseLeaseSkipsMetadataLines(t *testing.T) {
	t.Parallel()

	for _, line := range []string{
		"duid 00:01:00:01:ff:6f:ff:6e:aa:cf:ff:af:4a:8b",
		"vendorclass something",
		"   ",
	} {
		if lease, err := parseLease(line); !errors.Is(err, errSkipLease) || lease != nil {
			t.Fatalf("parseLease(%q) = (%v, %v), want skip error", line, lease, err)
		}
	}
}


================================================
FILE: collector/testdata/dnsmasq.leases
================================================
duid 00:01:00:01:ff:6f:ff:6e:aa:cf:ff:af:4a:8b
vendorclass some-vendor-info
1625595932 00:00:00:00:00:00 10.10.10.10 host-1 00:00:00:00:00:00
0 00:00:00:00:00:01 10.10.10.11 host-2 00:00:00:00:00:01



================================================
FILE: dnsmasq-mixin/Makefile
================================================
JSONNET_FMT := jsonnetfmt -n 2 --max-blank-lines 2 --string-style s --comment-style s

all: fmt lint build clean

fmt:
	find . -name 'vendor' -prune -o -name '*.libsonnet' -print -o -name '*.jsonnet' -print | \
		xargs -n 1 -- $(JSONNET_FMT) -i

lint:
	find . -name 'vendor' -prune -o -name '*.libsonnet' -print -o -name '*.jsonnet' -print | \
		while read f; do \
			$(JSONNET_FMT) "$$f" | diff -u "$$f" -; \
		done

	mixtool lint mixin.libsonnet

build:
	mixtool generate all mixin.libsonnet

clean:
	rm -rf dashboards_out alerts.yaml rules.yaml


================================================
FILE: dnsmasq-mixin/README.md
================================================
# dnsmasq mixin

_This is a work in progress. We aim for it to become a good role model for alerts
and dashboards eventually, but it is not quite there yet._

The dnsmasq mixin is a set of configurable, reusable, and extensible alerts and
dashboards based on the metrics exported by the dnsmasq exporter. The mixin creates
recording and alerting rules for Prometheus and suitable dashboard descriptions
for Grafana.

To use them, you need to have `mixtool` and `jsonnetfmt` installed. If you
have a working Go development environment, it's easiest to run the following:
```bash
$ go get github.com/monitoring-mixins/mixtool/cmd/mixtool
$ go get github.com/google/go-jsonnet/cmd/jsonnetfmt
```

You can then build the Prometheus rules files `alerts.yaml` and
`rules.yaml` and a directory `dashboard_out` with the JSON dashboard files
for Grafana:
```bash
$ make build
```

For more advanced uses of mixins, see
https://github.com/monitoring-mixins/docs.


================================================
FILE: dnsmasq-mixin/dnsmasq-overview.json
================================================
{
  "annotations": {
    "list": [
      {
        "builtIn": 1,
        "datasource": {
          "type": "datasource",
          "uid": "grafana"
        },
        "enable": true,
        "hide": true,
        "iconColor": "rgba(0, 211, 255, 1)",
        "name": "Annotations & Alerts",
        "target": {
          "limit": 100,
          "matchAny": false,
          "tags": [],
          "type": "dashboard"
        },
        "type": "dashboard"
      }
    ]
  },
  "editable": true,
  "fiscalYearStartMonth": 0,
  "graphTooltip": 0,
  "id": 94,
  "links": [],
  "liveNow": false,
  "panels": [
    {
      "collapsed": false,
      "datasource": {
        "type": "datasource",
        "uid": "grafana"
      },
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 0
      },
      "id": 15,
      "panels": [],
      "targets": [
        {
          "datasource": {
            "type": "datasource",
            "uid": "grafana"
          },
          "refId": "A"
        }
      ],
      "title": "DNS Stats",
      "type": "row"
    },
    {
      "datasource": {
        "uid": "$datasource"
      },
      "fieldConfig": {
        "defaults": {
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 80
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 6,
        "w": 6,
        "x": 0,
        "y": 1
      },
      "id": 2,
      "options": {
        "colorMode": "value",
        "graphMode": "area",
        "justifyMode": "auto",
        "orientation": "auto",
        "reduceOptions": {
          "calcs": [
            "mean"
          ],
          "fields": "",
          "values": false
        },
        "textMode": "auto"
      },
      "pluginVersion": "9.3.2-67a213dc85",
      "targets": [
        {
          "datasource": {
            "uid": "$datasource"
          },
          "expr": "sum(dnsmasq_leases{job=~\"$job\", instance=~\"$instance\"})",
          "instant": false,
          "interval": "",
          "legendFormat": "",
          "refId": "A"
        }
      ],
      "title": "Leases",
      "type": "stat"
    },
    {
      "datasource": {
        "uid": "$datasource"
      },
      "fieldConfig": {
        "defaults": {
          "mappings": [],
          "noValue": "0",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 80
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 6,
        "w": 6,
        "x": 6,
        "y": 1
      },
      "id": 16,
      "options": {
        "colorMode": "value",
        "graphMode": "area",
        "justifyMode": "auto",
        "orientation": "auto",
        "reduceOptions": {
          "calcs": [
            "mean"
          ],
          "fields": "",
          "values": false
        },
        "textMode": "auto"
      },
      "pluginVersion": "9.3.2-67a213dc85",
      "targets": [
        {
          "datasource": {
            "uid": "$datasource"
          },
          "expr": "sum(dnsmasq_servers_queries{job=~\"$job\", instance=~\"$instance\"})",
          "instant": false,
          "interval": "",
          "legendFormat": "",
          "refId": "A"
        }
      ],
      "title": "Upstream Queries",
      "type": "stat"
    },
    {
      "datasource": {
        "uid": "$datasource"
      },
      "fieldConfig": {
        "defaults": {
          "mappings": [],
          "max": 1,
          "min": 0,
          "noValue": "0%",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 80
              }
            ]
          },
          "unit": "percentunit"
        },
        "overrides": []
      },
      "gridPos": {
        "h": 6,
        "w": 6,
        "x": 12,
        "y": 1
      },
      "id": 17,
      "options": {
        "colorMode": "value",
        "graphMode": "area",
        "justifyMode": "auto",
        "orientation": "auto",
        "reduceOptions": {
          "calcs": [
            "mean"
          ],
          "fields": "",
          "values": false
        },
        "textMode": "auto"
      },
      "pluginVersion": "9.3.2-67a213dc85",
      "targets": [
        {
          "datasource": {
            "uid": "$datasource"
          },
          "expr": "sum(dnsmasq_servers_queries_failed{job=~\"$job\", instance=~\"$instance\"}) / sum(dnsmasq_servers_queries{job=~\"$job\", instance=~\"$instance\"})",
          "instant": false,
          "interval": "",
          "legendFormat": "",
          "refId": "A"
        }
      ],
      "title": "Upstream Failed Queries",
      "type": "stat"
    },
    {
      "collapsed": false,
      "datasource": {
        "type": "datasource",
        "uid": "grafana"
      },
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 7
      },
      "id": 13,
      "panels": [],
      "targets": [
        {
          "datasource": {
            "type": "datasource",
            "uid": "grafana"
          },
          "refId": "A"
        }
      ],
      "title": "Build Info",
      "type": "row"
    },
    {
      "datasource": {
        "uid": "$datasource"
      },
      "fieldConfig": {
        "defaults": {
          "custom": {
            "displayMode": "auto",
            "inspect": false
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 80
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 6,
        "w": 24,
        "x": 0,
        "y": 8
      },
      "id": 4,
      "options": {
        "footer": {
          "fields": "",
          "reducer": [
            "sum"
          ],
          "show": false
        },
        "showHeader": true
      },
      "pluginVersion": "9.3.2-67a213dc85",
      "targets": [
        {
          "datasource": {
            "uid": "$datasource"
          },
          "expr": "dnsmasq_exporter_build_info{job=~\"$job\", instance=~\"$instance\"}",
          "format": "time_series",
          "instant": true,
          "interval": "",
          "legendFormat": "",
          "refId": "A"
        }
      ],
      "title": "Build Info",
      "transformations": [
        {
          "id": "labelsToFields",
          "options": {}
        },
        {
          "id": "merge",
          "options": {}
        },
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "Time": true,
              "Value": true,
              "instance": false,
              "job": true
            },
            "indexByName": {
              "Time": 5,
              "Value": 7,
              "branch": 4,
              "goversion": 2,
              "instance": 0,
              "job": 6,
              "revision": 3,
              "version": 1
            },
            "renameByName": {}
          }
        }
      ],
      "type": "table"
    },
    {
      "collapsed": false,
      "datasource": {
        "type": "datasource",
        "uid": "grafana"
      },
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 14
      },
      "id": 11,
      "panels": [],
      "targets": [
        {
          "datasource": {
            "type": "datasource",
            "uid": "grafana"
          },
          "refId": "A"
        }
      ],
      "title": "Cache Stats",
      "type": "row"
    },
    {
      "datasource": {
        "uid": "$datasource"
      },
      "fieldConfig": {
        "defaults": {
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 80
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 6,
        "w": 6,
        "x": 0,
        "y": 15
      },
      "id": 8,
      "options": {
        "colorMode": "value",
        "graphMode": "area",
        "justifyMode": "auto",
        "orientation": "auto",
        "reduceOptions": {
          "calcs": [
            "mean"
          ],
          "fields": "",
          "values": false
        },
        "textMode": "auto"
      },
      "pluginVersion": "9.3.2-67a213dc85",
      "targets": [
        {
          "datasource": {
            "uid": "$datasource"
          },
          "expr": "sum(dnsmasq_cachesize{job=~\"$job\", instance=~\"$instance\"})",
          "instant": false,
          "interval": "",
          "legendFormat": "",
          "refId": "A"
        }
      ],
      "title": "Cache Size",
      "type": "stat"
    },
    {
      "datasource": {
        "uid": "$datasource"
      },
      "fieldConfig": {
        "defaults": {
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 80
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 6,
        "w": 6,
        "x": 6,
        "y": 15
      },
      "id": 6,
      "options": {
        "colorMode": "value",
        "graphMode": "area",
        "justifyMode": "auto",
        "orientation": "auto",
        "reduceOptions": {
          "calcs": [
            "mean"
          ],
          "fields": "",
          "values": false
        },
        "textMode": "auto"
      },
      "pluginVersion": "9.3.2-67a213dc85",
      "targets": [
        {
          "datasource": {
            "uid": "$datasource"
          },
          "expr": "sum(dnsmasq_hits{job=~\"$job\", instance=~\"$instance\"})",
          "instant": false,
          "interval": "",
          "legendFormat": "",
          "refId": "A"
        }
      ],
      "title": "Cache Hits",
      "type": "stat"
    },
    {
      "datasource": {
        "uid": "$datasource"
      },
      "fieldConfig": {
        "defaults": {
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 80
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 6,
        "w": 6,
        "x": 12,
        "y": 15
      },
      "id": 7,
      "options": {
        "colorMode": "value",
        "graphMode": "area",
        "justifyMode": "auto",
        "orientation": "auto",
        "reduceOptions": {
          "calcs": [
            "mean"
          ],
          "fields": "",
          "values": false
        },
        "textMode": "auto"
      },
      "pluginVersion": "9.3.2-67a213dc85",
      "targets": [
        {
          "datasource": {
            "uid": "$datasource"
          },
          "expr": "sum(dnsmasq_insertions{job=~\"$job\", instance=~\"$instance\"})",
          "instant": false,
          "interval": "",
          "legendFormat": "",
          "refId": "A"
        }
      ],
      "title": "Cache Insertions",
      "type": "stat"
    }
  ],
  "schemaVersion": 37,
  "style": "dark",
  "tags": [],
  "templating": {
    "list": [
      {
        "current": {
          "selected": false,
          "text": "default",
          "value": "default"
        },
        "hide": 0,
        "includeAll": false,
        "label": "Data Source",
        "multi": false,
        "name": "datasource",
        "options": [],
        "query": "prometheus",
        "queryValue": "",
        "refresh": 1,
        "regex": "",
        "skipUrlSync": false,
        "type": "datasource"
      },
      {
        "allValue": ".+",
        "current": {
          "selected": false,
          "text": "All",
          "value": "$__all"
        },
        "datasource": {
          "uid": "$datasource"
        },
        "definition": "label_values(dnsmasq_exporter_build_info, job)",
        "hide": 0,
        "includeAll": true,
        "label": "job",
        "multi": true,
        "name": "job",
        "options": [],
        "query": "label_values(dnsmasq_exporter_build_info, job)",
        "refresh": 1,
        "regex": "",
        "skipUrlSync": false,
        "sort": 0,
        "tagValuesQuery": "",
        "tagsQuery": "",
        "type": "query",
        "useTags": false
      },
      {
        "allValue": ".+",
        "current": {
          "selected": false,
          "text": "All",
          "value": "$__all"
        },
        "datasource": {
          "uid": "$datasource"
        },
        "definition": "label_values(dnsmasq_exporter_build_info, instance)",
        "hide": 0,
        "includeAll": true,
        "label": "instance",
        "multi": true,
        "name": "instance",
        "options": [],
        "query": "label_values(dnsmasq_exporter_build_info, instance)",
        "refresh": 1,
        "regex": "",
        "skipUrlSync": false,
        "sort": 0,
        "tagValuesQuery": "",
        "tagsQuery": "",
        "type": "query",
        "useTags": false
      }
    ]
  },
  "time": {
    "from": "now-6h",
    "to": "now"
  },
  "timepicker": {
    "refresh_intervals": [
      "10s",
      "30s",
      "1m",
      "5m",
      "15m",
      "30m",
      "1h",
      "2h",
      "1d"
    ]
  },
  "timezone": "",
  "title": "dnsmasq",
  "uid": "ySypWTcMk",
  "version": 2,
  "weekStart": ""
}

================================================
FILE: dnsmasq-mixin/go.mod
================================================
module github.com/google/dnsmasq_exporter/dnsmasq-mixin

go 1.14

require (
	github.com/campoy/embedmd v1.0.0 // indirect
	github.com/google/go-jsonnet v0.16.0 // indirect
	github.com/monitoring-mixins/mixtool v0.0.0-20201009093517-e5001c032796 // indirect
)


================================================
FILE: dnsmasq-mixin/mixin.libsonnet
================================================
{
  grafanaDashboards: {
    'dnsmasq-overview.json': (import 'dnsmasq-overview.json'),
  },
}


================================================
FILE: dnsmasq.go
================================================
// Copyright 2016 Google Inc. All Rights Reserved.
//
// 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.

// Binary dnsmasq_exporter is a Prometheus exporter for dnsmasq statistics.
package main

import (
	"flag"
	"log"
	"net/http"

	"github.com/google/dnsmasq_exporter/collector"
	"github.com/miekg/dns"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/collectors"
	"github.com/prometheus/client_golang/prometheus/collectors/version"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
	listen = flag.String("listen",
		"localhost:9153",
		"listen address")

	exposeLeases = flag.Bool("expose_leases",
		false,
		"expose dnsmasq leases as metrics (high cardinality)")

	leasesPath = flag.String("leases_path",
		"/var/lib/misc/dnsmasq.leases",
		"path to the dnsmasq leases file")

	dnsmasqAddr = flag.String("dnsmasq",
		"localhost:53",
		"dnsmasq host:port address")
	dnsmasqProtocol = flag.String("protocol",
		"udp",
		"connect using udp or tcp")

	metricsPath = flag.String("metrics_path",
		"/metrics",
		"path under which metrics are served")
)

func init() {
	prometheus.MustRegister(collectors.NewBuildInfoCollector())
	prometheus.MustRegister(version.NewCollector("dnsmasq_exporter"))
}

func main() {
	flag.Parse()

	var (
		dnsClient = &dns.Client{
			SingleInflight: true,
			Net:            *dnsmasqProtocol,
		}
		cfg = collector.Config{
			DnsClient:    dnsClient,
			DnsmasqAddr:  *dnsmasqAddr,
			LeasesPath:   *leasesPath,
			ExposeLeases: *exposeLeases,
		}
		collector = collector.New(cfg)
		reg       = prometheus.NewRegistry()
	)

	reg.MustRegister(collector)

	http.Handle(*metricsPath, promhttp.HandlerFor(
		prometheus.Gatherers{prometheus.DefaultGatherer, reg},
		promhttp.HandlerOpts{},
	))
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`<html>
      <head><title>Dnsmasq Exporter</title></head>
      <body>
      <h1>Dnsmasq Exporter</h1>
      <p><a href="` + *metricsPath + `">Metrics</a></p>
      </body></html>`))
	})
	log.Println("Listening on", *listen)
	log.Println("Service metrics under", *metricsPath)
	log.Fatal(http.ListenAndServe(*listen, nil))
}


================================================
FILE: dnsmasq_exporter.service
================================================
[Unit]
Description=dnsmasq exporter for Prometheus
Documentation=https://prometheus.io/docs/introduction/overview/

[Service]
Restart=always
User=prometheus
ExecStart=/usr/bin/dnsmasq_exporter

[Install]
WantedBy=multi-user.target


================================================
FILE: examples/openwrt-init.d/dnsmasq_exporter
================================================
#!/bin/sh /etc/rc.common

START=99

USE_PROCD=1
PROG="/usr/bin/dnsmasq_exporter"
LEASES_PATH="/tmp/dhcp.leases"
LISTEN_ADDR=":9153"

start_service() {
	procd_open_instance
	procd_set_param command "$PROG" "-leases_path=${LEASES_PATH}" "-listen=${LISTEN_ADDR}"
	procd_set_param stdout 1 # forward stdout of the command to logd
	procd_set_param stderr 1 # same for stderr
	procd_close_instance
}


================================================
FILE: go.mod
================================================
module github.com/google/dnsmasq_exporter

go 1.24.0

require (
	github.com/miekg/dns v1.1.72
	github.com/prometheus/client_golang v1.23.2
	golang.org/x/sync v0.19.0
)

require (
	github.com/beorn7/perks v1.0.1 // indirect
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/kr/text v0.2.0 // indirect
	github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
	github.com/prometheus/client_model v0.6.2 // indirect
	github.com/prometheus/common v0.67.5 // indirect
	github.com/prometheus/procfs v0.19.2 // indirect
	go.yaml.in/yaml/v2 v2.4.3 // indirect
	golang.org/x/mod v0.32.0 // indirect
	golang.org/x/net v0.49.0 // indirect
	golang.org/x/sys v0.40.0 // indirect
	golang.org/x/tools v0.41.0 // indirect
	google.golang.org/protobuf v1.36.11 // indirect
)


================================================
FILE: go.sum
================================================
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
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/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
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 v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws=
github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c=
golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU=
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=


================================================
FILE: travis/Dockerfile
================================================
# vim:ft=Dockerfile
FROM debian:sid

RUN echo force-unsafe-io > /etc/dpkg/dpkg.cfg.d/docker-apt-speedup
# Paper over occasional network flakiness of some mirrors.
RUN echo 'APT::Acquire::Retries "5";' > /etc/apt/apt.conf.d/80retry

# NOTE: I tried exclusively using gce_debian_mirror.storage.googleapis.com
# instead of httpredir.debian.org, but the results (Fetched 123 MB in 36s (3357
# kB/s)) are not any better than httpredir.debian.org (Fetched 123 MB in 34s
# (3608 kB/s)). Hence, let’s stick with httpredir.debian.org (default) for now.

RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
    dnsmasq && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /usr/src
gitextract_gu75wkps/

├── .github/
│   └── workflows/
│       └── go.yml
├── .gitignore
├── .promu.yml
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── README.md
├── collector/
│   ├── collector.go
│   ├── collector_test.go
│   └── testdata/
│       └── dnsmasq.leases
├── dnsmasq-mixin/
│   ├── Makefile
│   ├── README.md
│   ├── dnsmasq-overview.json
│   ├── go.mod
│   └── mixin.libsonnet
├── dnsmasq.go
├── dnsmasq_exporter.service
├── examples/
│   └── openwrt-init.d/
│       └── dnsmasq_exporter
├── go.mod
├── go.sum
└── travis/
    └── Dockerfile
Condensed preview — 21 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (62K chars).
[
  {
    "path": ".github/workflows/go.yml",
    "chars": 732,
    "preview": "name: CI\n\non:\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\njobs:\n  tests:\n    runs-on: ubuntu-..."
  },
  {
    "path": ".gitignore",
    "chars": 6,
    "preview": "build\n"
  },
  {
    "path": ".promu.yml",
    "chars": 659,
    "preview": "go:\n    # Whenever the Go version is updated here,\n    # .circle/config.yml should also be updated.\n    version: 1.25\nre..."
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 969,
    "preview": "# How to Contribute\n\nWe'd love to accept your patches and contributions to this project. There are\njust a few small guid..."
  },
  {
    "path": "Dockerfile",
    "chars": 267,
    "preview": "# build stage\nFROM golang:1.25.6-trixie AS build-env\nADD . /src\nENV CGO_ENABLED=0\nWORKDIR /src\nRUN go build -o dnsmasq_e..."
  },
  {
    "path": "LICENSE",
    "chars": 11358,
    "preview": "\n                                 Apache License\n                           Version 2.0, January 2004..."
  },
  {
    "path": "README.md",
    "chars": 1213,
    "preview": "# dnsmasq exporter\n\n[![Build Status](https://github.com/google/dnsmasq_exporter/actions/workflows/go.yml/badge.svg?branc..."
  },
  {
    "path": "collector/collector.go",
    "chars": 8379,
    "preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");..."
  },
  {
    "path": "collector/collector_test.go",
    "chars": 6601,
    "preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");..."
  },
  {
    "path": "collector/testdata/dnsmasq.leases",
    "chars": 200,
    "preview": "duid 00:01:00:01:ff:6f:ff:6e:aa:cf:ff:af:4a:8b\nvendorclass some-vendor-info\n1625595932 00:00:00:00:00:00 10.10.10.10 hos..."
  },
  {
    "path": "dnsmasq-mixin/Makefile",
    "chars": 548,
    "preview": "JSONNET_FMT := jsonnetfmt -n 2 --max-blank-lines 2 --string-style s --comment-style s\n\nall: fmt lint build clean\n\nfmt:..."
  },
  {
    "path": "dnsmasq-mixin/README.md",
    "chars": 953,
    "preview": "# dnsmasq mixin\n\n_This is a work in progress. We aim for it to become a good role model for alerts\nand dashboards eventu..."
  },
  {
    "path": "dnsmasq-mixin/dnsmasq-overview.json",
    "chars": 14468,
    "preview": "{\n  \"annotations\": {\n    \"list\": [\n      {\n        \"builtIn\": 1,\n        \"datasource\": {\n          \"type\": \"datasource\",..."
  },
  {
    "path": "dnsmasq-mixin/go.mod",
    "chars": 259,
    "preview": "module github.com/google/dnsmasq_exporter/dnsmasq-mixin\n\ngo 1.14\n\nrequire (\n\tgithub.com/campoy/embedmd v1.0.0 // indirec..."
  },
  {
    "path": "dnsmasq-mixin/mixin.libsonnet",
    "chars": 95,
    "preview": "{\n  grafanaDashboards: {\n    'dnsmasq-overview.json': (import 'dnsmasq-overview.json'),\n  },\n}\n"
  },
  {
    "path": "dnsmasq.go",
    "chars": 2702,
    "preview": "// Copyright 2016 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");..."
  },
  {
    "path": "dnsmasq_exporter.service",
    "chars": 231,
    "preview": "[Unit]\nDescription=dnsmasq exporter for Prometheus\nDocumentation=https://prometheus.io/docs/introduction/overview/\n\n[Ser..."
  },
  {
    "path": "examples/openwrt-init.d/dnsmasq_exporter",
    "chars": 394,
    "preview": "#!/bin/sh /etc/rc.common\n\nSTART=99\n\nUSE_PROCD=1\nPROG=\"/usr/bin/dnsmasq_exporter\"\nLEASES_PATH=\"/tmp/dhcp.leases\"\nLISTEN_A..."
  },
  {
    "path": "go.mod",
    "chars": 787,
    "preview": "module github.com/google/dnsmasq_exporter\n\ngo 1.24.0\n\nrequire (\n\tgithub.com/miekg/dns v1.1.72\n\tgithub.com/prometheus/cli..."
  },
  {
    "path": "go.sum",
    "chars": 4815,
    "preview": "github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=\ngithub.com/beorn7/perks v1.0.1/go.mod h1:..."
  },
  {
    "path": "travis/Dockerfile",
    "chars": 716,
    "preview": "# vim:ft=Dockerfile\nFROM debian:sid\n\nRUN echo force-unsafe-io > /etc/dpkg/dpkg.cfg.d/docker-apt-speedup\n# Paper over occ..."
  }
]

About this extraction

This page contains the full source code of the google/dnsmasq_exporter GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 21 files (55.0 KB), approximately 16.8k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!