-
Notifications
You must be signed in to change notification settings - Fork 4
/
crd_scenario.go
308 lines (244 loc) · 8.62 KB
/
crd_scenario.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/*
Copyright 2021-2023 ICS-FORTH.
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 v1alpha1
import (
"fmt"
"sort"
"strings"
"time"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/json"
)
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// Scenario is the Schema for the Scenarios API.
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type Scenario struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ScenarioSpec `json:"spec,omitempty"`
Status ScenarioStatus `json:"status,omitempty"`
}
func (in *Scenario) Table() (header []string, data [][]string) {
header = []string{
"Test",
"Scenario",
"Age",
"Actions",
"Phase",
"Duration",
}
var scheduled string
if in.Spec.Suspend != nil && *in.Spec.Suspend {
scheduled = fmt.Sprintf("%d/%d (Suspended)", len(in.Status.ScheduledJobs), len(in.Spec.Actions))
} else {
scheduled = fmt.Sprintf("%d/%d", len(in.Status.ScheduledJobs), len(in.Spec.Actions))
}
// age is the elapsed time since the test was created
age := time.Since(in.GetCreationTimestamp().Time)
if age < 0 {
scenariolog.Info("Time skew between Kubernetes Server and Controller.")
}
// duration is the elapsed time until the test was completed (either succeeded or failed).
// if the test is not yet completed, it is equal to the age.
duration := age
if meta.IsStatusConditionTrue(in.Status.Conditions, ConditionAllJobsAreCompleted.String()) {
cond := meta.FindStatusCondition(in.Status.Conditions, ConditionAllJobsAreCompleted.String())
duration = cond.LastTransitionTime.Sub(in.GetCreationTimestamp().Time)
}
if meta.IsStatusConditionTrue(in.Status.Conditions, ConditionJobUnexpectedTermination.String()) {
cond := meta.FindStatusCondition(in.Status.Conditions, ConditionJobUnexpectedTermination.String())
duration = cond.LastTransitionTime.Sub(in.GetCreationTimestamp().Time)
}
if meta.IsStatusConditionTrue(in.Status.Conditions, ConditionAssertionError.String()) {
cond := meta.FindStatusCondition(in.Status.Conditions, ConditionAssertionError.String())
duration = cond.LastTransitionTime.Sub(in.GetCreationTimestamp().Time)
}
data = append(data, []string{
in.GetNamespace(),
in.GetName(),
age.Round(time.Second).String(),
scheduled,
in.Status.Phase.String(),
duration.Round(time.Second).String(),
})
return header, data
}
type ActionType string
const (
// ActionService creates a new service.
ActionService ActionType = "Service"
// ActionCluster creates multiple services running in a shared context.
ActionCluster ActionType = "Cluster"
// ActionChaos injects failures into the running system.
ActionChaos ActionType = "Chaos"
// ActionCascade injects multiple failures into the running system.
ActionCascade ActionType = "Cascade"
// ActionDelete deletes a created Frisbee resource (i.e services, clusters,).
ActionDelete ActionType = "Delete"
// ActionCall starts a remote process execution, from the controller to the targeted services.
ActionCall ActionType = "Call"
)
// Action is a step in a workflow that defines a particular part of a testing process.
type Action struct {
// ActionType refers to a category of actions that can be associated with a specific controller.
// +kubebuilder:validation:Enum=Service;Cluster;Chaos;Cascade;Delete;Call
ActionType ActionType `json:"action"`
// Name is a unique identifier of the action
Name string `json:"name"`
// DependsOn defines the conditions for the execution of this action
// +optional
DependsOn *WaitSpec `json:"depends,omitempty"`
// Assert defines the conditions that must be maintained after the action has been started.
// If the evaluation of the condition is false, the Scenario will abort immediately.
// +optional
Assert *ConditionalExpr `json:"assert,omitempty"`
*EmbedActions `json:",inline"`
}
type WaitSpec struct {
// Running waits for the given groups to be running
// +optional
Running []string `json:"running,omitempty"`
// Success waits for the given groups to be succeeded
// +optional
Success []string `json:"success,omitempty"`
// After is the time offset since the beginning of this action.
// +optional
After *metav1.Duration `json:"after,omitempty"`
}
type DeleteSpec struct {
// Jobs is a list of jobs to be deleted. The format is {"kind":"name"}, e.g, {"service","client"}
Jobs []string `json:"jobs"`
}
type EmbedActions struct {
// +optional
Service *GenerateObjectFromTemplate `json:"service,omitempty"`
// +optional
Cluster *ClusterSpec `json:"cluster,omitempty"`
// +optional
Chaos *GenerateObjectFromTemplate `json:"chaos,omitempty"`
// +optional
Cascade *CascadeSpec `json:"cascade,omitempty"`
// +optional
Delete *DeleteSpec `json:"delete,omitempty"`
// +optional
Call *CallSpec `json:"call,omitempty"`
}
type TestdataVolume struct {
Claim v1.PersistentVolumeClaimVolumeSource `json:"volume,omitempty"`
// GlobalNamespace if disabled, all containers see the name root directory. If enabled, each container
// sees its own namespace.
// +optional
GlobalNamespace bool `json:"globalNamespace,omitempty"`
}
// ScenarioSpec defines the desired state of Scenario.
type ScenarioSpec struct {
// TestData defines a volume that will be mounted across the Scenario's Services.
TestData *TestdataVolume `json:"testData,omitempty"`
// Actions are the tasks that will be taken.
Actions []Action `json:"actions"`
// Suspend flag tells the controller to suspend subsequent executions, it does
// not apply to already started executions. Defaults to false.
// +optional
Suspend *bool `json:"suspend,omitempty"`
}
// ScenarioStatus defines the observed state of Scenario.
type ScenarioStatus struct {
Lifecycle `json:",inline"`
// ScheduledJobs is a list of references to the names of executed actions.
// +optional
ScheduledJobs []string `json:"scheduledJobs,omitempty"`
// GrafanaEndpoint points to the local Grafana instance
GrafanaEndpoint string `json:"grafanaEndpoint,omitempty"`
// PrometheusEndpoint points to the local Prometheus instance
PrometheusEndpoint string `json:"prometheusEndpoint,omitempty"`
// Dataviewer points to the local Dataviewer instance
DataviewerEndpoint string `json:"dataviewerEndpoint,omitempty"`
}
func (in *ScenarioStatus) Table() (header []string, data [][]string) {
header = []string{
"Phase",
"Reason",
"Message",
"Conditions",
}
// encode message to escape it
message, _ := json.Marshal(in.Message)
// encode conditions for better visualization
var conditions strings.Builder
{
if len(in.Conditions) > 0 {
for _, condition := range in.Conditions {
if condition.Status == metav1.ConditionTrue {
conditions.WriteString(condition.Type)
}
}
} else {
conditions.WriteString("\t----")
}
}
data = append(data, []string{
in.Phase.String(),
in.Reason,
string(message),
conditions.String(),
})
return header, data
}
func (in *Scenario) GetReconcileStatus() Lifecycle {
return in.Status.Lifecycle
}
func (in *Scenario) SetReconcileStatus(lifecycle Lifecycle) {
in.Status.Lifecycle = lifecycle
}
// +kubebuilder:object:root=true
// ScenarioList contains a list of Scenario.
type ScenarioList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Scenario `json:"items"`
}
func (in *ScenarioList) TestNames() []string {
testNames := make([]string, len(in.Items))
for i, scenario := range in.Items {
testNames[i] = scenario.GetNamespace()
}
return testNames
}
// Table returns a tabular form of the structure for pretty printing.
func (in *ScenarioList) Table() (header []string, data [][]string) {
header = []string{
"Test",
"Scenario",
"Age",
"Actions",
"Phase",
"Duration",
}
// arrange in descending order (latest created goes first)
sort.SliceStable(in.Items, func(i, j int) bool {
tsI := in.Items[i].GetCreationTimestamp()
tsJ := in.Items[j].GetCreationTimestamp()
return tsI.After(tsJ.Time)
})
for _, scenario := range in.Items {
_, scenarioData := scenario.Table()
data = append(data, scenarioData...)
}
return header, data
}
func init() {
SchemeBuilder.Register(&Scenario{}, &ScenarioList{})
}