Skip to content

DNS probe for various authoritative dns servers #1193

Closed

Description

@kerus1024

I am currently using cloudprober in practice to monitor multiple DNS connectivity paths, including checks against specific DNS authoritative servers.

I previously used smokeping, but as the number of targets increased and the probing interval became shorter, the reliability of the generated RRD data degraded. In contrast, cloudprober, being a Go-based tool, does not fork a process per probe. By leveraging Prometheus increase() queries and latency buckets, it allows me to collect higher-resolution and more reliable metrics.

However, the current DNS probe implementation appears to always send queries with the RD (Recursion Desired) flag enabled.
For my use case—especially when probing authoritative DNS servers—I need finer control over the DNS query behavior and response validation.

As a workaround, I am currently using the HTTP probe with a dedicated receiver server that performs DNS probing logic, similar to the following:

Details

config and targets

probe {
  name: "dns-2s"
  type: HTTP
  interval_msec: 2100
  timeout_msec: 2100
  targets {
    file_targets {
      file_path: "./config/targets-dns-2s.yaml"
      re_eval_sec: 60
    }
  }
  stats_export_interval_msec: 5000

  http_probe {
    protocol: HTTP
    method: GET
    port: 2001
    user_agent: "cloudprober"
    latency_breakdown: FIRST_BYTE_LATENCY
  }

  validator {
      name: "status_code_2xx"
      http_validator {
          success_status_codes: "200"
      }
  }

  latency_unit: "ms"
  latency_distribution {
    explicit_buckets: "5,10,30,50,75,100,125,150,175,200,250,300,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500,1600,1700,1800,1900,2000,INF"
  }

  ip_version: IPV4

  additional_label {
    key: "group"
    value: "@target.label.group@"
  }
  additional_label {
    key: "alert_group"
    value: "@target.label.alert_group@"
  }
  additional_label {
    key: "network"
    value: "@target.label.network@"
  }
  additional_label {
    key: "region"
    value: "@target.label.region@"
  }
  additional_label {
    key: "location"
    value: "@target.label.location@"
  }
  additional_label {
    key: "comment"
    value: "@target.label.comment@"
  }
}
resource:
#
# Resolvers
#
- name: CloudFlare:1.1.1.1
  ip: 127.0.0.1
  labels:
    network: cloudflare
    group: public-resolver
    region: anycast
    location: anycast
    __cp_path__: "/probing/dns/query?host=1.1.1.1&rd=1&qname=www.google.com.&qtype=A&timeout=2s"

- name: Google:8.8.8.8
  ip: 127.0.0.1
  labels:
    network: google
    group: public-resolver
    region: anycast
    location: anycast
    __cp_path__: "/probing/dns/query?host=8.8.8.8&rd=1&qname=www.facebook.com.&qtype=A&timeout=2s"

- name: GTLD:m.gtld-servers.net.
  ip: 127.0.0.1
  labels:
    network: gtld-servers
    group: gtld-servers
    alert_group: gtld-servers
    region: anycast
    __cp_path__: "/probing/dns/query?host=m.gtld-servers.net.&qname=m.gtld-servers.net.&qtype=A&timeout=2s&"

- name: Root:d.root-servers.net.
  ip: 127.0.0.1
  labels:
    network: tld-root-servers
    group: tld-root-servers
    alert_group: tld-root-servers
    region: anycast
    __cp_path__: "/probing/dns/query?host=d.root-servers.net.&qname=com.&qtype=NS&timeout=2s&min_authority=1"

- name: ARPA:f.in-addr-servers.arpa.
  ip: 127.0.0.1
  labels:
    network: arpa
    group: arpa-servers
    alert_group: arpa-servers
    region: anycast
    __cp_path__: "/probing/dns/query?host=f.in-addr-servers.arpa.&qname=f.in-addr-servers.arpa.&qtype=A&timeout=2s&aarequired=1&min_answer=1"

main.go

var listenString = "127.0.0.1:2001"
var resolverAddrString = "127.0.0.1:7453"

