/
work_creator.go
329 lines (276 loc) · 9.32 KB
/
work_creator.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
package pipeline
import (
"context"
"crypto/md5"
"fmt"
"io"
"os"
"path/filepath"
goerr "errors"
"slices"
ctrl "sigs.k8s.io/controller-runtime"
"github.com/syntasso/kratix/api/v1alpha1"
"github.com/syntasso/kratix/lib/hash"
"github.com/syntasso/kratix/lib/resourceutil"
"k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/controller-runtime/pkg/client"
)
type WorkCreator struct {
K8sClient client.Client
}
func (w *WorkCreator) Execute(rootDirectory, promiseName, namespace, resourceName, workflowType, pipelineName string) error {
identifier := fmt.Sprintf("%s-%s", promiseName, resourceName)
if workflowType == string(v1alpha1.WorkflowTypePromise) {
identifier = promiseName
}
if namespace == "" {
namespace = "kratix-platform-system"
}
var logger = ctrl.Log.WithName("work-creator").
WithValues("identifier", identifier).
WithValues("workName", identifier).
WithValues("namespace", namespace).
WithValues("resourceName", resourceName).
WithValues("promiseName", promiseName).
WithValues("pipelineName", pipelineName)
workflowScheduling, err := w.getWorkflowScheduling(rootDirectory)
if err != nil {
return err
}
var workloadGroups []v1alpha1.WorkloadGroup
var directoriesToIgnoreForTheBaseScheduling []string
var defaultDestinationSelectors map[string]string
pipelineOutputDir := filepath.Join(rootDirectory, "input")
for _, workflowDestinationSelector := range workflowScheduling {
directory := workflowDestinationSelector.Directory
if !isRootDirectory(directory) {
directoriesToIgnoreForTheBaseScheduling = append(directoriesToIgnoreForTheBaseScheduling, directory)
workloads, err := w.getWorkloadsFromDir(pipelineOutputDir, filepath.Join(pipelineOutputDir, directory), nil)
if err != nil {
return err
}
workloadGroups = append(workloadGroups, v1alpha1.WorkloadGroup{
Workloads: workloads,
Directory: directory,
ID: fmt.Sprintf("%x", md5.Sum([]byte(directory))),
DestinationSelectors: []v1alpha1.WorkloadGroupScheduling{
{
MatchLabels: workflowDestinationSelector.MatchLabels,
Source: workflowType + "-" + "workflow",
},
},
})
} else {
defaultDestinationSelectors = workflowDestinationSelector.MatchLabels
}
}
workloads, err := w.getWorkloadsFromDir(pipelineOutputDir, pipelineOutputDir, directoriesToIgnoreForTheBaseScheduling)
if err != nil {
return err
}
if len(workloads) > 0 {
defaultWorkloadGroup := v1alpha1.WorkloadGroup{
Workloads: workloads,
Directory: v1alpha1.DefaultWorkloadGroupDirectory,
ID: hash.ComputeHash(v1alpha1.DefaultWorkloadGroupDirectory),
}
if defaultDestinationSelectors != nil {
defaultWorkloadGroup.DestinationSelectors = []v1alpha1.WorkloadGroupScheduling{
{
MatchLabels: defaultDestinationSelectors,
Source: workflowType + "-" + "workflow",
},
}
}
destinationSelectors, err := w.getPromiseScheduling(rootDirectory)
if err != nil {
return err
}
if len(destinationSelectors) > 0 {
p := []v1alpha1.PromiseScheduling{}
pw := []v1alpha1.PromiseScheduling{}
for _, selector := range destinationSelectors {
switch selector.Source {
case "promise":
p = append(p, v1alpha1.PromiseScheduling{
MatchLabels: selector.MatchLabels,
})
case "promise-workflow":
pw = append(pw, v1alpha1.PromiseScheduling{
MatchLabels: selector.MatchLabels,
})
}
}
if len(pw) > 0 {
defaultWorkloadGroup.DestinationSelectors = append(defaultWorkloadGroup.DestinationSelectors, v1alpha1.WorkloadGroupScheduling{
MatchLabels: v1alpha1.SquashPromiseScheduling(pw),
Source: "promise-workflow",
})
}
if len(p) > 0 {
defaultWorkloadGroup.DestinationSelectors = append(
defaultWorkloadGroup.DestinationSelectors,
v1alpha1.WorkloadGroupScheduling{
MatchLabels: v1alpha1.SquashPromiseScheduling(p),
Source: "promise",
},
)
}
}
workloadGroups = append(workloadGroups, defaultWorkloadGroup)
}
work := &v1alpha1.Work{}
work.Name = resourceutil.GenerateObjectName(identifier)
work.Namespace = namespace
work.Spec.Replicas = v1alpha1.ResourceRequestReplicas
work.Spec.WorkloadGroups = workloadGroups
work.Spec.PromiseName = promiseName
work.Spec.ResourceName = resourceName
work.Labels = map[string]string{}
resourceutil.SetResourceWorkLabels(work.Labels, promiseName, resourceName, pipelineName)
if workflowType == string(v1alpha1.WorkflowTypePromise) {
work.Namespace = v1alpha1.SystemNamespace
work.Spec.Replicas = v1alpha1.DependencyReplicas
work.Spec.ResourceName = ""
work.Labels = v1alpha1.GenerateSharedLabelsForPromise(promiseName)
resourceutil.SetPromiseWorkLabels(work.Labels, promiseName, pipelineName)
}
var currentWork *v1alpha1.Work
if resourceName == "" {
currentWork, err = resourceutil.GetWorkForPromisePipeline(w.K8sClient, namespace, promiseName, pipelineName)
} else {
currentWork, err = resourceutil.GetWorkForResourcePipeline(w.K8sClient, namespace, promiseName, resourceName, pipelineName)
}
if err != nil {
return err
}
if currentWork == nil {
err := w.K8sClient.Create(context.Background(), work)
if err != nil {
return err
}
logger.Info("Work created", "workName", work.Name)
return nil
}
logger.Info("Work already exists, will update")
currentWork.Spec = work.Spec
err = w.K8sClient.Update(context.Background(), currentWork)
if err != nil {
logger.Error(err, "Error updating Work")
return err
}
logger.Info("Work updated", "workName", currentWork.Name)
return nil
}
// /kratix/output/ /kratix/output/ "bar"
func (w *WorkCreator) getWorkloadsFromDir(prefixToTrimFromWorkloadFilepath, rootDir string, directoriesToIgnoreAtTheRootLevel []string) ([]v1alpha1.Workload, error) {
filesAndDirs, err := os.ReadDir(rootDir)
if err != nil {
return nil, err
}
workloads := []v1alpha1.Workload{}
for _, info := range filesAndDirs {
// TODO: currently we assume everything is a file or a dir, we don't handle
// more advanced scenarios, e.g. symlinks, file sizes, file permissions etc
if info.IsDir() {
if !slices.Contains(directoriesToIgnoreAtTheRootLevel, info.Name()) {
dir := filepath.Join(rootDir, info.Name())
newWorkloads, err := w.getWorkloadsFromDir(prefixToTrimFromWorkloadFilepath, dir, nil)
if err != nil {
return nil, err
}
workloads = append(workloads, newWorkloads...)
}
} else {
filePath := filepath.Join(rootDir, info.Name())
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
byteValue, err := io.ReadAll(file)
if err != nil {
return nil, err
}
// trim /kratix/output/ from the filepath
path, err := filepath.Rel(prefixToTrimFromWorkloadFilepath, filePath)
if err != nil {
return nil, err
}
workload := v1alpha1.Workload{
Content: string(byteValue),
Filepath: path,
}
workloads = append(workloads, workload)
}
}
return workloads, nil
}
func (w *WorkCreator) getWorkflowScheduling(rootDirectory string) ([]v1alpha1.WorkflowDestinationSelectors, error) {
metadataDirectory := filepath.Join(rootDirectory, "metadata")
return getSelectorsFromFile(filepath.Join(metadataDirectory, "destination-selectors.yaml"))
}
func (w *WorkCreator) getPromiseScheduling(rootDirectory string) ([]v1alpha1.WorkloadGroupScheduling, error) {
kratixSystemDirectory := filepath.Join(rootDirectory, "kratix-system")
file := filepath.Join(kratixSystemDirectory, "promise-scheduling")
fileContents, err := os.ReadFile(file)
if err != nil {
if goerr.Is(err, os.ErrNotExist) {
return nil, nil
}
return nil, err
}
var schedulingConfig []v1alpha1.WorkloadGroupScheduling
err = yaml.Unmarshal(fileContents, &schedulingConfig)
if err != nil {
return nil, err
}
return schedulingConfig, nil
}
func getSelectorsFromFile(file string) ([]v1alpha1.WorkflowDestinationSelectors, error) {
fileContents, err := os.ReadFile(file)
if err != nil {
if goerr.Is(err, os.ErrNotExist) {
return nil, nil
}
return nil, err
}
var schedulingConfig []v1alpha1.WorkflowDestinationSelectors
err = yaml.Unmarshal(fileContents, &schedulingConfig)
if err != nil {
return nil, err
}
for i := range schedulingConfig {
schedulingConfig[i].Directory = filepath.Clean(schedulingConfig[i].Directory)
}
if containsDuplicateScheduling(schedulingConfig) {
err = fmt.Errorf("duplicate entries in destination-selectors.yaml: \n%v", schedulingConfig)
return nil, err
}
if path, found := containsNonRootDirectory(schedulingConfig); found {
return nil, fmt.Errorf("invalid directory in destination-selectors.yaml: %s, directory must be top-level", path)
}
return schedulingConfig, nil
}
func containsNonRootDirectory(schedulingConfig []v1alpha1.WorkflowDestinationSelectors) (string, bool) {
for _, selector := range schedulingConfig {
directory := selector.Directory
if filepath.Base(directory) != directory {
return directory, true
}
}
return "", false
}
func containsDuplicateScheduling(schedulingConfig []v1alpha1.WorkflowDestinationSelectors) bool {
directoriesSeen := []string{}
for _, selector := range schedulingConfig {
if slices.Contains(directoriesSeen, selector.Directory) {
return true
}
directoriesSeen = append(directoriesSeen, selector.Directory)
}
return false
}
// Assumes Dir has already been filepath.Clean'd
func isRootDirectory(dir string) bool {
return dir == v1alpha1.DefaultWorkloadGroupDirectory
}