### Install go-metrics Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/rcrowley/go-metrics/README.md Command to install the library via go get. ```sh go get github.com/rcrowley/go-metrics ``` -------------------------------- ### Install go-proxyproto Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/pires/go-proxyproto/README.md Use 'go get' to install the go-proxyproto library. This command fetches and installs the latest version of the library. ```shell $ go get -u github.com/pires/go-proxyproto ``` -------------------------------- ### Install go-colorable Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/mattn/go-colorable/README.md Use the go get command to add the package to your project. ```bash $ go get github.com/mattn/go-colorable ``` -------------------------------- ### Install color library Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/fatih/color/README.md Command to install the package via go get. ```bash go get github.com/fatih/color ``` -------------------------------- ### Install doublestar Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/bmatcuk/doublestar/README.md Use the go get command to install the package. ```bash go get github.com/bmatcuk/doublestar ``` -------------------------------- ### Install go-isatty Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/mattn/go-isatty/README.md Command to install the library using the Go toolchain. ```bash $ go get github.com/mattn/go-isatty ``` -------------------------------- ### Install the YAML package Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/go.yaml.in/yaml/v3/README.md Use the go get command to add the package to your Go project. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Build and Install miekg/dns Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/acceptance_tests/dns-acceptance-release/src/test-recursor/vendor/github.com/miekg/dns/README.md Instructions for building and installing the miekg/dns library using Go modules. ```bash go get github.com/miekg/dns go build github.com/miekg/dns ``` -------------------------------- ### Install graphemes package Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/clipperhouse/uax29/v2/graphemes/README.md Use `go get` to add the graphemes package to your project. ```bash go get github.com/clipperhouse/uax29/v2/graphemes ``` -------------------------------- ### Install Ginkgo Locally Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Installs Ginkgo locally using go install. Ensure you have Go installed and configured. ```bash go install "./..." ``` -------------------------------- ### Initialize and Start a SOCKS5 Server Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/cloudfoundry/go-socks5/README.md Configures and starts a basic SOCKS5 proxy server on the local interface. Ensure the server is properly initialized before calling ListenAndServe. ```go // Create a SOCKS5 server conf := &socks5.Config{} server, err := socks5.New(conf) if err != nil { panic(err) } // Create SOCKS5 proxy on localhost port 8000 if err := server.ListenAndServe("tcp", "127.0.0.1:8000"); err != nil { panic(err) } ``` -------------------------------- ### Install Backoff Package Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/jpillora/backoff/README.md Use 'go get' to install the backoff package. This command fetches and installs the package and its dependencies. ```bash $ go get -v github.com/jpillora/backoff ``` -------------------------------- ### Example output Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/go.yaml.in/yaml/v3/README.md The expected output generated by the provided Go example code. ```text --- t: {Easy! {2 [3 4]}} --- t dump: a: Easy! b: c: 2 d: [3, 4] --- m: map[a:Easy! b:map[c:2 d:[3 4]]] --- m dump: a: Easy! b: c: 2 d: - 3 - 4 ``` -------------------------------- ### Install StatHat support Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/rcrowley/go-metrics/README.md Command to install the required StatHat Go client. ```sh go get github.com/stathat/go ``` -------------------------------- ### Serve Static Files Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/coredns/caddy/README.md Start the Caddy server to serve files from the current working directory. ```bash caddy ``` -------------------------------- ### Install otgrpc package Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc/README.md Command to install the OpenTracing gRPC middleware. ```bash go get github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc ``` -------------------------------- ### Install Counterfeiter Tool Dependency Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/maxbrunsfeld/counterfeiter/v6/README.md Add `counterfeiter` as a tool dependency using `go get -tool`. This is the first step before using `go generate` directives. ```shell go get -tool github.com/maxbrunsfeld/counterfeiter/v6 ``` -------------------------------- ### Define a Ginkgo Test Suite Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/onsi/ginkgo/v2/README.md A comprehensive example demonstrating Describe, Context, When, and It blocks to structure library checkout tests. ```go import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ... ) var _ = Describe("Checking books out of the library", Label("library"), func() { var library *libraries.Library var book *books.Book var valjean *users.User BeforeEach(func() { library = libraries.NewClient() book = &books.Book{ Title: "Les Miserables", Author: "Victor Hugo", } valjean = users.NewUser("Jean Valjean") }) When("the library has the book in question", func() { BeforeEach(func(ctx SpecContext) { Expect(library.Store(ctx, book)).To(Succeed()) }) Context("and the book is available", func() { It("lends it to the reader", func(ctx SpecContext) { Expect(valjean.Checkout(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Books()).To(ContainElement(book)) Expect(library.UserWithBook(ctx, book)).To(Equal(valjean)) }, SpecTimeout(time.Second * 5)) }) Context("but the book has already been checked out", func() { var javert *users.User BeforeEach(func(ctx SpecContext) { javert = users.NewUser("Javert") Expect(javert.Checkout(ctx, library, "Les Miserables")).To(Succeed()) }) It("tells the user", func(ctx SpecContext) { err := valjean.Checkout(ctx, library, "Les Miserables") Expect(err).To(MatchError("Les Miserables is currently checked out")) }, SpecTimeout(time.Second * 5)) It("lets the user place a hold and get notified later", func(ctx SpecContext) { Expect(valjean.Hold(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Holds(ctx)).To(ContainElement(book)) By("when Javert returns the book") Expect(javert.Return(ctx, library, book)).To(Succeed()) By("it eventually informs Valjean") notification := "Les Miserables is ready for pick up" Eventually(ctx, valjean.Notifications).Should(ContainElement(notification)) Expect(valjean.Checkout(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Books(ctx)).To(ContainElement(book)) Expect(valjean.Holds(ctx)).To(BeEmpty()) }, SpecTimeout(time.Second * 10)) }) }) When("the library does not have the book in question", func() { It("tells the reader the book is unavailable", func(ctx SpecContext) { err := valjean.Checkout(ctx, library, "Les Miserables") Expect(err).To(MatchError("Les Miserables is not in the library catalog")) }, SpecTimeout(time.Second * 5)) }) }) ``` -------------------------------- ### Simple Backoff Example Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/jpillora/backoff/README.md Demonstrates the basic usage of the backoff counter. It initializes a backoff with default settings, calls Duration() multiple times to observe increasing delays, and then resets it. ```go b := &backoff.Backoff{ //These are the defaults Min: 100 * time.Millisecond, Max: 10 * time.Second, Factor: 2, Jitter: false, } fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("Reset!\n") b.Reset() fmt.Printf("%s\n", b.Duration()) ``` ```text 100ms 200ms 400ms Reset! 100ms ``` -------------------------------- ### Convert format-string logs to structured key-value logs Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/go-logr/logr/README.md Examples demonstrating how to refactor standard format-string logging calls into structured logr-style calls. ```go klog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err) ``` ```go logger.Error(err, "client returned an error", "code", responseCode) ``` ```go klog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", seconds, retries, url) ``` ```go logger.V(4).Info("got a retry-after response when requesting url", "attempt", retries, "after seconds", seconds, "url", url) ``` ```go log.Printf("unable to reflect over type %T") ``` ```go logger.Info("unable to reflect over type", "type", fmt.Sprintf("%T")) ``` -------------------------------- ### Install Counterfeiter to `$GOPATH/bin` Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/maxbrunsfeld/counterfeiter/v6/README.md Install `counterfeiter` globally to your `$GOPATH/bin` directory. This allows invoking the `counterfeiter` command directly from your shell, even outside of a Go module. ```shell go install github.com/maxbrunsfeld/counterfeiter/v6 ~/go/bin/counterfeiter USAGE counterfeiter [-generate>] [-o ] [-p] [--fake-name ] [-header ] [] [-] ``` -------------------------------- ### Create Root Span Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/opentracing/opentracing-go/README.md Start a new trace without any parent or causal reference. ```go func xyz() { ... sp := opentracing.StartSpan("operation_name") defer sp.Finish() ... } ``` -------------------------------- ### macOS Test Setup Source: https://context7.com/cloudfoundry/bosh-dns-release/llms.txt Configure loopback interfaces and network settings on macOS for running tests. This involves aliasing IP addresses to the loopback interface and adjusting the maximum number of connections. ```bash sudo ifconfig lo0 alias 127.0.0.2 up sudo ifconfig lo0 alias 127.0.0.3 up sudo ifconfig lo0 alias 127.0.0.253 up sudo ifconfig lo0 alias 127.0.0.254 up sudo sysctl -w kern.ipc.somaxconn=1024 ``` -------------------------------- ### Full go-flags Example: Parsing Diverse Argument Types Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/jessevdk/go-flags/README.md Demonstrates parsing various command-line arguments including slices, callbacks, required flags, choices, pointers, maps, and environment variables. Use flags.ParseArgs for testing with predefined arguments; use flags.Parse for actual command-line parsing. ```go var opts struct { // Slice of bool will append 'true' each time the option // is encountered (can be set multiple times, like -vvv) Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"` // Example of automatic marshalling to desired type (uint) Offset uint `long:"offset" description:"Offset"` // Example of a callback, called each time the option is found. Call func(string) `short:"c" description:"Call phone number"` // Example of a required flag Name string `short:"n" long:"name" description:"A name" required:"true"` // Example of a flag restricted to a pre-defined set of strings Animal string `long:"animal" choice:"cat" choice:"dog"` // Example of a value name File string `short:"f" long:"file" description:"A file" value-name:"FILE"` // Example of a pointer Ptr *int `short:"p" description:"A pointer to an integer"` // Example of a slice of strings StringSlice []string `short:"s" description:"A slice of strings"` // Example of a slice of pointers PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"` // Example of a map IntMap map[string]int `long:"intmap" description:"A map from string to int"` // Example of env variable Thresholds []int `long:"thresholds" default:"1" default:"2" env:"THRESHOLD_VALUES" env-delim:","` } // Callback which will invoke callto: to call a number. // Note that this works just on OS X (and probably only with // Skype) but it shows the idea. opts.Call = func(num string) { cmd := exec.Command("open", "callto:"+num) cmd.Start() cmd.Process.Release() } // Make some fake arguments to parse. args := []string{ "-vv", "--offset=5", "-n", "Me", "--animal", "dog", // anything other than "cat" or "dog" will raise an error "-p", "3", "-s", "hello", "-s", "world", "--ptrslice", "hello", "--ptrslice", "world", "--intmap", "a:1", "--intmap", "b:5", "arg1", "arg2", "arg3", } // Parse flags from `args'. Note that here we use flags.ParseArgs for // the sake of making a working example. Normally, you would simply use // flags.Parse(&opts) which uses os.Args args, err := flags.ParseArgs(&opts, args) if err != nil { panic(err) } fmt.Printf("Verbosity: %v\n", opts.Verbose) fmt.Printf("Offset: %d\n", opts.Offset) fmt.Printf("Name: %s\n", opts.Name) fmt.Printf("Animal: %s\n", opts.Animal) fmt.Printf("Ptr: %d\n", *opts.Ptr) fmt.Printf("StringSlice: %v\n", opts.StringSlice) fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1]) fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"]) fmt.Printf("Remaining args: %s\n", strings.Join(args, " ")) // Output: Verbosity: [true true] // Offset: 5 // Name: Me // Ptr: 3 // StringSlice: [hello world] // PtrSlice: [hello world] // IntMap: [a:1 b:5] // Remaining args: arg1 arg2 arg3 ``` -------------------------------- ### Define Command Line Options with Struct Tags Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/jessevdk/go-flags/README.md Define command-line options using a struct and struct field tags. This example shows how to define a verbose flag that can be set multiple times. ```go type Options struct { Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"` } ``` -------------------------------- ### Configure Prometheus Metrics via Environment Variable Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/coredns/coredns/plugin/metrics/README.md This example demonstrates using an environment variable to set the listening address for Prometheus metrics, offering dynamic configuration. ```corefile . { prometheus localhost:{$PORT} } ``` -------------------------------- ### Log Information with logr.Logger in Go Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/go-logr/logr/README.md Example of emitting log messages using the logr.Logger interface. This snippet shows logging an informational message with associated key-value pairs. ```go func (app *appObject) Run() { app.logger.Info("starting up", "timestamp", time.Now()) // ... app code ... } ``` -------------------------------- ### Backoff with Jitter for Randomization Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/jpillora/backoff/README.md Shows how to enable 'Jitter' for randomized backoff durations. Seeding the random number generator is optional but allows for repeatable results. This example demonstrates the effect of jitter on consecutive calls and after a reset. ```go import "math/rand" b := &backoff.Backoff{ Jitter: true, } rand.Seed(42) fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("Reset!\n") b.Reset() fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) ``` ```text 100ms 106.600049ms 281.228155ms Reset! 100ms 104.381845ms 214.957989ms ``` -------------------------------- ### Sample Encoded Queries with New Scheme Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/docs/encoding_queries.md These examples demonstrate the new encoding scheme using a short dictionary. The default query includes status '0' (healthy), and additional parameters are appended. ```plaintext a100a101n102s0 ``` ```plaintext n102s0z103 ``` -------------------------------- ### Build Caddy with Plugins Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/coredns/caddy/README.md Create a custom main.go file to include plugins when building Caddy from source. ```go package main import ( "github.com/caddyserver/caddy/caddy/caddymain" // plug in plugins here, for example: // _ "import/path/here" ) func main() { // optional: disable telemetry // caddymain.EnableTelemetry = false caddymain.Run() } ``` -------------------------------- ### Initialize blockdevice FS Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/prometheus/procfs/README.md Initializes a blockdevice filesystem instance requiring access to both /proc and /sys. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Implement simple backoff Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/jpillora/backoff/README.md Demonstrates basic usage of the Backoff struct with default settings. ```go b := &backoff.Backoff{ //These are the defaults Min: 100 * time.Millisecond, Max: 10 * time.Second, Factor: 2, Jitter: false, } fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("Reset!\n") b.Reset() fmt.Printf("%s\n", b.Duration()) ``` -------------------------------- ### Create and update metrics Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/rcrowley/go-metrics/README.md Demonstrates initializing and updating various metric types including counters, gauges, histograms, meters, and timers. ```go c := metrics.NewCounter() metrics.Register("foo", c) c.Inc(47) g := metrics.NewGauge() metrics.Register("bar", g) g.Update(47) r := NewRegistry() g := metrics.NewRegisteredFunctionalGauge("cache-evictions", r, func() int64 { return cache.getEvictionsCount() }) s := metrics.NewExpDecaySample(1028, 0.015) // or metrics.NewUniformSample(1028) h := metrics.NewHistogram(s) metrics.Register("baz", h) h.Update(47) m := metrics.NewMeter() metrics.Register("quux", m) m.Mark(47) t := metrics.NewTimer() metrics.Register("bang", t) t.Time(func() {}) t.Update(47) ``` -------------------------------- ### Troubleshoot I/O Timeout Errors During 'go get' Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/google.golang.org/grpc/README.md This console output shows a typical I/O timeout error when trying to 'go get' gRPC-Go, indicating a network issue with accessing google.golang.org. ```console $ go get -u google.golang.org/grpc package google.golang.org/grpc: unrecognized import path "google.golang.org/grpc" (https fetch: Get https://google.golang.org/grpc?go-get=1: dial tcp 216.239.37.1:443: i/o timeout) ``` -------------------------------- ### Configure Separate Cache Sizes for Success and Denial Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/coredns/coredns/plugin/cache/README.md Enables caching for 'example.org' with a positive cache size of 5000 entries and a negative cache size (for denials) of 2500 entries. This allows fine-grained control over cache capacity for different response types. ```corefile example.org { cache { success 5000 denial 2500 } } ``` -------------------------------- ### Build All Files (Old System) Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/acceptance_tests/dns-acceptance-release/src/test-recursor/vendor/golang.org/x/sys/unix/README.md Use this script to generate Go files for your current OS and architecture using the old build system. Ensure GOOS and GOARCH are set correctly. Requirements: bash, go. ```bash mkall.sh ``` -------------------------------- ### Define Interface for Mocking Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/maxbrunsfeld/counterfeiter/v6/README.md Example interface definition used as the target for generating a test double. ```go package foo type MySpecialInterface interface { DoThings(string, uint64) (int, error) } ``` -------------------------------- ### Initialize QPACK Interop Files Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/quic-go/qpack/README.md Use this command to initialize the QPACK interop files as a git submodule. This is a prerequisite for running the interop tests. ```bash git submodule update --init --recursive ``` -------------------------------- ### Show Build Commands (Old System) Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/acceptance_tests/dns-acceptance-release/src/test-recursor/vendor/golang.org/x/sys/unix/README.md Run this command with the -n flag to see the build commands that will be executed by mkall.sh without actually running them. Requirements: bash, go. ```bash mkall.sh -n ``` -------------------------------- ### GET /instances - DNS API Endpoint Source: https://context7.com/cloudfoundry/bosh-dns-release/llms.txt Retrieves a list of all instances within the BOSH deployment. The response is newline-delimited JSON. ```APIDOC ## DNS API Endpoints The BOSH DNS server exposes an API for querying instance information and health state. The API runs on a configurable port (default 53080) with mutual TLS authentication. ### GET /instances * **Method**: GET * **Endpoint**: `https://:/instances` * **Description**: Retrieves all instances. * **Authentication**: Mutual TLS with `health.bosh-dns` common name. ### Request Example ```bash # Get all instances curl --cacert /var/vcap/jobs/bosh-dns/config/certs/api/server_ca.crt \ --cert /var/vcap/jobs/bosh-dns/config/certs/api/client.crt \ --key /var/vcap/jobs/bosh-dns/config/certs/api/client.key \ https://127.0.0.1:53080/instances ``` ### Response Example (Newline-delimited JSON) ```json {"id":"abc123","group":"web-server","network":"default","deployment":"cf","ip":"10.0.0.5","domain":"bosh.","az":"z1","index":"0","health_state":"running"} ``` ``` -------------------------------- ### Preview Documentation Changes Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Builds and serves the documentation locally using Jekyll. Navigate to the docs directory and run this command to preview your documentation updates. ```bash bundle && bundle exec jekyll serve ``` -------------------------------- ### Initialize procfs and read CPU statistics Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem mount point and retrieves CPU statistics from /proc/stat. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Example JSON Query for BOSH DNS Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/docs/encoding_queries.md This JSON structure represents a sample query that needs to be encoded into a hostname. Consider its character count when evaluating encoding methods. ```json { azs:[us-east-1,us-east-2], status:healthy, job:database } ``` -------------------------------- ### Benchmark Commands Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/cespare/xxhash/v2/README.md Commands to compare pure-Go and assembly implementations using benchstat. ```bash benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### Get All Instances via BOSH DNS API Source: https://context7.com/cloudfoundry/bosh-dns-release/llms.txt Use curl to query the BOSH DNS API for a list of all instances within the deployment. Requires mutual TLS authentication. ```bash # Get all instances curl --cacert /var/vcap/jobs/bosh-dns/config/certs/api/server_ca.crt \ --cert /var/vcap/jobs/bosh-dns/config/certs/api/client.crt \ --key /var/vcap/jobs/bosh-dns/config/certs/api/client.key \ https://127.0.0.1:53080/instances # Response (newline-delimited JSON): # {"id":"abc123","group":"web-server","network":"default","deployment":"cf","ip":"10.0.0.5","domain":"bosh.","az":"z1","index":"0","health_state":"running"} ``` -------------------------------- ### Read and scan /proc files Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Use util.ReadFileNoStat to read pseudo-files in one operation, then process with a bufio.Scanner. ```go data, err := util.ReadFileNoStat("/proc/cpuinfo") if err != nil { return err } reader := bytes.NewReader(data) scanner := bufio.NewScanner(reader) ``` -------------------------------- ### Run QPACK Interop Tests Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/quic-go/qpack/README.md Execute the interop tests for the QPACK implementation using the Go test command. Ensure interop files are initialized before running. ```bash go test -v ./interop ``` -------------------------------- ### View Interface File Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/maxbrunsfeld/counterfeiter/v6/README.md Display the contents of the Go file containing the interface to be mocked. ```shell $ cat path/to/foo/file.go ``` -------------------------------- ### Client: Write PROXY Protocol Header Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/pires/go-proxyproto/README.md Demonstrates how a client can write a PROXY protocol header before sending data. Ensure the target listener supports the PROXY protocol. The header can be constructed manually or using HeaderProxyFromAddrs if two connections are available. ```go package main import ( io "log" "net" proxyproto "github.com/pires/go-proxyproto" ) func chkErr(err error) { if err != nil { log.Fatalf("Error: %s", err.Error()) } } func main() { // Dial some proxy listener e.g. https://github.com/mailgun/proxyproto target, err := net.ResolveTCPAddr("tcp", "127.0.0.1:2319") chkErr(err) conn, err := net.DialTCP("tcp", nil, target) chkErr(err) defer conn.Close() // Create a proxyprotocol header or use HeaderProxyFromAddrs() if you // have two conn's header := &proxyproto.Header{ Version: 1, Command: proxyproto.PROXY, TransportProtocol: proxyproto.TCPv4, SourceAddr: &net.TCPAddr{ IP: net.ParseIP("10.1.1.1"), Port: 1000, }, DestinationAddr: &net.TCPAddr{ IP: net.ParseIP("20.2.2.2"), Port: 2000, }, } // After the connection was created write the proxy headers first _, err = header.WriteTo(conn) chkErr(err) // Then your data... e.g.: _, err = io.WriteString(conn, "HELO") chkErr(err) } ``` -------------------------------- ### Create Root Logger Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/go-logr/logr/README.md Initialize the root logger with a chosen implementation and initial parameters. This is typically done early in an application's lifecycle. ```Go func main() { // ... other setup code ... // Create the "root" logger. We have chosen the "logimpl" implementation, // which takes some initial parameters and returns a logr.Logger. logger := logimpl.New(param1, param2) // ... other setup code ... } ``` -------------------------------- ### Plug into existing code Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/fatih/color/README.md Apply global color settings to existing code blocks, ensuring they are unset afterwards. ```go // Use handy standard colors color.Set(color.FgYellow) fmt.Println("Existing text will now be in yellow") fmt.Printf("This one %s\n", "too") color.Unset() // Don't forget to unset // You can mix up parameters color.Set(color.FgMagenta, color.Bold) defer color.Unset() // Use it in your function fmt.Println("All text will now be bold magenta.") ``` -------------------------------- ### Create and Use EWMA Averages Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/VividCortex/ewma/README.md Demonstrates creating both SimpleEWMA and VariableEWMA instances and adding samples to them. SimpleEWMA is created with no parameters, while VariableEWMA requires a decay parameter. Note the different resulting values. ```go package main import "github.com/VividCortex/ewma" func main() { samples := [100]float64{ 4599, 5711, 4746, 4621, 5037, 4218, 4925, 4281, 5207, 5203, 5594, 5149, } e := ewma.NewMovingAverage() //=> Returns a SimpleEWMA if called without params a := ewma.NewMovingAverage(5) //=> returns a VariableEWMA with a decay of 2 / (5 + 1) for _, f := range samples { e.Add(f) a.Add(f) } e.Value() //=> 13.577404704631077 a.Value() //=> 1.5806140565521463e-12 } ``` -------------------------------- ### Manage Go dependencies Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Commands to fetch specific versions of external packages. ```bash # Pick the latest tagged release. go get example.com/some/module/pkg # Pick a specific version. go get example.com/some/module/pkg@vX.Y.Z ``` -------------------------------- ### Import doublestar Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/bmatcuk/doublestar/README.md Include the package in your Go source files. ```go import "github.com/bmatcuk/doublestar" ``` -------------------------------- ### View Caddy CLI Help Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/coredns/caddy/README.md Displays basic help information for the Caddy command-line interface. For more details, refer to the official CLI documentation. ```bash caddy -h ``` -------------------------------- ### Server: Accept PROXY Protocol Connections Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/pires/go-proxyproto/README.md Wraps a standard net.Listener with a proxyproto.Listener to accept connections with PROXY protocol headers. The remote and local addresses of the connection will be populated from the header. ```go package main import ( "log" "net" proxyproto "github.com/pires/go-proxyproto" ) func main() { // Create a listener addr := "localhost:9876" list, err := net.Listen("tcp", addr) if err != nil { log.Fatalf("couldn't listen to %q: %q\n", addr, err.Error()) } // Wrap listener in a proxyproto listener proxyListener := &proxyproto.Listener{Listener: list} defer proxyListener.Close() // Wait for a connection and accept it conn, err := proxyListener.Accept() defer conn.Close() // Print connection details if conn.LocalAddr() == nil { log.Fatal("couldn't retrieve local address") } log.Printf("local address: %q", conn.LocalAddr().String()) if conn.RemoteAddr() == nil { log.Fatal("couldn't retrieve remote address") } log.Printf("remote address: %q", conn.RemoteAddr().String()) } ``` -------------------------------- ### Check Version Against Constraints Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/Masterminds/semver/v3/README.md Parses a constraint string and a version string, then evaluates if the version satisfies the constraint. ```go c, err := semver.NewConstraint(">= 1.2.3") if err != nil { // Handle constraint not being parsable. } v, err := semver.NewVersion("1.3") if err != nil { // Handle version not being parsable. } // Check if the version meets the constraints. The variable a will be true. a := c.Check(v) ``` -------------------------------- ### Backoff with Net Package for Retries Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/jpillora/backoff/README.md Illustrates using backoff with the 'net' package for handling network connection retries. It attempts to establish a TCP connection and, upon failure, waits for a backoff duration before retrying. ```go b := &backoff.Backoff{ Max: 5 * time.Minute, } for { conn, err := net.Dial("tcp", "example.com:5309") if err != nil { d := b.Duration() fmt.Printf("%s, reconnecting in %s", err, d) time.Sleep(d) continue } //connected b.Reset() conn.Write([]byte("hello world!")) // ... Read ... Write ... etc conn.Close() //disconnected } ``` -------------------------------- ### Use custom io.Writer Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/debug/vendor/github.com/fatih/color/README.md Direct colorized output to a specific io.Writer. ```go // Use your own io.Writer output color.New(color.FgBlue).Fprintln(myWriter, "blue color!") blue := color.New(color.FgBlue) blue.Fprint(writer, "This will print text in blue.") ``` -------------------------------- ### Unmarshal and Marshal YAML in Go Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/go.yaml.in/yaml/v2/README.md Demonstrates how to unmarshal YAML data into a struct and a map, and then marshal them back into YAML format. Ensure struct fields are public for correct unmarshalling. ```Go package main import ( "fmt" "log" "go.yaml.in/yaml/v2" ) var data = ` a: Easy! b: c: 2 d: [3, 4] ` // Note: struct fields must be public in order for unmarshal to // correctly populate the data. type T struct { A string B struct { RenamedC int `yaml:"c"` D []int `yaml:",flow"` } } func main() { t := T{} err := yaml.Unmarshal([]byte(data), &t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t:\n%v\n\n", t) d, err := yaml.Marshal(&t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t dump:\n%s\n\n", string(d)) m := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(data), &m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m:\n%v\n\n", m) d, err = yaml.Marshal(&m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m dump:\n%s\n\n", string(d)) } ``` -------------------------------- ### Instantiate Generated Fake Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/maxbrunsfeld/counterfeiter/v6/README.md Import the generated package and instantiate the fake object for use in tests. ```go import "my-repo/path/to/foo/foofakes" var fake = &foofakes.FakeMySpecialInterface{} ``` -------------------------------- ### Go Configuration Structures Source: https://context7.com/cloudfoundry/bosh-dns-release/llms.txt Defines the Go configuration structures for BOSH DNS. Useful for understanding the configuration schema and building tools that interact with BOSH DNS. ```go package config import ( "time" ) type Config struct { Address string `json:"address"` Port int `json:"port"` BindTimeout DurationJSON `json:"timeout,omitempty"` RecursorMaxRetries int `json:"recursor_max_retries,omitempty"` RequestTimeout DurationJSON `json:"request_timeout,omitempty"` RecursorTimeout DurationJSON `json:"recursor_timeout,omitempty"` Recursors []string `json:"recursors,omitempty"` DisableRecursors bool `json:"disable_recursors,omitempty"` ConfigureSystemdResolved bool `json:"configure_systemd_resolved,omitempty"` ExcludedRecursors []string `json:"excluded_recursors,omitempty"` RecordsFile string `json:"records_file,omitempty"` RecursorSelection string `json:"recursor_selection"` // "smart" or "serial" AliasFilesGlob string `json:"alias_files_glob,omitempty"` HandlersFilesGlob string `json:"handlers_files_glob,omitempty"` AddressesFilesGlob string `json:"addresses_files_glob,omitempty"` UpcheckDomains []string `json:"upcheck_domains,omitempty"` JobsDir string `json:"jobs_dir,omitempty"` LogLevel string `json:"log_level,omitempty"` API APIConfig `json:"api"` Health HealthConfig `json:"health"` Metrics MetricsConfig `json:"metrics"` Cache Cache `json:"cache"` InternalUpcheckDomain InternalUpcheckDomain `json:"internal_upcheck_domain"` Logging LoggingConfig `json:"logging,omitempty"` } type APIConfig struct { Port int `json:"port"` CertificateFile string `json:"certificate_file"` PrivateKeyFile string `json:"private_key_file"` CAFile string `json:"ca_file"` } type HealthConfig struct { Enabled bool `json:"enabled"` Port int `json:"port"` CertificateFile string `json:"certificate_file"` PrivateKeyFile string `json:"private_key_file"` CAFile string `json:"ca_file"` CheckInterval DurationJSON `json:"check_interval,omitempty"` MaxTrackedQueries int `json:"max_tracked_queries,omitempty"` SynchronousCheckTimeout DurationJSON `json:"synchronous_check_timeout,omitempty"` } type MetricsConfig struct { Enabled bool `json:"enabled"` Address string `json:"address"` Port int `json:"port"` } ``` ```go // Example: Load configuration from file func LoadConfig(path string) (*Config, error) { cfg, err := LoadFromFile(path) if err != nil { return nil, err } return &cfg, nil } ``` ```go // Example: Create default configuration func DefaultConfig() Config { return NewDefaultConfig() } ``` -------------------------------- ### Define OS interface Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/bmatcuk/doublestar/README.md Interface for abstracting filesystem operations, allowing custom implementations or cross-platform testing. ```go type OS interface { Lstat(name string) (os.FileInfo, error) Open(name string) (*os.File, error) PathSeparator() rune Stat(name string) (os.FileInfo, error) } ``` -------------------------------- ### Run project tests Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Execute the test suite to ensure changes are valid before committing. ```makefile make test # Make sure all the tests pass before you commit and push :) ``` -------------------------------- ### Update Go modules and vendor directory Source: https://github.com/cloudfoundry/bosh-dns-release/blob/master/src/bosh-dns/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Commands to clean up module files and synchronize the vendor directory. ```bash # The GO111MODULE variable can be omitted when the code isn't located in GOPATH. GO111MODULE=on go mod tidy GO111MODULE=on go mod vendor ```