-
Notifications
You must be signed in to change notification settings - Fork 36
/
S3IO.cpp
301 lines (234 loc) · 10.6 KB
/
S3IO.cpp
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
/*
* This File is part of Davix, The IO library for HTTP based protocols
* Copyright (C) CERN 2017
* Author: Georgios Bitzes <georgios.bitzes@cern.ch>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "S3IO.hpp"
#include <core/ContentProvider.hpp>
#include <utils/davix_logger_internal.hpp>
#include <xml/S3MultiPartInitiationParser.hpp>
#define SSTR(message) static_cast<std::ostringstream&>(std::ostringstream().flush() << message).str()
namespace Davix{
static bool is_s3_operation(IOChainContext & context){
if(context._reqparams->getProtocol() == RequestProtocol::AwsS3) {
return true;
}
return false;
}
static bool should_use_s3_multipart(IOChainContext & context, dav_size_t size) {
bool is_s3 = is_s3_operation(context);
if(!is_s3) return false;
if(context._uri.fragmentParamExists("forceMultiPart")) {
return true;
}
return size > (1024 * 1024 * 512); // 512 MB
}
S3IO::S3IO() {
}
S3IO::~S3IO() {
}
std::string S3IO::initiateMultipart(IOChainContext & iocontext) {
Uri url(iocontext._uri);
url.addQueryParam("uploads", "");
return initiateMultipart(iocontext, url);
}
std::string S3IO::initiateMultipart(IOChainContext & iocontext, const Uri &url) {
DavixError * tmp_err=NULL;
PostRequest req(iocontext._context, url, &tmp_err);
checkDavixError(&tmp_err);
req.setParameters(iocontext._reqparams);
req.setRequestBody("");
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
checkDavixError(&tmp_err);
std::string response = req.getAnswerContent();
S3MultiPartInitiationParser parser;
if(parser.parseChunk(response) != 0) {
DavixError::setupError(&tmp_err, "S3::MultiPart", StatusCode::InvalidServerResponse, "Unable to parse server response for multi-part initiation");
}
checkDavixError(&tmp_err);
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN,
"S3IO: Obtained multi-part upload id {} for {}",
parser.getUploadId(), iocontext._uri);
return parser.getUploadId();
}
std::string S3IO::writeChunk(IOChainContext & iocontext, const char* buff, dav_size_t size, const std::string &uploadId, int partNumber) {
Uri url(iocontext._uri);
url.addQueryParam("uploadId", uploadId);
url.addQueryParam("partNumber", SSTR(partNumber));
return writeChunk(iocontext, buff, size, url, partNumber);
}
std::string S3IO::writeChunk(IOChainContext & iocontext, const char* buff, dav_size_t size, const Uri &url, int partNumber) {
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "writing chunk #{} with size {}", partNumber, size);
DavixError * tmp_err=NULL;
PutRequest req(iocontext._context, url, &tmp_err);
checkDavixError(&tmp_err);
req.setParameters(iocontext._reqparams);
req.setRequestBody(buff, size);
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "write result size {}", size);
checkDavixError(&tmp_err);
std::string etag;
if(!req.getAnswerHeader("Etag", etag)) {
DavixError::setupError(&tmp_err, "S3::MultiPart", StatusCode::InvalidServerResponse, "Unable to retrieve chunk Etag, necessary when committing chunks");
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "chunk #{} written successfully, etag: {}", partNumber, etag);
return etag;
}
bool S3IO::commitChunks(IOChainContext & iocontext, const std::string &uploadId, const std::vector<std::string> &etags) {
Uri url(iocontext._uri);
url.addQueryParam("uploadId", uploadId);
commitChunks(iocontext, url, etags);
return true;
}
void S3IO::commitChunks(IOChainContext & iocontext, const Uri &url, const std::vector<std::string> &etags) {
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "committing {} chunks", etags.size());
std::ostringstream payload;
payload << "<CompleteMultipartUpload>";
for(size_t i = 1; i <= etags.size(); i++) {
payload << "<Part>";
payload << "<PartNumber>" << i << "</PartNumber>";
payload << "<ETag>" << etags[i-1] << "</ETag>";
payload << "</Part>";
}
payload << "</CompleteMultipartUpload>";
DavixError * tmp_err=NULL;
PostRequest req(iocontext._context, url, &tmp_err);
req.setParameters(iocontext._reqparams);
req.setRequestBody(payload.str());
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
checkDavixError(&tmp_err);
}
static dav_size_t fillBufferWithProviderData(std::vector<char> &buffer, const dav_size_t maxChunkSize, ContentProvider &provider) {
dav_size_t written = 0u;
dav_size_t remaining = maxChunkSize;
while(true) {
dav_ssize_t bytesRead = provider.pullBytes(buffer.data(), remaining);
if(bytesRead < 0) {
throw DavixException(davix_scope_io_buff(), StatusCode::InvalidFileHandle, fmt::format("Error when reading from callback: {}", bytesRead));
}
remaining -= bytesRead;
written += bytesRead;
if(bytesRead == 0) {
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Reached data provider EOF, received 0 bytes, even though asked for {}", remaining);
break; // EOF
}
if(remaining == 0) {
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Data provider buffer has been filled");
break; // buffer is full
}
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Retrieved {} bytes from data provider", written);
return written;
}
// write from a buffer
bool S3IO::writeFromBuffer(IOChainContext& iocontext, const char* buff,
dav_size_t size, const std::string& uploadId,
std::vector<std::string>& etags, int partNumber) {
etags.emplace_back(writeChunk(iocontext, buff, size, uploadId, partNumber));
return true;
}
// write from content provider
dav_ssize_t S3IO::writeFromProvider(IOChainContext & iocontext, ContentProvider &provider) {
if(!should_use_s3_multipart(iocontext, provider.getSize())) {
CHAIN_FORWARD(writeFromProvider(iocontext, provider));
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Initiating multi-part upload towards {} to upload file with size {}", iocontext._uri, provider.getSize());
std::string uploadId = initiateMultipart(iocontext);
size_t remaining = provider.getSize();
const dav_size_t MAX_CHUNK_SIZE = 1024 * 1024 * 256; // 256 MB
std::vector<char> buffer;
buffer.resize(std::min(MAX_CHUNK_SIZE, (dav_size_t) provider.getSize()) + 10);
std::vector<std::string> etags;
size_t partNumber = 0;
while(remaining > 0) {
size_t toRead = std::min( (dav_size_t) provider.getSize(), MAX_CHUNK_SIZE);
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "S3IO write: toRead from cb {}", toRead);
dav_size_t bytesRead = fillBufferWithProviderData(buffer, MAX_CHUNK_SIZE, provider);
if(bytesRead == 0) break; // EOF
partNumber++;
etags.emplace_back(writeChunk(iocontext, buffer.data(), bytesRead, uploadId, partNumber));
}
commitChunks(iocontext, uploadId, etags);
return provider.getSize();
}
DynafedUris S3IO::retrieveDynafedUris(IOChainContext & iocontext, const std::string &uploadId, const std::string &pluginId, size_t nchunks) {
DynafedUris retval;
DavixError *tmp_err = NULL;
PutRequest req(iocontext._context, iocontext._uri, &tmp_err);
checkDavixError(&tmp_err);
req.setParameters(iocontext._reqparams);
req.addHeaderField("x-s3-uploadid", uploadId);
req.addHeaderField("x-ugrpluginid", pluginId);
req.addHeaderField("x-s3-upload-nchunks", SSTR(nchunks));
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
checkDavixError(&tmp_err);
// We have a response, parse it into lines
retval.chunks = StrUtil::tokenSplit(req.getAnswerContent(), "\n");
if(!retval.chunks.empty()) {
retval.post = retval.chunks.back();
retval.chunks.pop_back();
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "retrieveDynafedUris: Obtained list with {} chunk URIs in total", retval.chunks.size());
return retval;
}
void S3IO::performUgrS3MultiPart(IOChainContext & iocontext, const std::string &posturl, const std::string &pluginId, ContentProvider &provider, DavixError **err) {
try {
Uri uri(posturl);
std::string uploadId = initiateMultipart(iocontext, posturl);
const dav_size_t MAX_CHUNK_SIZE = 1024 * 1024 * 256; // 256 MB
std::vector<char> buffer;
buffer.resize(std::min(MAX_CHUNK_SIZE, (dav_size_t) provider.getSize()) + 10);
size_t nchunks = (provider.getSize() / MAX_CHUNK_SIZE) + 2;
DynafedUris uris = retrieveDynafedUris(iocontext, uploadId, pluginId, nchunks);
if(uris.chunks.size() != nchunks) {
DAVIX_SLOG(DAVIX_LOG_WARNING, DAVIX_LOG_CHAIN, "Dynafed returned different number of URIs than expected: {} vs {]", "} retrieveDynafedUris: Obtained list with {} chunk URIs in total", uris.chunks.size(), nchunks);
throw DavixException("S3::MultiPart", StatusCode::InvalidServerResponse, "Dynafed returned different number of URIs than expected");
}
std::vector<std::string> etags;
size_t partNumber = 1;
uint64_t remaining = provider.getSize();
while(remaining > 0) {
dav_size_t bytesRetrieved = fillBufferWithProviderData(buffer, MAX_CHUNK_SIZE, provider);
if(bytesRetrieved == 0) {
break; // EOF
}
etags.emplace_back(writeChunk(iocontext, buffer.data(), bytesRetrieved, Uri(uris.chunks[partNumber-1]), partNumber));
partNumber++;
remaining -= bytesRetrieved;
}
commitChunks(iocontext, Uri(uris.post), etags);
}
CATCH_DAVIX(err);
}
}