### Install json-iterator/go Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/json-iterator/go/README.md Install the library using the go get command. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Install jsonreference Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-openapi/jsonreference/README.md Use 'go get' to add the jsonreference library to your project. ```cmd go get github.com/go-openapi/jsonreference ``` -------------------------------- ### Install go-openapi/jsonpointer Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-openapi/jsonpointer/README.md Use 'go get' to add the jsonpointer library to your project. ```cmd go get github.com/go-openapi/jsonpointer ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.yaml.in/yaml/v3/README.md Use 'go get' to install the YAML package for your Go project. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Define a WebService with Routes Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/emicklei/go-restful/v3/README.md Example of defining a new WebService, setting its path, supported content types, and defining a GET route for retrieving a user. This snippet demonstrates basic route configuration and parameter definition. ```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 and Run Local Go Doc Site Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Installs the pkgsite tool and runs a local Go documentation site. This is useful for previewing package documentation. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Install uuid Package Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/google/uuid/README.md Install the uuid package using the go get command. ```sh go get github.com/google/uuid ``` -------------------------------- ### Install multierr Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.uber.org/multierr/README.md Install the latest version of the multierr library using the go get command. ```bash go get -u go.uber.org/multierr@latest ``` -------------------------------- ### Install Cobra Library Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/spf13/cobra/README.md Install the latest version of the Cobra library using go get. ```bash go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Initialize Procfs and Get CPU Stats Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem and retrieves CPU statistics. Use this to get basic CPU usage information. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Setup Zap Repository Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.uber.org/zap/CONTRIBUTING.md Clone the zap repository and set up the upstream remote for contributing. ```bash mkdir -p $GOPATH/src/go.uber.org cd $GOPATH/src/go.uber.org git clone git@github.com:your_github_username/zap.git cd zap git remote add upstream https://github.com/uber-go/zap.git git fetch upstream ``` -------------------------------- ### Coexist with glog Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/k8s.io/klog/v2/README.md Example demonstrating how to initialize and synchronize flags between klog and glog, using stderr for combined output. ```go package main import ( "flag" "k8s.io/klog/v2" "github.com/golang/glog" ) func main() { // Initialize glog flags glog.InitFlags() // Initialize klog flags klog.InitFlags(nil) // Set alsologtostderr to true for combined output to stderr flag.Set("alsologtostderr", "true") // Use klog and glog as usual klog.Info("This is a klog message") glog.Info("This is a glog message") // Flush logs before exiting klog.Flush() glog.Flush() } ``` -------------------------------- ### Get OpenTelemetry Go Project Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use 'go get' to download the OpenTelemetry Go project, which places it within your GOPATH. Ignore potential build constraint warnings. ```go go get -d go.opentelemetry.io/otel ``` -------------------------------- ### Example: TagSet and TagOptions Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/fxamacker/cbor/v2/README.md Demonstrates creating a TagSet, registering a tag (COSE_Sign1, tag 18) with specific encoding/decoding options, and then using this TagSet to create decoding and encoding modes. ```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 } ``` -------------------------------- ### Go float16 Usage Examples Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/x448/float16/README.md Demonstrates converting between float32 and float16 using the float16 package. Includes examples for direct conversion and conditional conversion based on precision. ```Go import ( "math" "github.com/x448/float16" ) // Convert float32 to float16 pi := float32(math.Pi) pi16 := float16.Fromfloat32(pi) // Convert float16 to float32 pi32 := pi16.Float32() // PrecisionFromfloat32() is faster than the overhead of calling a function. // This example only converts if there's no data loss and input is not a subnormal. if float16.PrecisionFromfloat32(pi) == float16.PrecisionExact { pi16 := float16.Fromfloat32(pi) } ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/spf13/cobra/README.md Install the cobra-cli command line program for generating Cobra application scaffolding. ```bash go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Convert klog Infof to logr Info Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-logr/logr/README.md Example of converting a klog.Infof call with format specifiers to a logr.Info call with key-value pairs. ```go logger.V(4).Info("got a retry-after response when requesting url", "attempt", retries, "after seconds", seconds, "url", url) ``` -------------------------------- ### Initialize Block Device FS and Get Disk Stats Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/prometheus/procfs/README.md Initializes a filesystem object requiring both /proc and /sys, then retrieves block device statistics. Use this for disk I/O metrics. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Zap Logger Quick Start Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.uber.org/zap/README.md Use Logger when performance and type safety are critical. It is faster than SugaredLogger and allocates less, supporting only structured logging. ```go logger, _ := zap.NewProduction() deferr logger.Sync() logger.Info("failed to fetch URL", // Structured context as strongly typed Field values. zap.String("url", url), zap.Int("attempt", 3), zap.Duration("backoff", time.Second), ) ``` -------------------------------- ### Dynamic JSON Unmarshaling Example Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-openapi/swag/jsonutils/README.md Demonstrates how to unmarshal JSON into a generic 'any' type to represent dynamic JSON structures. ```go var value any jsonBytes := `{"a": 1, ... }` _ = json.Unmarshal(jsonBytes, &value) ``` -------------------------------- ### Windows Kubelet Registration Probe Configuration Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/README.md Example container configuration for the node-driver-registrar on Windows, using the kubelet-registration-probe mode. Note the use of .exe for the command and Windows-style paths. ```yaml containers: - name: csi-driver-registrar image: k8s.gcr.io/sig-storage/csi-node-driver-registrar:v2.5.0 args: - --v=5 - --csi-address=unix://C:\\csi\\csi.sock - --kubelet-registration-path=C:\\var\\lib\\kubelet\\plugins\\\\csi.sock livenessProbe: exec: command: - /csi-node-driver-registrar.exe - --kubelet-registration-path=C:\\var\\lib\\kubelet\\plugins\\\\csi.sock - --mode=kubelet-registration-probe initialDelaySeconds: 30 timeoutSeconds: 15 ``` -------------------------------- ### Linux Kubelet Registration Probe Configuration Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/README.md Example container configuration for the node-driver-registrar on Linux, utilizing the kubelet-registration-probe mode. Ensure the --kubelet-registration-path matches the container arguments. ```yaml containers: - name: csi-driver-registrar image: k8s.gcr.io/sig-storage/csi-node-driver-registrar:v2.5.0 args: - "--v=5" - "--csi-address=/csi/csi.sock" - "--kubelet-registration-path=/var/lib/kubelet/plugins//csi.sock" livenessProbe: exec: command: - /csi-node-driver-registrar - --kubelet-registration-path=/var/lib/kubelet/plugins//csi.sock - --mode=kubelet-registration-probe initialDelaySeconds: 30 timeoutSeconds: 15 ``` -------------------------------- ### Import Swag Library Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-openapi/swag/README.md Import the swag library into your Go project using go get. Two commands are provided for direct import or backward compatibility. ```cmd go get github.com/go-openapi/swag/{module} ``` ```cmd go get github.com/go-openapi/swag ``` -------------------------------- ### Deterministic Testing Setup in Go Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Isolate state for deterministic testing by restoring global variables after tests and using environment variable manipulation. Reset component ID counters to ensure deterministic component names. ```go func TestObservability(t *testing.T) { // Restore state after test to ensure this does not affect other tests. prev := otel.GetMeterProvider() t.Cleanup(func() { otel.SetMeterProvider(prev) }) // Isolate the meter provider for deterministic testing reader := metric.NewManualReader() meterProvider := metric.NewMeterProvider(metric.WithReader(reader)) otel.SetMeterProvider(meterProvider) // Use t.Setenv to ensure environment variable is restored after test. t.Setenv("OTEL_GO_X_OBSERVABILITY", "true") // Reset component ID counter to ensure deterministic component names. componentIDCounter.Store(0) /* ... test code ... */ } ``` -------------------------------- ### Add or Update a Single Dependency with Go Modules Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/release-tools/README.md Use 'go get' to add a new dependency or update an existing one to its latest version. ```shell GO111MODULE=on go get ``` -------------------------------- ### Create Root Logger in Main Function Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-logr/logr/README.md Demonstrates how to initialize the root logger using a specific implementation (e.g., 'logimpl') early in the application's lifecycle. This sets up the logging for the entire 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 ... } ``` -------------------------------- ### Instantiation with Options Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Demonstrates how to instantiate a type T using a variadic slice of Option parameters. Required parameters can precede the options. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Check if Started by Explorer Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/inconshreveable/mousetrap/README.md This function returns a boolean indicating if the process was started by double-clicking in Windows Explorer. It is the sole interface provided by the library. ```Go func StartedByExplorer() (bool) ``` -------------------------------- ### Get and Set Interface{} Value with reflect2 Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/modern-go/reflect2/README.md Demonstrates how to get and set values of an interface{} type using `reflect2`. Always use the pointer `*type` for setting values. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.Set(&i, &j) // i will be 10 ``` -------------------------------- ### Run Standard Tests Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/google.golang.org/grpc/CONTRIBUTING.md Execute the Go tests with specified CPU configurations and timeout. ```bash go test -cpu 1,4 -timeout 7m ./... ``` -------------------------------- ### Get and Set unsafe.Pointer with reflect2 Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/modern-go/reflect2/README.md Illustrates getting and setting values via `unsafe.Pointer` using `reflect2`. This method bypasses type checking. Always use the pointer `*type` for setting values. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.UnsafeSet(unsafe.Pointer(&i), unsafe.Pointer(&j)) // i will be 10 ``` -------------------------------- ### Basic Usage with slog Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-logr/zapr/README.md Shows how to initialize zapr and use it as a slog.Logger. Requires zap, logr/slogr, and zapr imports. ```go package main import ( "fmt" "log/slog" "github.com/go-logr/logr/slogr" "github.com/go-logr/zapr" "go.uber.org/zap" ) func main() { var log *slog.Logger zapLog, err := zap.NewDevelopment() if err != nil { panic(fmt.Sprintf("who watches the watchmen (%v)?", err)) } log = slog.New(slogr.NewSlogHandler(zapr.NewLogger(zapLog))) log.Info("Logr in action!", "the answer", 42) } ``` -------------------------------- ### Basic Usage with logr Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-logr/zapr/README.md Demonstrates how to initialize zapr and use it as a logr.Logger. Requires zap and logr imports. ```go package main import ( "fmt" "go.uber.org/zap" "github.com/go-logr/logr" "github.com/go-logr/zapr" ) func main() { var log logr.Logger zapLog, err := zap.NewDevelopment() if err != nil { panic(fmt.Sprintf("who watches the watchmen (%v)?", err)) } log = zapr.NewLogger(zapLog) log.Info("Logr in action!", "the answer", 42) } ``` -------------------------------- ### Lock Dependency to a Specific Version Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/release-tools/README.md Pin a specific dependency to a particular version using 'go get'. ```shell GO111MODULE=on go get @ ``` -------------------------------- ### Set a value using JSON Pointer Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-openapi/jsonpointer/README.md Shows how to create a JSON Pointer and use it to set a value within a document. Includes error handling for pointer creation and value setting operations. ```go ... var doc any ... pointer, err := jsonpointer.New("/foo/1") if err != nil { ... // error: e.g. invalid JSON pointer specification } doc, err = p.Set(doc, "value") if err != nil { ... // error: e.g. key not found, index out of bounds, etc. } ``` -------------------------------- ### Zap SugaredLogger Quick Start Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.uber.org/zap/README.md Use SugaredLogger for contexts where performance is important but not critical. It supports both structured and printf-style APIs. ```go logger, _ := zap.NewProduction() deferr logger.Sync() // flushes buffer, if any sugar := logger.Sugar() sugar.Infow("failed to fetch URL", // Structured context as loosely typed key-value pairs. "url", url, "attempt", 3, "backoff", time.Second, ) sugar.Infof("Failed to fetch URL: %s", url) ``` -------------------------------- ### Create New Configuration with Options Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md A factory function to create and configure a struct using a variadic list of options. It sets default values, applies options, and performs validation. ```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 } ``` -------------------------------- ### Create and Resolve JSON References Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-openapi/jsonreference/README.md Demonstrates creating new JSON references from strings, creating fragment-only references, and resolving references relative to a parent reference. ```go // Creating a new reference ref, err := jsonreference.New("http://example.com/doc.json#/definitions/Pet") // Fragment-only reference fragRef := jsonreference.MustCreateRef("#/definitions/Pet") // Resolving references parent, _ := jsonreference.New("http://example.com/base.json") child, _ := jsonreference.New("#/definitions/Pet") resolved, _ := parent.Inherits(child) // Result: "http://example.com/base.json#/definitions/Pet" ``` -------------------------------- ### Convert klog Infof to logr Error Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-logr/logr/README.md Example of converting a klog.Infof call with format specifiers to a logr.Error call with key-value pairs. ```go logger.Error(err, "client returned an error", "code", responseCode) ``` -------------------------------- ### Clone the OpenTelemetry Go Repository Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Clone the official OpenTelemetry Go repository to start development. This command fetches the entire project history. ```sh git clone https://github.com/open-telemetry/opentelemetry-go.git ``` -------------------------------- ### Handling Overlapping Configurations Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Illustrates a pattern for managing overlapping configurations between different types (e.g., Dog and Bird) using distinct option interfaces that all implement a common Option interface. ```go // config holds options for all animals. type config struct { Weight float64 Color string MaxAltitude float64 } // DogOption apply Dog specific options. type DogOption interface { applyDog(config) config } // BirdOption apply Bird specific options. type BirdOption interface { applyBird(config) config } // Option apply options for all animals. type Option interface { BirdOption DogOption } type weightOption float64 func (o weightOption) applyDog(c config) config { c.Weight = float64(o) return c } func (o weightOption) applyBird(c config) config { c.Weight = float64(o) return c } func WithWeight(w float64) Option { return weightOption(w) } type furColorOption string func (o furColorOption) applyDog(c config) config { c.Color = string(o) return c } func WithFurColor(c string) DogOption { return furColorOption(c) } type maxAltitudeOption float64 func (o maxAltitudeOption) applyBird(c config) config { c.MaxAltitude = float64(o) return c } func WithMaxAltitude(a float64) BirdOption { return maxAltitudeOption(a) } func NewDog(name string, o ...DogOption) Dog {…} func NewBird(name string, o ...BirdOption) Bird {…} ``` -------------------------------- ### Initialize Instrumentation Explicitly in Constructor Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Encapsulate instrumentation setup in constructor functions for clear ownership and scope. This ensures explicit, side-effect-free initialization. ```go import ( "errors" semconv "go.opentelemetry.io/otel/semconv/v1.40.0" "go.opentelemetry.io/otel/semconv/v1.40.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 } ``` -------------------------------- ### Run prerelease make target Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/RELEASING.md Execute the 'prerelease' make target to create a release branch with updated module versions. ```bash make prerelease MODSET= ``` -------------------------------- ### Format Code and Run Tests with Make Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/spf13/cobra/CONTRIBUTING.md Ensure code consistency by formatting and running all tests using the make utility. This command should be run before submitting changes. ```bash make all ``` -------------------------------- ### Add or Update Dependency Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Use 'go get' to add or update external package dependencies. This command manages versions and ensures dependencies are vendored. ```bash # Pick the latest tagged release. go get example.com/some/module/pkg # Pick a specific version. go get example.com/some/module/pkg@vX.Y.Z ``` -------------------------------- ### Get Integer Value from FlagSet Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/spf13/pflag/README.md Retrieve the integer value of a flag from a FlagSet using GetInt(). Ensure the flag exists and is of type integer, otherwise it will fail. ```go i, err := flagset.GetInt("flagname") ``` -------------------------------- ### Basic Info Log Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/k8s.io/klog/v2/README.md Use glog.Info for standard informational messages. ```go glog.Info("Prepare to repel boarders") ``` -------------------------------- ### Get Type by Name with reflect2 Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/modern-go/reflect2/README.md Retrieves a type by its fully qualified name, similar to Java's `Class.forName`. Ensure the type has been used to prevent compiler elimination. ```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 ``` -------------------------------- ### Develop and Submit Changes Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Create a new branch, make modifications, run precommit checks, stage changes, commit, and push to your fork. Update the CHANGELOG.md accordingly. ```sh git checkout -b # edit files # update changelog make precommit git add -p git commit git push ``` -------------------------------- ### Manage Attribute and Option Allocation with sync.Pool Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Illustrates how to use sync.Pool to minimize allocations for attribute slices and options in measurement calls with dynamic attributes. ```go var ( attrPool = sync.Pool{ New: func() any { // Pre-allocate common capacity knownCap := 8 // Adjust based on expected usage s := make([]attribute.KeyValue, 0, knownCap) // Return a pointer to avoid extra allocation on Put(). return &s }, } addOptPool = &sync.Pool{ New: func() any { const n = 1 // WithAttributeSet o := make([]metric.AddOption, 0, n) // Return a pointer to avoid extra allocation on Put(). return &o }, } ) func (i *instrumentation) record(ctx context.Context, value int64, baseAttrs ...attribute.KeyValue) { attrs := attrPool.Get().(*[]attribute.KeyValue) defer func() { *attrs = (*attrs)[:0] // Reset. attrPool.Put(attrs) }() *attrs = append(*attrs, baseAttrs...) // Add any dynamic attributes. *attrs = append(*attrs, semconv.OTelComponentName("exporter-1")) addOpt := addOptPool.Get().(*[]metric.AddOption) defer func() { *addOpt = (*addOpt)[:0] addOptPool.Put(addOpt) }() set := attribute.NewSet(*attrs...) *addOpt = append(*addOpt, metric.WithAttributeSet(set)) i.counter.Add(ctx, value, *addOpt...) } ``` -------------------------------- ### Get GPG key ID Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/RELEASING.md List secret GPG keys to find the correct key ID for signing artifacts. The ID is the 16-character string following 'sec rsa4096/' or similar. ```terminal gpg --list-secret-keys --keyid-format=long ``` -------------------------------- ### Creating Custom CBOR Encoding Modes Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/fxamacker/cbor/v2/README.md Construct custom CBOR encoding modes by starting with preset options and modifying settings as needed. Once created, these modes are immutable and safe for concurrent use. ```go // Create encoding mode. opts := cbor.CoreDetEncOptions() // use preset options as a starting point opts.Time = cbor.TimeUnix // change any settings if needed em, err := opts.EncMode() // create an immutable encoding mode // Reuse the encoding mode. It is safe for concurrent use. // API matches encoding/json. b, err := em.Marshal(v) // encode v to []byte b encoder := em.NewEncoder(w) // create encoder with io.Writer w err := encoder.Encode(v) // encode v to io.Writer w ``` -------------------------------- ### Retrieve a value using JSON Pointer Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-openapi/jsonpointer/README.md Demonstrates how to create a JSON Pointer and use it to retrieve a value from a document. Handles potential errors during pointer creation and value retrieval. ```go import ( "github.com/go-openapi/jsonpointer" ) var doc any ... pointer, err := jsonpointer.New("/foo/1") if err != nil { ... // error: e.g. invalid JSON pointer specification } value, kind, err := pointer.Get(doc) if err != nil { ... // error: e.g. key not found, index out of bounds, etc. } ... ``` -------------------------------- ### Syscall Entry Points in Assembly Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/golang.org/x/sys/unix/README.md These are the hand-written assembly entry points for system call dispatch in the sys/unix package. They differ in the number of arguments that can be passed to the kernel. ```go func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) ``` -------------------------------- ### Proper Error Handling in Go Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Return errors to the caller when initialization fails, even if partial initialization occurred. Avoid dumping errors to otel.Handle if the caller can manage them. ```go func newInstrumentation() (*instrumentation, error) { if !x.Observability.Enabled() { return nil, nil } m := otel.GetMeterProvider().Meter(/* initialize meter */) counter, err := otelconv.NewSDKComponentCounter(m) // Use the partially initialized counter if available. i := &instrumentation{counter: counter} // Return any error to the caller. return i, err } ``` ```go // ❌ Avoid this pattern. func newInstrumentation() *instrumentation { if !x.Observability.Enabled() { return nil, nil } m := otel.GetMeterProvider().Meter(/* initialize meter */) counter, err := otelconv.NewSDKComponentCounter(m) if err != nil { // ❌ Do not dump the error to the OTel Handler. Return it to the // caller. otel.Handle(err) // ❌ Do not return nil if we can still use the partially initialized // counter. return nil } return &instrumentation{counter: counter} } ``` -------------------------------- ### Example CSI Node Driver Registrar Sidecar Spec Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/README.md A sample sidecar specification for the node-driver-registrar within a driver DaemonSet. This includes volume mounts for CSI and registration directories, and configures an HTTP health check endpoint. ```yaml containers: - name: csi-driver-registrar image: k8s.gcr.io/sig-storage/csi-node-driver-registrar:v2.5.0 args: - "--csi-address=/csi/csi.sock" - "--kubelet-registration-path=/var/lib/kubelet/plugins//csi.sock" - "--health-port=9809" volumeMounts: - name: plugin-dir mountPath: /csi - name: registration-dir mountPath: /registration ports: - containerPort: 9809 name: healthz livenessProbe: httpGet: path: /healthz port: healthz initialDelaySeconds: 5 timeoutSeconds: 5 volumes: - name: registration-dir hostPath: path: /var/lib/kubelet/plugins_registry/ type: Directory - name: plugin-dir hostPath: path: /var/lib/kubelet/plugins// type: DirectoryOrCreate ``` -------------------------------- ### Example: Embedded JSON Tag for CBOR (tag 262) Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/fxamacker/cbor/v2/README.md Shows how to encode and decode a tagged CBOR data item with tag number 262, where the tag content is a JSON object embedded as a CBOR byte string. This implementation includes custom MarshalCBOR and UnmarshalCBOR methods. ```go // https://github.com/fxamacker/cbor/issues/657 package cbor_test // NOTE: RFC 8949 does not mention tag number 262. IANA assigned // CBOR tag number 262 as "Embedded JSON Object" specified by the // document Embedded JSON Tag for CBOR: // // "Tag 262 can be applied to a byte string (major type 2) to indicate // that the byte string is a JSON Object. The length of the byte string // indicates the content." // // For more info, see Embedded JSON Tag for CBOR at: // https://github.com/toravir/CBOR-Tag-Specs/blob/master/embeddedJSON.md import ( "bytes" "encoding/json" "fmt" "github.com/fxamacker/cbor/v2" ) // cborTagNumForEmbeddedJSON is the CBOR tag number 262. const cborTagNumForEmbeddedJSON = 262 // EmbeddedJSON represents a Go value to be encoded as a tagged CBOR data item // with tag number 262 and the tag content is a JSON object "embedded" as a // CBOR byte string (major type 2). type EmbeddedJSON struct { any } func NewEmbeddedJSON(val any) EmbeddedJSON { return EmbeddedJSON{val} } // MarshalCBOR encodes EmbeddedJSON to a tagged CBOR data item with the // tag number 262 and the tag content is a JSON object that is // "embedded" as a CBOR byte string. func (v EmbeddedJSON) MarshalCBOR() ([]byte, error) { // Encode v to JSON object. data, err := json.Marshal(v) if err != nil { return nil, err } // Create cbor.Tag representing a tagged CBOR data item. tag := cbor.Tag{ Number: cborTagNumForEmbeddedJSON, Content: data, } // Marshal to a tagged CBOR data item. return cbor.Marshal(tag) } // UnmarshalCBOR decodes a tagged CBOR data item to EmbeddedJSON. // The byte slice provided to this function must contain a single // tagged CBOR data item with the tag number 262 and tag content // must be a JSON object "embedded" as a CBOR byte string. func (v *EmbeddedJSON) UnmarshalCBOR(b []byte) error { // Unmarshal tagged CBOR data item. var tag cbor.Tag if err := cbor.Unmarshal(b, &tag); err != nil { return err } // Check tag number. if tag.Number != cborTagNumForEmbeddedJSON { return fmt.Errorf("got tag number %d, expect tag number %d", tag.Number, cborTagNumForEmbeddedJSON) } // Check tag content. jsonData, isByteString := tag.Content.([]byte) if !isByteString { return fmt.Errorf("got tag content type %T, expect tag content []byte", tag.Content) } // Unmarshal JSON object. return json.Unmarshal(jsonData, v) } // MarshalJSON encodes EmbeddedJSON to a JSON object. func (v EmbeddedJSON) MarshalJSON() ([]byte, error) { return json.Marshal(v.any) } // UnmarshalJSON decodes a JSON object. func (v *EmbeddedJSON) UnmarshalJSON(b []byte) error { dec := json.NewDecoder(bytes.NewReader(b)) dec.UseNumber() return dec.Decode(&v.any) } func Example_embeddedJSONTagForCBOR() { value := NewEmbeddedJSON(map[string]any{ "name": "gopher", "id": json.Number("42"), }) data, err := cbor.Marshal(value) if err != nil { panic(err) } fmt.Printf("cbor: %x\n", data) var v EmbeddedJSON err = cbor.Unmarshal(data, &v) if err != nil { panic(err) } ``` -------------------------------- ### Run Benchmarks Source: https://github.com/kubernetes-csi/node-driver-registrar/blob/master/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md This command is used to execute benchmarks for the go-openapi/swag project. It specifies the benchmark and run targets. ```bash go test -bench XXX -run XXX -benchtime 30s ```