-
Notifications
You must be signed in to change notification settings - Fork 253
/
Copy pathdistribution.go
282 lines (250 loc) · 10 KB
/
distribution.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
package inttestutils
import (
"encoding/json"
"fmt"
"github.com/jfrog/jfrog-client-go/utils/errorutils"
"net/http"
"os"
"path/filepath"
"testing"
"time"
"github.com/jfrog/jfrog-cli-core/v2/common/spec"
"github.com/jfrog/jfrog-cli-core/v2/utils/coreutils"
coreTests "github.com/jfrog/jfrog-cli-core/v2/utils/tests"
"github.com/buger/jsonparser"
"github.com/jfrog/jfrog-cli-core/v2/utils/config"
"github.com/jfrog/jfrog-cli/utils/tests"
"github.com/jfrog/jfrog-client-go/distribution/services/utils"
"github.com/jfrog/jfrog-client-go/http/httpclient"
"github.com/jfrog/jfrog-client-go/utils/io/httputils"
"github.com/jfrog/jfrog-client-go/utils/log"
"github.com/stretchr/testify/assert"
)
const (
distributionGpgKeyCreatePattern = `{"public_key":"%s","private_key":"%s"}`
ArtifactoryGpgKeyCreatePattern = `{"alias":"cli tests distribution key","public_key":"%s"}`
)
type distributableDistributionStatus string
type receivedDistributionStatus string
const (
// Release bundle created and open for changes:
open distributableDistributionStatus = "OPEN"
// Release bundle is signed, but not stored:
signed distributableDistributionStatus = "SIGNED"
// Release bundle is signed and stored, but not scanned by Xray:
stored distributableDistributionStatus = "STORED"
// Release bundle is signed, stored and scanned by Xray:
readyForDistribution distributableDistributionStatus = "READY_FOR_DISTRIBUTION"
NotDistributed receivedDistributionStatus = "Not distributed"
InProgress receivedDistributionStatus = "In progress"
Completed receivedDistributionStatus = "Completed"
Failed receivedDistributionStatus = "Failed"
)
// GET api/v1/release_bundle/:name/:version
// Retrieve the status of a release bundle before distribution.
type distributableResponse struct {
utils.ReleaseBundleBody
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
State distributableDistributionStatus `json:"state,omitempty"`
}
// Get api/v1/release_bundle/:name/:version/distribution
// Retrieve the status of a release bundle after distribution.
type receivedResponse struct {
Id string `json:"id,omitempty"`
Status receivedDistributionStatus `json:"status,omitempty"`
}
type ReceivedResponses struct {
receivedResponses []receivedResponse
}
// Send GPG keys to Distribution and Artifactory to allow signing of release bundles
func SendGpgKeys(artHttpDetails httputils.HttpClientDetails, distHttpDetails httputils.HttpClientDetails) {
// Read gpg public and private keys
keysDir := filepath.Join(tests.GetTestResourcesPath(), "distribution")
publicKey, err := os.ReadFile(filepath.Join(keysDir, "public.key.1"))
coreutils.ExitOnErr(err)
privateKey, err := os.ReadFile(filepath.Join(keysDir, "private.key"))
coreutils.ExitOnErr(err)
// Create http client
client, err := httpclient.ClientBuilder().Build()
coreutils.ExitOnErr(err)
// Send public and private keys to Distribution
content := fmt.Sprintf(distributionGpgKeyCreatePattern, publicKey, privateKey)
resp, body, err := client.SendPut(*tests.JfrogUrl+"distribution/api/v1/keys/pgp", []byte(content), distHttpDetails, "")
coreutils.ExitOnErr(err)
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK); err != nil {
log.Error(err.Error())
os.Exit(1)
}
// Send public key to Artifactory
content = fmt.Sprintf(ArtifactoryGpgKeyCreatePattern, publicKey)
resp, body, err = client.SendPost(*tests.JfrogUrl+"artifactory/api/security/keys/trusted", []byte(content), artHttpDetails, "")
coreutils.ExitOnErr(err)
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusCreated, http.StatusConflict); err != nil {
log.Error(err.Error())
os.Exit(1)
}
}
// Get a local release bundle
func GetLocalBundle(t *testing.T, bundleName, bundleVersion string, distHttpDetails httputils.HttpClientDetails) *distributableResponse {
resp, body := getLocalBundle(t, bundleName, bundleVersion, distHttpDetails)
if err := errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK); err != nil {
t.Error(err.Error())
return nil
}
response := &distributableResponse{}
err := json.Unmarshal(body, &response)
if err != nil {
t.Error(err)
return nil
}
return response
}
// Return true if the release bundle exists locally on distribution
func VerifyLocalBundleExistence(t *testing.T, bundleName, bundleVersion string, expectExist bool, distHttpDetails httputils.HttpClientDetails) {
for i := 0; i < 120; i++ {
resp, body := getLocalBundle(t, bundleName, bundleVersion, distHttpDetails)
switch resp.StatusCode {
case http.StatusOK:
if expectExist {
return
}
case http.StatusNotFound:
if !expectExist {
return
}
default:
t.Error(resp.Status)
t.Error(string(body))
return
}
t.Log("Waiting for " + bundleName + "/" + bundleVersion + "...")
time.Sleep(time.Second)
}
t.Errorf("Release bundle %s/%s exist: %v unlike expected", bundleName, bundleVersion, expectExist)
}
// Assert release bundle status is OPEN
func AssertReleaseBundleOpen(t *testing.T, distributableResponse *distributableResponse) {
assert.NotNil(t, distributableResponse)
assert.Equal(t, open, distributableResponse.State)
}
// Assert release bundle status is SIGNED, STORED or READY_FOR_DISTRIBUTION
func AssertReleaseBundleSigned(t *testing.T, distributableResponse *distributableResponse) {
assert.NotNil(t, distributableResponse)
assert.Contains(t, []distributableDistributionStatus{signed, stored, readyForDistribution}, distributableResponse.State)
}
// Wait for distribution of a release bundle
func WaitForDistribution(t *testing.T, bundleName, bundleVersion string, distHttpDetails httputils.HttpClientDetails) {
client, err := httpclient.ClientBuilder().Build()
assert.NoError(t, err)
for i := 0; i < 120; i++ {
resp, body, _, err := client.SendGet(*tests.JfrogUrl+"distribution/api/v1/release_bundle/"+bundleName+"/"+bundleVersion+"/distribution", true, distHttpDetails, "")
assert.NoError(t, err)
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK); err != nil {
t.Error(err.Error())
return
}
response := &ReceivedResponses{}
err = json.Unmarshal(body, &response.receivedResponses)
if err != nil {
t.Error(err)
return
}
if len(response.receivedResponses) == 0 {
t.Error("Release bundle \"" + bundleName + "/" + bundleVersion + "\" not found")
return
}
switch response.receivedResponses[0].Status {
case Completed:
return
case Failed:
t.Error("Distribution failed for " + bundleName + "/" + bundleVersion)
return
case InProgress, NotDistributed:
// Wait
}
t.Log("Waiting for " + bundleName + "/" + bundleVersion + "...")
time.Sleep(time.Second)
}
t.Error("Timeout for release bundle distribution " + bundleName + "/" + bundleVersion)
}
// Wait for deletion of a release bundle
func WaitForDeletion(t *testing.T, bundleName, bundleVersion string, distHttpDetails httputils.HttpClientDetails) {
client, err := httpclient.ClientBuilder().Build()
assert.NoError(t, err)
for i := 0; i < 120; i++ {
resp, body, _, err := client.SendGet(*tests.JfrogUrl+"distribution/api/v1/release_bundle/"+bundleName+"/"+bundleVersion+"/distribution", true, distHttpDetails, "")
assert.NoError(t, err)
if resp.StatusCode == http.StatusNotFound {
return
}
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK); err != nil {
t.Error(err.Error())
return
}
t.Log("Waiting for distribution deletion " + bundleName + "/" + bundleVersion + "...")
time.Sleep(time.Second)
}
t.Error("Timeout for release bundle deletion " + bundleName + "/" + bundleVersion)
}
func getLocalBundle(t *testing.T, bundleName, bundleVersion string, distHttpDetails httputils.HttpClientDetails) (*http.Response, []byte) {
client, err := httpclient.ClientBuilder().Build()
assert.NoError(t, err)
resp, body, _, err := client.SendGet(*tests.JfrogUrl+"distribution/api/v1/release_bundle/"+bundleName+"/"+bundleVersion, true, distHttpDetails, "")
assert.NoError(t, err)
return resp, body
}
func CleanUpOldBundles(distHttpDetails httputils.HttpClientDetails, bundleVersion string, distributionCli *coreTests.JfrogCli) {
getActualItems := func() ([]string, error) { return ListAllBundlesNames(distHttpDetails) }
deleteItem := func(bundleName string) {
err := distributionCli.Exec("rbdel", bundleName, bundleVersion, "--site=*", "--delete-from-dist", "--quiet")
if err != nil {
log.Error(err)
} else {
log.Info("Bundle", bundleName, "deleted.")
}
}
tests.CleanUpOldItems([]string{tests.BundleName}, getActualItems, deleteItem)
}
func ListAllBundlesNames(distHttpDetails httputils.HttpClientDetails) ([]string, error) {
var bundlesNames []string
// Build http client
client, err := httpclient.ClientBuilder().Build()
if err != nil {
return nil, err
}
// Send get request
resp, body, _, err := client.SendGet(*tests.JfrogUrl+"distribution/api/v1/release_bundle/distribution", true, distHttpDetails, "")
if err != nil {
return nil, err
}
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK, http.StatusCreated); err != nil {
return nil, err
}
// Extract release bundle names from the json response
var keyError error
_, err = jsonparser.ArrayEach(body, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
if err != nil || keyError != nil {
return
}
bundleName, err := jsonparser.GetString(value, "release_bundle_name")
if err != nil {
keyError = err
return
}
bundlesNames = append(bundlesNames, bundleName)
})
if keyError != nil {
return nil, err
}
return bundlesNames, err
}
// Clean up 'cli-dist1-<timestamp>' and 'cli-dist2-<timestamp>' after running a distribution test
func CleanDistributionRepositories(t *testing.T, distributionDetails *config.ServerDetails) {
deleteSpec := spec.NewBuilder().Pattern(tests.DistRepo1).BuildSpec()
_, _, err := tests.DeleteFiles(deleteSpec, distributionDetails)
assert.NoError(t, err)
deleteSpec = spec.NewBuilder().Pattern(tests.DistRepo2).BuildSpec()
_, _, err = tests.DeleteFiles(deleteSpec, distributionDetails)
assert.NoError(t, err)
}