ECS3Attachment.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. #include "config.h"
  2. #ifdef HAVE_LIBS3_H
  3. #include <kopano/platform.h>
  4. #include <algorithm>
  5. #include <mutex>
  6. #include <stdexcept>
  7. #include <cerrno>
  8. #include <unistd.h>
  9. #include <zlib.h>
  10. #include <mapidefs.h>
  11. #include <mapitags.h>
  12. #include <kopano/stringutil.h>
  13. #include "../../common/ECSerializer.h"
  14. #include "../common/SOAPUtils.h"
  15. #include "ECAttachmentStorage.h"
  16. #include "ECS3Attachment.h"
  17. #include "StreamUtil.h"
  18. namespace KC {
  19. /* Number of times the server should retry to send the command to the S3 servers, this is required to process redirects. */
  20. #define S3_RETRIES 5
  21. /* Number of seconds to sleep before trying again */
  22. #define S3_SLEEP_DELAY 1
  23. /* callback data */
  24. struct s3_cd {
  25. struct soap *soap;
  26. unsigned char *data;
  27. ECSerializer *sink;
  28. bool alloc_data;
  29. int size;
  30. int processed;
  31. int retries;
  32. S3Status status;
  33. };
  34. /* callback data wrapper */
  35. struct s3_cdw {
  36. ECS3Attachment *caller;
  37. void *cbdata;
  38. };
  39. static void *ec_libs3_handle;
  40. #define W(n) static decltype(S3_ ## n) *DY_ ## n;
  41. W(put_object)
  42. W(initialize)
  43. W(status_is_retryable)
  44. W(deinitialize)
  45. W(get_status_name)
  46. W(head_object)
  47. W(delete_object)
  48. W(get_object)
  49. #undef W
  50. /**
  51. * Static function used to forward the response properties callback to the
  52. * right object.
  53. *
  54. * @param properties the response properties of the S3 request.
  55. * @param cbdata contains the callback pointer to the ECS3Attachment instance and its callback data.
  56. *
  57. * @return The status of the response properties callback function.
  58. */
  59. S3Status ECS3Attachment::response_prop_cb(const S3ResponseProperties *properties, void *cbdata)
  60. {
  61. auto data = static_cast<struct s3_cdw *>(cbdata);
  62. return data->caller->response_prop(properties, data->cbdata);
  63. }
  64. /**
  65. * Static function used to forward the callback to the right object.
  66. *
  67. * @param status the S3 resonse code of our request
  68. * @param errorDetails can be NULL, otherwise it contains details on the error that occurred.
  69. * @param cbdata contains the callback pointer to the ECS3Attachment instance and its callback data.
  70. */
  71. void ECS3Attachment::response_complete_cb(S3Status status,
  72. const S3ErrorDetails *error, void *cbdata)
  73. {
  74. auto data = static_cast<struct s3_cdw *>(cbdata);
  75. return data->caller->response_complete(status, error, data->cbdata);
  76. }
  77. /**
  78. * Static function used to forward the callback to the right object.
  79. *
  80. * @param bufferSize the size of the buffer which we can read from
  81. * @param buffer is the buffer reference that we need to read from
  82. * @param cbdata contains the callback pointer to the ECS3Attachment instance and its callback data.
  83. *
  84. * @return The status of the reading more data from the buffer.
  85. */
  86. S3Status ECS3Attachment::get_obj_cb(int bufferSize, const char *buffer, void *cbdata)
  87. {
  88. auto data = static_cast<struct s3_cdw *>(cbdata);
  89. return data->caller->get_obj(bufferSize, buffer, data->cbdata);
  90. }
  91. /**
  92. * Static function used to forward the callback to the right object.
  93. *
  94. * @param bufferSize the size of the buffer which we can write to
  95. * @param buffer is the buffer reference that we need to write to
  96. * @param cbdata contains the callback pointer to the ECS3Attachment instance and its callback data.
  97. *
  98. * @return the number of bytes that have been written to the buffer.
  99. */
  100. int ECS3Attachment::put_obj_cb(int bufferSize, char *buffer, void *cbdata)
  101. {
  102. auto data = static_cast<struct s3_cdw *>(cbdata);
  103. return data->caller->put_obj(bufferSize, buffer, data->cbdata);
  104. }
  105. ECRESULT ECS3Attachment::StaticInit(ECConfig *cf)
  106. {
  107. ec_log_info("Initializing S3 Attachment Storage");
  108. /*
  109. * Do a dlopen of libs3.so.3 so that the implicit pull-in of
  110. * libldap-2.4.so.2 symbols does not pollute our namespace of
  111. * libldap_r-2.4.so.2 symbols.
  112. */
  113. void *h = ec_libs3_handle = dlopen("libs3.so.3", RTLD_LAZY | RTLD_LOCAL);
  114. const char *err;
  115. if (ec_libs3_handle == NULL) {
  116. ec_log_warn("dlopen libs3.so.3: %s", (err = dlerror()) ? err : "<none>");
  117. return KCERR_DATABASE_ERROR;
  118. }
  119. #define W(n) do { \
  120. DY_ ## n = reinterpret_cast<decltype(DY_ ## n)>(dlsym(h, "S3_" #n)); \
  121. if (DY_ ## n == NULL) { \
  122. ec_log_warn("dlsym S3_" #n ": %s", (err = dlerror()) ? err : "<none>"); \
  123. dlclose(h); \
  124. ec_libs3_handle = NULL; \
  125. return KCERR_DATABASE_ERROR; \
  126. } \
  127. } while (false)
  128. W(put_object);
  129. W(initialize);
  130. W(status_is_retryable);
  131. W(deinitialize);
  132. W(get_status_name);
  133. W(head_object);
  134. W(delete_object);
  135. W(get_object);
  136. #undef W
  137. S3Status status = DY_initialize("Kopano Mail", S3_INIT_ALL, cf->GetSetting("attachment_s3_hostname"));
  138. if (status != S3StatusOK) {
  139. ec_log_err("Error while initializing S3 Attachment Storage, error type: %s",
  140. DY_get_status_name(status));
  141. return KCERR_NETWORK_ERROR;
  142. }
  143. return erSuccess;
  144. }
  145. ECRESULT ECS3Attachment::StaticDeinit(void)
  146. {
  147. ec_log_info("Deinitializing S3 Attachment Storage");
  148. /* Deinitialize the S3 storage environment */
  149. if (ec_libs3_handle != NULL) {
  150. DY_deinitialize();
  151. dlclose(ec_libs3_handle);
  152. }
  153. return erSuccess;
  154. }
  155. /*
  156. * Locking requirements of ECAttachmentStorage: In the case of
  157. * ECAttachmentStorage locking to protect against concurrent access is futile.
  158. * The theory is as follows:
  159. *
  160. * If two users have a reference to the same attachment, neither can delete the
  161. * mail causing the other person to lose the attachment. This means that
  162. * concurrent copy and delete actions are possible on the same attachment. The
  163. * only case where this does not hold is the case when a user deletes the mail
  164. * he is copying at the same time and that this is the last mail which
  165. * references that specific attachment.
  166. *
  167. * The only race condition which might occur is that the dagent delivers a mail
  168. * with attachment, the server returns the attachment id back to the dagent,
  169. * but the user for whom the message was intended deletes the mail &
  170. * attachment. In this case the dagent will no longer send the attachment but
  171. * only the attachment id. When that happens the server can return an error and
  172. * simply request the dagent to resend the attachment and to obtain a new
  173. * attachment id.
  174. */
  175. /**
  176. * The ECS3Attachment Storage engine is used to store attachments as separate
  177. * files in the S3 storage cluster. This is useful to ensure you have enough
  178. * storage capacity on your servers and can be used to cluster multiple Kopano
  179. * servers together, allowing each of them to access the same storage for the
  180. * attachments.
  181. *
  182. * @param database The database connection of the Kopano Server
  183. * @param protocol sets the type of protocol that should be used to connect to the Amazon S3 cluster.
  184. * The options are http or https, of which https is the preferred option.
  185. * @param uriStyle The uri style of the bucket, allowed options are virtualhost or path,
  186. * @param accessKeyId The access key of your Amazon account for S3 storage.
  187. * @param secretAccessKey The secret access key of your Amazon account for S3 storage.
  188. * @param bucketName The name of the bucket in which you want to store all the attachments.
  189. * @param basepath In order to use the same bucket with different Kopano clusters, you can select
  190. * different basepaths for each cluster, this works like a separate directory where
  191. * all the files are stored in. NOTE: Use the same basepath for all the servers in
  192. * a single server cluster.
  193. * @param ulCompressionLevel the compression level used to gzip the attachment data.
  194. */
  195. ECS3Attachment::ECS3Attachment(ECDatabase *database, const char *protocol,
  196. const char *uri_style, const char *access_key_id,
  197. const char *secret_access_key, const char *bucket_name, const char *region,
  198. const char *basepath, unsigned int complvl) :
  199. ECAttachmentStorage(database, complvl), m_basepath(basepath)
  200. {
  201. memset(&m_bucket_ctx, 0, sizeof(m_bucket_ctx));
  202. m_bucket_ctx.bucketName = bucket_name;
  203. m_bucket_ctx.protocol = strncmp(protocol, "https", 5) == 0 ? S3ProtocolHTTPS : S3ProtocolHTTP;
  204. m_bucket_ctx.uriStyle = strncmp(uri_style, "path", 4) == 0 ? S3UriStylePath : S3UriStyleVirtualHost;
  205. m_bucket_ctx.accessKeyId = access_key_id;
  206. m_bucket_ctx.secretAccessKey = secret_access_key;
  207. m_bucket_ctx.authRegion = region;
  208. /* Set the handlers */
  209. m_response_handler.propertiesCallback = &ECS3Attachment::response_prop_cb;
  210. m_response_handler.completeCallback = &ECS3Attachment::response_complete_cb;
  211. m_put_obj_handler.responseHandler = m_response_handler;
  212. m_put_obj_handler.putObjectDataCallback = &ECS3Attachment::put_obj_cb;
  213. m_get_obj_handler.responseHandler = m_response_handler;
  214. m_get_obj_handler.getObjectDataCallback = &ECS3Attachment::get_obj_cb;
  215. m_get_conditions.ifModifiedSince = -1;
  216. m_get_conditions.ifNotModifiedSince = -1;
  217. m_get_conditions.ifMatchETag = NULL;
  218. m_get_conditions.ifNotMatchETag = NULL;
  219. }
  220. ECS3Attachment::~ECS3Attachment(void)
  221. {
  222. assert(!m_transact);
  223. }
  224. /**
  225. * As soon as the response properties are returned by S3, this callback will be
  226. * called to process them.
  227. *
  228. * @param properties the properties object that contains details on the request
  229. * @param cbdata the callback data reference that was given at the time the request fired.
  230. *
  231. * @return the status of processing the information. Generally, this will
  232. * return S3StatusOK, however, if it should allocate memory for the data
  233. * buffer, and fails to do so, it will return with S3StatusAbortedByCallback.
  234. */
  235. S3Status ECS3Attachment::response_prop(const S3ResponseProperties *properties, void *cbdata)
  236. {
  237. auto data = static_cast<struct s3_cd *>(cbdata);
  238. if (properties->contentLength != 0) {
  239. data->size = properties->contentLength;
  240. ec_log_debug("Received the response properties, content length: %d", data->size);
  241. } else {
  242. ec_log_debug("Received the response properties");
  243. }
  244. /*
  245. * Only allocate memory if we are not able to use a serializer sink, we
  246. * are instructed to alloc data->data and have not allocated it yet.
  247. */
  248. if (data->sink == NULL && data->alloc_data && data->data == NULL) {
  249. data->data = s_alloc_nothrow<unsigned char>(data->soap, data->size);
  250. if (data->data == NULL) {
  251. ec_log_err("Unable to claim memory of size: %d bytes.", data->size);
  252. return S3StatusAbortedByCallback;
  253. }
  254. }
  255. return S3StatusOK;
  256. }
  257. /**
  258. * Once the request has been processed by S3 and we received all the data, this
  259. * function will be called to react accordingly.
  260. *
  261. * @param status the S3 resonse code of our request
  262. * @param errorDetails can be NULL, otherwise it contains details on the error that occurred.
  263. * @param cbdata contains the callback pointer to the ECS3Attachment instance and its callback data.
  264. *
  265. * @return The status of the response properties callback function.
  266. */
  267. void ECS3Attachment::response_complete(S3Status status,
  268. const S3ErrorDetails *error, void *cbdata)
  269. {
  270. auto data = static_cast<struct s3_cd *>(cbdata);
  271. data->status = status;
  272. ec_log_debug("Response completed: %s.", DY_get_status_name(status));
  273. if (status == S3StatusOK)
  274. return;
  275. if (error == 0) {
  276. ec_log_err("Amazon S3 return status %s", DY_get_status_name(status));
  277. return;
  278. }
  279. ec_log_err("Amazon S3 return status %s, error: %s, resource: \"%s\"",
  280. DY_get_status_name(status),
  281. error->message ? error->message : "<unknown>",
  282. error->resource ? error->resource : "<none>");
  283. if (error->furtherDetails != NULL)
  284. ec_log_err("Amazon S3 error details: %s", error->furtherDetails);
  285. for (ssize_t i = 0; i < error->extraDetailsCount; ++i)
  286. ec_log_err("Amazon S3 error details: %s: %s",
  287. error->extraDetails[i].name, error->extraDetails[i].value);
  288. }
  289. /**
  290. * This callback function will read more data from the buffer used to receive
  291. * data from S3.
  292. *
  293. * @param bufferSize the size of the buffer which we can read from
  294. * @param buffer is the buffer reference that we need to read from
  295. * @param cbdata contains the callback pointer to the ECS3Attachment instance and its callback data.
  296. *
  297. * @return The status of the reading more data from the buffer.
  298. */
  299. S3Status ECS3Attachment::get_obj(int bufferSize, const char *buffer, void *cbdata)
  300. {
  301. auto data = static_cast<struct s3_cd *>(cbdata);
  302. ECRESULT er;
  303. /*
  304. * Check if we were able to acquire the memory. There are two cases
  305. * where this could go wrong: Either we ran out of memory, in which
  306. * case we should never have reached this call, so cancel it. Or S3 did
  307. * not return the properties of the object, and therefore we have not
  308. * allocated the memory yet, in this case we should abort too.
  309. */
  310. if (data->data == NULL && data->sink == NULL)
  311. return S3StatusAbortedByCallback;
  312. /*
  313. * Check if we are not trying to write outside the acquired memory
  314. * scope, if so abort.
  315. */
  316. if (data->processed + bufferSize > data->size)
  317. return S3StatusAbortedByCallback;
  318. ec_log_debug("Getting bytes from S3 callback: Remaining bytes to get: %d. Reading %d bytes",
  319. data->size - data->processed, bufferSize);
  320. if (data->sink != NULL) {
  321. er = data->sink->Write(buffer, 1, bufferSize);
  322. if (er != erSuccess) {
  323. ec_log_err("Unable to write to serializer sink");
  324. return S3StatusAbortedByCallback;
  325. }
  326. } else {
  327. memcpy(data->data + data->processed, buffer, bufferSize);
  328. }
  329. data->processed += bufferSize;
  330. return S3StatusOK;
  331. }
  332. /**
  333. * This callback function will write more data from the buffer used to write
  334. * data to S3.
  335. *
  336. * @param bufferSize the size of the buffer which we can write to
  337. * @param buffer is the buffer reference that we need to write to
  338. * @param cbdata contains the callback pointer to the ECS3Attachment instance and its callback data.
  339. *
  340. * @return the number of bytes that have been written to the buffer.
  341. */
  342. int ECS3Attachment::put_obj(int bufferSize, char *buffer, void *cbdata)
  343. {
  344. auto data = static_cast<struct s3_cd *>(cbdata);
  345. ECRESULT ret;
  346. int toRead = 0, remaining = 0;
  347. /*
  348. * Check if we have a data buffer or serializer to read from.
  349. */
  350. if (data->data == NULL && data->sink == NULL)
  351. return -1;
  352. /* Check if we are not trying to write outside the acquired memory scope, if so abort. */
  353. if (data->processed > data->size)
  354. return -1;
  355. remaining = data->size - data->processed;
  356. if (remaining > 0) {
  357. toRead = remaining > bufferSize ? bufferSize : remaining;
  358. ec_log_debug("Putting data using callback: "
  359. "Remaining bytes to put: %d - Writing %d bytes in %d buffer",
  360. remaining, toRead, bufferSize);
  361. if (data->sink != NULL) {
  362. ret = data->sink->Read(buffer, 1, toRead);
  363. if (ret != erSuccess) {
  364. ec_log_err("Unable to read from the serializer sink");
  365. return -1;
  366. }
  367. } else {
  368. memcpy(buffer, data->data + data->processed, toRead);
  369. }
  370. data->processed += toRead;
  371. } else {
  372. ec_log_debug("Putting data using callback: Remaining bytes to put: %d - We processed all the data, but S3 expects more", remaining);
  373. }
  374. return toRead;
  375. }
  376. /**
  377. * For a given instance id, check if this has valid attachment data present.
  378. *
  379. * @param[in] ins_id instance id to check validity
  380. *
  381. * @return instance present
  382. */
  383. bool ECS3Attachment::ExistAttachmentInstance(ULONG ins_id)
  384. {
  385. struct s3_cd cdata = create_cd();
  386. struct s3_cd *cdp = &cdata;
  387. struct s3_cdw cwdata;
  388. cwdata.caller = this;
  389. cwdata.cbdata = cdp;
  390. std::string filename = make_att_filename(ins_id, false);
  391. ec_log_debug("Checking whether the attachment exists: %s", filename.c_str());
  392. /*
  393. * Loop at most S3_RETRIES times, to make sure that if the servers of S3
  394. * reply with a redirect, we actually try again and process it.
  395. */
  396. cdp->retries = S3_RETRIES;
  397. do {
  398. DY_head_object(&m_bucket_ctx, filename.c_str(), 0,
  399. &m_response_handler, &cwdata);
  400. if (DY_status_is_retryable(cdp->status))
  401. ec_log_debug("Existence check result in while: %s",
  402. DY_get_status_name(cdp->status));
  403. } while (DY_status_is_retryable(cdp->status) && should_retry(cdp));
  404. ec_log_debug("Result of the existence check: %s",
  405. DY_get_status_name(cdp->status));
  406. return cdp->status == S3StatusOK;
  407. }
  408. /**
  409. * Load instance data using soap and return as blob.
  410. *
  411. * IMPORTANT: We allocated the data in referred to by data_p to store the
  412. * attachment. The caller of this function is responsible for freeing the
  413. * memory after its use.
  414. *
  415. * @param[in] soap soap to use memory allocations for
  416. * @param[in] ins_id InstanceID to load
  417. * @param[out] size_p size in data_p
  418. * @param[out] data_p data of instance
  419. *
  420. * @return Kopano error code
  421. */
  422. ECRESULT ECS3Attachment::LoadAttachmentInstance(struct soap *soap,
  423. ULONG ins_id, size_t *size_p, unsigned char **data_p)
  424. {
  425. ECRESULT ret = KCERR_NOT_FOUND;
  426. struct s3_cd cdata = create_cd();
  427. struct s3_cd *cdp = &cdata;
  428. cdp->sink = NULL;
  429. cdp->data = NULL;
  430. cdp->alloc_data = true;
  431. cdp->size = 0;
  432. cdp->processed = 0;
  433. cdp->soap = soap;
  434. struct s3_cdw cwdata;
  435. cwdata.caller = this;
  436. cwdata.cbdata = cdp;
  437. std::string filename = make_att_filename(ins_id, false);
  438. ec_log_debug("Load attachment instance: %s", filename.c_str());
  439. /*
  440. * Loop at most S3_RETRIES times, to make sure that if the servers of S3
  441. * reply with a redirect, we actually try again and process it.
  442. */
  443. cdp->retries = S3_RETRIES;
  444. do {
  445. DY_get_object(&m_bucket_ctx, filename.c_str(),
  446. &m_get_conditions, /*startByte*/ 0, /*byteCount*/ 0, 0,
  447. &m_get_obj_handler, &cwdata);
  448. if (DY_status_is_retryable(cdp->status))
  449. ec_log_debug("Load instance result in while: %s",
  450. DY_get_status_name(cdp->status));
  451. } while (DY_status_is_retryable(cdp->status) && should_retry(cdp));
  452. ec_log_debug("Result of the load instance: %s",
  453. DY_get_status_name(cdp->status));
  454. if (cdp->size != cdp->processed) {
  455. ec_log_err("Short read while reading attachment data, key: %s", filename.c_str());
  456. ret = KCERR_DATABASE_ERROR;
  457. goto exit;
  458. } else if (cdp->data == NULL) {
  459. ret = KCERR_NOT_ENOUGH_MEMORY;
  460. goto exit;
  461. } else if (cdp->status != S3StatusOK) {
  462. ret = KCERR_NETWORK_ERROR;
  463. goto exit;
  464. }
  465. /*
  466. * We allocated the data in cdp->data, which is referred to by
  467. * data_p. The caller of this function is responsible for freeing the
  468. * memory after its use.
  469. */
  470. *size_p = cdp->size;
  471. *data_p = cdp->data;
  472. ret = erSuccess;
  473. exit:
  474. if (ret != erSuccess && cdp->data != NULL && soap == NULL)
  475. delete cdp->data;
  476. /*
  477. * Make sure we clear the cdp->data variable so we cannot write
  478. * to it after it is freed externally.
  479. */
  480. cdp->data = NULL;
  481. return ret;
  482. }
  483. /**
  484. * Load instance data using a serializer.
  485. *
  486. * @param[in] ins_id InstanceID to load
  487. * @param[out] size_p size written in in sink
  488. * @param[in] sink serializer to write in
  489. *
  490. * @return erSuccess if we were able to load the instance, or the error code
  491. * if we could not.
  492. */
  493. ECRESULT ECS3Attachment::LoadAttachmentInstance(ULONG ins_id, size_t *size_p, ECSerializer *sink)
  494. {
  495. ECRESULT ret = KCERR_NOT_FOUND;
  496. struct s3_cd cdata = create_cd();
  497. struct s3_cd *cdp = &cdata;
  498. cdp->sink = sink;
  499. cdp->data = NULL;
  500. cdp->alloc_data = false;
  501. cdp->size = 0;
  502. cdp->processed = 0;
  503. struct s3_cdw cwdata;
  504. cwdata.caller = this;
  505. cwdata.cbdata = cdp;
  506. std::string filename = make_att_filename(ins_id, false);
  507. ec_log_debug("Load attachment instance: %s", filename.c_str());
  508. /*
  509. * Loop at most S3_RETRIES times, to make sure that if the servers of S3
  510. * reply with a redirect, we actually try again and process it.
  511. */
  512. cdp->retries = S3_RETRIES;
  513. do {
  514. DY_get_object(&m_bucket_ctx, filename.c_str(),
  515. &m_get_conditions, /*startByte*/ 0, /*byteCount*/ 0, 0,
  516. &m_get_obj_handler, &cwdata);
  517. if (DY_status_is_retryable(cdp->status))
  518. ec_log_debug("Load instance result in while: %s",
  519. DY_get_status_name(cdp->status));
  520. } while (DY_status_is_retryable(cdp->status) && should_retry(cdp));
  521. ec_log_debug("Result of the load instance: %s",
  522. DY_get_status_name(cdp->status));
  523. if (cdp->size != cdp->processed) {
  524. ec_log_err("Short read while reading attachment data from S3, key: %s", filename.c_str());
  525. ret = KCERR_DATABASE_ERROR;
  526. goto exit;
  527. } else if (cdp->status == S3StatusOK) {
  528. ret = erSuccess;
  529. goto exit;
  530. } else if (cdp->data == NULL) {
  531. ret = KCERR_NOT_ENOUGH_MEMORY;
  532. goto exit;
  533. }
  534. *size_p = cdp->size;
  535. exit:
  536. /*
  537. * Make sure we do not write to the sink accidentally, therefore reset
  538. * it to NULL.
  539. */
  540. cdp->sink = NULL;
  541. return ret;
  542. }
  543. /**
  544. * Save a property in a new instance from a blob
  545. *
  546. * @param[in] ins_id InstanceID to save data under
  547. * @param[in] propid unused, required by interface, see ECDatabaseAttachment
  548. * @param[in] size size of data
  549. * @param[in] data Data of property
  550. *
  551. * @return Kopano error code
  552. */
  553. ECRESULT ECS3Attachment::SaveAttachmentInstance(ULONG ins_id, ULONG propid,
  554. size_t size, unsigned char *data)
  555. {
  556. ECRESULT ret = KCERR_NOT_FOUND;
  557. bool comp = false;
  558. struct s3_cd cdata = create_cd();
  559. struct s3_cd *cdp = &cdata;
  560. cdp->sink = NULL;
  561. cdp->data = data;
  562. cdp->size = size;
  563. cdp->alloc_data = false;
  564. struct s3_cdw cwdata;
  565. cwdata.caller = this;
  566. cwdata.cbdata = cdp;
  567. std::string filename = make_att_filename(ins_id, comp && size != 0);
  568. ec_log_debug("Save attachment instance data: %s: %d of %ld", filename.c_str(), cdp->data != NULL, size);
  569. /*
  570. * Loop at most S3_RETRIES times, to make sure that if the servers of S3
  571. * reply with a redirect, we actually try again and process it.
  572. */
  573. cdp->retries = S3_RETRIES;
  574. do {
  575. DY_put_object(&m_bucket_ctx, filename.c_str(), size, NULL,
  576. NULL, &m_put_obj_handler, &cwdata);
  577. if (DY_status_is_retryable(cdp->status))
  578. ec_log_debug("Save attachment result in while: %s",
  579. DY_get_status_name(cdp->status));
  580. } while (DY_status_is_retryable(cdp->status) && should_retry(cdp));
  581. ec_log_debug("Result of the save attachment: %s",
  582. DY_get_status_name(cdp->status));
  583. /* set in transaction before disk full check to remove empty file */
  584. if (m_transact)
  585. m_new_att.insert(ins_id);
  586. if (cdp->size != cdp->processed) {
  587. ec_log_err("Unable to write attachment data to S3, key: %s", filename.c_str());
  588. ret = KCERR_DATABASE_ERROR;
  589. goto exit;
  590. } else if (cdp->status == S3StatusOK) {
  591. ret = erSuccess;
  592. goto exit;
  593. }
  594. exit:
  595. cdp->data = NULL;
  596. return ret;
  597. }
  598. /**
  599. * Save a property in a new instance from a serializer
  600. *
  601. * @param[in] ins_id InstanceID to save data under
  602. * @param[in] propid unused, required by interface, see ECDatabaseAttachment
  603. * @param[in] size size in source
  604. * @param[in] source serializer to read data from
  605. *
  606. * @return Kopano error code
  607. */
  608. ECRESULT ECS3Attachment::SaveAttachmentInstance(ULONG ins_id, ULONG propid,
  609. size_t size, ECSerializer *source)
  610. {
  611. ECRESULT ret = KCERR_NOT_FOUND;
  612. bool comp = false;
  613. struct s3_cd cdata = create_cd();
  614. struct s3_cd *cdp = &cdata;
  615. cdp->sink = source;
  616. cdp->data = NULL;
  617. cdp->alloc_data = false;
  618. cdp->size = size;
  619. struct s3_cdw cwdata;
  620. cwdata.caller = this;
  621. cwdata.cbdata = cdp;
  622. std::string filename = make_att_filename(ins_id, comp && size != 0);
  623. ec_log_debug("Save attachment instance source: %s: %d of %ld", filename.c_str(), cdp->sink != NULL, size);
  624. /*
  625. * Loop at most S3_RETRIES times, to make sure that if the servers of S3
  626. * reply with a redirect, we actually try again and process it.
  627. */
  628. cdp->retries = S3_RETRIES;
  629. do {
  630. DY_put_object(&m_bucket_ctx, filename.c_str(), size, NULL,
  631. NULL, &m_put_obj_handler, &cwdata);
  632. if (DY_status_is_retryable(cdp->status))
  633. ec_log_debug("Save attachment result in while: %s",
  634. DY_get_status_name(cdp->status));
  635. }
  636. while (DY_status_is_retryable(cdp->status) && should_retry(cdp));
  637. ec_log_debug("Result of the save attachment: %s",
  638. DY_get_status_name(cdp->status));
  639. /* set in transaction before disk full check to remove empty file */
  640. if (m_transact)
  641. m_new_att.insert(ins_id);
  642. if (cdp->size != cdp->processed) {
  643. ec_log_err("Unable to write attachment data to S3, key: %s", filename.c_str());
  644. ret = KCERR_DATABASE_ERROR;
  645. goto exit;
  646. } else if (cdp->status == S3StatusOK) {
  647. ret = erSuccess;
  648. goto exit;
  649. }
  650. exit:
  651. cdp->sink = NULL;
  652. return ret;
  653. }
  654. /**
  655. * Delete given instances from the filesystem
  656. *
  657. * @param[in] lstDeleteInstances List of instance ids to remove from the filesystem
  658. * @param[in] bReplace Transaction marker
  659. *
  660. * @return Kopano error code
  661. */
  662. ECRESULT ECS3Attachment::DeleteAttachmentInstances(const std::list<ULONG> &lstDeleteInstances, bool bReplace)
  663. {
  664. ECRESULT ret = erSuccess;
  665. int errors = 0;
  666. for (auto del_id : lstDeleteInstances) {
  667. ret = this->DeleteAttachmentInstance(del_id, bReplace);
  668. if (ret != erSuccess)
  669. ++errors;
  670. }
  671. return errors == 0 ? erSuccess : KCERR_DATABASE_ERROR;
  672. }
  673. /**
  674. * Mark a file deleted by renaming it
  675. *
  676. * @param[in] ins_id instance id to mark
  677. *
  678. * @return Kopano error code
  679. */
  680. ECRESULT ECS3Attachment::mark_att_for_del(ULONG ins_id)
  681. {
  682. ec_log_debug("Mark attachment for deletion");
  683. m_marked_att.insert(ins_id);
  684. return erSuccess;
  685. }
  686. /**
  687. * Revert a delete marked instance
  688. *
  689. * @param[in] ins_id instance id to restore
  690. *
  691. * @return Kopano error code
  692. */
  693. ECRESULT ECS3Attachment::restore_marked_att(ULONG ins_id)
  694. {
  695. ec_log_debug("Restored attachment, unmark for deletion");
  696. m_marked_att.erase(ins_id);
  697. return erSuccess;
  698. }
  699. /**
  700. * Delete a marked instance from the filesystem
  701. *
  702. * @param[in] ins_id instance id to remove
  703. *
  704. * @return Kopano error code
  705. */
  706. ECRESULT ECS3Attachment::del_marked_att(ULONG ins_id)
  707. {
  708. struct s3_cd cdata = create_cd();
  709. struct s3_cd *cdp = &cdata;
  710. struct s3_cdw cwdata;
  711. cwdata.caller = this;
  712. cwdata.cbdata = cdp;
  713. std::string filename = make_att_filename(ins_id, false);
  714. ec_log_debug("Delete marked attachment: %s", filename.c_str());
  715. /*
  716. * Loop at most S3_RETRIES times, to make sure that if the servers of
  717. * S3 reply with a redirect, we actually try again and process it.
  718. */
  719. cdp->retries = S3_RETRIES;
  720. do {
  721. DY_delete_object(&m_bucket_ctx, filename.c_str(), 0,
  722. &m_response_handler, &cwdata);
  723. if (DY_status_is_retryable(cdp->status))
  724. ec_log_debug("Delete marked attachment result in while: %s",
  725. DY_get_status_name(cdp->status));
  726. } while (DY_status_is_retryable(cdp->status) && should_retry(cdp));
  727. ec_log_debug("Result of the delete marked attachment: %s",
  728. DY_get_status_name(cdp->status));
  729. if (cdp->status == S3StatusOK)
  730. return erSuccess;
  731. return KCERR_NOT_FOUND;
  732. }
  733. /**
  734. * Delete a single instanceid from the filesystem
  735. *
  736. * @param[in] ins_id instance id to remove
  737. * @param[in] bReplace Transaction marker
  738. *
  739. * @return
  740. */
  741. ECRESULT ECS3Attachment::DeleteAttachmentInstance(ULONG ins_id,
  742. bool bReplace)
  743. {
  744. ECRESULT ret = erSuccess;
  745. std::string filename = make_att_filename(ins_id, m_bFileCompression);
  746. if (!m_transact)
  747. return del_marked_att(ins_id);
  748. ret = mark_att_for_del(ins_id);
  749. if (ret != erSuccess && ret != KCERR_NOT_FOUND) {
  750. assert(false);
  751. return ret;
  752. }
  753. return erSuccess;
  754. }
  755. /**
  756. * Return a filename for an instance id
  757. *
  758. * @param[in] ins_id instance id to convert to a filename
  759. * @param[in] bCompressed add compression marker to filename
  760. *
  761. * @return Kopano error code
  762. */
  763. std::string ECS3Attachment::make_att_filename(ULONG ins_id, bool comp)
  764. {
  765. std::string filename = m_basepath + PATH_SEPARATOR + stringify(ins_id);
  766. if (comp)
  767. filename += ".gz";
  768. return filename;
  769. }
  770. /**
  771. * This function will check whether we should give it one more try or not.
  772. *
  773. * @return whether we should retry
  774. */
  775. bool ECS3Attachment::should_retry(struct s3_cd *cdp)
  776. {
  777. if (cdp->retries <= 0)
  778. return false;
  779. --cdp->retries;
  780. sleep(S3_SLEEP_DELAY);
  781. return true;
  782. }
  783. /**
  784. * This function creates a nrew S3Attachment Callback Data struct instance,
  785. * this will make sure that all the variables are initialized to default
  786. * values.
  787. *
  788. * @return a new s3_cd struct instance
  789. */
  790. struct s3_cd ECS3Attachment::create_cd(void)
  791. {
  792. struct s3_cd c;
  793. c.soap = NULL;
  794. c.data = NULL;
  795. c.sink = NULL;
  796. c.alloc_data = false;
  797. c.size = 0;
  798. c.processed = 0;
  799. c.status = S3StatusOK;
  800. return c;
  801. }
  802. /**
  803. * Return the size of an instance
  804. *
  805. * @param[in] ins_id InstanceID to check the size for
  806. * @param[out] size_p Size of the instance
  807. * @param[out] compr_p the instance was compressed
  808. *
  809. * @return Kopano error code
  810. */
  811. ECRESULT ECS3Attachment::GetSizeInstance(ULONG ins_id, size_t *size_p,
  812. bool *compr_p)
  813. {
  814. ECRESULT ret = KCERR_NOT_FOUND;
  815. bool comp = false;
  816. struct s3_cd cdata = create_cd();
  817. struct s3_cd *cdp = &cdata;
  818. struct s3_cdw cwdata;
  819. cwdata.caller = this;
  820. cwdata.cbdata = cdp;
  821. std::string filename = make_att_filename(ins_id, comp);
  822. ec_log_debug("Get size attachment instance: %s", filename.c_str());
  823. /*
  824. * Loop at most S3_RETRIES times, to make sure that if the servers of
  825. * S3 reply with a redirect, we actually try again and process it.
  826. */
  827. cdp->retries = S3_RETRIES;
  828. do {
  829. DY_head_object(&m_bucket_ctx, filename.c_str(), 0,
  830. &m_response_handler, &cwdata);
  831. if (DY_status_is_retryable(cdp->status))
  832. ec_log_debug("Get size attachment result in while: %s",
  833. DY_get_status_name(cdp->status));
  834. } while (DY_status_is_retryable(cdp->status) && should_retry(cdp));
  835. ec_log_debug("Get size of attachment: %s -> %d",
  836. DY_get_status_name(cdp->status), cdp->size);
  837. if (cdp->status == S3StatusOK) {
  838. *size_p = cdp->size;
  839. if (compr_p != NULL)
  840. *compr_p = comp;
  841. ret = erSuccess;
  842. }
  843. return ret;
  844. }
  845. ECRESULT ECS3Attachment::Begin(void)
  846. {
  847. ec_log_debug("Begin transaction");
  848. if (m_transact) {
  849. /* Possible a duplicate begin call, don't destroy the data in production */
  850. assert(false);
  851. return erSuccess;
  852. }
  853. m_new_att.clear();
  854. m_deleted_att.clear();
  855. m_marked_att.clear();
  856. m_transact = true;
  857. return erSuccess;
  858. }
  859. ECRESULT ECS3Attachment::Commit(void)
  860. {
  861. bool error = false;
  862. ec_log_debug("Commit transaction");
  863. if (!m_transact) {
  864. assert(false);
  865. return erSuccess;
  866. }
  867. /* Disable the transaction */
  868. m_transact = false;
  869. /* Delete the attachments */
  870. for (auto att_id : m_deleted_att)
  871. if (DeleteAttachmentInstance(att_id, false) != erSuccess)
  872. error = true;
  873. /* Delete marked attachments */
  874. for (auto att_id : m_marked_att)
  875. if (del_marked_att(att_id) != erSuccess)
  876. error = true;
  877. m_new_att.clear();
  878. m_deleted_att.clear();
  879. m_marked_att.clear();
  880. return error ? KCERR_DATABASE_ERROR : erSuccess;
  881. }
  882. ECRESULT ECS3Attachment::Rollback(void)
  883. {
  884. bool error = false;
  885. ec_log_debug("Rollback transaction");
  886. if (!m_transact) {
  887. assert(false);
  888. return erSuccess;
  889. }
  890. /* Disable the transaction */
  891. m_transact = false;
  892. /* Do not delete the attachments */
  893. m_deleted_att.clear();
  894. /* Remove the created attachments */
  895. for (auto att_id : m_new_att)
  896. if (DeleteAttachmentInstance(att_id, false) != erSuccess)
  897. error = true;
  898. /* Restore marked attachment */
  899. for (auto att_id : m_marked_att)
  900. if (restore_marked_att(att_id) != erSuccess)
  901. error = true;
  902. m_new_att.clear();
  903. m_marked_att.clear();
  904. return error ? KCERR_DATABASE_ERROR : erSuccess;
  905. }
  906. } /* namespace */
  907. #endif /* LIBS3_H */