### Install Ginkgo and Gomega CLI Tools Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/onsi/ginkgo/README.md This snippet shows how to install the Ginkgo command-line interface and the Gomega matcher library using the Go command. These tools are essential for setting up and running tests. ```bash go get -u github.com/onsi/ginkgo/ginkgo # installs the ginkgo CLI go get -u github.com/onsi/gomega/... ``` -------------------------------- ### Go: Application Setup with logr Logger Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/go-logr/logr/README.md Demonstrates how an application initializes a root logger using a specific implementation (e.g., `logimpl`) and then passes this logger to other parts of the application. ```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 ... } ``` -------------------------------- ### Enable and Start Podman Socket (Bash) Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/README.md Commands to enable and start the podman socket service. This is a prerequisite for using podman with cluster-up. It ensures the podman service is ready to accept connections. ```bash sudo systemctl enable podman.socket sudo systemctl start podman.socket ``` -------------------------------- ### Install Development Tools for Hostpath Provisioner Builds Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/README.md These commands install necessary packages for building the hostpath provisioner. 'gcc' is required for dynamically linked builds, and 'buildah' is needed for OCI builds. These tools ensure that the build environment is correctly configured. ```bash #Enable dynamically linked builds: $ sudo dnf -y install gcc #Enable OCI builds: $ sudo dnf -y install buildah ``` -------------------------------- ### Setup Ginkgo Development Environment Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md These commands set up the Ginkgo development environment by fetching the Ginkgo library and its dependencies, configuring a remote for your fork, and running initial tests and linting checks. ```shell go get github.com/onsi/ginkgo go get github.com/onsi/gomega/... cd $GOPATH/src/github.com/onsi/ginkgo git remote add fork git@github.com:/ginkgo.git ginkgo -r -p # ensure tests are green go vet ./... # ensure linter is happy ``` -------------------------------- ### Install Mergo Go Package Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/imdario/mergo/README.md Installs the Mergo library using the Go build tool. This command fetches the specified version of the Mergo package and its dependencies, making it available for use in your Go projects. ```go go get github.com/imdario/mergo ``` -------------------------------- ### Installing go-colorable Package Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/README.md This command installs the go-colorable package, which is a dependency for enabling colorized output on Windows in Go applications. Ensure you have a working Go environment set up. ```bash $ go get github.com/mattn/go-colorable ``` -------------------------------- ### Install json-iterator/go using go get Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/json-iterator/go/README.md Provides the command to install the json-iterator/go library using Go modules. This is the standard way to fetch dependencies for Go projects. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Execute Kubernetes Cluster Provisioning Script Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/K8S_DEV_GUIDE.md Initiates the Kubernetes cluster provisioning process using a specific provider version. This script orchestrates the setup of core Kubernetes components, including DNS, networking, and Kubelet. ```bash export KUBEVIRT_PROVIDER=k8s-${KUBEVIRT_PROVIDER_VERSION} make cluster-up ``` -------------------------------- ### Install mkpj Tool Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/kind-sriov/TROUBLESHOOTING.md Installs the mkpj tool, a utility for crafting custom Prow Jobs, using go get. This tool is a prerequisite for launching custom jobs on the CI cluster. ```bash go get k8s.io/test-infra/prow/cmd/mkpj ``` -------------------------------- ### Initialize Procfs Filesystem and Get Stats (Go) Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/prometheus/procfs/README.md This snippet demonstrates how to initialize a procfs filesystem object for the /proc directory and then retrieve general statistics. It requires the procfs library. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Complete Struct Merge Example in Go Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/imdario/mergo/README.md Provides a complete, runnable example demonstrating Mergo's struct merging capabilities. It defines two `Foo` structs, merges `src` into `dest` using `mergo.Merge`, and prints the resulting `dest` struct. This example highlights how Mergo populates uninitialized fields. ```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} } ``` -------------------------------- ### Define a RESTful Web Service with go-restful Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/emicklei/go-restful/v3/README.md This Go example illustrates how to define a RESTful web service using the go-restful package. It sets up a WebService with a path, specifies supported MIME types for consumption and production, and defines a route for handling GET requests to retrieve a user by ID. It also shows how to access path parameters within a route handler. ```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") ... } ``` -------------------------------- ### Basic glog Logging Examples in Go Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/k8s.io/klog/v2/README.md Demonstrates basic usage of the glog package for logging informational and fatal messages. It utilizes functions like Info and Fatalf for outputting log entries. ```go glog.Info("Prepare to repel boarders") glog.Fatalf("Initialization failed: %s", err) ``` -------------------------------- ### CSI StorageClass Example for Kubevirt Hostpath Provisioner Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/README.md This example shows how to define a StorageClass for the Kubevirt Hostpath CSI provisioner. It utilizes WaitForFirstConsumer binding mode and specifies the correct provisioner name. Ensure your Kubernetes version is v1.19 or newer for Storage Capacity reporting. ```yaml apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: "hostpath-csi" provisioner: "kubevirt.io.hostpath-provisioner" parameters: # (optional) if you want to use a specific directory for volumes # basedir: "/var/lib/kubelet/pods" # (optional) specify if you want to use a subdirectory for each volume # volumedir: "volumes" # (optional) for CSI topology # nodeTopology: "topology.kubernetes.io/region=us-east-1" reclaimPolicy: Delete volumeBindingMode: WaitForFirstConsumer allowVolumeExpansion: true ``` -------------------------------- ### Install YAML Package for Go Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/imdario/mergo/README.md Installs the `yaml.v2` package, which may be a dependency for certain Go projects, particularly those dealing with YAML configuration or data serialization. This command ensures the package is available in your Go environment. ```go go get gopkg.in/yaml.v2 ``` -------------------------------- ### Install gRPC-Go Dependency Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/google.golang.org/grpc/README.md This snippet shows the basic import statement required to include the gRPC-Go library in your Go project. When you build, run, or test your code, the Go toolchain will automatically fetch this dependency. ```go import "google.golang.org/grpc" ``` -------------------------------- ### Initialize Block Device Filesystem and Get Disk Stats (Go) Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/prometheus/procfs/README.md This code shows how to initialize a procfs filesystem object that accesses both /proc and /sys, specifically for retrieving block device statistics. It requires the blockdevice sub-package of procfs. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Interact with Kubernetes Cluster via kubectl Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/README.md This example demonstrates how to use the provided `kubectl.sh` script to interact with the Kubernetes cluster. The script acts as a wrapper for kubectl, simplifying access to cluster resources. This command retrieves a list of all pods across all namespaces. ```bash $ ./cluster-up/kubectl.sh get pods --all-namespaces ``` -------------------------------- ### Inspect QEMU Process within VM Container Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/K8S_DEV_GUIDE.md Lists running processes within the VM container, specifically filtering for the QEMU process which manages the virtual machine. This helps in understanding the VM's resource utilization and configuration. ```bash [root@855de8c8310f /]# ps -ef | grep qemu root 1 0 36 13:39 ? 00:05:22 qemu-system-x86_64 -enable-kvm -drive format=qcow2,file=/var/run/disk/disk.qcow2,if=virtio,cache=unsafe -device virtio-net-pci,netdev=network0,mac=52:55:00:d1:55:01 -netdev tap,id=network0,ifname=tap01,script=no,downscript=no -device virtio-rng-pci -vnc :01 -cpu host -m 5120M -smp 5 -serial pty ``` -------------------------------- ### Bootstrap and Generate Ginkgo Test Suite Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/onsi/ginkgo/README.md These commands are used to initialize a new Ginkgo testing suite within a Go project. 'ginkgo bootstrap' sets up the necessary directories and files, and 'ginkgo generate' creates a sample test file to begin with. ```bash cd path/to/package/you/want/to/test ginkgo bootstrap ginkgo generate ``` -------------------------------- ### Run Tests with Go Test and Ginkgo CLI Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/onsi/ginkgo/README.md This section demonstrates two ways to execute your tests. 'go test' is the standard Go command for running tests, while 'ginkgo' is a command provided by the Ginkgo CLI that can also run your tests and offers additional features. ```bash go test ginkgo ``` -------------------------------- ### Split Trace into Multiple Steps in Go Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/k8s.io/utils/trace/README.md Shows how to create a trace and then split its execution into distinct steps, logging each step with optional fields. This helps in analyzing the timing of different stages within an operation. ```go func doSomething() { opTrace := trace.New("operation") defer opTrace.LogIfLong(100 * time.Millisecond) // do step 1 opTrace.Step("step1", Field{Key: "stepFieldKey1", Value: "stepFieldValue1"}) // do step 2 opTrace.Step("step2") } ``` -------------------------------- ### Bring Up Kubernetes Cluster with Nested Virtualization Required Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/K8S.md This command ensures that the cluster will only start if nested virtualization is enabled on the host, by setting the KUBEVIRT_NESTED_VIRTUALIZATION_REQUIRED environment variable to true before running 'make cluster-up'. ```bash export KUBEVIRT_NESTED_VIRTUALIZATION_REQUIRED=true make cluster-up ``` -------------------------------- ### Get integer flag value from FlagSet in Go Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/spf13/pflag/README.md This Go example shows how to retrieve the integer value of a flag named 'flagname' from a pflag.FlagSet object. It includes error handling for cases where the flag might not exist or is not of the expected type. ```go i, err := flagset.GetInt("flagname") ``` -------------------------------- ### Structured Logging: Standard Log vs. Controller-runtime (Go) Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/sigs.k8s.io/controller-runtime/TMP-LOGGING.md Compares traditional formatted string logging in Go's standard library with structured logging in controller-runtime. The example shows how a single log statement with variables is transformed into a constant message with key-value pairs, improving log structure and searchability. ```go log.Printf("starting reconciliation for pod %s/%s", podNamespace, podName) ``` ```go logger.Info("starting reconciliation", "pod", req.NamespacedName) ``` -------------------------------- ### Structured Logging: Basic Info Message (Go) Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/sigs.k8s.io/controller-runtime/TMP-LOGGING.md Demonstrates the basic usage of structured logging in Go using controller-runtime. It replaces traditional formatted string logging with key-value pairs for better log analysis. This approach uses the 'logger.Info' function to log a message with associated context. ```go logger.Info("starting reconciliation", "pod", req.NamespacedName) ``` -------------------------------- ### Legacy Provisioner - Create PersistentVolume (Go) Source: https://context7.com/kubevirt/hostpath-provisioner/llms.txt This Go code snippet demonstrates how to initialize and run the legacy KubeVirt Hostpath Provisioner. It requires in-cluster Kubernetes configuration and sets up a provision controller to manage PersistentVolume creation using local hostpath directories. Key environment variables include NODE_NAME, PV_DIR, and USE_NAMING_PREFIX. ```go package main import ( "kubevirt.io/hostpath-provisioner/controller" "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/apimachinery/pkg/util/wait" ) func main() { // Initialize in-cluster Kubernetes client config, err := rest.InClusterConfig() if err != nil { panic(err) } clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err) } // Create hostpath provisioner instance provisioner := NewHostPathProvisioner() // Start the provision controller serverVersion, _ := clientset.Discovery().ServerVersion() pc := controller.NewProvisionController( clientset, "kubevirt.io/hostpath-provisioner", provisioner, serverVersion.GitVersion, ) // Run the controller (blocks) pc.Run(wait.NeverStop) } // Required environment variables: // NODE_NAME=worker-node-01 // PV_DIR=/var/hpvolumes // USE_NAMING_PREFIX=false ``` -------------------------------- ### Build and Deploy Commands (Bash) Source: https://context7.com/kubevirt/hostpath-provisioner/llms.txt Provides bash commands for building the provisioner and CSI driver binaries and container images. It includes commands for building specific components, creating multi-arch manifests, pushing images, deploying to a local cluster, and running various tests. ```bash # Build both provisioner and CSI driver make build # Build only the legacy provisioner make hostpath-provisioner # Build only the CSI driver make hostpath-csi-driver # Build container images for both make image # Build and push multi-arch manifests export DOCKER_REPO=quay.io/myorg export TAG=v1.0.0 export GOARCH=amd64 make push # Deploy to local development cluster export KUBEVIRT_PROVIDER=kind-1.32 make cluster-up make cluster-sync # Run tests make test make test-functional make test-sanity ``` -------------------------------- ### Run Go Tests Locally for Kubevirt Hostpath Provisioner Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/google.golang.org/grpc/CONTRIBUTING.md These commands are used to run Go tests locally for the Kubevirt hostpath-provisioner project. They include commands for running standard tests, tests with race detection, and vet checks. Ensure you have Go installed and are in the project's root directory. ```shell # Run standard tests go test -cpu 1,4 -timeout 7m ./... # Run tests in race mode go test -race -cpu 1,4 -timeout 7m ./... # Run vet checks ./scripts/vet.sh ``` -------------------------------- ### Go: Create and Use Filesystem Watcher Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/fsnotify/fsnotify/README.md This Go code snippet demonstrates how to create a new fsnotify watcher, set up goroutines to listen for filesystem events and errors, and add a directory to be watched. It includes basic error handling and logging for events and errors. Requires Go 1.16 or newer. ```go package main import ( "log" "github.com/fsnotify/fsnotify" ) func main() { // Create new watcher. watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() // Start listening for events. go func() { for { select { case event, ok := <-watcher.Events: if !ok { return } log.Println("event:", event) if event.Has(fsnotify.Write) { log.Println("modified file:", event.Name) } case err, ok := <-watcher.Errors: if !ok { return } log.Println("error:", err) } } }() // Add a path. err = watcher.Add("/tmp") if err != nil { log.Fatal(err) } // Block main goroutine forever. <-make(chan struct{})) } ``` -------------------------------- ### Define Custom Flag Normalization Function in Go Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/spf13/pflag/README.md Allows mutation of flag names for consistent comparison. Example 1 normalizes separators like '-', '_', and '.' to '.'. Example 2 aliases flag names. This functionality is useful for making flag parsing more flexible. ```go func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { from := []string{"-", "_"} to := "." for _, sep := range from { name = strings.Replace(name, sep, to, -1) } return pflag.NormalizedName(name) } myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc) ``` ```go func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { switch name { case "old-flag-name": name = "new-flag-name" break } return pflag.NormalizedName(name) } myFlagSet.SetNormalizeFunc(aliasNormalizeFunc) ``` -------------------------------- ### Set Interface{} Value using reflect2 Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/modern-go/reflect2/README.md Allows getting and setting the value of an interface{}. To correctly set a type, its pointer (*type) should always be used. This operation is type-checked. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.Set(&i, &j) // i will be 10 ``` -------------------------------- ### CSI Driver - Initialize Hostpath Driver (Go) Source: https://context7.com/kubevirt/hostpath-provisioner/llms.txt This Go code initializes the KubeVirt Hostpath CSI driver. It parses command-line flags for configuration such as the CSI endpoint, driver name, storage pool data directory, node ID, and version. It also starts a Prometheus metrics server and runs the CSI driver until a shutdown signal is received. ```go package main import ( "context" "flag" "os" "kubevirt.io/hostpath-provisioner/pkg/hostpath" "k8s.io/klog/v2" "sigs.k8s.io/controller-runtime/pkg/manager/signals" ) func main() { cfg := &hostpath.Config{} var dataDir string // Parse command-line flags flag.StringVar(&cfg.Endpoint, "endpoint", "unix://tmp/csi.sock", "CSI endpoint") flag.StringVar(&cfg.DriverName, "drivername", "hostpath.csi.kubevirt.io", "name of the driver") flag.StringVar(&dataDir, "datadir", `[{"name":"legacy","path":"/csi-data-dir"}]`, "storage pool configuration JSON") flag.StringVar(&cfg.NodeID, "nodeid", "", "node id") flag.StringVar(&cfg.Version, "version", "v1.0.0", "version of the plugin") flag.Parse() // Start Prometheus metrics server klog.V(1).Info("Starting Prometheus metrics endpoint server") hostpath.RunPrometheusServer(":8080") // Create driver with context for graceful shutdown ctx := signals.SetupSignalHandler() driver, err := hostpath.NewHostPathDriver(ctx, cfg, dataDir) if err != nil { klog.Errorf("Failed to initialize driver: %s", err.Error()) os.Exit(1) } // Run the CSI driver (blocks until shutdown) if err := driver.Run(); err != nil { klog.Errorf("Failed to run driver: %s", err.Error()) os.Exit(1) } } // Storage pool JSON format: [{"name":"pool1","path":"/data/pool1"},{"name":"pool2","path":"/data/pool2"}] ``` -------------------------------- ### Benchmark Sum64 with Pure Go and Assembly (Shell) Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/cespare/xxhash/v2/README.md These commands demonstrate how to benchmark the `Sum64` function using `benchstat`. The first command benchmarks the pure Go implementation by specifying the `purego` build tag, while the second command benchmarks the optimized assembly implementation. This allows for performance comparisons between the two versions. ```shell benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### Access VM Container via Docker Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/K8S_DEV_GUIDE.md Connects to the Docker container that hosts the virtual machine. This allows direct access to the VM's environment for debugging or advanced operations. ```bash CONTAINER=$(docker ps | grep vm | awk '{print $1}') docker exec -it $CONTAINER bash ``` -------------------------------- ### Create and Log Latency Trace in Go Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/k8s.io/utils/trace/README.md Demonstrates how to create a new trace for an operation with initial fields and log it if its duration exceeds a specified limit. This is useful for performance monitoring. ```go func doSomething() { opTrace := trace.New("operation", Field{Key: "fieldKey1", Value: "fieldValue1"}) defer opTrace.LogIfLong(100 * time.Millisecond) // do something } ``` -------------------------------- ### Connect to Cluster Node via SSH Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/K8S_DEV_GUIDE.md Establishes an SSH connection to a specified node within the cluster. This is the primary method for interactive access to cluster nodes for management and debugging. ```bash ./cluster-up/ssh.sh node01 ``` -------------------------------- ### Create and Push Git Tag for Release Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/k8s.io/klog/v2/RELEASE.md This snippet demonstrates the Git commands used to create a signed tag for a new release and push it to the repository. It requires specifying the desired version number. ```bash git tag -s $VERSION git push $VERSION ``` -------------------------------- ### concurrent.Executor: Manage Goroutines (Go) Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/modern-go/concurrent/README.md Provides an Executor for managing goroutines, enabling cancellation via Stop/StopAndWait/StopAndWaitForever and handling panics gracefully. This example shows an unbounded executor with a ticking goroutine. ```Go executor := concurrent.NewUnboundedExecutor()executor.Go(func(ctx context.Context) { everyMillisecond := time.NewTicker(time.Millisecond) for { select { case <-ctx.Done(): fmt.Println("goroutine exited") return case <-everyMillisecond.C: // do something } } }) time.Sleep(time.Second)executor.StopAndWaitForever() fmt.Println("executor stopped") ``` -------------------------------- ### Configure Provision Controller (Go) Source: https://context7.com/kubevirt/hostpath-provisioner/llms.txt Configures the hostpath provision controller with custom options, including retry behavior and leader election settings. This Go code snippet demonstrates how to instantiate the controller using the Kubernetes client-go library and apply specific configurations for resync period, threadiness, and failure thresholds. ```go package main import ( "time" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/apimachinery/pkg/util/wait" "kubevirt.io/hostpath-provisioner/controller" "k8s.io/client-go/util/workqueue" ) func main() { config, _ := rest.InClusterConfig() clientset, _ := kubernetes.NewForConfig(config) provisioner := NewHostPathProvisioner() serverVersion, _ := clientset.Discovery().ServerVersion() // Create controller with custom configuration pc := controller.NewProvisionController( clientset, "kubevirt.io/hostpath-provisioner", provisioner, serverVersion.GitVersion, // Custom options controller.ResyncPeriod(5*time.Minute), controller.Threadiness(8), controller.FailedProvisionThreshold(20), controller.FailedDeleteThreshold(20), controller.LeaderElection(false), // Disabled for multi-node provisioning controller.CreateProvisionedPVLimiter( workqueue.NewItemExponentialFailureRateLimiter(5*time.Second, 300*time.Second), ), ) pc.Run(wait.NeverStop) } ``` -------------------------------- ### Publish New Provider Image to Quay.io Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/K8S_DEV_GUIDE.md This script is used to publish a newly created KubeVirtCI provider image to quay.io. It's part of the manual process for integrating new providers. ```shell ./cluster-provision/k8s/${KUBEVIRT_PROVIDER_DIR}/publish.sh ``` -------------------------------- ### Check Kubelet Service Status Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/K8S_DEV_GUIDE.md Verifies the operational status of the kubelet service on a Kubernetes node. This command is essential for diagnosing node-level issues and ensuring the Kubernetes agent is running correctly. ```bash [vagrant@node01 ~]$ systemctl status kubelet ● kubelet.service - kubelet: The Kubernetes Node Agent Loaded: loaded (/usr/lib/systemd/system/kubelet.service; enabled; vendor preset: disabled) Drop-In: /usr/lib/systemd/system/kubelet.service.d └─10-kubeadm.conf Active: active (running) since Wed 2020-01-15 13:39:54 UTC; 11min ago Docs: https://kubernetes.io/docs/ Main PID: 4294 (kubelet) CGroup: /system.slice/kubelet.service ‣ 4294 /usr/bin/kubelet --bootstrap-kubeconfig=/etc/kubernetes/boo... ``` -------------------------------- ### List Pods using Crictl Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/K8S_DEV_GUIDE.md Retrieves a list of all running pods on a Kubernetes node using the `crictl` command. This is useful for monitoring pod status, identifying running containers, and debugging. ```bash [vagrant@node01 ~]$ sudo crictl pods POD ID CREATED STATE NAME NAMESPACE ATTEMPT 403513878c8b7 10 minutes ago Ready coredns-6955765f44-m6ckl kube-system 4 0c3e25e58b9d0 10 minutes ago Ready local-volume-provisioner-fkzgk default 4 e6d96770770f4 10 minutes ago Ready coredns-6955765f44-mhfgg kube-system 4 19ad529c78acc 10 minutes ago Ready kube-flannel-ds-amd64-mq5cx kube-system 0 47acef4276900 10 minutes ago Ready kube-proxy-vtj59 kube-system 0 df5863c55a52f 11 minutes ago Ready kube-scheduler-node01 kube-system 0 ca0637d5ac82f 11 minutes ago Ready kube-apiserver-node01 kube-system 0 f0d90506ce3b8 11 minutes ago Ready kube-controller-manager-node01 kube-system 0 f873785341215 11 minutes ago Ready etcd-node01 kube-system 0 ``` -------------------------------- ### Get Type by Name using reflect2.TypeByName Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/modern-go/reflect2/README.md Retrieves a type by its fully qualified name, similar to Java's Class.forName. Note that if a type is not used, the compiler may eliminate it, making it unavailable at runtime. ```go // given package is github.com/your/awesome-package type MyStruct struct { // ... } // will return the type reflect2.TypeByName("awesome-package.MyStruct") // however, if the type has not been used // it will be eliminated by compiler, so we can not get it in runtime ``` -------------------------------- ### Bring Up Kubernetes Cluster with Cluster Network Addons Operator Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/K8S.md This command enables the provisioning of the cluster-network-addons-operator by setting the KUBEVIRT_WITH_CNAO environment variable to true before executing 'make cluster-up'. ```bash export KUBEVIRT_WITH_CNAO=true make cluster-up ``` -------------------------------- ### Export KUBEVIRTCI_TAG Environment Variable (Bash) Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/README.md Exports the KUBEVIRTCI_TAG environment variable by fetching the latest tag from a GCS bucket. This is crucial for ensuring the correct version of gocli is used when integrating with kubevirtci. ```bash export KUBEVIRTCI_TAG=`curl -L -Ss https://storage.googleapis.com/kubevirt-prow/release/kubevirt/kubevirtci/latest` ``` -------------------------------- ### Log to a Single File with klog in Go Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/k8s.io/klog/v2/README.md Example of how to configure klog to log messages to a single file instead of a directory. This is achieved by using the 'log_file' flag, replacing the older 'log_dir' flag. ```go import ( "flag" "k8s.io/klog/v2" ) func main() { // Define and parse flags, including 'log_file' klog.InitFlags(nil) flag.Parse() // klog will now log to the file specified by the 'log_file' flag klog.Info("This message will be logged to the specified file.") } ``` -------------------------------- ### Run Tests with Make Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/vendor/github.com/prometheus/procfs/CONTRIBUTING.md This command is used to ensure all tests pass before committing and pushing changes. It's a crucial step in the contribution workflow for Go projects managed with Make. ```bash make test ``` -------------------------------- ### Bring Up Kind Kubernetes Cluster with KubeVirt Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/README_VGPU.md This snippet demonstrates the commands to initiate a Kind Kubernetes cluster with KubeVirt pre-installed. It requires root privileges and sets the KUBEVIRT_PROVIDER environment variable. The output shows how to verify the cluster status using kubectl. ```bash export KUBEVIRT_PROVIDER=kind-1.x-vgpu make cluster-up $ cluster-up/kubectl.sh get nodes NAME STATUS ROLES AGE VERSION vgpu-control-plane Ready master 6m14s v1.x.y ``` -------------------------------- ### Set Kubernetes Cluster Version with KUBEVIRT_PROVIDER Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/K8S.md This command sets the environment variable KUBEVIRT_PROVIDER to specify the desired Kubernetes version for the kubevirtci provider. This determines which Kubernetes version will be provisioned. ```bash export KUBEVIRT_PROVIDER=k8s-1.22 ``` -------------------------------- ### Add Custom Manifest to Kubernetes Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/K8S_DEV_GUIDE.md This snippet demonstrates how to add a custom YAML manifest to a Kubernetes cluster using kubectl. It assumes the manifest file is located at /tmp/custom_manifest.yaml and uses the admin configuration for kubectl. ```shell custom_manifest="/tmp/custom_manifest.yaml"kubectl --kubeconfig=/etc/kubernetes/admin.conf create -f "$custom_manifest" ``` -------------------------------- ### Start OVN K8S Cluster with Kind Source: https://github.com/kubevirt/hostpath-provisioner/blob/main/cluster-up/cluster/kind-ovn/README.md Sets the KUBEVIRT_PROVIDER environment variable and executes the 'make cluster-up' command to provision a Kubernetes cluster with OVN. This is typically used for local development and testing environments. ```bash export KUBEVIRT_PROVIDER=kind-ovn make cluster-up ```