-
Notifications
You must be signed in to change notification settings - Fork 345
/
util.go
745 lines (610 loc) · 17 KB
/
util.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
/*
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 util
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/fs"
"math/rand"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/apache/camel-k/v2/pkg/util/sets"
"go.uber.org/multierr"
yaml2 "gopkg.in/yaml.v2"
)
// Directories and file names:
// DefaultDependenciesDirectoryName --.
const DefaultDependenciesDirectoryName = "dependencies"
// DefaultPropertiesDirectoryName --.
const DefaultPropertiesDirectoryName = "properties"
// DefaultRoutesDirectoryName --.
const DefaultRoutesDirectoryName = "routes"
// DefaultWorkingDirectoryName --.
const DefaultWorkingDirectoryName = "workspace"
// CustomQuarkusDirectoryName --.
const CustomQuarkusDirectoryName = "quarkus"
// CustomAppDirectoryName --.
const CustomAppDirectoryName = "app"
// CustomLibDirectoryName --.
const CustomLibDirectoryName = "lib/main"
// ContainerDependenciesDirectory --.
var ContainerDependenciesDirectory = "/deployments/dependencies"
// ContainerPropertiesDirectory --.
var ContainerPropertiesDirectory = "/etc/camel/conf.d"
// ContainerRoutesDirectory --.
var ContainerRoutesDirectory = "/etc/camel/sources"
// ContainerResourcesDirectory --.
var ContainerResourcesDirectory = "/etc/camel/resources"
// ContainerQuarkusDirectoryName --.
const ContainerQuarkusDirectoryName = "/quarkus"
// ContainerAppDirectoryName --.
const ContainerAppDirectoryName = "/app"
// ContainerLibDirectoryName --.
const ContainerLibDirectoryName = "/lib/main"
// QuarkusDependenciesBaseDirectory --.
var QuarkusDependenciesBaseDirectory = "/quarkus-app"
// ListOfLazyEvaluatedEnvVars -- List of unevaluated environment variables.
// These are sensitive values or values that may have different values depending on
// where the integration is run (locally vs. the cloud). These environment variables
// are evaluated at the time of the integration invocation.
var ListOfLazyEvaluatedEnvVars []string
// CLIEnvVars -- List of CLI provided environment variables. They take precedence over
// any environment variables with the same name.
var CLIEnvVars = make([]string, 0)
func StringSliceJoin(slices ...[]string) []string {
size := 0
for _, s := range slices {
size += len(s)
}
result := make([]string, 0, size)
for _, s := range slices {
result = append(result, s...)
}
return result
}
func StringSliceContains(slice []string, items []string) bool {
for i := 0; i < len(items); i++ {
if !StringSliceExists(slice, items[i]) {
return false
}
}
return true
}
func StringSliceExists(slice []string, item string) bool {
for i := 0; i < len(slice); i++ {
if slice[i] == item {
return true
}
}
return false
}
func StringContainsPrefix(slice []string, prefix string) bool {
for i := 0; i < len(slice); i++ {
if strings.HasPrefix(slice[i], prefix) {
return true
}
}
return false
}
func StringSliceContainsAnyOf(slice []string, items ...string) bool {
for i := 0; i < len(slice); i++ {
for j := 0; j < len(items); j++ {
if strings.Contains(slice[i], items[j]) {
return true
}
}
}
return false
}
// StringSliceUniqueAdd appends the given item if not already present in the slice.
func StringSliceUniqueAdd(slice *[]string, item string) bool {
if slice == nil {
newSlice := make([]string, 0)
slice = &newSlice
}
for _, i := range *slice {
if i == item {
return false
}
}
*slice = append(*slice, item)
return true
}
// StringSliceUniqueConcat appends all the items of the "items" slice if they are not already present in the slice.
func StringSliceUniqueConcat(slice *[]string, items []string) bool {
changed := false
for _, item := range items {
if StringSliceUniqueAdd(slice, item) {
changed = true
}
}
return changed
}
func SubstringFrom(s string, substr string) string {
index := strings.Index(s, substr)
if index != -1 {
return s[index:]
}
return ""
}
func SubstringBefore(s string, substr string) string {
index := strings.LastIndex(s, substr)
if index != -1 {
return s[:index]
}
return ""
}
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
var randomSource = rand.NewSource(time.Now().UnixNano())
var randomSourceUTC = rand.NewSource(time.Now().UTC().UnixNano())
func RandomString(n int) string {
sb := strings.Builder{}
sb.Grow(n)
for i, cache, remain := n-1, randomSource.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = randomSource.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
sb.WriteByte(letterBytes[idx])
i--
}
cache >>= letterIdxBits
remain--
}
return sb.String()
}
func RandomInt63() int64 {
return randomSourceUTC.Int63()
}
func EncodeXMLWithoutHeader(content interface{}) ([]byte, error) {
return encodeXML(content, "")
}
func EncodeXML(content interface{}) ([]byte, error) {
return encodeXML(content, xml.Header)
}
func encodeXML(content interface{}, xmlHeader string) ([]byte, error) {
w := &bytes.Buffer{}
w.WriteString(xmlHeader)
e := xml.NewEncoder(w)
e.Indent("", " ")
if err := e.Encode(content); err != nil {
return []byte{}, err
}
return w.Bytes(), nil
}
func CopyFile(src, dst string) (int64, error) {
stat, err := os.Stat(src)
if err != nil {
return 0, err
}
if !stat.Mode().IsRegular() {
err = fmt.Errorf("%s is not a regular file", src)
return 0, err
}
source, err := Open(src)
if err != nil {
return 0, err
}
defer func() {
err = Close(err, source)
}()
// we need to have group and other to be able to access the directory as the user
// in the container may not be the same as the one owning the files
//
// #nosec G301
if err = os.MkdirAll(path.Dir(dst), 0o755); err != nil {
return 0, err
}
destination, err := OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, stat.Mode())
if err != nil {
return 0, err
}
defer func() {
err = Close(err, destination)
}()
nBytes, err := io.Copy(destination, source)
return nBytes, err
}
func CopyDir(src, dst string) error {
entries, err := os.ReadDir(src)
if err != nil {
return err
}
for _, entry := range entries {
srcEntry := filepath.Join(src, entry.Name())
dstEntry := filepath.Join(dst, entry.Name())
realEntry := entry
if entry.Type() == os.ModeSymlink {
realPath, err := filepath.EvalSymlinks(srcEntry)
if err != nil {
return err
}
realInfo, err := os.Stat(realPath)
if err != nil {
return err
}
srcEntry = realPath
realEntry = fs.FileInfoToDirEntry(realInfo)
}
if realEntry.IsDir() {
if err := CopyDir(srcEntry, dstEntry); err != nil {
return err
}
} else {
if _, err := CopyFile(srcEntry, dstEntry); err != nil {
return err
}
}
}
return nil
}
func WriteFileWithBytesMarshallerContent(basePath string, filePath string, content BytesMarshaller) error {
data, err := content.MarshalBytes()
if err != nil {
return err
}
return WriteFileWithContent(filepath.Join(basePath, filePath), data)
}
func FindAllDistinctStringSubmatch(data string, regexps ...*regexp.Regexp) []string {
submatchs := sets.NewSet()
for _, reg := range regexps {
hits := reg.FindAllStringSubmatch(data, -1)
for _, hit := range hits {
if len(hit) > 1 {
for _, match := range hit[1:] {
submatchs.Add(match)
}
}
}
}
return submatchs.List()
}
func FindNamedMatches(expr string, str string) map[string]string {
regex := regexp.MustCompile(expr)
match := regex.FindStringSubmatch(str)
results := map[string]string{}
for i, name := range match {
results[regex.SubexpNames()[i]] = name
}
return results
}
func FileExists(name string) (bool, error) {
info, err := os.Stat(name)
if os.IsNotExist(err) {
return false, nil
}
return !info.IsDir(), err
}
func DirectoryExists(directory string) (bool, error) {
info, err := os.Stat(directory)
if os.IsNotExist(err) {
return false, nil
}
if err != nil {
return false, err
}
return info.IsDir(), nil
}
func DirectoryEmpty(directory string) (bool, error) {
f, err := Open(directory)
if err != nil {
return false, err
}
defer func() {
err = Close(err, f)
}()
ok := false
if _, err = f.Readdirnames(1); errors.Is(err, io.EOF) {
ok = true
}
return ok, err
}
// CreateDirectory creates a directory if it does not exist.
func CreateDirectory(directory string) error {
if directory == "" {
return errors.New("directory name must not be empty")
}
directoryExists, err := DirectoryExists(directory)
if err != nil {
return err
}
if !directoryExists {
// #nosec G301
if err := os.MkdirAll(directory, 0o755); err != nil {
return err
}
}
return nil
}
type BytesMarshaller interface {
MarshalBytes() ([]byte, error)
}
func SortedMapKeys(m map[string]interface{}) []string {
res := make([]string, len(m))
i := 0
for k := range m {
res[i] = k
i++
}
sort.Strings(res)
return res
}
func SortedStringMapKeys(m map[string]string) []string {
res := make([]string, len(m))
i := 0
for k := range m {
res[i] = k
i++
}
sort.Strings(res)
return res
}
// CopyMap clones a map of strings.
func CopyMap(source map[string]string) map[string]string {
if source == nil {
return nil
}
dest := make(map[string]string, len(source))
for k, v := range source {
dest[k] = v
}
return dest
}
func JSONToYAML(src []byte) ([]byte, error) {
mapdata, err := JSONToMap(src)
if err != nil {
return nil, err
}
return MapToYAML(mapdata)
}
func JSONToMap(src []byte) (map[string]interface{}, error) {
jsondata := map[string]interface{}{}
err := json.Unmarshal(src, &jsondata)
if err != nil {
return nil, fmt.Errorf("error unmarshalling json: %w", err)
}
return jsondata, nil
}
func MapToYAML(src map[string]interface{}) ([]byte, error) {
yamldata, err := yaml2.Marshal(&src)
if err != nil {
return nil, fmt.Errorf("error marshalling to yaml: %w", err)
}
return yamldata, nil
}
func WriteToFile(filePath string, fileContents string) error {
err := os.WriteFile(filePath, []byte(fileContents), 0o400)
if err != nil {
return fmt.Errorf("error writing file: %v", filePath)
}
return nil
}
func GetEnvironmentVariable(variable string) (string, error) {
value, isPresent := os.LookupEnv(variable)
if !isPresent {
return "", fmt.Errorf("environment variable %v does not exist", variable)
}
if value == "" {
return "", fmt.Errorf("environment variable %v is not set", variable)
}
return value, nil
}
// EvaluateCLIAndLazyEnvVars creates a list of environment
// variables with entries VAR=value that can be passed when running the integration.
func EvaluateCLIAndLazyEnvVars() ([]string, error) {
evaluatedEnvVars := []string{}
// Add CLI environment variables
setEnvVars := []string{}
for _, cliEnvVar := range CLIEnvVars {
// Mark variable name as set.
varAndValue := strings.Split(cliEnvVar, "=")
setEnvVars = append(setEnvVars, varAndValue[0])
evaluatedEnvVars = append(evaluatedEnvVars, cliEnvVar)
}
// Add lazily evaluated environment variables if they have not
// already been set via the CLI --env option.
for _, lazyEnvVar := range ListOfLazyEvaluatedEnvVars {
alreadySet := false
for _, setEnvVar := range setEnvVars {
if setEnvVar == lazyEnvVar {
alreadySet = true
break
}
}
if !alreadySet {
value, err := GetEnvironmentVariable(lazyEnvVar)
if err != nil {
return nil, err
}
evaluatedEnvVars = append(evaluatedEnvVars, lazyEnvVar+"="+value)
}
}
return evaluatedEnvVars, nil
}
// Open a safe wrapper of os.Open.
func Open(name string) (*os.File, error) {
return os.Open(filepath.Clean(name))
}
// OpenFile a safe wrapper of os.OpenFile.
func OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
// #nosec G304
return os.OpenFile(filepath.Clean(name), flag, perm)
}
// ReadFile a safe wrapper of os.ReadFile.
func ReadFile(filename string) ([]byte, error) {
return os.ReadFile(filepath.Clean(filename))
}
func Close(err error, closer io.Closer) error {
return multierr.Append(err, closer.Close())
}
// CloseQuietly unconditionally close an io.Closer
// It should not be used to replace the Close statement(s).
func CloseQuietly(closer io.Closer) {
_ = closer.Close()
}
// WithFile a safe wrapper to process a file.
func WithFile(name string, flag int, perm os.FileMode, consumer func(file *os.File) error) error {
// #nosec G304
file, err := os.OpenFile(filepath.Clean(name), flag, perm)
if err == nil {
err = consumer(file)
}
return Close(err, file)
}
// WithFileReader a safe wrapper to process a file.
func WithFileReader(name string, consumer func(reader io.Reader) error) error {
// #nosec G304
file, err := os.Open(filepath.Clean(name))
if err == nil {
err = consumer(file)
}
return Close(err, file)
}
// WithFileContent a safe wrapper to process a file content.
func WithFileContent(name string, consumer func(file *os.File, data []byte) error) error {
return WithFile(name, os.O_RDWR|os.O_CREATE, 0o644, func(file *os.File) error {
content, err := ReadFile(name)
if err != nil {
return err
}
return consumer(file, content)
})
}
// WriteFileWithContent a safe wrapper to write content to a file.
func WriteFileWithContent(filePath string, content []byte) error {
fileDir := path.Dir(filePath)
// Create dir if not present
err := os.MkdirAll(fileDir, 0o700)
if err != nil {
return fmt.Errorf("could not create dir for file "+filePath+": %w", err)
}
// Create file
file, err := os.Create(filePath)
if err != nil {
return fmt.Errorf("could not create file "+filePath+": %w", err)
}
_, err = file.Write(content)
if err != nil {
err = fmt.Errorf("could not write to file "+filePath+": %w", err)
}
return Close(err, file)
}
// WithTempDir a safe wrapper to deal with temporary directories.
func WithTempDir(pattern string, consumer func(string) error) error {
tmpDir, err := os.MkdirTemp("", pattern)
if err != nil {
return err
}
consumerErr := consumer(tmpDir)
removeErr := os.RemoveAll(tmpDir)
return multierr.Append(consumerErr, removeErr)
}
var propertyRegex = regexp.MustCompile("'.+'|\".+\"|[^.]+")
// ConfigTreePropertySplit Parses a property spec and returns its parts.
func ConfigTreePropertySplit(property string) []string {
var res = make([]string, 0)
initialParts := propertyRegex.FindAllString(property, -1)
for _, p := range initialParts {
cur := trimQuotes(p)
var tmp []string
for strings.Contains(cur[1:], "[") && strings.HasSuffix(cur, "]") {
pos := strings.LastIndex(cur, "[")
tmp = append(tmp, cur[pos:])
cur = cur[0:pos]
}
if len(cur) > 0 {
tmp = append(tmp, cur)
}
for i := len(tmp) - 1; i >= 0; i-- {
res = append(res, tmp[i])
}
}
return res
}
func trimQuotes(s string) string {
if len(s) >= 2 {
if c := s[len(s)-1]; s[0] == c && (c == '"' || c == '\'') {
return s[1 : len(s)-1]
}
}
return s
}
// NavigateConfigTree switch to the element in the tree represented by the "nodes" spec and creates intermediary
// nodes if missing. Nodes specs starting with "[" and ending in "]" are treated as slice indexes.
func NavigateConfigTree(current interface{}, nodes []string) (interface{}, error) {
if len(nodes) == 0 {
return current, nil
}
isSlice := func(idx int) bool {
if idx >= len(nodes) {
return false
}
return strings.HasPrefix(nodes[idx], "[") && strings.HasSuffix(nodes[idx], "]")
}
makeNext := func() interface{} {
if isSlice(1) {
slice := make([]interface{}, 0)
return &slice
}
return make(map[string]interface{})
}
switch c := current.(type) {
case map[string]interface{}:
var next interface{}
if n, ok := c[nodes[0]]; ok {
next = n
} else {
next = makeNext()
c[nodes[0]] = next
}
return NavigateConfigTree(next, nodes[1:])
case *[]interface{}:
if !isSlice(0) {
return nil, fmt.Errorf("attempting to set map value %q into a slice", nodes[0])
}
pos, err := strconv.Atoi(nodes[0][1 : len(nodes[0])-1])
if err != nil {
return nil, fmt.Errorf("value %q inside brackets is not numeric: %w", nodes[0], err)
}
var next interface{}
if len(*c) > pos && (*c)[pos] != nil {
next = (*c)[pos]
} else {
next = makeNext()
for len(*c) <= pos {
*c = append(*c, nil)
}
(*c)[pos] = next
}
return NavigateConfigTree(next, nodes[1:])
default:
return nil, errors.New("invalid node type in configuration")
}
}