-
Notifications
You must be signed in to change notification settings - Fork 784
/
step_create_task.go
359 lines (324 loc) · 10.1 KB
/
step_create_task.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
package cmd
import (
"fmt"
"github.com/ghodss/yaml"
"github.com/jenkins-x/jx/pkg/config"
"github.com/jenkins-x/jx/pkg/jenkinsfile"
"github.com/jenkins-x/jx/pkg/jenkinsfile/gitresolver"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
buildapi "github.com/knative/build/pkg/apis/build/v1alpha1"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1/terminal"
"io"
"io/ioutil"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"os"
"path/filepath"
"strings"
)
var (
createTaskLong = templates.LongDesc(`
Creates a Knative Pipeline Task for a project
`)
createTaskExample = templates.Examples(`
# create a Knative Pipeline Task and render to the console
jx step create task
# create a Knative Pipeline Task
jx step create task -o mybuild.yaml
`)
)
// StepCreateTaskOptions contains the command line flags
type StepCreateTaskOptions struct {
StepOptions
Pack string
Dir string
OutputFile string
BuildPackURL string
BuildPackRef string
PipelineKind string
PodTemplates map[string]*corev1.Pod
MissingPodTemplates map[string]bool
}
// NewCmdStepCreateTask Creates a new Command object
func NewCmdStepCreateTask(f Factory, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) *cobra.Command {
options := &StepCreateTaskOptions{
StepOptions: StepOptions{
CommonOptions: CommonOptions{
Factory: f,
In: in,
Out: out,
Err: errOut,
},
},
}
cmd := &cobra.Command{
Use: "task",
Short: "Creates a Knative Pipeline Task for the current folder or given build pack",
Long: createTaskLong,
Example: createTaskExample,
Aliases: []string{"bt"},
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
options.addCommonFlags(cmd)
cmd.Flags().StringVarP(&options.Dir, "dir", "d", "", "The directory to query to find the projects .git directory")
cmd.Flags().StringVarP(&options.OutputFile, "output", "o", "", "The output file to write the output to as YAML")
cmd.Flags().StringVarP(&options.BuildPackURL, "url", "u", "", "The URL for the build pack Git repository")
cmd.Flags().StringVarP(&options.BuildPackRef, "ref", "r", "", "The Git reference (branch,tag,sha) in the Git repository to use")
cmd.Flags().StringVarP(&options.Pack, "pack", "p", "", "The build pack name. If none is specified its discovered from the source code")
cmd.Flags().StringVarP(&options.PipelineKind, "kind", "k", "release", "The kind of pipeline to create such as: "+strings.Join(jenkinsfile.PipelineKinds, ", "))
return cmd
}
// Run implements this command
func (o *StepCreateTaskOptions) Run() error {
settings, err := o.TeamSettings()
if err != nil {
return err
}
if o.BuildPackURL == "" || o.BuildPackRef == "" {
if o.BuildPackURL == "" {
o.BuildPackURL = settings.BuildPackURL
}
if o.BuildPackRef == "" {
o.BuildPackRef = settings.BuildPackRef
}
}
if o.BuildPackURL == "" {
return util.MissingOption("url")
}
if o.BuildPackRef == "" {
return util.MissingOption("ref")
}
if o.PipelineKind == "" {
return util.MissingOption("kind")
}
if o.Dir == "" {
o.Dir, err = os.Getwd()
if err != nil {
return err
}
}
projectConfig, projectConfigFile, err := config.LoadProjectConfig(o.Dir)
if err != nil {
return errors.Wrapf(err, "failed to load project config in dir %s", o.Dir)
}
if o.Pack == "" {
o.Pack = projectConfig.BuildPack
}
if o.Pack == "" {
o.Pack, err = o.discoverBuildPack(o.Dir, projectConfig)
}
if o.Pack == "" {
return util.MissingOption("pack")
}
err = o.loadPodTemplates()
if err != nil {
return err
}
o.MissingPodTemplates = map[string]bool{}
packsDir, err := gitresolver.InitBuildPack(o.Git(), o.BuildPackURL, o.BuildPackRef)
if err != nil {
return err
}
resolver, err := gitresolver.CreateResolver(packsDir, o.Git())
if err != nil {
return err
}
name := o.Pack
packDir := filepath.Join(packsDir, name)
pipelineFile := filepath.Join(packDir, jenkinsfile.PipelineConfigFileName)
exists, err := util.FileExists(pipelineFile)
if err != nil {
return errors.Wrapf(err, "failed to find build pack pipeline YAML: %s", pipelineFile)
}
if !exists {
return fmt.Errorf("no build pack for %s exists at directory %s", name, packDir)
}
jenkinsfileRunner := true
pipelineConfig, err := jenkinsfile.LoadPipelineConfig(pipelineFile, resolver, jenkinsfileRunner)
if err != nil {
return errors.Wrapf(err, "failed to load build pack pipeline YAML: %s", pipelineFile)
}
localPipelineConfig := projectConfig.PipelineConfig
if localPipelineConfig != nil {
err = localPipelineConfig.ExtendPipeline(pipelineConfig, jenkinsfileRunner)
if err != nil {
return errors.Wrapf(err, "failed to override PipelineConfig using configuration in file %s", projectConfigFile)
}
pipelineConfig = localPipelineConfig
}
err = o.generateTask(name, pipelineConfig)
if err != nil {
return errors.Wrapf(err, "failed to generate Task for build pack pipeline YAML: %s", pipelineFile)
}
return err
}
func (o *StepCreateTaskOptions) loadPodTemplates() error {
o.PodTemplates = map[string]*corev1.Pod{}
kubeClient, ns, err := o.KubeClientAndDevNamespace()
if err != nil {
return err
}
configMapName := kube.ConfigMapJenkinsPodTemplates
cm, err := kubeClient.CoreV1().ConfigMaps(ns).Get(configMapName, metav1.GetOptions{})
if err != nil {
return err
}
for k, v := range cm.Data {
pod := &corev1.Pod{}
if v != "" {
err := yaml.Unmarshal([]byte(v), pod)
if err != nil {
return err
}
o.PodTemplates[k] = pod
}
}
return nil
}
func (o *StepCreateTaskOptions) generateTask(name string, pipelineConfig *jenkinsfile.PipelineConfig) error {
var lifecycles *jenkinsfile.PipelineLifecycles
kind := o.PipelineKind
pipelines := pipelineConfig.Pipelines
switch kind {
case jenkinsfile.PipelineKindRelease:
lifecycles = pipelines.Release
case jenkinsfile.PipelineKindPullRequest:
lifecycles = pipelines.PullRequest
case jenkinsfile.PipelineKindFeature:
lifecycles = pipelines.Feature
default:
return fmt.Errorf("Unknown pipeline kind %s. Supported values are %s", kind, strings.Join(jenkinsfile.PipelineKinds, ", "))
}
return o.generatePipeline(name, pipelineConfig, lifecycles, kind)
}
func (o *StepCreateTaskOptions) generatePipeline(languageName string, pipelineConfig *jenkinsfile.PipelineConfig, lifecycles *jenkinsfile.PipelineLifecycles, templateKind string) error {
if lifecycles == nil {
return nil
}
container := pipelineConfig.Agent.Container
dir := "/workspace"
steps := []corev1.Container{}
for _, l := range lifecycles.All() {
if l == nil {
continue
}
for _, s := range l.Steps {
ss, err := o.createSteps(languageName, pipelineConfig, templateKind, s, container, dir)
if err != nil {
return err
}
steps = append(steps, ss...)
}
}
name := "jx-buildtemplate-" + languageName + "-" + templateKind
build := &buildapi.BuildTemplate{
TypeMeta: metav1.TypeMeta{
APIVersion: "build.knative.dev/v1alpha1",
Kind: "BuildTemplate",
},
ObjectMeta: metav1.ObjectMeta{
Name: kube.ToValidName(name),
},
Spec: buildapi.BuildTemplateSpec{
Steps: steps,
},
}
data, err := yaml.Marshal(build)
if err != nil {
return errors.Wrapf(err, "failed to marshal Build YAML")
}
fileName := o.OutputFile
if fileName == "" {
log.Infof("%s\n", string(data))
return nil
}
err = ioutil.WriteFile(fileName, data, util.DefaultWritePermissions)
if err != nil {
return errors.Wrapf(err, "failed to save build template file %s", fileName)
}
log.Infof("generated Task at %s\n", util.ColorInfo(fileName))
return nil
}
func (o *StepCreateTaskOptions) createSteps(languageName string, pipelineConfig *jenkinsfile.PipelineConfig, templateKind string, step *jenkinsfile.PipelineStep, containerName string, dir string) ([]corev1.Container, error) {
steps := []corev1.Container{}
if step.Container != "" {
containerName = step.Container
} else if step.Dir != "" {
dir = step.Dir
}
if step.Command != "" {
if containerName == "" {
containerName = defaultContainerName
}
podTemplate := o.PodTemplates[containerName]
if podTemplate == nil {
o.MissingPodTemplates[containerName] = true
podTemplate = o.PodTemplates[defaultContainerName]
}
containers := podTemplate.Spec.Containers
if len(containers) == 0 {
return steps, fmt.Errorf("No Containers for pod template %s", containerName)
}
c := containers[0]
o.removeUnnecessaryVolumes(&c)
o.removeUnnecessaryEnvVars(&c)
c.Command = []string{"/bin/sh"}
c.Args = []string{"-c", step.Command}
if strings.HasPrefix(dir, "./") {
dir = "/workspace" + strings.TrimPrefix(dir, ".")
}
if !filepath.IsAbs(dir) {
dir = filepath.Join("/workspace", dir)
}
c.WorkingDir = dir
// TODO use different image based on if its jx or not?
c.Image = "jenkinsxio/jx:latest"
steps = append(steps, c)
}
for _, s := range step.Steps {
childSteps, err := o.createSteps(languageName, pipelineConfig, templateKind, s, containerName, dir)
if err != nil {
return steps, err
}
steps = append(steps, childSteps...)
}
return steps, nil
}
func (o *StepCreateTaskOptions) discoverBuildPack(dir string, projectConfig *config.ProjectConfig) (string, error) {
args := &InvokeDraftPack{
Dir: o.Dir,
CustomDraftPack: o.Pack,
ProjectConfig: projectConfig,
DisableAddFiles: true,
}
pack, err := o.invokeDraftPack(args)
if err != nil {
return pack, errors.Wrapf(err, "failed to discover build pack in dir %s", o.Dir)
}
return pack, nil
}
func (o *StepCreateTaskOptions) removeUnnecessaryVolumes(container *corev1.Container) {
// for now let remove them all?
container.VolumeMounts = nil
}
func (o *StepCreateTaskOptions) removeUnnecessaryEnvVars(container *corev1.Container) {
envVars := []corev1.EnvVar{}
for _, e := range container.Env {
name := e.Name
if strings.HasPrefix(name, "GIT_") || strings.HasPrefix(name, "DOCKER_") || strings.HasPrefix(name, "XDG_") {
continue
}
envVars = append(envVars, e)
}
container.Env = envVars
}