-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathcontroller.go
246 lines (235 loc) · 10.1 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* 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 container
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/chaosblade-io/chaosblade-exec-cri/exec/container"
"github.com/chaosblade-io/chaosblade-spec-go/util"
"github.com/sirupsen/logrus"
"k8s.io/api/core/v1"
"github.com/chaosblade-io/chaosblade-spec-go/spec"
"github.com/chaosblade-io/chaosblade-operator/channel"
"github.com/chaosblade-io/chaosblade-operator/exec/model"
"github.com/chaosblade-io/chaosblade-operator/pkg/apis/chaosblade/v1alpha1"
)
type ExpController struct {
model.BaseExperimentController
}
func NewExpController(client *channel.Client) model.ExperimentController {
return &ExpController{
model.BaseExperimentController{
Client: client,
ResourceModelSpec: NewResourceModelSpec(client),
},
}
}
func (*ExpController) Name() string {
return "container"
}
// Create an experiment about container
func (e *ExpController) Create(ctx context.Context, expSpec v1alpha1.ExperimentSpec) *spec.Response {
expModel := model.ExtractExpModelFromExperimentSpec(expSpec)
// priority: id > name > index
containerIdsValue := strings.TrimSpace(expModel.ActionFlags[model.ContainerIdsFlag.Name])
containerNamesValue := strings.TrimSpace(expModel.ActionFlags[model.ContainerNamesFlag.Name])
containerIndexValue := strings.TrimSpace(expModel.ActionFlags[model.ContainerIndexFlag.Name])
experimentId := model.GetExperimentIdFromContext(ctx)
logrusField := logrus.WithField("experiment", experimentId).WithField("location", util.GetRunFuncName())
lessParameter := fmt.Sprintf("%s|%s|%s", model.ContainerIdsFlag.Name, model.ContainerNamesFlag.Name, model.ContainerIndexFlag.Name)
if containerIdsValue == "" && containerNamesValue == "" && containerIndexValue == "" {
errMsg := spec.ParameterLess.Sprintf(lessParameter)
logrusField.Errorln(errMsg)
return spec.ResponseFailWithResult(spec.ParameterLess, v1alpha1.CreateFailExperimentStatus(errMsg, nil), lessParameter)
}
pods, resp := e.GetMatchedPodResources(ctx, *expModel)
if !resp.Success {
logrusField.Errorf("uid: %s, get matched pod resources failed, %v", experimentId, resp.Err)
resp.Result = v1alpha1.CreateFailExperimentStatus(resp.Err, []v1alpha1.ResourceStatus{})
return resp
}
containerObjectMetaList, resp := getMatchedContainerMetaList(pods, containerIdsValue, containerNamesValue, containerIndexValue)
if !resp.Success {
logrusField.Errorf("get matched container meta list failed, %v", resp.Err)
resp.Result = v1alpha1.CreateFailExperimentStatus(resp.Err, []v1alpha1.ResourceStatus{})
return resp
}
if len(containerObjectMetaList) == 0 {
// TODO need to optimize
errMsg := spec.ParameterInvalid.Sprintf(
strings.Join([]string{model.ContainerIdsFlag.Name, model.ContainerNamesFlag.Name, model.ContainerIndexFlag.Name}, "|"),
strings.Join([]string{containerIdsValue, containerNamesValue, containerIndexValue}, "|"),
"cannot find the containers")
logrusField.Errorln(errMsg)
response := spec.ResponseFailWithResult(
spec.ParameterInvalid,
v1alpha1.CreateFailExperimentStatus(errMsg, []v1alpha1.ResourceStatus{}),
strings.Join([]string{model.ContainerIdsFlag.Name, model.ContainerNamesFlag.Name, model.ContainerIndexFlag.Name}, "|"),
strings.Join([]string{containerIdsValue, containerNamesValue, containerIndexValue}, "|"),
"cannot find the containers")
return response
}
ctx = model.SetContainerObjectMetaListToContext(ctx, containerObjectMetaList)
return e.Exec(ctx, expModel)
}
// Destroy
func (e *ExpController) Destroy(ctx context.Context, expSpec v1alpha1.ExperimentSpec, oldExpStatus v1alpha1.ExperimentStatus) *spec.Response {
logrus.WithField("experiment", model.GetExperimentIdFromContext(ctx)).WithField("location", util.GetRunFuncName()).Infof("start to destroy")
expModel := model.ExtractExpModelFromExperimentSpec(expSpec)
statuses := oldExpStatus.ResStatuses
if statuses == nil {
return spec.ReturnSuccess(v1alpha1.CreateSuccessExperimentStatus([]v1alpha1.ResourceStatus{}))
}
containerObjectMetaList := model.ContainerMatchedList{}
for _, status := range statuses {
if !status.Success {
// does not need to destroy
continue
}
containerObjectMeta := model.ParseIdentifier(status.Identifier)
containerObjectMeta.Id = status.Id
containerObjectMetaList = append(containerObjectMetaList, containerObjectMeta)
}
if len(containerObjectMetaList) == 0 {
return spec.ReturnSuccess(v1alpha1.CreateSuccessExperimentStatus(statuses))
}
ctx = model.SetContainerObjectMetaListToContext(ctx, containerObjectMetaList)
return e.Exec(ctx, expModel)
}
// getMatchedContainerMetaList which will be used in the executor
func getMatchedContainerMetaList(pods []v1.Pod, containerIdsValue, containerNamesValue, containerIndexValue string) (
model.ContainerMatchedList, *spec.Response) {
containerObjectMetaList := model.ContainerMatchedList{}
expectedContainerIds := strings.Split(containerIdsValue, ",")
expectedContainerNames := strings.Split(containerNamesValue, ",")
// priority id>name>index
for _, pod := range pods {
containerStatuses := pod.Status.ContainerStatuses
if containerStatuses == nil {
continue
}
var containerStatusErr error
for _, containerStatus := range containerStatuses {
// If target container's status is not running, the containerId can not be obtained
// The container's status should be checked and return err if not running
var containerRuntime, containerId string
containerName := containerStatus.Name
if containerStatus.ContainerID == "" {
containerStatusErr = errors.New("containerId is empty")
} else {
containerRuntime, containerId = model.TruncateContainerObjectMetaUid(containerStatus.ContainerID)
if containerRuntime == container.DockerRuntime {
containerId = containerId[:12]
}
}
if containerStatus.State.Running == nil {
if containerStatusErr != nil {
containerStatusErr = errors.New("is not running, " + containerStatusErr.Error())
} else {
containerStatusErr = errors.New("is not running, containerId: " + containerStatus.ContainerID)
}
}
if containerIdsValue != "" {
for _, expectedContainerId := range expectedContainerIds {
if expectedContainerId == "" {
continue
}
if strings.HasPrefix(expectedContainerId, containerId) {
if containerStatusErr != nil {
return containerObjectMetaList, spec.ResponseFailWithFlags(spec.ParameterInvalid,
model.ContainerIdsFlag.Name, expectedContainerId,
fmt.Sprintf("container: %s %s", containerName, containerStatusErr.Error()))
}
containerObjectMetaList = append(containerObjectMetaList, model.ContainerObjectMeta{
ContainerRuntime: containerRuntime,
ContainerId: containerId,
ContainerName: containerName,
PodName: pod.Name,
Namespace: pod.Namespace,
NodeName: pod.Spec.NodeName,
})
}
}
} else if containerNamesValue != "" {
for _, expectedName := range expectedContainerNames {
if expectedName == "" {
continue
}
if expectedName == containerName {
// matched
if containerStatusErr != nil {
return containerObjectMetaList, spec.ResponseFailWithFlags(spec.ParameterInvalid,
model.ContainerNamesFlag.Name, expectedName,
fmt.Sprintf("container: %s %s", containerName, containerStatusErr.Error()))
}
containerObjectMetaList = append(containerObjectMetaList, model.ContainerObjectMeta{
ContainerRuntime: containerRuntime,
ContainerId: containerId,
ContainerName: containerName,
PodName: pod.Name,
Namespace: pod.Namespace,
NodeName: pod.Spec.NodeName,
})
}
}
}
}
if containerIdsValue == "" && containerNamesValue == "" && containerIndexValue != "" {
idx, err := strconv.Atoi(containerIndexValue)
if err != nil {
return containerObjectMetaList,
spec.ResponseFailWithFlags(spec.ParameterIllegal, model.ContainerIndexFlag.Name, containerIndexValue, err)
}
if idx > len(containerStatuses)-1 {
return containerObjectMetaList,
spec.ResponseFailWithFlags(spec.ParameterIllegal, model.ContainerIndexFlag.Name, containerIndexValue, "out of bound")
}
// If target container's status is not running, the containerId can not be obtained
// The container's status should be checked and return err if not running
if containerStatuses[idx].ContainerID == "" {
containerStatusErr = errors.New("containerId is empty")
}
if containerStatuses[idx].State.Running == nil {
if containerStatusErr != nil {
containerStatusErr = errors.New("is not running, " + containerStatusErr.Error())
} else {
containerStatusErr = errors.New("is not running, containerId: " + containerStatuses[idx].ContainerID)
}
}
if containerStatusErr != nil {
return containerObjectMetaList, spec.ResponseFailWithFlags(spec.ParameterInvalid,
model.ContainerIndexFlag.Name, idx,
fmt.Sprintf("container: %s %s", containerStatuses[idx].Name, containerStatusErr.Error()))
}
containerRuntime, containerId := model.TruncateContainerObjectMetaUid(containerStatuses[idx].ContainerID)
if containerRuntime == container.DockerRuntime {
containerId = containerId[:12]
}
containerObjectMetaList = append(containerObjectMetaList, model.ContainerObjectMeta{
ContainerRuntime: containerRuntime,
ContainerId: containerId,
ContainerName: containerStatuses[idx].Name,
PodName: pod.Name,
Namespace: pod.Namespace,
NodeName: pod.Spec.NodeName,
})
}
}
return containerObjectMetaList, spec.Success()
}