forked from tektoncd/pipeline
/
artifacts_storage.go
323 lines (285 loc) · 11.8 KB
/
artifacts_storage.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
/*
Copyright 2019 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 artifacts
import (
"fmt"
"strings"
"github.com/tektoncd/pipeline/pkg/apis/pipeline"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
"github.com/tektoncd/pipeline/pkg/system"
"go.uber.org/zap"
"golang.org/x/xerrors"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
const (
// PvcConfigName is the name of the configmap containing all
// customizations for the storage PVC.
PvcConfigName = "config-artifact-pvc"
// PvcSizeKey is the name of the configmap entry that specifies the size of the PVC to create
PvcSizeKey = "size"
// DefaultPvcSize is the default size of the PVC to create
DefaultPvcSize = "5Gi"
// PvcStorageClassNameKey is the name of the configmap entry that specifies the storage class of the PVC to create
PvcStorageClassNameKey = "storageClassName"
// BucketConfigName is the name of the configmap containing all
// customizations for the storage bucket.
BucketConfigName = "config-artifact-bucket"
// BucketLocationKey is the name of the configmap entry that specifies
// loction of the bucket.
BucketLocationKey = "location"
// BucketServiceAccountSecretName is the name of the configmap entry that specifies
// the name of the secret that will provide the servie account with bucket access.
// This secret must have a key called serviceaccount that will have a value with
// the service account with access to the bucket
BucketServiceAccountSecretName = "bucket.service.account.secret.name"
// BucketServiceAccountSecretKey is the name of the configmap entry that specifies
// the secret key that will have a value with the service account json with access
// to the bucket
BucketServiceAccountSecretKey = "bucket.service.account.secret.key"
// BucketServiceAccountFieldName is the name of the configmap entry that specifies
// the field name that should be used for the service account.
// Valid values: GOOGLE_APPLICATION_CREDENTIALS, BOTO_CONFIG. Defaults to GOOGLE_APPLICATION_CREDENTIALS.
BucketServiceAccountFieldName = "bucket.service.account.field.name"
)
// ArtifactStorageInterface is an interface to define the steps to copy
// an pipeline artifact to/from temporary storage
type ArtifactStorageInterface interface {
GetCopyToStorageFromSteps(name, sourcePath, destinationPath string) []v1alpha1.Step
GetCopyFromStorageToSteps(name, sourcePath, destinationPath string) []v1alpha1.Step
GetSecretsVolumes() []corev1.Volume
GetType() string
StorageBasePath(pr *v1alpha1.PipelineRun) string
}
// ArtifactStorageNone is used when no storage is needed.
type ArtifactStorageNone struct{}
// GetCopyToStorageFromSteps returns no containers because none are needed.
func (a *ArtifactStorageNone) GetCopyToStorageFromSteps(name, sourcePath, destinationPath string) []v1alpha1.Step {
return nil
}
// GetCopyFromStorageToSteps returns no containers because none are needed.
func (a *ArtifactStorageNone) GetCopyFromStorageToSteps(name, sourcePath, destinationPath string) []v1alpha1.Step {
return nil
}
// GetSecretsVolumes returns no volumes because none are needed.
func (a *ArtifactStorageNone) GetSecretsVolumes() []corev1.Volume {
return nil
}
// GetType returns the string "none" to indicate this is the None storage type.
func (a *ArtifactStorageNone) GetType() string {
return "none"
}
// StorageBasePath returns an empty string because no storage is being used and so
// there is no path that resources should be copied from / to.
func (a *ArtifactStorageNone) StorageBasePath(pr *v1alpha1.PipelineRun) string {
return ""
}
// InitializeArtifactStorage will check if there is there is a
// bucket configured, create a PVC or return nil if no storage is required.
func InitializeArtifactStorage(images pipeline.Images, pr *v1alpha1.PipelineRun, ps *v1alpha1.PipelineSpec, c kubernetes.Interface, logger *zap.SugaredLogger) (ArtifactStorageInterface, error) {
// Artifact storage is needed under the following condition:
// Any Task in the pipeline contains an Output resource
// AND that Output resource is one of the AllowedOutputResource types.
needStorage := false
// Build an index of resources used in the pipeline that are an AllowedOutputResource
possibleOutputs := map[string]struct{}{}
for _, r := range ps.Resources {
if _, ok := v1alpha1.AllowedOutputResources[r.Type]; ok {
possibleOutputs[r.Name] = struct{}{}
}
}
// Use that index to see if any of these are used as OutputResources.
for _, t := range ps.Tasks {
if t.Resources != nil {
for _, o := range t.Resources.Outputs {
if _, ok := possibleOutputs[o.Resource]; ok {
needStorage = true
}
}
}
}
if !needStorage {
return &ArtifactStorageNone{}, nil
}
configMap, err := c.CoreV1().ConfigMaps(system.GetNamespace()).Get(BucketConfigName, metav1.GetOptions{})
shouldCreatePVC, err := ConfigMapNeedsPVC(configMap, err, logger)
if err != nil {
return nil, err
}
if shouldCreatePVC {
pvc, err := createPVC(pr, c)
if err != nil {
return nil, err
}
return &v1alpha1.ArtifactPVC{Name: pr.Name, PersistentVolumeClaim: pvc, ShellImage: images.ShellImage}, nil
}
return NewArtifactBucketConfigFromConfigMap(images)(configMap)
}
// CleanupArtifactStorage will delete the PipelineRun's artifact storage PVC if it exists. The PVC is created for using
// an output workspace or artifacts from one Task to another Task. No other PVCs will be impacted by this cleanup.
func CleanupArtifactStorage(pr *v1alpha1.PipelineRun, c kubernetes.Interface, logger *zap.SugaredLogger) error {
configMap, err := c.CoreV1().ConfigMaps(system.GetNamespace()).Get(BucketConfigName, metav1.GetOptions{})
shouldCreatePVC, err := ConfigMapNeedsPVC(configMap, err, logger)
if err != nil {
return err
}
if shouldCreatePVC {
err = deletePVC(pr, c)
if err != nil {
return err
}
}
return nil
}
// ConfigMapNeedsPVC checks if the possibly-nil config map passed to it is configured to use a bucket for artifact storage,
// returning true if instead a PVC is needed.
func ConfigMapNeedsPVC(configMap *corev1.ConfigMap, err error, logger *zap.SugaredLogger) (bool, error) {
if err != nil {
if errors.IsNotFound(err) {
return true, nil
}
return false, xerrors.Errorf("couldn't determine if PVC was needed from config map: %w", err)
}
if configMap == nil {
return true, nil
}
if configMap.Data == nil {
logger.Warn("the configmap has no data")
return true, nil
}
if location, ok := configMap.Data[BucketLocationKey]; !ok {
return true, nil
} else {
logger.Warnf("the configmap key %q is empty", BucketLocationKey)
if strings.TrimSpace(location) == "" {
return true, nil
}
}
return false, nil
}
// GetArtifactStorage returns the storage interface to enable
// consumer code to get a container step for copy to/from storage
func GetArtifactStorage(images pipeline.Images, prName string, c kubernetes.Interface, logger *zap.SugaredLogger) (ArtifactStorageInterface, error) {
configMap, err := c.CoreV1().ConfigMaps(system.GetNamespace()).Get(BucketConfigName, metav1.GetOptions{})
pvc, err := ConfigMapNeedsPVC(configMap, err, logger)
if err != nil {
return nil, xerrors.Errorf("couldn't determine if PVC was needed from config map: %w", err)
}
if pvc {
return &v1alpha1.ArtifactPVC{Name: prName, ShellImage: images.ShellImage}, nil
}
return NewArtifactBucketConfigFromConfigMap(images)(configMap)
}
// NewArtifactBucketConfigFromConfigMap creates a Bucket from the supplied ConfigMap
func NewArtifactBucketConfigFromConfigMap(images pipeline.Images) func(configMap *corev1.ConfigMap) (*v1alpha1.ArtifactBucket, error) {
return func(configMap *corev1.ConfigMap) (*v1alpha1.ArtifactBucket, error) {
c := &v1alpha1.ArtifactBucket{
ShellImage: images.ShellImage,
GsutilImage: images.GsutilImage,
}
if configMap.Data == nil {
return c, nil
}
if location, ok := configMap.Data[BucketLocationKey]; !ok {
c.Location = ""
} else {
c.Location = location
}
sp := v1alpha1.SecretParam{}
if secretName, ok := configMap.Data[BucketServiceAccountSecretName]; ok {
if secretKey, ok := configMap.Data[BucketServiceAccountSecretKey]; ok {
sp.FieldName = "GOOGLE_APPLICATION_CREDENTIALS"
if fieldName, ok := configMap.Data[BucketServiceAccountFieldName]; ok {
sp.FieldName = fieldName
}
sp.SecretName = secretName
sp.SecretKey = secretKey
c.Secrets = append(c.Secrets, sp)
}
}
return c, nil
}
}
func createPVC(pr *v1alpha1.PipelineRun, c kubernetes.Interface) (*corev1.PersistentVolumeClaim, error) {
if _, err := c.CoreV1().PersistentVolumeClaims(pr.Namespace).Get(GetPVCName(pr), metav1.GetOptions{}); err != nil {
if errors.IsNotFound(err) {
configMap, err := c.CoreV1().ConfigMaps(system.GetNamespace()).Get(PvcConfigName, metav1.GetOptions{})
if err != nil && !errors.IsNotFound(err) {
return nil, xerrors.Errorf("failed to get PVC ConfigMap %s for %q due to error: %w", PvcConfigName, pr.Name, err)
}
var pvcSizeStr string
var pvcStorageClassNameStr string
if configMap != nil {
pvcSizeStr = configMap.Data[PvcSizeKey]
pvcStorageClassNameStr = configMap.Data[PvcStorageClassNameKey]
}
if pvcSizeStr == "" {
pvcSizeStr = DefaultPvcSize
}
pvcSize, err := resource.ParseQuantity(pvcSizeStr)
if err != nil {
return nil, xerrors.Errorf("failed to create Persistent Volume spec for %q due to error: %w", pr.Name, err)
}
var pvcStorageClassName *string
if pvcStorageClassNameStr == "" {
pvcStorageClassName = nil
} else {
pvcStorageClassName = &pvcStorageClassNameStr
}
pvcSpec := GetPVCSpec(pr, pvcSize, pvcStorageClassName)
pvc, err := c.CoreV1().PersistentVolumeClaims(pr.Namespace).Create(pvcSpec)
if err != nil {
return nil, xerrors.Errorf("failed to claim Persistent Volume %q due to error: %w", pr.Name, err)
}
return pvc, nil
}
return nil, xerrors.Errorf("failed to get claim Persistent Volume %q due to error: %w", pr.Name, err)
}
return nil, nil
}
func deletePVC(pr *v1alpha1.PipelineRun, c kubernetes.Interface) error {
if _, err := c.CoreV1().PersistentVolumeClaims(pr.Namespace).Get(GetPVCName(pr), metav1.GetOptions{}); err != nil {
if !errors.IsNotFound(err) {
return xerrors.Errorf("failed to get Persistent Volume %q due to error: %w", GetPVCName(pr), err)
}
} else if err := c.CoreV1().PersistentVolumeClaims(pr.Namespace).Delete(GetPVCName(pr), &metav1.DeleteOptions{}); err != nil {
return xerrors.Errorf("failed to delete Persistent Volume %q due to error: %w", pr.Name, err)
}
return nil
}
// GetPVCSpec returns the PVC to create for a given PipelineRun
func GetPVCSpec(pr *v1alpha1.PipelineRun, pvcSize resource.Quantity, storageClassName *string) *corev1.PersistentVolumeClaim {
return &corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Namespace: pr.Namespace,
Name: GetPVCName(pr),
OwnerReferences: pr.GetOwnerReference(),
},
Spec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce},
Resources: corev1.ResourceRequirements{
Requests: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceStorage: pvcSize,
},
},
StorageClassName: storageClassName,
},
}
}
// GetPVCName returns the name that should be used for the PVC for a PipelineRun
func GetPVCName(pr *v1alpha1.PipelineRun) string {
return fmt.Sprintf("%s-pvc", pr.Name)
}