-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.go
215 lines (199 loc) · 6.61 KB
/
main.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
package main
import (
"context"
"fmt"
"log/slog"
"net/http"
"os"
"strings"
"github.com/chainguard-dev/clog/gcp"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/types"
"github.com/imjasonh/kontain.me/pkg/serve"
)
func main() {
ctx := context.Background()
st, err := serve.NewStorage(ctx)
if err != nil {
slog.ErrorContext(ctx, "serve.NewStorage", "err", err)
os.Exit(1)
}
http.Handle("/v2/", gcp.WithCloudTraceContext(&server{storage: st}))
http.Handle("/", http.RedirectHandler("https://github.com/imjasonh/kontain.me/blob/main/cmd/mirror", http.StatusSeeOther))
port := os.Getenv("PORT")
if port == "" {
port = "8080"
slog.InfoContext(ctx, "Defaulting port", "port", port)
}
slog.InfoContext(ctx, "Listening...", "port", port)
slog.ErrorContext(ctx, "ListenAndServe", "err", http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
type server struct{ storage *serve.Storage }
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.String(), "/v2/")
w.Header().Set("Access-Control-Allow-Origin", "*") // Allow CORS requests from any domain.
w.Header().Set("Access-Control-Expose-Headers", "*") // Respond with all headers to requests from any domain.
w.Header().Set("Access-Control-Allow-Credentials", "true") // Allow... credentials? I guess?
w.Header().Set("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS") // Allow CORS requests to use these methods.
w.Header().Set("Access-Control-Allow-Headers", "*") // Allow all CORS headers in the OPTIONS request.
if r.Method == http.MethodOptions {
return
}
switch {
case path == "":
// API Version check.
w.Header().Set("Docker-Distribution-API-Version", "registry/2.0")
return
case strings.Contains(path, "/blobs/"),
strings.Contains(path, "/manifests/sha256:"):
// Extract requested blob digest and redirect to serve it from GCS.
// If it doesn't exist, this will return 404.
parts := strings.Split(r.URL.Path, "/")
digest := parts[len(parts)-1]
serve.Blob(w, r, digest)
case strings.Contains(path, "/manifests/"):
s.serveMirrorManifest(w, r)
default:
serve.Error(w, serve.ErrNotFound)
}
}
// mirror.kontain.me/ubuntu -> mirror ubuntu and serve
func (s *server) serveMirrorManifest(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
path := strings.TrimPrefix(r.URL.Path, "/v2/")
parts := strings.Split(path, "/")
refstr := strings.Join(parts[:len(parts)-2], "/")
tagOrDigest := parts[len(parts)-1]
if strings.HasPrefix(tagOrDigest, "sha256:") {
refstr += "@" + tagOrDigest
} else {
refstr += ":" + tagOrDigest
}
for strings.HasPrefix(refstr, "mirror.kontain.me/") {
refstr = strings.TrimPrefix(refstr, "mirror.kontain.me/")
}
ref, err := name.ParseReference(refstr)
if err != nil {
slog.ErrorContext(ctx, "name.ParseReference", "ref", refstr, "err", err)
serve.Error(w, err)
return
}
// If it's a HEAD request, and request was by digest, and we have that
// manifest mirrored by digest already, serve HEAD response from GCS.
// If it's a HEAD request and the other conditions aren't met, we'll
// handle this later by consulting the real registry.
if r.Method == http.MethodHead {
if d, ok := ref.(name.Digest); ok {
if desc, err := s.storage.BlobExists(ctx, d.DigestStr()); err == nil {
w.Header().Set("Docker-Content-Digest", d.DigestStr())
w.Header().Set("Content-Type", string(desc.MediaType))
w.Header().Set("Content-Length", fmt.Sprintf("%d", desc.Size))
return
}
}
}
var idx v1.ImageIndex
var img v1.Image
// Get the original image's digest, and check if we have that manifest
// blob.
d, err := remote.Head(ref, remote.WithContext(ctx))
if err != nil {
slog.ErrorContext(ctx, "remote.Head", "ref", ref, "err", err)
var desci interface {
Digest() (v1.Hash, error)
Size() (int64, error)
MediaType() (types.MediaType, error)
}
// HEAD failed, let's figure out if it was an index or image by doing GETs.
idx, err = remote.Index(ref, remote.WithContext(ctx))
if err != nil {
slog.ErrorContext(ctx, "remote.Index", "ref", ref, "err", err)
img, err = remote.Image(ref, remote.WithContext(ctx))
if err != nil {
slog.ErrorContext(ctx, "remote.Image", "ref", ref, "err", err)
serve.Error(w, err)
return
}
desci = img
} else {
desci = idx
}
h, err := desci.Digest()
if err != nil {
slog.ErrorContext(ctx, "Digest()", "ref", ref, "err", err)
serve.Error(w, err)
return
}
sz, err := desci.Size()
if err != nil {
slog.ErrorContext(ctx, "Size()", "ref", ref, "err", err)
serve.Error(w, err)
return
}
mt, err := desci.MediaType()
if err != nil {
slog.ErrorContext(ctx, "MediaType()", "ref", ref, "err", err)
serve.Error(w, err)
return
}
d = &v1.Descriptor{
Digest: h,
MediaType: mt,
Size: sz,
}
}
if r.Method == http.MethodHead {
w.Header().Set("Docker-Content-Digest", d.Digest.String())
w.Header().Set("Content-Type", string(d.MediaType))
w.Header().Set("Content-Length", fmt.Sprintf("%d", d.Size))
return
}
if _, err := s.storage.BlobExists(ctx, d.Digest.String()); err == nil {
serve.Blob(w, r, d.Digest.String())
return
} else {
slog.InfoContext(ctx, "BlobExists", "digest", d.Digest.String(), "err", err)
}
// Blob doesn't exist yet. Try to get the image manifest+layers
// and cache them.
switch d.MediaType {
case types.OCIImageIndex, types.DockerManifestList:
if idx == nil {
// If the image is a manifest list, fetch and mirror
// the image index.
idx, err = remote.Index(ref, remote.WithContext(ctx))
if err != nil {
slog.ErrorContext(ctx, "remote.Index", "ref", ref, "err", err)
serve.Error(w, err)
return
}
}
if err := s.storage.ServeIndex(w, r, idx); err != nil {
slog.ErrorContext(ctx, "storage.ServeIndex", "err", err)
serve.Error(w, err)
return
}
case types.OCIManifestSchema1, types.DockerManifestSchema2:
if img == nil {
// If it's a simple image, fetch and mirror its
// manifest.
img, err = remote.Image(ref, remote.WithContext(ctx))
if err != nil {
slog.ErrorContext(ctx, "remote.Image", "ref", ref, "err", err)
serve.Error(w, err)
return
}
}
if err := s.storage.ServeManifest(w, r, img); err != nil {
slog.ErrorContext(ctx, "storage.ServeManifest", "err", err)
serve.Error(w, err)
return
}
default:
err := fmt.Errorf("unknown media type: %s", d.MediaType)
slog.ErrorContext(ctx, "unknown media type", "ref", refstr, "err", err)
serve.Error(w, err)
}
}