Skip to content

Commit

Permalink
memory support
Browse files Browse the repository at this point in the history
  • Loading branch information
narmidm committed Nov 10, 2024
1 parent 89ed125 commit ca8cd67
Show file tree
Hide file tree
Showing 4 changed files with 140 additions and 10 deletions.
55 changes: 47 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ To use the `k8s-pod-cpu-stressor`, you need to have the following installed:
go build -o cpu-stress .
```

### Applying Sample Manifests

To quickly apply the sample Kubernetes manifests, navigate to the `k8s-manifests` folder and run the following command:

```shell
kubectl apply -f deployment.yaml
kubectl apply -f job.yaml
```

## Running with Docker

Build the Docker image using the provided Dockerfile:
Expand All @@ -54,13 +63,13 @@ Build the Docker image using the provided Dockerfile:
docker build -t k8s-pod-cpu-stressor .
```

Run the Docker container, specifying the desired CPU usage, stress duration, and optionally whether to run CPU stress indefinitely:
Run the Docker container, specifying the desired CPU usage, stress duration, memory usage, memory stress duration, and optionally whether to run CPU and memory stress indefinitely:

```shell
docker run --rm k8s-pod-cpu-stressor -cpu=0.2 -duration=10s -forever
docker run --rm k8s-pod-cpu-stressor -cpu=0.2 -duration=10s -forever -memory=0.2 -memduration=10s -memforever
```

Replace `0.2` and `10s` with the desired CPU usage (fraction) and duration, respectively. Add `-forever` flag to run CPU stress indefinitely.
Replace `0.2` and `10s` with the desired CPU usage (fraction), duration, memory usage (fraction), and memory stress duration, respectively. Add `-forever` and `-memforever` flags to run CPU and memory stress indefinitely.

## CPU Usage and Duration

Expand All @@ -72,14 +81,24 @@ The `k8s-pod-cpu-stressor` allows you to specify the desired CPU usage and stres

- **Run Indefinitely**: To run CPU stress indefinitely, include the `-forever` flag.

Adjust these parameters according to your requirements to simulate different CPU load scenarios.
## Memory Usage and Duration

The `k8s-pod-cpu-stressor` also allows you to specify the desired memory usage and stress duration using the following parameters:

- **Memory Usage**: The memory usage is defined as a fraction of memory resources. It is specified using the `-memory` argument. For example, `-memory=0.2` represents a memory usage of 20%.

- **Memory Stress Duration**: The memory stress duration defines how long the memory stress operation should run. It is specified using the `-memduration` argument, which accepts a duration value with a unit. Supported units include seconds (s), minutes (m), hours (h), and days (d). For example, `-memduration=10s` represents a memory stress duration of 10 seconds, `-memduration=5m` represents 5 minutes, `-memduration=2h` represents 2 hours, and `-memduration=1d` represents 1 day.

- **Run Memory Stress Indefinitely**: To run memory stress indefinitely, include the `-memforever` flag.

Adjust these parameters according to your requirements to simulate different CPU and memory load scenarios.

### Kubernetes Resource Requests and Limits

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:
It is recommended to specify Kubernetes resource requests and limits to control the amount of CPU and memory resources consumed by the pod, and to prevent overloading your cluster. For example:

- **Requests**: This defines the minimum amount of CPU that the pod is guaranteed to have.
- **Limits**: This defines the maximum amount of CPU that the pod can use.
- **Requests**: This defines the minimum amount of CPU and memory that the pod is guaranteed to have.
- **Limits**: This defines the maximum amount of CPU and memory that the pod can use.

Adding requests and limits helps Kubernetes manage resources efficiently and ensures that your cluster remains stable during stress testing.

Expand All @@ -89,8 +108,10 @@ Example:
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "200m"
memory: "256Mi"
```

## Check the Public Docker Image
Expand Down Expand Up @@ -127,16 +148,21 @@ spec:
- "-cpu=0.2"
- "-duration=10s"
- "-forever"
- "-memory=0.2"
- "-memduration=10s"
- "-memforever"
resources:
limits:
cpu: "200m"
memory: "256Mi"
requests:
cpu: "100m"
memory: "128Mi"
```

## Sample Job Manifest

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:
If you want to run the CPU and memory stressor for a fixed duration as a one-time job, you can use the following Kubernetes Job manifest:

