-
Notifications
You must be signed in to change notification settings - Fork 265
/
minio.js
2239 lines (2055 loc) · 79.3 KB
/
minio.js
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* 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.
*/
import fs from 'fs'
import Crypto from 'crypto'
import Http from 'http'
import Https from 'https'
import Stream from 'stream'
import BlockStream2 from 'block-stream2'
import Xml from 'xml'
import xml2js from 'xml2js'
import async from 'async'
import querystring from 'querystring'
import mkdirp from 'mkdirp'
import path from 'path'
import _ from 'lodash'
import { extractMetadata, prependXAMZMeta, isValidPrefix, isValidEndpoint, isValidBucketName,
isValidPort, isValidObjectName, isAmazonEndpoint, getScope,
uriEscape, uriResourceEscape, isBoolean, isFunction, isNumber,
isString, isObject, isArray, isValidDate, pipesetup,
readableStream, isReadableStream, isVirtualHostStyle,
insertContentType, makeDateLong, promisify } from './helpers.js'
import { signV4, presignSignatureV4, postPresignSignatureV4 } from './signing.js'
import ObjectUploader from './object-uploader'
import * as transformers from './transformers'
import * as errors from './errors.js'
import { getS3Endpoint } from './s3-endpoints.js'
import { NotificationConfig, NotificationPoller } from './notification'
var Package = require('../../package.json')
export class Client {
constructor(params) {
if (typeof params.secure !== 'undefined') throw new Error('"secure" option deprecated, "useSSL" should be used instead')
// Default values if not specified.
if (typeof params.useSSL === 'undefined') params.useSSL = true
if (!params.port) params.port = 0
// Validate input params.
if (!isValidEndpoint(params.endPoint)) {
throw new errors.InvalidEndpointError(`Invalid endPoint : ${params.endPoint}`)
}
if (!isValidPort(params.port)) {
throw new errors.InvalidArgumentError(`Invalid port : ${params.port}`)
}
if (!isBoolean(params.useSSL)) {
throw new errors.InvalidArgumentError(`Invalid useSSL flag type : ${params.useSSL}, expected to be of type "boolean"`)
}
// Validate region only if its set.
if (params.region) {
if (!isString(params.region)) {
throw new errors.InvalidArgumentError(`Invalid region : ${params.region}`)
}
}
var host = params.endPoint.toLowerCase()
var port = params.port
var protocol = ''
var transport
// Validate if configuration is not using SSL
// for constructing relevant endpoints.
if (params.useSSL === false) {
transport = Http
protocol = 'http:'
if (port === 0) {
port = 80
}
} else {
// Defaults to secure.
transport = Https
protocol = 'https:'
if (port === 0) {
port = 443
}
}
// if custom transport is set, use it.
if (params.transport) {
if (!isObject(params.transport)) {
throw new errors.InvalidArgumentError('Invalid transport type : ${params.transport}, expected to be type "object"')
}
transport = params.transport
}
// User Agent should always following the below style.
// Please open an issue to discuss any new changes here.
//
// MinIO (OS; ARCH) LIB/VER APP/VER
//
var libraryComments = `(${process.platform}; ${process.arch})`
var libraryAgent = `MinIO ${libraryComments} minio-js/${Package.version}`
// User agent block ends.
this.transport = transport
this.host = host
this.port = port
this.protocol = protocol
this.accessKey = params.accessKey
this.secretKey = params.secretKey
this.sessionToken = params.sessionToken
this.userAgent = `${libraryAgent}`
if (!this.accessKey) this.accessKey = ''
if (!this.secretKey) this.secretKey = ''
this.anonymous = !this.accessKey || !this.secretKey
this.regionMap = {}
if (params.region) {
this.region = params.region
}
this.partSize = 64*1024*1024
if (params.partSize) {
this.partSize = params.partSize
this.overRidePartSize = true
}
if (this.partSize < 5*1024*1024) {
throw new errors.InvalidArgumentError(`Part size should be greater than 5MB`)
}
if (this.partSize > 5*1024*1024*1024) {
throw new errors.InvalidArgumentError(`Part size should be less than 5GB`)
}
this.maximumPartSize = 5*1024*1024*1024
this.maxObjectSize = 5*1024*1024*1024*1024
// SHA256 is enabled only for authenticated http requests. If the request is authenticated
// and the connection is https we use x-amz-content-sha256=UNSIGNED-PAYLOAD
// header for signature calculation.
this.enableSHA256 = !this.anonymous && !params.useSSL
this.reqOptions = {}
}
// Sets the supported request options.
setRequestOptions(options) {
if (!isObject(options)) {
throw new TypeError('request options should be of type "object"')
}
this.reqOptions = _.pick(options, ['agent', 'ca', 'cert', 'ciphers', 'clientCertEngine', 'crl', 'dhparam', 'ecdhCurve', 'family', 'honorCipherOrder', 'key', 'passphrase', 'pfx', 'rejectUnauthorized', 'secureOptions', 'secureProtocol', 'servername', 'sessionIdContext'])
}
// returns *options* object that can be used with http.request()
// Takes care of constructing virtual-host-style or path-style hostname
getRequestOptions(opts) {
var method = opts.method
var region = opts.region
var bucketName = opts.bucketName
var objectName = opts.objectName
var headers = opts.headers
var query = opts.query
var reqOptions = {method}
reqOptions.headers = {}
// Verify if virtual host supported.
var virtualHostStyle
if (bucketName) {
virtualHostStyle = isVirtualHostStyle(this.host,
this.protocol,
bucketName)
}
if (this.port) reqOptions.port = this.port
reqOptions.protocol = this.protocol
if (objectName) {
objectName = `${uriResourceEscape(objectName)}`
}
reqOptions.path = '/'
// Save host.
reqOptions.host = this.host
// For Amazon S3 endpoint, get endpoint based on region.
if (isAmazonEndpoint(reqOptions.host)) {
reqOptions.host = getS3Endpoint(region)
}
if (virtualHostStyle && !opts.pathStyle) {
// For all hosts which support virtual host style, `bucketName`
// is part of the hostname in the following format:
//
// var host = 'bucketName.example.com'
//
if (bucketName) reqOptions.host = `${bucketName}.${reqOptions.host}`
if (objectName) reqOptions.path = `/${objectName}`
} else {
// For all S3 compatible storage services we will fallback to
// path style requests, where `bucketName` is part of the URI
// path.
if (bucketName) reqOptions.path = `/${bucketName}`
if (objectName) reqOptions.path = `/${bucketName}/${objectName}`
}
if (query) reqOptions.path += `?${query}`
reqOptions.headers.host = reqOptions.host
if ((reqOptions.protocol === 'http:' && reqOptions.port !== 80) ||
(reqOptions.protocol === 'https:' && reqOptions.port !== 443)) {
reqOptions.headers.host = `${reqOptions.host}:${reqOptions.port}`
}
reqOptions.headers['user-agent'] = this.userAgent
if (headers) {
// have all header keys in lower case - to make signing easy
_.map(headers, (v, k) => reqOptions.headers[k.toLowerCase()] = v)
}
// Use any request option specified in minioClient.setRequestOptions()
reqOptions = Object.assign({}, this.reqOptions, reqOptions)
return reqOptions
}
// Set application specific information.
//
// Generates User-Agent in the following style.
//
// MinIO (OS; ARCH) LIB/VER APP/VER
//
// __Arguments__
// * `appName` _string_ - Application name.
// * `appVersion` _string_ - Application version.
setAppInfo(appName, appVersion) {
if (!isString(appName)) {
throw new TypeError(`Invalid appName: ${appName}`)
}
if (appName.trim() === '') {
throw new errors.InvalidArgumentError('Input appName cannot be empty.')
}
if (!isString(appVersion)) {
throw new TypeError(`Invalid appVersion: ${appVersion}`)
}
if (appVersion.trim() === '') {
throw new errors.InvalidArgumentError('Input appVersion cannot be empty.')
}
this.userAgent = `${this.userAgent} ${appName}/${appVersion}`
}
// Calculate part size given the object size. Part size will be atleast this.partSize
calculatePartSize(size) {
if (!isNumber(size)) {
throw new TypeError('size should be of type "number"')
}
if (size > this.maxObjectSize) {
throw new TypeError(`size should not be more than ${this.maxObjectSize}`)
}
if (this.overRidePartSize) {
return this.partSize
}
var partSize = this.partSize
for (;;) { // while(true) {...} throws linting error.
// If partSize is big enough to accomodate the object size, then use it.
if ((partSize * 10000) > size) {
return partSize
}
// Try part sizes as 64MB, 80MB, 96MB etc.
partSize += 16*1024*1024
}
}
// log the request, response, error
logHTTP(reqOptions, response, err) {
// if no logstreamer available return.
if (!this.logStream) return
if (!isObject(reqOptions)) {
throw new TypeError('reqOptions should be of type "object"')
}
if (response && !isReadableStream(response)) {
throw new TypeError('response should be of type "Stream"')
}
if (err && !(err instanceof Error)) {
throw new TypeError('err should be of type "Error"')
}
var logHeaders = (headers) => {
_.forEach(headers, (v, k) => {
if (k == 'authorization') {
var redacter = new RegExp('Signature=([0-9a-f]+)')
v = v.replace(redacter, 'Signature=**REDACTED**')
}
this.logStream.write(`${k}: ${v}\n`)
})
this.logStream.write('\n')
}
this.logStream.write(`REQUEST: ${reqOptions.method} ${reqOptions.path}\n`)
logHeaders(reqOptions.headers)
if (response) {
this.logStream.write(`RESPONSE: ${response.statusCode}\n`)
logHeaders(response.headers)
}
if (err) {
this.logStream.write('ERROR BODY:\n')
var errJSON = JSON.stringify(err, null, '\t')
this.logStream.write(`${errJSON}\n`)
}
}
// Enable tracing
traceOn(stream) {
if (!stream) stream = process.stdout
this.logStream = stream
}
// Disable tracing
traceOff() {
this.logStream = null
}
// makeRequest is the primitive used by the apis for making S3 requests.
// payload can be empty string in case of no payload.
// statusCode is the expected statusCode. If response.statusCode does not match
// we parse the XML error and call the callback with the error message.
// A valid region is passed by the calls - listBuckets, makeBucket and
// getBucketRegion.
makeRequest(options, payload, statusCode, region, returnResponse, cb) {
if (!isObject(options)) {
throw new TypeError('options should be of type "object"')
}
if (!isString(payload) && !isObject(payload)) {
// Buffer is of type 'object'
throw new TypeError('payload should be of type "string" or "Buffer"')
}
if (!isNumber(statusCode)) {
throw new TypeError('statusCode should be of type "number"')
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isBoolean(returnResponse)) {
throw new TypeError('returnResponse should be of type "boolean"')
}
if(!isFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
if (!options.headers) options.headers = {}
if (options.method === 'POST' || options.method === 'PUT' || options.method === 'DELETE') {
options.headers['content-length'] = payload.length
}
var sha256sum = ''
if (this.enableSHA256) sha256sum = Crypto.createHash('sha256').update(payload).digest('hex')
var stream = readableStream(payload)
this.makeRequestStream(options, stream, sha256sum, statusCode, region, returnResponse, cb)
}
// makeRequestStream will be used directly instead of makeRequest in case the payload
// is available as a stream. for ex. putObject
makeRequestStream(options, stream, sha256sum, statusCode, region, returnResponse, cb) {
if (!isObject(options)) {
throw new TypeError('options should be of type "object"')
}
if (!isReadableStream(stream)) {
throw new errors.InvalidArgumentError('stream should be a readable Stream')
}
if (!isString(sha256sum)) {
throw new TypeError('sha256sum should be of type "string"')
}
if (!isNumber(statusCode)) {
throw new TypeError('statusCode should be of type "number"')
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isBoolean(returnResponse)) {
throw new TypeError('returnResponse should be of type "boolean"')
}
if(!isFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
// sha256sum will be empty for anonymous or https requests
if (!this.enableSHA256 && sha256sum.length !== 0) {
throw new errors.InvalidArgumentError(`sha256sum expected to be empty for anonymous or https requests`)
}
// sha256sum should be valid for non-anonymous http requests.
if (this.enableSHA256 && sha256sum.length !== 64) {
throw new errors.InvalidArgumentError(`Invalid sha256sum : ${sha256sum}`)
}
var _makeRequest = (e, region) => {
if (e) return cb(e)
options.region = region
var reqOptions = this.getRequestOptions(options)
if (!this.anonymous) {
// For non-anonymous https requests sha256sum is 'UNSIGNED-PAYLOAD' for signature calculation.
if (!this.enableSHA256) sha256sum = 'UNSIGNED-PAYLOAD'
let date = new Date()
reqOptions.headers['x-amz-date'] = makeDateLong(date)
reqOptions.headers['x-amz-content-sha256'] = sha256sum
if (this.sessionToken) {
reqOptions.headers['x-amz-security-token'] = this.sessionToken
}
var authorization = signV4(reqOptions, this.accessKey, this.secretKey, region, date)
reqOptions.headers.authorization = authorization
}
var req = this.transport.request(reqOptions, response => {
if (statusCode !== response.statusCode) {
// For an incorrect region, S3 server always sends back 400.
// But we will do cache invalidation for all errors so that,
// in future, if AWS S3 decides to send a different status code or
// XML error code we will still work fine.
delete(this.regionMap[options.bucketName])
var errorTransformer = transformers.getErrorTransformer(response)
pipesetup(response, errorTransformer)
.on('error', e => {
this.logHTTP(reqOptions, response, e)
cb(e)
})
return
}
this.logHTTP(reqOptions, response)
if (returnResponse) return cb(null, response)
// We drain the socket so that the connection gets closed. Note that this
// is not expensive as the socket will not have any data.
response.on('data', ()=>{})
cb(null)
})
let pipe = pipesetup(stream, req)
pipe.on('error', e => {
this.logHTTP(reqOptions, null, e)
cb(e)
})
}
if (region) return _makeRequest(null, region)
this.getBucketRegion(options.bucketName, _makeRequest)
}
// gets the region of the bucket
getBucketRegion(bucketName, cb) {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError(`Invalid bucket name : ${bucketName}`)
}
if (!isFunction(cb)) {
throw new TypeError('cb should be of type "function"')
}
// Region is set with constructor, return the region right here.
if (this.region) return cb(null, this.region)
if (this.regionMap[bucketName]) return cb(null, this.regionMap[bucketName])
var extractRegion = (response) => {
var transformer = transformers.getBucketRegionTransformer()
var region = 'us-east-1'
pipesetup(response, transformer)
.on('error', cb)
.on('data', data => {
if (data) region = data
})
.on('end', () => {
this.regionMap[bucketName] = region
cb(null, region)
})
}
var method = 'GET'
var query = 'location'
// `getBucketLocation` behaves differently in following ways for
// different environments.
//
// - For nodejs env we default to path style requests.
// - For browser env path style requests on buckets yields CORS
// error. To circumvent this problem we make a virtual host
// style request signed with 'us-east-1'. This request fails
// with an error 'AuthorizationHeaderMalformed', additionally
// the error XML also provides Region of the bucket. To validate
// this region is proper we retry the same request with the newly
// obtained region.
var pathStyle = typeof window === 'undefined'
this.makeRequest({method, bucketName, query, pathStyle}, '', 200, 'us-east-1', true, (e, response) => {
if (e) {
if (e.name === 'AuthorizationHeaderMalformed') {
var region = e.Region
if (!region) return cb(e)
this.makeRequest({method, bucketName, query}, '', 200, region, true, (e, response) => {
if (e) return cb(e)
extractRegion(response)
})
return
}
return cb(e)
}
extractRegion(response)
})
}
// Creates the bucket `bucketName`.
//
// __Arguments__
// * `bucketName` _string_ - Name of the bucket
// * `region` _string_ - region valid values are _us-west-1_, _us-west-2_, _eu-west-1_, _eu-central-1_, _ap-southeast-1_, _ap-northeast-1_, _ap-southeast-2_, _sa-east-1_.
// * `callback(err)` _function_ - callback function with `err` as the error argument. `err` is null if the bucket is successfully created.
makeBucket(bucketName, region, cb) {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)
}
if (isFunction(region)) {
cb = region
region = ''
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
var payload = ''
// Region already set in constructor, validate if
// caller requested bucket location is same.
if (region && this.region) {
if (region !== this.region) {
throw new errors.InvalidArgumentError(`Configured region ${this.region}, requested ${region}`)
}
}
// sending makeBucket request with XML containing 'us-east-1' fails. For
// default region server expects the request without body
if (region && region !== 'us-east-1') {
var createBucketConfiguration = []
createBucketConfiguration.push({
_attr: {
xmlns: 'http://s3.amazonaws.com/doc/2006-03-01/'
}
})
createBucketConfiguration.push({
LocationConstraint: region
})
var payloadObject = {
CreateBucketConfiguration: createBucketConfiguration
}
payload = Xml(payloadObject)
}
var method = 'PUT'
var headers = {}
if (!region) region = 'us-east-1'
this.makeRequest({method, bucketName, headers}, payload, 200, region, false, cb)
}
// List of buckets created.
//
// __Arguments__
// * `callback(err, buckets)` _function_ - callback function with error as the first argument. `buckets` is an array of bucket information
//
// `buckets` array element:
// * `bucket.name` _string_ : bucket name
// * `bucket.creationDate` _Date_: date when bucket was created
listBuckets(cb) {
if (!isFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
var method = 'GET'
this.makeRequest({method}, '', 200, 'us-east-1', true, (e, response) => {
if (e) return cb(e)
var transformer = transformers.getListBucketTransformer()
var buckets
pipesetup(response, transformer)
.on('data', result => buckets = result)
.on('error', e => cb(e))
.on('end', () => cb(null, buckets))
})
}
// Returns a stream that emits objects that are partially uploaded.
//
// __Arguments__
// * `bucketname` _string_: name of the bucket
// * `prefix` _string_: prefix of the object names that are partially uploaded (optional, default `''`)
// * `recursive` _bool_: directory style listing when false, recursive listing when true (optional, default `false`)
//
// __Return Value__
// * `stream` _Stream_ : emits objects of the format:
// * `object.key` _string_: name of the object
// * `object.uploadId` _string_: upload ID of the object
// * `object.size` _Integer_: size of the partially uploaded object
listIncompleteUploads(bucket, prefix, recursive) {
if (prefix === undefined) prefix = ''
if (recursive === undefined) recursive = false
if (!isValidBucketName(bucket)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucket)
}
if (!isValidPrefix(prefix)) {
throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`)
}
if (!isBoolean(recursive)) {
throw new TypeError('recursive should be of type "boolean"')
}
var delimiter = recursive ? '' : '/'
var keyMarker = ''
var uploadIdMarker = ''
var uploads = []
var ended = false
var readStream = Stream.Readable({objectMode: true})
readStream._read = () => {
// push one upload info per _read()
if (uploads.length) {
return readStream.push(uploads.shift())
}
if (ended) return readStream.push(null)
this.listIncompleteUploadsQuery(bucket, prefix, keyMarker, uploadIdMarker, delimiter)
.on('error', e => readStream.emit('error', e))
.on('data', result => {
result.prefixes.forEach(prefix => uploads.push(prefix))
async.eachSeries(result.uploads, (upload, cb) => {
// for each incomplete upload add the sizes of its uploaded parts
this.listParts(bucket, upload.key, upload.uploadId, (err, parts) => {
if (err) return cb(err)
upload.size = parts.reduce((acc, item) => acc + item.size, 0)
uploads.push(upload)
cb()
})
}, err => {
if (err) {
readStream.emit('error', err)
return
}
if (result.isTruncated) {
keyMarker = result.nextKeyMarker
uploadIdMarker = result.nextUploadIdMarker
} else {
ended = true
}
readStream._read()
})
})
}
return readStream
}
// To check if a bucket already exists.
//
// __Arguments__
// * `bucketName` _string_ : name of the bucket
// * `callback(err)` _function_ : `err` is `null` if the bucket exists
bucketExists(bucketName, cb) {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)
}
if (!isFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
var method = 'HEAD'
this.makeRequest({method, bucketName}, '', 200, '', false, err => {
if (err) {
if (err.code == 'NoSuchBucket' || err.code == 'NotFound') return cb(null, false)
return cb(err)
}
cb(null, true)
})
}
// Remove a bucket.
//
// __Arguments__
// * `bucketName` _string_ : name of the bucket
// * `callback(err)` _function_ : `err` is `null` if the bucket is removed successfully.
removeBucket(bucketName, cb) {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)
}
if (!isFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
var method = 'DELETE'
this.makeRequest({method, bucketName}, '', 204, '', false, (e) => {
// If the bucket was successfully removed, remove the region map entry.
if (!e) delete(this.regionMap[bucketName])
cb(e)
})
}
// Remove the partially uploaded object.
//
// __Arguments__
// * `bucketName` _string_: name of the bucket
// * `objectName` _string_: name of the object
// * `callback(err)` _function_: callback function is called with non `null` value in case of error
removeIncompleteUpload(bucketName, objectName, cb) {
if (!isValidBucketName(bucketName)) {
throw new errors.isValidBucketNameError('Invalid bucket name: ' + bucketName)
}
if (!isValidObjectName(objectName)) {
throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)
}
if (!isFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
var removeUploadId
async.during(
cb => {
this.findUploadId(bucketName, objectName, (e, uploadId) => {
if (e) return cb(e)
removeUploadId = uploadId
cb(null, uploadId)
})
},
cb => {
var method = 'DELETE'
var query = `uploadId=${removeUploadId}`
this.makeRequest({method, bucketName, objectName, query}, '', 204, '', false, e => cb(e))
},
cb
)
}
// Callback is called with `error` in case of error or `null` in case of success
//
// __Arguments__
// * `bucketName` _string_: name of the bucket
// * `objectName` _string_: name of the object
// * `filePath` _string_: path to which the object data will be written to
// * `callback(err)` _function_: callback is called with `err` in case of error.
fGetObject(bucketName, objectName, filePath, cb) {
// Input validation.
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)
}
if (!isValidObjectName(objectName)) {
throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)
}
if (!isString(filePath)) {
throw new TypeError('filePath should be of type "string"')
}
if (!isFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
// Internal data.
var partFile
var partFileStream
var objStat
// Rename wrapper.
var rename = err => {
if (err) return cb(err)
fs.rename(partFile, filePath, cb)
}
async.waterfall([
cb => this.statObject(bucketName, objectName, cb),
(result, cb) => {
objStat = result
// Create any missing top level directories.
mkdirp(path.dirname(filePath), cb)
},
(ignore, cb) => {
partFile = `${filePath}.${objStat.etag}.part.minio`
fs.stat(partFile, (e, stats) => {
var offset = 0
if (e) {
partFileStream = fs.createWriteStream(partFile, {flags: 'w'})
} else {
if (objStat.size === stats.size) return rename()
offset = stats.size
partFileStream = fs.createWriteStream(partFile, {flags: 'a'})
}
this.getPartialObject(bucketName, objectName, offset, 0, cb)
})
},
(downloadStream, cb) => {
pipesetup(downloadStream, partFileStream)
.on('error', e => cb(e))
.on('finish', cb)
},
cb => fs.stat(partFile, cb),
(stats, cb) => {
if (stats.size === objStat.size) return cb()
cb(new Error('Size mismatch between downloaded file and the object'))
}
], rename)
}
// Callback is called with readable stream of the object content.
//
// __Arguments__
// * `bucketName` _string_: name of the bucket
// * `objectName` _string_: name of the object
// * `callback(err, stream)` _function_: callback is called with `err` in case of error. `stream` is the object content stream
getObject(bucketName, objectName, cb) {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)
}
if (!isValidObjectName(objectName)) {
throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)
}
if (!isFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
this.getPartialObject(bucketName, objectName, 0, 0, cb)
}
// Callback is called with readable stream of the partial object content.
//
// __Arguments__
// * `bucketName` _string_: name of the bucket
// * `objectName` _string_: name of the object
// * `offset` _number_: offset of the object from where the stream will start
// * `length` _number_: length of the object that will be read in the stream (optional, if not specified we read the rest of the file from the offset)
// * `callback(err, stream)` _function_: callback is called with `err` in case of error. `stream` is the object content stream
getPartialObject(bucketName, objectName, offset, length, cb) {
if (isFunction(length)) {
cb = length
length = 0
}
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)
}
if (!isValidObjectName(objectName)) {
throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)
}
if (!isNumber(offset)) {
throw new TypeError('offset should be of type "number"')
}
if (!isNumber(length)) {
throw new TypeError('length should be of type "number"')
}
if (!isFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
var range = ''
if (offset || length) {
if (offset) {
range = `bytes=${+offset}-`
} else {
range = 'bytes=0-'
offset = 0
}
if (length) {
range += `${(+length + offset) - 1}`
}
}
var headers = {}
if (range !== '') {
headers.range = range
}
var expectedStatus = 200
if (range) {
expectedStatus = 206
}
var method = 'GET'
this.makeRequest({method, bucketName, objectName, headers}, '', expectedStatus, '', true, cb)
}
// Uploads the object using contents from a file
//
// __Arguments__
// * `bucketName` _string_: name of the bucket
// * `objectName` _string_: name of the object
// * `filePath` _string_: file path of the file to be uploaded
// * `metaData` _Javascript Object_: metaData assosciated with the object
// * `callback(err, etag)` _function_: non null `err` indicates error, `etag` _string_ is the etag of the object uploaded.
fPutObject(bucketName, objectName, filePath, metaData, callback) {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)
}
if (!isValidObjectName(objectName)) {
throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)
}
if (!isString(filePath)) {
throw new TypeError('filePath should be of type "string"')
}
if (isFunction(metaData)) {
callback = metaData
metaData = {} // Set metaData empty if no metaData provided.
}
if (!isObject(metaData)) {
throw new TypeError('metaData should be of type "object"')
}
// Inserts correct `content-type` attribute based on metaData and filePath
metaData = insertContentType(metaData, filePath)
//Updates metaData to have the correct prefix if needed
metaData = prependXAMZMeta(metaData)
var size
var partSize
async.waterfall([
cb => fs.stat(filePath, cb),
(stats, cb) => {
size = stats.size
if (size > this.maxObjectSize) {
return cb(new Error(`${filePath} size : ${stats.size}, max allowed size : 5TB`))
}
if (size <= this.partSize) {
// simple PUT request, no multipart
var multipart = false
var uploader = this.getUploader(bucketName, objectName, metaData, multipart)
var hash = transformers.getHashSummer(this.enableSHA256)
var start = 0
var end = size - 1
var autoClose = true
if (size === 0) end = 0
var options = {start, end, autoClose}
pipesetup(fs.createReadStream(filePath, options), hash)
.on('data', data => {
var md5sum = data.md5sum
var sha256sum = data.sha256sum
var stream = fs.createReadStream(filePath, options)
uploader(stream, size, sha256sum, md5sum, (err, etag) => {
callback(err, etag)
cb(true)
})
})
.on('error', e => cb(e))
return
}
this.findUploadId(bucketName, objectName, cb)
},
(uploadId, cb) => {
// if there was a previous incomplete upload, fetch all its uploaded parts info
if (uploadId) return this.listParts(bucketName, objectName, uploadId, (e, etags) => cb(e, uploadId, etags))
// there was no previous upload, initiate a new one
this.initiateNewMultipartUpload(bucketName, objectName, metaData, (e, uploadId) => cb(e, uploadId, []))
},
(uploadId, etags, cb) => {
partSize = this.calculatePartSize(size)
var multipart = true
var uploader = this.getUploader(bucketName, objectName, metaData, multipart)
// convert array to object to make things easy
var parts = etags.reduce(function(acc, item) {
if (!acc[item.part]) {
acc[item.part] = item
}
return acc
}, {})
var partsDone = []
var partNumber = 1
var uploadedSize = 0
async.whilst(
cb => { cb(null, uploadedSize < size) },
cb => {
var part = parts[partNumber]
var hash = transformers.getHashSummer(this.enableSHA256)
var length = partSize
if (length > (size - uploadedSize)) {
length = size - uploadedSize
}
var start = uploadedSize
var end = uploadedSize + length - 1
var autoClose = true
var options = {autoClose, start, end}
// verify md5sum of each part
pipesetup(fs.createReadStream(filePath, options), hash)
.on('data', data => {
var md5sumHex = (Buffer.from(data.md5sum, 'base64')).toString('hex')
if (part && (md5sumHex === part.etag)) {
//md5 matches, chunk already uploaded
partsDone.push({part: partNumber, etag: part.etag})
partNumber++
uploadedSize += length
return cb()
}
// part is not uploaded yet, or md5 mismatch
var stream = fs.createReadStream(filePath, options)
uploader(uploadId, partNumber, stream, length,
data.sha256sum, data.md5sum, (e, etag) => {
if (e) return cb(e)
partsDone.push({part: partNumber, etag})
partNumber++
uploadedSize += length
return cb()
})
})
.on('error', e => cb(e))
},
e => {
if (e) return cb(e)
cb(null, partsDone, uploadId)
}
)
},