-
Notifications
You must be signed in to change notification settings - Fork 1
/
executor_kubernetes.go
268 lines (221 loc) · 6.11 KB
/
executor_kubernetes.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
package kubernetes
import (
"fmt"
"strings"
"golang.org/x/net/context"
"k8s.io/kubernetes/pkg/api"
client "k8s.io/kubernetes/pkg/client/unversioned"
"gitlab.com/gitlab-org/gitlab-ci-multi-runner/common"
"gitlab.com/gitlab-org/gitlab-ci-multi-runner/executors"
)
var (
executorOptions = executors.ExecutorOptions{
SharedBuildsDir: false,
Shell: common.ShellScriptInfo{
Shell: "bash",
Type: common.NormalShell,
RunnerCommand: "/usr/bin/gitlab-runner-helper",
},
ShowHostname: true,
SupportedOptions: []string{"image", "services", "artifacts", "cache"},
}
)
type kubernetesOptions struct {
Image string `json:"image"`
Services []string `json:"services"`
}
type executor struct {
executors.AbstractExecutor
kubeClient *client.Client
prepod *api.Pod
pod *api.Pod
options *kubernetesOptions
buildLimits api.ResourceList
serviceLimits api.ResourceList
}
func (s *executor) Prepare(globalConfig *common.Config, config *common.RunnerConfig, build *common.Build) error {
err := s.AbstractExecutor.Prepare(globalConfig, config, build)
if err != nil {
return err
}
if s.BuildShell.PassFile {
return fmt.Errorf("kubernetes doesn't support shells that require script file")
}
err = build.Options.Decode(&s.options)
if err != nil {
return err
}
s.kubeClient, err = getKubeClient(config.Kubernetes)
if err != nil {
return fmt.Errorf("error connecting to Kubernetes: %s", err.Error())
}
if s.serviceLimits, err = limits(s.Config.Kubernetes.ServiceCPUs, s.Config.Kubernetes.ServiceMemory); err != nil {
return err
}
if s.buildLimits, err = limits(s.Config.Kubernetes.CPUs, s.Config.Kubernetes.Memory); err != nil {
return err
}
if err = s.checkDefaults(); err != nil {
return err
}
s.Println("Using Kubernetes executor with image", s.options.Image, "...")
return nil
}
func (s *executor) Run(cmd common.ExecutorCommand) error {
s.Debugln("Starting Kubernetes command...")
if s.pod == nil {
err := s.setupBuildPod()
if err != nil {
return err
}
}
containerName := "build"
ctx, cancel := context.WithCancel(context.Background())
select {
case err := <-s.runInContainer(ctx, containerName, cmd.Script):
if err != nil && strings.Contains(err.Error(), "executing in Docker Container") {
return &common.BuildError{Inner: err}
}
return err
case <-cmd.Abort:
cancel()
return fmt.Errorf("build aborted")
}
}
func (s *executor) Cleanup() {
if s.pod != nil {
err := s.kubeClient.Pods(s.pod.Namespace).Delete(s.pod.Name, nil)
if err != nil {
s.Errorln(fmt.Sprintf("Error cleaning up pod: %s", err.Error()))
}
}
closeKubeClient(s.kubeClient)
s.AbstractExecutor.Cleanup()
}
func (s *executor) buildContainer(name, image string, limits api.ResourceList, command ...string) api.Container {
path := strings.Split(s.Build.BuildDir, "/")
path = path[:len(path)-1]
privileged := false
if s.Config.Kubernetes != nil {
privileged = s.Config.Kubernetes.Privileged
}
return api.Container{
Name: name,
Image: image,
Command: command,
Env: buildVariables(s.Build.GetAllVariables().PublicOrInternal()),
Resources: api.ResourceRequirements{
Limits: limits,
},
VolumeMounts: []api.VolumeMount{
api.VolumeMount{
Name: "repo",
MountPath: strings.Join(path, "/"),
},
},
SecurityContext: &api.SecurityContext{
Privileged: &privileged,
},
Stdin: true,
}
}
func (s *executor) setupBuildPod() error {
services := make([]api.Container, len(s.options.Services))
for i, image := range s.options.Services {
resolvedImage := s.Build.GetAllVariables().ExpandValue(image)
services[i] = s.buildContainer(fmt.Sprintf("svc-%d", i), resolvedImage, s.serviceLimits)
}
buildImage := s.Build.GetAllVariables().ExpandValue(s.options.Image)
pod, err := s.kubeClient.Pods(s.Config.Kubernetes.Namespace).Create(&api.Pod{
ObjectMeta: api.ObjectMeta{
GenerateName: s.Build.ProjectUniqueName(),
Namespace: s.Config.Kubernetes.Namespace,
},
Spec: api.PodSpec{
Volumes: []api.Volume{
api.Volume{
Name: "repo",
VolumeSource: api.VolumeSource{
EmptyDir: &api.EmptyDirVolumeSource{},
},
},
},
RestartPolicy: api.RestartPolicyNever,
Containers: append([]api.Container{
s.buildContainer("build", buildImage, s.buildLimits, s.BuildShell.DockerCommand...),
}, services...),
},
})
if err != nil {
return err
}
s.pod = pod
return nil
}
func (s *executor) runInContainer(ctx context.Context, name, command string) <-chan error {
errc := make(chan error, 1)
go func() {
defer close(errc)
status, err := waitForPodRunning(ctx, s.kubeClient, s.pod, s.BuildTrace)
if err != nil {
errc <- err
return
}
if status != api.PodRunning {
errc <- fmt.Errorf("pod failed to enter running state: %s", status)
return
}
config, err := getKubeClientConfig(s.Config.Kubernetes)
if err != nil {
errc <- err
return
}
exec := ExecOptions{
PodName: s.pod.Name,
Namespace: s.pod.Namespace,
ContainerName: name,
Command: s.BuildShell.DockerCommand,
In: strings.NewReader(command),
Out: s.BuildTrace,
Err: s.BuildTrace,
Stdin: true,
Config: config,
Client: s.kubeClient,
Executor: &DefaultRemoteExecutor{},
}
errc <- exec.Run()
}()
return errc
}
func (s *executor) checkDefaults() error {
if s.options.Image == "" {
if s.Config.Kubernetes.Image == "" {
return fmt.Errorf("no image specified and no default set in config")
}
s.options.Image = s.Config.Kubernetes.Image
}
if s.Config.Kubernetes.Namespace == "" {
s.Config.Kubernetes.Namespace = "default"
}
return nil
}
func createFn() common.Executor {
return &executor{
AbstractExecutor: executors.AbstractExecutor{
ExecutorOptions: executorOptions,
},
}
}
func featuresFn(features *common.FeaturesInfo) {
features.Variables = true
features.Image = true
features.Services = true
features.Artifacts = true
features.Cache = true
}
func init() {
common.RegisterExecutor("kubernetes", executors.DefaultExecutorProvider{
Creator: createFn,
FeaturesUpdater: featuresFn,
})
}