### Install automemlimit Go Package Source: https://github.com/kimmachinegun/automemlimit/blob/main/README.md This command installs the latest version of the automemlimit Go package using the go get command. It's the standard way to add external dependencies to a Go project. ```shell go get github.com/KimMachineGun/automemlimit@latest ``` -------------------------------- ### ApplyRatio Provider: Apply Multiplier to Memory Limit Source: https://context7.com/kimmachinegun/automemlimit/llms.txt Wraps a memory limit provider to apply a ratio multiplier to the returned memory limit. The ratio must be in the range (0.0, 1.0]. This is useful for setting a memory limit that is a fraction of the available limit, for example, 75% of the cgroup limit. ```go package main import ( "log" "github.com/KimMachineGun/automemlimit/memlimit" ) func init() { // Create a provider that returns 75% of cgroup limit provider := memlimit.ApplyRatio(memlimit.FromCgroup, 0.75) limit, err := provider() if err != nil { log.Printf("failed to get limit: %v", err) return } log.Printf("75%% of cgroup limit: %d bytes", limit) } func main() {} ``` -------------------------------- ### Custom Provider Implementation: Define Custom Memory Limit Sources Source: https://context7.com/kimmachinegun/automemlimit/llms.txt Allows the creation of custom memory limit providers for specialized sources. Providers must return the memory limit in uint64 bytes and an error. Use `memlimit.ErrNoLimit` when no limit is set. An example shows reading the limit from a file. ```go package main import ( "bytes" "errors" "log/slog" "os" "strconv" "time" "github.com/KimMachineGun/automemlimit/memlimit" ) // FileProvider reads memory limit from a file (useful for custom orchestrators) func FileProvider(path string) memlimit.Provider { return func() (uint64, error) { b, err := os.ReadFile(path) if err != nil { if errors.Is(err, os.ErrNotExist) { // Fall back to cgroup/system when file doesn't exist return memlimit.ApplyFallback(memlimit.FromCgroup, memlimit.FromSystem)() } return 0, err } b = bytes.TrimSpace(b) if len(b) == 0 { return 0, memlimit.ErrNoLimit } return strconv.ParseUint(string(b), 10, 64) } } func init() { memlimit.SetGoMemLimitWithOpts( memlimit.WithProvider(FileProvider("limit.txt")), memlimit.WithRefreshInterval(5*time.Second), memlimit.WithLogger(slog.Default()), ) } func main() {} ``` -------------------------------- ### Automemlimit Advanced Configuration Options Source: https://github.com/kimmachinegun/automemlimit/blob/main/README.md This Go code showcases various advanced configuration options for the automemlimit package within an init function. It demonstrates setting GOMEMLIMIT with specific ratios, choosing memory limit providers (cgroup, system, or a fallback), configuring logging, setting refresh intervals, and directly specifying limits or providers. ```go package main import "github.com/KimMachineGun/automemlimit/memlimit" func init() { memlimit.SetGoMemLimitWithOpts( memlimit.WithRatio(0.9), memlimit.WithProvider(memlimit.FromCgroup), memlimit.WithLogger(slog.Default()), memlimit.WithRefreshInterval(1*time.Minute), ) memlimit.SetGoMemLimitWithOpts( memlimit.WithRatio(0.9), memlimit.WithProvider( memlimit.ApplyFallback( memlimit.FromCgroup, memlimit.FromSystem, ), ), memlimit.WithRefreshInterval(1*time.Minute), ) memlimit.SetGoMemLimit(0.9) memlimit.SetGoMemLimitWithProvider(memlimit.Limit(1024*1024), 0.9) memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroup, 0.9) memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroupV1, 0.9) memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroupHybrid, 0.9) memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroupV2, 0.9) } ``` -------------------------------- ### Configure GOMEMLIMIT via Blank Import Source: https://context7.com/kimmachinegun/automemlimit/llms.txt The simplest implementation using a blank import to automatically configure GOMEMLIMIT at package initialization. It defaults to 90% of the detected cgroup memory limit. ```go package main import ( // Automatically sets GOMEMLIMIT to 90% of cgroup's memory limit _ "github.com/KimMachineGun/automemlimit" ) func main() { // Your application code // GOMEMLIMIT is already configured } ``` -------------------------------- ### Configure GOMEMLIMIT with Functional Options Source: https://context7.com/kimmachinegun/automemlimit/llms.txt Uses SetGoMemLimitWithOpts for granular control over memory ratio, provider selection, logging, and refresh intervals. This is the recommended approach for production applications requiring custom behavior. ```go package main import ( "log/slog" "os" "time" "github.com/KimMachineGun/automemlimit/memlimit" ) func init() { limit, err := memlimit.SetGoMemLimitWithOpts( memlimit.WithRatio(0.9), // Use 90% of available memory memlimit.WithProvider(memlimit.FromCgroup), // Use cgroup as memory source memlimit.WithLogger(slog.Default()), // Enable logging memlimit.WithRefreshInterval(1*time.Minute), // Refresh limit every minute ) if err != nil { slog.Error("failed to set memory limit", slog.Any("error", err)) return } slog.Info("memory limit configured", slog.Int64("limit_bytes", limit)) } func main() {} ``` -------------------------------- ### Automemlimit Basic Usage with Import Source: https://github.com/kimmachinegun/automemlimit/blob/main/README.md This Go code snippet demonstrates the simplest way to use the automemlimit package. By importing the package as a blank identifier, it automatically initializes and sets GOMEMLIMIT to 90% of the cgroup's memory limit upon program startup. It also enables default logging using slog.Default(). ```go package main // By default, it sets `GOMEMLIMIT` to 90% of cgroup's memory limit. // This is equivalent to `memlimit.SetGoMemLimitWithOpts(memlimit.WithLogger(slog.Default()))` // To disable logging, use `memlimit.SetGoMemLimitWithOpts` directly. import _ "github.com/KimMachineGun/automemlimit" ``` -------------------------------- ### FromSystem Provider: Use Total System Memory Source: https://context7.com/kimmachinegun/automemlimit/llms.txt Provides the total system memory as the limit. This can be used as an experimental fallback or directly as a provider. It can be enabled via an environment variable or explicitly included in the provider chain. ```go package main import ( "log" "os" "github.com/KimMachineGun/automemlimit/memlimit" ) func init() { // Option 1: Enable via environment variable // export AUTOMEMLIMIT_EXPERIMENT=system // Option 2: Use directly as a fallback provider memlimit.SetGoMemLimitWithOpts( memlimit.WithProvider( memlimit.ApplyFallback( memlimit.FromCgroup, memlimit.FromSystem, // Falls back to total system RAM ), ), ) // Option 3: Use system memory directly limit, err := memlimit.FromSystem() if err != nil { log.Printf("failed to get system memory: %v", err) return } log.Printf("total system memory: %d bytes", limit) } func main() {} ``` -------------------------------- ### Set GOMEMLIMIT with Custom Provider Source: https://context7.com/kimmachinegun/automemlimit/llms.txt Allows explicit selection of the memory provider (e.g., forcing cgroup v2) combined with a specific ratio. Useful for environments with specific cgroup configurations. ```go package main import ( "log" "github.com/KimMachineGun/automemlimit/memlimit" ) func init() { // Using cgroup v2 explicitly limit, err := memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroupV2, 0.9) if err != nil { log.Printf("failed to set memory limit: %v", err) return } log.Printf("GOMEMLIMIT set to %d bytes from cgroup v2", limit) } func main() {} ``` -------------------------------- ### Configure Go Memory Limit with Options in Go Source: https://context7.com/kimmachinegun/automemlimit/llms.txt This Go code configures the Go memory limit using SetGoMemLimitWithOpts. It automatically checks environment variables for existing configurations and allows overriding with options like ratio and logger. It logs the set limit or any errors encountered. ```go package main import ( "log/slog" "os" "github.com/KimMachineGun/automemlimit/memlimit" ) func init() { // SetGoMemLimitWithOpts checks environment variables automatically: // - If GOMEMLIMIT is set, it skips configuration // - If AUTOMEMLIMIT=off, it skips configuration // - If AUTOMEMLIMIT=0.8, it uses 0.8 as ratio instead of default/option // - If AUTOMEMLIMIT_EXPERIMENT=system, enables system memory fallback limit, err := memlimit.SetGoMemLimitWithOpts( memlimit.WithRatio(0.9), // Can be overridden by AUTOMEMLIMIT env var memlimit.WithLogger(slog.Default()), ) if err != nil { slog.Error("failed to set limit", slog.Any("error", err)) } if limit > 0 { slog.Info("limit set", slog.Int64("bytes", limit)) } } func main() {} ``` -------------------------------- ### Set GOMEMLIMIT with Simplified Ratio Source: https://context7.com/kimmachinegun/automemlimit/llms.txt A streamlined function to set the memory limit based on cgroups using only a specified ratio. Ideal for simple use cases where default providers are sufficient. ```go package main import ( "log" "github.com/KimMachineGun/automemlimit/memlimit" ) func init() { // Set GOMEMLIMIT to 80% of cgroup memory limit limit, err := memlimit.SetGoMemLimit(0.8) if err != nil { log.Printf("failed to set memory limit: %v", err) return } log.Printf("GOMEMLIMIT set to %d bytes", limit) } func main() {} ``` -------------------------------- ### Set Fixed Memory Limit Helper Source: https://context7.com/kimmachinegun/automemlimit/llms.txt Uses the Limit helper to create a provider with a static memory value. Useful for testing or overriding environment-detected limits with a hardcoded value. ```go package main import ( "log/slog" "os" "github.com/KimMachineGun/automemlimit/memlimit" ) func init() { // Set a fixed 1GB memory limit memlimit.SetGoMemLimitWithOpts( memlimit.WithProvider( memlimit.Limit(1024*1024*1024), // 1 GB in bytes ), memlimit.WithLogger(slog.New(slog.NewJSONHandler(os.Stderr, nil))), ) } func main() {} ``` -------------------------------- ### Define Custom Memory Provider Source: https://context7.com/kimmachinegun/automemlimit/llms.txt Demonstrates the Provider function type and available built-in providers. This allows developers to define how the library retrieves memory limits. ```go package main import ( "github.com/KimMachineGun/automemlimit/memlimit" ) // Provider signature: func() (uint64, error) type Provider = memlimit.Provider func init() { // Built-in providers: // memlimit.FromCgroup - Auto-detect cgroup v1/v2 // memlimit.FromCgroupV1 - Force cgroup v1 // memlimit.FromCgroupV2 - Force cgroup v2 // memlimit.FromCgroupHybrid - Try v2 then v1 (same as FromCgroup) // memlimit.FromSystem - Use total system memory memlimit.SetGoMemLimitWithOpts( memlimit.WithProvider(memlimit.FromCgroup), ) } func main() {} ``` -------------------------------- ### ApplyFallback Provider: Chain Providers with Fallback Source: https://context7.com/kimmachinegun/automemlimit/llms.txt Chains multiple memory limit providers, using a fallback provider when the primary one returns an error. This is useful for graceful degradation in mixed environments, such as trying cgroup limits first and falling back to system memory if not in a container. ```go package main import ( "github.com/KimMachineGun/automemlimit/memlimit" ) func init() { // Try cgroup first, fall back to system memory if not in a container memlimit.SetGoMemLimitWithOpts( memlimit.WithProvider( memlimit.ApplyFallback( memlimit.FromCgroup, // Primary: try cgroup memlimit.FromSystem, // Fallback: use system memory ), ), ) } func main() {} ``` -------------------------------- ### Environment Variables: Configure Automemlimit Without Code Source: https://context7.com/kimmachinegun/automemlimit/llms.txt Automemlimit respects several environment variables for configuration, allowing changes without modifying code. These include disabling the library, setting a custom ratio, respecting an existing GOMEMLIMIT, and enabling experimental features like system memory fallback. ```bash # Disable automemlimit entirely export AUTOMEMLIMIT=off # Set custom ratio (0.0-1.0] export AUTOMEMLIMIT=0.8 # Skip if GOMEMLIMIT is already set export GOMEMLIMIT=1073741824 # 1GB - automemlimit will not override # Enable experimental system memory fallback export AUTOMEMLIMIT_EXPERIMENT=system ``` -------------------------------- ### Handle Specific Errors from Cgroup Memory Limit in Go Source: https://context7.com/kimmachinegun/automemlimit/llms.txt This Go code demonstrates how to retrieve memory limits from cgroups and handle specific errors like ErrNoLimit, ErrNoCgroup, and ErrCgroupsNotSupported. It logs informative messages based on the error encountered. ```go package main import ( "errors" "log" "github.com/KimMachineGun/automemlimit/memlimit" ) func main() { limit, err := memlimit.FromCgroup() if err != nil { if errors.Is(err, memlimit.ErrNoLimit) { log.Println("memory is not limited (cgroup limit set to 'max')") } else if errors.Is(err, memlimit.ErrNoCgroup) { log.Println("process is not running in a cgroup") } else if errors.Is(err, memlimit.ErrCgroupsNotSupported) { log.Println("cgroups not supported on this system") } else { log.Printf("unexpected error: %v", err) } return } log.Printf("cgroup memory limit: %d bytes", limit) } ``` -------------------------------- ### Disable Experiments with Environment Variable Source: https://context7.com/kimmachinegun/automemlimit/llms.txt This snippet shows how to disable all experiments for the automemlimit by setting the AUTOMEMLIMIT_EXPERIMENT environment variable to 'none'. This is a simple shell command. ```shell export AUTOMEMLIMIT_EXPERIMENT=none ``` -------------------------------- ### WithRefreshInterval Option: Periodic Memory Limit Refresh Source: https://context7.com/kimmachinegun/automemlimit/llms.txt Enables periodic refreshing of the memory limit from the provider. This is useful for dynamic environments where memory limits may change at runtime, such as with Kubernetes vertical pod autoscaling. The memory limit is refreshed at the specified interval. ```go package main import ( "log/slog" "os" "os/signal" "time" "github.com/KimMachineGun/automemlimit/memlimit" ) func init() { slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, nil))) // Refresh memory limit every 5 seconds memlimit.SetGoMemLimitWithOpts( memlimit.WithProvider(memlimit.FromCgroup), memlimit.WithRefreshInterval(5*time.Second), memlimit.WithLogger(slog.Default()), ) } func main() { // Application runs with dynamic memory limit updates c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) <-c } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.