### Install xstrings Go Package Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/huandu/xstrings/README.md This snippet demonstrates how to install the xstrings Go package using the `go get` command. This is the standard method for acquiring external Go libraries. ```Go go get github.com/huandu/xstrings ``` -------------------------------- ### Install Blackfriday v2 Package (Go) Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/russross/blackfriday/v2/README.md Installs the Blackfriday v2 package for Go in module mode. This command fetches the package, adds it to your project's dependencies, and builds it. Alternatively, importing the package and running 'go get' will achieve the same result. ```go go get github.com/russross/blackfriday/v2 ``` -------------------------------- ### Install Blackfriday Tool (Go) Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/russross/blackfriday/v2/README.md Installs the `blackfriday-tool`, a command-line utility for processing Markdown files. This command also downloads and installs the Blackfriday package as a dependency. The binary will be placed in your `$GOPATH/bin` directory. ```go go get github.com/russross/blackfriday-tool ``` -------------------------------- ### Functional CLI App Example (Go) Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Shows how to create a functional CLI application with a name, usage, and an action. This example defines a 'greet' command that prints 'Greetings' when executed. ```Go package cli // import "github.com/urfave/cli/v2" import ( "fmt" "os" ) func main() { app := &cli.App{ Name: "greet", Usage: "say a greeting", Action: func(c *cli.Context) error { fmt.Println("Greetings") return nil }, } app.Run(os.Args) } ``` -------------------------------- ### Install copystructure Go Library Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/mitchellh/copystructure/README.md This snippet shows the standard Go command for installing the copystructure library using 'go get'. This is a prerequisite for using the library in your Go projects. ```bash go get github.com/mitchellh/copystructure ``` -------------------------------- ### Install nvkind using Go Source: https://github.com/nvidia/nvkind/blob/main/README.md Installs the nvkind command-line tool using the Go build tool. Ensure Go is installed and the project path is in your GOPATH. ```bash go install github.com/NVIDIA/nvkind/cmd/nvkind@latest ``` -------------------------------- ### Minimal CLI App Example (Go) Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Demonstrates the simplest possible command-line application using the 'cli' package. It initializes an empty application and runs it with provided arguments. ```Go package cli // import "github.com/urfave/cli/v2" import "os" func main() { (&cli.App{}).Run(os.Args) } ``` -------------------------------- ### Install json-iterator/go using go get Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/json-iterator/go/README.md This command provides instructions on how to install the json-iterator/go library into your Go project using the `go get` command. This is the standard method for managing Go dependencies. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Go App Setup Method Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Performs initialization tasks to prepare the application's data structures for execution or inspection. It's called internally by `Run` and will return early if already set up. ```go func (a *App) Setup() Setup runs initialization code to ensure all data structures are ready for `Run` or inspection prior to `Run`. It is internally called by `Run`, but will return early if setup has already happened. ``` -------------------------------- ### Defining a User Resource with go-restful Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/emicklei/go-restful/v3/README.md This Go code example illustrates how to define a RESTful WebService for managing users using the go-restful package. It sets the path, consumes and produces media types, and defines a GET route for retrieving a user by ID. ```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 Go Package Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/imdario/mergo/README.md Instructions for installing the Mergo Go package using the go get command. This is a prerequisite for using Mergo in your Go projects. ```bash go get github.com/imdario/mergo ``` -------------------------------- ### Install YAML Package for Testing Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/imdario/mergo/README.md A note indicating that if tests are failing due to a missing package, the user should install the `gopkg.in/yaml.v2` package using `go get`. This is typically for test setup or related functionalities. ```bash go get gopkg.in/yaml.v2 ``` -------------------------------- ### Install uuid package using go get Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/google/uuid/README.md This command installs the uuid package using the Go module system. It fetches the latest version of the package from its remote repository. ```sh go get github.com/google/uuid ``` -------------------------------- ### Install k8s-device-plugin using Helm Source: https://github.com/nvidia/nvkind/blob/main/README.md Instructions for installing the NVIDIA k8s-device-plugin on a cluster using Helm. This involves adding the NVIDIA Helm repository, updating it, setting the target cluster name, and then performing a Helm upgrade to install the plugin. It also shows how to verify the plugin pods are running. ```bash helm repo add nvdp https://nvidia.github.io/k8s-device-plugin helm repo update ``` ```bash export KIND_CLUSTER_NAME=evenly-distributed-2-by-4 ``` ```bash helm upgrade -i \ --kube-context=kind-${KIND_CLUSTER_NAME} \ --namespace nvidia \ --create-namespace \ nvidia-device-plugin nvdp/nvidia-device-plugin ``` ```bash $ kubectl --context=kind-${KIND_CLUSTER_NAME} get pod -n nvidia ``` -------------------------------- ### Create a Markdown definition list Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/russross/blackfriday/v2/README.md This example illustrates the Markdown syntax for creating a definition list. A term is followed by a colon and its definition. A blank line is required to separate subsequent terms and their definitions. ```markdown Cat : Fluffy animal everyone likes Internet : Vector of transmission for pictures of cats ``` -------------------------------- ### Args Interface Definition (Go) Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt The Args interface defines methods for accessing command-line arguments, including getting specific arguments by index, retrieving the first argument, the rest of the arguments, their length, checking for presence, and getting a copy of the argument slice. ```Go type Args interface { // Get returns the nth argument, or else a blank string Get(n int) string // First returns the first argument, or else a blank string First() string // Tail returns the rest of the arguments (not the first one) // or else an empty string slice Tail() []string // Len returns the length of the wrapped slice Len() int // Present checks if there are any arguments present Present() bool // Slice returns a copy of the internal slice Slice() []string } ``` -------------------------------- ### Check Go Version Source: https://github.com/nvidia/nvkind/blob/main/vendor/golang.org/x/oauth2/CONTRIBUTING.md Command to check the installed version of Go. This is crucial information when reporting issues or ensuring compatibility. ```bash go version ``` -------------------------------- ### Coexist klog and glog Source: https://github.com/nvidia/nvkind/blob/main/vendor/k8s.io/klog/v2/README.md Example illustrating how to run klog and the original glog side-by-side. It covers initializing and synchronizing flags from the global flag.CommandLine FlagSet and using stderr for combined output. Requires Go 1.11.4 or greater. ```go package main import ( "flag" "github.com/golang/glog" "k8s.io/klog/v2" ) func main() { // Initialize klog flags. The second argument (nil) means it uses the default command-line flags. klog.InitFlags(nil) // Explicitly parse the command line flags. This is crucial for both klog and glog to see the flags. flag.Parse() // Ensure logs are flushed before exiting defer klog.Flush() defer glog.Flush() // Set klog to log to stderr as well, making it easier to combine output. klog.SetOutput(os.Stderr) // Assuming os is imported // glog defaults to stderr, so no explicit setting is usually needed if alsologtostderr is true. // If you need to control glog's output explicitly, you might use: // flag.Set("logtostderr", "true") // Or similar flag manipulation klog.Info("This is a message from klog/v2.") glog.Info("This is a message from glog.") // Note: Synchronization of flags between klog and glog is handled by parsing // the global flag.CommandLine FlagSet. Ensure that flags like --logtostderr // are set appropriately for both libraries if needed. } ``` -------------------------------- ### Swagger 1.2 and OpenAPI Example Update (Go) Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/emicklei/go-restful/v3/CHANGES.md This update involves revising examples for Swagger 1.2 and OpenAPI specifications. It aims to ensure that the examples accurately reflect the current state of the library's support for these API documentation standards. The code is written in Go. ```go package main import ( "github.com/emicklei/go-restful/v3" go_restful_swagger "github.com/emicklei/go-restful-swagger12" "log" "net/http" ) func main() { wbs := go_restful.NewWebService() // Example of documenting a route for Swagger/OpenAPI wbs.Route(wbs.GET("/users/{id}"). To(getUser). // Handler function Doc("get a user by id"). // Documentation description Param(wbs.PathParameter("id", "identifier of the user").DataType("string")). // Path parameter Writes(User{})) // Response model go_restful.DefaultContainer.Add(wbs) // Configure Swagger/OpenAPI documentation service config := go_restful_swagger.Config{ WebServices: go_restful.DefaultContainer.RegisteredWebServices(), // APIInfo: api.ApiInfo{ // Define API information here if needed // Title: "Swagger First", // Description: "This is the first version of sample server Petstore server.", // TermsOfService: "http://swagger.io/terms/", // Contact: &api.ContactInfo{Name: "Swagger", Email: "apiteam@swagger.io"}, // License: &api.LicenseInfo{Name: "Apache 2.0", URL: "http://www.apache.org/licenses/LICENSE-2.0.html"}, // }, // Use the correct Swagger version (e.g., "2.0" or "3.0") SwaggerVersion: "2.0", ApiPath: "/apidocs.json", // Path for the Swagger JSON endpoint } go_restful.DefaultContainer.Add(go_restful_swagger.NewSwaggerService(config)) log.Printf("Start server listening on port 8080...") http.ListenAndServe(":8080", nil) } // Dummy User struct for example type User struct { ID string `json:"id"` Name string `json:"name"` } // Dummy handler function func getUser(request *go_restful.Request, response *go_restful.Response) { userID := request.PathParameter("id") user := User{ID: userID, Name: "Example User " + userID} response.WriteEntity(user) } ``` -------------------------------- ### Coexist klog v1 and v2 Source: https://github.com/nvidia/nvkind/blob/main/vendor/k8s.io/klog/v2/README.md Example showing how to use both klog/v1 and klog/v2 within the same application. This is useful during migration phases or when integrating with older codebases. Requires Go 1.11.4 or greater. ```go package main import ( "flag" _ "k8s.io/klog" older "k8s.io/klog/v1" "k8s.io/klog/v2" ) func main() { // Initialize flags for both klog versions if necessary. Usually, you only need to init once. klog.InitFlags(nil) flag.Parse() defer klog.Flush() // Use klog/v2 klog.Info("Message from klog/v2") // Use klog/v1 (note the explicit import alias) older.Info("Message from klog/v1") // You might need to synchronize flags if they are managed separately, // but typically InitFlags(nil) handles the global flag set. } ``` -------------------------------- ### Complete Struct Merging Example Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/imdario/mergo/README.md A comprehensive Go example demonstrating the `mergo.Merge` function. It defines two `Foo` structs, initializes them, merges the source into the destination, and prints the result, showing how exported fields are updated. ```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} } ``` -------------------------------- ### Create a Markdown table Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/russross/blackfriday/v2/README.md This example demonstrates the Markdown syntax for creating a table. It uses pipes (|) to separate columns and hyphens (-) to create the header separator row. This allows for structured data presentation within Markdown documents. ```markdown Name | Age --------|------ Bob | 27 Alice | 23 ``` -------------------------------- ### Create fenced code block with language hint Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/russross/blackfriday/v2/README.md This example shows the Markdown syntax for creating a fenced code block. By preceding the code content with ```go, you indicate that the code is written in Go, which can be used by syntax highlighters. The block is terminated by three or more backticks. ```markdown ```go func getTrue() bool { return true } ``` ``` -------------------------------- ### IntFlag Structure and Methods in Go Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Defines the IntFlag structure and its associated methods for managing integer flags. It includes functions for applying flags, getting values, checking requirements, and executing actions. Dependencies include the 'flag' package and a 'Context' type. ```go type IntFlag struct { Name string Category string DefaultText string FilePath string Usage string Required bool Hidden bool HasBeenSet bool Value int Destination *int Aliases []string EnvVars []string Base int Action func(*Context, int) error // Has unexported fields. } func (f *IntFlag) Apply(set *flag.FlagSet) error func (f *IntFlag) Get(ctx *Context) int func (f *IntFlag) GetCategory() string func (f *IntFlag) GetDefaultText() string func (f *IntFlag) GetEnvVars() []string func (f *IntFlag) GetUsage() string func (f *IntFlag) GetValue() string func (f *IntFlag) IsRequired() bool func (f *IntFlag) IsSet() bool func (f *IntFlag) IsVisible() bool func (f *IntFlag) Names() []string func (f *IntFlag) RunAction(c *Context) error func (f *IntFlag) String() string func (f *IntFlag) TakesValue() bool ``` -------------------------------- ### Float64Slice Methods Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Defines methods for Float64Slice, a wrapper for []float64, enabling it to satisfy flag.Value. Includes functions for getting the slice, serializing it, setting values from strings, and providing a readable string representation. ```go func NewFloat64Slice(defaults ...float64) *Float64Slice NewFloat64Slice makes a *Float64Slice with default values func (f *Float64Slice) Get() interface{} Get returns the slice of float64s set by this flag func (f *Float64Slice) Serialize() string Serialize allows Float64Slice to fulfill Serializer func (f *Float64Slice) Set(value string) error Set parses the value into a float64 and appends it to the list of values func (f *Float64Slice) String() string String returns a readable representation of this value (for usage defaults) func (f *Float64Slice) Value() []float64 Value returns the slice of float64s set by this flag func (f *Float64Slice) WithSeparatorSpec(spec separatorSpec) ``` -------------------------------- ### Float64Flag Methods Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Provides methods for Float64Flag to check if it's required, set, visible, retrieve its names, run actions, get its string representation, and determine if it takes a value. These are essential for managing command-line arguments effectively. ```go func (f *Float64Flag) IsRequired() bool IsRequired returns whether or not the flag is required func (f *Float64Flag) IsSet() bool IsSet returns whether or not the flag has been set through env or file func (f *Float64Flag) IsVisible() bool IsVisible returns true if the flag is not hidden, otherwise false func (f *Float64Flag) Names() []string Names returns the names of the flag func (f *Float64Flag) RunAction(c *Context) error RunAction executes flag action if set func (f *Float64Flag) String() string String returns a readable representation of this value (for usage defaults) func (f *Float64Flag) TakesValue() bool TakesValue returns true of the flag takes a value, otherwise false ``` -------------------------------- ### Uint64Flag Methods - Go Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Provides methods for interacting with a Uint64 flag. These include retrieving its value, category, default text, environment variables, usage information, and checking if it's required, set, or visible. It also covers how to get the flag names and run associated actions. ```go func (f *Uint64Flag) Get(ctx *Context) uint64 Get returns the flag’s value in the given Context. func (f *Uint64Flag) GetCategory() string GetCategory returns the category for the flag func (f *Uint64Flag) GetDefaultText() string GetDefaultText returns the default text for this flag func (f *Uint64Flag) GetEnvVars() []string GetEnvVars returns the env vars for this flag func (f *Uint64Flag) GetUsage() string GetUsage returns the usage string for the flag func (f *Uint64Flag) GetValue() string GetValue returns the flags value as string representation and an empty string if the flag takes no value at all. func (f *Uint64Flag) IsRequired() bool IsRequired returns whether or not the flag is required func (f *Uint64Flag) IsSet() bool IsSet returns whether or not the flag has been set through env or file func (f *Uint64Flag) IsVisible() bool IsVisible returns true if the flag is not hidden, otherwise false func (f *Uint64Flag) Names() []string Names returns the names of the flag func (f *Uint64Flag) RunAction(c *Context) error RunAction executes flag action if set func (f *Uint64Flag) String() string String returns a readable representation of this value (for usage defaults) func (f *Uint64Flag) TakesValue() bool TakesValue returns true of the flag takes a value, otherwise false ``` -------------------------------- ### IntSlice Structure and Methods in Go Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Defines the IntSlice structure and its associated methods for managing slices of integers as flags. It provides functions for creating new IntSlices, getting and setting values, and serializing the slice. Dependencies include the 'flag' package. ```go type IntSlice struct { // Has unexported fields. } func NewIntSlice(defaults ...int) *IntSlice func (i *IntSlice) Get() interface{} func (i *IntSlice) Serialize() string func (i *IntSlice) Set(value string) error func (i *IntSlice) SetInt(value int) func (i *IntSlice) String() string func (i *IntSlice) Value() []int func (i *IntSlice) WithSeparatorSpec(spec separatorSpec) ``` -------------------------------- ### Calculate String Distances using smetrics Algorithms (Go) Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/xrash/smetrics/README.md This example demonstrates the usage of various string metric functions from the smetrics package. It includes calculations for Wagner-Fischer, Ukkonen, Jaro, Jaro-Winkler, Soundex, and Hamming distances, showcasing their respective parameters and typical use cases. ```go package main import ( "github.com/xrash/smetrics" ) func main() { smetrics.WagnerFischer("POTATO", "POTATTO", 1, 1, 2) smetrics.WagnerFischer("MOUSE", "HOUSE", 2, 2, 4) smetrics.Ukkonen("POTATO", "POTATTO", 1, 1, 2) smetrics.Ukkonen("MOUSE", "HOUSE", 2, 2, 4) smetrics.Jaro("AL", "AL") smetrics.Jaro("MARTHA", "MARHTA") smetrics.JaroWinkler("AL", "AL", 0.7, 4) smetrics.JaroWinkler("MARTHA", "MARHTA", 0.7, 4) smetrics.Soundex("Euler") smetrics.Soundex("Ellery") smetrics.Hamming("aaa", "aaa") smetrics.Hamming("aaa", "aab") } ``` -------------------------------- ### Timestamp Constructor and Methods - Go Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt This section covers the Timestamp type in Go, including its constructor and methods. The constructor `NewTimestamp` initializes a Timestamp object. Methods allow for getting the flag structure, setting values from strings or directly, defining parsing layouts and timezones, and retrieving the stored timestamp value. ```go func NewTimestamp(timestamp time.Time) *Timestamp func (t *Timestamp) Get() interface{} func (t *Timestamp) Set(value string) error func (t *Timestamp) SetLayout(layout string) func (t *Timestamp) SetLocation(loc *time.Location) func (t *Timestamp) SetTimestamp(value time.Time) func (t *Timestamp) String() string func (t *Timestamp) Value() *time.Time ``` -------------------------------- ### UintSlice Methods - Go Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Defines methods for UintSlice to create new instances, get the current slice of integers, serialize its value, set a new value from a string, directly set an unsigned integer, and return its string representation. This type wraps a slice of integers for flag handling. ```go func NewUintSlice(defaults ...uint) *UintSlice func (i *UintSlice) Get() interface{} func (i *UintSlice) Serialize() string func (i *UintSlice) Set(value string) error func (i *UintSlice) SetUint(value uint) func (i *UintSlice) String() string func (i *UintSlice) Value() []uint func (i *UintSlice) WithSeparatorSpec(spec separatorSpec) ``` -------------------------------- ### Go NewApp Function Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Creates a new `cli.App` instance with default settings for Name, Usage, Version, and Action. This is the recommended way to initialize an application. ```go func NewApp() *App NewApp creates a new cli Application with some reasonable defaults for Name, Usage, Version and Action. ``` -------------------------------- ### Go: Display Command Help Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Prints the help information for a specified command. This allows users to understand how to use individual commands within the application. ```go func ShowCommandHelp(ctx *Context, command string) error ShowCommandHelp prints help for the given command ``` -------------------------------- ### Verify GPU Allocation and Deploy Workload Source: https://github.com/nvidia/nvkind/blob/main/README.md Commands to verify GPU allocation on cluster nodes and deploy a test workload that utilizes GPUs. It shows how to get node information, including allocatable GPUs, and how to apply a Kubernetes Pod manifest that requests a specific number of GPUs. The output of the workload is also displayed. ```bash $ kubectl --context=kind-${KIND_CLUSTER_NAME} get nodes -o json | jq -r '.items[] | select(.metadata.name | test("-worker[0-9]*$")) | {name: .metadata.name, "nvidia.com/gpu": .status.allocatable["nvidia.com/gpu"]}' ``` ```yaml apiVersion: v1 kind: Pod metadata: name: gpu-test spec: restartPolicy: OnFailure containers: - name: ctr image: ubuntu:22.04 command: ["nvidia-smi", "-L"] resources: limits: nvidia.com/gpu: 2 ``` ```bash $ kubectl --context=kind-${KIND_CLUSTER_NAME} logs gpu-test ``` -------------------------------- ### Get/Set unsafe.Pointer Value using reflect2.TypeOf (Go) Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/modern-go/reflect2/README.md This example shows how to get and set values using `unsafe.Pointer` with `reflect2.TypeOf`. Similar to interface{} manipulation, it requires using pointers to the types. The code demonstrates changing the value of `i` from 1 to 10 via unsafe pointers. ```Go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.UnsafeSet(unsafe.Pointer(&i), unsafe.Pointer(&j)) // i will be 10 ``` -------------------------------- ### Build Script (New System) Source: https://github.com/nvidia/nvkind/blob/main/vendor/golang.org/x/sys/unix/README.md The `mkall.sh` script for the new build system, which uses Docker. This script generates Go files for all GOOS/GOARCH pairs supported by the new system. It requires bash, Go, and Docker. Running `mkall.sh -n` displays the commands to be executed without running them. ```bash #!/bin/bash # Example skeleton for mkall.sh (New Build System) GOOS=${GOOS:-linux} GOARCH=${GOARCH:-amd64} if [ "$1" == "-n" ]; then echo "Running commands for GOOS=$GOOS GOARCH=$GOARCH using Docker" echo "docker build -t nvkind/sysunix:${GOOS}-${GOARCH} ${GOOS}/" echo "docker run --rm -v $(pwd):/go/src/nvkind/nvkind nvkind/sysunix:${GOOS}-${GOARCH} /go/src/nvkind/nvkind/${GOOS}/mkall.go" exit 0 fi if [ "$GOOS" != "linux" ] || [ "$GOARCH" != "amd64" ]; then echo "New build system currently requires GOOS=linux and GOARCH=amd64." exit 1 fi echo "Building all files using new build system (Docker)..." # Example Docker build and run commands: # docker build -t nvkind/sysunix:${GOOS}-${GOARCH} ${GOOS}/ # docker run --rm -v $(pwd):/go/src/nvkind/nvkind nvkind/sysunix:${GOOS}-${GOARCH} /go/src/nvkind/nvkind/${GOOS}/mkall.go exit 0 ``` -------------------------------- ### Bind an integer flag to a variable using pflag Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/spf13/pflag/README.md This Go example shows how to bind an integer flag to an existing variable using `flag.IntVar`. The flag is defined within an `init` function, making it available when the program starts. The flag is identified by its name and a help message. ```go var flagvar int func init() { flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") } ``` -------------------------------- ### Int64Flag Methods in Go Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt This Go code defines methods for the Int64Flag type, which extends GenericFlag functionality for int64 values. It includes methods for applying the flag to a flag set, getting its value within a context, and retrieving configuration details like category, default text, environment variables, and usage. It also allows checking if the flag is required, set, or visible, accessing its names, running associated actions, and determining if it accepts a value. ```go func (f *Int64Flag) Apply(set *flag.FlagSet) error Apply populates the flag given the flag set and environment func (f *Int64Flag) Get(ctx *Context) int64 Get returns the flag’s value in the given Context. func (f *Int64Flag) GetCategory() string GetCategory returns the category for the flag func (f *Int64Flag) GetDefaultText() string GetDefaultText returns the default text for this flag func (f *Int64Flag) GetEnvVars() []string GetEnvVars returns the env vars for this flag func (f *Int64Flag) GetUsage() string GetUsage returns the usage string for the flag func (f *Int64Flag) GetValue() string GetValue returns the flags value as string representation and an empty string if the flag takes no value at all. func (f *Int64Flag) IsRequired() bool IsRequired returns whether or not the flag is required func (f *Int64Flag) IsSet() bool IsSet returns whether or not the flag has been set through env or file func (f *Int64Flag) IsVisible() bool IsVisible returns true if the flag is not hidden, otherwise false func (f *Int64Flag) Names() []string Names returns the names of the flag func (f *Int64Flag) RunAction(c *Context) error RunAction executes flag action if set func (f *Int64Flag) String() string String returns a readable representation of this value (for usage defaults) func (f *Int64Flag) TakesValue() bool TakesValue returns true of the flag takes a value, otherwise false ``` -------------------------------- ### Customizable Command Help Template (Go) Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Defines the CommandHelpTemplate variable, a text template for rendering individual command help topics. Similar to AppHelpTemplate, it leverages text/template for flexible output. ```Go var CommandHelpTemplate = `NAME: {{template "helpNameTemplate" .}} USAGE: {{template "usageTemplate" .}}{{if .Category}} CATEGORY: {{.Category}}{{end}}{{if .Description}} DESCRIPTION: {{template "descriptionTemplate" .}}{{end}}{{if .VisibleFlagCategories}} OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} OPTIONS:{{template "visibleFlagTemplate" .}}{{end}} ` ``` -------------------------------- ### Customizable Help Template (Go) Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Defines the AppHelpTemplate variable, a text template for rendering the default help topic in CLI applications. It utilizes Go's text/template package for customization. ```Go var AppHelpTemplate = `NAME: {{template "helpNameTemplate" .}} USAGE: {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}}{{if .ArgsUsage}} {{.ArgsUsage}}{{else}}{{if .Args}} [arguments...]{{end}}{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} VERSION: {{.Version}}{{end}}{{end}}{{if .Description}} DESCRIPTION: {{template "descriptionTemplate" .}}{{end}}{{if len .Authors}} AUTHOR{{template "authorsTemplate" .}}{{end}}{{if .VisibleCommands}} COMMANDS:{{template "visibleCommandCategoryTemplate" .}}{{end}}{{if .VisibleFlagCategories}} GLOBAL OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} GLOBAL OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .Copyright}} COPYRIGHT: {{template "copyrightTemplate" .}}{{end}} ` ``` -------------------------------- ### Build Script (Old System) Source: https://github.com/nvidia/nvkind/blob/main/vendor/golang.org/x/sys/unix/README.md The `mkall.sh` script for the old build system. This script generates Go files based on C header files present on the system. It requires bash and Go, and running `mkall.sh -n` shows the commands that would be executed without actually running them. ```bash #!/bin/bash # Example skeleton for mkall.sh GOOS=${GOOS:-$(go env GOOS)} GOARCH=${GOARCH:-$(go env GOARCH)} if [ "$1" == "-n" ]; then echo "Running commands for GOOS=$GOOS GOARCH=$GOARCH" # Simulate commands without execution echo "go run mksysnum_*.go" echo "go build -o sysall_*.o" exit 0 fi if [ "$GOOS" == "" ] || [ "$GOARCH" == "" ]; then echo "GOOS and GOARCH must be set." exit 1 fi echo "Generating Go files for GOOS=$GOOS GOARCH=$GOARCH using old build system..." # Actual commands would go here, e.g.: # go run mksysnum_*.go # go build -o sysall_*.o exit 0 ``` -------------------------------- ### Go: Application Structure Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Defines the structure for an application, including its name, help name, usage information, and arguments format. It also contains fields for version and description. ```go type App struct { // The name of the program. Defaults to path.Base(os.Args[0]) Name string // Full name of command for help, defaults to Name HelpName string // Description of the program. Usage string // Text to override the USAGE section of help UsageText string // Whether this command supports arguments Args bool // Description of the program argument format. ArgsUsage string // Version of the program ``` -------------------------------- ### Initialize Input Source Context for CLI Commands Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Sets up an InputSourceContext for a cli.Command's Before method. It creates a new input source using a provided function and applies it to supported flags if successful. This function does not directly use the cli.Context. ```go func InitInputSource(flags []cli.Flag, createInputSource func() (InputSourceContext, error)) cli.BeforeFunc InitInputSource is used to to setup an InputSourceContext on a cli.Command Before method. It will create a new input source based on the func provided. If there is no error it will then apply the new input source to any flags that are supported by the input source ``` -------------------------------- ### Go App ToMan Method Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Generates a man page string for the `*App` configuration. Returns an error if the man page generation process fails. ```go func (a *App) ToMan() (string, error) ToMan creates a man page string for the `*App` The function errors if either ``` -------------------------------- ### Go: Predefined Flags for Bash Completion, Help, and Version Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Provides predefined Flag instances for common command-line functionalities: Bash completion, help display, and version information. These flags are typically boolean and can be customized with aliases and usage strings. ```go var BashCompletionFlag Flag = &BoolFlag{ Name: "generate-bash-completion", Hidden: true, } var HelpFlag Flag = &BoolFlag{ Name: "help", Aliases: []string{"h"}, Usage: "show help", DisableDefaultText: true, } var VersionFlag Flag = &BoolFlag{ Name: "version", Aliases: []string{"v"}, Usage: "print the version", DisableDefaultText: true, } ``` -------------------------------- ### Add JWT HMAC with SHA-512 Authentication Code Example (Go) Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/emicklei/go-restful/v3/CHANGES.md This snippet provides an example of implementing JWT HMAC with SHA-512 authentication. It demonstrates how to secure API endpoints using this authentication method within the Go programming language. No specific dependencies are mentioned, but it's part of the go-restful library. ```go package main import ( "fmt" "log" "net/http" "github.com/emicklei/go-restful/v3" // Assuming jwt and hmac packages are imported for the actual implementation ) func main() { // Example usage: // Create a new service wbs := go_restful.NewWebService() // Define a route that requires JWT HMAC SHA-512 authentication wbs.GET("/protected", func(request *go_restful.Request, response *go_restful.Response) { // Authentication middleware would typically check the JWT here response.WriteEntity("This is a protected resource.") }) // Add the service to the container go_restful.DefaultContainer.Add(wbs) // Start the HTTP server log.Printf("Start GlassFish server listening on port 8080 of all interfaces http://localhost:8080/go-restful") log.Fatal(http.ListenAndServe(":8080", nil)) } // Placeholder for the actual JWT HMAC SHA-512 authentication logic // This would involve verifying the JWT signature using HMAC SHA-512. func authenticateJWT_HMAC_SHA512(token string) (bool, error) { // ... implementation details ... fmt.Println("Verifying JWT with HMAC SHA-512...") return true, nil // Placeholder } ``` -------------------------------- ### MapInputSource: Get Source File Path Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt The Source method returns the path of the source file associated with the MapInputSource. This is helpful for tracking the origin of the input data. ```go func (fsm *MapInputSource) Source() string { // ... implementation details ... } ``` -------------------------------- ### Initialize Root Logger in Go Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/go-logr/logr/README.md Demonstrates the typical usage pattern for initializing the root logger in a Go application. It shows how to create a logger instance using a specific implementation and parameters. ```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 ... } ``` -------------------------------- ### Go: Display Application Help Information Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt An action function that displays the help information for the application. This is typically invoked when a user requests help. ```go func ShowAppHelp(cCtx *Context) error ShowAppHelp is an action that displays the help. ``` -------------------------------- ### Get Generic from Map Input Source Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Retrieves a generic cli.Generic type from the MapInputSource. This method is part of the MapInputSource type and is used for retrieving unspecified types. ```Go func (fsm *MapInputSource) Generic(name string) (cli.Generic, error) ``` -------------------------------- ### Verify NVIDIA Driver Source: https://github.com/nvidia/nvkind/blob/main/README.md This command verifies that the NVIDIA driver is installed and functioning correctly on the host system. It lists the detected GPUs and their UUIDs. This is a prerequisite for using nvkind. ```bash $ nvidia-smi -L GPU 0: NVIDIA A100-SXM4-40GB (UUID: GPU-4cf8db2d-06c0-7d70-1a51-e59b25b2c16c) GPU 1: NVIDIA A100-SXM4-40GB (UUID: GPU-4404041a-04cf-1ccf-9e70-f139a9b1e23c) GPU 2: NVIDIA A100-SXM4-40GB (UUID: GPU-79a2ba02-a537-ccbf-2965-8e9d90c0bd54) GPU 3: NVIDIA A100-SXM4-40GB (UUID: GPU-662077db-fa3f-0d8f-9502-21ab0ef058a2) GPU 4: NVIDIA A100-SXM4-40GB (UUID: GPU-ec9d53cc-125d-d4a3-9687-304df8eb4749) GPU 5: NVIDIA A100-SXM4-40GB (UUID: GPU-3eb87630-93d5-b2b6-b8ff-9b359caf4ee2) GPU 6: NVIDIA A100-SXM4-40GB (UUID: GPU-8216274a-c05d-def0-af18-c74647300267) GPU 7: NVIDIA A100-SXM4-40GB (UUID: GPU-b1028956-cfa2-0990-bf4a-5da9abb51763) ``` -------------------------------- ### Go App Run Method Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt The primary entry point for executing the CLI application. It parses the provided command-line arguments and dispatches to the appropriate flags and commands. ```go func (a *App) Run(arguments []string) (err error) Run is the entry point to the cli app. Parses the arguments slice and routes to the proper flag/args combination ``` -------------------------------- ### Get Duration from Map Input Source Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Retrieves a time.Duration value from the MapInputSource. If the key exists and corresponds to a duration, it's returned. Otherwise, it returns 0. This is a method of MapInputSource. ```Go func (fsm *MapInputSource) Duration(name string) (time.Duration, error) // Duration returns a duration from the map if it exists otherwise returns 0 ``` -------------------------------- ### Configure nvidia-container-toolkit for Docker Source: https://github.com/nvidia/nvkind/blob/main/README.md Configures the nvidia-container-toolkit for Docker, setting it as the default runtime and enabling CDI. This setup is crucial for injecting GPU support into Kubernetes worker nodes. ```bash sudo nvidia-ctk runtime configure --runtime=docker --set-as-default --cdi.enabled sudo nvidia-ctk config --set accept-nvidia-visible-devices-as-volume-mounts=true --in-place sudo systemctl restart docker ``` -------------------------------- ### Initialize Input Source Context with CLI Context Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Sets up an InputSourceContext for a cli.Command's Before method, allowing the use of the cli.Context for initialization. It creates a new input source using a provided function and applies it to supported flags if successful. This function can leverage existing cli.Context values. ```go func InitInputSourceWithContext(flags []cli.Flag, createInputSource func(cCtx *cli.Context) (InputSourceContext, error)) cli.BeforeFunc InitInputSourceWithContext is used to to setup an InputSourceContext on a cli.Command Before method. It will create a new input source based on the func provided with potentially using existing cli.Context values to initialize itself. If there is no error it will then apply the new input source to any flags that are supported by the input source ``` -------------------------------- ### Go: Display Command Completions Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Prints custom completion suggestions for a specific command. This is useful for shell integration and auto-completion features. ```go func ShowCommandCompletions(ctx *Context, command string) ShowCommandCompletions prints the custom completions for a given command ``` -------------------------------- ### Get Float64 from Map Input Source Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Retrieves a float64 value from the MapInputSource. If the key exists and is a float64, it's returned. Otherwise, it returns 0. This method is part of the MapInputSource struct. ```Go func (fsm *MapInputSource) Float64(name string) (float64, error) // Float64 returns an float64 from the map if it exists otherwise returns 0 ``` -------------------------------- ### Create Default GPU-Enabled Cluster Source: https://github.com/nvidia/nvkind/blob/main/README.md Creates a default nvkind cluster with a single worker node that has access to all available GPUs on the machine. Assumes prerequisites and setup steps are completed. ```bash ./nvkind cluster create ``` -------------------------------- ### Go App ToFishCompletion Method Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Generates a completion script for the fish shell for the current `*App` configuration. Returns an error if parsing or writing the script fails. ```go func (a *App) ToFishCompletion() (string, error) ToFishCompletion creates a fish completion string for the `*App` The function errors if either parsing or writing of the string fails. ``` -------------------------------- ### Go App RunAsSubcommand Method Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt A legacy method for running the application as a subcommand. New code should use `App.RunContext`. This method is scheduled for removal in v3. ```go func (a *App) RunAsSubcommand(ctx *Context) (err error) RunAsSubcommand is for legacy/compatibility purposes only. New code should only use App.RunContext. This function is slated to be removed in v3. ``` -------------------------------- ### Get Float64 Slice from Map Input Source Source: https://github.com/nvidia/nvkind/blob/main/vendor/github.com/urfave/cli/v2/godoc-current.txt Retrieves a slice of float64 values from the MapInputSource. If the key exists and is a slice of float64, it's returned. Otherwise, it returns nil. This is a method of MapInputSource. ```Go func (fsm *MapInputSource) Float64Slice(name string) ([]float64, error) // Float64Slice returns an []float64 from the map if it exists otherwise // returns nil ```