~tsileo/blobstash

ref: b178995e346d blobstash/pkg/client/client.go -rw-r--r-- 9.7 KiB
b178995eThomas Sileo vendor: update deps 1 year, 11 months ago
                                                                                
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package client // import "a4.io/blobstash/pkg/client"

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"

	"a4.io/blobstash/pkg/client/response"
)

// TODO(tsileo): RESHAPE this! with doReq and simpler API (especially for the blob upload).

// ErrBlobNotFound is returned from a get/stat request
// if the blob does not exist.
var ErrBlobNotFound = errors.New("blob not found")
var ErrKeyNotFound = errors.New("key doest not exist")

var defaultServerAddr = "http://localhost:8050"

type KvStore struct {
	ServerAddr string
	client     *http.Client
}

func NewKvStore(serverAddr string) *KvStore {
	if serverAddr == "" {
		serverAddr = defaultServerAddr
	}
	return &KvStore{
		ServerAddr: serverAddr,
		client:     &http.Client{},
	}
}

func (kvs *KvStore) Put(key, value string, version int) (*response.KeyValue, error) {
	data := url.Values{}
	data.Set("value", value)
	if version != -1 {
		data.Set("version", strconv.Itoa(version))
	}
	request, err := http.NewRequest("PUT", kvs.ServerAddr+"/api/v1/vkv/key/"+key, strings.NewReader(data.Encode())) //data.Encode()))
	if err != nil {
		return nil, err
	}
	resp, err := kvs.client.Do(request)
	if err != nil {
		return nil, err
	}
	var body bytes.Buffer
	body.ReadFrom(resp.Body)
	resp.Body.Close()
	switch resp.StatusCode {
	case 200:
		kv := &response.KeyValue{}
		if err := json.Unmarshal(body.Bytes(), kv); err != nil {
			return nil, err
		}
		return kv, nil
	default:
		return nil, fmt.Errorf("failed to put key %v: %v", key, body.String())
	}
}

func (kvs *KvStore) Get(key string, version int) (*response.KeyValue, error) {
	request, err := http.NewRequest("GET", kvs.ServerAddr+"/api/v1/vkv/key/"+key, nil)
	if err != nil {
		return nil, err
	}
	resp, err := kvs.client.Do(request)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	switch {
	case resp.StatusCode == 200:
		kv := &response.KeyValue{}
		if err := json.Unmarshal(body, kv); err != nil {
			return nil, err
		}
		return kv, nil
	case resp.StatusCode == 404:
		return nil, ErrKeyNotFound
	default:
		return nil, fmt.Errorf("failed to get key %v: %v", key, string(body))
	}

}

func (kvs *KvStore) Versions(key string, start, end, limit int) (*response.KeyValueVersions, error) {
	// TODO handle start, end and limit
	request, err := http.NewRequest("GET", kvs.ServerAddr+"/api/v1/vkv/key/"+key+"/versions", nil)
	if err != nil {
		return nil, err
	}
	resp, err := kvs.client.Do(request)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	switch {
	case resp.StatusCode == 200:
		kvversions := &response.KeyValueVersions{}
		if err := json.Unmarshal(body, kvversions); err != nil {
			return nil, err
		}
		return kvversions, nil
	case resp.StatusCode == 404:
		return nil, ErrBlobNotFound
	default:
		return nil, fmt.Errorf("failed to get key %v: %v", key, string(body))
	}
}

// NextKey returns the next key for lexigraphical (key = NextKey(lastkey))
func NextKey(key string) string {
	bkey := []byte(key)
	i := len(bkey)
	for i > 0 {
		i--
		bkey[i]++
		if bkey[i] != 0 {
			break
		}
	}
	return string(bkey)
}

