forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mirror.go
368 lines (298 loc) · 11 KB
/
mirror.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
package images
import (
"crypto/rand"
"encoding/base64"
"fmt"
"regexp"
"strings"
"time"
g "github.com/onsi/ginkgo"
o "github.com/onsi/gomega"
kapiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/wait"
kclientset "k8s.io/client-go/kubernetes"
"k8s.io/kubernetes/test/e2e/framework"
exutil "github.com/openshift/origin/test/extended/util"
)
const podStartupTimeout = 3 * time.Minute
const testPod1 = `kind: Pod
id: oc-image-mirror-test-1
apiVersion: v1
metadata:
name: oc-image-mirror-test-1
labels:
name: oc-image-mirror-test-1
spec:
containers:
- name: registry-1
image: docker.io/library/registry
env:
- name: REGISTRY_HTTP_ADDR
value: :5001
- name: REGISTRY_HTTP_NET
value: tcp
- name: REGISTRY_LOGLEVEL
value: debug
- name: REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY
value: /tmp
- name: shell
image: openshift/origin:latest
command:
- /bin/sleep
- infinity
`
const testPod2 = `kind: Pod
id: oc-image-mirror-test-2
apiVersion: v1
metadata:
name: oc-image-mirror-test-2
labels:
name: oc-image-mirror-test-2
spec:
containers:
- name: registry-1
image: docker.io/library/registry
env:
- name: REGISTRY_HTTP_ADDR
value: :5002
- name: REGISTRY_HTTP_NET
value: tcp
- name: REGISTRY_LOGLEVEL
value: debug
- name: REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY
value: /tmp
- name: registry-2
image: docker.io/library/registry
env:
- name: REGISTRY_HTTP_ADDR
value: :5003
- name: REGISTRY_HTTP_NET
value: tcp
- name: REGISTRY_LOGLEVEL
value: debug
- name: REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY
value: /tmp
- name: shell
image: openshift/origin:latest
command:
- /bin/sleep
- infinity
`
func getRandName() string {
c := 20
b := make([]byte, c)
_, err := rand.Read(b)
o.Expect(err).NotTo(o.HaveOccurred())
return fmt.Sprintf("%02x", b)
}
func getCreds(oc *exutil.CLI) (string, string) {
user, err := oc.Run("whoami").Args().Output()
o.Expect(err).NotTo(o.HaveOccurred())
token, err := oc.Run("whoami").Args("-t").Output()
o.Expect(err).NotTo(o.HaveOccurred())
return strings.TrimSpace(user), strings.TrimSpace(token)
}
type testPod struct {
oc *exutil.CLI
name string
spec string
}
func NewTestPod(oc *exutil.CLI, name, spec string) *testPod {
return &testPod{
oc: oc,
name: name,
spec: spec,
}
}
func (pod *testPod) syncState(c kclientset.Interface, ns string, timeout time.Duration, state kapiv1.PodPhase) (err error) {
label := labels.SelectorFromSet(map[string]string{
"name": pod.name,
})
err = wait.Poll(2*time.Second, timeout,
func() (bool, error) {
podList, err := framework.WaitForPodsWithLabel(c, ns, label)
if err != nil {
framework.Logf("Failed getting pods: %v", err)
return false, nil // Ignore this error (nil) and try again in "Poll" time
}
pods := podList.Items
if pods == nil || len(pods) == 0 {
return true, nil
}
for _, p := range pods {
if p.Status.Phase != state {
return false, nil
}
}
return true, nil
})
return err
}
func (pod *testPod) syncRunning(c kclientset.Interface, ns string, timeout time.Duration) (err error) {
err = pod.syncState(c, ns, timeout, kapiv1.PodRunning)
if err == nil {
framework.Logf("All pods running in %s", ns)
}
return err
}
func (pod *testPod) NotErr(err error) {
if err != nil {
exutil.DumpPodLogsStartingWithInNamespace(pod.name, pod.oc.Namespace(), pod.oc)
}
o.Expect(err).NotTo(o.HaveOccurred())
}
func (pod *testPod) Run() *testPod {
g.By("Set up and fetch the URL of external registry server")
err := pod.oc.Run("create").Args("-f", "-").InputString(pod.spec).Execute()
o.Expect(err).NotTo(o.HaveOccurred())
pod.NotErr(pod.syncRunning(pod.oc.AdminKubeClient(), pod.oc.Namespace(), podStartupTimeout))
return pod
}
func (pod *testPod) ShellExec(command ...string) *exutil.CLI {
args := []string{}
args = append(args, pod.name, "-i", "-c", "shell", "--")
for _, a := range command {
args = append(args, a)
}
return pod.oc.Run("exec").Args(args...)
}
func genDockerConfig(pod *testPod, registryURL, user, token string) {
config := fmt.Sprintf(`{"auths":{%q:{"auth":%q}}}`, registryURL, base64.StdEncoding.EncodeToString([]byte(user+":"+token)))
err := pod.ShellExec("bash", "-c", "cd /tmp; cat > config.json").InputString(config).Execute()
o.Expect(err).NotTo(o.HaveOccurred())
}
func getRegistrySchema(pod *testPod, host string) (schema string, err error) {
for _, schema = range []string{"https", "http"} {
framework.Logf("try %s protocol", schema)
err = pod.ShellExec("curl", "-s", "-k", "-L", "-o", "/dev/null", fmt.Sprintf("%s://%s/v2/", schema, host)).Execute()
if err == nil {
return
}
}
return
}
func runHTTPRequest(pod *testPod, URL string, headers map[string]string) (string, error) {
command := []string{"curl", "-s", "-v", "-k", "-L", "-o", "/dev/null"}
for k, v := range headers {
command = append(command, "-H", fmt.Sprintf("%s", k+":"+v))
}
command = append(command, URL)
return pod.ShellExec(command...).Output()
}
func requestHasStatusCode(pod *testPod, URL, token, statusCode string) {
headers := map[string]string{}
if len(token) > 0 {
headers["Authorization"] = "bearer " + token
}
out, err := runHTTPRequest(pod, URL, headers)
o.Expect(err).NotTo(o.HaveOccurred())
m := regexp.MustCompile(fmt.Sprintf(`(?m)^< HTTP/1\.1 %s `, statusCode)).FindString(out)
if len(m) == 0 {
err = fmt.Errorf("unexpected status code (expected %s): %s", statusCode, out)
}
pod.NotErr(err)
}
func testNewBuild(oc *exutil.CLI) (string, string) {
isName := "mirror-" + getRandName()
istName := isName + ":latest"
testDockerfile := fmt.Sprintf(`FROM busybox:latest
RUN echo %s > /1
RUN echo %s > /2
RUN echo %s > /3
`,
getRandName(),
getRandName(),
getRandName(),
)
err := oc.Run("new-build").Args("-D", "-", "--to", istName).InputString(testDockerfile).Execute()
o.Expect(err).NotTo(o.HaveOccurred())
g.By("starting a test build")
bc, err := oc.BuildClient().Build().BuildConfigs(oc.Namespace()).Get(isName, metav1.GetOptions{})
o.Expect(err).NotTo(o.HaveOccurred())
o.Expect(*bc.Spec.Source.Dockerfile).To(o.Equal(testDockerfile))
g.By("expecting the Dockerfile build is in Complete phase")
err = exutil.WaitForABuild(oc.BuildClient().Build().Builds(oc.Namespace()), isName+"-1", nil, nil, nil)
o.Expect(err).NotTo(o.HaveOccurred())
g.By(fmt.Sprintf("checking for the imported tag: %s", istName))
ist, err := oc.ImageClient().Image().ImageStreamTags(oc.Namespace()).Get(istName, metav1.GetOptions{})
o.Expect(err).NotTo(o.HaveOccurred())
return isName, ist.Image.Name
}
var _ = g.Describe("[Feature:ImageMirror][registry][Slow] Image mirror", func() {
defer g.GinkgoRecover()
var oc = exutil.NewCLI("image-mirror", exutil.KubeConfigPath())
g.It("mirror image from integrated registry to external registry", func() {
g.By("get user credentials")
user, token := getCreds(oc)
g.By("fetch the URL of integrated registry server")
registryHost, err := GetDockerRegistryURL(oc)
o.Expect(err).NotTo(o.HaveOccurred())
g.By("Set up and fetch the URL of external registry server")
pod := NewTestPod(oc, "oc-image-mirror-test-1", testPod1).Run()
g.By("get the protocol of integrated registry server")
schema, err := getRegistrySchema(pod, registryHost)
pod.NotErr(err)
framework.Logf("the protocol is %s://%s", schema, registryHost)
g.By("generate config.json for integrated registry server")
genDockerConfig(pod, registryHost, user, token)
g.By("calling oc new-build with Dockerfile")
isName, imgName := testNewBuild(oc)
repoName := oc.Namespace() + "/" + isName
g.By("Check that we have it in the integrated registry server")
requestHasStatusCode(pod, fmt.Sprintf("%s://%s/v2/%s/manifests/%s", schema, registryHost, repoName, imgName), token, "200")
g.By("Check that we do not have it in the external registry server")
requestHasStatusCode(pod, fmt.Sprintf("http://127.0.0.1:5001/v2/%s/manifests/%s", repoName, imgName), "", "404")
g.By("Mirror image from the integrated registry server to the external registry server")
command := fmt.Sprintf("cd /tmp; oc --loglevel=8 image mirror %s/%s:latest %s/%s:stable --insecure=true",
registryHost, repoName, "127.0.0.1:5001", repoName,
)
err = pod.ShellExec([]string{"bash", "-c", command}...).Execute()
pod.NotErr(err)
g.By("Check that we have it in the external registry server")
requestHasStatusCode(pod, fmt.Sprintf("http://127.0.0.1:5001/v2/%s/manifests/%s", repoName, imgName), "", "200")
g.By("remove external registry pods")
err = exutil.RemovePodsWithPrefixes(oc, pod.name)
o.Expect(err).NotTo(o.HaveOccurred())
})
g.It("mirror image from integrated registry into few external registries", func() {
g.By("get user credentials")
user, token := getCreds(oc)
g.By("fetch the URL of integrated registry server")
registryHost, err := GetDockerRegistryURL(oc)
o.Expect(err).NotTo(o.HaveOccurred())
g.By("Set up and fetch the URL of external registry server")
pod := NewTestPod(oc, "oc-image-mirror-test-2", testPod2).Run()
g.By("get the protocol of integrated registry server")
schema, err := getRegistrySchema(pod, registryHost)
pod.NotErr(err)
framework.Logf("the protocol is %s://%s", schema, registryHost)
g.By("generate config.json for integrated registry server")
genDockerConfig(pod, registryHost, user, token)
g.By("calling oc new-build with Dockerfile")
isName, imgName := testNewBuild(oc)
repoName := oc.Namespace() + "/" + isName
g.By("Check that we have it in the integrated registry server")
requestHasStatusCode(pod, fmt.Sprintf("%s://%s/v2/%s/manifests/%s", schema, registryHost, repoName, imgName), token, "200")
g.By("Check that we do not have it in the first external registry server")
requestHasStatusCode(pod, fmt.Sprintf("http://127.0.0.1:5002/v2/%s/manifests/%s", repoName, imgName), "", "404")
g.By("Check that we do not have it in the second external registry server")
requestHasStatusCode(pod, fmt.Sprintf("http://127.0.0.1:5003/v2/%s/manifests/%s", repoName, imgName), "", "404")
g.By("Mirror image from the integrated registry server to the external registry server")
command := fmt.Sprintf("cd /tmp; oc image mirror %s/%s:latest %s/%s:stable %s/%s:prod --insecure=true",
registryHost, repoName,
"127.0.0.1:5002", repoName,
"127.0.0.1:5003", repoName,
)
err = pod.ShellExec([]string{"bash", "-c", command}...).Execute()
pod.NotErr(err)
g.By("Check that we have it in the first external registry server")
requestHasStatusCode(pod, fmt.Sprintf("http://127.0.0.1:5002/v2/%s/manifests/%s", repoName, imgName), "", "200")
g.By("Check that we have it in the second external registry server")
requestHasStatusCode(pod, fmt.Sprintf("http://127.0.0.1:5003/v2/%s/manifests/%s", repoName, imgName), "", "200")
g.By("remove external registry pods")
err = exutil.RemovePodsWithPrefixes(oc, pod.name)
o.Expect(err).NotTo(o.HaveOccurred())
})
})