/
helpers.go
336 lines (290 loc) · 8.62 KB
/
helpers.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
// Copyright 2021 The Audit 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 pkg
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
semverv4 "github.com/blang/semver/v4"
log "github.com/sirupsen/logrus"
)
const JSON = "json"
const Yes = "YES"
const No = "NO"
const DefaultContainerTool = Docker
const Docker = "docker"
const Podman = "podman"
const InfrastructureAnnotation = "operators.openshift.io/infrastructure-features"
// PropertiesAnnotation used to Unmarshal the JSON in the CSV annotation
type PropertiesAnnotation struct {
Type string
Value string
}
func (p PropertiesAnnotation) String() string {
return fmt.Sprintf("{\"type\": \"%s\", \"value\": \"%s\"}", p.Type, p.Value)
}
// GetYesOrNo return the text yes for true values and No for false one.
func GetYesOrNo(value bool) string {
if value {
return Yes
}
return No
}
// Run executes the provided command within this context
func RunCommand(cmd *exec.Cmd) ([]byte, error) {
command := strings.Join(cmd.Args, " ")
log.Infof("running: %s\n", command)
output, err := cmd.CombinedOutput()
if err != nil {
return output, fmt.Errorf("%s failed with error: (%v) %s", command, err, string(output))
}
if len(output) > 0 {
log.Debugf("command output :%s", output)
}
return output, nil
}
// GetFormatArray return the values without duplicates and in a string such as "v","v"...
func GetFormatArrayWithBreakLine(array []string) string {
var result string
for _, n := range array {
if !strings.Contains(result, n) {
if len(result) > 0 {
result = fmt.Sprintf("%s\n%s", result, n)
} else {
result = n
}
}
}
return result
}
// GetUniqueValues return the values without duplicates
func GetUniqueValues(array []string) []string {
var result []string
for _, n := range array {
if len(result) == 0 {
result = append(result, n)
continue
}
found := false
for _, v := range result {
if strings.TrimSpace(n) == strings.TrimSpace(v) {
found = true
break
}
}
if !found {
result = append(result, n)
}
}
return result
}
func WriteJSON(data []byte, imageName, outputPath, typeName string) error {
var prettyJSON bytes.Buffer
err := json.Indent(&prettyJSON, data, "", "\t")
if err != nil {
return err
}
path := filepath.Join(outputPath, GetReportName(imageName, typeName, "json"))
_, err = os.ReadFile(path)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return os.WriteFile(path, prettyJSON.Bytes(), 0644)
}
func GetReportName(imageName, typeName, typeFile string) string {
//prepare image name to use as name of the file
name := strings.ReplaceAll(imageName, "/", "_")
name = strings.ReplaceAll(name, ":", "_")
name = strings.ReplaceAll(name, "-", "_")
return fmt.Sprintf("%s_%s.%s", typeName, name, typeFile)
}
func GenerateTemporaryDirs() {
command := exec.Command("rm", "-rf", "tmp")
_, _ = RunCommand(command)
command = exec.Command("rm", "-rf", "./output/")
_, _ = RunCommand(command)
command = exec.Command("mkdir", "./output/")
_, err := RunCommand(command)
if err != nil {
log.Fatal(err)
}
command = exec.Command("mkdir", "tmp")
_, err = RunCommand(command)
if err != nil {
log.Fatal(err)
}
}
func CleanupTemporaryDirs() {
command := exec.Command("rm", "-rf", "tmp")
_, _ = RunCommand(command)
command = exec.Command("rm", "-rf", "./output/")
_, _ = RunCommand(command)
}
type DockerInspect struct {
ID string `json:"ID"`
RepoDigests []string `json:"RepoDigests"`
Created string `json:"Created"`
DockerConfig DockerConfig `json:"Config"`
}
type DockerManifestInspect struct {
ManifestData []ManifestData `json:"manifests"`
}
type ManifestData struct {
Platform Platform `json:"platform"`
}
type Platform struct {
Architecture string `json:"architecture"`
OS string `json:"os"`
}
type DockerConfig struct {
Labels map[string]string `json:"Labels"`
}
func RunDockerInspect(image string, containerEngine string) (DockerInspect, error) {
cmd := exec.Command(containerEngine, "inspect", image)
output, err := RunCommand(cmd)
if err != nil || len(output) < 1 {
return DockerInspect{}, err
}
var dockerInspect []DockerInspect
if err := json.Unmarshal(output, &dockerInspect); err != nil {
return DockerInspect{}, err
}
return dockerInspect[0], nil
}
func RunDockerManifestInspect(image string, containerEngine string) (DockerManifestInspect, error) {
cmd := exec.Command(containerEngine, "manifest", "inspect", image)
output, err := RunCommand(cmd)
if err != nil || len(output) < 1 {
return DockerManifestInspect{}, err
}
var dockerInspect DockerManifestInspect
if err := json.Unmarshal(output, &dockerInspect); err != nil {
return DockerManifestInspect{}, err
}
return dockerInspect, nil
}
// HasClusterRunning will return true when is possible to check that the env has a cluster running
func HasClusterRunning() bool {
command := exec.Command("kubectl", "cluster-info")
output, err := RunCommand(command)
if err != nil || !strings.Contains(string(output), "is running at") {
return false
}
return true
}
// HasSDKInstalled will return true when find an SDK version installed
func HasSDKInstalled() bool {
command := exec.Command("operator-sdk", "version")
_, err := RunCommand(command)
return err == nil
}
// ReadFile will return the bites of file
func ReadFile(file string) ([]byte, error) {
jsonFile, err := os.Open(file)
if err != nil {
return []byte{}, err
}
var byteValue []byte
byteValue, err = io.ReadAll(jsonFile)
if err != nil {
return []byte{}, err
}
return byteValue, err
}
// IsFollowingChannelNameConventional will check the channels.
func IsFollowingChannelNameConventional(channel string) bool {
const candidate = "candidate"
const stable = "stable"
const fast = "fast"
if !strings.HasPrefix(channel, candidate) &&
!strings.HasPrefix(channel, stable) &&
!strings.HasPrefix(channel, fast) {
return false
}
return true
}
// GetContainerToolFromEnvVar retrieves the value of the environment variable and defaults to docker when not set
func GetContainerToolFromEnvVar() string {
if value, ok := os.LookupEnv("CONTAINER_ENGINE"); ok {
return value
}
return DefaultContainerTool
}
// RangeContainsVersion expected the range and the targetVersion version and returns true
// when the targetVersion version contains in the range
func RangeContainsVersion(r string, v string, tolerantParse bool) (bool, error) {
if len(r) == 0 {
return false, errors.New("range is empty")
}
if len(v) == 0 {
return false, errors.New("version is empty")
}
v = strings.TrimPrefix(v, "v")
compV, err := semverv4.Parse(v + ".0")
if err != nil {
splitTarget := strings.Split(v, ".")
if tolerantParse {
compV, err = semverv4.Parse(splitTarget[0] + "." + splitTarget[1] + ".0")
if err != nil {
return false, fmt.Errorf("invalid truncated version %q: %t", compV, err)
}
} else {
return false, fmt.Errorf("invalid version %q: %t", v, err)
}
}
// special legacy cases
if r == "v4.5,v4.6" || r == "v4.6,v4.5" {
semverRange := semverv4.MustParseRange(">=4.5.0")
return semverRange(compV), nil
}
var semverRange semverv4.Range
rs := strings.SplitN(r, "-", 2)
switch len(rs) {
case 1:
// Range specify exact version
if strings.HasPrefix(r, "=") {
trimmed := strings.TrimPrefix(r, "=v")
semverRange, err = semverv4.ParseRange(fmt.Sprintf("%s.0", trimmed))
} else {
trimmed := strings.TrimPrefix(r, "v")
// Range specifies minimum version
semverRange, err = semverv4.ParseRange(fmt.Sprintf(">=%s.0", trimmed))
}
if err != nil {
return false, fmt.Errorf("invalid range %q: %v", r, err)
}
case 2:
min := rs[0]
max := rs[1]
if strings.HasPrefix(min, "=") || strings.HasPrefix(max, "=") {
return false, fmt.Errorf("invalid range %q: cannot use equal prefix with range", r)
}
min = strings.TrimPrefix(min, "v")
max = strings.TrimPrefix(max, "v")
semverRangeStr := fmt.Sprintf(">=%s.0 <=%s.0", min, max)
semverRange, err = semverv4.ParseRange(semverRangeStr)
if err != nil {
return false, fmt.Errorf("invalid range %q: %v", r, err)
}
default:
return false, fmt.Errorf("invalid range %q", r)
}
return semverRange(compV), nil
}