forked from AliyunContainerService/pouch
/
image_bridge.go
256 lines (211 loc) · 7.36 KB
/
image_bridge.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
package server
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/alibaba/pouch/apis/filters"
"github.com/alibaba/pouch/apis/metrics"
"github.com/alibaba/pouch/apis/types"
"github.com/alibaba/pouch/daemon/mgr"
"github.com/alibaba/pouch/pkg/errtypes"
"github.com/alibaba/pouch/pkg/httputils"
"github.com/alibaba/pouch/pkg/log"
util_metrics "github.com/alibaba/pouch/pkg/utils/metrics"
"github.com/go-openapi/strfmt"
"github.com/gorilla/mux"
"github.com/opencontainers/go-digest"
)
// pullImage will pull an image from a specified registry.
func (s *Server) pullImage(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
image := req.FormValue("fromImage")
tag := req.FormValue("tag")
if image == "" {
err := fmt.Errorf("fromImage cannot be empty")
return httputils.NewHTTPError(err, http.StatusBadRequest)
}
if tag != "" {
image = image + ":" + tag
}
label := util_metrics.ActionPullLabel
// record the time spent during image pull procedure.
defer func(start time.Time) {
metrics.ImageActionsCounter.WithLabelValues(label).Inc()
metrics.ImagePullSummary.WithLabelValues(image).Observe(util_metrics.SinceInMicroseconds(start))
metrics.ImageActionsTimer.WithLabelValues(label).Observe(time.Since(start).Seconds())
}(time.Now())
// get registry auth from Request header
authStr := req.Header.Get("X-Registry-Auth")
authConfig := types.AuthConfig{}
if authStr != "" {
data := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authStr))
if err := json.NewDecoder(data).Decode(&authConfig); err != nil {
return err
}
}
// Error information has be sent to client, so no need call resp.Write
if err := s.ImageMgr.PullImage(ctx, image, &authConfig, newWriteFlusher(rw)); err != nil {
log.With(ctx).Errorf("failed to pull image %s: %v", image, err)
if err == errtypes.ErrNotfound {
return httputils.NewHTTPError(err, http.StatusNotFound)
}
return err
}
metrics.ImageSuccessActionsCounter.WithLabelValues(label).Inc()
return nil
}
func (s *Server) getImage(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
idOrRef := mux.Vars(req)["name"]
imageInfo, err := s.ImageMgr.GetImage(ctx, idOrRef)
if err != nil {
log.With(ctx).Errorf("failed to get image: %v", err)
return err
}
return EncodeResponse(rw, http.StatusOK, imageInfo)
}
func (s *Server) listImages(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
filter, err := filters.FromParam(req.FormValue("filters"))
if err != nil {
return err
}
imageList, err := s.ImageMgr.ListImages(ctx, filter)
if err != nil {
log.With(ctx).Errorf("failed to list images: %v", err)
return err
}
return EncodeResponse(rw, http.StatusOK, imageList)
}
func (s *Server) searchImages(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
searchPattern := req.FormValue("term")
registry := req.FormValue("registry")
// get registry auth from Request header
authStr := req.Header.Get("X-Registry-Auth")
authConfig := types.AuthConfig{}
if authStr != "" {
data := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authStr))
if err := json.NewDecoder(data).Decode(&authConfig); err != nil {
return err
}
if err := authConfig.Validate(strfmt.NewFormats()); err != nil {
return err
}
}
searchResultItem, err := s.ImageMgr.SearchImages(ctx, searchPattern, registry, &authConfig)
if err != nil {
log.With(ctx).Errorf("failed to search images from registry: %v", err)
return err
}
return EncodeResponse(rw, http.StatusOK, searchResultItem)
}
// removeImage deletes an image by reference.
func (s *Server) removeImage(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
name := mux.Vars(req)["name"]
image, err := s.ImageMgr.GetImage(ctx, name)
if err != nil {
return err
}
refs, err := s.ImageMgr.ListReferences(ctx, digest.Digest(image.ID))
if err != nil {
return err
}
label := util_metrics.ActionDeleteLabel
defer func(start time.Time) {
metrics.ImageActionsCounter.WithLabelValues(label).Inc()
metrics.ImageActionsTimer.WithLabelValues(label).Observe(time.Since(start).Seconds())
}(time.Now())
isForce := httputils.BoolValue(req, "force")
isImageIDPrefix := func(imageID string, name string) bool {
if strings.HasPrefix(imageID, name) || strings.HasPrefix(digest.Digest(imageID).Hex(), name) {
return true
}
return false
}
// We should check the image whether used by container when there is only one primary reference
// or the image is removed by image ID.
if len(refs) == 1 || isImageIDPrefix(image.ID, name) {
containers, err := s.ContainerMgr.List(ctx, &mgr.ContainerListOption{
All: true,
FilterFunc: func(c *mgr.Container) bool {
return c.Image == image.ID
}})
if err != nil {
return err
}
if !isForce && len(containers) > 0 {
return fmt.Errorf("Unable to remove the image %q (must force) - container (%s, %s) is using this image", image.ID, containers[0].ID, containers[0].Name)
}
}
if err := s.ImageMgr.RemoveImage(ctx, name, isForce); err != nil {
return err
}
metrics.ImageSuccessActionsCounter.WithLabelValues(label).Inc()
rw.WriteHeader(http.StatusNoContent)
return nil
}
// postImageTag adds tag for the existing image.
func (s *Server) postImageTag(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
name := mux.Vars(req)["name"]
targetRef := req.FormValue("repo")
if tag := req.FormValue("tag"); tag != "" {
targetRef = fmt.Sprintf("%s:%s", targetRef, tag)
}
if err := s.ImageMgr.AddTag(ctx, name, targetRef); err != nil {
return err
}
rw.WriteHeader(http.StatusCreated)
return nil
}
// loadImage loads an image by http tar stream.
func (s *Server) loadImage(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
imageName := req.FormValue("name")
if err := s.ImageMgr.LoadImage(ctx, imageName, req.Body); err != nil {
return err
}
rw.WriteHeader(http.StatusOK)
return nil
}
// saveImage saves an image by http tar stream.
func (s *Server) saveImage(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
imageName := req.FormValue("name")
rw.Header().Set("Content-Type", "application/x-tar")
r, err := s.ImageMgr.SaveImage(ctx, imageName)
if err != nil {
return err
}
defer r.Close()
output := newWriteFlusher(rw)
_, err = io.Copy(output, r)
return err
}
// getImageHistory gets image history.
func (s *Server) getImageHistory(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
imageName := mux.Vars(req)["name"]
history, err := s.ImageMgr.ImageHistory(ctx, imageName)
if err != nil {
return err
}
return EncodeResponse(rw, http.StatusOK, history)
}
// pushImage will push an image to a specified registry.
func (s *Server) pushImage(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
name := mux.Vars(req)["name"]
tag := req.FormValue("tag")
// get registry auth from Request header
authStr := req.Header.Get("X-Registry-Auth")
authConfig := types.AuthConfig{}
if authStr != "" {
data := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authStr))
if err := json.NewDecoder(data).Decode(&authConfig); err != nil {
return err
}
}
if err := s.ImageMgr.PushImage(ctx, name, tag, &authConfig, newWriteFlusher(rw)); err != nil {
log.With(ctx).Errorf("failed to push image %s with tag %s: %v", name, tag, err)
return err
}
return nil
}