]> git.proxmox.com Git - ceph.git/blame - ceph/src/rgw/rgw_data_sync.cc
update sources to v12.2.1
[ceph.git] / ceph / src / rgw / rgw_data_sync.cc
CommitLineData
7c673cae
FG
1#include <boost/utility/string_ref.hpp>
2
3#include "common/ceph_json.h"
4#include "common/RWLock.h"
5#include "common/RefCountedObj.h"
6#include "common/WorkQueue.h"
7#include "common/Throttle.h"
8#include "common/errno.h"
9
10#include "rgw_common.h"
11#include "rgw_rados.h"
12#include "rgw_sync.h"
13#include "rgw_data_sync.h"
14#include "rgw_rest_conn.h"
15#include "rgw_cr_rados.h"
16#include "rgw_cr_rest.h"
17#include "rgw_http_client.h"
18#include "rgw_bucket.h"
19#include "rgw_metadata.h"
7c673cae
FG
20#include "rgw_sync_module.h"
21
22#include "cls/lock/cls_lock_client.h"
23
31f18b77
FG
24#include "auth/Crypto.h"
25
26#include <boost/asio/yield.hpp>
27
7c673cae
FG
28#define dout_subsys ceph_subsys_rgw
29
30#undef dout_prefix
31#define dout_prefix (*_dout << "data sync: ")
32
33static string datalog_sync_status_oid_prefix = "datalog.sync-status";
34static string datalog_sync_status_shard_prefix = "datalog.sync-status.shard";
35static string datalog_sync_full_sync_index_prefix = "data.full-sync.index";
36static string bucket_status_oid_prefix = "bucket.sync-status";
37
38class RGWSyncDebugLogger {
39 CephContext *cct;
40 string prefix;
41
42 bool ended;
43
44public:
45 RGWSyncDebugLogger(CephContext *_cct, const string& source_zone,
46 const string& sync_type, const string& sync_stage,
47 const string& resource, bool log_start = true) {
48 init(_cct, source_zone, sync_type, sync_stage, resource, log_start);
49 }
50 RGWSyncDebugLogger() : cct(NULL), ended(false) {}
51 ~RGWSyncDebugLogger();
52
53 void init(CephContext *_cct, const string& source_zone,
54 const string& sync_type, const string& sync_stage,
55 const string& resource, bool log_start = true);
56 void log(const string& state);
57 void finish(int status);
58};
59
60void RGWSyncDebugLogger::init(CephContext *_cct, const string& source_zone,
61 const string& sync_type, const string& sync_section,
62 const string& resource, bool log_start)
63{
64 cct = _cct;
65 ended = false;
66 string zone_str = source_zone.substr(0, 8);
67 prefix = "Sync:" + zone_str + ":" + sync_type + ":" + sync_section + ":" + resource;
68 if (log_start) {
69 log("start");
70 }
71}
72
73RGWSyncDebugLogger::~RGWSyncDebugLogger()
74{
75 if (!ended) {
76 log("finish");
77 }
78}
79
80void RGWSyncDebugLogger::log(const string& state)
81{
82 ldout(cct, 5) << prefix << ":" << state << dendl;
83}
84
85void RGWSyncDebugLogger::finish(int status)
86{
87 ended = true;
88 ldout(cct, 5) << prefix << ":" << "finish r=" << status << dendl;
89}
90
91class RGWDataSyncDebugLogger : public RGWSyncDebugLogger {
92public:
93 RGWDataSyncDebugLogger() {}
94 RGWDataSyncDebugLogger(RGWDataSyncEnv *sync_env, const string& sync_section,
95 const string& resource, bool log_start = true) {
96 init(sync_env, sync_section, resource, log_start);
97 }
98 void init(RGWDataSyncEnv *sync_env, const string& sync_section,
99 const string& resource, bool log_start = true) {
100 RGWSyncDebugLogger::init(sync_env->cct, sync_env->source_zone, "data", sync_section, resource, log_start);
101 }
102
103};
104
105void rgw_datalog_info::decode_json(JSONObj *obj) {
106 JSONDecoder::decode_json("num_objects", num_shards, obj);
107}
108
109void rgw_datalog_entry::decode_json(JSONObj *obj) {
110 JSONDecoder::decode_json("key", key, obj);
111 utime_t ut;
112 JSONDecoder::decode_json("timestamp", ut, obj);
113 timestamp = ut.to_real_time();
114}
115
116void rgw_datalog_shard_data::decode_json(JSONObj *obj) {
117 JSONDecoder::decode_json("marker", marker, obj);
118 JSONDecoder::decode_json("truncated", truncated, obj);
119 JSONDecoder::decode_json("entries", entries, obj);
120};
121
122class RGWReadDataSyncStatusMarkersCR : public RGWShardCollectCR {
123 static constexpr int MAX_CONCURRENT_SHARDS = 16;
124
125 RGWDataSyncEnv *env;
126 const int num_shards;
127 int shard_id{0};;
128
129 map<uint32_t, rgw_data_sync_marker>& markers;
130
131 public:
132 RGWReadDataSyncStatusMarkersCR(RGWDataSyncEnv *env, int num_shards,
133 map<uint32_t, rgw_data_sync_marker>& markers)
134 : RGWShardCollectCR(env->cct, MAX_CONCURRENT_SHARDS),
135 env(env), num_shards(num_shards), markers(markers)
136 {}
137 bool spawn_next() override;
138};
139
140bool RGWReadDataSyncStatusMarkersCR::spawn_next()
141{
142 if (shard_id >= num_shards) {
143 return false;
144 }
145 using CR = RGWSimpleRadosReadCR<rgw_data_sync_marker>;
146 spawn(new CR(env->async_rados, env->store,
147 rgw_raw_obj(env->store->get_zone_params().log_pool, RGWDataSyncStatusManager::shard_obj_name(env->source_zone, shard_id)),
148 &markers[shard_id]),
149 false);
150 shard_id++;
151 return true;
152}
153
154class RGWReadDataSyncStatusCoroutine : public RGWCoroutine {
155 RGWDataSyncEnv *sync_env;
156 rgw_data_sync_status *sync_status;
157
158public:
159 RGWReadDataSyncStatusCoroutine(RGWDataSyncEnv *_sync_env,
160 rgw_data_sync_status *_status)
161 : RGWCoroutine(_sync_env->cct), sync_env(_sync_env), sync_status(_status)
162 {}
163 int operate() override;
164};
165
166int RGWReadDataSyncStatusCoroutine::operate()
167{
168 reenter(this) {
169 // read sync info
170 using ReadInfoCR = RGWSimpleRadosReadCR<rgw_data_sync_info>;
171 yield {
172 bool empty_on_enoent = false; // fail on ENOENT
173 call(new ReadInfoCR(sync_env->async_rados, sync_env->store,
174 rgw_raw_obj(sync_env->store->get_zone_params().log_pool, RGWDataSyncStatusManager::sync_status_oid(sync_env->source_zone)),
175 &sync_status->sync_info, empty_on_enoent));
176 }
177 if (retcode < 0) {
178 ldout(sync_env->cct, 4) << "failed to read sync status info with "
179 << cpp_strerror(retcode) << dendl;
180 return set_cr_error(retcode);
181 }
182 // read shard markers
183 using ReadMarkersCR = RGWReadDataSyncStatusMarkersCR;
184 yield call(new ReadMarkersCR(sync_env, sync_status->sync_info.num_shards,
185 sync_status->sync_markers));
186 if (retcode < 0) {
187 ldout(sync_env->cct, 4) << "failed to read sync status markers with "
188 << cpp_strerror(retcode) << dendl;
189 return set_cr_error(retcode);
190 }
191 return set_cr_done();
192 }
193 return 0;
194}
195
196class RGWReadRemoteDataLogShardInfoCR : public RGWCoroutine {
197 RGWDataSyncEnv *sync_env;
198
199 RGWRESTReadResource *http_op;
200
201 int shard_id;
202 RGWDataChangesLogInfo *shard_info;
203
204public:
205 RGWReadRemoteDataLogShardInfoCR(RGWDataSyncEnv *_sync_env,
206 int _shard_id, RGWDataChangesLogInfo *_shard_info) : RGWCoroutine(_sync_env->cct),
207 sync_env(_sync_env),
208 http_op(NULL),
209 shard_id(_shard_id),
210 shard_info(_shard_info) {
211 }
212
213 ~RGWReadRemoteDataLogShardInfoCR() override {
214 if (http_op) {
215 http_op->put();
216 }
217 }
218
219 int operate() override {
220 reenter(this) {
221 yield {
222 char buf[16];
223 snprintf(buf, sizeof(buf), "%d", shard_id);
224 rgw_http_param_pair pairs[] = { { "type" , "data" },
225 { "id", buf },
226 { "info" , NULL },
227 { NULL, NULL } };
228
229 string p = "/admin/log/";
230
231 http_op = new RGWRESTReadResource(sync_env->conn, p, pairs, NULL, sync_env->http_manager);
232
233 http_op->set_user_info((void *)stack);
234
235 int ret = http_op->aio_read();
236 if (ret < 0) {
237 ldout(sync_env->cct, 0) << "ERROR: failed to read from " << p << dendl;
238 log_error() << "failed to send http operation: " << http_op->to_str() << " ret=" << ret << std::endl;
239 return set_cr_error(ret);
240 }
241
242 return io_block(0);
243 }
244 yield {
245 int ret = http_op->wait(shard_info);
246 if (ret < 0) {
247 return set_cr_error(ret);
248 }
249 return set_cr_done();
250 }
251 }
252 return 0;
253 }
254};
255
256struct read_remote_data_log_response {
257 string marker;
258 bool truncated;
259 list<rgw_data_change_log_entry> entries;
260
261 read_remote_data_log_response() : truncated(false) {}
262
263 void decode_json(JSONObj *obj) {
264 JSONDecoder::decode_json("marker", marker, obj);
265 JSONDecoder::decode_json("truncated", truncated, obj);
266 JSONDecoder::decode_json("entries", entries, obj);
267 };
268};
269
270class RGWReadRemoteDataLogShardCR : public RGWCoroutine {
271 RGWDataSyncEnv *sync_env;
272
273 RGWRESTReadResource *http_op;
274
275 int shard_id;
276 string *pmarker;
277 list<rgw_data_change_log_entry> *entries;
278 bool *truncated;
279
280 read_remote_data_log_response response;
281
282public:
283 RGWReadRemoteDataLogShardCR(RGWDataSyncEnv *_sync_env,
284 int _shard_id, string *_pmarker, list<rgw_data_change_log_entry> *_entries, bool *_truncated) : RGWCoroutine(_sync_env->cct),
285 sync_env(_sync_env),
286 http_op(NULL),
287 shard_id(_shard_id),
288 pmarker(_pmarker),
289 entries(_entries),
290 truncated(_truncated) {
291 }
292 ~RGWReadRemoteDataLogShardCR() override {
293 if (http_op) {
294 http_op->put();
295 }
296 }
297
298 int operate() override {
299 reenter(this) {
300 yield {
301 char buf[16];
302 snprintf(buf, sizeof(buf), "%d", shard_id);
303 rgw_http_param_pair pairs[] = { { "type" , "data" },
304 { "id", buf },
305 { "marker", pmarker->c_str() },
306 { "extra-info", "true" },
307 { NULL, NULL } };
308
309 string p = "/admin/log/";
310
311 http_op = new RGWRESTReadResource(sync_env->conn, p, pairs, NULL, sync_env->http_manager);
312
313 http_op->set_user_info((void *)stack);
314
315 int ret = http_op->aio_read();
316 if (ret < 0) {
317 ldout(sync_env->cct, 0) << "ERROR: failed to read from " << p << dendl;
318 log_error() << "failed to send http operation: " << http_op->to_str() << " ret=" << ret << std::endl;
319 return set_cr_error(ret);
320 }
321
322 return io_block(0);
323 }
324 yield {
325 int ret = http_op->wait(&response);
326 if (ret < 0) {
327 return set_cr_error(ret);
328 }
329 entries->clear();
330 entries->swap(response.entries);
331 *pmarker = response.marker;
332 *truncated = response.truncated;
333 return set_cr_done();
334 }
335 }
336 return 0;
337 }
338};
339
340class RGWReadRemoteDataLogInfoCR : public RGWShardCollectCR {
341 RGWDataSyncEnv *sync_env;
342
343 int num_shards;
344 map<int, RGWDataChangesLogInfo> *datalog_info;
345
346 int shard_id;
347#define READ_DATALOG_MAX_CONCURRENT 10
348
349public:
350 RGWReadRemoteDataLogInfoCR(RGWDataSyncEnv *_sync_env,
351 int _num_shards,
352 map<int, RGWDataChangesLogInfo> *_datalog_info) : RGWShardCollectCR(_sync_env->cct, READ_DATALOG_MAX_CONCURRENT),
353 sync_env(_sync_env), num_shards(_num_shards),
354 datalog_info(_datalog_info), shard_id(0) {}
355 bool spawn_next() override;
356};
357
358bool RGWReadRemoteDataLogInfoCR::spawn_next() {
359 if (shard_id >= num_shards) {
360 return false;
361 }
362 spawn(new RGWReadRemoteDataLogShardInfoCR(sync_env, shard_id, &(*datalog_info)[shard_id]), false);
363 shard_id++;
364 return true;
365}
366
367class RGWListRemoteDataLogShardCR : public RGWSimpleCoroutine {
368 RGWDataSyncEnv *sync_env;
369 RGWRESTReadResource *http_op;
370
371 int shard_id;
372 string marker;
373 uint32_t max_entries;
374 rgw_datalog_shard_data *result;
375
376public:
377 RGWListRemoteDataLogShardCR(RGWDataSyncEnv *env, int _shard_id,
378 const string& _marker, uint32_t _max_entries,
379 rgw_datalog_shard_data *_result)
380 : RGWSimpleCoroutine(env->store->ctx()), sync_env(env), http_op(NULL),
381 shard_id(_shard_id), marker(_marker), max_entries(_max_entries), result(_result) {}
382
383 int send_request() override {
384 RGWRESTConn *conn = sync_env->conn;
385 RGWRados *store = sync_env->store;
386
387 char buf[32];
388 snprintf(buf, sizeof(buf), "%d", shard_id);
389
390 char max_entries_buf[32];
391 snprintf(max_entries_buf, sizeof(max_entries_buf), "%d", (int)max_entries);
392
393 const char *marker_key = (marker.empty() ? "" : "marker");
394
395 rgw_http_param_pair pairs[] = { { "type", "data" },
396 { "id", buf },
397 { "max-entries", max_entries_buf },
398 { marker_key, marker.c_str() },
399 { NULL, NULL } };
400
401 string p = "/admin/log/";
402
403 http_op = new RGWRESTReadResource(conn, p, pairs, NULL, sync_env->http_manager);
404 http_op->set_user_info((void *)stack);
405
406 int ret = http_op->aio_read();
407 if (ret < 0) {
408 ldout(store->ctx(), 0) << "ERROR: failed to read from " << p << dendl;
409 log_error() << "failed to send http operation: " << http_op->to_str() << " ret=" << ret << std::endl;
410 http_op->put();
411 return ret;
412 }
413
414 return 0;
415 }
416
417 int request_complete() override {
418 int ret = http_op->wait(result);
419 http_op->put();
420 if (ret < 0 && ret != -ENOENT) {
421 ldout(sync_env->store->ctx(), 0) << "ERROR: failed to list remote datalog shard, ret=" << ret << dendl;
422 return ret;
423 }
424 return 0;
425 }
426};
427
428class RGWListRemoteDataLogCR : public RGWShardCollectCR {
429 RGWDataSyncEnv *sync_env;
430
431 map<int, string> shards;
432 int max_entries_per_shard;
433 map<int, rgw_datalog_shard_data> *result;
434
435 map<int, string>::iterator iter;
436#define READ_DATALOG_MAX_CONCURRENT 10
437
438public:
439 RGWListRemoteDataLogCR(RGWDataSyncEnv *_sync_env,
440 map<int, string>& _shards,
441 int _max_entries_per_shard,
442 map<int, rgw_datalog_shard_data> *_result) : RGWShardCollectCR(_sync_env->cct, READ_DATALOG_MAX_CONCURRENT),
443 sync_env(_sync_env), max_entries_per_shard(_max_entries_per_shard),
444 result(_result) {
445 shards.swap(_shards);
446 iter = shards.begin();
447 }
448 bool spawn_next() override;
449};
450
451bool RGWListRemoteDataLogCR::spawn_next() {
452 if (iter == shards.end()) {
453 return false;
454 }
455
456 spawn(new RGWListRemoteDataLogShardCR(sync_env, iter->first, iter->second, max_entries_per_shard, &(*result)[iter->first]), false);
457 ++iter;
458 return true;
459}
460
461class RGWInitDataSyncStatusCoroutine : public RGWCoroutine {
462 static constexpr uint32_t lock_duration = 30;
463 RGWDataSyncEnv *sync_env;
464 RGWRados *store;
465 const rgw_pool& pool;
466 const uint32_t num_shards;
467
468 string sync_status_oid;
469
470 string lock_name;
471 string cookie;
472 rgw_data_sync_status *status;
473 map<int, RGWDataChangesLogInfo> shards_info;
474public:
475 RGWInitDataSyncStatusCoroutine(RGWDataSyncEnv *_sync_env, uint32_t num_shards,
31f18b77 476 uint64_t instance_id,
7c673cae
FG
477 rgw_data_sync_status *status)
478 : RGWCoroutine(_sync_env->cct), sync_env(_sync_env), store(sync_env->store),
479 pool(store->get_zone_params().log_pool),
480 num_shards(num_shards), status(status) {
481 lock_name = "sync_lock";
482
31f18b77
FG
483 status->sync_info.instance_id = instance_id;
484
7c673cae
FG
485#define COOKIE_LEN 16
486 char buf[COOKIE_LEN + 1];
487
488 gen_rand_alphanumeric(cct, buf, sizeof(buf) - 1);
489 cookie = buf;
490
491 sync_status_oid = RGWDataSyncStatusManager::sync_status_oid(sync_env->source_zone);
492 }
493
494 int operate() override {
495 int ret;
496 reenter(this) {
497 using LockCR = RGWSimpleRadosLockCR;
498 yield call(new LockCR(sync_env->async_rados, store,
499 rgw_raw_obj{pool, sync_status_oid},
500 lock_name, cookie, lock_duration));
501 if (retcode < 0) {
502 ldout(cct, 0) << "ERROR: failed to take a lock on " << sync_status_oid << dendl;
503 return set_cr_error(retcode);
504 }
505 using WriteInfoCR = RGWSimpleRadosWriteCR<rgw_data_sync_info>;
506 yield call(new WriteInfoCR(sync_env->async_rados, store,
507 rgw_raw_obj{pool, sync_status_oid},
508 status->sync_info));
509 if (retcode < 0) {
510 ldout(cct, 0) << "ERROR: failed to write sync status info with " << retcode << dendl;
511 return set_cr_error(retcode);
512 }
513
514 /* take lock again, we just recreated the object */
515 yield call(new LockCR(sync_env->async_rados, store,
516 rgw_raw_obj{pool, sync_status_oid},
517 lock_name, cookie, lock_duration));
518 if (retcode < 0) {
519 ldout(cct, 0) << "ERROR: failed to take a lock on " << sync_status_oid << dendl;
520 return set_cr_error(retcode);
521 }
522
523 /* fetch current position in logs */
524 yield {
525 RGWRESTConn *conn = store->get_zone_conn_by_id(sync_env->source_zone);
526 if (!conn) {
527 ldout(cct, 0) << "ERROR: connection to zone " << sync_env->source_zone << " does not exist!" << dendl;
528 return set_cr_error(-EIO);
529 }
530 for (uint32_t i = 0; i < num_shards; i++) {
531 spawn(new RGWReadRemoteDataLogShardInfoCR(sync_env, i, &shards_info[i]), true);
532 }
533 }
534 while (collect(&ret, NULL)) {
535 if (ret < 0) {
536 ldout(cct, 0) << "ERROR: failed to read remote data log shards" << dendl;
537 return set_state(RGWCoroutine_Error);
538 }
539 yield;
540 }
541 yield {
542 for (uint32_t i = 0; i < num_shards; i++) {
543 RGWDataChangesLogInfo& info = shards_info[i];
544 auto& marker = status->sync_markers[i];
545 marker.next_step_marker = info.marker;
546 marker.timestamp = info.last_update;
547 const auto& oid = RGWDataSyncStatusManager::shard_obj_name(sync_env->source_zone, i);
548 using WriteMarkerCR = RGWSimpleRadosWriteCR<rgw_data_sync_marker>;
549 spawn(new WriteMarkerCR(sync_env->async_rados, store,
550 rgw_raw_obj{pool, oid}, marker), true);
551 }
552 }
553 while (collect(&ret, NULL)) {
554 if (ret < 0) {
555 ldout(cct, 0) << "ERROR: failed to write data sync status markers" << dendl;
556 return set_state(RGWCoroutine_Error);
557 }
558 yield;
559 }
560
561 status->sync_info.state = rgw_data_sync_info::StateBuildingFullSyncMaps;
562 yield call(new WriteInfoCR(sync_env->async_rados, store,
563 rgw_raw_obj{pool, sync_status_oid},
564 status->sync_info));
565 if (retcode < 0) {
566 ldout(cct, 0) << "ERROR: failed to write sync status info with " << retcode << dendl;
567 return set_cr_error(retcode);
568 }
569 yield call(new RGWSimpleRadosUnlockCR(sync_env->async_rados, store,
570 rgw_raw_obj{pool, sync_status_oid},
571 lock_name, cookie));
572 return set_cr_done();
573 }
574 return 0;
575 }
576};
577
578int RGWRemoteDataLog::read_log_info(rgw_datalog_info *log_info)
579{
580 rgw_http_param_pair pairs[] = { { "type", "data" },
581 { NULL, NULL } };
582
583 int ret = sync_env.conn->get_json_resource("/admin/log", pairs, *log_info);
584 if (ret < 0) {
585 ldout(store->ctx(), 0) << "ERROR: failed to fetch datalog info" << dendl;
586 return ret;
587 }
588
589 ldout(store->ctx(), 20) << "remote datalog, num_shards=" << log_info->num_shards << dendl;
590
591 return 0;
592}
593
594int RGWRemoteDataLog::read_source_log_shards_info(map<int, RGWDataChangesLogInfo> *shards_info)
595{
596 rgw_datalog_info log_info;
597 int ret = read_log_info(&log_info);
598 if (ret < 0) {
599 return ret;
600 }
601
602 return run(new RGWReadRemoteDataLogInfoCR(&sync_env, log_info.num_shards, shards_info));
603}
604
605int RGWRemoteDataLog::read_source_log_shards_next(map<int, string> shard_markers, map<int, rgw_datalog_shard_data> *result)
606{
607 if (store->is_meta_master()) {
608 return 0;
609 }
610
611 return run(new RGWListRemoteDataLogCR(&sync_env, shard_markers, 1, result));
612}
613
614int RGWRemoteDataLog::init(const string& _source_zone, RGWRESTConn *_conn, RGWSyncErrorLogger *_error_logger, RGWSyncModuleInstanceRef& _sync_module)
615{
616 sync_env.init(store->ctx(), store, _conn, async_rados, &http_manager, _error_logger, _source_zone, _sync_module);
617
618 if (initialized) {
619 return 0;
620 }
621
622 int ret = http_manager.set_threaded();
623 if (ret < 0) {
624 ldout(store->ctx(), 0) << "failed in http_manager.set_threaded() ret=" << ret << dendl;
625 return ret;
626 }
627
628 initialized = true;
629
630 return 0;
631}
632
633void RGWRemoteDataLog::finish()
634{
635 stop();
636}
637
7c673cae
FG
638int RGWRemoteDataLog::read_sync_status(rgw_data_sync_status *sync_status)
639{
640 // cannot run concurrently with run_sync(), so run in a separate manager
641 RGWCoroutinesManager crs(store->ctx(), store->get_cr_registry());
642 RGWHTTPManager http_manager(store->ctx(), crs.get_completion_mgr());
643 int ret = http_manager.set_threaded();
644 if (ret < 0) {
645 ldout(store->ctx(), 0) << "failed in http_manager.set_threaded() ret=" << ret << dendl;
646 return ret;
647 }
648 RGWDataSyncEnv sync_env_local = sync_env;
649 sync_env_local.http_manager = &http_manager;
650 ret = crs.run(new RGWReadDataSyncStatusCoroutine(&sync_env_local, sync_status));
651 http_manager.stop();
652 return ret;
653}
654
655int RGWRemoteDataLog::init_sync_status(int num_shards)
656{
657 rgw_data_sync_status sync_status;
658 RGWCoroutinesManager crs(store->ctx(), store->get_cr_registry());
659 RGWHTTPManager http_manager(store->ctx(), crs.get_completion_mgr());
660 int ret = http_manager.set_threaded();
661 if (ret < 0) {
662 ldout(store->ctx(), 0) << "failed in http_manager.set_threaded() ret=" << ret << dendl;
663 return ret;
664 }
665 RGWDataSyncEnv sync_env_local = sync_env;
666 sync_env_local.http_manager = &http_manager;
31f18b77
FG
667 uint64_t instance_id;
668 get_random_bytes((char *)&instance_id, sizeof(instance_id));
669 ret = crs.run(new RGWInitDataSyncStatusCoroutine(&sync_env_local, num_shards, instance_id, &sync_status));
7c673cae
FG
670 http_manager.stop();
671 return ret;
672}
673
674static string full_data_sync_index_shard_oid(const string& source_zone, int shard_id)
675{
676 char buf[datalog_sync_full_sync_index_prefix.size() + 1 + source_zone.size() + 1 + 16];
677 snprintf(buf, sizeof(buf), "%s.%s.%d", datalog_sync_full_sync_index_prefix.c_str(), source_zone.c_str(), shard_id);
678 return string(buf);
679}
680
681struct bucket_instance_meta_info {
682 string key;
683 obj_version ver;
684 utime_t mtime;
685 RGWBucketInstanceMetadataObject data;
686
687 bucket_instance_meta_info() {}
688
689 void decode_json(JSONObj *obj) {
690 JSONDecoder::decode_json("key", key, obj);
691 JSONDecoder::decode_json("ver", ver, obj);
692 JSONDecoder::decode_json("mtime", mtime, obj);
693 JSONDecoder::decode_json("data", data, obj);
694 }
695};
696
697class RGWListBucketIndexesCR : public RGWCoroutine {
698 RGWDataSyncEnv *sync_env;
699
700 RGWRados *store;
701
702 rgw_data_sync_status *sync_status;
703 int num_shards;
704
705 int req_ret;
706 int ret;
707
708 list<string> result;
709 list<string>::iterator iter;
710
711 RGWShardedOmapCRManager *entries_index;
712
713 string oid_prefix;
714
715 string path;
716 bucket_instance_meta_info meta_info;
717 string key;
718 string s;
719 int i;
720
721 bool failed;
722
723public:
724 RGWListBucketIndexesCR(RGWDataSyncEnv *_sync_env,
725 rgw_data_sync_status *_sync_status) : RGWCoroutine(_sync_env->cct), sync_env(_sync_env),
726 store(sync_env->store), sync_status(_sync_status),
727 req_ret(0), ret(0), entries_index(NULL), i(0), failed(false) {
728 oid_prefix = datalog_sync_full_sync_index_prefix + "." + sync_env->source_zone;
729 path = "/admin/metadata/bucket.instance";
730 num_shards = sync_status->sync_info.num_shards;
731 }
732 ~RGWListBucketIndexesCR() override {
733 delete entries_index;
734 }
735
736 int operate() override {
737 reenter(this) {
738 entries_index = new RGWShardedOmapCRManager(sync_env->async_rados, store, this, num_shards,
739 store->get_zone_params().log_pool,
740 oid_prefix);
741 yield {
742 string entrypoint = string("/admin/metadata/bucket.instance");
743 /* FIXME: need a better scaling solution here, requires streaming output */
744 call(new RGWReadRESTResourceCR<list<string> >(store->ctx(), sync_env->conn, sync_env->http_manager,
745 entrypoint, NULL, &result));
746 }
747 if (get_ret_status() < 0) {
748 ldout(sync_env->cct, 0) << "ERROR: failed to fetch metadata for section bucket.index" << dendl;
749 return set_state(RGWCoroutine_Error);
750 }
751 for (iter = result.begin(); iter != result.end(); ++iter) {
752 ldout(sync_env->cct, 20) << "list metadata: section=bucket.index key=" << *iter << dendl;
753
754 key = *iter;
755
756 yield {
757 rgw_http_param_pair pairs[] = { { "key", key.c_str() },
758 { NULL, NULL } };
759
760 call(new RGWReadRESTResourceCR<bucket_instance_meta_info>(store->ctx(), sync_env->conn, sync_env->http_manager, path, pairs, &meta_info));
761 }
762
763 num_shards = meta_info.data.get_bucket_info().num_shards;
764 if (num_shards > 0) {
765 for (i = 0; i < num_shards; i++) {
766 char buf[16];
767 snprintf(buf, sizeof(buf), ":%d", i);
768 s = key + buf;
769 yield entries_index->append(s, store->data_log->get_log_shard_id(meta_info.data.get_bucket_info().bucket, i));
770 }
771 } else {
772 yield entries_index->append(key, store->data_log->get_log_shard_id(meta_info.data.get_bucket_info().bucket, -1));
773 }
774 }
775 yield {
776 if (!entries_index->finish()) {
777 failed = true;
778 }
779 }
780 if (!failed) {
781 for (map<uint32_t, rgw_data_sync_marker>::iterator iter = sync_status->sync_markers.begin(); iter != sync_status->sync_markers.end(); ++iter) {
782 int shard_id = (int)iter->first;
783 rgw_data_sync_marker& marker = iter->second;
784 marker.total_entries = entries_index->get_total_entries(shard_id);
785 spawn(new RGWSimpleRadosWriteCR<rgw_data_sync_marker>(sync_env->async_rados, store,
786 rgw_raw_obj(store->get_zone_params().log_pool, RGWDataSyncStatusManager::shard_obj_name(sync_env->source_zone, shard_id)),
787 marker), true);
788 }
789 } else {
790 yield call(sync_env->error_logger->log_error_cr(sync_env->conn->get_remote_id(), "data.init", "",
791 EIO, string("failed to build bucket instances map")));
792 }
793 while (collect(&ret, NULL)) {
794 if (ret < 0) {
795 yield call(sync_env->error_logger->log_error_cr(sync_env->conn->get_remote_id(), "data.init", "",
796 -ret, string("failed to store sync status: ") + cpp_strerror(-ret)));
797 req_ret = ret;
798 }
799 yield;
800 }
801 drain_all();
802 if (req_ret < 0) {
803 yield return set_cr_error(req_ret);
804 }
805 yield return set_cr_done();
806 }
807 return 0;
808 }
809};
810
811#define DATA_SYNC_UPDATE_MARKER_WINDOW 1
812
813class RGWDataSyncShardMarkerTrack : public RGWSyncShardMarkerTrack<string, string> {
814 RGWDataSyncEnv *sync_env;
815
816 string marker_oid;
817 rgw_data_sync_marker sync_marker;
818
819 map<string, string> key_to_marker;
820 map<string, string> marker_to_key;
821
822 void handle_finish(const string& marker) override {
823 map<string, string>::iterator iter = marker_to_key.find(marker);
824 if (iter == marker_to_key.end()) {
825 return;
826 }
827 key_to_marker.erase(iter->second);
828 reset_need_retry(iter->second);
829 marker_to_key.erase(iter);
830 }
831
832public:
833 RGWDataSyncShardMarkerTrack(RGWDataSyncEnv *_sync_env,
834 const string& _marker_oid,
835 const rgw_data_sync_marker& _marker) : RGWSyncShardMarkerTrack(DATA_SYNC_UPDATE_MARKER_WINDOW),
836 sync_env(_sync_env),
837 marker_oid(_marker_oid),
838 sync_marker(_marker) {}
839
840 RGWCoroutine *store_marker(const string& new_marker, uint64_t index_pos, const real_time& timestamp) override {
841 sync_marker.marker = new_marker;
842 sync_marker.pos = index_pos;
843
844 ldout(sync_env->cct, 20) << __func__ << "(): updating marker marker_oid=" << marker_oid << " marker=" << new_marker << dendl;
845 RGWRados *store = sync_env->store;
846
847 return new RGWSimpleRadosWriteCR<rgw_data_sync_marker>(sync_env->async_rados, store,
848 rgw_raw_obj(store->get_zone_params().log_pool, marker_oid),
849 sync_marker);
850 }
851
852 /*
853 * create index from key -> marker, and from marker -> key
854 * this is useful so that we can insure that we only have one
855 * entry for any key that is used. This is needed when doing
856 * incremenatl sync of data, and we don't want to run multiple
857 * concurrent sync operations for the same bucket shard
858 */
859 bool index_key_to_marker(const string& key, const string& marker) {
860 if (key_to_marker.find(key) != key_to_marker.end()) {
861 set_need_retry(key);
862 return false;
863 }
864 key_to_marker[key] = marker;
865 marker_to_key[marker] = key;
866 return true;
867 }
868};
869
870// ostream wrappers to print buckets without copying strings
871struct bucket_str {
872 const rgw_bucket& b;
873 bucket_str(const rgw_bucket& b) : b(b) {}
874};
875std::ostream& operator<<(std::ostream& out, const bucket_str& rhs) {
876 auto& b = rhs.b;
877 if (!b.tenant.empty()) {
878 out << b.tenant << '/';
879 }
880 out << b.name;
881 if (!b.bucket_id.empty()) {
882 out << ':' << b.bucket_id;
883 }
884 return out;
885}
886
887struct bucket_shard_str {
888 const rgw_bucket_shard& bs;
889 bucket_shard_str(const rgw_bucket_shard& bs) : bs(bs) {}
890};
891std::ostream& operator<<(std::ostream& out, const bucket_shard_str& rhs) {
892 auto& bs = rhs.bs;
893 out << bucket_str{bs.bucket};
894 if (bs.shard_id >= 0) {
895 out << ':' << bs.shard_id;
896 }
897 return out;
898}
899
900class RGWRunBucketSyncCoroutine : public RGWCoroutine {
901 RGWDataSyncEnv *sync_env;
902 rgw_bucket_shard bs;
903 RGWBucketInfo bucket_info;
904 rgw_bucket_shard_sync_info sync_status;
905 RGWMetaSyncEnv meta_sync_env;
906
907 RGWDataSyncDebugLogger logger;
908 const std::string status_oid;
909
910 boost::intrusive_ptr<RGWContinuousLeaseCR> lease_cr;
911 boost::intrusive_ptr<RGWCoroutinesStack> lease_stack;
912
913public:
914 RGWRunBucketSyncCoroutine(RGWDataSyncEnv *_sync_env, const rgw_bucket_shard& bs)
915 : RGWCoroutine(_sync_env->cct), sync_env(_sync_env), bs(bs),
916 status_oid(RGWBucketSyncStatusManager::status_oid(sync_env->source_zone, bs)) {
917 logger.init(sync_env, "Bucket", bs.get_key());
918 }
919 ~RGWRunBucketSyncCoroutine() override {
920 if (lease_cr) {
921 lease_cr->abort();
922 }
923 }
924
925 int operate() override;
926};
927
928class RGWDataSyncSingleEntryCR : public RGWCoroutine {
929 RGWDataSyncEnv *sync_env;
930
931 string raw_key;
932 string entry_marker;
933
934 rgw_bucket_shard bs;
935
936 int sync_status;
937
938 bufferlist md_bl;
939
940 RGWDataSyncShardMarkerTrack *marker_tracker;
941
942 boost::intrusive_ptr<RGWOmapAppend> error_repo;
943 bool remove_from_repo;
944
945 set<string> keys;
946
947public:
948 RGWDataSyncSingleEntryCR(RGWDataSyncEnv *_sync_env,
949 const string& _raw_key, const string& _entry_marker, RGWDataSyncShardMarkerTrack *_marker_tracker,
950 RGWOmapAppend *_error_repo, bool _remove_from_repo) : RGWCoroutine(_sync_env->cct),
951 sync_env(_sync_env),
952 raw_key(_raw_key), entry_marker(_entry_marker),
953 sync_status(0),
954 marker_tracker(_marker_tracker),
955 error_repo(_error_repo), remove_from_repo(_remove_from_repo) {
956 set_description() << "data sync single entry (source_zone=" << sync_env->source_zone << ") key=" <<_raw_key << " entry=" << entry_marker;
957 }
958
959 int operate() override {
960 reenter(this) {
961 do {
962 yield {
963 int ret = rgw_bucket_parse_bucket_key(sync_env->cct, raw_key,
964 &bs.bucket, &bs.shard_id);
965 if (ret < 0) {
966 return set_cr_error(-EIO);
967 }
968 if (marker_tracker) {
969 marker_tracker->reset_need_retry(raw_key);
970 }
971 call(new RGWRunBucketSyncCoroutine(sync_env, bs));
972 }
973 } while (marker_tracker && marker_tracker->need_retry(raw_key));
974
975 sync_status = retcode;
976
977 if (sync_status == -ENOENT) {
978 // this was added when 'tenant/' was added to datalog entries, because
979 // preexisting tenant buckets could never sync and would stay in the
980 // error_repo forever
981 ldout(sync_env->store->ctx(), 0) << "WARNING: skipping data log entry "
982 "for missing bucket " << raw_key << dendl;
983 sync_status = 0;
984 }
985
986 if (sync_status < 0) {
987 yield call(sync_env->error_logger->log_error_cr(sync_env->conn->get_remote_id(), "data", raw_key,
988 -sync_status, string("failed to sync bucket instance: ") + cpp_strerror(-sync_status)));
989 if (retcode < 0) {
990 ldout(sync_env->store->ctx(), 0) << "ERROR: failed to log sync failure: retcode=" << retcode << dendl;
991 }
992 if (error_repo && !error_repo->append(raw_key)) {
993 ldout(sync_env->store->ctx(), 0) << "ERROR: failed to log sync failure in error repo: retcode=" << retcode << dendl;
994 }
995 } else if (error_repo && remove_from_repo) {
996 keys = {raw_key};
997 yield call(new RGWRadosRemoveOmapKeysCR(sync_env->store, error_repo->get_obj(), keys));
998 if (retcode < 0) {
999 ldout(sync_env->store->ctx(), 0) << "ERROR: failed to remove omap key from error repo ("
1000 << error_repo->get_obj() << " retcode=" << retcode << dendl;
1001 }
1002 }
1003 /* FIXME: what do do in case of error */
1004 if (marker_tracker && !entry_marker.empty()) {
1005 /* update marker */
1006 yield call(marker_tracker->finish(entry_marker));
1007 }
1008 if (sync_status == 0) {
1009 sync_status = retcode;
1010 }
1011 if (sync_status < 0) {
1012 return set_cr_error(sync_status);
1013 }
1014 return set_cr_done();
1015 }
1016 return 0;
1017 }
1018};
1019
1020#define BUCKET_SHARD_SYNC_SPAWN_WINDOW 20
1021#define DATA_SYNC_MAX_ERR_ENTRIES 10
1022
181888fb
FG
1023enum RemoteDatalogStatus {
1024 RemoteNotTrimmed = 0,
1025 RemoteTrimmed = 1,
1026 RemoteMightTrimmed = 2
1027};
1028
7c673cae
FG
1029class RGWDataSyncShardCR : public RGWCoroutine {
1030 RGWDataSyncEnv *sync_env;
1031
1032 rgw_pool pool;
1033
1034 uint32_t shard_id;
1035 rgw_data_sync_marker sync_marker;
1036
1037 map<string, bufferlist> entries;
1038 map<string, bufferlist>::iterator iter;
1039
1040 string oid;
1041
1042 RGWDataSyncShardMarkerTrack *marker_tracker;
1043
1044 list<rgw_data_change_log_entry> log_entries;
1045 list<rgw_data_change_log_entry>::iterator log_iter;
1046 bool truncated;
1047
1048 RGWDataChangesLogInfo shard_info;
1049 string datalog_marker;
1050
181888fb 1051 RemoteDatalogStatus remote_trimmed;
7c673cae
FG
1052 Mutex inc_lock;
1053 Cond inc_cond;
1054
1055 boost::asio::coroutine incremental_cr;
1056 boost::asio::coroutine full_cr;
1057
1058
1059 set<string> modified_shards;
1060 set<string> current_modified;
1061
1062 set<string>::iterator modified_iter;
1063
1064 int total_entries;
1065
1066 int spawn_window;
1067
1068 bool *reset_backoff;
1069
1070 set<string> spawned_keys;
1071
31f18b77
FG
1072 boost::intrusive_ptr<RGWContinuousLeaseCR> lease_cr;
1073 boost::intrusive_ptr<RGWCoroutinesStack> lease_stack;
7c673cae
FG
1074 string status_oid;
1075
1076
1077 string error_oid;
1078 RGWOmapAppend *error_repo;
1079 map<string, bufferlist> error_entries;
1080 string error_marker;
1081 int max_error_entries;
1082
1083 ceph::real_time error_retry_time;
1084
1085#define RETRY_BACKOFF_SECS_MIN 60
1086#define RETRY_BACKOFF_SECS_DEFAULT 60
1087#define RETRY_BACKOFF_SECS_MAX 600
1088 uint32_t retry_backoff_secs;
1089
1090 RGWDataSyncDebugLogger logger;
1091public:
1092 RGWDataSyncShardCR(RGWDataSyncEnv *_sync_env,
1093 rgw_pool& _pool,
1094 uint32_t _shard_id, rgw_data_sync_marker& _marker, bool *_reset_backoff) : RGWCoroutine(_sync_env->cct),
1095 sync_env(_sync_env),
1096 pool(_pool),
1097 shard_id(_shard_id),
1098 sync_marker(_marker),
181888fb 1099 marker_tracker(NULL), truncated(false), remote_trimmed(RemoteNotTrimmed), inc_lock("RGWDataSyncShardCR::inc_lock"),
7c673cae
FG
1100 total_entries(0), spawn_window(BUCKET_SHARD_SYNC_SPAWN_WINDOW), reset_backoff(NULL),
1101 lease_cr(nullptr), lease_stack(nullptr), error_repo(nullptr), max_error_entries(DATA_SYNC_MAX_ERR_ENTRIES),
1102 retry_backoff_secs(RETRY_BACKOFF_SECS_DEFAULT) {
1103 set_description() << "data sync shard source_zone=" << sync_env->source_zone << " shard_id=" << shard_id;
1104 status_oid = RGWDataSyncStatusManager::shard_obj_name(sync_env->source_zone, shard_id);
1105 error_oid = status_oid + ".retry";
1106
1107 logger.init(sync_env, "DataShard", status_oid);
1108 }
1109
1110 ~RGWDataSyncShardCR() override {
1111 delete marker_tracker;
1112 if (lease_cr) {
1113 lease_cr->abort();
7c673cae
FG
1114 }
1115 if (error_repo) {
1116 error_repo->put();
1117 }
1118 }
1119
1120 void append_modified_shards(set<string>& keys) {
1121 Mutex::Locker l(inc_lock);
1122 modified_shards.insert(keys.begin(), keys.end());
1123 }
1124
1125 void set_marker_tracker(RGWDataSyncShardMarkerTrack *mt) {
1126 delete marker_tracker;
1127 marker_tracker = mt;
1128 }
1129
1130 int operate() override {
1131 int r;
1132 while (true) {
1133 switch (sync_marker.state) {
1134 case rgw_data_sync_marker::FullSync:
1135 r = full_sync();
1136 if (r < 0) {
1137 ldout(cct, 10) << "sync: full_sync: shard_id=" << shard_id << " r=" << r << dendl;
1138 return set_cr_error(r);
1139 }
1140 return 0;
1141 case rgw_data_sync_marker::IncrementalSync:
1142 r = incremental_sync();
1143 if (r < 0) {
1144 ldout(cct, 10) << "sync: incremental_sync: shard_id=" << shard_id << " r=" << r << dendl;
1145 return set_cr_error(r);
1146 }
1147 return 0;
1148 default:
1149 return set_cr_error(-EIO);
1150 }
1151 }
1152 return 0;
1153 }
1154
1155 void init_lease_cr() {
1156 set_status("acquiring sync lock");
1157 uint32_t lock_duration = cct->_conf->rgw_sync_lease_period;
1158 string lock_name = "sync_lock";
1159 if (lease_cr) {
1160 lease_cr->abort();
7c673cae
FG
1161 }
1162 RGWRados *store = sync_env->store;
31f18b77
FG
1163 lease_cr.reset(new RGWContinuousLeaseCR(sync_env->async_rados, store,
1164 rgw_raw_obj(store->get_zone_params().log_pool, status_oid),
1165 lock_name, lock_duration, this));
1166 lease_stack.reset(spawn(lease_cr.get(), false));
7c673cae
FG
1167 }
1168
1169 int full_sync() {
1170#define OMAP_GET_MAX_ENTRIES 100
1171 int max_entries = OMAP_GET_MAX_ENTRIES;
1172 reenter(&full_cr) {
1173 yield init_lease_cr();
1174 while (!lease_cr->is_locked()) {
1175 if (lease_cr->is_done()) {
1176 ldout(cct, 5) << "lease cr failed, done early " << dendl;
1177 set_status("lease lock failed, early abort");
1178 return set_cr_error(lease_cr->get_ret_status());
1179 }
1180 set_sleeping(true);
1181 yield;
1182 }
1183 logger.log("full sync");
1184 oid = full_data_sync_index_shard_oid(sync_env->source_zone, shard_id);
1185 set_marker_tracker(new RGWDataSyncShardMarkerTrack(sync_env, status_oid, sync_marker));
1186 total_entries = sync_marker.pos;
1187 do {
1188 yield call(new RGWRadosGetOmapKeysCR(sync_env->store, rgw_raw_obj(pool, oid), sync_marker.marker, &entries, max_entries));
1189 if (retcode < 0) {
1190 ldout(sync_env->cct, 0) << "ERROR: " << __func__ << "(): RGWRadosGetOmapKeysCR() returned ret=" << retcode << dendl;
1191 lease_cr->go_down();
1192 drain_all();
1193 return set_cr_error(retcode);
1194 }
1195 iter = entries.begin();
1196 for (; iter != entries.end(); ++iter) {
1197 ldout(sync_env->cct, 20) << __func__ << ": full sync: " << iter->first << dendl;
1198 total_entries++;
1199 if (!marker_tracker->start(iter->first, total_entries, real_time())) {
1200 ldout(sync_env->cct, 0) << "ERROR: cannot start syncing " << iter->first << ". Duplicate entry?" << dendl;
1201 } else {
1202 // fetch remote and write locally
1203 yield spawn(new RGWDataSyncSingleEntryCR(sync_env, iter->first, iter->first, marker_tracker, error_repo, false), false);
1204 if (retcode < 0) {
1205 lease_cr->go_down();
1206 drain_all();
1207 return set_cr_error(retcode);
1208 }
1209 }
1210 sync_marker.marker = iter->first;
1211 }
1212 } while ((int)entries.size() == max_entries);
1213
1214 lease_cr->go_down();
1215 drain_all();
1216
1217 yield {
1218 /* update marker to reflect we're done with full sync */
1219 sync_marker.state = rgw_data_sync_marker::IncrementalSync;
1220 sync_marker.marker = sync_marker.next_step_marker;
1221 sync_marker.next_step_marker.clear();
1222 RGWRados *store = sync_env->store;
1223 call(new RGWSimpleRadosWriteCR<rgw_data_sync_marker>(sync_env->async_rados, store,
1224 rgw_raw_obj(store->get_zone_params().log_pool, status_oid),
1225 sync_marker));
1226 }
1227 if (retcode < 0) {
1228 ldout(sync_env->cct, 0) << "ERROR: failed to set sync marker: retcode=" << retcode << dendl;
1229 lease_cr->go_down();
1230 return set_cr_error(retcode);
1231 }
1232 }
1233 return 0;
1234 }
1235
1236 int incremental_sync() {
1237 reenter(&incremental_cr) {
1238 yield init_lease_cr();
1239 while (!lease_cr->is_locked()) {
1240 if (lease_cr->is_done()) {
1241 ldout(cct, 5) << "lease cr failed, done early " << dendl;
1242 set_status("lease lock failed, early abort");
1243 return set_cr_error(lease_cr->get_ret_status());
1244 }
1245 set_sleeping(true);
1246 yield;
1247 }
1248 set_status("lease acquired");
1249 error_repo = new RGWOmapAppend(sync_env->async_rados, sync_env->store,
1250 rgw_raw_obj(pool, error_oid),
1251 1 /* no buffer */);
1252 error_repo->get();
1253 spawn(error_repo, false);
1254 logger.log("inc sync");
1255 set_marker_tracker(new RGWDataSyncShardMarkerTrack(sync_env, status_oid, sync_marker));
1256 do {
1257 current_modified.clear();
1258 inc_lock.Lock();
1259 current_modified.swap(modified_shards);
1260 inc_lock.Unlock();
1261
1262 /* process out of band updates */
1263 for (modified_iter = current_modified.begin(); modified_iter != current_modified.end(); ++modified_iter) {
1264 yield {
1265 ldout(sync_env->cct, 20) << __func__ << "(): async update notification: " << *modified_iter << dendl;
1266 spawn(new RGWDataSyncSingleEntryCR(sync_env, *modified_iter, string(), marker_tracker, error_repo, false), false);
1267 }
1268 }
1269
1270 /* process bucket shards that previously failed */
1271 yield call(new RGWRadosGetOmapKeysCR(sync_env->store, rgw_raw_obj(pool, error_oid),
1272 error_marker, &error_entries,
1273 max_error_entries));
1274 ldout(sync_env->cct, 20) << __func__ << "(): read error repo, got " << error_entries.size() << " entries" << dendl;
1275 iter = error_entries.begin();
1276 for (; iter != error_entries.end(); ++iter) {
1277 ldout(sync_env->cct, 20) << __func__ << "(): handle error entry: " << iter->first << dendl;
1278 spawn(new RGWDataSyncSingleEntryCR(sync_env, iter->first, iter->first, nullptr /* no marker tracker */, error_repo, true), false);
1279 error_marker = iter->first;
1280 }
1281 if ((int)error_entries.size() != max_error_entries) {
1282 if (error_marker.empty() && error_entries.empty()) {
1283 /* the retry repo is empty, we back off a bit before calling it again */
1284 retry_backoff_secs *= 2;
1285 if (retry_backoff_secs > RETRY_BACKOFF_SECS_MAX) {
1286 retry_backoff_secs = RETRY_BACKOFF_SECS_MAX;
1287 }
1288 } else {
1289 retry_backoff_secs = RETRY_BACKOFF_SECS_DEFAULT;
1290 }
1291 error_retry_time = ceph::real_clock::now() + make_timespan(retry_backoff_secs);
1292 error_marker.clear();
1293 }
1294
1295
1296 yield call(new RGWReadRemoteDataLogShardInfoCR(sync_env, shard_id, &shard_info));
1297 if (retcode < 0) {
1298 ldout(sync_env->cct, 0) << "ERROR: failed to fetch remote data log info: ret=" << retcode << dendl;
1299 stop_spawned_services();
1300 drain_all();
1301 return set_cr_error(retcode);
1302 }
1303 datalog_marker = shard_info.marker;
181888fb 1304 remote_trimmed = RemoteNotTrimmed;
7c673cae
FG
1305#define INCREMENTAL_MAX_ENTRIES 100
1306 ldout(sync_env->cct, 20) << __func__ << ":" << __LINE__ << ": shard_id=" << shard_id << " datalog_marker=" << datalog_marker << " sync_marker.marker=" << sync_marker.marker << dendl;
1307 if (datalog_marker > sync_marker.marker) {
1308 spawned_keys.clear();
181888fb
FG
1309 if (sync_marker.marker.empty())
1310 remote_trimmed = RemoteMightTrimmed; //remote data log shard might be trimmed;
7c673cae
FG
1311 yield call(new RGWReadRemoteDataLogShardCR(sync_env, shard_id, &sync_marker.marker, &log_entries, &truncated));
1312 if (retcode < 0) {
1313 ldout(sync_env->cct, 0) << "ERROR: failed to read remote data log info: ret=" << retcode << dendl;
1314 stop_spawned_services();
1315 drain_all();
1316 return set_cr_error(retcode);
1317 }
181888fb
FG
1318 if ((remote_trimmed == RemoteMightTrimmed) && sync_marker.marker.empty() && log_entries.empty())
1319 remote_trimmed = RemoteTrimmed;
1320 else
1321 remote_trimmed = RemoteNotTrimmed;
7c673cae
FG
1322 for (log_iter = log_entries.begin(); log_iter != log_entries.end(); ++log_iter) {
1323 ldout(sync_env->cct, 20) << __func__ << ":" << __LINE__ << ": shard_id=" << shard_id << " log_entry: " << log_iter->log_id << ":" << log_iter->log_timestamp << ":" << log_iter->entry.key << dendl;
1324 if (!marker_tracker->index_key_to_marker(log_iter->entry.key, log_iter->log_id)) {
1325 ldout(sync_env->cct, 20) << __func__ << ": skipping sync of entry: " << log_iter->log_id << ":" << log_iter->entry.key << " sync already in progress for bucket shard" << dendl;
1326 marker_tracker->try_update_high_marker(log_iter->log_id, 0, log_iter->log_timestamp);
1327 continue;
1328 }
1329 if (!marker_tracker->start(log_iter->log_id, 0, log_iter->log_timestamp)) {
1330 ldout(sync_env->cct, 0) << "ERROR: cannot start syncing " << log_iter->log_id << ". Duplicate entry?" << dendl;
1331 } else {
1332 /*
1333 * don't spawn the same key more than once. We can do that as long as we don't yield
1334 */
1335 if (spawned_keys.find(log_iter->entry.key) == spawned_keys.end()) {
1336 spawned_keys.insert(log_iter->entry.key);
1337 spawn(new RGWDataSyncSingleEntryCR(sync_env, log_iter->entry.key, log_iter->log_id, marker_tracker, error_repo, false), false);
1338 if (retcode < 0) {
1339 stop_spawned_services();
1340 drain_all();
1341 return set_cr_error(retcode);
1342 }
1343 }
1344 }
1345 }
1346 while ((int)num_spawned() > spawn_window) {
1347 set_status() << "num_spawned() > spawn_window";
1348 yield wait_for_child();
1349 int ret;
31f18b77 1350 while (collect(&ret, lease_stack.get())) {
7c673cae
FG
1351 if (ret < 0) {
1352 ldout(sync_env->cct, 0) << "ERROR: a sync operation returned error" << dendl;
1353 /* we have reported this error */
1354 }
1355 /* not waiting for child here */
1356 }
1357 }
1358 }
1359 ldout(sync_env->cct, 20) << __func__ << ":" << __LINE__ << ": shard_id=" << shard_id << " datalog_marker=" << datalog_marker << " sync_marker.marker=" << sync_marker.marker << dendl;
181888fb 1360 if (datalog_marker == sync_marker.marker || remote_trimmed == RemoteTrimmed) {
7c673cae
FG
1361#define INCREMENTAL_INTERVAL 20
1362 yield wait(utime_t(INCREMENTAL_INTERVAL, 0));
1363 }
1364 } while (true);
1365 }
1366 return 0;
1367 }
1368 void stop_spawned_services() {
1369 lease_cr->go_down();
1370 if (error_repo) {
1371 error_repo->finish();
1372 error_repo->put();
1373 error_repo = NULL;
1374 }
1375 }
1376};
1377
1378class RGWDataSyncShardControlCR : public RGWBackoffControlCR {
1379 RGWDataSyncEnv *sync_env;
1380
1381 rgw_pool pool;
1382
1383 uint32_t shard_id;
1384 rgw_data_sync_marker sync_marker;
1385
1386public:
1387 RGWDataSyncShardControlCR(RGWDataSyncEnv *_sync_env, rgw_pool& _pool,
1388 uint32_t _shard_id, rgw_data_sync_marker& _marker) : RGWBackoffControlCR(_sync_env->cct, false),
1389 sync_env(_sync_env),
1390 pool(_pool),
1391 shard_id(_shard_id),
1392 sync_marker(_marker) {
1393 }
1394
1395 RGWCoroutine *alloc_cr() override {
1396 return new RGWDataSyncShardCR(sync_env, pool, shard_id, sync_marker, backoff_ptr());
1397 }
1398
1399 RGWCoroutine *alloc_finisher_cr() override {
1400 RGWRados *store = sync_env->store;
1401 return new RGWSimpleRadosReadCR<rgw_data_sync_marker>(sync_env->async_rados, store,
1402 rgw_raw_obj(store->get_zone_params().log_pool, RGWDataSyncStatusManager::shard_obj_name(sync_env->source_zone, shard_id)),
1403 &sync_marker);
1404 }
1405
1406 void append_modified_shards(set<string>& keys) {
1407 Mutex::Locker l(cr_lock());
1408
1409 RGWDataSyncShardCR *cr = static_cast<RGWDataSyncShardCR *>(get_cr());
1410 if (!cr) {
1411 return;
1412 }
1413
1414 cr->append_modified_shards(keys);
1415 }
1416};
1417
1418class RGWDataSyncCR : public RGWCoroutine {
1419 RGWDataSyncEnv *sync_env;
1420 uint32_t num_shards;
1421
1422 rgw_data_sync_status sync_status;
1423
1424 RGWDataSyncShardMarkerTrack *marker_tracker;
1425
1426 Mutex shard_crs_lock;
1427 map<int, RGWDataSyncShardControlCR *> shard_crs;
1428
1429 bool *reset_backoff;
1430
1431 RGWDataSyncDebugLogger logger;
31f18b77
FG
1432
1433 RGWDataSyncModule *data_sync_module{nullptr};
7c673cae
FG
1434public:
1435 RGWDataSyncCR(RGWDataSyncEnv *_sync_env, uint32_t _num_shards, bool *_reset_backoff) : RGWCoroutine(_sync_env->cct),
1436 sync_env(_sync_env),
1437 num_shards(_num_shards),
1438 marker_tracker(NULL),
1439 shard_crs_lock("RGWDataSyncCR::shard_crs_lock"),
1440 reset_backoff(_reset_backoff), logger(sync_env, "Data", "all") {
31f18b77 1441
7c673cae
FG
1442 }
1443
1444 ~RGWDataSyncCR() override {
1445 for (auto iter : shard_crs) {
1446 iter.second->put();
1447 }
1448 }
1449
1450 int operate() override {
1451 reenter(this) {
1452
1453 /* read sync status */
1454 yield call(new RGWReadDataSyncStatusCoroutine(sync_env, &sync_status));
1455
31f18b77
FG
1456 data_sync_module = sync_env->sync_module->get_data_handler();
1457
224ce89b 1458 if (retcode < 0 && retcode != -ENOENT) {
7c673cae
FG
1459 ldout(sync_env->cct, 0) << "ERROR: failed to fetch sync status, retcode=" << retcode << dendl;
1460 return set_cr_error(retcode);
1461 }
1462
1463 /* state: init status */
1464 if ((rgw_data_sync_info::SyncState)sync_status.sync_info.state == rgw_data_sync_info::StateInit) {
1465 ldout(sync_env->cct, 20) << __func__ << "(): init" << dendl;
224ce89b 1466 sync_status.sync_info.num_shards = num_shards;
31f18b77
FG
1467 uint64_t instance_id;
1468 get_random_bytes((char *)&instance_id, sizeof(instance_id));
1469 yield call(new RGWInitDataSyncStatusCoroutine(sync_env, num_shards, instance_id, &sync_status));
7c673cae
FG
1470 if (retcode < 0) {
1471 ldout(sync_env->cct, 0) << "ERROR: failed to init sync, retcode=" << retcode << dendl;
1472 return set_cr_error(retcode);
1473 }
1474 // sets state = StateBuildingFullSyncMaps
1475
1476 *reset_backoff = true;
1477 }
1478
31f18b77
FG
1479 data_sync_module->init(sync_env, sync_status.sync_info.instance_id);
1480
7c673cae 1481 if ((rgw_data_sync_info::SyncState)sync_status.sync_info.state == rgw_data_sync_info::StateBuildingFullSyncMaps) {
31f18b77
FG
1482 /* call sync module init here */
1483 yield call(data_sync_module->init_sync(sync_env));
1484 if (retcode < 0) {
1485 ldout(sync_env->cct, 0) << "ERROR: sync module init_sync() failed, retcode=" << retcode << dendl;
1486 return set_cr_error(retcode);
1487 }
7c673cae
FG
1488 /* state: building full sync maps */
1489 ldout(sync_env->cct, 20) << __func__ << "(): building full sync maps" << dendl;
1490 yield call(new RGWListBucketIndexesCR(sync_env, &sync_status));
1491 if (retcode < 0) {
1492 ldout(sync_env->cct, 0) << "ERROR: failed to build full sync maps, retcode=" << retcode << dendl;
1493 return set_cr_error(retcode);
1494 }
1495 sync_status.sync_info.state = rgw_data_sync_info::StateSync;
1496
1497 /* update new state */
1498 yield call(set_sync_info_cr());
1499 if (retcode < 0) {
1500 ldout(sync_env->cct, 0) << "ERROR: failed to write sync status, retcode=" << retcode << dendl;
1501 return set_cr_error(retcode);
1502 }
1503
1504 *reset_backoff = true;
1505 }
1506
1507 yield {
1508 if ((rgw_data_sync_info::SyncState)sync_status.sync_info.state == rgw_data_sync_info::StateSync) {
1509 for (map<uint32_t, rgw_data_sync_marker>::iterator iter = sync_status.sync_markers.begin();
1510 iter != sync_status.sync_markers.end(); ++iter) {
1511 RGWDataSyncShardControlCR *cr = new RGWDataSyncShardControlCR(sync_env, sync_env->store->get_zone_params().log_pool,
1512 iter->first, iter->second);
1513 cr->get();
1514 shard_crs_lock.Lock();
1515 shard_crs[iter->first] = cr;
1516 shard_crs_lock.Unlock();
1517 spawn(cr, true);
1518 }
1519 }
1520 }
1521
1522 return set_cr_done();
1523 }
1524 return 0;
1525 }
1526
1527 RGWCoroutine *set_sync_info_cr() {
1528 RGWRados *store = sync_env->store;
1529 return new RGWSimpleRadosWriteCR<rgw_data_sync_info>(sync_env->async_rados, store,
1530 rgw_raw_obj(store->get_zone_params().log_pool, RGWDataSyncStatusManager::sync_status_oid(sync_env->source_zone)),
1531 sync_status.sync_info);
1532 }
1533
1534 void wakeup(int shard_id, set<string>& keys) {
1535 Mutex::Locker l(shard_crs_lock);
1536 map<int, RGWDataSyncShardControlCR *>::iterator iter = shard_crs.find(shard_id);
1537 if (iter == shard_crs.end()) {
1538 return;
1539 }
1540 iter->second->append_modified_shards(keys);
1541 iter->second->wakeup();
1542 }
1543};
1544
1545class RGWDefaultDataSyncModule : public RGWDataSyncModule {
1546public:
1547 RGWDefaultDataSyncModule() {}
1548
31f18b77
FG
1549 RGWCoroutine *sync_object(RGWDataSyncEnv *sync_env, RGWBucketInfo& bucket_info, rgw_obj_key& key, uint64_t versioned_epoch, rgw_zone_set *zones_trace) override;
1550 RGWCoroutine *remove_object(RGWDataSyncEnv *sync_env, RGWBucketInfo& bucket_info, rgw_obj_key& key, real_time& mtime, bool versioned, uint64_t versioned_epoch, rgw_zone_set *zones_trace) override;
7c673cae 1551 RGWCoroutine *create_delete_marker(RGWDataSyncEnv *sync_env, RGWBucketInfo& bucket_info, rgw_obj_key& key, real_time& mtime,
31f18b77 1552 rgw_bucket_entry_owner& owner, bool versioned, uint64_t versioned_epoch, rgw_zone_set *zones_trace) override;
7c673cae
FG
1553};
1554
1555class RGWDefaultSyncModuleInstance : public RGWSyncModuleInstance {
1556 RGWDefaultDataSyncModule data_handler;
1557public:
1558 RGWDefaultSyncModuleInstance() {}
1559 RGWDataSyncModule *get_data_handler() override {
1560 return &data_handler;
1561 }
1562};
1563
31f18b77 1564int RGWDefaultSyncModule::create_instance(CephContext *cct, map<string, string, ltstr_nocase>& config, RGWSyncModuleInstanceRef *instance)
7c673cae
FG
1565{
1566 instance->reset(new RGWDefaultSyncModuleInstance());
1567 return 0;
1568}
1569
31f18b77 1570RGWCoroutine *RGWDefaultDataSyncModule::sync_object(RGWDataSyncEnv *sync_env, RGWBucketInfo& bucket_info, rgw_obj_key& key, uint64_t versioned_epoch, rgw_zone_set *zones_trace)
7c673cae
FG
1571{
1572 return new RGWFetchRemoteObjCR(sync_env->async_rados, sync_env->store, sync_env->source_zone, bucket_info,
1573 key, versioned_epoch,
31f18b77 1574 true, zones_trace);
7c673cae
FG
1575}
1576
1577RGWCoroutine *RGWDefaultDataSyncModule::remove_object(RGWDataSyncEnv *sync_env, RGWBucketInfo& bucket_info, rgw_obj_key& key,
31f18b77 1578 real_time& mtime, bool versioned, uint64_t versioned_epoch, rgw_zone_set *zones_trace)
7c673cae
FG
1579{
1580 return new RGWRemoveObjCR(sync_env->async_rados, sync_env->store, sync_env->source_zone,
1581 bucket_info, key, versioned, versioned_epoch,
31f18b77 1582 NULL, NULL, false, &mtime, zones_trace);
7c673cae
FG
1583}
1584
1585RGWCoroutine *RGWDefaultDataSyncModule::create_delete_marker(RGWDataSyncEnv *sync_env, RGWBucketInfo& bucket_info, rgw_obj_key& key, real_time& mtime,
31f18b77 1586 rgw_bucket_entry_owner& owner, bool versioned, uint64_t versioned_epoch, rgw_zone_set *zones_trace)
7c673cae
FG
1587{
1588 return new RGWRemoveObjCR(sync_env->async_rados, sync_env->store, sync_env->source_zone,
1589 bucket_info, key, versioned, versioned_epoch,
31f18b77 1590 &owner.id, &owner.display_name, true, &mtime, zones_trace);
7c673cae
FG
1591}
1592
1593class RGWDataSyncControlCR : public RGWBackoffControlCR
1594{
1595 RGWDataSyncEnv *sync_env;
1596 uint32_t num_shards;
1597
1598public:
1599 RGWDataSyncControlCR(RGWDataSyncEnv *_sync_env, uint32_t _num_shards) : RGWBackoffControlCR(_sync_env->cct, true),
1600 sync_env(_sync_env), num_shards(_num_shards) {
1601 }
1602
1603 RGWCoroutine *alloc_cr() override {
1604 return new RGWDataSyncCR(sync_env, num_shards, backoff_ptr());
1605 }
1606
1607 void wakeup(int shard_id, set<string>& keys) {
1608 Mutex& m = cr_lock();
1609
1610 m.Lock();
1611 RGWDataSyncCR *cr = static_cast<RGWDataSyncCR *>(get_cr());
1612 if (!cr) {
1613 m.Unlock();
1614 return;
1615 }
1616
1617 cr->get();
1618 m.Unlock();
1619
1620 if (cr) {
1621 cr->wakeup(shard_id, keys);
1622 }
1623
1624 cr->put();
1625 }
1626};
1627
1628void RGWRemoteDataLog::wakeup(int shard_id, set<string>& keys) {
1629 RWLock::RLocker rl(lock);
1630 if (!data_sync_cr) {
1631 return;
1632 }
1633 data_sync_cr->wakeup(shard_id, keys);
1634}
1635
1636int RGWRemoteDataLog::run_sync(int num_shards)
1637{
1638 lock.get_write();
1639 data_sync_cr = new RGWDataSyncControlCR(&sync_env, num_shards);
1640 data_sync_cr->get(); // run() will drop a ref, so take another
1641 lock.unlock();
1642
1643 int r = run(data_sync_cr);
1644
1645 lock.get_write();
1646 data_sync_cr->put();
1647 data_sync_cr = NULL;
1648 lock.unlock();
1649
1650 if (r < 0) {
1651 ldout(store->ctx(), 0) << "ERROR: failed to run sync" << dendl;
1652 return r;
1653 }
1654 return 0;
1655}
1656
1657int RGWDataSyncStatusManager::init()
1658{
1659 auto zone_def_iter = store->zone_by_id.find(source_zone);
1660 if (zone_def_iter == store->zone_by_id.end()) {
1661 ldout(store->ctx(), 0) << "ERROR: failed to find zone config info for zone=" << source_zone << dendl;
1662 return -EIO;
1663 }
1664
1665 auto& zone_def = zone_def_iter->second;
1666
1667 if (!store->get_sync_modules_manager()->supports_data_export(zone_def.tier_type)) {
1668 return -ENOTSUP;
1669 }
1670
1671 RGWZoneParams& zone_params = store->get_zone_params();
1672
1673 sync_module = store->get_sync_module();
1674
1675 conn = store->get_zone_conn_by_id(source_zone);
1676 if (!conn) {
1677 ldout(store->ctx(), 0) << "connection object to zone " << source_zone << " does not exist" << dendl;
1678 return -EINVAL;
1679 }
1680
1681 error_logger = new RGWSyncErrorLogger(store, RGW_SYNC_ERROR_LOG_SHARD_PREFIX, ERROR_LOGGER_SHARDS);
1682
1683 int r = source_log.init(source_zone, conn, error_logger, sync_module);
1684 if (r < 0) {
1685 lderr(store->ctx()) << "ERROR: failed to init remote log, r=" << r << dendl;
1686 finalize();
1687 return r;
1688 }
1689
1690 rgw_datalog_info datalog_info;
1691 r = source_log.read_log_info(&datalog_info);
1692 if (r < 0) {
1693 ldout(store->ctx(), 5) << "ERROR: master.read_log_info() returned r=" << r << dendl;
1694 finalize();
1695 return r;
1696 }
1697
1698 num_shards = datalog_info.num_shards;
1699
1700 for (int i = 0; i < num_shards; i++) {
1701 shard_objs[i] = rgw_raw_obj(zone_params.log_pool, shard_obj_name(source_zone, i));
1702 }
1703
1704 return 0;
1705}
1706
1707void RGWDataSyncStatusManager::finalize()
1708{
1709 delete error_logger;
1710 error_logger = nullptr;
1711}
1712
1713string RGWDataSyncStatusManager::sync_status_oid(const string& source_zone)
1714{
1715 char buf[datalog_sync_status_oid_prefix.size() + source_zone.size() + 16];
1716 snprintf(buf, sizeof(buf), "%s.%s", datalog_sync_status_oid_prefix.c_str(), source_zone.c_str());
1717
1718 return string(buf);
1719}
1720
1721string RGWDataSyncStatusManager::shard_obj_name(const string& source_zone, int shard_id)
1722{
1723 char buf[datalog_sync_status_shard_prefix.size() + source_zone.size() + 16];
1724 snprintf(buf, sizeof(buf), "%s.%s.%d", datalog_sync_status_shard_prefix.c_str(), source_zone.c_str(), shard_id);
1725
1726 return string(buf);
1727}
1728
1729int RGWRemoteBucketLog::init(const string& _source_zone, RGWRESTConn *_conn,
1730 const rgw_bucket& bucket, int shard_id,
1731 RGWSyncErrorLogger *_error_logger,
1732 RGWSyncModuleInstanceRef& _sync_module)
1733{
1734 conn = _conn;
1735 source_zone = _source_zone;
1736 bs.bucket = bucket;
1737 bs.shard_id = shard_id;
1738
1739 sync_env.init(store->ctx(), store, conn, async_rados, http_manager, _error_logger, source_zone, _sync_module);
1740
1741 return 0;
1742}
1743
1744struct bucket_index_marker_info {
1745 string bucket_ver;
1746 string master_ver;
1747 string max_marker;
c07f9fc5 1748 bool syncstopped{false};
7c673cae
FG
1749
1750 void decode_json(JSONObj *obj) {
1751 JSONDecoder::decode_json("bucket_ver", bucket_ver, obj);
1752 JSONDecoder::decode_json("master_ver", master_ver, obj);
1753 JSONDecoder::decode_json("max_marker", max_marker, obj);
c07f9fc5 1754 JSONDecoder::decode_json("syncstopped", syncstopped, obj);
7c673cae
FG
1755 }
1756};
1757
1758class RGWReadRemoteBucketIndexLogInfoCR : public RGWCoroutine {
1759 RGWDataSyncEnv *sync_env;
1760 const string instance_key;
1761
1762 bucket_index_marker_info *info;
1763
1764public:
1765 RGWReadRemoteBucketIndexLogInfoCR(RGWDataSyncEnv *_sync_env,
1766 const rgw_bucket_shard& bs,
1767 bucket_index_marker_info *_info)
1768 : RGWCoroutine(_sync_env->cct), sync_env(_sync_env),
1769 instance_key(bs.get_key()), info(_info) {}
1770
1771 int operate() override {
1772 reenter(this) {
1773 yield {
1774 rgw_http_param_pair pairs[] = { { "type" , "bucket-index" },
1775 { "bucket-instance", instance_key.c_str() },
1776 { "info" , NULL },
1777 { NULL, NULL } };
1778
1779 string p = "/admin/log/";
1780 call(new RGWReadRESTResourceCR<bucket_index_marker_info>(sync_env->cct, sync_env->conn, sync_env->http_manager, p, pairs, info));
1781 }
1782 if (retcode < 0) {
1783 return set_cr_error(retcode);
1784 }
1785 return set_cr_done();
1786 }
1787 return 0;
1788 }
1789};
1790
1791class RGWInitBucketShardSyncStatusCoroutine : public RGWCoroutine {
1792 RGWDataSyncEnv *sync_env;
1793
1794 rgw_bucket_shard bs;
1795 const string sync_status_oid;
1796
1797 rgw_bucket_shard_sync_info& status;
1798
1799 bucket_index_marker_info info;
1800public:
1801 RGWInitBucketShardSyncStatusCoroutine(RGWDataSyncEnv *_sync_env,
1802 const rgw_bucket_shard& bs,
1803 rgw_bucket_shard_sync_info& _status)
1804 : RGWCoroutine(_sync_env->cct), sync_env(_sync_env), bs(bs),
1805 sync_status_oid(RGWBucketSyncStatusManager::status_oid(sync_env->source_zone, bs)),
1806 status(_status)
1807 {}
1808
1809 int operate() override {
1810 reenter(this) {
1811 /* fetch current position in logs */
1812 yield call(new RGWReadRemoteBucketIndexLogInfoCR(sync_env, bs, &info));
1813 if (retcode < 0 && retcode != -ENOENT) {
1814 ldout(cct, 0) << "ERROR: failed to fetch bucket index status" << dendl;
1815 return set_cr_error(retcode);
1816 }
1817 yield {
7c673cae 1818 auto store = sync_env->store;
c07f9fc5
FG
1819 rgw_raw_obj obj(store->get_zone_params().log_pool, sync_status_oid);
1820
1821 if (info.syncstopped) {
1822 call(new RGWRadosRemoveCR(store, obj));
1823 } else {
1824 status.state = rgw_bucket_shard_sync_info::StateFullSync;
1825 status.inc_marker.position = info.max_marker;
1826 map<string, bufferlist> attrs;
1827 status.encode_all_attrs(attrs);
1828 call(new RGWSimpleRadosWriteAttrsCR(sync_env->async_rados, store, obj, attrs));
1829 }
7c673cae
FG
1830 }
1831 return set_cr_done();
1832 }
1833 return 0;
1834 }
1835};
1836
1837RGWCoroutine *RGWRemoteBucketLog::init_sync_status_cr()
1838{
1839 return new RGWInitBucketShardSyncStatusCoroutine(&sync_env, bs, init_status);
1840}
1841
1842template <class T>
1843static void decode_attr(CephContext *cct, map<string, bufferlist>& attrs, const string& attr_name, T *val)
1844{
1845 map<string, bufferlist>::iterator iter = attrs.find(attr_name);
1846 if (iter == attrs.end()) {
1847 *val = T();
1848 return;
1849 }
1850
1851 bufferlist::iterator biter = iter->second.begin();
1852 try {
1853 ::decode(*val, biter);
1854 } catch (buffer::error& err) {
1855 ldout(cct, 0) << "ERROR: failed to decode attribute: " << attr_name << dendl;
1856 }
1857}
1858
1859void rgw_bucket_shard_sync_info::decode_from_attrs(CephContext *cct, map<string, bufferlist>& attrs)
1860{
1861 decode_attr(cct, attrs, "state", &state);
1862 decode_attr(cct, attrs, "full_marker", &full_marker);
1863 decode_attr(cct, attrs, "inc_marker", &inc_marker);
1864}
1865
1866void rgw_bucket_shard_sync_info::encode_all_attrs(map<string, bufferlist>& attrs)
1867{
1868 encode_state_attr(attrs);
1869 full_marker.encode_attr(attrs);
1870 inc_marker.encode_attr(attrs);
1871}
1872
1873void rgw_bucket_shard_sync_info::encode_state_attr(map<string, bufferlist>& attrs)
1874{
1875 ::encode(state, attrs["state"]);
1876}
1877
1878void rgw_bucket_shard_full_sync_marker::encode_attr(map<string, bufferlist>& attrs)
1879{
1880 ::encode(*this, attrs["full_marker"]);
1881}
1882
1883void rgw_bucket_shard_inc_sync_marker::encode_attr(map<string, bufferlist>& attrs)
1884{
1885 ::encode(*this, attrs["inc_marker"]);
1886}
1887
1888class RGWReadBucketSyncStatusCoroutine : public RGWCoroutine {
1889 RGWDataSyncEnv *sync_env;
1890 string oid;
1891 rgw_bucket_shard_sync_info *status;
1892
1893 map<string, bufferlist> attrs;
1894public:
1895 RGWReadBucketSyncStatusCoroutine(RGWDataSyncEnv *_sync_env,
1896 const rgw_bucket_shard& bs,
1897 rgw_bucket_shard_sync_info *_status)
1898 : RGWCoroutine(_sync_env->cct), sync_env(_sync_env),
1899 oid(RGWBucketSyncStatusManager::status_oid(sync_env->source_zone, bs)),
1900 status(_status) {}
1901 int operate() override;
1902};
1903
1904int RGWReadBucketSyncStatusCoroutine::operate()
1905{
1906 reenter(this) {
1907 yield call(new RGWSimpleRadosReadAttrsCR(sync_env->async_rados, sync_env->store,
1908 rgw_raw_obj(sync_env->store->get_zone_params().log_pool, oid),
1909 &attrs));
1910 if (retcode == -ENOENT) {
1911 *status = rgw_bucket_shard_sync_info();
1912 return set_cr_done();
1913 }
1914 if (retcode < 0) {
1915 ldout(sync_env->cct, 0) << "ERROR: failed to call fetch bucket shard info oid=" << oid << " ret=" << retcode << dendl;
1916 return set_cr_error(retcode);
1917 }
1918 status->decode_from_attrs(sync_env->cct, attrs);
1919 return set_cr_done();
1920 }
1921 return 0;
1922}
1923RGWCoroutine *RGWRemoteBucketLog::read_sync_status_cr(rgw_bucket_shard_sync_info *sync_status)
1924{
1925 return new RGWReadBucketSyncStatusCoroutine(&sync_env, bs, sync_status);
1926}
1927
1928RGWBucketSyncStatusManager::~RGWBucketSyncStatusManager() {
1929 for (map<int, RGWRemoteBucketLog *>::iterator iter = source_logs.begin(); iter != source_logs.end(); ++iter) {
1930 delete iter->second;
1931 }
1932 delete error_logger;
1933}
1934
1935
1936void rgw_bucket_entry_owner::decode_json(JSONObj *obj)
1937{
1938 JSONDecoder::decode_json("ID", id, obj);
1939 JSONDecoder::decode_json("DisplayName", display_name, obj);
1940}
1941
1942struct bucket_list_entry {
1943 bool delete_marker;
1944 rgw_obj_key key;
1945 bool is_latest;
1946 real_time mtime;
1947 string etag;
1948 uint64_t size;
1949 string storage_class;
1950 rgw_bucket_entry_owner owner;
1951 uint64_t versioned_epoch;
1952 string rgw_tag;
1953
1954 bucket_list_entry() : delete_marker(false), is_latest(false), size(0), versioned_epoch(0) {}
1955
1956 void decode_json(JSONObj *obj) {
1957 JSONDecoder::decode_json("IsDeleteMarker", delete_marker, obj);
1958 JSONDecoder::decode_json("Key", key.name, obj);
1959 JSONDecoder::decode_json("VersionId", key.instance, obj);
1960 JSONDecoder::decode_json("IsLatest", is_latest, obj);
1961 string mtime_str;
1962 JSONDecoder::decode_json("RgwxMtime", mtime_str, obj);
1963
1964 struct tm t;
1965 uint32_t nsec;
1966 if (parse_iso8601(mtime_str.c_str(), &t, &nsec)) {
1967 ceph_timespec ts;
1968 ts.tv_sec = (uint64_t)internal_timegm(&t);
1969 ts.tv_nsec = nsec;
1970 mtime = real_clock::from_ceph_timespec(ts);
1971 }
1972 JSONDecoder::decode_json("ETag", etag, obj);
1973 JSONDecoder::decode_json("Size", size, obj);
1974 JSONDecoder::decode_json("StorageClass", storage_class, obj);
1975 JSONDecoder::decode_json("Owner", owner, obj);
1976 JSONDecoder::decode_json("VersionedEpoch", versioned_epoch, obj);
1977 JSONDecoder::decode_json("RgwxTag", rgw_tag, obj);
1978 }
1979};
1980
1981struct bucket_list_result {
1982 string name;
1983 string prefix;
1984 string key_marker;
1985 string version_id_marker;
1986 int max_keys;
1987 bool is_truncated;
1988 list<bucket_list_entry> entries;
1989
1990 bucket_list_result() : max_keys(0), is_truncated(false) {}
1991
1992 void decode_json(JSONObj *obj) {
1993 JSONDecoder::decode_json("Name", name, obj);
1994 JSONDecoder::decode_json("Prefix", prefix, obj);
1995 JSONDecoder::decode_json("KeyMarker", key_marker, obj);
1996 JSONDecoder::decode_json("VersionIdMarker", version_id_marker, obj);
1997 JSONDecoder::decode_json("MaxKeys", max_keys, obj);
1998 JSONDecoder::decode_json("IsTruncated", is_truncated, obj);
1999 JSONDecoder::decode_json("Entries", entries, obj);
2000 }
2001};
2002
2003class RGWListBucketShardCR: public RGWCoroutine {
2004 RGWDataSyncEnv *sync_env;
2005 const rgw_bucket_shard& bs;
2006 const string instance_key;
2007 rgw_obj_key marker_position;
2008
2009 bucket_list_result *result;
2010
2011public:
2012 RGWListBucketShardCR(RGWDataSyncEnv *_sync_env, const rgw_bucket_shard& bs,
2013 rgw_obj_key& _marker_position, bucket_list_result *_result)
2014 : RGWCoroutine(_sync_env->cct), sync_env(_sync_env), bs(bs),
2015 instance_key(bs.get_key()), marker_position(_marker_position),
2016 result(_result) {}
2017
2018 int operate() override {
2019 reenter(this) {
2020 yield {
2021 rgw_http_param_pair pairs[] = { { "rgwx-bucket-instance", instance_key.c_str() },
2022 { "versions" , NULL },
2023 { "format" , "json" },
2024 { "objs-container" , "true" },
2025 { "key-marker" , marker_position.name.c_str() },
2026 { "version-id-marker" , marker_position.instance.c_str() },
2027 { NULL, NULL } };
2028 // don't include tenant in the url, it's already part of instance_key
2029 string p = string("/") + bs.bucket.name;
2030 call(new RGWReadRESTResourceCR<bucket_list_result>(sync_env->cct, sync_env->conn, sync_env->http_manager, p, pairs, result));
2031 }
2032 if (retcode < 0) {
2033 return set_cr_error(retcode);
2034 }
2035 return set_cr_done();
2036 }
2037 return 0;
2038 }
2039};
2040
2041class RGWListBucketIndexLogCR: public RGWCoroutine {
2042 RGWDataSyncEnv *sync_env;
2043 const string instance_key;
2044 string marker;
2045
2046 list<rgw_bi_log_entry> *result;
2047
2048public:
2049 RGWListBucketIndexLogCR(RGWDataSyncEnv *_sync_env, const rgw_bucket_shard& bs,
2050 string& _marker, list<rgw_bi_log_entry> *_result)
2051 : RGWCoroutine(_sync_env->cct), sync_env(_sync_env),
2052 instance_key(bs.get_key()), marker(_marker), result(_result) {}
2053
2054 int operate() override {
2055 reenter(this) {
2056 yield {
2057 rgw_http_param_pair pairs[] = { { "bucket-instance", instance_key.c_str() },
2058 { "format" , "json" },
2059 { "marker" , marker.c_str() },
2060 { "type", "bucket-index" },
2061 { NULL, NULL } };
2062
2063 call(new RGWReadRESTResourceCR<list<rgw_bi_log_entry> >(sync_env->cct, sync_env->conn, sync_env->http_manager, "/admin/log", pairs, result));
2064 }
2065 if (retcode < 0) {
2066 return set_cr_error(retcode);
2067 }
2068 return set_cr_done();
2069 }
2070 return 0;
2071 }
2072};
2073
2074#define BUCKET_SYNC_UPDATE_MARKER_WINDOW 10
2075
2076class RGWBucketFullSyncShardMarkerTrack : public RGWSyncShardMarkerTrack<rgw_obj_key, rgw_obj_key> {
2077 RGWDataSyncEnv *sync_env;
2078
2079 string marker_oid;
2080 rgw_bucket_shard_full_sync_marker sync_marker;
2081
2082public:
2083 RGWBucketFullSyncShardMarkerTrack(RGWDataSyncEnv *_sync_env,
2084 const string& _marker_oid,
2085 const rgw_bucket_shard_full_sync_marker& _marker) : RGWSyncShardMarkerTrack(BUCKET_SYNC_UPDATE_MARKER_WINDOW),
2086 sync_env(_sync_env),
2087 marker_oid(_marker_oid),
2088 sync_marker(_marker) {}
2089
2090 RGWCoroutine *store_marker(const rgw_obj_key& new_marker, uint64_t index_pos, const real_time& timestamp) override {
2091 sync_marker.position = new_marker;
2092 sync_marker.count = index_pos;
2093
2094 map<string, bufferlist> attrs;
2095 sync_marker.encode_attr(attrs);
2096
2097 RGWRados *store = sync_env->store;
2098
2099 ldout(sync_env->cct, 20) << __func__ << "(): updating marker marker_oid=" << marker_oid << " marker=" << new_marker << dendl;
2100 return new RGWSimpleRadosWriteAttrsCR(sync_env->async_rados, store,
2101 rgw_raw_obj(store->get_zone_params().log_pool, marker_oid),
2102 attrs);
2103 }
2104};
2105
2106class RGWBucketIncSyncShardMarkerTrack : public RGWSyncShardMarkerTrack<string, rgw_obj_key> {
2107 RGWDataSyncEnv *sync_env;
2108
2109 string marker_oid;
2110 rgw_bucket_shard_inc_sync_marker sync_marker;
2111
2112 map<rgw_obj_key, string> key_to_marker;
2113 map<string, rgw_obj_key> marker_to_key;
2114
2115 void handle_finish(const string& marker) override {
2116 map<string, rgw_obj_key>::iterator iter = marker_to_key.find(marker);
2117 if (iter == marker_to_key.end()) {
2118 return;
2119 }
2120 key_to_marker.erase(iter->second);
2121 reset_need_retry(iter->second);
2122 marker_to_key.erase(iter);
2123 }
2124
2125public:
2126 RGWBucketIncSyncShardMarkerTrack(RGWDataSyncEnv *_sync_env,
2127 const string& _marker_oid,
2128 const rgw_bucket_shard_inc_sync_marker& _marker) : RGWSyncShardMarkerTrack(BUCKET_SYNC_UPDATE_MARKER_WINDOW),
2129 sync_env(_sync_env),
2130 marker_oid(_marker_oid),
2131 sync_marker(_marker) {}
2132
2133 RGWCoroutine *store_marker(const string& new_marker, uint64_t index_pos, const real_time& timestamp) override {
2134 sync_marker.position = new_marker;
2135
2136 map<string, bufferlist> attrs;
2137 sync_marker.encode_attr(attrs);
2138
2139 RGWRados *store = sync_env->store;
2140
2141 ldout(sync_env->cct, 20) << __func__ << "(): updating marker marker_oid=" << marker_oid << " marker=" << new_marker << dendl;
2142 return new RGWSimpleRadosWriteAttrsCR(sync_env->async_rados,
2143 store,
2144 rgw_raw_obj(store->get_zone_params().log_pool, marker_oid),
2145 attrs);
2146 }
2147
2148 /*
2149 * create index from key -> <op, marker>, and from marker -> key
2150 * this is useful so that we can insure that we only have one
2151 * entry for any key that is used. This is needed when doing
2152 * incremenatl sync of data, and we don't want to run multiple
2153 * concurrent sync operations for the same bucket shard
2154 * Also, we should make sure that we don't run concurrent operations on the same key with
2155 * different ops.
2156 */
2157 bool index_key_to_marker(const rgw_obj_key& key, const string& marker) {
2158 if (key_to_marker.find(key) != key_to_marker.end()) {
2159 set_need_retry(key);
2160 return false;
2161 }
2162 key_to_marker[key] = marker;
2163 marker_to_key[marker] = key;
2164 return true;
2165 }
2166
2167 bool can_do_op(const rgw_obj_key& key) {
2168 return (key_to_marker.find(key) == key_to_marker.end());
2169 }
2170};
2171
2172template <class T, class K>
2173class RGWBucketSyncSingleEntryCR : public RGWCoroutine {
2174 RGWDataSyncEnv *sync_env;
2175
2176 RGWBucketInfo *bucket_info;
2177 const rgw_bucket_shard& bs;
2178
2179 rgw_obj_key key;
2180 bool versioned;
2181 uint64_t versioned_epoch;
2182 rgw_bucket_entry_owner owner;
2183 real_time timestamp;
2184 RGWModifyOp op;
2185 RGWPendingState op_state;
2186
2187 T entry_marker;
2188 RGWSyncShardMarkerTrack<T, K> *marker_tracker;
2189
2190 int sync_status;
2191
2192 stringstream error_ss;
2193
2194 RGWDataSyncDebugLogger logger;
2195
2196 bool error_injection;
2197
2198 RGWDataSyncModule *data_sync_module;
31f18b77
FG
2199
2200 rgw_zone_set zones_trace;
7c673cae
FG
2201
2202public:
2203 RGWBucketSyncSingleEntryCR(RGWDataSyncEnv *_sync_env,
2204 RGWBucketInfo *_bucket_info,
2205 const rgw_bucket_shard& bs,
2206 const rgw_obj_key& _key, bool _versioned, uint64_t _versioned_epoch,
2207 real_time& _timestamp,
2208 const rgw_bucket_entry_owner& _owner,
2209 RGWModifyOp _op, RGWPendingState _op_state,
31f18b77 2210 const T& _entry_marker, RGWSyncShardMarkerTrack<T, K> *_marker_tracker, rgw_zone_set& _zones_trace) : RGWCoroutine(_sync_env->cct),
7c673cae
FG
2211 sync_env(_sync_env),
2212 bucket_info(_bucket_info), bs(bs),
2213 key(_key), versioned(_versioned), versioned_epoch(_versioned_epoch),
2214 owner(_owner),
2215 timestamp(_timestamp), op(_op),
2216 op_state(_op_state),
2217 entry_marker(_entry_marker),
2218 marker_tracker(_marker_tracker),
31f18b77 2219 sync_status(0){
7c673cae
FG
2220 stringstream ss;
2221 ss << bucket_shard_str{bs} << "/" << key << "[" << versioned_epoch << "]";
2222 set_description() << "bucket sync single entry (source_zone=" << sync_env->source_zone << ") b=" << ss.str() << " log_entry=" << entry_marker << " op=" << (int)op << " op_state=" << (int)op_state;
2223 ldout(sync_env->cct, 20) << "bucket sync single entry (source_zone=" << sync_env->source_zone << ") b=" << ss.str() << " log_entry=" << entry_marker << " op=" << (int)op << " op_state=" << (int)op_state << dendl;
2224 set_status("init");
2225
2226 logger.init(sync_env, "Object", ss.str());
2227
2228 error_injection = (sync_env->cct->_conf->rgw_sync_data_inject_err_probability > 0);
2229
2230 data_sync_module = sync_env->sync_module->get_data_handler();
31f18b77
FG
2231
2232 zones_trace = _zones_trace;
2233 zones_trace.insert(sync_env->store->get_zone().id);
7c673cae
FG
2234 }
2235
2236 int operate() override {
2237 reenter(this) {
2238 /* skip entries that are not complete */
2239 if (op_state != CLS_RGW_STATE_COMPLETE) {
2240 goto done;
2241 }
2242 do {
2243 yield {
2244 marker_tracker->reset_need_retry(key);
2245 if (key.name.empty()) {
2246 /* shouldn't happen */
2247 set_status("skipping empty entry");
2248 ldout(sync_env->cct, 0) << "ERROR: " << __func__ << "(): entry with empty obj name, skipping" << dendl;
2249 goto done;
2250 }
2251 if (error_injection &&
2252 rand() % 10000 < cct->_conf->rgw_sync_data_inject_err_probability * 10000.0) {
2253 ldout(sync_env->cct, 0) << __func__ << ": injecting data sync error on key=" << key.name << dendl;
2254 retcode = -EIO;
2255 } else if (op == CLS_RGW_OP_ADD ||
2256 op == CLS_RGW_OP_LINK_OLH) {
2257 if (op == CLS_RGW_OP_ADD && !key.instance.empty() && key.instance != "null") {
2258 set_status("skipping entry");
2259 ldout(sync_env->cct, 10) << "bucket skipping sync obj: " << sync_env->source_zone << "/" << bucket_info->bucket << "/" << key << "[" << versioned_epoch << "]: versioned object will be synced on link_olh" << dendl;
2260 goto done;
2261
2262 }
2263 set_status("syncing obj");
2264 ldout(sync_env->cct, 5) << "bucket sync: sync obj: " << sync_env->source_zone << "/" << bucket_info->bucket << "/" << key << "[" << versioned_epoch << "]" << dendl;
2265 logger.log("fetch");
31f18b77 2266 call(data_sync_module->sync_object(sync_env, *bucket_info, key, versioned_epoch, &zones_trace));
7c673cae
FG
2267 } else if (op == CLS_RGW_OP_DEL || op == CLS_RGW_OP_UNLINK_INSTANCE) {
2268 set_status("removing obj");
2269 if (op == CLS_RGW_OP_UNLINK_INSTANCE) {
2270 versioned = true;
2271 }
2272 logger.log("remove");
31f18b77 2273 call(data_sync_module->remove_object(sync_env, *bucket_info, key, timestamp, versioned, versioned_epoch, &zones_trace));
7c673cae
FG
2274 } else if (op == CLS_RGW_OP_LINK_OLH_DM) {
2275 logger.log("creating delete marker");
2276 set_status("creating delete marker");
2277 ldout(sync_env->cct, 10) << "creating delete marker: obj: " << sync_env->source_zone << "/" << bucket_info->bucket << "/" << key << "[" << versioned_epoch << "]" << dendl;
31f18b77 2278 call(data_sync_module->create_delete_marker(sync_env, *bucket_info, key, timestamp, owner, versioned, versioned_epoch, &zones_trace));
7c673cae
FG
2279 }
2280 }
2281 } while (marker_tracker->need_retry(key));
2282 {
2283 stringstream ss;
2284 if (retcode >= 0) {
2285 ss << "done";
2286 } else {
2287 ss << "done, retcode=" << retcode;
2288 }
2289 logger.log(ss.str());
2290 }
2291
2292 if (retcode < 0 && retcode != -ENOENT) {
2293 set_status() << "failed to sync obj; retcode=" << retcode;
2294 ldout(sync_env->cct, 0) << "ERROR: failed to sync object: "
2295 << bucket_shard_str{bs} << "/" << key.name << dendl;
2296 error_ss << bucket_shard_str{bs} << "/" << key.name;
2297 sync_status = retcode;
2298 }
2299 if (!error_ss.str().empty()) {
2300 yield call(sync_env->error_logger->log_error_cr(sync_env->conn->get_remote_id(), "data", error_ss.str(), -retcode, "failed to sync object"));
2301 }
2302done:
2303 if (sync_status == 0) {
2304 /* update marker */
2305 set_status() << "calling marker_tracker->finish(" << entry_marker << ")";
2306 yield call(marker_tracker->finish(entry_marker));
2307 sync_status = retcode;
2308 }
2309 if (sync_status < 0) {
2310 return set_cr_error(sync_status);
2311 }
2312 return set_cr_done();
2313 }
2314 return 0;
2315 }
2316};
2317
2318#define BUCKET_SYNC_SPAWN_WINDOW 20
2319
2320class RGWBucketShardFullSyncCR : public RGWCoroutine {
2321 RGWDataSyncEnv *sync_env;
2322 const rgw_bucket_shard& bs;
2323 RGWBucketInfo *bucket_info;
2324 boost::intrusive_ptr<RGWContinuousLeaseCR> lease_cr;
2325 bucket_list_result list_result;
2326 list<bucket_list_entry>::iterator entries_iter;
2327 rgw_bucket_shard_full_sync_marker& full_marker;
2328 RGWBucketFullSyncShardMarkerTrack marker_tracker;
2329 rgw_obj_key list_marker;
2330 bucket_list_entry *entry{nullptr};
2331 RGWModifyOp op{CLS_RGW_OP_ADD};
2332
2333 int total_entries{0};
2334
2335 int sync_status{0};
2336
2337 const string& status_oid;
2338
2339 RGWDataSyncDebugLogger logger;
31f18b77 2340 rgw_zone_set zones_trace;
7c673cae
FG
2341public:
2342 RGWBucketShardFullSyncCR(RGWDataSyncEnv *_sync_env, const rgw_bucket_shard& bs,
2343 RGWBucketInfo *_bucket_info,
2344 const std::string& status_oid,
2345 RGWContinuousLeaseCR *lease_cr,
2346 rgw_bucket_shard_full_sync_marker& _full_marker)
2347 : RGWCoroutine(_sync_env->cct), sync_env(_sync_env), bs(bs),
2348 bucket_info(_bucket_info), lease_cr(lease_cr), full_marker(_full_marker),
2349 marker_tracker(sync_env, status_oid, full_marker),
2350 status_oid(status_oid) {
2351 logger.init(sync_env, "BucketFull", bs.get_key());
31f18b77 2352 zones_trace.insert(sync_env->source_zone);
7c673cae
FG
2353 }
2354
2355 int operate() override;
2356};
2357
2358int RGWBucketShardFullSyncCR::operate()
2359{
2360 int ret;
2361 reenter(this) {
2362 list_marker = full_marker.position;
2363
2364 total_entries = full_marker.count;
2365 do {
2366 if (!lease_cr->is_locked()) {
2367 drain_all();
2368 return set_cr_error(-ECANCELED);
2369 }
2370 set_status("listing remote bucket");
2371 ldout(sync_env->cct, 20) << __func__ << "(): listing bucket for full sync" << dendl;
2372 yield call(new RGWListBucketShardCR(sync_env, bs, list_marker,
2373 &list_result));
2374 if (retcode < 0 && retcode != -ENOENT) {
2375 set_status("failed bucket listing, going down");
2376 drain_all();
2377 return set_cr_error(retcode);
2378 }
2379 entries_iter = list_result.entries.begin();
2380 for (; entries_iter != list_result.entries.end(); ++entries_iter) {
2381 if (!lease_cr->is_locked()) {
2382 drain_all();
2383 return set_cr_error(-ECANCELED);
2384 }
2385 ldout(sync_env->cct, 20) << "[full sync] syncing object: "
2386 << bucket_shard_str{bs} << "/" << entries_iter->key << dendl;
2387 entry = &(*entries_iter);
2388 total_entries++;
2389 list_marker = entries_iter->key;
2390 if (!marker_tracker.start(entry->key, total_entries, real_time())) {
2391 ldout(sync_env->cct, 0) << "ERROR: cannot start syncing " << entry->key << ". Duplicate entry?" << dendl;
2392 } else {
2393 op = (entry->key.instance.empty() || entry->key.instance == "null" ? CLS_RGW_OP_ADD : CLS_RGW_OP_LINK_OLH);
7c673cae
FG
2394 using SyncCR = RGWBucketSyncSingleEntryCR<rgw_obj_key, rgw_obj_key>;
2395 yield spawn(new SyncCR(sync_env, bucket_info, bs, entry->key,
2396 false, /* versioned, only matters for object removal */
2397 entry->versioned_epoch, entry->mtime,
2398 entry->owner, op, CLS_RGW_STATE_COMPLETE,
31f18b77 2399 entry->key, &marker_tracker, zones_trace),
7c673cae
FG
2400 false);
2401 }
2402 while (num_spawned() > BUCKET_SYNC_SPAWN_WINDOW) {
2403 yield wait_for_child();
2404 bool again = true;
2405 while (again) {
2406 again = collect(&ret, nullptr);
2407 if (ret < 0) {
2408 ldout(sync_env->cct, 0) << "ERROR: a sync operation returned error" << dendl;
2409 sync_status = ret;
2410 /* we have reported this error */
2411 }
2412 }
2413 }
2414 }
2415 } while (list_result.is_truncated && sync_status == 0);
2416 set_status("done iterating over all objects");
2417 /* wait for all operations to complete */
2418 while (num_spawned()) {
2419 yield wait_for_child();
2420 bool again = true;
2421 while (again) {
2422 again = collect(&ret, nullptr);
2423 if (ret < 0) {
2424 ldout(sync_env->cct, 0) << "ERROR: a sync operation returned error" << dendl;
2425 sync_status = ret;
2426 /* we have reported this error */
2427 }
2428 }
2429 }
2430 if (!lease_cr->is_locked()) {
2431 return set_cr_error(-ECANCELED);
2432 }
2433 /* update sync state to incremental */
2434 if (sync_status == 0) {
2435 yield {
2436 rgw_bucket_shard_sync_info sync_status;
2437 sync_status.state = rgw_bucket_shard_sync_info::StateIncrementalSync;
2438 map<string, bufferlist> attrs;
2439 sync_status.encode_state_attr(attrs);
2440 RGWRados *store = sync_env->store;
2441 call(new RGWSimpleRadosWriteAttrsCR(sync_env->async_rados, store,
2442 rgw_raw_obj(store->get_zone_params().log_pool, status_oid),
2443 attrs));
2444 }
2445 } else {
2446 ldout(sync_env->cct, 0) << "ERROR: failure in sync, backing out (sync_status=" << sync_status<< ")" << dendl;
2447 }
2448 if (retcode < 0 && sync_status == 0) { /* actually tried to set incremental state and failed */
2449 ldout(sync_env->cct, 0) << "ERROR: failed to set sync state on bucket "
2450 << bucket_shard_str{bs} << " retcode=" << retcode << dendl;
2451 return set_cr_error(retcode);
2452 }
2453 if (sync_status < 0) {
2454 return set_cr_error(sync_status);
2455 }
2456 return set_cr_done();
2457 }
2458 return 0;
2459}
2460
2461class RGWBucketShardIncrementalSyncCR : public RGWCoroutine {
2462 RGWDataSyncEnv *sync_env;
2463 const rgw_bucket_shard& bs;
2464 RGWBucketInfo *bucket_info;
2465 boost::intrusive_ptr<RGWContinuousLeaseCR> lease_cr;
2466 list<rgw_bi_log_entry> list_result;
2467 list<rgw_bi_log_entry>::iterator entries_iter;
2468 map<pair<string, string>, pair<real_time, RGWModifyOp> > squash_map;
2469 rgw_bucket_shard_inc_sync_marker& inc_marker;
2470 rgw_obj_key key;
2471 rgw_bi_log_entry *entry{nullptr};
2472 RGWBucketIncSyncShardMarkerTrack marker_tracker;
2473 bool updated_status{false};
2474 const string& status_oid;
31f18b77 2475 const string& zone_id;
c07f9fc5 2476 ceph::real_time sync_modify_time;
7c673cae
FG
2477
2478 string cur_id;
2479
2480 RGWDataSyncDebugLogger logger;
2481
2482 int sync_status{0};
c07f9fc5 2483 bool syncstopped{false};
7c673cae
FG
2484
2485public:
2486 RGWBucketShardIncrementalSyncCR(RGWDataSyncEnv *_sync_env,
2487 const rgw_bucket_shard& bs,
2488 RGWBucketInfo *_bucket_info,
2489 const std::string& status_oid,
2490 RGWContinuousLeaseCR *lease_cr,
2491 rgw_bucket_shard_inc_sync_marker& _inc_marker)
2492 : RGWCoroutine(_sync_env->cct), sync_env(_sync_env), bs(bs),
2493 bucket_info(_bucket_info), lease_cr(lease_cr), inc_marker(_inc_marker),
31f18b77 2494 marker_tracker(sync_env, status_oid, inc_marker), status_oid(status_oid) , zone_id(_sync_env->store->get_zone().id){
7c673cae
FG
2495 set_description() << "bucket shard incremental sync bucket="
2496 << bucket_shard_str{bs};
2497 set_status("init");
2498 logger.init(sync_env, "BucketInc", bs.get_key());
2499 }
2500
2501 int operate() override;
2502};
2503
2504int RGWBucketShardIncrementalSyncCR::operate()
2505{
2506 int ret;
2507 reenter(this) {
2508 do {
2509 if (!lease_cr->is_locked()) {
2510 drain_all();
2511 return set_cr_error(-ECANCELED);
2512 }
c07f9fc5 2513 ldout(sync_env->cct, 20) << __func__ << "(): listing bilog for incremental sync" << inc_marker.position << dendl;
7c673cae
FG
2514 set_status() << "listing bilog; position=" << inc_marker.position;
2515 yield call(new RGWListBucketIndexLogCR(sync_env, bs, inc_marker.position,
2516 &list_result));
c07f9fc5 2517 if (retcode < 0 && retcode != -ENOENT ) {
7c673cae 2518 drain_all();
c07f9fc5
FG
2519 if (!syncstopped) {
2520 /* wait for all operations to complete */
2521 return set_cr_error(retcode);
2522 } else {
2523 /* no need to retry */
2524 break;
2525 }
7c673cae
FG
2526 }
2527 squash_map.clear();
2528 for (auto& e : list_result) {
c07f9fc5
FG
2529 if (e.op == RGWModifyOp::CLS_RGW_OP_SYNCSTOP && (sync_modify_time < e.timestamp)) {
2530 ldout(sync_env->cct, 20) << " syncstop on " << e.timestamp << dendl;
2531 sync_modify_time = e.timestamp;
2532 syncstopped = true;
2533 continue;
2534 }
2535 if (e.op == RGWModifyOp::CLS_RGW_OP_RESYNC && (sync_modify_time < e.timestamp)) {
2536 ldout(sync_env->cct, 20) << " resync on " << e.timestamp << dendl;
2537 sync_modify_time = e.timestamp;
2538 syncstopped = false;
2539 continue;
2540 }
7c673cae
FG
2541 if (e.state != CLS_RGW_STATE_COMPLETE) {
2542 continue;
2543 }
31f18b77
FG
2544 if (e.zones_trace.find(zone_id) != e.zones_trace.end()) {
2545 continue;
2546 }
7c673cae
FG
2547 auto& squash_entry = squash_map[make_pair(e.object, e.instance)];
2548 if (squash_entry.first <= e.timestamp) {
2549 squash_entry = make_pair<>(e.timestamp, e.op);
2550 }
2551 }
c07f9fc5 2552
7c673cae
FG
2553 entries_iter = list_result.begin();
2554 for (; entries_iter != list_result.end(); ++entries_iter) {
2555 if (!lease_cr->is_locked()) {
2556 drain_all();
2557 return set_cr_error(-ECANCELED);
2558 }
2559 entry = &(*entries_iter);
2560 {
2561 ssize_t p = entry->id.find('#'); /* entries might have explicit shard info in them, e.g., 6#00000000004.94.3 */
2562 if (p < 0) {
2563 cur_id = entry->id;
2564 } else {
2565 cur_id = entry->id.substr(p + 1);
2566 }
2567 }
2568 inc_marker.position = cur_id;
2569
c07f9fc5
FG
2570 if (entry->op == RGWModifyOp::CLS_RGW_OP_SYNCSTOP || entry->op == RGWModifyOp::CLS_RGW_OP_RESYNC) {
2571 ldout(sync_env->cct, 20) << "detected syncstop or resync on " << entries_iter->timestamp << " , skipping entry" << dendl;
2572 marker_tracker.try_update_high_marker(cur_id, 0, entry->timestamp);
2573 continue;
2574 }
2575
7c673cae
FG
2576 if (!key.set(rgw_obj_index_key{entry->object, entry->instance})) {
2577 set_status() << "parse_raw_oid() on " << entry->object << " returned false, skipping entry";
2578 ldout(sync_env->cct, 20) << "parse_raw_oid() on " << entry->object << " returned false, skipping entry" << dendl;
2579 marker_tracker.try_update_high_marker(cur_id, 0, entry->timestamp);
2580 continue;
2581 }
2582
2583 ldout(sync_env->cct, 20) << "parsed entry: id=" << cur_id << " iter->object=" << entry->object << " iter->instance=" << entry->instance << " name=" << key.name << " instance=" << key.instance << " ns=" << key.ns << dendl;
2584
2585 if (!key.ns.empty()) {
2586 set_status() << "skipping entry in namespace: " << entry->object;
2587 ldout(sync_env->cct, 20) << "skipping entry in namespace: " << entry->object << dendl;
2588 marker_tracker.try_update_high_marker(cur_id, 0, entry->timestamp);
2589 continue;
2590 }
2591
2592 set_status() << "got entry.id=" << cur_id << " key=" << key << " op=" << (int)entry->op;
2593 if (entry->op == CLS_RGW_OP_CANCEL) {
2594 set_status() << "canceled operation, skipping";
2595 ldout(sync_env->cct, 20) << "[inc sync] skipping object: "
2596 << bucket_shard_str{bs} << "/" << key << ": canceled operation" << dendl;
2597 marker_tracker.try_update_high_marker(cur_id, 0, entry->timestamp);
2598 continue;
2599 }
2600 if (entry->state != CLS_RGW_STATE_COMPLETE) {
2601 set_status() << "non-complete operation, skipping";
2602 ldout(sync_env->cct, 20) << "[inc sync] skipping object: "
2603 << bucket_shard_str{bs} << "/" << key << ": non-complete operation" << dendl;
2604 marker_tracker.try_update_high_marker(cur_id, 0, entry->timestamp);
2605 continue;
2606 }
31f18b77
FG
2607 if (entry->zones_trace.find(zone_id) != entry->zones_trace.end()) {
2608 set_status() << "redundant operation, skipping";
2609 ldout(sync_env->cct, 20) << "[inc sync] skipping object: "
2610 <<bucket_shard_str{bs} <<"/"<<key<<": redundant operation" << dendl;
2611 marker_tracker.try_update_high_marker(cur_id, 0, entry->timestamp);
2612 continue;
2613 }
7c673cae
FG
2614 if (make_pair<>(entry->timestamp, entry->op) != squash_map[make_pair(entry->object, entry->instance)]) {
2615 set_status() << "squashed operation, skipping";
2616 ldout(sync_env->cct, 20) << "[inc sync] skipping object: "
2617 << bucket_shard_str{bs} << "/" << key << ": squashed operation" << dendl;
2618 /* not updating high marker though */
2619 continue;
2620 }
2621 ldout(sync_env->cct, 20) << "[inc sync] syncing object: "
2622 << bucket_shard_str{bs} << "/" << key << dendl;
2623 updated_status = false;
2624 while (!marker_tracker.can_do_op(key)) {
2625 if (!updated_status) {
2626 set_status() << "can't do op, conflicting inflight operation";
2627 updated_status = true;
2628 }
2629 ldout(sync_env->cct, 5) << *this << ": [inc sync] can't do op on key=" << key << " need to wait for conflicting operation to complete" << dendl;
2630 yield wait_for_child();
2631 bool again = true;
2632 while (again) {
2633 again = collect(&ret, nullptr);
2634 if (ret < 0) {
2635 ldout(sync_env->cct, 0) << "ERROR: a child operation returned error (ret=" << ret << ")" << dendl;
2636 sync_status = ret;
2637 /* we have reported this error */
2638 }
2639 }
2640 }
2641 if (!marker_tracker.index_key_to_marker(key, cur_id)) {
2642 set_status() << "can't do op, sync already in progress for object";
2643 ldout(sync_env->cct, 20) << __func__ << ": skipping sync of entry: " << cur_id << ":" << key << " sync already in progress for object" << dendl;
2644 marker_tracker.try_update_high_marker(cur_id, 0, entry->timestamp);
2645 continue;
2646 }
2647 // yield {
2648 set_status() << "start object sync";
2649 if (!marker_tracker.start(cur_id, 0, entry->timestamp)) {
2650 ldout(sync_env->cct, 0) << "ERROR: cannot start syncing " << cur_id << ". Duplicate entry?" << dendl;
2651 } else {
2652 uint64_t versioned_epoch = 0;
2653 rgw_bucket_entry_owner owner(entry->owner, entry->owner_display_name);
2654 if (entry->ver.pool < 0) {
2655 versioned_epoch = entry->ver.epoch;
2656 }
2657 ldout(sync_env->cct, 20) << __func__ << "(): entry->timestamp=" << entry->timestamp << dendl;
2658 using SyncCR = RGWBucketSyncSingleEntryCR<string, rgw_obj_key>;
2659 spawn(new SyncCR(sync_env, bucket_info, bs, key,
2660 entry->is_versioned(), versioned_epoch,
2661 entry->timestamp, owner, entry->op, entry->state,
31f18b77 2662 cur_id, &marker_tracker, entry->zones_trace),
7c673cae
FG
2663 false);
2664 }
2665 // }
2666 while (num_spawned() > BUCKET_SYNC_SPAWN_WINDOW) {
2667 set_status() << "num_spawned() > spawn_window";
2668 yield wait_for_child();
2669 bool again = true;
2670 while (again) {
2671 again = collect(&ret, nullptr);
2672 if (ret < 0) {
2673 ldout(sync_env->cct, 0) << "ERROR: a sync operation returned error" << dendl;
2674 sync_status = ret;
2675 /* we have reported this error */
2676 }
2677 /* not waiting for child here */
2678 }
2679 }
2680 }
2681 } while (!list_result.empty() && sync_status == 0);
2682
c07f9fc5
FG
2683 if (syncstopped) {
2684 drain_all();
2685
2686 yield {
2687 const string& oid = RGWBucketSyncStatusManager::status_oid(sync_env->source_zone, bs);
2688 RGWRados *store = sync_env->store;
2689 call(new RGWRadosRemoveCR(store, rgw_raw_obj{store->get_zone_params().log_pool, oid}));
2690 }
2691 lease_cr->abort();
2692 return set_cr_done();
2693 }
2694
7c673cae
FG
2695 while (num_spawned()) {
2696 yield wait_for_child();
2697 bool again = true;
2698 while (again) {
2699 again = collect(&ret, nullptr);
2700 if (ret < 0) {
2701 ldout(sync_env->cct, 0) << "ERROR: a sync operation returned error" << dendl;
2702 sync_status = ret;
2703 /* we have reported this error */
2704 }
2705 /* not waiting for child here */
2706 }
2707 }
2708
2709 yield call(marker_tracker.flush());
2710 if (retcode < 0) {
2711 ldout(sync_env->cct, 0) << "ERROR: marker_tracker.flush() returned retcode=" << retcode << dendl;
2712 return set_cr_error(retcode);
2713 }
2714 if (sync_status < 0) {
2715 ldout(sync_env->cct, 0) << "ERROR: failure in sync, backing out (sync_status=" << sync_status<< ")" << dendl;
2716 }
2717
2718 /* wait for all operations to complete */
2719 drain_all();
2720
2721 if (sync_status < 0) {
2722 return set_cr_error(sync_status);
2723 }
2724
2725 return set_cr_done();
2726 }
2727 return 0;
2728}
2729
2730int RGWRunBucketSyncCoroutine::operate()
2731{
2732 reenter(this) {
2733 yield {
2734 set_status("acquiring sync lock");
2735 auto store = sync_env->store;
31f18b77
FG
2736 lease_cr.reset(new RGWContinuousLeaseCR(sync_env->async_rados, store,
2737 rgw_raw_obj(store->get_zone_params().log_pool, status_oid),
2738 "sync_lock",
2739 cct->_conf->rgw_sync_lease_period,
2740 this));
2741 lease_stack.reset(spawn(lease_cr.get(), false));
7c673cae
FG
2742 }
2743 while (!lease_cr->is_locked()) {
2744 if (lease_cr->is_done()) {
2745 ldout(cct, 5) << "lease cr failed, done early" << dendl;
2746 set_status("lease lock failed, early abort");
2747 return set_cr_error(lease_cr->get_ret_status());
2748 }
2749 set_sleeping(true);
2750 yield;
2751 }
2752
2753 yield call(new RGWReadBucketSyncStatusCoroutine(sync_env, bs, &sync_status));
2754 if (retcode < 0 && retcode != -ENOENT) {
2755 ldout(sync_env->cct, 0) << "ERROR: failed to read sync status for bucket="
2756 << bucket_shard_str{bs} << dendl;
2757 lease_cr->go_down();
2758 drain_all();
2759 return set_cr_error(retcode);
2760 }
2761
2762 ldout(sync_env->cct, 20) << __func__ << "(): sync status for bucket "
2763 << bucket_shard_str{bs} << ": " << sync_status.state << dendl;
2764
2765 yield call(new RGWGetBucketInstanceInfoCR(sync_env->async_rados, sync_env->store, bs.bucket, &bucket_info));
2766 if (retcode == -ENOENT) {
2767 /* bucket instance info has not been synced in yet, fetch it now */
2768 yield {
2769 ldout(sync_env->cct, 10) << "no local info for bucket "
2770 << bucket_str{bs.bucket} << ": fetching metadata" << dendl;
2771 string raw_key = string("bucket.instance:") + bs.bucket.get_key();
2772
2773 meta_sync_env.init(cct, sync_env->store, sync_env->store->rest_master_conn, sync_env->async_rados, sync_env->http_manager, sync_env->error_logger);
2774
2775 call(new RGWMetaSyncSingleEntryCR(&meta_sync_env, raw_key,
2776 string() /* no marker */,
2777 MDLOG_STATUS_COMPLETE,
2778 NULL /* no marker tracker */));
2779 }
2780 if (retcode < 0) {
2781 ldout(sync_env->cct, 0) << "ERROR: failed to fetch bucket instance info for " << bucket_str{bs.bucket} << dendl;
2782 lease_cr->go_down();
2783 drain_all();
2784 return set_cr_error(retcode);
2785 }
2786
2787 yield call(new RGWGetBucketInstanceInfoCR(sync_env->async_rados, sync_env->store, bs.bucket, &bucket_info));
2788 }
2789 if (retcode < 0) {
2790 ldout(sync_env->cct, 0) << "ERROR: failed to retrieve bucket info for bucket=" << bucket_str{bs.bucket} << dendl;
2791 lease_cr->go_down();
2792 drain_all();
2793 return set_cr_error(retcode);
2794 }
2795
2796 if (sync_status.state == rgw_bucket_shard_sync_info::StateInit) {
2797 yield call(new RGWInitBucketShardSyncStatusCoroutine(sync_env, bs, sync_status));
2798 if (retcode < 0) {
2799 ldout(sync_env->cct, 0) << "ERROR: init sync on " << bucket_shard_str{bs}
2800 << " failed, retcode=" << retcode << dendl;
2801 lease_cr->go_down();
2802 drain_all();
2803 return set_cr_error(retcode);
2804 }
2805 }
2806
2807 if (sync_status.state == rgw_bucket_shard_sync_info::StateFullSync) {
2808 yield call(new RGWBucketShardFullSyncCR(sync_env, bs, &bucket_info,
2809 status_oid, lease_cr.get(),
2810 sync_status.full_marker));
2811 if (retcode < 0) {
2812 ldout(sync_env->cct, 5) << "full sync on " << bucket_shard_str{bs}
2813 << " failed, retcode=" << retcode << dendl;
2814 lease_cr->go_down();
2815 drain_all();
2816 return set_cr_error(retcode);
2817 }
2818 sync_status.state = rgw_bucket_shard_sync_info::StateIncrementalSync;
2819 }
2820
2821 if (sync_status.state == rgw_bucket_shard_sync_info::StateIncrementalSync) {
2822 yield call(new RGWBucketShardIncrementalSyncCR(sync_env, bs, &bucket_info,
2823 status_oid, lease_cr.get(),
2824 sync_status.inc_marker));
2825 if (retcode < 0) {
2826 ldout(sync_env->cct, 5) << "incremental sync on " << bucket_shard_str{bs}
2827 << " failed, retcode=" << retcode << dendl;
2828 lease_cr->go_down();
2829 drain_all();
2830 return set_cr_error(retcode);
2831 }
2832 }
2833
2834 lease_cr->go_down();
2835 drain_all();
2836 return set_cr_done();
2837 }
2838
2839 return 0;
2840}
2841
2842RGWCoroutine *RGWRemoteBucketLog::run_sync_cr()
2843{
2844 return new RGWRunBucketSyncCoroutine(&sync_env, bs);
2845}
2846
2847int RGWBucketSyncStatusManager::init()
2848{
2849 conn = store->get_zone_conn_by_id(source_zone);
2850 if (!conn) {
2851 ldout(store->ctx(), 0) << "connection object to zone " << source_zone << " does not exist" << dendl;
2852 return -EINVAL;
2853 }
2854
2855 int ret = http_manager.set_threaded();
2856 if (ret < 0) {
2857 ldout(store->ctx(), 0) << "failed in http_manager.set_threaded() ret=" << ret << dendl;
2858 return ret;
2859 }
2860
2861
2862 const string key = bucket.get_key();
2863
2864 rgw_http_param_pair pairs[] = { { "key", key.c_str() },
2865 { NULL, NULL } };
2866
2867 string path = string("/admin/metadata/bucket.instance");
2868
2869 bucket_instance_meta_info result;
2870 ret = cr_mgr.run(new RGWReadRESTResourceCR<bucket_instance_meta_info>(store->ctx(), conn, &http_manager, path, pairs, &result));
2871 if (ret < 0) {
2872 ldout(store->ctx(), 0) << "ERROR: failed to fetch bucket metadata info from zone=" << source_zone << " path=" << path << " key=" << key << " ret=" << ret << dendl;
2873 return ret;
2874 }
2875
2876 RGWBucketInfo& bi = result.data.get_bucket_info();
2877 num_shards = bi.num_shards;
2878
2879 error_logger = new RGWSyncErrorLogger(store, RGW_SYNC_ERROR_LOG_SHARD_PREFIX, ERROR_LOGGER_SHARDS);
2880
2881 sync_module.reset(new RGWDefaultSyncModuleInstance());
2882
2883 int effective_num_shards = (num_shards ? num_shards : 1);
2884
2885 auto async_rados = store->get_async_rados();
2886
2887 for (int i = 0; i < effective_num_shards; i++) {
2888 RGWRemoteBucketLog *l = new RGWRemoteBucketLog(store, this, async_rados, &http_manager);
2889 ret = l->init(source_zone, conn, bucket, (num_shards ? i : -1), error_logger, sync_module);
2890 if (ret < 0) {
2891 ldout(store->ctx(), 0) << "ERROR: failed to initialize RGWRemoteBucketLog object" << dendl;
2892 return ret;
2893 }
2894 source_logs[i] = l;
2895 }
2896
2897 return 0;
2898}
2899
2900int RGWBucketSyncStatusManager::init_sync_status()
2901{
2902 list<RGWCoroutinesStack *> stacks;
2903
2904 for (map<int, RGWRemoteBucketLog *>::iterator iter = source_logs.begin(); iter != source_logs.end(); ++iter) {
2905 RGWCoroutinesStack *stack = new RGWCoroutinesStack(store->ctx(), &cr_mgr);
2906 RGWRemoteBucketLog *l = iter->second;
2907 stack->call(l->init_sync_status_cr());
2908
2909 stacks.push_back(stack);
2910 }
2911
2912 return cr_mgr.run(stacks);
2913}
2914
2915int RGWBucketSyncStatusManager::read_sync_status()
2916{
2917 list<RGWCoroutinesStack *> stacks;
2918
2919 for (map<int, RGWRemoteBucketLog *>::iterator iter = source_logs.begin(); iter != source_logs.end(); ++iter) {
2920 RGWCoroutinesStack *stack = new RGWCoroutinesStack(store->ctx(), &cr_mgr);
2921 RGWRemoteBucketLog *l = iter->second;
2922 stack->call(l->read_sync_status_cr(&sync_status[iter->first]));
2923
2924 stacks.push_back(stack);
2925 }
2926
2927 int ret = cr_mgr.run(stacks);
2928 if (ret < 0) {
2929 ldout(store->ctx(), 0) << "ERROR: failed to read sync status for "
2930 << bucket_str{bucket} << dendl;
2931 return ret;
2932 }
2933
2934 return 0;
2935}
2936
2937int RGWBucketSyncStatusManager::run()
2938{
2939 list<RGWCoroutinesStack *> stacks;
2940
2941 for (map<int, RGWRemoteBucketLog *>::iterator iter = source_logs.begin(); iter != source_logs.end(); ++iter) {
2942 RGWCoroutinesStack *stack = new RGWCoroutinesStack(store->ctx(), &cr_mgr);
2943 RGWRemoteBucketLog *l = iter->second;
2944 stack->call(l->run_sync_cr());
2945
2946 stacks.push_back(stack);
2947 }
2948
2949 int ret = cr_mgr.run(stacks);
2950 if (ret < 0) {
2951 ldout(store->ctx(), 0) << "ERROR: failed to read sync status for "
2952 << bucket_str{bucket} << dendl;
2953 return ret;
2954 }
2955
2956 return 0;
2957}
2958
2959string RGWBucketSyncStatusManager::status_oid(const string& source_zone,
2960 const rgw_bucket_shard& bs)
2961{
2962 return bucket_status_oid_prefix + "." + source_zone + ":" + bs.get_key();
2963}
2964
2965
2966// TODO: move into rgw_data_sync_trim.cc
2967#undef dout_prefix
2968#define dout_prefix (*_dout << "data trim: ")
2969
2970namespace {
2971
2972/// return the marker that it's safe to trim up to
2973const std::string& get_stable_marker(const rgw_data_sync_marker& m)
2974{
2975 return m.state == m.FullSync ? m.next_step_marker : m.marker;
2976}
2977
2978/// comparison operator for take_min_markers()
2979bool operator<(const rgw_data_sync_marker& lhs,
2980 const rgw_data_sync_marker& rhs)
2981{
2982 // sort by stable marker
2983 return get_stable_marker(lhs) < get_stable_marker(rhs);
2984}
2985
2986/// populate the container starting with 'dest' with the minimum stable marker
2987/// of each shard for all of the peers in [first, last)
2988template <typename IterIn, typename IterOut>
2989void take_min_markers(IterIn first, IterIn last, IterOut dest)
2990{
2991 if (first == last) {
2992 return;
2993 }
2994 // initialize markers with the first peer's
2995 auto m = dest;
2996 for (auto &shard : first->sync_markers) {
2997 *m = std::move(shard.second);
2998 ++m;
2999 }
3000 // for remaining peers, replace with smaller markers
3001 for (auto p = first + 1; p != last; ++p) {
3002 m = dest;
3003 for (auto &shard : p->sync_markers) {
3004 if (shard.second < *m) {
3005 *m = std::move(shard.second);
3006 }
3007 ++m;
3008 }
3009 }
3010}
3011
3012} // anonymous namespace
3013
3014class DataLogTrimCR : public RGWCoroutine {
3015 RGWRados *store;
3016 RGWHTTPManager *http;
3017 const int num_shards;
3018 const std::string& zone_id; //< my zone id
3019 std::vector<rgw_data_sync_status> peer_status; //< sync status for each peer
3020 std::vector<rgw_data_sync_marker> min_shard_markers; //< min marker per shard
3021 std::vector<std::string>& last_trim; //< last trimmed marker per shard
3022 int ret{0};
3023
3024 public:
3025 DataLogTrimCR(RGWRados *store, RGWHTTPManager *http,
3026 int num_shards, std::vector<std::string>& last_trim)
3027 : RGWCoroutine(store->ctx()), store(store), http(http),
3028 num_shards(num_shards),
3029 zone_id(store->get_zone().id),
3030 peer_status(store->zone_conn_map.size()),
3031 min_shard_markers(num_shards),
3032 last_trim(last_trim)
3033 {}
3034
3035 int operate() override;
3036};
3037
3038int DataLogTrimCR::operate()
3039{
3040 reenter(this) {
3041 ldout(cct, 10) << "fetching sync status for zone " << zone_id << dendl;
3042 set_status("fetching sync status");
3043 yield {
3044 // query data sync status from each sync peer
3045 rgw_http_param_pair params[] = {
3046 { "type", "data" },
3047 { "status", nullptr },
3048 { "source-zone", zone_id.c_str() },
3049 { nullptr, nullptr }
3050 };
3051
3052 auto p = peer_status.begin();
3053 for (auto& c : store->zone_conn_map) {
3054 ldout(cct, 20) << "query sync status from " << c.first << dendl;
3055 using StatusCR = RGWReadRESTResourceCR<rgw_data_sync_status>;
3056 spawn(new StatusCR(cct, c.second, http, "/admin/log/", params, &*p),
3057 false);
3058 ++p;
3059 }
3060 }
3061
3062 // must get a successful reply from all peers to consider trimming
3063 ret = 0;
3064 while (ret == 0 && num_spawned() > 0) {
3065 yield wait_for_child();
3066 collect_next(&ret);
3067 }
3068 drain_all();
3069
3070 if (ret < 0) {
3071 ldout(cct, 4) << "failed to fetch sync status from all peers" << dendl;
3072 return set_cr_error(ret);
3073 }
3074
3075 ldout(cct, 10) << "trimming log shards" << dendl;
3076 set_status("trimming log shards");
3077 yield {
3078 // determine the minimum marker for each shard
3079 take_min_markers(peer_status.begin(), peer_status.end(),
3080 min_shard_markers.begin());
3081
3082 for (int i = 0; i < num_shards; i++) {
3083 const auto& m = min_shard_markers[i];
3084 auto& stable = get_stable_marker(m);
3085 if (stable <= last_trim[i]) {
3086 continue;
3087 }
3088 ldout(cct, 10) << "trimming log shard " << i
3089 << " at marker=" << stable
3090 << " last_trim=" << last_trim[i] << dendl;
3091 using TrimCR = RGWSyncLogTrimCR;
3092 spawn(new TrimCR(store, store->data_log->get_oid(i),
3093 stable, &last_trim[i]),
3094 true);
3095 }
3096 }
3097 return set_cr_done();
3098 }
3099 return 0;
3100}
3101
3102class DataLogTrimPollCR : public RGWCoroutine {
3103 RGWRados *store;
3104 RGWHTTPManager *http;
3105 const int num_shards;
3106 const utime_t interval; //< polling interval
3107 const std::string lock_oid; //< use first data log shard for lock
3108 const std::string lock_cookie;
3109 std::vector<std::string> last_trim; //< last trimmed marker per shard
3110
3111 public:
3112 DataLogTrimPollCR(RGWRados *store, RGWHTTPManager *http,
3113 int num_shards, utime_t interval)
3114 : RGWCoroutine(store->ctx()), store(store), http(http),
3115 num_shards(num_shards), interval(interval),
3116 lock_oid(store->data_log->get_oid(0)),
3117 lock_cookie(RGWSimpleRadosLockCR::gen_random_cookie(cct)),
3118 last_trim(num_shards)
3119 {}
3120
3121 int operate() override;
3122};
3123
3124int DataLogTrimPollCR::operate()
3125{
3126 reenter(this) {
3127 for (;;) {
3128 set_status("sleeping");
3129 wait(interval);
3130
3131 // request a 'data_trim' lock that covers the entire wait interval to
3132 // prevent other gateways from attempting to trim for the duration
3133 set_status("acquiring trim lock");
3134 yield call(new RGWSimpleRadosLockCR(store->get_async_rados(), store,
3135 rgw_raw_obj(store->get_zone_params().log_pool, lock_oid),
3136 "data_trim", lock_cookie,
3137 interval.sec()));
3138 if (retcode < 0) {
3139 // if the lock is already held, go back to sleep and try again later
3140 ldout(cct, 4) << "failed to lock " << lock_oid << ", trying again in "
3141 << interval.sec() << "s" << dendl;
3142 continue;
3143 }
3144
3145 set_status("trimming");
3146 yield call(new DataLogTrimCR(store, http, num_shards, last_trim));
3147
3148 // note that the lock is not released. this is intentional, as it avoids
3149 // duplicating this work in other gateways
3150 }
3151 }
3152 return 0;
3153}
3154
3155RGWCoroutine* create_data_log_trim_cr(RGWRados *store,
3156 RGWHTTPManager *http,
3157 int num_shards, utime_t interval)
3158{
3159 return new DataLogTrimPollCR(store, http, num_shards, interval);
3160}