forked from chaos-mesh/chaos-mesh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
170 lines (144 loc) · 4.89 KB
/
controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// Copyright 2021 Chaos Mesh Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package podiochaos
import (
"context"
"encoding/json"
"strings"
"github.com/go-logr/logr"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/retry"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
"github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
"github.com/chaos-mesh/chaos-mesh/controllers/utils/chaosdaemon"
"github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
)
// Reconciler applys podioworkchaos
type Reconciler struct {
client.Client
Recorder record.EventRecorder
Log logr.Logger
ChaosDaemonClientBuilder *chaosdaemon.ChaosDaemonClientBuilder
}
func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
obj := &v1alpha1.PodIOChaos{}
if err := r.Client.Get(ctx, req.NamespacedName, obj); err != nil {
if apierrors.IsNotFound(err) {
r.Log.Info("chaos not found")
} else {
// TODO: handle this error
r.Log.Error(err, "unable to get chaos")
}
return ctrl.Result{}, nil
}
if obj.ObjectMeta.Generation <= obj.Status.ObservedGeneration && obj.Status.FailedMessage == "" {
r.Log.Info("the target pod has been up to date", "pod", obj.Namespace+"/"+obj.Name)
return ctrl.Result{}, nil
}
r.Log.Info("updating io chaos", "pod", obj.Namespace+"/"+obj.Name, "spec", obj.Spec)
pod := &v1.Pod{}
err := r.Client.Get(ctx, types.NamespacedName{
Name: obj.Name,
Namespace: obj.Namespace,
}, pod)
if err != nil {
r.Log.Error(err, "fail to find pod")
return ctrl.Result{}, nil
}
failedMessage := ""
observedGeneration := obj.ObjectMeta.Generation
pid := obj.Status.Pid
startTime := obj.Status.StartTime
defer func() {
if err != nil {
failedMessage = err.Error()
}
updateError := retry.RetryOnConflict(retry.DefaultBackoff, func() error {
obj := &v1alpha1.PodIOChaos{}
if err := r.Client.Get(context.TODO(), req.NamespacedName, obj); err != nil {
r.Log.Error(err, "unable to get chaos")
return err
}
obj.Status.FailedMessage = failedMessage
obj.Status.ObservedGeneration = observedGeneration
obj.Status.Pid = pid
obj.Status.StartTime = startTime
return r.Client.Status().Update(context.TODO(), obj)
})
if updateError != nil {
r.Log.Error(updateError, "fail to update")
r.Recorder.Eventf(obj, "Normal", "Failed", "Failed to update status: %s", updateError.Error())
}
}()
pbClient, err := r.ChaosDaemonClientBuilder.Build(ctx, pod, &types.NamespacedName{
Namespace: obj.Namespace,
Name: obj.Name,
})
if err != nil {
r.Recorder.Event(obj, "Warning", "Failed", err.Error())
return ctrl.Result{Requeue: true}, nil
}
defer pbClient.Close()
if len(pod.Status.ContainerStatuses) == 0 {
err = errors.Wrapf(utils.ErrContainerNotFound, "pod %s/%s has empty container status", pod.Namespace, pod.Name)
r.Recorder.Event(obj, "Warning", "Failed", err.Error())
return ctrl.Result{}, nil
}
containerID := pod.Status.ContainerStatuses[0].ContainerID
if obj.Spec.Container != nil &&
len(strings.TrimSpace(*obj.Spec.Container)) != 0 {
containerID = ""
for _, container := range pod.Status.ContainerStatuses {
if container.Name == *obj.Spec.Container {
containerID = container.ContainerID
break
}
}
if len(containerID) == 0 {
err = errors.Errorf("cannot find container with name %s", *obj.Spec.Container)
r.Recorder.Event(obj, "Warning", "Failed", err.Error())
return ctrl.Result{}, nil
}
}
actions, err := json.Marshal(obj.Spec.Actions)
if err != nil {
r.Recorder.Event(obj, "Warning", "Failed", err.Error())
return ctrl.Result{Requeue: true}, nil
}
input := string(actions)
r.Log.Info("input with", "config", input)
res, err := pbClient.ApplyIOChaos(ctx, &pb.ApplyIOChaosRequest{
Actions: input,
Volume: obj.Spec.VolumeMountPath,
ContainerId: containerID,
Instance: obj.Status.Pid,
StartTime: obj.Status.StartTime,
EnterNS: true,
})
if err != nil {
err = errors.Wrapf(err, "failed to apply for pod %s/%s", pod.Namespace, pod.Name)
r.Recorder.Event(obj, "Warning", "Failed", err.Error())
return ctrl.Result{Requeue: true}, nil
}
startTime = res.StartTime
pid = res.Instance
return ctrl.Result{}, nil
}