-
Notifications
You must be signed in to change notification settings - Fork 254
/
http-datasource.go
359 lines (315 loc) · 10.8 KB
/
http-datasource.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
/*
Copyright 2018 The CDI 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 importer
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
"path/filepath"
"strconv"
"sync"
"time"
"github.com/pkg/errors"
"k8s.io/klog/v2"
cdiv1 "kubevirt.io/containerized-data-importer/pkg/apis/core/v1beta1"
"kubevirt.io/containerized-data-importer/pkg/util"
)
const (
tempFile = "tmpimage"
)
// HTTPDataSource is the data provider for http(s) endpoints.
// Sequence of phases:
// 1a. Info -> Convert (In Info phase the format readers are configured), if the source Reader image is not archived, and no custom CA is used, and can be converted by QEMU-IMG (RAW/QCOW2)
// 1b. Info -> TransferArchive if the content type is archive
// 1c. Info -> Transfer in all other cases.
// 2a. Transfer -> Process if content type is kube virt
// 2b. Transfer -> Complete if content type is archive (Transfer is called with the target instead of the scratch space). Non block PVCs only.
// 3. Process -> Convert
type HTTPDataSource struct {
httpReader io.ReadCloser
ctx context.Context
cancel context.CancelFunc
cancelLock sync.Mutex
// content type expected by the to live on the endpoint.
contentType cdiv1.DataVolumeContentType
// stack of readers
readers *FormatReaders
// endpoint the http endpoint to retrieve the data from.
endpoint *url.URL
// url the url to report to the caller of getURL, could be the endpoint, or a file in scratch space.
url *url.URL
// true if we are using a custom CA (and thus have to use scratch storage)
customCA bool
// true if we know `qemu-img` will fail to download this
brokenForQemuImg bool
// the content length reported by the http server.
contentLength uint64
}
// NewHTTPDataSource creates a new instance of the http data provider.
func NewHTTPDataSource(endpoint, accessKey, secKey, certDir string, contentType cdiv1.DataVolumeContentType) (*HTTPDataSource, error) {
ep, err := ParseEndpoint(endpoint)
if err != nil {
return nil, errors.Wrapf(err, fmt.Sprintf("unable to parse endpoint %q", endpoint))
}
ctx, cancel := context.WithCancel(context.Background())
httpReader, contentLength, brokenForQemuImg, err := createHTTPReader(ctx, ep, accessKey, secKey, certDir)
if err != nil {
cancel()
return nil, err
}
if accessKey != "" && secKey != "" {
ep.User = url.UserPassword(accessKey, secKey)
}
httpSource := &HTTPDataSource{
ctx: ctx,
cancel: cancel,
httpReader: httpReader,
contentType: contentType,
endpoint: ep,
customCA: certDir != "",
brokenForQemuImg: brokenForQemuImg,
contentLength: contentLength,
}
// We know this is a counting reader, so no need to check.
countingReader := httpReader.(*util.CountingReader)
go httpSource.pollProgress(countingReader, 10*time.Minute, time.Second)
return httpSource, nil
}
// Info is called to get initial information about the data.
func (hs *HTTPDataSource) Info() (ProcessingPhase, error) {
var err error
hs.readers, err = NewFormatReaders(hs.httpReader, hs.contentLength)
if hs.contentType == cdiv1.DataVolumeArchive {
return ProcessingPhaseTransferDataDir, nil
}
if err != nil {
klog.Errorf("Error creating readers: %v", err)
return ProcessingPhaseError, err
}
// The readers now contain all the information needed to determine if we can stream directly or if we need scratch space to download
// the file to, before converting.
if !hs.readers.Archived && !hs.customCA && !hs.brokenForQemuImg && hs.readers.Convert {
// We can pass straight to conversion from the endpoint. No scratch required.
hs.url = hs.endpoint
return ProcessingPhaseConvert, nil
}
if !hs.readers.Convert {
return ProcessingPhaseTransferDataFile, nil
}
return ProcessingPhaseTransferScratch, nil
}
// Transfer is called to transfer the data from the source to a scratch location.
func (hs *HTTPDataSource) Transfer(path string) (ProcessingPhase, error) {
if hs.contentType == cdiv1.DataVolumeKubeVirt {
size, err := util.GetAvailableSpace(path)
if size <= int64(0) {
//Path provided is invalid.
return ProcessingPhaseError, ErrInvalidPath
}
file := filepath.Join(path, tempFile)
err = util.StreamDataToFile(hs.readers.TopReader(), file)
if err != nil {
return ProcessingPhaseError, err
}
// If we successfully wrote to the file, then the parse will succeed.
hs.url, _ = url.Parse(file)
return ProcessingPhaseConvert, nil
} else if hs.contentType == cdiv1.DataVolumeArchive {
if err := util.UnArchiveTar(hs.readers.TopReader(), path); err != nil {
return ProcessingPhaseError, errors.Wrap(err, "unable to untar files from endpoint")
}
hs.url = nil
return ProcessingPhaseComplete, nil
}
return ProcessingPhaseError, errors.Errorf("Unknown content type: %s", hs.contentType)
}
// TransferFile is called to transfer the data from the source to the passed in file.
func (hs *HTTPDataSource) TransferFile(fileName string) (ProcessingPhase, error) {
hs.readers.StartProgressUpdate()
err := util.StreamDataToFile(hs.readers.TopReader(), fileName)
if err != nil {
return ProcessingPhaseError, err
}
return ProcessingPhaseResize, nil
}
// GetURL returns the URI that the data processor can use when converting the data.
func (hs *HTTPDataSource) GetURL() *url.URL {
return hs.url
}
// Close all readers.
func (hs *HTTPDataSource) Close() error {
var err error
if hs.readers != nil {
err = hs.readers.Close()
}
hs.cancelLock.Lock()
if hs.cancel != nil {
hs.cancel()
hs.cancel = nil
}
hs.cancelLock.Unlock()
return err
}
func createHTTPClient(certDir string) (*http.Client, error) {
client := &http.Client{
// Don't set timeout here, since that will be an absolute timeout, we need a relative to last progress timeout.
}
if certDir == "" {
return client, nil
}
// let's get system certs as well
certPool, err := x509.SystemCertPool()
if err != nil {
return nil, errors.Wrap(err, "Error getting system certs")
}
files, err := ioutil.ReadDir(certDir)
if err != nil {
return nil, errors.Wrapf(err, "Error listing files in %s", certDir)
}
for _, file := range files {
if file.IsDir() || file.Name()[0] == '.' {
continue
}
fp := path.Join(certDir, file.Name())
klog.Infof("Attempting to get certs from %s", fp)
certs, err := ioutil.ReadFile(fp)
if err != nil {
return nil, errors.Wrapf(err, "Error reading file %s", fp)
}
if ok := certPool.AppendCertsFromPEM(certs); !ok {
klog.Warningf("No certs in %s", fp)
}
}
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: certPool,
},
}
return client, nil
}
func createHTTPReader(ctx context.Context, ep *url.URL, accessKey, secKey, certDir string) (io.ReadCloser, uint64, bool, error) {
var brokenForQemuImg bool
client, err := createHTTPClient(certDir)
if err != nil {
return nil, uint64(0), false, errors.Wrap(err, "Error creating http client")
}
client.CheckRedirect = func(r *http.Request, via []*http.Request) error {
if len(accessKey) > 0 && len(secKey) > 0 {
r.SetBasicAuth(accessKey, secKey) // Redirects will lose basic auth, so reset them manually
}
return nil
}
total, err := getContentLength(client, ep, accessKey, secKey)
if err != nil {
brokenForQemuImg = true
}
// http.NewRequest can only return error on invalid METHOD, or invalid url. Here the METHOD is always GET, and the url is always valid, thus error cannot happen.
req, _ := http.NewRequest("GET", ep.String(), nil)
req = req.WithContext(ctx)
if len(accessKey) > 0 && len(secKey) > 0 {
req.SetBasicAuth(accessKey, secKey)
}
klog.V(2).Infof("Attempting to get object %q via http client\n", ep.String())
resp, err := client.Do(req)
if err != nil {
return nil, uint64(0), true, errors.Wrap(err, "HTTP request errored")
}
if resp.StatusCode != 200 {
klog.Errorf("http: expected status code 200, got %d", resp.StatusCode)
return nil, uint64(0), true, errors.Errorf("expected status code 200, got %d. Status: %s", resp.StatusCode, resp.Status)
}
acceptRanges, ok := resp.Header["Accept-Ranges"]
if !ok || acceptRanges[0] == "none" {
klog.V(2).Infof("Accept-Ranges isn't bytes, avoiding qemu-img")
brokenForQemuImg = true
}
if total == 0 {
// The total seems bogus. Let's try the GET Content-Length header
total = parseHTTPHeader(resp)
}
countingReader := &util.CountingReader{
Reader: resp.Body,
Current: 0,
}
return countingReader, total, brokenForQemuImg, nil
}
func (hs *HTTPDataSource) pollProgress(reader *util.CountingReader, idleTime, pollInterval time.Duration) {
count := reader.Current
lastUpdate := time.Now()
for {
if count < reader.Current {
// Some progress was made, reset now.
lastUpdate = time.Now()
count = reader.Current
}
if time.Until(lastUpdate.Add(idleTime)).Nanoseconds() < 0 {
hs.cancelLock.Lock()
if hs.cancel != nil {
// No progress for the idle time, cancel http client.
hs.cancel() // This will trigger dp.ctx.Done()
}
hs.cancelLock.Unlock()
}
select {
case <-time.After(pollInterval):
continue
case <-hs.ctx.Done():
return // Don't leak, once the transfer is cancelled or completed this is called.
}
}
}
func getContentLength(client *http.Client, ep *url.URL, accessKey, secKey string) (uint64, error) {
req, err := http.NewRequest("HEAD", ep.String(), nil)
if err != nil {
return uint64(0), errors.Wrap(err, "could not create HTTP request")
}
if len(accessKey) > 0 && len(secKey) > 0 {
req.SetBasicAuth(accessKey, secKey)
}
klog.V(2).Infof("Attempting to HEAD %q via http client\n", ep.String())
resp, err := client.Do(req)
if err != nil {
return uint64(0), errors.Wrap(err, "HTTP request errored")
}
if resp.StatusCode != 200 {
klog.Errorf("http: expected status code 200, got %d", resp.StatusCode)
return uint64(0), errors.Errorf("expected status code 200, got %d. Status: %s", resp.StatusCode, resp.Status)
}
for k, v := range resp.Header {
klog.V(3).Infof("GO CLIENT: key: %s, value: %s\n", k, v)
}
total := parseHTTPHeader(resp)
err = resp.Body.Close()
if err != nil {
return uint64(0), errors.Wrap(err, "could not close head read")
}
return total, nil
}
func parseHTTPHeader(resp *http.Response) uint64 {
var err error
total := uint64(0)
if val, ok := resp.Header["Content-Length"]; ok {
total, err = strconv.ParseUint(val[0], 10, 64)
if err != nil {
klog.Errorf("could not convert content length, got %v", err)
}
klog.V(3).Infof("Content length: %d\n", total)
}
return total
}