forked from apache/camel-k
/
s2i.go
346 lines (290 loc) · 8.77 KB
/
s2i.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
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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 builder
import (
"archive/tar"
"bufio"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
ctrl "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
ctrlutil "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"github.com/pkg/errors"
buildv1 "github.com/openshift/api/build/v1"
imagev1 "github.com/openshift/api/image/v1"
v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
"github.com/apache/camel-k/pkg/client"
"github.com/apache/camel-k/pkg/util"
"github.com/apache/camel-k/pkg/util/log"
)
type s2iTask struct {
c client.Client
build *v1.Build
task *v1.S2iTask
}
var _ Task = &s2iTask{}
func (t *s2iTask) Do(ctx context.Context) v1.BuildStatus {
status := v1.BuildStatus{}
bc := &buildv1.BuildConfig{
TypeMeta: metav1.TypeMeta{
APIVersion: buildv1.GroupVersion.String(),
Kind: "BuildConfig",
},
ObjectMeta: metav1.ObjectMeta{
Name: "camel-k-" + t.build.Name,
Namespace: t.build.Namespace,
Labels: t.build.Labels,
},
Spec: buildv1.BuildConfigSpec{
CommonSpec: buildv1.CommonSpec{
Source: buildv1.BuildSource{
Type: buildv1.BuildSourceBinary,
},
Strategy: buildv1.BuildStrategy{
DockerStrategy: &buildv1.DockerBuildStrategy{},
},
Output: buildv1.BuildOutput{
To: &corev1.ObjectReference{
Kind: "ImageStreamTag",
Name: "camel-k-" + t.build.Name + ":" + t.task.Tag,
},
},
},
},
}
err := t.c.Delete(ctx, bc)
if err != nil && !apierrors.IsNotFound(err) {
return status.Failed(errors.Wrap(err, "cannot delete build config"))
}
// Set the build controller as owner reference
owner := t.getControllerReference()
if owner == nil {
// Default to the Build if no controller reference is present
owner = t.build
}
if err := ctrlutil.SetOwnerReference(owner, bc, t.c.GetScheme()); err != nil {
return status.Failed(errors.Wrapf(err, "cannot set owner reference on BuildConfig: %s", bc.Name))
}
err = t.c.Create(ctx, bc)
if err != nil {
return status.Failed(errors.Wrap(err, "cannot create build config"))
}
is := &imagev1.ImageStream{
TypeMeta: metav1.TypeMeta{
APIVersion: imagev1.GroupVersion.String(),
Kind: "ImageStream",
},
ObjectMeta: metav1.ObjectMeta{
Name: "camel-k-" + t.build.Name,
Namespace: t.build.Namespace,
Labels: t.build.Labels,
},
Spec: imagev1.ImageStreamSpec{
LookupPolicy: imagev1.ImageLookupPolicy{
Local: true,
},
},
}
err = t.c.Delete(ctx, is)
if err != nil && !apierrors.IsNotFound(err) {
return status.Failed(errors.Wrap(err, "cannot delete image stream"))
}
if err := ctrlutil.SetOwnerReference(owner, is, t.c.GetScheme()); err != nil {
return status.Failed(errors.Wrapf(err, "cannot set owner reference on ImageStream: %s", is.Name))
}
err = t.c.Create(ctx, is)
if err != nil {
return status.Failed(errors.Wrap(err, "cannot create image stream"))
}
err = util.WithTempDir(t.build.Name+"-s2i-", func(tmpDir string) error {
archive := path.Join(tmpDir, "archive.tar.gz")
contextDir := t.task.ContextDir
if contextDir == "" {
// Use the working directory.
// This is useful when the task is executed in-container,
// so that its WorkingDir can be used to share state and
// coordinate with other tasks.
pwd, err := os.Getwd()
if err != nil {
return err
}
contextDir = path.Join(pwd, ContextDir)
}
archiveFile, err := os.Create(archive)
if err != nil {
return errors.Wrap(err, "cannot create tar archive")
}
err = tarDir(contextDir, archiveFile)
if err != nil {
return errors.Wrap(err, "cannot tar context directory")
}
f, err := util.Open(archive)
if err != nil {
return err
}
restClient, err := apiutil.RESTClientForGVK(
schema.GroupVersionKind{Group: "build.openshift.io", Version: "v1"}, false,
t.c.GetConfig(), serializer.NewCodecFactory(t.c.GetScheme()))
if err != nil {
return err
}
r := restClient.Post().
Namespace(t.build.Namespace).
Body(bufio.NewReader(f)).
Resource("buildconfigs").
Name("camel-k-" + t.build.Name).
SubResource("instantiatebinary").
Do(ctx)
if r.Error() != nil {
return errors.Wrap(r.Error(), "cannot instantiate binary")
}
data, err := r.Raw()
if err != nil {
return errors.Wrap(err, "no raw data retrieved")
}
s2iBuild := buildv1.Build{}
err = json.Unmarshal(data, &s2iBuild)
if err != nil {
return errors.Wrap(err, "cannot unmarshal instantiated binary response")
}
err = t.waitForS2iBuildCompletion(ctx, t.c, &s2iBuild)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
// nolint: contextcheck
if err := t.cancelBuild(context.Background(), &s2iBuild); err != nil {
log.Errorf(err, "cannot cancel s2i Build: %s/%s", s2iBuild.Namespace, s2iBuild.Name)
}
}
return err
}
if s2iBuild.Status.Output.To != nil {
status.Digest = s2iBuild.Status.Output.To.ImageDigest
}
err = t.c.Get(ctx, ctrl.ObjectKeyFromObject(is), is)
if err != nil {
return err
}
if is.Status.DockerImageRepository == "" {
return errors.New("dockerImageRepository not available in ImageStream")
}
status.Image = is.Status.DockerImageRepository + ":" + t.task.Tag
return f.Close()
})
if err != nil {
return status.Failed(err)
}
return status
}
func (t *s2iTask) getControllerReference() metav1.Object {
var owner metav1.Object
for _, ref := range t.build.GetOwnerReferences() {
if ref.Controller != nil && *ref.Controller {
o := &unstructured.Unstructured{}
o.SetNamespace(t.build.Namespace)
o.SetName(ref.Name)
o.SetUID(ref.UID)
o.SetAPIVersion(ref.APIVersion)
o.SetKind(ref.Kind)
owner = o
break
}
}
return owner
}
func (t *s2iTask) waitForS2iBuildCompletion(ctx context.Context, c client.Client, build *buildv1.Build) error {
key := ctrl.ObjectKeyFromObject(build)
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(1 * time.Second):
err := c.Get(ctx, key, build)
if err != nil {
if apierrors.IsNotFound(err) {
continue
}
return err
}
if build.Status.Phase == buildv1.BuildPhaseComplete {
return nil
} else if build.Status.Phase == buildv1.BuildPhaseCancelled ||
build.Status.Phase == buildv1.BuildPhaseFailed ||
build.Status.Phase == buildv1.BuildPhaseError {
return errors.New("build failed")
}
}
}
}
func (t *s2iTask) cancelBuild(ctx context.Context, build *buildv1.Build) error {
target := build.DeepCopy()
target.Status.Cancelled = true
if err := t.c.Patch(ctx, target, ctrl.MergeFrom(build)); err != nil {
return err
}
*build = *target
return nil
}
func tarDir(src string, writers ...io.Writer) error {
// ensure the src actually exists before trying to tar it
if _, err := os.Stat(src); err != nil {
return fmt.Errorf("unable to tar files: %w", err)
}
mw := io.MultiWriter(writers...)
gzw := gzip.NewWriter(mw)
defer util.CloseQuietly(gzw)
tw := tar.NewWriter(gzw)
defer util.CloseQuietly(tw)
return filepath.Walk(src, func(file string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
if !fi.Mode().IsRegular() {
return nil
}
header, err := tar.FileInfoHeader(fi, fi.Name())
if err != nil {
return err
}
// update the name to correctly reflect the desired destination when un-taring
header.Name = strings.TrimPrefix(strings.ReplaceAll(file, src, ""), string(filepath.Separator))
if err := tw.WriteHeader(header); err != nil {
return err
}
f, err := util.Open(file)
if err != nil {
return err
}
if _, err := io.Copy(tw, f); err != nil {
return err
}
// manually close here after each file operation; deferring would cause each file close
// to wait until all operations have completed.
return f.Close()
})
}