func (kvs *KvStore) Keys(start, end string, limit int) ([]*response.KeyValue, error) {
	request, err := http.NewRequest("GET", kvs.ServerAddr+"/api/v1/vkv/keys?start="+start+"&end="+fmt.Sprintf("%v&limit=%d", end, limit), nil)
	if err != nil {
		return nil, err
	}
	resp, err := kvs.client.Do(request)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	switch {
	case resp.StatusCode == 200:
		keys := &response.KeysResponse{}
		if err := json.Unmarshal(body, keys); err != nil {
			return nil, err
		}
		return keys.Keys, nil
	default:
		return nil, fmt.Errorf("failed to get keys: %v", string(body))
	}
}

type Blob struct {
	Hash string
	Blob string
}

type BlobStore struct {
	pipeline   bool
	wg         sync.WaitGroup
	stop       chan struct{}
	blobs      chan *Blob
	ServerAddr string
	client     *http.Client
	apiKey     string
}

func NewBlobStore(serverAddr string) *BlobStore {
	if serverAddr == "" {
		serverAddr = defaultServerAddr
	}
	return &BlobStore{
		ServerAddr: serverAddr,
		client:     &http.Client{},
		blobs:      make(chan *Blob),
		stop:       make(chan struct{}),
		pipeline:   false,
	}
}
func (bs *BlobStore) SetAPIKey(apiKey string) {
	bs.apiKey = apiKey
}

// Get fetch the given blob.
func (bs *BlobStore) Get(hash string) ([]byte, error) {
	request, err := http.NewRequest("GET", bs.ServerAddr+"/api/v1/blobstore/blob/"+hash, nil)
	if err != nil {
		return nil, err
	}
	if bs.apiKey != "" {
		request.SetBasicAuth("", bs.apiKey)
	}
	resp, err := bs.client.Do(request)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	switch {
	case resp.StatusCode == 200:
		return body, nil
	case resp.StatusCode == 404:
		return nil, ErrBlobNotFound
	default:
		return nil, fmt.Errorf("failed to get blob %v: %v", hash, string(body))
	}
}

type BlobsResp struct {
	Blobs []string `json:"blobs"`
}

func (bs *BlobStore) Enumerate(blobs chan<- string, start, end string, limit int) error {
	request, err := http.NewRequest("GET", bs.ServerAddr+"/api/v1/blobstore/blobs?start="+start+"&end="+end+"&limit="+strconv.Itoa(limit), nil)
	if err != nil {
		return err
	}
	if bs.apiKey != "" {
		request.SetBasicAuth("", bs.apiKey)
	}
	resp, err := bs.client.Do(request)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	switch {
	case resp.StatusCode == 200:
		br := &BlobsResp{}
		if err := json.Unmarshal(body, br); err != nil {
			return err
		}
		for _, h := range br.Blobs {
			blobs <- h
		}
		return nil
	default:
		return fmt.Errorf("failed to enumerate blobs: %v", string(body))
	}
}

// Stat checks wether a blob exists or not.
func (bs *BlobStore) Stat(hash string) (bool, error) {
	request, err := http.NewRequest("HEAD", bs.ServerAddr+"/api/v1/blobstore/blob/"+hash, nil)
	if err != nil {
		return false, err
	}
	if bs.apiKey != "" {
		request.SetBasicAuth("", bs.apiKey)
	}
	resp, err := bs.client.Do(request)
	if err != nil {
		return false, err
	}
	resp.Body.Close()
	switch {
	case resp.StatusCode == 200:
		return true, nil
	case resp.StatusCode == 404:
		return false, nil
	default:
		return false, fmt.Errorf("failed to put blob %v", hash)
	}
}

func (bs *BlobStore) WaitBlobs() {
	//close(bs.stop)
	bs.wg.Wait()
	close(bs.blobs)
}

