├── go.mod ├── Makefile ├── .github ├── ISSUE_TEMPLATE │ ├── custom.md │ ├── feature_request.md │ └── bug_report.md └── workflows │ ├── trivy-image-scan.yml │ └── docker-publish-image.yml ├── Dockerfile ├── .gitignore ├── SECURITY.md ├── code_of_conduct.md ├── main.go ├── README.md └── LICENSE /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/narmidm/k8s-pod-cpu-stressor 2 | 3 | go 1.24 4 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: docker-build 2 | docker-build: 3 | docker build -t k8s-pod-cpu-stressor:latest . 4 | 5 | .PHONY: build 6 | build: 7 | go build -o cpu-stress . 8 | 9 | 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.24-alpine AS build 2 | 3 | WORKDIR /app 4 | 5 | COPY . . 6 | 7 | RUN go build -o cpu-stress . 8 | 9 | FROM alpine:latest 10 | 11 | COPY --from=build /app/cpu-stress /usr/local/bin/cpu-stress 12 | 13 | ENTRYPOINT ["cpu-stress"] 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # If you prefer the allow list template instead of the deny list, see community template: 2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore 3 | # 4 | # Binaries for programs and plugins 5 | *.exe 6 | *.exe~ 7 | *.dll 8 | *.so 9 | *.dylib 10 | 11 | # Test binary, built with `go test -c` 12 | *.test 13 | 14 | # Output of the go coverage tool, specifically when used with LiteIDE 15 | *.out 16 | 17 | # Dependency directories (remove the comment below to include it) 18 | # vendor/ 19 | 20 | # Go workspace file 21 | go.work 22 | .idea 23 | 24 | 25 | .idea/k8s-pod-cpu-stressor.iml 26 | .idea/modules.xml 27 | cpu-stress 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/workflows/trivy-image-scan.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | 6 | name: trivy-docker-image-scan 7 | 8 | on: 9 | push: 10 | branches: [ "master" ] 11 | pull_request: 12 | # The branches below must be a subset of the branches above 13 | branches: [ "master" ] 14 | schedule: 15 | - cron: '28 0 * * 1' 16 | 17 | permissions: 18 | contents: read 19 | 20 | jobs: 21 | build: 22 | permissions: 23 | contents: read # for actions/checkout to fetch code 24 | security-events: write # for github/codeql-action/upload-sarif to upload SARIF results 25 | actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status 26 | name: Build 27 | runs-on: "ubuntu-20.04" 28 | steps: 29 | - name: Checkout code 30 | uses: actions/checkout@v4 31 | 32 | - name: Build an image from Dockerfile 33 | run: | 34 | docker build -t docker.io/narmidm/k8s-pod-cpu-stressor:${{ github.sha }} . 35 | 36 | - name: Run Trivy vulnerability scanner 37 | uses: aquasecurity/trivy-action@7b7aa264d83dc58691451798b4d117d53d21edfe 38 | with: 39 | image-ref: 'docker.io/narmidm/k8s-pod-cpu-stressor:${{ github.sha }}' 40 | format: 'template' 41 | template: '@/contrib/sarif.tpl' 42 | output: 'trivy-results.sarif' 43 | severity: 'CRITICAL,HIGH' 44 | 45 | - name: Upload Trivy scan results to GitHub Security tab 46 | uses: github/codeql-action/upload-sarif@v3 47 | with: 48 | sarif_file: 'trivy-results.sarif' 49 | -------------------------------------------------------------------------------- /.github/workflows/docker-publish-image.yml: -------------------------------------------------------------------------------- 1 | name: CD Pipeline 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | push: 9 | name: Push Docker Image to Registry 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | # Step 1: Check out the repository 14 | - name: Checkout repository 15 | uses: actions/checkout@v2 16 | 17 | # Step 2: Set up Docker 18 | - name: Set up Docker Buildx 19 | uses: docker/setup-buildx-action@v2 20 | 21 | # Step 3: Log in to Docker Hub 22 | - name: Log in to Docker Hub 23 | uses: docker/login-action@v2 24 | with: 25 | username: ${{ vars.DOCKERHUB_USERNAME }} 26 | password: ${{ secrets.DOCKERHUB_TOKEN }} 27 | 28 | # Step 4: Extract version from release tag 29 | - name: Extract Version from Release Tag 30 | run: | 31 | VERSION=${GITHUB_REF##*/} 32 | echo "VERSION=$VERSION" >> $GITHUB_ENV 33 | 34 | # Step 5: Build Docker Image 35 | - name: Build Docker Image 36 | run: | 37 | # Build Docker image 38 | docker build -t narmidm/k8s-pod-cpu-stressor:latest . 39 | # Tag the Docker image with the release version 40 | docker tag narmidm/k8s-pod-cpu-stressor:latest narmidm/k8s-pod-cpu-stressor:${{ env.VERSION }} 41 | 42 | # Step 6: Push Docker Image with Latest and Version Tags 43 | - name: Push Docker Image 44 | run: | 45 | # Ensure the image is built and tagged successfully 46 | docker images 47 | 48 | # Push Docker image with latest tag 49 | docker push narmidm/k8s-pod-cpu-stressor:latest 50 | 51 | # Push Docker image with version tag 52 | docker push narmidm/k8s-pod-cpu-stressor:${{ env.VERSION }} 53 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | We maintain security updates and support for the following versions of `k8s-pod-cpu-stressor`: 6 | 7 | | Version | Supported | 8 | | ------- | ------------------ | 9 | | 1.x | :white_check_mark: | 10 | | < 1.0 | :x: | 11 | 12 | Please ensure you are running a supported version to benefit from security patches. 13 | 14 | ## Reporting a Vulnerability 15 | 16 | If you discover a vulnerability in this project, please follow these steps to report it securely: 17 | 18 | 1. **Do not open a public issue** on GitHub, as this may expose the vulnerability to others before it can be addressed. 19 | 2. Contact us by sending an email to [imranaec@outlook.com](mailto:imranaec@outlook.com) with the details of the vulnerability, including steps to reproduce it, affected versions, and potential impact. 20 | 3. Please allow us **at least 90 days** to investigate and apply a fix before disclosing the issue publicly. 21 | 22 | We will work to acknowledge your report within **7 days** and provide an estimated timeline for a fix. 23 | 24 | ## Security Best Practices for Users 25 | 26 | To help ensure the security of your Kubernetes environment, consider the following when using `k8s-pod-cpu-stressor`: 27 | 28 | - **Namespace Isolation**: Run the tool in a dedicated namespace to limit any potential impact. 29 | - **Permissions**: Grant minimal permissions needed for the pod to run. Avoid giving it elevated privileges unless explicitly necessary. 30 | - **Network Policies**: Apply appropriate network policies to restrict access to and from the pods running this tool. 31 | 32 | ## Responsible Disclosure Policy 33 | 34 | We believe in and support responsible disclosure. If you report a vulnerability and work with us constructively, we are committed to acknowledging your contributions in the release notes or other appropriate acknowledgments (with your permission). 35 | 36 | ## Contact 37 | 38 | If you have general security concerns or questions, please contact the maintainers at [imranaec@outlook.com](mailto:imranaec@outlook.com). 39 | -------------------------------------------------------------------------------- /code_of_conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to a positive environment for our community include: 12 | 13 | * Demonstrating empathy and kindness toward other people 14 | * Being respectful of differing opinions, viewpoints, and experiences 15 | * Giving and gracefully accepting constructive feedback 16 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | * Focusing on what is best not just for us as individuals, but for the overall community 18 | 19 | Examples of unacceptable behavior include: 20 | 21 | * The use of sexualized language or imagery, and sexual attention or advances of any kind 22 | * Trolling, insulting or derogatory comments, and personal or political attacks 23 | * Public or private harassment 24 | * Publishing others’ private information, such as a physical or email address, without their explicit permission 25 | * Other conduct which could reasonably be considered inappropriate in a professional setting 26 | 27 | ## Enforcement Responsibilities 28 | 29 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 32 | 33 | ## Scope 34 | 35 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 36 | 37 | ## Enforcement 38 | 39 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at imranaec@outlook.com. All complaints will be reviewed and investigated promptly and fairly. 40 | 41 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 42 | 43 | ## Enforcement Guidelines 44 | 45 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 46 | 47 | ### 1. Correction 48 | 49 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 50 | 51 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 52 | 53 | ### 2. Warning 54 | 55 | **Community Impact**: A violation through a single incident or series of actions. 56 | 57 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 58 | 59 | ### 3. Temporary Ban 60 | 61 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 62 | 63 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 64 | 65 | ### 4. Permanent Ban 66 | 67 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 68 | 69 | **Consequence**: A permanent ban from any sort of public interaction within the community. 70 | 71 | ## Attribution 72 | 73 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html. 74 | 75 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 76 | 77 | For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 78 | 79 | [homepage]: https://www.contributor-covenant.org 80 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | "math/rand" 8 | "os" 9 | "os/signal" 10 | "runtime" 11 | "sync" 12 | "sync/atomic" 13 | "time" 14 | ) 15 | 16 | const ( 17 | version = "1.0.0" 18 | ) 19 | 20 | // CPUUsageMonitor tracks CPU usage and provides feedback 21 | type CPUUsageMonitor struct { 22 | targetUsage float64 23 | currentUsage float64 24 | adjustmentLock sync.Mutex 25 | scaleFactor float64 // Adjustment multiplier for workload 26 | } 27 | 28 | // NewCPUUsageMonitor creates a new CPU usage monitor 29 | func NewCPUUsageMonitor(targetUsage float64) *CPUUsageMonitor { 30 | return &CPUUsageMonitor{ 31 | targetUsage: targetUsage, 32 | scaleFactor: 1.0, // Start with no adjustment 33 | currentUsage: 0, 34 | } 35 | } 36 | 37 | // AdjustWorkload returns the current scale factor for the workload 38 | func (m *CPUUsageMonitor) AdjustWorkload() float64 { 39 | m.adjustmentLock.Lock() 40 | defer m.adjustmentLock.Unlock() 41 | return m.scaleFactor 42 | } 43 | 44 | // UpdateUsage updates the current CPU usage and adjusts the scale factor 45 | func (m *CPUUsageMonitor) UpdateUsage(actualUsage float64) { 46 | m.adjustmentLock.Lock() 47 | defer m.adjustmentLock.Unlock() 48 | 49 | m.currentUsage = actualUsage 50 | 51 | // Simple proportional control - adjust based on ratio of target to actual 52 | if actualUsage > 0.01 { // Avoid division by very small numbers 53 | // If we're using too much CPU, decrease the scale factor 54 | // If we're using too little, increase it 55 | adjustment := m.targetUsage / actualUsage 56 | 57 | // Limit adjustment rate to avoid oscillation 58 | if adjustment > 2.0 { 59 | adjustment = 2.0 60 | } else if adjustment < 0.5 { 61 | adjustment = 0.5 62 | } 63 | 64 | // Gradually adjust the scale factor with stronger weight for recent measurements 65 | m.scaleFactor = m.scaleFactor*0.5 + adjustment*0.5 66 | } 67 | 68 | fmt.Printf("CPU Usage: %.2f%% (target: %.2f%%), adjustment factor: %.2f\n", 69 | actualUsage*100, m.targetUsage*100, m.scaleFactor) 70 | } 71 | 72 | // getCPUUsage returns a relative measure of CPU performance 73 | func getCPUUsage() float64 { 74 | // Get the start time 75 | start := time.Now() 76 | var iterations uint64 77 | 78 | // Run some work to measure how many ops/sec we can do 79 | for i := 0; i < 1000000; i++ { 80 | iterations++ 81 | // Do some meaningless work 82 | _ = math.Sqrt(rand.Float64()) 83 | } 84 | elapsed := time.Since(start) 85 | 86 | // Calculate the CPU usage based on how much work we accomplished 87 | return float64(iterations) / float64(elapsed.Nanoseconds()) 88 | } 89 | 90 | func printUsage() { 91 | fmt.Printf("k8s-pod-cpu-stressor %s\n", version) 92 | fmt.Println("A tool for simulating CPU load in Kubernetes pods") 93 | fmt.Println("\nUsage:") 94 | fmt.Println(" cpu-stress [options]") 95 | fmt.Println("\nOptions:") 96 | fmt.Println(" -cpu=0.2 CPU usage as a fraction (e.g., 0.2 for 20% CPU usage)") 97 | fmt.Println(" -duration=10s Duration for the CPU stress (e.g., 10s, 5m, 1h)") 98 | fmt.Println(" -forever Run CPU stress indefinitely") 99 | fmt.Println(" -version Show version information") 100 | fmt.Println(" -help Show this help message") 101 | fmt.Println("\nExamples:") 102 | fmt.Println(" cpu-stress -cpu=0.5 -duration=30s # Use 50% CPU for 30 seconds") 103 | fmt.Println(" cpu-stress -cpu=0.8 -forever # Use 80% CPU indefinitely") 104 | } 105 | 106 | func main() { 107 | // Parse command-line flags 108 | cpuUsagePtr := flag.Float64("cpu", 0.2, "CPU usage as a fraction (e.g., 0.2 for 20% CPU usage)") 109 | durationPtr := flag.Duration("duration", 10*time.Second, "Duration for the CPU stress (e.g., 10s)") 110 | runForeverPtr := flag.Bool("forever", false, "Run CPU stress indefinitely") 111 | showVersion := flag.Bool("version", false, "Show version information") 112 | showHelp := flag.Bool("help", false, "Show help message") 113 | 114 | flag.Parse() 115 | 116 | // Show version if requested 117 | if *showVersion { 118 | fmt.Printf("k8s-pod-cpu-stressor version %s\n", version) 119 | os.Exit(0) 120 | } 121 | 122 | // Show help if requested 123 | if *showHelp { 124 | printUsage() 125 | os.Exit(0) 126 | } 127 | 128 | // Validate CPU usage 129 | if *cpuUsagePtr <= 0 || *cpuUsagePtr > 1.0 { 130 | fmt.Printf("Error: CPU usage must be between 0 and 1.0, got %.2f\n", *cpuUsagePtr) 131 | os.Exit(1) 132 | } 133 | 134 | numCPU := runtime.NumCPU() 135 | runtime.GOMAXPROCS(numCPU) 136 | 137 | // Get baseline CPU measurement for calibration 138 | baselineCPU := getCPUUsage() 139 | fmt.Printf("Baseline CPU measurement: %.6f ops/ns\n", baselineCPU) 140 | 141 | // Create CPU usage monitor with the target usage 142 | monitor := NewCPUUsageMonitor(*cpuUsagePtr) 143 | 144 | // Number of goroutines to use for stressing CPU 145 | numGoroutines := int(float64(numCPU)*(*cpuUsagePtr)) + 1 146 | if numGoroutines < 1 { 147 | numGoroutines = 1 148 | } 149 | 150 | fmt.Printf("Starting CPU stress with %d goroutines targeting %.2f CPU usage...\n", numGoroutines, *cpuUsagePtr) 151 | 152 | done := make(chan struct{}) 153 | 154 | // Prevent channel close race condition 155 | var doneClosed sync.Once 156 | closeDone := func() { 157 | doneClosed.Do(func() { 158 | close(done) 159 | }) 160 | } 161 | 162 | // Capture termination signals 163 | quit := make(chan os.Signal, 1) 164 | signal.Notify(quit, os.Interrupt, os.Kill) 165 | 166 | var stopFlag int32 167 | 168 | // Launch worker goroutines 169 | for i := 0; i < numGoroutines; i++ { 170 | go func() { 171 | // Base workload parameters 172 | baseWorkload := 500 * time.Microsecond 173 | baseIdleTime := time.Duration((1 - *cpuUsagePtr) / *cpuUsagePtr * float64(baseWorkload)) 174 | if baseIdleTime < 1*time.Microsecond { 175 | baseIdleTime = 1 * time.Microsecond 176 | } 177 | 178 | for { 179 | if atomic.LoadInt32(&stopFlag) == 1 { 180 | return 181 | } 182 | 183 | // Get current adjustment factor 184 | scaleFactor := monitor.AdjustWorkload() 185 | 186 | // Scale the workload 187 | workDuration := time.Duration(float64(baseWorkload) * scaleFactor) 188 | 189 | // Perform work (busy-wait) 190 | startWork := time.Now() 191 | for time.Since(startWork) < workDuration { 192 | // CPU-intensive operations 193 | _ = math.Sqrt(rand.Float64()) * math.Sqrt(rand.Float64()) 194 | } 195 | 196 | // Calculate appropriate idle time based on desired duty cycle 197 | idleTime := time.Duration(float64(workDuration) * (1 - *cpuUsagePtr) / *cpuUsagePtr) 198 | if idleTime < 1*time.Microsecond { 199 | idleTime = 1 * time.Microsecond 200 | } 201 | 202 | // Idle for the calculated time 203 | time.Sleep(idleTime) 204 | } 205 | }() 206 | } 207 | 208 | // Start the monitoring goroutine 209 | go func() { 210 | // Wait for initial stabilization 211 | time.Sleep(500 * time.Millisecond) 212 | 213 | const monitorInterval = 1 * time.Second 214 | for { 215 | if atomic.LoadInt32(&stopFlag) == 1 { 216 | return 217 | } 218 | 219 | // Take a series of samples 220 | var totalUsage float64 221 | const numSamples = 3 222 | for i := 0; i < numSamples; i++ { 223 | start := time.Now() 224 | var counter uint64 225 | for j := 0; j < 100000 && time.Since(start) < 100*time.Millisecond; j++ { 226 | counter++ 227 | _ = math.Sqrt(rand.Float64()) 228 | } 229 | elapsed := time.Since(start) 230 | cpuEff := float64(counter) / float64(elapsed.Nanoseconds()) 231 | // Calculate as a percentage of baseline 232 | currentUsage := cpuEff / baselineCPU 233 | totalUsage += currentUsage 234 | time.Sleep(10 * time.Millisecond) 235 | } 236 | 237 | // Calculate average and adjust for number of CPUs 238 | avgUsage := (totalUsage / numSamples) / float64(numCPU) 239 | 240 | // Update CPU usage monitor with observed usage 241 | monitor.UpdateUsage(avgUsage) 242 | 243 | time.Sleep(monitorInterval) 244 | } 245 | }() 246 | 247 | go func() { 248 | // Wait for termination signal 249 | <-quit 250 | fmt.Println("\nTermination signal received. Stopping CPU stress...") 251 | atomic.StoreInt32(&stopFlag, 1) 252 | closeDone() 253 | }() 254 | 255 | if !*runForeverPtr { 256 | time.Sleep(*durationPtr) 257 | fmt.Println("\nCPU stress completed.") 258 | atomic.StoreInt32(&stopFlag, 1) 259 | closeDone() 260 | // Keep the process running to prevent the pod from restarting 261 | select {} 262 | } else { 263 | // Run stress indefinitely 264 | fmt.Println("CPU stress will run indefinitely. Press Ctrl+C to stop.") 265 | <-done 266 | } 267 | } 268 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![CI Status](https://github.com/narmidm/k8s-pod-cpu-stressor/actions/workflows/trivy-image-scan.yml/badge.svg)](https://github.com/narmidm/k8s-pod-cpu-stressor/actions/workflows/trivy-image-scan.yml) 2 | [![CD Status](https://github.com/narmidm/k8s-pod-cpu-stressor/actions/workflows/docker-publish-image.yml/badge.svg)](https://github.com/narmidm/k8s-pod-cpu-stressor/actions/workflows/docker-publish-image.yml) 3 | [![Docker Image Version](https://img.shields.io/docker/v/narmidm/k8s-pod-cpu-stressor?sort=semver)](https://hub.docker.com/repository/docker/narmidm/k8s-pod-cpu-stressor) 4 | [![Docker Pulls](https://img.shields.io/docker/pulls/narmidm/k8s-pod-cpu-stressor)](https://hub.docker.com/repository/docker/narmidm/k8s-pod-cpu-stressor) 5 | [![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/narmidm/k8s-pod-cpu-stressor)](https://raw.githubusercontent.com/narmidm/k8s-pod-cpu-stressor/refs/heads/master/go.mod) 6 | [![GitHub License](https://img.shields.io/github/license/narmidm/k8s-pod-cpu-stressor)](https://raw.githubusercontent.com/narmidm/k8s-pod-cpu-stressor/refs/heads/master/LICENSE) 7 | [![Go Report Card](https://goreportcard.com/badge/github.com/narmidm/k8s-pod-cpu-stressor)](https://goreportcard.com/report/github.com/narmidm/k8s-pod-cpu-stressor) 8 | ![Contributors](https://img.shields.io/github/contributors/narmidm/k8s-pod-cpu-stressor) 9 | [![GitHub Issues](https://img.shields.io/github/issues/narmidm/k8s-pod-cpu-stressor)](https://github.com/narmidm/k8s-pod-cpu-stressor/issues) 10 | [![GitHub Stars](https://img.shields.io/github/stars/narmidm/k8s-pod-cpu-stressor)](https://github.com/narmidm/k8s-pod-cpu-stressor/stargazers) 11 | [![GitHub Forks](https://img.shields.io/github/forks/narmidm/k8s-pod-cpu-stressor)](https://github.com/narmidm/k8s-pod-cpu-stressor/forks) 12 | [![Last Commit](https://img.shields.io/github/last-commit/narmidm/k8s-pod-cpu-stressor)](https://github.com/narmidm/k8s-pod-cpu-stressor/commits/master/) 13 | 14 | ### Connect with me 15 | [![X (formerly Twitter) Follow](https://img.shields.io/twitter/follow/that_imran)](https://x.com/intent/user?screen_name=that_imran) 16 | narmidm 17 | 18 | 19 | # k8s-pod-cpu-stressor 20 | 21 | The `k8s-pod-cpu-stressor` is a tool designed to simulate CPU stress on Kubernetes pods. It allows you to specify the desired CPU usage and stress duration, helping you test the behavior of your Kubernetes cluster under different CPU load scenarios. 22 | 23 | ## Features 24 | 25 | - Simulates CPU stress on Kubernetes pods. 26 | - Configurable CPU usage (in millicores) and stress duration. 27 | - Option to run CPU stress indefinitely. 28 | - Adaptive feedback control mechanism to maintain target CPU usage. 29 | - Respects Kubernetes resource limits. 30 | - Helps evaluate Kubernetes cluster performance and resource allocation. 31 | 32 | ## Getting Started 33 | 34 | ### Prerequisites 35 | 36 | To use the `k8s-pod-cpu-stressor`, you need to have the following installed: 37 | 38 | - Go (version 1.24 or higher) 39 | - Docker 40 | 41 | ### Building the Binary 42 | 43 | 1. Clone this repository to your local machine. 44 | 2. Navigate to the repository directory. 45 | 3. Build the binary using the following command: 46 | 47 | ```shell 48 | go build -o cpu-stress . 49 | ``` 50 | 51 | ## Running with Docker 52 | 53 | Build the Docker image using the provided Dockerfile: 54 | 55 | ```shell 56 | docker build -t k8s-pod-cpu-stressor . 57 | ``` 58 | 59 | Run the Docker container, specifying the desired CPU usage, stress duration, and optionally whether to run CPU stress indefinitely: 60 | 61 | ```shell 62 | docker run --rm k8s-pod-cpu-stressor -cpu=0.2 -duration=10s -forever 63 | ``` 64 | 65 | Replace `0.2` and `10s` with the desired CPU usage (fraction) and duration, respectively. Add `-forever` flag to run CPU stress indefinitely. 66 | 67 | ## CPU Usage and Duration 68 | 69 | The `k8s-pod-cpu-stressor` allows you to specify the desired CPU usage and stress duration using the following parameters: 70 | 71 | - **CPU Usage**: The CPU usage is defined as a fraction of CPU resources. It is specified using the `-cpu` argument. For example, `-cpu=0.2` represents a CPU usage of 20% or 200 milliCPU (mCPU). 72 | 73 | - **Stress Duration**: The stress duration defines how long the CPU stress operation should run. It is specified using the `-duration` argument, which accepts a duration value with a unit. Supported units include seconds (s), minutes (m), hours (h), and days (d). For example, `-duration=10s` represents a stress duration of 10 seconds, `-duration=5m` represents 5 minutes, `-duration=2h` represents 2 hours, and `-duration=1d` represents 1 day. 74 | 75 | - **Run Indefinitely**: To run CPU stress indefinitely, include the `-forever` flag. 76 | 77 | Adjust these parameters according to your requirements to simulate different CPU load scenarios. 78 | 79 | ### Kubernetes Resource Requests and Limits 80 | 81 | It is recommended to specify Kubernetes resource requests and limits to control the amount of CPU resources consumed by the pod, and to prevent overloading your cluster. For example: 82 | 83 | - **Requests**: This defines the minimum amount of CPU that the pod is guaranteed to have. 84 | - **Limits**: This defines the maximum amount of CPU that the pod can use. 85 | 86 | Adding requests and limits helps Kubernetes manage resources efficiently and ensures that your cluster remains stable during stress testing. 87 | 88 | Example: 89 | 90 | ```yaml 91 | resources: 92 | requests: 93 | cpu: "100m" 94 | limits: 95 | cpu: "200m" 96 | ``` 97 | 98 | ## Check the Public Docker Image 99 | 100 | The [`k8s-pod-cpu-stressor`](https://hub.docker.com/r/narmidm/k8s-pod-cpu-stressor "Docker Hub - narmidm/k8s-pod-cpu-stressor") Docker image is publicly available on Docker Hub. You can check and pull the image using the following command: 101 | 102 | ```shell 103 | docker pull narmidm/k8s-pod-cpu-stressor:latest 104 | ``` 105 | 106 | ## Sample Deployment Manifest 107 | 108 | Use the following deployment manifest as a starting point to deploy the k8s-pod-cpu-stressor image in your Kubernetes cluster: 109 | 110 | ```yaml 111 | apiVersion: apps/v1 112 | kind: Deployment 113 | metadata: 114 | name: cpu-stressor-deployment 115 | spec: 116 | replicas: 1 117 | selector: 118 | matchLabels: 119 | app: cpu-stressor 120 | template: 121 | metadata: 122 | labels: 123 | app: cpu-stressor 124 | spec: 125 | containers: 126 | - name: cpu-stressor 127 | image: narmidm/k8s-pod-cpu-stressor:latest 128 | args: 129 | - "-cpu=0.2" 130 | - "-duration=10s" 131 | - "-forever" 132 | resources: 133 | limits: 134 | cpu: "200m" 135 | requests: 136 | cpu: "100m" 137 | ``` 138 | 139 | ## Sample Job Manifest 140 | 141 | If you want to run the CPU stressor for a fixed duration as a one-time job, you can use the following Kubernetes Job manifest: 142 | 143 | ```yaml 144 | apiVersion: batch/v1 145 | kind: Job 146 | metadata: 147 | name: cpu-stressor-job 148 | spec: 149 | template: 150 | metadata: 151 | labels: 152 | app: cpu-stressor 153 | spec: 154 | containers: 155 | - name: cpu-stressor 156 | image: narmidm/k8s-pod-cpu-stressor:latest 157 | args: 158 | - "-cpu=0.5" 159 | - "-duration=5m" 160 | resources: 161 | limits: 162 | cpu: "500m" 163 | requests: 164 | cpu: "250m" 165 | restartPolicy: Never 166 | backoffLimit: 3 167 | ``` 168 | 169 | This manifest runs the `k8s-pod-cpu-stressor` as a Kubernetes Job, which will execute the stress test once for 5 minutes and then stop. The `backoffLimit` specifies the number of retries if the job fails. 170 | 171 | ## How It Works 172 | 173 | The CPU stressor uses an adaptive feedback control mechanism to maintain the target CPU usage even in constrained environments: 174 | 175 | 1. **Baseline Measurement**: At startup, the tool measures the baseline CPU performance of the environment. 176 | 2. **Feedback Control**: A continuous monitoring loop measures actual CPU usage and dynamically adjusts the workload to match the target usage. 177 | 3. **Resource Awareness**: The tool respects container CPU limits, preventing resource overconsumption. 178 | 4. **Adaptive Scaling**: The control mechanism automatically adapts to different CPU allocations, from very small (100m) to large (multiple cores). 179 | 180 | This approach ensures consistent behavior across different Kubernetes environments, regardless of the underlying hardware or resource constraints. 181 | 182 | ## Contributing 183 | 184 | Contributions are welcome! If you find a bug or have a suggestion, please open an issue or submit a pull request. For major changes, please discuss them first in the issue tracker. 185 | 186 | ## License 187 | 188 | This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. 189 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------