### Install gziphandler Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/NYTimes/gziphandler/README.md Use go get to install the gziphandler package. ```bash go get -u github.com/NYTimes/gziphandler ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/go.yaml.in/yaml/v3/README.md Use 'go get' to install the package. The import path is go.yaml.in/yaml/v3. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Define a RESTful WebService with Routes Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/emicklei/go-restful/v3/README.md Example of setting up a WebService with a path, supported content types, and defining a GET route for retrieving a user. Includes parameter definition and 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 json-iterator/go Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/json-iterator/go/README.md Use the go get command to install the library. This is the standard method for adding Go packages to your project. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Install etcd/client/v3 Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/go.etcd.io/etcd/client/v3/README.md Install the official Go etcd client using go modules. ```bash go get go.etcd.io/etcd/client/v3 ``` -------------------------------- ### Install Cobra Library Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/spf13/cobra/README.md Install the latest version of the Cobra library using go get. ```go go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Install multierr Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/go.uber.org/multierr/README.md Use go get to install the latest version of the multierr package. ```bash go get -u go.uber.org/multierr@latest ``` -------------------------------- ### Initialize Procfs and Get Stat Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem and retrieves CPU statistics. Use this to get started with basic system metrics. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Install and Run Local Go Doc Site Source: https://github.com/kubernetes-sigs/cluster-capacity/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-sigs/cluster-capacity/blob/master/vendor/github.com/google/uuid/README.md Use 'go get' to install the UUID package. This command fetches and installs the package into your Go workspace. ```sh go get github.com/google/uuid ``` -------------------------------- ### Install yaml.v3 Package Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/gopkg.in/yaml.v3/README.md Use 'go get' to install the yaml.v3 package for use in your Go projects. ```bash go get gopkg.in/yaml.v3 ``` -------------------------------- ### Install Cron V3 Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/robfig/cron/v3/README.md Download the specific tagged release of Cron V3 using go get. ```go go get github.com/robfig/cron/v3@v3.0.0 ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/spf13/cobra/README.md Install the cobra-cli tool for generating Cobra application scaffolding. ```go go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Get opentelemetry-go with go get Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md This command fetches the opentelemetry-go project into your GOPATH. Ignore any build constraint warnings. ```go go get -d go.opentelemetry.io/otel ``` -------------------------------- ### Create Root Logger (Go) Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/go-logr/logr/README.md Initialize the root logger early in an application's lifecycle. This example shows creating a logger using a hypothetical 'logimpl' implementation. ```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 ... } ``` -------------------------------- ### Install gRPC-Go Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/google.golang.org/grpc/README.md Add this import to your Go code to automatically fetch gRPC-Go dependencies during build, run, or test. ```go import "google.golang.org/grpc" ``` -------------------------------- ### Quick Start: Logger Source: https://github.com/kubernetes-sigs/cluster-capacity/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), ) ``` -------------------------------- ### Coexist with glog Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/k8s.io/klog/v2/README.md Example demonstrating how to initialize and synchronize flags between klog and glog. It also shows how to use stderr as a combined output by setting 'alsologtostderr' or 'logtostderr' to true. ```go package main import ( "flag" "os" "k8s.io/klog/v2" ) func main() { // Initialize glog flags // Note: This is a simplified example. In a real scenario, you might need to parse flags more carefully. // For actual coexistence, refer to the examples directory in the klog repository. // Example of setting flags that might be common to both var alsologtostderr = flag.Bool("logtostderr", true, "log to standard error instead of files") flag.Parse() // Initialize klog klog.InitFlags(nil) // If alsologtostderr is true, klog will also log to stderr if *alsologtostderr { klog.SetOutput(os.Stderr) } klog.Info("This is an info message.") klog.Warning("This is a warning message.") klog.Error("This is an error message.") // In a real scenario, you would also need to manage glog's logging behavior. // This example focuses on the klog initialization and output redirection aspect. } ``` -------------------------------- ### Example Test Script Syntax Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Demonstrates the basic format for creating test cases using a shell-like syntax within the testdata directory. This includes commands and expected output. ```shell # Create a new empty file with some data. watch / echo data >/file Output: create /file write /file ``` -------------------------------- ### Demonstrate Cluster Capacity Analysis Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/README.md Example of running cluster capacity analysis with verbose output to show pod requirements and scheduling results. ```sh ./cluster-capacity --podspec=pod.yaml --verbose ``` -------------------------------- ### Platform-Specific Test Example Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Provides an example of how to define platform-specific test cases within the output section of a script. This allows for tests that only apply to certain operating systems. ```shell watch / touch /file Output: # Tested if nothing else matches create /file # Windows-specific test. windows: write /file ``` -------------------------------- ### Quick Start: SugaredLogger Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/go.uber.org/zap/README.md Use SugaredLogger when performance is important but not critical. It supports both structured and printf-style APIs and is 4-10x faster than other structured logging packages. ```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) ``` -------------------------------- ### Rotate Logger Example Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/gopkg.in/natefinch/lumberjack.v2/README.md Example of how to rotate logs in response to SIGHUP. Ensure the logger is set as the output for the log package and a signal channel is set up to catch SIGHUP. A goroutine listens for the signal and calls l.Rotate() when received. ```go l := &lumberjack.Logger{} log.SetOutput(l) c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP) go func() { for { <-c l.Rotate() } }() ``` -------------------------------- ### Example Pod Specification Source: https://context7.com/kubernetes-sigs/cluster-capacity/llms.txt A sample pod specification file used as input for the cluster-capacity tool. Defines resource requests and limits. ```yaml apiVersion: v1 kind: Pod metadata: name: small-pod labels: app: guestbook tier: frontend spec: containers: - name: php-redis image: gcr.io/google-samples/gb-frontend:v4 imagePullPolicy: Always resources: limits: cpu: 150m memory: 100Mi requests: cpu: 150m memory: 100Mi restartPolicy: "OnFailure" dnsPolicy: "Default" terminationGracePeriodSeconds: 5 ``` -------------------------------- ### Add or Update Dependencies Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Use `go get` to fetch specific versions of external packages. Ensure Go modules are enabled and 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 ``` -------------------------------- ### Setup Zap Repository Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/go.uber.org/zap/CONTRIBUTING.md Clone the Zap repository and set up remote upstream for contributing. This involves forking the repository, cloning it to your GOPATH, and configuring the upstream remote. ```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 ``` -------------------------------- ### StartedByExplorer Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/inconshreveable/mousetrap/README.md Checks if the current process was started by double-clicking the executable in Windows Explorer. ```APIDOC ## StartedByExplorer ### Description This function returns true if the process was invoked by double-clicking the executable file while browsing in Windows Explorer. This is useful for providing more helpful behavior to users unfamiliar with command-line tools. ### Signature ```go func StartedByExplorer() (bool) ``` ### Returns - `bool`: `true` if started by Explorer, `false` otherwise. ``` -------------------------------- ### Set up Namespace and Resource Limits for Analysis Source: https://context7.com/kubernetes-sigs/cluster-capacity/llms.txt Commands to create a namespace and define resource limits (LimitRange) for constrained analysis. This setup ensures that capacity estimations reflect namespace-specific quotas. ```sh # Create the namespace and resource limits for constrained analysis kubectl apply -f examples/namespace.yml # creates namespace "cluster-capacity" kubectl apply -f examples/limits.yml # creates LimitRange "hpclimits" ``` -------------------------------- ### Server-side Interceptor Setup Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/README.md Initialize your gRPC server with stream and unary interceptors for Prometheus metrics. Ensure Prometheus metrics are registered after service implementations and the metrics handler is set up. ```go import "github.com/grpc-ecosystem/go-grpc-prometheus" ... // Initialize your gRPC server's interceptor. myServer := grpc.NewServer( grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor), grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor), ) // Register your gRPC service implementations. myservice.RegisterMyServiceServer(s.server, &myServiceImpl{}) // After all your registrations, make sure all of the Prometheus metrics are initialized. grpc_prometheus.Register(myServer) // Register Prometheus metrics handler. http.Handle("/metrics", promhttp.Handler()) ... ``` -------------------------------- ### Build and Run Cluster Capacity Tool Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/README.md Steps to clone the repository, build the framework using make, and run the analysis with a pod specification. ```sh cd $GOPATH/src/sigs.k8s.io git clone https://github.com/kubernetes-sigs/cluster-capacity cd cluster-capacity make build ``` ```sh ./cluster-capacity --podspec=examples/pod.yaml ``` ```sh ./cluster-capacity --help ``` -------------------------------- ### Run Cluster Capacity Analysis Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/doc/cluster-capacity.md This command-line example demonstrates how to run the cluster-capacity analysis tool. It specifies the kubeconfig path, API server address, and the pod specification file to use for the analysis. The --verbose flag provides detailed output. ```sh $ ./cluster-capacity --kubeconfig --master --podspec=examples/pod.yaml --verbose ``` -------------------------------- ### Install JSON-Patch v4 Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/gopkg.in/evanphx/json-patch.v4/README.md Use this command to get version 4 of the json-patch library. ```bash go get -u gopkg.in/evanphx/json-patch.v4 ``` -------------------------------- ### Install Latest JSON-Patch v5 Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/gopkg.in/evanphx/json-patch.v4/README.md Use this command to get the latest version of the json-patch library. ```bash go get -u github.com/evanphx/json-patch/v5 ``` -------------------------------- ### Instantiation with Functional Options Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Demonstrates how to instantiate a type using functional options. Parameters can be declared before the variadic options. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Find the first occurrence of a substring Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/google/cel-go/ext/README.md Use `.indexOf()` to find the starting index of a substring. Returns -1 if not found. An optional starting position can be provided. Returns the starting index if the search string is empty. ```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 ``` -------------------------------- ### Initialize Procfs and Sysfs for Block Devices Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/prometheus/procfs/README.md Initializes both proc and sys filesystems to access block device information. Required when data spans both pseudo-filesystems. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Server Started Counter Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/README.md This counter is incremented immediately after the server receives a call. It tracks the start of an RPC handling process. ```jsoniq grpc_server_started_total{grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1 ``` -------------------------------- ### Even Slice Validator Example Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/k8s.io/apimachinery/pkg/api/validate/README.md Example of a generic validator function that checks if a slice has an even number of items. It can be used with slices of any type. ```go // Even validates that a slice has an even number of items. func Even[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList ``` -------------------------------- ### Basic glog Usage Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/k8s.io/klog/v2/README.md Demonstrates basic Info and Fatalf logging. Use Fatalf for critical errors that should stop execution. ```go glog.Info("Prepare to repel boarders") ``` ```go glog.Fatalf("Initialization failed: %s", err) ``` -------------------------------- ### Example of DPanic usage Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/go.uber.org/zap/FAQ.md Use DPanic to catch errors that should not happen in development but are not critical enough to crash production. This example shows how to replace a panic with DPanic. ```go if err != nil { panic(fmt.Sprintf("shouldn't ever get here: %v", err)) } ``` -------------------------------- ### Example Pod Specification Generated by genpod Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/README.md An example of a pod specification generated by the `genpod` tool, reflecting namespace annotations for node selectors and resource limits. ```yaml apiVersion: v1 kind: Pod metadata: creationTimestamp: null name: cluster-capacity-stub-container namespace: cluster-capacity spec: containers: - image: gcr.io/google_containers/pause:2.0 imagePullPolicy: Always name: cluster-capacity-stub-container resources: limits: cpu: 200m memory: 100Mi requests: cpu: 200m memory: 100Mi dnsPolicy: Default nodeSelector: load: high region: hpc restartPolicy: OnFailure status: {} ``` -------------------------------- ### NonEmpty Validator Example Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/k8s.io/apimachinery/pkg/api/validate/README.md Example of a simple validator function that checks if a string value is not empty. It takes context, operation, field path, and the string value to validate. ```go // NonEmpty validates that a string is not empty. func NonEmpty(ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList ``` -------------------------------- ### Example using TagSet and TagOptions Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/fxamacker/cbor/v2/README.md Shows how to create a `TagSet`, register custom tags with `TagOptions`, and use these tags to create `DecMode` and `EncMode` for handling CBOR data with specific tag numbers. This is useful for custom data types that require specific CBOR tag representations. ```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 } ``` -------------------------------- ### Basic fsnotify Watcher Usage in Go Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/fsnotify/fsnotify/README.md Demonstrates how to create a new watcher, listen for events and errors in a separate goroutine, add a directory to watch, and keep the main goroutine running. ```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{}) } ``` -------------------------------- ### Prometheus Histogram Metrics Example Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/README.md Example of Prometheus histogram metric values for `grpc_server_handling_seconds_bucket`, `grpc_server_handling_seconds_sum`, and `grpc_server_handling_seconds_count`. These metrics provide detailed insights into RPC handling times and counts. ```prometheus grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.005"} 1 grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.01"} 1 grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.025"} 1 grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.05"} 1 grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.1"} 1 grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.25"} 1 grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.5"} 1 grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="1"} 1 grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="2.5"} 1 grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="5"} 1 grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="10"} 1 grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="+Inf"} 1 grpc_server_handling_seconds_sum{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 0.0003866430000000001 grpc_server_handling_seconds_count{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1 ``` -------------------------------- ### KeysMaxLen Map Validator Example Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/k8s.io/apimachinery/pkg/api/validate/README.md Example of a generic validator function that enforces a maximum length for all string keys in a map. It accepts a map of any value type and the maximum allowed key length. ```go // KeysMaxLen validates that all of the string keys in a map are under the // specified length. func KeysMaxLen[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ map[string]T, maxLen int) field.ErrorList ``` -------------------------------- ### Building Boilersuite Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/cert-manager/boilersuite/README.md Build the boilersuite binary using the provided make command. The executable will be available in the `_bin/` directory. ```console make build ``` -------------------------------- ### String Substring Function Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/google/cel-go/ext/README.md Extracts a substring from a string based on character positions. The start index is inclusive, and the end index is exclusive. Errors occur if indices are out of bounds or the end index is less than the start index. ```cel 'tacocat'.substring(4) // returns 'cat' ``` ```cel 'tacocat'.substring(0, 4) // returns 'taco' ``` ```cel 'tacocat'.substring(-1) // error ``` ```cel 'tacocat'.substring(2, 1) // error ``` -------------------------------- ### Benchmarking xxhash Implementations Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/cespare/xxhash/v2/README.md Compares the performance of pure Go and assembly implementations of Sum64 across different input sizes. Run these commands to generate benchmarks. ```bash benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### Get Pod Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/doc/html/api-reference/operations.html Retrieves pod information from the cluster. Supports pretty-printing the output. ```APIDOC ## GET /capacity/pod ### Description Retrieves pod information from the cluster. Supports pretty-printing the output. ### Method GET ### Endpoint /capacity/pod ### Parameters #### Query Parameters - **pretty** (string) - Optional - If true, then the output is pretty printed. ### Responses #### Success Response (200) - **success** (kubernetes v1.pod) - Description of the pod object. ### Response Example { "example": "{\"apiVersion\": \"v1\", \"kind\": \"Pod\", ...}" } ``` -------------------------------- ### Configuring Overlapping Options with Interfaces Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Illustrates how to handle overlapping configurations for 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 {…} ``` -------------------------------- ### Lists.Slice Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/google/cel-go/ext/README.md Returns a new sub-list using the provided start and end indexes. Introduced in version 0. ```APIDOC ## Slice ### Description Returns a new sub-list using the indexes provided. ### Signature ``` .slice(, ) -> ``` ### Examples ``` [1,2,3,4].slice(1, 3) // return [2, 3] [1,2,3,4].slice(2, 4) // return [3, 4] ``` ``` -------------------------------- ### Generate Integer Range Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/google/cel-go/ext/README.md The lists.range() function generates a list of integers starting from 0 up to (but not including) the specified integer. ```cel lists.range(5) -> [0, 1, 2, 3, 4] ``` -------------------------------- ### Create Branch, Commit, and Push Changes Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Follow these steps to create a new branch, make modifications, run precommit checks, stage changes, commit, and push to your fork. ```sh git checkout -b # edit files # update changelog make precommit git add -p git commit git push ``` -------------------------------- ### Nested Cel.Bind Example Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/google/cel-go/ext/README.md Demonstrates how to use nested cel.bind to define and use local variables in a CEL expression. ```cel cel.bind(a, 'hello', cel.bind(b, 'world', a + b + b + a)) // "helloworldworldhello" ``` -------------------------------- ### Snapshot live cluster state with SyncWithClient Source: https://context7.com/kubernetes-sigs/cluster-capacity/llms.txt Copies cluster resources into the simulator's fake client. Must be called before `Run()`. Nodes listed in `excludeNodes` are skipped. ```go import ( "k8s.io/client-go/tools/clientcmd" clientset "k8s.io/client-go/kubernetes" ) // Build a real client from kubeconfig cfg, err := clientcmd.BuildConfigFromFlags("", "/home/user/.kube/config") if err != nil { panic(err) } kubeClient, err := clientset.NewForConfig(cfg) if err != nil { panic(err) } // Snapshot the live cluster into the simulator if err := cc.SyncWithClient(kubeClient); err != nil { panic(err) // e.g. "unable to list nodes: ..." } ``` -------------------------------- ### Strings.IndexOf Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/google/cel-go/ext/README.md Finds the first occurrence of a substring within a string, optionally starting from a specified index. Returns -1 if not found. ```APIDOC ## Strings.IndexOf ### Description Returns the integer index of the first occurrence of the search string. If the search string is not found the function returns -1. The function also accepts an optional position from which to begin the substring search. If the substring is the empty string, the index where the search starts is returned (zero or custom). ### Signatures `.indexOf() -> ` `.indexOf(, ) -> ` ### Examples ``` '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 ``` ``` -------------------------------- ### Basic Usage of gziphandler Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/NYTimes/gziphandler/README.md Wrap an existing http.Handler with gziphandler.GzipHandler to enable transparent gzip compression for responses. This example demonstrates setting up a simple HTTP server that serves plain text and compresses responses. ```go package main import ( io "net/http" "github.com/NYTimes/gziphandler" ) func main() { withoutGz := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") io.WriteString(w, "Hello, World") }) withGz := gziphandler.GzipHandler(withoutGz) http.Handle("/", withGz) http.ListenAndServe("0.0.0.0:8000", nil) } ``` -------------------------------- ### Script Comments Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Illustrates how to include comments in the test script. Comments start with '#' and can appear on their own line or at the end of a command line. ```shell # Comment cmd arg arg # Comment ``` -------------------------------- ### ClusterCapacity.Run Source: https://context7.com/kubernetes-sigs/cluster-capacity/llms.txt Starts the embedded scheduler goroutines and drives the simulation loop. This method blocks until the simulation terminates. It must be called after `SyncWithClient`. ```APIDOC ## ClusterCapacity.Run — Execute the scheduling simulation ### Description Starts the embedded scheduler goroutines and drives the simulation loop: creates one pod at a time, waits for the scheduler to bind or reject it, then creates the next. The method blocks until the simulation terminates (no more resources, `maxPods` reached, or unschedulable condition). Must be called after `SyncWithClient`. ### Method ```go if err := cc.Run(); err != nil { // e.g. "Unable to create next pod to schedule: ..." panic(err) } // Simulation complete — retrieve results report := cc.Report() fmt.Printf("Schedulable replicas: %d\n", report.Status.Replicas) // Output: Schedulable replicas: 52 ``` ``` -------------------------------- ### Get Status Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/doc/html/api-reference/operations.html Retrieves the status of cluster operations. Supports filtering by number of records, watching for new statuses, and time ranges. ```APIDOC ## GET /capacity/status ### Description Retrieves the status of cluster operations. Supports filtering by number of records, watching for new statuses, and time ranges. ### Method GET ### Endpoint /capacity/status ### Parameters #### Query Parameters - **num** (number) - Optional - Number of records to be shown. If not set, all records are listed. - **watch** (boolean) - Optional - Watch for new statuses. - **since** (time) - Optional - Time in RFC 3339 form. Do not list records acquired before this time. Defaults to 1970-01-01T00:00:00+00:00. - **to** (time) - Optional - Time in RFC 3339 form. Do not list records acquired after this time. Defaults to time.now. ### Responses #### Success Response (200) - **success** (Report array) - An array of report objects. ### Response Example { "example": "[ { \"report_field\": \"value\" }, ... ]" } ``` -------------------------------- ### Custom Mode Creation Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/fxamacker/cbor/v2/README.md Demonstrates how to create custom encoding modes by starting with preset options, modifying settings, and then creating an immutable `EncMode`. ```APIDOC ## Custom Mode Creation ### Description Custom encoding modes are created from `EncOptions`. Once created, these modes have immutable settings and are safe for concurrent use. It is recommended to create modes at startup and reuse them. ### Steps 1. **Obtain Preset Options**: Start with a preset like `cbor.CoreDetEncOptions()`. 2. **Modify Settings**: Adjust any desired settings on the `EncOptions` struct (e.g., `opts.Time = cbor.TimeUnix`). 3. **Create Encoding Mode**: Call `opts.EncMode()` to create an immutable `EncMode`. ### Usage Once an `EncMode` (`em`) is created: - **Marshal(v interface{}) ([]byte, error)**: Encodes `v` to a CBOR byte slice `b`. - **NewEncoder(w io.Writer) *Encoder**: Creates an encoder that writes to `io.Writer` `w`. - **Encoder.Encode(v interface{}) error**: Encodes `v` to the `io.Writer`. Default mode and custom modes automatically apply struct tags. ``` -------------------------------- ### Create cluster capacity simulator with New Source: https://context7.com/kubernetes-sigs/cluster-capacity/llms.txt Constructs a new ClusterCapacity instance with a fake Kubernetes client and scheduler. Set `maxPods` to 0 for unlimited simulation or provide a slice of node names to `excludeNodes`. ```go import ( "sigs.k8s.io/cluster-capacity/pkg/framework" "sigs.k8s.io/cluster-capacity/pkg/utils" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func main() { // Build default scheduler config (uses ClusterCapacityBinder plugin) kubeSchedulerConfig, err := utils.BuildKubeSchedulerCompletedConfig(nil) if err != nil { panic(err) } // Define the pod to simulate grace := int64(30) simulatedPod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "my-workload", Namespace: "default", }, Spec: v1.PodSpec{ RestartPolicy: v1.RestartPolicyAlways, DNSPolicy: v1.DNSClusterFirst, TerminationGracePeriodSeconds: &grace, SecurityContext: &v1.PodSecurityContext{}, Containers: []v1.Container{ { Name: "app", Image: "nginx:latest", Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("150m"), v1.ResourceMemory: resource.MustParse("100Mi"), }, Limits: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("150m"), v1.ResourceMemory: resource.MustParse("100Mi"), }, }, }, }, }, } // maxPods=0 means run until resources are exhausted; excludeNodes=nil means use all nodes cc, err := framework.New(kubeSchedulerConfig, nil, simulatedPod, 0, nil) if err != nil { panic(err) } defer cc.Close() } ``` -------------------------------- ### Create and Apply JSON Patch Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/gopkg.in/evanphx/json-patch.v4/README.md Demonstrates creating a patch from operations and applying it to a JSON document. Ensure the patch operations are valid and the target document is well-formed JSON. ```go package main import ( "fmt" jsonpatch "github.com/evanphx/json-patch" ) func main() { original := []byte(`{"name": "John", "age": 24, "height": 3.21}`) patchJSON := []byte(`[ {"op": "replace", "path": "/name", "value": "Jane"}, {"op": "remove", "path": "/height"} ]`) patch, err := jsonpatch.DecodePatch(patchJSON) if err != nil { panic(err) } modified, err := patch.Apply(original) if err != nil { panic(err) } fmt.Printf("Original document: %s\n", original) fmt.Printf("Modified document: %s\n", modified) } ``` ```bash $ go run main.go Original document: {"name": "John", "age": 24, "height": 3.21} Modified document: {"age":24,"name":"Jane"} ``` -------------------------------- ### Create and Apply a Merge Patch Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/gopkg.in/evanphx/json-patch.v4/README.md Demonstrates creating a JSON merge patch from two documents and then applying it to a third document. Ensure the 'jsonpatch' package is imported. ```go package main import ( "fmt" jsonpatch "github.com/evanphx/json-patch" ) func main() { // Let's create a merge patch from these two documents... original := []byte(`{"name": "John", "age": 24, "height": 3.21}`) target := []byte(`{"name": "Jane", "age": 24}`) patch, err := jsonpatch.CreateMergePatch(original, target) if err != nil { panic(err) } // Now lets apply the patch against a different JSON document... alternative := []byte(`{"name": "Tina", "age": 28, "height": 3.75}`) modifiedAlternative, err := jsonpatch.MergePatch(alternative, patch) fmt.Printf("patch document: %s\n", patch) fmt.Printf("updated alternative doc: %s\n", modifiedAlternative) } ``` -------------------------------- ### Extract Sub-list with Slice Source: https://github.com/kubernetes-sigs/cluster-capacity/blob/master/vendor/github.com/google/cel-go/ext/README.md The slice() method returns a new list containing elements from a specified start index up to (but not including) a specified end index. ```cel [1,2,3,4].slice(1, 3) // return [2, 3] ``` ```cel [1,2,3,4].slice(2, 4) // return [3, 4] ```