### Install go.yaml.in/yaml/v3 Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/go.yaml.in/yaml/v3/README.md Use 'go get' to install the v3 version of the YAML package. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install Ordered Map Library Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/pb33f/ordered-map/v2/README.md Install the ordered-map library using go get. ```bash go get -u github.com/pb33f/ordered-map ``` -------------------------------- ### Install blackfriday-tool Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Install the blackfriday-tool command-line utility using 'go get'. This tool provides a standalone way to process markdown files. ```bash go get github.com/russross/blackfriday-tool ``` -------------------------------- ### Install and Run Local Go Doc Site Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Installs and runs a local Go Doc site using pkgsite. Ensure you have Go installed and set up. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Install go.yaml.in/yaml/v2 Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/go.yaml.in/yaml/v2/README.md Use 'go get' to install the YAML package for Go. This command fetches and installs the specified package and its dependencies. ```bash go get go.yaml.in/yaml/v2 ``` -------------------------------- ### Initialize Instrumentation Explicitly Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Encapsulate instrumentation setup in constructor functions for clear ownership and scope. This example shows explicit initialization, checking for observability enablement, and joining errors during metric setup. ```go import ( "errors" semconv "go.opentelemetry.io/otel/semconv/v1.41.0" "go.opentelemetry.io/otel/semconv/v1.41.0/otelconv" ) type SDKComponent struct { inst *instrumentation } func NewSDKComponent(config Config) (*SDKComponent, error) { inst, err := newInstrumentation() if err != nil { return nil, err } return &SDKComponent{inst: inst}, nil } type instrumentation struct { inflight otelconv.SDKComponentInflight exported otelconv.SDKComponentExported } func newInstrumentation() (*instrumentation, error) { if !x.Observability.Enabled() { return nil, nil } meter := otel.GetMeterProvider().Meter( "", metric.WithInstrumentationVersion(sdk.Version()), metric.WithSchemaURL(semconv.SchemaURL), ) inst := &instrumentation{} var err, e error inst.inflight, e = otelconv.NewSDKComponentInflight(meter) err = errors.Join(err, e) inst.exported, e = otelconv.NewSDKComponentExported(meter) err = errors.Join(err, e) return inst, err } ``` ```go // ❌ Avoid this pattern. func (c *Component) initObservability() { // Initialize observability metrics if !x.Observability.Enabled() { return } // Initialize observability metrics c.inst = &instrumentation {/* ... */} } ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/json-iterator/go/README.md Install the json-iterator/go library using the go get command. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Install go.yaml.in/yaml/v4 Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/go.yaml.in/yaml/v4/README.md Use 'go get' to install the v4 version of the YAML package for your Go projects. ```bash go get go.yaml.in/yaml/v4 ``` -------------------------------- ### Install golangci-lint Linter Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/AGENTS.md Install the recommended linter for the project. This helps maintain code quality and consistency. ```bash make install.lint ``` -------------------------------- ### Install Ginkgo v2 for Parallel Testing Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/validation.md Install the Ginkgo v2 test framework using `go install` to enable parallel test execution. ```sh go install github.com/onsi/ginkgo/v2/ginkgo@latest ``` -------------------------------- ### SpdyStream Client Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/moby/spdystream/README.md Client example for connecting to a mirroring server without authentication. Requires establishing a TCP connection and then a SpdyStream connection. ```go package main import ( "fmt" "github.com/moby/spdystream" "net" "net/http" ) func main() { conn, err := net.Dial("tcp", "localhost:8080") if err != nil { panic(err) } spdyConn, err := spdystream.NewConnection(conn, false) if err != nil { panic(err) } go spdyConn.Serve(spdystream.NoOpStreamHandler) stream, err := spdyConn.CreateStream(http.Header{}, nil, false) if err != nil { panic(err) } stream.Wait() fmt.Fprint(stream, "Writing to stream") buf := make([]byte, 25) stream.Read(buf) fmt.Println(string(buf)) stream.Close() } ``` -------------------------------- ### Install Ginkgo Locally Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Installs the Ginkgo CLI tool locally using Go modules. ```bash go install ./... ``` -------------------------------- ### Install uuid Package Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/google/uuid/README.md Use this command to install the uuid package using go get. ```sh go get github.com/google/uuid ``` -------------------------------- ### Build and Install cri-tools Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/developer-guide.md Execute 'make' to build cri-tools (critest and crictl), followed by 'make install' to install them to a common location. Use 'sudo' if permission issues arise. ```bash $ make && make install # prefix sudo if run into permissions issues ``` -------------------------------- ### Install critest Binary Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/benchmark.md Download and install the `critest` benchmarking binary. Ensure you have `wget` and `tar` available. ```sh VERSION="v1.36.0" ARCH="amd64" wget https://github.com/kubernetes-sigs/cri-tools/releases/download/$VERSION/critest-$VERSION-linux-$ARCH.tar.gz sudo tar zxvf critest-$VERSION-linux-$ARCH.tar.gz -C /usr/local/bin rm -f critest-$VERSION-linux-$ARCH.tar.gz ``` -------------------------------- ### Install Blackfriday v2 Package Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Use 'go get' to install the v2 version of the Blackfriday package. This command resolves and adds the package to your module. ```bash go get github.com/russross/blackfriday/v2 ``` -------------------------------- ### App Constructor and Initialization Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt Provides methods for creating a new App instance and performing initial setup. ```APIDOC ## App Constructor and Initialization ### Description Methods for creating and setting up a new CLI application. ### Methods #### `NewApp() *App` **Description**: Creates a new cli Application with some reasonable defaults for Name, Usage, Version and Action. #### `Setup()` **Description**: 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. ``` -------------------------------- ### Coexist with glog Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/k8s.io/klog/v2/README.md This example demonstrates how to initialize and synchronize flags between klog and glog using the global flag.CommandLine FlagSet. It also configures stderr as the combined output. ```go import ( "flag" "k8s.io/klog/v2" ) func main() { // Initialize klog flags klog.InitFlags(nil) // Parse command-line flags flag.Parse() // Ensure logs are written to stderr klog.SetOutput(os.Stderr) // Example logging klog.Info("This is an info message.") klog.Warning("This is a warning message.") klog.Error("This is an error message.") // Flush logs before exiting klog.Flush() } ``` -------------------------------- ### SpdyStream Server Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/moby/spdystream/README.md Server example for mirroring client streams without authentication. It listens for TCP connections and serves them using the MirrorStreamHandler. ```go package main import ( "github.com/moby/spdystream" "net" ) func main() { listener, err := net.Listen("tcp", "localhost:8080") if err != nil { panic(err) } for { conn, err := listener.Accept() if err != nil { panic(err) } spdyConn, err := spdystream.NewConnection(conn, true) if err != nil { panic(err) } go spdyConn.Serve(spdystream.MirrorStreamHandler) } } ``` -------------------------------- ### Start Container Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/crictl.md Starts a container that has been previously created. After starting, the container's state changes to 'Running'. ```sh $ crictl start 3e025dd50a72d956c4f14881fbb5b1080c9275674e95fb67f965f6478a957d60 3e025dd50a72d956c4f14881fbb5b1080c9275674e95fb67f965f6478a957d60 $ crictl ps CONTAINER ID IMAGE CREATED STATE NAME ATTEMPT 3e025dd50a72d busybox About a minute ago Running busybox 0 ``` -------------------------------- ### Install cri-tools Dependencies Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/developer-guide.md Run the 'make install.tools' command to install the necessary dependencies for building cri-tools. ```bash $ make install.tools ``` -------------------------------- ### Ginkgo Spec Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/onsi/ginkgo/v2/README.md An example of a Ginkgo spec demonstrating BeforeEach, When, Context, It, and various Gomega matchers for testing library operations. ```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)) }) }) ``` -------------------------------- ### Preview Ginkgo Documentation Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Builds and serves the Ginkgo documentation locally using Jekyll. Ensure you have Bundler installed. ```bash bundle && bundle exec jekyll serve ``` -------------------------------- ### Create and Start Container in One Command Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/crictl.md Creates and starts a container in a single command. The image will be automatically pulled if not present locally. The container is immediately in the 'Running' state. ```sh $ cat pod-config.json { "metadata": { "name": "nginx-sandbox", "namespace": "default", "attempt": 1, "uid": "hdishd83djaidwnduwk28bcsb" }, "log_directory": "/tmp", "linux": { } } $ cat container-config.json { "metadata": { "name": "busybox" }, "image":{ "image": "busybox" }, "command": [ "top" ], "log_path":"busybox.0.log", "linux": { } } $ crictl run container-config.json pod-config.json b25b4f26e342969eb40d05e98130eee0846557d667e93deac992471a3b8f1cf4 ``` ```sh $ crictl ps CONTAINER IMAGE CREATED STATE NAME ATTEMPT POD ID b25b4f26e3429 busybox:latest 14 seconds ago Running busybox 0 158d7a6665ff3 ``` -------------------------------- ### Definition List Syntax Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Demonstrates the syntax for creating definition lists, with terms followed by a colon and their definitions. ```markdown Cat : Fluffy animal everyone likes Internet : Vector of transmission for pictures of cats ``` -------------------------------- ### Go Clock Implementation Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/tetratelabs/wazero/RATIONALE.md This Go function demonstrates how to retrieve both wall time and nanosecond time, combining them into a single call. ```Go func time_now() (sec int64, nsec int32, mono int64) { sec, nsec = walltime() return sec, nsec, nanotime() } ``` -------------------------------- ### fsnotify Test Script Syntax Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Example demonstrating the 'shell-like' syntax for creating test cases in the testdata directory. This format allows defining scripts and their expected output for testing fsnotify functionality. ```bash # Create a new empty file with some data. watch / echo data >/file Output: create /file write /file ``` -------------------------------- ### Table Syntax Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Illustrates the syntax for creating tables in Markdown using pipes and hyphens for separation. ```markdown Name | Age --------|------ Bob | 27 Alice | 23 ``` -------------------------------- ### Signed Integer Global Constant Initializer Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/tetratelabs/wazero/RATIONALE.md This example demonstrates how wazero treats integer global constant initializers as signed, even though WebAssembly has no explicit signed integer value type. The binary encoding of certain numbers can differ between signed and unsigned interpretations. ```wast (global (export "start_epoch") i64 (i64.const 1620216263544)) ``` -------------------------------- ### Create and Use fsnotify Watcher Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/fsnotify/fsnotify/README.md This example demonstrates how to create a new fsnotify watcher, set up goroutines to listen for events and errors, add a directory to watch, and handle file write events. Ensure the watcher's channels are closed properly. ```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{}) } ``` -------------------------------- ### Proper Initialization of RuntimeConfig Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/tetratelabs/wazero/RATIONALE.md Demonstrates the correct way to initialize a RuntimeConfig using the NewRuntimeConfig constructor, contrasting it with incorrect methods. ```go rt := &RuntimeConfig{} // not initialized properly (fields are nil which shouldn't be) rt := RuntimeConfig{} // not initialized properly (should be a pointer) rt := wazero.NewRuntimeConfig() // initialized properly ``` -------------------------------- ### ModuleConfig with Option Functions Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/tetratelabs/wazero/RATIONALE.md Demonstrates the option function pattern for configuring modules, allowing for more flexible initialization. ```go type ModuleConfig interface { } struct moduleConfig { name string fs fs.FS } type ModuleConfigOption func(c *moduleConfig) func ModuleConfigName(name string) ModuleConfigOption { return func(c *moduleConfig) { c.name = name } } func ModuleConfigFS(fs fs.FS) ModuleConfigOption { return func(c *moduleConfig) { c.fs = fs } } func (r *runtime) NewModuleConfig(opts ...ModuleConfigOption) ModuleConfig { ret := newModuleConfig() // defaults for _, opt := range opts { opt(&ret.config) } return ret } func (c *moduleConfig) WithOptions(opts ...ModuleConfigOption) ModuleConfig { ret := *c // copy base config for _, opt := range opts { opt(&ret.config) } return ret } config := r.NewModuleConfig(ModuleConfigFS(fs)) configDerived := config.WithOptions(ModuleConfigName("name")) ``` -------------------------------- ### Create Root Logger in Go Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/go-logr/logr/README.md Demonstrates how to create the initial 'root' logger using a specific implementation like 'logimpl'. This is typically done early in an application's setup. ```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 ... } ``` -------------------------------- ### Get Latest wazero Version Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/tetratelabs/wazero/README.md Install or update the wazero library to the latest stable version using the Go toolchain. This command ensures you have the most recent features and bug fixes. ```bash go get github.com/tetratelabs/wazero@latest ``` -------------------------------- ### Get/Set unsafe.Pointer Value with reflect2 Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/modern-go/reflect2/README.md This example shows how to get and set values using `unsafe.Pointer` with `reflect2`. Similar to interface operations, ensure you are using the pointer `*type` for accurate results. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.UnsafeSet(unsafe.Pointer(&i), unsafe.Pointer(&j)) // i will be 10 ``` -------------------------------- ### Verify Go Environment Setup Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/developer-guide.md Check if the 'go' directory exists in the home directory and if the 'go/bin' directory is included in the system's PATH environment variable. ```bash $ ls $HOME go ``` ```bash $ echo $PATH | grep go PATH=$PATH:/usr/local/go/bin:$HOME/go/bin # $PATH here refers to truncated version of additional `env` paths that are unrelated this guide / setup ``` -------------------------------- ### Check if a File Descriptor is a Terminal and Get Window Size Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/moby/term/README.md This example demonstrates how to check if a given file descriptor belongs to a terminal and, if so, retrieve its dimensions (height and width). Ensure the 'term' package is imported. ```go package main import ( "log" "os" "github.com/moby/term" ) func main() { fd := os.Stdin.Fd() if term.IsTerminal(fd) { ws, err := term.GetWinsize(fd) if err != nil { log.Fatalf("term.GetWinsize: %s", err) } log.Printf("%d:%d\n", ws.Height, ws.Width) } } ``` -------------------------------- ### JSONParser Usage Examples Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/buger/jsonparser/README.md Demonstrates various ways to use the `jsonparser` library, including accessing specific fields, getting typed values, iterating over arrays and objects, and efficiently extracting multiple keys. ```APIDOC ## Example Usage ### Accessing Specific Fields ```go import "github.com/buger/jsonparser" data := []byte(`{ "person": { "name": { "first": "Leonid", "last": "Bugaev", "fullName": "Leonid Bugaev" }, "github": { "handle": "buger", "followers": 109 }, "avatars": [ { "url": "https://avatars1.githubusercontent.com/u/14009?v=3&s=460", "type": "thumbnail" } ] }, "company": { "name": "Acme" } }`) // Get string value fullName, _, _, _ := jsonparser.Get(data, "person", "name", "fullName") // Get integer value using helper followers, _ := jsonparser.GetInt(data, "person", "github", "followers") // Get object as byte slice companyData, _, _, _ := jsonparser.Get(data, "company") // Handling non-existent keys var size int64 if value, err := jsonparser.GetInt(data, "company", "size"); err == nil { size = value } ``` ### Iterating Over Arrays (`ArrayEach`) ```go jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) { fmt.Println(jsonparser.Get(value, "url")) }, "person", "avatars") ``` ### Accessing Array Elements by Index ```go avatarURL, _, _, _ := jsonparser.GetString(data, "person", "avatars", "[0]", "url") ``` ### Iterating Over Objects (`ObjectEach`) ```go jsonparser.ObjectEach(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error { fmt.Printf("Key: '%s'\n Value: '%s'\n Type: %s\n", string(key), string(value), dataType) return nil }, "person", "name") ``` ### Efficiently Extracting Multiple Keys (`EachKey`) ```go paths := [][]string{ []string{"person", "name", "fullName"}, []string{"person", "avatars", "[0]", "url"}, []string{"company", "url"}, } jsonparser.EachKey(data, func(idx int, value []byte, vt jsonparser.ValueType, err error){ switch idx { case 0: // []string{"person", "name", "fullName"} // Handle fullName case 1: // []string{"person", "avatars", "[0]", "url"} // Handle avatarURL case 2: // []string{"company", "url"}, // Handle companyURL } }, paths...) ``` ``` -------------------------------- ### Ordered Map with Capacity Hint Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/pb33f/ordered-map/v2/README.md Shows how to initialize an ordered map with a capacity hint for performance optimization. ```go om := orderedmap.New[int, *myStruct](28) ``` -------------------------------- ### Get Float64Flag Value Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt The Get method retrieves the float64 value of the flag from the given Context. ```go func (f *Float64Flag) Get(ctx *Context) float64 Get returns the flag’s value in the given Context. ``` -------------------------------- ### Basic CLI Application with Action Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt An example of a functional CLI application that defines a name, usage, and a simple action to be executed. The action prints 'Greetings' to the console. ```go package main import ( "fmt" "os" "github.com/urfave/cli/v2" ) 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) } ``` -------------------------------- ### Verify cri-tools Installation Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/developer-guide.md Check if the 'crictl' and 'critest' binaries are installed and accessible in the system's PATH. ```bash $ which crictl /usr/local/bin/crictl ``` ```bash $ which critest /usr/local/bin/critest ``` -------------------------------- ### Footnote Syntax Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Provides an example of how to create footnotes in Markdown, with a marker in the text and the definition at the end. ```markdown This is a footnote.[^1] [^1]: the footnote text. ``` -------------------------------- ### Install Prettier for Formatting Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/AGENTS.md Install Prettier, a tool for consistent code formatting, primarily for Markdown files. Requires Node.js. ```bash make install.prettier ``` -------------------------------- ### Install Zizmor Static Analyzer Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/AGENTS.md Install Zizmor, a static analyzer for GitHub Actions workflows. It runs as part of `make verify`. ```bash make install.zizmor ``` -------------------------------- ### Wrap String Example in Go Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/mitchellh/go-wordwrap/README.md Demonstrates basic usage of the `WrapString` function from the `wordwrap` package to wrap a given string to a specified width. Ensure the `wordwrap` package is imported. ```go wrapped := wordwrap.WrapString("foo bar baz", 3) fmt.Println(wrapped) ``` -------------------------------- ### Get OpenTelemetry Go with go get Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md This command fetches the OpenTelemetry Go project into your GOPATH. Ignore any build constraint warnings. ```sh go get -d go.opentelemetry.io/otel ``` -------------------------------- ### Sanitize Untrusted Content Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md This example demonstrates how to sanitize untrusted content to protect against JavaScript injection using the bluemonday HTML sanitizer. ```go p := bluemonday.UGCPolicy() p.AllowAttrs("class").Matching(regexp.MustCompile("^language-[a-zA-Z0-9]+$")).OnElements("code") html := p.SanitizeBytes(unsafe) ``` -------------------------------- ### Create New Configuration with Options Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Wraps default settings and applies user-provided options to create a configured struct. This function is typically unexported and handles default value assignment and option application. ```go // newConfig returns an appropriately configured config. func newConfig(options ...Option) config { // Set default values for config. config := config{/* […] */} for _, option := range options { config = option.apply(config) } // Perform any validation here. return config } ``` -------------------------------- ### New Function Signature with Options Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Demonstrates the signature for a New function that accepts variadic Option parameters for configuration. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Run Pod Sandbox with Configuration Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/crictl.md Example of defining a pod sandbox configuration in JSON format and then using `crictl runp` to create the sandbox. Includes an alternative configuration for runtimes using systemd cgroup driver. ```json { "metadata": { "name": "nginx-sandbox", "namespace": "default", "attempt": 1, "uid": "hdishd83djaidwnduwk28bcsb" }, "log_directory": "/tmp", "linux": { } } ``` ```json { "metadata": { "name": "nginx-sandbox", "namespace": "default", "attempt": 1, "uid": "hdishd83djaidwnduwk28bcsb" }, "log_directory": "/tmp", "linux": { "cgroup_parent": "/test.slice" } } ``` ```sh $ crictl runp pod-config.json f84dd361f8dc51518ed291fbadd6db537b0496536c1d2d6c05ff943ce8c9a54f ``` -------------------------------- ### Chaining Configuration Methods for Error Handling Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/tetratelabs/wazero/RATIONALE.md Illustrates how chaining configuration methods simplifies error handling by consolidating checks to a single call site. ```go cfg = cfg.WithFS(fs).WithName(name) mod, err = rt.InstantiateModuleWithConfig(ctx, code, cfg) if err != nil { return err } ``` -------------------------------- ### fsnotify Output Format Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Example of the expected output format for fsnotify tests. Events are listed with their path, and platform-specific outputs can be specified using GOOS. ```bash # Comment event path # Comment system: event path system2: event path ``` -------------------------------- ### Basic glog Usage Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/k8s.io/klog/v2/README.md Demonstrates basic logging functions like Info and Fatalf. Ensure glog is imported to use these functions. ```go glog.Info("Prepare to repel boarders") ``` ```go glog.Fatalf("Initialization failed: %s", err) ``` -------------------------------- ### Install crictl CLI Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/README.md Installs the crictl CLI tool by downloading a specific version and extracting it to the /usr/local/bin directory. Ensure the VERSION variable is set to the desired release. ```sh VERSION="v1.36.0" wget https://github.com/kubernetes-sigs/cri-tools/releases/download/$VERSION/crictl-$VERSION-linux-amd64.tar.gz sudo tar zxvf crictl-$VERSION-linux-amd64.tar.gz -C /usr/local/bin rm -f crictl-$VERSION-linux-amd64.tar.gz ``` -------------------------------- ### ModuleConfig with Chaining Fields Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/tetratelabs/wazero/RATIONALE.md Illustrates the traditional Go approach to configuration using method chaining. ```go type ModuleConfig interface { WithName(string) ModuleConfig WithFS(fs.FS) ModuleConfig } struct moduleConfig { name string fs fs.FS } func (c *moduleConfig) WithName(name string) ModuleConfig { ret := *c // copy ret.name = name return &ret } func (c *moduleConfig) WithFS(fs fs.FS) ModuleConfig { ret := *c // copy ret.setFS("/", fs) return &ret } config := r.NewModuleConfig().WithFS(fs) configDerived := config.WithName("name") ``` -------------------------------- ### Install critest Validation Tool Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/README.md Installs the critest validation tool by downloading a specific version and extracting it to the /usr/local/bin directory. Ensure the VERSION variable is set to the desired release. ```sh VERSION="v1.36.0" wget https://github.com/kubernetes-sigs/cri-tools/releases/download/$VERSION/critest-$VERSION-linux-amd64.tar.gz sudo tar zxvf critest-$VERSION-linux-amd64.tar.gz -C /usr/local/bin rm -f critest-$VERSION-linux-amd64.tar.gz ``` -------------------------------- ### Get/Set Interface{} Value with reflect2 Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/modern-go/reflect2/README.md This snippet demonstrates how to get and set values of an interface type using `reflect2`. Always use the pointer `*type` when getting or setting values to ensure correct behavior. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.Set(&i, &j) // i will be 10 ``` -------------------------------- ### JSONParser Get Method Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/buger/jsonparser/README.md The core `Get` method allows extraction of values from JSON data by specifying a path through keys and array indexes. It returns the value, its data type, offset, and any errors encountered. ```APIDOC ## Get ### Description Receives data structure, and key path to extract value from. Returns: * `value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error * `dataType` - Can be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null` * `offset` - Offset from provided data structure where key value ends. Used mostly internally, for example for `ArrayEach` helper. * `err` - If the key is not found or any other parsing issue, it should return error. If key not found it also sets `dataType` to `NotExist` Accepts multiple keys to specify path to JSON value (in case of quering nested structures). If no keys are provided it will try to extract the closest JSON value (simple ones or object/array), useful for reading streams or arrays, see `ArrayEach` implementation. Note that keys can be an array indexes: `jsonparser.GetInt("person", "avatars", "[0]", "url")`, pretty cool, yeah? ### Method ```go func Get(data []byte, keys ...string) (value []byte, dataType jsonparser.ValueType, offset int, err error) ``` ``` -------------------------------- ### Run golangci-lint locally Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/Microsoft/go-winio/README.md Install golangci-lint locally and run it from the repository root to check for linting errors. Use flags to control the output of lint errors. ```shell # use . or specify a path to only lint a package # to show all lint errors, use flags "--max-issues-per-linter=0 --max-same-issues=0" > golangci-lint run ./... ``` -------------------------------- ### Install crictl using curl Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/crictl.md Download and install the crictl binary for Linux amd64 using curl. This snippet sets the version, downloads the tarball with an output file, extracts it to /usr/local/bin, and cleans up the downloaded file. ```sh VERSION="v1.36.0" curl -L https://github.com/kubernetes-sigs/cri-tools/releases/download/$VERSION/crictl-${VERSION}-linux-amd64.tar.gz --output crictl-${VERSION}-linux-amd64.tar.gz sudo tar zxvf crictl-$VERSION-linux-amd64.tar.gz -C /usr/local/bin rm -f crictl-$VERSION-linux-amd64.tar.gz ``` -------------------------------- ### Example: TagSet and TagOptions for CBOR Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/fxamacker/cbor/v2/README.md Shows how to create a TagSet, register a tag (COSE_Sign1 18) with a specific type, and use it to create immutable decoding and encoding modes for CBOR 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 := em.Marshal(v); err != nil { return err } ``` -------------------------------- ### Get Float64Flag Category Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt GetCategory returns the category assigned to the Float64Flag. ```go func (f *Float64Flag) GetCategory() string GetCategory returns the category for the flag ``` -------------------------------- ### Format Code with Make Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/buger/jsonparser/README.md Runs go fmt to format the project's Go code. ```bash make fmt ``` -------------------------------- ### Calling Exported Function Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/tetratelabs/wazero/RATIONALE.md Demonstrates how to call an exported WebAssembly function from Go, passing parameters as uint64 and handling results and errors. This syntax is applicable for various integer types. ```go x, y := uint64(1), uint64(2) results, err := mod.ExportedFunction("add").Call(ctx, x, y) if err != nil { log.Panicln(err) } fmt.Printf("%d + %d = %d\n", x, y, results[0]) ``` -------------------------------- ### Migration Guide: Update Import Statements Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/sigs.k8s.io/yaml/goyaml.v3/README.md Shows how to change import statements when migrating from sigs.k8s.io/yaml/goyaml.v3 to go.yaml.in/yaml/v3. ```go // From import "sigs.k8s.io/yaml/goyaml.v3" // To import "go.yaml.in/yaml/v3" ``` -------------------------------- ### Import Blackfriday v2 Package Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Import the Blackfriday v2 package into your Go project. This is typically done after installing it. ```go import "github.com/russross/blackfriday/v2" ``` -------------------------------- ### Runtime Struct Example Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/tetratelabs/wazero/RATIONALE.md Illustrates how a runtime struct might be defined to wrap a wasm.Store, demonstrating a pattern to avoid cyclic dependencies by using a cover type. ```go type runtime struct { s *wasm.Store } ``` -------------------------------- ### Initialize Input Source Context Source: https://github.com/kubernetes-sigs/cri-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt Use InitInputSource to set up an InputSourceContext on a cli.Command Before method. It creates a new input source based on the provided function and applies it to supported flags. ```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 ```