repo
stringlengths
1
152
file
stringlengths
15
205
code
stringlengths
0
41.6M
file_length
int64
0
41.6M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
90 values
null
ceph-main/src/test/librbd/journal/test_Replay.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_fixture.h" #include "test/librbd/test_support.h" #include "cls/rbd/cls_rbd_types.h" #include "cls/journal/cls_journal_types.h" #include "cls/journal/cls_journal_client.h" #include "journal/Journaler.h" #include "librbd/ExclusiveLock.h" #include "librbd/ImageCtx.h" #include "librbd/ImageState.h" #include "librbd/ImageWatcher.h" #include "librbd/internal.h" #include "librbd/Journal.h" #include "librbd/Operations.h" #include "librbd/api/Io.h" #include "librbd/api/Snapshot.h" #include "librbd/io/AioCompletion.h" #include "librbd/io/ImageDispatchSpec.h" #include "librbd/io/ImageRequest.h" #include "librbd/io/ReadResult.h" #include "librbd/journal/Types.h" void register_test_journal_replay() { } namespace librbd { namespace journal { class TestJournalReplay : public TestFixture { public: int when_acquired_lock(librbd::ImageCtx *ictx) { C_SaferCond lock_ctx; { std::unique_lock owner_locker{ictx->owner_lock}; ictx->exclusive_lock->acquire_lock(&lock_ctx); } int r = lock_ctx.wait(); if (r < 0) { return r; } C_SaferCond refresh_ctx; ictx->state->refresh(&refresh_ctx); return refresh_ctx.wait(); } template<typename T> void inject_into_journal(librbd::ImageCtx *ictx, T event) { C_SaferCond ctx; librbd::journal::EventEntry event_entry(event); { std::shared_lock owner_locker{ictx->owner_lock}; uint64_t tid = ictx->journal->append_io_event(std::move(event_entry),0, 0, true, 0); ictx->journal->wait_event(tid, &ctx); } ASSERT_EQ(0, ctx.wait()); } void get_journal_commit_position(librbd::ImageCtx *ictx, int64_t *tag, int64_t *entry) { const std::string client_id = ""; std::string journal_id = ictx->id; C_SaferCond close_cond; ictx->journal->close(&close_cond); ASSERT_EQ(0, close_cond.wait()); ictx->journal->put(); ictx->journal = nullptr; C_SaferCond cond; uint64_t minimum_set; uint64_t active_set; std::set<cls::journal::Client> registered_clients; std::string oid = ::journal::Journaler::header_oid(journal_id); cls::journal::client::get_mutable_metadata(ictx->md_ctx, oid, &minimum_set, &active_set, &registered_clients, &cond); ASSERT_EQ(0, cond.wait()); std::set<cls::journal::Client>::const_iterator c; for (c = registered_clients.begin(); c != registered_clients.end(); ++c) { if (c->id == client_id) { break; } } if (c == registered_clients.end() || c->commit_position.object_positions.empty()) { *tag = 0; *entry = -1; } else { const cls::journal::ObjectPosition &object_position = *c->commit_position.object_positions.begin(); *tag = object_position.tag_tid; *entry = object_position.entry_tid; } C_SaferCond open_cond; ictx->journal = new librbd::Journal<>(*ictx); ictx->journal->open(&open_cond); ASSERT_EQ(0, open_cond.wait()); } }; TEST_F(TestJournalReplay, AioDiscardEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); // write to the image w/o using the journal librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ictx->features &= ~RBD_FEATURE_JOURNALING; std::string payload(4096, '1'); bufferlist payload_bl; payload_bl.append(payload); auto aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_write(*ictx, aio_comp, 0, payload.size(), std::move(payload_bl), 0, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_flush(*ictx, aio_comp, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); std::string read_payload(4096, '\0'); librbd::io::ReadResult read_result{&read_payload[0], read_payload.size()}; aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_read(*ictx, aio_comp, 0, read_payload.size(), librbd::io::ReadResult{read_result}, 0, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); ASSERT_EQ(payload, read_payload); close_image(ictx); ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject a discard operation into the journal inject_into_journal(ictx, librbd::journal::AioDiscardEvent( 0, payload.size(), ictx->discard_granularity_bytes)); close_image(ictx); // re-open the journal so that it replays the new entry ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_read(*ictx, aio_comp, 0, read_payload.size(), librbd::io::ReadResult{read_result}, 0, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); if (ictx->discard_granularity_bytes > 0) { ASSERT_EQ(payload, read_payload); } else { ASSERT_EQ(std::string(read_payload.size(), '\0'), read_payload); } // check the commit position is properly updated int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 1, current_tag); ASSERT_EQ(0, current_entry); // replay several envents and check the commit position inject_into_journal(ictx, librbd::journal::AioDiscardEvent( 0, payload.size(), ictx->discard_granularity_bytes)); inject_into_journal(ictx, librbd::journal::AioDiscardEvent( 0, payload.size(), ictx->discard_granularity_bytes)); close_image(ictx); ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 2, current_tag); ASSERT_EQ(1, current_entry); // verify lock ordering constraints aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_discard(*ictx, aio_comp, 0, read_payload.size(), ictx->discard_granularity_bytes, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); } TEST_F(TestJournalReplay, AioWriteEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject a write operation into the journal std::string payload(4096, '1'); bufferlist payload_bl; payload_bl.append(payload); inject_into_journal(ictx, librbd::journal::AioWriteEvent(0, payload.size(), payload_bl)); close_image(ictx); // re-open the journal so that it replays the new entry ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); std::string read_payload(4096, '\0'); librbd::io::ReadResult read_result{&read_payload[0], read_payload.size()}; auto aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_read(*ictx, aio_comp, 0, read_payload.size(), std::move(read_result), 0, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); ASSERT_EQ(payload, read_payload); // check the commit position is properly updated int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 1, current_tag); ASSERT_EQ(0, current_entry); // replay several events and check the commit position inject_into_journal(ictx, librbd::journal::AioWriteEvent(0, payload.size(), payload_bl)); inject_into_journal(ictx, librbd::journal::AioWriteEvent(0, payload.size(), payload_bl)); close_image(ictx); ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 2, current_tag); ASSERT_EQ(1, current_entry); // verify lock ordering constraints aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_write(*ictx, aio_comp, 0, payload.size(), bufferlist{payload_bl}, 0, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); } TEST_F(TestJournalReplay, AioFlushEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject a flush operation into the journal inject_into_journal(ictx, librbd::journal::AioFlushEvent()); close_image(ictx); // re-open the journal so that it replays the new entry ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); // check the commit position is properly updated int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 1, current_tag); ASSERT_EQ(0, current_entry); // replay several events and check the commit position inject_into_journal(ictx, librbd::journal::AioFlushEvent()); inject_into_journal(ictx, librbd::journal::AioFlushEvent()); close_image(ictx); ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 2, current_tag); ASSERT_EQ(1, current_entry); // verify lock ordering constraints auto aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_flush(*ictx, aio_comp, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); } TEST_F(TestJournalReplay, SnapCreate) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject snapshot ops into journal inject_into_journal(ictx, librbd::journal::SnapCreateEvent(1, cls::rbd::UserSnapshotNamespace(), "snap")); inject_into_journal(ictx, librbd::journal::OpFinishEvent(1, 0)); close_image(ictx); // replay journal ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 1, current_tag); ASSERT_EQ(1, current_entry); { std::shared_lock image_locker{ictx->image_lock}; ASSERT_NE(CEPH_NOSNAP, ictx->get_snap_id(cls::rbd::UserSnapshotNamespace(), "snap")); } // verify lock ordering constraints librbd::NoOpProgressContext no_op_progress; ASSERT_EQ(0, ictx->operations->snap_create(cls::rbd::UserSnapshotNamespace(), "snap2", 0, no_op_progress)); } TEST_F(TestJournalReplay, SnapProtect) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); librbd::NoOpProgressContext no_op_progress; ASSERT_EQ(0, ictx->operations->snap_create(cls::rbd::UserSnapshotNamespace(), "snap", 0, no_op_progress)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject snapshot ops into journal inject_into_journal(ictx, librbd::journal::SnapProtectEvent(1, cls::rbd::UserSnapshotNamespace(), "snap")); inject_into_journal(ictx, librbd::journal::OpFinishEvent(1, 0)); close_image(ictx); // replay journal ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag, current_tag); ASSERT_EQ(initial_entry + 2, current_entry); bool is_protected; ASSERT_EQ(0, librbd::api::Snapshot<>::is_protected(ictx, "snap", &is_protected)); ASSERT_TRUE(is_protected); // verify lock ordering constraints ASSERT_EQ(0, ictx->operations->snap_create(cls::rbd::UserSnapshotNamespace(), "snap2", 0, no_op_progress)); ASSERT_EQ(0, ictx->operations->snap_protect(cls::rbd::UserSnapshotNamespace(), "snap2")); } TEST_F(TestJournalReplay, SnapUnprotect) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); librbd::NoOpProgressContext no_op_progress; ASSERT_EQ(0, ictx->operations->snap_create(cls::rbd::UserSnapshotNamespace(), "snap", 0, no_op_progress)); uint64_t snap_id; { std::shared_lock image_locker{ictx->image_lock}; snap_id = ictx->get_snap_id(cls::rbd::UserSnapshotNamespace(), "snap"); ASSERT_NE(CEPH_NOSNAP, snap_id); } ASSERT_EQ(0, ictx->operations->snap_protect(cls::rbd::UserSnapshotNamespace(), "snap")); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject snapshot ops into journal inject_into_journal(ictx, librbd::journal::SnapUnprotectEvent(1, cls::rbd::UserSnapshotNamespace(), "snap")); inject_into_journal(ictx, librbd::journal::OpFinishEvent(1, 0)); close_image(ictx); // replay journal ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag, current_tag); ASSERT_EQ(initial_entry + 2, current_entry); bool is_protected; ASSERT_EQ(0, librbd::api::Snapshot<>::is_protected(ictx, "snap", &is_protected)); ASSERT_FALSE(is_protected); // verify lock ordering constraints ASSERT_EQ(0, ictx->operations->snap_create(cls::rbd::UserSnapshotNamespace(), "snap2", 0, no_op_progress)); ASSERT_EQ(0, ictx->operations->snap_protect(cls::rbd::UserSnapshotNamespace(), "snap2")); ASSERT_EQ(0, ictx->operations->snap_unprotect(cls::rbd::UserSnapshotNamespace(), "snap2")); } TEST_F(TestJournalReplay, SnapRename) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); librbd::NoOpProgressContext no_op_progress; ASSERT_EQ(0, ictx->operations->snap_create(cls::rbd::UserSnapshotNamespace(), "snap", 0, no_op_progress)); uint64_t snap_id; { std::shared_lock image_locker{ictx->image_lock}; snap_id = ictx->get_snap_id(cls::rbd::UserSnapshotNamespace(), "snap"); ASSERT_NE(CEPH_NOSNAP, snap_id); } // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject snapshot ops into journal inject_into_journal(ictx, librbd::journal::SnapRenameEvent(1, snap_id, "snap", "snap2")); inject_into_journal(ictx, librbd::journal::OpFinishEvent(1, 0)); close_image(ictx); // replay journal ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag, current_tag); ASSERT_EQ(initial_entry + 2, current_entry); ASSERT_EQ(0, ictx->state->refresh()); { std::shared_lock image_locker{ictx->image_lock}; snap_id = ictx->get_snap_id(cls::rbd::UserSnapshotNamespace(), "snap2"); ASSERT_NE(CEPH_NOSNAP, snap_id); } // verify lock ordering constraints ASSERT_EQ(0, ictx->operations->snap_rename("snap2", "snap3")); } TEST_F(TestJournalReplay, SnapRollback) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); librbd::NoOpProgressContext no_op_progress; ASSERT_EQ(0, ictx->operations->snap_create(cls::rbd::UserSnapshotNamespace(), "snap", 0, no_op_progress)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject snapshot ops into journal inject_into_journal(ictx, librbd::journal::SnapRollbackEvent(1, cls::rbd::UserSnapshotNamespace(), "snap")); inject_into_journal(ictx, librbd::journal::OpFinishEvent(1, 0)); close_image(ictx); // replay journal ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag, current_tag); ASSERT_EQ(initial_entry + 2, current_entry); // verify lock ordering constraints ASSERT_EQ(0, ictx->operations->snap_rollback(cls::rbd::UserSnapshotNamespace(), "snap", no_op_progress)); } TEST_F(TestJournalReplay, SnapRemove) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); librbd::NoOpProgressContext no_op_progress; ASSERT_EQ(0, ictx->operations->snap_create(cls::rbd::UserSnapshotNamespace(), "snap", 0, no_op_progress)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject snapshot ops into journal inject_into_journal(ictx, librbd::journal::SnapRemoveEvent(1, cls::rbd::UserSnapshotNamespace(), "snap")); inject_into_journal(ictx, librbd::journal::OpFinishEvent(1, 0)); close_image(ictx); // replay journal ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag, current_tag); ASSERT_EQ(initial_entry + 2, current_entry); { std::shared_lock image_locker{ictx->image_lock}; uint64_t snap_id = ictx->get_snap_id(cls::rbd::UserSnapshotNamespace(), "snap"); ASSERT_EQ(CEPH_NOSNAP, snap_id); } // verify lock ordering constraints ASSERT_EQ(0, ictx->operations->snap_create(cls::rbd::UserSnapshotNamespace(), "snap", 0, no_op_progress)); ASSERT_EQ(0, ictx->operations->snap_remove(cls::rbd::UserSnapshotNamespace(), "snap")); } TEST_F(TestJournalReplay, Rename) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject snapshot ops into journal std::string new_image_name(get_temp_image_name()); inject_into_journal(ictx, librbd::journal::RenameEvent(1, new_image_name)); inject_into_journal(ictx, librbd::journal::OpFinishEvent(1, 0)); close_image(ictx); // replay journal ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 1, current_tag); ASSERT_EQ(1, current_entry); // verify lock ordering constraints librbd::RBD rbd; ASSERT_EQ(0, rbd.rename(m_ioctx, new_image_name.c_str(), m_image_name.c_str())); } TEST_F(TestJournalReplay, Resize) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject snapshot ops into journal inject_into_journal(ictx, librbd::journal::ResizeEvent(1, 16)); inject_into_journal(ictx, librbd::journal::OpFinishEvent(1, 0)); close_image(ictx); // replay journal ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 1, current_tag); ASSERT_EQ(1, current_entry); // verify lock ordering constraints librbd::NoOpProgressContext no_op_progress; ASSERT_EQ(0, ictx->operations->resize(0, true, no_op_progress)); } TEST_F(TestJournalReplay, Flatten) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING | RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); librbd::NoOpProgressContext no_op_progress; ASSERT_EQ(0, ictx->operations->snap_create(cls::rbd::UserSnapshotNamespace(), "snap", 0, no_op_progress)); ASSERT_EQ(0, ictx->operations->snap_protect(cls::rbd::UserSnapshotNamespace(), "snap")); std::string clone_name = get_temp_image_name(); int order = ictx->order; ASSERT_EQ(0, librbd::clone(m_ioctx, m_image_name.c_str(), "snap", m_ioctx, clone_name.c_str(), ictx->features, &order, 0, 0)); librbd::ImageCtx *ictx2; ASSERT_EQ(0, open_image(clone_name, &ictx2)); ASSERT_EQ(0, when_acquired_lock(ictx2)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx2, &initial_tag, &initial_entry); // inject snapshot ops into journal inject_into_journal(ictx2, librbd::journal::FlattenEvent(1)); inject_into_journal(ictx2, librbd::journal::OpFinishEvent(1, 0)); close_image(ictx2); // replay journal ASSERT_EQ(0, open_image(clone_name, &ictx2)); ASSERT_EQ(0, when_acquired_lock(ictx2)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx2, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 1, current_tag); ASSERT_EQ(1, current_entry); ASSERT_EQ(0, ictx->operations->snap_unprotect(cls::rbd::UserSnapshotNamespace(), "snap")); // verify lock ordering constraints librbd::NoOpProgressContext no_op; ASSERT_EQ(-EINVAL, ictx2->operations->flatten(no_op)); } TEST_F(TestJournalReplay, UpdateFeatures) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); uint64_t features = RBD_FEATURE_OBJECT_MAP | RBD_FEATURE_FAST_DIFF; bool enabled = !ictx->test_features(features); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject update_features op into journal inject_into_journal(ictx, librbd::journal::UpdateFeaturesEvent(1, features, enabled)); close_image(ictx); // replay journal ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 1, current_tag); ASSERT_EQ(0, current_entry); ASSERT_EQ(enabled, ictx->test_features(features)); // verify lock ordering constraints ASSERT_EQ(0, ictx->operations->update_features(features, !enabled)); } TEST_F(TestJournalReplay, MetadataSet) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject metadata_set op into journal inject_into_journal(ictx, librbd::journal::MetadataSetEvent( 1, "conf_rbd_mirroring_replay_delay", "9876")); inject_into_journal(ictx, librbd::journal::OpFinishEvent(1, 0)); close_image(ictx); // replay journal ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 1, current_tag); ASSERT_EQ(1, current_entry); ASSERT_EQ(9876U, ictx->mirroring_replay_delay); std::string value; ASSERT_EQ(0, librbd::metadata_get(ictx, "conf_rbd_mirroring_replay_delay", &value)); ASSERT_EQ("9876", value); // verify lock ordering constraints ASSERT_EQ(0, ictx->operations->metadata_set("key2", "value")); } TEST_F(TestJournalReplay, MetadataRemove) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); ASSERT_EQ(0, ictx->operations->metadata_set( "conf_rbd_mirroring_replay_delay", "9876")); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); // inject metadata_remove op into journal inject_into_journal(ictx, librbd::journal::MetadataRemoveEvent( 1, "conf_rbd_mirroring_replay_delay")); inject_into_journal(ictx, librbd::journal::OpFinishEvent(1, 0)); close_image(ictx); // replay journal ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag, current_tag); ASSERT_EQ(initial_entry + 2, current_entry); ASSERT_EQ(0U, ictx->mirroring_replay_delay); std::string value; ASSERT_EQ(-ENOENT, librbd::metadata_get(ictx, "conf_rbd_mirroring_replay_delay", &value)); // verify lock ordering constraints ASSERT_EQ(0, ictx->operations->metadata_set("key", "value")); ASSERT_EQ(0, ictx->operations->metadata_remove("key")); } TEST_F(TestJournalReplay, ObjectPosition) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, when_acquired_lock(ictx)); // get current commit position int64_t initial_tag; int64_t initial_entry; get_journal_commit_position(ictx, &initial_tag, &initial_entry); std::string payload(4096, '1'); bufferlist payload_bl; payload_bl.append(payload); auto aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_write(*ictx, aio_comp, 0, payload.size(), bufferlist{payload_bl}, 0, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_flush(*ictx, aio_comp, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); // check the commit position updated int64_t current_tag; int64_t current_entry; get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 1, current_tag); ASSERT_EQ(1, current_entry); // write again aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_write(*ictx, aio_comp, 0, payload.size(), bufferlist{payload_bl}, 0, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); aio_comp = new librbd::io::AioCompletion(); api::Io<>::aio_flush(*ictx, aio_comp, true); ASSERT_EQ(0, aio_comp->wait_for_complete()); aio_comp->release(); // user flush requests are ignored when journaling + cache are enabled C_SaferCond flush_ctx; aio_comp = librbd::io::AioCompletion::create_and_start( &flush_ctx, ictx, librbd::io::AIO_TYPE_FLUSH); auto req = librbd::io::ImageDispatchSpec::create_flush( *ictx, librbd::io::IMAGE_DISPATCH_LAYER_INTERNAL_START, aio_comp, librbd::io::FLUSH_SOURCE_INTERNAL, {}); req->send(); ASSERT_EQ(0, flush_ctx.wait()); // check the commit position updated get_journal_commit_position(ictx, &current_tag, &current_entry); ASSERT_EQ(initial_tag + 1, current_tag); ASSERT_EQ(3, current_entry); } } // namespace journal } // namespace librbd
28,942
31.630214
98
cc
null
ceph-main/src/test/librbd/journal/test_mock_OpenRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/journal/mock/MockJournaler.h" #include "common/ceph_mutex.h" #include "cls/journal/cls_journal_types.h" #include "librbd/journal/OpenRequest.h" #include "librbd/journal/Types.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { explicit MockTestImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace journal { template <> struct TypeTraits<MockTestImageCtx> { typedef ::journal::MockJournaler Journaler; }; } // namespace journal } // namespace librbd // template definitions #include "librbd/journal/OpenRequest.cc" template class librbd::journal::OpenRequest<librbd::MockTestImageCtx>; namespace librbd { namespace journal { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Return; using ::testing::SetArgPointee; using ::testing::WithArg; class TestMockJournalOpenRequest : public TestMockFixture { public: typedef OpenRequest<MockTestImageCtx> MockOpenRequest; TestMockJournalOpenRequest() = default; void expect_init_journaler(::journal::MockJournaler &mock_journaler, int r) { EXPECT_CALL(mock_journaler, init(_)) .WillOnce(CompleteContext(r, static_cast<asio::ContextWQ*>(NULL))); } void expect_get_journaler_cached_client(::journal::MockJournaler &mock_journaler, int r) { journal::ImageClientMeta image_client_meta; image_client_meta.tag_class = 345; journal::ClientData client_data; client_data.client_meta = image_client_meta; cls::journal::Client client; encode(client_data, client.data); EXPECT_CALL(mock_journaler, get_cached_client("", _)) .WillOnce(DoAll(SetArgPointee<1>(client), Return(r))); } void expect_get_journaler_tags(MockImageCtx &mock_image_ctx, ::journal::MockJournaler &mock_journaler, int r) { journal::TagData tag_data; tag_data.mirror_uuid = "remote mirror"; bufferlist tag_data_bl; encode(tag_data, tag_data_bl); ::journal::Journaler::Tags tags = {{0, 345, {}}, {1, 345, tag_data_bl}}; EXPECT_CALL(mock_journaler, get_tags(345, _, _)) .WillOnce(DoAll(SetArgPointee<1>(tags), WithArg<2>(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)))); } ceph::mutex m_lock = ceph::make_mutex("m_lock"); ImageClientMeta m_client_meta; uint64_t m_tag_tid = 0; TagData m_tag_data; }; TEST_F(TestMockJournalOpenRequest, Success) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); ::journal::MockJournaler mock_journaler; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_init_journaler(mock_journaler, 0); expect_get_journaler_cached_client(mock_journaler, 0); expect_get_journaler_tags(mock_image_ctx, mock_journaler, 0); C_SaferCond ctx; auto req = MockOpenRequest::create(&mock_image_ctx, &mock_journaler, &m_lock, &m_client_meta, &m_tag_tid, &m_tag_data, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); ASSERT_EQ(345U, m_client_meta.tag_class); ASSERT_EQ(1U, m_tag_tid); ASSERT_EQ("remote mirror", m_tag_data.mirror_uuid); } TEST_F(TestMockJournalOpenRequest, InitError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); ::journal::MockJournaler mock_journaler; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_init_journaler(mock_journaler, -ENOENT); C_SaferCond ctx; auto req = MockOpenRequest::create(&mock_image_ctx, &mock_journaler, &m_lock, &m_client_meta, &m_tag_tid, &m_tag_data, &ctx); req->send(); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockJournalOpenRequest, GetCachedClientError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); ::journal::MockJournaler mock_journaler; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_init_journaler(mock_journaler, 0); expect_get_journaler_cached_client(mock_journaler, -EINVAL); C_SaferCond ctx; auto req = MockOpenRequest::create(&mock_image_ctx, &mock_journaler, &m_lock, &m_client_meta, &m_tag_tid, &m_tag_data, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockJournalOpenRequest, GetTagsError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); ::journal::MockJournaler mock_journaler; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_init_journaler(mock_journaler, 0); expect_get_journaler_cached_client(mock_journaler, 0); expect_get_journaler_tags(mock_image_ctx, mock_journaler, -EBADMSG); C_SaferCond ctx; auto req = MockOpenRequest::create(&mock_image_ctx, &mock_journaler, &m_lock, &m_client_meta, &m_tag_tid, &m_tag_data, &ctx); req->send(); ASSERT_EQ(-EBADMSG, ctx.wait()); } } // namespace journal } // namespace librbd
5,829
29.051546
108
cc
null
ceph-main/src/test/librbd/journal/test_mock_PromoteRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/journal/mock/MockJournaler.h" #include "librbd/journal/OpenRequest.h" #include "librbd/journal/PromoteRequest.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { explicit MockTestImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace journal { template <> struct TypeTraits<MockTestImageCtx> { typedef ::journal::MockJournalerProxy Journaler; typedef ::journal::MockFutureProxy Future; }; template <> struct OpenRequest<MockTestImageCtx> { Context *on_finish = nullptr; static OpenRequest *s_instance; static OpenRequest *create(MockTestImageCtx *image_ctx, ::journal::MockJournalerProxy *journaler, ceph::mutex *lock, ImageClientMeta *client_meta, uint64_t *tag_tid, journal::TagData *tag_data, Context *on_finish) { ceph_assert(s_instance != nullptr); client_meta->tag_class = 456; tag_data->mirror_uuid = Journal<>::ORPHAN_MIRROR_UUID; *tag_tid = 567; s_instance->on_finish = on_finish; return s_instance; } OpenRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; OpenRequest<MockTestImageCtx> *OpenRequest<MockTestImageCtx>::s_instance = nullptr; } // namespace journal } // namespace librbd // template definitions #include "librbd/journal/PromoteRequest.cc" template class librbd::journal::PromoteRequest<librbd::MockTestImageCtx>; namespace librbd { namespace journal { using ::testing::_; using ::testing::A; using ::testing::InSequence; using ::testing::Return; using ::testing::WithArg; class TestMockJournalPromoteRequest : public TestMockFixture { public: typedef PromoteRequest<MockTestImageCtx> MockPromoteRequest; typedef OpenRequest<MockTestImageCtx> MockOpenRequest; void expect_construct_journaler(::journal::MockJournaler &mock_journaler) { EXPECT_CALL(mock_journaler, construct()); } void expect_open_journaler(MockTestImageCtx &mock_image_ctx, MockOpenRequest &mock_open_request, int r) { EXPECT_CALL(mock_open_request, send()) .WillOnce(FinishRequest(&mock_open_request, r, &mock_image_ctx)); } void expect_allocate_tag(::journal::MockJournaler &mock_journaler, const journal::TagPredecessor &predecessor, int r) { TagData tag_data; tag_data.mirror_uuid = Journal<>::LOCAL_MIRROR_UUID; tag_data.predecessor = predecessor; bufferlist tag_data_bl; using ceph::encode; encode(tag_data, tag_data_bl); EXPECT_CALL(mock_journaler, allocate_tag(456, ContentsEqual(tag_data_bl), _, _)) .WillOnce(WithArg<3>(CompleteContext(r, static_cast<asio::ContextWQ*>(NULL)))); } void expect_append_journaler(::journal::MockJournaler &mock_journaler) { EXPECT_CALL(mock_journaler, append(_, _)) .WillOnce(Return(::journal::MockFutureProxy())); } void expect_future_flush(::journal::MockFuture &mock_future, int r) { EXPECT_CALL(mock_future, flush(_)) .WillOnce(CompleteContext(r, static_cast<asio::ContextWQ*>(NULL))); } void expect_future_committed(::journal::MockJournaler &mock_journaler) { EXPECT_CALL(mock_journaler, committed(A<const ::journal::MockFutureProxy &>())); } void expect_flush_commit_position(::journal::MockJournaler &mock_journaler, int r) { EXPECT_CALL(mock_journaler, flush_commit_position(_)) .WillOnce(CompleteContext(r, static_cast<asio::ContextWQ*>(NULL))); } void expect_start_append(::journal::MockJournaler &mock_journaler) { EXPECT_CALL(mock_journaler, start_append(_)); } void expect_stop_append(::journal::MockJournaler &mock_journaler, int r) { EXPECT_CALL(mock_journaler, stop_append(_)) .WillOnce(CompleteContext(r, static_cast<asio::ContextWQ*>(NULL))); } void expect_shut_down_journaler(::journal::MockJournaler &mock_journaler, int r) { EXPECT_CALL(mock_journaler, shut_down(_)) .WillOnce(CompleteContext(r, static_cast<asio::ContextWQ*>(NULL))); } }; TEST_F(TestMockJournalPromoteRequest, SuccessOrderly) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); ::journal::MockJournaler mock_journaler; MockOpenRequest mock_open_request; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_construct_journaler(mock_journaler); expect_open_journaler(mock_image_ctx, mock_open_request, 0); expect_allocate_tag(mock_journaler, {Journal<>::ORPHAN_MIRROR_UUID, true, 567, 1}, 0); ::journal::MockFuture mock_future; expect_start_append(mock_journaler); expect_append_journaler(mock_journaler); expect_future_flush(mock_future, 0); expect_future_committed(mock_journaler); expect_flush_commit_position(mock_journaler, 0); expect_stop_append(mock_journaler, 0); expect_shut_down_journaler(mock_journaler, 0); C_SaferCond ctx; auto req = MockPromoteRequest::create(&mock_image_ctx, false, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockJournalPromoteRequest, SuccessForced) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); ::journal::MockJournaler mock_journaler; MockOpenRequest mock_open_request; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_construct_journaler(mock_journaler); expect_open_journaler(mock_image_ctx, mock_open_request, 0); expect_allocate_tag(mock_journaler, {Journal<>::LOCAL_MIRROR_UUID, true, 567, 0}, 0); ::journal::MockFuture mock_future; expect_start_append(mock_journaler); expect_append_journaler(mock_journaler); expect_future_flush(mock_future, 0); expect_future_committed(mock_journaler); expect_flush_commit_position(mock_journaler, 0); expect_stop_append(mock_journaler, 0); expect_shut_down_journaler(mock_journaler, 0); C_SaferCond ctx; auto req = MockPromoteRequest::create(&mock_image_ctx, true, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockJournalPromoteRequest, OpenError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); ::journal::MockJournaler mock_journaler; MockOpenRequest mock_open_request; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_construct_journaler(mock_journaler); expect_open_journaler(mock_image_ctx, mock_open_request, -ENOENT); expect_shut_down_journaler(mock_journaler, -EINVAL); C_SaferCond ctx; auto req = MockPromoteRequest::create(&mock_image_ctx, false, &ctx); req->send(); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockJournalPromoteRequest, AllocateTagError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); ::journal::MockJournaler mock_journaler; MockOpenRequest mock_open_request; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_construct_journaler(mock_journaler); expect_open_journaler(mock_image_ctx, mock_open_request, 0); expect_allocate_tag(mock_journaler, {Journal<>::LOCAL_MIRROR_UUID, true, 567, 0}, -EBADMSG); expect_shut_down_journaler(mock_journaler, -EINVAL); C_SaferCond ctx; auto req = MockPromoteRequest::create(&mock_image_ctx, true, &ctx); req->send(); ASSERT_EQ(-EBADMSG, ctx.wait()); } TEST_F(TestMockJournalPromoteRequest, AppendEventError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); ::journal::MockJournaler mock_journaler; MockOpenRequest mock_open_request; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_construct_journaler(mock_journaler); expect_open_journaler(mock_image_ctx, mock_open_request, 0); expect_allocate_tag(mock_journaler, {Journal<>::ORPHAN_MIRROR_UUID, true, 567, 1}, 0); ::journal::MockFuture mock_future; expect_start_append(mock_journaler); expect_append_journaler(mock_journaler); expect_future_flush(mock_future, -EPERM); expect_stop_append(mock_journaler, 0); expect_shut_down_journaler(mock_journaler, 0); C_SaferCond ctx; auto req = MockPromoteRequest::create(&mock_image_ctx, false, &ctx); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } TEST_F(TestMockJournalPromoteRequest, CommitEventError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); ::journal::MockJournaler mock_journaler; MockOpenRequest mock_open_request; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_construct_journaler(mock_journaler); expect_open_journaler(mock_image_ctx, mock_open_request, 0); expect_allocate_tag(mock_journaler, {Journal<>::ORPHAN_MIRROR_UUID, true, 567, 1}, 0); ::journal::MockFuture mock_future; expect_start_append(mock_journaler); expect_append_journaler(mock_journaler); expect_future_flush(mock_future, 0); expect_future_committed(mock_journaler); expect_flush_commit_position(mock_journaler, -EINVAL); expect_stop_append(mock_journaler, 0); expect_shut_down_journaler(mock_journaler, 0); C_SaferCond ctx; auto req = MockPromoteRequest::create(&mock_image_ctx, false, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockJournalPromoteRequest, ShutDownError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); ::journal::MockJournaler mock_journaler; MockOpenRequest mock_open_request; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_construct_journaler(mock_journaler); expect_open_journaler(mock_image_ctx, mock_open_request, 0); expect_allocate_tag(mock_journaler, {Journal<>::LOCAL_MIRROR_UUID, true, 567, 0}, 0); ::journal::MockFuture mock_future; expect_start_append(mock_journaler); expect_append_journaler(mock_journaler); expect_future_flush(mock_future, 0); expect_future_committed(mock_journaler); expect_flush_commit_position(mock_journaler, 0); expect_stop_append(mock_journaler, 0); expect_shut_down_journaler(mock_journaler, -EINVAL); C_SaferCond ctx; auto req = MockPromoteRequest::create(&mock_image_ctx, true, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } } // namespace journal } // namespace librbd
11,216
30.420168
85
cc
null
ceph-main/src/test/librbd/journal/test_mock_Replay.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "librbd/io/ImageRequest.h" #include "librbd/journal/Replay.h" #include "librbd/journal/Types.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <boost/scope_exit.hpp> namespace librbd { namespace { struct MockReplayImageCtx : public MockImageCtx { explicit MockReplayImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace io { template <> struct ImageRequest<MockReplayImageCtx> { static ImageRequest *s_instance; MOCK_METHOD4(aio_write, void(AioCompletion *c, const Extents &image_extents, const bufferlist &bl, int op_flags)); static void aio_write(MockReplayImageCtx *ictx, AioCompletion *c, Extents&& image_extents, ImageArea area, bufferlist&& bl, int op_flags, const ZTracer::Trace &parent_trace) { ceph_assert(s_instance != nullptr); s_instance->aio_write(c, image_extents, bl, op_flags); } MOCK_METHOD3(aio_discard, void(AioCompletion *c, const Extents& image_extents, uint32_t discard_granularity_bytes)); static void aio_discard(MockReplayImageCtx *ictx, AioCompletion *c, Extents&& image_extents, ImageArea area, uint32_t discard_granularity_bytes, const ZTracer::Trace &parent_trace) { ceph_assert(s_instance != nullptr); s_instance->aio_discard(c, image_extents, discard_granularity_bytes); } MOCK_METHOD1(aio_flush, void(AioCompletion *c)); static void aio_flush(MockReplayImageCtx *ictx, AioCompletion *c, FlushSource, const ZTracer::Trace &parent_trace) { ceph_assert(s_instance != nullptr); s_instance->aio_flush(c); } MOCK_METHOD4(aio_writesame, void(AioCompletion *c, const Extents& image_extents, const bufferlist &bl, int op_flags)); static void aio_writesame(MockReplayImageCtx *ictx, AioCompletion *c, Extents&& image_extents, ImageArea area, bufferlist&& bl, int op_flags, const ZTracer::Trace &parent_trace) { ceph_assert(s_instance != nullptr); s_instance->aio_writesame(c, image_extents, bl, op_flags); } MOCK_METHOD6(aio_compare_and_write, void(AioCompletion *c, const Extents &image_extents, const bufferlist &cmp_bl, const bufferlist &bl, uint64_t *mismatch_offset, int op_flags)); static void aio_compare_and_write(MockReplayImageCtx *ictx, AioCompletion *c, Extents&& image_extents, ImageArea area, bufferlist&& cmp_bl, bufferlist&& bl, uint64_t* mismatch_offset, int op_flags, const ZTracer::Trace &parent_trace) { ceph_assert(s_instance != nullptr); s_instance->aio_compare_and_write(c, image_extents, cmp_bl, bl, mismatch_offset, op_flags); } ImageRequest() { s_instance = this; } }; ImageRequest<MockReplayImageCtx> *ImageRequest<MockReplayImageCtx>::s_instance = nullptr; } // namespace io namespace util { inline ImageCtx *get_image_ctx(librbd::MockReplayImageCtx *image_ctx) { return image_ctx->image_ctx; } } // namespace util } // namespace librbd // template definitions #include "librbd/journal/Replay.cc" template class librbd::journal::Replay<librbd::MockReplayImageCtx>; using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Return; using ::testing::SaveArg; using ::testing::StrEq; using ::testing::WithArgs; MATCHER_P(BufferlistEqual, str, "") { bufferlist bl(arg); return (strncmp(bl.c_str(), str, strlen(str)) == 0); } MATCHER_P(CStrEq, str, "") { return (strncmp(arg, str, strlen(str)) == 0); } ACTION_P2(NotifyInvoke, lock, cond) { std::lock_guard locker{*lock}; cond->notify_all(); } ACTION_P2(CompleteAioCompletion, r, image_ctx) { image_ctx->op_work_queue->queue(new LambdaContext([this, arg0](int r) { arg0->get(); arg0->init_time(image_ctx, librbd::io::AIO_TYPE_NONE); arg0->set_request_count(1); arg0->complete_request(r); }), r); } namespace librbd { namespace journal { class TestMockJournalReplay : public TestMockFixture { public: typedef io::ImageRequest<MockReplayImageCtx> MockIoImageRequest; typedef Replay<MockReplayImageCtx> MockJournalReplay; TestMockJournalReplay() = default; void expect_accept_ops(MockExclusiveLock &mock_exclusive_lock, bool accept) { EXPECT_CALL(mock_exclusive_lock, accept_ops()).WillRepeatedly( Return(accept)); } void expect_aio_discard(MockIoImageRequest &mock_io_image_request, io::AioCompletion **aio_comp, uint64_t off, uint64_t len, uint32_t discard_granularity_bytes) { EXPECT_CALL(mock_io_image_request, aio_discard(_, io::Extents{{off, len}}, discard_granularity_bytes)) .WillOnce(SaveArg<0>(aio_comp)); } void expect_aio_flush(MockIoImageRequest &mock_io_image_request, io::AioCompletion **aio_comp) { EXPECT_CALL(mock_io_image_request, aio_flush(_)) .WillOnce(SaveArg<0>(aio_comp)); } void expect_aio_flush(MockReplayImageCtx &mock_image_ctx, MockIoImageRequest &mock_io_image_request, int r) { EXPECT_CALL(mock_io_image_request, aio_flush(_)) .WillOnce(CompleteAioCompletion(r, mock_image_ctx.image_ctx)); } void expect_aio_write(MockIoImageRequest &mock_io_image_request, io::AioCompletion **aio_comp, uint64_t off, uint64_t len, const char *data) { EXPECT_CALL(mock_io_image_request, aio_write(_, io::Extents{{off, len}}, BufferlistEqual(data), _)) .WillOnce(SaveArg<0>(aio_comp)); } void expect_aio_writesame(MockIoImageRequest &mock_io_image_request, io::AioCompletion **aio_comp, uint64_t off, uint64_t len, const char *data) { EXPECT_CALL(mock_io_image_request, aio_writesame(_, io::Extents{{off, len}}, BufferlistEqual(data), _)) .WillOnce(SaveArg<0>(aio_comp)); } void expect_aio_compare_and_write(MockIoImageRequest &mock_io_image_request, io::AioCompletion **aio_comp, uint64_t off, uint64_t len, const char *cmp_data, const char *data, uint64_t *mismatch_offset) { EXPECT_CALL(mock_io_image_request, aio_compare_and_write(_, io::Extents{{off, len}}, BufferlistEqual(cmp_data), BufferlistEqual(data), mismatch_offset, _)) .WillOnce(SaveArg<0>(aio_comp)); } void expect_flatten(MockReplayImageCtx &mock_image_ctx, Context **on_finish) { EXPECT_CALL(*mock_image_ctx.operations, execute_flatten(_, _)) .WillOnce(DoAll(SaveArg<1>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_rename(MockReplayImageCtx &mock_image_ctx, Context **on_finish, const char *image_name) { EXPECT_CALL(*mock_image_ctx.operations, execute_rename(StrEq(image_name), _)) .WillOnce(DoAll(SaveArg<1>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_resize(MockReplayImageCtx &mock_image_ctx, Context **on_finish, uint64_t size, uint64_t op_tid) { EXPECT_CALL(*mock_image_ctx.operations, execute_resize(size, _, _, _, op_tid)) .WillOnce(DoAll(SaveArg<3>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_snap_create(MockReplayImageCtx &mock_image_ctx, Context **on_finish, const char *snap_name, uint64_t op_tid) { EXPECT_CALL(*mock_image_ctx.operations, execute_snap_create(_, StrEq(snap_name), _, op_tid, SNAP_CREATE_FLAG_SKIP_NOTIFY_QUIESCE, _)) .WillOnce(DoAll(SaveArg<2>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_snap_remove(MockReplayImageCtx &mock_image_ctx, Context **on_finish, const char *snap_name) { EXPECT_CALL(*mock_image_ctx.operations, execute_snap_remove(_, StrEq(snap_name), _)) .WillOnce(DoAll(SaveArg<2>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_snap_rename(MockReplayImageCtx &mock_image_ctx, Context **on_finish, uint64_t snap_id, const char *snap_name) { EXPECT_CALL(*mock_image_ctx.operations, execute_snap_rename(snap_id, StrEq(snap_name), _)) .WillOnce(DoAll(SaveArg<2>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_snap_protect(MockReplayImageCtx &mock_image_ctx, Context **on_finish, const char *snap_name) { EXPECT_CALL(*mock_image_ctx.operations, execute_snap_protect(_, StrEq(snap_name), _)) .WillOnce(DoAll(SaveArg<2>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_snap_unprotect(MockReplayImageCtx &mock_image_ctx, Context **on_finish, const char *snap_name) { EXPECT_CALL(*mock_image_ctx.operations, execute_snap_unprotect(_, StrEq(snap_name), _)) .WillOnce(DoAll(SaveArg<2>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_snap_rollback(MockReplayImageCtx &mock_image_ctx, Context **on_finish, const char *snap_name) { EXPECT_CALL(*mock_image_ctx.operations, execute_snap_rollback(_, StrEq(snap_name), _, _)) .WillOnce(DoAll(SaveArg<3>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_update_features(MockReplayImageCtx &mock_image_ctx, Context **on_finish, uint64_t features, bool enabled, uint64_t op_tid) { EXPECT_CALL(*mock_image_ctx.operations, execute_update_features(features, enabled, _, op_tid)) .WillOnce(DoAll(SaveArg<2>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_metadata_set(MockReplayImageCtx &mock_image_ctx, Context **on_finish, const char *key, const char *value) { EXPECT_CALL(*mock_image_ctx.operations, execute_metadata_set(StrEq(key), StrEq(value), _)) .WillOnce(DoAll(SaveArg<2>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_metadata_remove(MockReplayImageCtx &mock_image_ctx, Context **on_finish, const char *key) { EXPECT_CALL(*mock_image_ctx.operations, execute_metadata_remove(StrEq(key), _)) .WillOnce(DoAll(SaveArg<1>(on_finish), NotifyInvoke(&m_invoke_lock, &m_invoke_cond))); } void expect_refresh_image(MockReplayImageCtx &mock_image_ctx, bool required, int r) { EXPECT_CALL(*mock_image_ctx.state, is_refresh_required()) .WillOnce(Return(required)); if (required) { EXPECT_CALL(*mock_image_ctx.state, refresh(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); } } void when_process(MockJournalReplay &mock_journal_replay, EventEntry &&event_entry, Context *on_ready, Context *on_safe) { bufferlist bl; encode(event_entry, bl); auto it = bl.cbegin(); when_process(mock_journal_replay, &it, on_ready, on_safe); } void when_process(MockJournalReplay &mock_journal_replay, bufferlist::const_iterator *it, Context *on_ready, Context *on_safe) { EventEntry event_entry; int r = mock_journal_replay.decode(it, &event_entry); ASSERT_EQ(0, r); mock_journal_replay.process(event_entry, on_ready, on_safe); } void when_complete(MockReplayImageCtx &mock_image_ctx, io::AioCompletion *aio_comp, int r) { aio_comp->get(); aio_comp->init_time(mock_image_ctx.image_ctx, librbd::io::AIO_TYPE_NONE); aio_comp->set_request_count(1); aio_comp->complete_request(r); } int when_flush(MockJournalReplay &mock_journal_replay) { C_SaferCond ctx; mock_journal_replay.flush(&ctx); return ctx.wait(); } int when_shut_down(MockJournalReplay &mock_journal_replay, bool cancel_ops) { C_SaferCond ctx; mock_journal_replay.shut_down(cancel_ops, &ctx); return ctx.wait(); } void when_replay_op_ready(MockJournalReplay &mock_journal_replay, uint64_t op_tid, Context *on_resume) { mock_journal_replay.replay_op_ready(op_tid, on_resume); } void wait_for_op_invoked(Context **on_finish, int r) { { std::unique_lock locker{m_invoke_lock}; m_invoke_cond.wait(locker, [on_finish] { return *on_finish != nullptr; }); } (*on_finish)->complete(r); } bufferlist to_bl(const std::string &str) { bufferlist bl; bl.append(str); return bl; } ceph::mutex m_invoke_lock = ceph::make_mutex("m_invoke_lock"); ceph::condition_variable m_invoke_cond; }; TEST_F(TestMockJournalReplay, AioDiscard) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); InSequence seq; io::AioCompletion *aio_comp; C_SaferCond on_ready; C_SaferCond on_safe; expect_aio_discard(mock_io_image_request, &aio_comp, 123, 456, ictx->discard_granularity_bytes); when_process(mock_journal_replay, EventEntry{AioDiscardEvent(123, 456, ictx->discard_granularity_bytes)}, &on_ready, &on_safe); when_complete(mock_image_ctx, aio_comp, 0); ASSERT_EQ(0, on_ready.wait()); expect_aio_flush(mock_image_ctx, mock_io_image_request, 0); ASSERT_EQ(0, when_shut_down(mock_journal_replay, false)); ASSERT_EQ(0, on_safe.wait()); } TEST_F(TestMockJournalReplay, AioWrite) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); InSequence seq; io::AioCompletion *aio_comp; C_SaferCond on_ready; C_SaferCond on_safe; expect_aio_write(mock_io_image_request, &aio_comp, 123, 456, "test"); when_process(mock_journal_replay, EventEntry{AioWriteEvent(123, 456, to_bl("test"))}, &on_ready, &on_safe); when_complete(mock_image_ctx, aio_comp, 0); ASSERT_EQ(0, on_ready.wait()); expect_aio_flush(mock_image_ctx, mock_io_image_request, 0); ASSERT_EQ(0, when_shut_down(mock_journal_replay, false)); ASSERT_EQ(0, on_safe.wait()); } TEST_F(TestMockJournalReplay, AioFlush) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); InSequence seq; io::AioCompletion *aio_comp; C_SaferCond on_ready; C_SaferCond on_safe; expect_aio_flush(mock_io_image_request, &aio_comp); when_process(mock_journal_replay, EventEntry{AioFlushEvent()}, &on_ready, &on_safe); when_complete(mock_image_ctx, aio_comp, 0); ASSERT_EQ(0, on_safe.wait()); ASSERT_EQ(0, when_shut_down(mock_journal_replay, false)); ASSERT_EQ(0, on_ready.wait()); } TEST_F(TestMockJournalReplay, AioWriteSame) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); InSequence seq; io::AioCompletion *aio_comp; C_SaferCond on_ready; C_SaferCond on_safe; expect_aio_writesame(mock_io_image_request, &aio_comp, 123, 456, "333"); when_process(mock_journal_replay, EventEntry{AioWriteSameEvent(123, 456, to_bl("333"))}, &on_ready, &on_safe); when_complete(mock_image_ctx, aio_comp, 0); ASSERT_EQ(0, on_ready.wait()); expect_aio_flush(mock_image_ctx, mock_io_image_request, 0); ASSERT_EQ(0, when_shut_down(mock_journal_replay, false)); ASSERT_EQ(0, on_safe.wait()); } TEST_F(TestMockJournalReplay, AioCompareAndWrite) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_write_journal_replay(mock_image_ctx); MockJournalReplay mock_compare_and_write_journal_replay(mock_image_ctx); MockJournalReplay mock_mis_compare_and_write_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); InSequence seq; io::AioCompletion *aio_comp; C_SaferCond on_ready; C_SaferCond on_safe; expect_aio_write(mock_io_image_request, &aio_comp, 512, 512, "test"); when_process(mock_write_journal_replay, EventEntry{AioWriteEvent(512, 512, to_bl("test"))}, &on_ready, &on_safe); when_complete(mock_image_ctx, aio_comp, 0); ASSERT_EQ(0, on_ready.wait()); expect_aio_flush(mock_image_ctx, mock_io_image_request, 0); ASSERT_EQ(0, when_shut_down(mock_write_journal_replay, false)); ASSERT_EQ(0, on_safe.wait()); expect_aio_compare_and_write(mock_io_image_request, &aio_comp, 512, 512, "test", "test", nullptr); when_process(mock_compare_and_write_journal_replay, EventEntry{AioCompareAndWriteEvent(512, 512, to_bl("test"), to_bl("test"))}, &on_ready, &on_safe); when_complete(mock_image_ctx, aio_comp, 0); ASSERT_EQ(0, on_ready.wait()); expect_aio_flush(mock_image_ctx, mock_io_image_request, 0); ASSERT_EQ(0, when_shut_down(mock_compare_and_write_journal_replay, false)); ASSERT_EQ(0, on_safe.wait()); expect_aio_compare_and_write(mock_io_image_request, &aio_comp, 512, 512, "111", "test", nullptr); when_process(mock_mis_compare_and_write_journal_replay, EventEntry{AioCompareAndWriteEvent(512, 512, to_bl("111"), to_bl("test"))}, &on_ready, &on_safe); when_complete(mock_image_ctx, aio_comp, 0); ASSERT_EQ(0, on_ready.wait()); expect_aio_flush(mock_image_ctx, mock_io_image_request, 0); ASSERT_EQ(0, when_shut_down(mock_mis_compare_and_write_journal_replay, false)); ASSERT_EQ(0, on_safe.wait()); } TEST_F(TestMockJournalReplay, IOError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); InSequence seq; io::AioCompletion *aio_comp; C_SaferCond on_ready; C_SaferCond on_safe; expect_aio_discard(mock_io_image_request, &aio_comp, 123, 456, ictx->discard_granularity_bytes); when_process(mock_journal_replay, EventEntry{AioDiscardEvent(123, 456, ictx->discard_granularity_bytes)}, &on_ready, &on_safe); when_complete(mock_image_ctx, aio_comp, -EINVAL); ASSERT_EQ(-EINVAL, on_safe.wait()); expect_aio_flush(mock_image_ctx, mock_io_image_request, 0); ASSERT_EQ(0, when_shut_down(mock_journal_replay, false)); ASSERT_EQ(0, on_ready.wait()); } TEST_F(TestMockJournalReplay, SoftFlushIO) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); InSequence seq; const size_t io_count = 32; C_SaferCond on_safes[io_count]; for (size_t i = 0; i < io_count; ++i) { io::AioCompletion *aio_comp; io::AioCompletion *flush_comp = nullptr; C_SaferCond on_ready; expect_aio_discard(mock_io_image_request, &aio_comp, 123, 456, ictx->discard_granularity_bytes); if (i == io_count - 1) { expect_aio_flush(mock_io_image_request, &flush_comp); } when_process(mock_journal_replay, EventEntry{AioDiscardEvent(123, 456, ictx->discard_granularity_bytes)}, &on_ready, &on_safes[i]); when_complete(mock_image_ctx, aio_comp, 0); ASSERT_EQ(0, on_ready.wait()); if (flush_comp != nullptr) { when_complete(mock_image_ctx, flush_comp, 0); } } for (auto &on_safe : on_safes) { ASSERT_EQ(0, on_safe.wait()); } ASSERT_EQ(0, when_shut_down(mock_journal_replay, false)); } TEST_F(TestMockJournalReplay, PauseIO) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); InSequence seq; const size_t io_count = 64; std::list<io::AioCompletion *> flush_comps; C_SaferCond on_safes[io_count]; for (size_t i = 0; i < io_count; ++i) { io::AioCompletion *aio_comp; C_SaferCond on_ready; expect_aio_write(mock_io_image_request, &aio_comp, 123, 456, "test"); if ((i + 1) % 32 == 0) { flush_comps.push_back(nullptr); expect_aio_flush(mock_io_image_request, &flush_comps.back()); } when_process(mock_journal_replay, EventEntry{AioWriteEvent(123, 456, to_bl("test"))}, &on_ready, &on_safes[i]); when_complete(mock_image_ctx, aio_comp, 0); if (i < io_count - 1) { ASSERT_EQ(0, on_ready.wait()); } else { for (auto flush_comp : flush_comps) { when_complete(mock_image_ctx, flush_comp, 0); } ASSERT_EQ(0, on_ready.wait()); } } for (auto &on_safe : on_safes) { ASSERT_EQ(0, on_safe.wait()); } ASSERT_EQ(0, when_shut_down(mock_journal_replay, false)); } TEST_F(TestMockJournalReplay, Flush) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); InSequence seq; io::AioCompletion *aio_comp = nullptr; C_SaferCond on_ready; C_SaferCond on_safe; expect_aio_discard(mock_io_image_request, &aio_comp, 123, 456, ictx->discard_granularity_bytes); when_process(mock_journal_replay, EventEntry{AioDiscardEvent(123, 456, ictx->discard_granularity_bytes)}, &on_ready, &on_safe); when_complete(mock_image_ctx, aio_comp, 0); ASSERT_EQ(0, on_ready.wait()); expect_aio_flush(mock_image_ctx, mock_io_image_request, 0); ASSERT_EQ(0, when_flush(mock_journal_replay)); ASSERT_EQ(0, on_safe.wait()); } TEST_F(TestMockJournalReplay, OpFinishError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapRemoveEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, -EIO)}, &on_finish_ready, &on_finish_safe); ASSERT_EQ(-EIO, on_start_safe.wait()); ASSERT_EQ(-EIO, on_finish_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); } TEST_F(TestMockJournalReplay, BlockedOpFinishError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_create(mock_image_ctx, &on_finish, "snap", 123); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapCreateEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); C_SaferCond on_resume; when_replay_op_ready(mock_journal_replay, 123, &on_resume); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, -EBADMSG)}, &on_finish_ready, &on_finish_safe); ASSERT_EQ(-EBADMSG, on_resume.wait()); wait_for_op_invoked(&on_finish, -ESTALE); ASSERT_EQ(-ESTALE, on_start_safe.wait()); ASSERT_EQ(-ESTALE, on_finish_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); } TEST_F(TestMockJournalReplay, MissingOpFinishEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); EXPECT_CALL(*mock_image_ctx.state, is_refresh_required()) .WillRepeatedly(Return(false)); InSequence seq; Context *on_snap_create_finish = nullptr; expect_snap_create(mock_image_ctx, &on_snap_create_finish, "snap", 123); Context *on_snap_remove_finish = nullptr; expect_snap_remove(mock_image_ctx, &on_snap_remove_finish, "snap"); C_SaferCond on_snap_remove_ready; C_SaferCond on_snap_remove_safe; when_process(mock_journal_replay, EventEntry{SnapRemoveEvent(122, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_snap_remove_ready, &on_snap_remove_safe); ictx->op_work_queue->drain(); ASSERT_EQ(0, on_snap_remove_ready.wait()); C_SaferCond on_snap_create_ready; C_SaferCond on_snap_create_safe; when_process(mock_journal_replay, EventEntry{SnapCreateEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_snap_create_ready, &on_snap_create_safe); ictx->op_work_queue->drain(); C_SaferCond on_shut_down; mock_journal_replay.shut_down(false, &on_shut_down); wait_for_op_invoked(&on_snap_remove_finish, 0); ASSERT_EQ(0, on_snap_remove_safe.wait()); C_SaferCond on_snap_create_resume; when_replay_op_ready(mock_journal_replay, 123, &on_snap_create_resume); ASSERT_EQ(0, on_snap_create_resume.wait()); wait_for_op_invoked(&on_snap_create_finish, 0); ASSERT_EQ(0, on_snap_create_ready.wait()); ASSERT_EQ(0, on_snap_create_safe.wait()); ASSERT_EQ(0, on_shut_down.wait()); } TEST_F(TestMockJournalReplay, MissingOpFinishEventCancelOps) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_snap_create_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_create(mock_image_ctx, &on_snap_create_finish, "snap", 123); C_SaferCond on_snap_remove_ready; C_SaferCond on_snap_remove_safe; when_process(mock_journal_replay, EventEntry{SnapRemoveEvent(122, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_snap_remove_ready, &on_snap_remove_safe); ictx->op_work_queue->drain(); ASSERT_EQ(0, on_snap_remove_ready.wait()); C_SaferCond on_snap_create_ready; C_SaferCond on_snap_create_safe; when_process(mock_journal_replay, EventEntry{SnapCreateEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_snap_create_ready, &on_snap_create_safe); ictx->op_work_queue->drain(); C_SaferCond on_resume; when_replay_op_ready(mock_journal_replay, 123, &on_resume); ASSERT_EQ(0, on_snap_create_ready.wait()); C_SaferCond on_shut_down; mock_journal_replay.shut_down(true, &on_shut_down); ASSERT_EQ(-ERESTART, on_resume.wait()); on_snap_create_finish->complete(-ERESTART); ASSERT_EQ(-ERESTART, on_snap_create_safe.wait()); ASSERT_EQ(-ERESTART, on_snap_remove_safe.wait()); ASSERT_EQ(0, on_shut_down.wait()); } TEST_F(TestMockJournalReplay, UnknownOpFinishEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; C_SaferCond on_ready; C_SaferCond on_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_ready, &on_safe); ASSERT_EQ(0, on_safe.wait()); ASSERT_EQ(0, on_ready.wait()); } TEST_F(TestMockJournalReplay, OpEventError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_remove(mock_image_ctx, &on_finish, "snap"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapRemoveEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, -EINVAL); ASSERT_EQ(-EINVAL, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(-EINVAL, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, SnapCreateEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_create(mock_image_ctx, &on_finish, "snap", 123); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapCreateEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); C_SaferCond on_resume; when_replay_op_ready(mock_journal_replay, 123, &on_resume); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); ASSERT_EQ(0, on_resume.wait()); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, SnapCreateEventExists) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_create(mock_image_ctx, &on_finish, "snap", 123); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapCreateEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); wait_for_op_invoked(&on_finish, -EEXIST); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, SnapRemoveEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_remove(mock_image_ctx, &on_finish, "snap"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapRemoveEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, SnapRemoveEventDNE) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_remove(mock_image_ctx, &on_finish, "snap"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapRemoveEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, -ENOENT); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, SnapRenameEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_rename(mock_image_ctx, &on_finish, 234, "snap"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapRenameEvent(123, 234, "snap1", "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, SnapRenameEventExists) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_rename(mock_image_ctx, &on_finish, 234, "snap"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapRenameEvent(123, 234, "snap1", "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, -EEXIST); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, SnapProtectEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_protect(mock_image_ctx, &on_finish, "snap"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapProtectEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, SnapProtectEventBusy) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_protect(mock_image_ctx, &on_finish, "snap"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapProtectEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, -EBUSY); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, SnapUnprotectEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_unprotect(mock_image_ctx, &on_finish, "snap"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapUnprotectEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, SnapUnprotectOpFinishBusy) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapUnprotectEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); // aborts the snap unprotect op if image had children C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, -EBUSY)}, &on_finish_ready, &on_finish_safe); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); } TEST_F(TestMockJournalReplay, SnapUnprotectEventInvalid) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_unprotect(mock_image_ctx, &on_finish, "snap"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapUnprotectEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, -EINVAL); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, SnapRollbackEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_snap_rollback(mock_image_ctx, &on_finish, "snap"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{SnapRollbackEvent(123, cls::rbd::UserSnapshotNamespace(), "snap")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, RenameEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_rename(mock_image_ctx, &on_finish, "image"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{RenameEvent(123, "image")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, RenameEventExists) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_rename(mock_image_ctx, &on_finish, "image"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{RenameEvent(123, "image")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, -EEXIST); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, ResizeEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_resize(mock_image_ctx, &on_finish, 234, 123); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{ResizeEvent(123, 234)}, &on_start_ready, &on_start_safe); C_SaferCond on_resume; when_replay_op_ready(mock_journal_replay, 123, &on_resume); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); ASSERT_EQ(0, on_resume.wait()); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, FlattenEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_flatten(mock_image_ctx, &on_finish); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{FlattenEvent(123)}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, FlattenEventInvalid) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_flatten(mock_image_ctx, &on_finish); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{FlattenEvent(123)}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, -EINVAL); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, UpdateFeaturesEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); uint64_t features = RBD_FEATURE_OBJECT_MAP | RBD_FEATURE_FAST_DIFF; bool enabled = !ictx->test_features(features); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, false, 0); expect_update_features(mock_image_ctx, &on_finish, features, enabled, 123); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{UpdateFeaturesEvent(123, features, enabled)}, &on_start_ready, &on_start_safe); C_SaferCond on_resume; when_replay_op_ready(mock_journal_replay, 123, &on_resume); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); ASSERT_EQ(0, on_resume.wait()); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, MetadataSetEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_metadata_set(mock_image_ctx, &on_finish, "key", "value"); expect_refresh_image(mock_image_ctx, false, 0); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{MetadataSetEvent(123, "key", "value")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, MetadataRemoveEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_metadata_remove(mock_image_ctx, &on_finish, "key"); expect_refresh_image(mock_image_ctx, false, 0); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{MetadataRemoveEvent(123, "key")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, MetadataRemoveEventDNE) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_metadata_remove(mock_image_ctx, &on_finish, "key"); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{MetadataRemoveEvent(123, "key")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); wait_for_op_invoked(&on_finish, -ENOENT); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, UnknownEvent) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; bufferlist bl; ENCODE_START(1, 1, bl); encode(static_cast<uint32_t>(-1), bl); ENCODE_FINISH(bl); auto it = bl.cbegin(); C_SaferCond on_ready; C_SaferCond on_safe; when_process(mock_journal_replay, &it, &on_ready, &on_safe); ASSERT_EQ(0, on_safe.wait()); ASSERT_EQ(0, on_ready.wait()); } TEST_F(TestMockJournalReplay, RefreshImageBeforeOpStart) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; Context *on_finish = nullptr; expect_refresh_image(mock_image_ctx, true, 0); expect_resize(mock_image_ctx, &on_finish, 234, 123); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{ResizeEvent(123, 234)}, &on_start_ready, &on_start_safe); C_SaferCond on_resume; when_replay_op_ready(mock_journal_replay, 123, &on_resume); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); ASSERT_EQ(0, on_resume.wait()); wait_for_op_invoked(&on_finish, 0); ASSERT_EQ(0, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(0, on_finish_safe.wait()); } TEST_F(TestMockJournalReplay, FlushEventAfterShutDown) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); ASSERT_EQ(0, when_shut_down(mock_journal_replay, false)); C_SaferCond on_ready; C_SaferCond on_safe; when_process(mock_journal_replay, EventEntry{AioFlushEvent()}, &on_ready, &on_safe); ASSERT_EQ(0, on_ready.wait()); ASSERT_EQ(-ESHUTDOWN, on_safe.wait()); } TEST_F(TestMockJournalReplay, ModifyEventAfterShutDown) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); ASSERT_EQ(0, when_shut_down(mock_journal_replay, false)); C_SaferCond on_ready; C_SaferCond on_safe; when_process(mock_journal_replay, EventEntry{AioWriteEvent(123, 456, to_bl("test"))}, &on_ready, &on_safe); ASSERT_EQ(0, on_ready.wait()); ASSERT_EQ(-ESHUTDOWN, on_safe.wait()); } TEST_F(TestMockJournalReplay, OpEventAfterShutDown) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, true); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); ASSERT_EQ(0, when_shut_down(mock_journal_replay, false)); C_SaferCond on_ready; C_SaferCond on_safe; when_process(mock_journal_replay, EventEntry{RenameEvent(123, "image")}, &on_ready, &on_safe); ASSERT_EQ(0, on_ready.wait()); ASSERT_EQ(-ESHUTDOWN, on_safe.wait()); } TEST_F(TestMockJournalReplay, LockLostBeforeProcess) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, false); MockJournalReplay mock_journal_replay(mock_image_ctx); MockIoImageRequest mock_io_image_request; expect_op_work_queue(mock_image_ctx); InSequence seq; C_SaferCond on_ready; C_SaferCond on_safe; when_process(mock_journal_replay, EventEntry{AioFlushEvent()}, &on_ready, &on_safe); ASSERT_EQ(0, on_ready.wait()); ASSERT_EQ(-ECANCELED, on_safe.wait()); ASSERT_EQ(0, when_shut_down(mock_journal_replay, false)); } TEST_F(TestMockJournalReplay, LockLostBeforeExecuteOp) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockReplayImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; mock_image_ctx.exclusive_lock = &mock_exclusive_lock; expect_accept_ops(mock_exclusive_lock, false); MockJournalReplay mock_journal_replay(mock_image_ctx); expect_op_work_queue(mock_image_ctx); InSequence seq; EXPECT_CALL(mock_exclusive_lock, accept_ops()).WillOnce(Return(true)); EXPECT_CALL(mock_exclusive_lock, accept_ops()).WillOnce(Return(true)); expect_refresh_image(mock_image_ctx, false, 0); C_SaferCond on_start_ready; C_SaferCond on_start_safe; when_process(mock_journal_replay, EventEntry{RenameEvent(123, "image")}, &on_start_ready, &on_start_safe); ASSERT_EQ(0, on_start_ready.wait()); C_SaferCond on_finish_ready; C_SaferCond on_finish_safe; when_process(mock_journal_replay, EventEntry{OpFinishEvent(123, 0)}, &on_finish_ready, &on_finish_safe); ASSERT_EQ(-ECANCELED, on_start_safe.wait()); ASSERT_EQ(0, on_finish_ready.wait()); ASSERT_EQ(-ECANCELED, on_finish_safe.wait()); } } // namespace journal } // namespace librbd
67,341
31.978452
100
cc
null
ceph-main/src/test/librbd/journal/test_mock_ResetRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/journal/mock/MockJournaler.h" #include "cls/journal/cls_journal_types.h" #include "librbd/journal/CreateRequest.h" #include "librbd/journal/RemoveRequest.h" #include "librbd/journal/ResetRequest.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace journal { template <> struct TypeTraits<MockTestImageCtx> { typedef ::journal::MockJournalerProxy Journaler; }; template <> struct CreateRequest<MockTestImageCtx> { static CreateRequest* s_instance; Context* on_finish = nullptr; static CreateRequest* create(IoCtx &ioctx, const std::string &imageid, uint8_t order, uint8_t splay_width, const std::string &object_pool, uint64_t tag_class, TagData &tag_data, const std::string &client_id, ContextWQ *op_work_queue, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } MOCK_METHOD0(send, void()); CreateRequest() { s_instance = this; } }; template <> struct RemoveRequest<MockTestImageCtx> { static RemoveRequest* s_instance; Context* on_finish = nullptr; static RemoveRequest* create(IoCtx &ioctx, const std::string &image_id, const std::string &client_id, ContextWQ *op_work_queue, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } MOCK_METHOD0(send, void()); RemoveRequest() { s_instance = this; } }; CreateRequest<MockTestImageCtx>* CreateRequest<MockTestImageCtx>::s_instance = nullptr; RemoveRequest<MockTestImageCtx>* RemoveRequest<MockTestImageCtx>::s_instance = nullptr; } // namespace journal } // namespace librbd #include "librbd/journal/ResetRequest.cc" namespace librbd { namespace journal { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::WithArg; class TestMockJournalResetRequest : public TestMockFixture { public: typedef ResetRequest<MockTestImageCtx> MockResetRequest; typedef CreateRequest<MockTestImageCtx> MockCreateRequest; typedef RemoveRequest<MockTestImageCtx> MockRemoveRequest; void expect_construct_journaler(::journal::MockJournaler &mock_journaler) { EXPECT_CALL(mock_journaler, construct()); } void expect_init_journaler(::journal::MockJournaler &mock_journaler, int r) { EXPECT_CALL(mock_journaler, init(_)) .WillOnce(CompleteContext(r, static_cast<ContextWQ*>(NULL))); } void expect_get_metadata(::journal::MockJournaler& mock_journaler) { EXPECT_CALL(mock_journaler, get_metadata(_, _, _)) .WillOnce(Invoke([](uint8_t* order, uint8_t* splay_width, int64_t* pool_id) { *order = 24; *splay_width = 4; *pool_id = -1; })); } void expect_shut_down_journaler(::journal::MockJournaler &mock_journaler, int r) { EXPECT_CALL(mock_journaler, shut_down(_)) .WillOnce(CompleteContext(r, static_cast<ContextWQ*>(NULL))); } void expect_remove(MockRemoveRequest& mock_remove_request, int r) { EXPECT_CALL(mock_remove_request, send()) .WillOnce(Invoke([&mock_remove_request, r]() { mock_remove_request.on_finish->complete(r); })); } void expect_create(MockCreateRequest& mock_create_request, int r) { EXPECT_CALL(mock_create_request, send()) .WillOnce(Invoke([&mock_create_request, r]() { mock_create_request.on_finish->complete(r); })); } }; TEST_F(TestMockJournalResetRequest, Success) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); InSequence seq; ::journal::MockJournaler mock_journaler; expect_construct_journaler(mock_journaler); expect_init_journaler(mock_journaler, 0); expect_get_metadata(mock_journaler); expect_shut_down_journaler(mock_journaler, 0); MockRemoveRequest mock_remove_request; expect_remove(mock_remove_request, 0); MockCreateRequest mock_create_request; expect_create(mock_create_request, 0); ContextWQ* context_wq; Journal<>::get_work_queue(ictx->cct, &context_wq); C_SaferCond ctx; auto req = MockResetRequest::create(m_ioctx, "image id", Journal<>::IMAGE_CLIENT_ID, Journal<>::LOCAL_MIRROR_UUID, context_wq, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockJournalResetRequest, InitError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); InSequence seq; ::journal::MockJournaler mock_journaler; expect_construct_journaler(mock_journaler); expect_init_journaler(mock_journaler, -EINVAL); expect_shut_down_journaler(mock_journaler, 0); ContextWQ* context_wq; Journal<>::get_work_queue(ictx->cct, &context_wq); C_SaferCond ctx; auto req = MockResetRequest::create(m_ioctx, "image id", Journal<>::IMAGE_CLIENT_ID, Journal<>::LOCAL_MIRROR_UUID, context_wq, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockJournalResetRequest, ShutDownError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); InSequence seq; ::journal::MockJournaler mock_journaler; expect_construct_journaler(mock_journaler); expect_init_journaler(mock_journaler, 0); expect_get_metadata(mock_journaler); expect_shut_down_journaler(mock_journaler, -EINVAL); ContextWQ* context_wq; Journal<>::get_work_queue(ictx->cct, &context_wq); C_SaferCond ctx; auto req = MockResetRequest::create(m_ioctx, "image id", Journal<>::IMAGE_CLIENT_ID, Journal<>::LOCAL_MIRROR_UUID, context_wq, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockJournalResetRequest, RemoveError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); InSequence seq; ::journal::MockJournaler mock_journaler; expect_construct_journaler(mock_journaler); expect_init_journaler(mock_journaler, 0); expect_get_metadata(mock_journaler); expect_shut_down_journaler(mock_journaler, 0); MockRemoveRequest mock_remove_request; expect_remove(mock_remove_request, -EINVAL); ContextWQ* context_wq; Journal<>::get_work_queue(ictx->cct, &context_wq); C_SaferCond ctx; auto req = MockResetRequest::create(m_ioctx, "image id", Journal<>::IMAGE_CLIENT_ID, Journal<>::LOCAL_MIRROR_UUID, context_wq, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockJournalResetRequest, CreateError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); InSequence seq; ::journal::MockJournaler mock_journaler; expect_construct_journaler(mock_journaler); expect_init_journaler(mock_journaler, 0); expect_get_metadata(mock_journaler); expect_shut_down_journaler(mock_journaler, 0); MockRemoveRequest mock_remove_request; expect_remove(mock_remove_request, 0); MockCreateRequest mock_create_request; expect_create(mock_create_request, -EINVAL); ContextWQ* context_wq; Journal<>::get_work_queue(ictx->cct, &context_wq); C_SaferCond ctx; auto req = MockResetRequest::create(m_ioctx, "image id", Journal<>::IMAGE_CLIENT_ID, Journal<>::LOCAL_MIRROR_UUID, context_wq, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } } // namespace journal } // namespace librbd
8,638
29.964158
87
cc
null
ceph-main/src/test/librbd/managed_lock/test_mock_AcquireRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "cls/lock/cls_lock_ops.h" #include "librbd/managed_lock/AcquireRequest.h" #include "librbd/managed_lock/BreakRequest.h" #include "librbd/managed_lock/GetLockerRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <arpa/inet.h> #include <list> namespace librbd { namespace watcher { template <> struct Traits<MockImageCtx> { typedef librbd::MockImageWatcher Watcher; }; } namespace managed_lock { template<> struct BreakRequest<librbd::MockImageCtx> { Context *on_finish = nullptr; static BreakRequest *s_instance; static BreakRequest* create(librados::IoCtx& ioctx, AsioEngine& asio_engine, const std::string& oid, const Locker &locker, bool exclusive, bool blocklist_locker, uint32_t blocklist_expire_seconds, bool force_break_lock, Context *on_finish) { CephContext *cct = reinterpret_cast<CephContext *>(ioctx.cct()); EXPECT_EQ(cct->_conf.get_val<bool>("rbd_blocklist_on_break_lock"), blocklist_locker); EXPECT_EQ(cct->_conf.get_val<uint64_t>("rbd_blocklist_expire_seconds"), blocklist_expire_seconds); EXPECT_FALSE(force_break_lock); ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } BreakRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; template <> struct GetLockerRequest<librbd::MockImageCtx> { Locker *locker = nullptr; Context *on_finish = nullptr; static GetLockerRequest *s_instance; static GetLockerRequest* create(librados::IoCtx& ioctx, const std::string& oid, bool exclusive, Locker *locker, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->locker = locker; s_instance->on_finish = on_finish; return s_instance; } GetLockerRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; BreakRequest<librbd::MockImageCtx> *BreakRequest<librbd::MockImageCtx>::s_instance = nullptr; GetLockerRequest<librbd::MockImageCtx> *GetLockerRequest<librbd::MockImageCtx>::s_instance = nullptr; } // namespace managed_lock } // namespace librbd // template definitions #include "librbd/managed_lock/AcquireRequest.cc" template class librbd::managed_lock::AcquireRequest<librbd::MockImageCtx>; namespace { MATCHER_P(IsLockType, exclusive, "") { cls_lock_lock_op op; bufferlist bl; bl.share(arg); auto iter = bl.cbegin(); decode(op, iter); return op.type == (exclusive ? ClsLockType::EXCLUSIVE : ClsLockType::SHARED); } } // anonymous namespace namespace librbd { namespace managed_lock { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::SetArgPointee; using ::testing::StrEq; using ::testing::WithArg; static const std::string TEST_COOKIE("auto 123"); class TestMockManagedLockAcquireRequest : public TestMockFixture { public: typedef AcquireRequest<MockImageCtx> MockAcquireRequest; typedef BreakRequest<MockImageCtx> MockBreakRequest; typedef GetLockerRequest<MockImageCtx> MockGetLockerRequest; void expect_lock(MockImageCtx &mock_image_ctx, int r, bool exclusive = true) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("lock"), StrEq("lock"), IsLockType(exclusive), _, _, _)) .WillOnce(Return(r)); } void expect_get_locker(MockImageCtx &mock_image_ctx, MockGetLockerRequest &mock_get_locker_request, const Locker &locker, int r) { EXPECT_CALL(mock_get_locker_request, send()) .WillOnce(Invoke([&mock_image_ctx, &mock_get_locker_request, locker, r]() { *mock_get_locker_request.locker = locker; mock_image_ctx.image_ctx->op_work_queue->queue( mock_get_locker_request.on_finish, r); })); } void expect_break_lock(MockImageCtx &mock_image_ctx, MockBreakRequest &mock_break_request, int r) { EXPECT_CALL(mock_break_request, send()) .WillOnce(FinishRequest(&mock_break_request, r, &mock_image_ctx)); } }; TEST_F(TestMockManagedLockAcquireRequest, SuccessExclusive) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockGetLockerRequest mock_get_locker_request; InSequence seq; expect_get_locker(mock_image_ctx, mock_get_locker_request, {}, 0); expect_lock(mock_image_ctx, 0); C_SaferCond ctx; MockAcquireRequest *req = MockAcquireRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.image_watcher, *ictx->asio_engine, mock_image_ctx.header_oid, TEST_COOKIE, true, true, 0, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockManagedLockAcquireRequest, SuccessShared) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockGetLockerRequest mock_get_locker_request; InSequence seq; expect_get_locker(mock_image_ctx, mock_get_locker_request, {}, 0); expect_lock(mock_image_ctx, 0, false); C_SaferCond ctx; MockAcquireRequest *req = MockAcquireRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.image_watcher, *ictx->asio_engine, mock_image_ctx.header_oid, TEST_COOKIE, false, true, 0, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockManagedLockAcquireRequest, LockBusy) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockGetLockerRequest mock_get_locker_request; MockBreakRequest mock_break_request; expect_op_work_queue(mock_image_ctx); InSequence seq; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}, 0); expect_lock(mock_image_ctx, -EBUSY); expect_break_lock(mock_image_ctx, mock_break_request, 0); expect_lock(mock_image_ctx, -ENOENT); C_SaferCond ctx; MockAcquireRequest *req = MockAcquireRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.image_watcher, *ictx->asio_engine, mock_image_ctx.header_oid, TEST_COOKIE, true, true, 0, &ctx); req->send(); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockManagedLockAcquireRequest, GetLockInfoError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockGetLockerRequest mock_get_locker_request; InSequence seq; expect_get_locker(mock_image_ctx, mock_get_locker_request, {}, -EINVAL); C_SaferCond ctx; MockAcquireRequest *req = MockAcquireRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.image_watcher, *ictx->asio_engine, mock_image_ctx.header_oid, TEST_COOKIE, true, true, 0, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockManagedLockAcquireRequest, GetLockInfoEmpty) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockGetLockerRequest mock_get_locker_request; InSequence seq; expect_get_locker(mock_image_ctx, mock_get_locker_request, {}, -ENOENT); expect_lock(mock_image_ctx, -EINVAL); C_SaferCond ctx; MockAcquireRequest *req = MockAcquireRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.image_watcher, *ictx->asio_engine, mock_image_ctx.header_oid, TEST_COOKIE, true, true, 0, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockManagedLockAcquireRequest, BreakLockError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockGetLockerRequest mock_get_locker_request; MockBreakRequest mock_break_request; InSequence seq; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}, 0); expect_lock(mock_image_ctx, -EBUSY); expect_break_lock(mock_image_ctx, mock_break_request, -EINVAL); C_SaferCond ctx; MockAcquireRequest *req = MockAcquireRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.image_watcher, *ictx->asio_engine, mock_image_ctx.header_oid, TEST_COOKIE, true, true, 0, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } } // namespace managed_lock } // namespace librbd
8,851
31.544118
101
cc
null
ceph-main/src/test/librbd/managed_lock/test_mock_BreakRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "cls/lock/cls_lock_ops.h" #include "librbd/managed_lock/BreakRequest.h" #include "librbd/managed_lock/GetLockerRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <arpa/inet.h> #include <list> namespace librbd { namespace { struct MockTestImageCtx : public librbd::MockImageCtx { MockTestImageCtx(librbd::ImageCtx &image_ctx) : librbd::MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace managed_lock { template <> struct GetLockerRequest<librbd::MockTestImageCtx> { Locker *locker; Context *on_finish = nullptr; static GetLockerRequest *s_instance; static GetLockerRequest* create(librados::IoCtx& ioctx, const std::string& oid, bool exclusive, Locker *locker, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->locker = locker; s_instance->on_finish = on_finish; return s_instance; } GetLockerRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; GetLockerRequest<librbd::MockTestImageCtx> *GetLockerRequest<librbd::MockTestImageCtx>::s_instance = nullptr; } // namespace managed_lock } // namespace librbd // template definitions #include "librbd/managed_lock/BreakRequest.cc" namespace librbd { namespace managed_lock { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::SetArgPointee; using ::testing::StrEq; using ::testing::WithArg; class TestMockManagedLockBreakRequest : public TestMockFixture { public: typedef BreakRequest<MockTestImageCtx> MockBreakRequest; typedef GetLockerRequest<MockTestImageCtx> MockGetLockerRequest; void expect_list_watchers(MockTestImageCtx &mock_image_ctx, int r, const std::string &address, uint64_t watch_handle) { auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), list_watchers(mock_image_ctx.header_oid, _)); if (r < 0) { expect.WillOnce(Return(r)); } else { obj_watch_t watcher; strncpy(watcher.addr, (address + ":0/0").c_str(), sizeof(watcher.addr) - 1); watcher.addr[sizeof(watcher.addr) - 1] = '\0'; watcher.watcher_id = 0; watcher.cookie = watch_handle; std::list<obj_watch_t> watchers; watchers.push_back(watcher); expect.WillOnce(DoAll(SetArgPointee<1>(watchers), Return(0))); } } void expect_get_locker(MockImageCtx &mock_image_ctx, MockGetLockerRequest &mock_get_locker_request, const Locker &locker, int r) { EXPECT_CALL(mock_get_locker_request, send()) .WillOnce(Invoke([&mock_image_ctx, &mock_get_locker_request, locker, r]() { *mock_get_locker_request.locker = locker; mock_image_ctx.image_ctx->op_work_queue->queue( mock_get_locker_request.on_finish, r); })); } void expect_blocklist_add(MockTestImageCtx &mock_image_ctx, int r) { auto& mock_rados_client = librados::get_mock_rados_client( mock_image_ctx.rados_api); EXPECT_CALL(mock_rados_client, blocklist_add(_, _)).WillOnce(Return(r)); } void expect_wait_for_latest_osd_map(MockTestImageCtx &mock_image_ctx, int r) { auto& mock_rados_client = librados::get_mock_rados_client( mock_image_ctx.rados_api); EXPECT_CALL(mock_rados_client, wait_for_latest_osd_map()) .WillOnce(Return(r)); } void expect_break_lock(MockTestImageCtx &mock_image_ctx, int r) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("lock"), StrEq("break_lock"), _, _, _, _)) .WillOnce(Return(r)); } void expect_get_instance_id(MockTestImageCtx &mock_image_ctx, uint64_t id) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), get_instance_id()) .WillOnce(Return(id)); } }; TEST_F(TestMockManagedLockBreakRequest, DeadLockOwner) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "dead client", 123); MockGetLockerRequest mock_get_locker_request; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}, 0); expect_blocklist_add(mock_image_ctx, 0); expect_wait_for_latest_osd_map(mock_image_ctx, 0); expect_break_lock(mock_image_ctx, 0); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, true, 0, false, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, ForceBreak) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "1.2.3.4", 123); MockGetLockerRequest mock_get_locker_request; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}, 0); expect_blocklist_add(mock_image_ctx, 0); expect_wait_for_latest_osd_map(mock_image_ctx, 0); expect_break_lock(mock_image_ctx, 0); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, true, 0, true, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, GetWatchersError) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, -EINVAL, "dead client", 123); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, true, 0, false, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, GetWatchersAlive) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "1.2.3.4", 123); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, true, 0, false, &ctx); req->send(); ASSERT_EQ(-EAGAIN, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, GetLockerUpdated) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "dead client", 123); MockGetLockerRequest mock_get_locker_request; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(2), "auto 123", "1.2.3.4:0/0", 123}, 0); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, false, 0, false, &ctx); req->send(); ASSERT_EQ(-EAGAIN, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, GetLockerBusy) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "dead client", 123); MockGetLockerRequest mock_get_locker_request; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}, -EBUSY); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, false, 0, false, &ctx); req->send(); ASSERT_EQ(-EAGAIN, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, GetLockerMissing) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "dead client", 123); MockGetLockerRequest mock_get_locker_request; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}, -ENOENT); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, false, 0, false, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, GetLockerError) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "dead client", 123); MockGetLockerRequest mock_get_locker_request; expect_get_locker(mock_image_ctx, mock_get_locker_request, {}, -EINVAL); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, false, 0, false, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, BlocklistDisabled) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "dead client", 123); MockGetLockerRequest mock_get_locker_request; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}, 0); expect_break_lock(mock_image_ctx, 0); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, false, 0, false, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, BlocklistSelf) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "dead client", 456); MockGetLockerRequest mock_get_locker_request; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(456), "auto 123", "1.2.3.4:0/0", 123}, 0); expect_get_instance_id(mock_image_ctx, 456); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(456), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, true, 0, false, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, BlocklistError) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "dead client", 123); MockGetLockerRequest mock_get_locker_request; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}, 0); expect_blocklist_add(mock_image_ctx, -EINVAL); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, true, 0, false, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, BreakLockMissing) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "dead client", 123); MockGetLockerRequest mock_get_locker_request; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}, 0); expect_blocklist_add(mock_image_ctx, 0); expect_wait_for_latest_osd_map(mock_image_ctx, 0); expect_break_lock(mock_image_ctx, -ENOENT); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, true, 0, false, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockManagedLockBreakRequest, BreakLockError) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_list_watchers(mock_image_ctx, 0, "dead client", 123); MockGetLockerRequest mock_get_locker_request; expect_get_locker(mock_image_ctx, mock_get_locker_request, {entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}, 0); expect_blocklist_add(mock_image_ctx, 0); expect_wait_for_latest_osd_map(mock_image_ctx, 0); expect_break_lock(mock_image_ctx, -EINVAL); C_SaferCond ctx; Locker locker{entity_name_t::CLIENT(1), "auto 123", "1.2.3.4:0/0", 123}; MockBreakRequest *req = MockBreakRequest::create( mock_image_ctx.md_ctx, *ictx->asio_engine, mock_image_ctx.header_oid, locker, true, true, 0, false, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } } // namespace managed_lock } // namespace librbd
15,949
31.886598
109
cc
null
ceph-main/src/test/librbd/managed_lock/test_mock_GetLockerRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "cls/lock/cls_lock_ops.h" #include "librbd/managed_lock/GetLockerRequest.h" #include "librbd/managed_lock/Types.h" #include "librbd/managed_lock/Utils.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <arpa/inet.h> #include <list> namespace librbd { namespace { struct MockTestImageCtx : public librbd::MockImageCtx { MockTestImageCtx(librbd::ImageCtx &image_ctx) : librbd::MockImageCtx(image_ctx) { } }; } // anonymous namespace } // namespace librbd // template definitions #include "librbd/managed_lock/GetLockerRequest.cc" namespace librbd { namespace managed_lock { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; class TestMockManagedLockGetLockerRequest : public TestMockFixture { public: typedef GetLockerRequest<MockTestImageCtx> MockGetLockerRequest; void expect_get_lock_info(MockTestImageCtx &mock_image_ctx, int r, const entity_name_t &locker_entity, const std::string &locker_address, const std::string &locker_cookie, const std::string &lock_tag, ClsLockType lock_type) { auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("lock"), StrEq("get_info"), _, _, _, _)); if (r < 0 && r != -ENOENT) { expect.WillOnce(Return(r)); } else { entity_name_t entity(locker_entity); entity_addr_t entity_addr; entity_addr.parse(locker_address.c_str(), NULL); cls_lock_get_info_reply reply; if (r != -ENOENT) { reply.lockers.emplace( rados::cls::lock::locker_id_t(entity, locker_cookie), rados::cls::lock::locker_info_t(utime_t(), entity_addr, "")); reply.tag = lock_tag; reply.lock_type = lock_type; } bufferlist bl; encode(reply, bl, CEPH_FEATURES_SUPPORTED_DEFAULT); std::string str(bl.c_str(), bl.length()); expect.WillOnce(DoAll(WithArg<5>(CopyInBufferlist(str)), Return(0))); } } }; TEST_F(TestMockManagedLockGetLockerRequest, SuccessExclusive) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_get_lock_info(mock_image_ctx, 0, entity_name_t::CLIENT(1), "1.2.3.4", "auto 123", util::get_watcher_lock_tag(), ClsLockType::EXCLUSIVE); C_SaferCond ctx; Locker locker; MockGetLockerRequest *req = MockGetLockerRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, true, &locker, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); ASSERT_EQ(entity_name_t::CLIENT(1), locker.entity); ASSERT_EQ("1.2.3.4:0/0", locker.address); ASSERT_EQ("auto 123", locker.cookie); ASSERT_EQ(123U, locker.handle); } TEST_F(TestMockManagedLockGetLockerRequest, SuccessShared) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_get_lock_info(mock_image_ctx, 0, entity_name_t::CLIENT(1), "1.2.3.4", "auto 123", util::get_watcher_lock_tag(), ClsLockType::SHARED); C_SaferCond ctx; Locker locker; MockGetLockerRequest *req = MockGetLockerRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, false, &locker, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); ASSERT_EQ(entity_name_t::CLIENT(1), locker.entity); ASSERT_EQ("1.2.3.4:0/0", locker.address); ASSERT_EQ("auto 123", locker.cookie); ASSERT_EQ(123U, locker.handle); } TEST_F(TestMockManagedLockGetLockerRequest, GetLockInfoError) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_get_lock_info(mock_image_ctx, -EINVAL, entity_name_t::CLIENT(1), "", "", "", ClsLockType::EXCLUSIVE); C_SaferCond ctx; Locker locker; MockGetLockerRequest *req = MockGetLockerRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, true, &locker, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockManagedLockGetLockerRequest, GetLockInfoEmpty) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_get_lock_info(mock_image_ctx, -ENOENT, entity_name_t::CLIENT(1), "", "", "", ClsLockType::EXCLUSIVE); C_SaferCond ctx; Locker locker; MockGetLockerRequest *req = MockGetLockerRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, true, &locker, &ctx); req->send(); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockManagedLockGetLockerRequest, GetLockInfoExternalTag) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_get_lock_info(mock_image_ctx, 0, entity_name_t::CLIENT(1), "1.2.3.4", "auto 123", "external tag", ClsLockType::EXCLUSIVE); C_SaferCond ctx; Locker locker; MockGetLockerRequest *req = MockGetLockerRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, true, &locker, &ctx); req->send(); ASSERT_EQ(-EBUSY, ctx.wait()); } TEST_F(TestMockManagedLockGetLockerRequest, GetLockInfoIncompatibleShared) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_get_lock_info(mock_image_ctx, 0, entity_name_t::CLIENT(1), "1.2.3.4", "auto 123", util::get_watcher_lock_tag(), ClsLockType::SHARED); C_SaferCond ctx; Locker locker; MockGetLockerRequest *req = MockGetLockerRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, true, &locker, &ctx); req->send(); ASSERT_EQ(-EBUSY, ctx.wait()); } TEST_F(TestMockManagedLockGetLockerRequest, GetLockInfoIncompatibleExclusive) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_get_lock_info(mock_image_ctx, 0, entity_name_t::CLIENT(1), "1.2.3.4", "auto 123", util::get_watcher_lock_tag(), ClsLockType::EXCLUSIVE); C_SaferCond ctx; Locker locker; MockGetLockerRequest *req = MockGetLockerRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, false, &locker, &ctx); req->send(); ASSERT_EQ(-EBUSY, ctx.wait()); } TEST_F(TestMockManagedLockGetLockerRequest, GetLockInfoExternalCookie) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_get_lock_info(mock_image_ctx, 0, entity_name_t::CLIENT(1), "1.2.3.4", "external cookie", util::get_watcher_lock_tag(), ClsLockType::EXCLUSIVE); C_SaferCond ctx; Locker locker; MockGetLockerRequest *req = MockGetLockerRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, true, &locker, &ctx); req->send(); ASSERT_EQ(-EBUSY, ctx.wait()); } TEST_F(TestMockManagedLockGetLockerRequest, GetLockInfoEmptyCookie) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_get_lock_info(mock_image_ctx, 0, entity_name_t::CLIENT(1), "1.2.3.4", "", util::get_watcher_lock_tag(), ClsLockType::EXCLUSIVE); C_SaferCond ctx; Locker locker; MockGetLockerRequest *req = MockGetLockerRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, true, &locker, &ctx); req->send(); ASSERT_EQ(-EBUSY, ctx.wait()); } TEST_F(TestMockManagedLockGetLockerRequest, GetLockInfoBlankAddress) { REQUIRE_FEATURE(RBD_FEATURE_EXCLUSIVE_LOCK); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_get_lock_info(mock_image_ctx, 0, entity_name_t::CLIENT(1), "", "auto 123", util::get_watcher_lock_tag(), ClsLockType::EXCLUSIVE); C_SaferCond ctx; Locker locker; MockGetLockerRequest *req = MockGetLockerRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, true, &locker, &ctx); req->send(); ASSERT_EQ(-EBUSY, ctx.wait()); } } // namespace managed_lock } // namespace librbd
9,888
30.9
80
cc
null
ceph-main/src/test/librbd/managed_lock/test_mock_ReacquireRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "cls/lock/cls_lock_ops.h" #include "librbd/managed_lock/ReacquireRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <arpa/inet.h> #include <list> // template definitions #include "librbd/managed_lock/ReacquireRequest.cc" template class librbd::managed_lock::ReacquireRequest<librbd::MockImageCtx>; namespace { MATCHER_P(IsLockType, exclusive, "") { cls_lock_set_cookie_op op; bufferlist bl; bl.share(arg); auto iter = bl.cbegin(); decode(op, iter); return op.type == (exclusive ? ClsLockType::EXCLUSIVE : ClsLockType::SHARED); } } // anonymous namespace namespace librbd { namespace managed_lock { using ::testing::_; using ::testing::InSequence; using ::testing::Return; using ::testing::StrEq; class TestMockManagedLockReacquireRequest : public TestMockFixture { public: typedef ReacquireRequest<MockImageCtx> MockReacquireRequest; void expect_set_cookie(MockImageCtx &mock_image_ctx, int r, bool exclusive = true) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("lock"), StrEq("set_cookie"), IsLockType(exclusive), _, _, _)) .WillOnce(Return(r)); } }; TEST_F(TestMockManagedLockReacquireRequest, SuccessExclusive) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); InSequence seq; expect_set_cookie(mock_image_ctx, 0); C_SaferCond ctx; MockReacquireRequest *req = MockReacquireRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, "old_cookie", "new_cookie", true, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockManagedLockReacquireRequest, SuccessShared) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); InSequence seq; expect_set_cookie(mock_image_ctx, 0, false); C_SaferCond ctx; MockReacquireRequest *req = MockReacquireRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, "old_cookie", "new_cookie", false, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockManagedLockReacquireRequest, NotSupported) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); InSequence seq; expect_set_cookie(mock_image_ctx, -EOPNOTSUPP); C_SaferCond ctx; MockReacquireRequest *req = MockReacquireRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, "old_cookie", "new_cookie", true, &ctx); req->send(); ASSERT_EQ(-EOPNOTSUPP, ctx.wait()); } TEST_F(TestMockManagedLockReacquireRequest, Error) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); InSequence seq; expect_set_cookie(mock_image_ctx, -EBUSY); C_SaferCond ctx; MockReacquireRequest *req = MockReacquireRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.header_oid, "old_cookie", "new_cookie", true, &ctx); req->send(); ASSERT_EQ(-EBUSY, ctx.wait()); } } // namespace managed_lock } // namespace librbd
3,474
27.024194
79
cc
null
ceph-main/src/test/librbd/managed_lock/test_mock_ReleaseRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "librbd/managed_lock/ReleaseRequest.h" #include "common/WorkQueue.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <list> namespace librbd { namespace watcher { template <> struct Traits<MockImageCtx> { typedef librbd::MockImageWatcher Watcher; }; } } // template definitions #include "librbd/managed_lock/ReleaseRequest.cc" template class librbd::managed_lock::ReleaseRequest<librbd::MockImageCtx>; namespace librbd { namespace managed_lock { using ::testing::_; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; static const std::string TEST_COOKIE("auto 123"); class TestMockManagedLockReleaseRequest : public TestMockFixture { public: typedef ReleaseRequest<MockImageCtx> MockReleaseRequest; void expect_unlock(MockImageCtx &mock_image_ctx, int r) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("lock"), StrEq("unlock"), _, _, _, _)) .WillOnce(Return(r)); } }; TEST_F(TestMockManagedLockReleaseRequest, Success) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_unlock(mock_image_ctx, 0); C_SaferCond ctx; MockReleaseRequest *req = MockReleaseRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.image_watcher, ictx->op_work_queue, mock_image_ctx.header_oid, TEST_COOKIE, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockManagedLockReleaseRequest, UnlockError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_unlock(mock_image_ctx, -EINVAL); C_SaferCond ctx; MockReleaseRequest *req = MockReleaseRequest::create( mock_image_ctx.md_ctx, mock_image_ctx.image_watcher, ictx->op_work_queue, mock_image_ctx.header_oid, TEST_COOKIE, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } } // namespace managed_lock } // namespace librbd
2,406
25.163043
79
cc
null
ceph-main/src/test/librbd/migration/test_mock_FileStream.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "include/rbd_types.h" #include "common/ceph_mutex.h" #include "librbd/migration/FileStream.h" #include "gtest/gtest.h" #include "gmock/gmock.h" #include "json_spirit/json_spirit.h" #include <filesystem> namespace fs = std::filesystem; namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace } // namespace librbd #include "librbd/migration/FileStream.cc" namespace librbd { namespace migration { using ::testing::Invoke; class TestMockMigrationFileStream : public TestMockFixture { public: typedef FileStream<MockTestImageCtx> MockFileStream; librbd::ImageCtx *m_image_ctx; void SetUp() override { TestMockFixture::SetUp(); ASSERT_EQ(0, open_image(m_image_name, &m_image_ctx)); file_name = fs::temp_directory_path() / "TestMockMigrationFileStream"; file_name += stringify(getpid()); json_object["file_path"] = file_name; } void TearDown() override { fs::remove(file_name); TestMockFixture::TearDown(); } std::string file_name; json_spirit::mObject json_object; }; TEST_F(TestMockMigrationFileStream, OpenClose) { MockTestImageCtx mock_image_ctx(*m_image_ctx); bufferlist bl; ASSERT_EQ(0, bl.write_file(file_name.c_str())); MockFileStream mock_file_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_file_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; mock_file_stream.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationFileStream, GetSize) { MockTestImageCtx mock_image_ctx(*m_image_ctx); bufferlist expect_bl; expect_bl.append(std::string(128, '1')); ASSERT_EQ(0, expect_bl.write_file(file_name.c_str())); MockFileStream mock_file_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_file_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; uint64_t size; mock_file_stream.get_size(&size, &ctx2); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(128, size); C_SaferCond ctx3; mock_file_stream.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationFileStream, Read) { MockTestImageCtx mock_image_ctx(*m_image_ctx); bufferlist expect_bl; expect_bl.append(std::string(128, '1')); ASSERT_EQ(0, expect_bl.write_file(file_name.c_str())); MockFileStream mock_file_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_file_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; bufferlist bl; mock_file_stream.read({{0, 128}}, &bl, &ctx2); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; mock_file_stream.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationFileStream, SeekRead) { MockTestImageCtx mock_image_ctx(*m_image_ctx); bufferlist write_bl; write_bl.append(std::string(32, '1')); write_bl.append(std::string(64, '2')); write_bl.append(std::string(16, '3')); ASSERT_EQ(0, write_bl.write_file(file_name.c_str())); MockFileStream mock_file_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_file_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; bufferlist bl; mock_file_stream.read({{96, 16}, {32, 64}, {0, 32}}, &bl, &ctx2); ASSERT_EQ(0, ctx2.wait()); bufferlist expect_bl; expect_bl.append(std::string(16, '3')); expect_bl.append(std::string(64, '2')); expect_bl.append(std::string(32, '1')); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; mock_file_stream.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationFileStream, DNE) { MockTestImageCtx mock_image_ctx(*m_image_ctx); MockFileStream mock_file_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_file_stream.open(&ctx1); ASSERT_EQ(-ENOENT, ctx1.wait()); C_SaferCond ctx2; mock_file_stream.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationFileStream, SeekError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); bufferlist bl; ASSERT_EQ(0, bl.write_file(file_name.c_str())); MockFileStream mock_file_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_file_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; mock_file_stream.read({{128, 128}}, &bl, &ctx2); ASSERT_EQ(-ERANGE, ctx2.wait()); C_SaferCond ctx3; mock_file_stream.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationFileStream, ShortReadError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); bufferlist expect_bl; expect_bl.append(std::string(128, '1')); ASSERT_EQ(0, expect_bl.write_file(file_name.c_str())); MockFileStream mock_file_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_file_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; bufferlist bl; mock_file_stream.read({{0, 256}}, &bl, &ctx2); ASSERT_EQ(-ERANGE, ctx2.wait()); C_SaferCond ctx3; mock_file_stream.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } } // namespace migration } // namespace librbd
5,237
23.476636
74
cc
null
ceph-main/src/test/librbd/migration/test_mock_HttpClient.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "include/rbd_types.h" #include "common/ceph_mutex.h" #include "librbd/migration/HttpClient.h" #include "gtest/gtest.h" #include "gmock/gmock.h" #include <unistd.h> #include <boost/asio/ip/tcp.hpp> #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace util { inline ImageCtx *get_image_ctx(MockTestImageCtx *image_ctx) { return image_ctx->image_ctx; } } // namespace util } // namespace librbd #include "librbd/migration/HttpClient.cc" using EmptyHttpRequest = boost::beast::http::request< boost::beast::http::empty_body>; using HttpResponse = boost::beast::http::response< boost::beast::http::string_body>; namespace boost { namespace beast { namespace http { template <typename Body> bool operator==(const boost::beast::http::request<Body>& lhs, const boost::beast::http::request<Body>& rhs) { return (lhs.method() == rhs.method() && lhs.target() == rhs.target()); } template <typename Body> bool operator==(const boost::beast::http::response<Body>& lhs, const boost::beast::http::response<Body>& rhs) { return (lhs.result() == rhs.result() && lhs.body() == rhs.body()); } } // namespace http } // namespace beast } // namespace boost namespace librbd { namespace migration { using ::testing::Invoke; class TestMockMigrationHttpClient : public TestMockFixture { public: typedef HttpClient<MockTestImageCtx> MockHttpClient; void SetUp() override { TestMockFixture::SetUp(); ASSERT_EQ(0, open_image(m_image_name, &m_image_ctx)); create_acceptor(false); } void TearDown() override { m_acceptor.reset(); TestMockFixture::TearDown(); } // if we have a racing where another thread manages to bind and listen the // port picked by this acceptor, try again. static constexpr int MAX_BIND_RETRIES = 60; void create_acceptor(bool reuse) { for (int retries = 0;; retries++) { try { m_acceptor.emplace(*m_image_ctx->asio_engine, boost::asio::ip::tcp::endpoint( boost::asio::ip::tcp::v4(), m_server_port), reuse); // yay! break; } catch (const boost::system::system_error& e) { if (retries == MAX_BIND_RETRIES) { throw; } if (e.code() != boost::system::errc::address_in_use) { throw; } } // backoff a little bit sleep(1); } m_server_port = m_acceptor->local_endpoint().port(); } std::string get_local_url(UrlScheme url_scheme) { std::stringstream sstream; switch (url_scheme) { case URL_SCHEME_HTTP: sstream << "http://127.0.0.1"; break; case URL_SCHEME_HTTPS: sstream << "https://localhost"; break; default: ceph_assert(false); break; } sstream << ":" << m_server_port << "/target"; return sstream.str(); } void client_accept(boost::asio::ip::tcp::socket* socket, bool close, Context* on_connect) { m_acceptor->async_accept( boost::asio::make_strand(m_image_ctx->asio_engine->get_executor()), [socket, close, on_connect] (auto ec, boost::asio::ip::tcp::socket in_socket) { if (close) { in_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both); } else { ASSERT_FALSE(ec) << "Unexpected error: " << ec; *socket = std::move(in_socket); } on_connect->complete(0); }); } template <typename Body> void client_read_request(boost::asio::ip::tcp::socket& socket, boost::beast::http::request<Body>& expected_req) { boost::beast::http::request<Body> req; boost::beast::error_code ec; boost::beast::http::read(socket, m_buffer, req, ec); ASSERT_FALSE(ec) << "Unexpected errror: " << ec; expected_req.target("/target"); ASSERT_EQ(expected_req, req); } void client_write_response(boost::asio::ip::tcp::socket& socket, HttpResponse& expected_res) { expected_res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); expected_res.set(boost::beast::http::field::content_type, "text/plain"); expected_res.content_length(expected_res.body().size()); expected_res.prepare_payload(); boost::beast::error_code ec; boost::beast::http::write(socket, expected_res, ec); ASSERT_FALSE(ec) << "Unexpected errror: " << ec; } template <typename Stream> void client_ssl_handshake(Stream& stream, bool ignore_failure, Context* on_handshake) { stream.async_handshake( boost::asio::ssl::stream_base::server, [ignore_failure, on_handshake](auto ec) { ASSERT_FALSE(!ignore_failure && ec) << "Unexpected error: " << ec; on_handshake->complete(-ec.value()); }); } template <typename Stream> void client_ssl_shutdown(Stream& stream, Context* on_shutdown) { stream.async_shutdown( [on_shutdown](auto ec) { ASSERT_FALSE(ec) << "Unexpected error: " << ec; on_shutdown->complete(-ec.value()); }); } void load_server_certificate(boost::asio::ssl::context& ctx) { ctx.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); ctx.use_certificate_chain( boost::asio::buffer(CERTIFICATE.data(), CERTIFICATE.size())); ctx.use_private_key( boost::asio::buffer(KEY.data(), KEY.size()), boost::asio::ssl::context::file_format::pem); ctx.use_tmp_dh( boost::asio::buffer(DH.data(), DH.size())); } // dummy self-signed cert for localhost const std::string CERTIFICATE = "-----BEGIN CERTIFICATE-----\n" "MIIDXzCCAkegAwIBAgIUYH6rAaq66LC6yJ3XK1WEMIfmY4cwDQYJKoZIhvcNAQEL\n" "BQAwPzELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAlZBMQ8wDQYDVQQHDAZNY0xlYW4x\n" "EjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0yMDExMDIyMTM5NTVaFw00ODAzMjAyMTM5\n" "NTVaMD8xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJWQTEPMA0GA1UEBwwGTWNMZWFu\n" "MRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK\n" "AoIBAQCeRkyxjP0eNHxzj4/R+Bg/31p7kEjB5d/LYtrzBIYNe+3DN8gdReixEpR5\n" "lgTLDsl8gfk2HRz4cnAiseqYL6GKtw/cFadzLyXTbW4iavmTWiGYw/8RJlKunbhA\n" "hDjM6H99ysLf0NS6t14eK+bEJIW1PiTYRR1U5I4kSIjpCX7+nJVuwMEZ2XBpN3og\n" "nHhv2hZYTdzEkQEyZHz4V/ApfD7rlja5ecd/vJfPJeA8nudnGCh3Uo6f8I9TObAj\n" "8hJdfRiRBvnA4NnkrMrxW9UtVjScnw9Xia11FM/IGJIgMpLQ5dqBw930p6FxMYtn\n" "tRD1AF9sT+YjoCaHv0hXZvBEUEF3AgMBAAGjUzBRMB0GA1UdDgQWBBTQoIiX3+p/\n" "P4Xz2vwERz6pbjPGhzAfBgNVHSMEGDAWgBTQoIiX3+p/P4Xz2vwERz6pbjPGhzAP\n" "BgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCVKoYAw+D1qqWRDSh3\n" "2KlKMnT6sySo7XmReGArj8FTKiZUprByj5CfAtaiDSdPOpcg3EazWbdasZbMmSQm\n" "+jpe5WoKnxL9b12lwwUYHrLl6RlrDHVkIVlXLNbJFY5TpfjvZfHpwVAygF3fnbgW\n" "PPuODUNAS5NDwST+t29jBZ/wwU0pyW0CS4K5d3XMGHBc13j2V/FyvmsZ5xfA4U9H\n" "oEnmZ/Qm+FFK/nR40rTAZ37cuv4ysKFtwvatNgTfHGJwaBUkKFdDbcyxt9abCi6x\n" "/K+ScoJtdIeVcfx8Fnc5PNtSpy8bHI3Zy4IEyw4kOqwwI1h37iBafZ2WdQkTxlAx\n" "JIDj\n" "-----END CERTIFICATE-----\n"; const std::string KEY = "-----BEGIN PRIVATE KEY-----\n" "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCeRkyxjP0eNHxz\n" "j4/R+Bg/31p7kEjB5d/LYtrzBIYNe+3DN8gdReixEpR5lgTLDsl8gfk2HRz4cnAi\n" "seqYL6GKtw/cFadzLyXTbW4iavmTWiGYw/8RJlKunbhAhDjM6H99ysLf0NS6t14e\n" "K+bEJIW1PiTYRR1U5I4kSIjpCX7+nJVuwMEZ2XBpN3ognHhv2hZYTdzEkQEyZHz4\n" "V/ApfD7rlja5ecd/vJfPJeA8nudnGCh3Uo6f8I9TObAj8hJdfRiRBvnA4NnkrMrx\n" "W9UtVjScnw9Xia11FM/IGJIgMpLQ5dqBw930p6FxMYtntRD1AF9sT+YjoCaHv0hX\n" "ZvBEUEF3AgMBAAECggEACCaYpoAbPOX5Dr5y6p47KXboIvrgNFQRPVke62rtOF6M\n" "dQQ3YwKJpCzPxp8qKgbd63KKEfZX2peSHMdKzIGPcSRSRcQ7tlvUN9on1M/rgGIg\n" "3swhI5H0qhdnOLNWdX73qdO6S2pmuiLdTvJ11N4IoLfNj/GnPAr1Ivs1ScL6bkQv\n" "UybaNQ/g2lB0tO7vUeVe2W/AqsIb1eQlf2g+SH7xRj2bGQkr4cWTylqfiVoL/Xic\n" "QVTCks3BWaZhYIhTFgvqVhXZpp52O9J+bxsWJItKQrrCBemxwp82xKbiW/KoI9L1\n" "wSnKvxx7Q3RUN5EvXeOpTRR8QIpBoxP3TTeoj+EOMQKBgQDQb/VfLDlLgfYJpgRC\n" "hKCLW90un9op3nA2n9Dmm9TTLYOmUyiv5ub8QDINEw/YK/NE2JsTSUk2msizqTLL\n" "Z82BFbz9kPlDbJ5MgxG5zXeLvOLurAFmZk/z5JJO+65PKjf0QVLncSAJvMCeNFuC\n" "2yZrEzbrItrjQsN6AedWdx6TTwKBgQDCZAsSI3lQgOh2q1GSxjuIzRAc7JnSGBvD\n" "nG8+SkfKAy7BWe638772Dgx8KYO7TLI4zlm8c9Tr/nkZsGWmM5S2DMI69PWOQWNa\n" "R6QzOFFwNg2JETH7ow+x8+9Q9d3WsPzROz3r5uDXgEk0glthaymVoPILFOiYpz3r\n" "heUbd6mFWQKBgQCCJBVJGhyf54IOHij0u0heGrpr/QTDNY5MnNZa1hs4y2cydyOl\n" "SH8aKp7ViPxQlYhriO6ySQS8YkJD4rXDSImIOmFo1Ja9oVjpHsD3iLFGf2YVbTHm\n" "lKUA+8raI8x+wzZyfELeHMTLL534aWpltp0zJ6kXgQi38pyIVh3x36gogwKBgQCt\n" "nba5k49VVFzLKEXqBjzD+QqMGtFjcH7TnZNJmgQ2K9OFgzIPf5atomyKNHXgQibn\n" "T32cMAQaZqR4SjDvWSBX3FtZVtE+Ja57woKn8IPj6ZL7Oa1fpwpskIbM01s31cln\n" "gjbSy9lC/+PiDw9YmeKBLkcfmKQJO021Xlf6yUxRuQKBgBWPODUO8oKjkuJXNI/w\n" "El9hNWkd+/SZDfnt93dlVyXTtTF0M5M95tlOgqvLtWKSyB/BOnoZYWqR8luMl15d\n" "bf75j5mB0lHMWtyQgvZSkFqe9Or7Zy7hfTShDlZ/w+OXK7PGesaE1F14irShXSji\n" "yn5DZYAZ5pU52xreJeYvDngO\n" "-----END PRIVATE KEY-----\n"; const std::string DH = "-----BEGIN DH PARAMETERS-----\n" "MIIBCAKCAQEA4+DA1j0gDWS71okwHpnvA65NmmR4mf+B3H39g163zY5S+cnWS2LI\n" "dvqnUDpw13naWtQ+Nu7I4rk1XoPaxOPSTu1MTbtYOxxU9M1ceBu4kQjDeHwasPVM\n" "zyEs1XXX3tsbPUxAuayX+AgW6QQAQUEjKDnv3FzVnQTFjwI49LqjnrSjbgQcoMaH\n" "EdGGUc6t1/We2vtsJZx0/dbaMkzFYO8dAbEYHL4sPKQb2mLpCPJZC3vwzpFkHFCd\n" "QSnLW2qRhy+66Mf8shdr6uvpoMcnKMOAvjKdXl9PBeJM9eJPz2lC4tnTiM3DqNzK\n" "Hn8+Pu3KkSIFL/5uBVu1fZSq+lFIEI23wwIBAg==\n" "-----END DH PARAMETERS-----\n"; librbd::ImageCtx *m_image_ctx; std::optional<boost::asio::ip::tcp::acceptor> m_acceptor; boost::beast::flat_buffer m_buffer; uint64_t m_server_port = 0; }; TEST_F(TestMockMigrationHttpClient, OpenCloseHttp) { boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx; client_accept(&socket, false, &on_connect_ctx); MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx.wait()); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; http_client.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationHttpClient, OpenCloseHttps) { boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx; client_accept(&socket, false, &on_connect_ctx); MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTPS)); http_client.set_ignore_self_signed_cert(true); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx.wait()); boost::asio::ssl::context ssl_context{boost::asio::ssl::context::tlsv12}; load_server_certificate(ssl_context); boost::beast::ssl_stream<boost::beast::tcp_stream> ssl_stream{ std::move(socket), ssl_context}; C_SaferCond on_ssl_handshake_ctx; client_ssl_handshake(ssl_stream, false, &on_ssl_handshake_ctx); ASSERT_EQ(0, on_ssl_handshake_ctx.wait()); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; http_client.close(&ctx2); C_SaferCond on_ssl_shutdown_ctx; client_ssl_shutdown(ssl_stream, &on_ssl_shutdown_ctx); ASSERT_EQ(0, on_ssl_shutdown_ctx.wait()); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationHttpClient, OpenHttpsHandshakeFail) { boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx; client_accept(&socket, false, &on_connect_ctx); MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTPS)); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx.wait()); boost::asio::ssl::context ssl_context{boost::asio::ssl::context::tlsv12}; load_server_certificate(ssl_context); boost::beast::ssl_stream<boost::beast::tcp_stream> ssl_stream{ std::move(socket), ssl_context}; C_SaferCond on_ssl_handshake_ctx; client_ssl_handshake(ssl_stream, true, &on_ssl_handshake_ctx); ASSERT_NE(0, on_ssl_handshake_ctx.wait()); ASSERT_NE(0, ctx1.wait()); } TEST_F(TestMockMigrationHttpClient, OpenInvalidUrl) { MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, "ftp://nope/"); C_SaferCond ctx; http_client.open(&ctx); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMigrationHttpClient, OpenResolveFail) { MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, "http://foo.example"); C_SaferCond ctx; http_client.open(&ctx); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockMigrationHttpClient, OpenConnectFail) { MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, "http://localhost:2/"); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(-ECONNREFUSED, ctx1.wait()); } TEST_F(TestMockMigrationHttpClient, IssueHead) { boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx; client_accept(&socket, false, &on_connect_ctx); MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx.wait()); ASSERT_EQ(0, ctx1.wait()); EmptyHttpRequest req; req.method(boost::beast::http::verb::head); C_SaferCond ctx2; HttpResponse res; http_client.issue(EmptyHttpRequest{req}, [&ctx2, &res](int r, HttpResponse&& response) mutable { res = std::move(response); ctx2.complete(r); }); HttpResponse expected_res; client_read_request(socket, req); client_write_response(socket, expected_res); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(expected_res, res); C_SaferCond ctx3; http_client.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationHttpClient, IssueGet) { boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx; client_accept(&socket, false, &on_connect_ctx); MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx.wait()); ASSERT_EQ(0, ctx1.wait()); EmptyHttpRequest req; req.method(boost::beast::http::verb::get); C_SaferCond ctx2; HttpResponse res; http_client.issue(EmptyHttpRequest{req}, [&ctx2, &res](int r, HttpResponse&& response) mutable { res = std::move(response); ctx2.complete(r); }); HttpResponse expected_res; expected_res.body() = "test"; client_read_request(socket, req); client_write_response(socket, expected_res); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(expected_res, res); C_SaferCond ctx3; http_client.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationHttpClient, IssueSendFailed) { boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx1; client_accept(&socket, false, &on_connect_ctx1); MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx1.wait()); ASSERT_EQ(0, ctx1.wait()); // close connection to client boost::system::error_code ec; socket.close(ec); C_SaferCond on_connect_ctx2; client_accept(&socket, false, &on_connect_ctx2); // send request via closed connection EmptyHttpRequest req; req.method(boost::beast::http::verb::get); C_SaferCond ctx2; http_client.issue(EmptyHttpRequest{req}, [&ctx2](int r, HttpResponse&&) mutable { ctx2.complete(r); }); // connection will be reset and request retried ASSERT_EQ(0, on_connect_ctx2.wait()); HttpResponse expected_res; expected_res.body() = "test"; client_read_request(socket, req); client_write_response(socket, expected_res); ASSERT_EQ(0, ctx2.wait()); C_SaferCond ctx3; http_client.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationHttpClient, IssueReceiveFailed) { boost::asio::ip::tcp::socket socket1(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx1; client_accept(&socket1, false, &on_connect_ctx1); MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx1.wait()); ASSERT_EQ(0, ctx1.wait()); // send request via closed connection EmptyHttpRequest req; req.method(boost::beast::http::verb::get); C_SaferCond ctx2; http_client.issue(EmptyHttpRequest{req}, [&ctx2](int r, HttpResponse&&) mutable { ctx2.complete(r); }); // close connection to client after reading request client_read_request(socket1, req); C_SaferCond on_connect_ctx2; boost::asio::ip::tcp::socket socket2(*m_image_ctx->asio_engine); client_accept(&socket2, false, &on_connect_ctx2); boost::system::error_code ec; socket1.close(ec); ASSERT_EQ(0, on_connect_ctx2.wait()); // connection will be reset and request retried HttpResponse expected_res; expected_res.body() = "test"; client_read_request(socket2, req); client_write_response(socket2, expected_res); ASSERT_EQ(0, ctx2.wait()); C_SaferCond ctx3; http_client.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationHttpClient, IssueResetFailed) { m_server_port = 0; create_acceptor(true); boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx1; client_accept(&socket, false, &on_connect_ctx1); MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx1.wait()); ASSERT_EQ(0, ctx1.wait()); // send requests then close connection EmptyHttpRequest req; req.method(boost::beast::http::verb::get); C_SaferCond ctx2; http_client.issue(EmptyHttpRequest{req}, [&ctx2](int r, HttpResponse&&) mutable { ctx2.complete(r); }); C_SaferCond ctx3; http_client.issue(EmptyHttpRequest{req}, [&ctx3](int r, HttpResponse&&) mutable { ctx3.complete(r); }); client_read_request(socket, req); client_read_request(socket, req); // close connection to client and verify requests are failed m_acceptor.reset(); boost::system::error_code ec; socket.close(ec); ASSERT_EQ(-ECONNREFUSED, ctx2.wait()); ASSERT_EQ(-ECONNREFUSED, ctx3.wait()); // additional request will retry the failed connection create_acceptor(true); C_SaferCond on_connect_ctx2; client_accept(&socket, false, &on_connect_ctx2); C_SaferCond ctx4; http_client.issue(EmptyHttpRequest{req}, [&ctx4](int r, HttpResponse&&) mutable { ctx4.complete(r); }); ASSERT_EQ(0, on_connect_ctx2.wait()); client_read_request(socket, req); HttpResponse expected_res; expected_res.body() = "test"; client_write_response(socket, expected_res); ASSERT_EQ(0, ctx4.wait()); C_SaferCond ctx5; http_client.close(&ctx5); ASSERT_EQ(0, ctx5.wait()); } TEST_F(TestMockMigrationHttpClient, IssuePipelined) { boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx; client_accept(&socket, false, &on_connect_ctx); MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx.wait()); ASSERT_EQ(0, ctx1.wait()); // issue two pipelined (concurrent) get requests EmptyHttpRequest req1; req1.method(boost::beast::http::verb::get); C_SaferCond ctx2; HttpResponse res1; http_client.issue(EmptyHttpRequest{req1}, [&ctx2, &res1](int r, HttpResponse&& response) mutable { res1 = std::move(response); ctx2.complete(r); }); EmptyHttpRequest req2; req2.method(boost::beast::http::verb::get); C_SaferCond ctx3; HttpResponse res2; http_client.issue(EmptyHttpRequest{req2}, [&ctx3, &res2](int r, HttpResponse&& response) mutable { res2 = std::move(response); ctx3.complete(r); }); client_read_request(socket, req1); client_read_request(socket, req2); // read the responses sequentially HttpResponse expected_res1; expected_res1.body() = "test"; client_write_response(socket, expected_res1); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(expected_res1, res1); HttpResponse expected_res2; expected_res2.body() = "test"; client_write_response(socket, expected_res2); ASSERT_EQ(0, ctx3.wait()); ASSERT_EQ(expected_res2, res2); C_SaferCond ctx4; http_client.close(&ctx4); ASSERT_EQ(0, ctx4.wait()); } TEST_F(TestMockMigrationHttpClient, IssuePipelinedRestart) { boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx1; client_accept(&socket, false, &on_connect_ctx1); MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx1.wait()); ASSERT_EQ(0, ctx1.wait()); // issue two pipelined (concurrent) get requests EmptyHttpRequest req1; req1.keep_alive(false); req1.method(boost::beast::http::verb::get); C_SaferCond on_connect_ctx2; client_accept(&socket, false, &on_connect_ctx2); C_SaferCond ctx2; HttpResponse res1; http_client.issue(EmptyHttpRequest{req1}, [&ctx2, &res1](int r, HttpResponse&& response) mutable { res1 = std::move(response); ctx2.complete(r); }); EmptyHttpRequest req2; req2.method(boost::beast::http::verb::get); C_SaferCond ctx3; HttpResponse res2; http_client.issue(EmptyHttpRequest{req2}, [&ctx3, &res2](int r, HttpResponse&& response) mutable { res2 = std::move(response); ctx3.complete(r); }); client_read_request(socket, req1); client_read_request(socket, req2); // read the responses sequentially HttpResponse expected_res1; expected_res1.body() = "test"; expected_res1.keep_alive(false); client_write_response(socket, expected_res1); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(expected_res1, res1); // second request will need to be re-sent due to 'need_eof' condition ASSERT_EQ(0, on_connect_ctx2.wait()); client_read_request(socket, req2); HttpResponse expected_res2; expected_res2.body() = "test"; client_write_response(socket, expected_res2); ASSERT_EQ(0, ctx3.wait()); ASSERT_EQ(expected_res2, res2); C_SaferCond ctx4; http_client.close(&ctx4); ASSERT_EQ(0, ctx4.wait()); } TEST_F(TestMockMigrationHttpClient, ShutdownInFlight) { boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx; client_accept(&socket, false, &on_connect_ctx); MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx.wait()); ASSERT_EQ(0, ctx1.wait()); EmptyHttpRequest req; req.method(boost::beast::http::verb::get); C_SaferCond ctx2; http_client.issue(EmptyHttpRequest{req}, [&ctx2](int r, HttpResponse&&) mutable { ctx2.complete(r); }); client_read_request(socket, req); C_SaferCond ctx3; http_client.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); ASSERT_EQ(-ESHUTDOWN, ctx2.wait()); } TEST_F(TestMockMigrationHttpClient, GetSize) { MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx; client_accept(&socket, false, &on_connect_ctx); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx.wait()); ASSERT_EQ(0, ctx1.wait()); uint64_t size = 0; C_SaferCond ctx2; http_client.get_size(&size, &ctx2); EmptyHttpRequest expected_req; expected_req.method(boost::beast::http::verb::head); client_read_request(socket, expected_req); HttpResponse expected_res; expected_res.body() = std::string(123, '1'); client_write_response(socket, expected_res); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(123, size); C_SaferCond ctx3; http_client.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationHttpClient, GetSizeError) { MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx; client_accept(&socket, false, &on_connect_ctx); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx.wait()); ASSERT_EQ(0, ctx1.wait()); uint64_t size = 0; C_SaferCond ctx2; http_client.get_size(&size, &ctx2); EmptyHttpRequest expected_req; expected_req.method(boost::beast::http::verb::head); client_read_request(socket, expected_req); HttpResponse expected_res; expected_res.result(boost::beast::http::status::internal_server_error); client_write_response(socket, expected_res); ASSERT_EQ(-EIO, ctx2.wait()); C_SaferCond ctx3; http_client.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationHttpClient, Read) { MockTestImageCtx mock_test_image_ctx(*m_image_ctx); MockHttpClient http_client(&mock_test_image_ctx, get_local_url(URL_SCHEME_HTTP)); boost::asio::ip::tcp::socket socket(*m_image_ctx->asio_engine); C_SaferCond on_connect_ctx; client_accept(&socket, false, &on_connect_ctx); C_SaferCond ctx1; http_client.open(&ctx1); ASSERT_EQ(0, on_connect_ctx.wait()); ASSERT_EQ(0, ctx1.wait()); bufferlist bl; C_SaferCond ctx2; http_client.read({{0, 128}, {256, 64}}, &bl, &ctx2); EmptyHttpRequest expected_req1; expected_req1.method(boost::beast::http::verb::get); expected_req1.set(boost::beast::http::field::range, "bytes=0-127"); client_read_request(socket, expected_req1); EmptyHttpRequest expected_req2; expected_req2.method(boost::beast::http::verb::get); expected_req2.set(boost::beast::http::field::range, "bytes=256-319"); client_read_request(socket, expected_req2); HttpResponse expected_res1; expected_res1.result(boost::beast::http::status::partial_content); expected_res1.body() = std::string(128, '1'); client_write_response(socket, expected_res1); HttpResponse expected_res2; expected_res2.result(boost::beast::http::status::partial_content); expected_res2.body() = std::string(64, '2'); client_write_response(socket, expected_res2); ASSERT_EQ(192, ctx2.wait()); bufferlist expect_bl; expect_bl.append(std::string(128, '1')); expect_bl.append(std::string(64, '2')); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; http_client.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } } // namespace migration } // namespace librbd
28,130
30.572391
77
cc
null
ceph-main/src/test/librbd/migration/test_mock_HttpStream.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "include/rbd_types.h" #include "common/ceph_mutex.h" #include "librbd/migration/HttpClient.h" #include "librbd/migration/HttpStream.h" #include "gtest/gtest.h" #include "gmock/gmock.h" #include "json_spirit/json_spirit.h" #include <boost/beast/http.hpp> namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace migration { template <> struct HttpClient<MockTestImageCtx> { static HttpClient* s_instance; static HttpClient* create(MockTestImageCtx*, const std::string&) { ceph_assert(s_instance != nullptr); return s_instance; } MOCK_METHOD1(open, void(Context*)); MOCK_METHOD1(close, void(Context*)); MOCK_METHOD2(get_size, void(uint64_t*, Context*)); MOCK_METHOD3(do_read, void(const io::Extents&, bufferlist*, Context*)); void read(io::Extents&& extents, bufferlist* bl, Context* ctx) { do_read(extents, bl, ctx); } HttpClient() { s_instance = this; } }; HttpClient<MockTestImageCtx>* HttpClient<MockTestImageCtx>::s_instance = nullptr; } // namespace migration } // namespace librbd #include "librbd/migration/HttpStream.cc" namespace librbd { namespace migration { using ::testing::_; using ::testing::Invoke; using ::testing::InSequence; using ::testing::WithArgs; class TestMockMigrationHttpStream : public TestMockFixture { public: typedef HttpStream<MockTestImageCtx> MockHttpStream; typedef HttpClient<MockTestImageCtx> MockHttpClient; librbd::ImageCtx *m_image_ctx; void SetUp() override { TestMockFixture::SetUp(); ASSERT_EQ(0, open_image(m_image_name, &m_image_ctx)); json_object["url"] = "http://some.site/file"; } void expect_open(MockHttpClient& mock_http_client, int r) { EXPECT_CALL(mock_http_client, open(_)) .WillOnce(Invoke([r](Context* ctx) { ctx->complete(r); })); } void expect_close(MockHttpClient& mock_http_client, int r) { EXPECT_CALL(mock_http_client, close(_)) .WillOnce(Invoke([r](Context* ctx) { ctx->complete(r); })); } void expect_get_size(MockHttpClient& mock_http_client, uint64_t size, int r) { EXPECT_CALL(mock_http_client, get_size(_, _)) .WillOnce(Invoke([size, r](uint64_t* out_size, Context* ctx) { *out_size = size; ctx->complete(r); })); } void expect_read(MockHttpClient& mock_http_client, io::Extents byte_extents, const bufferlist& bl, int r) { uint64_t len = 0; for (auto [_, byte_len] : byte_extents) { len += byte_len; } EXPECT_CALL(mock_http_client, do_read(byte_extents, _, _)) .WillOnce(WithArgs<1, 2>(Invoke( [len, bl, r](bufferlist* out_bl, Context* ctx) { *out_bl = bl; ctx->complete(r < 0 ? r : len); }))); } json_spirit::mObject json_object; }; TEST_F(TestMockMigrationHttpStream, OpenClose) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; auto mock_http_client = new MockHttpClient(); expect_open(*mock_http_client, 0); expect_close(*mock_http_client, 0); MockHttpStream mock_http_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_http_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; mock_http_stream.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationHttpStream, GetSize) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; auto mock_http_client = new MockHttpClient(); expect_open(*mock_http_client, 0); expect_get_size(*mock_http_client, 128, 0); expect_close(*mock_http_client, 0); MockHttpStream mock_http_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_http_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; uint64_t size; mock_http_stream.get_size(&size, &ctx2); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(128, size); C_SaferCond ctx3; mock_http_stream.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationHttpStream, Read) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; auto mock_http_client = new MockHttpClient(); expect_open(*mock_http_client, 0); bufferlist expect_bl; expect_bl.append(std::string(192, '1')); expect_read(*mock_http_client, {{0, 128}, {256, 64}}, expect_bl, 0); expect_close(*mock_http_client, 0); MockHttpStream mock_http_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_http_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; bufferlist bl; mock_http_stream.read({{0, 128}, {256, 64}}, &bl, &ctx2); ASSERT_EQ(192, ctx2.wait()); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; mock_http_stream.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } } // namespace migration } // namespace librbd
5,003
24.661538
81
cc
null
ceph-main/src/test/librbd/migration/test_mock_QCOWFormat.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/migration/MockStreamInterface.h" #include "include/rbd_types.h" #include "common/ceph_mutex.h" #include "librbd/migration/QCOWFormat.h" #include "librbd/migration/SourceSpecBuilder.h" #include "acconfig.h" #include "gtest/gtest.h" #include "gmock/gmock.h" #include "json_spirit/json_spirit.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace migration { template<> struct SourceSpecBuilder<librbd::MockTestImageCtx> { MOCK_CONST_METHOD2(build_stream, int(const json_spirit::mObject&, std::shared_ptr<StreamInterface>*)); }; } // namespace migration bool operator==(const SnapInfo& lhs, const SnapInfo& rhs) { return (lhs.name == rhs.name && lhs.size == rhs.size); } } // namespace librbd #include "librbd/migration/QCOWFormat.cc" using ::testing::_; using ::testing::InSequence; using ::testing::Invoke; using ::testing::ReturnRef; using ::testing::WithArg; using ::testing::WithArgs; namespace librbd { namespace migration { using ::testing::Invoke; class TestMockMigrationQCOWFormat : public TestMockFixture { public: typedef QCOWFormat<MockTestImageCtx> MockQCOWFormat; typedef SourceSpecBuilder<MockTestImageCtx> MockSourceSpecBuilder; librbd::ImageCtx *m_image_ctx; void SetUp() override { TestMockFixture::SetUp(); ASSERT_EQ(0, open_image(m_image_name, &m_image_ctx)); json_spirit::mObject stream_obj; stream_obj["type"] = "file"; json_object["stream"] = stream_obj; } void expect_build_stream(MockSourceSpecBuilder& mock_source_spec_builder, MockStreamInterface* mock_stream_interface, int r) { EXPECT_CALL(mock_source_spec_builder, build_stream(_, _)) .WillOnce(WithArgs<1>(Invoke([mock_stream_interface, r] (std::shared_ptr<StreamInterface>* ptr) { ptr->reset(mock_stream_interface); return r; }))); } void expect_stream_open(MockStreamInterface& mock_stream_interface, int r) { EXPECT_CALL(mock_stream_interface, open(_)) .WillOnce(Invoke([r](Context* ctx) { ctx->complete(r); })); } void expect_stream_close(MockStreamInterface& mock_stream_interface, int r) { EXPECT_CALL(mock_stream_interface, close(_)) .WillOnce(Invoke([r](Context* ctx) { ctx->complete(r); })); } void expect_stream_read(MockStreamInterface& mock_stream_interface, const io::Extents& byte_extents, const bufferlist& bl, int r) { EXPECT_CALL(mock_stream_interface, read(byte_extents, _, _)) .WillOnce(WithArgs<1, 2>(Invoke([bl, r] (bufferlist* out_bl, Context* ctx) { *out_bl = bl; ctx->complete(r); }))); } void expect_probe_header(MockStreamInterface& mock_stream_interface, uint32_t magic, uint32_t version, int r) { magic = htobe32(magic); version = htobe32(version); bufferlist probe_bl; probe_bl.append(std::string_view(reinterpret_cast<char*>(&magic), 4)); probe_bl.append(std::string_view(reinterpret_cast<char*>(&version), 4)); expect_stream_read(mock_stream_interface, {{0, 8}}, probe_bl, r); } void expect_read_header(MockStreamInterface& mock_stream_interface, uint32_t snapshot_count, int r) { QCowHeader qcow_header; memset(&qcow_header, 0, sizeof(qcow_header)); qcow_header.magic = htobe32(QCOW_MAGIC); qcow_header.version = htobe32(2); qcow_header.size = htobe64(1<<30); qcow_header.cluster_bits = htobe32(16); qcow_header.l1_size = htobe32(2); qcow_header.l1_table_offset = htobe64(1<<20); if (snapshot_count > 0) { qcow_header.nb_snapshots = htobe32(snapshot_count); qcow_header.snapshots_offset = htobe64(1<<21); } bufferlist header_bl; header_bl.append(std::string_view(reinterpret_cast<char*>(&qcow_header), sizeof(qcow_header))); expect_stream_read(mock_stream_interface, {{0, sizeof(qcow_header)}}, header_bl, r); } void expect_read_l1_table(MockStreamInterface& mock_stream_interface, std::optional<std::vector<uint64_t>>&& l1_table, int r) { bufferlist l1_table_bl; if (!l1_table) { l1_table.emplace(2); } l1_table->resize(2); for (size_t idx = 0; idx < l1_table->size(); ++idx) { (*l1_table)[idx] = htobe64((*l1_table)[idx]); } l1_table_bl.append( std::string_view(reinterpret_cast<char*>(l1_table->data()), 16)); expect_stream_read(mock_stream_interface, {{1<<20, 16}}, l1_table_bl, r); } void expect_read_l2_table(MockStreamInterface& mock_stream_interface, uint64_t l2_table_offset, std::optional<std::vector<uint64_t>>&& l2_table, int r) { size_t l2_table_size = 1<<(16 - 3); // cluster_bit - 3 bits for offset bufferlist l2_table_bl; if (!l2_table) { l2_table.emplace(l2_table_size); } l2_table->resize(l2_table_size); for (size_t idx = 0; idx < l2_table->size(); ++idx) { (*l2_table)[idx] = htobe64((*l2_table)[idx]); } l2_table_bl.append( std::string_view(reinterpret_cast<char*>(l2_table->data()), l2_table->size() * sizeof(uint64_t))); expect_stream_read(mock_stream_interface, {{l2_table_offset, l2_table->size() * sizeof(uint64_t)}}, l2_table_bl, r); } void expect_read_cluster(MockStreamInterface& mock_stream_interface, uint64_t cluster_offset, uint32_t offset, const bufferlist& bl, int r) { uint32_t cluster_size = 1<<16; bufferlist cluster_bl; if (offset > 0) { cluster_size -= offset; cluster_bl.append_zero(offset); } cluster_size -= bl.length(); cluster_bl.append(bl); if (cluster_size > 0) { cluster_bl.append_zero(cluster_size); } expect_stream_read(mock_stream_interface, {{cluster_offset, cluster_bl.length()}}, cluster_bl, r); } void expect_open(MockStreamInterface& mock_stream_interface, std::optional<std::vector<uint64_t>>&& l1_table) { expect_stream_open(mock_stream_interface, 0); expect_probe_header(mock_stream_interface, QCOW_MAGIC, 2, 0); expect_read_header(mock_stream_interface, 0, 0); expect_read_l1_table(mock_stream_interface, std::move(l1_table), 0); } void expect_read_snapshot_header(MockStreamInterface& mock_stream_interface, const std::string& id, const std::string& name, uint64_t l1_table_offset, uint64_t* snapshot_offset, int r) { QCowSnapshotHeader snapshot_header; memset(&snapshot_header, 0, sizeof(snapshot_header)); snapshot_header.id_str_size = htobe16(id.size()); snapshot_header.name_size = htobe16(name.size()); snapshot_header.extra_data_size = htobe32(16); snapshot_header.l1_size = htobe32(1); snapshot_header.l1_table_offset = htobe64(l1_table_offset); bufferlist snapshot_header_bl; snapshot_header_bl.append( std::string_view(reinterpret_cast<char*>(&snapshot_header), sizeof(snapshot_header))); expect_stream_read(mock_stream_interface, {{*snapshot_offset, sizeof(snapshot_header)}}, snapshot_header_bl, r); *snapshot_offset += sizeof(snapshot_header); } void expect_read_snapshot_header_extra( MockStreamInterface& mock_stream_interface, const std::string& id, const std::string& name, uint64_t size, uint64_t* snapshot_offset, int r) { QCowSnapshotExtraData snapshot_header_extra; memset(&snapshot_header_extra, 0, sizeof(snapshot_header_extra)); snapshot_header_extra.disk_size = htobe64(size); bufferlist snapshot_header_extra_bl; snapshot_header_extra_bl.append( std::string_view(reinterpret_cast<char*>(&snapshot_header_extra), 16)); snapshot_header_extra_bl.append(id); snapshot_header_extra_bl.append(name); expect_stream_read(mock_stream_interface, {{*snapshot_offset, 16 + id.size() + name.size()}}, snapshot_header_extra_bl, r); *snapshot_offset += 16 + id.size() + name.size(); *snapshot_offset = p2roundup(*snapshot_offset, static_cast<uint64_t>(8)); } void expect_read_snapshot_l1_table(MockStreamInterface& mock_stream_interface, uint64_t l1_table_offset, int r) { uint64_t l2_table_cluster = htobe64(l1_table_offset); bufferlist snapshot_l1_table_bl; snapshot_l1_table_bl.append( std::string_view(reinterpret_cast<char*>(&l2_table_cluster), 8)); expect_stream_read(mock_stream_interface, {{l1_table_offset, 8}}, snapshot_l1_table_bl, r); } void expect_read_snapshot(MockStreamInterface& mock_stream_interface, const std::string& id, const std::string& name, uint64_t size, uint64_t l1_table_offset, uint64_t* snapshot_offset) { expect_read_snapshot_header(mock_stream_interface, id, name, l1_table_offset, snapshot_offset, 0); expect_read_snapshot_header_extra(mock_stream_interface, id, name, size, snapshot_offset, 0); expect_read_snapshot_l1_table(mock_stream_interface, l1_table_offset, 0); } json_spirit::mObject json_object; }; TEST_F(TestMockMigrationQCOWFormat, OpenCloseV1) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); int expected_open_ret_val = 0; QCowHeaderV1 qcow_header; memset(&qcow_header, 0, sizeof(qcow_header)); qcow_header.magic = htobe32(QCOW_MAGIC); qcow_header.version = htobe32(1); qcow_header.size = htobe64(1<<30); qcow_header.l1_table_offset = htobe64(1<<20); qcow_header.cluster_bits = 16; qcow_header.l2_bits = 13; bufferlist probe_bl; probe_bl.append(std::string_view(reinterpret_cast<char*>(&qcow_header), 8)); expect_stream_read(*mock_stream_interface, {{0, 8}}, probe_bl, 0); #ifdef WITH_RBD_MIGRATION_FORMAT_QCOW_V1 bufferlist header_bl; header_bl.append(std::string_view(reinterpret_cast<char*>(&qcow_header), sizeof(qcow_header))); expect_stream_read(*mock_stream_interface, {{0, sizeof(qcow_header)}}, header_bl, 0); bufferlist l1_table_bl; l1_table_bl.append_zero(16); expect_stream_read(*mock_stream_interface, {{1<<20, 16}}, l1_table_bl, 0); #else // WITH_RBD_MIGRATION_FORMAT_QCOW_V1 expected_open_ret_val = -ENOTSUP; #endif // WITH_RBD_MIGRATION_FORMAT_QCOW_V1 expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(expected_open_ret_val, ctx1.wait()); C_SaferCond ctx2; mock_qcow_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationQCOWFormat, OpenCloseV2) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_open(*mock_stream_interface, {}); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; mock_qcow_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationQCOWFormat, ProbeInvalidMagic) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, 0, 2, 0); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(-EINVAL, ctx1.wait()); C_SaferCond ctx2; mock_qcow_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationQCOWFormat, ProbeInvalidVersion) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 0, 0); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(-EINVAL, ctx1.wait()); C_SaferCond ctx2; mock_qcow_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationQCOWFormat, ProbeError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 2, -EIO); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(-EIO, ctx1.wait()); C_SaferCond ctx2; mock_qcow_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } #ifdef WITH_RBD_MIGRATION_FORMAT_QCOW_V1 TEST_F(TestMockMigrationQCOWFormat, ReadHeaderV1Error) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 1, 0); QCowHeaderV1 qcow_header; memset(&qcow_header, 0, sizeof(qcow_header)); qcow_header.magic = htobe32(QCOW_MAGIC); qcow_header.version = htobe32(1); qcow_header.size = htobe64(1<<30); qcow_header.l1_table_offset = htobe64(1<<20); qcow_header.cluster_bits = 16; qcow_header.l2_bits = 13; bufferlist header_bl; header_bl.append(std::string_view(reinterpret_cast<char*>(&qcow_header), sizeof(qcow_header))); expect_stream_read(*mock_stream_interface, {{0, sizeof(qcow_header)}}, header_bl, -EPERM); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(-EPERM, ctx1.wait()); C_SaferCond ctx2; mock_qcow_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } #endif // WITH_RBD_MIGRATION_FORMAT_QCOW_V1 TEST_F(TestMockMigrationQCOWFormat, ReadHeaderV2Error) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 2, 0); expect_read_header(*mock_stream_interface, 0, -EIO); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(-EIO, ctx1.wait()); C_SaferCond ctx2; mock_qcow_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationQCOWFormat, ReadL1TableError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 2, 0); expect_read_header(*mock_stream_interface, 0, 0); expect_read_l1_table(*mock_stream_interface, {}, -EPERM); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(-EPERM, ctx1.wait()); C_SaferCond ctx2; mock_qcow_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationQCOWFormat, Snapshots) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 2, 0); expect_read_header(*mock_stream_interface, 2, 0); uint64_t snapshot_offset = 1<<21; expect_read_snapshot(*mock_stream_interface, "1", "snap1", 1<<29, 1<<22, &snapshot_offset); expect_read_snapshot(*mock_stream_interface, "2", "snap2", 1<<29, 1<<22, &snapshot_offset); expect_read_l1_table(*mock_stream_interface, {}, 0); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); FormatInterface::SnapInfos snap_infos; C_SaferCond ctx2; mock_qcow_format.get_snapshots(&snap_infos, &ctx2); ASSERT_EQ(0, ctx2.wait()); FormatInterface::SnapInfos expected_snap_infos{ {1, {"snap1", cls::rbd::UserSnapshotNamespace{}, 1<<29, {}, 0, 0, {}}}, {2, {"snap2", cls::rbd::UserSnapshotNamespace{}, 1<<29, {}, 0, 0, {}}}}; ASSERT_EQ(expected_snap_infos, snap_infos); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, SnapshotHeaderError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 2, 0); expect_read_header(*mock_stream_interface, 2, 0); uint64_t snapshot_offset = 1<<21; expect_read_snapshot_header(*mock_stream_interface, "1", "snap1", 1<<22, &snapshot_offset, -EINVAL); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(-EINVAL, ctx1.wait()); C_SaferCond ctx2; mock_qcow_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationQCOWFormat, SnapshotExtraError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 2, 0); expect_read_header(*mock_stream_interface, 2, 0); uint64_t snapshot_offset = 1<<21; expect_read_snapshot_header(*mock_stream_interface, "1", "snap1", 1<<22, &snapshot_offset, 0); expect_read_snapshot_header_extra(*mock_stream_interface, "1", "snap1", 1<<29, &snapshot_offset, -EINVAL); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(-EINVAL, ctx1.wait()); C_SaferCond ctx2; mock_qcow_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationQCOWFormat, SnapshotL1TableError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 2, 0); expect_read_header(*mock_stream_interface, 2, 0); uint64_t snapshot_offset = 1<<21; expect_read_snapshot_header(*mock_stream_interface, "1", "snap1", 1<<22, &snapshot_offset, 0); expect_read_snapshot_header_extra(*mock_stream_interface, "1", "snap1", 1<<29, &snapshot_offset, 0); expect_read_snapshot_l1_table(*mock_stream_interface, 1<<22, -EINVAL); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(-EINVAL, ctx1.wait()); C_SaferCond ctx2; mock_qcow_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationQCOWFormat, GetImageSize) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_open(*mock_stream_interface, {}); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); uint64_t size = 0; C_SaferCond ctx2; mock_qcow_format.get_image_size(CEPH_NOSNAP, &size, &ctx2); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(1<<30, size); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, GetImageSizeSnap) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 2, 0); expect_read_header(*mock_stream_interface, 1, 0); uint64_t snapshot_offset = 1<<21; expect_read_snapshot(*mock_stream_interface, "1", "snap1", 1<<29, 1<<22, &snapshot_offset); expect_read_l1_table(*mock_stream_interface, {}, 0); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); uint64_t size = 0; C_SaferCond ctx2; mock_qcow_format.get_image_size(1U, &size, &ctx2); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(1<<29, size); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, GetImageSizeSnapDNE) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_open(*mock_stream_interface, {}); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); uint64_t size = 0; C_SaferCond ctx2; mock_qcow_format.get_image_size(1U, &size, &ctx2); ASSERT_EQ(-ENOENT, ctx2.wait()); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, Read) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_open(*mock_stream_interface, {{1ULL<<40}}); expect_read_l2_table(*mock_stream_interface, 1ULL<<40, {{0, 1ULL<<32}}, 0); bufferlist expect_bl; expect_bl.append(std::string(123, '1')); expect_read_cluster(*mock_stream_interface, 1ULL<<32, 123, expect_bl, 0); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; auto aio_comp = io::AioCompletion::create_and_start( &ctx2, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl; io::ReadResult read_result{&bl}; ASSERT_TRUE(mock_qcow_format.read(aio_comp, CEPH_NOSNAP, {{65659, 123}}, std::move(read_result), 0, 0, {})); ASSERT_EQ(123, ctx2.wait()); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, ReadL1DNE) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_open(*mock_stream_interface, {}); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; auto aio_comp = io::AioCompletion::create_and_start( &ctx2, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl; io::ReadResult read_result{&bl}; ASSERT_TRUE(mock_qcow_format.read(aio_comp, CEPH_NOSNAP, {{234, 123}}, std::move(read_result), 0, 0, {})); ASSERT_EQ(123, ctx2.wait()); bufferlist expect_bl; expect_bl.append_zero(123); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, ReadL2DNE) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_open(*mock_stream_interface, {{1ULL<<40}}); expect_read_l2_table(*mock_stream_interface, 1ULL<<40, {{0, 1ULL<<32}}, 0); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; auto aio_comp = io::AioCompletion::create_and_start( &ctx2, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl; io::ReadResult read_result{&bl}; ASSERT_TRUE(mock_qcow_format.read(aio_comp, CEPH_NOSNAP, {{234, 123}}, std::move(read_result), 0, 0, {})); ASSERT_EQ(123, ctx2.wait()); bufferlist expect_bl; expect_bl.append_zero(123); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, ReadZero) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_open(*mock_stream_interface, {{1ULL<<40}}); expect_read_l2_table(*mock_stream_interface, 1ULL<<40, {{0, QCOW_OFLAG_ZERO}}, 0); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; auto aio_comp = io::AioCompletion::create_and_start( &ctx2, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl; io::ReadResult read_result{&bl}; ASSERT_TRUE(mock_qcow_format.read(aio_comp, CEPH_NOSNAP, {{65659, 123}}, std::move(read_result), 0, 0, {})); ASSERT_EQ(123, ctx2.wait()); bufferlist expect_bl; expect_bl.append_zero(123); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, ReadSnap) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 2, 0); expect_read_header(*mock_stream_interface, 1, 0); uint64_t snapshot_offset = 1<<21; expect_read_snapshot(*mock_stream_interface, "1", "snap1", 1<<29, 1<<22, &snapshot_offset); expect_read_l1_table(*mock_stream_interface, {}, 0); expect_read_l2_table(*mock_stream_interface, 1<<22, {{0, 1ULL<<32}}, 0); bufferlist expect_bl; expect_bl.append(std::string(123, '1')); expect_read_cluster(*mock_stream_interface, 1ULL<<32, 123, expect_bl, 0); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; auto aio_comp = io::AioCompletion::create_and_start( &ctx2, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl; io::ReadResult read_result{&bl}; ASSERT_TRUE(mock_qcow_format.read(aio_comp, 1, {{65659, 123}}, std::move(read_result), 0, 0, {})); ASSERT_EQ(123, ctx2.wait()); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, ReadSnapDNE) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_open(*mock_stream_interface, {{1ULL<<40}}); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; auto aio_comp = io::AioCompletion::create_and_start( &ctx2, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl; io::ReadResult read_result{&bl}; ASSERT_TRUE(mock_qcow_format.read(aio_comp, 1, {{65659, 123}}, std::move(read_result), 0, 0, {})); ASSERT_EQ(-ENOENT, ctx2.wait()); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, ReadClusterCacheHit) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_open(*mock_stream_interface, {{1ULL<<40}}); expect_read_l2_table(*mock_stream_interface, 1ULL<<40, {{0, 1ULL<<32}}, 0); bufferlist expect_bl1; expect_bl1.append(std::string(123, '1')); bufferlist expect_bl2; expect_bl2.append(std::string(234, '2')); bufferlist cluster_bl; cluster_bl.append_zero(123); cluster_bl.append(expect_bl1); cluster_bl.append_zero(234); cluster_bl.append(expect_bl2); expect_read_cluster(*mock_stream_interface, 1ULL<<32, 0, cluster_bl, 0); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; auto aio_comp1 = io::AioCompletion::create_and_start( &ctx2, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl1; io::ReadResult read_result1{&bl1}; ASSERT_TRUE(mock_qcow_format.read(aio_comp1, CEPH_NOSNAP, {{65659, 123}}, std::move(read_result1), 0, 0, {})); ASSERT_EQ(123, ctx2.wait()); ASSERT_EQ(expect_bl1, bl1); C_SaferCond ctx3; auto aio_comp2 = io::AioCompletion::create_and_start( &ctx3, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl2; io::ReadResult read_result2{&bl2}; ASSERT_TRUE(mock_qcow_format.read(aio_comp2, CEPH_NOSNAP, {{66016, 234}}, std::move(read_result2), 0, 0, {})); ASSERT_EQ(234, ctx3.wait()); ASSERT_EQ(expect_bl2, bl2); C_SaferCond ctx4; mock_qcow_format.close(&ctx4); ASSERT_EQ(0, ctx4.wait()); } TEST_F(TestMockMigrationQCOWFormat, ReadClusterError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_open(*mock_stream_interface, {{1ULL<<40}}); expect_read_l2_table(*mock_stream_interface, 1ULL<<40, {{0, 1ULL<<32}}, 0); bufferlist expect_bl; expect_bl.append(std::string(123, '1')); expect_read_cluster(*mock_stream_interface, 1ULL<<32, 123, expect_bl, -EIO); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; auto aio_comp = io::AioCompletion::create_and_start( &ctx2, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl; io::ReadResult read_result{&bl}; ASSERT_TRUE(mock_qcow_format.read(aio_comp, CEPH_NOSNAP, {{65659, 123}}, std::move(read_result), 0, 0, {})); ASSERT_EQ(-EIO, ctx2.wait()); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, ReadL2TableError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_open(*mock_stream_interface, {{1ULL<<40}}); expect_read_l2_table(*mock_stream_interface, 1ULL<<40, {{0, 1ULL<<32}}, -EIO); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; auto aio_comp = io::AioCompletion::create_and_start( &ctx2, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl; io::ReadResult read_result{&bl}; ASSERT_TRUE(mock_qcow_format.read(aio_comp, CEPH_NOSNAP, {{65659, 123}}, std::move(read_result), 0, 0, {})); ASSERT_EQ(-EIO, ctx2.wait()); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationQCOWFormat, ListSnaps) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_probe_header(*mock_stream_interface, QCOW_MAGIC, 2, 0); expect_read_header(*mock_stream_interface, 2, 0); uint64_t snapshot_offset = 1<<21; expect_read_snapshot(*mock_stream_interface, "1", "snap1", 1<<29, 1<<22, &snapshot_offset); expect_read_snapshot(*mock_stream_interface, "2", "snap2", 1<<29, 1<<23, &snapshot_offset); expect_read_l1_table(*mock_stream_interface, {{1ULL<<28}}, 0); io::SparseExtents sparse_extents_1; sparse_extents_1.insert(0, 196608, {io::SPARSE_EXTENT_STATE_DATA, 196608}); expect_read_l2_table(*mock_stream_interface, 1ULL<<22, {{1ULL<<23, 1ULL<<24, 1ULL<<25}}, 0); io::SparseExtents sparse_extents_2; sparse_extents_2.insert(0, 65536, {io::SPARSE_EXTENT_STATE_DATA, 65536}); sparse_extents_2.insert(65536, 65536, {io::SPARSE_EXTENT_STATE_ZEROED, 65536}); expect_read_l2_table(*mock_stream_interface, 1ULL<<23, {{1ULL<<26, QCOW_OFLAG_ZERO, 1ULL<<25}}, 0); io::SparseExtents sparse_extents_head; sparse_extents_head.insert(131072, 65536, {io::SPARSE_EXTENT_STATE_DATA, 65536}); expect_read_l2_table(*mock_stream_interface, 1ULL<<28, {{1ULL<<26, QCOW_OFLAG_ZERO, 1ULL<<27}}, 0); expect_stream_close(*mock_stream_interface, 0); MockQCOWFormat mock_qcow_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_qcow_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; io::SnapshotDelta snapshot_delta; mock_qcow_format.list_snaps({{0, 196608}}, {1, CEPH_NOSNAP}, 0, &snapshot_delta, {}, &ctx2); ASSERT_EQ(0, ctx2.wait()); io::SnapshotDelta expected_snapshot_delta; expected_snapshot_delta[{1, 1}] = sparse_extents_1; expected_snapshot_delta[{CEPH_NOSNAP, 2}] = sparse_extents_2; expected_snapshot_delta[{CEPH_NOSNAP, CEPH_NOSNAP}] = sparse_extents_head; ASSERT_EQ(expected_snapshot_delta, snapshot_delta); C_SaferCond ctx3; mock_qcow_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } } // namespace migration } // namespace librbd
40,351
31.025397
80
cc
null
ceph-main/src/test/librbd/migration/test_mock_RawFormat.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/migration/MockSnapshotInterface.h" #include "include/rbd_types.h" #include "common/ceph_mutex.h" #include "librbd/migration/RawFormat.h" #include "librbd/migration/SourceSpecBuilder.h" #include "gtest/gtest.h" #include "gmock/gmock.h" #include "json_spirit/json_spirit.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace migration { template<> struct SourceSpecBuilder<librbd::MockTestImageCtx> { MOCK_CONST_METHOD3(build_snapshot, int(const json_spirit::mObject&, uint64_t, std::shared_ptr<SnapshotInterface>*)); }; } // namespace migration } // namespace librbd #include "librbd/migration/RawFormat.cc" using ::testing::_; using ::testing::InSequence; using ::testing::Invoke; using ::testing::ReturnRef; using ::testing::WithArg; using ::testing::WithArgs; namespace librbd { namespace migration { using ::testing::Invoke; class TestMockMigrationRawFormat : public TestMockFixture { public: typedef RawFormat<MockTestImageCtx> MockRawFormat; typedef SourceSpecBuilder<MockTestImageCtx> MockSourceSpecBuilder; librbd::ImageCtx *m_image_ctx; void SetUp() override { TestMockFixture::SetUp(); ASSERT_EQ(0, open_image(m_image_name, &m_image_ctx)); json_spirit::mObject stream_obj; stream_obj["type"] = "file"; json_object["stream"] = stream_obj; } void expect_build_snapshot(MockSourceSpecBuilder& mock_source_spec_builder, uint64_t index, MockSnapshotInterface* mock_snapshot_interface, int r) { EXPECT_CALL(mock_source_spec_builder, build_snapshot(_, index, _)) .WillOnce(WithArgs<2>(Invoke([mock_snapshot_interface, r] (std::shared_ptr<SnapshotInterface>* ptr) { ptr->reset(mock_snapshot_interface); return r; }))); } void expect_snapshot_open(MockSnapshotInterface& mock_snapshot_interface, int r) { EXPECT_CALL(mock_snapshot_interface, open(_, _)) .WillOnce(WithArg<1>(Invoke([r](Context* ctx) { ctx->complete(r); }))); } void expect_snapshot_close(MockSnapshotInterface& mock_snapshot_interface, int r) { EXPECT_CALL(mock_snapshot_interface, close(_)) .WillOnce(Invoke([r](Context* ctx) { ctx->complete(r); })); } void expect_snapshot_get_info(MockSnapshotInterface& mock_snapshot_interface, const SnapInfo& snap_info) { EXPECT_CALL(mock_snapshot_interface, get_snap_info()) .WillOnce(ReturnRef(snap_info)); } void expect_snapshot_read(MockSnapshotInterface& mock_snapshot_interface, const io::Extents& image_extents, const bufferlist& bl, int r) { EXPECT_CALL(mock_snapshot_interface, read(_, image_extents, _)) .WillOnce(WithArgs<0, 2>(Invoke([bl, image_extents, r] (io::AioCompletion* aio_comp, io::ReadResult& read_result) { aio_comp->read_result = std::move(read_result); aio_comp->read_result.set_image_extents(image_extents); aio_comp->set_request_count(1); auto ctx = new io::ReadResult::C_ImageReadRequest(aio_comp, 0, image_extents); ctx->bl = std::move(bl); ctx->complete(r); }))); } void expect_snapshot_list_snap(MockSnapshotInterface& mock_snapshot_interface, const io::Extents& image_extents, const io::SparseExtents& sparse_extents, int r) { EXPECT_CALL(mock_snapshot_interface, list_snap(image_extents, _, _)) .WillOnce(WithArgs<1, 2>(Invoke( [sparse_extents, r](io::SparseExtents* out_sparse_extents, Context* ctx) { out_sparse_extents->insert(sparse_extents); ctx->complete(r); }))); } void expect_close(MockTestImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.state, close(_)) .WillOnce(Invoke([r](Context* ctx) { ctx->complete(r); })); } json_spirit::mObject json_object; }; TEST_F(TestMockMigrationRawFormat, OpenClose) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_snapshot_interface = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, CEPH_NOSNAP, mock_snapshot_interface, 0); expect_snapshot_open(*mock_snapshot_interface, 0); expect_snapshot_close(*mock_snapshot_interface, 0); MockRawFormat mock_raw_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_raw_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; mock_raw_format.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationRawFormat, OpenError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_snapshot_interface = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, CEPH_NOSNAP, mock_snapshot_interface, 0); expect_snapshot_open(*mock_snapshot_interface, -ENOENT); expect_snapshot_close(*mock_snapshot_interface, 0); expect_close(mock_image_ctx, 0); MockRawFormat mock_raw_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx; mock_raw_format.open(&ctx); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockMigrationRawFormat, OpenSnapshotError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_snapshot_interface_head = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, CEPH_NOSNAP, mock_snapshot_interface_head, 0); auto mock_snapshot_interface_1 = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, 1, mock_snapshot_interface_1, 0); expect_snapshot_open(*mock_snapshot_interface_1, -ENOENT); expect_snapshot_open(*mock_snapshot_interface_head, 0); expect_snapshot_close(*mock_snapshot_interface_1, 0); expect_snapshot_close(*mock_snapshot_interface_head, 0); expect_close(mock_image_ctx, 0); json_spirit::mArray snapshots; snapshots.push_back(json_spirit::mObject{}); json_object["snapshots"] = snapshots; MockRawFormat mock_raw_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx; mock_raw_format.open(&ctx); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockMigrationRawFormat, GetSnapshots) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_snapshot_interface = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, CEPH_NOSNAP, mock_snapshot_interface, 0); expect_snapshot_open(*mock_snapshot_interface, 0); expect_snapshot_close(*mock_snapshot_interface, 0); MockRawFormat mock_raw_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_raw_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; FormatInterface::SnapInfos snap_infos; mock_raw_format.get_snapshots(&snap_infos, &ctx2); ASSERT_EQ(0, ctx2.wait()); ASSERT_TRUE(snap_infos.empty()); C_SaferCond ctx3; mock_raw_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationRawFormat, GetImageSize) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_snapshot_interface = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, CEPH_NOSNAP, mock_snapshot_interface, 0); expect_snapshot_open(*mock_snapshot_interface, 0); SnapInfo snap_info{{}, {}, 123, {}, 0, 0, {}}; expect_snapshot_get_info(*mock_snapshot_interface, snap_info); expect_snapshot_close(*mock_snapshot_interface, 0); MockRawFormat mock_raw_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_raw_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; uint64_t size; mock_raw_format.get_image_size(CEPH_NOSNAP, &size, &ctx2); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(size, 123); C_SaferCond ctx3; mock_raw_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationRawFormat, GetImageSizeSnapshotDNE) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_snapshot_interface = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, CEPH_NOSNAP, mock_snapshot_interface, 0); expect_snapshot_open(*mock_snapshot_interface, 0); expect_snapshot_close(*mock_snapshot_interface, 0); MockRawFormat mock_raw_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_raw_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; uint64_t size; mock_raw_format.get_image_size(0, &size, &ctx2); ASSERT_EQ(-ENOENT, ctx2.wait()); C_SaferCond ctx3; mock_raw_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationRawFormat, Read) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_snapshot_interface = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, CEPH_NOSNAP, mock_snapshot_interface, 0); expect_snapshot_open(*mock_snapshot_interface, 0); bufferlist expect_bl; expect_bl.append(std::string(123, '1')); expect_snapshot_read(*mock_snapshot_interface, {{123, 123}}, expect_bl, 0); expect_snapshot_close(*mock_snapshot_interface, 0); MockRawFormat mock_raw_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_raw_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; auto aio_comp = io::AioCompletion::create_and_start( &ctx2, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl; io::ReadResult read_result{&bl}; ASSERT_TRUE(mock_raw_format.read(aio_comp, CEPH_NOSNAP, {{123, 123}}, std::move(read_result), 0, 0, {})); ASSERT_EQ(123, ctx2.wait()); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; mock_raw_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationRawFormat, ListSnaps) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_snapshot_interface = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, CEPH_NOSNAP, mock_snapshot_interface, 0); expect_snapshot_open(*mock_snapshot_interface, 0); SnapInfo snap_info{{}, {}, 123, {}, 0, 0, {}}; expect_snapshot_get_info(*mock_snapshot_interface, snap_info); io::SparseExtents sparse_extents; sparse_extents.insert(0, 123, {io::SPARSE_EXTENT_STATE_DATA, 123}); expect_snapshot_list_snap(*mock_snapshot_interface, {{0, 123}}, sparse_extents, 0); expect_snapshot_close(*mock_snapshot_interface, 0); MockRawFormat mock_raw_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_raw_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; io::SnapshotDelta snapshot_delta; mock_raw_format.list_snaps({{0, 123}}, {CEPH_NOSNAP}, 0, &snapshot_delta, {}, &ctx2); ASSERT_EQ(0, ctx2.wait()); io::SnapshotDelta expected_snapshot_delta; expected_snapshot_delta[{CEPH_NOSNAP, CEPH_NOSNAP}] = sparse_extents; ASSERT_EQ(expected_snapshot_delta, snapshot_delta); C_SaferCond ctx3; mock_raw_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationRawFormat, ListSnapsError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_snapshot_interface = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, CEPH_NOSNAP, mock_snapshot_interface, 0); expect_snapshot_open(*mock_snapshot_interface, 0); SnapInfo snap_info{{}, {}, 123, {}, 0, 0, {}}; expect_snapshot_get_info(*mock_snapshot_interface, snap_info); io::SparseExtents sparse_extents; sparse_extents.insert(0, 123, {io::SPARSE_EXTENT_STATE_DATA, 123}); expect_snapshot_list_snap(*mock_snapshot_interface, {{0, 123}}, sparse_extents, -EINVAL); expect_snapshot_close(*mock_snapshot_interface, 0); MockRawFormat mock_raw_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_raw_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; io::SnapshotDelta snapshot_delta; mock_raw_format.list_snaps({{0, 123}}, {CEPH_NOSNAP}, 0, &snapshot_delta, {}, &ctx2); ASSERT_EQ(-EINVAL, ctx2.wait()); C_SaferCond ctx3; mock_raw_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationRawFormat, ListSnapsMerge) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_snapshot_interface_head = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, CEPH_NOSNAP, mock_snapshot_interface_head, 0); auto mock_snapshot_interface_1 = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, 1, mock_snapshot_interface_1, 0); auto mock_snapshot_interface_2 = new MockSnapshotInterface(); expect_build_snapshot(mock_source_spec_builder, 2, mock_snapshot_interface_2, 0); expect_snapshot_open(*mock_snapshot_interface_1, 0); expect_snapshot_open(*mock_snapshot_interface_2, 0); expect_snapshot_open(*mock_snapshot_interface_head, 0); SnapInfo snap_info_head{{}, {}, 256, {}, 0, 0, {}}; SnapInfo snap_info_1{snap_info_head}; snap_info_1.size = 123; expect_snapshot_get_info(*mock_snapshot_interface_1, snap_info_1); io::SparseExtents sparse_extents_1; sparse_extents_1.insert(0, 123, {io::SPARSE_EXTENT_STATE_DATA, 123}); expect_snapshot_list_snap(*mock_snapshot_interface_1, {{0, 123}}, sparse_extents_1, 0); SnapInfo snap_info_2{snap_info_head}; snap_info_2.size = 64; expect_snapshot_get_info(*mock_snapshot_interface_2, snap_info_2); io::SparseExtents sparse_extents_2; sparse_extents_2.insert(0, 32, {io::SPARSE_EXTENT_STATE_DATA, 32}); expect_snapshot_list_snap(*mock_snapshot_interface_2, {{0, 123}}, sparse_extents_2, 0); expect_snapshot_get_info(*mock_snapshot_interface_head, snap_info_head); io::SparseExtents sparse_extents_head; sparse_extents_head.insert(0, 16, {io::SPARSE_EXTENT_STATE_DATA, 16}); expect_snapshot_list_snap(*mock_snapshot_interface_head, {{0, 123}}, sparse_extents_head, 0); expect_snapshot_close(*mock_snapshot_interface_1, 0); expect_snapshot_close(*mock_snapshot_interface_2, 0); expect_snapshot_close(*mock_snapshot_interface_head, 0); json_spirit::mArray snapshots; snapshots.push_back(json_spirit::mObject{}); snapshots.push_back(json_spirit::mObject{}); json_object["snapshots"] = snapshots; MockRawFormat mock_raw_format(&mock_image_ctx, json_object, &mock_source_spec_builder); C_SaferCond ctx1; mock_raw_format.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; io::SnapshotDelta snapshot_delta; mock_raw_format.list_snaps({{0, 123}}, {1, CEPH_NOSNAP}, 0, &snapshot_delta, {}, &ctx2); ASSERT_EQ(0, ctx2.wait()); io::SnapshotDelta expected_snapshot_delta; expected_snapshot_delta[{1, 1}] = sparse_extents_1; sparse_extents_2.erase(0, 16); sparse_extents_2.insert(64, 59, {io::SPARSE_EXTENT_STATE_ZEROED, 59}); expected_snapshot_delta[{CEPH_NOSNAP, 2}] = sparse_extents_2; expected_snapshot_delta[{CEPH_NOSNAP, CEPH_NOSNAP}] = sparse_extents_head; ASSERT_EQ(expected_snapshot_delta, snapshot_delta); C_SaferCond ctx3; mock_raw_format.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } } // namespace migration } // namespace librbd
17,229
31.881679
80
cc
null
ceph-main/src/test/librbd/migration/test_mock_RawSnapshot.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/migration/MockStreamInterface.h" #include "include/rbd_types.h" #include "common/ceph_mutex.h" #include "librbd/migration/FileStream.h" #include "librbd/migration/RawSnapshot.h" #include "librbd/migration/SourceSpecBuilder.h" #include "gtest/gtest.h" #include "gmock/gmock.h" #include "json_spirit/json_spirit.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace migration { template<> struct SourceSpecBuilder<librbd::MockTestImageCtx> { MOCK_CONST_METHOD2(build_stream, int(const json_spirit::mObject&, std::shared_ptr<StreamInterface>*)); }; } // namespace migration } // namespace librbd #include "librbd/migration/RawSnapshot.cc" using ::testing::_; using ::testing::InSequence; using ::testing::Invoke; using ::testing::WithArgs; namespace librbd { namespace migration { using ::testing::Invoke; class TestMockMigrationRawSnapshot : public TestMockFixture { public: typedef RawSnapshot<MockTestImageCtx> MockRawSnapshot; typedef SourceSpecBuilder<MockTestImageCtx> MockSourceSpecBuilder; librbd::ImageCtx *m_image_ctx; void SetUp() override { TestMockFixture::SetUp(); ASSERT_EQ(0, open_image(m_image_name, &m_image_ctx)); json_spirit::mObject stream_obj; stream_obj["type"] = "file"; json_object["stream"] = stream_obj; } void expect_build_stream(MockSourceSpecBuilder& mock_source_spec_builder, MockStreamInterface* mock_stream_interface, int r) { EXPECT_CALL(mock_source_spec_builder, build_stream(_, _)) .WillOnce(WithArgs<1>(Invoke([mock_stream_interface, r] (std::shared_ptr<StreamInterface>* ptr) { ptr->reset(mock_stream_interface); return r; }))); } void expect_stream_open(MockStreamInterface& mock_stream_interface, int r) { EXPECT_CALL(mock_stream_interface, open(_)) .WillOnce(Invoke([r](Context* ctx) { ctx->complete(r); })); } void expect_stream_close(MockStreamInterface& mock_stream_interface, int r) { EXPECT_CALL(mock_stream_interface, close(_)) .WillOnce(Invoke([r](Context* ctx) { ctx->complete(r); })); } void expect_stream_get_size(MockStreamInterface& mock_stream_interface, uint64_t size, int r) { EXPECT_CALL(mock_stream_interface, get_size(_, _)) .WillOnce(Invoke([size, r](uint64_t* out_size, Context* ctx) { *out_size = size; ctx->complete(r); })); } void expect_stream_read(MockStreamInterface& mock_stream_interface, const io::Extents& byte_extents, const bufferlist& bl, int r) { EXPECT_CALL(mock_stream_interface, read(byte_extents, _, _)) .WillOnce(WithArgs<1, 2>(Invoke([bl, r] (bufferlist* out_bl, Context* ctx) { *out_bl = bl; ctx->complete(r); }))); } json_spirit::mObject json_object; }; TEST_F(TestMockMigrationRawSnapshot, OpenClose) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_stream_get_size(*mock_stream_interface, 123, 0); expect_stream_close(*mock_stream_interface, 0); json_object["name"] = "snap1"; MockRawSnapshot mock_raw_snapshot(&mock_image_ctx, json_object, &mock_source_spec_builder, 1); C_SaferCond ctx1; mock_raw_snapshot.open(nullptr, &ctx1); ASSERT_EQ(0, ctx1.wait()); auto snap_info = mock_raw_snapshot.get_snap_info(); ASSERT_EQ("snap1", snap_info.name); ASSERT_EQ(123, snap_info.size); C_SaferCond ctx2; mock_raw_snapshot.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationRawSnapshot, OpenError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, -ENOENT); MockRawSnapshot mock_raw_snapshot(&mock_image_ctx, json_object, &mock_source_spec_builder, 0); C_SaferCond ctx; mock_raw_snapshot.open(nullptr, &ctx); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockMigrationRawSnapshot, GetSizeError) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_stream_get_size(*mock_stream_interface, 0, -EINVAL); expect_stream_close(*mock_stream_interface, 0); MockRawSnapshot mock_raw_snapshot(&mock_image_ctx, json_object, &mock_source_spec_builder, 0); C_SaferCond ctx; mock_raw_snapshot.open(nullptr, &ctx); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMigrationRawSnapshot, Read) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_stream_get_size(*mock_stream_interface, 0, 0); bufferlist expect_bl; expect_bl.append(std::string(123, '1')); expect_stream_read(*mock_stream_interface, {{123, 123}}, expect_bl, 0); expect_stream_close(*mock_stream_interface, 0); MockRawSnapshot mock_raw_snapshot(&mock_image_ctx, json_object, &mock_source_spec_builder, 0); C_SaferCond ctx1; mock_raw_snapshot.open(nullptr, &ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; auto aio_comp = io::AioCompletion::create_and_start( &ctx2, m_image_ctx, io::AIO_TYPE_READ); bufferlist bl; io::ReadResult read_result{&bl}; mock_raw_snapshot.read(aio_comp, {{123, 123}}, std::move(read_result), 0, 0, {}); ASSERT_EQ(123, ctx2.wait()); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; mock_raw_snapshot.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationRawSnapshot, ListSnap) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; MockSourceSpecBuilder mock_source_spec_builder; auto mock_stream_interface = new MockStreamInterface(); expect_build_stream(mock_source_spec_builder, mock_stream_interface, 0); expect_stream_open(*mock_stream_interface, 0); expect_stream_get_size(*mock_stream_interface, 0, 0); expect_stream_close(*mock_stream_interface, 0); MockRawSnapshot mock_raw_snapshot(&mock_image_ctx, json_object, &mock_source_spec_builder, 0); C_SaferCond ctx1; mock_raw_snapshot.open(nullptr, &ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; io::SparseExtents sparse_extents; mock_raw_snapshot.list_snap({{0, 123}}, 0, &sparse_extents, {}, &ctx2); ASSERT_EQ(0, ctx2.wait()); C_SaferCond ctx3; mock_raw_snapshot.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } } // namespace migration } // namespace librbd
7,706
29.105469
79
cc
null
ceph-main/src/test/librbd/migration/test_mock_S3Stream.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "include/rbd_types.h" #include "common/ceph_mutex.h" #include "librbd/migration/HttpClient.h" #include "librbd/migration/S3Stream.h" #include "gtest/gtest.h" #include "gmock/gmock.h" #include "json_spirit/json_spirit.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/beast/http.hpp> namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace migration { template <> struct HttpClient<MockTestImageCtx> { static HttpClient* s_instance; static HttpClient* create(MockTestImageCtx*, const std::string&) { ceph_assert(s_instance != nullptr); return s_instance; } HttpProcessorInterface* http_processor = nullptr; void set_http_processor(HttpProcessorInterface* http_processor) { this->http_processor = http_processor; } MOCK_METHOD1(open, void(Context*)); MOCK_METHOD1(close, void(Context*)); MOCK_METHOD2(get_size, void(uint64_t*, Context*)); MOCK_METHOD3(do_read, void(const io::Extents&, bufferlist*, Context*)); void read(io::Extents&& extents, bufferlist* bl, Context* ctx) { do_read(extents, bl, ctx); } HttpClient() { s_instance = this; } }; HttpClient<MockTestImageCtx>* HttpClient<MockTestImageCtx>::s_instance = nullptr; } // namespace migration } // namespace librbd #include "librbd/migration/S3Stream.cc" namespace librbd { namespace migration { using ::testing::_; using ::testing::Invoke; using ::testing::InSequence; using ::testing::WithArgs; class TestMockMigrationS3Stream : public TestMockFixture { public: typedef S3Stream<MockTestImageCtx> MockS3Stream; typedef HttpClient<MockTestImageCtx> MockHttpClient; using EmptyBody = boost::beast::http::empty_body; using EmptyRequest = boost::beast::http::request<EmptyBody>; librbd::ImageCtx *m_image_ctx; void SetUp() override { TestMockFixture::SetUp(); ASSERT_EQ(0, open_image(m_image_name, &m_image_ctx)); json_object["url"] = "http://some.site/bucket/file"; json_object["access_key"] = "0555b35654ad1656d804"; json_object["secret_key"] = "h7GhxuBLTrlhVUyxSPUKUV8r/2EI4ngqJxD7iBdBYLhwluN30JaT3Q=="; } void expect_open(MockHttpClient& mock_http_client, int r) { EXPECT_CALL(mock_http_client, open(_)) .WillOnce(Invoke([r](Context* ctx) { ctx->complete(r); })); } void expect_close(MockHttpClient& mock_http_client, int r) { EXPECT_CALL(mock_http_client, close(_)) .WillOnce(Invoke([r](Context* ctx) { ctx->complete(r); })); } void expect_get_size(MockHttpClient& mock_http_client, uint64_t size, int r) { EXPECT_CALL(mock_http_client, get_size(_, _)) .WillOnce(Invoke([size, r](uint64_t* out_size, Context* ctx) { *out_size = size; ctx->complete(r); })); } void expect_read(MockHttpClient& mock_http_client, io::Extents byte_extents, const bufferlist& bl, int r) { uint64_t len = 0; for (auto [_, byte_len] : byte_extents) { len += byte_len; } EXPECT_CALL(mock_http_client, do_read(byte_extents, _, _)) .WillOnce(WithArgs<1, 2>(Invoke( [len, bl, r](bufferlist* out_bl, Context* ctx) { *out_bl = bl; ctx->complete(r < 0 ? r : len); }))); } json_spirit::mObject json_object; }; TEST_F(TestMockMigrationS3Stream, OpenClose) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; auto mock_http_client = new MockHttpClient(); expect_open(*mock_http_client, 0); expect_close(*mock_http_client, 0); MockS3Stream mock_http_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_http_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; mock_http_stream.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } TEST_F(TestMockMigrationS3Stream, GetSize) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; auto mock_http_client = new MockHttpClient(); expect_open(*mock_http_client, 0); expect_get_size(*mock_http_client, 128, 0); expect_close(*mock_http_client, 0); MockS3Stream mock_http_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_http_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; uint64_t size; mock_http_stream.get_size(&size, &ctx2); ASSERT_EQ(0, ctx2.wait()); ASSERT_EQ(128, size); C_SaferCond ctx3; mock_http_stream.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationS3Stream, Read) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; auto mock_http_client = new MockHttpClient(); expect_open(*mock_http_client, 0); bufferlist expect_bl; expect_bl.append(std::string(192, '1')); expect_read(*mock_http_client, {{0, 128}, {256, 64}}, expect_bl, 0); expect_close(*mock_http_client, 0); MockS3Stream mock_http_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_http_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); C_SaferCond ctx2; bufferlist bl; mock_http_stream.read({{0, 128}, {256, 64}}, &bl, &ctx2); ASSERT_EQ(192, ctx2.wait()); ASSERT_EQ(expect_bl, bl); C_SaferCond ctx3; mock_http_stream.close(&ctx3); ASSERT_EQ(0, ctx3.wait()); } TEST_F(TestMockMigrationS3Stream, ProcessRequest) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; auto mock_http_client = new MockHttpClient(); expect_open(*mock_http_client, 0); expect_close(*mock_http_client, 0); MockS3Stream mock_http_stream(&mock_image_ctx, json_object); C_SaferCond ctx1; mock_http_stream.open(&ctx1); ASSERT_EQ(0, ctx1.wait()); EmptyRequest request; request.method(boost::beast::http::verb::get); request.target("/bucket/resource"); mock_http_client->http_processor->process_request(request); // basic test for date and known portion of authorization ASSERT_EQ(1U, request.count(boost::beast::http::field::date)); ASSERT_EQ(1U, request.count(boost::beast::http::field::authorization)); ASSERT_TRUE(boost::algorithm::starts_with( request[boost::beast::http::field::authorization], "AWS 0555b35654ad1656d804:")); C_SaferCond ctx2; mock_http_stream.close(&ctx2); ASSERT_EQ(0, ctx2.wait()); } } // namespace migration } // namespace librbd
6,454
26.008368
91
cc
null
ceph-main/src/test/librbd/migration/test_mock_Utils.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "librbd/migration/Utils.h" #include "gtest/gtest.h" #include "gmock/gmock.h" namespace librbd { namespace migration { namespace util { class TestMockMigrationUtils : public TestMockFixture { public: }; TEST_F(TestMockMigrationUtils, ParseUrl) { UrlSpec url_spec; ASSERT_EQ(-EINVAL, parse_url(g_ceph_context, "", &url_spec)); ASSERT_EQ(-EINVAL, parse_url(g_ceph_context, "jttp://google.com/path", &url_spec)); ASSERT_EQ(-EINVAL, parse_url(g_ceph_context, "http://google.com:absd/path", &url_spec)); ASSERT_EQ(0, parse_url(g_ceph_context, "ceph.io/path", &url_spec)); ASSERT_EQ(UrlSpec(URL_SCHEME_HTTP, "ceph.io", "80", "/path"), url_spec); ASSERT_EQ(0, parse_url(g_ceph_context, "http://google.com/path", &url_spec)); ASSERT_EQ(UrlSpec(URL_SCHEME_HTTP, "google.com", "80", "/path"), url_spec); ASSERT_EQ(0, parse_url(g_ceph_context, "https://ceph.io/", &url_spec)); ASSERT_EQ(UrlSpec(URL_SCHEME_HTTPS, "ceph.io", "443", "/"), url_spec); ASSERT_EQ(0, parse_url(g_ceph_context, "http://google.com:1234/some/other/path", &url_spec)); ASSERT_EQ(UrlSpec(URL_SCHEME_HTTP, "google.com", "1234", "/some/other/path"), url_spec); ASSERT_EQ(0, parse_url(g_ceph_context, "http://1.2.3.4/", &url_spec)); ASSERT_EQ(UrlSpec(URL_SCHEME_HTTP, "1.2.3.4", "80", "/"), url_spec); } } // namespace util } // namespace migration } // namespace librbd
1,697
34.375
80
cc
null
ceph-main/src/test/librbd/mirror/test_mock_DisableRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/MockImageState.h" #include "test/librbd/mock/MockOperations.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "librbd/journal/PromoteRequest.h" #include "librbd/mirror/DisableRequest.h" #include "librbd/mirror/GetInfoRequest.h" #include "librbd/mirror/ImageRemoveRequest.h" #include "librbd/mirror/ImageStateUpdateRequest.h" #include "librbd/mirror/snapshot/PromoteRequest.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { explicit MockTestImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace journal { template <> struct PromoteRequest<librbd::MockTestImageCtx> { Context *on_finish = nullptr; static PromoteRequest *s_instance; static PromoteRequest *create(librbd::MockTestImageCtx *, bool force, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } PromoteRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; PromoteRequest<librbd::MockTestImageCtx> *PromoteRequest<librbd::MockTestImageCtx>::s_instance = nullptr; } // namespace journal namespace mirror { template <> struct GetInfoRequest<librbd::MockTestImageCtx> { cls::rbd::MirrorImage *mirror_image; PromotionState *promotion_state; Context *on_finish = nullptr; static GetInfoRequest *s_instance; static GetInfoRequest *create(librbd::MockTestImageCtx &, cls::rbd::MirrorImage *mirror_image, PromotionState *promotion_state, std::string* primary_mirror_uuid, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->mirror_image = mirror_image; s_instance->promotion_state = promotion_state; s_instance->on_finish = on_finish; return s_instance; } GetInfoRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; template <> struct ImageRemoveRequest<librbd::MockTestImageCtx> { static ImageRemoveRequest* s_instance; Context* on_finish = nullptr; static ImageRemoveRequest* create( librados::IoCtx& io_ctx, const std::string& global_image_id, const std::string& image_id, Context* on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } MOCK_METHOD0(send, void()); ImageRemoveRequest() { s_instance = this; } }; template <> struct ImageStateUpdateRequest<librbd::MockTestImageCtx> { static ImageStateUpdateRequest* s_instance; Context* on_finish = nullptr; static ImageStateUpdateRequest* create( librados::IoCtx& io_ctx, const std::string& image_id, cls::rbd::MirrorImageState mirror_image_state, const cls::rbd::MirrorImage& mirror_image, Context* on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } MOCK_METHOD0(send, void()); ImageStateUpdateRequest() { s_instance = this; } }; GetInfoRequest<librbd::MockTestImageCtx> *GetInfoRequest<librbd::MockTestImageCtx>::s_instance = nullptr; ImageRemoveRequest<librbd::MockTestImageCtx> *ImageRemoveRequest<librbd::MockTestImageCtx>::s_instance = nullptr; ImageStateUpdateRequest<librbd::MockTestImageCtx> *ImageStateUpdateRequest<librbd::MockTestImageCtx>::s_instance = nullptr; namespace snapshot { template <> struct PromoteRequest<librbd::MockTestImageCtx> { Context *on_finish = nullptr; static PromoteRequest *s_instance; static PromoteRequest *create(librbd::MockTestImageCtx*, const std::string& global_image_id, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } PromoteRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; PromoteRequest<librbd::MockTestImageCtx> *PromoteRequest<librbd::MockTestImageCtx>::s_instance = nullptr; } // namespace snapshot } // namespace mirror } // namespace librbd // template definitions #include "librbd/mirror/DisableRequest.cc" template class librbd::mirror::DisableRequest<librbd::MockTestImageCtx>; ACTION_P(TestFeatures, image_ctx) { return ((image_ctx->features & arg0) != 0); } namespace librbd { namespace mirror { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; class TestMockMirrorDisableRequest : public TestMockFixture { public: typedef DisableRequest<MockTestImageCtx> MockDisableRequest; typedef Journal<MockTestImageCtx> MockJournal; typedef journal::PromoteRequest<MockTestImageCtx> MockJournalPromoteRequest; typedef mirror::GetInfoRequest<MockTestImageCtx> MockGetInfoRequest; typedef mirror::ImageRemoveRequest<MockTestImageCtx> MockImageRemoveRequest; typedef mirror::ImageStateUpdateRequest<MockTestImageCtx> MockImageStateUpdateRequest; typedef mirror::snapshot::PromoteRequest<MockTestImageCtx> MockSnapshotPromoteRequest; void expect_get_mirror_info(MockTestImageCtx &mock_image_ctx, MockGetInfoRequest &mock_get_info_request, const cls::rbd::MirrorImage &mirror_image, PromotionState promotion_state, int r) { EXPECT_CALL(mock_get_info_request, send()) .WillOnce( Invoke([&mock_image_ctx, &mock_get_info_request, mirror_image, promotion_state, r]() { if (r == 0) { *mock_get_info_request.mirror_image = mirror_image; *mock_get_info_request.promotion_state = promotion_state; } mock_image_ctx.op_work_queue->queue( mock_get_info_request.on_finish, r); })); } void expect_mirror_image_state_update( MockTestImageCtx &mock_image_ctx, MockImageStateUpdateRequest& mock_request, int r) { EXPECT_CALL(mock_request, send()) .WillOnce( Invoke([&mock_image_ctx, &mock_request, r]() { mock_image_ctx.op_work_queue->queue(mock_request.on_finish, r); })); } void expect_mirror_image_remove( MockTestImageCtx &mock_image_ctx, MockImageRemoveRequest& mock_request, int r) { EXPECT_CALL(mock_request, send()) .WillOnce( Invoke([&mock_image_ctx, &mock_request, r]() { mock_image_ctx.op_work_queue->queue(mock_request.on_finish, r); })); } void expect_journal_client_list(MockTestImageCtx &mock_image_ctx, const std::set<cls::journal::Client> &clients, int r) { bufferlist bl; using ceph::encode; encode(clients, bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(::journal::Journaler::header_oid(mock_image_ctx.id), _, StrEq("journal"), StrEq("client_list"), _, _, _, _)) .WillOnce(DoAll(WithArg<5>(CopyInBufferlist(bl)), Return(r))); } void expect_journal_client_unregister(MockTestImageCtx &mock_image_ctx, const std::string &client_id, int r) { bufferlist bl; using ceph::encode; encode(client_id, bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(::journal::Journaler::header_oid(mock_image_ctx.id), _, StrEq("journal"), StrEq("client_unregister"), ContentsEqual(bl), _, _, _)) .WillOnce(Return(r)); } void expect_journal_promote(MockTestImageCtx &mock_image_ctx, MockJournalPromoteRequest &mock_promote_request, int r) { EXPECT_CALL(mock_promote_request, send()) .WillOnce(FinishRequest(&mock_promote_request, r, &mock_image_ctx)); } void expect_snapshot_promote(MockTestImageCtx &mock_image_ctx, MockSnapshotPromoteRequest &mock_promote_request, int r) { EXPECT_CALL(mock_promote_request, send()) .WillOnce(FinishRequest(&mock_promote_request, r, &mock_image_ctx)); } void expect_is_refresh_required(MockTestImageCtx &mock_image_ctx, bool refresh_required) { EXPECT_CALL(*mock_image_ctx.state, is_refresh_required()) .WillOnce(Return(refresh_required)); } void expect_refresh_image(MockTestImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.state, refresh(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); } void expect_snap_remove(MockTestImageCtx &mock_image_ctx, const std::string &snap_name, int r) { EXPECT_CALL(*mock_image_ctx.operations, snap_remove(_, StrEq(snap_name), _)) .WillOnce(WithArg<2>(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue))); } template <typename T> bufferlist encode(const T &t) { using ceph::encode; bufferlist bl; encode(t, bl); return bl; } }; TEST_F(TestMockMirrorDisableRequest, Success) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); expect_snap_remove(mock_image_ctx, "snap 1", 0); expect_snap_remove(mock_image_ctx, "snap 2", 0); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_PRIMARY, 0); MockImageStateUpdateRequest mock_image_state_update_request; expect_mirror_image_state_update( mock_image_ctx, mock_image_state_update_request, 0); expect_journal_client_list( mock_image_ctx, { {"", encode(journal::ClientData{journal::ImageClientMeta{}})}, {"peer 1", encode(journal::ClientData{journal::MirrorPeerClientMeta{}})}, {"peer 2", encode(journal::ClientData{journal::MirrorPeerClientMeta{ "remote image id", {{cls::rbd::UserSnapshotNamespace(), "snap 1", boost::optional<uint64_t>(0)}, {cls::rbd::UserSnapshotNamespace(), "snap 2", boost::optional<uint64_t>(0)}}} })} }, 0); expect_journal_client_unregister(mock_image_ctx, "peer 1", 0); expect_journal_client_unregister(mock_image_ctx, "peer 2", 0); expect_journal_client_list(mock_image_ctx, {}, 0); MockImageRemoveRequest mock_image_remove_request; expect_mirror_image_remove( mock_image_ctx, mock_image_remove_request, 0); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, false, true, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, SuccessNoRemove) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_PRIMARY, 0); MockImageStateUpdateRequest mock_image_state_update_request; expect_mirror_image_state_update( mock_image_ctx, mock_image_state_update_request, 0); expect_journal_client_list(mock_image_ctx, {}, 0); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, false, false, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, SuccessNonPrimary) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockJournalPromoteRequest mock_promote_request; expect_op_work_queue(mock_image_ctx); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_NON_PRIMARY, 0); MockImageStateUpdateRequest mock_image_state_update_request; expect_mirror_image_state_update( mock_image_ctx, mock_image_state_update_request, 0); expect_journal_promote(mock_image_ctx, mock_promote_request, 0); expect_is_refresh_required(mock_image_ctx, false); expect_journal_client_list(mock_image_ctx, {}, 0); MockImageRemoveRequest mock_image_remove_request; expect_mirror_image_remove( mock_image_ctx, mock_image_remove_request, 0); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, true, true, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, NonPrimaryError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_NON_PRIMARY, 0); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, false, false, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, GetMirrorInfoError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_PRIMARY, -EINVAL); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, false, true, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, MirrorImageSetError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_PRIMARY, 0); MockImageStateUpdateRequest mock_image_state_update_request; expect_mirror_image_state_update( mock_image_ctx, mock_image_state_update_request, -ENOENT); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, false, true, &ctx); req->send(); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, JournalPromoteError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockJournalPromoteRequest mock_promote_request; expect_op_work_queue(mock_image_ctx); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_NON_PRIMARY, 0); MockImageStateUpdateRequest mock_image_state_update_request; expect_mirror_image_state_update( mock_image_ctx, mock_image_state_update_request, 0); expect_journal_promote(mock_image_ctx, mock_promote_request, -EPERM); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, true, true, &ctx); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, JournalClientListError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_PRIMARY, 0); MockImageStateUpdateRequest mock_image_state_update_request; expect_mirror_image_state_update( mock_image_ctx, mock_image_state_update_request, 0); expect_journal_client_list(mock_image_ctx, {}, -EBADMSG); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, false, true, &ctx); req->send(); ASSERT_EQ(-EBADMSG, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, SnapRemoveError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); expect_snap_remove(mock_image_ctx, "snap 1", 0); expect_snap_remove(mock_image_ctx, "snap 2", -EPERM); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_PRIMARY, 0); MockImageStateUpdateRequest mock_image_state_update_request; expect_mirror_image_state_update( mock_image_ctx, mock_image_state_update_request, 0); expect_journal_client_list( mock_image_ctx, { {"", encode(journal::ClientData{journal::ImageClientMeta{}})}, {"peer 1", encode(journal::ClientData{journal::MirrorPeerClientMeta{}})}, {"peer 2", encode(journal::ClientData{journal::MirrorPeerClientMeta{ "remote image id", {{cls::rbd::UserSnapshotNamespace(), "snap 1", boost::optional<uint64_t>(0)}, {cls::rbd::UserSnapshotNamespace(), "snap 2", boost::optional<uint64_t>(0)}}} })} }, 0); expect_journal_client_unregister(mock_image_ctx, "peer 1", 0); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, false, true, &ctx); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, JournalClientUnregisterError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); expect_snap_remove(mock_image_ctx, "snap 1", 0); expect_snap_remove(mock_image_ctx, "snap 2", 0); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_PRIMARY, 0); MockImageStateUpdateRequest mock_image_state_update_request; expect_mirror_image_state_update( mock_image_ctx, mock_image_state_update_request, 0); expect_journal_client_list( mock_image_ctx, { {"", encode(journal::ClientData{journal::ImageClientMeta{}})}, {"peer 1", encode(journal::ClientData{journal::MirrorPeerClientMeta{}})}, {"peer 2", encode(journal::ClientData{journal::MirrorPeerClientMeta{ "remote image id", {{cls::rbd::UserSnapshotNamespace(), "snap 1", boost::optional<uint64_t>(0)}, {cls::rbd::UserSnapshotNamespace(), "snap 2", boost::optional<uint64_t>(0)}}} })} }, 0); expect_journal_client_unregister(mock_image_ctx, "peer 1", -EINVAL); expect_journal_client_unregister(mock_image_ctx, "peer 2", 0); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, false, true, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, SnapshotPromoteError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockSnapshotPromoteRequest mock_promote_request; expect_op_work_queue(mock_image_ctx); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_SNAPSHOT, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_NON_PRIMARY, 0); MockImageStateUpdateRequest mock_image_state_update_request; expect_mirror_image_state_update( mock_image_ctx, mock_image_state_update_request, 0); expect_snapshot_promote(mock_image_ctx, mock_promote_request, -EPERM); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, true, true, &ctx); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, RefreshError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockSnapshotPromoteRequest mock_promote_request; expect_op_work_queue(mock_image_ctx); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_SNAPSHOT, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_NON_PRIMARY, 0); MockImageStateUpdateRequest mock_image_state_update_request; expect_mirror_image_state_update( mock_image_ctx, mock_image_state_update_request, 0); expect_snapshot_promote(mock_image_ctx, mock_promote_request, 0); expect_is_refresh_required(mock_image_ctx, true); expect_refresh_image(mock_image_ctx, -EPERM); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, true, true, &ctx); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } TEST_F(TestMockMirrorDisableRequest, MirrorImageRemoveError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; MockGetInfoRequest mock_get_info_request; expect_get_mirror_info( mock_image_ctx, mock_get_info_request, {cls::rbd::MIRROR_IMAGE_MODE_JOURNAL, "global id", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, PROMOTION_STATE_PRIMARY, 0); MockImageStateUpdateRequest mock_image_state_update_request; expect_mirror_image_state_update( mock_image_ctx, mock_image_state_update_request, 0); expect_journal_client_list(mock_image_ctx, {}, 0); MockImageRemoveRequest mock_image_remove_request; expect_mirror_image_remove( mock_image_ctx, mock_image_remove_request, -EINVAL); C_SaferCond ctx; auto req = new MockDisableRequest(&mock_image_ctx, false, true, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } } // namespace mirror } // namespace librbd
23,373
32.631655
123
cc
null
ceph-main/src/test/librbd/mirror/snapshot/test_mock_CreateNonPrimaryRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/MockOperations.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "librbd/mirror/snapshot/CreateNonPrimaryRequest.h" #include "librbd/mirror/snapshot/Utils.h" #include "librbd/mirror/snapshot/WriteImageStateRequest.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { explicit MockTestImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace mirror { namespace snapshot { namespace util { namespace { struct Mock { static Mock* s_instance; Mock() { s_instance = this; } MOCK_METHOD1(can_create_non_primary_snapshot, bool(librbd::MockTestImageCtx *)); }; Mock *Mock::s_instance = nullptr; } // anonymous namespace template<> bool can_create_non_primary_snapshot( librbd::MockTestImageCtx *image_ctx) { return Mock::s_instance->can_create_non_primary_snapshot(image_ctx); } } // namespace util template <> struct WriteImageStateRequest<MockTestImageCtx> { uint64_t snap_id = CEPH_NOSNAP; ImageState image_state; Context* on_finish = nullptr; static WriteImageStateRequest* s_instance; static WriteImageStateRequest *create(MockTestImageCtx *image_ctx, uint64_t snap_id, const ImageState &image_state, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->snap_id = snap_id; s_instance->image_state = image_state; s_instance->on_finish = on_finish; return s_instance; } MOCK_METHOD0(send, void()); WriteImageStateRequest() { s_instance = this; } }; WriteImageStateRequest<MockTestImageCtx>* WriteImageStateRequest<MockTestImageCtx>::s_instance = nullptr; } // namespace snapshot } // namespace mirror } // namespace librbd // template definitions #include "librbd/mirror/snapshot/CreateNonPrimaryRequest.cc" template class librbd::mirror::snapshot::CreateNonPrimaryRequest<librbd::MockTestImageCtx>; namespace librbd { namespace mirror { namespace snapshot { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; class TestMockMirrorSnapshotCreateNonPrimaryRequest : public TestMockFixture { public: typedef CreateNonPrimaryRequest<MockTestImageCtx> MockCreateNonPrimaryRequest; typedef WriteImageStateRequest<MockTestImageCtx> MockWriteImageStateRequest; typedef util::Mock MockUtils; void expect_clone_md_ctx(MockTestImageCtx &mock_image_ctx) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), clone()) .WillOnce(Invoke([&mock_image_ctx]() { get_mock_io_ctx(mock_image_ctx.md_ctx).get(); return &get_mock_io_ctx(mock_image_ctx.md_ctx); })); } void expect_refresh_image(MockTestImageCtx &mock_image_ctx, bool refresh_required, int r) { EXPECT_CALL(*mock_image_ctx.state, is_refresh_required()) .WillOnce(Return(refresh_required)); if (refresh_required) { EXPECT_CALL(*mock_image_ctx.state, refresh(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); } } void expect_get_mirror_image(MockTestImageCtx &mock_image_ctx, const cls::rbd::MirrorImage &mirror_image, int r) { using ceph::encode; bufferlist bl; encode(mirror_image, bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(RBD_MIRRORING, _, StrEq("rbd"), StrEq("mirror_image_get"), _, _, _, _)) .WillOnce(DoAll(WithArg<5>(CopyInBufferlist(bl)), Return(r))); } void expect_can_create_non_primary_snapshot(MockUtils &mock_utils, bool result) { EXPECT_CALL(mock_utils, can_create_non_primary_snapshot(_)) .WillOnce(Return(result)); } void expect_get_mirror_peers(MockTestImageCtx &mock_image_ctx, const std::vector<cls::rbd::MirrorPeer> &peers, int r) { using ceph::encode; bufferlist bl; encode(peers, bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(RBD_MIRRORING, _, StrEq("rbd"), StrEq("mirror_peer_list"), _, _, _, _)) .WillOnce(DoAll(WithArg<5>(CopyInBufferlist(bl)), Return(r))); } void expect_create_snapshot(MockTestImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.operations, snap_create(_, _, _, _, _)) .WillOnce(WithArg<4>(CompleteContext( r, mock_image_ctx.image_ctx->op_work_queue))); } void expect_write_image_state( MockTestImageCtx &mock_image_ctx, MockWriteImageStateRequest &mock_write_image_state_request, int r) { EXPECT_CALL(mock_image_ctx, get_snap_id(_, _)) .WillOnce(Return(123)); EXPECT_CALL(mock_write_image_state_request, send()) .WillOnce(Invoke([&mock_image_ctx, &mock_write_image_state_request, r]() { mock_image_ctx.image_ctx->op_work_queue->queue( mock_write_image_state_request.on_finish, r); })); } }; TEST_F(TestMockMirrorSnapshotCreateNonPrimaryRequest, Success) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_refresh_image(mock_image_ctx, true, 0); expect_get_mirror_image( mock_image_ctx, {cls::rbd::MIRROR_IMAGE_MODE_SNAPSHOT, "gid", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, 0); MockUtils mock_utils; expect_can_create_non_primary_snapshot(mock_utils, true); expect_create_snapshot(mock_image_ctx, 0); MockWriteImageStateRequest mock_write_image_state_request; expect_write_image_state(mock_image_ctx, mock_write_image_state_request, 0); C_SaferCond ctx; auto req = new MockCreateNonPrimaryRequest(&mock_image_ctx, false, "mirror_uuid", 123, {{1, 2}}, {}, nullptr, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreateNonPrimaryRequest, SuccessDemoted) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_clone_md_ctx(mock_image_ctx); expect_refresh_image(mock_image_ctx, true, 0); expect_get_mirror_image( mock_image_ctx, {cls::rbd::MIRROR_IMAGE_MODE_SNAPSHOT, "gid", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, 0); MockUtils mock_utils; expect_can_create_non_primary_snapshot(mock_utils, true); expect_get_mirror_peers(mock_image_ctx, {{"uuid", cls::rbd::MIRROR_PEER_DIRECTION_TX, "ceph", "mirror", "mirror uuid"}}, 0); expect_create_snapshot(mock_image_ctx, 0); MockWriteImageStateRequest mock_write_image_state_request; expect_write_image_state(mock_image_ctx, mock_write_image_state_request, 0); C_SaferCond ctx; auto req = new MockCreateNonPrimaryRequest(&mock_image_ctx, true, "mirror_uuid", 123, {{1, 2}}, {}, nullptr, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreateNonPrimaryRequest, RefreshError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_refresh_image(mock_image_ctx, true, -EINVAL); C_SaferCond ctx; auto req = new MockCreateNonPrimaryRequest(&mock_image_ctx, false, "mirror_uuid", 123, {{1, 2}}, {}, nullptr, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreateNonPrimaryRequest, GetMirrorImageError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_refresh_image(mock_image_ctx, false, 0); expect_get_mirror_image( mock_image_ctx, {cls::rbd::MIRROR_IMAGE_MODE_SNAPSHOT, "gid", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, -EINVAL); C_SaferCond ctx; auto req = new MockCreateNonPrimaryRequest(&mock_image_ctx, false, "mirror_uuid", 123, {{1, 2}}, {}, nullptr, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreateNonPrimaryRequest, CanNotError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_refresh_image(mock_image_ctx, false, 0); expect_get_mirror_image( mock_image_ctx, {cls::rbd::MIRROR_IMAGE_MODE_SNAPSHOT, "gid", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, 0); MockUtils mock_utils; expect_can_create_non_primary_snapshot(mock_utils, false); C_SaferCond ctx; auto req = new MockCreateNonPrimaryRequest(&mock_image_ctx, false, "mirror_uuid", 123, {{1, 2}}, {}, nullptr, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreateNonPrimaryRequest, GetMirrorPeersError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_clone_md_ctx(mock_image_ctx); expect_refresh_image(mock_image_ctx, true, 0); expect_get_mirror_image( mock_image_ctx, {cls::rbd::MIRROR_IMAGE_MODE_SNAPSHOT, "gid", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, 0); MockUtils mock_utils; expect_can_create_non_primary_snapshot(mock_utils, true); expect_get_mirror_peers(mock_image_ctx, {}, -EPERM); C_SaferCond ctx; auto req = new MockCreateNonPrimaryRequest(&mock_image_ctx, true, "mirror_uuid", 123, {{1, 2}}, {}, nullptr, &ctx); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreateNonPrimaryRequest, CreateSnapshotError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_refresh_image(mock_image_ctx, true, 0); expect_get_mirror_image( mock_image_ctx, {cls::rbd::MIRROR_IMAGE_MODE_SNAPSHOT, "gid", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, 0); MockUtils mock_utils; expect_can_create_non_primary_snapshot(mock_utils, true); expect_create_snapshot(mock_image_ctx, -EINVAL); C_SaferCond ctx; auto req = new MockCreateNonPrimaryRequest(&mock_image_ctx, false, "mirror_uuid", 123, {{1, 2}}, {}, nullptr, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreateNonPrimaryRequest, WriteImageStateError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_refresh_image(mock_image_ctx, true, 0); expect_get_mirror_image( mock_image_ctx, {cls::rbd::MIRROR_IMAGE_MODE_SNAPSHOT, "gid", cls::rbd::MIRROR_IMAGE_STATE_ENABLED}, 0); MockUtils mock_utils; expect_can_create_non_primary_snapshot(mock_utils, true); expect_create_snapshot(mock_image_ctx, 0); MockWriteImageStateRequest mock_write_image_state_request; expect_write_image_state(mock_image_ctx, mock_write_image_state_request, -EINVAL); C_SaferCond ctx; auto req = new MockCreateNonPrimaryRequest(&mock_image_ctx, false, "mirror_uuid", 123, {{1, 2}}, {}, nullptr, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } } // namespace snapshot } // namespace mirror } // namespace librbd
12,833
31.992288
105
cc
null
ceph-main/src/test/librbd/mirror/snapshot/test_mock_CreatePrimaryRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/stringify.h" #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/MockOperations.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "librbd/mirror/snapshot/CreatePrimaryRequest.h" #include "librbd/mirror/snapshot/UnlinkPeerRequest.h" #include "librbd/mirror/snapshot/Utils.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { explicit MockTestImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace mirror { namespace snapshot { namespace util { namespace { struct Mock { static Mock* s_instance; Mock() { s_instance = this; } MOCK_METHOD4(can_create_primary_snapshot, bool(librbd::MockTestImageCtx *, bool, bool, uint64_t *)); }; Mock *Mock::s_instance = nullptr; } // anonymous namespace template<> bool can_create_primary_snapshot(librbd::MockTestImageCtx *image_ctx, bool demoted, bool force, bool* requires_orphan, uint64_t *rollback_snap_id) { return Mock::s_instance->can_create_primary_snapshot(image_ctx, demoted, force, rollback_snap_id); } } // namespace util template <> struct UnlinkPeerRequest<MockTestImageCtx> { uint64_t snap_id = CEPH_NOSNAP; std::string mirror_peer_uuid; bool allow_remove; Context* on_finish = nullptr; static UnlinkPeerRequest* s_instance; static UnlinkPeerRequest *create(MockTestImageCtx *image_ctx, uint64_t snap_id, const std::string &mirror_peer_uuid, bool allow_remove, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->snap_id = snap_id; s_instance->mirror_peer_uuid = mirror_peer_uuid; s_instance->allow_remove = allow_remove; s_instance->on_finish = on_finish; return s_instance; } MOCK_METHOD0(send, void()); UnlinkPeerRequest() { s_instance = this; } }; UnlinkPeerRequest<MockTestImageCtx>* UnlinkPeerRequest<MockTestImageCtx>::s_instance = nullptr; } // namespace snapshot } // namespace mirror } // namespace librbd // template definitions #include "librbd/mirror/snapshot/CreatePrimaryRequest.cc" template class librbd::mirror::snapshot::CreatePrimaryRequest<librbd::MockTestImageCtx>; namespace librbd { namespace mirror { namespace snapshot { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; class TestMockMirrorSnapshotCreatePrimaryRequest : public TestMockFixture { public: typedef CreatePrimaryRequest<MockTestImageCtx> MockCreatePrimaryRequest; typedef UnlinkPeerRequest<MockTestImageCtx> MockUnlinkPeerRequest; typedef util::Mock MockUtils; uint64_t m_snap_seq = 0; void snap_create(MockTestImageCtx &mock_image_ctx, const cls::rbd::SnapshotNamespace &ns, const std::string& snap_name) { ASSERT_TRUE(mock_image_ctx.snap_info.insert( {m_snap_seq++, SnapInfo{snap_name, ns, 0, {}, 0, 0, {}}}).second); } void expect_clone_md_ctx(MockTestImageCtx &mock_image_ctx) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), clone()) .WillOnce(Invoke([&mock_image_ctx]() { get_mock_io_ctx(mock_image_ctx.md_ctx).get(); return &get_mock_io_ctx(mock_image_ctx.md_ctx); })); } void expect_can_create_primary_snapshot(MockUtils &mock_utils, bool demoted, bool force, bool result) { EXPECT_CALL(mock_utils, can_create_primary_snapshot(_, demoted, force, nullptr)) .WillOnce(Return(result)); } void expect_get_mirror_peers(MockTestImageCtx &mock_image_ctx, const std::vector<cls::rbd::MirrorPeer> &peers, int r) { using ceph::encode; bufferlist bl; encode(peers, bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(RBD_MIRRORING, _, StrEq("rbd"), StrEq("mirror_peer_list"), _, _, _, _)) .WillOnce(DoAll(WithArg<5>(CopyInBufferlist(bl)), Return(r))); } void expect_create_snapshot(MockTestImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.operations, snap_create(_, _, _, _, _)) .WillOnce(DoAll( Invoke([this, &mock_image_ctx, r]( const cls::rbd::SnapshotNamespace &ns, const std::string& snap_name, uint64_t flags, ProgressContext &prog_ctx, Context *on_finish) { if (r != 0) { return; } auto mirror_ns = std::get<cls::rbd::MirrorSnapshotNamespace>(ns); mirror_ns.complete = true; snap_create(mock_image_ctx, mirror_ns, snap_name); }), WithArg<4>(CompleteContext( r, mock_image_ctx.image_ctx->op_work_queue)) )); } void expect_refresh_image(MockTestImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.state, refresh(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); } void expect_unlink_peer(MockTestImageCtx &mock_image_ctx, MockUnlinkPeerRequest &mock_unlink_peer_request, uint64_t snap_id, const std::string &peer_uuid, bool is_linked, bool complete, bool allow_remove, int r) { EXPECT_CALL(mock_unlink_peer_request, send()) .WillOnce(Invoke([&mock_image_ctx, &mock_unlink_peer_request, snap_id, peer_uuid, is_linked, complete, allow_remove, r]() { ASSERT_EQ(mock_unlink_peer_request.mirror_peer_uuid, peer_uuid); ASSERT_EQ(mock_unlink_peer_request.snap_id, snap_id); ASSERT_EQ(mock_unlink_peer_request.allow_remove, allow_remove); if (r == 0) { auto it = mock_image_ctx.snap_info.find(snap_id); ASSERT_NE(it, mock_image_ctx.snap_info.end()); auto info = std::get_if<cls::rbd::MirrorSnapshotNamespace>( &it->second.snap_namespace); ASSERT_NE(nullptr, info); ASSERT_EQ(complete, info->complete); ASSERT_EQ(is_linked, info->mirror_peer_uuids.erase( peer_uuid)); if (info->mirror_peer_uuids.empty()) { mock_image_ctx.snap_info.erase(it); } } mock_image_ctx.image_ctx->op_work_queue->queue( mock_unlink_peer_request.on_finish, r); })); } }; TEST_F(TestMockMirrorSnapshotCreatePrimaryRequest, Success) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_clone_md_ctx(mock_image_ctx); MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, false, false, true); expect_get_mirror_peers(mock_image_ctx, {{"uuid", cls::rbd::MIRROR_PEER_DIRECTION_TX, "ceph", "mirror", "mirror uuid"}}, 0); expect_create_snapshot(mock_image_ctx, 0); expect_refresh_image(mock_image_ctx, 0); C_SaferCond ctx; auto req = new MockCreatePrimaryRequest(&mock_image_ctx, "gid", CEPH_NOSNAP, 0U, 0U, nullptr, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreatePrimaryRequest, CanNotError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_clone_md_ctx(mock_image_ctx); MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, false, false, false); C_SaferCond ctx; auto req = new MockCreatePrimaryRequest(&mock_image_ctx, "gid", CEPH_NOSNAP, 0U, 0U, nullptr, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreatePrimaryRequest, GetMirrorPeersError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_clone_md_ctx(mock_image_ctx); MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, false, false, true); expect_get_mirror_peers(mock_image_ctx, {{"uuid", cls::rbd::MIRROR_PEER_DIRECTION_TX, "ceph", "mirror", "mirror uuid"}}, -EINVAL); C_SaferCond ctx; auto req = new MockCreatePrimaryRequest(&mock_image_ctx, "gid", CEPH_NOSNAP, 0U, 0U, nullptr, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreatePrimaryRequest, CreateSnapshotError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_clone_md_ctx(mock_image_ctx); MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, false, false, true); expect_get_mirror_peers(mock_image_ctx, {{"uuid", cls::rbd::MIRROR_PEER_DIRECTION_TX, "ceph", "mirror", "mirror uuid"}}, 0); expect_create_snapshot(mock_image_ctx, -EINVAL); C_SaferCond ctx; auto req = new MockCreatePrimaryRequest(&mock_image_ctx, "gid", CEPH_NOSNAP, 0U, 0U, nullptr, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreatePrimaryRequest, SuccessUnlinkIncomplete) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ictx->config.set_val("rbd_mirroring_max_mirroring_snapshots", "3"); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"uuid"}, "", CEPH_NOSNAP}; ns.complete = false; snap_create(mock_image_ctx, ns, "mirror_snap"); InSequence seq; expect_clone_md_ctx(mock_image_ctx); MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, false, false, true); expect_get_mirror_peers(mock_image_ctx, {{"uuid", cls::rbd::MIRROR_PEER_DIRECTION_TX, "ceph", "mirror", "mirror uuid"}}, 0); expect_create_snapshot(mock_image_ctx, 0); expect_refresh_image(mock_image_ctx, 0); MockUnlinkPeerRequest mock_unlink_peer_request; auto it = mock_image_ctx.snap_info.rbegin(); auto snap_id = it->first; expect_unlink_peer(mock_image_ctx, mock_unlink_peer_request, snap_id, "uuid", true, false, true, 0); C_SaferCond ctx; auto req = new MockCreatePrimaryRequest(&mock_image_ctx, "gid", CEPH_NOSNAP, 0U, 0U, nullptr, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreatePrimaryRequest, SuccessUnlinkPeer) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ictx->config.set_val("rbd_mirroring_max_mirroring_snapshots", "3"); MockTestImageCtx mock_image_ctx(*ictx); for (int i = 0; i < 3; i++) { cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"uuid"}, "", CEPH_NOSNAP}; ns.complete = true; snap_create(mock_image_ctx, ns, "mirror_snap"); } InSequence seq; expect_clone_md_ctx(mock_image_ctx); MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, false, false, true); expect_get_mirror_peers(mock_image_ctx, {{"uuid", cls::rbd::MIRROR_PEER_DIRECTION_TX, "ceph", "mirror", "mirror uuid"}}, 0); expect_create_snapshot(mock_image_ctx, 0); expect_refresh_image(mock_image_ctx, 0); MockUnlinkPeerRequest mock_unlink_peer_request; auto it = mock_image_ctx.snap_info.rbegin(); auto snap_id = it->first; expect_unlink_peer(mock_image_ctx, mock_unlink_peer_request, snap_id, "uuid", true, true, true, 0); C_SaferCond ctx; auto req = new MockCreatePrimaryRequest(&mock_image_ctx, "gid", CEPH_NOSNAP, 0U, 0U, nullptr, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreatePrimaryRequest, SuccessUnlinkNoPeer) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ictx->config.set_val("rbd_mirroring_max_mirroring_snapshots", "3"); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {}, "", CEPH_NOSNAP}; ns.complete = true; snap_create(mock_image_ctx, ns, "mirror_snap"); InSequence seq; expect_clone_md_ctx(mock_image_ctx); MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, false, false, true); expect_get_mirror_peers(mock_image_ctx, {{"uuid", cls::rbd::MIRROR_PEER_DIRECTION_TX, "ceph", "mirror", "mirror uuid"}}, 0); expect_create_snapshot(mock_image_ctx, 0); expect_refresh_image(mock_image_ctx, 0); MockUnlinkPeerRequest mock_unlink_peer_request; auto it = mock_image_ctx.snap_info.rbegin(); auto snap_id = it->first; expect_unlink_peer(mock_image_ctx, mock_unlink_peer_request, snap_id, "uuid", false, true, true, 0); C_SaferCond ctx; auto req = new MockCreatePrimaryRequest(&mock_image_ctx, "gid", CEPH_NOSNAP, 0U, 0U, nullptr, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotCreatePrimaryRequest, SuccessUnlinkMultiplePeers) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ictx->config.set_val("rbd_mirroring_max_mirroring_snapshots", "3"); MockTestImageCtx mock_image_ctx(*ictx); for (int i = 0; i < 3; i++) { cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"uuid1", "uuid2"}, "", CEPH_NOSNAP}; ns.complete = true; snap_create(mock_image_ctx, ns, "mirror_snap"); } InSequence seq; expect_clone_md_ctx(mock_image_ctx); MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, false, false, true); expect_get_mirror_peers(mock_image_ctx, {{"uuid1", cls::rbd::MIRROR_PEER_DIRECTION_TX, "ceph", "mirror", "mirror uuid"}, {"uuid2", cls::rbd::MIRROR_PEER_DIRECTION_TX, "ceph", "mirror", "mirror uuid"}}, 0); expect_create_snapshot(mock_image_ctx, 0); expect_refresh_image(mock_image_ctx, 0); MockUnlinkPeerRequest mock_unlink_peer_request; auto it = mock_image_ctx.snap_info.rbegin(); auto snap_id = it->first; expect_unlink_peer(mock_image_ctx, mock_unlink_peer_request, snap_id, "uuid1", true, true, true, 0); expect_unlink_peer(mock_image_ctx, mock_unlink_peer_request, snap_id, "uuid2", true, true, true, 0); C_SaferCond ctx; auto req = new MockCreatePrimaryRequest(&mock_image_ctx, "gid", CEPH_NOSNAP, 0U, 0U, nullptr, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } } // namespace snapshot } // namespace mirror } // namespace librbd
16,643
35.182609
95
cc
null
ceph-main/src/test/librbd/mirror/snapshot/test_mock_ImageMeta.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "librbd/ImageState.h" #include "librbd/mirror/snapshot/ImageMeta.h" #include "librbd/mirror/snapshot/Utils.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace } // namespace librbd #include "librbd/mirror/snapshot/ImageMeta.cc" namespace librbd { namespace mirror { namespace snapshot { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; class TestMockMirrorSnapshotImageMeta : public TestMockFixture { public: typedef ImageMeta<MockTestImageCtx> MockImageMeta; void expect_metadata_get(MockTestImageCtx& mock_image_ctx, const std::string& mirror_uuid, const std::string& value, int r) { bufferlist in_bl; ceph::encode(util::get_image_meta_key(mirror_uuid), in_bl); bufferlist out_bl; ceph::encode(value, out_bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("rbd"), StrEq("metadata_get"), ContentsEqual(in_bl), _, _, _)) .WillOnce(DoAll(WithArg<5>(CopyInBufferlist(out_bl)), Return(r))); } void expect_metadata_set(MockTestImageCtx& mock_image_ctx, const std::string& mirror_uuid, const std::string& value, int r) { bufferlist value_bl; value_bl.append(value); bufferlist in_bl; ceph::encode( std::map<std::string, bufferlist>{ {util::get_image_meta_key(mirror_uuid), value_bl}}, in_bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("rbd"), StrEq("metadata_set"), ContentsEqual(in_bl), _, _, _)) .WillOnce(Return(r)); } }; TEST_F(TestMockMirrorSnapshotImageMeta, Load) { librbd::ImageCtx* image_ctx; ASSERT_EQ(0, open_image(m_image_name, &image_ctx)); MockTestImageCtx mock_image_ctx(*image_ctx); InSequence seq; expect_metadata_get(mock_image_ctx, "mirror uuid", "{\"resync_requested\": true}", 0); MockImageMeta mock_image_meta(&mock_image_ctx, "mirror uuid"); C_SaferCond ctx; mock_image_meta.load(&ctx); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotImageMeta, LoadError) { librbd::ImageCtx* image_ctx; ASSERT_EQ(0, open_image(m_image_name, &image_ctx)); MockTestImageCtx mock_image_ctx(*image_ctx); InSequence seq; expect_metadata_get(mock_image_ctx, "mirror uuid", "{\"resync_requested\": true}", -EINVAL); MockImageMeta mock_image_meta(&mock_image_ctx, "mirror uuid"); C_SaferCond ctx; mock_image_meta.load(&ctx); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotImageMeta, LoadCorrupt) { librbd::ImageCtx* image_ctx; ASSERT_EQ(0, open_image(m_image_name, &image_ctx)); MockTestImageCtx mock_image_ctx(*image_ctx); InSequence seq; expect_metadata_get(mock_image_ctx, "mirror uuid", "\"resync_requested\": true}", 0); MockImageMeta mock_image_meta(&mock_image_ctx, "mirror uuid"); C_SaferCond ctx; mock_image_meta.load(&ctx); ASSERT_EQ(-EBADMSG, ctx.wait()); } TEST_F(TestMockMirrorSnapshotImageMeta, Save) { librbd::ImageCtx* image_ctx; ASSERT_EQ(0, open_image(m_image_name, &image_ctx)); MockTestImageCtx mock_image_ctx(*image_ctx); InSequence seq; expect_metadata_set(mock_image_ctx, "mirror uuid", "{\"resync_requested\": true}", 0); MockImageMeta mock_image_meta(&mock_image_ctx, "mirror uuid"); mock_image_meta.resync_requested = true; C_SaferCond ctx; mock_image_meta.save(&ctx); ASSERT_EQ(0, ctx.wait()); // should have sent image-update notification ASSERT_TRUE(image_ctx->state->is_refresh_required()); } TEST_F(TestMockMirrorSnapshotImageMeta, SaveError) { librbd::ImageCtx* image_ctx; ASSERT_EQ(0, open_image(m_image_name, &image_ctx)); MockTestImageCtx mock_image_ctx(*image_ctx); InSequence seq; expect_metadata_set(mock_image_ctx, "mirror uuid", "{\"resync_requested\": false}", -EINVAL); MockImageMeta mock_image_meta(&mock_image_ctx, "mirror uuid"); C_SaferCond ctx; mock_image_meta.save(&ctx); ASSERT_EQ(-EINVAL, ctx.wait()); } } // namespace snapshot } // namespace mirror } // namespace librbd
4,816
29.10625
75
cc
null
ceph-main/src/test/librbd/mirror/snapshot/test_mock_PromoteRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/stringify.h" #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/MockOperations.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "librbd/image/ListWatchersRequest.h" #include "librbd/mirror/snapshot/CreateNonPrimaryRequest.h" #include "librbd/mirror/snapshot/CreatePrimaryRequest.h" #include "librbd/mirror/snapshot/PromoteRequest.h" #include "librbd/mirror/snapshot/Utils.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { explicit MockTestImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace image { template <> struct ListWatchersRequest<MockTestImageCtx> { std::list<obj_watch_t> *watchers; Context* on_finish = nullptr; static ListWatchersRequest* s_instance; static ListWatchersRequest *create(MockTestImageCtx &image_ctx, int flags, std::list<obj_watch_t> *watchers, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->watchers = watchers; s_instance->on_finish = on_finish; return s_instance; } MOCK_METHOD0(send, void()); ListWatchersRequest() { s_instance = this; } }; ListWatchersRequest<MockTestImageCtx>* ListWatchersRequest<MockTestImageCtx>::s_instance = nullptr; } // namespace image namespace mirror { namespace snapshot { namespace util { namespace { struct Mock { static Mock* s_instance; Mock() { s_instance = this; } MOCK_METHOD5(can_create_primary_snapshot, bool(librbd::MockTestImageCtx *, bool, bool, bool*, uint64_t *)); }; Mock *Mock::s_instance = nullptr; } // anonymous namespace template<> bool can_create_primary_snapshot(librbd::MockTestImageCtx *image_ctx, bool demoted, bool force, bool* requires_orphan, uint64_t *rollback_snap_id) { return Mock::s_instance->can_create_primary_snapshot(image_ctx, demoted, force, requires_orphan, rollback_snap_id); } } // namespace util template <> struct CreateNonPrimaryRequest<MockTestImageCtx> { std::string primary_mirror_uuid; uint64_t primary_snap_id = CEPH_NOSNAP; Context* on_finish = nullptr; static CreateNonPrimaryRequest* s_instance; static CreateNonPrimaryRequest *create(MockTestImageCtx *image_ctx, bool demoted, const std::string &primary_mirror_uuid, uint64_t primary_snap_id, SnapSeqs snap_seqs, const ImageState &image_state, uint64_t *snap_id, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->primary_mirror_uuid = primary_mirror_uuid; s_instance->primary_snap_id = primary_snap_id; s_instance->on_finish = on_finish; return s_instance; } MOCK_METHOD0(send, void()); CreateNonPrimaryRequest() { s_instance = this; } }; CreateNonPrimaryRequest<MockTestImageCtx>* CreateNonPrimaryRequest<MockTestImageCtx>::s_instance = nullptr; template <> struct CreatePrimaryRequest<MockTestImageCtx> { bool demoted = false; bool force = false; Context* on_finish = nullptr; static CreatePrimaryRequest* s_instance; static CreatePrimaryRequest *create(MockTestImageCtx *image_ctx, const std::string& global_image_id, uint64_t clean_since_snap_id, uint64_t snap_create_flags, uint32_t flags, uint64_t *snap_id, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->demoted = ((flags & CREATE_PRIMARY_FLAG_DEMOTED) != 0); s_instance->force = ((flags & CREATE_PRIMARY_FLAG_FORCE) != 0); s_instance->on_finish = on_finish; return s_instance; } MOCK_METHOD0(send, void()); CreatePrimaryRequest() { s_instance = this; } }; CreatePrimaryRequest<MockTestImageCtx>* CreatePrimaryRequest<MockTestImageCtx>::s_instance = nullptr; } // namespace snapshot } // namespace mirror } // namespace librbd // template definitions #include "librbd/mirror/snapshot/PromoteRequest.cc" template class librbd::mirror::snapshot::PromoteRequest<librbd::MockTestImageCtx>; namespace librbd { namespace mirror { namespace snapshot { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; using ::testing::WithArgs; class TestMockMirrorSnapshotPromoteRequest : public TestMockFixture { public: typedef librbd::image::ListWatchersRequest<MockTestImageCtx> MockListWatchersRequest; typedef PromoteRequest<MockTestImageCtx> MockPromoteRequest; typedef CreateNonPrimaryRequest<MockTestImageCtx> MockCreateNonPrimaryRequest; typedef CreatePrimaryRequest<MockTestImageCtx> MockCreatePrimaryRequest; typedef util::Mock MockUtils; void expect_can_create_primary_snapshot(MockUtils &mock_utils, bool force, bool requires_orphan, uint64_t rollback_snap_id, bool result) { EXPECT_CALL(mock_utils, can_create_primary_snapshot(_, false, force, _, _)) .WillOnce(DoAll( WithArgs<3,4 >(Invoke( [requires_orphan, rollback_snap_id] (bool* orphan, uint64_t *snap_id) { *orphan = requires_orphan; *snap_id = rollback_snap_id; })), Return(result))); } void expect_create_orphan_snapshot( MockTestImageCtx &mock_image_ctx, MockCreateNonPrimaryRequest &mock_create_non_primary_request, int r) { EXPECT_CALL(mock_create_non_primary_request, send()) .WillOnce( Invoke([&mock_image_ctx, &mock_create_non_primary_request, r]() { mock_image_ctx.image_ctx->op_work_queue->queue( mock_create_non_primary_request.on_finish, r); })); } void expect_list_watchers( MockTestImageCtx &mock_image_ctx, MockListWatchersRequest &mock_list_watchers_request, const std::list<obj_watch_t> &watchers, int r) { EXPECT_CALL(mock_list_watchers_request, send()) .WillOnce( Invoke([&mock_image_ctx, &mock_list_watchers_request, watchers, r]() { *mock_list_watchers_request.watchers = watchers; mock_image_ctx.image_ctx->op_work_queue->queue( mock_list_watchers_request.on_finish, r); })); } void expect_acquire_lock(MockTestImageCtx &mock_image_ctx, int r) { if (mock_image_ctx.exclusive_lock == nullptr) { return; } EXPECT_CALL(*mock_image_ctx.exclusive_lock, is_lock_owner()) .WillOnce(Return(false)); EXPECT_CALL(*mock_image_ctx.exclusive_lock, block_requests(_)); EXPECT_CALL(*mock_image_ctx.exclusive_lock, acquire_lock(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); if (r == 0) { EXPECT_CALL(*mock_image_ctx.exclusive_lock, is_lock_owner()) .WillOnce(Return(true)); } } void expect_get_snap_info(MockTestImageCtx &mock_image_ctx, uint64_t snap_id, const SnapInfo* snap_info) { EXPECT_CALL(mock_image_ctx, get_snap_info(snap_id)) .WillOnce(Return(snap_info)); } void expect_rollback(MockTestImageCtx &mock_image_ctx, uint64_t snap_id, const SnapInfo* snap_info, int r) { expect_get_snap_info(mock_image_ctx, snap_id, snap_info); EXPECT_CALL(*mock_image_ctx.operations, execute_snap_rollback(snap_info->snap_namespace, snap_info->name, _, _)) .WillOnce(WithArg<3>(CompleteContext( r, mock_image_ctx.image_ctx->op_work_queue))); } void expect_create_promote_snapshot( MockTestImageCtx &mock_image_ctx, MockCreatePrimaryRequest &mock_create_primary_request, int r) { EXPECT_CALL(mock_create_primary_request, send()) .WillOnce( Invoke([&mock_image_ctx, &mock_create_primary_request, r]() { mock_image_ctx.image_ctx->op_work_queue->queue( mock_create_primary_request.on_finish, r); })); } void expect_release_lock(MockTestImageCtx &mock_image_ctx, int r) { if (mock_image_ctx.exclusive_lock == nullptr) { return; } EXPECT_CALL(*mock_image_ctx.exclusive_lock, unblock_requests()); EXPECT_CALL(*mock_image_ctx.exclusive_lock, release_lock(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); } }; TEST_F(TestMockMirrorSnapshotPromoteRequest, Success) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, true, false, CEPH_NOSNAP, true); MockCreatePrimaryRequest mock_create_primary_request; expect_create_promote_snapshot(mock_image_ctx, mock_create_primary_request, 0); C_SaferCond ctx; auto req = new MockPromoteRequest(&mock_image_ctx, "gid", &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotPromoteRequest, SuccessForce) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } InSequence seq; MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, true, true, CEPH_NOSNAP, true); MockCreateNonPrimaryRequest mock_create_non_primary_request; expect_create_orphan_snapshot(mock_image_ctx, mock_create_non_primary_request, 0); MockListWatchersRequest mock_list_watchers_request; expect_list_watchers(mock_image_ctx, mock_list_watchers_request, {}, 0); expect_acquire_lock(mock_image_ctx, 0); SnapInfo snap_info = {"snap", cls::rbd::MirrorSnapshotNamespace{}, 0, {}, 0, 0, {}}; MockCreatePrimaryRequest mock_create_primary_request; expect_create_promote_snapshot(mock_image_ctx, mock_create_primary_request, 0); expect_release_lock(mock_image_ctx, 0); C_SaferCond ctx; auto req = new MockPromoteRequest(&mock_image_ctx, "gid", &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotPromoteRequest, SuccessRollback) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } InSequence seq; MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, true, false, 123, true); MockCreateNonPrimaryRequest mock_create_non_primary_request; expect_create_orphan_snapshot(mock_image_ctx, mock_create_non_primary_request, 0); MockListWatchersRequest mock_list_watchers_request; expect_list_watchers(mock_image_ctx, mock_list_watchers_request, {}, 0); expect_acquire_lock(mock_image_ctx, 0); SnapInfo snap_info = {"snap", cls::rbd::MirrorSnapshotNamespace{}, 0, {}, 0, 0, {}}; expect_rollback(mock_image_ctx, 123, &snap_info, 0); MockCreatePrimaryRequest mock_create_primary_request; expect_create_promote_snapshot(mock_image_ctx, mock_create_primary_request, 0); expect_release_lock(mock_image_ctx, 0); C_SaferCond ctx; auto req = new MockPromoteRequest(&mock_image_ctx, "gid", &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotPromoteRequest, ErrorCannotRollback) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); InSequence seq; MockUtils mock_utils; expect_can_create_primary_snapshot(mock_utils, true, false, CEPH_NOSNAP, false); C_SaferCond ctx; auto req = new MockPromoteRequest(&mock_image_ctx, "gid", &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } } // namespace snapshot } // namespace mirror } // namespace librbd
13,444
33.474359
107
cc
null
ceph-main/src/test/librbd/mirror/snapshot/test_mock_UnlinkPeerRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/MockOperations.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "librbd/mirror/snapshot/UnlinkPeerRequest.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { explicit MockTestImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace } // namespace librbd // template definitions #include "librbd/mirror/snapshot/UnlinkPeerRequest.cc" template class librbd::mirror::snapshot::UnlinkPeerRequest<librbd::MockTestImageCtx>; namespace librbd { namespace mirror { namespace snapshot { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; class TestMockMirrorSnapshotUnlinkPeerRequest : public TestMockFixture { public: typedef UnlinkPeerRequest<MockTestImageCtx> MockUnlinkPeerRequest; uint64_t m_snap_seq = 0; uint64_t snap_create(MockTestImageCtx &mock_image_ctx, const cls::rbd::SnapshotNamespace &ns, const std::string& snap_name) { EXPECT_TRUE(mock_image_ctx.snap_info.insert( {++m_snap_seq, SnapInfo{snap_name, ns, 0, {}, 0, 0, {}}}).second); return m_snap_seq; } void expect_get_snap_info(MockTestImageCtx &mock_image_ctx, librados::snap_t snap_id) { EXPECT_CALL(mock_image_ctx, get_snap_info(snap_id)) .WillRepeatedly(Invoke([&mock_image_ctx]( librados::snap_t snap_id) -> librbd::SnapInfo * { auto it = mock_image_ctx.snap_info.find(snap_id); if (it == mock_image_ctx.snap_info.end()) { return nullptr; } return &it->second; })); } void expect_is_refresh_required(MockTestImageCtx &mock_image_ctx, bool refresh_required) { EXPECT_CALL(*mock_image_ctx.state, is_refresh_required()) .WillOnce(Return(refresh_required)); } void expect_refresh_image(MockTestImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.state, refresh(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); } void expect_unlink_peer(MockTestImageCtx &mock_image_ctx, uint64_t snap_id, const std::string &peer_uuid, int r) { using ceph::encode; bufferlist bl; encode(snapid_t{snap_id}, bl); encode(peer_uuid, bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("rbd"), StrEq("mirror_image_snapshot_unlink_peer"), ContentsEqual(bl), _, _, _)) .WillOnce(Invoke([&mock_image_ctx, snap_id, peer_uuid, r](auto&&... args) -> int { if (r == 0) { auto it = mock_image_ctx.snap_info.find(snap_id); EXPECT_NE(it, mock_image_ctx.snap_info.end()); auto info = std::get_if<cls::rbd::MirrorSnapshotNamespace>( &it->second.snap_namespace); EXPECT_NE(nullptr, info); EXPECT_NE(0, info->mirror_peer_uuids.erase( peer_uuid)); } return r; })); } void expect_notify_update(MockTestImageCtx &mock_image_ctx, int r) { EXPECT_CALL(mock_image_ctx, notify_update(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); } void expect_remove_snapshot(MockTestImageCtx &mock_image_ctx, uint64_t snap_id, int r) { EXPECT_CALL(*mock_image_ctx.operations, snap_remove(_, _, _)) .WillOnce(Invoke([&mock_image_ctx, snap_id, r]( const cls::rbd::SnapshotNamespace &snap_namespace, const std::string &snap_name, Context *on_finish) { if (r == 0) { auto it = mock_image_ctx.snap_info.find(snap_id); EXPECT_NE(it, mock_image_ctx.snap_info.end()); EXPECT_EQ(it->second.snap_namespace, snap_namespace); EXPECT_EQ(it->second.name, snap_name); mock_image_ctx.snap_info.erase(it); } mock_image_ctx.image_ctx->op_work_queue->queue( on_finish, r); })); } }; TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, Success) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"peer1_uuid", "peer2_uuid"}, "", CEPH_NOSNAP}; auto snap_id = snap_create(mock_image_ctx, ns, "mirror_snap"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, true); expect_refresh_image(mock_image_ctx, 0); expect_unlink_peer(mock_image_ctx, snap_id, "peer1_uuid", 0); expect_notify_update(mock_image_ctx, 0); expect_refresh_image(mock_image_ctx, 0); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "peer1_uuid", true, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, RemoveSnapshot) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"peer_uuid"}, "", CEPH_NOSNAP}; auto snap_id = snap_create(mock_image_ctx, ns, "mirror_snap"); snap_create(mock_image_ctx, ns, "mirror_snap2"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, true); expect_refresh_image(mock_image_ctx, 0); expect_remove_snapshot(mock_image_ctx, snap_id, 0); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "peer_uuid", true, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, RemoveSnapshotNotAllowed) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"peer_uuid"}, "", CEPH_NOSNAP}; auto snap_id = snap_create(mock_image_ctx, ns, "mirror_snap"); snap_create(mock_image_ctx, ns, "mirror_snap2"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, true); expect_refresh_image(mock_image_ctx, 0); expect_unlink_peer(mock_image_ctx, snap_id, "peer_uuid", 0); expect_notify_update(mock_image_ctx, 0); expect_refresh_image(mock_image_ctx, 0); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "peer_uuid", false, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, SnapshotRemoveEmptyPeers) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {}, "", CEPH_NOSNAP}; auto snap_id = snap_create(mock_image_ctx, ns, "mirror_snap"); ns.mirror_peer_uuids = {"peer_uuid"}; snap_create(mock_image_ctx, ns, "mirror_snap2"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, true); expect_refresh_image(mock_image_ctx, 0); expect_remove_snapshot(mock_image_ctx, snap_id, 0); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "peer_uuid", true, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, SnapshotRemoveEmptyPeersNotAllowed) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {}, "", CEPH_NOSNAP}; auto snap_id = snap_create(mock_image_ctx, ns, "mirror_snap"); ns.mirror_peer_uuids = {"peer_uuid"}; snap_create(mock_image_ctx, ns, "mirror_snap2"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, true); expect_refresh_image(mock_image_ctx, 0); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "peer_uuid", false, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, SnapshotDNE) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); expect_get_snap_info(mock_image_ctx, 123); InSequence seq; expect_is_refresh_required(mock_image_ctx, true); expect_refresh_image(mock_image_ctx, 0); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, 123, "peer_uuid", true, &ctx); req->send(); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, PeerDNE) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"peer_uuid"}, "", CEPH_NOSNAP}; auto snap_id = snap_create(mock_image_ctx, ns, "mirror_snap"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, true); expect_refresh_image(mock_image_ctx, 0); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "unknown_peer", true, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, MultiPeerPeerDNE) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"peer1_uuid", "peer2_uuid"}, "", CEPH_NOSNAP}; auto snap_id = snap_create(mock_image_ctx, ns, "mirror_snap"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, true); expect_refresh_image(mock_image_ctx, 0); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "unknown_peer", true, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, InvalidSnapshot) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::UserSnapshotNamespace ns; auto snap_id = snap_create(mock_image_ctx, ns, "user_snap"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, false); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "peer_uuid", true, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, RefreshError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); InSequence seq; expect_is_refresh_required(mock_image_ctx, true); expect_refresh_image(mock_image_ctx, -EINVAL); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, 123, "peer_uuid", true, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, UnlinkError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"peer1_uuid", "peer2_uuid"}, "", CEPH_NOSNAP}; auto snap_id = snap_create(mock_image_ctx, ns, "mirror_snap"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, false); expect_unlink_peer(mock_image_ctx, snap_id, "peer1_uuid", -EINVAL); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "peer1_uuid", true, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, UnlinkErrorRestart) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"peer_uuid"}, "", CEPH_NOSNAP}; auto snap_id = snap_create(mock_image_ctx, ns, "mirror_snap"); snap_create(mock_image_ctx, ns, "mirror_snap2"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, true); expect_refresh_image(mock_image_ctx, 0); expect_unlink_peer(mock_image_ctx, snap_id, "peer_uuid", -ERESTART); expect_refresh_image(mock_image_ctx, 0); expect_remove_snapshot(mock_image_ctx, snap_id, 0); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "peer_uuid", false, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, NotifyError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"peer1_uuid", "peer2_uuid"}, "", CEPH_NOSNAP}; auto snap_id = snap_create(mock_image_ctx, ns, "mirror_snap"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, false); expect_unlink_peer(mock_image_ctx, snap_id, "peer1_uuid", 0); expect_notify_update(mock_image_ctx, -EINVAL); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "peer1_uuid", true, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockMirrorSnapshotUnlinkPeerRequest, RemoveSnapshotError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); cls::rbd::MirrorSnapshotNamespace ns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"peer_uuid"}, "", CEPH_NOSNAP}; auto snap_id = snap_create(mock_image_ctx, ns, "mirror_snap"); snap_create(mock_image_ctx, ns, "mirror_snap2"); expect_get_snap_info(mock_image_ctx, snap_id); InSequence seq; expect_is_refresh_required(mock_image_ctx, false); expect_remove_snapshot(mock_image_ctx, snap_id, -EINVAL); C_SaferCond ctx; auto req = new MockUnlinkPeerRequest(&mock_image_ctx, snap_id, "peer_uuid", true, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } } // namespace snapshot } // namespace mirror } // namespace librbd
16,314
31.5
88
cc
null
ceph-main/src/test/librbd/mirror/snapshot/test_mock_Utils.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/stringify.h" #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/MockOperations.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "librbd/mirror/snapshot/UnlinkPeerRequest.h" #include "librbd/mirror/snapshot/Utils.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { explicit MockTestImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace } // namespace librbd // template definitions #include "librbd/mirror/snapshot/Utils.cc" template bool librbd::mirror::snapshot::util::can_create_primary_snapshot( librbd::MockTestImageCtx *image_ctx, bool demoted, bool force, bool* requires_orphan, uint64_t *rollback_snap_id); template bool librbd::mirror::snapshot::util::can_create_non_primary_snapshot( librbd::MockTestImageCtx *image_ctx); namespace librbd { namespace mirror { namespace snapshot { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; class TestMockMirrorSnapshotUtils : public TestMockFixture { public: uint64_t m_snap_seq = 0; uint64_t snap_create(MockTestImageCtx &mock_image_ctx, const cls::rbd::SnapshotNamespace &ns, const std::string& snap_name) { EXPECT_TRUE(mock_image_ctx.snap_info.insert( {++m_snap_seq, SnapInfo{snap_name, ns, 0, {}, 0, 0, {}}}).second); return m_snap_seq; } }; TEST_F(TestMockMirrorSnapshotUtils, CanCreatePrimarySnapshot) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); // no previous mirror snapshots found bool requires_orphan; uint64_t rollback_snap_id; ASSERT_TRUE(util::can_create_primary_snapshot(&mock_image_ctx, false, false, &requires_orphan, &rollback_snap_id)); ASSERT_FALSE(requires_orphan); ASSERT_EQ(rollback_snap_id, CEPH_NOSNAP); cls::rbd::MirrorSnapshotNamespace nns{ cls::rbd::MIRROR_SNAPSHOT_STATE_NON_PRIMARY, {}, "mirror_uuid", 123}; nns.complete = true; auto copied_snap_id = snap_create(mock_image_ctx, nns, "NPS1"); // without force, previous snapshot is non-primary ASSERT_FALSE(util::can_create_primary_snapshot(&mock_image_ctx, false, false, nullptr, nullptr)); // demoted, previous snapshot is non-primary ASSERT_FALSE(util::can_create_primary_snapshot(&mock_image_ctx, true, true, nullptr, nullptr)); // previous non-primary snapshot is copied ASSERT_TRUE(util::can_create_primary_snapshot(&mock_image_ctx, false, true, &requires_orphan, &rollback_snap_id)); ASSERT_TRUE(requires_orphan); ASSERT_EQ(rollback_snap_id, CEPH_NOSNAP); nns.complete = false; snap_create(mock_image_ctx, nns, "NPS2"); // previous non-primary snapshot is not copied yet ASSERT_FALSE(util::can_create_primary_snapshot(&mock_image_ctx, false, true, nullptr, nullptr)); // can rollback ASSERT_TRUE(util::can_create_primary_snapshot(&mock_image_ctx, false, true, nullptr, &rollback_snap_id)); ASSERT_EQ(rollback_snap_id, copied_snap_id); nns.state = cls::rbd::MIRROR_SNAPSHOT_STATE_NON_PRIMARY_DEMOTED; snap_create(mock_image_ctx, nns, "NPS3"); // previous non-primary snapshot is orphan ASSERT_TRUE(util::can_create_primary_snapshot(&mock_image_ctx, false, true, nullptr, nullptr)); cls::rbd::MirrorSnapshotNamespace pns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY_DEMOTED, {"uuid"}, "", CEPH_NOSNAP}; snap_create(mock_image_ctx, pns, "PS1"); // previous primary snapshot is demoted, no force ASSERT_FALSE(util::can_create_primary_snapshot(&mock_image_ctx, false, false, nullptr, nullptr)); // previous primary snapshot is demoted, force ASSERT_TRUE(util::can_create_primary_snapshot(&mock_image_ctx, false, true, nullptr, nullptr)); pns.state = cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY; snap_create(mock_image_ctx, pns, "PS2"); // previous snapshot is not demoted primary ASSERT_TRUE(util::can_create_primary_snapshot(&mock_image_ctx, false, false, nullptr, nullptr)); } TEST_F(TestMockMirrorSnapshotUtils, CanCreateNonPrimarySnapshot) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); // no previous mirror snapshots found ASSERT_TRUE(util::can_create_non_primary_snapshot(&mock_image_ctx)); cls::rbd::MirrorSnapshotNamespace nns{ cls::rbd::MIRROR_SNAPSHOT_STATE_NON_PRIMARY, {}, "mirror_uuid", 123}; snap_create(mock_image_ctx, nns, "NPS1"); // previous non-primary snapshot is not copied yet ASSERT_FALSE(util::can_create_non_primary_snapshot(&mock_image_ctx)); nns.complete = true; snap_create(mock_image_ctx, nns, "NPS2"); // previous non-primary snapshot is copied ASSERT_TRUE(util::can_create_non_primary_snapshot(&mock_image_ctx)); cls::rbd::MirrorSnapshotNamespace pns{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {"uuid"}, "", CEPH_NOSNAP}; snap_create(mock_image_ctx, pns, "PS1"); // previous primary snapshot is not in demoted state ASSERT_FALSE(util::can_create_non_primary_snapshot(&mock_image_ctx)); pns.state = cls::rbd::MIRROR_SNAPSHOT_STATE_NON_PRIMARY_DEMOTED; snap_create(mock_image_ctx, pns, "PS2"); // previous primary snapshot is in demoted state ASSERT_TRUE(util::can_create_non_primary_snapshot(&mock_image_ctx)); } } // namespace snapshot } // namespace mirror } // namespace librbd
6,376
34.825843
84
cc
null
ceph-main/src/test/librbd/mock/MockContextWQ.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_CONTEXT_WQ_H #define CEPH_TEST_LIBRBD_MOCK_CONTEXT_WQ_H #include "gmock/gmock.h" struct Context; namespace librbd { struct MockContextWQ { MOCK_METHOD2(queue, void(Context *, int r)); }; } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_CONTEXT_WQ_H
391
18.6
70
h
null
ceph-main/src/test/librbd/mock/MockExclusiveLock.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_EXCLUSIVE_LOCK_H #define CEPH_TEST_LIBRBD_MOCK_EXCLUSIVE_LOCK_H #include "common/RefCountedObj.h" #include "include/int_types.h" #include "include/rados/librados.hpp" #include "librbd/exclusive_lock/Policy.h" #include "librbd/io/Types.h" #include "gmock/gmock.h" class Context; namespace librbd { struct MockExclusiveLock { MOCK_CONST_METHOD0(is_lock_owner, bool()); MOCK_METHOD2(init, void(uint64_t features, Context*)); MOCK_METHOD1(shut_down, void(Context*)); MOCK_METHOD1(reacquire_lock, void(Context*)); MOCK_METHOD1(try_acquire_lock, void(Context*)); MOCK_METHOD1(block_requests, void(int)); MOCK_METHOD0(unblock_requests, void()); MOCK_METHOD1(acquire_lock, void(Context *)); MOCK_METHOD1(release_lock, void(Context *)); MOCK_METHOD2(accept_request, bool(exclusive_lock::OperationRequestType, int *)); MOCK_METHOD0(accept_ops, bool()); MOCK_METHOD0(get_unlocked_op_error, int()); MOCK_METHOD3(set_require_lock, void(bool init_shutdown, io::Direction, Context*)); MOCK_METHOD1(unset_require_lock, void(io::Direction)); MOCK_METHOD1(start_op, Context*(int*)); void get() {} void put() {} }; } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_EXCLUSIVE_LOCK_H
1,418
26.823529
73
h
null
ceph-main/src/test/librbd/mock/MockImageCtx.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/neorados/RADOS.hpp" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/MockSafeTimer.h" #include "test/librbd/mock/crypto/MockEncryptionFormat.h" #include "librbd/io/AsyncOperation.h" static MockSafeTimer *s_timer; static ceph::mutex *s_timer_lock; namespace librbd { MockImageCtx* MockImageCtx::s_instance = nullptr; MockImageCtx::MockImageCtx(librbd::ImageCtx &image_ctx) : image_ctx(&image_ctx), cct(image_ctx.cct), perfcounter(image_ctx.perfcounter), snap_namespace(image_ctx.snap_namespace), snap_name(image_ctx.snap_name), snap_id(image_ctx.snap_id), snap_exists(image_ctx.snap_exists), snapc(image_ctx.snapc), snaps(image_ctx.snaps), snap_info(image_ctx.snap_info), snap_ids(image_ctx.snap_ids), old_format(image_ctx.old_format), read_only(image_ctx.read_only), read_only_flags(image_ctx.read_only_flags), read_only_mask(image_ctx.read_only_mask), clone_copy_on_read(image_ctx.clone_copy_on_read), lockers(image_ctx.lockers), exclusive_locked(image_ctx.exclusive_locked), lock_tag(image_ctx.lock_tag), asio_engine(image_ctx.asio_engine), rados_api(image_ctx.rados_api), owner_lock(image_ctx.owner_lock), image_lock(image_ctx.image_lock), timestamp_lock(image_ctx.timestamp_lock), async_ops_lock(image_ctx.async_ops_lock), copyup_list_lock(image_ctx.copyup_list_lock), order(image_ctx.order), size(image_ctx.size), features(image_ctx.features), flags(image_ctx.flags), op_features(image_ctx.op_features), operations_disabled(image_ctx.operations_disabled), stripe_unit(image_ctx.stripe_unit), stripe_count(image_ctx.stripe_count), object_prefix(image_ctx.object_prefix), header_oid(image_ctx.header_oid), id(image_ctx.id), name(image_ctx.name), parent_md(image_ctx.parent_md), format_string(image_ctx.format_string), group_spec(image_ctx.group_spec), layout(image_ctx.layout), io_image_dispatcher(new io::MockImageDispatcher()), io_object_dispatcher(new io::MockObjectDispatcher()), op_work_queue(new MockContextWQ()), plugin_registry(new MockPluginRegistry()), readahead_max_bytes(image_ctx.readahead_max_bytes), event_socket(image_ctx.event_socket), parent(NULL), operations(new MockOperations()), state(new MockImageState()), image_watcher(NULL), object_map(NULL), exclusive_lock(NULL), journal(NULL), trace_endpoint(image_ctx.trace_endpoint), sparse_read_threshold_bytes(image_ctx.sparse_read_threshold_bytes), discard_granularity_bytes(image_ctx.discard_granularity_bytes), mirroring_replay_delay(image_ctx.mirroring_replay_delay), non_blocking_aio(image_ctx.non_blocking_aio), blkin_trace_all(image_ctx.blkin_trace_all), enable_alloc_hint(image_ctx.enable_alloc_hint), alloc_hint_flags(image_ctx.alloc_hint_flags), read_flags(image_ctx.read_flags), ignore_migrating(image_ctx.ignore_migrating), enable_sparse_copyup(image_ctx.enable_sparse_copyup), mtime_update_interval(image_ctx.mtime_update_interval), atime_update_interval(image_ctx.atime_update_interval), cache(image_ctx.cache), config(image_ctx.config) { md_ctx.dup(image_ctx.md_ctx); data_ctx.dup(image_ctx.data_ctx); if (image_ctx.image_watcher != NULL) { image_watcher = new MockImageWatcher(); } } MockImageCtx::~MockImageCtx() { wait_for_async_requests(); wait_for_async_ops(); image_ctx->md_ctx.aio_flush(); image_ctx->data_ctx.aio_flush(); image_ctx->op_work_queue->drain(); delete state; delete operations; delete image_watcher; delete op_work_queue; delete plugin_registry; delete io_image_dispatcher; delete io_object_dispatcher; } void MockImageCtx::set_timer_instance(MockSafeTimer *timer, ceph::mutex *timer_lock) { s_timer = timer; s_timer_lock = timer_lock; } void MockImageCtx::get_timer_instance(CephContext *cct, MockSafeTimer **timer, ceph::mutex **timer_lock) { *timer = s_timer; *timer_lock = s_timer_lock; } void MockImageCtx::wait_for_async_ops() { io::AsyncOperation async_op; async_op.start_op(*image_ctx); C_SaferCond ctx; async_op.flush(&ctx); ctx.wait(); async_op.finish_op(); } IOContext MockImageCtx::get_data_io_context() { auto ctx = std::make_shared<neorados::IOContext>( data_ctx.get_id(), data_ctx.get_namespace()); if (snap_id != CEPH_NOSNAP) { ctx->read_snap(snap_id); } if (!snapc.snaps.empty()) { ctx->write_snap_context( {{snapc.seq, {snapc.snaps.begin(), snapc.snaps.end()}}}); } return ctx; } IOContext MockImageCtx::duplicate_data_io_context() { return std::make_shared<neorados::IOContext>(*get_data_io_context()); } } // namespace librbd
4,932
31.886667
78
cc
null
ceph-main/src/test/librbd/mock/MockImageCtx.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_IMAGE_CTX_H #define CEPH_TEST_LIBRBD_MOCK_IMAGE_CTX_H #include "include/rados/librados.hpp" #include "test/librbd/mock/MockContextWQ.h" #include "test/librbd/mock/MockExclusiveLock.h" #include "test/librbd/mock/MockImageState.h" #include "test/librbd/mock/MockImageWatcher.h" #include "test/librbd/mock/MockJournal.h" #include "test/librbd/mock/MockObjectMap.h" #include "test/librbd/mock/MockOperations.h" #include "test/librbd/mock/MockPluginRegistry.h" #include "test/librbd/mock/MockReadahead.h" #include "test/librbd/mock/io/MockImageDispatcher.h" #include "test/librbd/mock/io/MockObjectDispatcher.h" #include "common/WorkQueue.h" #include "common/zipkin_trace.h" #include "librbd/ImageCtx.h" #include "gmock/gmock.h" #include <string> class MockSafeTimer; namespace librbd { namespace operation { template <typename> class ResizeRequest; } namespace crypto { class MockEncryptionFormat; } struct MockImageCtx { static MockImageCtx *s_instance; static MockImageCtx *create(const std::string &image_name, const std::string &image_id, const char *snap, librados::IoCtx& p, bool read_only) { ceph_assert(s_instance != nullptr); return s_instance; } MockImageCtx(librbd::ImageCtx &image_ctx); virtual ~MockImageCtx(); void wait_for_async_ops(); void wait_for_async_requests() { async_ops_lock.lock(); if (async_requests.empty()) { async_ops_lock.unlock(); return; } C_SaferCond ctx; async_requests_waiters.push_back(&ctx); async_ops_lock.unlock(); ctx.wait(); } MOCK_METHOD1(init_layout, void(int64_t)); MOCK_CONST_METHOD1(get_object_name, std::string(uint64_t)); MOCK_CONST_METHOD0(get_object_size, uint64_t()); MOCK_CONST_METHOD0(get_current_size, uint64_t()); MOCK_CONST_METHOD1(get_image_size, uint64_t(librados::snap_t)); MOCK_CONST_METHOD1(get_area_size, uint64_t(io::ImageArea)); MOCK_CONST_METHOD1(get_object_count, uint64_t(librados::snap_t)); MOCK_CONST_METHOD1(get_read_flags, int(librados::snap_t)); MOCK_CONST_METHOD2(get_flags, int(librados::snap_t in_snap_id, uint64_t *flags)); MOCK_CONST_METHOD2(get_snap_id, librados::snap_t(cls::rbd::SnapshotNamespace snap_namespace, std::string in_snap_name)); MOCK_CONST_METHOD1(get_snap_info, const SnapInfo*(librados::snap_t)); MOCK_CONST_METHOD2(get_snap_name, int(librados::snap_t, std::string *)); MOCK_CONST_METHOD2(get_snap_namespace, int(librados::snap_t, cls::rbd::SnapshotNamespace *out_snap_namespace)); MOCK_CONST_METHOD2(get_parent_spec, int(librados::snap_t in_snap_id, cls::rbd::ParentImageSpec *pspec)); MOCK_CONST_METHOD1(get_parent_info, const ParentImageInfo*(librados::snap_t)); MOCK_CONST_METHOD2(get_parent_overlap, int(librados::snap_t in_snap_id, uint64_t *raw_overlap)); MOCK_CONST_METHOD2(reduce_parent_overlap, std::pair<uint64_t, io::ImageArea>(uint64_t, bool)); MOCK_CONST_METHOD4(prune_parent_extents, uint64_t(std::vector<std::pair<uint64_t, uint64_t>>&, io::ImageArea, uint64_t, bool)); MOCK_CONST_METHOD2(is_snap_protected, int(librados::snap_t in_snap_id, bool *is_protected)); MOCK_CONST_METHOD2(is_snap_unprotected, int(librados::snap_t in_snap_id, bool *is_unprotected)); MOCK_CONST_METHOD0(get_create_timestamp, utime_t()); MOCK_CONST_METHOD0(get_access_timestamp, utime_t()); MOCK_CONST_METHOD0(get_modify_timestamp, utime_t()); MOCK_METHOD1(set_access_timestamp, void(const utime_t at)); MOCK_METHOD1(set_modify_timestamp, void(const utime_t at)); MOCK_METHOD8(add_snap, void(cls::rbd::SnapshotNamespace in_snap_namespace, std::string in_snap_name, librados::snap_t id, uint64_t in_size, const ParentImageInfo &parent, uint8_t protection_status, uint64_t flags, utime_t timestamp)); MOCK_METHOD3(rm_snap, void(cls::rbd::SnapshotNamespace in_snap_namespace, std::string in_snap_name, librados::snap_t id)); MOCK_METHOD0(user_flushed, void()); MOCK_METHOD1(flush_copyup, void(Context *)); MOCK_CONST_METHOD1(test_features, bool(uint64_t test_features)); MOCK_CONST_METHOD2(test_features, bool(uint64_t test_features, const ceph::shared_mutex &in_image_lock)); MOCK_CONST_METHOD1(test_op_features, bool(uint64_t op_features)); MOCK_METHOD1(cancel_async_requests, void(Context*)); MOCK_METHOD0(create_exclusive_lock, MockExclusiveLock*()); MOCK_METHOD1(create_object_map, MockObjectMap*(uint64_t)); MOCK_METHOD0(create_journal, MockJournal*()); MOCK_METHOD0(notify_update, void()); MOCK_METHOD1(notify_update, void(Context *)); MOCK_CONST_METHOD0(get_exclusive_lock_policy, exclusive_lock::Policy*()); MOCK_METHOD1(set_exclusive_lock_policy, void(exclusive_lock::Policy*)); MOCK_CONST_METHOD0(get_journal_policy, journal::Policy*()); MOCK_METHOD1(set_journal_policy, void(journal::Policy*)); MOCK_METHOD2(apply_metadata, int(const std::map<std::string, bufferlist> &, bool)); MOCK_CONST_METHOD0(get_stripe_count, uint64_t()); MOCK_CONST_METHOD0(get_stripe_period, uint64_t()); MOCK_METHOD0(rebuild_data_io_context, void()); IOContext get_data_io_context(); IOContext duplicate_data_io_context(); static void set_timer_instance(MockSafeTimer *timer, ceph::mutex *timer_lock); static void get_timer_instance(CephContext *cct, MockSafeTimer **timer, ceph::mutex **timer_lock); ImageCtx *image_ctx; CephContext *cct; PerfCounters *perfcounter; cls::rbd::SnapshotNamespace snap_namespace; std::string snap_name; uint64_t snap_id; bool snap_exists; ::SnapContext snapc; std::vector<librados::snap_t> snaps; std::map<librados::snap_t, SnapInfo> snap_info; std::map<ImageCtx::SnapKey, librados::snap_t, ImageCtx::SnapKeyComparator> snap_ids; bool old_format; bool read_only; uint32_t read_only_flags; uint32_t read_only_mask; bool clone_copy_on_read; std::map<rados::cls::lock::locker_id_t, rados::cls::lock::locker_info_t> lockers; bool exclusive_locked; std::string lock_tag; std::shared_ptr<AsioEngine> asio_engine; neorados::RADOS& rados_api; librados::IoCtx md_ctx; librados::IoCtx data_ctx; ceph::shared_mutex &owner_lock; ceph::shared_mutex &image_lock; ceph::shared_mutex &timestamp_lock; ceph::mutex &async_ops_lock; ceph::mutex &copyup_list_lock; uint8_t order; uint64_t size; uint64_t features; uint64_t flags; uint64_t op_features; bool operations_disabled; uint64_t stripe_unit; uint64_t stripe_count; std::string object_prefix; std::string header_oid; std::string id; std::string name; ParentImageInfo parent_md; MigrationInfo migration_info; char *format_string; cls::rbd::GroupSpec group_spec; file_layout_t layout; xlist<operation::ResizeRequest<MockImageCtx>*> resize_reqs; xlist<AsyncRequest<MockImageCtx>*> async_requests; std::list<Context*> async_requests_waiters; std::map<uint64_t, io::CopyupRequest<MockImageCtx>*> copyup_list; io::MockImageDispatcher *io_image_dispatcher; io::MockObjectDispatcher *io_object_dispatcher; MockContextWQ *op_work_queue; MockPluginRegistry* plugin_registry; MockReadahead readahead; uint64_t readahead_max_bytes; EventSocket &event_socket; MockImageCtx *child = nullptr; MockImageCtx *parent; MockOperations *operations; MockImageState *state; MockImageWatcher *image_watcher; MockObjectMap *object_map; MockExclusiveLock *exclusive_lock; MockJournal *journal; ZTracer::Endpoint trace_endpoint; std::unique_ptr<crypto::MockEncryptionFormat> encryption_format; uint64_t sparse_read_threshold_bytes; uint32_t discard_granularity_bytes; int mirroring_replay_delay; bool non_blocking_aio; bool blkin_trace_all; bool enable_alloc_hint; uint32_t alloc_hint_flags; uint32_t read_flags; bool ignore_migrating; bool enable_sparse_copyup; uint64_t mtime_update_interval; uint64_t atime_update_interval; bool cache; ConfigProxy config; std::set<std::string> config_overrides; }; } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_IMAGE_CTX_H
8,644
31.996183
86
h
null
ceph-main/src/test/librbd/mock/MockImageState.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_IMAGE_STATE_H #define CEPH_TEST_LIBRBD_MOCK_IMAGE_STATE_H #include <gmock/gmock.h> #include "cls/rbd/cls_rbd_types.h" class Context; namespace librbd { class UpdateWatchCtx; struct MockImageState { MOCK_CONST_METHOD0(is_refresh_required, bool()); MOCK_METHOD1(refresh, void(Context*)); MOCK_METHOD2(open, void(bool, Context*)); MOCK_METHOD0(close, int()); MOCK_METHOD1(close, void(Context*)); MOCK_METHOD2(snap_set, void(uint64_t snap_id, Context*)); MOCK_METHOD1(prepare_lock, void(Context*)); MOCK_METHOD0(handle_prepare_lock_complete, void()); MOCK_METHOD2(register_update_watcher, int(UpdateWatchCtx *, uint64_t *)); MOCK_METHOD2(unregister_update_watcher, void(uint64_t, Context *)); MOCK_METHOD0(handle_update_notification, void()); }; } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_IMAGE_STATE_H
975
23.4
75
h
null
ceph-main/src/test/librbd/mock/MockImageWatcher.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_IMAGE_WATCHER_H #define CEPH_TEST_LIBRBD_MOCK_IMAGE_WATCHER_H #include "gmock/gmock.h" class Context; namespace librbd { class ProgressContext; struct MockImageWatcher { MOCK_METHOD0(is_registered, bool()); MOCK_METHOD0(is_unregistered, bool()); MOCK_METHOD0(is_blocklisted, bool()); MOCK_METHOD0(unregister_watch, void()); MOCK_METHOD1(flush, void(Context *)); MOCK_CONST_METHOD0(get_watch_handle, uint64_t()); MOCK_METHOD0(notify_acquired_lock, void()); MOCK_METHOD0(notify_released_lock, void()); MOCK_METHOD0(notify_request_lock, void()); MOCK_METHOD3(notify_quiesce, void(uint64_t *, ProgressContext &, Context *)); MOCK_METHOD2(notify_unquiesce, void(uint64_t, Context *)); }; } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_IMAGE_WATCHER_H
914
25.142857
79
h
null
ceph-main/src/test/librbd/mock/MockJournal.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/mock/MockJournal.h" namespace librbd { MockJournal *MockJournal::s_instance = nullptr; } // namespace librbd
233
20.272727
70
cc
null
ceph-main/src/test/librbd/mock/MockJournal.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_JOURNAL_H #define CEPH_TEST_LIBRBD_MOCK_JOURNAL_H #include "common/RefCountedObj.h" #include "gmock/gmock.h" #include "include/rados/librados_fwd.hpp" #include "librbd/Journal.h" #include "librbd/journal/Types.h" #include <list> struct Context; struct ContextWQ; namespace librbd { struct ImageCtx; struct MockJournal { static MockJournal *s_instance; static MockJournal *get_instance() { ceph_assert(s_instance != nullptr); return s_instance; } template <typename ImageCtxT> static int is_tag_owner(ImageCtxT *image_ctx, bool *is_tag_owner) { return get_instance()->is_tag_owner(is_tag_owner); } static void get_tag_owner(librados::IoCtx &, const std::string &global_image_id, std::string *tag_owner, ContextWQ *work_queue, Context *on_finish) { get_instance()->get_tag_owner(global_image_id, tag_owner, work_queue, on_finish); } MockJournal() { s_instance = this; } void get() {} void put() {} MOCK_CONST_METHOD0(is_journal_ready, bool()); MOCK_CONST_METHOD0(is_journal_replaying, bool()); MOCK_CONST_METHOD0(is_journal_appending, bool()); MOCK_METHOD1(wait_for_journal_ready, void(Context *)); MOCK_METHOD4(get_tag_owner, void(const std::string &, std::string *, ContextWQ *, Context *)); MOCK_CONST_METHOD0(is_tag_owner, bool()); MOCK_CONST_METHOD1(is_tag_owner, int(bool *)); MOCK_METHOD3(allocate_tag, void(const std::string &mirror_uuid, const journal::TagPredecessor &predecessor, Context *on_finish)); MOCK_METHOD1(open, void(Context *)); MOCK_METHOD1(close, void(Context *)); MOCK_CONST_METHOD0(get_tag_tid, uint64_t()); MOCK_CONST_METHOD0(get_tag_data, journal::TagData()); MOCK_METHOD0(allocate_op_tid, uint64_t()); MOCK_METHOD0(user_flushed, void()); MOCK_METHOD3(append_op_event_mock, void(uint64_t, const journal::EventEntry&, Context *)); void append_op_event(uint64_t op_tid, journal::EventEntry &&event_entry, Context *on_safe) { // googlemock doesn't support move semantics append_op_event_mock(op_tid, event_entry, on_safe); } MOCK_METHOD2(flush_event, void(uint64_t, Context *)); MOCK_METHOD2(wait_event, void(uint64_t, Context *)); MOCK_METHOD3(commit_op_event, void(uint64_t, int, Context *)); MOCK_METHOD2(replay_op_ready, void(uint64_t, Context *)); MOCK_METHOD1(add_listener, void(journal::Listener *)); MOCK_METHOD1(remove_listener, void(journal::Listener *)); MOCK_METHOD1(is_resync_requested, int(bool *)); }; } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_JOURNAL_H
2,977
29.701031
79
h
null
ceph-main/src/test/librbd/mock/MockJournalPolicy.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_JOURNAL_POLICY_H #define CEPH_TEST_LIBRBD_MOCK_JOURNAL_POLICY_H #include "librbd/journal/Policy.h" #include "gmock/gmock.h" namespace librbd { struct MockJournalPolicy : public journal::Policy { MOCK_CONST_METHOD0(append_disabled, bool()); MOCK_CONST_METHOD0(journal_disabled, bool()); MOCK_METHOD1(allocate_tag_on_lock, void(Context*)); }; } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_JOURNAL_POLICY_H
554
23.130435
70
h
null
ceph-main/src/test/librbd/mock/MockObjectMap.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_OBJECT_MAP_H #define CEPH_TEST_LIBRBD_MOCK_OBJECT_MAP_H #include "librbd/Utils.h" #include "gmock/gmock.h" namespace librbd { struct MockObjectMap { MOCK_METHOD1(at, uint8_t(uint64_t)); uint8_t operator[](uint64_t object_no) { return at(object_no); } MOCK_CONST_METHOD0(size, uint64_t()); MOCK_METHOD1(open, void(Context *on_finish)); MOCK_METHOD1(close, void(Context *on_finish)); MOCK_METHOD3(aio_resize, void(uint64_t new_size, uint8_t default_object_state, Context *on_finish)); void get() {} void put() {} template <typename T, void(T::*MF)(int) = &T::complete> bool aio_update(uint64_t snap_id, uint64_t start_object_no, uint8_t new_state, const boost::optional<uint8_t> &current_state, const ZTracer::Trace &parent_trace, bool ignore_enoent, T *callback_object) { return aio_update<T, MF>(snap_id, start_object_no, start_object_no + 1, new_state, current_state, parent_trace, ignore_enoent, callback_object); } template <typename T, void(T::*MF)(int) = &T::complete> bool aio_update(uint64_t snap_id, uint64_t start_object_no, uint64_t end_object_no, uint8_t new_state, const boost::optional<uint8_t> &current_state, const ZTracer::Trace &parent_trace, bool ignore_enoent, T *callback_object) { auto ctx = util::create_context_callback<T, MF>(callback_object); bool updated = aio_update(snap_id, start_object_no, end_object_no, new_state, current_state, parent_trace, ignore_enoent, ctx); if (!updated) { delete ctx; } return updated; } MOCK_METHOD8(aio_update, bool(uint64_t snap_id, uint64_t start_object_no, uint64_t end_object_no, uint8_t new_state, const boost::optional<uint8_t> &current_state, const ZTracer::Trace &parent_trace, bool ignore_enoent, Context *on_finish)); MOCK_METHOD2(snapshot_add, void(uint64_t snap_id, Context *on_finish)); MOCK_METHOD2(snapshot_remove, void(uint64_t snap_id, Context *on_finish)); MOCK_METHOD2(rollback, void(uint64_t snap_id, Context *on_finish)); MOCK_CONST_METHOD1(object_may_exist, bool(uint64_t)); }; } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_OBJECT_MAP_H
2,646
36.28169
80
h
null
ceph-main/src/test/librbd/mock/MockOperations.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_OPERATIONS_H #define CEPH_TEST_LIBRBD_MOCK_OPERATIONS_H #include "cls/rbd/cls_rbd_types.h" #include "include/int_types.h" #include "include/rbd/librbd.hpp" #include "gmock/gmock.h" #include <string> class Context; namespace librbd { struct MockOperations { MOCK_METHOD2(execute_flatten, void(ProgressContext &prog_ctx, Context *on_finish)); MOCK_METHOD2(execute_rebuild_object_map, void(ProgressContext &prog_ctx, Context *on_finish)); MOCK_METHOD2(execute_rename, void(const std::string &dstname, Context *on_finish)); MOCK_METHOD5(execute_resize, void(uint64_t size, bool allow_shrink, ProgressContext &prog_ctx, Context *on_finish, uint64_t journal_op_tid)); MOCK_METHOD5(snap_create, void(const cls::rbd::SnapshotNamespace &snapshot_namespace, const std::string &snap_name, uint64_t flags, ProgressContext &prog_ctx, Context *on_finish)); MOCK_METHOD6(execute_snap_create, void(const cls::rbd::SnapshotNamespace &snapshot_namespace, const std::string &snap_name, Context *on_finish, uint64_t journal_op_tid, uint64_t flags, ProgressContext &prog_ctx)); MOCK_METHOD3(snap_remove, void(const cls::rbd::SnapshotNamespace &snap_namespace, const std::string &snap_name, Context *on_finish)); MOCK_METHOD3(execute_snap_remove, void(const cls::rbd::SnapshotNamespace &snap_namespace, const std::string &snap_name, Context *on_finish)); MOCK_METHOD3(execute_snap_rename, void(uint64_t src_snap_id, const std::string &snap_name, Context *on_finish)); MOCK_METHOD4(execute_snap_rollback, void(const cls::rbd::SnapshotNamespace &snap_namespace, const std::string &snap_name, ProgressContext &prog_ctx, Context *on_finish)); MOCK_METHOD3(execute_snap_protect, void(const cls::rbd::SnapshotNamespace &snap_namespace, const std::string &snap_name, Context *on_finish)); MOCK_METHOD3(execute_snap_unprotect, void(const cls::rbd::SnapshotNamespace &snap_namespace, const std::string &snap_name, Context *on_finish)); MOCK_METHOD2(execute_snap_set_limit, void(uint64_t limit, Context *on_finish)); MOCK_METHOD4(execute_update_features, void(uint64_t features, bool enabled, Context *on_finish, uint64_t journal_op_tid)); MOCK_METHOD3(execute_metadata_set, void(const std::string &key, const std::string &value, Context *on_finish)); MOCK_METHOD2(execute_metadata_remove, void(const std::string &key, Context *on_finish)); }; } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_OPERATIONS_H
3,640
48.876712
95
h
null
ceph-main/src/test/librbd/mock/MockPluginRegistry.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_PLUGIN_REGISTRY_H #define CEPH_TEST_LIBRBD_MOCK_PLUGIN_REGISTRY_H #include <gmock/gmock.h> class Context; namespace librbd { struct MockPluginRegistry{ MOCK_METHOD2(init, void(const std::string&, Context*)); MOCK_METHOD1(acquired_exclusive_lock, void(Context*)); MOCK_METHOD1(prerelease_exclusive_lock, void(Context*)); }; } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_PLUGIN_REGISTRY_H
536
23.409091
70
h
null
ceph-main/src/test/librbd/mock/MockReadahead.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_READAHEAD_H #define CEPH_TEST_LIBRBD_MOCK_READAHEAD_H #include "include/int_types.h" #include "gmock/gmock.h" class Context; namespace librbd { struct MockReadahead { MOCK_METHOD1(set_max_readahead_size, void(uint64_t)); MOCK_METHOD1(wait_for_pending, void(Context *)); }; } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_READAHEAD_H
478
20.772727
70
h
null
ceph-main/src/test/librbd/mock/MockSafeTimer.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_MOCK_SAFE_TIMER_H #define CEPH_MOCK_SAFE_TIMER_H #include <gmock/gmock.h> struct Context; struct MockSafeTimer { virtual ~MockSafeTimer() { } MOCK_METHOD2(add_event_after, Context*(double, Context *)); MOCK_METHOD2(add_event_at, Context*(ceph::real_clock::time_point, Context *)); MOCK_METHOD1(cancel_event, bool(Context *)); }; #endif // CEPH_MOCK_SAFE_TIMER_H
489
22.333333
80
h
null
ceph-main/src/test/librbd/mock/cache/MockImageCache.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_CACHE_MOCK_IMAGE_CACHE_H #define CEPH_TEST_LIBRBD_CACHE_MOCK_IMAGE_CACHE_H #include "gmock/gmock.h" #include "librbd/io/Types.h" #include <vector> namespace librbd { namespace cache { struct MockImageCache { typedef std::vector<std::pair<uint64_t,uint64_t> > Extents; MOCK_METHOD4(aio_read_mock, void(const Extents &, ceph::bufferlist*, int, Context *)); void aio_read(Extents&& image_extents, ceph::bufferlist* bl, int fadvise_flags, Context *on_finish) { aio_read_mock(image_extents, bl, fadvise_flags, on_finish); } MOCK_METHOD4(aio_write_mock, void(const Extents &, const ceph::bufferlist &, int, Context *)); void aio_write(Extents&& image_extents, ceph::bufferlist&& bl, int fadvise_flags, Context *on_finish) { aio_write_mock(image_extents, bl, fadvise_flags, on_finish); } MOCK_METHOD4(aio_discard, void(uint64_t, uint64_t, uint32_t, Context *)); MOCK_METHOD1(aio_flush, void(Context *)); MOCK_METHOD2(aio_flush, void(librbd::io::FlushSource, Context *)); MOCK_METHOD5(aio_writesame_mock, void(uint64_t, uint64_t, ceph::bufferlist& bl, int, Context *)); void aio_writesame(uint64_t off, uint64_t len, ceph::bufferlist&& bl, int fadvise_flags, Context *on_finish) { aio_writesame_mock(off, len, bl, fadvise_flags, on_finish); } MOCK_METHOD6(aio_compare_and_write_mock, void(const Extents &, const ceph::bufferlist &, const ceph::bufferlist &, uint64_t *, int, Context *)); void aio_compare_and_write(Extents&& image_extents, ceph::bufferlist&& cmp_bl, ceph::bufferlist&& bl, uint64_t *mismatch_offset, int fadvise_flags, Context *on_finish) { aio_compare_and_write_mock(image_extents, cmp_bl, bl, mismatch_offset, fadvise_flags, on_finish); } }; } // namespace cache } // namespace librbd #endif // CEPH_TEST_LIBRBD_CACHE_MOCK_IMAGE_CACHE_H
2,329
38.491525
81
h
null
ceph-main/src/test/librbd/mock/crypto/MockCryptoInterface.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_CRYPTO_MOCK_CRYPTO_INTERFACE_H #define CEPH_TEST_LIBRBD_MOCK_CRYPTO_MOCK_CRYPTO_INTERFACE_H #include "include/buffer.h" #include "gmock/gmock.h" #include "librbd/crypto/CryptoInterface.h" namespace librbd { namespace crypto { struct MockCryptoInterface : CryptoInterface { static const uint64_t BLOCK_SIZE = 4096; static const uint64_t DATA_OFFSET = 4 * 1024 * 1024; MOCK_METHOD2(encrypt, int(ceph::bufferlist*, uint64_t)); MOCK_METHOD2(decrypt, int(ceph::bufferlist*, uint64_t)); MOCK_CONST_METHOD0(get_key, const unsigned char*()); MOCK_CONST_METHOD0(get_key_length, int()); uint64_t get_block_size() const override { return BLOCK_SIZE; } uint64_t get_data_offset() const override { return DATA_OFFSET; } }; } // namespace crypto } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_CRYPTO_MOCK_CRYPTO_INTERFACE_H
983
25.594595
70
h
null
ceph-main/src/test/librbd/mock/crypto/MockDataCryptor.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_CRYPTO_MOCK_DATA_CRYPTOR_H #define CEPH_TEST_LIBRBD_MOCK_CRYPTO_MOCK_DATA_CRYPTOR_H #include "gmock/gmock.h" #include "librbd/crypto/DataCryptor.h" namespace librbd { namespace crypto { struct MockCryptoContext {}; class MockDataCryptor : public DataCryptor<MockCryptoContext> { public: uint32_t block_size = 16; uint32_t iv_size = 16; uint32_t get_block_size() const override { return block_size; } uint32_t get_iv_size() const override { return iv_size; } MOCK_METHOD1(get_context, MockCryptoContext*(CipherMode)); MOCK_METHOD2(return_context, void(MockCryptoContext*, CipherMode)); MOCK_CONST_METHOD3(init_context, int(MockCryptoContext*, const unsigned char*, uint32_t)); MOCK_CONST_METHOD4(update_context, int(MockCryptoContext*, const unsigned char*, unsigned char*, uint32_t)); MOCK_CONST_METHOD0(get_key, const unsigned char*()); MOCK_CONST_METHOD0(get_key_length, int()); }; } // namespace crypto } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_CRYPTO_MOCK_DATA_CRYPTOR_H
1,279
28.090909
78
h
null
ceph-main/src/test/librbd/mock/crypto/MockEncryptionFormat.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_CRYPTO_MOCK_ENCRYPTION_FORMAT_H #define CEPH_TEST_LIBRBD_MOCK_CRYPTO_MOCK_ENCRYPTION_FORMAT_H #include "gmock/gmock.h" #include "librbd/crypto/EncryptionFormat.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/crypto/MockCryptoInterface.h" namespace librbd { namespace crypto { struct MockEncryptionFormat { MOCK_CONST_METHOD0(clone, std::unique_ptr<MockEncryptionFormat>()); MOCK_METHOD2(format, void(MockImageCtx*, Context*)); MOCK_METHOD3(load, void(MockImageCtx*, std::string*, Context*)); MOCK_METHOD2(flatten, void(MockImageCtx*, Context*)); MOCK_METHOD0(get_crypto, MockCryptoInterface*()); }; } // namespace crypto } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_CRYPTO_MOCK_ENCRYPTION_FORMAT_H
876
31.481481
70
h
null
ceph-main/src/test/librbd/mock/exclusive_lock/MockPolicy.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_EXCLUSIVE_LOCK_POLICY_H #define CEPH_TEST_LIBRBD_MOCK_EXCLUSIVE_LOCK_POLICY_H #include "librbd/exclusive_lock/Policy.h" #include <gmock/gmock.h> namespace librbd { namespace exclusive_lock { struct MockPolicy : public Policy { MOCK_METHOD0(may_auto_request_lock, bool()); MOCK_METHOD1(lock_requested, int(bool)); MOCK_METHOD1(accept_blocked_request, bool(OperationRequestType)); }; } // namespace exclusive_lock } // librbd #endif
572
22.875
70
h
null
ceph-main/src/test/librbd/mock/io/MockImageDispatch.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_IO_IMAGE_DISPATCH_H #define CEPH_TEST_LIBRBD_MOCK_IO_IMAGE_DISPATCH_H #include "gmock/gmock.h" #include "include/Context.h" #include "librbd/io/ImageDispatchInterface.h" #include "librbd/io/Types.h" class Context; namespace librbd { namespace io { struct MockImageDispatch : public ImageDispatchInterface { public: MOCK_CONST_METHOD0(get_dispatch_layer, ImageDispatchLayer()); MOCK_METHOD1(shut_down, void(Context*)); bool read( AioCompletion* aio_comp, Extents &&image_extents, ReadResult &&read_result, IOContext io_context, int op_flags, int read_flags, const ZTracer::Trace &parent_trace, uint64_t tid, std::atomic<uint32_t>* image_dispatch_flags, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) override { return false; } bool write( AioCompletion* aio_comp, Extents &&image_extents, bufferlist &&bl, int op_flags, const ZTracer::Trace &parent_trace, uint64_t tid, std::atomic<uint32_t>* image_dispatch_flags, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) override { return false; } bool discard( AioCompletion* aio_comp, Extents &&image_extents, uint32_t discard_granularity_bytes, const ZTracer::Trace &parent_trace, uint64_t tid, std::atomic<uint32_t>* image_dispatch_flags, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) override { return false; } bool write_same( AioCompletion* aio_comp, Extents &&image_extents, bufferlist &&bl, int op_flags, const ZTracer::Trace &parent_trace, uint64_t tid, std::atomic<uint32_t>* image_dispatch_flags, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) override { return false; } bool compare_and_write( AioCompletion* aio_comp, Extents &&image_extents, bufferlist &&cmp_bl, bufferlist &&bl, uint64_t *mismatch_offset, int op_flags, const ZTracer::Trace &parent_trace, uint64_t tid, std::atomic<uint32_t>* image_dispatch_flags, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) override { return false; } bool flush( AioCompletion* aio_comp, FlushSource flush_source, const ZTracer::Trace &parent_trace, uint64_t tid, std::atomic<uint32_t>* image_dispatch_flags, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) override { return false; } bool list_snaps( AioCompletion* aio_comp, Extents&& image_extents, SnapIds&& snap_ids, int list_snaps_flags, SnapshotDelta* snapshot_delta, const ZTracer::Trace &parent_trace, uint64_t tid, std::atomic<uint32_t>* image_dispatch_flags, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) override { return false; } bool invalidate_cache(Context* on_finish) override { return false; } }; } // namespace io } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_IO_IMAGE_DISPATCH_H
3,209
31.424242
77
h
null
ceph-main/src/test/librbd/mock/io/MockImageDispatcher.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_IO_IMAGE_DISPATCHER_H #define CEPH_TEST_LIBRBD_MOCK_IO_IMAGE_DISPATCHER_H #include "gmock/gmock.h" #include "include/Context.h" #include "librbd/io/ImageDispatcher.h" #include "librbd/io/ImageDispatchSpec.h" #include "librbd/io/Types.h" class Context; namespace librbd { namespace io { struct ImageDispatchInterface; struct MockImageDispatcher : public ImageDispatcherInterface { public: MOCK_METHOD1(shut_down, void(Context*)); MOCK_METHOD1(register_dispatch, void(ImageDispatchInterface*)); MOCK_METHOD1(exists, bool(ImageDispatchLayer)); MOCK_METHOD2(shut_down_dispatch, void(ImageDispatchLayer, Context*)); MOCK_METHOD1(invalidate_cache, void(Context *)); MOCK_METHOD1(send, void(ImageDispatchSpec*)); MOCK_METHOD3(finish, void(int r, ImageDispatchLayer, uint64_t)); MOCK_METHOD1(apply_qos_schedule_tick_min, void(uint64_t)); MOCK_METHOD4(apply_qos_limit, void(uint64_t, uint64_t, uint64_t, uint64_t)); MOCK_METHOD1(apply_qos_exclude_ops, void(uint64_t)); MOCK_CONST_METHOD0(writes_blocked, bool()); MOCK_METHOD0(block_writes, int()); MOCK_METHOD1(block_writes, void(Context*)); MOCK_METHOD0(unblock_writes, void()); MOCK_METHOD1(wait_on_writes_unblocked, void(Context*)); MOCK_METHOD2(remap_to_physical, void(Extents&, ImageArea)); MOCK_METHOD1(remap_to_logical, ImageArea(Extents&)); }; } // namespace io } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_IO_IMAGE_DISPATCHER_H
1,563
29.666667
78
h
null
ceph-main/src/test/librbd/mock/io/MockObjectDispatch.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_IO_OBJECT_DISPATCH_H #define CEPH_TEST_LIBRBD_MOCK_IO_OBJECT_DISPATCH_H #include "gmock/gmock.h" #include "common/ceph_mutex.h" #include "librbd/io/ObjectDispatchInterface.h" #include "librbd/io/Types.h" class Context; namespace librbd { namespace io { struct MockObjectDispatch : public ObjectDispatchInterface { public: ceph::shared_mutex lock = ceph::make_shared_mutex("MockObjectDispatch::lock"); MockObjectDispatch() {} MOCK_CONST_METHOD0(get_dispatch_layer, ObjectDispatchLayer()); MOCK_METHOD1(shut_down, void(Context*)); MOCK_METHOD6(execute_read, bool(uint64_t, ReadExtents*, IOContext io_context, uint64_t*, DispatchResult*, Context*)); bool read( uint64_t object_no, ReadExtents* extents, IOContext io_context, int op_flags, int read_flags, const ZTracer::Trace& parent_trace, uint64_t* version, int* dispatch_flags, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) { return execute_read(object_no, extents, io_context, version, dispatch_result, on_dispatched); } MOCK_METHOD9(execute_discard, bool(uint64_t, uint64_t, uint64_t, IOContext, int, int*, uint64_t*, DispatchResult*, Context*)); bool discard( uint64_t object_no, uint64_t object_off, uint64_t object_len, IOContext io_context, int discard_flags, const ZTracer::Trace &parent_trace, int* dispatch_flags, uint64_t* journal_tid, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) { return execute_discard(object_no, object_off, object_len, io_context, discard_flags, dispatch_flags, journal_tid, dispatch_result, on_dispatched); } MOCK_METHOD10(execute_write, bool(uint64_t, uint64_t, const ceph::bufferlist&, IOContext, int, std::optional<uint64_t>, int*, uint64_t*, DispatchResult*, Context *)); bool write( uint64_t object_no, uint64_t object_off, ceph::bufferlist&& data, IOContext io_context, int op_flags, int write_flags, std::optional<uint64_t> assert_version, const ZTracer::Trace &parent_trace, int* dispatch_flags, uint64_t* journal_tid, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) override { return execute_write(object_no, object_off, data, io_context, write_flags, assert_version, dispatch_flags, journal_tid, dispatch_result, on_dispatched); } MOCK_METHOD10(execute_write_same, bool(uint64_t, uint64_t, uint64_t, const LightweightBufferExtents&, const ceph::bufferlist&, IOContext, int*, uint64_t*, DispatchResult*, Context *)); bool write_same( uint64_t object_no, uint64_t object_off, uint64_t object_len, LightweightBufferExtents&& buffer_extents, ceph::bufferlist&& data, IOContext io_context, int op_flags, const ZTracer::Trace &parent_trace, int* dispatch_flags, uint64_t* journal_tid, DispatchResult* dispatch_result, Context* *on_finish, Context* on_dispatched) override { return execute_write_same(object_no, object_off, object_len, buffer_extents, data, io_context, dispatch_flags, journal_tid, dispatch_result, on_dispatched); } MOCK_METHOD9(execute_compare_and_write, bool(uint64_t, uint64_t, const ceph::bufferlist&, const ceph::bufferlist&, uint64_t*, int*, uint64_t*, DispatchResult*, Context *)); bool compare_and_write( uint64_t object_no, uint64_t object_off, ceph::bufferlist&& cmp_data, ceph::bufferlist&& write_data, IOContext io_context, int op_flags, const ZTracer::Trace &parent_trace, uint64_t* mismatch_offset, int* dispatch_flags, uint64_t* journal_tid, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) override { return execute_compare_and_write(object_no, object_off, cmp_data, write_data, mismatch_offset, dispatch_flags, journal_tid, dispatch_result, on_dispatched); } MOCK_METHOD4(execute_flush, bool(FlushSource, uint64_t*, DispatchResult*, Context*)); bool flush(FlushSource flush_source, const ZTracer::Trace &parent_trace, uint64_t* journal_tid, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) { return execute_flush(flush_source, journal_tid, dispatch_result, on_dispatched); } MOCK_METHOD7(execute_list_snaps, bool(uint64_t, const Extents&, const SnapIds&, int, SnapshotDelta*, DispatchResult*, Context*)); bool list_snaps( uint64_t object_no, io::Extents&& extents, SnapIds&& snap_ids, int list_snaps_flags, const ZTracer::Trace &parent_trace, SnapshotDelta* snapshot_delta, int* object_dispatch_flags, DispatchResult* dispatch_result, Context** on_finish, Context* on_dispatched) override { return execute_list_snaps(object_no, extents, snap_ids, list_snaps_flags, snapshot_delta, dispatch_result, on_dispatched); } MOCK_METHOD1(invalidate_cache, bool(Context*)); MOCK_METHOD1(reset_existence_cache, bool(Context*)); MOCK_METHOD5(extent_overwritten, void(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t)); MOCK_METHOD2(prepare_copyup, int(uint64_t, SnapshotSparseBufferlist*)); }; } // namespace io } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_IO_OBJECT_DISPATCH_H
6,074
43.021739
80
h
null
ceph-main/src/test/librbd/mock/io/MockObjectDispatcher.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_IO_OBJECT_DISPATCHER_H #define CEPH_TEST_LIBRBD_MOCK_IO_OBJECT_DISPATCHER_H #include "gmock/gmock.h" #include "include/Context.h" #include "librbd/io/ObjectDispatcher.h" #include "librbd/io/ObjectDispatchSpec.h" #include "librbd/io/Types.h" class Context; namespace librbd { namespace io { struct ObjectDispatchInterface; struct MockObjectDispatcher : public ObjectDispatcherInterface { public: MOCK_METHOD1(shut_down, void(Context*)); MOCK_METHOD1(register_dispatch, void(ObjectDispatchInterface*)); MOCK_METHOD1(exists, bool(ObjectDispatchLayer)); MOCK_METHOD2(shut_down_dispatch, void(ObjectDispatchLayer, Context*)); MOCK_METHOD2(flush, void(FlushSource, Context*)); MOCK_METHOD1(invalidate_cache, void(Context*)); MOCK_METHOD1(reset_existence_cache, void(Context*)); MOCK_METHOD5(extent_overwritten, void(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t)); MOCK_METHOD2(prepare_copyup, int(uint64_t, SnapshotSparseBufferlist*)); MOCK_METHOD1(send, void(ObjectDispatchSpec*)); }; } // namespace io } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_IO_OBJECT_DISPATCHER_H
1,281
27.488889
79
h
null
ceph-main/src/test/librbd/mock/io/MockQosImageDispatch.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_IO_QOS_IMAGE_DISPATCH_H #define CEPH_TEST_LIBRBD_MOCK_IO_QOS_IMAGE_DISPATCH_H #include "gmock/gmock.h" #include "librbd/io/Types.h" #include <atomic> struct Context; namespace librbd { namespace io { struct MockQosImageDispatch { MOCK_METHOD4(needs_throttle, bool(bool, const Extents&, std::atomic<uint32_t>*, Context*)); }; } // namespace io } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_IO_QOS_IMAGE_DISPATCH_H
594
22.8
71
h
null
ceph-main/src/test/librbd/mock/migration/MockSnapshotInterface.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_MIGRATION_MOCK_SNAPSHOT_INTERFACE_H #define CEPH_TEST_LIBRBD_MOCK_MIGRATION_MOCK_SNAPSHOT_INTERFACE_H #include "include/buffer.h" #include "gmock/gmock.h" #include "librbd/io/AioCompletion.h" #include "librbd/io/ReadResult.h" #include "librbd/io/Types.h" #include "librbd/migration/SnapshotInterface.h" namespace librbd { namespace migration { struct MockSnapshotInterface : public SnapshotInterface { MOCK_METHOD2(open, void(SnapshotInterface*, Context*)); MOCK_METHOD1(close, void(Context*)); MOCK_CONST_METHOD0(get_snap_info, const SnapInfo&()); MOCK_METHOD3(read, void(io::AioCompletion*, const io::Extents&, io::ReadResult&)); void read(io::AioCompletion* aio_comp, io::Extents&& image_extents, io::ReadResult&& read_result, int op_flags, int read_flags, const ZTracer::Trace &parent_trace) override { read(aio_comp, image_extents, read_result); } MOCK_METHOD3(list_snap, void(const io::Extents&, io::SparseExtents*, Context*)); void list_snap(io::Extents&& image_extents, int list_snaps_flags, io::SparseExtents* sparse_extents, const ZTracer::Trace &parent_trace, Context* on_finish) override { list_snap(image_extents, sparse_extents, on_finish); } }; } // namespace migration } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_MIGRATION_MOCK_SNAPSHOT_INTERFACE_H
1,570
33.911111
71
h
null
ceph-main/src/test/librbd/mock/migration/MockStreamInterface.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_TEST_LIBRBD_MOCK_MIGRATION_MOCK_STREAM_INTERFACE_H #define CEPH_TEST_LIBRBD_MOCK_MIGRATION_MOCK_STREAM_INTERFACE_H #include "include/buffer.h" #include "gmock/gmock.h" #include "librbd/migration/StreamInterface.h" namespace librbd { namespace migration { struct MockStreamInterface : public StreamInterface { MOCK_METHOD1(open, void(Context*)); MOCK_METHOD1(close, void(Context*)); MOCK_METHOD2(get_size, void(uint64_t*, Context*)); MOCK_METHOD3(read, void(const io::Extents&, bufferlist*, Context*)); void read(io::Extents&& byte_extents, bufferlist* bl, Context* on_finish) { read(byte_extents, bl, on_finish); } }; } // namespace migration } // namespace librbd #endif // CEPH_TEST_LIBRBD_MOCK_MIGRATION_MOCK_STREAM_INTERFACE_H
866
27.9
77
h
null
ceph-main/src/test/librbd/object_map/test_mock_DiffRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "include/rbd_types.h" #include "common/ceph_mutex.h" #include "librbd/object_map/DiffRequest.h" #include "gtest/gtest.h" #include "gmock/gmock.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace } // namespace librbd #include "librbd/object_map/DiffRequest.cc" using ::testing::_; using ::testing::Invoke; using ::testing::InSequence; using ::testing::StrEq; using ::testing::WithArg; namespace librbd { namespace object_map { class TestMockObjectMapDiffRequest : public TestMockFixture { public: typedef DiffRequest<MockTestImageCtx> MockDiffRequest; void SetUp() override { TestMockFixture::SetUp(); ASSERT_EQ(0, open_image(m_image_name, &m_image_ctx)); } void expect_get_flags(MockTestImageCtx& mock_image_ctx, uint64_t snap_id, int32_t flags, int r) { EXPECT_CALL(mock_image_ctx, get_flags(snap_id, _)) .WillOnce(WithArg<1>(Invoke([flags, r](uint64_t *out_flags) { *out_flags = flags; return r; }))); } template <typename Lambda> void expect_load_map(MockTestImageCtx& mock_image_ctx, uint64_t snap_id, const BitVector<2>& object_map, int r, Lambda&& lambda) { std::string snap_oid(ObjectMap<>::object_map_name(mock_image_ctx.id, snap_id)); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(snap_oid, _, StrEq("rbd"), StrEq("object_map_load"), _, _, _, _)) .WillOnce(WithArg<5>(Invoke([object_map, r, lambda=std::move(lambda)] (bufferlist* out_bl) { lambda(); auto out_object_map{object_map}; out_object_map.set_crc_enabled(false); encode(out_object_map, *out_bl); return r; }))); } void expect_load_map(MockTestImageCtx& mock_image_ctx, uint64_t snap_id, const BitVector<2>& object_map, int r) { expect_load_map(mock_image_ctx, snap_id, object_map, r, [](){}); } librbd::ImageCtx* m_image_ctx = nullptr; BitVector<2> m_object_diff_state; }; TEST_F(TestMockObjectMapDiffRequest, InvalidStartSnap) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, CEPH_NOSNAP, 0, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockObjectMapDiffRequest, StartEndSnapEqual) { MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 1, 1, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); ASSERT_EQ(0U, m_object_diff_state.size()); } TEST_F(TestMockObjectMapDiffRequest, FastDiffDisabled) { // negative test -- object-map implicitly enables fast-diff REQUIRE(!is_feature_enabled(RBD_FEATURE_OBJECT_MAP)); MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 0, CEPH_NOSNAP, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockObjectMapDiffRequest, FastDiffInvalid) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); MockTestImageCtx mock_image_ctx(*m_image_ctx); mock_image_ctx.snap_info = { {1U, {"snap1", {cls::rbd::UserSnapshotNamespace{}}, {}, {}, {}, {}, {}}} }; InSequence seq; expect_get_flags(mock_image_ctx, 1U, RBD_FLAG_FAST_DIFF_INVALID, 0); C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 0, CEPH_NOSNAP, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockObjectMapDiffRequest, FullDelta) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); uint32_t object_count = 5; m_image_ctx->size = object_count * (1 << m_image_ctx->order); MockTestImageCtx mock_image_ctx(*m_image_ctx); mock_image_ctx.snap_info = { {1U, {"snap1", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}}, {2U, {"snap2", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}} }; InSequence seq; expect_get_flags(mock_image_ctx, 1U, 0, 0); BitVector<2> object_map_1; object_map_1.resize(object_count); object_map_1[1] = OBJECT_EXISTS_CLEAN; expect_load_map(mock_image_ctx, 1U, object_map_1, 0); expect_get_flags(mock_image_ctx, 2U, 0, 0); BitVector<2> object_map_2; object_map_2.resize(object_count); object_map_2[1] = OBJECT_EXISTS_CLEAN; object_map_2[2] = OBJECT_EXISTS; object_map_2[3] = OBJECT_EXISTS; expect_load_map(mock_image_ctx, 2U, object_map_2, 0); expect_get_flags(mock_image_ctx, CEPH_NOSNAP, 0, 0); BitVector<2> object_map_head; object_map_head.resize(object_count); object_map_head[1] = OBJECT_EXISTS_CLEAN; object_map_head[2] = OBJECT_EXISTS_CLEAN; expect_load_map(mock_image_ctx, CEPH_NOSNAP, object_map_head, 0); C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 0, CEPH_NOSNAP, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); BitVector<2> expected_diff_state; expected_diff_state.resize(object_count); expected_diff_state[1] = DIFF_STATE_DATA_UPDATED; expected_diff_state[2] = DIFF_STATE_DATA_UPDATED; expected_diff_state[3] = DIFF_STATE_HOLE_UPDATED; ASSERT_EQ(expected_diff_state, m_object_diff_state); } TEST_F(TestMockObjectMapDiffRequest, IntermediateDelta) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); uint32_t object_count = 5; m_image_ctx->size = object_count * (1 << m_image_ctx->order); MockTestImageCtx mock_image_ctx(*m_image_ctx); mock_image_ctx.snap_info = { {1U, {"snap1", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}}, {2U, {"snap2", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}} }; InSequence seq; expect_get_flags(mock_image_ctx, 1U, 0, 0); BitVector<2> object_map_1; object_map_1.resize(object_count); object_map_1[1] = OBJECT_EXISTS; object_map_1[2] = OBJECT_EXISTS_CLEAN; expect_load_map(mock_image_ctx, 1U, object_map_1, 0); expect_get_flags(mock_image_ctx, 2U, 0, 0); BitVector<2> object_map_2; object_map_2.resize(object_count); object_map_2[1] = OBJECT_EXISTS_CLEAN; object_map_2[2] = OBJECT_EXISTS; object_map_2[3] = OBJECT_EXISTS; expect_load_map(mock_image_ctx, 2U, object_map_2, 0); C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 1, 2, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); BitVector<2> expected_diff_state; expected_diff_state.resize(object_count); expected_diff_state[1] = DIFF_STATE_DATA; expected_diff_state[2] = DIFF_STATE_DATA_UPDATED; expected_diff_state[3] = DIFF_STATE_DATA_UPDATED; ASSERT_EQ(expected_diff_state, m_object_diff_state); } TEST_F(TestMockObjectMapDiffRequest, EndDelta) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); uint32_t object_count = 5; m_image_ctx->size = object_count * (1 << m_image_ctx->order); MockTestImageCtx mock_image_ctx(*m_image_ctx); mock_image_ctx.snap_info = { {1U, {"snap1", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}}, {2U, {"snap2", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}} }; InSequence seq; expect_get_flags(mock_image_ctx, 2U, 0, 0); BitVector<2> object_map_2; object_map_2.resize(object_count); object_map_2[1] = OBJECT_EXISTS_CLEAN; object_map_2[2] = OBJECT_EXISTS; object_map_2[3] = OBJECT_EXISTS; expect_load_map(mock_image_ctx, 2U, object_map_2, 0); expect_get_flags(mock_image_ctx, CEPH_NOSNAP, 0, 0); BitVector<2> object_map_head; object_map_head.resize(object_count); object_map_head[1] = OBJECT_EXISTS_CLEAN; object_map_head[2] = OBJECT_EXISTS_CLEAN; expect_load_map(mock_image_ctx, CEPH_NOSNAP, object_map_head, 0); C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 2, CEPH_NOSNAP, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); BitVector<2> expected_diff_state; expected_diff_state.resize(object_count); expected_diff_state[1] = DIFF_STATE_DATA; expected_diff_state[2] = DIFF_STATE_DATA; expected_diff_state[3] = DIFF_STATE_HOLE_UPDATED; ASSERT_EQ(expected_diff_state, m_object_diff_state); } TEST_F(TestMockObjectMapDiffRequest, StartSnapDNE) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); uint32_t object_count = 5; m_image_ctx->size = object_count * (1 << m_image_ctx->order); MockTestImageCtx mock_image_ctx(*m_image_ctx); mock_image_ctx.snap_info = { {2U, {"snap2", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}} }; InSequence seq; C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 1, CEPH_NOSNAP, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockObjectMapDiffRequest, EndSnapDNE) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); uint32_t object_count = 5; m_image_ctx->size = object_count * (1 << m_image_ctx->order); MockTestImageCtx mock_image_ctx(*m_image_ctx); mock_image_ctx.snap_info = { {1U, {"snap1", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}} }; InSequence seq; expect_get_flags(mock_image_ctx, 1U, 0, 0); BitVector<2> object_map_1; object_map_1.resize(object_count); expect_load_map(mock_image_ctx, 1U, object_map_1, 0); C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 1, 2, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockObjectMapDiffRequest, IntermediateSnapDNE) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); uint32_t object_count = 5; m_image_ctx->size = object_count * (1 << m_image_ctx->order); MockTestImageCtx mock_image_ctx(*m_image_ctx); mock_image_ctx.snap_info = { {1U, {"snap1", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}}, {2U, {"snap2", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}} }; InSequence seq; expect_get_flags(mock_image_ctx, 1U, 0, 0); BitVector<2> object_map_1; object_map_1.resize(object_count); object_map_1[1] = OBJECT_EXISTS_CLEAN; expect_load_map(mock_image_ctx, 1U, object_map_1, 0, [&mock_image_ctx]() { mock_image_ctx.snap_info.erase(2); }); expect_get_flags(mock_image_ctx, CEPH_NOSNAP, 0, 0); BitVector<2> object_map_head; object_map_head.resize(object_count); object_map_head[1] = OBJECT_EXISTS_CLEAN; expect_load_map(mock_image_ctx, CEPH_NOSNAP, object_map_head, 0); C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 0, CEPH_NOSNAP, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); BitVector<2> expected_diff_state; expected_diff_state.resize(object_count); expected_diff_state[1] = DIFF_STATE_DATA_UPDATED; ASSERT_EQ(expected_diff_state, m_object_diff_state); } TEST_F(TestMockObjectMapDiffRequest, LoadObjectMapDNE) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); uint32_t object_count = 5; m_image_ctx->size = object_count * (1 << m_image_ctx->order); MockTestImageCtx mock_image_ctx(*m_image_ctx); InSequence seq; expect_get_flags(mock_image_ctx, CEPH_NOSNAP, 0, 0); BitVector<2> object_map_head; expect_load_map(mock_image_ctx, CEPH_NOSNAP, object_map_head, -ENOENT); C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 0, CEPH_NOSNAP, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(-ENOENT, ctx.wait()); } TEST_F(TestMockObjectMapDiffRequest, LoadIntermediateObjectMapDNE) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); uint32_t object_count = 5; m_image_ctx->size = object_count * (1 << m_image_ctx->order); MockTestImageCtx mock_image_ctx(*m_image_ctx); mock_image_ctx.snap_info = { {1U, {"snap1", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}} }; InSequence seq; expect_get_flags(mock_image_ctx, 1U, 0, 0); BitVector<2> object_map_1; expect_load_map(mock_image_ctx, 1U, object_map_1, -ENOENT); expect_get_flags(mock_image_ctx, CEPH_NOSNAP, 0, 0); BitVector<2> object_map_head; object_map_head.resize(object_count); object_map_head[1] = OBJECT_EXISTS_CLEAN; expect_load_map(mock_image_ctx, CEPH_NOSNAP, object_map_head, 0); C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 0, CEPH_NOSNAP, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); BitVector<2> expected_diff_state; expected_diff_state.resize(object_count); expected_diff_state[1] = DIFF_STATE_DATA_UPDATED; ASSERT_EQ(expected_diff_state, m_object_diff_state); } TEST_F(TestMockObjectMapDiffRequest, LoadObjectMapError) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); uint32_t object_count = 5; m_image_ctx->size = object_count * (1 << m_image_ctx->order); MockTestImageCtx mock_image_ctx(*m_image_ctx); mock_image_ctx.snap_info = { {1U, {"snap1", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}} }; InSequence seq; expect_get_flags(mock_image_ctx, 1U, 0, 0); BitVector<2> object_map_1; expect_load_map(mock_image_ctx, 1U, object_map_1, -EPERM); C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 0, CEPH_NOSNAP, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } TEST_F(TestMockObjectMapDiffRequest, ObjectMapTooSmall) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); uint32_t object_count = 5; m_image_ctx->size = object_count * (1 << m_image_ctx->order); MockTestImageCtx mock_image_ctx(*m_image_ctx); mock_image_ctx.snap_info = { {1U, {"snap1", {cls::rbd::UserSnapshotNamespace{}}, mock_image_ctx.size, {}, {}, {}, {}}} }; InSequence seq; expect_get_flags(mock_image_ctx, 1U, 0, 0); BitVector<2> object_map_1; expect_load_map(mock_image_ctx, 1U, object_map_1, 0); C_SaferCond ctx; auto req = new MockDiffRequest(&mock_image_ctx, 0, CEPH_NOSNAP, &m_object_diff_state, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } } // namespace object_map } // librbd
15,059
29.48583
80
cc
null
ceph-main/src/test/librbd/object_map/test_mock_InvalidateRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "librbd/internal.h" #include "librbd/api/Image.h" #include "librbd/object_map/InvalidateRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace object_map { using ::testing::_; using ::testing::DoDefault; using ::testing::Return; using ::testing::StrEq; class TestMockObjectMapInvalidateRequest : public TestMockFixture { public: }; TEST_F(TestMockObjectMapInvalidateRequest, UpdatesInMemoryFlag) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); bool flags_set; ASSERT_EQ(0, ictx->test_flags(CEPH_NOSNAP, RBD_FLAG_OBJECT_MAP_INVALID, &flags_set)); ASSERT_FALSE(flags_set); C_SaferCond cond_ctx; AsyncRequest<> *request = new InvalidateRequest<>(*ictx, CEPH_NOSNAP, true, &cond_ctx); EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(ictx->header_oid, _, StrEq("rbd"), StrEq("set_flags"), _, _, _, _)) .WillOnce(DoDefault()); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx.wait()); ASSERT_EQ(0, ictx->test_flags(CEPH_NOSNAP, RBD_FLAG_OBJECT_MAP_INVALID, &flags_set)); ASSERT_TRUE(flags_set); } TEST_F(TestMockObjectMapInvalidateRequest, UpdatesHeadOnDiskFlag) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); C_SaferCond cond_ctx; AsyncRequest<> *request = new InvalidateRequest<>(*ictx, CEPH_NOSNAP, false, &cond_ctx); EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(ictx->header_oid, _, StrEq("rbd"), StrEq("set_flags"), _, _, _, _)) .WillOnce(DoDefault()); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapInvalidateRequest, UpdatesSnapOnDiskFlag) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, librbd::api::Image<>::snap_set(ictx, cls::rbd::UserSnapshotNamespace(), "snap1")); C_SaferCond cond_ctx; AsyncRequest<> *request = new InvalidateRequest<>(*ictx, ictx->snap_id, false, &cond_ctx); EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(ictx->header_oid, _, StrEq("rbd"), StrEq("set_flags"), _, _, _, _)) .WillOnce(DoDefault()); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockObjectMapInvalidateRequest, ErrorOnDiskUpdateWithoutLock) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); C_SaferCond cond_ctx; AsyncRequest<> *request = new InvalidateRequest<>(*ictx, CEPH_NOSNAP, false, &cond_ctx); EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(ictx->header_oid, _, StrEq("rbd"), StrEq("set_flags"), _, _, _, _)) .Times(0); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(-EROFS, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapInvalidateRequest, ErrorOnDiskUpdateFailure) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); C_SaferCond cond_ctx; AsyncRequest<> *request = new InvalidateRequest<>(*ictx, CEPH_NOSNAP, false, &cond_ctx); EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(ictx->header_oid, _, StrEq("rbd"), StrEq("set_flags"), _, _, _, _)) .WillOnce(Return(-EINVAL)); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } } // namespace object_map } // namespace librbd
4,766
28.981132
90
cc
null
ceph-main/src/test/librbd/object_map/test_mock_LockRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "cls/lock/cls_lock_ops.h" #include "librbd/ObjectMap.h" #include "librbd/object_map/LockRequest.h" // template definitions #include "librbd/object_map/LockRequest.cc" namespace librbd { namespace object_map { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; class TestMockObjectMapLockRequest : public TestMockFixture { public: typedef LockRequest<MockImageCtx> MockLockRequest; void expect_lock(MockImageCtx &mock_image_ctx, int r) { std::string oid(ObjectMap<>::object_map_name(mock_image_ctx.id, CEPH_NOSNAP)); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(oid, _, StrEq("lock"), StrEq("lock"), _, _, _, _)) .WillOnce(Return(r)); } void expect_get_lock_info(MockImageCtx &mock_image_ctx, int r) { std::string oid(ObjectMap<>::object_map_name(mock_image_ctx.id, CEPH_NOSNAP)); auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(oid, _, StrEq("lock"), StrEq("get_info"), _, _, _, _)); if (r < 0) { expect.WillOnce(Return(r)); } else { entity_name_t entity1(entity_name_t::CLIENT(1)); entity_name_t entity2(entity_name_t::CLIENT(2)); cls_lock_get_info_reply reply; reply.lockers = decltype(reply.lockers){ {rados::cls::lock::locker_id_t(entity1, "cookie1"), rados::cls::lock::locker_info_t()}, {rados::cls::lock::locker_id_t(entity2, "cookie2"), rados::cls::lock::locker_info_t()}}; bufferlist bl; encode(reply, bl, CEPH_FEATURES_SUPPORTED_DEFAULT); std::string str(bl.c_str(), bl.length()); expect.WillOnce(DoAll(WithArg<5>(CopyInBufferlist(str)), Return(r))); } } void expect_break_lock(MockImageCtx &mock_image_ctx, int r) { std::string oid(ObjectMap<>::object_map_name(mock_image_ctx.id, CEPH_NOSNAP)); auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(oid, _, StrEq("lock"), StrEq("break_lock"), _, _, _, _)); if (r < 0) { expect.WillOnce(Return(r)); } else { expect.Times(2).WillRepeatedly(Return(0)); } } }; TEST_F(TestMockObjectMapLockRequest, Success) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); C_SaferCond ctx; MockLockRequest *req = new MockLockRequest(mock_image_ctx, &ctx); InSequence seq; expect_lock(mock_image_ctx, 0); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapLockRequest, LockBusy) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); C_SaferCond ctx; MockLockRequest *req = new MockLockRequest(mock_image_ctx, &ctx); InSequence seq; expect_lock(mock_image_ctx, -EBUSY); expect_get_lock_info(mock_image_ctx, 0); expect_break_lock(mock_image_ctx, 0); expect_lock(mock_image_ctx, 0); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapLockRequest, LockError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); C_SaferCond ctx; MockLockRequest *req = new MockLockRequest(mock_image_ctx, &ctx); InSequence seq; expect_lock(mock_image_ctx, -ENOENT); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapLockRequest, GetLockInfoMissing) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); C_SaferCond ctx; MockLockRequest *req = new MockLockRequest(mock_image_ctx, &ctx); InSequence seq; expect_lock(mock_image_ctx, -EBUSY); expect_get_lock_info(mock_image_ctx, -ENOENT); expect_lock(mock_image_ctx, 0); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapLockRequest, GetLockInfoError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); C_SaferCond ctx; MockLockRequest *req = new MockLockRequest(mock_image_ctx, &ctx); InSequence seq; expect_lock(mock_image_ctx, -EBUSY); expect_get_lock_info(mock_image_ctx, -EINVAL); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapLockRequest, BreakLockMissing) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); C_SaferCond ctx; MockLockRequest *req = new MockLockRequest(mock_image_ctx, &ctx); InSequence seq; expect_lock(mock_image_ctx, -EBUSY); expect_get_lock_info(mock_image_ctx, 0); expect_break_lock(mock_image_ctx, -ENOENT); expect_lock(mock_image_ctx, 0); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapLockRequest, BreakLockError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); C_SaferCond ctx; MockLockRequest *req = new MockLockRequest(mock_image_ctx, &ctx); InSequence seq; expect_lock(mock_image_ctx, -EBUSY); expect_get_lock_info(mock_image_ctx, 0); expect_break_lock(mock_image_ctx, -EINVAL); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapLockRequest, LockErrorAfterBrokeLock) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); C_SaferCond ctx; MockLockRequest *req = new MockLockRequest(mock_image_ctx, &ctx); InSequence seq; expect_lock(mock_image_ctx, -EBUSY); expect_get_lock_info(mock_image_ctx, 0); expect_break_lock(mock_image_ctx, 0); expect_lock(mock_image_ctx, -EBUSY); req->send(); ASSERT_EQ(0, ctx.wait()); } } // namespace object_map } // namespace librbd
6,268
27.238739
80
cc
null
ceph-main/src/test/librbd/object_map/test_mock_RefreshRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/object_map/mock/MockInvalidateRequest.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "common/bit_vector.hpp" #include "librbd/ObjectMap.h" #include "librbd/object_map/RefreshRequest.h" #include "librbd/object_map/LockRequest.h" namespace librbd { namespace { struct MockObjectMapImageCtx : public MockImageCtx { MockObjectMapImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace object_map { template <> class LockRequest<MockObjectMapImageCtx> { public: static LockRequest *s_instance; static LockRequest *create(MockObjectMapImageCtx &image_ctx, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } Context *on_finish = nullptr; LockRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; template<> struct InvalidateRequest<MockObjectMapImageCtx> : public MockInvalidateRequestBase<MockObjectMapImageCtx> { }; LockRequest<MockObjectMapImageCtx> *LockRequest<MockObjectMapImageCtx>::s_instance = nullptr; } // namespace object_map } // namespace librbd // template definitions #include "librbd/object_map/RefreshRequest.cc" #include "librbd/object_map/LockRequest.cc" namespace librbd { namespace object_map { using ::testing::_; using ::testing::DoAll; using ::testing::DoDefault; using ::testing::InSequence; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; class TestMockObjectMapRefreshRequest : public TestMockFixture { public: static const uint64_t TEST_SNAP_ID = 123; typedef RefreshRequest<MockObjectMapImageCtx> MockRefreshRequest; typedef LockRequest<MockObjectMapImageCtx> MockLockRequest; typedef InvalidateRequest<MockObjectMapImageCtx> MockInvalidateRequest; void expect_object_map_lock(MockObjectMapImageCtx &mock_image_ctx, MockLockRequest &mock_lock_request) { EXPECT_CALL(mock_lock_request, send()) .WillOnce(FinishRequest(&mock_lock_request, 0, &mock_image_ctx)); } void expect_object_map_load(MockObjectMapImageCtx &mock_image_ctx, ceph::BitVector<2> *object_map, uint64_t snap_id, int r) { std::string oid(ObjectMap<>::object_map_name(mock_image_ctx.id, snap_id)); auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(oid, _, StrEq("rbd"), StrEq("object_map_load"), _, _, _, _)); if (r < 0) { expect.WillOnce(Return(r)); } else { ceph_assert(object_map); object_map->set_crc_enabled(false); bufferlist bl; encode(*object_map, bl); std::string str(bl.c_str(), bl.length()); expect.WillOnce(DoAll(WithArg<5>(CopyInBufferlist(str)), Return(0))); } } void expect_get_image_size(MockObjectMapImageCtx &mock_image_ctx, uint64_t snap_id, uint64_t size) { EXPECT_CALL(mock_image_ctx, get_image_size(snap_id)) .WillOnce(Return(size)); } void expect_invalidate_request(MockObjectMapImageCtx &mock_image_ctx, MockInvalidateRequest &invalidate_request, int r) { EXPECT_CALL(invalidate_request, send()) .WillOnce(FinishRequest(&invalidate_request, r, &mock_image_ctx)); } void expect_truncate_request(MockObjectMapImageCtx &mock_image_ctx) { std::string oid(ObjectMap<>::object_map_name(mock_image_ctx.id, TEST_SNAP_ID)); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), truncate(oid, 0, _)) .WillOnce(Return(0)); } void expect_object_map_resize(MockObjectMapImageCtx &mock_image_ctx, uint64_t num_objects, int r) { std::string oid(ObjectMap<>::object_map_name(mock_image_ctx.id, TEST_SNAP_ID)); auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(oid, _, StrEq("rbd"), StrEq("object_map_resize"), _, _, _, _)); expect.WillOnce(Return(r)); } void init_object_map(MockObjectMapImageCtx &mock_image_ctx, ceph::BitVector<2> *object_map) { uint64_t num_objs = Striper::get_num_objects( mock_image_ctx.layout, mock_image_ctx.image_ctx->size); object_map->resize(num_objs); for (uint64_t i = 0; i < num_objs; ++i) { (*object_map)[i] = rand() % 3; } } }; TEST_F(TestMockObjectMapRefreshRequest, SuccessHead) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockObjectMapImageCtx mock_image_ctx(*ictx); ceph::BitVector<2> on_disk_object_map; init_object_map(mock_image_ctx, &on_disk_object_map); C_SaferCond ctx; ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; MockLockRequest mock_lock_request; MockRefreshRequest *req = new MockRefreshRequest( mock_image_ctx, &object_map_lock, &object_map, CEPH_NOSNAP, &ctx); InSequence seq; expect_get_image_size(mock_image_ctx, CEPH_NOSNAP, mock_image_ctx.image_ctx->size); expect_object_map_lock(mock_image_ctx, mock_lock_request); expect_object_map_load(mock_image_ctx, &on_disk_object_map, CEPH_NOSNAP, 0); expect_get_image_size(mock_image_ctx, CEPH_NOSNAP, mock_image_ctx.image_ctx->size); req->send(); ASSERT_EQ(0, ctx.wait()); ASSERT_EQ(on_disk_object_map, object_map); } TEST_F(TestMockObjectMapRefreshRequest, SuccessSnapshot) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockObjectMapImageCtx mock_image_ctx(*ictx); ceph::BitVector<2> on_disk_object_map; init_object_map(mock_image_ctx, &on_disk_object_map); C_SaferCond ctx; ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; MockRefreshRequest *req = new MockRefreshRequest( mock_image_ctx, &object_map_lock, &object_map, TEST_SNAP_ID, &ctx); InSequence seq; expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); expect_object_map_load(mock_image_ctx, &on_disk_object_map, TEST_SNAP_ID, 0); expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); req->send(); ASSERT_EQ(0, ctx.wait()); ASSERT_EQ(on_disk_object_map, object_map); } TEST_F(TestMockObjectMapRefreshRequest, LoadError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockObjectMapImageCtx mock_image_ctx(*ictx); ceph::BitVector<2> on_disk_object_map; init_object_map(mock_image_ctx, &on_disk_object_map); C_SaferCond ctx; ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; MockRefreshRequest *req = new MockRefreshRequest( mock_image_ctx, &object_map_lock, &object_map, TEST_SNAP_ID, &ctx); InSequence seq; expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); expect_object_map_load(mock_image_ctx, nullptr, TEST_SNAP_ID, -ENOENT); MockInvalidateRequest invalidate_request; expect_invalidate_request(mock_image_ctx, invalidate_request, 0); expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapRefreshRequest, LoadInvalidateError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockObjectMapImageCtx mock_image_ctx(*ictx); ceph::BitVector<2> on_disk_object_map; init_object_map(mock_image_ctx, &on_disk_object_map); C_SaferCond ctx; ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; MockRefreshRequest *req = new MockRefreshRequest( mock_image_ctx, &object_map_lock, &object_map, TEST_SNAP_ID, &ctx); InSequence seq; expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); expect_object_map_load(mock_image_ctx, nullptr, TEST_SNAP_ID, -ENOENT); MockInvalidateRequest invalidate_request; expect_invalidate_request(mock_image_ctx, invalidate_request, -EPERM); expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } TEST_F(TestMockObjectMapRefreshRequest, LoadCorrupt) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockObjectMapImageCtx mock_image_ctx(*ictx); ceph::BitVector<2> on_disk_object_map; init_object_map(mock_image_ctx, &on_disk_object_map); C_SaferCond ctx; ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; MockRefreshRequest *req = new MockRefreshRequest( mock_image_ctx, &object_map_lock, &object_map, TEST_SNAP_ID, &ctx); InSequence seq; expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); expect_object_map_load(mock_image_ctx, nullptr, TEST_SNAP_ID, -EINVAL); MockInvalidateRequest invalidate_request; expect_invalidate_request(mock_image_ctx, invalidate_request, 0); expect_truncate_request(mock_image_ctx); expect_object_map_resize(mock_image_ctx, on_disk_object_map.size(), 0); expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapRefreshRequest, TooSmall) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockObjectMapImageCtx mock_image_ctx(*ictx); ceph::BitVector<2> on_disk_object_map; init_object_map(mock_image_ctx, &on_disk_object_map); ceph::BitVector<2> small_object_map; C_SaferCond ctx; ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; MockRefreshRequest *req = new MockRefreshRequest( mock_image_ctx, &object_map_lock, &object_map, TEST_SNAP_ID, &ctx); InSequence seq; expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); expect_object_map_load(mock_image_ctx, &small_object_map, TEST_SNAP_ID, 0); MockInvalidateRequest invalidate_request; expect_invalidate_request(mock_image_ctx, invalidate_request, 0); expect_object_map_resize(mock_image_ctx, on_disk_object_map.size(), 0); expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapRefreshRequest, TooSmallInvalidateError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockObjectMapImageCtx mock_image_ctx(*ictx); ceph::BitVector<2> on_disk_object_map; init_object_map(mock_image_ctx, &on_disk_object_map); ceph::BitVector<2> small_object_map; C_SaferCond ctx; ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; MockRefreshRequest *req = new MockRefreshRequest( mock_image_ctx, &object_map_lock, &object_map, TEST_SNAP_ID, &ctx); InSequence seq; expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); expect_object_map_load(mock_image_ctx, &small_object_map, TEST_SNAP_ID, 0); MockInvalidateRequest invalidate_request; expect_invalidate_request(mock_image_ctx, invalidate_request, -EPERM); expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } TEST_F(TestMockObjectMapRefreshRequest, TooLarge) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockObjectMapImageCtx mock_image_ctx(*ictx); ceph::BitVector<2> on_disk_object_map; init_object_map(mock_image_ctx, &on_disk_object_map); ceph::BitVector<2> large_object_map; large_object_map.resize(on_disk_object_map.size() * 2); C_SaferCond ctx; ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; MockRefreshRequest *req = new MockRefreshRequest( mock_image_ctx, &object_map_lock, &object_map, TEST_SNAP_ID, &ctx); InSequence seq; expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); expect_object_map_load(mock_image_ctx, &large_object_map, TEST_SNAP_ID, 0); expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapRefreshRequest, ResizeError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockObjectMapImageCtx mock_image_ctx(*ictx); ceph::BitVector<2> on_disk_object_map; init_object_map(mock_image_ctx, &on_disk_object_map); ceph::BitVector<2> small_object_map; C_SaferCond ctx; ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; MockRefreshRequest *req = new MockRefreshRequest( mock_image_ctx, &object_map_lock, &object_map, TEST_SNAP_ID, &ctx); InSequence seq; expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); expect_object_map_load(mock_image_ctx, &small_object_map, TEST_SNAP_ID, 0); MockInvalidateRequest invalidate_request; expect_invalidate_request(mock_image_ctx, invalidate_request, 0); expect_object_map_resize(mock_image_ctx, on_disk_object_map.size(), -ESTALE); expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, mock_image_ctx.image_ctx->size); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapRefreshRequest, LargeImageError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockObjectMapImageCtx mock_image_ctx(*ictx); ceph::BitVector<2> on_disk_object_map; init_object_map(mock_image_ctx, &on_disk_object_map); C_SaferCond ctx; ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; MockRefreshRequest *req = new MockRefreshRequest( mock_image_ctx, &object_map_lock, &object_map, TEST_SNAP_ID, &ctx); InSequence seq; expect_get_image_size(mock_image_ctx, TEST_SNAP_ID, std::numeric_limits<int64_t>::max()); MockInvalidateRequest invalidate_request; expect_invalidate_request(mock_image_ctx, invalidate_request, 0); req->send(); ASSERT_EQ(-EFBIG, ctx.wait()); } } // namespace object_map } // namespace librbd
15,673
32.635193
93
cc
null
ceph-main/src/test/librbd/object_map/test_mock_ResizeRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "common/bit_vector.hpp" #include "librbd/internal.h" #include "librbd/ObjectMap.h" #include "librbd/api/Image.h" #include "librbd/object_map/ResizeRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace object_map { using ::testing::_; using ::testing::DoDefault; using ::testing::Return; using ::testing::StrEq; class TestMockObjectMapResizeRequest : public TestMockFixture { public: void expect_resize(librbd::ImageCtx *ictx, uint64_t snap_id, int r) { std::string oid(ObjectMap<>::object_map_name(ictx->id, snap_id)); if (snap_id == CEPH_NOSNAP) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("lock"), StrEq("assert_locked"), _, _, _, _)) .WillOnce(DoDefault()); } if (r < 0) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("rbd"), StrEq("object_map_resize"), _, _, _, _)) .WillOnce(Return(r)); } else { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("rbd"), StrEq("object_map_resize"), _, _, _, _)) .WillOnce(DoDefault()); } } void expect_invalidate(librbd::ImageCtx *ictx) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(ictx->header_oid, _, StrEq("rbd"), StrEq("set_flags"), _, _, _, _)) .WillOnce(DoDefault()); } }; TEST_F(TestMockObjectMapResizeRequest, UpdateInMemory) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(1); C_SaferCond cond_ctx; AsyncRequest<> *req = new ResizeRequest( *ictx, &object_map_lock, &object_map, CEPH_NOSNAP, object_map.size(), OBJECT_EXISTS, &cond_ctx); req->send(); ASSERT_EQ(0, cond_ctx.wait()); for (uint64_t i = 0; i < object_map.size(); ++i) { ASSERT_EQ(i == 0 ? OBJECT_NONEXISTENT : OBJECT_EXISTS, object_map[i]); } } TEST_F(TestMockObjectMapResizeRequest, UpdateHeadOnDisk) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); expect_resize(ictx, CEPH_NOSNAP, 0); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(1); C_SaferCond cond_ctx; AsyncRequest<> *req = new ResizeRequest( *ictx, &object_map_lock, &object_map, CEPH_NOSNAP, object_map.size(), OBJECT_EXISTS, &cond_ctx); req->send(); ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapResizeRequest, UpdateSnapOnDisk) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, librbd::api::Image<>::snap_set(ictx, cls::rbd::UserSnapshotNamespace(), "snap1")); uint64_t snap_id = ictx->snap_id; expect_resize(ictx, snap_id, 0); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(1); C_SaferCond cond_ctx; AsyncRequest<> *req = new ResizeRequest( *ictx, &object_map_lock, &object_map, snap_id, object_map.size(), OBJECT_EXISTS, &cond_ctx); req->send(); ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapResizeRequest, UpdateOnDiskError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); expect_resize(ictx, CEPH_NOSNAP, -EINVAL); expect_invalidate(ictx); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(1); C_SaferCond cond_ctx; AsyncRequest<> *req = new ResizeRequest( *ictx, &object_map_lock, &object_map, CEPH_NOSNAP, object_map.size(), OBJECT_EXISTS, &cond_ctx); req->send(); ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } } // namespace object_map } // namespace librbd
4,695
29.296774
78
cc
null
ceph-main/src/test/librbd/object_map/test_mock_SnapshotCreateRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "common/bit_vector.hpp" #include "cls/rbd/cls_rbd_types.h" #include "librbd/internal.h" #include "librbd/ObjectMap.h" #include "librbd/object_map/SnapshotCreateRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace object_map { using ::testing::_; using ::testing::DoDefault; using ::testing::Return; using ::testing::StrEq; class TestMockObjectMapSnapshotCreateRequest : public TestMockFixture { public: void inject_snap_info(librbd::ImageCtx *ictx, uint64_t snap_id) { std::unique_lock image_locker{ictx->image_lock}; ictx->add_snap(cls::rbd::UserSnapshotNamespace(), "snap name", snap_id, ictx->size, ictx->parent_md, RBD_PROTECTION_STATUS_UNPROTECTED, 0, utime_t()); } void expect_read_map(librbd::ImageCtx *ictx, int r) { if (r < 0) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), read(ObjectMap<>::object_map_name(ictx->id, CEPH_NOSNAP), 0, 0, _, _, _)).WillOnce(Return(r)); } else { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), read(ObjectMap<>::object_map_name(ictx->id, CEPH_NOSNAP), 0, 0, _, _, _)).WillOnce(DoDefault()); } } void expect_write_map(librbd::ImageCtx *ictx, uint64_t snap_id, int r) { if (r < 0) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), write_full( ObjectMap<>::object_map_name(ictx->id, snap_id), _, _)) .WillOnce(Return(r)); } else { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), write_full( ObjectMap<>::object_map_name(ictx->id, snap_id), _, _)) .WillOnce(DoDefault()); } } void expect_add_snapshot(librbd::ImageCtx *ictx, int r) { std::string oid(ObjectMap<>::object_map_name(ictx->id, CEPH_NOSNAP)); if (r < 0) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("lock"), StrEq("assert_locked"), _, _, _, _)) .WillOnce(Return(r)); } else { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("lock"), StrEq("assert_locked"), _, _, _, _)) .WillOnce(DoDefault()); EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("rbd"), StrEq("object_map_snap_add"), _, _, _, _)) .WillOnce(DoDefault()); } } void expect_invalidate(librbd::ImageCtx *ictx) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(ictx->header_oid, _, StrEq("rbd"), StrEq("set_flags"), _, _, _, _)) .WillOnce(DoDefault()); } }; TEST_F(TestMockObjectMapSnapshotCreateRequest, Success) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; uint64_t snap_id = 1; inject_snap_info(ictx, snap_id); expect_read_map(ictx, 0); expect_write_map(ictx, snap_id, 0); if (ictx->test_features(RBD_FEATURE_FAST_DIFF)) { expect_add_snapshot(ictx, 0); } C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotCreateRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotCreateRequest, ReadMapError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; uint64_t snap_id = 1; inject_snap_info(ictx, snap_id); expect_read_map(ictx, -ENOENT); expect_invalidate(ictx); C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotCreateRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(-ENOENT, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotCreateRequest, WriteMapError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; uint64_t snap_id = 1; inject_snap_info(ictx, snap_id); expect_read_map(ictx, 0); expect_write_map(ictx, snap_id, -EINVAL); expect_invalidate(ictx); C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotCreateRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(-ENOENT, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotCreateRequest, AddSnapshotError) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; uint64_t snap_id = 1; inject_snap_info(ictx, snap_id); expect_read_map(ictx, 0); expect_write_map(ictx, snap_id, 0); expect_add_snapshot(ictx, -EINVAL); expect_invalidate(ictx); C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotCreateRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(-ENOENT, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotCreateRequest, FlagCleanObjects) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(1024); for (uint64_t i = 0; i < object_map.size(); ++i) { object_map[i] = i % 2 == 0 ? OBJECT_EXISTS : OBJECT_NONEXISTENT; } uint64_t snap_id = 1; inject_snap_info(ictx, snap_id); C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotCreateRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx.wait()); for (uint64_t i = 0; i < object_map.size(); ++i) { ASSERT_EQ(i % 2 == 0 ? OBJECT_EXISTS_CLEAN : OBJECT_NONEXISTENT, object_map[i]); } } } // namespace object_map } // namespace librbd
7,270
30.206009
80
cc
null
ceph-main/src/test/librbd/object_map/test_mock_SnapshotRemoveRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "common/bit_vector.hpp" #include "librbd/ImageState.h" #include "librbd/internal.h" #include "librbd/ObjectMap.h" #include "librbd/object_map/SnapshotRemoveRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace object_map { using ::testing::_; using ::testing::DoDefault; using ::testing::Return; using ::testing::StrEq; class TestMockObjectMapSnapshotRemoveRequest : public TestMockFixture { public: void expect_load_map(librbd::ImageCtx *ictx, uint64_t snap_id, int r) { std::string snap_oid(ObjectMap<>::object_map_name(ictx->id, snap_id)); if (r < 0) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(snap_oid, _, StrEq("rbd"), StrEq("object_map_load"), _, _, _, _)) .WillOnce(Return(r)); } else { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(snap_oid, _, StrEq("rbd"), StrEq("object_map_load"), _, _, _, _)) .WillOnce(DoDefault()); } } void expect_remove_snapshot(librbd::ImageCtx *ictx, int r) { std::string oid(ObjectMap<>::object_map_name(ictx->id, CEPH_NOSNAP)); if (r < 0) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("lock"), StrEq("assert_locked"), _, _, _, _)) .WillOnce(Return(r)); } else { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("lock"), StrEq("assert_locked"), _, _, _, _)) .WillOnce(DoDefault()); EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("rbd"), StrEq("object_map_snap_remove"), _, _, _, _)) .WillOnce(DoDefault()); } } void expect_remove_map(librbd::ImageCtx *ictx, uint64_t snap_id, int r) { std::string snap_oid(ObjectMap<>::object_map_name(ictx->id, snap_id)); if (r < 0) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), remove(snap_oid, _)) .WillOnce(Return(r)); } else { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), remove(snap_oid, _)) .WillOnce(DoDefault()); } } void expect_invalidate(librbd::ImageCtx *ictx) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(ictx->header_oid, _, StrEq("rbd"), StrEq("set_flags"), _, _, _, _)) .WillOnce(DoDefault()); } }; TEST_F(TestMockObjectMapSnapshotRemoveRequest, Success) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); uint64_t snap_id = ictx->snap_info.rbegin()->first; if (ictx->test_features(RBD_FEATURE_FAST_DIFF)) { expect_load_map(ictx, snap_id, 0); expect_remove_snapshot(ictx, 0); } expect_remove_map(ictx, snap_id, 0); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotRemoveRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotRemoveRequest, LoadMapMissing) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); uint64_t snap_id = ictx->snap_info.rbegin()->first; auto snap_it = ictx->snap_info.find(snap_id); ASSERT_NE(ictx->snap_info.end(), snap_it); snap_it->second.flags |= RBD_FLAG_OBJECT_MAP_INVALID; expect_load_map(ictx, snap_id, -ENOENT); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotRemoveRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx.wait()); { // shouldn't invalidate the HEAD revision when we fail to load // the already deleted snapshot std::shared_lock image_locker{ictx->image_lock}; uint64_t flags; ASSERT_EQ(0, ictx->get_flags(CEPH_NOSNAP, &flags)); ASSERT_EQ(0U, flags & RBD_FLAG_OBJECT_MAP_INVALID); } expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotRemoveRequest, LoadMapError) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_load_map(ictx, snap_id, -EINVAL); expect_invalidate(ictx); expect_remove_map(ictx, snap_id, 0); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotRemoveRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotRemoveRequest, RemoveSnapshotMissing) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_load_map(ictx, snap_id, 0); expect_remove_snapshot(ictx, -ENOENT); expect_remove_map(ictx, snap_id, 0); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotRemoveRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotRemoveRequest, RemoveSnapshotError) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_load_map(ictx, snap_id, 0); expect_remove_snapshot(ictx, -EINVAL); expect_invalidate(ictx); expect_remove_map(ictx, snap_id, 0); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotRemoveRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotRemoveRequest, RemoveMapMissing) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); uint64_t snap_id = ictx->snap_info.rbegin()->first; if (ictx->test_features(RBD_FEATURE_FAST_DIFF)) { expect_load_map(ictx, snap_id, 0); expect_remove_snapshot(ictx, 0); } expect_remove_map(ictx, snap_id, -ENOENT); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotRemoveRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotRemoveRequest, RemoveMapError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); uint64_t snap_id = ictx->snap_info.rbegin()->first; if (ictx->test_features(RBD_FEATURE_FAST_DIFF)) { expect_load_map(ictx, snap_id, 0); expect_remove_snapshot(ictx, 0); } expect_remove_map(ictx, snap_id, -EINVAL); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotRemoveRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotRemoveRequest, ScrubCleanObjects) { REQUIRE_FEATURE(RBD_FEATURE_FAST_DIFF); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); librbd::NoOpProgressContext prog_ctx; uint64_t size = 4294967296; // 4GB = 1024 * 4MB ASSERT_EQ(0, resize(ictx, size)); // update image objectmap for snap inherit ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(1024); for (uint64_t i = 512; i < object_map.size(); ++i) { object_map[i] = i % 2 == 0 ? OBJECT_EXISTS : OBJECT_NONEXISTENT; } C_SaferCond cond_ctx1; { librbd::ObjectMap<> *om = new librbd::ObjectMap<>(*ictx, ictx->snap_id); std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; om->set_object_map(object_map); om->aio_save(&cond_ctx1); om->put(); } ASSERT_EQ(0, cond_ctx1.wait()); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); // simutate the image objectmap state after creating snap for (uint64_t i = 512; i < object_map.size(); ++i) { object_map[i] = i % 2 == 0 ? OBJECT_EXISTS_CLEAN : OBJECT_NONEXISTENT; } C_SaferCond cond_ctx2; uint64_t snap_id = ictx->snap_info.rbegin()->first; AsyncRequest<> *request = new SnapshotRemoveRequest( *ictx, &object_map_lock, &object_map, snap_id, &cond_ctx2); { std::shared_lock owner_locker{ictx->owner_lock}; std::unique_lock image_locker{ictx->image_lock}; request->send(); } ASSERT_EQ(0, cond_ctx2.wait()); for (uint64_t i = 512; i < object_map.size(); ++i) { ASSERT_EQ(i % 2 == 0 ? OBJECT_EXISTS : OBJECT_NONEXISTENT, object_map[i]); } } } // namespace object_map } // namespace librbd
11,512
32.274566
80
cc
null
ceph-main/src/test/librbd/object_map/test_mock_SnapshotRollbackRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "librbd/ImageState.h" #include "librbd/internal.h" #include "librbd/ObjectMap.h" #include "librbd/object_map/SnapshotRollbackRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace object_map { using ::testing::_; using ::testing::DoDefault; using ::testing::Return; using ::testing::StrEq; class TestMockObjectMapSnapshotRollbackRequest : public TestMockFixture { public: void expect_read_map(librbd::ImageCtx *ictx, uint64_t snap_id, int r) { if (r < 0) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), read(ObjectMap<>::object_map_name(ictx->id, snap_id), 0, 0, _, _, _)).WillOnce(Return(r)); } else { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), read(ObjectMap<>::object_map_name(ictx->id, snap_id), 0, 0, _, _, _)).WillOnce(DoDefault()); } } void expect_write_map(librbd::ImageCtx *ictx, int r) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(ObjectMap<>::object_map_name(ictx->id, CEPH_NOSNAP), _, StrEq("lock"), StrEq("assert_locked"), _, _, _, _)) .WillOnce(DoDefault()); if (r < 0) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), write_full( ObjectMap<>::object_map_name(ictx->id, CEPH_NOSNAP), _, _)) .WillOnce(Return(r)); } else { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), write_full( ObjectMap<>::object_map_name(ictx->id, CEPH_NOSNAP), _, _)) .WillOnce(DoDefault()); } } void expect_invalidate(librbd::ImageCtx *ictx, uint32_t times) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(ictx->header_oid, _, StrEq("rbd"), StrEq("set_flags"), _, _, _, _)) .Times(times) .WillRepeatedly(DoDefault()); } }; TEST_F(TestMockObjectMapSnapshotRollbackRequest, Success) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_read_map(ictx, snap_id, 0); expect_write_map(ictx, 0); C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotRollbackRequest( *ictx, snap_id, &cond_ctx); request->send(); ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotRollbackRequest, ReadMapError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_read_map(ictx, snap_id, -ENOENT); expect_invalidate(ictx, 2); C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotRollbackRequest( *ictx, snap_id, &cond_ctx); request->send(); ASSERT_EQ(0, cond_ctx.wait()); { std::shared_lock image_locker{ictx->image_lock}; uint64_t flags; ASSERT_EQ(0, ictx->get_flags(snap_id, &flags)); ASSERT_NE(0U, flags & RBD_FLAG_OBJECT_MAP_INVALID); } bool flags_set; ASSERT_EQ(0, ictx->test_flags(CEPH_NOSNAP, RBD_FLAG_OBJECT_MAP_INVALID, &flags_set)); ASSERT_TRUE(flags_set); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapSnapshotRollbackRequest, WriteMapError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_read_map(ictx, snap_id, 0); expect_write_map(ictx, -EINVAL); expect_invalidate(ictx, 1); C_SaferCond cond_ctx; AsyncRequest<> *request = new SnapshotRollbackRequest( *ictx, snap_id, &cond_ctx); request->send(); ASSERT_EQ(0, cond_ctx.wait()); { std::shared_lock image_locker{ictx->image_lock}; uint64_t flags; ASSERT_EQ(0, ictx->get_flags(snap_id, &flags)); ASSERT_EQ(0U, flags & RBD_FLAG_OBJECT_MAP_INVALID); } bool flags_set; ASSERT_EQ(0, ictx->test_flags(CEPH_NOSNAP, RBD_FLAG_OBJECT_MAP_INVALID, &flags_set)); ASSERT_TRUE(flags_set); expect_unlock_exclusive_lock(*ictx); } } // namespace object_map } // namespace librbd
4,797
31.201342
79
cc
null
ceph-main/src/test/librbd/object_map/test_mock_UnlockRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "cls/lock/cls_lock_ops.h" #include "librbd/ObjectMap.h" #include "librbd/object_map/UnlockRequest.h" // template definitions #include "librbd/object_map/UnlockRequest.cc" namespace librbd { namespace object_map { using ::testing::_; using ::testing::InSequence; using ::testing::Return; using ::testing::StrEq; class TestMockObjectMapUnlockRequest : public TestMockFixture { public: typedef UnlockRequest<MockImageCtx> MockUnlockRequest; void expect_unlock(MockImageCtx &mock_image_ctx, int r) { std::string oid(ObjectMap<>::object_map_name(mock_image_ctx.id, CEPH_NOSNAP)); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(oid, _, StrEq("lock"), StrEq("unlock"), _, _, _, _)) .WillOnce(Return(r)); } }; TEST_F(TestMockObjectMapUnlockRequest, Success) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); C_SaferCond ctx; MockUnlockRequest *req = new MockUnlockRequest(mock_image_ctx, &ctx); InSequence seq; expect_unlock(mock_image_ctx, 0); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockObjectMapUnlockRequest, UnlockError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); C_SaferCond ctx; MockUnlockRequest *req = new MockUnlockRequest(mock_image_ctx, &ctx); InSequence seq; expect_unlock(mock_image_ctx, -ENOENT); req->send(); ASSERT_EQ(0, ctx.wait()); } } // namespace object_map } // namespace librbd
1,879
25.857143
73
cc
null
ceph-main/src/test/librbd/object_map/test_mock_UpdateRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "common/bit_vector.hpp" #include "librbd/ImageState.h" #include "librbd/internal.h" #include "librbd/ObjectMap.h" #include "librbd/Operations.h" #include "librbd/api/Image.h" #include "librbd/object_map/UpdateRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace object_map { using ::testing::_; using ::testing::DoDefault; using ::testing::InSequence; using ::testing::Return; using ::testing::StrEq; class TestMockObjectMapUpdateRequest : public TestMockFixture { public: void expect_update(librbd::ImageCtx *ictx, uint64_t snap_id, uint64_t start_object_no, uint64_t end_object_no, uint8_t new_state, const boost::optional<uint8_t>& current_state, int r) { bufferlist bl; encode(start_object_no, bl); encode(end_object_no, bl); encode(new_state, bl); encode(current_state, bl); std::string oid(ObjectMap<>::object_map_name(ictx->id, snap_id)); if (snap_id == CEPH_NOSNAP) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("lock"), StrEq("assert_locked"), _, _, _, _)) .WillOnce(DoDefault()); } if (r < 0) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("rbd"), StrEq("object_map_update"), ContentsEqual(bl), _, _, _)) .WillOnce(Return(r)); } else { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(oid, _, StrEq("rbd"), StrEq("object_map_update"), ContentsEqual(bl), _, _, _)) .WillOnce(DoDefault()); } } void expect_invalidate(librbd::ImageCtx *ictx) { EXPECT_CALL(get_mock_io_ctx(ictx->md_ctx), exec(ictx->header_oid, _, StrEq("rbd"), StrEq("set_flags"), _, _, _, _)) .WillOnce(DoDefault()); } }; TEST_F(TestMockObjectMapUpdateRequest, UpdateInMemory) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); librbd::NoOpProgressContext no_progress; ASSERT_EQ(0, ictx->operations->resize(4 << ictx->order, true, no_progress)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(4); for (uint64_t i = 0; i < object_map.size(); ++i) { object_map[i] = i % 4; } C_SaferCond cond_ctx; AsyncRequest<> *req = new UpdateRequest<>( *ictx, &object_map_lock, &object_map, CEPH_NOSNAP, 0, object_map.size(), OBJECT_NONEXISTENT, OBJECT_EXISTS, {}, false, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; std::unique_lock object_map_locker{object_map_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); for (uint64_t i = 0; i < object_map.size(); ++i) { if (i % 4 == OBJECT_EXISTS || i % 4 == OBJECT_EXISTS_CLEAN) { ASSERT_EQ(OBJECT_NONEXISTENT, object_map[i]); } else { ASSERT_EQ(i % 4, object_map[i]); } } } TEST_F(TestMockObjectMapUpdateRequest, UpdateHeadOnDisk) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); expect_update(ictx, CEPH_NOSNAP, 0, 1, OBJECT_NONEXISTENT, OBJECT_EXISTS, 0); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(1); C_SaferCond cond_ctx; AsyncRequest<> *req = new UpdateRequest<>( *ictx, &object_map_lock, &object_map, CEPH_NOSNAP, 0, object_map.size(), OBJECT_NONEXISTENT, OBJECT_EXISTS, {}, false, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; std::unique_lock object_map_locker{object_map_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapUpdateRequest, UpdateSnapOnDisk) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, librbd::api::Image<>::snap_set(ictx, cls::rbd::UserSnapshotNamespace(), "snap1")); uint64_t snap_id = ictx->snap_id; expect_update(ictx, snap_id, 0, 1, OBJECT_NONEXISTENT, OBJECT_EXISTS, 0); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(1); C_SaferCond cond_ctx; AsyncRequest<> *req = new UpdateRequest<>( *ictx, &object_map_lock, &object_map, snap_id, 0, object_map.size(), OBJECT_NONEXISTENT, OBJECT_EXISTS, {}, false, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; std::unique_lock object_map_locker{object_map_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapUpdateRequest, UpdateOnDiskError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); expect_update(ictx, CEPH_NOSNAP, 0, 1, OBJECT_NONEXISTENT, OBJECT_EXISTS, -EINVAL); expect_invalidate(ictx); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(1); C_SaferCond cond_ctx; AsyncRequest<> *req = new UpdateRequest<>( *ictx, &object_map_lock, &object_map, CEPH_NOSNAP, 0, object_map.size(), OBJECT_NONEXISTENT, OBJECT_EXISTS, {}, false, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; std::unique_lock object_map_locker{object_map_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } TEST_F(TestMockObjectMapUpdateRequest, RebuildSnapOnDisk) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); ASSERT_EQ(CEPH_NOSNAP, ictx->snap_id); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_update(ictx, snap_id, 0, 1, OBJECT_EXISTS_CLEAN, boost::optional<uint8_t>(), 0); expect_unlock_exclusive_lock(*ictx); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(1); C_SaferCond cond_ctx; AsyncRequest<> *req = new UpdateRequest<>( *ictx, &object_map_lock, &object_map, snap_id, 0, object_map.size(), OBJECT_EXISTS_CLEAN, boost::optional<uint8_t>(), {}, false, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; std::unique_lock object_map_locker{object_map_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); // do not update the in-memory map if rebuilding a snapshot ASSERT_NE(OBJECT_EXISTS_CLEAN, object_map[0]); } TEST_F(TestMockObjectMapUpdateRequest, BatchUpdate) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); librbd::NoOpProgressContext no_progress; ASSERT_EQ(0, ictx->operations->resize(712312 * ictx->get_object_size(), false, no_progress)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); expect_unlock_exclusive_lock(*ictx); InSequence seq; expect_update(ictx, CEPH_NOSNAP, 0, 262144, OBJECT_NONEXISTENT, OBJECT_EXISTS, 0); expect_update(ictx, CEPH_NOSNAP, 262144, 524288, OBJECT_NONEXISTENT, OBJECT_EXISTS, 0); expect_update(ictx, CEPH_NOSNAP, 524288, 712312, OBJECT_NONEXISTENT, OBJECT_EXISTS, 0); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(712312); C_SaferCond cond_ctx; AsyncRequest<> *req = new UpdateRequest<>( *ictx, &object_map_lock, &object_map, CEPH_NOSNAP, 0, object_map.size(), OBJECT_NONEXISTENT, OBJECT_EXISTS, {}, false, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; std::unique_lock object_map_locker{object_map_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockObjectMapUpdateRequest, IgnoreMissingObjectMap) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, acquire_exclusive_lock(*ictx)); expect_update(ictx, CEPH_NOSNAP, 0, 1, OBJECT_NONEXISTENT, OBJECT_EXISTS, -ENOENT); ceph::shared_mutex object_map_lock = ceph::make_shared_mutex("lock"); ceph::BitVector<2> object_map; object_map.resize(1); C_SaferCond cond_ctx; AsyncRequest<> *req = new UpdateRequest<>( *ictx, &object_map_lock, &object_map, CEPH_NOSNAP, 0, object_map.size(), OBJECT_NONEXISTENT, OBJECT_EXISTS, {}, true, &cond_ctx); { std::shared_lock image_locker{ictx->image_lock}; std::unique_lock object_map_locker{object_map_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); expect_unlock_exclusive_lock(*ictx); } } // namespace object_map } // namespace librbd
9,522
31.613014
80
cc
null
ceph-main/src/test/librbd/object_map/mock/MockInvalidateRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "librbd/object_map/InvalidateRequest.h" // template definitions #include "librbd/object_map/InvalidateRequest.cc" namespace librbd { namespace object_map { template <typename I> struct MockInvalidateRequestBase { static std::list<InvalidateRequest<I>*> s_requests; uint64_t snap_id = 0; bool force = false; Context *on_finish = nullptr; static InvalidateRequest<I>* create(I &image_ctx, uint64_t snap_id, bool force, Context *on_finish) { ceph_assert(!s_requests.empty()); InvalidateRequest<I>* req = s_requests.front(); req->snap_id = snap_id; req->force = force; req->on_finish = on_finish; s_requests.pop_front(); return req; } MockInvalidateRequestBase() { s_requests.push_back(static_cast<InvalidateRequest<I>*>(this)); } MOCK_METHOD0(send, void()); }; template <typename I> std::list<InvalidateRequest<I>*> MockInvalidateRequestBase<I>::s_requests; } // namespace object_map } // namespace librbd
1,107
25.380952
74
h
null
ceph-main/src/test/librbd/operation/test_mock_DisableFeaturesRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/MockJournalPolicy.h" #include "cls/rbd/cls_rbd_client.h" #include "librbd/internal.h" #include "librbd/Journal.h" #include "librbd/image/SetFlagsRequest.h" #include "librbd/io/AioCompletion.h" #include "librbd/mirror/DisableRequest.h" #include "librbd/journal/RemoveRequest.h" #include "librbd/journal/StandardPolicy.h" #include "librbd/journal/Types.h" #include "librbd/journal/TypeTraits.h" #include "librbd/object_map/RemoveRequest.h" #include "librbd/operation/DisableFeaturesRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace { struct MockOperationImageCtx : public MockImageCtx { MockOperationImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace template<> struct Journal<MockOperationImageCtx> { static void get_work_queue(CephContext*, MockContextWQ**) { } }; namespace image { template<> class SetFlagsRequest<MockOperationImageCtx> { public: static SetFlagsRequest *s_instance; Context *on_finish = nullptr; static SetFlagsRequest *create(MockOperationImageCtx *image_ctx, uint64_t flags, uint64_t mask, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } SetFlagsRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; SetFlagsRequest<MockOperationImageCtx> *SetFlagsRequest<MockOperationImageCtx>::s_instance; } // namespace image namespace journal { template<> class RemoveRequest<MockOperationImageCtx> { public: static RemoveRequest *s_instance; Context *on_finish = nullptr; static RemoveRequest *create(IoCtx &ioctx, const std::string &imageid, const std::string &client_id, MockContextWQ *op_work_queue, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } RemoveRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; RemoveRequest<MockOperationImageCtx> *RemoveRequest<MockOperationImageCtx>::s_instance; template<> class StandardPolicy<MockOperationImageCtx> : public MockJournalPolicy { public: StandardPolicy(MockOperationImageCtx* image_ctx) { } }; template <> struct TypeTraits<MockOperationImageCtx> { typedef librbd::MockContextWQ ContextWQ; }; } // namespace journal namespace mirror { template<> class DisableRequest<MockOperationImageCtx> { public: static DisableRequest *s_instance; Context *on_finish = nullptr; static DisableRequest *create(MockOperationImageCtx *image_ctx, bool force, bool remove, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } DisableRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; DisableRequest<MockOperationImageCtx> *DisableRequest<MockOperationImageCtx>::s_instance; } // namespace mirror namespace object_map { template<> class RemoveRequest<MockOperationImageCtx> { public: static RemoveRequest *s_instance; Context *on_finish = nullptr; static RemoveRequest *create(MockOperationImageCtx *image_ctx, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } RemoveRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; RemoveRequest<MockOperationImageCtx> *RemoveRequest<MockOperationImageCtx>::s_instance; } // namespace object_map template <> struct AsyncRequest<MockOperationImageCtx> : public AsyncRequest<MockImageCtx> { MockOperationImageCtx &m_image_ctx; AsyncRequest(MockOperationImageCtx &image_ctx, Context *on_finish) : AsyncRequest<MockImageCtx>(image_ctx, on_finish), m_image_ctx(image_ctx) { } }; } // namespace librbd // template definitions #include "librbd/AsyncRequest.cc" #include "librbd/AsyncObjectThrottle.cc" #include "librbd/operation/Request.cc" #include "librbd/operation/DisableFeaturesRequest.cc" namespace librbd { namespace operation { using ::testing::Invoke; using ::testing::Return; using ::testing::WithArg; using ::testing::_; class TestMockOperationDisableFeaturesRequest : public TestMockFixture { public: typedef librbd::image::SetFlagsRequest<MockOperationImageCtx> MockSetFlagsRequest; typedef librbd::journal::RemoveRequest<MockOperationImageCtx> MockRemoveJournalRequest; typedef librbd::mirror::DisableRequest<MockOperationImageCtx> MockDisableMirrorRequest; typedef librbd::object_map::RemoveRequest<MockOperationImageCtx> MockRemoveObjectMapRequest; typedef DisableFeaturesRequest<MockOperationImageCtx> MockDisableFeaturesRequest; class MirrorModeEnabler { public: MirrorModeEnabler(librados::IoCtx &ioctx, cls::rbd::MirrorMode mirror_mode) : m_ioctx(ioctx), m_mirror_mode(mirror_mode) { EXPECT_EQ(0, librbd::cls_client::mirror_uuid_set(&m_ioctx, "test-uuid")); EXPECT_EQ(0, librbd::cls_client::mirror_mode_set(&m_ioctx, m_mirror_mode)); } ~MirrorModeEnabler() { EXPECT_EQ(0, librbd::cls_client::mirror_mode_set( &m_ioctx, cls::rbd::MIRROR_MODE_DISABLED)); } private: librados::IoCtx &m_ioctx; cls::rbd::MirrorMode m_mirror_mode; }; void expect_prepare_lock(MockOperationImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.state, prepare_lock(_)) .WillOnce(Invoke([](Context *on_ready) { on_ready->complete(0); })); expect_op_work_queue(mock_image_ctx); } void expect_handle_prepare_lock_complete(MockOperationImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.state, handle_prepare_lock_complete()); } void expect_block_writes(MockOperationImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, block_writes(_)) .WillOnce(CompleteContext(0, mock_image_ctx.image_ctx->op_work_queue)); } void expect_unblock_writes(MockOperationImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, unblock_writes()).Times(1); } void expect_verify_lock_ownership(MockOperationImageCtx &mock_image_ctx) { if (mock_image_ctx.exclusive_lock != nullptr) { EXPECT_CALL(*mock_image_ctx.exclusive_lock, is_lock_owner()) .WillRepeatedly(Return(true)); } } void expect_block_requests(MockOperationImageCtx &mock_image_ctx) { if (mock_image_ctx.exclusive_lock != nullptr) { EXPECT_CALL(*mock_image_ctx.exclusive_lock, block_requests(0)).Times(1); } } void expect_unblock_requests(MockOperationImageCtx &mock_image_ctx) { if (mock_image_ctx.exclusive_lock != nullptr) { EXPECT_CALL(*mock_image_ctx.exclusive_lock, unblock_requests()).Times(1); } } void expect_set_flags_request_send( MockOperationImageCtx &mock_image_ctx, MockSetFlagsRequest &mock_set_flags_request, int r) { EXPECT_CALL(mock_set_flags_request, send()) .WillOnce(FinishRequest(&mock_set_flags_request, r, &mock_image_ctx)); } void expect_disable_mirror_request_send( MockOperationImageCtx &mock_image_ctx, MockDisableMirrorRequest &mock_disable_mirror_request, int r) { EXPECT_CALL(mock_disable_mirror_request, send()) .WillOnce(FinishRequest(&mock_disable_mirror_request, r, &mock_image_ctx)); } void expect_close_journal(MockOperationImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.journal, close(_)) .WillOnce(Invoke([&mock_image_ctx, r](Context *on_finish) { mock_image_ctx.journal = nullptr; mock_image_ctx.image_ctx->op_work_queue->queue(on_finish, r); })); } void expect_remove_journal_request_send( MockOperationImageCtx &mock_image_ctx, MockRemoveJournalRequest &mock_remove_journal_request, int r) { EXPECT_CALL(mock_remove_journal_request, send()) .WillOnce(FinishRequest(&mock_remove_journal_request, r, &mock_image_ctx)); } void expect_remove_object_map_request_send( MockOperationImageCtx &mock_image_ctx, MockRemoveObjectMapRequest &mock_remove_object_map_request, int r) { EXPECT_CALL(mock_remove_object_map_request, send()) .WillOnce(FinishRequest(&mock_remove_object_map_request, r, &mock_image_ctx)); } void expect_notify_update(MockOperationImageCtx &mock_image_ctx) { EXPECT_CALL(mock_image_ctx, notify_update(_)) .WillOnce(CompleteContext(0, mock_image_ctx.image_ctx->op_work_queue)); } }; TEST_F(TestMockOperationDisableFeaturesRequest, All) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); uint64_t features; ASSERT_EQ(0, librbd::get_features(ictx, &features)); uint64_t features_to_disable = RBD_FEATURES_MUTABLE & features; REQUIRE(features_to_disable); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_verify_lock_ownership(mock_image_ctx); MockSetFlagsRequest mock_set_flags_request; MockRemoveJournalRequest mock_remove_journal_request; MockDisableMirrorRequest mock_disable_mirror_request; MockRemoveObjectMapRequest mock_remove_object_map_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); if (mock_image_ctx.journal != nullptr) { expect_is_journal_replaying(*mock_image_ctx.journal); } expect_block_requests(mock_image_ctx); if (features_to_disable & RBD_FEATURE_JOURNALING) { expect_disable_mirror_request_send(mock_image_ctx, mock_disable_mirror_request, 0); expect_close_journal(mock_image_ctx, 0); expect_remove_journal_request_send(mock_image_ctx, mock_remove_journal_request, 0); } if (features_to_disable & RBD_FEATURE_OBJECT_MAP) { expect_remove_object_map_request_send(mock_image_ctx, mock_remove_object_map_request, 0); } if (features_to_disable & (RBD_FEATURE_OBJECT_MAP | RBD_FEATURE_FAST_DIFF)) { expect_set_flags_request_send(mock_image_ctx, mock_set_flags_request, 0); } expect_notify_update(mock_image_ctx); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); C_SaferCond cond_ctx; MockDisableFeaturesRequest *req = new MockDisableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, features_to_disable, false); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationDisableFeaturesRequest, ObjectMap) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_verify_lock_ownership(mock_image_ctx); MockSetFlagsRequest mock_set_flags_request; MockRemoveObjectMapRequest mock_remove_object_map_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); if (mock_image_ctx.journal != nullptr) { expect_is_journal_replaying(*mock_image_ctx.journal); } expect_block_requests(mock_image_ctx); expect_append_op_event(mock_image_ctx, true, 0); expect_remove_object_map_request_send(mock_image_ctx, mock_remove_object_map_request, 0); expect_set_flags_request_send(mock_image_ctx, mock_set_flags_request, 0); expect_notify_update(mock_image_ctx); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); expect_commit_op_event(mock_image_ctx, 0); C_SaferCond cond_ctx; MockDisableFeaturesRequest *req = new MockDisableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, RBD_FEATURE_OBJECT_MAP | RBD_FEATURE_FAST_DIFF, false); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationDisableFeaturesRequest, ObjectMapError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_verify_lock_ownership(mock_image_ctx); MockSetFlagsRequest mock_set_flags_request; MockRemoveObjectMapRequest mock_remove_object_map_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); if (mock_image_ctx.journal != nullptr) { expect_is_journal_replaying(*mock_image_ctx.journal); } expect_block_requests(mock_image_ctx); expect_append_op_event(mock_image_ctx, true, 0); expect_remove_object_map_request_send(mock_image_ctx, mock_remove_object_map_request, -EINVAL); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); expect_commit_op_event(mock_image_ctx, -EINVAL); C_SaferCond cond_ctx; MockDisableFeaturesRequest *req = new MockDisableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, RBD_FEATURE_OBJECT_MAP | RBD_FEATURE_FAST_DIFF, false); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationDisableFeaturesRequest, Mirroring) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); MirrorModeEnabler mirror_mode_enabler(m_ioctx, cls::rbd::MIRROR_MODE_POOL); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_verify_lock_ownership(mock_image_ctx); MockRemoveJournalRequest mock_remove_journal_request; MockDisableMirrorRequest mock_disable_mirror_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); expect_is_journal_replaying(*mock_image_ctx.journal); expect_block_requests(mock_image_ctx); expect_disable_mirror_request_send(mock_image_ctx, mock_disable_mirror_request, 0); expect_close_journal(mock_image_ctx, 0); expect_remove_journal_request_send(mock_image_ctx, mock_remove_journal_request, 0); expect_notify_update(mock_image_ctx); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); C_SaferCond cond_ctx; MockDisableFeaturesRequest *req = new MockDisableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, RBD_FEATURE_JOURNALING, false); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationDisableFeaturesRequest, MirroringError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_verify_lock_ownership(mock_image_ctx); MockRemoveJournalRequest mock_remove_journal_request; MockDisableMirrorRequest mock_disable_mirror_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); expect_is_journal_replaying(*mock_image_ctx.journal); expect_block_requests(mock_image_ctx); expect_disable_mirror_request_send(mock_image_ctx, mock_disable_mirror_request, -EINVAL); expect_close_journal(mock_image_ctx, 0); expect_remove_journal_request_send(mock_image_ctx, mock_remove_journal_request, 0); expect_notify_update(mock_image_ctx); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); C_SaferCond cond_ctx; MockDisableFeaturesRequest *req = new MockDisableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, RBD_FEATURE_JOURNALING, false); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } } // namespace operation } // namespace librbd
17,530
31.525046
94
cc
null
ceph-main/src/test/librbd/operation/test_mock_EnableFeaturesRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "cls/rbd/cls_rbd_client.h" #include "librbd/Operations.h" #include "librbd/internal.h" #include "librbd/Journal.h" #include "librbd/image/SetFlagsRequest.h" #include "librbd/io/AioCompletion.h" #include "librbd/mirror/EnableRequest.h" #include "librbd/journal/CreateRequest.h" #include "librbd/journal/Types.h" #include "librbd/journal/TypeTraits.h" #include "librbd/object_map/CreateRequest.h" #include "librbd/operation/EnableFeaturesRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace { struct MockOperationImageCtx : public MockImageCtx { MockOperationImageCtx(librbd::ImageCtx& image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace template<> struct Journal<MockOperationImageCtx> { static void get_work_queue(CephContext*, MockContextWQ**) { } }; namespace image { template<> class SetFlagsRequest<MockOperationImageCtx> { public: static SetFlagsRequest *s_instance; Context *on_finish = nullptr; static SetFlagsRequest *create(MockOperationImageCtx *image_ctx, uint64_t flags, uint64_t mask, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } SetFlagsRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; SetFlagsRequest<MockOperationImageCtx> *SetFlagsRequest<MockOperationImageCtx>::s_instance; } // namespace image namespace journal { template<> class CreateRequest<MockOperationImageCtx> { public: static CreateRequest *s_instance; Context *on_finish = nullptr; static CreateRequest *create(IoCtx &ioctx, const std::string &imageid, uint8_t order, uint8_t splay_width, const std::string &object_pool, uint64_t tag_class, TagData &tag_data, const std::string &client_id, MockContextWQ *op_work_queue, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } CreateRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; CreateRequest<MockOperationImageCtx> *CreateRequest<MockOperationImageCtx>::s_instance = nullptr; template <> struct TypeTraits<MockOperationImageCtx> { typedef librbd::MockContextWQ ContextWQ; }; } // namespace journal namespace mirror { template<> class EnableRequest<MockOperationImageCtx> { public: static EnableRequest *s_instance; Context *on_finish = nullptr; static EnableRequest *create(MockOperationImageCtx *image_ctx, cls::rbd::MirrorImageMode mirror_image_mode, const std::string& non_primary_global_image_id, bool image_clean, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } EnableRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; EnableRequest<MockOperationImageCtx> *EnableRequest<MockOperationImageCtx>::s_instance = nullptr; } // namespace mirror namespace object_map { template<> class CreateRequest<MockOperationImageCtx> { public: static CreateRequest *s_instance; Context *on_finish = nullptr; static CreateRequest *create(MockOperationImageCtx *image_ctx, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } CreateRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; CreateRequest<MockOperationImageCtx> *CreateRequest<MockOperationImageCtx>::s_instance = nullptr; } // namespace object_map template <> struct AsyncRequest<MockOperationImageCtx> : public AsyncRequest<MockImageCtx> { MockOperationImageCtx &m_image_ctx; AsyncRequest(MockOperationImageCtx &image_ctx, Context *on_finish) : AsyncRequest<MockImageCtx>(image_ctx, on_finish), m_image_ctx(image_ctx) { } }; } // namespace librbd // template definitions #include "librbd/AsyncRequest.cc" #include "librbd/AsyncObjectThrottle.cc" #include "librbd/operation/Request.cc" #include "librbd/operation/EnableFeaturesRequest.cc" namespace librbd { namespace operation { using ::testing::Invoke; using ::testing::Return; using ::testing::WithArg; using ::testing::_; class TestMockOperationEnableFeaturesRequest : public TestMockFixture { public: typedef librbd::image::SetFlagsRequest<MockOperationImageCtx> MockSetFlagsRequest; typedef librbd::journal::CreateRequest<MockOperationImageCtx> MockCreateJournalRequest; typedef librbd::mirror::EnableRequest<MockOperationImageCtx> MockEnableMirrorRequest; typedef librbd::object_map::CreateRequest<MockOperationImageCtx> MockCreateObjectMapRequest; typedef EnableFeaturesRequest<MockOperationImageCtx> MockEnableFeaturesRequest; class MirrorModeEnabler { public: MirrorModeEnabler(librados::IoCtx &ioctx, cls::rbd::MirrorMode mirror_mode) : m_ioctx(ioctx), m_mirror_mode(mirror_mode) { EXPECT_EQ(0, librbd::cls_client::mirror_uuid_set(&m_ioctx, "test-uuid")); EXPECT_EQ(0, librbd::cls_client::mirror_mode_set(&m_ioctx, m_mirror_mode)); } ~MirrorModeEnabler() { EXPECT_EQ(0, librbd::cls_client::mirror_mode_set( &m_ioctx, cls::rbd::MIRROR_MODE_DISABLED)); } private: librados::IoCtx &m_ioctx; cls::rbd::MirrorMode m_mirror_mode; }; void ensure_features_disabled(librbd::ImageCtx *ictx, uint64_t features_to_disable) { uint64_t features; ASSERT_EQ(0, librbd::get_features(ictx, &features)); features_to_disable &= features; if (!features_to_disable) { return; } ASSERT_EQ(0, ictx->operations->update_features(features_to_disable, false)); ASSERT_EQ(0, librbd::get_features(ictx, &features)); ASSERT_EQ(0U, features & features_to_disable); } void expect_prepare_lock(MockOperationImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.state, prepare_lock(_)) .WillOnce(Invoke([](Context *on_ready) { on_ready->complete(0); })); expect_op_work_queue(mock_image_ctx); } void expect_handle_prepare_lock_complete(MockOperationImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.state, handle_prepare_lock_complete()); } void expect_block_writes(MockOperationImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, block_writes(_)) .WillOnce(CompleteContext(0, mock_image_ctx.image_ctx->op_work_queue)); } void expect_unblock_writes(MockOperationImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, unblock_writes()).Times(1); } void expect_verify_lock_ownership(MockOperationImageCtx &mock_image_ctx) { if (mock_image_ctx.exclusive_lock != nullptr) { EXPECT_CALL(*mock_image_ctx.exclusive_lock, is_lock_owner()) .WillRepeatedly(Return(true)); } } void expect_block_requests(MockOperationImageCtx &mock_image_ctx) { if (mock_image_ctx.exclusive_lock != nullptr) { EXPECT_CALL(*mock_image_ctx.exclusive_lock, block_requests(0)).Times(1); } } void expect_unblock_requests(MockOperationImageCtx &mock_image_ctx) { if (mock_image_ctx.exclusive_lock != nullptr) { EXPECT_CALL(*mock_image_ctx.exclusive_lock, unblock_requests()).Times(1); } } void expect_set_flags_request_send( MockOperationImageCtx &mock_image_ctx, MockSetFlagsRequest &mock_set_flags_request, int r) { EXPECT_CALL(mock_set_flags_request, send()) .WillOnce(FinishRequest(&mock_set_flags_request, r, &mock_image_ctx)); } void expect_create_journal_request_send( MockOperationImageCtx &mock_image_ctx, MockCreateJournalRequest &mock_create_journal_request, int r) { EXPECT_CALL(mock_create_journal_request, send()) .WillOnce(FinishRequest(&mock_create_journal_request, r, &mock_image_ctx)); } void expect_enable_mirror_request_send( MockOperationImageCtx &mock_image_ctx, MockEnableMirrorRequest &mock_enable_mirror_request, int r) { EXPECT_CALL(mock_enable_mirror_request, send()) .WillOnce(FinishRequest(&mock_enable_mirror_request, r, &mock_image_ctx)); } void expect_create_object_map_request_send( MockOperationImageCtx &mock_image_ctx, MockCreateObjectMapRequest &mock_create_object_map_request, int r) { EXPECT_CALL(mock_create_object_map_request, send()) .WillOnce(FinishRequest(&mock_create_object_map_request, r, &mock_image_ctx)); } void expect_notify_update(MockOperationImageCtx &mock_image_ctx) { EXPECT_CALL(mock_image_ctx, notify_update(_)) .WillOnce(CompleteContext(0, mock_image_ctx.image_ctx->op_work_queue)); } }; TEST_F(TestMockOperationEnableFeaturesRequest, All) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); uint64_t features; ASSERT_EQ(0, librbd::get_features(ictx, &features)); uint64_t features_to_enable = RBD_FEATURES_MUTABLE & features; REQUIRE(features_to_enable); ensure_features_disabled(ictx, features_to_enable); MockOperationImageCtx mock_image_ctx(*ictx); MockSetFlagsRequest mock_set_flags_request; MockCreateJournalRequest mock_create_journal_request; MockCreateObjectMapRequest mock_create_object_map_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); expect_block_requests(mock_image_ctx); if (features_to_enable & RBD_FEATURE_JOURNALING) { expect_create_journal_request_send(mock_image_ctx, mock_create_journal_request, 0); } if (features_to_enable & (RBD_FEATURE_OBJECT_MAP | RBD_FEATURE_FAST_DIFF)) { expect_set_flags_request_send(mock_image_ctx, mock_set_flags_request, 0); } if (features_to_enable & RBD_FEATURE_OBJECT_MAP) { expect_create_object_map_request_send(mock_image_ctx, mock_create_object_map_request, 0); } expect_notify_update(mock_image_ctx); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); C_SaferCond cond_ctx; MockEnableFeaturesRequest *req = new MockEnableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, features_to_enable); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationEnableFeaturesRequest, ObjectMap) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); uint64_t features; ASSERT_EQ(0, librbd::get_features(ictx, &features)); ensure_features_disabled( ictx, RBD_FEATURE_OBJECT_MAP | RBD_FEATURE_FAST_DIFF); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_verify_lock_ownership(mock_image_ctx); MockSetFlagsRequest mock_set_flags_request; MockCreateObjectMapRequest mock_create_object_map_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); if (mock_image_ctx.journal != nullptr) { expect_is_journal_replaying(*mock_image_ctx.journal); } expect_block_requests(mock_image_ctx); expect_append_op_event(mock_image_ctx, true, 0); expect_set_flags_request_send(mock_image_ctx, mock_set_flags_request, 0); expect_create_object_map_request_send(mock_image_ctx, mock_create_object_map_request, 0); expect_notify_update(mock_image_ctx); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); expect_commit_op_event(mock_image_ctx, 0); C_SaferCond cond_ctx; MockEnableFeaturesRequest *req = new MockEnableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, RBD_FEATURE_OBJECT_MAP); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationEnableFeaturesRequest, ObjectMapError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); uint64_t features; ASSERT_EQ(0, librbd::get_features(ictx, &features)); ensure_features_disabled( ictx, RBD_FEATURE_OBJECT_MAP | RBD_FEATURE_FAST_DIFF); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_verify_lock_ownership(mock_image_ctx); MockSetFlagsRequest mock_set_flags_request; MockCreateObjectMapRequest mock_create_object_map_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); if (mock_image_ctx.journal != nullptr) { expect_is_journal_replaying(*mock_image_ctx.journal); } expect_block_requests(mock_image_ctx); expect_append_op_event(mock_image_ctx, true, 0); expect_set_flags_request_send(mock_image_ctx, mock_set_flags_request, 0); expect_create_object_map_request_send( mock_image_ctx, mock_create_object_map_request, -EINVAL); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); expect_commit_op_event(mock_image_ctx, -EINVAL); C_SaferCond cond_ctx; MockEnableFeaturesRequest *req = new MockEnableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, RBD_FEATURE_OBJECT_MAP); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationEnableFeaturesRequest, SetFlagsError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); uint64_t features; ASSERT_EQ(0, librbd::get_features(ictx, &features)); ensure_features_disabled( ictx, RBD_FEATURE_OBJECT_MAP | RBD_FEATURE_FAST_DIFF); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_verify_lock_ownership(mock_image_ctx); MockSetFlagsRequest mock_set_flags_request; MockCreateObjectMapRequest mock_create_object_map_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); if (mock_image_ctx.journal != nullptr) { expect_is_journal_replaying(*mock_image_ctx.journal); } expect_block_requests(mock_image_ctx); expect_append_op_event(mock_image_ctx, true, 0); expect_set_flags_request_send(mock_image_ctx, mock_set_flags_request, -EINVAL); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); expect_commit_op_event(mock_image_ctx, -EINVAL); C_SaferCond cond_ctx; MockEnableFeaturesRequest *req = new MockEnableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, RBD_FEATURE_OBJECT_MAP); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationEnableFeaturesRequest, Mirroring) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); MirrorModeEnabler mirror_mode_enabler(m_ioctx, cls::rbd::MIRROR_MODE_POOL); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); uint64_t features; ASSERT_EQ(0, librbd::get_features(ictx, &features)); ensure_features_disabled(ictx, RBD_FEATURE_JOURNALING); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_verify_lock_ownership(mock_image_ctx); MockCreateJournalRequest mock_create_journal_request; MockEnableMirrorRequest mock_enable_mirror_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); expect_block_requests(mock_image_ctx); expect_create_journal_request_send(mock_image_ctx, mock_create_journal_request, 0); expect_enable_mirror_request_send(mock_image_ctx, mock_enable_mirror_request, 0); expect_notify_update(mock_image_ctx); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); C_SaferCond cond_ctx; MockEnableFeaturesRequest *req = new MockEnableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, RBD_FEATURE_JOURNALING); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationEnableFeaturesRequest, JournalingError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); MirrorModeEnabler mirror_mode_enabler(m_ioctx, cls::rbd::MIRROR_MODE_POOL); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); uint64_t features; ASSERT_EQ(0, librbd::get_features(ictx, &features)); ensure_features_disabled(ictx, RBD_FEATURE_JOURNALING); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_verify_lock_ownership(mock_image_ctx); MockCreateJournalRequest mock_create_journal_request; MockEnableMirrorRequest mock_enable_mirror_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); expect_block_requests(mock_image_ctx); expect_create_journal_request_send(mock_image_ctx, mock_create_journal_request, -EINVAL); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); C_SaferCond cond_ctx; MockEnableFeaturesRequest *req = new MockEnableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, RBD_FEATURE_JOURNALING); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationEnableFeaturesRequest, MirroringError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); MirrorModeEnabler mirror_mode_enabler(m_ioctx, cls::rbd::MIRROR_MODE_POOL); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); uint64_t features; ASSERT_EQ(0, librbd::get_features(ictx, &features)); ensure_features_disabled(ictx, RBD_FEATURE_JOURNALING); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_verify_lock_ownership(mock_image_ctx); MockCreateJournalRequest mock_create_journal_request; MockEnableMirrorRequest mock_enable_mirror_request; ::testing::InSequence seq; expect_prepare_lock(mock_image_ctx); expect_block_writes(mock_image_ctx); expect_block_requests(mock_image_ctx); expect_create_journal_request_send(mock_image_ctx, mock_create_journal_request, 0); expect_enable_mirror_request_send(mock_image_ctx, mock_enable_mirror_request, -EINVAL); expect_notify_update(mock_image_ctx); expect_unblock_requests(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_handle_prepare_lock_complete(mock_image_ctx); C_SaferCond cond_ctx; MockEnableFeaturesRequest *req = new MockEnableFeaturesRequest( mock_image_ctx, &cond_ctx, 0, RBD_FEATURE_JOURNALING); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } } // namespace operation } // namespace librbd
21,064
31.658915
97
cc
null
ceph-main/src/test/librbd/operation/test_mock_Request.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/MockJournal.h" #include "librbd/AsyncRequest.h" #include "librbd/operation/Request.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace template <> struct AsyncRequest<librbd::MockTestImageCtx> { librbd::MockTestImageCtx &m_image_ctx; Context *m_on_finish; AsyncRequest(librbd::MockTestImageCtx &image_ctx, Context *on_finish) : m_image_ctx(image_ctx), m_on_finish(on_finish) { } virtual ~AsyncRequest() { } virtual void finish(int r) { m_on_finish->complete(r); } virtual void finish_and_destroy(int r) { finish(r); delete this; } }; } // namespace librbd #include "librbd/operation/Request.cc" namespace librbd { namespace journal { std::ostream& operator<<(std::ostream& os, const Event&) { return os; } } // namespace journal namespace operation { using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; struct MockRequest : public Request<librbd::MockTestImageCtx> { MockRequest(librbd::MockTestImageCtx &image_ctx, Context *on_finish, uint64_t journal_op_tid) : Request<librbd::MockTestImageCtx>(image_ctx, on_finish, journal_op_tid) { } void complete(int r) { finish_and_destroy(r); } void send_op_impl(int r) { bool appending = append_op_event< MockRequest, &MockRequest::handle_send>(this); if (!appending) { complete(r); } } MOCK_METHOD1(should_complete, bool(int)); MOCK_METHOD0(send_op, void()); MOCK_METHOD1(handle_send, Context*(int*)); MOCK_CONST_METHOD0(can_affect_io, bool()); MOCK_CONST_METHOD1(create_event, journal::Event(uint64_t)); }; struct TestMockOperationRequest : public TestMockFixture { void expect_can_affect_io(MockRequest &mock_request, bool can_affect) { EXPECT_CALL(mock_request, can_affect_io()) .WillOnce(Return(can_affect)); } void expect_is_journal_replaying(MockJournal &mock_journal, bool replaying) { EXPECT_CALL(mock_journal, is_journal_replaying()) .WillOnce(Return(replaying)); } void expect_is_journal_appending(MockJournal &mock_journal, bool appending) { EXPECT_CALL(mock_journal, is_journal_appending()) .WillOnce(Return(appending)); } void expect_send_op(MockRequest &mock_request, int r) { EXPECT_CALL(mock_request, send_op()) .WillOnce(Invoke([&mock_request, r]() { mock_request.complete(r); })); } void expect_send_op_affects_io(MockImageCtx &mock_image_ctx, MockRequest &mock_request, int r) { EXPECT_CALL(mock_request, send_op()) .WillOnce(Invoke([&mock_image_ctx, &mock_request, r]() { mock_image_ctx.image_ctx->op_work_queue->queue( new LambdaContext([&mock_request, r](int _) { mock_request.send_op_impl(r); }), 0); })); } }; TEST_F(TestMockOperationRequest, SendJournalDisabled) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockJournal mock_journal; mock_image_ctx.journal = &mock_journal; C_SaferCond ctx; MockRequest *mock_request = new MockRequest(mock_image_ctx, &ctx, 0); InSequence seq; expect_can_affect_io(*mock_request, false); expect_is_journal_appending(mock_journal, false); expect_send_op(*mock_request, 0); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; mock_request->send(); } ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockOperationRequest, SendAffectsIOJournalDisabled) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockJournal mock_journal; mock_image_ctx.journal = &mock_journal; C_SaferCond ctx; MockRequest *mock_request = new MockRequest(mock_image_ctx, &ctx, 0); InSequence seq; expect_can_affect_io(*mock_request, true); expect_send_op_affects_io(mock_image_ctx, *mock_request, 0); expect_can_affect_io(*mock_request, true); expect_is_journal_replaying(mock_journal, false); expect_is_journal_appending(mock_journal, false); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; mock_request->send(); } ASSERT_EQ(0, ctx.wait()); } } // namespace operation } // namespace librbd
4,750
25.994318
79
cc
null
ceph-main/src/test/librbd/operation/test_mock_ResizeRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/io/MockObjectDispatch.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "common/bit_vector.hpp" #include "librbd/internal.h" #include "librbd/ObjectMap.h" #include "librbd/operation/ResizeRequest.h" #include "librbd/operation/TrimRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace util { inline ImageCtx* get_image_ctx(MockImageCtx* image_ctx) { return image_ctx->image_ctx; } } // namespace util namespace operation { template <> class TrimRequest<MockImageCtx> { public: static TrimRequest *s_instance; static TrimRequest *create(MockImageCtx &image_ctx, Context *on_finish, uint64_t original_size, uint64_t new_size, ProgressContext &prog_ctx) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } Context *on_finish = nullptr; TrimRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; TrimRequest<MockImageCtx> *TrimRequest<MockImageCtx>::s_instance = nullptr; } // namespace operation } // namespace librbd // template definitions #include "librbd/operation/ResizeRequest.cc" namespace librbd { namespace operation { using ::testing::_; using ::testing::DoAll; using ::testing::Invoke; using ::testing::InSequence; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; class TestMockOperationResizeRequest : public TestMockFixture { public: typedef ResizeRequest<MockImageCtx> MockResizeRequest; typedef TrimRequest<MockImageCtx> MockTrimRequest; void expect_block_writes(MockImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, block_writes(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); } void expect_unblock_writes(MockImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, unblock_writes()) .Times(1); } void expect_is_lock_owner(MockImageCtx &mock_image_ctx) { if (mock_image_ctx.exclusive_lock != nullptr) { EXPECT_CALL(*mock_image_ctx.exclusive_lock, is_lock_owner()) .WillOnce(Return(true)); } } void expect_grow_object_map(MockImageCtx &mock_image_ctx) { if (mock_image_ctx.object_map != nullptr) { expect_is_lock_owner(mock_image_ctx); EXPECT_CALL(*mock_image_ctx.object_map, aio_resize(_, _, _)) .WillOnce(WithArg<2>(CompleteContext(0, mock_image_ctx.image_ctx->op_work_queue))); } } void expect_shrink_object_map(MockImageCtx &mock_image_ctx) { if (mock_image_ctx.object_map != nullptr) { expect_is_lock_owner(mock_image_ctx); EXPECT_CALL(*mock_image_ctx.object_map, aio_resize(_, _, _)) .WillOnce(WithArg<2>(CompleteContext(0, mock_image_ctx.image_ctx->op_work_queue))); } } void expect_update_header(MockImageCtx &mock_image_ctx, int r) { if (mock_image_ctx.old_format) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), write(mock_image_ctx.header_oid, _, _, _, _)) .WillOnce(Return(r)); } else { expect_is_lock_owner(mock_image_ctx); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("rbd"), StrEq("set_size"), _, _, _, _)) .WillOnce(Return(r)); } } void expect_trim(MockImageCtx &mock_image_ctx, MockTrimRequest &mock_trim_request, int r) { EXPECT_CALL(mock_trim_request, send()) .WillOnce(FinishRequest(&mock_trim_request, r, &mock_image_ctx)); } void expect_flush_cache(MockImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, send(_)) .WillOnce(Invoke([&mock_image_ctx, r](io::ImageDispatchSpec* spec) { ASSERT_TRUE(boost::get<io::ImageDispatchSpec::Flush>( &spec->request) != nullptr); spec->dispatch_result = io::DISPATCH_RESULT_COMPLETE; auto aio_comp = spec->aio_comp; auto ctx = new LambdaContext([aio_comp](int r) { if (r < 0) { aio_comp->fail(r); } else { aio_comp->set_request_count(1); aio_comp->add_request(); aio_comp->complete_request(r); } }); mock_image_ctx.image_ctx->op_work_queue->queue(ctx, r); })); } void expect_invalidate_cache(MockImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, invalidate_cache(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); expect_op_work_queue(mock_image_ctx); } void expect_resize_object_map(MockImageCtx &mock_image_ctx, uint64_t new_size) { EXPECT_CALL(*mock_image_ctx.object_map, aio_resize(new_size, _, _)) .WillOnce(WithArg<2>(CompleteContext(0, mock_image_ctx.image_ctx->op_work_queue))); } int when_resize(MockImageCtx &mock_image_ctx, uint64_t new_size, bool allow_shrink, uint64_t journal_op_tid, bool disable_journal) { C_SaferCond cond_ctx; librbd::NoOpProgressContext prog_ctx; MockResizeRequest *req = new MockResizeRequest( mock_image_ctx, &cond_ctx, new_size, allow_shrink, prog_ctx, journal_op_tid, disable_journal); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } return cond_ctx.wait(); } }; TEST_F(TestMockOperationResizeRequest, NoOpSuccess) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, 0); expect_append_op_event(mock_image_ctx, true, 0); expect_unblock_writes(mock_image_ctx); expect_commit_op_event(mock_image_ctx, 0); ASSERT_EQ(0, when_resize(mock_image_ctx, ictx->size, true, 0, false)); } TEST_F(TestMockOperationResizeRequest, GrowSuccess) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, 0); expect_append_op_event(mock_image_ctx, true, 0); expect_grow_object_map(mock_image_ctx); expect_update_header(mock_image_ctx, 0); expect_unblock_writes(mock_image_ctx); expect_commit_op_event(mock_image_ctx, 0); ASSERT_EQ(0, when_resize(mock_image_ctx, ictx->size * 2, true, 0, false)); } TEST_F(TestMockOperationResizeRequest, ShrinkSuccess) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, 0); expect_append_op_event(mock_image_ctx, true, 0); expect_unblock_writes(mock_image_ctx); MockTrimRequest mock_trim_request; expect_flush_cache(mock_image_ctx, 0); expect_invalidate_cache(mock_image_ctx, 0); expect_trim(mock_image_ctx, mock_trim_request, 0); expect_block_writes(mock_image_ctx, 0); expect_update_header(mock_image_ctx, 0); expect_shrink_object_map(mock_image_ctx); expect_unblock_writes(mock_image_ctx); expect_commit_op_event(mock_image_ctx, 0); ASSERT_EQ(0, when_resize(mock_image_ctx, ictx->size / 2, true, 0, false)); } TEST_F(TestMockOperationResizeRequest, ShrinkError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, -EINVAL); expect_unblock_writes(mock_image_ctx); ASSERT_EQ(-EINVAL, when_resize(mock_image_ctx, ictx->size / 2, false, 0, false)); } TEST_F(TestMockOperationResizeRequest, PreBlockWritesError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, -EINVAL); expect_unblock_writes(mock_image_ctx); ASSERT_EQ(-EINVAL, when_resize(mock_image_ctx, ictx->size, true, 0, false)); } TEST_F(TestMockOperationResizeRequest, TrimError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, 0); expect_append_op_event(mock_image_ctx, true, 0); expect_unblock_writes(mock_image_ctx); MockTrimRequest mock_trim_request; expect_flush_cache(mock_image_ctx, 0); expect_invalidate_cache(mock_image_ctx, -EBUSY); expect_trim(mock_image_ctx, mock_trim_request, -EINVAL); expect_commit_op_event(mock_image_ctx, -EINVAL); ASSERT_EQ(-EINVAL, when_resize(mock_image_ctx, ictx->size / 2, true, 0, false)); } TEST_F(TestMockOperationResizeRequest, FlushCacheError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); REQUIRE(ictx->cache); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, 0); expect_append_op_event(mock_image_ctx, true, 0); expect_unblock_writes(mock_image_ctx); MockTrimRequest mock_trim_request; expect_flush_cache(mock_image_ctx, -EINVAL); expect_commit_op_event(mock_image_ctx, -EINVAL); ASSERT_EQ(-EINVAL, when_resize(mock_image_ctx, ictx->size / 2, true, 0, false)); } TEST_F(TestMockOperationResizeRequest, InvalidateCacheError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); REQUIRE(ictx->cache); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, 0); expect_append_op_event(mock_image_ctx, true, 0); expect_unblock_writes(mock_image_ctx); MockTrimRequest mock_trim_request; expect_flush_cache(mock_image_ctx, 0); expect_invalidate_cache(mock_image_ctx, -EINVAL); expect_commit_op_event(mock_image_ctx, -EINVAL); ASSERT_EQ(-EINVAL, when_resize(mock_image_ctx, ictx->size / 2, true, 0, false)); } TEST_F(TestMockOperationResizeRequest, PostBlockWritesError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, 0); expect_append_op_event(mock_image_ctx, true, 0); expect_unblock_writes(mock_image_ctx); MockTrimRequest mock_trim_request; expect_flush_cache(mock_image_ctx, 0); expect_invalidate_cache(mock_image_ctx, 0); expect_trim(mock_image_ctx, mock_trim_request, 0); expect_block_writes(mock_image_ctx, -EINVAL); expect_unblock_writes(mock_image_ctx); expect_commit_op_event(mock_image_ctx, -EINVAL); ASSERT_EQ(-EINVAL, when_resize(mock_image_ctx, ictx->size / 2, true, 0, false)); } TEST_F(TestMockOperationResizeRequest, UpdateHeaderError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, 0); expect_append_op_event(mock_image_ctx, true, 0); expect_grow_object_map(mock_image_ctx); expect_update_header(mock_image_ctx, -EINVAL); expect_unblock_writes(mock_image_ctx); expect_commit_op_event(mock_image_ctx, -EINVAL); ASSERT_EQ(-EINVAL, when_resize(mock_image_ctx, ictx->size * 2, true, 0, false)); } TEST_F(TestMockOperationResizeRequest, JournalAppendError) { REQUIRE_FEATURE(RBD_FEATURE_JOURNALING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, 0); expect_append_op_event(mock_image_ctx, true, -EINVAL); expect_unblock_writes(mock_image_ctx); ASSERT_EQ(-EINVAL, when_resize(mock_image_ctx, ictx->size, true, 0, false)); } TEST_F(TestMockOperationResizeRequest, JournalDisabled) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); InSequence seq; expect_block_writes(mock_image_ctx, 0); expect_unblock_writes(mock_image_ctx); ASSERT_EQ(0, when_resize(mock_image_ctx, ictx->size, true, 0, true)); } } // namespace operation } // namespace librbd
15,166
33.786697
103
cc
null
ceph-main/src/test/librbd/operation/test_mock_SnapshotCreateRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "common/bit_vector.hpp" #include "librbd/internal.h" #include "librbd/ObjectMap.h" #include "librbd/mirror/snapshot/SetImageStateRequest.h" #include "librbd/operation/SnapshotCreateRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace mirror { namespace snapshot { template<> class SetImageStateRequest<MockImageCtx> { public: static SetImageStateRequest *s_instance; Context *on_finish = nullptr; static SetImageStateRequest *create(MockImageCtx *image_ctx, uint64_t snap_id, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } SetImageStateRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; SetImageStateRequest<MockImageCtx> *SetImageStateRequest<MockImageCtx>::s_instance; } // namespace snapshot } // namespace mirror } // namespace librbd // template definitions #include "librbd/operation/SnapshotCreateRequest.cc" namespace librbd { namespace operation { using ::testing::_; using ::testing::DoAll; using ::testing::DoDefault; using ::testing::Return; using ::testing::SetArgPointee; using ::testing::StrEq; using ::testing::WithArg; class TestMockOperationSnapshotCreateRequest : public TestMockFixture { public: typedef SnapshotCreateRequest<MockImageCtx> MockSnapshotCreateRequest; typedef mirror::snapshot::SetImageStateRequest<MockImageCtx> MockSetImageStateRequest; void expect_notify_quiesce(MockImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.image_watcher, notify_quiesce(_, _, _)) .WillOnce(WithArg<2>(CompleteContext( r, mock_image_ctx.image_ctx->op_work_queue))); } void expect_block_writes(MockImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, block_writes(_)) .WillOnce(CompleteContext(0, mock_image_ctx.image_ctx->op_work_queue)); } void expect_verify_lock_ownership(MockImageCtx &mock_image_ctx) { if (mock_image_ctx.exclusive_lock != nullptr) { EXPECT_CALL(*mock_image_ctx.exclusive_lock, is_lock_owner()) .WillRepeatedly(Return(true)); } } void expect_allocate_snap_id(MockImageCtx &mock_image_ctx, int r) { auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.data_ctx), selfmanaged_snap_create(_)); if (r < 0 && r != -ESTALE) { expect.WillOnce(Return(r)); } else { expect.Times(r < 0 ? 2 : 1).WillRepeatedly(DoDefault()); } } void expect_release_snap_id(MockImageCtx &mock_image_ctx, int r) { auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.data_ctx), selfmanaged_snap_remove(_)); if (r < 0) { expect.WillOnce(Return(r)); } else { expect.WillOnce(DoDefault()); } } void expect_snap_create(MockImageCtx &mock_image_ctx, int r) { auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("rbd"), StrEq(mock_image_ctx.old_format ? "snap_add" : "snapshot_add"), _, _, _, _)); if (r == -ESTALE) { expect.WillOnce(Return(r)).WillOnce(DoDefault()); } else if (r < 0) { expect.WillOnce(Return(r)); } else { expect.WillOnce(DoDefault()); } } void expect_object_map_snap_create(MockImageCtx &mock_image_ctx) { if (mock_image_ctx.object_map != nullptr) { EXPECT_CALL(*mock_image_ctx.object_map, snapshot_add(_, _)) .WillOnce(WithArg<1>(CompleteContext( 0, mock_image_ctx.image_ctx->op_work_queue))); } } void expect_set_image_state( MockImageCtx &mock_image_ctx, MockSetImageStateRequest &mock_set_image_state_request, int r) { EXPECT_CALL(mock_set_image_state_request, send()) .WillOnce(FinishRequest(&mock_set_image_state_request, r, &mock_image_ctx)); } void expect_update_snap_context(MockImageCtx &mock_image_ctx) { // state machine checks to ensure a refresh hasn't already added the snap EXPECT_CALL(mock_image_ctx, get_snap_info(_)) .WillOnce(Return(static_cast<const librbd::SnapInfo*>(NULL))); EXPECT_CALL(mock_image_ctx, add_snap(_, "snap1", _, _, _, _, _, _)); } void expect_unblock_writes(MockImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, unblock_writes()) .Times(1); } void expect_notify_unquiesce(MockImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.image_watcher, notify_unquiesce(_, _)) .WillOnce(WithArg<1>( CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue))); } }; TEST_F(TestMockOperationSnapshotCreateRequest, Success) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_verify_lock_ownership(mock_image_ctx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_notify_quiesce(mock_image_ctx, -EINVAL); expect_block_writes(mock_image_ctx); expect_allocate_snap_id(mock_image_ctx, 0); expect_snap_create(mock_image_ctx, 0); expect_object_map_snap_create(mock_image_ctx); expect_update_snap_context(mock_image_ctx); EXPECT_CALL(mock_image_ctx, rebuild_data_io_context()); expect_unblock_writes(mock_image_ctx); expect_notify_unquiesce(mock_image_ctx, -EINVAL); C_SaferCond cond_ctx; librbd::NoOpProgressContext prog_ctx; MockSnapshotCreateRequest *req = new MockSnapshotCreateRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", 0, SNAP_CREATE_FLAG_IGNORE_NOTIFY_QUIESCE_ERROR, prog_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotCreateRequest, NotifyQuiesceError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_notify_quiesce(mock_image_ctx, -EINVAL); expect_notify_unquiesce(mock_image_ctx, 0); C_SaferCond cond_ctx; librbd::NoOpProgressContext prog_ctx; MockSnapshotCreateRequest *req = new MockSnapshotCreateRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", 0, 0, prog_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotCreateRequest, AllocateSnapIdError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } expect_verify_lock_ownership(mock_image_ctx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_notify_quiesce(mock_image_ctx, 0); expect_block_writes(mock_image_ctx); expect_allocate_snap_id(mock_image_ctx, -EINVAL); expect_unblock_writes(mock_image_ctx); expect_notify_unquiesce(mock_image_ctx, 0); C_SaferCond cond_ctx; librbd::NoOpProgressContext prog_ctx; MockSnapshotCreateRequest *req = new MockSnapshotCreateRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", 0, 0, prog_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotCreateRequest, CreateSnapStale) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_verify_lock_ownership(mock_image_ctx); expect_op_work_queue(mock_image_ctx); expect_notify_quiesce(mock_image_ctx, 0); expect_block_writes(mock_image_ctx); expect_allocate_snap_id(mock_image_ctx, -ESTALE); expect_snap_create(mock_image_ctx, -ESTALE); expect_object_map_snap_create(mock_image_ctx); expect_update_snap_context(mock_image_ctx); EXPECT_CALL(mock_image_ctx, rebuild_data_io_context()); expect_unblock_writes(mock_image_ctx); expect_notify_unquiesce(mock_image_ctx, 0); C_SaferCond cond_ctx; librbd::NoOpProgressContext prog_ctx; MockSnapshotCreateRequest *req = new MockSnapshotCreateRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", 0, 0, prog_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotCreateRequest, CreateSnapError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } expect_verify_lock_ownership(mock_image_ctx); expect_op_work_queue(mock_image_ctx); expect_notify_quiesce(mock_image_ctx, 0); expect_block_writes(mock_image_ctx); expect_allocate_snap_id(mock_image_ctx, 0); expect_snap_create(mock_image_ctx, -EINVAL); expect_release_snap_id(mock_image_ctx, 0); expect_unblock_writes(mock_image_ctx); expect_notify_unquiesce(mock_image_ctx, 0); C_SaferCond cond_ctx; librbd::NoOpProgressContext prog_ctx; MockSnapshotCreateRequest *req = new MockSnapshotCreateRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", 0, 0, prog_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotCreateRequest, ReleaseSnapIdError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } expect_verify_lock_ownership(mock_image_ctx); expect_op_work_queue(mock_image_ctx); expect_notify_quiesce(mock_image_ctx, 0); expect_block_writes(mock_image_ctx); expect_allocate_snap_id(mock_image_ctx, 0); expect_snap_create(mock_image_ctx, -EINVAL); expect_release_snap_id(mock_image_ctx, -ESTALE); expect_unblock_writes(mock_image_ctx); expect_notify_unquiesce(mock_image_ctx, 0); C_SaferCond cond_ctx; librbd::NoOpProgressContext prog_ctx; MockSnapshotCreateRequest *req = new MockSnapshotCreateRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", 0, 0, prog_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotCreateRequest, SkipObjectMap) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; mock_image_ctx.object_map = &mock_object_map; expect_verify_lock_ownership(mock_image_ctx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_notify_quiesce(mock_image_ctx, 0); expect_block_writes(mock_image_ctx); expect_allocate_snap_id(mock_image_ctx, 0); expect_snap_create(mock_image_ctx, 0); expect_update_snap_context(mock_image_ctx); EXPECT_CALL(mock_image_ctx, rebuild_data_io_context()); expect_unblock_writes(mock_image_ctx); expect_notify_unquiesce(mock_image_ctx, 0); C_SaferCond cond_ctx; librbd::NoOpProgressContext prog_ctx; MockSnapshotCreateRequest *req = new MockSnapshotCreateRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", 0, SNAP_CREATE_FLAG_SKIP_OBJECT_MAP, prog_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotCreateRequest, SkipNotifyQuiesce) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_verify_lock_ownership(mock_image_ctx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_block_writes(mock_image_ctx); expect_allocate_snap_id(mock_image_ctx, 0); expect_snap_create(mock_image_ctx, 0); expect_object_map_snap_create(mock_image_ctx); expect_update_snap_context(mock_image_ctx); EXPECT_CALL(mock_image_ctx, rebuild_data_io_context()); expect_unblock_writes(mock_image_ctx); C_SaferCond cond_ctx; librbd::NoOpProgressContext prog_ctx; MockSnapshotCreateRequest *req = new MockSnapshotCreateRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", 0, SNAP_CREATE_FLAG_SKIP_NOTIFY_QUIESCE, prog_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotCreateRequest, SetImageState) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_verify_lock_ownership(mock_image_ctx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_notify_quiesce(mock_image_ctx, 0); expect_block_writes(mock_image_ctx); expect_allocate_snap_id(mock_image_ctx, 0); expect_snap_create(mock_image_ctx, 0); expect_object_map_snap_create(mock_image_ctx); MockSetImageStateRequest mock_set_image_state_request; expect_set_image_state(mock_image_ctx, mock_set_image_state_request, 0); expect_update_snap_context(mock_image_ctx); EXPECT_CALL(mock_image_ctx, rebuild_data_io_context()); expect_unblock_writes(mock_image_ctx); expect_notify_unquiesce(mock_image_ctx, 0); C_SaferCond cond_ctx; librbd::NoOpProgressContext prog_ctx; MockSnapshotCreateRequest *req = new MockSnapshotCreateRequest( mock_image_ctx, &cond_ctx, cls::rbd::MirrorSnapshotNamespace{ cls::rbd::MIRROR_SNAPSHOT_STATE_PRIMARY, {}, "", CEPH_NOSNAP}, "snap1", 0, 0, prog_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } } // namespace operation } // namespace librbd
16,216
31.695565
89
cc
null
ceph-main/src/test/librbd/operation/test_mock_SnapshotProtectRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "common/bit_vector.hpp" #include "librbd/ImageState.h" #include "librbd/internal.h" #include "librbd/operation/SnapshotProtectRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" // template definitions #include "librbd/operation/SnapshotProtectRequest.cc" namespace librbd { namespace operation { using ::testing::_; using ::testing::DoAll; using ::testing::DoDefault; using ::testing::Return; using ::testing::SetArgPointee; using ::testing::StrEq; using ::testing::WithArg; class TestMockOperationSnapshotProtectRequest : public TestMockFixture { public: typedef SnapshotProtectRequest<MockImageCtx> MockSnapshotProtectRequest; void expect_get_snap_id(MockImageCtx &mock_image_ctx, uint64_t snap_id) { EXPECT_CALL(mock_image_ctx, get_snap_id(_, _)) .WillOnce(Return(snap_id)); } void expect_is_snap_protected(MockImageCtx &mock_image_ctx, bool is_protected, int r) { auto &expect = EXPECT_CALL(mock_image_ctx, is_snap_protected(_, _)); if (r < 0) { expect.WillOnce(Return(r)); } else { expect.WillOnce(DoAll(SetArgPointee<1>(is_protected), Return(0))); } } void expect_set_protection_status(MockImageCtx &mock_image_ctx, int r) { auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("rbd"), StrEq("set_protection_status"), _, _, _, _)); if (r < 0) { expect.WillOnce(Return(r)); } else { expect.WillOnce(DoDefault()); } } }; TEST_F(TestMockOperationSnapshotProtectRequest, Success) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_get_snap_id(mock_image_ctx, ictx->snap_info.rbegin()->first); expect_is_snap_protected(mock_image_ctx, false, 0); expect_set_protection_status(mock_image_ctx, 0); C_SaferCond cond_ctx; MockSnapshotProtectRequest *req = new MockSnapshotProtectRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1"); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotProtectRequest, GetSnapIdMissing) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_get_snap_id(mock_image_ctx, CEPH_NOSNAP); C_SaferCond cond_ctx; MockSnapshotProtectRequest *req = new MockSnapshotProtectRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1"); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-ENOENT, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotProtectRequest, IsSnapProtectedError) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_get_snap_id(mock_image_ctx, ictx->snap_info.rbegin()->first); expect_is_snap_protected(mock_image_ctx, false, -EINVAL); C_SaferCond cond_ctx; MockSnapshotProtectRequest *req = new MockSnapshotProtectRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1"); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotProtectRequest, SnapAlreadyProtected) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_get_snap_id(mock_image_ctx, ictx->snap_info.rbegin()->first); expect_is_snap_protected(mock_image_ctx, true, 0); C_SaferCond cond_ctx; MockSnapshotProtectRequest *req = new MockSnapshotProtectRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1"); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EBUSY, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotProtectRequest, SetProtectionStateError) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_get_snap_id(mock_image_ctx, ictx->snap_info.rbegin()->first); expect_is_snap_protected(mock_image_ctx, false, 0); expect_set_protection_status(mock_image_ctx, -EINVAL); C_SaferCond cond_ctx; MockSnapshotProtectRequest *req = new MockSnapshotProtectRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1"); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } } // namespace operation } // namespace librbd
6,075
30.319588
80
cc
null
ceph-main/src/test/librbd/operation/test_mock_SnapshotRemoveRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "common/bit_vector.hpp" #include "librbd/ImageState.h" #include "librbd/internal.h" #include "librbd/Operations.h" #include "librbd/image/DetachChildRequest.h" #include "librbd/mirror/snapshot/RemoveImageStateRequest.h" #include "librbd/operation/SnapshotRemoveRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace image { template <> class DetachChildRequest<MockImageCtx> { public: static DetachChildRequest *s_instance; static DetachChildRequest *create(MockImageCtx &image_ctx, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } Context *on_finish = nullptr; DetachChildRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; DetachChildRequest<MockImageCtx> *DetachChildRequest<MockImageCtx>::s_instance; } // namespace image namespace mirror { namespace snapshot { template<> class RemoveImageStateRequest<MockImageCtx> { public: static RemoveImageStateRequest *s_instance; Context *on_finish = nullptr; static RemoveImageStateRequest *create(MockImageCtx *image_ctx, uint64_t snap_id, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } RemoveImageStateRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; RemoveImageStateRequest<MockImageCtx> *RemoveImageStateRequest<MockImageCtx>::s_instance; } // namespace snapshot } // namespace mirror } // namespace librbd // template definitions #include "librbd/operation/SnapshotRemoveRequest.cc" namespace librbd { namespace operation { using ::testing::_; using ::testing::DoAll; using ::testing::DoDefault; using ::testing::Invoke; using ::testing::Return; using ::testing::SetArgPointee; using ::testing::StrEq; using ::testing::WithArg; class TestMockOperationSnapshotRemoveRequest : public TestMockFixture { public: typedef SnapshotRemoveRequest<MockImageCtx> MockSnapshotRemoveRequest; typedef image::DetachChildRequest<MockImageCtx> MockDetachChildRequest; typedef mirror::snapshot::RemoveImageStateRequest<MockImageCtx> MockRemoveImageStateRequest; int create_snapshot(const char *snap_name) { librbd::ImageCtx *ictx; int r = open_image(m_image_name, &ictx); if (r < 0) { return r; } r = snap_create(*ictx, snap_name); if (r < 0) { return r; } r = snap_protect(*ictx, snap_name); if (r < 0) { return r; } close_image(ictx); return 0; } void expect_snapshot_trash_add(MockImageCtx &mock_image_ctx, int r) { if (mock_image_ctx.old_format) { return; } auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("rbd"), StrEq("snapshot_trash_add"), _, _, _, _)); if (r < 0) { expect.WillOnce(Return(r)); } else { expect.WillOnce(DoDefault()); } } void expect_snapshot_get(MockImageCtx &mock_image_ctx, const cls::rbd::SnapshotInfo& snap_info, int r) { if (mock_image_ctx.old_format) { return; } using ceph::encode; EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("rbd"), StrEq("snapshot_get"), _, _, _, _)) .WillOnce(WithArg<5>(Invoke([snap_info, r](bufferlist* bl) { encode(snap_info, *bl); return r; }))); } void expect_children_list(MockImageCtx &mock_image_ctx, const cls::rbd::ChildImageSpecs& child_images, int r) { if (mock_image_ctx.old_format) { return; } using ceph::encode; EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("rbd"), StrEq("children_list"), _, _, _, _)) .WillOnce(WithArg<5>(Invoke([child_images, r](bufferlist* bl) { encode(child_images, *bl); return r; }))); } void expect_detach_stale_child(MockImageCtx &mock_image_ctx, int r) { auto& parent_spec = mock_image_ctx.parent_md.spec; bufferlist bl; encode(parent_spec.snap_id, bl); encode(cls::rbd::ChildImageSpec{mock_image_ctx.md_ctx.get_id(), "", mock_image_ctx.id}, bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(util::header_name(parent_spec.image_id), _, StrEq("rbd"), StrEq("child_detach"), ContentsEqual(bl), _, _, _)) .WillOnce(Return(r)); } void expect_object_map_snap_remove(MockImageCtx &mock_image_ctx, int r) { if (mock_image_ctx.object_map != nullptr) { EXPECT_CALL(*mock_image_ctx.object_map, snapshot_remove(_, _)) .WillOnce(WithArg<1>(CompleteContext( r, mock_image_ctx.image_ctx->op_work_queue))); } } void expect_remove_image_state( MockImageCtx &mock_image_ctx, MockRemoveImageStateRequest &mock_remove_image_state_request, int r) { EXPECT_CALL(mock_remove_image_state_request, send()) .WillOnce(FinishRequest(&mock_remove_image_state_request, r, &mock_image_ctx)); } void expect_get_parent_spec(MockImageCtx &mock_image_ctx, int r) { if (mock_image_ctx.old_format) { return; } auto &expect = EXPECT_CALL(mock_image_ctx, get_parent_spec(_, _)); if (r < 0) { expect.WillOnce(Return(r)); } else { auto &parent_spec = mock_image_ctx.snap_info.rbegin()->second.parent.spec; expect.WillOnce(DoAll(SetArgPointee<1>(parent_spec), Return(0))); } } void expect_detach_child(MockImageCtx &mock_image_ctx, MockDetachChildRequest& mock_request, int r) { EXPECT_CALL(mock_request, send()) .WillOnce(FinishRequest(&mock_request, r, &mock_image_ctx)); } void expect_snap_remove(MockImageCtx &mock_image_ctx, int r) { auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("rbd"), StrEq(mock_image_ctx.old_format ? "snap_remove" : "snapshot_remove"), _, _, _, _)); if (r < 0) { expect.WillOnce(Return(r)); } else { expect.WillOnce(DoDefault()); } } void expect_rm_snap(MockImageCtx &mock_image_ctx) { EXPECT_CALL(mock_image_ctx, rm_snap(_, _, _)).Times(1); } void expect_release_snap_id(MockImageCtx &mock_image_ctx) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.data_ctx), selfmanaged_snap_remove(_)) .WillOnce(DoDefault()); } }; TEST_F(TestMockOperationSnapshotRemoveRequest, Success) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, 0); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::UserSnapshotNamespace{}}, "snap1", 123, {}, 0}, 0); expect_get_parent_spec(mock_image_ctx, 0); expect_object_map_snap_remove(mock_image_ctx, 0); expect_release_snap_id(mock_image_ctx); expect_snap_remove(mock_image_ctx, 0); expect_rm_snap(mock_image_ctx); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, SuccessCloneParent) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, 0); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::UserSnapshotNamespace{}}, "snap1", 123, {}, 1}, 0); const cls::rbd::ChildImageSpecs child_images; expect_children_list(mock_image_ctx, child_images, 0); expect_get_parent_spec(mock_image_ctx, 0); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, SuccessTrash) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, 0); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::TrashSnapshotNamespace{ cls::rbd::SNAPSHOT_NAMESPACE_TYPE_USER, "snap1"}}, "snap1", 123, {}, 0}, 0); expect_get_parent_spec(mock_image_ctx, 0); expect_object_map_snap_remove(mock_image_ctx, 0); expect_release_snap_id(mock_image_ctx); expect_snap_remove(mock_image_ctx, 0); expect_rm_snap(mock_image_ctx); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, FlattenedCloneRemovesChild) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); REQUIRE(!is_feature_enabled(RBD_FEATURE_DEEP_FLATTEN)) ASSERT_EQ(0, create_snapshot("snap1")); int order = 22; uint64_t features; ASSERT_TRUE(::get_features(&features)); std::string clone_name = get_temp_image_name(); ASSERT_EQ(0, librbd::clone(m_ioctx, m_image_name.c_str(), "snap1", m_ioctx, clone_name.c_str(), features, &order, 0, 0)); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(clone_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); librbd::NoOpProgressContext prog_ctx; ASSERT_EQ(0, flatten(*ictx, prog_ctx)); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, 0); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::UserSnapshotNamespace{}}, "snap1", 123, {}, 0}, 0); expect_get_parent_spec(mock_image_ctx, 0); MockDetachChildRequest mock_detach_child_request; expect_detach_child(mock_image_ctx, mock_detach_child_request, -ENOENT); expect_object_map_snap_remove(mock_image_ctx, 0); expect_release_snap_id(mock_image_ctx); expect_snap_remove(mock_image_ctx, 0); expect_rm_snap(mock_image_ctx); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, TrashCloneParent) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); NoOpProgressContext prog_ctx; ASSERT_EQ(0, ictx->operations->snap_create( {cls::rbd::TrashSnapshotNamespace{}}, "snap1", 0, prog_ctx)); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::TrashSnapshotNamespace{}}, "snap1", 123, {}, 1}, 0); const cls::rbd::ChildImageSpecs child_images; expect_children_list(mock_image_ctx, child_images, 0); expect_get_parent_spec(mock_image_ctx, 0); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::TrashSnapshotNamespace{}, "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EBUSY, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, MirrorSnapshot) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, 0); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::MirrorSnapshotNamespace{}}, "mirror", 123, {}, 0}, 0); expect_get_parent_spec(mock_image_ctx, 0); expect_object_map_snap_remove(mock_image_ctx, 0); MockRemoveImageStateRequest mock_remove_image_state_request; expect_remove_image_state(mock_image_ctx, mock_remove_image_state_request, 0); expect_release_snap_id(mock_image_ctx); expect_snap_remove(mock_image_ctx, 0); expect_rm_snap(mock_image_ctx); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::MirrorSnapshotNamespace(), "mirror", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, SnapshotTrashAddNotSupported) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, -EOPNOTSUPP); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_get_parent_spec(mock_image_ctx, 0); expect_object_map_snap_remove(mock_image_ctx, 0); expect_release_snap_id(mock_image_ctx); expect_snap_remove(mock_image_ctx, 0); expect_rm_snap(mock_image_ctx); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, SnapshotTrashAddError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_trash_add(mock_image_ctx, -EINVAL); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, SnapshotGetError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, 0); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::UserSnapshotNamespace{}}, "snap1", 123, {}, 0}, -EOPNOTSUPP); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EOPNOTSUPP, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, ObjectMapSnapRemoveError) { REQUIRE_FEATURE(RBD_FEATURE_OBJECT_MAP); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockObjectMap mock_object_map; mock_image_ctx.object_map = &mock_object_map; expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, 0); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::UserSnapshotNamespace{}}, "snap1", 123, {}, 0}, 0); expect_get_parent_spec(mock_image_ctx, 0); expect_object_map_snap_remove(mock_image_ctx, -EINVAL); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, RemoveChildParentError) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, 0); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::UserSnapshotNamespace{}}, "snap1", 123, {}, 0}, 0); expect_get_parent_spec(mock_image_ctx, -ENOENT); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-ENOENT, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, RemoveChildError) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); ASSERT_EQ(0, create_snapshot("snap1")); int order = 22; uint64_t features; ASSERT_TRUE(::get_features(&features)); std::string clone_name = get_temp_image_name(); ASSERT_EQ(0, librbd::clone(m_ioctx, m_image_name.c_str(), "snap1", m_ioctx, clone_name.c_str(), features, &order, 0, 0)); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(clone_name, &ictx)); if (ictx->test_features(RBD_FEATURE_DEEP_FLATTEN)) { GTEST_SKIP() << "Skipping due to enabled deep-flatten"; } ASSERT_EQ(0, snap_create(*ictx, "snap1")); librbd::NoOpProgressContext prog_ctx; ASSERT_EQ(0, flatten(*ictx, prog_ctx)); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_get_parent_spec(mock_image_ctx, 0); MockDetachChildRequest mock_detach_child_request; expect_detach_child(mock_image_ctx, mock_detach_child_request, -EINVAL); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, RemoveSnapError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, 0); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::UserSnapshotNamespace{}}, "snap1", 123, {}, 0}, 0); expect_get_parent_spec(mock_image_ctx, 0); expect_object_map_snap_remove(mock_image_ctx, 0); expect_release_snap_id(mock_image_ctx); expect_snap_remove(mock_image_ctx, -ENOENT); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-ENOENT, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, MissingSnap) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; uint64_t snap_id = 456; C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-ENOENT, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, ListChildrenError) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } MockObjectMap mock_object_map; if (ictx->test_features(RBD_FEATURE_OBJECT_MAP)) { mock_image_ctx.object_map = &mock_object_map; } expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, 0); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::UserSnapshotNamespace{}}, "snap1", 123, {}, 1}, 0); const cls::rbd::ChildImageSpecs child_images; expect_children_list(mock_image_ctx, child_images, -EINVAL); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotRemoveRequest, DetachStaleChildError) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); ASSERT_EQ(0, create_snapshot("snap1")); int order = 22; uint64_t features; ASSERT_TRUE(::get_features(&features)); std::string clone_name = get_temp_image_name(); ASSERT_EQ(0, librbd::clone(m_ioctx, m_image_name.c_str(), "snap1", m_ioctx, clone_name.c_str(), features, &order, 0, 0)); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(clone_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_snapshot_trash_add(mock_image_ctx, 0); uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_snapshot_get(mock_image_ctx, {snap_id, {cls::rbd::UserSnapshotNamespace{}}, "snap1", 123, {}, 1}, 0); const cls::rbd::ChildImageSpecs child_images; expect_children_list(mock_image_ctx, child_images, -EINVAL); C_SaferCond cond_ctx; MockSnapshotRemoveRequest *req = new MockSnapshotRemoveRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1", snap_id); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } } // namespace operation } // namespace librbd
29,070
30.462121
94
cc
null
ceph-main/src/test/librbd/operation/test_mock_SnapshotRollbackRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/io/MockObjectDispatch.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "include/stringify.h" #include "common/bit_vector.hpp" #include "librbd/ImageState.h" #include "librbd/internal.h" #include "librbd/operation/SnapshotRollbackRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace librbd { namespace { struct MockOperationImageCtx : public MockImageCtx { MockOperationImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace operation { template <> struct ResizeRequest<MockOperationImageCtx> { static ResizeRequest *s_instance; Context *on_finish = nullptr; static ResizeRequest* create(MockOperationImageCtx &image_ctx, Context *on_finish, uint64_t new_size, bool allow_shrink, ProgressContext &prog_ctx, uint64_t journal_op_tid, bool disable_journal) { ceph_assert(s_instance != nullptr); ceph_assert(journal_op_tid == 0); ceph_assert(disable_journal); s_instance->on_finish = on_finish; return s_instance; } ResizeRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; ResizeRequest<MockOperationImageCtx> *ResizeRequest<MockOperationImageCtx>::s_instance = nullptr; } // namespace operation template <> struct AsyncRequest<MockOperationImageCtx> : public AsyncRequest<MockImageCtx> { MockOperationImageCtx &m_image_ctx; AsyncRequest(MockOperationImageCtx &image_ctx, Context *on_finish) : AsyncRequest<MockImageCtx>(image_ctx, on_finish), m_image_ctx(image_ctx) { } }; } // namespace librbd // template definitions #include "librbd/AsyncRequest.cc" #include "librbd/AsyncObjectThrottle.cc" #include "librbd/operation/Request.cc" #include "librbd/operation/SnapshotRollbackRequest.cc" namespace librbd { namespace operation { using ::testing::_; using ::testing::InSequence; using ::testing::Return; using ::testing::WithArg; class TestMockOperationSnapshotRollbackRequest : public TestMockFixture { public: typedef SnapshotRollbackRequest<MockOperationImageCtx> MockSnapshotRollbackRequest; typedef ResizeRequest<MockOperationImageCtx> MockResizeRequest; void expect_block_writes(MockOperationImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, block_writes(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); } void expect_unblock_writes(MockOperationImageCtx &mock_image_ctx) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, unblock_writes()) .Times(1); } void expect_get_image_size(MockOperationImageCtx &mock_image_ctx, uint64_t size) { EXPECT_CALL(mock_image_ctx, get_image_size(CEPH_NOSNAP)) .WillOnce(Return(size)); } void expect_resize(MockOperationImageCtx &mock_image_ctx, MockResizeRequest &mock_resize_request, int r) { expect_get_image_size(mock_image_ctx, 123); EXPECT_CALL(mock_resize_request, send()) .WillOnce(FinishRequest(&mock_resize_request, r, &mock_image_ctx)); } void expect_get_flags(MockOperationImageCtx &mock_image_ctx, uint64_t snap_id, int r) { EXPECT_CALL(mock_image_ctx, get_flags(snap_id, _)) .WillOnce(Return(r)); } void expect_object_may_exist(MockOperationImageCtx &mock_image_ctx, uint64_t object_no, bool exists) { if (mock_image_ctx.object_map != nullptr) { EXPECT_CALL(*mock_image_ctx.object_map, object_may_exist(object_no)) .WillOnce(Return(exists)); } } void expect_get_snap_object_map(MockOperationImageCtx &mock_image_ctx, MockObjectMap *mock_object_map, uint64_t snap_id) { if (mock_image_ctx.object_map != nullptr) { EXPECT_CALL(mock_image_ctx, create_object_map(snap_id)) .WillOnce(Return(mock_object_map)); EXPECT_CALL(*mock_object_map, open(_)) .WillOnce(CompleteContext(0, mock_image_ctx.image_ctx->op_work_queue)); } } void expect_rollback_object_map(MockOperationImageCtx &mock_image_ctx, MockObjectMap &mock_object_map) { if (mock_image_ctx.object_map != nullptr) { EXPECT_CALL(mock_object_map, rollback(_, _)) .WillOnce(WithArg<1>(CompleteContext(0, mock_image_ctx.image_ctx->op_work_queue))); } } void expect_get_object_name(MockOperationImageCtx &mock_image_ctx, uint64_t object_num) { EXPECT_CALL(mock_image_ctx, get_object_name(object_num)) .WillOnce(Return("object-name-" + stringify(object_num))); } void expect_get_current_size(MockOperationImageCtx &mock_image_ctx, uint64_t size) { EXPECT_CALL(mock_image_ctx, get_current_size()) .WillOnce(Return(size)); } void expect_rollback_snap_id(MockOperationImageCtx &mock_image_ctx, const std::string &oid, int r) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.data_ctx), selfmanaged_snap_rollback(oid, _)) .WillOnce(Return(r)); } void expect_rollback(MockOperationImageCtx &mock_image_ctx, int r) { expect_get_current_size(mock_image_ctx, 1); expect_object_may_exist(mock_image_ctx, 0, true); expect_get_object_name(mock_image_ctx, 0); expect_rollback_snap_id(mock_image_ctx, "object-name-0", r); } void expect_create_object_map(MockOperationImageCtx &mock_image_ctx, MockObjectMap *mock_object_map) { EXPECT_CALL(mock_image_ctx, create_object_map(_)) .WillOnce(Return(mock_object_map)); } void expect_open_object_map(MockOperationImageCtx &mock_image_ctx, MockObjectMap &mock_object_map) { EXPECT_CALL(mock_object_map, open(_)) .WillOnce(CompleteContext(0, mock_image_ctx.image_ctx->op_work_queue)); } void expect_refresh_object_map(MockOperationImageCtx &mock_image_ctx, MockObjectMap &mock_object_map) { if (mock_image_ctx.object_map != nullptr) { expect_create_object_map(mock_image_ctx, &mock_object_map); expect_open_object_map(mock_image_ctx, mock_object_map); } } void expect_invalidate_cache(MockOperationImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.io_image_dispatcher, invalidate_cache(_)) .WillOnce(CompleteContext(r, mock_image_ctx.image_ctx->op_work_queue)); } int when_snap_rollback(MockOperationImageCtx &mock_image_ctx, const std::string &snap_name, uint64_t snap_id, uint64_t snap_size) { C_SaferCond cond_ctx; librbd::NoOpProgressContext prog_ctx; MockSnapshotRollbackRequest *req = new MockSnapshotRollbackRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), snap_name, snap_id, snap_size, prog_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } return cond_ctx.wait(); } }; TEST_F(TestMockOperationSnapshotRollbackRequest, Success) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; MockObjectMap mock_snap_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); InSequence seq; MockResizeRequest mock_resize_request; expect_append_op_event(mock_image_ctx, false, 0); expect_block_writes(mock_image_ctx, 0); expect_resize(mock_image_ctx, mock_resize_request, 0); expect_get_flags(mock_image_ctx, 123, 0); expect_get_snap_object_map(mock_image_ctx, &mock_snap_object_map, 123); expect_rollback_object_map(mock_image_ctx, mock_object_map); expect_rollback(mock_image_ctx, 0); expect_refresh_object_map(mock_image_ctx, mock_object_map); expect_invalidate_cache(mock_image_ctx, 0); expect_commit_op_event(mock_image_ctx, 0); expect_unblock_writes(mock_image_ctx); ASSERT_EQ(0, when_snap_rollback(mock_image_ctx, "snap", 123, 0)); } TEST_F(TestMockOperationSnapshotRollbackRequest, BlockWritesError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_append_op_event(mock_image_ctx, false, 0); expect_block_writes(mock_image_ctx, -EINVAL); expect_commit_op_event(mock_image_ctx, -EINVAL); expect_unblock_writes(mock_image_ctx); ASSERT_EQ(-EINVAL, when_snap_rollback(mock_image_ctx, "snap", 123, 0)); } TEST_F(TestMockOperationSnapshotRollbackRequest, SkipResize) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; MockObjectMap mock_snap_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); InSequence seq; expect_append_op_event(mock_image_ctx, false, 0); expect_block_writes(mock_image_ctx, 0); expect_get_image_size(mock_image_ctx, 345); expect_get_flags(mock_image_ctx, 123, 0); expect_get_snap_object_map(mock_image_ctx, &mock_snap_object_map, 123); expect_rollback_object_map(mock_image_ctx, mock_object_map); expect_rollback(mock_image_ctx, 0); expect_refresh_object_map(mock_image_ctx, mock_object_map); expect_invalidate_cache(mock_image_ctx, 0); expect_commit_op_event(mock_image_ctx, 0); expect_unblock_writes(mock_image_ctx); ASSERT_EQ(0, when_snap_rollback(mock_image_ctx, "snap", 123, 345)); } TEST_F(TestMockOperationSnapshotRollbackRequest, ResizeError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); InSequence seq; MockResizeRequest mock_resize_request; expect_append_op_event(mock_image_ctx, false, 0); expect_block_writes(mock_image_ctx, 0); expect_resize(mock_image_ctx, mock_resize_request, -EINVAL); expect_commit_op_event(mock_image_ctx, -EINVAL); expect_unblock_writes(mock_image_ctx); ASSERT_EQ(-EINVAL, when_snap_rollback(mock_image_ctx, "snap", 123, 0)); } TEST_F(TestMockOperationSnapshotRollbackRequest, RollbackObjectsError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; MockObjectMap mock_snap_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); InSequence seq; MockResizeRequest mock_resize_request; expect_append_op_event(mock_image_ctx, false, 0); expect_block_writes(mock_image_ctx, 0); expect_resize(mock_image_ctx, mock_resize_request, 0); expect_get_flags(mock_image_ctx, 123, 0); expect_get_snap_object_map(mock_image_ctx, &mock_snap_object_map, 123); expect_rollback_object_map(mock_image_ctx, mock_object_map); expect_rollback(mock_image_ctx, -EINVAL); expect_commit_op_event(mock_image_ctx, -EINVAL); expect_unblock_writes(mock_image_ctx); ASSERT_EQ(-EINVAL, when_snap_rollback(mock_image_ctx, "snap", 123, 0)); } TEST_F(TestMockOperationSnapshotRollbackRequest, InvalidateCacheError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); REQUIRE(ictx->cache); MockOperationImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; MockObjectMap mock_snap_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); InSequence seq; MockResizeRequest mock_resize_request; expect_append_op_event(mock_image_ctx, false, 0); expect_block_writes(mock_image_ctx, 0); expect_resize(mock_image_ctx, mock_resize_request, 0); expect_get_flags(mock_image_ctx, 123, 0); expect_get_snap_object_map(mock_image_ctx, &mock_snap_object_map, 123); expect_rollback_object_map(mock_image_ctx, mock_object_map); expect_rollback(mock_image_ctx, 0); expect_refresh_object_map(mock_image_ctx, mock_object_map); expect_invalidate_cache(mock_image_ctx, -EINVAL); expect_commit_op_event(mock_image_ctx, -EINVAL); expect_unblock_writes(mock_image_ctx); ASSERT_EQ(-EINVAL, when_snap_rollback(mock_image_ctx, "snap", 123, 0)); } } // namespace operation } // namespace librbd
13,800
36.502717
103
cc
null
ceph-main/src/test/librbd/operation/test_mock_SnapshotUnprotectRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "include/rados/librados.hpp" #include "common/bit_vector.hpp" #include "librbd/ImageState.h" #include "librbd/internal.h" #include "librbd/operation/SnapshotUnprotectRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" // template definitions #include "librbd/operation/SnapshotUnprotectRequest.cc" namespace librbd { namespace operation { using ::testing::_; using ::testing::DoAll; using ::testing::DoDefault; using ::testing::Return; using ::testing::SetArgReferee; using ::testing::SetArgPointee; using ::testing::StrEq; using ::testing::WithArg; class TestMockOperationSnapshotUnprotectRequest : public TestMockFixture { public: typedef SnapshotUnprotectRequest<MockImageCtx> MockSnapshotUnprotectRequest; void expect_get_snap_id(MockImageCtx &mock_image_ctx, uint64_t snap_id) { EXPECT_CALL(mock_image_ctx, get_snap_id(_, _)) .WillOnce(Return(snap_id)); } void expect_is_snap_unprotected(MockImageCtx &mock_image_ctx, bool is_unprotected, int r) { auto &expect = EXPECT_CALL(mock_image_ctx, is_snap_unprotected(_, _)); if (r < 0) { expect.WillOnce(Return(r)); } else { expect.WillOnce(DoAll(SetArgPointee<1>(is_unprotected), Return(0))); } } void expect_set_protection_status(MockImageCtx &mock_image_ctx, uint64_t snap_id, uint8_t status, int r) { bufferlist bl; encode(snap_id, bl); encode(status, bl); auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(mock_image_ctx.header_oid, _, StrEq("rbd"), StrEq("set_protection_status"), ContentsEqual(bl), _, _, _)); if (r < 0) { expect.WillOnce(Return(r)); } else { expect.WillOnce(DoDefault()); } } size_t expect_create_pool_io_contexts(MockImageCtx &mock_image_ctx) { librados::MockTestMemIoCtxImpl &io_ctx_impl = get_mock_io_ctx(mock_image_ctx.md_ctx); librados::MockTestMemRadosClient *rados_client = io_ctx_impl.get_mock_rados_client(); std::list<std::pair<int64_t, std::string> > pools; int r = rados_client->pool_list(pools); if (r < 0) { ADD_FAILURE() << "failed to list pools"; return 0; } EXPECT_CALL(*rados_client, create_ioctx(_, _)) .Times(pools.size()).WillRepeatedly(DoAll( GetReference(&io_ctx_impl), Return(&io_ctx_impl))); return pools.size(); } void expect_get_children(MockImageCtx &mock_image_ctx, size_t pools, int r) { bufferlist bl; std::set<std::string> children; encode(children, bl); auto &expect = EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(RBD_CHILDREN, _, StrEq("rbd"), StrEq("get_children"), _, _, _, _)); if (r < 0) { expect.WillRepeatedly(Return(r)); } else { expect.Times(pools).WillRepeatedly(DoAll( SetArgPointee<5>(bl), Return(0))); } } }; TEST_F(TestMockOperationSnapshotUnprotectRequest, Success) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_get_snap_id(mock_image_ctx, snap_id); expect_is_snap_unprotected(mock_image_ctx, false, 0); expect_set_protection_status(mock_image_ctx, snap_id, RBD_PROTECTION_STATUS_UNPROTECTING, 0); size_t pools = expect_create_pool_io_contexts(mock_image_ctx); expect_get_children(mock_image_ctx, pools, -ENOENT); expect_set_protection_status(mock_image_ctx, snap_id, RBD_PROTECTION_STATUS_UNPROTECTED, 0); C_SaferCond cond_ctx; MockSnapshotUnprotectRequest *req = new MockSnapshotUnprotectRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1"); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotUnprotectRequest, GetSnapIdMissing) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_get_snap_id(mock_image_ctx, CEPH_NOSNAP); C_SaferCond cond_ctx; MockSnapshotUnprotectRequest *req = new MockSnapshotUnprotectRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1"); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-ENOENT, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotUnprotectRequest, IsSnapUnprotectedError) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_get_snap_id(mock_image_ctx, ictx->snap_info.rbegin()->first); expect_is_snap_unprotected(mock_image_ctx, false, -EBADMSG); C_SaferCond cond_ctx; MockSnapshotUnprotectRequest *req = new MockSnapshotUnprotectRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1"); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EBADMSG, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotUnprotectRequest, SnapAlreadyUnprotected) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; expect_get_snap_id(mock_image_ctx, ictx->snap_info.rbegin()->first); expect_is_snap_unprotected(mock_image_ctx, true, 0); C_SaferCond cond_ctx; MockSnapshotUnprotectRequest *req = new MockSnapshotUnprotectRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1"); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotUnprotectRequest, SetProtectionStatusError) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_get_snap_id(mock_image_ctx, snap_id); expect_is_snap_unprotected(mock_image_ctx, false, 0); expect_set_protection_status(mock_image_ctx, snap_id, RBD_PROTECTION_STATUS_UNPROTECTING, -EINVAL); C_SaferCond cond_ctx; MockSnapshotUnprotectRequest *req = new MockSnapshotUnprotectRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1"); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationSnapshotUnprotectRequest, ChildrenExist) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap1")); ASSERT_EQ(0, ictx->state->refresh_if_required()); MockImageCtx mock_image_ctx(*ictx); expect_op_work_queue(mock_image_ctx); ::testing::InSequence seq; uint64_t snap_id = ictx->snap_info.rbegin()->first; expect_get_snap_id(mock_image_ctx, snap_id); expect_is_snap_unprotected(mock_image_ctx, false, 0); expect_set_protection_status(mock_image_ctx, snap_id, RBD_PROTECTION_STATUS_UNPROTECTING, 0); size_t pools = expect_create_pool_io_contexts(mock_image_ctx); expect_get_children(mock_image_ctx, pools, 0); expect_set_protection_status(mock_image_ctx, snap_id, RBD_PROTECTION_STATUS_PROTECTED, 0); C_SaferCond cond_ctx; MockSnapshotUnprotectRequest *req = new MockSnapshotUnprotectRequest( mock_image_ctx, &cond_ctx, cls::rbd::UserSnapshotNamespace(), "snap1"); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EBUSY, cond_ctx.wait()); } } // namespace operation } // namespace librbd
9,303
32.467626
79
cc
null
ceph-main/src/test/librbd/operation/test_mock_TrimRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/io/MockObjectDispatch.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "common/bit_vector.hpp" #include "librbd/AsyncRequest.h" #include "librbd/internal.h" #include "librbd/ObjectMap.h" #include "librbd/Utils.h" #include "librbd/operation/TrimRequest.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <boost/variant.hpp> namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace template<> struct AsyncRequest<librbd::MockTestImageCtx> { librbd::MockTestImageCtx& m_image_ctx; Context *on_finish; AsyncRequest(librbd::MockTestImageCtx& image_ctx, Context* on_finish) : m_image_ctx(image_ctx), on_finish(on_finish) { } virtual ~AsyncRequest() { } Context* create_callback_context() { return util::create_context_callback(this); } Context* create_async_callback_context() { return util::create_context_callback<AsyncRequest, &AsyncRequest::async_complete>(this); } void complete(int r) { if (should_complete(r)) { async_complete(r); } } void async_complete(int r) { on_finish->complete(r); delete this; } bool is_canceled() const { return false; } virtual void send() = 0; virtual bool should_complete(int r) = 0; }; namespace io { struct DiscardVisitor : public boost::static_visitor<ObjectDispatchSpec::DiscardRequest*> { ObjectDispatchSpec::DiscardRequest* operator()(ObjectDispatchSpec::DiscardRequest& discard) const { return &discard; } template <typename T> ObjectDispatchSpec::DiscardRequest* operator()(T& t) const { return nullptr; } }; } // namespace io } // namespace librbd // template definitions #include "librbd/AsyncObjectThrottle.cc" #include "librbd/operation/TrimRequest.cc" namespace librbd { namespace operation { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; class TestMockOperationTrimRequest : public TestMockFixture { public: typedef TrimRequest<MockTestImageCtx> MockTrimRequest; int create_snapshot(const char *snap_name) { librbd::ImageCtx *ictx; int r = open_image(m_image_name, &ictx); if (r < 0) { return r; } r = snap_create(*ictx, snap_name); if (r < 0) { return r; } r = snap_protect(*ictx, snap_name); if (r < 0) { return r; } close_image(ictx); return 0; } void expect_is_lock_owner(MockTestImageCtx &mock_image_ctx) { if (mock_image_ctx.exclusive_lock != nullptr) { EXPECT_CALL(*mock_image_ctx.exclusive_lock, is_lock_owner()) .WillRepeatedly(Return(true)); } } void expect_object_map_update(MockTestImageCtx &mock_image_ctx, uint64_t start_object, uint64_t end_object, uint8_t state, uint8_t current_state, bool updated, int ret_val) { if (mock_image_ctx.object_map != nullptr) { EXPECT_CALL(*mock_image_ctx.object_map, aio_update(CEPH_NOSNAP, start_object, end_object, state, boost::optional<uint8_t>(current_state), _, false, _)) .WillOnce(WithArg<7>(Invoke([&mock_image_ctx, updated, ret_val](Context *ctx) { if (updated) { mock_image_ctx.op_work_queue->queue(ctx, ret_val); } return updated; }))); } } void expect_get_parent_overlap(MockTestImageCtx &mock_image_ctx, uint64_t overlap) { EXPECT_CALL(mock_image_ctx, get_parent_overlap(CEPH_NOSNAP, _)) .WillOnce(WithArg<1>(Invoke([overlap](uint64_t *o) { *o = overlap; return 0; }))); } void expect_reduce_parent_overlap(MockTestImageCtx& mock_image_ctx, uint64_t overlap) { EXPECT_CALL(mock_image_ctx, reduce_parent_overlap(overlap, false)) .WillOnce(Return(std::make_pair(overlap, io::ImageArea::DATA))); } void expect_get_area_size(MockTestImageCtx& mock_image_ctx) { EXPECT_CALL(mock_image_ctx, get_area_size(io::ImageArea::CRYPTO_HEADER)) .WillOnce(Return(0)); } void expect_object_may_exist(MockTestImageCtx &mock_image_ctx, uint64_t object_no, bool exists) { if (mock_image_ctx.object_map != nullptr) { EXPECT_CALL(*mock_image_ctx.object_map, object_may_exist(object_no)) .WillOnce(Return(exists)); } } void expect_get_object_name(MockTestImageCtx &mock_image_ctx, uint64_t object_no, const std::string& oid) { EXPECT_CALL(mock_image_ctx, get_object_name(object_no)) .WillOnce(Return(oid)); } void expect_aio_remove(MockTestImageCtx &mock_image_ctx, const std::string& oid, int ret_val) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.data_ctx), remove(oid, _)) .WillOnce(Return(ret_val)); } void expect_object_discard(MockImageCtx &mock_image_ctx, io::MockObjectDispatch& mock_io_object_dispatch, uint64_t offset, uint64_t length, bool update_object_map, int r) { EXPECT_CALL(*mock_image_ctx.io_object_dispatcher, send(_)) .WillOnce(Invoke([&mock_image_ctx, offset, length, update_object_map, r] (io::ObjectDispatchSpec* spec) { auto discard = boost::apply_visitor(io::DiscardVisitor(), spec->request); ASSERT_TRUE(discard != nullptr); ASSERT_EQ(offset, discard->object_off); ASSERT_EQ(length, discard->object_len); int flags = 0; if (!update_object_map) { flags = io::OBJECT_DISCARD_FLAG_DISABLE_OBJECT_MAP_UPDATE; } ASSERT_EQ(flags, discard->discard_flags); spec->dispatch_result = io::DISPATCH_RESULT_COMPLETE; mock_image_ctx.op_work_queue->queue(&spec->dispatcher_ctx, r); })); } }; TEST_F(TestMockOperationTrimRequest, SuccessRemove) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); expect_is_lock_owner(mock_image_ctx); InSequence seq; EXPECT_CALL(mock_image_ctx, get_stripe_period()).WillOnce(Return(ictx->get_object_size())); EXPECT_CALL(mock_image_ctx, get_stripe_count()).WillOnce(Return(ictx->get_stripe_count())); // pre expect_object_map_update(mock_image_ctx, 0, 1, OBJECT_PENDING, OBJECT_EXISTS, true, 0); // copy-up expect_get_area_size(mock_image_ctx); expect_get_parent_overlap(mock_image_ctx, 0); expect_reduce_parent_overlap(mock_image_ctx, 0); // remove expect_object_may_exist(mock_image_ctx, 0, true); expect_get_object_name(mock_image_ctx, 0, "object0"); expect_aio_remove(mock_image_ctx, "object0", 0); // post expect_object_map_update(mock_image_ctx, 0, 1, OBJECT_NONEXISTENT, OBJECT_PENDING, true, 0); C_SaferCond cond_ctx; librbd::NoOpProgressContext progress_ctx; MockTrimRequest *req = new MockTrimRequest( mock_image_ctx, &cond_ctx, m_image_size, 0, progress_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationTrimRequest, SuccessCopyUp) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING) ASSERT_EQ(0, create_snapshot("snap1")); int order = 22; uint64_t features; ASSERT_TRUE(::get_features(&features)); std::string clone_name = get_temp_image_name(); ASSERT_EQ(0, librbd::clone(m_ioctx, m_image_name.c_str(), "snap1", m_ioctx, clone_name.c_str(), features, &order, 0, 0)); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(clone_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap")); MockTestImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); expect_is_lock_owner(mock_image_ctx); InSequence seq; EXPECT_CALL(mock_image_ctx, get_stripe_period()).WillOnce(Return(ictx->get_object_size())); EXPECT_CALL(mock_image_ctx, get_stripe_count()).WillOnce(Return(ictx->get_stripe_count())); // pre expect_object_map_update(mock_image_ctx, 0, 2, OBJECT_PENDING, OBJECT_EXISTS, true, 0); // copy-up io::MockObjectDispatch mock_io_object_dispatch; expect_get_area_size(mock_image_ctx); expect_get_parent_overlap(mock_image_ctx, ictx->get_object_size()); expect_reduce_parent_overlap(mock_image_ctx, ictx->get_object_size()); expect_get_object_name(mock_image_ctx, 0, "object0"); expect_object_discard(mock_image_ctx, mock_io_object_dispatch, 0, ictx->get_object_size(), false, 0); // remove expect_object_may_exist(mock_image_ctx, 1, true); expect_get_object_name(mock_image_ctx, 1, "object1"); expect_aio_remove(mock_image_ctx, "object1", 0); // post expect_object_map_update(mock_image_ctx, 0, 2, OBJECT_NONEXISTENT, OBJECT_PENDING, true, 0); C_SaferCond cond_ctx; librbd::NoOpProgressContext progress_ctx; MockTrimRequest *req = new MockTrimRequest( mock_image_ctx, &cond_ctx, 2 * ictx->get_object_size(), 0, progress_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationTrimRequest, SuccessBoundary) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); expect_is_lock_owner(mock_image_ctx); InSequence seq; EXPECT_CALL(mock_image_ctx, get_stripe_period()).WillOnce(Return(ictx->get_object_size())); EXPECT_CALL(mock_image_ctx, get_stripe_count()).WillOnce(Return(ictx->get_stripe_count())); // boundary io::MockObjectDispatch mock_io_object_dispatch; expect_object_discard(mock_image_ctx, mock_io_object_dispatch, 1, ictx->get_object_size() - 1, true, 0); C_SaferCond cond_ctx; librbd::NoOpProgressContext progress_ctx; MockTrimRequest *req = new MockTrimRequest( mock_image_ctx, &cond_ctx, ictx->get_object_size(), 1, progress_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(0, cond_ctx.wait()); } TEST_F(TestMockOperationTrimRequest, SuccessNoOp) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); } TEST_F(TestMockOperationTrimRequest, RemoveError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); expect_is_lock_owner(mock_image_ctx); InSequence seq; EXPECT_CALL(mock_image_ctx, get_stripe_period()).WillOnce(Return(ictx->get_object_size())); EXPECT_CALL(mock_image_ctx, get_stripe_count()).WillOnce(Return(ictx->get_stripe_count())); // pre expect_object_map_update(mock_image_ctx, 0, 1, OBJECT_PENDING, OBJECT_EXISTS, false, 0); // copy-up expect_get_area_size(mock_image_ctx); expect_get_parent_overlap(mock_image_ctx, 0); expect_reduce_parent_overlap(mock_image_ctx, 0); // remove expect_object_may_exist(mock_image_ctx, 0, true); expect_get_object_name(mock_image_ctx, 0, "object0"); expect_aio_remove(mock_image_ctx, "object0", -EPERM); C_SaferCond cond_ctx; librbd::NoOpProgressContext progress_ctx; MockTrimRequest *req = new MockTrimRequest( mock_image_ctx, &cond_ctx, m_image_size, 0, progress_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EPERM, cond_ctx.wait()); } TEST_F(TestMockOperationTrimRequest, CopyUpError) { REQUIRE_FEATURE(RBD_FEATURE_LAYERING) ASSERT_EQ(0, create_snapshot("snap1")); int order = 22; uint64_t features; ASSERT_TRUE(::get_features(&features)); std::string clone_name = get_temp_image_name(); ASSERT_EQ(0, librbd::clone(m_ioctx, m_image_name.c_str(), "snap1", m_ioctx, clone_name.c_str(), features, &order, 0, 0)); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(clone_name, &ictx)); ASSERT_EQ(0, snap_create(*ictx, "snap")); MockTestImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); expect_is_lock_owner(mock_image_ctx); InSequence seq; EXPECT_CALL(mock_image_ctx, get_stripe_period()).WillOnce(Return(ictx->get_object_size())); EXPECT_CALL(mock_image_ctx, get_stripe_count()).WillOnce(Return(ictx->get_stripe_count())); // pre expect_object_map_update(mock_image_ctx, 0, 2, OBJECT_PENDING, OBJECT_EXISTS, false, 0); // copy-up io::MockObjectDispatch mock_io_object_dispatch; expect_get_area_size(mock_image_ctx); expect_get_parent_overlap(mock_image_ctx, ictx->get_object_size()); expect_reduce_parent_overlap(mock_image_ctx, ictx->get_object_size()); expect_get_object_name(mock_image_ctx, 0, "object0"); expect_object_discard(mock_image_ctx, mock_io_object_dispatch, 0, ictx->get_object_size(), false, -EINVAL); C_SaferCond cond_ctx; librbd::NoOpProgressContext progress_ctx; MockTrimRequest *req = new MockTrimRequest( mock_image_ctx, &cond_ctx, 2 * ictx->get_object_size(), 0, progress_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } TEST_F(TestMockOperationTrimRequest, BoundaryError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; MockJournal mock_journal; MockObjectMap mock_object_map; initialize_features(ictx, mock_image_ctx, mock_exclusive_lock, mock_journal, mock_object_map); expect_op_work_queue(mock_image_ctx); expect_is_lock_owner(mock_image_ctx); InSequence seq; EXPECT_CALL(mock_image_ctx, get_stripe_period()).WillOnce(Return(ictx->get_object_size())); EXPECT_CALL(mock_image_ctx, get_stripe_count()).WillOnce(Return(ictx->get_stripe_count())); // boundary io::MockObjectDispatch mock_io_object_dispatch; expect_object_discard(mock_image_ctx, mock_io_object_dispatch, 1, ictx->get_object_size() - 1, true, -EINVAL); C_SaferCond cond_ctx; librbd::NoOpProgressContext progress_ctx; MockTrimRequest *req = new MockTrimRequest( mock_image_ctx, &cond_ctx, ictx->get_object_size(), 1, progress_ctx); { std::shared_lock owner_locker{mock_image_ctx.owner_lock}; req->send(); } ASSERT_EQ(-EINVAL, cond_ctx.wait()); } } // namespace operation } // namespace librbd
16,781
32.97166
93
cc
null
ceph-main/src/test/librbd/trash/test_mock_MoveRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockExclusiveLock.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/MockImageState.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "include/rbd/librbd.hpp" #include "librbd/Utils.h" #include "librbd/trash/MoveRequest.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { static MockTestImageCtx *s_instance; static MockTestImageCtx *create(const std::string &image_name, const std::string &image_id, const char *snap, librados::IoCtx& p, bool read_only) { ceph_assert(s_instance != nullptr); s_instance->construct(image_name, image_id); return s_instance; } MOCK_METHOD2(construct, void(const std::string&, const std::string&)); MockTestImageCtx(librbd::ImageCtx &image_ctx) : librbd::MockImageCtx(image_ctx) { s_instance = this; } }; MockTestImageCtx *MockTestImageCtx::s_instance = nullptr; } // anonymous namespace } // namespace librbd #include "librbd/trash/MoveRequest.cc" namespace librbd { namespace trash { using ::testing::_; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; struct TestMockTrashMoveRequest : public TestMockFixture { typedef MoveRequest<librbd::MockTestImageCtx> MockMoveRequest; void expect_trash_add(MockTestImageCtx &mock_image_ctx, const std::string& image_id, cls::rbd::TrashImageSource trash_image_source, const std::string& name, const utime_t& end_time, int r) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(StrEq("rbd_trash"), _, StrEq("rbd"), StrEq("trash_add"), _, _, _, _)) .WillOnce(WithArg<4>(Invoke([=](bufferlist& in_bl) { std::string id; cls::rbd::TrashImageSpec trash_image_spec; auto bl_it = in_bl.cbegin(); decode(id, bl_it); decode(trash_image_spec, bl_it); EXPECT_EQ(id, image_id); EXPECT_EQ(trash_image_spec.source, trash_image_source); EXPECT_EQ(trash_image_spec.name, name); EXPECT_EQ(trash_image_spec.deferment_end_time, end_time); return r; }))); } void expect_aio_remove(MockTestImageCtx &mock_image_ctx, const std::string& oid, int r) { EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), remove(oid, _)) .WillOnce(Return(r)); } void expect_dir_remove(MockTestImageCtx& mock_image_ctx, const std::string& name, const std::string& id, int r) { bufferlist in_bl; encode(name, in_bl); encode(id, in_bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(StrEq("rbd_directory"), _, StrEq("rbd"), StrEq("dir_remove_image"), ContentsEqual(in_bl), _, _, _)) .WillOnce(Return(r)); } }; TEST_F(TestMockTrashMoveRequest, Success) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } expect_op_work_queue(mock_image_ctx); InSequence seq; utime_t delete_time{ceph_clock_now()}; expect_trash_add(mock_image_ctx, "image id", cls::rbd::TRASH_IMAGE_SOURCE_USER, "image name", delete_time, 0); expect_aio_remove(mock_image_ctx, util::id_obj_name("image name"), 0); expect_dir_remove(mock_image_ctx, "image name", "image id", 0); C_SaferCond ctx; cls::rbd::TrashImageSpec trash_image_spec{ cls::rbd::TRASH_IMAGE_SOURCE_USER, "image name", delete_time, delete_time}; auto req = MockMoveRequest::create(mock_image_ctx.md_ctx, "image id", trash_image_spec, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockTrashMoveRequest, TrashAddError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } expect_op_work_queue(mock_image_ctx); InSequence seq; utime_t delete_time{ceph_clock_now()}; expect_trash_add(mock_image_ctx, "image id", cls::rbd::TRASH_IMAGE_SOURCE_USER, "image name", delete_time, -EPERM); C_SaferCond ctx; cls::rbd::TrashImageSpec trash_image_spec{ cls::rbd::TRASH_IMAGE_SOURCE_USER, "image name", delete_time, delete_time}; auto req = MockMoveRequest::create(mock_image_ctx.md_ctx, "image id", trash_image_spec, &ctx); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } TEST_F(TestMockTrashMoveRequest, RemoveIdError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } expect_op_work_queue(mock_image_ctx); InSequence seq; utime_t delete_time{ceph_clock_now()}; expect_trash_add(mock_image_ctx, "image id", cls::rbd::TRASH_IMAGE_SOURCE_USER, "image name", delete_time, 0); expect_aio_remove(mock_image_ctx, util::id_obj_name("image name"), -EPERM); C_SaferCond ctx; cls::rbd::TrashImageSpec trash_image_spec{ cls::rbd::TRASH_IMAGE_SOURCE_USER, "image name", delete_time, delete_time}; auto req = MockMoveRequest::create(mock_image_ctx.md_ctx, "image id", trash_image_spec, &ctx); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } TEST_F(TestMockTrashMoveRequest, DirectoryRemoveError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockExclusiveLock mock_exclusive_lock; if (ictx->test_features(RBD_FEATURE_EXCLUSIVE_LOCK)) { mock_image_ctx.exclusive_lock = &mock_exclusive_lock; } expect_op_work_queue(mock_image_ctx); InSequence seq; utime_t delete_time{ceph_clock_now()}; expect_trash_add(mock_image_ctx, "image id", cls::rbd::TRASH_IMAGE_SOURCE_USER, "image name", delete_time, 0); expect_aio_remove(mock_image_ctx, util::id_obj_name("image name"), 0); expect_dir_remove(mock_image_ctx, "image name", "image id", -EPERM); C_SaferCond ctx; cls::rbd::TrashImageSpec trash_image_spec{ cls::rbd::TRASH_IMAGE_SOURCE_USER, "image name", delete_time, delete_time}; auto req = MockMoveRequest::create(mock_image_ctx.md_ctx, "image id", trash_image_spec, &ctx); req->send(); ASSERT_EQ(-EPERM, ctx.wait()); } } // namespace trash } // namespace librbd
7,803
32.78355
88
cc
null
ceph-main/src/test/librbd/trash/test_mock_RemoveRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockExclusiveLock.h" #include "test/librbd/mock/MockImageCtx.h" #include "test/librbd/mock/MockImageState.h" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "include/rbd/librbd.hpp" #include "librbd/Utils.h" #include "librbd/image/TypeTraits.h" #include "librbd/image/RemoveRequest.h" #include "librbd/internal.h" #include "librbd/trash/RemoveRequest.h" namespace librbd { namespace { struct MockTestImageCtx : public MockImageCtx { MockTestImageCtx(ImageCtx &image_ctx) : MockImageCtx(image_ctx) { } }; } // anonymous namespace namespace image { // template <> // struct TypeTraits<MockTestImageCtx> { // typedef librbd::MockContextWQ ContextWQ; // }; template <> class RemoveRequest<MockTestImageCtx> { private: typedef ::librbd::image::TypeTraits<MockTestImageCtx> TypeTraits; typedef typename TypeTraits::ContextWQ ContextWQ; public: static RemoveRequest *s_instance; static RemoveRequest *create(librados::IoCtx &ioctx, const std::string &image_name, const std::string &image_id, bool force, bool from_trash_remove, ProgressContext &prog_ctx, ContextWQ *op_work_queue, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } static RemoveRequest *create(librados::IoCtx &ioctx, MockTestImageCtx *image_ctx, bool force, bool from_trash_remove, ProgressContext &prog_ctx, ContextWQ *op_work_queue, Context *on_finish) { ceph_assert(s_instance != nullptr); s_instance->on_finish = on_finish; return s_instance; } Context *on_finish = nullptr; RemoveRequest() { s_instance = this; } MOCK_METHOD0(send, void()); }; RemoveRequest<MockTestImageCtx> *RemoveRequest<MockTestImageCtx>::s_instance; } // namespace image } // namespace librbd #include "librbd/trash/RemoveRequest.cc" namespace librbd { namespace trash { using ::testing::_; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; struct TestMockTrashRemoveRequest : public TestMockFixture { typedef RemoveRequest<librbd::MockTestImageCtx> MockRemoveRequest; typedef image::RemoveRequest<librbd::MockTestImageCtx> MockImageRemoveRequest; NoOpProgressContext m_prog_ctx; void expect_set_state(MockTestImageCtx& mock_image_ctx, cls::rbd::TrashImageState trash_set_state, cls::rbd::TrashImageState trash_expect_state, int r) { bufferlist in_bl; encode(mock_image_ctx.id, in_bl); encode(trash_set_state, in_bl); encode(trash_expect_state, in_bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(StrEq("rbd_trash"), _, StrEq("rbd"), StrEq("trash_state_set"), ContentsEqual(in_bl), _, _, _)) .WillOnce(Return(r)); } void expect_set_deleting_state(MockTestImageCtx& mock_image_ctx, int r) { expect_set_state(mock_image_ctx, cls::rbd::TRASH_IMAGE_STATE_REMOVING, cls::rbd::TRASH_IMAGE_STATE_NORMAL, r); } void expect_restore_normal_state(MockTestImageCtx& mock_image_ctx, int r) { expect_set_state(mock_image_ctx, cls::rbd::TRASH_IMAGE_STATE_NORMAL, cls::rbd::TRASH_IMAGE_STATE_REMOVING, r); } void expect_close_image(MockTestImageCtx &mock_image_ctx, int r) { EXPECT_CALL(*mock_image_ctx.state, close(_)) .WillOnce(Invoke([r](Context *on_finish) { on_finish->complete(r); })); } void expect_remove_image(MockImageRemoveRequest& mock_image_remove_request, int r) { EXPECT_CALL(mock_image_remove_request, send()) .WillOnce(Invoke([&mock_image_remove_request, r]() { mock_image_remove_request.on_finish->complete(r); })); } void expect_remove_trash_entry(MockTestImageCtx& mock_image_ctx, int r) { bufferlist in_bl; encode(mock_image_ctx.id, in_bl); EXPECT_CALL(get_mock_io_ctx(mock_image_ctx.md_ctx), exec(StrEq("rbd_trash"), _, StrEq("rbd"), StrEq("trash_remove"), ContentsEqual(in_bl), _, _, _)) .WillOnce(Return(r)); } }; TEST_F(TestMockTrashRemoveRequest, Success) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockImageRemoveRequest mock_image_remove_request; InSequence seq; expect_set_deleting_state(mock_image_ctx, 0); expect_remove_image(mock_image_remove_request, 0); expect_remove_trash_entry(mock_image_ctx, 0); C_SaferCond ctx; auto req = MockRemoveRequest::create(mock_image_ctx.md_ctx, &mock_image_ctx, nullptr, false, m_prog_ctx, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } TEST_F(TestMockTrashRemoveRequest, SetDeletingStateError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockImageRemoveRequest mock_image_remove_request; InSequence seq; expect_set_deleting_state(mock_image_ctx, -EINVAL); expect_close_image(mock_image_ctx, 0); C_SaferCond ctx; auto req = MockRemoveRequest::create(mock_image_ctx.md_ctx, &mock_image_ctx, nullptr, false, m_prog_ctx, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockTrashRemoveRequest, RemoveImageError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockImageRemoveRequest mock_image_remove_request; InSequence seq; expect_set_deleting_state(mock_image_ctx, 0); expect_remove_image(mock_image_remove_request, -EINVAL); expect_restore_normal_state(mock_image_ctx, 0); C_SaferCond ctx; auto req = MockRemoveRequest::create(mock_image_ctx.md_ctx, &mock_image_ctx, nullptr, false, m_prog_ctx, &ctx); req->send(); ASSERT_EQ(-EINVAL, ctx.wait()); } TEST_F(TestMockTrashRemoveRequest, RemoveTrashEntryError) { REQUIRE_FORMAT_V2(); librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockTestImageCtx mock_image_ctx(*ictx); MockImageRemoveRequest mock_image_remove_request; InSequence seq; expect_set_deleting_state(mock_image_ctx, 0); expect_remove_image(mock_image_remove_request, 0); expect_remove_trash_entry(mock_image_ctx, -EINVAL); C_SaferCond ctx; auto req = MockRemoveRequest::create(mock_image_ctx.md_ctx, &mock_image_ctx, nullptr, false, m_prog_ctx, &ctx); req->send(); ASSERT_EQ(0, ctx.wait()); } } // namespace trash } // namespace librbd
7,328
30.727273
83
cc
null
ceph-main/src/test/librbd/watcher/test_mock_RewatchRequest.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "test/librbd/test_mock_fixture.h" #include "include/rados/librados.hpp" #include "test/librados_test_stub/MockTestMemIoCtxImpl.h" #include "test/librados_test_stub/MockTestMemRadosClient.h" #include "test/librbd/test_support.h" #include "test/librbd/mock/MockImageCtx.h" #include "librados/AioCompletionImpl.h" #include "librbd/watcher/RewatchRequest.h" namespace librbd { namespace watcher { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::WithArg; using ::testing::WithArgs; struct TestMockWatcherRewatchRequest : public TestMockFixture { typedef RewatchRequest MockRewatchRequest; TestMockWatcherRewatchRequest() = default; void expect_aio_watch(MockImageCtx &mock_image_ctx, int r) { librados::MockTestMemIoCtxImpl &mock_io_ctx(get_mock_io_ctx( mock_image_ctx.md_ctx)); EXPECT_CALL(mock_io_ctx, aio_watch(mock_image_ctx.header_oid, _, _, _)) .WillOnce(DoAll(WithArgs<1, 2>(Invoke([&mock_image_ctx, &mock_io_ctx, r](librados::AioCompletionImpl *c, uint64_t *cookie) { *cookie = 234; c->get(); mock_image_ctx.image_ctx->op_work_queue->queue(new LambdaContext([&mock_io_ctx, c](int r) { mock_io_ctx.get_mock_rados_client()->finish_aio_completion(c, r); }), r); })), Return(0))); } void expect_aio_unwatch(MockImageCtx &mock_image_ctx, int r) { librados::MockTestMemIoCtxImpl &mock_io_ctx(get_mock_io_ctx( mock_image_ctx.md_ctx)); EXPECT_CALL(mock_io_ctx, aio_unwatch(m_watch_handle, _)) .WillOnce(DoAll(Invoke([&mock_image_ctx, &mock_io_ctx, r](uint64_t handle, librados::AioCompletionImpl *c) { c->get(); mock_image_ctx.image_ctx->op_work_queue->queue(new LambdaContext([&mock_io_ctx, c](int r) { mock_io_ctx.get_mock_rados_client()->finish_aio_completion(c, r); }), r); }), Return(0))); } struct WatchCtx : public librados::WatchCtx2 { void handle_notify(uint64_t, uint64_t, uint64_t, ceph::bufferlist&) override { ceph_abort(); } void handle_error(uint64_t, int) override { ceph_abort(); } }; ceph::shared_mutex m_watch_lock = ceph::make_shared_mutex("watch_lock"); WatchCtx m_watch_ctx; uint64_t m_watch_handle = 123; }; TEST_F(TestMockWatcherRewatchRequest, Success) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); InSequence seq; expect_aio_unwatch(mock_image_ctx, 0); expect_aio_watch(mock_image_ctx, 0); C_SaferCond ctx; MockRewatchRequest *req = MockRewatchRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.header_oid, m_watch_lock, &m_watch_ctx, &m_watch_handle, &ctx); { std::unique_lock watch_locker{m_watch_lock}; req->send(); } ASSERT_EQ(0, ctx.wait()); ASSERT_EQ(234U, m_watch_handle); } TEST_F(TestMockWatcherRewatchRequest, UnwatchError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); InSequence seq; expect_aio_unwatch(mock_image_ctx, -EINVAL); expect_aio_watch(mock_image_ctx, 0); C_SaferCond ctx; MockRewatchRequest *req = MockRewatchRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.header_oid, m_watch_lock, &m_watch_ctx, &m_watch_handle, &ctx); { std::unique_lock watch_locker{m_watch_lock}; req->send(); } ASSERT_EQ(0, ctx.wait()); ASSERT_EQ(234U, m_watch_handle); } TEST_F(TestMockWatcherRewatchRequest, WatchBlocklist) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); InSequence seq; expect_aio_unwatch(mock_image_ctx, 0); expect_aio_watch(mock_image_ctx, -EBLOCKLISTED); C_SaferCond ctx; MockRewatchRequest *req = MockRewatchRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.header_oid, m_watch_lock, &m_watch_ctx, &m_watch_handle, &ctx); { std::unique_lock watch_locker{m_watch_lock}; req->send(); } ASSERT_EQ(-EBLOCKLISTED, ctx.wait()); ASSERT_EQ(0U, m_watch_handle); } TEST_F(TestMockWatcherRewatchRequest, WatchDNE) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); InSequence seq; expect_aio_unwatch(mock_image_ctx, 0); expect_aio_watch(mock_image_ctx, -ENOENT); C_SaferCond ctx; MockRewatchRequest *req = MockRewatchRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.header_oid, m_watch_lock, &m_watch_ctx, &m_watch_handle, &ctx); { std::unique_lock watch_locker{m_watch_lock}; req->send(); } ASSERT_EQ(-ENOENT, ctx.wait()); ASSERT_EQ(0U, m_watch_handle); } TEST_F(TestMockWatcherRewatchRequest, WatchError) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); InSequence seq; expect_aio_unwatch(mock_image_ctx, 0); expect_aio_watch(mock_image_ctx, -EINVAL); C_SaferCond ctx; MockRewatchRequest *req = MockRewatchRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.header_oid, m_watch_lock, &m_watch_ctx, &m_watch_handle, &ctx); { std::unique_lock watch_locker{m_watch_lock}; req->send(); } ASSERT_EQ(-EINVAL, ctx.wait()); ASSERT_EQ(0U, m_watch_handle); } TEST_F(TestMockWatcherRewatchRequest, InvalidWatchHandler) { librbd::ImageCtx *ictx; ASSERT_EQ(0, open_image(m_image_name, &ictx)); MockImageCtx mock_image_ctx(*ictx); InSequence seq; expect_aio_watch(mock_image_ctx, 0); m_watch_handle = 0; C_SaferCond ctx; MockRewatchRequest *req = MockRewatchRequest::create(mock_image_ctx.md_ctx, mock_image_ctx.header_oid, m_watch_lock, &m_watch_ctx, &m_watch_handle, &ctx); { std::unique_lock watch_locker{m_watch_lock}; req->send(); } ASSERT_EQ(0, ctx.wait()); ASSERT_EQ(234U, m_watch_handle); } } // namespace watcher } // namespace librbd
8,036
34.25
130
cc
null
ceph-main/src/test/mds/TestMDSAuthCaps.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2012 Inktank * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include "include/stringify.h" #include "mds/MDSAuthCaps.h" #include "gtest/gtest.h" using namespace std; entity_addr_t addr; string fsnamecap = "fsname=a"; string pathcap = "path=/dir1"; string rscap = "root_squash"; string uidcap = "uid=1000"; string gidscap = "gids=1000,1001,1002"; vector<string> parse_good = { "allow rw uid=1 gids=1", "allow * path=\"/foo\"", "allow * path=/foo", "allow * path=/foo-bar_baz", "allow * path=\"/foo bar/baz\"", "allow * uid=1", "allow * path=\"/foo\" uid=1", "allow *", "allow r", "allow rw", "allow r, allow rw path=/foo", "allow r, allow * uid=1", "allow r ,allow * uid=1", "allow r ;allow * uid=1", "allow r ; allow * uid=1", "allow r ; allow * uid=1", "allow r uid=1 gids=1,2,3, allow * uid=2", "allow r network 1.2.3.4/8", "allow rw path=/foo uid=1 gids=1,2,3 network 2.3.4.5/16", // Following are all types of MDS caps, or in other words, all // (mathematical) combinations of fsnamecap, pathcap, rscap, uidcap, and // gidscaps. "allow rw " + fsnamecap, "allow rw " + pathcap, "allow rw " + rscap, "allow rw " + uidcap, "allow rw " + gidscap, "allow rw " + fsnamecap + " " + pathcap, "allow rw " + fsnamecap + " " + rscap, "allow rw " + fsnamecap + " " + uidcap, "allow rw " + fsnamecap + " " + gidscap, "allow rw " + pathcap + " " + rscap, "allow rw " + pathcap + " " + uidcap, "allow rw " + pathcap + " " + gidscap, "allow rw " + rscap + " " + uidcap, "allow rw " + rscap + " " + gidscap, "allow rw " + uidcap + " " + gidscap, "allow rw " + fsnamecap + " " + pathcap + " " + rscap, "allow rw " + fsnamecap + " " + pathcap + " " + uidcap, "allow rw " + fsnamecap + " " + pathcap + " " + gidscap, "allow rw " + fsnamecap + " " + rscap + " " + uidcap, "allow rw " + fsnamecap + " " + rscap + " " + gidscap, "allow rw " + fsnamecap + " " + uidcap + " " + gidscap, "allow rw " + pathcap + " " + rscap + " " + uidcap, "allow rw " + pathcap + " " + rscap + " " + gidscap, "allow rw " + pathcap + " " + uidcap + " " + gidscap, "allow rw " + rscap + " " + uidcap + " " + gidscap, "allow rw " + fsnamecap + " " + pathcap + " " + rscap + " " + uidcap, "allow rw " + fsnamecap + " " + pathcap + " " + rscap + " " + gidscap, "allow rw " + fsnamecap + " " + pathcap + " " + uidcap + " " + gidscap, "allow rw " + fsnamecap + " " + rscap + " " + uidcap + " " + gidscap, "allow rw " + pathcap + " " + rscap + " " + uidcap + " " + gidscap, "allow rw " + fsnamecap + " " + pathcap + " " + rscap + " " + uidcap + " " + gidscap }; TEST(MDSAuthCaps, ParseGood) { for (auto str : parse_good) { MDSAuthCaps cap; std::cout << "Testing good input: '" << str << "'" << std::endl; ASSERT_TRUE(cap.parse(str, &cout)); } } TEST(MDSAuthCaps, ParseDumpReparseCaps) { for (auto str : parse_good) { MDSAuthCaps cap1; ASSERT_TRUE(cap1.parse(str, &cout)); std::cout << "Testing by parsing caps, dumping to string, reparsing " "string and then redumping and checking strings from " "first and second dumps: '" << str << "'" << std::endl; // Convert cap object to string, reparse and check if converting again // gives same string as before. MDSAuthCaps cap2; std::ostringstream cap1_ostream; cap1_ostream << cap1; string cap1_str = cap1_ostream.str(); // Removing "MDSAuthCaps[" from cap1_str cap1_str.replace(0, 12, ""); // Removing "]" from cap1_str cap1_str.replace(cap1_str.length() - 1, 1, ""); ASSERT_TRUE(cap2.parse(cap1_str, &cout)); std::ostringstream cap2_ostream; cap2_ostream << cap2; ASSERT_TRUE(cap1_ostream.str().compare(cap2_ostream.str()) == 0); } } const char *parse_bad[] = { "allow r poolfoo", "allow r w", "ALLOW r", "allow w", "allow rwx,", "allow rwx x", "allow r pool foo r", "allow wwx pool taco", "allow wwx pool taco^funny&chars", "allow rwx pool 'weird name''", "allow rwx object_prefix \"beforepool\" pool weird", "allow rwx auid 123 pool asdf", "allow xrwx pool foo,, allow r pool bar", ";allow rwx pool foo rwx ; allow r pool bar", "allow rwx pool foo ;allow r pool bar gibberish", "allow rwx auid 123 pool asdf namespace=foo", "allow rwx auid 123 namespace", "allow rwx namespace", "allow namespace", "allow namespace=foo", "allow rwx auid 123 namespace asdf", "allow wwx pool ''", "allow rw uid=123 gids=asdf", "allow rw uid=123 gids=1,2,asdf", 0 }; TEST(MDSAuthCaps, ParseBad) { for (int i=0; parse_bad[i]; i++) { string str = parse_bad[i]; MDSAuthCaps cap; std::cout << "Testing bad input: '" << str << "'" << std::endl; ASSERT_FALSE(cap.parse(str, &cout)); // error message from parse() doesn't have newline char at the end of it std::cout << std::endl; } } TEST(MDSAuthCaps, AllowAll) { MDSAuthCaps cap; ASSERT_FALSE(cap.allow_all()); ASSERT_TRUE(cap.parse("allow r", NULL)); ASSERT_FALSE(cap.allow_all()); cap = MDSAuthCaps(); ASSERT_TRUE(cap.parse("allow rw", NULL)); ASSERT_FALSE(cap.allow_all()); cap = MDSAuthCaps(); ASSERT_TRUE(cap.parse("allow", NULL)); ASSERT_FALSE(cap.allow_all()); cap = MDSAuthCaps(); ASSERT_TRUE(cap.parse("allow *", NULL)); ASSERT_TRUE(cap.allow_all()); ASSERT_TRUE(cap.is_capable("foo/bar", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); } TEST(MDSAuthCaps, AllowUid) { MDSAuthCaps cap; ASSERT_TRUE(cap.parse("allow * uid=10", NULL)); ASSERT_FALSE(cap.allow_all()); // uid/gid must be valid ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0777, 0, 0, NULL, MAY_READ, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 0, 0777, 10, 0, NULL, MAY_READ, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 0, 0777, 10, 10, NULL, MAY_READ, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0777, 12, 12, NULL, MAY_READ, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 0, 0777, 10, 13, NULL, MAY_READ, 0, 0, addr)); } TEST(MDSAuthCaps, AllowUidGid) { MDSAuthCaps cap; ASSERT_TRUE(cap.parse("allow * uid=10 gids=10,11,12; allow * uid=12 gids=12,10", NULL)); ASSERT_FALSE(cap.allow_all()); // uid/gid must be valid ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0777, 0, 0, NULL, MAY_READ, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0777, 10, 0, NULL, MAY_READ, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0777, 9, 10, NULL, MAY_READ, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 0, 0777, 10, 10, NULL, MAY_READ, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 0, 0777, 12, 12, NULL, MAY_READ, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0777, 10, 13, NULL, MAY_READ, 0, 0, addr)); // user ASSERT_TRUE(cap.is_capable("foo", 10, 10, 0500, 10, 11, NULL, MAY_READ, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 10, 10, 0500, 10, 11, NULL, MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 10, 10, 0500, 10, 11, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 10, 10, 0700, 10, 11, NULL, MAY_READ, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 10, 10, 0700, 10, 11, NULL, MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 10, 10, 0700, 10, 10, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 10, 0, 0700, 10, 10, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 12, 0, 0700, 10, 10, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 12, 0, 0700, 12, 12, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0700, 10, 10, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); // group vector<uint64_t> glist10; glist10.push_back(10); vector<uint64_t> dglist10; dglist10.push_back(8); dglist10.push_back(10); vector<uint64_t> glist11; glist11.push_back(11); vector<uint64_t> glist12; glist12.push_back(12); ASSERT_TRUE(cap.is_capable("foo", 0, 10, 0750, 10, 10, NULL, MAY_READ, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 10, 0750, 10, 10, NULL, MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 10, 0770, 10, 10, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 10, 0770, 10, 11, &glist10, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 11, 0770, 10, 10, &glist11, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 11, 0770, 10, 11, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 12, 0770, 12, 12, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 10, 0770, 12, 12, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 10, 0770, 12, 12, &glist10, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 10, 0770, 12, 12, &dglist10, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 11, 0770, 12, 12, &glist11, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 12, 0770, 10, 10, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 12, 0770, 10, 10, &glist12, MAY_READ | MAY_WRITE, 0, 0, addr)); // user > group ASSERT_TRUE(cap.is_capable("foo", 10, 10, 0570, 10, 10, NULL, MAY_READ, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 10, 10, 0570, 10, 10, NULL, MAY_WRITE, 0, 0, addr)); // other ASSERT_TRUE(cap.is_capable("foo", 0, 0, 0775, 10, 10, NULL, MAY_READ, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0770, 10, 10, NULL, MAY_READ, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0775, 10, 10, NULL, MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0775, 10, 10, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("foo", 0, 0, 0777, 10, 10, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0773, 10, 10, NULL, MAY_READ, 0, 0, addr)); // group > other ASSERT_TRUE(cap.is_capable("foo", 0, 0, 0557, 10, 10, NULL, MAY_READ, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 10, 0557, 10, 10, NULL, MAY_WRITE, 0, 0, addr)); // user > other ASSERT_TRUE(cap.is_capable("foo", 0, 0, 0557, 10, 10, NULL, MAY_READ, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 10, 0, 0557, 10, 10, NULL, MAY_WRITE, 0, 0, addr)); } TEST(MDSAuthCaps, AllowPath) { MDSAuthCaps cap; ASSERT_TRUE(cap.parse("allow * path=/sandbox", NULL)); ASSERT_FALSE(cap.allow_all()); ASSERT_TRUE(cap.is_capable("sandbox/foo", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(cap.is_capable("sandbox", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("sandboxed", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); } TEST(MDSAuthCaps, AllowPathChars) { MDSAuthCaps unquo_cap; ASSERT_TRUE(unquo_cap.parse("allow * path=/sandbox-._foo", NULL)); ASSERT_FALSE(unquo_cap.allow_all()); ASSERT_TRUE(unquo_cap.is_capable("sandbox-._foo/foo", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(unquo_cap.is_capable("sandbox", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(unquo_cap.is_capable("sandbox-._food", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(unquo_cap.is_capable("foo", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); } TEST(MDSAuthCaps, AllowPathCharsQuoted) { MDSAuthCaps quo_cap; ASSERT_TRUE(quo_cap.parse("allow * path=\"/sandbox-._foo\"", NULL)); ASSERT_FALSE(quo_cap.allow_all()); ASSERT_TRUE(quo_cap.is_capable("sandbox-._foo/foo", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(quo_cap.is_capable("sandbox", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(quo_cap.is_capable("sandbox-._food", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(quo_cap.is_capable("foo", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); } TEST(MDSAuthCaps, RootSquash) { MDSAuthCaps rs_cap; ASSERT_TRUE(rs_cap.parse("allow rw root_squash, allow rw path=/sandbox", NULL)); ASSERT_TRUE(rs_cap.is_capable("foo", 0, 0, 0777, 0, 0, NULL, MAY_READ, 0, 0, addr)); ASSERT_TRUE(rs_cap.is_capable("foo", 0, 0, 0777, 10, 10, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_FALSE(rs_cap.is_capable("foo", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(rs_cap.is_capable("sandbox", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(rs_cap.is_capable("sandbox/foo", 0, 0, 0777, 0, 0, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); ASSERT_TRUE(rs_cap.is_capable("sandbox/foo", 0, 0, 0777, 10, 10, NULL, MAY_READ | MAY_WRITE, 0, 0, addr)); } TEST(MDSAuthCaps, OutputParsed) { struct CapsTest { const char *input; const char *output; }; CapsTest test_values[] = { {"allow", "MDSAuthCaps[allow rwps]"}, {"allow *", "MDSAuthCaps[allow *]"}, {"allow r", "MDSAuthCaps[allow r]"}, {"allow rw", "MDSAuthCaps[allow rw]"}, {"allow * uid=1", "MDSAuthCaps[allow * uid=1]"}, {"allow * uid=1 gids=1", "MDSAuthCaps[allow * uid=1 gids=1]"}, {"allow * uid=1 gids=1,2,3", "MDSAuthCaps[allow * uid=1 gids=1,2,3]"}, {"allow * path=/foo", "MDSAuthCaps[allow * path=\"/foo\"]"}, {"allow * path=\"/foo\"", "MDSAuthCaps[allow * path=\"/foo\"]"}, {"allow rw root_squash", "MDSAuthCaps[allow rw root_squash]"}, {"allow rw fsname=a root_squash", "MDSAuthCaps[allow rw fsname=a root_squash]"}, {"allow * path=\"/foo\" root_squash", "MDSAuthCaps[allow * path=\"/foo\" root_squash]"}, {"allow * path=\"/foo\" uid=1", "MDSAuthCaps[allow * path=\"/foo\" uid=1]"}, {"allow * path=\"/foo\" uid=1 gids=1,2,3", "MDSAuthCaps[allow * path=\"/foo\" uid=1 gids=1,2,3]"}, {"allow r uid=1 gids=1,2,3, allow * uid=2", "MDSAuthCaps[allow r uid=1 gids=1,2,3, allow * uid=2]"}, {"allow r uid=1 gids=1,2,3, allow * uid=2 network 10.0.0.0/8", "MDSAuthCaps[allow r uid=1 gids=1,2,3, allow * uid=2 network 10.0.0.0/8]"}, {"allow rw fsname=b, allow rw fsname=a root_squash", "MDSAuthCaps[allow rw fsname=b, allow rw fsname=a root_squash]"}, }; size_t num_tests = sizeof(test_values) / sizeof(*test_values); for (size_t i = 0; i < num_tests; ++i) { MDSAuthCaps cap; std::cout << "Testing input '" << test_values[i].input << "'" << std::endl; ASSERT_TRUE(cap.parse(test_values[i].input, &cout)); ASSERT_EQ(test_values[i].output, stringify(cap)); } } TEST(MDSAuthCaps, network) { entity_addr_t a, b, c; a.parse("10.1.2.3"); b.parse("192.168.2.3"); c.parse("192.167.2.3"); MDSAuthCaps cap; ASSERT_TRUE(cap.parse("allow * network 192.168.0.0/16, allow * network 10.0.0.0/8", NULL)); ASSERT_TRUE(cap.is_capable("foo", 0, 0, 0777, 0, 0, NULL, MAY_READ, 0, 0, a)); ASSERT_TRUE(cap.is_capable("foo", 0, 0, 0777, 0, 0, NULL, MAY_READ, 0, 0, b)); ASSERT_FALSE(cap.is_capable("foo", 0, 0, 0777, 0, 0, NULL, MAY_READ, 0, 0, c)); }
15,600
40.381963
115
cc
null
ceph-main/src/test/mds/TestSessionFilter.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2012 Inktank * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include "include/stringify.h" #include "mds/SessionMap.h" #include "gtest/gtest.h" typedef std::vector<std::string> args_eg; typedef std::vector<args_eg> args_eg_set; TEST(MDSSessionFilter, ParseGood) { args_eg_set examples = { {"id=34"}, {"auth_name=foxtrot"}, {"state=reconnecting"}, {"reconnecting=true"}, {"client_metadata.root=/foo/bar"}, {}, {"id=123"}, {"id=34", "client_metadata.root=/foo/bar", "auth_name=foxtrot", "state=reconnecting", "reconnecting=true"} }; for (auto ex : examples) { SessionFilter f; std::stringstream ss; std::cout << "Testing '" << ex << "'" << std::endl; int r = f.parse(ex, &ss); ASSERT_EQ(r, 0); ASSERT_TRUE(ss.str().empty()); } } TEST(MDSSessionFilter, ParseBad) { args_eg_set examples = { {"rhubarb"}, {"id="}, {"id=custard"}, {"=custard"}, {"reconnecting=MAYBE"}, {"reconnecting=2"} }; for (auto ex : examples) { SessionFilter f; std::stringstream ss; std::cout << "Testing '" << ex << "'" << std::endl; int r = f.parse(ex, &ss); ASSERT_EQ(r, -EINVAL); ASSERT_FALSE(ss.str().empty()); } } TEST(MDSSessionFilter, IdEquality) { SessionFilter filter; std::stringstream ss; filter.parse({"id=123"}, &ss); auto a = ceph::make_ref<Session>(nullptr);; auto b = ceph::make_ref<Session>(nullptr);; a->info.inst.name.parse("client.123"); b->info.inst.name.parse("client.456"); ASSERT_TRUE(filter.match(*a, [](client_t c) -> bool {return false;})); ASSERT_FALSE(filter.match(*b, [](client_t c) -> bool {return false;})); } TEST(MDSSessionFilter, StateEquality) { SessionFilter filter; std::stringstream ss; filter.parse({"state=closing"}, &ss); auto a = ceph::make_ref<Session>(nullptr); a->set_state(Session::STATE_CLOSING); auto b = ceph::make_ref<Session>(nullptr); b->set_state(Session::STATE_OPENING); ASSERT_TRUE(filter.match(*a, [](client_t c) -> bool {return false;})); ASSERT_FALSE(filter.match(*b, [](client_t c) -> bool {return false;})); } TEST(MDSSessionFilter, AuthEquality) { SessionFilter filter; std::stringstream ss; filter.parse({"auth_name=rhubarb"}, &ss); auto a = ceph::make_ref<Session>(nullptr); a->info.auth_name.set_id("rhubarb"); auto b = ceph::make_ref<Session>(nullptr); b->info.auth_name.set_id("custard"); ASSERT_TRUE(filter.match(*a, [](client_t c) -> bool {return false;})); ASSERT_FALSE(filter.match(*b, [](client_t c) -> bool {return false;})); } TEST(MDSSessionFilter, MetadataEquality) { SessionFilter filter; std::stringstream ss; int r = filter.parse({"client_metadata.root=/rhubarb"}, &ss); ASSERT_EQ(r, 0); client_metadata_t meta; auto a = ceph::make_ref<Session>(nullptr); meta.kv_map = {{"root", "/rhubarb"}}; a->set_client_metadata(meta); auto b = ceph::make_ref<Session>(nullptr); meta.kv_map = {{"root", "/custard"}}; b->set_client_metadata(meta); ASSERT_TRUE(filter.match(*a, [](client_t c) -> bool {return false;})); ASSERT_FALSE(filter.match(*b, [](client_t c) -> bool {return false;})); } TEST(MDSSessionFilter, ReconnectingEquality) { SessionFilter filter; std::stringstream ss; int r = filter.parse({"reconnecting=true"}, &ss); ASSERT_EQ(r, 0); auto a = ceph::make_ref<Session>(nullptr); ASSERT_TRUE(filter.match(*a, [](client_t c) -> bool {return true;})); ASSERT_FALSE(filter.match(*a, [](client_t c) -> bool {return false;})); }
3,870
26.06993
73
cc
null
ceph-main/src/test/memuse/test_pool_memuse.sh
#! /bin/sh -x # # Create a bunch of pools in parallel # This test isn't very smart -- run it from your src dir. # set -e CEPH_NUM_MON=1 CEPH_NUM_MDS=1 CEPH_NUM_OSD=$2 ./vstart.sh -n -d --valgrind_osd 'massif' for i in `seq 0 $1`; do for j in `seq 0 9`; do poolnum=$((i*10+j)) poolname="pool$poolnum" ./ceph osd pool create $poolname 8 & done wait done
371
17.6
87
sh
null
ceph-main/src/test/memuse/test_pool_memuse_tcmalloc.sh
#! /bin/sh -x # # Create a bunch of pools in parallel # This test isn't very smart -- run it from your src dir. # set -e CEPH_NUM_MON=1 CEPH_NUM_MDS=1 CEPH_NUM_OSD=$2 ./vstart.sh -n -d num_osd=$2 maxosd=$((num_osd-1)) for osd_num in `seq 0 $maxosd`; do ./ceph osd tell $osd_num start_profiler done for i in `seq 0 $1`; do for j in `seq 0 9`; do poolnum=$((i*10+j)) poolname="pool$poolnum" ./ceph osd pool create $poolname 8 & done wait done
465
16.923077
63
sh
null
ceph-main/src/test/memuse/test_written_pool_memuse.sh
#! /bin/sh -x set -e for i in `seq 0 $1`; do for j in `seq 0 9`; do poolnum=$((i*10+j)) poolname="pool$poolnum" ./rados -p $poolname bench 1 write -t 1 & done wait done
185
14.5
42
sh
null
ceph-main/src/test/memuse/test_written_pool_memuse_tcmalloc.sh
#!/bin/sh -x set -e num_osd=$2 maxosd=$((num_osd-1)) eval "rm out/*.heap" || echo "no heap dumps to rm" mkdir -p out/pg_stable for osd_num in `seq 0 $maxosd`; do ./ceph osd tell $osd_num heapdump sleep 1 eval "mv out/*.heap out/pg_stable" done for i in `seq 0 $1`; do for j in `seq 0 9`; do poolnum=$((i*10+j)) poolname="pool$poolnum" ./rados -p $poolname bench 1 write -t 1 & done wait done eval "rm out/*.heap" || echo "no heap dumps to rm" mkdir out/one_write for osd_num in `seq 0 $maxosd`; do ./ceph osd tell $osd_num heapdump sleep 1 eval "mv out/*.heap out/one_write" done for i in `seq 0 $1`; do for j in `seq 0 9`; do poolnum=$((i*10+j)) poolname="pool$poolnum" ./rados -p $poolname bench 1 write -t 4 & done wait done eval "rm out/*.heap" mkdir out/five_writes for osd_num in `seq 0 $maxosd`; do ./ceph osd tell $osd_num heapdump sleep 1 eval "mv out/*.heap out/five_writes" done
969
16.636364
50
sh
null
ceph-main/src/test/mgr/mgr-dashboard-smoke.sh
#!/usr/bin/env bash # # Copyright (C) 2014,2015,2017 Red Hat <[email protected]> # Copyright (C) 2018 SUSE LLC # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Library Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library Public License for more details. # source $(dirname $0)/../detect-build-env-vars.sh source $CEPH_ROOT/qa/standalone/ceph-helpers.sh mon_port=$(get_unused_port) dashboard_port=$((mon_port+1)) function run() { local dir=$1 shift export CEPH_MON=127.0.0.1:$mon_port export CEPH_ARGS CEPH_ARGS+="--fsid=$(uuidgen) --auth-supported=none " CEPH_ARGS+="--mon-initial-members=a --mon-host=$MON " CEPH_ARGS+="--mgr-initial-modules=dashboard " CEPH_ARGS+="--mon-host=$CEPH_MON" setup $dir || return 1 TEST_dashboard $dir || return 1 teardown $dir || return 1 } function TEST_dashboard() { local dir=$1 shift run_mon $dir a || return 1 timeout 30 ceph mon stat || return 1 ceph config-key set mgr/dashboard/x/server_port $dashboard_port MGR_ARGS+="--mgr_module_path=${CEPH_ROOT}/src/pybind/mgr " run_mgr $dir x ${MGR_ARGS} || return 1 tries=0 while [[ $tries < 30 ]] ; do if [ $(ceph status -f json | jq .mgrmap.available) = "true" ] then break fi tries=$((tries+1)) sleep 1 done DASHBOARD_ADMIN_SECRET_FILE="/tmp/dashboard-admin-secret.txt" printf 'admin' > "${DASHBOARD_ADMIN_SECRET_FILE}" ceph_adm dashboard ac-user-create admin -i "${DASHBOARD_ADMIN_SECRET_FILE}" --force-password tries=0 while [[ $tries < 30 ]] ; do if curl -c $dir/cookiefile -X POST -d '{"username":"admin","password":"admin"}' http://127.0.0.1:$dashboard_port/api/auth then if curl -b $dir/cookiefile -s http://127.0.0.1:$dashboard_port/api/summary | \ jq '.health.overall_status' | grep HEALTH_ then break fi fi tries=$((tries+1)) sleep 0.5 done } main mgr-dashboard-smoke "$@" # Local Variables: # compile-command: "cd ../.. ; make -j4 TESTS=test/mgr/mgr-dashboard-smoke.sh check" # End:
2,492
29.402439
129
sh
null
ceph-main/src/test/mgr/test_mgrcap.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2012 Inktank * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include "include/stringify.h" #include "mgr/MgrCap.h" #include "gtest/gtest.h" using namespace std; const char *parse_good[] = { // MgrCapMatch "allow *", "allow r", "allow rwx", "allow r", " allow rwx", "allow rwx ", " allow rwx ", " allow\t rwx ", "\tallow\nrwx\t", "allow service=foo x", "allow service=\"froo\" x", "allow profile read-only", "allow profile read-write", "allow profile \"rbd-read-only\", allow *", "allow command \"a b c\"", "allow command abc", "allow command abc with arg=foo", "allow command abc with arg=foo arg2=bar", "allow command abc with arg=foo arg2=bar", "allow command abc with arg=foo arg2 prefix bar arg3 prefix baz", "allow command abc with arg=foo arg2 prefix \"bar bingo\" arg3 prefix baz", "allow command abc with arg regex \"^[0-9a-z.]*$\"", "allow command abc with arg regex \"\(invaluid regex\"", "allow service foo x", "allow service foo x; allow service bar x", "allow service foo w ;allow service bar x", "allow service foo w , allow service bar x", "allow service foo r , allow service bar x", "allow service foo_foo r, allow service bar r", "allow service foo-foo r, allow service bar r", "allow service \" foo \" w, allow service bar r", "allow module foo x", "allow module=foo x", "allow module foo_foo r", "allow module \" foo \" w", "allow module foo with arg1=value1 x", "allow command abc with arg=foo arg2=bar, allow service foo r", "allow command abc.def with arg=foo arg2=bar, allow service foo r", "allow command \"foo bar\" with arg=\"baz\"", "allow command \"foo bar\" with arg=\"baz.xx\"", "allow command \"foo bar\" with arg = \"baz.xx\"", "profile crash", "profile osd", "profile mds", "profile rbd pool=ABC namespace=NS", "profile \"rbd-read-only\", profile crash", "allow * network 1.2.3.4/24", "allow * network ::1/128", "allow * network [aa:bb::1]/128", "allow service=foo x network 1.2.3.4/16", "allow command abc network 1.2.3.4/8", "profile crash network 1.2.3.4/32", "allow profile crash network 1.2.3.4/32", 0 }; TEST(MgrCap, ParseGood) { for (int i=0; parse_good[i]; ++i) { string str = parse_good[i]; MgrCap cap; std::cout << "Testing good input: '" << str << "'" << std::endl; ASSERT_TRUE(cap.parse(str, &cout)); std::cout << " -> " << cap << std::endl; } } // these should stringify to the input value const char *parse_identity[] = { "allow *", "allow r", "allow rwx", "allow service foo x", "profile crash", "profile rbd-read-only, allow *", "profile rbd namespace=NS pool=ABC", "allow command abc", "allow command \"a b c\"", "allow command abc with arg=foo", "allow command abc with arg=foo arg2=bar", "allow command abc with arg=foo arg2=bar", "allow command abc with arg=foo arg2 prefix bar arg3 prefix baz", "allow command abc with arg=foo arg2 prefix \"bar bingo\" arg3 prefix baz", "allow service foo x", "allow service foo x, allow service bar x", "allow service foo w, allow service bar x", "allow service foo r, allow service bar x", "allow service foo_foo r, allow service bar r", "allow service foo-foo r, allow service bar r", "allow service \" foo \" w, allow service bar r", "allow module foo x", "allow module \" foo_foo \" r", "allow module foo with arg1=value1 x", "allow command abc with arg=foo arg2=bar, allow service foo r", 0 }; TEST(MgrCap, ParseIdentity) { for (int i=0; parse_identity[i]; ++i) { string str = parse_identity[i]; MgrCap cap; std::cout << "Testing good input: '" << str << "'" << std::endl; ASSERT_TRUE(cap.parse(str, &cout)); string out = stringify(cap); ASSERT_EQ(out, str); } } const char *parse_bad[] = { "allow r foo", "allow*", "foo allow *", "profile foo rwx", "profile", "profile foo bar rwx", "allow profile foo rwx", "allow profile", "allow profile foo bar rwx", "allow service bar", "allow command baz x", "allow r w", "ALLOW r", "allow rwx,", "allow rwx x", "allow r pool foo r", "allow wwx pool taco", "allow wwx pool taco^funny&chars", "allow rwx pool 'weird name''", "allow rwx object_prefix \"beforepool\" pool weird", "allow rwx auid 123 pool asdf", "allow command foo a prefix b", "allow command foo with a prefixb", "allow command foo with a = prefix b", "allow command foo with a prefix b c", 0 }; TEST(MgrCap, ParseBad) { for (int i=0; parse_bad[i]; ++i) { string str = parse_bad[i]; MgrCap cap; std::cout << "Testing bad input: '" << str << "'" << std::endl; ASSERT_FALSE(cap.parse(str, &cout)); } } TEST(MgrCap, AllowAll) { MgrCap cap; ASSERT_FALSE(cap.is_allow_all()); ASSERT_TRUE(cap.parse("allow r", nullptr)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow w", nullptr)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow x", nullptr)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow rwx", nullptr)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow rw", nullptr)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow rx", nullptr)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow wx", nullptr)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow *", nullptr)); ASSERT_TRUE(cap.is_allow_all()); ASSERT_TRUE(cap.is_capable(nullptr, {}, "foo", "", "asdf", {}, true, true, true, {})); MgrCap cap2; ASSERT_FALSE(cap2.is_allow_all()); cap2.set_allow_all(); ASSERT_TRUE(cap2.is_allow_all()); } TEST(MgrCap, Network) { MgrCap cap; bool r = cap.parse("allow * network 192.168.0.0/16, allow * network 10.0.0.0/8", nullptr); ASSERT_TRUE(r); entity_addr_t a, b, c; a.parse("10.1.2.3"); b.parse("192.168.2.3"); c.parse("192.167.2.3"); ASSERT_TRUE(cap.is_capable(nullptr, {}, "foo", "", "asdf", {}, true, true, true, a)); ASSERT_TRUE(cap.is_capable(nullptr, {}, "foo", "", "asdf", {}, true, true, true, b)); ASSERT_FALSE(cap.is_capable(nullptr, {}, "foo", "", "asdf", {}, true, true, true, c)); } TEST(MgrCap, CommandRegEx) { MgrCap cap; ASSERT_FALSE(cap.is_allow_all()); ASSERT_TRUE(cap.parse("allow command abc with arg regex \"^[0-9a-z.]*$\"", nullptr)); EntityName name; name.from_str("osd.123"); ASSERT_TRUE(cap.is_capable(nullptr, name, "", "", "abc", {{"arg", "12345abcde"}}, true, true, true, {})); ASSERT_FALSE(cap.is_capable(nullptr, name, "", "", "abc", {{"arg", "~!@#$"}}, true, true, true, {})); ASSERT_TRUE(cap.parse("allow command abc with arg regex \"[*\"", nullptr)); ASSERT_FALSE(cap.is_capable(nullptr, name, "", "", "abc", {{"arg", ""}}, true, true, true, {})); } TEST(MgrCap, Module) { MgrCap cap; ASSERT_FALSE(cap.is_allow_all()); ASSERT_TRUE(cap.parse("allow module abc r, allow module bcd w", nullptr)); ASSERT_FALSE(cap.is_capable(nullptr, {}, "", "abc", "", {}, true, true, false, {})); ASSERT_TRUE(cap.is_capable(nullptr, {}, "", "abc", "", {}, true, false, false, {})); ASSERT_FALSE(cap.is_capable(nullptr, {}, "", "bcd", "", {}, true, true, false, {})); ASSERT_TRUE(cap.is_capable(nullptr, {}, "", "bcd", "", {}, false, true, false, {})); } TEST(MgrCap, Profile) { MgrCap cap; ASSERT_FALSE(cap.is_allow_all()); ASSERT_FALSE(cap.parse("profile unknown")); ASSERT_FALSE(cap.parse("profile rbd invalid-key=value")); ASSERT_TRUE(cap.parse("profile rbd", nullptr)); ASSERT_FALSE(cap.is_capable(nullptr, {}, "", "abc", "", {}, true, false, false, {})); ASSERT_TRUE(cap.is_capable(nullptr, {}, "", "rbd_support", "", {}, true, true, false, {})); ASSERT_TRUE(cap.is_capable(nullptr, {}, "", "rbd_support", "", {}, true, false, false, {})); ASSERT_TRUE(cap.parse("profile rbd pool=abc namespace prefix def", nullptr)); ASSERT_FALSE(cap.is_capable(nullptr, {}, "", "rbd_support", "", {}, true, true, false, {})); ASSERT_FALSE(cap.is_capable(nullptr, {}, "", "rbd_support", "", {{"pool", "abc"}}, true, true, false, {})); ASSERT_TRUE(cap.is_capable(nullptr, {}, "", "rbd_support", "", {{"pool", "abc"}, {"namespace", "defghi"}}, true, true, false, {})); ASSERT_TRUE(cap.parse("profile rbd-read-only", nullptr)); ASSERT_FALSE(cap.is_capable(nullptr, {}, "", "abc", "", {}, true, false, false, {})); ASSERT_FALSE(cap.is_capable(nullptr, {}, "", "rbd_support", "", {}, true, true, false, {})); ASSERT_TRUE(cap.is_capable(nullptr, {}, "", "rbd_support", "", {}, true, false, false, {})); }
9,787
31.518272
92
cc
null
ceph-main/src/test/mgr/test_ttlcache.cc
#include <iostream> #include "mgr/TTLCache.h" #include "gtest/gtest.h" using namespace std; TEST(TTLCache, Get) { TTLCache<string, int> c{100}; c.insert("foo", 1); int foo = c.get("foo"); ASSERT_EQ(foo, 1); } TEST(TTLCache, Erase) { TTLCache<string, int> c{100}; c.insert("foo", 1); int foo = c.get("foo"); ASSERT_EQ(foo, 1); c.erase("foo"); try{ foo = c.get("foo"); FAIL(); } catch (std::out_of_range& e) { SUCCEED(); } } TEST(TTLCache, Clear) { TTLCache<string, int> c{100}; c.insert("foo", 1); c.insert("foo2", 2); c.clear(); ASSERT_FALSE(c.size()); } TEST(TTLCache, NoTTL) { TTLCache<string, int> c{100}; c.insert("foo", 1); int foo = c.get("foo"); ASSERT_EQ(foo, 1); c.set_ttl(0); c.insert("foo2", 2); try{ foo = c.get("foo2"); FAIL(); } catch (std::out_of_range& e) { SUCCEED(); } } TEST(TTLCache, SizeLimit) { TTLCache<string, int> c{100, 2}; c.insert("foo", 1); c.insert("foo2", 2); c.insert("foo3", 3); ASSERT_EQ(c.size(), 2); } TEST(TTLCache, HitRatio) { TTLCache<string, int> c{100}; c.insert("foo", 1); c.insert("foo2", 2); c.insert("foo3", 3); c.get("foo2"); c.get("foo3"); std::pair<uint64_t, uint64_t> hit_miss_ratio = c.get_hit_miss_ratio(); ASSERT_EQ(std::get<1>(hit_miss_ratio), 3); ASSERT_EQ(std::get<0>(hit_miss_ratio), 2); }
1,324
17.661972
71
cc
null
ceph-main/src/test/mon/MonMap.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2016 SUSE LINUX GmbH * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "mon/MonMap.h" #include "common/ceph_context.h" #include "common/dns_resolve.h" #include "test/common/dns_messages.h" #include "common/debug.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <boost/smart_ptr/intrusive_ptr.hpp> #include <sstream> #define TEST_DEBUG 20 #define dout_subsys ceph_subsys_mon using ::testing::Return; using ::testing::_; using ::testing::SetArrayArgument; using ::testing::DoAll; using ::testing::StrEq; class MonMapTest : public ::testing::Test { protected: virtual void SetUp() { g_ceph_context->_conf->subsys.set_log_level(dout_subsys, TEST_DEBUG); } virtual void TearDown() { DNSResolver::get_instance(nullptr); } }; TEST_F(MonMapTest, DISABLED_build_initial_config_from_dns) { MockResolvHWrapper *resolvH = new MockResolvHWrapper(); DNSResolver::get_instance(resolvH); int len = sizeof(ns_search_msg_ok_payload); int lena = sizeof(ns_query_msg_mon_a_payload); int lenb = sizeof(ns_query_msg_mon_b_payload); int lenc = sizeof(ns_query_msg_mon_c_payload); using ::testing::InSequence; { InSequence s; #ifdef HAVE_RES_NQUERY EXPECT_CALL(*resolvH, res_nsearch(_, StrEq("_cephmon._tcp"), C_IN, T_SRV, _, _)) .WillOnce(DoAll(SetArrayArgument<4>(ns_search_msg_ok_payload, ns_search_msg_ok_payload+len), Return(len))); EXPECT_CALL(*resolvH, res_nquery(_,StrEq("mon.a.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_a_payload, ns_query_msg_mon_a_payload+lena), Return(lena))); EXPECT_CALL(*resolvH, res_nquery(_, StrEq("mon.c.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_c_payload, ns_query_msg_mon_c_payload+lenc), Return(lenc))); EXPECT_CALL(*resolvH, res_nquery(_,StrEq("mon.b.ceph.com"), C_IN, T_A, _,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_b_payload, ns_query_msg_mon_b_payload+lenb), Return(lenb))); #else EXPECT_CALL(*resolvH, res_search(StrEq("_cephmon._tcp"), C_IN, T_SRV, _, _)) .WillOnce(DoAll(SetArrayArgument<3>(ns_search_msg_ok_payload, ns_search_msg_ok_payload+len), Return(len))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.a.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_a_payload, ns_query_msg_mon_a_payload+lena), Return(lena))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.c.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_c_payload, ns_query_msg_mon_c_payload+lenc), Return(lenc))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.b.ceph.com"), C_IN, T_A, _,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_b_payload, ns_query_msg_mon_b_payload+lenb), Return(lenb))); #endif } boost::intrusive_ptr<CephContext> cct = new CephContext(CEPH_ENTITY_TYPE_MON); cct->_conf.set_val("mon_dns_srv_name", "cephmon"); MonMap monmap; int r = monmap.build_initial(cct.get(), false, std::cerr); ASSERT_EQ(r, 0); ASSERT_EQ(monmap.mon_info.size(), (unsigned int)3); auto it = monmap.mon_info.find("mon.a"); ASSERT_NE(it, monmap.mon_info.end()); std::ostringstream os; os << it->second.public_addrs; ASSERT_EQ(os.str(), "192.168.1.11:6789/0"); os.str(""); it = monmap.mon_info.find("mon.b"); ASSERT_NE(it, monmap.mon_info.end()); os << it->second.public_addrs; ASSERT_EQ(os.str(), "192.168.1.12:6789/0"); os.str(""); it = monmap.mon_info.find("mon.c"); ASSERT_NE(it, monmap.mon_info.end()); os << it->second.public_addrs; ASSERT_EQ(os.str(), "192.168.1.13:6789/0"); } TEST_F(MonMapTest, DISABLED_build_initial_config_from_dns_fail) { MockResolvHWrapper *resolvH = new MockResolvHWrapper(); DNSResolver::get_instance(resolvH); #ifdef HAVE_RES_NQUERY EXPECT_CALL(*resolvH, res_nsearch(_, StrEq("_ceph-mon._tcp"), C_IN, T_SRV, _, _)) .WillOnce(Return(0)); #else EXPECT_CALL(*resolvH, res_search(StrEq("_ceph-mon._tcp"), C_IN, T_SRV, _, _)) .WillOnce(Return(0)); #endif boost::intrusive_ptr<CephContext> cct = new CephContext(CEPH_ENTITY_TYPE_MON); // using default value of mon_dns_srv_name option MonMap monmap; int r = monmap.build_initial(cct.get(), false, std::cerr); ASSERT_EQ(r, -ENOENT); ASSERT_EQ(monmap.mon_info.size(), (unsigned int)0); } TEST_F(MonMapTest, DISABLED_build_initial_config_from_dns_with_domain) { MockResolvHWrapper *resolvH = new MockResolvHWrapper(); DNSResolver::get_instance(resolvH); int len = sizeof(ns_search_msg_ok_payload); int lena = sizeof(ns_query_msg_mon_a_payload); int lenb = sizeof(ns_query_msg_mon_b_payload); int lenc = sizeof(ns_query_msg_mon_c_payload); using ::testing::InSequence; { InSequence s; #ifdef HAVE_RES_NQUERY EXPECT_CALL(*resolvH, res_nsearch(_, StrEq("_cephmon._tcp.ceph.com"), C_IN, T_SRV, _, _)) .WillOnce(DoAll(SetArrayArgument<4>(ns_search_msg_ok_payload, ns_search_msg_ok_payload+len), Return(len))); EXPECT_CALL(*resolvH, res_nquery(_,StrEq("mon.a.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_a_payload, ns_query_msg_mon_a_payload+lena), Return(lena))); EXPECT_CALL(*resolvH, res_nquery(_, StrEq("mon.c.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_c_payload, ns_query_msg_mon_c_payload+lenc), Return(lenc))); EXPECT_CALL(*resolvH, res_nquery(_,StrEq("mon.b.ceph.com"), C_IN, T_A, _,_)) .WillOnce(DoAll(SetArrayArgument<4>(ns_query_msg_mon_b_payload, ns_query_msg_mon_b_payload+lenb), Return(lenb))); #else EXPECT_CALL(*resolvH, res_search(StrEq("_cephmon._tcp.ceph.com"), C_IN, T_SRV, _, _)) .WillOnce(DoAll(SetArrayArgument<3>(ns_search_msg_ok_payload, ns_search_msg_ok_payload+len), Return(len))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.a.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_a_payload, ns_query_msg_mon_a_payload+lena), Return(lena))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.c.ceph.com"), C_IN, T_A,_,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_c_payload, ns_query_msg_mon_c_payload+lenc), Return(lenc))); EXPECT_CALL(*resolvH, res_query(StrEq("mon.b.ceph.com"), C_IN, T_A, _,_)) .WillOnce(DoAll(SetArrayArgument<3>(ns_query_msg_mon_b_payload, ns_query_msg_mon_b_payload+lenb), Return(lenb))); #endif } boost::intrusive_ptr<CephContext> cct = new CephContext(CEPH_ENTITY_TYPE_MON); cct->_conf.set_val("mon_dns_srv_name", "cephmon_ceph.com"); MonMap monmap; int r = monmap.build_initial(cct.get(), false, std::cerr); ASSERT_EQ(r, 0); ASSERT_EQ(monmap.mon_info.size(), (unsigned int)3); auto it = monmap.mon_info.find("mon.a"); ASSERT_NE(it, monmap.mon_info.end()); std::ostringstream os; os << it->second.public_addrs; ASSERT_EQ(os.str(), "192.168.1.11:6789/0"); os.str(""); it = monmap.mon_info.find("mon.b"); ASSERT_NE(it, monmap.mon_info.end()); os << it->second.public_addrs; ASSERT_EQ(os.str(), "192.168.1.12:6789/0"); os.str(""); it = monmap.mon_info.find("mon.c"); ASSERT_NE(it, monmap.mon_info.end()); os << it->second.public_addrs; ASSERT_EQ(os.str(), "192.168.1.13:6789/0"); } TEST(MonMapBuildInitial, build_initial_mon_host_from_dns) { boost::intrusive_ptr<CephContext> cct = new CephContext(CEPH_ENTITY_TYPE_MON); cct->_conf.set_val("mon_host", "ceph.io"); MonMap monmap; int r = monmap.build_initial(cct.get(), false, std::cerr); ASSERT_EQ(r, 0); ASSERT_GE(monmap.mon_info.size(), 1u); for (const auto& [name, info] : monmap.mon_info) { std::cerr << info << std::endl; } } TEST(MonMapBuildInitial, build_initial_mon_host_from_dns_fail) { boost::intrusive_ptr<CephContext> cct = new CephContext(CEPH_ENTITY_TYPE_MON); cct->_conf.set_val("mon_host", "ceph.noname"); MonMap monmap; int r = monmap.build_initial(cct.get(), false, std::cerr); ASSERT_EQ(r, -EINVAL); }
8,513
34.181818
93
cc
null
ceph-main/src/test/mon/PGMap.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2014 Inktank <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License version 2, as published by the Free Software * Foundation. See file COPYING. */ #include "mon/PGMap.h" #include "gtest/gtest.h" #include "include/stringify.h" using namespace std; namespace { class CheckTextTable : public TextTable { public: explicit CheckTextTable(bool verbose) { for (int i = 0; i < 5; i++) { define_column("", TextTable::LEFT, TextTable::LEFT); } if (verbose) { for (int i = 0; i < 9; i++) { define_column("", TextTable::LEFT, TextTable::LEFT); } } } const string& get(unsigned r, unsigned c) const { ceph_assert(r < row.size()); ceph_assert(c < row[r].size()); return row[r][c]; } }; // copied from PGMap.cc string percentify(float a) { stringstream ss; if (a < 0.01) ss << "0"; else ss << std::fixed << std::setprecision(2) << a; return ss.str(); } } // dump_object_stat_sum() is called by "ceph df" command // with table, without formatter, verbose = true, not empty, avail > 0 TEST(pgmap, dump_object_stat_sum_0) { bool verbose = true; CheckTextTable tbl(verbose); pool_stat_t pool_stat; object_stat_sum_t& sum = pool_stat.stats.sum; sum.num_bytes = 42 * 1024 * 1024; sum.num_objects = 42; sum.num_objects_degraded = 13; // there are 13 missings + not_yet_backfilled sum.num_objects_dirty = 2; sum.num_rd = 100; sum.num_rd_kb = 123; sum.num_wr = 101; sum.num_wr_kb = 321; pool_stat.num_store_stats = 3; store_statfs_t &statfs = pool_stat.store_stats; statfs.data_stored = 40 * 1024 * 1024; statfs.allocated = 41 * 1024 * 1024 * 2; statfs.data_compressed_allocated = 4334; statfs.data_compressed_original = 1213; sum.calc_copies(3); // assuming we have 3 copies for each obj // nominal amount of space available for new objects in this pool uint64_t avail = 2016 * 1024 * 1024; pg_pool_t pool; pool.quota_max_objects = 2000; pool.quota_max_bytes = 2000 * 1024 * 1024; pool.size = 2; pool.type = pg_pool_t::TYPE_REPLICATED; pool.tier_of = 0; PGMap::dump_object_stat_sum(tbl, nullptr, pool_stat, avail, pool.get_size(), verbose, true, true, &pool); float copies_rate = (static_cast<float>(sum.num_object_copies - sum.num_objects_degraded) / sum.num_object_copies) * pool.get_size(); float used_percent = (float)statfs.allocated / (statfs.allocated + avail) * 100; uint64_t stored = statfs.data_stored / copies_rate; unsigned col = 0; ASSERT_EQ(stringify(byte_u_t(stored)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(stored)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(stringify(si_u_t(sum.num_objects)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(statfs.allocated)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(statfs.allocated)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(percentify(used_percent), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(avail/copies_rate)), tbl.get(0, col++)); ASSERT_EQ(stringify(si_u_t(pool.quota_max_objects)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(pool.quota_max_bytes)), tbl.get(0, col++)); ASSERT_EQ(stringify(si_u_t(sum.num_objects_dirty)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(statfs.data_compressed_allocated)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(statfs.data_compressed_original)), tbl.get(0, col++)); } // with table, without formatter, verbose = true, empty, avail > 0 TEST(pgmap, dump_object_stat_sum_1) { bool verbose = true; CheckTextTable tbl(verbose); pool_stat_t pool_stat; object_stat_sum_t& sum = pool_stat.stats.sum; // zero by default ASSERT_TRUE(sum.is_zero()); // nominal amount of space available for new objects in this pool uint64_t avail = 2016 * 1024 * 1024; pg_pool_t pool; pool.quota_max_objects = 2000; pool.quota_max_bytes = 2000 * 1024 * 1024; pool.size = 2; pool.type = pg_pool_t::TYPE_REPLICATED; pool.tier_of = 0; PGMap::dump_object_stat_sum(tbl, nullptr, pool_stat, avail, pool.get_size(), verbose, true, true, &pool); unsigned col = 0; ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(stringify(si_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(percentify(0), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(avail/pool.size)), tbl.get(0, col++)); ASSERT_EQ(stringify(si_u_t(pool.quota_max_objects)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(pool.quota_max_bytes)), tbl.get(0, col++)); ASSERT_EQ(stringify(si_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); } // with table, without formatter, verbose = false, empty, avail = 0 TEST(pgmap, dump_object_stat_sum_2) { bool verbose = false; CheckTextTable tbl(verbose); pool_stat_t pool_stat; object_stat_sum_t& sum = pool_stat.stats.sum; // zero by default ASSERT_TRUE(sum.is_zero()); // nominal amount of space available for new objects in this pool uint64_t avail = 0; pg_pool_t pool; pool.quota_max_objects = 2000; pool.quota_max_bytes = 2000 * 1024 * 1024; pool.size = 2; pool.type = pg_pool_t::TYPE_REPLICATED; PGMap::dump_object_stat_sum(tbl, nullptr, pool_stat, avail, pool.get_size(), verbose, true, true, &pool); unsigned col = 0; ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(stringify(si_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(0)), tbl.get(0, col++)); ASSERT_EQ(percentify(0), tbl.get(0, col++)); ASSERT_EQ(stringify(byte_u_t(avail/pool.size)), tbl.get(0, col++)); }
6,264
35.852941
86
cc
null
ceph-main/src/test/mon/moncap.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2012 Inktank * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include "include/stringify.h" #include "mon/MonCap.h" #include "gtest/gtest.h" using namespace std; const char *parse_good[] = { // MonCapMatch "allow *", "allow r", "allow rwx", "allow r", " allow rwx", "allow rwx ", " allow rwx ", " allow\t rwx ", "\tallow\nrwx\t", "allow service=foo x", "allow service=\"froo\" x", "allow profile osd", "allow profile osd-bootstrap", "allow profile \"mds-bootstrap\", allow *", "allow command \"a b c\"", "allow command abc", "allow command abc with arg=foo", "allow command abc with arg=foo arg2=bar", "allow command abc with arg=foo arg2=bar", "allow command abc with arg=foo arg2 prefix bar arg3 prefix baz", "allow command abc with arg=foo arg2 prefix \"bar bingo\" arg3 prefix baz", "allow command abc with arg regex \"^[0-9a-z.]*$\"", "allow command abc with arg regex \"\(invaluid regex\"", "allow service foo x", "allow service foo x; allow service bar x", "allow service foo w ;allow service bar x", "allow service foo w , allow service bar x", "allow service foo r , allow service bar x", "allow service foo_foo r, allow service bar r", "allow service foo-foo r, allow service bar r", "allow service \" foo \" w, allow service bar r", "allow command abc with arg=foo arg2=bar, allow service foo r", "allow command abc.def with arg=foo arg2=bar, allow service foo r", "allow command \"foo bar\" with arg=\"baz\"", "allow command \"foo bar\" with arg=\"baz.xx\"", "profile osd", "profile \"mds-bootstrap\", profile foo", "allow * network 1.2.3.4/24", "allow * network ::1/128", "allow * network [aa:bb::1]/128", "allow service=foo x network 1.2.3.4/16", "allow command abc network 1.2.3.4/8", "profile osd network 1.2.3.4/32", "allow profile mon network 1.2.3.4/32", 0 }; TEST(MonCap, ParseGood) { for (int i=0; parse_good[i]; ++i) { string str = parse_good[i]; MonCap cap; std::cout << "Testing good input: '" << str << "'" << std::endl; ASSERT_TRUE(cap.parse(str, &cout)); std::cout << " -> " << cap << std::endl; } } // these should stringify to the input value const char *parse_identity[] = { "allow *", "allow r", "allow rwx", "allow service foo x", "allow profile osd", "allow profile osd-bootstrap", "allow profile mds-bootstrap, allow *", "allow profile \"foo bar\", allow *", "allow command abc", "allow command \"a b c\"", "allow command abc with arg=foo", "allow command abc with arg=foo arg2=bar", "allow command abc with arg=foo arg2=bar", "allow command abc with arg=foo arg2 prefix bar arg3 prefix baz", "allow command abc with arg=foo arg2 prefix \"bar bingo\" arg3 prefix baz", "allow service foo x", "allow service foo x, allow service bar x", "allow service foo w, allow service bar x", "allow service foo r, allow service bar x", "allow service foo_foo r, allow service bar r", "allow service foo-foo r, allow service bar r", "allow service \" foo \" w, allow service bar r", "allow command abc with arg=foo arg2=bar, allow service foo r", 0 }; TEST(MonCap, ParseIdentity) { for (int i=0; parse_identity[i]; ++i) { string str = parse_identity[i]; MonCap cap; std::cout << "Testing good input: '" << str << "'" << std::endl; ASSERT_TRUE(cap.parse(str, &cout)); string out = stringify(cap); ASSERT_EQ(out, str); } } const char *parse_bad[] = { "allow r foo", "allow*", "foo allow *", "allow profile foo rwx", "allow profile", "allow profile foo bar rwx", "allow service bar", "allow command baz x", "allow r w", "ALLOW r", "allow rwx,", "allow rwx x", "allow r pool foo r", "allow wwx pool taco", "allow wwx pool taco^funny&chars", "allow rwx pool 'weird name''", "allow rwx object_prefix \"beforepool\" pool weird", "allow rwx auid 123 pool asdf", "allow command foo a prefix b", "allow command foo with a prefixb", "allow command foo with a = prefix b", "allow command foo with a prefix b c", 0 }; TEST(MonCap, ParseBad) { for (int i=0; parse_bad[i]; ++i) { string str = parse_bad[i]; MonCap cap; std::cout << "Testing bad input: '" << str << "'" << std::endl; ASSERT_FALSE(cap.parse(str, &cout)); } } TEST(MonCap, AllowAll) { MonCap cap; ASSERT_FALSE(cap.is_allow_all()); ASSERT_TRUE(cap.parse("allow r", NULL)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow w", NULL)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow x", NULL)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow rwx", NULL)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow rw", NULL)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow rx", NULL)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow wx", NULL)); ASSERT_FALSE(cap.is_allow_all()); cap.grants.clear(); ASSERT_TRUE(cap.parse("allow *", NULL)); ASSERT_TRUE(cap.is_allow_all()); ASSERT_TRUE(cap.is_capable(NULL, {}, "foo", "asdf", {}, true, true, true, {})); MonCap cap2; ASSERT_FALSE(cap2.is_allow_all()); cap2.set_allow_all(); ASSERT_TRUE(cap2.is_allow_all()); } TEST(MonCap, Network) { MonCap cap; bool r = cap.parse("allow * network 192.168.0.0/16, allow * network 10.0.0.0/8", NULL); ASSERT_TRUE(r); entity_addr_t a, b, c; a.parse("10.1.2.3"); b.parse("192.168.2.3"); c.parse("192.167.2.3"); ASSERT_TRUE(cap.is_capable(NULL, {}, "foo", "asdf", {}, true, true, true, a)); ASSERT_TRUE(cap.is_capable(NULL, {}, "foo", "asdf", {}, true, true, true, b)); ASSERT_FALSE(cap.is_capable(NULL, {}, "foo", "asdf", {}, true, true, true, c)); } TEST(MonCap, ProfileOSD) { MonCap cap; bool r = cap.parse("allow profile osd", NULL); ASSERT_TRUE(r); EntityName name; name.from_str("osd.123"); map<string,string> ca; ASSERT_TRUE(cap.is_capable(NULL, name, "osd", "", ca, true, false, false, {})); ASSERT_TRUE(cap.is_capable(NULL, name, "osd", "", ca, true, true, false, {})); ASSERT_TRUE(cap.is_capable(NULL, name, "osd", "", ca, true, true, true, {})); ASSERT_TRUE(cap.is_capable(NULL, name, "osd", "", ca, true, true, true, {})); ASSERT_TRUE(cap.is_capable(NULL, name, "mon", "", ca, true, false, false, {})); ASSERT_FALSE(cap.is_capable(NULL, name, "mds", "", ca, true, true, true, {})); ASSERT_FALSE(cap.is_capable(NULL, name, "mon", "", ca, true, true, true, {})); ca.clear(); ASSERT_FALSE(cap.is_capable(NULL, name, "", "config-key get", ca, true, true, true, {})); ca["key"] = "daemon-private/osd.123"; ASSERT_FALSE(cap.is_capable(NULL, name, "", "config-key get", ca, true, true, true, {})); ca["key"] = "daemon-private/osd.12/asdf"; ASSERT_FALSE(cap.is_capable(NULL, name, "", "config-key get", ca, true, true, true, {})); ca["key"] = "daemon-private/osd.123/"; ASSERT_TRUE(cap.is_capable(NULL, name, "", "config-key get", ca, true, true, true, {})); ASSERT_TRUE(cap.is_capable(NULL, name, "", "config-key get", ca, true, true, true, {})); ASSERT_TRUE(cap.is_capable(NULL, name, "", "config-key get", ca, true, true, true, {})); ca["key"] = "daemon-private/osd.123/foo"; ASSERT_TRUE(cap.is_capable(NULL, name, "", "config-key get", ca, true, true, true, {})); ASSERT_TRUE(cap.is_capable(NULL, name, "", "config-key put", ca, true, true, true, {})); ASSERT_TRUE(cap.is_capable(NULL, name, "", "config-key set", ca, true, true, true, {})); ASSERT_TRUE(cap.is_capable(NULL, name, "", "config-key exists", ca, true, true, true, {})); ASSERT_TRUE(cap.is_capable(NULL, name, "", "config-key delete", ca, true, true, true, {})); } TEST(MonCap, CommandRegEx) { MonCap cap; ASSERT_FALSE(cap.is_allow_all()); ASSERT_TRUE(cap.parse("allow command abc with arg regex \"^[0-9a-z.]*$\"", NULL)); EntityName name; name.from_str("osd.123"); ASSERT_TRUE(cap.is_capable(nullptr, name, "", "abc", {{"arg", "12345abcde"}}, true, true, true, {})); ASSERT_FALSE(cap.is_capable(nullptr, name, "", "abc", {{"arg", "~!@#$"}}, true, true, true, {})); ASSERT_TRUE(cap.parse("allow command abc with arg regex \"[*\"", NULL)); ASSERT_FALSE(cap.is_capable(nullptr, name, "", "abc", {{"arg", ""}}, true, true, true, {})); } TEST(MonCap, ProfileBootstrapRBD) { MonCap cap; ASSERT_FALSE(cap.is_allow_all()); ASSERT_TRUE(cap.parse("profile bootstrap-rbd", NULL)); EntityName name; name.from_str("mon.a"); ASSERT_TRUE(cap.is_capable(nullptr, name, "", "auth get-or-create", { {"entity", "client.rbd"}, {"caps_mon", "profile rbd"}, {"caps_osd", "profile rbd pool=foo, profile rbd-read-only"}, }, true, true, true, {})); ASSERT_FALSE(cap.is_capable(nullptr, name, "", "auth get-or-create", { {"entity", "client.rbd"}, {"caps_mon", "allow *"}, {"caps_osd", "profile rbd"}, }, true, true, true, {})); ASSERT_FALSE(cap.is_capable(nullptr, name, "", "auth get-or-create", { {"entity", "client.rbd"}, {"caps_mon", "profile rbd"}, {"caps_osd", "profile rbd pool=foo, allow *, profile rbd-read-only"}, }, true, true, true, {})); } TEST(MonCap, ProfileBootstrapRBDMirror) { MonCap cap; ASSERT_FALSE(cap.is_allow_all()); ASSERT_TRUE(cap.parse("profile bootstrap-rbd-mirror", NULL)); EntityName name; name.from_str("mon.a"); ASSERT_TRUE(cap.is_capable(nullptr, name, "", "auth get-or-create", { {"entity", "client.rbd"}, {"caps_mon", "profile rbd-mirror"}, {"caps_osd", "profile rbd pool=foo, profile rbd-read-only"}, }, true, true, true, {})); ASSERT_FALSE(cap.is_capable(nullptr, name, "", "auth get-or-create", { {"entity", "client.rbd"}, {"caps_mon", "profile rbd"}, {"caps_osd", "profile rbd pool=foo, profile rbd-read-only"}, }, true, true, true, {})); ASSERT_FALSE(cap.is_capable(nullptr, name, "", "auth get-or-create", { {"entity", "client.rbd"}, {"caps_mon", "allow *"}, {"caps_osd", "profile rbd"}, }, true, true, true, {})); ASSERT_FALSE(cap.is_capable(nullptr, name, "", "auth get-or-create", { {"entity", "client.rbd"}, {"caps_mon", "profile rbd-mirror"}, {"caps_osd", "profile rbd pool=foo, allow *, profile rbd-read-only"}, }, true, true, true, {})); } TEST(MonCap, ProfileRBD) { MonCap cap; ASSERT_FALSE(cap.is_allow_all()); ASSERT_TRUE(cap.parse("profile rbd", NULL)); EntityName name; name.from_str("mon.a"); ASSERT_FALSE(cap.is_capable(nullptr, name, "config-key", "config-key get", { {"key", "rbd/mirror/peer/1/1234"}, }, true, false, false, {})); } TEST(MonCap, ProfileRBDMirror) { MonCap cap; ASSERT_FALSE(cap.is_allow_all()); ASSERT_TRUE(cap.parse("profile rbd-mirror", NULL)); EntityName name; name.from_str("mon.a"); ASSERT_TRUE(cap.is_capable(nullptr, name, "config-key", "config-key get", { {"key", "rbd/mirror/peer/1/1234"}, }, true, false, false, {})); }
13,171
33.754617
101
cc
null
ceph-main/src/test/mon/test-mon-msg.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2014 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #include <stdio.h> #include <string.h> #include <iostream> #include <sstream> #include <time.h> #include <stdlib.h> #include <map> #include "global/global_init.h" #include "global/global_context.h" #include "common/async/context_pool.h" #include "common/ceph_argparse.h" #include "common/version.h" #include "common/dout.h" #include "common/debug.h" #include "common/ceph_mutex.h" #include "common/Timer.h" #include "common/errno.h" #include "mon/MonClient.h" #include "msg/Dispatcher.h" #include "include/err.h" #include <boost/scoped_ptr.hpp> #include "gtest/gtest.h" #include "common/config.h" #include "include/ceph_assert.h" #include "messages/MMonProbe.h" #include "messages/MRoute.h" #include "messages/MGenericMessage.h" #include "messages/MMonJoin.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_ #undef dout_prefix #define dout_prefix *_dout << "test-mon-msg " using namespace std; class MonClientHelper : public Dispatcher { protected: CephContext *cct; ceph::async::io_context_pool poolctx; Messenger *msg; MonClient monc; ceph::mutex lock = ceph::make_mutex("mon-msg-test::lock"); set<int> wanted; public: explicit MonClientHelper(CephContext *cct_) : Dispatcher(cct_), cct(cct_), poolctx(1), msg(NULL), monc(cct_, poolctx) { } int post_init() { dout(1) << __func__ << dendl; if (!msg) return -EINVAL; msg->add_dispatcher_tail(this); return 0; } int init_messenger() { dout(1) << __func__ << dendl; std::string public_msgr_type = cct->_conf->ms_public_type.empty() ? cct->_conf.get_val<std::string>("ms_type") : cct->_conf->ms_public_type; msg = Messenger::create(cct, public_msgr_type, entity_name_t::CLIENT(-1), "test-mon-msg", 0); ceph_assert(msg != NULL); msg->set_default_policy(Messenger::Policy::lossy_client(0)); dout(0) << __func__ << " starting messenger at " << msg->get_myaddrs() << dendl; msg->start(); return 0; } int init_monc() { dout(1) << __func__ << dendl; ceph_assert(msg != NULL); int err = monc.build_initial_monmap(); if (err < 0) { derr << __func__ << " error building monmap: " << cpp_strerror(err) << dendl; return err; } monc.set_messenger(msg); msg->add_dispatcher_head(&monc); monc.set_want_keys(CEPH_ENTITY_TYPE_MON); err = monc.init(); if (err < 0) { derr << __func__ << " monc init failed: " << cpp_strerror(err) << dendl; goto fail; } err = monc.authenticate(); if (err < 0) { derr << __func__ << " monc auth failed: " << cpp_strerror(err) << dendl; goto fail_monc; } monc.wait_auth_rotating(30.0); monc.renew_subs(); dout(0) << __func__ << " finished" << dendl; return 0; fail_monc: derr << __func__ << " failing monc" << dendl; monc.shutdown(); fail: return err; } void shutdown_messenger() { dout(0) << __func__ << dendl; msg->shutdown(); msg->wait(); } void shutdown_monc() { dout(0) << __func__ << dendl; monc.shutdown(); } void shutdown() { dout(0) << __func__ << dendl; shutdown_monc(); shutdown_messenger(); } MonMap *get_monmap() { return &monc.monmap; } int init() { int err = init_messenger(); if (err < 0) goto fail; err = init_monc(); if (err < 0) goto fail_msgr; err = post_init(); if (err < 0) goto fail_monc; return 0; fail_monc: shutdown_monc(); fail_msgr: shutdown_messenger(); fail: return err; } virtual void handle_wanted(Message *m) { } bool handle_message(Message *m) { dout(1) << __func__ << " " << *m << dendl; if (!is_wanted(m)) { dout(10) << __func__ << " not wanted" << dendl; return false; } handle_wanted(m); m->put(); return true; } bool ms_dispatch(Message *m) override { return handle_message(m); } void ms_handle_connect(Connection *con) override { } void ms_handle_remote_reset(Connection *con) override { } bool ms_handle_reset(Connection *con) override { return false; } bool ms_handle_refused(Connection *con) override { return false; } bool is_wanted(Message *m) { dout(20) << __func__ << " " << *m << " type " << m->get_type() << dendl; return (wanted.find(m->get_type()) != wanted.end()); } void add_wanted(int t) { dout(20) << __func__ << " type " << t << dendl; wanted.insert(t); } void rm_wanted(int t) { dout(20) << __func__ << " type " << t << dendl; wanted.erase(t); } void send_message(Message *m) { dout(15) << __func__ << " " << *m << dendl; monc.send_mon_message(m); } void wait() { msg->wait(); } }; class MonMsgTest : public MonClientHelper, public ::testing::Test { protected: int reply_type = 0; Message *reply_msg = nullptr; ceph::mutex lock = ceph::make_mutex("lock"); ceph::condition_variable cond; MonMsgTest() : MonClientHelper(g_ceph_context) { } public: void SetUp() override { reply_type = -1; if (reply_msg) { reply_msg->put(); reply_msg = nullptr; } ASSERT_EQ(init(), 0); } void TearDown() override { shutdown(); if (reply_msg) { reply_msg->put(); reply_msg = nullptr; } } void handle_wanted(Message *m) override { std::lock_guard l{lock}; // caller will put() after they call us, so hold on to a ref m->get(); reply_msg = m; cond.notify_all(); } Message *send_wait_reply(Message *m, int t, double timeout=30.0) { std::unique_lock l{lock}; reply_type = t; add_wanted(t); send_message(m); std::cv_status status = std::cv_status::no_timeout; if (timeout > 0) { utime_t s = ceph_clock_now(); status = cond.wait_for(l, ceph::make_timespan(timeout)); utime_t e = ceph_clock_now(); dout(20) << __func__ << " took " << (e-s) << " seconds" << dendl; } else { cond.wait(l); } rm_wanted(t); l.unlock(); if (status == std::cv_status::timeout) { dout(20) << __func__ << " error: " << cpp_strerror(ETIMEDOUT) << dendl; return (Message*)((long)-ETIMEDOUT); } if (!reply_msg) dout(20) << __func__ << " reply_msg is nullptr" << dendl; else dout(20) << __func__ << " reply_msg " << *reply_msg << dendl; return reply_msg; } }; TEST_F(MonMsgTest, MMonProbeTest) { Message *m = new MMonProbe(get_monmap()->fsid, MMonProbe::OP_PROBE, "b", false, ceph_release()); Message *r = send_wait_reply(m, MSG_MON_PROBE); ASSERT_NE(IS_ERR(r), 0); ASSERT_EQ(PTR_ERR(r), -ETIMEDOUT); } TEST_F(MonMsgTest, MRouteTest) { Message *payload = new MGenericMessage(CEPH_MSG_SHUTDOWN); MRoute *m = new MRoute; m->msg = payload; Message *r = send_wait_reply(m, CEPH_MSG_SHUTDOWN); // we want an error ASSERT_NE(IS_ERR(r), 0); ASSERT_EQ(PTR_ERR(r), -ETIMEDOUT); } /* MMonScrub and MMonSync have other safeguards in place that prevent * us from actually receiving a reply even if the message is handled * by the monitor due to lack of cap checking. */ TEST_F(MonMsgTest, MMonJoin) { Message *m = new MMonJoin(get_monmap()->fsid, string("client"), msg->get_myaddrs()); send_wait_reply(m, MSG_MON_PAXOS, 10.0); int r = monc.get_monmap(); ASSERT_EQ(r, 0); ASSERT_FALSE(monc.monmap.contains("client")); } int main(int argc, char *argv[]) { auto args = argv_to_vec(argc, argv); auto cct = global_init(nullptr, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); g_ceph_context->_conf.apply_changes(nullptr); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
8,231
23.211765
144
cc
null
ceph-main/src/test/mon/test_election.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "gtest/gtest.h" #include "mon/ElectionLogic.h" #include "mon/ConnectionTracker.h" #include "common/dout.h" #include "global/global_context.h" #include "global/global_init.h" #include "common/common_init.h" #include "common/ceph_argparse.h" using namespace std; #define dout_subsys ceph_subsys_test #undef dout_prefix #define dout_prefix _prefix(_dout, prefix_name(), timestep_count()) static ostream& _prefix(std::ostream *_dout, const char *prefix, int timesteps) { return *_dout << prefix << timesteps << " "; } const char* prefix_name() { return "test_election: "; } int timestep_count() { return -1; } int main(int argc, char **argv) { vector<const char*> args(argv, argv+argc); bool user_set_debug = false; for (auto& arg : args) { if (strncmp("--debug_mon", arg, 11) == 0) user_set_debug = true; } auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); if (!user_set_debug) g_ceph_context->_conf.set_val("debug mon", "0/20"); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } class Owner; struct Election { map<int, Owner*> electors; map<int, set<int> > blocked_messages; int count; ElectionLogic::election_strategy election_strategy; int ping_interval; set<int> disallowed_leaders; vector< function<void()> > messages; int pending_election_messages; int timesteps_run = 0; int last_quorum_change = 0; int last_quorum_formed = -1; set<int> last_quorum_reported; int last_leader = -1; Election(int c, ElectionLogic::election_strategy es, int pingi=1, double tracker_halflife=5); ~Election(); // ElectionOwner interfaces int get_paxos_size() { return count; } const set<int>& get_disallowed_leaders() const { return disallowed_leaders; } void propose_to(int from, int to, epoch_t e, bufferlist& cbl); void defer_to(int from, int to, epoch_t e); void claim_victory(int from, int to, epoch_t e, const set<int>& members); void accept_victory(int from, int to, epoch_t e); void report_quorum(const set<int>& quorum); void queue_stable_message(int from, int to, function<void()> m); void queue_timeout_message(int from, int to, function<void()> m); void queue_stable_or_timeout(int from, int to, function<void()> m, function<void()> t); void queue_election_message(int from, int to, function<void()> m); // test runner interfaces int run_timesteps(int max); void start_one(int who); void start_all(); bool election_stable() const; bool quorum_stable(int timesteps_stable) const; bool all_agree_on_leader() const; bool check_epoch_agreement() const; void block_messages(int from, int to); void block_bidirectional_messages(int a, int b); void unblock_messages(int from, int to); void unblock_bidirectional_messages(int a, int b); void add_disallowed_leader(int disallowed) { disallowed_leaders.insert(disallowed); } void remove_elector(int rank); const char* prefix_name() const { return "Election: "; } int timestep_count() const { return timesteps_run; } }; struct Owner : public ElectionOwner, RankProvider { Election *parent; int rank; epoch_t persisted_epoch; bool ever_joined; ConnectionTracker peer_tracker; ElectionLogic logic; set<int> quorum; int victory_accepters; int timer_steps; // timesteps until we trigger timeout bool timer_election; // the timeout is for normal election, or victory bool rank_deleted = false; string prefix_str; Owner(int r, ElectionLogic::election_strategy es, double tracker_halflife, Election *p) : parent(p), rank(r), persisted_epoch(0), ever_joined(false), peer_tracker(this, rank, tracker_halflife, 5, g_ceph_context), logic(this, es, &peer_tracker, 0.0005, g_ceph_context), victory_accepters(0), timer_steps(-1), timer_election(true) { std::stringstream str; str << "Owner" << rank << " "; prefix_str = str.str(); } // in-memory store: just save to variable void persist_epoch(epoch_t e) { persisted_epoch = e; } // in-memory store: just return variable epoch_t read_persisted_epoch() const { return persisted_epoch; } // in-memory store: don't need to validate void validate_store() { return; } // don't need to do anything with our state right now void notify_bump_epoch() {} void notify_rank_removed(int removed_rank) { ldout(g_ceph_context, 1) << "removed_rank: " << removed_rank << dendl; ldout(g_ceph_context, 1) << "rank before: " << rank << dendl; if (removed_rank < rank) { --rank; } peer_tracker.notify_rank_removed(removed_rank, rank); ldout(g_ceph_context, 1) << "rank after: " << rank << dendl; } void notify_deleted() { rank_deleted = true; rank = -1; cancel_timer(); } // pass back to ElectionLogic; we don't need this redirect ourselves void trigger_new_election() { ceph_assert (!rank_deleted); logic.start(); } int get_my_rank() const { return rank; } // we don't need to persist scores as we don't reset and lose memory state void persist_connectivity_scores() {} void propose_to_peers(epoch_t e, bufferlist& bl) { ceph_assert (!rank_deleted); for (int i = 0; i < parent->get_paxos_size(); ++i) { if (i == rank) continue; parent->propose_to(rank, i, e, bl); } } void reset_election() { ceph_assert (!rank_deleted); _start(); logic.start(); } bool ever_participated() const { return ever_joined; } unsigned paxos_size() const { return parent->get_paxos_size(); } const set<int>& get_disallowed_leaders() const { return parent->get_disallowed_leaders(); } void cancel_timer() { timer_steps = -1; } void reset_timer(int steps) { cancel_timer(); timer_steps = 3 + steps; // FIXME? magic number, current step + roundtrip timer_election = true; } void start_victory_timer() { cancel_timer(); timer_election = false; timer_steps = 3; // FIXME? current step + roundtrip } void _start() { reset_timer(0); quorum.clear(); } void _defer_to(int who) { ceph_assert (!rank_deleted); parent->defer_to(rank, who, logic.get_epoch()); reset_timer(0); // wtf does changing this 0->1 cause breakage? } void message_victory(const std::set<int>& members) { ceph_assert (!rank_deleted); for (auto i : members) { if (i == rank) continue; parent->claim_victory(rank, i, logic.get_epoch(), members); } start_victory_timer(); quorum = members; victory_accepters = 1; } bool is_current_member(int r) const { return quorum.count(r) != 0; } void receive_propose(int from, epoch_t e, ConnectionTracker *oct) { if (rank_deleted) return; logic.receive_propose(from, e, oct); delete oct; } void receive_ack(int from, epoch_t e) { if (rank_deleted) return; if (e < logic.get_epoch()) return; logic.receive_ack(from, e); } void receive_victory_claim(int from, epoch_t e, const set<int>& members) { if (rank_deleted) return; if (e < logic.get_epoch()) return; if (logic.receive_victory_claim(from, e)) { quorum = members; cancel_timer(); parent->accept_victory(rank, from, e); } } void receive_victory_ack(int from, epoch_t e) { if (rank_deleted) return; if (e < logic.get_epoch()) return; ++victory_accepters; if (victory_accepters == static_cast<int>(quorum.size())) { cancel_timer(); parent->report_quorum(quorum); } } void receive_scores(bufferlist bl) { ConnectionTracker oct(bl, g_ceph_context); peer_tracker.receive_peer_report(oct); ldout(g_ceph_context, 10) << "received scores " << oct << dendl; } void receive_ping(int from_rank, bufferlist bl) { ldout(g_ceph_context, 6) << "receive ping from " << from_rank << dendl; peer_tracker.report_live_connection(from_rank, parent->ping_interval); receive_scores(bl); } void receive_ping_timeout(int from_rank) { ldout(g_ceph_context, 6) << "timeout ping from " << from_rank << dendl; peer_tracker.report_dead_connection(from_rank, parent->ping_interval); } void election_timeout() { ldout(g_ceph_context, 2) << "election epoch " << logic.get_epoch() << " timed out for " << rank << ", electing me:" << logic.electing_me << ", acked_me:" << logic.acked_me << dendl; ceph_assert (!rank_deleted); logic.end_election_period(); } void victory_timeout() { ldout(g_ceph_context, 2) << "victory epoch " << logic.get_epoch() << " timed out for " << rank << ", electing me:" << logic.electing_me << ", acked_me:" << logic.acked_me << dendl; ceph_assert (!rank_deleted); reset_election(); } void encode_scores(bufferlist& bl) { encode(peer_tracker, bl); } void send_pings() { ceph_assert (!rank_deleted); if (!parent->ping_interval || parent->timesteps_run % parent->ping_interval != 0) { return; } bufferlist bl; encode_scores(bl); for (int i = 0; i < parent->get_paxos_size(); ++i) { if (i == rank) continue; Owner *o = parent->electors[i]; parent->queue_stable_or_timeout(rank, i, [o, r=rank, bl] { o->receive_ping(r, bl); }, [o, r=rank] { o->receive_ping_timeout(r); } ); } } void notify_timestep() { ceph_assert (!rank_deleted); assert(timer_steps != 0); if (timer_steps > 0) { --timer_steps; } if (timer_steps == 0) { if (timer_election) { election_timeout(); } else { victory_timeout(); } } send_pings(); } const char *prefix_name() const { return prefix_str.c_str(); } int timestep_count() const { return parent->timesteps_run; } }; Election::Election(int c, ElectionLogic::election_strategy es, int pingi, double tracker_halflife) : count(c), election_strategy(es), ping_interval(pingi), pending_election_messages(0), timesteps_run(0), last_quorum_change(0), last_quorum_formed(-1) { for (int i = 0; i < count; ++i) { electors[i] = new Owner(i, election_strategy, tracker_halflife, this); } } Election::~Election() { { for (auto i : electors) { delete i.second; } } } void Election::queue_stable_message(int from, int to, function<void()> m) { if (!blocked_messages[from].count(to)) { messages.push_back(m); } } void Election::queue_election_message(int from, int to, function<void()> m) { if (last_quorum_reported.count(from)) { last_quorum_change = timesteps_run; last_quorum_reported.clear(); last_leader = -1; } if (!blocked_messages[from].count(to)) { bufferlist bl; electors[from]->encode_scores(bl); Owner *o = electors[to]; messages.push_back([this,m,o,bl] { --this->pending_election_messages; o->receive_scores(bl); m(); }); ++pending_election_messages; } } void Election::queue_timeout_message(int from, int to, function<void()> m) { ceph_assert(blocked_messages[from].count(to)); messages.push_back(m); } void Election::queue_stable_or_timeout(int from, int to, function<void()> m, function<void()> t) { if (blocked_messages[from].count(to)) { queue_timeout_message(from, to, t); } else { queue_stable_message(from, to, m); } } void Election::defer_to(int from, int to, epoch_t e) { Owner *o = electors[to]; queue_election_message(from, to, [o, from, e] { o->receive_ack(from, e); }); } void Election::propose_to(int from, int to, epoch_t e, bufferlist& cbl) { Owner *o = electors[to]; ConnectionTracker *oct = NULL; if (cbl.length()) { oct = new ConnectionTracker(cbl, g_ceph_context); // we leak these on blocked cons, meh } queue_election_message(from, to, [o, from, e, oct] { o->receive_propose(from, e, oct); }); } void Election::claim_victory(int from, int to, epoch_t e, const set<int>& members) { Owner *o = electors[to]; queue_election_message(from, to, [o, from, e, members] { o->receive_victory_claim(from, e, members); }); } void Election::accept_victory(int from, int to, epoch_t e) { Owner *o = electors[to]; queue_election_message(from, to, [o, from, e] { o->receive_victory_ack(from, e); }); } void Election::report_quorum(const set<int>& quorum) { for (int i : quorum) { electors[i]->ever_joined = true; } last_quorum_formed = last_quorum_change = timesteps_run; last_quorum_reported = quorum; last_leader = electors[*(quorum.begin())]->logic.get_election_winner(); } int Election::run_timesteps(int max) { vector< function<void()> > current_m; int steps = 0; for (; (!max || steps < max) && // we have timesteps left AND ONE OF (pending_election_messages || // there are messages pending. !election_stable()); // somebody's not happy and will act in future ++steps) { current_m.clear(); current_m.swap(messages); ++timesteps_run; for (auto& m : current_m) { m(); } for (auto o : electors) { o.second->notify_timestep(); } } return steps; } void Election::start_one(int who) { assert(who < static_cast<int>(electors.size())); electors[who]->logic.start(); } void Election::start_all() { for (auto e : electors) { e.second->logic.start(); } } bool Election::election_stable() const { // see if anybody has a timer running for (auto i : electors) { if (i.second->timer_steps != -1) { ldout(g_ceph_context, 30) << "rank " << i.first << " has timer value " << i.second->timer_steps << dendl; return false; } } return (pending_election_messages == 0); } bool Election::quorum_stable(int timesteps_stable) const { ldout(g_ceph_context, 1) << "quorum_stable? last formed:" << last_quorum_formed << ", last changed " << last_quorum_change << ", last reported members " << last_quorum_reported << dendl; if (last_quorum_reported.empty()) { return false; } if (last_quorum_formed < last_quorum_change) { return false; } for (auto i : last_quorum_reported) { if (electors.find(i)->second->timer_steps != -1) { return false; } } if (timesteps_run - timesteps_stable > last_quorum_change) return true; return election_stable(); } bool Election::all_agree_on_leader() const { int leader = electors.find(0)->second->logic.get_election_winner(); ldout(g_ceph_context, 10) << "all_agree_on_leader on " << leader << dendl; for (auto& i: electors) { if (leader != i.second->logic.get_election_winner()) { ldout(g_ceph_context, 10) << "rank " << i.first << " has different leader " << i.second->logic.get_election_winner() << dendl; return false; } } if (disallowed_leaders.count(leader)) { ldout(g_ceph_context, 10) << "that leader is disallowed! member of " << disallowed_leaders << dendl; return false; } return true; } bool Election::check_epoch_agreement() const { epoch_t epoch = electors.find(0)->second->logic.get_epoch(); for (auto& i : electors) { if (epoch != i.second->logic.get_epoch()) { return false; } } return true; } void Election::block_messages(int from, int to) { blocked_messages[from].insert(to); } void Election::block_bidirectional_messages(int a, int b) { block_messages(a, b); block_messages(b, a); } void Election::unblock_messages(int from, int to) { blocked_messages[from].erase(to); } void Election::unblock_bidirectional_messages(int a, int b) { unblock_messages(a, b); unblock_messages(b, a); } void Election::remove_elector(int rank) { for (auto ei = electors.begin(); ei != electors.end(); ) { if (ei->first == rank) { ei->second->notify_deleted(); electors.erase(ei++); continue; } ei->second->notify_rank_removed(rank); if (ei->first > rank) { electors[ei->first - 1] = ei->second; electors.erase(ei++); continue; } ++ei; } for (auto bi = blocked_messages.begin(); bi != blocked_messages.end(); ) { if (bi->first == rank) { blocked_messages.erase(bi++); continue; } bi->second.erase(rank); for (auto i = bi->second.upper_bound(rank); i != bi->second.end();) { bi->second.insert(*i - 1); bi->second.erase(*(i++)); } ++bi; } --count; } void single_startup_election_completes(ElectionLogic::election_strategy strategy) { for (int starter = 0; starter < 5; ++starter) { Election election(5, strategy); election.start_one(starter); // This test is not actually legit since you should start // all the ElectionLogics, but it seems to work int steps = election.run_timesteps(0); ldout(g_ceph_context, 1) << "ran in " << steps << " timesteps" << dendl; ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.quorum_stable(6)); // double the timer_steps we use ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } } void everybody_starts_completes(ElectionLogic::election_strategy strategy) { Election election(5, strategy); election.start_all(); int steps = election.run_timesteps(0); ldout(g_ceph_context, 1) << "ran in " << steps << " timesteps" << dendl; ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.quorum_stable(6)); // double the timer_steps we use ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } void blocked_connection_continues_election(ElectionLogic::election_strategy strategy) { Election election(5, strategy); election.block_bidirectional_messages(0, 1); election.start_all(); int steps = election.run_timesteps(100); ldout(g_ceph_context, 1) << "ran in " << steps << " timesteps" << dendl; // This is a failure mode! ASSERT_FALSE(election.election_stable()); ASSERT_FALSE(election.quorum_stable(6)); // double the timer_steps we use election.unblock_bidirectional_messages(0, 1); steps = election.run_timesteps(100); ldout(g_ceph_context, 1) << "ran in " << steps << " timesteps" << dendl; ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.quorum_stable(6)); // double the timer_steps we use ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } void blocked_connection_converges_election(ElectionLogic::election_strategy strategy) { Election election(5, strategy); election.block_bidirectional_messages(0, 1); election.start_all(); int steps = election.run_timesteps(100); ldout(g_ceph_context, 1) << "ran in " << steps << " timesteps" << dendl; ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); election.unblock_bidirectional_messages(0, 1); steps = election.run_timesteps(100); ldout(g_ceph_context, 1) << "ran in " << steps << " timesteps" << dendl; ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } void disallowed_doesnt_win(ElectionLogic::election_strategy strategy) { int MON_COUNT = 5; for (int i = 0; i < MON_COUNT - 1; ++i) { Election election(MON_COUNT, strategy); for (int j = 0; j <= i; ++j) { election.add_disallowed_leader(j); } election.start_all(); int steps = election.run_timesteps(0); ldout(g_ceph_context, 1) << "ran in " << steps << " timesteps" << dendl; ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.quorum_stable(6)); // double the timer_steps we use ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); int leader = election.electors[0]->logic.get_election_winner(); for (int j = 0; j <= i; ++j) { ASSERT_NE(j, leader); } } for (int i = MON_COUNT - 1; i > 0; --i) { Election election(MON_COUNT, strategy); for (int j = i; j <= MON_COUNT - 1; ++j) { election.add_disallowed_leader(j); } election.start_all(); int steps = election.run_timesteps(0); ldout(g_ceph_context, 1) << "ran in " << steps << " timesteps" << dendl; ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.quorum_stable(6)); // double the timer_steps we use ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); int leader = election.electors[0]->logic.get_election_winner(); for (int j = i; j < MON_COUNT; ++j) { ASSERT_NE(j, leader); } } } void converges_after_flapping(ElectionLogic::election_strategy strategy) { Election election(5, strategy); auto block_cons = [&] { auto& e = election; // leave 4 connected to both sides so it will trigger but not trivially win e.block_bidirectional_messages(0, 2); e.block_bidirectional_messages(0, 3); e.block_bidirectional_messages(1, 2); e.block_bidirectional_messages(1, 3); }; auto unblock_cons = [&] { auto& e = election; e.unblock_bidirectional_messages(0, 2); e.unblock_bidirectional_messages(0, 3); e.unblock_bidirectional_messages(1, 2); e.unblock_bidirectional_messages(1, 3); }; block_cons(); election.start_all(); for (int i = 0; i < 5; ++i) { election.run_timesteps(5); unblock_cons(); election.run_timesteps(5); block_cons(); } unblock_cons(); election.run_timesteps(100); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.quorum_stable(6)); // double the timer_steps we use ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } void converges_while_flapping(ElectionLogic::election_strategy strategy) { Election election(5, strategy); auto block_cons = [&] { auto& e = election; // leave 4 connected to both sides so it will trigger but not trivially win e.block_bidirectional_messages(0, 2); e.block_bidirectional_messages(0, 3); e.block_bidirectional_messages(1, 2); e.block_bidirectional_messages(1, 3); }; auto unblock_cons = [&] { auto& e = election; e.unblock_bidirectional_messages(0, 2); e.unblock_bidirectional_messages(0, 3); e.unblock_bidirectional_messages(1, 2); e.unblock_bidirectional_messages(1, 3); }; block_cons(); election.start_all(); for (int i = 0; i < 5; ++i) { election.run_timesteps(10); ASSERT_TRUE(election.quorum_stable(6)); unblock_cons(); election.run_timesteps(5); block_cons(); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } unblock_cons(); election.run_timesteps(100); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.quorum_stable(6)); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } void netsplit_with_disallowed_tiebreaker_converges(ElectionLogic::election_strategy strategy) { Election election(5, strategy); election.add_disallowed_leader(4); auto netsplit = [&] { auto& e = election; e.block_bidirectional_messages(0, 2); e.block_bidirectional_messages(0, 3); e.block_bidirectional_messages(1, 2); e.block_bidirectional_messages(1, 3); }; auto unsplit = [&] { auto& e = election; e.unblock_bidirectional_messages(0, 2); e.unblock_bidirectional_messages(0, 3); e.unblock_bidirectional_messages(1, 2); e.unblock_bidirectional_messages(1, 3); }; // hmm, we don't have timeouts to call elections automatically yet auto call_elections = [&] { for (auto i : election.electors) { i.second->trigger_new_election(); } }; // turn everybody on, run happy for a while election.start_all(); election.run_timesteps(0); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.quorum_stable(6)); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); int starting_leader = election.last_leader; // do some netsplits, but leave disallowed tiebreaker alive for (int i = 0; i < 5; ++i) { netsplit(); call_elections(); election.run_timesteps(15); // tests fail when I run 10 because 0 and 1 time out on same timestamp for some reason, why? // this ASSERT_EQ only holds while we bias for ranks ASSERT_EQ(starting_leader, election.last_leader); ASSERT_TRUE(election.quorum_stable(6)); ASSERT_FALSE(election.election_stable()); unsplit(); call_elections(); election.run_timesteps(10); ASSERT_EQ(starting_leader, election.last_leader); ASSERT_TRUE(election.quorum_stable(6)); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } // now disconnect the tiebreaker and make sure nobody can win int presplit_quorum_time = election.last_quorum_formed; netsplit(); election.block_bidirectional_messages(4, 0); election.block_bidirectional_messages(4, 1); election.block_bidirectional_messages(4, 2); election.block_bidirectional_messages(4, 3); call_elections(); election.run_timesteps(100); ASSERT_EQ(election.last_quorum_formed, presplit_quorum_time); // now let in the previously-losing side election.unblock_bidirectional_messages(4, 2); election.unblock_bidirectional_messages(4, 3); call_elections(); election.run_timesteps(100); ASSERT_TRUE(election.quorum_stable(50)); ASSERT_FALSE(election.election_stable()); // now reconnect everybody unsplit(); election.unblock_bidirectional_messages(4, 0); election.unblock_bidirectional_messages(4, 1); call_elections(); election.run_timesteps(100); ASSERT_TRUE(election.quorum_stable(50)); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } void handles_singly_connected_peon(ElectionLogic::election_strategy strategy) { Election election(5, strategy); election.block_bidirectional_messages(0, 1); election.block_bidirectional_messages(0, 2); election.block_bidirectional_messages(0, 3); election.block_bidirectional_messages(0, 4); election.start_all(); election.run_timesteps(20); ASSERT_TRUE(election.quorum_stable(5)); ASSERT_FALSE(election.election_stable()); election.unblock_bidirectional_messages(0, 1); election.run_timesteps(100); ASSERT_TRUE(election.quorum_stable(50)); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); election.block_bidirectional_messages(0, 1); election.unblock_bidirectional_messages(0, 4); for (auto i : election.electors) { i.second->trigger_new_election(); } election.run_timesteps(15); ASSERT_TRUE(election.quorum_stable(50)); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } ConnectionReport *get_connection_reports(ConnectionTracker& ct) { return &ct.my_reports; } map<int,ConnectionReport> *get_peer_reports(ConnectionTracker& ct) { return &ct.peer_reports; } void handles_outdated_scoring(ElectionLogic::election_strategy strategy) { Election election(3, strategy, 5); // ping every 5 timesteps so they start elections before settling scores! // start everybody up and run for a bit election.start_all(); election.run_timesteps(20); ASSERT_TRUE(election.quorum_stable(5)); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); // now mess up the scores to disagree ConnectionTracker& ct0 = election.electors[0]->peer_tracker; ConnectionReport& cr0 = *get_connection_reports(ct0); cr0.history[1] = 0.5; cr0.history[2] = 0.5; ct0.increase_version(); ConnectionTracker& ct1 = election.electors[1]->peer_tracker; ConnectionReport& cr1 = *get_connection_reports(ct1); cr1.history[0] = 0.5; cr1.history[2] = 0.5; ct1.increase_version(); ConnectionTracker& ct2 = election.electors[2]->peer_tracker; ConnectionReport& cr2 = *get_connection_reports(ct2); cr2.history[0] = 0.5; map<int,ConnectionReport>&cp2 = *get_peer_reports(ct2); cp2[0].history[2] = 0; cp2[1].history[2] = 0; ct2.increase_version(); election.ping_interval = 0; // disable pinging to update the scores ldout(g_ceph_context, 5) << "mangled the scores to be different" << dendl; election.start_all(); election.run_timesteps(50); ASSERT_TRUE(election.quorum_stable(30)); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } void handles_disagreeing_connectivity(ElectionLogic::election_strategy strategy) { Election election(5, strategy, 5); // ping every 5 timesteps so they start elections before settling scores! // start everybody up and run for a bit election.start_all(); election.run_timesteps(20); ASSERT_TRUE(election.quorum_stable(5)); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); // block all the connections for (int i = 0; i < 5; ++i) { for (int j = i+1; j < 5; ++j) { election.block_bidirectional_messages(i, j); } } // now start them electing, which will obviously fail election.start_all(); election.run_timesteps(50); // let them all demote scores of their peers ASSERT_FALSE(election.quorum_stable(10)); ASSERT_FALSE(election.election_stable()); // now reconnect them, at which point they should start running an election before exchanging scores for (int i = 0; i < 5; ++i) { for (int j = i+1; j < 5; ++j) { election.unblock_bidirectional_messages(i, j); } } election.run_timesteps(100); // these will pass if the nodes managed to converge on scores, but I expect failure ASSERT_TRUE(election.quorum_stable(5)); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } void handles_removing_ranks(ElectionLogic::election_strategy strategy) { ceph_assert(strategy == ElectionLogic::CONNECTIVITY); for (int deletee = 0; deletee < 5; ++deletee) { Election election(5, strategy); election.start_all(); int steps = election.run_timesteps(0); ldout(g_ceph_context, 10) << "ran in " << steps << " timesteps" << dendl; ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.quorum_stable(6)); // double the timer_steps we use ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); election.remove_elector(deletee); ldout(g_ceph_context, 1) << "removed rank " << deletee << " from set" << dendl; election.start_all(); steps = election.run_timesteps(0); ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.quorum_stable(6)); // double the timer_steps we use ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } { Election election(7, strategy); for (int i = 0; i < (7 - 3); ++i) { election.start_all(); election.remove_elector(0); int steps = election.run_timesteps(0); ldout(g_ceph_context, 1) << "ran in " << steps << " timesteps" << dendl; ASSERT_TRUE(election.election_stable()); ASSERT_TRUE(election.quorum_stable(6)); // double the timer_steps we use ASSERT_TRUE(election.all_agree_on_leader()); ASSERT_TRUE(election.check_epoch_agreement()); } } } // TODO: write a test with more complicated connectivity graphs and make sure // they are stable with multiple disconnected ranks pinging peons // TODO: Write a test that disallowing and disconnecting 0 is otherwise stable? // TODO: figure out how to test for bumping election epochs with changing scores, // a la what happened in run // http://pulpito.ceph.com/gregf-2019-11-26_10:50:50-rados:monthrash-wip-elector-distro-basic-mira/ #define test_classic(utest) TEST(classic, utest) { utest(ElectionLogic::CLASSIC); } #define test_disallowed(utest) TEST(disallowed, utest) { utest(ElectionLogic::DISALLOW); } #define test_connectivity(utest) TEST(connectivity, utest) { utest(ElectionLogic::CONNECTIVITY); } // TODO: test for expected failures; gtest probably supports that? test_classic(single_startup_election_completes) test_classic(everybody_starts_completes) test_classic(blocked_connection_continues_election) test_classic(converges_after_flapping) test_disallowed(single_startup_election_completes) test_disallowed(everybody_starts_completes) test_disallowed(blocked_connection_continues_election) test_disallowed(disallowed_doesnt_win) test_disallowed(converges_after_flapping) /* skip single_startup_election_completes because we crash on init conditions. That's fine since as noted above it's not quite following the rules anyway. */ test_connectivity(everybody_starts_completes) test_connectivity(blocked_connection_converges_election) test_connectivity(disallowed_doesnt_win) test_connectivity(converges_after_flapping) test_connectivity(converges_while_flapping) test_connectivity(netsplit_with_disallowed_tiebreaker_converges) test_connectivity(handles_singly_connected_peon) test_connectivity(handles_disagreeing_connectivity) test_connectivity(handles_outdated_scoring) test_connectivity(handles_removing_ranks)
33,536
32.403386
124
cc
null
ceph-main/src/test/mon/test_log_rss_usage.cc
#include <sys/types.h> #include <cstdint> #include <dirent.h> #include <errno.h> #include <vector> #include <string> #include <iostream> #include <fstream> #include <stdlib.h> #include <stdio.h> #include <unistd.h> using namespace std; int getPidByName(string procName) { int pid = -1; // Open the /proc directory DIR *dp = opendir("/proc"); if (dp != NULL) { // Enumerate all entries in '/proc' until process is found struct dirent *dirp; while (pid < 0 && (dirp = readdir(dp))) { // Skip non-numeric entries int id = atoi(dirp->d_name); if (id > 0) { // Read contents of virtual /proc/{pid}/cmdline file string cmdPath = string("/proc/") + dirp->d_name + "/cmdline"; ifstream cmdFile(cmdPath.c_str()); string cmdLine; getline(cmdFile, cmdLine); if (!cmdLine.empty()) { // Keep first cmdline item which contains the program path size_t pos = cmdLine.find('\0'); if (pos != string::npos) { cmdLine = cmdLine.substr(0, pos); } // Get program name only, removing the path pos = cmdLine.rfind('/'); if (pos != string::npos) { cmdLine = cmdLine.substr(pos + 1); } // Compare against requested process name if (procName == cmdLine) { pid = id; } } } } } closedir(dp); return pid; } uint64_t getRssUsage(string pid) { int totalSize = 0; int resSize = 0; string statmPath = string("/proc/") + pid + "/statm"; ifstream buffer(statmPath); buffer >> totalSize >> resSize; buffer.close(); long page_size = sysconf(_SC_PAGE_SIZE); uint64_t rss = resSize * page_size; return rss; } int main(int argc, char* argv[]) { if (argc != 2) { cout << "Syntax: " << "ceph_test_log_rss_usage <process name>" << endl; exit(EINVAL); } uint64_t rss = 0; int pid = getPidByName(argv[1]); string rssUsage; // Use the pid to get RSS memory usage // and print it to stdout if (pid != -1) { rss = getRssUsage(to_string(pid)); } else { cout << "Process " << argv[1] << " NOT FOUND!\n" << endl; exit(ESRCH); } rssUsage = to_string(rss) + ":" + to_string(pid) + ":"; cout << rssUsage.c_str() << endl; return 0; }
2,348
21.805825
70
cc
null
ceph-main/src/test/mon/test_mon_memory_target.cc
#include <algorithm> #include <cmath> #include <iostream> #include <string> #include <numeric> #include <regex> #include <system_error> #include <boost/process.hpp> #include <boost/tokenizer.hpp> namespace bp = boost::process; using namespace std; int main(int argc, char** argv) { cout << "Mon Memory Target Test" << endl; if (argc != 2) { cout << "Syntax: " << "ceph_test_mon_memory_target <mon-memory-target-bytes>" << endl; exit(EINVAL); } string target_directory("/var/log/ceph/"); unsigned long maxallowed = stoul(argv[1], nullptr, 10); regex reg(R"(cache_size:(\d*)\s)"); string grep_command("grep _set_new_cache_sizes " + target_directory + "ceph-mon.a.log"); bp::ipstream is; error_code ec; bp::child grep(grep_command, bp::std_out > is, ec); if (ec) { cout << "Error grepping logs! Exiting" << endl; cout << "Error: " << ec.value() << " " << ec.message() << endl; exit(ec.value()); } string line; vector<unsigned long> results; while (grep.running() && getline(is, line) && !line.empty()) { smatch match; if (regex_search(line, match, reg)) { results.push_back(stoul(match[1].str())); } } if (results.empty()) { cout << "Error: No grep results found!" << endl; exit(ENOENT); } auto maxe = *(max_element(results.begin(), results.end())); cout << "Results for mon_memory_target:" << endl; cout << "Max: " << maxe << endl; cout << "Min: " << *(min_element(results.begin(), results.end())) << endl; auto sum = accumulate(results.begin(), results.end(), static_cast<unsigned long long>(0)); auto mean = sum / results.size(); cout << "Mean average: " << mean << endl; vector<unsigned long> diff(results.size()); transform(results.begin(), results.end(), diff.begin(), [mean](unsigned long x) { return x - mean; }); auto sump = inner_product(diff.begin(), diff.end(), diff.begin(), 0.0); auto stdev = sqrt(sump / results.size()); cout << "Standard deviation: " << stdev << endl; if (maxe > maxallowed) { cout << "Error: Mon memory consumption exceeds maximum allowed!" << endl; exit(ENOMEM); } grep.wait(); cout << "Completed successfully" << endl; return 0; }
2,276
27.4625
77
cc
null
ceph-main/src/test/mon/test_mon_rss_usage.cc
#include <algorithm> #include <iostream> #include <fstream> #include <string> #include <numeric> #include <regex> #include <cmath> #include <system_error> using namespace std; int main(int argc, char **argv) { cout << "Mon RSS Usage Test" << endl; if (argc != 2) { cout << "Syntax: " << "ceph_test_mon_rss_usage <mon-memory-target-bytes>" << endl; exit(EINVAL); } unsigned long maxallowed = stoul(argv[1], nullptr, 10); // Set max allowed RSS usage to be 125% of mon-memory-target maxallowed *= 1.25; string target_directory("/var/log/ceph/"); string filePath = target_directory + "ceph-mon-rss-usage.log"; ifstream buffer(filePath.c_str()); string line; vector<unsigned long> results; while(getline(buffer, line) && !line.empty()) { string rssUsage; size_t pos = line.find(':'); if (pos != string::npos) { rssUsage = line.substr(0, pos); } if (!rssUsage.empty()) { results.push_back(stoul(rssUsage)); } } buffer.close(); if (results.empty()) { cout << "Error: No grep results found!" << endl; exit(ENOENT); } auto maxe = *(max_element(results.begin(), results.end())); cout << "Stats for mon RSS Memory Usage:" << endl; cout << "Parsed " << results.size() << " entries." << endl; cout << "Max: " << maxe << endl; cout << "Min: " << *(min_element(results.begin(), results.end())) << endl; auto sum = accumulate(results.begin(), results.end(), static_cast<unsigned long long>(0)); auto mean = sum / results.size(); cout << "Mean average: " << mean << endl; vector<unsigned long> diff(results.size()); transform(results.begin(), results.end(), diff.begin(), [mean](unsigned long x) { return x - mean; }); auto sump = inner_product(diff.begin(), diff.end(), diff.begin(), 0.0); auto stdev = sqrt(sump / results.size()); cout << fixed << "Standard deviation: " << stdev << endl; if (maxe > maxallowed) { cout << "Error: Mon RSS memory usage exceeds maximum allowed!" << endl; exit(ENOMEM); } cout << "Completed successfully" << endl; return 0; }
2,132
28.219178
76
cc
null
ceph-main/src/test/mon/test_mon_types.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2012 Inktank * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <iostream> #include "mon/mon_types.h" #include "gtest/gtest.h" TEST(mon_features, supported_v_persistent) { mon_feature_t supported = ceph::features::mon::get_supported(); mon_feature_t persistent = ceph::features::mon::get_persistent(); ASSERT_EQ(supported.intersection(persistent), persistent); ASSERT_TRUE(supported.contains_all(persistent)); mon_feature_t diff = supported.diff(persistent); ASSERT_TRUE((persistent | diff) == supported); ASSERT_TRUE((supported & persistent) == persistent); } TEST(mon_features, binary_ops) { mon_feature_t FEATURE_NONE(0ULL); mon_feature_t FEATURE_A((1ULL << 1)); mon_feature_t FEATURE_B((1ULL << 2)); mon_feature_t FEATURE_C((1ULL << 3)); mon_feature_t FEATURE_D((1ULL << 4)); mon_feature_t FEATURE_ALL( FEATURE_A | FEATURE_B | FEATURE_C | FEATURE_D ); mon_feature_t foo(FEATURE_A|FEATURE_B); mon_feature_t bar(FEATURE_C|FEATURE_D); ASSERT_EQ(FEATURE_A|FEATURE_B, foo); ASSERT_EQ(FEATURE_C|FEATURE_D, bar); ASSERT_NE(FEATURE_C, foo); ASSERT_NE(FEATURE_B, bar); ASSERT_NE(FEATURE_NONE, foo); ASSERT_NE(FEATURE_NONE, bar); ASSERT_FALSE(foo.empty()); ASSERT_FALSE(bar.empty()); ASSERT_TRUE(FEATURE_NONE.empty()); ASSERT_EQ(FEATURE_ALL, (foo ^ bar)); ASSERT_EQ(FEATURE_NONE, (foo & bar)); mon_feature_t baz = foo; ASSERT_EQ(baz, foo); baz |= bar; ASSERT_EQ(FEATURE_ALL, baz); baz ^= foo; ASSERT_EQ(baz, bar); baz |= FEATURE_A; ASSERT_EQ(FEATURE_C, baz & FEATURE_C); ASSERT_EQ((FEATURE_A|FEATURE_D), baz & (FEATURE_A|FEATURE_D)); ASSERT_EQ(FEATURE_B|FEATURE_C|FEATURE_D, (baz ^ foo)); } TEST(mon_features, set_funcs) { mon_feature_t FEATURE_A((1ULL << 1)); mon_feature_t FEATURE_B((1ULL << 2)); mon_feature_t FEATURE_C((1ULL << 3)); mon_feature_t FEATURE_D((1ULL << 4)); mon_feature_t FEATURE_ALL( FEATURE_A | FEATURE_B | FEATURE_C | FEATURE_D ); mon_feature_t foo(FEATURE_A|FEATURE_B); mon_feature_t bar(FEATURE_C|FEATURE_D); ASSERT_TRUE(FEATURE_ALL.contains_all(foo)); ASSERT_TRUE(FEATURE_ALL.contains_all(bar)); ASSERT_TRUE(FEATURE_ALL.contains_all(foo|bar)); ASSERT_EQ(foo.diff(bar), foo); ASSERT_EQ(bar.diff(foo), bar); ASSERT_EQ(FEATURE_ALL.diff(foo), bar); ASSERT_EQ(FEATURE_ALL.diff(bar), foo); ASSERT_TRUE(foo.contains_any(FEATURE_A|bar)); ASSERT_TRUE(bar.contains_any(FEATURE_ALL)); ASSERT_TRUE(FEATURE_ALL.contains_any(foo)); mon_feature_t FEATURE_X((1ULL << 10)); ASSERT_FALSE(FEATURE_ALL.contains_any(FEATURE_X)); ASSERT_FALSE(FEATURE_ALL.contains_all(FEATURE_X)); ASSERT_EQ(FEATURE_ALL.diff(FEATURE_X), FEATURE_ALL); ASSERT_EQ(foo.intersection(FEATURE_ALL), foo); ASSERT_EQ(bar.intersection(FEATURE_ALL), bar); } TEST(mon_features, set_unset) { mon_feature_t FEATURE_A((1ULL << 1)); mon_feature_t FEATURE_B((1ULL << 2)); mon_feature_t FEATURE_C((1ULL << 3)); mon_feature_t foo; ASSERT_EQ(ceph::features::mon::FEATURE_NONE, foo); foo.set_feature(FEATURE_A); ASSERT_EQ(FEATURE_A, foo); ASSERT_TRUE(foo.contains_all(FEATURE_A)); foo.set_feature(FEATURE_B|FEATURE_C); ASSERT_EQ((FEATURE_A|FEATURE_B|FEATURE_C), foo); ASSERT_TRUE(foo.contains_all((FEATURE_A|FEATURE_B|FEATURE_C))); foo.unset_feature(FEATURE_A); ASSERT_EQ((FEATURE_B|FEATURE_C), foo); ASSERT_FALSE(foo.contains_any(FEATURE_A)); ASSERT_TRUE(foo.contains_all((FEATURE_B|FEATURE_C))); foo.unset_feature(FEATURE_B|FEATURE_C); ASSERT_EQ(ceph::features::mon::FEATURE_NONE, foo); ASSERT_FALSE(foo.contains_any(FEATURE_A|FEATURE_B|FEATURE_C)); }
3,969
27.156028
70
cc
null
ceph-main/src/test/mon/test_mon_workloadgen.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "acconfig.h" #ifdef HAVE_SYS_MOUNT_H #include <sys/mount.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #ifdef HAVE_SYS_VFS_H #include <sys/vfs.h> #endif #include <iostream> #include <string> #include <map> #include <boost/scoped_ptr.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include "osd/osd_types.h" #include "osdc/Objecter.h" #include "mon/MonClient.h" #include "msg/Dispatcher.h" #include "msg/Messenger.h" #include "common/async/context_pool.h" #include "common/Timer.h" #include "common/ceph_argparse.h" #include "global/global_init.h" #include "global/signal_handler.h" #include "common/config.h" #include "common/debug.h" #include "common/errno.h" #include "common/ceph_mutex.h" #include "common/strtol.h" #include "common/LogEntry.h" #include "auth/KeyRing.h" #include "auth/AuthAuthorizeHandler.h" #include "include/uuid.h" #include "include/ceph_assert.h" #include "messages/MOSDBoot.h" #include "messages/MOSDAlive.h" #include "messages/MOSDPGRemove.h" #include "messages/MOSDMap.h" #include "messages/MPGStats.h" #include "messages/MLog.h" #include "messages/MOSDPGTemp.h" using namespace std; #define dout_context g_ceph_context #define dout_subsys ceph_subsys_ #undef dout_prefix #define dout_prefix _prefix(_dout, get_name()) static ostream& _prefix(std::ostream *_dout, const string &n) { return *_dout << " stub(" << n << ") "; } typedef boost::mt11213b rngen_t; typedef boost::scoped_ptr<Messenger> MessengerRef; typedef boost::scoped_ptr<Objecter> ObjecterRef; class TestStub : public Dispatcher { protected: MessengerRef messenger; ceph::async::io_context_pool poolctx; MonClient monc; ceph::mutex lock; ceph::condition_variable cond; SafeTimer timer; bool do_shutdown; double tick_seconds; struct C_Tick : public Context { TestStub *s; explicit C_Tick(TestStub *stub) : s(stub) {} void finish(int r) override { generic_dout(20) << "C_Tick::" << __func__ << dendl; if (r == -ECANCELED) { generic_dout(20) << "C_Tick::" << __func__ << " shutdown" << dendl; return; } s->tick(); } }; bool ms_dispatch(Message *m) override = 0; void ms_handle_connect(Connection *con) override = 0; void ms_handle_remote_reset(Connection *con) override = 0; virtual int _shutdown() = 0; // courtesy method to be implemented by the stubs at their // own discretion virtual void _tick() { } // different stubs may have different needs; if a stub needs // to tick, then it must call this function. void start_ticking(double t=1.0) { tick_seconds = t; if (t <= 0) { stop_ticking(); return; } dout(20) << __func__ << " adding tick timer" << dendl; timer.add_event_after(tick_seconds, new C_Tick(this)); } // If we have a function to start ticking that the stubs can // use at their own discretion, then we should also have a // function to disable said ticking to be used the same way. // Just in case. // For simplicity's sake, we don't cancel the tick right off // the bat; instead, we wait for the next tick to kick in and // disable itself. void stop_ticking() { dout(20) << __func__ << " disable tick" << dendl; tick_seconds = 0; } public: void tick() { std::cout << __func__ << std::endl; if (do_shutdown || (tick_seconds <= 0)) { std::cout << __func__ << " " << (do_shutdown ? "shutdown" : "stop ticking") << std::endl; return; } _tick(); timer.add_event_after(tick_seconds, new C_Tick(this)); } virtual const string get_name() = 0; virtual int init() = 0; virtual int shutdown() { std::lock_guard l{lock}; do_shutdown = true; int r = _shutdown(); if (r < 0) { dout(10) << __func__ << " error shutting down: " << cpp_strerror(-r) << dendl; return r; } monc.shutdown(); timer.shutdown(); messenger->shutdown(); poolctx.finish(); return 0; } virtual void print(ostream &out) { out << "stub(" << get_name() << ")"; } void wait() { if (messenger != NULL) messenger->wait(); } TestStub(CephContext *cct, string who) : Dispatcher(cct), monc(cct, poolctx), lock(ceph::make_mutex(who.append("::lock"))), timer(cct, lock), do_shutdown(false), tick_seconds(0.0) { } }; class ClientStub : public TestStub { ObjecterRef objecter; rngen_t gen; protected: bool ms_dispatch(Message *m) override { std::lock_guard l{lock}; dout(1) << "client::" << __func__ << " " << *m << dendl; switch (m->get_type()) { case CEPH_MSG_OSD_MAP: objecter->handle_osd_map((MOSDMap*)m); cond.notify_all(); break; } return true; } void ms_handle_connect(Connection *con) override { dout(1) << "client::" << __func__ << " " << con << dendl; std::lock_guard l{lock}; objecter->ms_handle_connect(con); } void ms_handle_remote_reset(Connection *con) override { dout(1) << "client::" << __func__ << " " << con << dendl; std::lock_guard l{lock}; objecter->ms_handle_remote_reset(con); } bool ms_handle_reset(Connection *con) override { dout(1) << "client::" << __func__ << dendl; std::lock_guard l{lock}; objecter->ms_handle_reset(con); return false; } bool ms_handle_refused(Connection *con) override { return false; } const string get_name() override { return "client"; } int _shutdown() override { if (objecter) { objecter->shutdown(); } return 0; } public: explicit ClientStub(CephContext *cct) : TestStub(cct, "client"), gen((int) time(NULL)) { } int init() override { int err; poolctx.start(1); err = monc.build_initial_monmap(); if (err < 0) { derr << "ClientStub::" << __func__ << " ERROR: build initial monmap: " << cpp_strerror(err) << dendl; return err; } messenger.reset(Messenger::create_client_messenger(cct, "stubclient")); ceph_assert(messenger.get() != NULL); messenger->set_default_policy( Messenger::Policy::lossy_client(CEPH_FEATURE_OSDREPLYMUX)); dout(10) << "ClientStub::" << __func__ << " starting messenger at " << messenger->get_myaddrs() << dendl; objecter.reset(new Objecter(cct, messenger.get(), &monc, poolctx)); ceph_assert(objecter.get() != NULL); objecter->set_balanced_budget(); monc.set_messenger(messenger.get()); objecter->init(); messenger->add_dispatcher_head(this); messenger->start(); monc.set_want_keys(CEPH_ENTITY_TYPE_MON|CEPH_ENTITY_TYPE_OSD); err = monc.init(); if (err < 0) { derr << "ClientStub::" << __func__ << " monc init error: " << cpp_strerror(-err) << dendl; return err; } err = monc.authenticate(); if (err < 0) { derr << "ClientStub::" << __func__ << " monc authenticate error: " << cpp_strerror(-err) << dendl; monc.shutdown(); return err; } monc.wait_auth_rotating(30.0); objecter->set_client_incarnation(0); objecter->start(); lock.lock(); timer.init(); monc.renew_subs(); lock.unlock(); objecter->wait_for_osd_map(); dout(10) << "ClientStub::" << __func__ << " done" << dendl; return 0; } }; class OSDStub : public TestStub { int whoami; OSDSuperblock sb; OSDMap osdmap; osd_stat_t osd_stat; map<pg_t,pg_stat_t> pgs; set<pg_t> pgs_changes; rngen_t gen; boost::uniform_int<> mon_osd_rng; utime_t last_boot_attempt; static const double STUB_BOOT_INTERVAL; public: enum { STUB_MON_OSD_ALIVE = 1, STUB_MON_OSD_PGTEMP = 2, STUB_MON_OSD_FAILURE = 3, STUB_MON_OSD_PGSTATS = 4, STUB_MON_LOG = 5, STUB_MON_OSD_FIRST = STUB_MON_OSD_ALIVE, STUB_MON_OSD_LAST = STUB_MON_LOG, }; struct C_CreatePGs : public Context { OSDStub *s; explicit C_CreatePGs(OSDStub *stub) : s(stub) {} void finish(int r) override { if (r == -ECANCELED) { generic_dout(20) << "C_CreatePGs::" << __func__ << " shutdown" << dendl; return; } generic_dout(20) << "C_CreatePGs::" << __func__ << dendl; s->auto_create_pgs(); } }; OSDStub(int _whoami, CephContext *cct) : TestStub(cct, "osd"), whoami(_whoami), gen(whoami), mon_osd_rng(STUB_MON_OSD_FIRST, STUB_MON_OSD_LAST) { dout(20) << __func__ << " auth supported: " << cct->_conf->auth_supported << dendl; stringstream ss; ss << "client-osd" << whoami; std::string public_msgr_type = cct->_conf->ms_public_type.empty() ? cct->_conf.get_val<std::string>("ms_type") : cct->_conf->ms_public_type; messenger.reset(Messenger::create(cct, public_msgr_type, entity_name_t::OSD(whoami), ss.str().c_str(), getpid())); Throttle throttler(g_ceph_context, "osd_client_bytes", g_conf()->osd_client_message_size_cap); messenger->set_default_policy( Messenger::Policy::stateless_server(0)); messenger->set_policy_throttlers(entity_name_t::TYPE_CLIENT, &throttler, NULL); messenger->set_policy(entity_name_t::TYPE_MON, Messenger::Policy::lossy_client( CEPH_FEATURE_UID | CEPH_FEATURE_PGID64 | CEPH_FEATURE_OSDENC)); messenger->set_policy(entity_name_t::TYPE_OSD, Messenger::Policy::stateless_server(0)); dout(10) << __func__ << " public addr " << g_conf()->public_addr << dendl; int err = messenger->bind(g_conf()->public_addr); if (err < 0) exit(1); if (monc.build_initial_monmap() < 0) exit(1); messenger->start(); monc.set_messenger(messenger.get()); } int init() override { dout(10) << __func__ << dendl; std::lock_guard l{lock}; dout(1) << __func__ << " fsid " << monc.monmap.fsid << " osd_fsid " << g_conf()->osd_uuid << dendl; dout(1) << __func__ << " name " << g_conf()->name << dendl; timer.init(); messenger->add_dispatcher_head(this); monc.set_want_keys(CEPH_ENTITY_TYPE_MON | CEPH_ENTITY_TYPE_OSD); int err = monc.init(); if (err < 0) { derr << __func__ << " monc init error: " << cpp_strerror(-err) << dendl; return err; } err = monc.authenticate(); if (err < 0) { derr << __func__ << " monc authenticate error: " << cpp_strerror(-err) << dendl; monc.shutdown(); return err; } ceph_assert(!monc.get_fsid().is_zero()); monc.wait_auth_rotating(30.0); dout(10) << __func__ << " creating osd superblock" << dendl; sb.cluster_fsid = monc.monmap.fsid; sb.osd_fsid.generate_random(); sb.whoami = whoami; sb.compat_features = CompatSet(); dout(20) << __func__ << " " << sb << dendl; dout(20) << __func__ << " osdmap " << osdmap << dendl; update_osd_stat(); start_ticking(); // give a chance to the mons to inform us of what PGs we should create timer.add_event_after(30.0, new C_CreatePGs(this)); return 0; } int _shutdown() override { return 0; } void boot() { dout(1) << __func__ << " boot?" << dendl; utime_t now = ceph_clock_now(); if ((last_boot_attempt > 0.0) && ((now - last_boot_attempt)) <= STUB_BOOT_INTERVAL) { dout(1) << __func__ << " backoff and try again later." << dendl; return; } dout(1) << __func__ << " boot!" << dendl; MOSDBoot *mboot = new MOSDBoot; mboot->sb = sb; last_boot_attempt = now; monc.send_mon_message(mboot); } void add_pg(pg_t pgid, epoch_t epoch, pg_t parent) { utime_t now = ceph_clock_now(); pg_stat_t s; s.created = epoch; s.last_epoch_clean = epoch; s.parent = parent; s.state |= PG_STATE_CLEAN | PG_STATE_ACTIVE; s.last_fresh = now; s.last_change = now; s.last_clean = now; s.last_active = now; s.last_unstale = now; pgs[pgid] = s; pgs_changes.insert(pgid); } void auto_create_pgs() { bool has_pgs = !pgs.empty(); dout(10) << __func__ << ": " << (has_pgs ? "has pgs; ignore" : "create pgs") << dendl; if (has_pgs) return; if (!osdmap.get_epoch()) { dout(1) << __func__ << " still don't have osdmap; reschedule pg creation" << dendl; timer.add_event_after(10.0, new C_CreatePGs(this)); return; } auto& osdmap_pools = osdmap.get_pools(); for (auto pit = osdmap_pools.begin(); pit != osdmap_pools.end(); ++pit) { const int64_t pool_id = pit->first; const pg_pool_t &pool = pit->second; int ruleno = pool.get_crush_rule(); if (!osdmap.crush->rule_exists(ruleno)) { dout(20) << __func__ << " no crush rule for pool id " << pool_id << " rule no " << ruleno << dendl; continue; } epoch_t pool_epoch = pool.get_last_change(); dout(20) << __func__ << " pool num pgs " << pool.get_pg_num() << " epoch " << pool_epoch << dendl; for (ps_t ps = 0; ps < pool.get_pg_num(); ++ps) { pg_t pgid(ps, pool_id); pg_t parent; dout(20) << __func__ << " pgid " << pgid << " parent " << parent << dendl; add_pg(pgid, pool_epoch, parent); } } } void update_osd_stat() { struct statfs stbuf; int ret = statfs(".", &stbuf); if (ret < 0) { ret = -errno; dout(0) << __func__ << " cannot statfs ." << cpp_strerror(ret) << dendl; return; } osd_stat.statfs.total = stbuf.f_blocks * stbuf.f_bsize; osd_stat.statfs.available = stbuf.f_bavail * stbuf.f_bsize; osd_stat.statfs.internally_reserved = 0; } void send_pg_stats() { dout(10) << __func__ << " pgs " << pgs.size() << " osdmap " << osdmap << dendl; MPGStats *mstats = new MPGStats(monc.get_fsid(), osdmap.get_epoch()); mstats->set_tid(1); mstats->osd_stat = osd_stat; set<pg_t>::iterator it; for (it = pgs_changes.begin(); it != pgs_changes.end(); ++it) { pg_t pgid = (*it); if (pgs.count(pgid) == 0) { derr << __func__ << " pgid " << pgid << " not on our map" << dendl; ceph_abort_msg("pgid not on our map"); } pg_stat_t &s = pgs[pgid]; mstats->pg_stat[pgid] = s; JSONFormatter f(true); s.dump(&f); dout(20) << __func__ << " pg " << pgid << " stats:\n"; f.flush(*_dout); *_dout << dendl; } dout(10) << __func__ << " send " << *mstats << dendl; monc.send_mon_message(mstats); } void modify_pg(pg_t pgid) { dout(10) << __func__ << " pg " << pgid << dendl; ceph_assert(pgs.count(pgid) > 0); pg_stat_t &s = pgs[pgid]; utime_t now = ceph_clock_now(); if (now - s.last_change < 10.0) { dout(10) << __func__ << " pg " << pgid << " changed in the last 10s" << dendl; return; } s.state ^= PG_STATE_CLEAN; if (s.state & PG_STATE_CLEAN) s.last_clean = now; s.last_change = now; s.reported_seq++; pgs_changes.insert(pgid); } void modify_pgs() { dout(10) << __func__ << dendl; if (pgs.empty()) { dout(1) << __func__ << " no pgs available! don't attempt to modify." << dendl; return; } boost::uniform_int<> pg_rng(0, pgs.size()-1); set<int> pgs_pos; int num_pgs = pg_rng(gen); while ((int)pgs_pos.size() < num_pgs) pgs_pos.insert(pg_rng(gen)); map<pg_t,pg_stat_t>::iterator it = pgs.begin(); set<int>::iterator pos_it = pgs_pos.begin(); int pgs_at = 0; while (pos_it != pgs_pos.end()) { int at = *pos_it; dout(20) << __func__ << " pg at pos " << at << dendl; while ((pgs_at != at) && (it != pgs.end())) { ++it; ++pgs_at; } ceph_assert(it != pgs.end()); dout(20) << __func__ << " pg at pos " << at << ": " << it->first << dendl; modify_pg(it->first); ++pos_it; } } void op_alive() { dout(10) << __func__ << dendl; if (!osdmap.exists(whoami)) { dout(0) << __func__ << " I'm not in the osdmap!!\n"; JSONFormatter f(true); osdmap.dump(&f); f.flush(*_dout); *_dout << dendl; } if (osdmap.get_epoch() == 0) { dout(1) << __func__ << " wait for osdmap" << dendl; return; } epoch_t up_thru = osdmap.get_up_thru(whoami); dout(10) << __func__ << "up_thru: " << osdmap.get_up_thru(whoami) << dendl; monc.send_mon_message(new MOSDAlive(osdmap.get_epoch(), up_thru)); } void op_pgtemp() { if (osdmap.get_epoch() == 0) { dout(1) << __func__ << " wait for osdmap" << dendl; return; } dout(10) << __func__ << dendl; MOSDPGTemp *m = new MOSDPGTemp(osdmap.get_epoch()); monc.send_mon_message(m); } void op_failure() { dout(10) << __func__ << dendl; } void op_pgstats() { dout(10) << __func__ << dendl; modify_pgs(); if (!pgs_changes.empty()) send_pg_stats(); monc.sub_want("osd_pg_creates", 0, CEPH_SUBSCRIBE_ONETIME); monc.renew_subs(); dout(20) << __func__ << " pg pools:\n"; JSONFormatter f(true); f.open_array_section("pools"); auto& osdmap_pools = osdmap.get_pools(); for (auto pit = osdmap_pools.begin(); pit != osdmap_pools.end(); ++pit) { const int64_t pool_id = pit->first; const pg_pool_t &pool = pit->second; f.open_object_section("pool"); f.dump_int("pool_id", pool_id); f.open_object_section("pool_dump"); pool.dump(&f); f.close_section(); f.close_section(); } f.close_section(); f.flush(*_dout); *_dout << dendl; } void op_log() { dout(10) << __func__ << dendl; MLog *m = new MLog(monc.get_fsid()); boost::uniform_int<> log_rng(1, 10); size_t num_entries = log_rng(gen); dout(10) << __func__ << " send " << num_entries << " log messages" << dendl; utime_t now = ceph_clock_now(); int seq = 0; for (; num_entries > 0; --num_entries) { LogEntry e; e.rank = messenger->get_myname(); e.addrs = messenger->get_myaddrs(); e.stamp = now; e.seq = seq++; e.prio = CLOG_DEBUG; e.msg = "OSDStub::op_log"; m->entries.push_back(e); } monc.send_mon_message(m); } void _tick() override { if (!osdmap.exists(whoami)) { std::cout << __func__ << " not in the cluster; boot!" << std::endl; boot(); return; } update_osd_stat(); boost::uniform_int<> op_rng(STUB_MON_OSD_FIRST, STUB_MON_OSD_LAST); int op = op_rng(gen); switch (op) { case STUB_MON_OSD_ALIVE: op_alive(); break; case STUB_MON_OSD_PGTEMP: op_pgtemp(); break; case STUB_MON_OSD_FAILURE: op_failure(); break; case STUB_MON_OSD_PGSTATS: op_pgstats(); break; case STUB_MON_LOG: op_log(); break; } } void handle_osd_map(MOSDMap *m) { dout(1) << __func__ << dendl; if (m->fsid != monc.get_fsid()) { dout(0) << __func__ << " message fsid " << m->fsid << " != " << monc.get_fsid() << dendl; dout(0) << __func__ << " " << m << " from " << m->get_source_inst() << dendl; dout(0) << monc.get_monmap() << dendl; } ceph_assert(m->fsid == monc.get_fsid()); epoch_t first = m->get_first(); epoch_t last = m->get_last(); dout(5) << __func__ << " epochs [" << first << "," << last << "]" << " current " << osdmap.get_epoch() << dendl; if (last <= osdmap.get_epoch()) { dout(5) << __func__ << " no new maps here; dropping" << dendl; m->put(); return; } if (first > osdmap.get_epoch() + 1) { dout(5) << __func__ << osdmap.get_epoch() + 1 << ".." << (first-1) << dendl; if ((m->cluster_osdmap_trim_lower_bound < first && osdmap.get_epoch() == 0) || m->cluster_osdmap_trim_lower_bound <= osdmap.get_epoch()) { monc.sub_want("osdmap", osdmap.get_epoch()+1, CEPH_SUBSCRIBE_ONETIME); monc.renew_subs(); m->put(); return; } } epoch_t start_full = std::max(osdmap.get_epoch() + 1, first); if (m->maps.size() > 0) { map<epoch_t,bufferlist>::reverse_iterator rit; rit = m->maps.rbegin(); if (start_full <= rit->first) { start_full = rit->first; dout(5) << __func__ << " full epoch " << start_full << dendl; bufferlist &bl = rit->second; auto p = bl.cbegin(); osdmap.decode(p); } } for (epoch_t e = start_full; e <= last; e++) { map<epoch_t,bufferlist>::iterator it; it = m->incremental_maps.find(e); if (it == m->incremental_maps.end()) continue; dout(20) << __func__ << " incremental epoch " << e << " on full epoch " << start_full << dendl; OSDMap::Incremental inc; bufferlist &bl = it->second; auto p = bl.cbegin(); inc.decode(p); int err = osdmap.apply_incremental(inc); if (err < 0) { derr << "osd." << whoami << "::" << __func__ << "** ERROR: applying incremental: " << cpp_strerror(err) << dendl; ceph_abort_msg("error applying incremental"); } } dout(30) << __func__ << "\nosdmap:\n"; JSONFormatter f(true); osdmap.dump(&f); f.flush(*_dout); *_dout << dendl; if (osdmap.is_up(whoami) && osdmap.get_addrs(whoami) == messenger->get_myaddrs()) { dout(1) << __func__ << " got into the osdmap and we're up!" << dendl; } if (m->newest_map && m->newest_map > last) { dout(1) << __func__ << " they have more maps; requesting them!" << dendl; monc.sub_want("osdmap", osdmap.get_epoch()+1, CEPH_SUBSCRIBE_ONETIME); monc.renew_subs(); } dout(10) << __func__ << " done" << dendl; m->put(); } bool ms_dispatch(Message *m) override { dout(1) << __func__ << " " << *m << dendl; switch (m->get_type()) { case CEPH_MSG_OSD_MAP: handle_osd_map((MOSDMap*)m); break; default: m->put(); break; } return true; } void ms_handle_connect(Connection *con) override { dout(1) << __func__ << " " << con << dendl; if (con->get_peer_type() == CEPH_ENTITY_TYPE_MON) { dout(10) << __func__ << " on mon" << dendl; } } void ms_handle_remote_reset(Connection *con) override {} bool ms_handle_reset(Connection *con) override { dout(1) << __func__ << dendl; return con->get_priv().get(); } bool ms_handle_refused(Connection *con) override { return false; } const string get_name() override { stringstream ss; ss << "osd." << whoami; return ss.str(); } }; double const OSDStub::STUB_BOOT_INTERVAL = 10.0; #undef dout_prefix #define dout_prefix *_dout << "main " const char *our_name = NULL; vector<TestStub*> stubs; ceph::mutex shutdown_lock = ceph::make_mutex("main::shutdown_lock"); ceph::condition_variable shutdown_cond; Context *shutdown_cb = NULL; SafeTimer *shutdown_timer = NULL; struct C_Shutdown : public Context { void finish(int r) override { generic_dout(10) << "main::shutdown time has ran out" << dendl; shutdown_cond.notify_all(); } }; void handle_test_signal(int signum) { if ((signum != SIGINT) && (signum != SIGTERM)) return; std::cerr << "*** Got signal " << sig_str(signum) << " ***" << std::endl; std::lock_guard l{shutdown_lock}; if (shutdown_timer) { shutdown_timer->cancel_all_events(); shutdown_cond.notify_all(); } } void usage() { ceph_assert(our_name != NULL); std::cout << "usage: " << our_name << " <--stub-id ID> [--stub-id ID...]" << std::endl; std::cout << "\n\ Global Options:\n\ -c FILE Read configuration from FILE\n\ --keyring FILE Read keyring from FILE\n\ --help This message\n\ \n\ Test-specific Options:\n\ --stub-id ID1..ID2 Interval of OSD ids for multiple stubs to mimic.\n\ --stub-id ID OSD id a stub will mimic to be\n\ (same as --stub-id ID..ID)\n\ " << std::endl; } int get_id_interval(int &first, int &last, string &str) { size_t found = str.find(".."); string first_str, last_str; if (found == string::npos) { first_str = last_str = str; } else { first_str = str.substr(0, found); last_str = str.substr(found+2); } string err; first = strict_strtol(first_str.c_str(), 10, &err); if ((first == 0) && (!err.empty())) { std::cerr << err << std::endl; return -1; } last = strict_strtol(last_str.c_str(), 10, &err); if ((last == 0) && (!err.empty())) { std::cerr << err << std::endl; return -1; } return 0; } int main(int argc, const char *argv[]) { our_name = argv[0]; auto args = argv_to_vec(argc, argv); auto cct = global_init(nullptr, args, CEPH_ENTITY_TYPE_OSD, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); g_ceph_context->_conf.apply_changes(nullptr); set<int> stub_ids; double duration = 300.0; for (std::vector<const char*>::iterator i = args.begin(); i != args.end();) { string val; if (ceph_argparse_double_dash(args, i)) { break; } else if (ceph_argparse_witharg(args, i, &val, "--stub-id", (char*) NULL)) { int first = -1, last = -1; if (get_id_interval(first, last, val) < 0) { std::cerr << "** error parsing stub id '" << val << "'" << std::endl; exit(1); } for (; first <= last; ++first) stub_ids.insert(first); } else if (ceph_argparse_witharg(args, i, &val, "--duration", (char*) NULL)) { string err; duration = (double) strict_strtol(val.c_str(), 10, &err); if ((duration == 0) && (!err.empty())) { std::cerr << "** error parsing '--duration " << val << "': '" << err << std::endl; exit(1); } } else if (ceph_argparse_flag(args, i, "--help", (char*) NULL)) { usage(); exit(0); } else { std::cerr << "unknown argument '" << *i << "'" << std::endl; return 1; } } if (stub_ids.empty()) { std::cerr << "** error: must specify at least one '--stub-id <ID>'" << std::endl; usage(); return 1; } for (set<int>::iterator i = stub_ids.begin(); i != stub_ids.end(); ++i) { int whoami = *i; std::cout << __func__ << " starting stub." << whoami << std::endl; OSDStub *stub = new OSDStub(whoami, g_ceph_context); int err = stub->init(); if (err < 0) { std::cerr << "** osd stub error: " << cpp_strerror(-err) << std::endl; return 1; } stubs.push_back(stub); } std::cout << __func__ << " starting client stub" << std::endl; ClientStub *cstub = new ClientStub(g_ceph_context); int err = cstub->init(); if (err < 0) { std::cerr << "** client stub error: " << cpp_strerror(-err) << std::endl; return 1; } stubs.push_back(cstub); init_async_signal_handler(); register_async_signal_handler_oneshot(SIGINT, handle_test_signal); register_async_signal_handler_oneshot(SIGTERM, handle_test_signal); { unique_lock locker{shutdown_lock}; shutdown_timer = new SafeTimer(g_ceph_context, shutdown_lock); shutdown_timer->init(); if (duration != 0) { std::cout << __func__ << " run test for " << duration << " seconds" << std::endl; shutdown_timer->add_event_after((double) duration, new C_Shutdown); } shutdown_cond.wait(locker); shutdown_timer->shutdown(); delete shutdown_timer; shutdown_timer = NULL; } unregister_async_signal_handler(SIGINT, handle_test_signal); unregister_async_signal_handler(SIGTERM, handle_test_signal); std::cout << __func__ << " waiting for stubs to finish" << std::endl; vector<TestStub*>::iterator it; int i; for (i = 0, it = stubs.begin(); it != stubs.end(); ++it, ++i) { if (*it != NULL) { (*it)->shutdown(); (*it)->wait(); std::cout << __func__ << " finished " << (*it)->get_name() << std::endl; delete (*it); (*it) = NULL; } } return 0; }
28,304
25.330233
144
cc
null
ceph-main/src/test/msgr/perf_msgr_client.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2015 Haomai Wang * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <stdlib.h> #include <stdint.h> #include <string> #include <unistd.h> #include <iostream> using namespace std; #include "common/ceph_argparse.h" #include "common/debug.h" #include "common/Cycles.h" #include "global/global_init.h" #include "msg/Messenger.h" #include "messages/MOSDOp.h" #include "auth/DummyAuth.h" #include <atomic> class MessengerClient { class ClientThread; class ClientDispatcher : public Dispatcher { uint64_t think_time; ClientThread *thread; public: ClientDispatcher(uint64_t delay, ClientThread *t): Dispatcher(g_ceph_context), think_time(delay), thread(t) {} bool ms_can_fast_dispatch_any() const override { return true; } bool ms_can_fast_dispatch(const Message *m) const override { switch (m->get_type()) { case CEPH_MSG_OSD_OPREPLY: return true; default: return false; } } void ms_handle_fast_connect(Connection *con) override {} void ms_handle_fast_accept(Connection *con) override {} bool ms_dispatch(Message *m) override { return true; } void ms_fast_dispatch(Message *m) override; bool ms_handle_reset(Connection *con) override { return true; } void ms_handle_remote_reset(Connection *con) override {} bool ms_handle_refused(Connection *con) override { return false; } int ms_handle_authentication(Connection *con) override { return 1; } }; class ClientThread : public Thread { Messenger *msgr; int concurrent; ConnectionRef conn; std::atomic<unsigned> client_inc = { 0 }; object_t oid; object_locator_t oloc; pg_t pgid; int msg_len; bufferlist data; int ops; ClientDispatcher dispatcher; public: ceph::mutex lock = ceph::make_mutex("MessengerBenchmark::ClientThread::lock"); ceph::condition_variable cond; uint64_t inflight; ClientThread(Messenger *m, int c, ConnectionRef con, int len, int ops, int think_time_us): msgr(m), concurrent(c), conn(con), oid("object-name"), oloc(1, 1), msg_len(len), ops(ops), dispatcher(think_time_us, this), inflight(0) { m->add_dispatcher_head(&dispatcher); bufferptr ptr(msg_len); memset(ptr.c_str(), 0, msg_len); data.append(ptr); } void *entry() override { std::unique_lock locker{lock}; for (int i = 0; i < ops; ++i) { if (inflight > uint64_t(concurrent)) { cond.wait(locker); } hobject_t hobj(oid, oloc.key, CEPH_NOSNAP, pgid.ps(), pgid.pool(), oloc.nspace); spg_t spgid(pgid); MOSDOp *m = new MOSDOp(client_inc, 0, hobj, spgid, 0, 0, 0); bufferlist msg_data(data); m->write(0, msg_len, msg_data); inflight++; conn->send_message(m); //cerr << __func__ << " send m=" << m << std::endl; } locker.unlock(); msgr->shutdown(); return 0; } }; string type; string serveraddr; int think_time_us; vector<Messenger*> msgrs; vector<ClientThread*> clients; DummyAuthClientServer dummy_auth; public: MessengerClient(const string &t, const string &addr, int delay): type(t), serveraddr(addr), think_time_us(delay), dummy_auth(g_ceph_context) { } ~MessengerClient() { for (uint64_t i = 0; i < clients.size(); ++i) delete clients[i]; for (uint64_t i = 0; i < msgrs.size(); ++i) { msgrs[i]->shutdown(); msgrs[i]->wait(); } } void ready(int c, int jobs, int ops, int msg_len) { entity_addr_t addr; addr.parse(serveraddr.c_str()); addr.set_nonce(0); dummy_auth.auth_registry.refresh_config(); for (int i = 0; i < jobs; ++i) { Messenger *msgr = Messenger::create(g_ceph_context, type, entity_name_t::CLIENT(0), "client", getpid()+i); msgr->set_default_policy(Messenger::Policy::lossless_client(0)); msgr->set_auth_client(&dummy_auth); msgr->start(); entity_addrvec_t addrs(addr); ConnectionRef conn = msgr->connect_to_osd(addrs); ClientThread *t = new ClientThread(msgr, c, conn, msg_len, ops, think_time_us); msgrs.push_back(msgr); clients.push_back(t); } usleep(1000*1000); } void start() { for (uint64_t i = 0; i < clients.size(); ++i) clients[i]->create("client"); for (uint64_t i = 0; i < msgrs.size(); ++i) msgrs[i]->wait(); } }; void MessengerClient::ClientDispatcher::ms_fast_dispatch(Message *m) { usleep(think_time); m->put(); std::lock_guard l{thread->lock}; thread->inflight--; thread->cond.notify_all(); } void usage(const string &name) { cout << "Usage: " << name << " [server ip:port] [numjobs] [concurrency] [ios] [thinktime us] [msg length]" << std::endl; cout << " [server ip:port]: connect to the ip:port pair" << std::endl; cout << " [numjobs]: how much client threads spawned and do benchmark" << std::endl; cout << " [concurrency]: the max inflight messages(like iodepth in fio)" << std::endl; cout << " [ios]: how much messages sent for each client" << std::endl; cout << " [thinktime]: sleep time when do fast dispatching(match client logic)" << std::endl; cout << " [msg length]: message data bytes" << std::endl; } int main(int argc, char **argv) { auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); g_ceph_context->_conf.apply_changes(nullptr); if (args.size() < 6) { usage(argv[0]); return 1; } int numjobs = atoi(args[1]); int concurrent = atoi(args[2]); int ios = atoi(args[3]); int think_time = atoi(args[4]); int len = atoi(args[5]); std::string public_msgr_type = g_ceph_context->_conf->ms_public_type.empty() ? g_ceph_context->_conf.get_val<std::string>("ms_type") : g_ceph_context->_conf->ms_public_type; cout << " using ms-public-type " << public_msgr_type << std::endl; cout << " server ip:port " << args[0] << std::endl; cout << " numjobs " << numjobs << std::endl; cout << " concurrency " << concurrent << std::endl; cout << " ios " << ios << std::endl; cout << " thinktime(us) " << think_time << std::endl; cout << " message data bytes " << len << std::endl; MessengerClient client(public_msgr_type, args[0], think_time); client.ready(concurrent, numjobs, ios, len); Cycles::init(); uint64_t start = Cycles::rdtsc(); client.start(); uint64_t stop = Cycles::rdtsc(); cout << " Total op " << (ios * numjobs) << " run time " << Cycles::to_microseconds(stop - start) << "us." << std::endl; return 0; }
7,103
31.290909
175
cc
null
ceph-main/src/test/msgr/perf_msgr_server.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2015 Haomai Wang * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <stdlib.h> #include <stdint.h> #include <string> #include <unistd.h> #include <iostream> using namespace std; #include "common/ceph_argparse.h" #include "common/debug.h" #include "common/WorkQueue.h" #include "global/global_init.h" #include "msg/Messenger.h" #include "messages/MOSDOp.h" #include "messages/MOSDOpReply.h" #include "auth/DummyAuth.h" class ServerDispatcher : public Dispatcher { uint64_t think_time; ThreadPool op_tp; class OpWQ : public ThreadPool::WorkQueue<Message> { list<Message*> messages; public: OpWQ(ceph::timespan timeout, ceph::timespan suicide_timeout, ThreadPool *tp) : ThreadPool::WorkQueue<Message>("ServerDispatcher::OpWQ", timeout, suicide_timeout, tp) {} bool _enqueue(Message *m) override { messages.push_back(m); return true; } void _dequeue(Message *m) override { ceph_abort(); } bool _empty() override { return messages.empty(); } Message *_dequeue() override { if (messages.empty()) return NULL; Message *m = messages.front(); messages.pop_front(); return m; } void _process(Message *m, ThreadPool::TPHandle &handle) override { MOSDOp *osd_op = static_cast<MOSDOp*>(m); MOSDOpReply *reply = new MOSDOpReply(osd_op, 0, 0, 0, false); m->get_connection()->send_message(reply); m->put(); } void _process_finish(Message *m) override { } void _clear() override { ceph_assert(messages.empty()); } } op_wq; public: ServerDispatcher(int threads, uint64_t delay): Dispatcher(g_ceph_context), think_time(delay), op_tp(g_ceph_context, "ServerDispatcher::op_tp", "tp_serv_disp", threads, "serverdispatcher_op_threads"), op_wq(ceph::make_timespan(30), ceph::make_timespan(30), &op_tp) { op_tp.start(); } ~ServerDispatcher() override { op_tp.stop(); } bool ms_can_fast_dispatch_any() const override { return true; } bool ms_can_fast_dispatch(const Message *m) const override { switch (m->get_type()) { case CEPH_MSG_OSD_OP: return true; default: return false; } } void ms_handle_fast_connect(Connection *con) override {} void ms_handle_fast_accept(Connection *con) override {} bool ms_dispatch(Message *m) override { return true; } bool ms_handle_reset(Connection *con) override { return true; } void ms_handle_remote_reset(Connection *con) override {} bool ms_handle_refused(Connection *con) override { return false; } void ms_fast_dispatch(Message *m) override { usleep(think_time); //cerr << __func__ << " reply message=" << m << std::endl; op_wq.queue(m); } int ms_handle_authentication(Connection *con) override { return 1; } }; class MessengerServer { Messenger *msgr; string type; string bindaddr; ServerDispatcher dispatcher; DummyAuthClientServer dummy_auth; public: MessengerServer(const string &t, const string &addr, int threads, int delay): msgr(NULL), type(t), bindaddr(addr), dispatcher(threads, delay), dummy_auth(g_ceph_context) { msgr = Messenger::create(g_ceph_context, type, entity_name_t::OSD(0), "server", 0); msgr->set_default_policy(Messenger::Policy::stateless_server(0)); dummy_auth.auth_registry.refresh_config(); msgr->set_auth_server(&dummy_auth); } ~MessengerServer() { msgr->shutdown(); msgr->wait(); } void start() { entity_addr_t addr; addr.parse(bindaddr.c_str()); msgr->bind(addr); msgr->add_dispatcher_head(&dispatcher); msgr->start(); msgr->wait(); } }; void usage(const string &name) { cerr << "Usage: " << name << " [bind ip:port] [server worker threads] [thinktime us]" << std::endl; cerr << " [bind ip:port]: The ip:port pair to bind, client need to specify this pair to connect" << std::endl; cerr << " [server worker threads]: threads will process incoming messages and reply(matching pg threads)" << std::endl; cerr << " [thinktime]: sleep time when do dispatching(match fast dispatch logic in OSD.cc)" << std::endl; } int main(int argc, char **argv) { auto args = argv_to_vec(argc, argv); auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); g_ceph_context->_conf.apply_changes(nullptr); if (args.size() < 3) { usage(argv[0]); return 1; } int worker_threads = atoi(args[1]); int think_time = atoi(args[2]); std::string public_msgr_type = g_ceph_context->_conf->ms_public_type.empty() ? g_ceph_context->_conf.get_val<std::string>("ms_type") : g_ceph_context->_conf->ms_public_type; cerr << " This tool won't handle connection error alike things, " << std::endl; cerr << "please ensure the proper network environment to test." << std::endl; cerr << " Or ctrl+c when meeting error and restart tests" << std::endl; cerr << " using ms-public-type " << public_msgr_type << std::endl; cerr << " bind ip:port " << args[0] << std::endl; cerr << " worker threads " << worker_threads << std::endl; cerr << " thinktime(us) " << think_time << std::endl; MessengerServer server(public_msgr_type, args[0], worker_threads, think_time); server.start(); return 0; }
5,735
31.40678
175
cc
null
ceph-main/src/test/msgr/test_async_driver.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2014 UnitedStack <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif #include <fcntl.h> #include <sys/socket.h> #include <pthread.h> #include <stdint.h> #include <arpa/inet.h> #include "include/Context.h" #include "common/ceph_mutex.h" #include "common/Cond.h" #include "global/global_init.h" #include "common/ceph_argparse.h" #include "msg/async/Event.h" #include <atomic> // We use epoll, kqueue, evport, select in descending order by performance. #if defined(__linux__) #define HAVE_EPOLL 1 #endif #if (defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined (__NetBSD__) #define HAVE_KQUEUE 1 #endif #ifdef __sun #include <sys/feature_tests.h> #ifdef _DTRACE_VERSION #define HAVE_EVPORT 1 #endif #endif #ifdef HAVE_EPOLL #include "msg/async/EventEpoll.h" #endif #ifdef HAVE_KQUEUE #include "msg/async/EventKqueue.h" #endif #include "msg/async/EventSelect.h" #include <gtest/gtest.h> using namespace std; class EventDriverTest : public ::testing::TestWithParam<const char*> { public: EventDriver *driver; EventDriverTest(): driver(0) {} void SetUp() override { cerr << __func__ << " start set up " << GetParam() << std::endl; #ifdef HAVE_EPOLL if (strcmp(GetParam(), "epoll")) driver = new EpollDriver(g_ceph_context); #endif #ifdef HAVE_KQUEUE if (strcmp(GetParam(), "kqueue")) driver = new KqueueDriver(g_ceph_context); #endif if (strcmp(GetParam(), "select")) driver = new SelectDriver(g_ceph_context); driver->init(NULL, 100); } void TearDown() override { delete driver; } }; int set_nonblock(int sd) { int flags; /* Set the socket nonblocking. * Note that fcntl(2) for F_GETFL and F_SETFL can't be * interrupted by a signal. */ if ((flags = fcntl(sd, F_GETFL)) < 0 ) { return -1; } if (fcntl(sd, F_SETFL, flags | O_NONBLOCK) < 0) { return -1; } return 0; } TEST_P(EventDriverTest, PipeTest) { int fds[2]; vector<FiredFileEvent> fired_events; int r; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 1; r = pipe(fds); ASSERT_EQ(r, 0); r = driver->add_event(fds[0], EVENT_NONE, EVENT_READABLE); ASSERT_EQ(r, 0); r = driver->event_wait(fired_events, &tv); ASSERT_EQ(r, 0); char c = 'A'; r = write(fds[1], &c, sizeof(c)); ASSERT_EQ(r, 1); r = driver->event_wait(fired_events, &tv); ASSERT_EQ(r, 1); ASSERT_EQ(fired_events[0].fd, fds[0]); fired_events.clear(); r = write(fds[1], &c, sizeof(c)); ASSERT_EQ(r, 1); r = driver->event_wait(fired_events, &tv); ASSERT_EQ(r, 1); ASSERT_EQ(fired_events[0].fd, fds[0]); fired_events.clear(); driver->del_event(fds[0], EVENT_READABLE, EVENT_READABLE); r = write(fds[1], &c, sizeof(c)); ASSERT_EQ(r, 1); r = driver->event_wait(fired_events, &tv); ASSERT_EQ(r, 0); } void* echoclient(void *arg) { intptr_t port = (intptr_t)arg; struct sockaddr_in sa; memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(port); char addr[] = "127.0.0.1"; int r = inet_pton(AF_INET, addr, &sa.sin_addr); ceph_assert(r == 1); int connect_sd = ::socket(AF_INET, SOCK_STREAM, 0); if (connect_sd >= 0) { r = connect(connect_sd, (struct sockaddr*)&sa, sizeof(sa)); ceph_assert(r == 0); int t = 0; do { char c[] = "banner"; r = write(connect_sd, c, sizeof(c)); char d[100]; r = read(connect_sd, d, sizeof(d)); if (r == 0) break; if (t++ == 30) break; } while (1); ::close(connect_sd); } return 0; } TEST_P(EventDriverTest, NetworkSocketTest) { int listen_sd = ::socket(AF_INET, SOCK_STREAM, 0); ASSERT_TRUE(listen_sd > 0); int on = 1; int r = ::setsockopt(listen_sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); ASSERT_EQ(r, 0); r = set_nonblock(listen_sd); ASSERT_EQ(r, 0); struct sockaddr_in sa; long port = 0; for (port = 38788; port < 40000; port++) { memset(&sa,0,sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(port); sa.sin_addr.s_addr = htonl(INADDR_ANY); r = ::bind(listen_sd, (struct sockaddr *)&sa, sizeof(sa)); if (r == 0) { break; } } ASSERT_EQ(r, 0); r = listen(listen_sd, 511); ASSERT_EQ(r, 0); vector<FiredFileEvent> fired_events; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 1; r = driver->add_event(listen_sd, EVENT_NONE, EVENT_READABLE); ASSERT_EQ(r, 0); r = driver->event_wait(fired_events, &tv); ASSERT_EQ(r, 0); fired_events.clear(); pthread_t thread1; r = pthread_create(&thread1, NULL, echoclient, (void*)(intptr_t)port); ASSERT_EQ(r, 0); tv.tv_sec = 5; tv.tv_usec = 0; r = driver->event_wait(fired_events, &tv); ASSERT_EQ(r, 1); ASSERT_EQ(fired_events[0].fd, listen_sd); fired_events.clear(); int client_sd = ::accept(listen_sd, NULL, NULL); ASSERT_TRUE(client_sd > 0); r = driver->add_event(client_sd, EVENT_NONE, EVENT_READABLE); ASSERT_EQ(r, 0); do { fired_events.clear(); tv.tv_sec = 5; tv.tv_usec = 0; r = driver->event_wait(fired_events, &tv); ASSERT_EQ(1, r); ASSERT_EQ(EVENT_READABLE, fired_events[0].mask); fired_events.clear(); char data[100]; r = ::read(client_sd, data, sizeof(data)); if (r == 0) break; ASSERT_GT(r, 0); r = driver->add_event(client_sd, EVENT_READABLE, EVENT_WRITABLE); ASSERT_EQ(0, r); r = driver->event_wait(fired_events, &tv); ASSERT_EQ(1, r); ASSERT_EQ(fired_events[0].mask, EVENT_WRITABLE); r = write(client_sd, data, strlen(data)); ASSERT_EQ((int)strlen(data), r); driver->del_event(client_sd, EVENT_READABLE|EVENT_WRITABLE, EVENT_WRITABLE); } while (1); ::close(client_sd); ::close(listen_sd); } class FakeEvent : public EventCallback { public: void do_request(uint64_t fd_or_id) override {} }; TEST(EventCenterTest, FileEventExpansion) { vector<int> sds; EventCenter center(g_ceph_context); center.init(100, 0, "posix"); center.set_owner(); EventCallbackRef e(new FakeEvent()); for (int i = 0; i < 300; i++) { int sd = ::socket(AF_INET, SOCK_STREAM, 0); center.create_file_event(sd, EVENT_READABLE, e); sds.push_back(sd); } for (vector<int>::iterator it = sds.begin(); it != sds.end(); ++it) center.delete_file_event(*it, EVENT_READABLE); } class Worker : public Thread { CephContext *cct; bool done; public: EventCenter center; explicit Worker(CephContext *c, int idx): cct(c), done(false), center(c) { center.init(100, idx, "posix"); } void stop() { done = true; center.wakeup(); } void* entry() override { center.set_owner(); while (!done) center.process_events(1000000); return 0; } }; class CountEvent: public EventCallback { std::atomic<unsigned> *count; ceph::mutex *lock; ceph::condition_variable *cond; public: CountEvent(std::atomic<unsigned> *atomic, ceph::mutex *l, ceph::condition_variable *c) : count(atomic), lock(l), cond(c) {} void do_request(uint64_t id) override { std::scoped_lock l{*lock}; (*count)--; cond->notify_all(); } }; TEST(EventCenterTest, DispatchTest) { Worker worker1(g_ceph_context, 1), worker2(g_ceph_context, 2); std::atomic<unsigned> count = { 0 }; ceph::mutex lock = ceph::make_mutex("DispatchTest::lock"); ceph::condition_variable cond; worker1.create("worker_1"); worker2.create("worker_2"); for (int i = 0; i < 10000; ++i) { count++; worker1.center.dispatch_event_external(EventCallbackRef(new CountEvent(&count, &lock, &cond))); count++; worker2.center.dispatch_event_external(EventCallbackRef(new CountEvent(&count, &lock, &cond))); std::unique_lock l{lock}; cond.wait(l, [&] { return count == 0; }); } worker1.stop(); worker2.stop(); worker1.join(); worker2.join(); } INSTANTIATE_TEST_SUITE_P( AsyncMessenger, EventDriverTest, ::testing::Values( #ifdef HAVE_EPOLL "epoll", #endif #ifdef HAVE_KQUEUE "kqueue", #endif "select" ) ); /* * Local Variables: * compile-command: "cd ../.. ; make ceph_test_async_driver && * ./ceph_test_async_driver * * End: */
8,636
23.329577
130
cc
null
ceph-main/src/test/msgr/test_async_networkstack.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2016 XSky <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <algorithm> #include <atomic> #include <iostream> #include <list> #include <random> #include <string> #include <set> #include <vector> #include <gtest/gtest.h> #include "acconfig.h" #include "common/config_obs.h" #include "include/Context.h" #include "msg/async/Event.h" #include "msg/async/Stack.h" using namespace std; class NoopConfigObserver : public md_config_obs_t { std::list<std::string> options; const char **ptrs = 0; public: NoopConfigObserver(std::list<std::string> l) : options(l) { ptrs = new const char*[options.size() + 1]; unsigned j = 0; for (auto& i : options) { ptrs[j++] = i.c_str(); } ptrs[j] = 0; } ~NoopConfigObserver() { delete[] ptrs; } const char** get_tracked_conf_keys() const override { return ptrs; } void handle_conf_change(const ConfigProxy& conf, const std::set <std::string> &changed) override { } }; class NetworkWorkerTest : public ::testing::TestWithParam<const char*> { public: std::shared_ptr<NetworkStack> stack; string addr, port_addr; NoopConfigObserver fake_obs = {{"ms_type", "ms_dpdk_coremask", "ms_dpdk_host_ipv4_addr", "ms_dpdk_gateway_ipv4_addr", "ms_dpdk_netmask_ipv4_addr"}}; NetworkWorkerTest() {} void SetUp() override { cerr << __func__ << " start set up " << GetParam() << std::endl; if (strncmp(GetParam(), "dpdk", 4)) { g_ceph_context->_conf.set_val("ms_type", "async+posix"); addr = "127.0.0.1:15000"; port_addr = "127.0.0.1:15001"; } else { g_ceph_context->_conf.set_val_or_die("ms_dpdk_debug_allow_loopback", "true"); g_ceph_context->_conf.set_val_or_die("ms_async_op_threads", "2"); string ipv4_addr = g_ceph_context->_conf.get_val<std::string>("ms_dpdk_host_ipv4_addr"); addr = ipv4_addr + std::string(":15000"); port_addr = ipv4_addr + std::string(":15001"); } stack = NetworkStack::create(g_ceph_context, GetParam()); stack->start(); } void TearDown() override { stack->stop(); } string get_addr() const { return addr; } string get_ip_different_port() const { return port_addr; } string get_different_ip() const { return "10.0.123.100:4323"; } EventCenter *get_center(unsigned i) { return &stack->get_worker(i)->center; } Worker *get_worker(unsigned i) { return stack->get_worker(i); } template<typename func> class C_dispatch : public EventCallback { Worker *worker; func f; std::atomic_bool done; public: C_dispatch(Worker *w, func &&_f): worker(w), f(std::move(_f)), done(false) {} void do_request(uint64_t id) override { f(worker); done = true; } void wait() { int us = 1000 * 1000 * 1000; while (!done) { ASSERT_TRUE(us > 0); usleep(100); us -= 100; } } }; template<typename func> void exec_events(func &&f) { std::vector<C_dispatch<func>*> dis; for (unsigned i = 0; i < stack->get_num_worker(); ++i) { Worker *w = stack->get_worker(i); C_dispatch<func> *e = new C_dispatch<func>(w, std::move(f)); stack->get_worker(i)->center.dispatch_event_external(e); dis.push_back(e); } for (auto &&e : dis) { e->wait(); delete e; } } }; class C_poll : public EventCallback { EventCenter *center; std::atomic<bool> woken; static const int sleepus = 500; public: explicit C_poll(EventCenter *c): center(c), woken(false) {} void do_request(uint64_t r) override { woken = true; } bool poll(int milliseconds) { auto start = ceph::coarse_real_clock::now(); while (!woken) { center->process_events(sleepus); usleep(sleepus); auto r = std::chrono::duration_cast<std::chrono::milliseconds>( ceph::coarse_real_clock::now() - start); if (r >= std::chrono::milliseconds(milliseconds)) break; } return woken; } void reset() { woken = false; } }; TEST_P(NetworkWorkerTest, SimpleTest) { entity_addr_t bind_addr; ASSERT_TRUE(bind_addr.parse(get_addr().c_str())); std::atomic_bool accepted(false); std::atomic_bool *accepted_p = &accepted; exec_events([this, accepted_p, bind_addr](Worker *worker) mutable { entity_addr_t cli_addr; SocketOptions options; ServerSocket bind_socket; EventCenter *center = &worker->center; ssize_t r = 0; if (stack->support_local_listen_table() || worker->id == 0) r = worker->listen(bind_addr, 0, options, &bind_socket); ASSERT_EQ(0, r); ConnectedSocket cli_socket, srv_socket; if (worker->id == 0) { r = worker->connect(bind_addr, options, &cli_socket); ASSERT_EQ(0, r); } bool is_my_accept = false; if (bind_socket) { C_poll cb(center); center->create_file_event(bind_socket.fd(), EVENT_READABLE, &cb); if (cb.poll(500)) { *accepted_p = true; is_my_accept = true; } ASSERT_TRUE(*accepted_p); center->delete_file_event(bind_socket.fd(), EVENT_READABLE); } if (is_my_accept) { r = bind_socket.accept(&srv_socket, options, &cli_addr, worker); ASSERT_EQ(0, r); ASSERT_TRUE(srv_socket.fd() > 0); } if (worker->id == 0) { C_poll cb(center); center->create_file_event(cli_socket.fd(), EVENT_READABLE, &cb); r = cli_socket.is_connected(); if (r == 0) { ASSERT_EQ(true, cb.poll(500)); r = cli_socket.is_connected(); } ASSERT_EQ(1, r); center->delete_file_event(cli_socket.fd(), EVENT_READABLE); } const char *message = "this is a new message"; int len = strlen(message); bufferlist bl; bl.append(message, len); if (worker->id == 0) { r = cli_socket.send(bl, false); ASSERT_EQ(len, r); } char buf[1024]; C_poll cb(center); if (is_my_accept) { center->create_file_event(srv_socket.fd(), EVENT_READABLE, &cb); { r = srv_socket.read(buf, sizeof(buf)); while (r == -EAGAIN) { ASSERT_TRUE(cb.poll(500)); r = srv_socket.read(buf, sizeof(buf)); cb.reset(); } ASSERT_EQ(len, r); ASSERT_EQ(0, memcmp(buf, message, len)); } bind_socket.abort_accept(); } if (worker->id == 0) { cli_socket.shutdown(); // ack delay is 200 ms } bl.clear(); bl.append(message, len); if (worker->id == 0) { r = cli_socket.send(bl, false); ASSERT_EQ(-EPIPE, r); } if (is_my_accept) { cb.reset(); ASSERT_TRUE(cb.poll(500)); r = srv_socket.read(buf, sizeof(buf)); if (r == -EAGAIN) { cb.reset(); ASSERT_TRUE(cb.poll(1000*500)); r = srv_socket.read(buf, sizeof(buf)); } ASSERT_EQ(0, r); center->delete_file_event(srv_socket.fd(), EVENT_READABLE); srv_socket.close(); } }); } TEST_P(NetworkWorkerTest, ConnectFailedTest) { entity_addr_t bind_addr; ASSERT_TRUE(bind_addr.parse(get_addr().c_str())); exec_events([this, bind_addr](Worker *worker) mutable { EventCenter *center = &worker->center; entity_addr_t cli_addr; SocketOptions options; ServerSocket bind_socket; int r = 0; if (stack->support_local_listen_table() || worker->id == 0) r = worker->listen(bind_addr, 0, options, &bind_socket); ASSERT_EQ(0, r); ConnectedSocket cli_socket1, cli_socket2; if (worker->id == 0) { ASSERT_TRUE(cli_addr.parse(get_ip_different_port().c_str())); r = worker->connect(cli_addr, options, &cli_socket1); ASSERT_EQ(0, r); C_poll cb(center); center->create_file_event(cli_socket1.fd(), EVENT_READABLE, &cb); r = cli_socket1.is_connected(); if (r == 0) { ASSERT_TRUE(cb.poll(500)); r = cli_socket1.is_connected(); } ASSERT_TRUE(r == -ECONNREFUSED || r == -ECONNRESET); } if (worker->id == 1) { ASSERT_TRUE(cli_addr.parse(get_different_ip().c_str())); r = worker->connect(cli_addr, options, &cli_socket2); ASSERT_EQ(0, r); C_poll cb(center); center->create_file_event(cli_socket2.fd(), EVENT_READABLE, &cb); r = cli_socket2.is_connected(); if (r == 0) { cb.poll(500); r = cli_socket2.is_connected(); } ASSERT_TRUE(r != 1); center->delete_file_event(cli_socket2.fd(), EVENT_READABLE); } }); } TEST_P(NetworkWorkerTest, ListenTest) { Worker *worker = get_worker(0); entity_addr_t bind_addr; ASSERT_TRUE(bind_addr.parse(get_addr().c_str())); SocketOptions options; ServerSocket bind_socket1, bind_socket2; int r = worker->listen(bind_addr, 0, options, &bind_socket1); ASSERT_EQ(0, r); r = worker->listen(bind_addr, 0, options, &bind_socket2); ASSERT_EQ(-EADDRINUSE, r); } TEST_P(NetworkWorkerTest, AcceptAndCloseTest) { entity_addr_t bind_addr; ASSERT_TRUE(bind_addr.parse(get_addr().c_str())); std::atomic_bool accepted(false); std::atomic_bool *accepted_p = &accepted; std::atomic_int unbind_count(stack->get_num_worker()); std::atomic_int *count_p = &unbind_count; exec_events([this, bind_addr, accepted_p, count_p](Worker *worker) mutable { SocketOptions options; EventCenter *center = &worker->center; entity_addr_t cli_addr; int r = 0; { ServerSocket bind_socket; if (stack->support_local_listen_table() || worker->id == 0) r = worker->listen(bind_addr, 0, options, &bind_socket); ASSERT_EQ(0, r); ConnectedSocket srv_socket, cli_socket; if (bind_socket) { r = bind_socket.accept(&srv_socket, options, &cli_addr, worker); ASSERT_EQ(-EAGAIN, r); } C_poll cb(center); if (worker->id == 0) { center->create_file_event(bind_socket.fd(), EVENT_READABLE, &cb); r = worker->connect(bind_addr, options, &cli_socket); ASSERT_EQ(0, r); ASSERT_TRUE(cb.poll(500)); } if (bind_socket) { cb.reset(); cb.poll(500); ConnectedSocket srv_socket2; do { r = bind_socket.accept(&srv_socket2, options, &cli_addr, worker); usleep(100); } while (r == -EAGAIN && !*accepted_p); if (r == 0) *accepted_p = true; ASSERT_TRUE(*accepted_p); // srv_socket2 closed center->delete_file_event(bind_socket.fd(), EVENT_READABLE); } if (worker->id == 0) { char buf[100]; cb.reset(); center->create_file_event(cli_socket.fd(), EVENT_READABLE, &cb); int i = 3; while (!i--) { ASSERT_TRUE(cb.poll(500)); r = cli_socket.read(buf, sizeof(buf)); if (r == 0) break; } ASSERT_EQ(0, r); center->delete_file_event(cli_socket.fd(), EVENT_READABLE); } if (bind_socket) center->create_file_event(bind_socket.fd(), EVENT_READABLE, &cb); if (worker->id == 0) { *accepted_p = false; r = worker->connect(bind_addr, options, &cli_socket); ASSERT_EQ(0, r); cb.reset(); ASSERT_TRUE(cb.poll(500)); cli_socket.close(); } if (bind_socket) { do { r = bind_socket.accept(&srv_socket, options, &cli_addr, worker); usleep(100); } while (r == -EAGAIN && !*accepted_p); if (r == 0) *accepted_p = true; ASSERT_TRUE(*accepted_p); center->delete_file_event(bind_socket.fd(), EVENT_READABLE); } // unbind } --*count_p; while (*count_p > 0) usleep(100); ConnectedSocket cli_socket; r = worker->connect(bind_addr, options, &cli_socket); ASSERT_EQ(0, r); { C_poll cb(center); center->create_file_event(cli_socket.fd(), EVENT_READABLE, &cb); r = cli_socket.is_connected(); if (r == 0) { ASSERT_TRUE(cb.poll(500)); r = cli_socket.is_connected(); } ASSERT_TRUE(r == -ECONNREFUSED || r == -ECONNRESET); } }); } TEST_P(NetworkWorkerTest, ComplexTest) { entity_addr_t bind_addr; std::atomic_bool listen_done(false); std::atomic_bool *listen_p = &listen_done; std::atomic_bool accepted(false); std::atomic_bool *accepted_p = &accepted; std::atomic_bool done(false); std::atomic_bool *done_p = &done; ASSERT_TRUE(bind_addr.parse(get_addr().c_str())); exec_events([this, bind_addr, listen_p, accepted_p, done_p](Worker *worker) mutable { entity_addr_t cli_addr; EventCenter *center = &worker->center; SocketOptions options; ServerSocket bind_socket; int r = 0; if (stack->support_local_listen_table() || worker->id == 0) { r = worker->listen(bind_addr, 0, options, &bind_socket); ASSERT_EQ(0, r); *listen_p = true; } ConnectedSocket cli_socket, srv_socket; if (worker->id == 1) { while (!*listen_p || stack->support_local_listen_table()) { usleep(50); r = worker->connect(bind_addr, options, &cli_socket); ASSERT_EQ(0, r); if (stack->support_local_listen_table()) break; } } if (bind_socket) { C_poll cb(center); center->create_file_event(bind_socket.fd(), EVENT_READABLE, &cb); int count = 3; while (count--) { if (cb.poll(500)) { r = bind_socket.accept(&srv_socket, options, &cli_addr, worker); ASSERT_EQ(0, r); *accepted_p = true; break; } } ASSERT_TRUE(*accepted_p); center->delete_file_event(bind_socket.fd(), EVENT_READABLE); } if (worker->id == 1) { C_poll cb(center); center->create_file_event(cli_socket.fd(), EVENT_WRITABLE, &cb); r = cli_socket.is_connected(); if (r == 0) { ASSERT_TRUE(cb.poll(500)); r = cli_socket.is_connected(); } ASSERT_EQ(1, r); center->delete_file_event(cli_socket.fd(), EVENT_WRITABLE); } const size_t message_size = 10240; size_t count = 100; string message(message_size, '!'); for (size_t i = 0; i < message_size; i += 100) message[i] = ','; size_t len = message_size * count; C_poll cb(center); if (worker->id == 1) center->create_file_event(cli_socket.fd(), EVENT_WRITABLE, &cb); if (srv_socket) center->create_file_event(srv_socket.fd(), EVENT_READABLE, &cb); size_t left = len; len *= 2; string read_string; int again_count = 0; int c = 2; bufferlist bl; for (size_t i = 0; i < count; ++i) bl.push_back(bufferptr((char*)message.data(), message_size)); while (!*done_p) { again_count = 0; if (worker->id == 1) { if (c > 0) { ssize_t r = 0; usleep(100); if (left > 0) { r = cli_socket.send(bl, false); ASSERT_TRUE(r >= 0 || r == -EAGAIN); if (r > 0) left -= r; if (r == -EAGAIN) ++again_count; } if (left == 0) { --c; left = message_size * count; ASSERT_EQ(0U, bl.length()); for (size_t i = 0; i < count; ++i) bl.push_back(bufferptr((char*)message.data(), message_size)); } } } if (srv_socket) { char buf[1000]; if (len > 0) { r = srv_socket.read(buf, sizeof(buf)); ASSERT_TRUE(r > 0 || r == -EAGAIN); if (r > 0) { read_string.append(buf, r); len -= r; } else if (r == -EAGAIN) { ++again_count; } } if (len == 0) { for (size_t i = 0; i < read_string.size(); i += message_size) ASSERT_EQ(0, memcmp(read_string.c_str()+i, message.c_str(), message_size)); *done_p = true; } } if (again_count) { cb.reset(); cb.poll(500); } } if (worker->id == 1) center->delete_file_event(cli_socket.fd(), EVENT_WRITABLE); if (srv_socket) center->delete_file_event(srv_socket.fd(), EVENT_READABLE); if (bind_socket) bind_socket.abort_accept(); if (srv_socket) srv_socket.close(); if (worker->id == 1) cli_socket.close(); }); } class StressFactory { struct Client; struct Server; struct ThreadData { Worker *worker; std::set<Client*> clients; std::set<Server*> servers; ~ThreadData() { for (auto && i : clients) delete i; for (auto && i : servers) delete i; } }; struct RandomString { size_t slen; vector<std::string> strs; std::random_device rd; std::default_random_engine rng; explicit RandomString(size_t s): slen(s), rng(rd()) {} void prepare(size_t n) { static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789"; std::uniform_int_distribution<> dist( 0, sizeof(alphabet) / sizeof(*alphabet) - 2); strs.reserve(n); std::generate_n( std::back_inserter(strs), strs.capacity(), [&] { std::string str; str.reserve(slen); std::generate_n(std::back_inserter(str), slen, [&]() { return alphabet[dist(rng)]; }); return str; } ); } std::string &get_random_string() { std::uniform_int_distribution<> dist( 0, strs.size() - 1); return strs[dist(rng)]; } }; struct Message { size_t idx; size_t len; std::string content; explicit Message(RandomString &rs, size_t i, size_t l): idx(i) { size_t slen = rs.slen; len = std::max(slen, l); std::vector<std::string> strs; strs.reserve(len / slen); std::generate_n( std::back_inserter(strs), strs.capacity(), [&] { return rs.get_random_string(); } ); len = slen * strs.size(); content.reserve(len); for (auto &&s : strs) content.append(s); } bool verify(const char *b, size_t len = 0) const { return content.compare(0, len, b, 0, len) == 0; } }; template <typename T> class C_delete : public EventCallback { T *ctxt; public: explicit C_delete(T *c): ctxt(c) {} void do_request(uint64_t id) override { delete ctxt; delete this; } }; class Client { StressFactory *factory; EventCenter *center; ConnectedSocket socket; std::deque<StressFactory::Message*> acking; std::deque<StressFactory::Message*> writings; std::string buffer; size_t index = 0; size_t left; bool write_enabled = false; size_t read_offset = 0, write_offset = 0; bool first = true; bool dead = false; StressFactory::Message homeless_message; class Client_read_handle : public EventCallback { Client *c; public: explicit Client_read_handle(Client *_c): c(_c) {} void do_request(uint64_t id) override { c->do_read_request(); } } read_ctxt; class Client_write_handle : public EventCallback { Client *c; public: explicit Client_write_handle(Client *_c): c(_c) {} void do_request(uint64_t id) override { c->do_write_request(); } } write_ctxt; public: Client(StressFactory *f, EventCenter *cen, ConnectedSocket s, size_t c) : factory(f), center(cen), socket(std::move(s)), left(c), homeless_message(factory->rs, -1, 1024), read_ctxt(this), write_ctxt(this) { center->create_file_event( socket.fd(), EVENT_READABLE, &read_ctxt); center->dispatch_event_external(&read_ctxt); } void close() { ASSERT_FALSE(write_enabled); dead = true; socket.shutdown(); center->delete_file_event(socket.fd(), EVENT_READABLE); center->dispatch_event_external(new C_delete<Client>(this)); } void do_read_request() { if (dead) return ; ASSERT_TRUE(socket.is_connected() >= 0); if (!socket.is_connected()) return ; ASSERT_TRUE(!acking.empty() || first); if (first) { first = false; center->dispatch_event_external(&write_ctxt); if (acking.empty()) return ; } StressFactory::Message *m = acking.front(); int r = 0; if (buffer.empty()) buffer.resize(m->len); bool must_no = false; while (true) { r = socket.read((char*)buffer.data() + read_offset, m->len - read_offset); ASSERT_TRUE(r == -EAGAIN || r > 0); if (r == -EAGAIN) break; read_offset += r; std::cerr << " client " << this << " receive " << m->idx << " len " << r << " content: " << std::endl; ASSERT_FALSE(must_no); if ((m->len - read_offset) == 0) { ASSERT_TRUE(m->verify(buffer.data(), 0)); delete m; acking.pop_front(); read_offset = 0; buffer.clear(); if (acking.empty()) { m = &homeless_message; must_no = true; } else { m = acking.front(); buffer.resize(m->len); } } } if (acking.empty()) { center->dispatch_event_external(&write_ctxt); return ; } } void do_write_request() { if (dead) return ; ASSERT_TRUE(socket.is_connected() > 0); while (left > 0 && factory->queue_depth > writings.size() + acking.size()) { StressFactory::Message *m = new StressFactory::Message( factory->rs, ++index, factory->rd() % factory->max_message_length); std::cerr << " client " << this << " generate message " << m->idx << " length " << m->len << std::endl; ASSERT_EQ(m->len, m->content.size()); writings.push_back(m); --left; --factory->message_left; } while (!writings.empty()) { StressFactory::Message *m = writings.front(); bufferlist bl; bl.append(m->content.data() + write_offset, m->content.size() - write_offset); ssize_t r = socket.send(bl, false); if (r == 0) break; std::cerr << " client " << this << " send " << m->idx << " len " << r << " content: " << std::endl; ASSERT_TRUE(r >= 0); write_offset += r; if (write_offset == m->content.size()) { write_offset = 0; writings.pop_front(); acking.push_back(m); } } if (writings.empty() && write_enabled) { center->delete_file_event(socket.fd(), EVENT_WRITABLE); write_enabled = false; } else if (!writings.empty() && !write_enabled) { ASSERT_EQ(0, center->create_file_event( socket.fd(), EVENT_WRITABLE, &write_ctxt)); write_enabled = true; } } bool finish() const { return left == 0 && acking.empty() && writings.empty(); } }; friend class Client; class Server { StressFactory *factory; EventCenter *center; ConnectedSocket socket; std::deque<std::string> buffers; bool write_enabled = false; bool dead = false; class Server_read_handle : public EventCallback { Server *s; public: explicit Server_read_handle(Server *_s): s(_s) {} void do_request(uint64_t id) override { s->do_read_request(); } } read_ctxt; class Server_write_handle : public EventCallback { Server *s; public: explicit Server_write_handle(Server *_s): s(_s) {} void do_request(uint64_t id) override { s->do_write_request(); } } write_ctxt; public: Server(StressFactory *f, EventCenter *c, ConnectedSocket s): factory(f), center(c), socket(std::move(s)), read_ctxt(this), write_ctxt(this) { center->create_file_event(socket.fd(), EVENT_READABLE, &read_ctxt); center->dispatch_event_external(&read_ctxt); } void close() { ASSERT_FALSE(write_enabled); socket.shutdown(); center->delete_file_event(socket.fd(), EVENT_READABLE); center->dispatch_event_external(new C_delete<Server>(this)); } void do_read_request() { if (dead) return ; int r = 0; while (true) { char buf[4096]; bufferptr data; r = socket.read(buf, sizeof(buf)); ASSERT_TRUE(r == -EAGAIN || (r >= 0 && (size_t)r <= sizeof(buf))); if (r == 0) { ASSERT_TRUE(buffers.empty()); dead = true; return ; } else if (r == -EAGAIN) break; buffers.emplace_back(buf, 0, r); std::cerr << " server " << this << " receive " << r << " content: " << std::endl; } if (!buffers.empty() && !write_enabled) center->dispatch_event_external(&write_ctxt); } void do_write_request() { if (dead) return ; while (!buffers.empty()) { bufferlist bl; auto it = buffers.begin(); for (size_t i = 0; i < buffers.size(); ++i) { bl.push_back(bufferptr((char*)it->data(), it->size())); ++it; } ssize_t r = socket.send(bl, false); std::cerr << " server " << this << " send " << r << std::endl; if (r == 0) break; ASSERT_TRUE(r >= 0); while (r > 0) { ASSERT_TRUE(!buffers.empty()); string &buffer = buffers.front(); if (r >= (int)buffer.size()) { r -= (int)buffer.size(); buffers.pop_front(); } else { std::cerr << " server " << this << " sent " << r << std::endl; buffer = buffer.substr(r, buffer.size()); break; } } } if (buffers.empty()) { if (write_enabled) { center->delete_file_event(socket.fd(), EVENT_WRITABLE); write_enabled = false; } } else if (!write_enabled) { ASSERT_EQ(0, center->create_file_event( socket.fd(), EVENT_WRITABLE, &write_ctxt)); write_enabled = true; } } bool finish() { return dead; } }; friend class Server; class C_accept : public EventCallback { StressFactory *factory; ServerSocket bind_socket; ThreadData *t_data; Worker *worker; public: C_accept(StressFactory *f, ServerSocket s, ThreadData *data, Worker *w) : factory(f), bind_socket(std::move(s)), t_data(data), worker(w) {} void do_request(uint64_t id) override { while (true) { entity_addr_t cli_addr; ConnectedSocket srv_socket; SocketOptions options; int r = bind_socket.accept(&srv_socket, options, &cli_addr, worker); if (r == -EAGAIN) { break; } ASSERT_EQ(0, r); ASSERT_TRUE(srv_socket.fd() > 0); Server *cb = new Server(factory, &t_data->worker->center, std::move(srv_socket)); t_data->servers.insert(cb); } } }; friend class C_accept; public: static const size_t min_client_send_messages = 100; static const size_t max_client_send_messages = 1000; std::shared_ptr<NetworkStack> stack; RandomString rs; std::random_device rd; const size_t client_num, queue_depth, max_message_length; atomic_int message_count, message_left; entity_addr_t bind_addr; std::atomic_bool already_bind = {false}; SocketOptions options; explicit StressFactory(const std::shared_ptr<NetworkStack> &s, const string &addr, size_t cli, size_t qd, size_t mc, size_t l) : stack(s), rs(128), client_num(cli), queue_depth(qd), max_message_length(l), message_count(mc), message_left(mc) { bind_addr.parse(addr.c_str()); rs.prepare(100); } ~StressFactory() { } void add_client(ThreadData *t_data) { static ceph::mutex lock = ceph::make_mutex("add_client_lock"); std::lock_guard l{lock}; ConnectedSocket sock; int r = t_data->worker->connect(bind_addr, options, &sock); std::default_random_engine rng(rd()); std::uniform_int_distribution<> dist( min_client_send_messages, max_client_send_messages); ASSERT_EQ(0, r); int c = dist(rng); if (c > message_count.load()) c = message_count.load(); Client *cb = new Client(this, &t_data->worker->center, std::move(sock), c); t_data->clients.insert(cb); message_count -= c; } void drop_client(ThreadData *t_data, Client *c) { c->close(); ASSERT_EQ(1U, t_data->clients.erase(c)); } void drop_server(ThreadData *t_data, Server *s) { s->close(); ASSERT_EQ(1U, t_data->servers.erase(s)); } void start(Worker *worker) { int r = 0; ThreadData t_data; t_data.worker = worker; ServerSocket bind_socket; if (stack->support_local_listen_table() || worker->id == 0) { r = worker->listen(bind_addr, 0, options, &bind_socket); ASSERT_EQ(0, r); already_bind = true; } while (!already_bind) usleep(50); C_accept *accept_handler = nullptr; int bind_fd = 0; if (bind_socket) { bind_fd = bind_socket.fd(); accept_handler = new C_accept(this, std::move(bind_socket), &t_data, worker); ASSERT_EQ(0, worker->center.create_file_event( bind_fd, EVENT_READABLE, accept_handler)); } int echo_throttle = message_count; while (message_count > 0 || !t_data.clients.empty() || !t_data.servers.empty()) { if (message_count > 0 && t_data.clients.size() < client_num && t_data.servers.size() < client_num) add_client(&t_data); for (auto &&c : t_data.clients) { if (c->finish()) { drop_client(&t_data, c); break; } } for (auto &&s : t_data.servers) { if (s->finish()) { drop_server(&t_data, s); break; } } worker->center.process_events(1); if (echo_throttle > message_left) { std::cerr << " clients " << t_data.clients.size() << " servers " << t_data.servers.size() << " message count " << message_left << std::endl; echo_throttle -= 100; } } if (bind_fd) worker->center.delete_file_event(bind_fd, EVENT_READABLE); delete accept_handler; } }; TEST_P(NetworkWorkerTest, StressTest) { StressFactory factory(stack, get_addr(), 16, 16, 10000, 1024); StressFactory *f = &factory; exec_events([f](Worker *worker) mutable { f->start(worker); }); ASSERT_EQ(0, factory.message_left); } INSTANTIATE_TEST_SUITE_P( NetworkStack, NetworkWorkerTest, ::testing::Values( #ifdef HAVE_DPDK "dpdk", #endif "posix" ) ); /* * Local Variables: * compile-command: "cd ../.. ; make ceph_test_async_networkstack && * ./ceph_test_async_networkstack * * End: */
31,246
28.121156
111
cc
null
ceph-main/src/test/msgr/test_comp_registry.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "include/types.h" #include "include/stringify.h" #include "compressor/Compressor.h" #include "msg/compressor_registry.h" #include "gtest/gtest.h" #include "common/ceph_context.h" #include "global/global_context.h" #include <sstream> TEST(CompressorRegistry, con_modes) { auto cct = g_ceph_context; CompressorRegistry reg(cct); std::vector<uint32_t> methods; uint32_t method; uint32_t mode; const std::vector<uint32_t> snappy_method = { Compressor::COMP_ALG_SNAPPY }; const std::vector<uint32_t> zlib_method = { Compressor::COMP_ALG_ZLIB }; const std::vector<uint32_t> both_methods = { Compressor::COMP_ALG_ZLIB, Compressor::COMP_ALG_SNAPPY}; const std::vector<uint32_t> no_method = { Compressor::COMP_ALG_NONE }; cct->_conf.set_val( "enable_experimental_unrecoverable_data_corrupting_features", "*"); // baseline: compression for communication with osd is enabled cct->_set_module_type(CEPH_ENTITY_TYPE_CLIENT); cct->_conf.set_val("ms_osd_compress_mode", "force"); cct->_conf.set_val("ms_osd_compression_algorithm", "snappy"); cct->_conf.set_val("ms_compress_secure", "false"); cct->_conf.apply_changes(NULL); ASSERT_EQ(reg.get_is_compress_secure(), false); methods = reg.get_methods(CEPH_ENTITY_TYPE_MON); ASSERT_EQ(methods.size(), 0); method = reg.pick_method(CEPH_ENTITY_TYPE_MON, both_methods); ASSERT_EQ(method, Compressor::COMP_ALG_NONE); mode = reg.get_mode(CEPH_ENTITY_TYPE_MON, false); ASSERT_EQ(mode, Compressor::COMP_NONE); methods = reg.get_methods(CEPH_ENTITY_TYPE_OSD); ASSERT_EQ(methods, snappy_method); const std::vector<uint32_t> rev_both_methods (both_methods.rbegin(), both_methods.rend()); method = reg.pick_method(CEPH_ENTITY_TYPE_OSD, rev_both_methods); ASSERT_EQ(method, Compressor::COMP_ALG_SNAPPY); mode = reg.get_mode(CEPH_ENTITY_TYPE_OSD, false); ASSERT_EQ(mode, Compressor::COMP_FORCE); mode = reg.get_mode(CEPH_ENTITY_TYPE_OSD, true); ASSERT_EQ(mode, Compressor::COMP_NONE); method = reg.pick_method(CEPH_ENTITY_TYPE_OSD, zlib_method); ASSERT_EQ(method, Compressor::COMP_ALG_NONE); // disable compression mode cct->_set_module_type(CEPH_ENTITY_TYPE_CLIENT); cct->_conf.set_val("ms_osd_compress_mode", "none"); cct->_conf.apply_changes(NULL); mode = reg.get_mode(CEPH_ENTITY_TYPE_OSD, false); ASSERT_EQ(mode, Compressor::COMP_NONE); // no compression methods cct->_conf.set_val("ms_osd_compress_mode", "force"); cct->_conf.set_val("ms_osd_compression_algorithm", "none"); cct->_conf.apply_changes(NULL); method = reg.pick_method(CEPH_ENTITY_TYPE_OSD, both_methods); ASSERT_EQ(method, Compressor::COMP_ALG_NONE); // min compression size cct->_conf.set_val("ms_osd_compress_min_size", "1024"); cct->_conf.apply_changes(NULL); uint32_t s = reg.get_min_compression_size(CEPH_ENTITY_TYPE_OSD); ASSERT_EQ(s, 1024); // allow secure with compression cct->_conf.set_val("ms_osd_compress_mode", "force"); cct->_conf.set_val("ms_osd_compression_algorithm", "snappy"); cct->_conf.set_val("ms_compress_secure", "true"); cct->_conf.apply_changes(NULL); ASSERT_EQ(reg.get_is_compress_secure(), true); mode = reg.get_mode(CEPH_ENTITY_TYPE_OSD, true); ASSERT_EQ(mode, Compressor::COMP_FORCE); mode = reg.get_mode(CEPH_ENTITY_TYPE_OSD, false); ASSERT_EQ(mode, Compressor::COMP_FORCE); // back to normalish, for the benefit of the next test(s) cct->_set_module_type(CEPH_ENTITY_TYPE_CLIENT); }
3,565
35.020202
103
cc
null
ceph-main/src/test/msgr/test_frames_v2.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2020 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "msg/async/frames_v2.h" #include <numeric> #include <ostream> #include <string> #include <tuple> #include "msg/async/compression_meta.h" #include "auth/Auth.h" #include "common/ceph_argparse.h" #include "global/global_init.h" #include "global/global_context.h" #include "include/Context.h" #include <gtest/gtest.h> #define COMP_THRESHOLD 1 << 10 #define EXPECT_COMPRESSED(is_compressed, val1, val2) \ if (is_compressed && val1 > COMP_THRESHOLD) { \ EXPECT_GE(val1, val2); \ } else { \ EXPECT_EQ(val1, val2); \ } using namespace std; namespace ceph::msgr::v2 { // MessageFrame with the first segment not fixed to ceph_msg_header2 struct TestFrame : Frame<TestFrame, /* four segments */ segment_t::DEFAULT_ALIGNMENT, segment_t::DEFAULT_ALIGNMENT, segment_t::DEFAULT_ALIGNMENT, segment_t::PAGE_SIZE_ALIGNMENT> { static constexpr Tag tag = static_cast<Tag>(123); static TestFrame Encode(const bufferlist& header, const bufferlist& front, const bufferlist& middle, const bufferlist& data) { TestFrame f; f.segments[SegmentIndex::Msg::HEADER] = header; f.segments[SegmentIndex::Msg::FRONT] = front; f.segments[SegmentIndex::Msg::MIDDLE] = middle; f.segments[SegmentIndex::Msg::DATA] = data; // discard cached crcs for perf tests f.segments[SegmentIndex::Msg::HEADER].invalidate_crc(); f.segments[SegmentIndex::Msg::FRONT].invalidate_crc(); f.segments[SegmentIndex::Msg::MIDDLE].invalidate_crc(); f.segments[SegmentIndex::Msg::DATA].invalidate_crc(); return f; } static TestFrame Decode(segment_bls_t& segment_bls) { TestFrame f; // Transfer segments' bufferlists. If segment_bls contains // less than SegmentsNumV segments, the missing ones will be // seen as empty. for (size_t i = 0; i < segment_bls.size(); i++) { f.segments[i] = std::move(segment_bls[i]); } return f; } bufferlist& header() { return segments[SegmentIndex::Msg::HEADER]; } bufferlist& front() { return segments[SegmentIndex::Msg::FRONT]; } bufferlist& middle() { return segments[SegmentIndex::Msg::MIDDLE]; } bufferlist& data() { return segments[SegmentIndex::Msg::DATA]; } protected: using Frame::Frame; }; struct mode_t { bool is_rev1; bool is_secure; bool is_compress; }; static std::ostream& operator<<(std::ostream& os, const mode_t& m) { os << "msgr2." << (m.is_rev1 ? "1" : "0") << (m.is_secure ? "-secure" : "-crc") << (m.is_compress ? "-compress": "-nocompress"); return os; } static const mode_t modes[] = { {false, false, false}, {false, true, false}, {true, false, false}, {true, true, false}, {false, false, true}, {false, true, true}, {true, false, true}, {true, true, true} }; struct round_trip_instance_t { uint32_t header_len; uint32_t front_len; uint32_t middle_len; uint32_t data_len; // expected number of segments (same for each mode) size_t num_segments; // expected layout (different for each mode) uint32_t onwire_lens[4][MAX_NUM_SEGMENTS + 2]; }; static std::ostream& operator<<(std::ostream& os, const round_trip_instance_t& rti) { os << rti.header_len << "+" << rti.front_len << "+" << rti.middle_len << "+" << rti.data_len; return os; } static bufferlist make_bufferlist(size_t len, char c) { bufferlist bl; if (len > 0) { bl.reserve(len); bl.append(std::string(len, c)); } return bl; } bool disassemble_frame(FrameAssembler& frame_asm, bufferlist& frame_bl, Tag& tag, segment_bls_t& segment_bls) { bufferlist preamble_bl; frame_bl.splice(0, frame_asm.get_preamble_onwire_len(), &preamble_bl); tag = frame_asm.disassemble_preamble(preamble_bl); do { size_t seg_idx = segment_bls.size(); segment_bls.emplace_back(); uint32_t onwire_len = frame_asm.get_segment_onwire_len(seg_idx); if (onwire_len > 0) { frame_bl.splice(0, onwire_len, &segment_bls.back()); } } while (segment_bls.size() < frame_asm.get_num_segments()); bufferlist epilogue_bl; uint32_t epilogue_onwire_len = frame_asm.get_epilogue_onwire_len(); if (epilogue_onwire_len > 0) { frame_bl.splice(0, epilogue_onwire_len, &epilogue_bl); } return frame_asm.disassemble_segments(preamble_bl, segment_bls.data(), epilogue_bl); } class RoundTripTestBase : public ::testing::TestWithParam< std::tuple<round_trip_instance_t, mode_t>> { protected: RoundTripTestBase() : m_tx_frame_asm(&m_tx_crypto, std::get<1>(GetParam()).is_rev1, true, &m_tx_comp), m_rx_frame_asm(&m_rx_crypto, std::get<1>(GetParam()).is_rev1, true, &m_rx_comp), m_header(make_bufferlist(std::get<0>(GetParam()).header_len, 'H')), m_front(make_bufferlist(std::get<0>(GetParam()).front_len, 'F')), m_middle(make_bufferlist(std::get<0>(GetParam()).middle_len, 'M')), m_data(make_bufferlist(std::get<0>(GetParam()).data_len, 'D')) { const auto& m = std::get<1>(GetParam()); if (m.is_secure) { AuthConnectionMeta auth_meta; auth_meta.con_mode = CEPH_CON_MODE_SECURE; // see AuthConnectionMeta::get_connection_secret_length() auth_meta.connection_secret.resize(64); g_ceph_context->random()->get_bytes(auth_meta.connection_secret.data(), auth_meta.connection_secret.size()); m_tx_crypto = ceph::crypto::onwire::rxtx_t::create_handler_pair( g_ceph_context, auth_meta, /*new_nonce_format=*/m.is_rev1, /*crossed=*/false); m_rx_crypto = ceph::crypto::onwire::rxtx_t::create_handler_pair( g_ceph_context, auth_meta, /*new_nonce_format=*/m.is_rev1, /*crossed=*/true); } if (m.is_compress) { CompConnectionMeta comp_meta; comp_meta.con_mode = Compressor::COMP_FORCE; comp_meta.con_method = Compressor::COMP_ALG_SNAPPY; m_tx_comp = ceph::compression::onwire::rxtx_t::create_handler_pair( g_ceph_context, comp_meta, /*min_compress_size=*/COMP_THRESHOLD ); m_rx_comp = ceph::compression::onwire::rxtx_t::create_handler_pair( g_ceph_context, comp_meta, /*min_compress_size=*/COMP_THRESHOLD ); } } void check_frame_assembler(const FrameAssembler& frame_asm) { const auto& [rti, m] = GetParam(); const auto& onwire_lens = rti.onwire_lens[m.is_rev1 << 1 | m.is_secure]; EXPECT_COMPRESSED(m.is_compress, rti.header_len + rti.front_len + rti.middle_len + rti.data_len, frame_asm.get_frame_logical_len()); ASSERT_EQ(rti.num_segments, frame_asm.get_num_segments()); EXPECT_COMPRESSED(m.is_compress, onwire_lens[0], frame_asm.get_preamble_onwire_len()); for (size_t i = 0; i < rti.num_segments; i++) { EXPECT_COMPRESSED(m.is_compress, onwire_lens[i + 1], frame_asm.get_segment_onwire_len(i)); } EXPECT_COMPRESSED(m.is_compress, onwire_lens[rti.num_segments + 1], frame_asm.get_epilogue_onwire_len()); EXPECT_COMPRESSED(m.is_compress, std::accumulate(std::begin(onwire_lens), std::end(onwire_lens), uint64_t(0)), frame_asm.get_frame_onwire_len()); } void test_round_trip() { auto tx_frame = TestFrame::Encode(m_header, m_front, m_middle, m_data); auto onwire_bl = tx_frame.get_buffer(m_tx_frame_asm); check_frame_assembler(m_tx_frame_asm); EXPECT_EQ(m_tx_frame_asm.get_frame_onwire_len(), onwire_bl.length()); Tag rx_tag; segment_bls_t rx_segment_bls; EXPECT_TRUE(disassemble_frame(m_rx_frame_asm, onwire_bl, rx_tag, rx_segment_bls)); check_frame_assembler(m_rx_frame_asm); EXPECT_EQ(0, onwire_bl.length()); EXPECT_EQ(TestFrame::tag, rx_tag); EXPECT_EQ(m_rx_frame_asm.get_num_segments(), rx_segment_bls.size()); auto rx_frame = TestFrame::Decode(rx_segment_bls); EXPECT_TRUE(m_header.contents_equal(rx_frame.header())); EXPECT_TRUE(m_front.contents_equal(rx_frame.front())); EXPECT_TRUE(m_middle.contents_equal(rx_frame.middle())); EXPECT_TRUE(m_data.contents_equal(rx_frame.data())); } ceph::crypto::onwire::rxtx_t m_tx_crypto; ceph::crypto::onwire::rxtx_t m_rx_crypto; ceph::compression::onwire::rxtx_t m_tx_comp; ceph::compression::onwire::rxtx_t m_rx_comp; FrameAssembler m_tx_frame_asm; FrameAssembler m_rx_frame_asm; const bufferlist m_header; const bufferlist m_front; const bufferlist m_middle; const bufferlist m_data; }; class RoundTripTest : public RoundTripTestBase {}; TEST_P(RoundTripTest, Basic) { test_round_trip(); } TEST_P(RoundTripTest, Reuse) { for (int i = 0; i < 3; i++) { test_round_trip(); } } static const round_trip_instance_t round_trip_instances[] = { // first segment is empty { 0, 0, 0, 0, 1, {{32, 0, 17, 0, 0, 0}, {32, 0, 32, 0, 0, 0}, {32, 0, 0, 0, 0, 0}, {96, 0, 0, 0, 0, 0}}}, { 0, 0, 0, 303, 4, {{32, 0, 0, 0, 303, 17}, {32, 0, 0, 0, 304, 32}, {32, 0, 0, 0, 303, 13}, {96, 0, 0, 0, 304, 32}}}, { 0, 0, 202, 0, 3, {{32, 0, 0, 202, 17, 0}, {32, 0, 0, 208, 32, 0}, {32, 0, 0, 202, 13, 0}, {96, 0, 0, 208, 32, 0}}}, { 0, 0, 202, 303, 4, {{32, 0, 0, 202, 303, 17}, {32, 0, 0, 208, 304, 32}, {32, 0, 0, 202, 303, 13}, {96, 0, 0, 208, 304, 32}}}, { 0, 101, 0, 0, 2, {{32, 0, 101, 17, 0, 0}, {32, 0, 112, 32, 0, 0}, {32, 0, 101, 13, 0, 0}, {96, 0, 112, 32, 0, 0}}}, { 0, 101, 0, 303, 4, {{32, 0, 101, 0, 303, 17}, {32, 0, 112, 0, 304, 32}, {32, 0, 101, 0, 303, 13}, {96, 0, 112, 0, 304, 32}}}, { 0, 101, 202, 0, 3, {{32, 0, 101, 202, 17, 0}, {32, 0, 112, 208, 32, 0}, {32, 0, 101, 202, 13, 0}, {96, 0, 112, 208, 32, 0}}}, { 0, 101, 202, 303, 4, {{32, 0, 101, 202, 303, 17}, {32, 0, 112, 208, 304, 32}, {32, 0, 101, 202, 303, 13}, {96, 0, 112, 208, 304, 32}}}, // first segment is fully inlined, inline buffer is not full { 1, 0, 0, 0, 1, {{32, 1, 17, 0, 0, 0}, {32, 16, 32, 0, 0, 0}, {32, 5, 0, 0, 0, 0}, {96, 0, 0, 0, 0, 0}}}, { 1, 0, 0, 303, 4, {{32, 1, 0, 0, 303, 17}, {32, 16, 0, 0, 304, 32}, {32, 5, 0, 0, 303, 13}, {96, 0, 0, 0, 304, 32}}}, { 1, 0, 202, 0, 3, {{32, 1, 0, 202, 17, 0}, {32, 16, 0, 208, 32, 0}, {32, 5, 0, 202, 13, 0}, {96, 0, 0, 208, 32, 0}}}, { 1, 0, 202, 303, 4, {{32, 1, 0, 202, 303, 17}, {32, 16, 0, 208, 304, 32}, {32, 5, 0, 202, 303, 13}, {96, 0, 0, 208, 304, 32}}}, { 1, 101, 0, 0, 2, {{32, 1, 101, 17, 0, 0}, {32, 16, 112, 32, 0, 0}, {32, 5, 101, 13, 0, 0}, {96, 0, 112, 32, 0, 0}}}, { 1, 101, 0, 303, 4, {{32, 1, 101, 0, 303, 17}, {32, 16, 112, 0, 304, 32}, {32, 5, 101, 0, 303, 13}, {96, 0, 112, 0, 304, 32}}}, { 1, 101, 202, 0, 3, {{32, 1, 101, 202, 17, 0}, {32, 16, 112, 208, 32, 0}, {32, 5, 101, 202, 13, 0}, {96, 0, 112, 208, 32, 0}}}, { 1, 101, 202, 303, 4, {{32, 1, 101, 202, 303, 17}, {32, 16, 112, 208, 304, 32}, {32, 5, 101, 202, 303, 13}, {96, 0, 112, 208, 304, 32}}}, // first segment is fully inlined, inline buffer is full {48, 0, 0, 0, 1, {{32, 48, 17, 0, 0, 0}, {32, 48, 32, 0, 0, 0}, {32, 52, 0, 0, 0, 0}, {96, 0, 0, 0, 0, 0}}}, {48, 0, 0, 303, 4, {{32, 48, 0, 0, 303, 17}, {32, 48, 0, 0, 304, 32}, {32, 52, 0, 0, 303, 13}, {96, 0, 0, 0, 304, 32}}}, {48, 0, 202, 0, 3, {{32, 48, 0, 202, 17, 0}, {32, 48, 0, 208, 32, 0}, {32, 52, 0, 202, 13, 0}, {96, 0, 0, 208, 32, 0}}}, {48, 0, 202, 303, 4, {{32, 48, 0, 202, 303, 17}, {32, 48, 0, 208, 304, 32}, {32, 52, 0, 202, 303, 13}, {96, 0, 0, 208, 304, 32}}}, {48, 101, 0, 0, 2, {{32, 48, 101, 17, 0, 0}, {32, 48, 112, 32, 0, 0}, {32, 52, 101, 13, 0, 0}, {96, 0, 112, 32, 0, 0}}}, {48, 101, 0, 303, 4, {{32, 48, 101, 0, 303, 17}, {32, 48, 112, 0, 304, 32}, {32, 52, 101, 0, 303, 13}, {96, 0, 112, 0, 304, 32}}}, {48, 101, 202, 0, 3, {{32, 48, 101, 202, 17, 0}, {32, 48, 112, 208, 32, 0}, {32, 52, 101, 202, 13, 0}, {96, 0, 112, 208, 32, 0}}}, {48, 101, 202, 303, 4, {{32, 48, 101, 202, 303, 17}, {32, 48, 112, 208, 304, 32}, {32, 52, 101, 202, 303, 13}, {96, 0, 112, 208, 304, 32}}}, // first segment is partially inlined {49, 0, 0, 0, 1, {{32, 49, 17, 0, 0, 0}, {32, 64, 32, 0, 0, 0}, {32, 53, 0, 0, 0, 0}, {96, 32, 0, 0, 0, 0}}}, {49, 0, 0, 303, 4, {{32, 49, 0, 0, 303, 17}, {32, 64, 0, 0, 304, 32}, {32, 53, 0, 0, 303, 13}, {96, 32, 0, 0, 304, 32}}}, {49, 0, 202, 0, 3, {{32, 49, 0, 202, 17, 0}, {32, 64, 0, 208, 32, 0}, {32, 53, 0, 202, 13, 0}, {96, 32, 0, 208, 32, 0}}}, {49, 0, 202, 303, 4, {{32, 49, 0, 202, 303, 17}, {32, 64, 0, 208, 304, 32}, {32, 53, 0, 202, 303, 13}, {96, 32, 0, 208, 304, 32}}}, {49, 101, 0, 0, 2, {{32, 49, 101, 17, 0, 0}, {32, 64, 112, 32, 0, 0}, {32, 53, 101, 13, 0, 0}, {96, 32, 112, 32, 0, 0}}}, {49, 101, 0, 303, 4, {{32, 49, 101, 0, 303, 17}, {32, 64, 112, 0, 304, 32}, {32, 53, 101, 0, 303, 13}, {96, 32, 112, 0, 304, 32}}}, {49, 101, 202, 0, 3, {{32, 49, 101, 202, 17, 0}, {32, 64, 112, 208, 32, 0}, {32, 53, 101, 202, 13, 0}, {96, 32, 112, 208, 32, 0}}}, {49, 101, 202, 303, 4, {{32, 49, 101, 202, 303, 17}, {32, 64, 112, 208, 304, 32}, {32, 53, 101, 202, 303, 13}, {96, 32, 112, 208, 304, 32}}}, }; INSTANTIATE_TEST_SUITE_P( RoundTripTests, RoundTripTest, ::testing::Combine( ::testing::ValuesIn(round_trip_instances), ::testing::ValuesIn(modes))); class RoundTripPerfTest : public RoundTripTestBase {}; TEST_P(RoundTripPerfTest, DISABLED_Basic) { for (int i = 0; i < 100000; i++) { auto tx_frame = TestFrame::Encode(m_header, m_front, m_middle, m_data); auto onwire_bl = tx_frame.get_buffer(m_tx_frame_asm); Tag rx_tag; segment_bls_t rx_segment_bls; ASSERT_TRUE(disassemble_frame(m_rx_frame_asm, onwire_bl, rx_tag, rx_segment_bls)); } } static const round_trip_instance_t round_trip_perf_instances[] = { {41, 250, 0, 0, 2, {{32, 41, 250, 17, 0, 0}, {32, 48, 256, 32, 0, 0}, {32, 45, 250, 13, 0, 0}, {96, 0, 256, 32, 0, 0}}}, {41, 250, 0, 512, 4, {{32, 41, 250, 0, 512, 17}, {32, 48, 256, 0, 512, 32}, {32, 45, 250, 0, 512, 13}, {96, 0, 256, 0, 512, 32}}}, {41, 250, 0, 4096, 4, {{32, 41, 250, 0, 4096, 17}, {32, 48, 256, 0, 4096, 32}, {32, 45, 250, 0, 4096, 13}, {96, 0, 256, 0, 4096, 32}}}, {41, 250, 0, 32768, 4, {{32, 41, 250, 0, 32768, 17}, {32, 48, 256, 0, 32768, 32}, {32, 45, 250, 0, 32768, 13}, {96, 0, 256, 0, 32768, 32}}}, {41, 250, 0, 131072, 4, {{32, 41, 250, 0, 131072, 17}, {32, 48, 256, 0, 131072, 32}, {32, 45, 250, 0, 131072, 13}, {96, 0, 256, 0, 131072, 32}}}, {41, 250, 0, 4194304, 4, {{32, 41, 250, 0, 4194304, 17}, {32, 48, 256, 0, 4194304, 32}, {32, 45, 250, 0, 4194304, 13}, {96, 0, 256, 0, 4194304, 32}}}, }; INSTANTIATE_TEST_SUITE_P( RoundTripPerfTests, RoundTripPerfTest, ::testing::Combine( ::testing::ValuesIn(round_trip_perf_instances), ::testing::ValuesIn(modes))); } // namespace ceph::msgr::v2 int main(int argc, char* argv[]) { auto args = argv_to_vec(argc, argv); auto cct = global_init(nullptr, args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(g_ceph_context); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
19,530
39.353306
100
cc