### Install Cobra Library Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/spf13/cobra/README.md Use 'go get' to install the latest version of the Cobra library. ```go go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Install etcd/clientv3 Go Package Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/go.etcd.io/etcd/client/v3/README.md Use 'go get' to install the etcd/clientv3 package. For pre-release versions, specify the version tag. ```bash go get go.etcd.io/etcd/client/v3 ``` ```bash go get go.etcd.io/etcd/client/v3@v3.5.0-pre ``` -------------------------------- ### Install gziphandler Package Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/NYTimes/gziphandler/README.md Use this command to install the gziphandler package using go get. ```bash go get -u github.com/NYTimes/gziphandler ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/json-iterator/go/README.md Install the json-iterator/go library using the go get command. ```go go get github.com/json-iterator/go ``` -------------------------------- ### Define a WebService with Routes Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/emicklei/go-restful/v3/README.md Example of defining a WebService, setting its path and supported MIME types, and adding a GET route for retrieving a user. The route specifies parameters, documentation, and the expected response type. ```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 go-autorest Libraries Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/Azure/go-autorest/README.md Provides the go get commands to install the core go-autorest libraries and its subpackages. ```bash go get github.com/Azure/go-autorest/autorest go get github.com/Azure/go-autorest/autorest/azure go get github.com/Azure/go-autorest/autorest/date go get github.com/Azure/go-autorest/autorest/to ``` -------------------------------- ### Install and Run Local Go Doc Site Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Installs and runs a local Go Doc site for viewing package documentation. Ensure you have the latest version of pkgsite installed. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Install go-autorest/autorest/adal Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/Azure/go-autorest/autorest/adal/README.md Install the adal package using go get. This command ensures you have the latest version of the package. ```bash go get -u github.com/Azure/go-autorest/autorest/adal ``` -------------------------------- ### Install YAML Package for Go Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/gopkg.in/yaml.v3/README.md Use 'go get' to install the YAML package. This command fetches and installs the specified package, making it available for use in your Go projects. ```bash go get gopkg.in/yaml.v3 ``` -------------------------------- ### Install godbus/dbus Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/godbus/dbus/v5/README.md Install the godbus/dbus library using the go get command. Requires Go 1.12 or later. ```go go get github.com/godbus/dbus/v5 ``` -------------------------------- ### Install govalidator Package Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/asaskevich/govalidator/README.md Use 'go get' to install the govalidator package. You can install the latest release or a specific version using gopkg.in. ```bash go get github.com/asaskevich/govalidator ``` ```bash go get gopkg.in/asaskevich/govalidator.v4 ``` -------------------------------- ### Install SMB CSI driver locally Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/docs/install-csi-driver-v1.20.1.md Installs the SMB CSI driver by cloning the repository, checking out a specific version, and running the local installation script. This method is useful for development or when direct internet access is limited. ```bash git clone https://github.com/kubernetes-csi/csi-driver-smb.git cd csi-driver-smb git checkout v1.20.1 ./deploy/install-driver.sh v1.20.1 local ``` -------------------------------- ### Install Ginkgo Locally Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Install the Ginkgo binary locally to run tests and other commands. This is a prerequisite for running tests. ```bash go install ./... ``` -------------------------------- ### Go float16 Usage Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/x448/float16/README.md Demonstrates converting between float32 and float16, and conditionally converting based on precision. Ensure the package is installed using 'go get'. ```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 jsontoml CLI Tool Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/pelletier/go-toml/v2/README.md Installs the jsontoml command-line tool using go install. Use this tool to convert JSON files to TOML. ```bash $ go install github.com/pelletier/go-toml/v2/cmd/jsontoml@latest $ jsontoml --help ``` -------------------------------- ### NewConfig Function Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Provides an example of an unexported `newConfig` function that initializes a configuration struct with default values and applies provided options. It also includes a placeholder for 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 } ``` -------------------------------- ### Install uuid Package Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/google/uuid/README.md Use this command to install the uuid package. Ensure you have Go installed and configured. ```sh go get github.com/google/uuid ``` -------------------------------- ### Install tomljson CLI Tool Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/pelletier/go-toml/v2/README.md Installs the tomljson command-line tool using go install. Use this tool to convert TOML files to JSON. ```bash $ go install github.com/pelletier/go-toml/v2/cmd/tomljson@latest $ tomljson --help ``` -------------------------------- ### Install CSI Driver SMB with Custom Values Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/charts/README.md Install the CSI Driver SMB chart using Helm, specifying a custom values file to override default configurations. Use the `--wait -v=5 --debug` flags for detailed installation logs and troubleshooting. ```bash helm install csi-driver-smb csi-driver-smb/csi-driver-smb --namespace kube-system -f custom-values.yaml ``` -------------------------------- ### Install tomll CLI Tool Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/pelletier/go-toml/v2/README.md Installs the tomll command-line tool using go install. Use this tool to lint and reformat TOML files. ```bash $ go install github.com/pelletier/go-toml/v2/cmd/tomll@latest $ tomll --help ``` -------------------------------- ### Install and Configure CSI-Proxy on Windows Node Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/docs/csi-debug.md Steps to download, extract, and install the CSI-proxy as a Windows service. Includes configuration for logging and failure recovery. ```powershell > cd c:\k Invoke-WebRequest https://acs-mirror.azureedge.net/csi-proxy/v1.0.2/binaries/csi-proxy-v1.0.2.tar.gz -OutFile csi-proxy.tar.gz; tar -xvf csi-proxy.tar.gz copy .\bin\csi-proxy.exe . sc.exe create csiproxy binPath= "c:\k\csi-proxy.exe -windows-service -log_file=c:\k\csi-proxy.log -logtostderr=false --v=5" sc.exe failure csiproxy reset= 0 actions= restart/10000 sc.exe start csiproxy ``` -------------------------------- ### Install SMB CSI driver remotely Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/docs/install-csi-driver-v1.20.1.md Installs the SMB CSI driver by downloading and executing an installation script from a remote URL. Specify the driver version as an argument. ```bash curl -skSL https://raw.githubusercontent.com/kubernetes-csi/csi-driver-smb/v1.20.1/deploy/install-driver.sh | bash -s v1.20.1 -- ``` -------------------------------- ### Install csc Tool Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/docs/csi-dev.md Install the `csc` tool for testing CSI drivers locally. Follow the instructions in the gocsi repository. ```console $ mkdir -p $GOPATH/src/github.com $ cd $GOPATH/src/github.com $ git clone https://github.com/rexray/gocsi.git $ cd rexray/gocsi/csc $ make build ``` -------------------------------- ### Basic fsnotify Usage Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/fsnotify/fsnotify/README.md This example demonstrates how to create a new watcher, listen for events and errors in a separate goroutine, and add a directory to watch. It's crucial to handle both watcher.Events and watcher.Errors channels to ensure proper operation. The watcher should be closed when no longer needed. ```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{}) } ``` -------------------------------- ### Setup Zap Repository Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/go.uber.org/zap/CONTRIBUTING.md Clone the zap repository and set up 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 ``` -------------------------------- ### Install Specific golangci-lint Version Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/pelletier/go-toml/v2/AGENTS.md Install a specific version of golangci-lint using the official installation script. Ensure the version matches the one used in the project's CI configuration. ```bash # Install specific version (check lint.yml for current version) curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/HEAD/install.sh | sh -s -- -b $(go env GOPATH)/bin ``` -------------------------------- ### Commented TOML Configuration Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/pelletier/go-toml/v2/README.md Demonstrates how go-toml can generate TOML files that include comments and commented-out values, useful for configuration files. This example shows inline comments and section comments. ```toml # Host IP to connect to. host = '127.0.0.1' # Port of the remote server. port = 4242 # Encryption parameters (optional) # [TLS] # cipher = 'AEAD-AES128-GCM-SHA256' # version = 'TLS 1.3' ``` -------------------------------- ### Start CSI Driver Locally Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/docs/csi-dev.md Start the SMB CSI driver locally for testing. Ensure the endpoint and node ID are correctly configured. ```console $ cd $GOPATH/src/github.com/kubernetes-csi/csi-driver-smb $ ./_output/amd64/smbplugin --endpoint tcp://127.0.0.1:10000 --nodeid CSINode -v=5 & ``` -------------------------------- ### Install CSI-Proxy on Windows Node Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/deploy/example/windows/README.md Apply the CSI-Proxy daemonset to install it on Kubernetes 1.23+ Windows nodes. This is required if `windows.useHostProcessContainers` is set to `false`. ```bash kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/csi-driver-smb/master/deploy/example/windows/csi-proxy.yaml ``` -------------------------------- ### Explicit Instrumentation Setup in Go Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Encapsulates observability setup within constructor functions for clear ownership and scope. Avoids global or implicit side effects during 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 } ``` -------------------------------- ### Install gRPC-Go Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/google.golang.org/grpc/README.md Add this import to your Go code to automatically fetch gRPC-Go dependencies during build or run. ```go import "google.golang.org/grpc" ``` -------------------------------- ### Install jwt-go Package Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/golang-jwt/jwt/v4/README.md Use this command to add jwt-go as a dependency in your Go program. ```sh go get -u github.com/golang-jwt/jwt/v4 ``` -------------------------------- ### Create a Windows Deployment with PVC Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/deploy/example/windows/README.md Apply the example statefulset configuration to create a Windows deployment that utilizes a PVC for SMB volume mounting. ```bash kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/csi-driver-smb/master/deploy/example/windows/statefulset.yaml ``` -------------------------------- ### ZFS Filesystem Operations in Go Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/mistifyio/go-zfs/README.md Demonstrates creating a ZFS filesystem, taking a snapshot, cloning it, and then destroying all created entities. Assumes a ZFS pool named 'test' exists. Error handling is omitted for brevity. ```go //assuming a zpool named test //error handling omitted f, err := zfs.CreateFilesystem("test/snapshot-test", nil) ok(t, err) s, err := f.Snapshot("test", nil) ok(t, err) // snapshot is named "test/snapshot-test@test" c, err := s.Clone("test/clone-test", nil) err := c.Destroy() err := s.Destroy() err := f.Destroy() ``` -------------------------------- ### Create Source PVC and Related Resources Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/deploy/example/cloning/README.md Apply the necessary StorageClass, source PVC, and a sample pod to set up the environment for cloning. Ensure the CSI driver for SMB is installed. ```console kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/csi-driver-smb/master/deploy/example/storageclass-smb.yaml kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/csi-driver-smb/master/deploy/example/pvc-smb.yaml kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/csi-driver-smb/master/deploy/example/nginx-pod-smb.yaml ``` -------------------------------- ### HTTP Request Pipeline Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/Azure/go-autorest/README.md Demonstrates the typical pattern for sending and responding to HTTP requests using Prepare, Send, and Respond phases with decorators. ```go req, err := Prepare(&http.Request{}, \ token.WithAuthorization()) resp, err := Send(req, \ WithLogging(logger), \ DoErrorIfStatusCode(http.StatusInternalServerError), \ DoCloseIfError(), \ DoRetryForAttempts(5, time.Second)) err = Respond(resp, \ ByDiscardingBody(), ByClosing()) ``` -------------------------------- ### URL Path Construction with Preparers Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/Azure/go-autorest/README.md Illustrates how multiple WithPath decorators in the Prepare phase can sequentially build a URL path. ```go req, err := Prepare(&http.Request{}, \ WithBaseURL("https://microsoft.com/"), \ WithPath("a"), \ WithPath("b"), \ WithPath("c")) ``` -------------------------------- ### Example using TagSet and TagOptions Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/fxamacker/cbor/v2/README.md Shows how to create a TagSet, register custom tags with specific encoding and decoding requirements, and use it to create decoding and encoding modes for custom types. ```go // Use signedCWT struct defined in "Decoding CWT" example. // Create TagSet (safe for concurrency). tags := cbor.NewTagSet() // Register tag COSE_Sign1 18 with signedCWT type. tags.Add( cbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired}, reflect.TypeOf(signedCWT{}), 18) // Create DecMode with immutable tags. dm, _ := cbor.DecOptions{}.DecModeWithTags(tags) // Unmarshal to signedCWT with tag support. var v signedCWT if err := dm.Unmarshal(data, &v); err != nil { return err } // Create EncMode with immutable tags. em, _ := cbor.EncOptions{}.EncModeWithTags(tags) // Marshal signedCWT with tag number. if data, err := cbor.Marshal(v); err != nil { return err } ``` -------------------------------- ### SpdyStream Client Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/moby/spdystream/README.md Connects to a mirroring server without authentication, creates a stream, writes data, reads data, and closes the stream. ```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() } ``` -------------------------------- ### Get Stable json-patch Version 4 Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/gopkg.in/evanphx/json-patch.v4/README.md Installs the stable v4 release of the json-patch library. ```bash go get -u gopkg.in/evanphx/json-patch.v4 ``` -------------------------------- ### Get Stable json-patch Version 5 Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/gopkg.in/evanphx/json-patch.v4/README.md Installs the stable v5 release of the json-patch library. ```bash go get -u gopkg.in/evanphx/json-patch.v5 ``` -------------------------------- ### Get Latest json-patch Version 5 Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/gopkg.in/evanphx/json-patch.v4/README.md Installs the latest version of the json-patch library (v5). ```bash go get -u github.com/evanphx/json-patch/v5 ``` -------------------------------- ### Incorrect Go Module Dependency Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/antlr4-go/antlr/v4/README.md This example shows how `go get` can resolve the ANTLR4 Go runtime with an unclear version tag when retrieved from the deeply nested main ANTLR4 repository. ```go require ( github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230219212500-1f9a474cc2dc ) ``` -------------------------------- ### Preview Ginkgo Documentation Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Build and serve the Ginkgo documentation locally to preview changes. Requires Jekyll and Bundler. ```bash bundle && bundle exec jekyll serve ``` -------------------------------- ### Initialize Block Device Filesystem Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/prometheus/procfs/README.md Initialize both proc and sys filesystems to gather block device statistics. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Create etcd Client with Configuration Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/go.etcd.io/etcd/client/v3/README.md Initialize a new etcd client using clientv3.New with a configuration struct. Ensure the client is closed after use to prevent resource leaks. ```go cli, err := clientv3.New(clientv3.Config{ Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, DialTimeout: 5 * time.Second, }) if err != nil { // handle error! } deferr cli.Close() ``` -------------------------------- ### SpdyStream Server Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/moby/spdystream/README.md Listens for incoming TCP connections, accepts them, and serves them using MirrorStreamHandler without authentication. ```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) } } ``` -------------------------------- ### Initialize and Use Framework in Ginkgo Tests Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/k8s.io/kubernetes/test/e2e/framework/README.md Demonstrates how to initialize a `Framework` instance using `NewDefaultFramework` and utilize its `ClientSet` within `AfterEach` and `It` callbacks in a Ginkgo test. The `Framework` instance is automatically cleaned up after the test completes. ```go f := framework.NewDefaultFramework("some tests") ginkgo.AfterEach(func() { # Do something with f.ClientSet. }) ginkgo.It("test something", func(ctx context.Context) { # The actual test. }) ``` -------------------------------- ### Add Helm repository and install CSI driver Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/charts/README.md Adds the CSI SMB driver Helm repository and installs the driver in the kube-system namespace. Ensure you have Helm 3 installed and meet the prerequisites. ```console helm repo add csi-driver-smb https://raw.githubusercontent.com/kubernetes-csi/csi-driver-smb/master/charts helm install csi-driver-smb csi-driver-smb/csi-driver-smb --namespace kube-system --version 1.20.1 ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/spf13/cobra/README.md Install the cobra-cli tool to bootstrap your Cobra application scaffolding. ```go go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Instantiation with Options Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Demonstrates how to instantiate a type `T` using a variadic `Option` parameter. Any required parameters can be declared before the options. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Run Go Benchmarks Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/pelletier/go-toml/v2/AGENTS.md Execute all benchmarks in the project to verify performance. Running with -count=10 helps ensure more stable results. ```bash go test ./... -bench=. -count=10 ``` -------------------------------- ### Text Log Output Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/sirupsen/logrus/README.md Example of a log entry with caller information formatted as text. ```text time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin ``` -------------------------------- ### JSON Log Output Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/sirupsen/logrus/README.md Example of a log entry with caller information formatted as JSON. ```json {"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by", "time":"2014-03-10 19:57:38.562543129 -0400 EDT"} ``` -------------------------------- ### Logfmt Formatter Output Example (No TTY) Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/sirupsen/logrus/README.md This example shows the output of the default TextFormatter when a TTY is not attached, which is compatible with the logfmt format. ```text time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true ``` -------------------------------- ### Run golangci-lint locally Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/Microsoft/go-winio/README.md Install and run golangci-lint from the repository root to check for linting errors in Go packages. Use flags to control the number of issues displayed. ```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 ./... ``` -------------------------------- ### Rotate Log on SIGHUP Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/gopkg.in/natefinch/lumberjack.v2/README.md Example of how to rotate logs in response to a SIGHUP signal. Ensure the logger is set as the output for the log package. ```go l := &lumberjack.Logger{} log.SetOutput(l) c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP) gO func() { for { <-c l.Rotate() } }() ``` -------------------------------- ### Initialize Procfs Filesystem Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/prometheus/procfs/README.md Initialize the proc filesystem mount point to retrieve CPU statistics. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Get OpenTelemetry Go Repository Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use 'go get' to download the OpenTelemetry Go source code. Ignore any build constraint warnings. ```sh go get -d go.opentelemetry.io/otel ``` -------------------------------- ### Coexist with glog Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/k8s.io/klog/v2/README.md Example demonstrating how to initialize and synchronize flags with glog from the global flag.CommandLine FlagSet. It also configures stderr as the combined output. ```go package main import ( "flag" "os" "testing" "time" "k8s.io/klog/v2" ) func TestCoexistGlog(t *testing.T) { // Initialize klog flags klog.InitFlags(nil) // Set glog flags flag.Set("logtostderr", "true") // Or alsologtostderr // Ensure flags are parsed flag.Parse() // Use klog and glog klog.Info("This is a klog message") // glog.Info("This is a glog message") // Assuming glog is also imported and used // Allow time for logs to be written (if asynchronous) time.Sleep(1 * time.Second) // Example assertions or checks can be added here // For instance, checking if logs were written to stderr // This would typically involve redirecting os.Stderr during the test } ``` -------------------------------- ### JSON Formatter Output Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/sirupsen/logrus/README.md This is an example of the output generated by the JSON formatter, suitable for parsing by log aggregation systems like Logstash or Splunk. ```text {"animal":"walrus","level":"info","msg":"A group of walrus emerges from the ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} {"level":"warning","msg":"The group's number increased tremendously!", "number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} {"animal":"walrus","level":"info","msg":"A giant walrus appears!", "size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} {"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", "size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} {"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, "time":"2014-03-10 19:57:38.562543128 -0400 EDT"} ``` -------------------------------- ### Development Panic Logging Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/go.uber.org/zap/FAQ.md Use DPanic to catch errors that should not occur in development but should not crash production. This example shows how to replace a panic with a DPanic log. ```go if err != nil { panic(fmt.Sprintf("shouldn't ever get here: %v", err)) } ``` -------------------------------- ### String Index of Substring Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/google/cel-go/ext/README.md Finds the first occurrence of a substring, optionally starting from a specified position. Returns -1 if not found. An empty substring returns the starting index. ```cel 'hello mellow'.indexOf('') // returns 0 'hello mellow'.indexOf('ello') // returns 1 'hello mellow'.indexOf('jello') // returns -1 'hello mellow'.indexOf('', 2) // returns 2 'hello mellow'.indexOf('ello', 2) // returns 7 'hello mellow'.indexOf('ello', 20) // returns -1 'hello mellow'.indexOf('ello', -1) // error ``` -------------------------------- ### Extract Sub-list using Slice Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/google/cel-go/ext/README.md The `slice(start, end)` method returns a new list containing elements from the start index (inclusive) to the end index (exclusive). ```cel [1,2,3,4].slice(1, 3) // return [2, 3] ``` ```cel [1,2,3,4].slice(2, 4) // return [3, 4] ``` -------------------------------- ### Import Statement Migration Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/sigs.k8s.io/yaml/goyaml.v2/README.md Shows the specific changes needed in import statements for migrating from sigs.k8s.io/yaml/goyaml.v2 to go.yaml.in/yaml/v2. ```go // From import "sigs.k8s.io/yaml/goyaml.v2" // To import "go.yaml.in/yaml/v2" ``` -------------------------------- ### Ginkgo Spec Example Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/vendor/github.com/onsi/ginkgo/v2/README.md Illustrates a typical Ginkgo spec structure with Describe, BeforeEach, When, Context, It, and assertions using Gomega's Expect. Includes SpecContext and SpecTimeout for managing test execution. ```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)) }) }) ``` -------------------------------- ### SMB Volume Mount Details Source: https://github.com/kubernetes-csi/csi-driver-smb/blob/master/deploy/example/e2e_usage.md Example output of the `df -h` command, showing the SMB share mounted at `/mnt/smb` within the container. ```text Filesystem Size Used Avail Use% Mounted on ... //smb-server.default.svc.cluster.local/share 124G 23G 102G 19% /mnt/smb /dev/sda1 124G 15G 110G 12% /etc/hosts ... ```