-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathrouteBackbeat.js
More file actions
1661 lines (1564 loc) · 65.7 KB
/
routeBackbeat.js
File metadata and controls
1661 lines (1564 loc) · 65.7 KB
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
const url = require('url');
const async = require('async');
const httpProxy = require('http-proxy');
const querystring = require('querystring');
const joi = require('@hapi/joi');
const backbeatProxy = httpProxy.createProxyServer({
ignorePath: true,
});
const { auth, errors, errorInstances, s3middleware, s3routes, models, storage } =
require('arsenal');
const { responseJSONBody } = s3routes.routesUtils;
const { getSubPartIds } = s3middleware.azureHelper.mpuUtils;
const { skipMpuPartProcessing } = storage.data.external.backendUtils;
const { parseLC, MultipleBackendGateway } = storage.data;
const vault = require('../auth/vault');
const dataWrapper = require('../data/wrapper');
const metadata = require('../metadata/wrapper');
const locationConstraintCheck = require(
'../api/apiUtils/object/locationConstraintCheck');
const locationStorageCheck =
require('../api/apiUtils/object/locationStorageCheck');
const { dataStore } = require('../api/apiUtils/object/storeObject');
const prepareRequestContexts = require(
'../api/apiUtils/authorization/prepareRequestContexts');
const { decodeVersionId } = require('../api/apiUtils/object/versioning');
const locationKeysHaveChanged
= require('../api/apiUtils/object/locationKeysHaveChanged');
const { standardMetadataValidateBucketAndObj,
metadataGetObject } = require('../metadata/metadataUtils');
const { config } = require('../Config');
const constants = require('../../constants');
const { BackendInfo } = models;
const { pushReplicationMetric } = require('./utilities/pushReplicationMetric');
const kms = require('../kms/wrapper');
const { listLifecycleCurrents } = require('../api/backbeat/listLifecycleCurrents');
const { listLifecycleNonCurrents } = require('../api/backbeat/listLifecycleNonCurrents');
const { listLifecycleOrphanDeleteMarkers } = require('../api/backbeat/listLifecycleOrphanDeleteMarkers');
const { objectDeleteInternal } = require('../api/objectDelete');
const quotaUtils = require('../api/apiUtils/quotas/quotaUtils');
const { CURRENT_TYPE, NON_CURRENT_TYPE, ORPHAN_DM_TYPE } = constants.lifecycleListing;
const lifecycleTypeCalls = {
[CURRENT_TYPE]: listLifecycleCurrents,
[NON_CURRENT_TYPE]: listLifecycleNonCurrents,
[ORPHAN_DM_TYPE]: listLifecycleOrphanDeleteMarkers,
};
auth.setHandler(vault);
const NAMESPACE = 'default';
const CIPHER = null; // replication/lifecycle does not work on encrypted objects
let { locationConstraints } = config;
const { nullVersionCompatMode } = config;
const { implName } = dataWrapper;
let dataClient = dataWrapper.client;
config.on('location-constraints-update', () => {
locationConstraints = config.locationConstraints;
if (implName === 'multipleBackends') {
const clients = parseLC(config, vault);
dataClient = new MultipleBackendGateway(
clients, metadata, locationStorageCheck);
}
});
function _decodeURI(uri) {
// do the same decoding than in S3 server
return decodeURIComponent(uri.replace(/\+/g, ' '));
}
function _normalizeBackbeatRequest(req) {
/* eslint-disable no-param-reassign */
const parsedUrl = url.parse(req.url, true);
req.path = _decodeURI(parsedUrl.pathname);
const pathArr = req.path.split('/');
req.query = parsedUrl.query;
req.resourceType = pathArr[3];
req.bucketName = pathArr[4];
req.objectKey = pathArr.slice(5).join('/');
req.actionImplicitDenies = false;
/* eslint-enable no-param-reassign */
}
function _isObjectRequest(req) {
return [
'data',
'metadata',
'multiplebackenddata',
'multiplebackendmetadata',
].includes(req.resourceType);
}
function _respondWithHeaders(response, payload, extraHeaders, log, callback) {
let body = '';
if (typeof payload === 'string') {
body = payload;
} else if (typeof payload === 'object') {
body = JSON.stringify(payload);
}
const httpHeaders = Object.assign({
'x-amz-id-2': log.getSerializedUids(),
'x-amz-request-id': log.getSerializedUids(),
'content-type': 'application/json',
'content-length': Buffer.byteLength(body),
}, extraHeaders);
response.writeHead(200, httpHeaders);
response.end(body, 'utf8', () => {
log.end().info('responded with payload', {
httpCode: 200,
contentLength: Buffer.byteLength(body),
});
callback();
});
}
function _respond(response, payload, log, callback) {
_respondWithHeaders(response, payload, {}, log, callback);
}
function _getRequestPayload(req, cb) {
const payload = [];
let payloadLen = 0;
req.on('data', chunk => {
payload.push(chunk);
payloadLen += chunk.length;
}).on('error', cb)
.on('end', () => cb(null, Buffer.concat(payload, payloadLen).toString()));
}
function _checkMultipleBackendRequest(request, log) {
const { headers, query } = request;
const storageType = headers['x-scal-storage-type'];
const { operation } = query;
let errMessage;
if (storageType === undefined) {
errMessage = 'bad request: missing x-scal-storage-type header';
log.error(errMessage);
return errorInstances.BadRequest.customizeDescription(errMessage);
}
if (operation === 'putpart' &&
headers['x-scal-part-number'] === undefined) {
errMessage = 'bad request: missing part-number header';
log.error(errMessage);
return errorInstances.BadRequest.customizeDescription(errMessage);
}
const isMPUOperation =
['putpart', 'completempu', 'abortmpu'].includes(operation);
if (isMPUOperation && headers['x-scal-upload-id'] === undefined) {
errMessage = 'bad request: missing upload-id header';
log.error(errMessage);
return errorInstances.BadRequest.customizeDescription(errMessage);
}
if (operation === 'putobject' &&
headers['x-scal-canonical-id'] === undefined) {
errMessage = 'bad request: missing x-scal-canonical-id header';
log.error(errMessage);
return errorInstances.BadRequest.customizeDescription(errMessage);
}
// Ensure the external backend has versioning before asserting version ID.
if (!constants.versioningNotImplBackends[storageType] &&
(operation === 'puttagging' || operation === 'deletetagging')) {
if (headers['x-scal-data-store-version-id'] === undefined) {
errMessage =
'bad request: missing x-scal-data-store-version-id header';
log.error(errMessage);
return errorInstances.BadRequest.customizeDescription(errMessage);
}
if (headers['x-scal-source-bucket'] === undefined) {
errMessage = 'bad request: missing x-scal-source-bucket header';
log.error(errMessage);
return errorInstances.BadRequest.customizeDescription(errMessage);
}
if (headers['x-scal-replication-endpoint-site'] === undefined) {
errMessage = 'bad request: missing ' +
'x-scal-replication-endpoint-site';
log.error(errMessage);
return errorInstances.BadRequest.customizeDescription(errMessage);
}
}
if (operation === 'putobject' &&
headers['content-md5'] === undefined) {
errMessage = 'bad request: missing content-md5 header';
log.error(errMessage);
return errorInstances.BadRequest.customizeDescription(errMessage);
}
if (headers['x-scal-storage-class'] === undefined) {
errMessage = 'bad request: missing x-scal-storage-class header';
log.error(errMessage);
return errorInstances.BadRequest.customizeDescription(errMessage);
}
const location = locationConstraints[headers['x-scal-storage-class']];
const storageTypeList = storageType.split(',');
const isValidLocation = location &&
storageTypeList.includes(location.type);
if (!isValidLocation) {
errMessage = 'invalid request: invalid location constraint in request';
log.debug(errMessage, {
method: request.method,
bucketName: request.bucketName,
objectKey: request.objectKey,
resourceType: request.resourceType,
});
return errorInstances.InvalidRequest.customizeDescription(errMessage);
}
return undefined;
}
function getPartList(parts, objectKey, uploadId, storageLocation) {
const partList = {};
if (locationConstraints[storageLocation].type === 'azure') {
partList.uncommittedBlocks = [];
parts.forEach(part => {
const location = {
key: objectKey,
partNumber: part.PartNumber[0],
dataStoreETag: part.ETag[0],
numberSubParts: part.NumberSubParts[0],
};
const subPartIds = getSubPartIds(location, uploadId);
partList.uncommittedBlocks.push(...subPartIds);
});
} else {
partList.Part = parts;
}
return partList;
}
function generateMpuAggregateInfo(parts) {
let aggregateSize;
// CopyLocationTask does transmit a size for each part,
// MultipleBackendTask does not, so check if size is defined in
// the first part.
if (parts[0] && parts[0].Size) {
aggregateSize = parts.reduce(
(agg, part) => agg + Number.parseInt(part.Size[0], 10), 0);
}
return {
aggregateSize,
aggregateETag: s3middleware.processMpuParts.createAggregateETag(
parts.map(part => part.ETag[0])),
};
}
/**
* Helper to create the response object for putObject and completeMPU
*
* @param {object} params - response info
* @param {string} params.dataStoreName - name of location
* @param {string} params.dataStoreType - location type (e.g. "aws_s3")
* @param {string} params.key - object key
* @param {number} params.size - total byte length
* @param {string} params.dataStoreETag - object ETag
* @param {string} [params.dataStoreVersionId] - object version ID, if
* versioned
* @return {object} - the response object to serialize and send back
*/
function constructPutResponse(params) {
// FIXME: The main data locations array may eventually resemble
// locations stored in replication info object, i.e. without
// size/start for cloud locations, which could ease passing
// standard location objects across services. For now let's just
// create the location as they are usually stored in the
// "locations" attribute, with size/start info.
const location = [{
dataStoreName: params.dataStoreName,
dataStoreType: params.dataStoreType,
key: params.key,
start: 0,
size: params.size,
dataStoreETag: params.dataStoreETag,
dataStoreVersionId: params.dataStoreVersionId,
}];
return {
// TODO: Remove '' when versioning implemented for Azure.
versionId: params.dataStoreVersionId || '',
location,
};
}
function handleTaggingOperation(request, response, type, dataStoreVersionId,
log, callback) {
const storageLocation = request.headers['x-scal-storage-class'];
const objectMD = {
dataStoreName: storageLocation,
location: [{ dataStoreVersionId }],
};
if (type === 'Put') {
try {
const tags = JSON.parse(request.headers['x-scal-tags']);
objectMD.tags = tags;
} catch {
// FIXME: add error type MalformedJSON
return callback(errors.MalformedPOSTRequest);
}
}
return dataClient.objectTagging(type, request.objectKey,
request.bucketName, objectMD, log, err => {
if (err) {
log.error(`error during object tagging: ${type}`, {
error: err,
method: 'handleTaggingOperation',
});
return callback(err);
}
const dataRetrievalInfo = {
versionId: dataStoreVersionId,
};
return response ? _respond(response, dataRetrievalInfo, log, callback) : callback();
});
}
/*
PUT /_/backbeat/metadata/<bucket name>/<object key>
GET /_/backbeat/metadata/<bucket name>/<object key>?versionId=<version id>
PUT /_/backbeat/data/<bucket name>/<object key>
PUT /_/backbeat/multiplebackenddata/<bucket name>/<object key>
?operation=putobject
PUT /_/backbeat/multiplebackenddata/<bucket name>/<object key>
?operation=putpart
DELETE /_/backbeat/multiplebackenddata/<bucket name>/<object key>
?operation=deleteobject
DELETE /_/backbeat/multiplebackenddata/<bucket name>/<object key>
?operation=abortmpu
DELETE /_/backbeat/multiplebackenddata/<bucket name>/<object key>
?operation=deleteobjecttagging
POST /_/backbeat/multiplebackenddata/<bucket name>/<object key>
?operation=initiatempu
POST /_/backbeat/multiplebackenddata/<bucket name>/<object key>
?operation=completempu
POST /_/backbeat/multiplebackenddata/<bucket name>/<object key>
?operation=puttagging
GET /_/backbeat/multiplebackendmetadata/<bucket name>/<object key>
POST /_/backbeat/batchdelete/<bucket name>
GET /_/backbeat/lifecycle/<bucket name>?list-type=current
GET /_/backbeat/lifecycle/<bucket name>?list-type=noncurrent
GET /_/backbeat/lifecycle/<bucket name>?list-type=orphan
POST /_/backbeat/index/<bucket name>?operation=add
POST /_/backbeat/index/<bucket name>?operation=delete
DELETE /_/backbeat/index/<bucket name>
*/
function _getLastModified(locations, log, cb) {
const reqUids = log.getSerializedUids();
return dataClient.head(locations, reqUids, (err, data) => {
if (err) {
log.error('head object request failed', {
method: 'headObject',
error: err,
});
return cb(err);
}
return cb(null, data.LastModified || data.lastModified);
});
}
function headObject(request, response, log, cb) {
let locations;
try {
locations = JSON.parse(request.headers['x-scal-locations']);
} catch {
const msg = 'x-scal-locations header is invalid';
return cb(errorInstances.InvalidRequest.customizeDescription(msg));
}
if (!Array.isArray(locations)) {
const msg = 'x-scal-locations header is invalid';
return cb(errorInstances.InvalidRequest.customizeDescription(msg));
}
return _getLastModified(locations, log, (err, lastModified) => {
if (err) {
return cb(err);
}
const dataRetrievalInfo = { lastModified };
return _respond(response, dataRetrievalInfo, log, cb);
});
}
function createCipherBundle(bucketInfo, isV2Request, log, cb) {
// Older backbeat versions do not support encryption (they ignore
// encryption parameters returned), hence we shall not encrypt if
// request comes from an older version of Backbeat
if (isV2Request) {
const serverSideEncryption = bucketInfo.getServerSideEncryption();
if (serverSideEncryption) {
return kms.createCipherBundle(serverSideEncryption, log, cb);
}
}
return cb(null, null);
}
function putData(request, response, bucketInfo, objMd, log, callback) {
let errMessage;
const canonicalID = request.headers['x-scal-canonical-id'];
if (canonicalID === undefined) {
errMessage = 'bad request: missing x-scal-canonical-id header';
log.error(errMessage);
return callback(errorInstances.BadRequest.customizeDescription(errMessage));
}
const contentMD5 = request.headers['content-md5'];
if (contentMD5 === undefined) {
errMessage = 'bad request: missing content-md5 header';
log.error(errMessage);
return callback(errorInstances.BadRequest.customizeDescription(errMessage));
}
const context = {
bucketName: request.bucketName,
owner: canonicalID,
namespace: NAMESPACE,
objectKey: request.objectKey,
};
const payloadLen = parseInt(request.headers['content-length'], 10);
const backendInfoObj = locationConstraintCheck(
request, null, bucketInfo, log);
if (backendInfoObj.err) {
log.error('error getting backendInfo', {
error: backendInfoObj.err,
method: 'routeBackbeat',
});
return callback(errors.InternalError);
}
const backendInfo = backendInfoObj.backendInfo;
const isV2Request = request.query.v2 === '';
return createCipherBundle(bucketInfo, isV2Request, log, (err, cipherBundle) => {
if (err) {
log.error('error creating cipher bundle', {
error: err,
method: 'routeBackbeat',
});
return callback(errors.InternalError);
}
return dataStore(
context, cipherBundle, request, payloadLen, {},
backendInfo, log, (err, retrievalInfo, md5) => {
if (err) {
log.error('error putting data', {
error: err,
method: 'putData',
});
return callback(err);
}
if (contentMD5 !== md5) {
return callback(errors.BadDigest);
}
const { key, dataStoreName } = retrievalInfo;
const dataRetrievalInfo = [{
key,
dataStoreName,
}];
if (cipherBundle) {
dataRetrievalInfo[0].cryptoScheme = cipherBundle.cryptoScheme;
dataRetrievalInfo[0].cipheredDataKey = cipherBundle.cipheredDataKey;
return _respondWithHeaders(response, dataRetrievalInfo, {
'x-amz-server-side-encryption': cipherBundle.algorithm,
'x-amz-server-side-encryption-aws-kms-key-id': cipherBundle.masterKeyId,
}, log, callback);
}
return _respond(response, dataRetrievalInfo, log, callback);
});
});
}
/**
* @callback CanonicalIdCallback
* @param {Error|null} err - Error object if operation failed, null otherwise
* @param {Object} [result] - Result object containing account information
* @param {string} [result.accountId] - The account ID
* @param {string} [result.canonicalId] - The canonical ID associated with the account
* @param {string} [result.name] - The display name associated with the account
* @returns {undefined}
*/
/**
*
* @param {string} accountId - account ID
* @param {Log} log - logger instance
* @param {CanonicalIdCallback} cb - callback function
* @returns {undefined}
*/
function getCanonicalIdsByAccountId(accountId, log, cb) {
return vault.getCanonicalIdsByAccountIds([accountId], log, (err, res) => {
if (err) {
log.error('error getting canonical ID by account ID', {
error: err,
accountId,
method: 'getCanonicalIdsByAccountIds',
});
return cb(err);
}
if (res.length === 0) {
log.error('account ID not found', {
accountId,
method: 'getCanonicalIdsByAccountIds',
});
return cb(errors.AccountNotFound);
}
return cb(null, res[0]);
});
}
function putMetadata(request, response, bucketInfo, objMd, log, callback) {
return _getRequestPayload(request, (err, payload) => {
if (err) {
return callback(err);
}
let omVal;
try {
omVal = JSON.parse(payload);
} catch {
// FIXME: add error type MalformedJSON
return callback(errors.MalformedPOSTRequest);
}
const { headers, bucketName, objectKey } = request;
// check if it's metadata only operation
if (headers['x-scal-replication-content'] === 'METADATA') {
if (!objMd) {
// if the target does not exist, return an error to
// backbeat, who will have to retry the operation as a
// complete replication
return callback(errors.ObjNotFound);
}
// use original data locations and encryption info
[
'location',
'x-amz-server-side-encryption',
'x-amz-server-side-encryption-aws-kms-key-id',
'x-amz-server-side-encryption-customer-algorithm',
].forEach(headerName => {
omVal[headerName] = objMd[headerName];
});
}
let versionId = decodeVersionId(request.query);
let versioning = bucketInfo.isVersioningEnabled();
let isNull = false;
if (versionId === 'null') {
isNull = true;
// Retrieve the null version id from the object metadata.
versionId = objMd && objMd.versionId;
if (!versionId) {
// Set isNull in the object metadata to be written.
// Since metadata will generate a versionId for the null version,
// the flag is needed to allow cloudserver to know that the version
// is a null version and allow access to it using the "null" versionId.
omVal.isNull = true;
// If the new null keys logic (S3C-7352) is supported (not compatibility mode),
// create a null key with the isNull2 flag.
if (!nullVersionCompatMode) {
omVal.isNull2 = true;
}
// Delete the version id from the version metadata payload to prevent issues
// with creating a non-version object (versioning set to false) that includes a version id.
// For example, this version ID might come from a null version of a suspended bucket being
// replicated to this bucket.
delete omVal.versionId;
if (versioning) {
// If the null version does not have a version id, it is a current null version.
// To update the metadata of a current version, versioning is set to false.
// This condition is to handle the case where a single null version looks like a master
// key and will not have a duplicate versioned key and no version ID.
// They are created when you have a non-versioned bucket with objects,
// and then convert bucket to versioned.
// If no new versioned objects are added for given object(s), they look like
// standalone master keys.
versioning = false;
} else {
const versioningConf = bucketInfo.getVersioningConfiguration();
// The purpose of this condition is to address situations in which
// - versioning is "suspended" and
// - no existing object or no null version.
// In such scenarios, we generate a new null version and designate it as the master version.
if (versioningConf && versioningConf.Status === 'Suspended') {
versionId = '';
}
}
}
}
// If the object is from a source bucket without versioning (i.e. NFS),
// then we want to create a version for the replica object even though
// none was provided in the object metadata value.
if (omVal.replicationInfo.isNFS) {
const isReplica = omVal.replicationInfo.status === 'REPLICA';
versioning = isReplica;
omVal.replicationInfo.isNFS = !isReplica;
}
const options = {
overheadField: constants.overheadField,
};
// NOTE: When 'versioning' is set to true and no 'versionId' is specified,
// it results in the creation of a "new" version, which also updates the master.
// NOTE: Since option fields are converted to strings when they're sent to Metadata via the query string,
// Metadata interprets the value "false" as if it were true.
// Therefore, to avoid this confusion, we don't pass the versioning parameter at all if its value is false.
if (versioning) {
options.versioning = true;
}
// NOTE: When options fields are sent to Metadata through the query string,
// they are converted to strings. As a result, Metadata interprets the value undefined
// in the versionId field as an empty string ('').
// To prevent this, the versionId field is only included in options when it is defined.
if (versionId !== undefined) {
options.versionId = versionId;
// In the MongoDB metadata backend, setting the versionId option leads to the creation
// or update of the version object, the master object is only updated if its versionId
// is the same as the version. This can lead to inconsistencies when replicating objects
// in the wrong order (can happen when retrying after failures), where the master object
// might point to a non current version. To prevent this, we need to set repairMaster to
// true which will update the master to the latest version available at the time of the put.
// The update is only done when putting a new version as updating versions that already exist
// shouldn't affect the master.
if (!objMd) {
options.repairMaster = true;
}
}
// If the new null keys logic (S3C-7352) is not supported (compatibility mode), 'isNull' remains undefined.
if (!nullVersionCompatMode) {
options.isNull = isNull;
}
return async.series([
// Zenko's CRR delegates replacing the account
// information to the destination's Cloudserver, as
// Vault admin APIs are not exposed externally.
next => {
// Internal users of this API (other features in Zenko) will
// not provide the accountId in the request, as they only update
// the metadata of existing objects, so there is no need to
// replace the account information.
if (!request.query?.accountId) {
return next();
}
return getCanonicalIdsByAccountId(request.query.accountId, log, (err, res) => {
if (err) {
return next(err);
}
omVal['owner-display-name'] = res.name;
omVal['owner-id'] = res.canonicalId;
return next();
});
},
next => {
log.trace('putting object version', {
objectKey: request.objectKey, omVal, options });
return metadata.putObjectMD(bucketName, objectKey, omVal, options, log,
(err, md) => {
if (err) {
log.error('error putting object metadata', {
error: err,
method: 'putMetadata',
});
return next(err);
}
pushReplicationMetric(objMd, omVal, bucketName, objectKey, log);
if (objMd &&
headers['x-scal-replication-content'] !== 'METADATA' &&
versionId &&
// The new data location is set to null when archiving to a Cold site.
// In that case "removing old data location key" is handled by the lifecycle
// transition processor. Check the content-length as a null location can
// also be from an empty object.
(omVal['content-length'] === 0 ||
(omVal.location && Array.isArray(omVal.location))) &&
locationKeysHaveChanged(objMd.location, omVal.location)) {
log.info('removing old data locations', {
method: 'putMetadata',
bucketName,
objectKey,
});
async.eachLimit(objMd.location, 5,
(loc, nextEach) => dataWrapper.data.delete(loc, log, err => {
if (err) {
log.warn('error removing old data location key', {
bucketName,
objectKey,
locationKey: loc,
error: err.message,
});
}
// do not forward the error to let other
// locations be deleted
nextEach();
}),
() => {
log.debug('done removing old data locations', {
method: 'putMetadata',
bucketName,
objectKey,
});
});
}
return _respond(response, md, log, next);
});
}
], callback);
});
}
function putObject(request, response, log, callback) {
const err = _checkMultipleBackendRequest(request, log);
if (err) {
return callback(err);
}
const storageLocation = request.headers['x-scal-storage-class'];
const sourceVersionId = request.headers['x-scal-version-id'];
const canonicalID = request.headers['x-scal-canonical-id'];
const contentMD5 = request.headers['content-md5'];
const contentType = request.headers['x-scal-content-type'];
const userMetadata = request.headers['x-scal-user-metadata'];
const cacheControl = request.headers['x-scal-cache-control'];
const contentDisposition = request.headers['x-scal-content-disposition'];
const contentEncoding = request.headers['x-scal-content-encoding'];
const tagging = request.headers['x-scal-tags'];
const metaHeaders = { 'x-amz-meta-scal-replication-status': 'REPLICA' };
if (sourceVersionId) {
metaHeaders['x-amz-meta-scal-version-id'] = sourceVersionId;
}
if (userMetadata !== undefined) {
try {
const metaData = JSON.parse(userMetadata);
Object.assign(metaHeaders, metaData);
} catch {
// FIXME: add error type MalformedJSON
return callback(errors.MalformedPOSTRequest);
}
}
const context = {
bucketName: request.bucketName,
owner: canonicalID,
namespace: NAMESPACE,
objectKey: request.objectKey,
metaHeaders,
contentType,
cacheControl,
contentDisposition,
contentEncoding,
};
if (tagging !== undefined) {
try {
const tags = JSON.parse(request.headers['x-scal-tags']);
context.tagging = querystring.stringify(tags);
} catch {
// FIXME: add error type MalformedJSON
return callback(errors.MalformedPOSTRequest);
}
}
const payloadLen = parseInt(request.headers['content-length'], 10);
const backendInfo = new BackendInfo(config, storageLocation);
return dataStore(context, CIPHER, request, payloadLen, {}, backendInfo, log,
(err, retrievalInfo, md5) => {
if (err) {
log.error('error putting data', {
error: err,
method: 'putObject',
});
return callback(err);
}
if (contentMD5 !== md5) {
return callback(errors.BadDigest);
}
const responsePayload = constructPutResponse({
dataStoreName: retrievalInfo.dataStoreName,
dataStoreType: retrievalInfo.dataStoreType,
key: retrievalInfo.key,
size: payloadLen,
dataStoreETag: retrievalInfo.dataStoreETag ?
`1:${retrievalInfo.dataStoreETag}` : `1:${md5}`,
dataStoreVersionId: retrievalInfo.dataStoreVersionId,
});
return _respond(response, responsePayload, log, callback);
});
}
function deleteObjectFromExpiration(request, response, userInfo, log, callback) {
return objectDeleteInternal(userInfo, request, log, true, err => {
if (err) {
log.error('error deleting object from expiration', {
error: err,
method: 'deleteObjectFromExpiration',
});
return callback(err);
}
return _respond(response, {}, log, callback);
});
}
function deleteObject(request, response, log, callback) {
const err = _checkMultipleBackendRequest(request, log);
if (err) {
return callback(err);
}
const storageLocation = request.headers['x-scal-storage-class'];
const objectGetInfo = dataClient.toObjectGetInfo(
request.objectKey, request.bucketName, storageLocation);
if (!objectGetInfo) {
log.error('error deleting object in multiple backend', {
error: 'cannot create objectGetInfo',
method: 'deleteObject',
});
return callback(errors.InternalError);
}
const reqUids = log.getSerializedUids();
return dataClient.delete(objectGetInfo, reqUids, err => {
if (err) {
log.error('error deleting object in multiple backend', {
error: err,
method: 'deleteObject',
});
return callback(err);
}
return _respond(response, {}, log, callback);
});
}
function getMetadata(request, response, bucketInfo, objectMd, log, cb) {
if (!objectMd) {
return cb(errors.ObjNotFound);
}
return _respond(response, { Body: JSON.stringify(objectMd) }, log, cb);
}
function initiateMultipartUpload(request, response, log, callback) {
const err = _checkMultipleBackendRequest(request, log);
if (err) {
return callback(err);
}
const storageLocation = request.headers['x-scal-storage-class'];
const sourceVersionId = request.headers['x-scal-version-id'];
const contentType = request.headers['x-scal-content-type'];
const userMetadata = request.headers['x-scal-user-metadata'];
const cacheControl = request.headers['x-scal-cache-control'];
const contentDisposition = request.headers['x-scal-content-disposition'];
const contentEncoding = request.headers['x-scal-content-encoding'];
const tags = request.headers['x-scal-tags'];
const metaHeaders = { 'x-amz-meta-scal-replication-status': 'REPLICA' };
if (sourceVersionId) {
metaHeaders['x-amz-meta-scal-version-id'] = sourceVersionId;
}
if (userMetadata !== undefined) {
try {
const metaData = JSON.parse(userMetadata);
Object.assign(metaHeaders, metaData);
} catch {
// FIXME: add error type MalformedJSON
return callback(errors.MalformedPOSTRequest);
}
}
let tagging;
if (tags !== undefined) {
try {
const parsedTags = JSON.parse(request.headers['x-scal-tags']);
tagging = querystring.stringify(parsedTags);
} catch {
// FIXME: add error type MalformedJSON
return callback(errors.MalformedPOSTRequest);
}
}
return dataClient.createMPU(request.objectKey, metaHeaders,
request.bucketName, undefined, storageLocation, contentType,
cacheControl, contentDisposition, contentEncoding, tagging, log,
(err, data) => {
if (err) {
log.error('error initiating multipart upload', {
error: err,
method: 'initiateMultipartUpload',
});
return callback(err);
}
const dataRetrievalInfo = {
uploadId: data.UploadId,
};
return _respond(response, dataRetrievalInfo, log, callback);
});
}
function abortMultipartUpload(request, response, log, callback) {
const err = _checkMultipleBackendRequest(request, log);
if (err) {
return callback(err);
}
const storageLocation = request.headers['x-scal-storage-class'];
const uploadId = request.headers['x-scal-upload-id'];
return dataClient.abortMPU(request.objectKey, uploadId,
storageLocation, request.bucketName, log, err => {
if (err) {
log.error('error aborting MPU', {
error: err,
method: 'abortMultipartUpload',
});
return callback(err);
}
return _respond(response, {}, log, callback);
});
}
function putPart(request, response, log, callback) {
const err = _checkMultipleBackendRequest(request, log);
if (err) {
return callback(err);
}
const storageLocation = request.headers['x-scal-storage-class'];
const partNumber = request.headers['x-scal-part-number'];
const uploadId = request.headers['x-scal-upload-id'];
const payloadLen = parseInt(request.headers['content-length'], 10);
return dataClient.uploadPart(undefined, {}, request, payloadLen,
storageLocation, request.objectKey, uploadId, partNumber,
request.bucketName, log, (err, data) => {
if (err) {
log.error('error putting MPU part', {
error: err,
method: 'putPart',
});
return callback(err);
}
const dataRetrievalInfo = {
partNumber,
ETag: data.dataStoreETag,
numberSubParts: data.numberSubParts,
};
return _respond(response, dataRetrievalInfo, log, callback);
});
}
function completeMultipartUpload(request, response, log, callback) {
const err = _checkMultipleBackendRequest(request, log);
if (err) {
return callback(err);
}
const storageLocation = request.headers['x-scal-storage-class'];
const sourceVersionId = request.headers['x-scal-version-id'];
const uploadId = request.headers['x-scal-upload-id'];
const userMetadata = request.headers['x-scal-user-metadata'];
const contentType = request.headers['x-scal-content-type'];
const cacheControl = request.headers['x-scal-cache-control'];
const contentDisposition = request.headers['x-scal-content-disposition'];
const contentEncoding = request.headers['x-scal-content-encoding'];
const tags = request.headers['x-scal-tags'];
const data = [];
let totalLength = 0;
request.on('data', chunk => {
totalLength += chunk.length;
data.push(chunk);
});
request.on('end', () => {
let parts;
try {
parts = JSON.parse(Buffer.concat(data), totalLength);
} catch {
// FIXME: add error type MalformedJSON
return callback(errors.MalformedPOSTRequest);
}
const partList = getPartList(
parts, request.objectKey, uploadId, storageLocation);
// Azure client will set user metadata at this point.
const metaHeaders = { 'x-amz-meta-scal-replication-status': 'REPLICA' };
if (sourceVersionId) {
metaHeaders['x-amz-meta-scal-version-id'] = sourceVersionId;
}
if (userMetadata !== undefined) {
try {
const metaData = JSON.parse(userMetadata);
Object.assign(metaHeaders, metaData);
} catch {
// FIXME: add error type MalformedJSON
return callback(errors.MalformedPOSTRequest);
}
}
// Azure does not have a notion of initiating an MPU, so we put any
// tagging fields during the complete MPU if using Azure.
let tagging;
if (tags !== undefined) {
try {
const parsedTags = JSON.parse(request.headers['x-scal-tags']);
tagging = querystring.stringify(parsedTags);
} catch {
// FIXME: add error type MalformedJSON
return callback(errors.MalformedPOSTRequest);
}
}
const contentSettings = {
contentType: contentType || undefined,
cacheControl: cacheControl || undefined,
contentDisposition: contentDisposition || undefined,
contentEncoding: contentEncoding || undefined,
};
return dataClient.completeMPU(request.objectKey, uploadId,
storageLocation, partList, undefined, request.bucketName,
metaHeaders, contentSettings, tagging, log,
(err, retrievalInfo) => {
if (err) {