func main() {

	gin.SetMode(gin.ReleaseMode)
	r := gin.New()

	// usage
	// /query?host=1.1.1.1&qname=cloudflare.com&qtype=NS&timeout=5s&min_authority=1&rd=0
	// /query?host=c.gtld-servers.net.&qname=cloudflare.com&qtype=NS&timeout=5s&min_authority=1
	// /query?host=ns1.cloudflare.net.&qname=www.cloudflare.com.cdn.cloudflare.net.&qtype=SOA&timeout=5s&min_answer=1
	// /query?host=123.123.123.123&qname=www.cloudflare.com.cdn.cloudflare.net.&qtype=SOA&min_answer=1&random_prefix=kerustest-nocache-@time@-@rand@&
	// /query?host=123.123.123.123&qname=kerus.net&qtype=A&aarequired=1

	// TODO: truncated-answer
	r.GET("/probing/dns/query", func(ctx *gin.Context) {

		now := time.Now()

		const queryHost = "host"
		const queryName = "qname"
		const queryType = "qtype"
		const queryTimeout = "timeout"
		const queryMinAnswer = "min_answer"
		const queryMinAuthority = "min_authority"
		const queryRd = "rd"

		const queryRandomPrefix = "random_prefix"
		const queryAARequired = "aarequired"

		ctx.Status(http.StatusInternalServerError)

		logz := logrus.New()
		logz.SetFormatter(&logrus.TextFormatter{
			DisableColors: true,
			FullTimestamp: true,
		})

		if os.Getenv("LOG_LEVEL") == "debug" {
			logz.SetLevel(logrus.DebugLevel)
		}

		log := logz.WithField("req", ctx.Request.RequestURI)

		client := new(dns.Client)
		client.DialTimeout = 10 * time.Second
		client.WriteTimeout = 10 * time.Second
		client.ReadTimeout = DNSTimeout

		if requestQueryTimeout := ctx.Query(queryTimeout); requestQueryTimeout != "" {
			parse, err := time.ParseDuration(requestQueryTimeout)
			if err != nil {
				log.Error(err)
				return
			}

			if parse == 0 {
				log.Error("request timeout is zero")
				return
			}

			if parse < 1*time.Millisecond {
				parse = parse * time.Millisecond
			}

			client.ReadTimeout = parse
		}

		m := new(dns.Msg)

		qtypeStr := strings.ToUpper(ctx.Query(queryType))
		if qtypeStr == "" {
			log.Errorf("no qtype '%s'", qtypeStr)
			return
		}

		var qtype uint16
		switch qtypeStr {
		case "A":
			qtype = dns.TypeA
		case "NS":
			qtype = dns.TypeNS
		case "SOA":
			qtype = dns.TypeSOA
		case "CNAME":
			qtype = dns.TypeCNAME
		case "PTR":
			qtype = dns.TypePTR
		case "MX":
			qtype = dns.TypeMX
		case "AAAA":
			qtype = dns.TypeAAAA
		case "SRV":
			qtype = dns.TypeSRV
		default:
			log.Errorf("unsupported qtype '%s' from request '%s'", qtypeStr, ctx.Request.RequestURI)
			return
		}

		qname := ctx.Query(queryName)
		if qname == "" {
			log.Errorf("no qname '%s'", qname)
			return
		}

		qname = dns.Fqdn(qname)

		if randomPrefix := ctx.Query(queryRandomPrefix); randomPrefix != "" {

			placehold := randomPrefix
			r := rand.New(rand.NewSource(time.Now().UnixNano()))
			randNumber := r.Intn(900) + 100
			placehold = strings.Replace(placehold, "@time@", fmt.Sprintf("%d", now.Unix()), 1)
			placehold = strings.Replace(placehold, "@rand@", fmt.Sprintf("%d", randNumber), 1)

			qname = placehold + "." + qname
		}
		m.SetQuestion(qname, qtype)

		if validBool(ctx.Query(queryRd)) {
			m.RecursionDesired = true
		}

		serverIP, err := pickTargetIP(ctx.Query(queryHost))
		if err != nil {
			log.Error(err)
			return
		}

		r, _, err := client.Exchange(m, serverIP)
		if r == nil {
			log.Debugf("*** error: %s", err)
			return
		}

		if validBool(ctx.Query(queryAARequired)) && !r.Authoritative {
			log.Warnf("request requiring authoritative answer, but was not, got RCODE=%d", r.Rcode)
			return
		}

		if r.Rcode != dns.RcodeSuccess {
			if ctx.Query(queryRandomPrefix) != "" {
				if r.Rcode == dns.RcodeNameError {
					log.Debugf("request is random-prefixed domain, expecting = NXDOMAIN, return code = %d ", r.Rcode)
					ctx.Status(http.StatusOK)
					return
				}
			}
			log.Warnf("requested query has failed, return code = %d", r.Rcode)
			return
		}

		if requestMinAnswer := getIntFromString(ctx.Query(queryMinAnswer), 0); requestMinAnswer > 0 {
			if len(r.Answer) < requestMinAnswer {
				log.Debugf("not enough answers for request, wants = %d, got = %d", requestMinAnswer, len(r.Answer))
				return
			}
		}

		if requestMinAuth := getIntFromString(ctx.Query(queryMinAuthority), 0); requestMinAuth > 0 {
			if len(r.Ns) < requestMinAuth {
				log.Debugf("not enough authority answers for request, wants = %d, got = %d", requestMinAuth, len(r.Ns))
				return
			}
		}

		log.Debug("OK")
		ctx.Status(http.StatusOK)
	})

	logrus.Info("Listening on ", listenString)
	if err := http.ListenAndServe(listenString, r); err != nil {
		log.Panic(err)
	}
}

