### Basic WebService Setup in go-restful Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/emicklei/go-restful/v3/README.md This example illustrates the basic setup of a WebService in go-restful. It defines the path, supported content types (consumes and produces), and routes for handling HTTP requests. ```go ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) ws.Route(ws.GET("/{user-id}").To(u.findUser). Doc("get a user"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")), Writes(User{})) ... func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") ... } ``` -------------------------------- ### Install Mergo Library Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/imdario/mergo/README.md Instructions for installing the Mergo library using the Go build tool. This is a prerequisite for using Mergo in your Go projects. ```go go get github.com/imdario/mergo ``` -------------------------------- ### Slack Release Announcement Example Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/sigs.k8s.io/controller-runtime/RELEASE.md An example of how to format a release announcement for the Slack channel. It includes key information like the version released, dependency changes, and a link to the release page. ```text :announce: Controller-Runtime v0.12.0 has been released! This release includes a Kubernetes dependency bump to v1.24. For more info, see the release page: https://github.com/kubernetes-sigs/controller-runtime/releases. :tada: Thanks to all our contributors! ``` -------------------------------- ### Install and Run Ginkgo Tests Locally Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md This snippet shows how to install Ginkgo locally, run tests with specific flags, and vet the code. It's essential for verifying changes before committing. ```bash go install "./..." ginkgo -r -p go vet "./..." ``` -------------------------------- ### Ginkgo Test Specification Example in Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/onsi/ginkgo/v2/README.md This Go code snippet demonstrates how to use Ginkgo for writing test specifications. It includes setup (BeforeEach), defining test cases (It, Context, When), and assertions using Gomega matchers. It also shows SpecContext for managing test execution scope and SpecTimeout for setting timeouts. ```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)) }) }) ``` -------------------------------- ### Setup: Clone zap repository and configure remotes (Bash) Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/go.uber.org/zap/CONTRIBUTING.md This snippet demonstrates how to clone the zap repository, set up upstream remote, and fetch changes. It assumes a Go development environment is already configured. ```bash mkdir -p $GOPATH/src/go.uber.org cd $GOPATH/src/go.uber.org git clone git@github.com:your_github_username/zap.git cd zap git remote add upstream https://github.com/uber-go/zap.git git fetch upstream ``` -------------------------------- ### Basic Structured Logging Example in Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/go-kit/log/README.md Demonstrates the difference between unstructured and structured logging using the Go kit log package. It shows how to log a message with contextual key-value pairs. ```go // Unstructured log.Printf("HTTP server listening on %s", addr) // Structured logger.Log("transport", "HTTP", "addr", addr, "msg", "listening") ``` -------------------------------- ### Setup: Run tests and linters (Bash) Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/go.uber.org/zap/CONTRIBUTING.md This snippet shows the commands to execute tests and linters for the zap project. These commands are essential for ensuring code quality and correctness. ```bash make test make lint ``` -------------------------------- ### Install json-iterator/go using go get Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/json-iterator/go/README.md This command installs the json-iterator/go library using Go's module system. It fetches the latest version of the library and makes it available for use in your Go projects. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Typical Application Logging with Logfmt in Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/go-kit/log/README.md Shows how to set up a basic structured logger using the Logfmt format and write logs to standard error. This example illustrates logging a simple key-value pair. ```go w := log.NewSyncWriter(os.Stderr) logger := log.NewLogfmtLogger(w) logger.Log("question", "what is the meaning of life?", "answer", 42) // Output: // question="what is the meaning of life?" answer=42 ``` -------------------------------- ### VirtualMachine with Allocated MAC Addresses (Output Example) Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/doc/vm-creation-example.md An example snippet showing the relevant parts of a VirtualMachine's YAML output after MAC addresses have been allocated by Kubemacpool. It highlights the `macAddress` field for both the default masquerade interface and the 'br1' bridge interface, demonstrating successful allocation. ```yaml apiVersion: kubevirt.io/v1 kind: VirtualMachine metadata: name: samplevm spec: domain: ... devices: ... interfaces: - macAddress: "02:00:00:00:00:09" masquerade: {} name: default - bridge: {} macAddress: "02:00:00:00:00:0a" ... ``` -------------------------------- ### Create VirtualMachine with Secondary NIC and MAC Allocation Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/doc/vm-creation-example.md Defines and creates a VirtualMachine named 'samplevm' with a secondary network interface configured to use the 'br1' NetworkAttachmentDefinition. This configuration implicitly uses Kubemacpool for MAC address allocation to the virtual machine's interfaces. The example shows how to specify the network attachment and includes a basic VM domain and network setup. ```yaml cat << EOF | kubectl create -f - apiVersion: kubevirt.io/v1 kind: VirtualMachine metadata: name: samplevm spec: runStrategy: Halted template: spec: domain: devices: disks: - disk: bus: virtio name: rootfs - disk: bus: virtio name: cloudinit interfaces: - name: default masquerade: {} - bridge: {} name: br1 resources: requests: memory: 64M networks: - name: default pod: {} - multus: networkName: br1 name: br1 volumes: - name: rootfs containerDisk: image: kubevirt/cirros-registry-disk-demo - name: cloudinit cloudInitNoCloud: userDataBase64: SGkuXG4= EOF ``` -------------------------------- ### Development Panic Example - Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/go.uber.org/zap/FAQ.md Demonstrates the use of 'DPanic' for catching errors in development that should not occur in production. This example shows how to log at 'PanicLevel' in development and 'ErrorLevel' otherwise, preventing production crashes. ```go if err != nil { panic(fmt.Sprintf("shouldn't ever get here: %v", err)) } ``` -------------------------------- ### Install YAML Dependency for Testing Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/imdario/mergo/README.md A command to install the `gopkg.in/yaml.v3` package, which may be required if tests related to Mergo are failing due to missing dependencies. This is typically run in the terminal. ```bash go get gopkg.in/yaml.v3 ``` -------------------------------- ### Preview Ginkgo Documentation Changes Locally Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md This command sequence allows contributors to preview their documentation changes locally using Jekyll. It requires Bundler to be installed. ```bash bundle && bundle exec jekyll serve ``` -------------------------------- ### Initialize Procfs and Get CPU Stats (Go) Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/prometheus/procfs/README.md This snippet demonstrates how to initialize the proc filesystem and retrieve CPU statistics. It requires the path to the proc filesystem as input and returns the CPU statistics or an error. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Install YAML Package for Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/gopkg.in/yaml.v2/README.md Command to install the 'gopkg.in/yaml.v2' package using the Go build tools. This is a prerequisite for using the YAML encoding and decoding functionalities in Go projects. ```bash go get gopkg.in/yaml.v2 ``` -------------------------------- ### Mergo Example: Merging Structs Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/imdario/mergo/README.md A complete Go program demonstrating the practical application of Mergo's `Merge` function. It defines two `Foo` structs, merges the source into the destination, and prints the result, showing how fields are combined. ```go package main import ( "fmt" "github.com/imdario/mergo" ) type Foo struct { A string B int64 } func main() { src := Foo{ A: "one", B: 2, } dest := Foo{ A: "two", } mergo.Merge(&dest, src) fmt.Println(dest) // Will print // {two 2} } ``` -------------------------------- ### Coexist klog with glog in Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/k8s.io/klog/v2/README.md Illustrates how to run klog and glog side-by-side within the same application. The example focuses on synchronizing flags from the global `flag.CommandLine` FlagSet and setting `alsologtostderr` or `logtostderr` for combined output. ```go // This is a conceptual example. Actual implementation details would be in the examples/coexist_glog/coexist_glog.go file. import ( glog "github.com/golang/glog" "k8s.io/klog/v2" flag "flag" ) func main() { // Example of synchronizing flags - specific code would be in the example file. flag.Parse() // Example of setting stderr output klog.SetOutput(os.Stderr) glog.CopyStandardLogTo("stderr") glog.Info("Message from glog") klog.Info("Message from klog") // ... rest of your application code } ``` -------------------------------- ### Coexist klog/v1 and klog/v2 in Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/k8s.io/klog/v2/README.md Provides an example demonstrating how to use both klog/v1 and klog/v2 within the same Go project. This is often necessary during migration phases or when dealing with dependencies that use different versions of klog. ```go // This is a conceptual example. Actual implementation details would be in the examples/coexist_klog_v1_and_v2/ directory. import ( "k8s.io/klog/v1" "k8s.io/klog/v2" ) func main() { // Initialize both versions if necessary, ensuring flag conflicts are managed. // The specific example would show how to handle imports and potentially flag sets. klogv1.Info("Message from klog v1") klogv2.Info("Message from klog v2") // ... rest of your application code } ``` -------------------------------- ### Install Open vSwitch and Create Bridge on Node Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/doc/pod-creation-example.md Installs Open vSwitch and its dependencies on a specified node and then creates a new Open vSwitch bridge named 'br1'. This is a prerequisite for network attachment. ```bash node=node01 ./cluster/cli.sh ssh ${node} -- sudo yum install -y http://cbs.centos.org/kojifiles/packages/openvswitch/2.9.2/1.el7/x86_64/openvswitch-2.9.2-1.el7.x86_64.rpm http://cbs.centos.org/kojifiles/packages/openvswitch/2.9.2/1.el7/x86_64/openvswitch-devel-2.9.2-1.el7.x86_64.rpm http://cbs.centos.org/kojifiles/packages/dpdk/17.11/3.el7/x86_64/dpdk-17.11-3.el7.x86_64.rpm ./cluster/cli.sh ssh ${node} -- sudo systemctl daemon-reload ./cluster/cli.sh ssh ${node} -- sudo systemctl restart openvswitch ./cluster/cli.sh ssh ${node} -- sudo ovs-vsctl add-br br1 ``` -------------------------------- ### Run Tests with Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/gopkg.in/evanphx/json-patch.v4/README.md This command executes all tests within the project using Go's built-in testing framework. It also reports code coverage. Ensure Go is installed and the project is cloned locally to run this command. ```bash go test -cover ./... ``` -------------------------------- ### Initialize Block Device FS and Get Disk Stats (Go) Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/prometheus/procfs/README.md This snippet shows how to initialize a filesystem that accesses both proc and sys for block device information. It takes paths to both filesystems as input and retrieves disk statistics. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Command Line Flag Syntax Examples Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/spf13/pflag/README.md Demonstrates the syntax for defining and using command-line flags, including boolean flags, flags with values, and shorthand notations. It highlights differences between single and double dashes and the behavior of flag parsing with arguments and terminators. ```Go ``` --flag // boolean flags, or flags with no option default values --flag x // only on flags without a default value --flag=x ``` Unlike the flag package, a single dash before an option means something different than a double dash. Single dashes signify a series of shorthand letters for flags. All but the last shorthand letter must be boolean flags or a flag with a default value ``` // boolean or flags where the 'no option default value' is set -f -f=true -abc but -b true is INVALID // non-boolean and flags without a 'no option default value' -n 1234 -n=1234 -n1234 // mixed -abcs "hello" -absd="hello" -abcs1234 ``` Flag parsing stops after the terminator "--". Unlike the flag package, flags can be interspersed with arguments anywhere on the command line before this terminator. Integer flags accept 1234, 0664, 0x1234 and may be negative. Boolean flags (in their long form) accept 1, 0, t, f, true, false, TRUE, FALSE, True, False. Duration flags accept any input valid for time.ParseDuration. ``` -------------------------------- ### Go YAML Encoding and Decoding Example Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/gopkg.in/yaml.v3/README.md Demonstrates how to use the yaml package in Go to unmarshal YAML data into a struct and a map, and then marshal them back into YAML format. Requires the 'gopkg.in/yaml.v3' package. ```Go package main import ( "fmt" "log" "gopkg.in/yaml.v3" ) 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)) } ``` -------------------------------- ### Deploy Kubemacpool from Release Manifest (Bash) Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/doc/deployment-on-arbitrary-cluster.md This snippet downloads the Kubemacpool release manifest, customizes the MAC address range using openssl and sed, and applies the manifest to the cluster. It requires wget, openssl, sed, and kubectl to be installed and configured. ```bash wget https://raw.githubusercontent.com/k8snetworkplumbingwg/kubemacpool/master/config/release/kubemacpool.yaml mac_oui=02:`openssl rand -hex 1`:`openssl rand -hex 1` sed -i "s/02:00:00:00:00:00/$mac_oui:00:00:00/" kubemacpool.yaml sed -i "s/02:FF:FF:FF:FF:FF/$mac_oui:FF:FF:FF/" kubemacpool.yaml kubectl apply -f ./kubemacpool.yaml ``` -------------------------------- ### Basic glog Usage in Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/k8s.io/klog/v2/README.md Demonstrates basic logging functions like Info and Fatalf provided by the glog package. These functions allow for different levels of logging output. ```go glog.Info("Prepare to repel boarders") glog.Fatalf("Initialization failed: %s", err) ``` -------------------------------- ### Build mkall.go Program - New System Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/golang.org/x/sys/unix/README.md The `mkall.go` program coordinates the generation of Go files for the sys/unix package using a Docker container. This program is located in the `${GOOS}` directory and is part of the new build system, primarily for `GOOS == "linux"`. It requires bash, go, and docker. The build process generates files for all GOOS/GOARCH pairs supported by the new build system. ```go package main import ( "fmt" "os" "os/exec" "path/filepath" "strings" ) func main() { // Ensure we are on Linux amd64 for this build system // ... platform checks ... // Iterate through GOOS/GOARCH pairs and generate files // ... loop and exec commands ... fmt.Println("All sys/unix files generated successfully.") } // Helper function to run commands within the Docker container func runInDocker(cmdArgs []string) error { // ... docker run command construction ... return nil } ``` -------------------------------- ### Build mkall.sh Script - New System Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/golang.org/x/sys/unix/README.md The `mkall.sh` script is used in the new build system to generate all Go files for the sys/unix package by invoking the `mkall.go` program within a Docker container. This script is intended for use on an amd64/Linux system with GOOS and GOARCH set appropriately. It requires bash, go, and docker. Running `mkall.sh -n` shows the commands that will be run. ```bash #!/bin/bash # Default GOOS and GOARCH if not set GOOS=${GOOS:-$(go env GOOS)} GOARCH=${GOARCH:-$(go env GOARCH)} if [[ "$GOOS" != "linux" || "$GOARCH" != "amd64" ]]; then echo "Warning: New build system is intended for linux/amd64. Results may vary." fi if [[ "$1" == "-n" ]]; then echo "Running mkall.sh -n with GOOS=$GOOS GOARCH=$GOARCH" # Show commands without executing echo "docker build -t sys-unix-builder . && docker run --rm -v \"$(pwd):/src\" sys-unix-builder go run ${GOOS}/mkall.go" else echo "Generating all sys/unix files using Docker for GOOS=$GOOS GOARCH=$GOARCH" # Build and run the Docker image docker build -t sys-unix-builder . docker run --rm -v "$(pwd):/src" sys-unix-builder go run ${GOOS}/mkall.go fi ``` -------------------------------- ### Quick Start: Logger for Performance-Critical Logging in Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/go.uber.org/zap/README.md Illustrates the initialization and usage of the Logger for performance-critical scenarios. This logger prioritizes speed and minimal allocations by exclusively supporting structured logging with strongly typed Field values. It is recommended for hot paths where performance and type safety are paramount. ```go logger, _ := zap.NewProduction() deferr logger.Sync() logger.Info("failed to fetch URL", // Structured context as strongly typed Field values. zap.String("url", url), zap.Int("attempt", 3), zap.Duration("backoff", time.Second) ) ``` -------------------------------- ### Kubernetes Pod MAC Address Allocation Example (YAML) Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/doc/design.md This example demonstrates the modification of a Pod's NetworkAttachmentDefinition to include a MAC address, illustrating the 'pre' and 'post' admission control intervention states for MAC address allocation. ```yaml apiVersion: v1 kind: Pod metadata: name: pod0 annotations: k8s.v1.cni.cncf.io/networks: '[ { "name" : "macvlan-conf-3" } ]' spec: containers: name: pod0 image: docker.io/centos/tools:latest command: /sbin/init ``` ```yaml # Post admission control intervention: apiVersion: v1 kind: Pod metadata: name: pod0 annotations: k8s.v1.cni.cncf.io/networks: '[ { "name" : "macvlan-conf-3","mac": "c2:b0:57:49:47:f1" } ]' spec: containers: name: pod0 image: docker.io/centos/tools:latest command: /sbin/init ``` -------------------------------- ### Run xxhash benchmarks with different implementations (Shell) Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/cespare/xxhash/v2/README.md This snippet demonstrates how to run benchmarks for the `xxhash` package using `go test` and `benchstat`. It shows commands for comparing the performance of the pure Go implementation (`-tags purego`) against the optimized assembly implementation for the `Sum64` function. ```bash # Benchmark pure Go implementation benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') # Benchmark optimized assembly implementation benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### Log Using logr with Zapr and Zap Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/go-logr/zapr/README.md This Go code snippet demonstrates how to initialize a Zap logger, create a logr.Logger using zapr, and log a message with associated key-value pairs. It requires the 'go.uber.org/zap' and 'github.com/go-logr/zapr' packages. ```go package main import ( "fmt" "go.uber.org/zap" "github.com/go-logr/logr" "github.com/go-logr/zapr" ) func main() { var log logr.Logger zapLog, err := zap.NewDevelopment() if err != nil { panic(fmt.Sprintf("who watches the watchmen (%v)?", err)) } log = zapr.NewLogger(zapLog) log.Info("Logr in action!", "the answer", 42) } ``` -------------------------------- ### Example VirtualMachine MAC Address Configuration Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/README.md This YAML snippet illustrates a VirtualMachine specification where Kubemacpool can allocate a MAC address. It shows the `macAddress` field within the `devices.interfaces` section, which is typically managed by Kubemacpool. ```yaml apiVersion: kubevirt.io/v1 kind: VirtualMachine metadata: name: simplevm spec: template: spec: domain: devices: interfaces: - macAddress: "02:00:00:00:00:00" masquerade: {} name: default networks: - name: default pod: {} ... ``` -------------------------------- ### Quick Start: SugaredLogger for Flexible Logging in Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/go.uber.org/zap/README.md Demonstrates how to initialize and use the SugaredLogger for flexible logging. This logger supports both structured and printf-style output, offering a balance between performance and ease of use. It is suitable for contexts where performance is important but not the absolute critical factor. ```go logger, _ := zap.NewProduction() deferr logger.Sync() // flushes buffer, if any sugar := logger.Sugar() sugar.Infow("failed to fetch URL", // Structured context as loosely typed key-value pairs. "url", url, "attempt", 3, "backoff", time.Second, ) sugar.Infof("Failed to fetch URL: %s", url) ``` -------------------------------- ### Handle SIGHUP to Rotate Logs - Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/gopkg.in/natefinch/lumberjack.v2/README.md Example demonstrating how to handle the SIGHUP signal to trigger log rotation using the Logger.Rotate() method. It sets up signal notification and a goroutine to listen for the signal. ```go l := &lumberjack.Logger{} log.SetOutput(l) c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP) go func() { for { <-c l.Rotate() } }() ``` -------------------------------- ### Basic Logging with glog in Go Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/golang/glog/README.md Demonstrates basic usage of the glog package for logging informational messages and fatal errors. It requires importing the 'glog' package. ```go package main import ( "github.com/golang/glog" "os" ) func main() { // Basic informational log glog.Info("Prepare to repel boarders") // Fatal error log, will terminate the program var err error // Assuming err is defined and potentially has an error value glog.Fatalf("Initialization failed: %s", err) // Ensure logs are flushed before exiting (important for some log configurations) glog.Flush() defer glog.Flush() } ``` -------------------------------- ### TagSet and TagOptions for CBOR Decoding/Encoding (Go) Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/fxamacker/cbor/v2/README.md Provides an example of creating a TagSet to register custom CBOR tags and their corresponding Go types. It shows how to create decoding and encoding modes with these custom tags and use them for unmarshalling and marshalling data. ```go // Use signedCWT struct defined in "Decoding CWT" example. // Create TagSet (safe for concurrency). tags := cbor.NewTagSet() // Register tag COSE_Sign1 18 with signedCWT type. tags.Add( cbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired}, reflect.TypeOf(signedCWT{}), 18) // Create DecMode with immutable tags. dm, _ := cbor.DecOptions{}.DecModeWithTags(tags) // Unmarshal to signedCWT with tag support. var v signedCWT if err := dm.Unmarshal(data, &v); err != nil { return err } // Create EncMode with immutable tags. em, _ := cbor.EncOptions{}.EncModeWithTags(tags) // Marshal signedCWT with tag number. if data, err := cbor.Marshal(v); err != nil { return err } ``` -------------------------------- ### Set Interface{} Value using reflect2 (Go) Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/modern-go/reflect2/README.md Demonstrates how to set the value of an interface{} type using reflect2. It requires passing a pointer to the target variable. The example shows changing the value of 'i' to 'j'. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.Set(&i, &j) // i will be 10 // to get set `type`, always use its pointer `*type` ``` -------------------------------- ### Set Unsafe.Pointer Value using reflect2 (Go) Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/modern-go/reflect2/README.md Illustrates setting a value through an unsafe.Pointer using reflect2. This method also requires pointers and allows modification of the target variable. The example changes 'i' to the value of 'j'. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.UnsafeSet(unsafe.Pointer(&i), unsafe.Pointer(&j)) // i will be 10 // to get set `type`, always use its pointer `*type` ``` -------------------------------- ### Kubernetes ConfigMap for MAC Address Ranges Source: https://context7.com/k8snetworkplumbingwg/kubemacpool/llms.txt Defines the start and end of the MAC address pool using a Kubernetes ConfigMap. This configuration is read by the Kubemacpool controller to manage MAC address allocation. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: kubemacpool-mac-range-config namespace: kubemacpool-system data: RANGE_START: "02:00:00:00:00:00" RANGE_END: "02:FF:FF:FF:FF:FF" ``` -------------------------------- ### VirtualMachine MAC Address Assignment (YAML Example) Source: https://context7.com/k8snetworkplumbingwg/kubemacpool/llms.txt Illustrates a KubeVirt VirtualMachine definition where Kubemacpool automatically assigns MAC addresses to its network interfaces. The webhook handles CREATE and UPDATE operations for VirtualMachines. ```yaml // Webhook registration at /mutate-virtualmachines // Handles: CREATE and UPDATE operations on kubevirt.io/v1/VirtualMachines // Example VirtualMachine with automatic MAC assignment apiVersion: kubevirt.io/v1 kind: VirtualMachine metadata: name: testvm namespace: default spec: running: true template: spec: domain: devices: interfaces: - name: default masquerade: {} - name: network1 bridge: {} resources: requests: memory: 1024M networks: - name: default pod: {} - name: network1 multus: networkName: bridge-network // After webhook mutation, interfaces include assigned MACs: // interfaces: // - name: default // masquerade: {} // macAddress: "02:00:00:00:00:01" // - name: network1 // bridge: {} // macAddress: "02:00:00:00:00:02" // // And a transaction timestamp annotation is added: // metadata: // annotations: // kubemacpool.io/transaction-timestamp: "2025-10-30T10:15:30.123456789Z" ``` -------------------------------- ### Gob Decoding Out-of-Memory Error Example Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/github.com/fxamacker/cbor/v2/README.md Demonstrates a scenario where encoding/gob encounters a 'fatal error: runtime: out of memory' during decoding. This highlights the security and memory safety limitations of encoding/gob when dealing with potentially adversarial inputs, contrasting it with more robust libraries like fxamacker/cbor. ```Go // Example of encoding/gob having "fatal error: runtime: out of memory" // while decoding 181 bytes. package main import ( "bytes" "encoding/gob" "encoding/hex" "fmt" ) // Example data is from https://github.com/golang/go/issues/24446 // (shortened to 181 bytes). const data = "4dffb503010102303001ff30000109010130010800010130010800010130" + "01ffb80001014a01ffb60001014b01ff860001013001ff860001013001ff" + "860001013001ff860001013001ffb80000001eff850401010e30303030" + "30303030303030303030303001ff3000010c0104000016ffb70201010830" + "303030303030303001ff3000010c000030ffb6040405fcff0030303030" + "303030303030303030303030303030303030303030303030303030303030" + "30" type X struct { J *X K map[string]int } func main() { raw, _ := hex.DecodeString(data) decoder := gob.NewDecoder(bytes.NewReader(raw)) var x X decoder.Decode(&x) // fatal error: runtime: out of memory fmt.Println("Decoding finished.") } ``` -------------------------------- ### Build mkall.sh Script - Old System Source: https://github.com/k8snetworkplumbingwg/kubemacpool/blob/main/vendor/golang.org/x/sys/unix/README.md The `mkall.sh` script is used in the old build system to generate Go files for the sys/unix package from C header files. This script is intended for use when GOOS is not 'linux'. It requires bash and Go. Running `mkall.sh -n` will show the commands that will be executed without actually running them. ```bash #!/bin/bash # Default GOOS and GOARCH if not set GOOS=${GOOS:-$(go env GOOS)} GOARCH=${GOARCH:-$(go env GOARCH)} # ... (rest of the script) if [[ "$1" == "-n" ]]; then echo "Running mkall.sh with GOOS=$GOOS GOARCH=$GOARCH" else echo "Generating Go files for GOOS=$GOOS GOARCH=$GOARCH" fi # Example of a command that might be run # go run mksysnum_$GOOS.go ../../../sys/unix/zentrap.h > zsysnum_$GOOS_$GOARCH.go # ... (more generation commands) ```