func (bs *BlobStore) processBlobs() {
	//bs.wg.Add(1)
	//defer bs.wg.Done()
	//bb := NewBlobsBuffer(bs)
	//defer func() {
	//	bb.Upload()
	//	bb.Close()
	//}()
	for blob := range bs.blobs {
		//select {
		//case blob := <-bs.blobs:
		data, err := base64.StdEncoding.DecodeString(blob.Blob)
		if err != nil {
			panic(err)
		}
		//if err := bb.AddBlob(blob.Hash, data); err != nil {
		//	panic(err)
		//}
		//if bb.size >= 10 {
		//	if err := bb.Upload(); err != nil {
		//		panic(err)
		//	}
		//}
		//if mpw.Cnt >=
		if err := bs.put(blob.Hash, data); err != nil {
			panic(err)
		}
		bs.wg.Done()
		//case <-bs.stop:
		//	return
		//}
	}
}

func (bs *BlobStore) ProcessBlobs() {
	go func() {
		for i := 0; i < 15; i++ {
			go bs.processBlobs()
		}
	}()
	bs.pipeline = true
}

func (bs *BlobStore) Put(hash string, blob []byte) error {
	if bs.pipeline {
		bs.wg.Add(1)
		bs.blobs <- &Blob{Hash: hash, Blob: base64.StdEncoding.EncodeToString(blob)}
		return nil
	}
	return bs.put(hash, blob)
}

type MultipartWriter struct {
	Buffer *bytes.Buffer
	Writer *multipart.Writer
	Blobs  int
}

func NewMultipartWriter() *MultipartWriter {
	buf := &bytes.Buffer{}
	return &MultipartWriter{
		Buffer: buf,
		Writer: multipart.NewWriter(buf),
	}
}

func (mpw *MultipartWriter) Close() error {
	return mpw.Writer.Close()
}

func (mpw *MultipartWriter) FormDataContentType() string {
	return mpw.Writer.FormDataContentType()
}

func (mpw *MultipartWriter) AddBlob(hash string, blob []byte) error {
	part, err := mpw.Writer.CreateFormFile(hash, hash)
	if err != nil {
		return err
	}
	if _, err := part.Write(blob); err != nil {
		return err
	}
	mpw.Blobs++
	return nil
}

type BlobsBuffer struct {
	mpw  *MultipartWriter
	bs   *BlobStore
	size int
	sync.Mutex
}

func NewBlobsBuffer(bs *BlobStore) *BlobsBuffer {
	return &BlobsBuffer{
		bs:  bs,
		mpw: NewMultipartWriter(),
	}
}
func (bb *BlobsBuffer) AddBlob(hash string, blob []byte) error {
	bb.Lock()
	defer bb.Unlock()
	bb.size++
	return bb.mpw.AddBlob(hash, blob)
}

func (bb *BlobsBuffer) Upload() error {
	if bb.size > 0 {
		bb.Lock()
		cmpw := bb.mpw
		bb.size = 0
		bb.Unlock()
		bb.mpw = NewMultipartWriter()
		if err := bb.bs.putmpw(cmpw); err != nil {
			return err
		}
	}
	return nil
}

func (bb *BlobsBuffer) Close() {
}

// Put upload the given blob, the caller is responsible for computing the blake2b hash
func (bs *BlobStore) put(hash string, blob []byte) error {
	mpw := NewMultipartWriter()
	if err := mpw.AddBlob(hash, blob); err != nil {
		return err
	}
	return bs.putmpw(mpw)
}

func (bs *BlobStore) putmpw(mpw *MultipartWriter) error {
	mpw.Close()
	// FIXME(tsileo): support namespace
	request, err := http.NewRequest("POST", bs.ServerAddr+"/api/v1/blobstore/upload", mpw.Buffer)
	if err != nil {
		return err
	}
	if bs.apiKey != "" {
		request.SetBasicAuth("", bs.apiKey)
	}
	request.Header.Add("Content-Type", mpw.FormDataContentType())
	resp, err := bs.client.Do(request)
	if err != nil {
		return err
	}
	var body bytes.Buffer
	body.ReadFrom(resp.Body)
	resp.Body.Close()
	if resp.StatusCode != 200 {
		return fmt.Errorf("failed to put blob %v", body.String())
	}
	return nil
}