func resolveViaCustomDNS(domain, dnsServer string) ([]string, error) {
	c := new(dns.Client)
	c.DialTimeout = 1000 * time.Millisecond
	c.ReadTimeout = 1000 * time.Millisecond
	m := new(dns.Msg)
	m.SetQuestion(dns.Fqdn(domain), dns.TypeA)

	resp, _, err := c.Exchange(m, dnsServer)
	if err != nil {
		return nil, err
	}

	var ips []string
	for _, a := range resp.Answer {
		if arec, ok := a.(*dns.A); ok {
			ips = append(ips, arec.A.String())
		}
	}
	return ips, nil
}

func pickTargetIP(inputHost string) (string, error) {

	host, port, err := net.SplitHostPort(inputHost)
	if err != nil {
		// 포트가 없다면 기본 포트 지정
		host = inputHost
		port = "53"
	}

	if net.ParseIP(host) != nil {
		return net.JoinHostPort(host, port), nil
	}

	// 도메인인 경우 resolver 에 질의
	ips, err := resolveViaCustomDNS(host, resolverAddrString)
	if err != nil || len(ips) == 0 {
		return "", fmt.Errorf("DNS resolution failed: %w", err)
	}

	r := rand.New(rand.NewSource(time.Now().UnixNano()))

	pick := ips[r.Intn(len(ips))]
	pick = pick + ":" + port
	return pick, nil
}

In addition, before a DNS probe is executed, if the probe target itself is specified as a DNS domain name, there may be cases where DNS resolution is not possible at all (for example, resolver failure or delegation issues). It would be helpful to have built-in handling strategies or ideas for such situations (e.g., explicit failure states, fallback behavior, or stale handling).

I believe that native support for these capabilities would significantly improve cloudprober’s usefulness for advanced DNS monitoring scenarios.

Thank you for your consideration.

Activity

  1. added
    enhancement
    on Jan 1, 2026
  2. manugarg commented on Jan 6, 2026

    @manugarg
    Contributor

    Hello @kerus1024! Thanks for reporting this issue.

    Adding an option to config RD for the queries makes sense to me. Regarding your other suggestion about handling target DNS resolve failures -- for the most part we do cache target's resolved IPs, with retries and longer fallback to cache in case of failures. I am not sure if we want to complicate that further. In most cases, targets for DNS probes are configured either as IP or some other discovered resource like k8s service/endpoints.

  3. self-assigned this
    on Jul 28, 2026
  4. manugarg commented on Jul 28, 2026

    @manugarg
    Contributor

    @kerus1024,

    I think #1395 and #1396 implement your use case.

  5. added this to the v0.14.5 milestone on Jul 28, 2026
  6. added a commit that references this issue on Jul 29, 2026
    170f0f9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions