/
matrix_types.go
362 lines (329 loc) · 12.6 KB
/
matrix_types.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*
Copyright 2023 The Tekton 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 v1beta1
import (
"context"
"fmt"
"sort"
"github.com/tektoncd/pipeline/pkg/apis/config"
"golang.org/x/exp/maps"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/utils/strings/slices"
"knative.dev/pkg/apis"
)
// Matrix is used to fan out Tasks in a Pipeline
type Matrix struct {
// Params is a list of parameters used to fan out the pipelineTask
// Params takes only `Parameters` of type `"array"`
// Each array element is supplied to the `PipelineTask` by substituting `params` of type `"string"` in the underlying `Task`.
// The names of the `params` in the `Matrix` must match the names of the `params` in the underlying `Task` that they will be substituting.
// +listType=atomic
Params Params `json:"params,omitempty"`
// Include is a list of IncludeParams which allows passing in specific combinations of Parameters into the Matrix.
// +optional
// +listType=atomic
Include IncludeParamsList `json:"include,omitempty"`
}
// IncludeParamsList is a list of IncludeParams which allows passing in specific combinations of Parameters into the Matrix.
type IncludeParamsList []IncludeParams
// IncludeParams allows passing in a specific combinations of Parameters into the Matrix.
type IncludeParams struct {
// Name the specified combination
Name string `json:"name,omitempty"`
// Params takes only `Parameters` of type `"string"`
// The names of the `params` must match the names of the `params` in the underlying `Task`
// +listType=atomic
Params Params `json:"params,omitempty"`
}
// Combination is a map, mainly defined to hold a single combination from a Matrix with key as param.Name and value as param.Value
type Combination map[string]string
// Combinations is a Combination list
type Combinations []Combination
// FanOut returns an list of params that represent combinations
func (m *Matrix) FanOut() []Params {
var combinations, includeCombinations Combinations
includeCombinations = m.getIncludeCombinations()
if m.HasInclude() && !m.HasParams() {
// If there are only Matrix Include Parameters return explicit combinations
return includeCombinations.toParams()
}
// Generate combinations from Matrix Parameters
for _, parameter := range m.Params {
combinations = combinations.fanOutMatrixParams(parameter)
}
combinations.overwriteCombinations(includeCombinations)
combinations = combinations.addNewCombinations(includeCombinations)
return combinations.toParams()
}
// overwriteCombinations replaces any missing include params in the initial
// matrix params combinations by overwriting the initial combinations with the
// include combinations
func (cs Combinations) overwriteCombinations(ics Combinations) {
for _, paramCombination := range cs {
for _, includeCombination := range ics {
if paramCombination.contains(includeCombination) {
// overwrite the parameter name and value in existing combination
// with the include combination
for name, val := range includeCombination {
paramCombination[name] = val
}
}
}
}
}
// addNewCombinations creates a new combination for any include parameter
// values that are missing entirely from the initial combinations and
// returns all combinations
func (cs Combinations) addNewCombinations(ics Combinations) Combinations {
for _, includeCombination := range ics {
if cs.shouldAddNewCombination(includeCombination) {
cs = append(cs, includeCombination)
}
}
return cs
}
// contains returns true if the include parameter name and value exists in combinations
func (c Combination) contains(includeCombination Combination) bool {
for name, val := range includeCombination {
if _, exist := c[name]; exist {
if c[name] != val {
return false
}
}
}
return true
}
// shouldAddNewCombination returns true if the include parameter name exists but the value is
// missing from combinations
func (cs Combinations) shouldAddNewCombination(includeCombination map[string]string) bool {
if len(includeCombination) == 0 {
return false
}
for _, paramCombination := range cs {
for name, val := range includeCombination {
if _, exist := paramCombination[name]; exist {
if paramCombination[name] == val {
return false
}
}
}
}
return true
}
// toParams transforms Combinations from a slice of map[string]string to a slice of Params
// such that, these combinations can be directly consumed in creating taskRun/run object
func (cs Combinations) toParams() []Params {
listOfParams := make([]Params, len(cs))
for i := range cs {
var params Params
combination := cs[i]
order, _ := combination.sortCombination()
for _, key := range order {
params = append(params, Param{
Name: key,
Value: ParamValue{Type: ParamTypeString, StringVal: combination[key]},
})
}
listOfParams[i] = params
}
return listOfParams
}
// fanOutMatrixParams generates new combinations based on Matrix Parameters.
func (cs Combinations) fanOutMatrixParams(param Param) Combinations {
if len(cs) == 0 {
return initializeCombinations(param)
}
return cs.distribute(param)
}
// getIncludeCombinations generates combinations based on Matrix Include Parameters
func (m *Matrix) getIncludeCombinations() Combinations {
var combinations Combinations
for i := range m.Include {
includeParams := m.Include[i].Params
newCombination := make(Combination)
for _, param := range includeParams {
newCombination[param.Name] = param.Value.StringVal
}
combinations = append(combinations, newCombination)
}
return combinations
}
// distribute generates a new Combination of Parameters by adding a new Parameter to an existing list of Combinations.
func (cs Combinations) distribute(param Param) Combinations {
var expandedCombinations Combinations
for _, value := range param.Value.ArrayVal {
for _, combination := range cs {
newCombination := make(Combination)
maps.Copy(newCombination, combination)
newCombination[param.Name] = value
_, orderedCombination := newCombination.sortCombination()
expandedCombinations = append(expandedCombinations, orderedCombination)
}
}
return expandedCombinations
}
// initializeCombinations generates a new Combination based on the first Parameter in the Matrix.
func initializeCombinations(param Param) Combinations {
var combinations Combinations
for _, value := range param.Value.ArrayVal {
combinations = append(combinations, Combination{param.Name: value})
}
return combinations
}
// sortCombination sorts the given Combination based on the Parameter names to produce a deterministic ordering
func (c Combination) sortCombination() ([]string, Combination) {
sortedCombination := make(Combination, len(c))
order := make([]string, 0, len(c))
for key := range c {
order = append(order, key)
}
sort.Slice(order, func(i, j int) bool {
return order[i] <= order[j]
})
for _, key := range order {
sortedCombination[key] = c[key]
}
return order, sortedCombination
}
// CountCombinations returns the count of Combinations of Parameters generated from the Matrix in PipelineTask.
func (m *Matrix) CountCombinations() int {
// Iterate over Matrix Parameters and compute count of all generated Combinations
count := m.countGeneratedCombinationsFromParams()
// Add any additional Combinations generated from Matrix Include Parameters
count += m.countNewCombinationsFromInclude()
return count
}
// countGeneratedCombinationsFromParams returns the count of Combinations of Parameters generated from the Matrix
// Parameters
func (m *Matrix) countGeneratedCombinationsFromParams() int {
if !m.HasParams() {
return 0
}
count := 1
for _, param := range m.Params {
count *= len(param.Value.ArrayVal)
}
return count
}
// countNewCombinationsFromInclude returns the count of Combinations of Parameters generated from the Matrix
// Include Parameters
func (m *Matrix) countNewCombinationsFromInclude() int {
if !m.HasInclude() {
return 0
}
if !m.HasParams() {
return len(m.Include)
}
count := 0
matrixParamMap := m.Params.extractParamMapArrVals()
for _, include := range m.Include {
for _, param := range include.Params {
if val, exist := matrixParamMap[param.Name]; exist {
// If the Matrix Include param values does not exist, a new Combination will be generated
if !slices.Contains(val, param.Value.StringVal) {
count++
} else {
break
}
}
}
}
return count
}
// HasInclude returns true if the Matrix has Include Parameters
func (m *Matrix) HasInclude() bool {
return m != nil && m.Include != nil && len(m.Include) > 0
}
// HasParams returns true if the Matrix has Parameters
func (m *Matrix) HasParams() bool {
return m != nil && m.Params != nil && len(m.Params) > 0
}
// GetAllParams returns a list of all Matrix Parameters
func (m *Matrix) GetAllParams() Params {
var params Params
if m.HasParams() {
params = append(params, m.Params...)
}
if m.HasInclude() {
for _, include := range m.Include {
params = append(params, include.Params...)
}
}
return params
}
func (m *Matrix) validateCombinationsCount(ctx context.Context) (errs *apis.FieldError) {
matrixCombinationsCount := m.CountCombinations()
maxMatrixCombinationsCount := config.FromContextOrDefaults(ctx).Defaults.DefaultMaxMatrixCombinationsCount
if matrixCombinationsCount > maxMatrixCombinationsCount {
errs = errs.Also(apis.ErrOutOfBoundsValue(matrixCombinationsCount, 0, maxMatrixCombinationsCount, "matrix"))
}
return errs
}
// validateParams validates the type of Parameter for Matrix.Params and Matrix.Include.Params
// Matrix.Params must be of type array. Matrix.Include.Params must be of type string.
// validateParams also validates Matrix.Params for a unique list of params
// and a unique list of params in each Matrix.Include.Params specification
func (m *Matrix) validateParams() (errs *apis.FieldError) {
if m != nil {
if m.HasInclude() {
for i, include := range m.Include {
errs = errs.Also(include.Params.validateDuplicateParameters().ViaField(fmt.Sprintf("matrix.include[%d].params", i)))
for _, param := range include.Params {
if param.Value.Type != ParamTypeString {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("parameters of type string only are allowed, but got param type %s", string(param.Value.Type)), "").ViaFieldKey("matrix.include.params", param.Name))
}
}
}
}
if m.HasParams() {
errs = errs.Also(m.Params.validateDuplicateParameters().ViaField("matrix.params"))
for _, param := range m.Params {
if param.Value.Type != ParamTypeArray {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("parameters of type array only are allowed, but got param type %s", string(param.Value.Type)), "").ViaFieldKey("matrix.params", param.Name))
}
}
}
}
return errs
}
// validatePipelineParametersVariablesInMatrixParameters validates all pipeline parameter variables including Matrix.Params and Matrix.Include.Params
// that may contain the reference(s) to other params to make sure those references are used appropriately.
func (m *Matrix) validatePipelineParametersVariablesInMatrixParameters(prefix string, paramNames sets.String, arrayParamNames sets.String, objectParamNameKeys map[string][]string) (errs *apis.FieldError) {
if m.HasInclude() {
for _, include := range m.Include {
for idx, param := range include.Params {
stringElement := param.Value.StringVal
// Matrix Include Params must be of type string
errs = errs.Also(validateStringVariable(stringElement, prefix, paramNames, arrayParamNames, objectParamNameKeys).ViaFieldIndex("", idx).ViaField("matrix.include.params", ""))
}
}
}
if m.HasParams() {
for _, param := range m.Params {
for idx, arrayElement := range param.Value.ArrayVal {
// Matrix Params must be of type array
errs = errs.Also(validateArrayVariable(arrayElement, prefix, paramNames, arrayParamNames, objectParamNameKeys).ViaFieldIndex("value", idx).ViaFieldKey("matrix.params", param.Name))
}
}
}
return errs
}
func (m *Matrix) validateParameterInOneOfMatrixOrParams(params Params) (errs *apis.FieldError) {
matrixParamNames := m.GetAllParams().ExtractNames()
for _, param := range params {
if matrixParamNames.Has(param.Name) {
errs = errs.Also(apis.ErrMultipleOneOf("matrix["+param.Name+"]", "params["+param.Name+"]"))
}
}
return errs
}