1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package stresschaos
17
18 import (
19 "encoding/json"
20 "fmt"
21 "io"
22 "net/http"
23
24 corev1 "k8s.io/api/core/v1"
25 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
26 "k8s.io/klog/v2"
27
28 "github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
29 )
30
31 func makeMemoryStressChaos(
32 namespace, name string,
33 podNs, podAppName string, memorySize string, worker int,
34 ) *v1alpha1.StressChaos {
35 return &v1alpha1.StressChaos{
36 ObjectMeta: metav1.ObjectMeta{
37 Name: name,
38 Namespace: namespace,
39 },
40 Spec: v1alpha1.StressChaosSpec{
41 ContainerSelector: v1alpha1.ContainerSelector{
42 PodSelector: v1alpha1.PodSelector{
43 Mode: v1alpha1.AllMode,
44 Selector: v1alpha1.PodSelectorSpec{
45 GenericSelectorSpec: v1alpha1.GenericSelectorSpec{
46 Namespaces: []string{podNs},
47 LabelSelectors: map[string]string{
48 "app": podAppName,
49 },
50 },
51 },
52 },
53 },
54 Stressors: &v1alpha1.Stressors{
55 MemoryStressor: &v1alpha1.MemoryStressor{
56 Size: memorySize,
57 Stressor: v1alpha1.Stressor{Workers: worker},
58 },
59 },
60 },
61 }
62 }
63
64 func makeCPUStressChaos(
65 namespace, name string,
66 podNs, podAppName string, worker int, load int,
67 ) *v1alpha1.StressChaos {
68 return &v1alpha1.StressChaos{
69 ObjectMeta: metav1.ObjectMeta{
70 Name: name,
71 Namespace: namespace,
72 },
73 Spec: v1alpha1.StressChaosSpec{
74 ContainerSelector: v1alpha1.ContainerSelector{
75 PodSelector: v1alpha1.PodSelector{
76 Mode: v1alpha1.AllMode,
77 Selector: v1alpha1.PodSelectorSpec{
78 GenericSelectorSpec: v1alpha1.GenericSelectorSpec{
79 Namespaces: []string{podNs},
80 LabelSelectors: map[string]string{
81 "app": podAppName,
82 },
83 },
84 },
85 },
86 },
87 Stressors: &v1alpha1.Stressors{
88 CPUStressor: &v1alpha1.CPUStressor{
89 Load: &load,
90 Stressor: v1alpha1.Stressor{Workers: worker},
91 },
92 },
93 },
94 }
95 }
96
97 type StressCondition struct {
98 CpuTime uint64 `json:"cpuTime"`
99 MemoryUsage uint64 `json:"memoryUsage"`
100 }
101
102 func getStressCondition(c http.Client, port uint16) (*StressCondition, error) {
103 klog.Infof("sending request to http://localhost:%d/stress", port)
104
105 resp, err := c.Get(fmt.Sprintf("http://localhost:%d/stress", port))
106 if err != nil {
107 return nil, err
108 }
109 defer resp.Body.Close()
110
111 out, err := io.ReadAll(resp.Body)
112 if err != nil {
113 return nil, err
114 }
115
116 condition := &StressCondition{}
117 err = json.Unmarshal(out, condition)
118 if err != nil {
119 return nil, err
120 }
121
122 return condition, nil
123 }
124
125 func probeStressCondition(
126 c http.Client, peers []*corev1.Pod, ports []uint16,
127 ) (map[int]*StressCondition, error) {
128 stressConditions := make(map[int]*StressCondition)
129
130 for index, port := range ports {
131 stressCondition, err := getStressCondition(c, port)
132 if err != nil {
133 return nil, err
134 }
135
136 stressConditions[index] = stressCondition
137 }
138
139 return stressConditions, nil
140 }
141