```yaml
apiVersion: batch/v1
Expand All @@ -155,17 +181,30 @@ spec:
args:
- "-cpu=0.5"
- "-duration=5m"
- "-memory=0.5"
- "-memduration=5m"
resources:
limits:
cpu: "500m"
memory: "512Mi"
requests:
cpu: "250m"
memory: "256Mi"
restartPolicy: Never
backoffLimit: 3
```

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.

## Sample Kubernetes Manifests

You can find sample Kubernetes manifests in the `k8s-manifests` folder. These manifests include deployment and job configurations for the `k8s-pod-cpu-stressor`. To quickly apply these manifests, navigate to the `k8s-manifests` folder and run the following command:

```shell
kubectl apply -f deployment.yaml
kubectl apply -f job.yaml
```

## Contributing

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.
Expand Down
31 changes: 31 additions & 0 deletions k8s-manifests/deployment.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: cpu-stressor-deployment
spec:
replicas: 1
selector:
matchLabels:
app: cpu-stressor
template:
metadata:
labels:
app: cpu-stressor
spec:
containers:
- name: cpu-stressor
image: narmidm/k8s-pod-cpu-stressor:latest
args:
- "-cpu=0.2"
- "-duration=10s"
- "-forever"
- "-memory=0.2"
- "-memduration=10s"
- "-memforever"
resources:
limits:
cpu: "200m"
memory: "256Mi"
requests:
cpu: "100m"
memory: "128Mi"
27 changes: 27 additions & 0 deletions k8s-manifests/job.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
apiVersion: batch/v1
kind: Job
metadata:
name: cpu-stressor-job
spec:
template:
metadata:
labels:
app: cpu-stressor
spec:
containers:
- name: cpu-stressor
image: narmidm/k8s-pod-cpu-stressor:latest
args:
- "-cpu=0.5"
- "-duration=5m"
- "-memory=0.5"
- "-memduration=5m"
resources:
limits:
cpu: "500m"
memory: "512Mi"
requests:
cpu: "250m"
memory: "256Mi"
restartPolicy: Never
backoffLimit: 3
37 changes: 35 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ func main() {
cpuUsagePtr := flag.Float64("cpu", 0.2, "CPU usage as a fraction (e.g., 0.2 for 20% CPU usage)")
durationPtr := flag.Duration("duration", 10*time.Second, "Duration for the CPU stress (e.g., 10s)")
runForeverPtr := flag.Bool("forever", false, "Run CPU stress indefinitely")
memoryUsagePtr := flag.Float64("memory", 0.2, "Memory usage as a fraction (e.g., 0.2 for 20% memory usage)")
memDurationPtr := flag.Duration("memduration", 10*time.Second, "Duration for the memory stress (e.g., 10s)")
memForeverPtr := flag.Bool("memforever", false, "Run memory stress indefinitely")
flag.Parse()

numCPU := runtime.NumCPU()
Expand Down Expand Up @@ -60,10 +63,31 @@ func main() {
}()
}

// Memory stress logic
go func() {
memUsage := int(float64(runtime.MemStats.Sys) * (*memoryUsagePtr))
memStress := make([]byte, memUsage)
for i := range memStress {
memStress[i] = byte(rand.Intn(256))
}

for {
if atomic.LoadInt32(&stopFlag) == 1 {
return
}

// Simulate memory usage
_ = memStress[rand.Intn(len(memStress))]

// Sleep for a short duration to simulate memory stress
time.Sleep(10 * time.Millisecond)
}
}()

go func() {
// Wait for termination signal
<-quit
fmt.Println("\nTermination signal received. Stopping CPU stress...")
fmt.Println("\nTermination signal received. Stopping CPU and memory stress...")
atomic.StoreInt32(&stopFlag, 1)
close(done)
}()
Expand All @@ -77,7 +101,16 @@ func main() {
select {}
}

if !*memForeverPtr {
time.Sleep(*memDurationPtr)
fmt.Println("\nMemory stress completed.")
atomic.StoreInt32(&stopFlag, 1)
close(done)
// Keep the process running to prevent the pod from restarting
select {}
}

// Run stress indefinitely
fmt.Println("CPU stress will run indefinitely. Press Ctrl+C to stop.")
fmt.Println("CPU and memory stress will run indefinitely. Press Ctrl+C to stop.")
<-done
}

0 comments on commit ca8cd67

Please sign in to comment.