...
1
24
25
26
27 package vishhstress
28
29 import (
30 "io"
31 "io/ioutil"
32 "os"
33 "time"
34
35 "github.com/spf13/cobra"
36 "k8s.io/apimachinery/pkg/api/resource"
37 "k8s.io/klog/v2"
38 )
39
40 var (
41 argMemTotal string
42 argMemStepSize string
43 argMemSleepDuration time.Duration
44 argCpus int
45 buffer [][]byte
46 )
47
48
49 var CmdStress = &cobra.Command{
50 Use: "stress",
51 Short: "Lightweight compute resource stress utlity",
52 Args: cobra.NoArgs,
53 Run: main,
54 }
55
56 func init() {
57 flags := CmdStress.Flags()
58 flags.StringVar(&argMemTotal, "mem-total", "0", "total memory to be consumed. Memory will be consumed via multiple allocations.")
59 flags.StringVar(&argMemStepSize, "mem-alloc-size", "4Ki", "amount of memory to be consumed in each allocation")
60 flags.DurationVar(&argMemSleepDuration, "mem-alloc-sleep", time.Millisecond, "duration to sleep between allocations")
61 flags.IntVar(&argCpus, "cpus", 0, "total number of CPUs to utilize")
62 }
63
64 func main(cmd *cobra.Command, _ []string) {
65 total := resource.MustParse(argMemTotal)
66 stepSize := resource.MustParse(argMemStepSize)
67 klog.Infof("Allocating %q memory, in %q chunks, with a %v sleep between allocations", total.String(), stepSize.String(), argMemSleepDuration)
68 burnCPU()
69 allocateMemory(total, stepSize)
70 klog.Infof("Allocated %q memory", total.String())
71 select {}
72 }
73
74 func burnCPU() {
75 src, err := os.Open("/dev/zero")
76 if err != nil {
77 klog.Fatalf("failed to open /dev/zero")
78 }
79 for i := 0; i < argCpus; i++ {
80 klog.Infof("Spawning a thread to consume CPU")
81 go func() {
82 _, err := io.Copy(ioutil.Discard, src)
83 if err != nil {
84 klog.Fatalf("failed to copy from /dev/zero to /dev/null: %v", err)
85 }
86 }()
87 }
88 }
89
90 func allocateMemory(total, stepSize resource.Quantity) {
91 for i := int64(1); i*stepSize.Value() <= total.Value(); i++ {
92 newBuffer := make([]byte, stepSize.Value())
93 for i := range newBuffer {
94 newBuffer[i] = 0
95 }
96 buffer = append(buffer, newBuffer)
97 time.Sleep(argMemSleepDuration)
98 }
99 }
100
View as plain text