/
openapi.go
347 lines (300 loc) · 10.1 KB
/
openapi.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
/*
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 trait
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/utils/pointer"
ctrl "sigs.k8s.io/controller-runtime/pkg/client"
v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
traitv1 "github.com/apache/camel-k/pkg/apis/camel/v1/trait"
"github.com/apache/camel-k/pkg/util"
"github.com/apache/camel-k/pkg/util/defaults"
"github.com/apache/camel-k/pkg/util/digest"
"github.com/apache/camel-k/pkg/util/gzip"
"github.com/apache/camel-k/pkg/util/jvm"
"github.com/apache/camel-k/pkg/util/kubernetes"
"github.com/apache/camel-k/pkg/util/maven"
)
type openAPITrait struct {
BaseTrait
traitv1.OpenAPITrait `property:",squash"`
}
func newOpenAPITrait() Trait {
return &openAPITrait{
BaseTrait: NewBaseTrait("openapi", 300),
}
}
// IsPlatformTrait overrides base class method.
func (t *openAPITrait) IsPlatformTrait() bool {
return true
}
func (t *openAPITrait) Configure(e *Environment) (bool, error) {
if !e.IntegrationInPhase(v1.IntegrationPhaseInitialization) || !pointer.BoolDeref(t.Enabled, true) {
return false, nil
}
// check if the runtime provides 'rest' capabilities
if _, ok := e.CamelCatalog.Runtime.Capabilities[v1.CapabilityRest]; !ok {
return false, fmt.Errorf("the runtime provider %s does not declare 'rest' capability", e.CamelCatalog.Runtime.Provider)
}
if t.Configmaps != nil {
return e.IntegrationInPhase(v1.IntegrationPhaseInitialization), nil
}
return false, nil
}
func (t *openAPITrait) Apply(e *Environment) error {
util.StringSliceUniqueAdd(&e.Integration.Status.Capabilities, v1.CapabilityRest)
root := os.TempDir()
tmpDir, err := ioutil.TempDir(root, "openapi")
if err != nil {
return err
}
defer os.RemoveAll(tmpDir)
generatedFromConfigmaps, err := t.generateFromConfigmaps(e, tmpDir)
if err != nil {
return err
}
e.Integration.Status.GeneratedSources = generatedFromConfigmaps
return nil
}
func (t *openAPITrait) generateFromConfigmaps(e *Environment, tmpDir string) ([]v1.SourceSpec, error) {
dataSpecs := make([]v1.DataSpec, 0, len(t.Configmaps))
for _, configmap := range t.Configmaps {
// verify if it was autogenerated
cm, err := kubernetes.GetUnstructured(e.Ctx, e.Client, schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMap"},
configmap, e.Integration.Namespace)
if err == nil && cm != nil && cm.GetLabels()[kubernetes.ConfigMapAutogenLabel] == "true" {
refCm := kubernetes.NewConfigMap(e.Integration.Namespace, configmap, "", "", "", nil)
e.Resources.Add(refCm)
}
// Iterate over each configmap key which may hold a different OpenAPI spec
if dataMap, ok := cm.UnstructuredContent()["data"].(map[string]interface{}); ok {
for k, v := range dataMap {
if content, ok := v.(string); ok {
dataSpecs = append(dataSpecs, v1.DataSpec{
Name: k,
Content: content,
Compression: false,
})
}
}
}
}
return t.generateFromDataSpecs(e, tmpDir, dataSpecs)
}
func (t *openAPITrait) generateFromDataSpecs(e *Environment, tmpDir string, specs []v1.DataSpec) ([]v1.SourceSpec, error) {
generatedSources := make([]v1.SourceSpec, 0, len(e.Integration.Status.GeneratedSources))
for i, resource := range specs {
generatedContentName := fmt.Sprintf("%s-openapi-%03d", e.Integration.Name, i)
generatedSourceName := strings.TrimSuffix(resource.Name, filepath.Ext(resource.Name)) + ".xml"
// Generate configmap or reuse existing one
if err := t.generateOpenAPIConfigMap(e, resource, tmpDir, generatedContentName); err != nil {
return nil, errors.Wrapf(err, "cannot generate configmap for openapi resource %s", resource.Name)
}
if e.Integration.Status.GeneratedSources != nil {
// Filter out the previously generated source
for _, x := range e.Integration.Status.GeneratedSources {
if x.Name != generatedSourceName {
generatedSources = append(generatedSources, x)
}
}
}
// Add a source that references the config map
generatedSources = append(generatedSources, v1.SourceSpec{
DataSpec: v1.DataSpec{
Name: generatedSourceName,
ContentRef: generatedContentName,
Compression: resource.Compression,
},
Language: v1.LanguageXML,
})
}
return generatedSources, nil
}
func (t *openAPITrait) generateOpenAPIConfigMap(e *Environment, resource v1.DataSpec, tmpDir, generatedContentName string) error {
cm := corev1.ConfigMap{}
key := ctrl.ObjectKey{
Namespace: e.Integration.Namespace,
Name: generatedContentName,
}
err := t.Client.Get(e.Ctx, key, &cm)
if err != nil && k8serrors.IsNotFound(err) {
return t.createNewOpenAPIConfigMap(e, resource, tmpDir, generatedContentName)
} else if err != nil {
return err
}
// ConfigMap already present, let's check if the source has not changed
foundDigest := cm.Annotations["camel.apache.org/source.digest"]
// Compute the new digest
newDigest, err := digest.ComputeForResource(resource)
if err != nil {
return err
}
if foundDigest == newDigest {
// ConfigMap already exists and matches the source
// Re-adding it to update its revision
cm.ResourceVersion = ""
// Clear the managed fields to support server-side apply
cm.ManagedFields = nil
e.Resources.Add(&cm)
return nil
}
return t.createNewOpenAPIConfigMap(e, resource, tmpDir, generatedContentName)
}
func (t *openAPITrait) createNewOpenAPIConfigMap(e *Environment, resource v1.DataSpec, tmpDir, generatedContentName string) error {
tmpDir = filepath.Join(tmpDir, generatedContentName)
err := os.MkdirAll(tmpDir, os.ModePerm)
if err != nil {
return err
}
content := []byte(resource.Content)
if resource.Compression {
content, err = gzip.UncompressBase64(content)
if err != nil {
return err
}
}
in := filepath.Join(tmpDir, resource.Name)
out := filepath.Join(tmpDir, "openapi-dsl.xml")
err = ioutil.WriteFile(in, content, 0o400)
if err != nil {
return err
}
project, err := t.generateMavenProject(e)
if err != nil {
return err
}
mc := maven.NewContext(tmpDir)
mc.LocalRepository = e.Platform.Status.Build.Maven.LocalRepository
mc.AdditionalArguments = e.Platform.Status.Build.Maven.CLIOptions
mc.AddArgument("-Dopenapi.spec=" + in)
mc.AddArgument("-Ddsl.out=" + out)
if settings, err := kubernetes.ResolveValueSource(e.Ctx, e.Client, e.Platform.Namespace, &e.Platform.Status.Build.Maven.Settings); err != nil {
return err
} else if settings != "" {
mc.UserSettings = []byte(settings)
}
settings, err := maven.NewSettings(maven.DefaultRepositories, maven.ProxyFromEnvironment)
if err != nil {
return err
}
data, err := settings.MarshalBytes()
if err != nil {
return err
}
mc.GlobalSettings = data
secrets := e.Platform.Status.Build.Maven.CASecrets
if secrets != nil {
certsData, err := kubernetes.GetSecretsRefData(e.Ctx, e.Client, e.Platform.Namespace, secrets)
if err != nil {
return err
}
trustStoreName := "trust.jks"
trustStorePass := jvm.NewKeystorePassword()
err = jvm.GenerateKeystore(e.Ctx, tmpDir, trustStoreName, trustStorePass, certsData)
if err != nil {
return err
}
mc.ExtraMavenOpts = append(mc.ExtraMavenOpts,
"-Djavax.net.ssl.trustStore="+trustStoreName,
"-Djavax.net.ssl.trustStorePassword="+trustStorePass,
)
}
ctx, cancel := context.WithTimeout(e.Ctx, e.Platform.Status.Build.GetTimeout().Duration)
defer cancel()
err = project.Command(mc).Do(ctx)
if err != nil {
return err
}
content, err = util.ReadFile(out)
if err != nil {
return err
}
if resource.Compression {
c, err := gzip.CompressBase64(content)
if err != nil {
return err
}
content = c
}
// Compute the input digest and store it along with the configmap
hash, err := digest.ComputeForResource(resource)
if err != nil {
return err
}
// Store the generated rest xml in a separate config map in order
// not to pollute the integration with generated data
cm := corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: generatedContentName,
Namespace: e.Integration.Namespace,
Labels: map[string]string{
v1.IntegrationLabel: e.Integration.Name,
},
Annotations: map[string]string{
"camel.apache.org/source.language": string(v1.LanguageXML),
"camel.apache.org/source.name": resource.Name,
"camel.apache.org/source.compression": strconv.FormatBool(resource.Compression),
"camel.apache.org/source.generated": "true",
"camel.apache.org/source.type": string(v1.ResourceTypeOpenAPI),
"camel.apache.org/source.digest": hash,
},
},
Data: map[string]string{
"content": string(content),
},
}
e.Resources.Add(&cm)
return nil
}
func (t *openAPITrait) generateMavenProject(e *Environment) (maven.Project, error) {
if e.CamelCatalog == nil {
return maven.Project{}, errors.New("unknown camel catalog")
}
p := maven.NewProjectWithGAV("org.apache.camel.k.integration", "camel-k-rest-dsl-generator", defaults.Version)
p.Build = &maven.Build{
DefaultGoal: "generate-resources",
Plugins: []maven.Plugin{
{
GroupID: "org.apache.camel.k",
ArtifactID: "camel-k-maven-plugin",
Version: e.CamelCatalog.Runtime.Version,
Executions: []maven.Execution{
{
Phase: "generate-resources",
Goals: []string{
"generate-rest-xml",
},
},
},
},
},
}
return p, nil
}