osd, cli: Pause writes while making a live snapshot #177

Open
koolkhel wants to merge 5 commits from koolkhel/vitastor:readonly-inode-check into master
23 changed files with 730 additions and 30 deletions

View File

@@ -1697,6 +1697,42 @@ jobs:
echo ""
done
test_snapshot_switch:
runs-on: ubuntu-latest
needs: build
container: ${{env.TEST_IMAGE}}:${{github.sha}}
steps:
- name: Run test
id: test
timeout-minutes: 3
run: /root/vitastor/tests/test_snapshot_switch.sh
- name: Print logs
if: always() && steps.test.outcome == 'failure'
run: |
for i in /root/vitastor/testdata/*.log /root/vitastor/testdata/*.txt; do
echo "-------- $i --------"
cat $i
echo ""
done
test_snapshot_switch_imm:
runs-on: ubuntu-latest
needs: build
container: ${{env.TEST_IMAGE}}:${{github.sha}}
steps:
- name: Run test
id: test
timeout-minutes: 3
run: IMMEDIATE_COMMIT=1 /root/vitastor/tests/test_snapshot_switch.sh
- name: Print logs
if: always() && steps.test.outcome == 'failure'
run: |
for i in /root/vitastor/testdata/*.log /root/vitastor/testdata/*.txt; do
echo "-------- $i --------"
cat $i
echo ""
done
test_heal_csum_32k_dmj:
runs-on: ubuntu-latest
needs: build

View File

@@ -152,11 +152,17 @@ vitastor-cli create --snapshot <snapshot> [OPTIONS] <image>
vitastor-cli snap-create [OPTIONS] <image>@<snapshot>
```
Create a snapshot of image `<image>`. May be used live if only a single writer is active.
Create a snapshot of image `<image>`. May be used live, even with several writers: writes
to the image are paused until all OSDs apply the pause (see `--pause-timeout`) and the snapshot
is made, so the snapshot gets every write sent before some moment and none sent after it.
Writers and OSDs of versions before the pause was added aren't paused, with them the snapshot
is only consistent with a single writer. If the command is interrupted while writes are paused,
repeat it to make the snapshot and resume writes.
Options:
* `-p|--pool POOL` - Move image to pool POOL, leaving the snapshot in the old pool.
* `--pause-timeout S` - Give up and resume writes if OSDs don't pause them in S seconds (default 10).
* `--enc-key random` - Change image encryption key to a new random AES-256-XTS key.
* `--enc-key KEY` - Change image encryption key to a specified key, Vault key or to an empty key.
By default, the image retains its old encryption key when taking a snapshot.

View File

@@ -157,11 +157,17 @@ vitastor-cli snap-create [ОПЦИИ] <image>@<snapshot>
```
Создать снимок образа `<image>` (можно использовать любую форму команды).
Снимок можно создавать без остановки клиентов, если пишущих клиентов не больше одного.
Снимок можно создавать без остановки клиентов, в том числе нескольких пишущих: запись в образ
приостанавливается, пока все OSD не применят паузу (см. `--pause-timeout`) и снимок не будет создан,
так что в снимок попадают все записи, отправленные до некоторого момента, и ни одной после него.
Клиенты и OSD версий до появления паузы запись не приостанавливают, с ними снимок согласован
только при одном пишущем клиенте. Если команду прервали, пока запись приостановлена, повторите
её — она создаст снимок и возобновит запись.
Опции:
* `-p|--pool POOL` - Переместить образ в пул POOL, оставив снимок в старом пуле.
* `--pause-timeout S` - Отказаться и возобновить запись, если OSD не приостановят её за S секунд (по умолчанию 10).
* `--enc-key random` - Изменить ключ шифрования образа на новый случайный ключ AES-256-XTS.
* `--enc-key KEY` - Изменить ключ шифрования образа на заданный ключ, ключ из Vault или пустой ключ.
По умолчанию шифрованные образы сохраняют старый ключ при снятии снимка.

View File

@@ -227,8 +227,13 @@ const etcd_tree = {
size?: uint64_t, // bytes
parent_pool?: <pool_id>,
parent_id?: <inode_t>,
// the layer that replaced this one when it was snapshotted
successor_pool?: <pool_id>,
successor_id?: <inode_t>,
readonly?: boolean,
deleted?: boolean,
// writes are paused while a snapshot of this layer is being made
paused?: boolean,
enc_key?: string,
owner?: string,
owner_group?: string,
@@ -254,6 +259,8 @@ const etcd_tree = {
port: uint16_t,
primary_enabled: boolean,
blockstore_enabled: boolean,
// config revision applied by the OSD, updated when it starts rejecting writes to a paused inode
config_revision: uint64_t,
}, */
},
stats: {

View File

@@ -28,6 +28,7 @@ cluster_client_t::cluster_client_t(ring_loop_t *ringloop, timerfd_manager_t *tfd
msgr = new osd_messenger_t();
msgr->osd_num = 0;
msgr->announce_readonly_check = true;
msgr->tfd = tfd;
msgr->ringloop = ringloop;
msgr->repeer_pgs = [this](osd_num_t peer_osd)
@@ -1330,17 +1331,23 @@ resume_2:
return 1;
}
else if (op->retval != 0 && op->opcode != OSD_OP_SYNC && !(op->flags & OP_FLUSH_BUFFER) &&
op->retval != -EPIPE && op->retval != -EAGAIN &&
op->retval != -EPIPE && op->retval != -EAGAIN && op->retval != -ESTALE &&
(op->retval != -EIO || !client_eio_retry_interval) &&
(op->retval != -ENOSPC || !client_retry_enospc))
{
// Fatal error (neither -EPIPE, -EAGAIN, -EIO nor -ENOSPC)
// Fatal error (neither -EPIPE, -EAGAIN, -ESTALE, -EIO nor -ENOSPC)
erase_op(op);
return 1;
}
else
{
// Non-fatal error - clear the error and retry
if (op->retval == -ESTALE && !follow_stale_write(op))
{
op->retval = -EROFS;
erase_op(op);
return 1;
}
op->retval = 0;
if (op->needs_reslice)
{
@@ -1566,7 +1573,8 @@ int cluster_client_t::try_send(cluster_op_t *op, int i, std::function<void(osd_o
.inode = op->cur_inode,
.offset = part->offset,
.len = part->len,
.flags = op->opcode == OSD_OP_READ && op->enc && !op->deoptimise_snapshot ? OSD_OP_RETURN_CHAIN : 0,
.flags = (op->opcode == OSD_OP_READ && op->enc && !op->deoptimise_snapshot ? OSD_OP_RETURN_CHAIN : 0) |
(op->flags & OSD_OP_IGNORE_READONLY ? OSD_OP_IGNORE_INODE_READONLY : 0),
.meta_revision = meta_rev,
.version = op->opcode == OSD_OP_WRITE || op->opcode == OSD_OP_DELETE ? op->version : 0,
} },
@@ -1707,7 +1715,8 @@ void cluster_client_t::handle_op_part(cluster_op_part_t *part)
if (ERR_PRIO(part->op.reply.hdr.retval) > ERR_PRIO(op->retval))
op->retval = part->op.reply.hdr.retval;
uint64_t stop_client_id = 0;
if (op->retval != -EINTR && op->retval != -EIO && op->retval != -ENOSPC && op->retval != -EPERM && op->retval != -EAGAIN)
if (op->retval != -EINTR && op->retval != -EIO && op->retval != -ENOSPC && op->retval != -EPERM &&
op->retval != -EAGAIN && op->retval != -ESTALE)
{
stop_client_id = part->op.client_id;
if (op->retval != -EPIPE || log_level > 0)
@@ -1729,11 +1738,12 @@ void cluster_client_t::handle_op_part(cluster_op_part_t *part)
// So do all these things after modifying operation state, otherwise we may hit reenterability bugs
// FIXME postpone such things to set_immediate here to avoid bugs
// Set op->retry_after to retry operation after a short pause (not immediately)
if (!op->retry_after && (op->retval == -EPIPE || op->retval == -EAGAIN ||
if (!op->retry_after && (op->retval == -EPIPE || op->retval == -EAGAIN || op->retval == -ESTALE ||
op->retval == -EIO && client_eio_retry_interval ||
op->retval == -ENOSPC && client_retry_enospc))
{
op->retry_after = op->retval != -EPIPE && op->retval != -EAGAIN ? client_eio_retry_interval : client_retry_interval;
op->retry_after = op->retval != -EPIPE && op->retval != -EAGAIN && op->retval != -ESTALE
? client_eio_retry_interval : client_retry_interval;
}
reset_retry_timer(op->retry_after);
if (stop_client_id)
@@ -1780,6 +1790,55 @@ void cluster_client_t::handle_op_part(cluster_op_part_t *part)
}
}
// An OSD rejected a write because the inode is paused for a snapshot or became a snapshot.
// Retry until we see the snapshot too, then resend the whole write to the layer that replaced it.
// Returns false if there's none.
bool cluster_client_t::follow_stale_write(cluster_op_t *op)
{
auto ino_it = st_cli->inode_config.find(op->inode);
if (ino_it == st_cli->inode_config.end() || !ino_it->second.readonly)
{
// Waiting is normal while a snapshot is being made, warn only if it takes long
time_t now = time(NULL);
if (!stale_warning_time)
stale_warning_time = now;
else if (now >= stale_warning_time + 10)
{
fprintf(stderr, "Waiting for etcd: OSDs pause writes to inode %ju in pool %u\n",
INODE_NO_POOL(op->inode), INODE_POOL(op->inode));
stale_warning_time = now;
}
return true;
}
stale_warning_time = 0;
// We may have missed several snapshots
for (size_t i = 0; ino_it->second.readonly; i++)
{
ino_it = st_cli->inode_config.find(ino_it->second.successor_id);
if (ino_it == st_cli->inode_config.end() || i >= st_cli->inode_config.size())
return false;
}
inode_t successor = ino_it->first;
auto icache = inode_cache_get(successor);
if (icache && icache->err_code)
{
// The successor's encryption key isn't loaded yet
return true;
}
if (op->flush_id)
{
// Move the copy kept for replay, it must not be replayed into the snapshot
wb->delete_flush(op->inode, op->offset, op->len, op->flush_id);
op->inode = successor;
wb->copy_write(op, CACHE_REPEATING, op->flush_id);
}
op->inode = op->cur_inode = successor;
op->enc = (op->opcode == OSD_OP_WRITE && icache && icache->op_enc
? std::shared_ptr<osd_op_enc_t>(icache, icache->op_enc) : nullptr);
op->needs_reslice = true;
return true;
}
void cluster_client_t::copy_part_bitmap(cluster_op_t *op, cluster_op_part_t *part)
{
// Copy (OR) bitmap

View File

@@ -155,6 +155,7 @@ class __attribute__((visibility("default"))) cluster_client_t
writeback_cache_t *wb = NULL;
std::set<osd_num_t> dirty_osds;
uint64_t dirty_bytes = 0, dirty_ops = 0;
time_t stale_warning_time = 0;
// inodes require some extra state for read/write, it's stored here.
// moreover, robin_hood access is slightly faster than std::map :)
@@ -239,6 +240,7 @@ protected:
void send_sync(cluster_op_t *op, cluster_op_part_t *part);
void handle_op_part(cluster_op_part_t *part);
void copy_part_bitmap(cluster_op_t *op, cluster_op_part_t *part);
bool follow_stale_write(cluster_op_t *op);
void erase_op(cluster_op_t *op);
void calc_wait(cluster_op_t *op);
void inc_wait(uint64_t opcode, uint64_t flags, cluster_op_t *next, int inc);

View File

@@ -1021,6 +1021,12 @@ json11::Json::object etcd_state_client_t::serialize_inode_cfg(inode_config_t *cf
new_cfg["parent_pool"] = (uint64_t)INODE_POOL(cfg->parent_id);
new_cfg["parent_id"] = (uint64_t)INODE_NO_POOL(cfg->parent_id);
}
if (cfg->successor_id)
{
if (INODE_POOL(cfg->num) != INODE_POOL(cfg->successor_id))
new_cfg["successor_pool"] = (uint64_t)INODE_POOL(cfg->successor_id);
new_cfg["successor_id"] = (uint64_t)INODE_NO_POOL(cfg->successor_id);
}
if (!cfg->enc_key.empty())
{
new_cfg["enc_key"] = cfg->enc_key;
@@ -1033,6 +1039,10 @@ json11::Json::object etcd_state_client_t::serialize_inode_cfg(inode_config_t *cf
{
new_cfg["deleted"] = true;
}
if (cfg->paused)
{
new_cfg["paused"] = true;
}
if (!cfg->owner.empty())
{
new_cfg["owner"] = cfg->owner;
@@ -1071,6 +1081,13 @@ inode_config_t etcd_state_client_t::deserialize_inode_cfg(uint64_t inode_num, js
else
parent_inode_num |= parent_pool_id << (64-POOL_ID_BITS);
}
inode_t successor_id = value["successor_id"].uint64_value();
uint64_t successor_pool = value["successor_pool"].uint64_value();
if (successor_id && !INODE_POOL(successor_id))
{
successor_id = successor_pool >= POOL_ID_MAX ? 0
: INODE_WITH_POOL(successor_pool ? successor_pool : INODE_POOL(inode_num), successor_id);
}
std::string enc_key;
if (!value["enc_key"].is_null())
{
@@ -1088,8 +1105,10 @@ inode_config_t etcd_state_client_t::deserialize_inode_cfg(uint64_t inode_num, js
.name = value["name"].string_value(),
.size = value["size"].uint64_value(),
.parent_id = parent_inode_num,
.successor_id = successor_id,
.readonly = value["readonly"].bool_value(),
.deleted = value["deleted"].bool_value(),
.paused = value["paused"].bool_value(),
.enc_key = std::move(enc_key),
.owner = value["owner"].string_value(),
.owner_group = value["owner_group"].string_value(),

View File

@@ -86,8 +86,12 @@ struct inode_config_t
std::string name;
uint64_t size = 0;
inode_t parent_id = 0;
// The layer that replaced this one when it was snapshotted
inode_t successor_id = 0;
bool readonly = false;
bool deleted = false;
// Writes are paused while a snapshot of this layer is being made
bool paused = false;
std::string enc_key;
// Permissions
std::string owner, owner_group, reader_group;

View File

@@ -181,10 +181,38 @@ void etcd_state_client_http_t::etcd_call_selected(const std::string & api, json1
http_request(keepalive_client, url.addr, req, { .timeout = timeout, .keepalive = true, .ssl = url.ssl }, cb);
}
void etcd_state_client_http_t::apply_watch_events(const json11::Json & events)
{
// First gather all changes into a hash to remove multiple overwrites
std::map<std::string, etcd_kv_t> changes;
for (auto & ev: events.array_items())
{
auto kv = parse_etcd_kv(ev["kv"]);
if (kv.key != "")
{
changes[kv.key] = kv;
}
}
for (auto & kv: changes)
{
if (this->log_level > 3)
{
fprintf(stderr, "Incoming event: %s -> %s\n", kv.first.c_str(), kv.second.value.dump().c_str());
}
parse_state(kv.second);
}
// React to changes
if (on_change_hook != NULL)
{
on_change_hook(changes);
}
}
void etcd_state_client_http_t::parse_config(const json11::Json & config)
{
auto old_etcd_ws_keepalive_interval = this->etcd_ws_keepalive_interval;
etcd_state_client_t::parse_config(config);
this->watch_delay_ms = config["etcd_watch_delay_ms"].uint64_value();
if (this->etcd_ws_keepalive_interval != old_etcd_ws_keepalive_interval && ws_keepalive_timer >= 0)
{
stop_ws_keepalive();
@@ -388,6 +416,9 @@ void etcd_state_client_http_t::start_etcd_watcher_selected()
data["result"]["compact_revision"].uint64_value());
http_close(etcd_watch_ws);
etcd_watch_revision_config = etcd_watch_revision_osd = etcd_watch_revision_pg = 0;
// The reload reads newer state, delayed events must not overwrite it
delayed_watch_events.clear();
watch_delay_gen++;
on_reload_hook();
}
}
@@ -430,29 +461,22 @@ void etcd_state_client_http_t::start_etcd_watcher_selected()
etcd_watch_revision_osd = watch_rev;
etcd_urls_to_try.clear();
}
// First gather all changes into a hash to remove multiple overwrites
std::map<std::string, etcd_kv_t> changes;
for (auto & ev: data["result"]["events"].array_items())
if (watch_delay_ms > 0)
{
auto kv = parse_etcd_kv(ev["kv"]);
if (kv.key != "")
// Debug: emulate a client lagging behind etcd
delayed_watch_events.push_back(data["result"]["events"]);
timers.insert(tfd->set_timer(watch_delay_ms, false, [this, gen = watch_delay_gen](int timer_id)
{
changes[kv.key] = kv;
}
}
for (auto & kv: changes)
{
if (this->log_level > 3)
{
fprintf(stderr, "Incoming event: %s -> %s\n", kv.first.c_str(), kv.second.value.dump().c_str());
}
parse_state(kv.second);
}
// React to changes
if (on_change_hook != NULL)
{
on_change_hook(changes);
timers.erase(timer_id);
if (gen != watch_delay_gen)
return;
json11::Json events = delayed_watch_events.front();
delayed_watch_events.pop_front();
apply_watch_events(events);
}));
}
else
apply_watch_events(data["result"]["events"]);
}
}
if (msg->eof)

View File

@@ -3,6 +3,7 @@
#pragma once
#include <deque>
#include "etcd_state_client.h"
struct http_context_t;
@@ -26,11 +27,15 @@ protected:
http_url_t selected_etcd_url;
size_t resolve_count = 0;
std::vector<std::function<void()>> on_resolve_queue;
uint64_t watch_delay_ms = 0;
uint64_t watch_delay_gen = 0;
std::deque<json11::Json> delayed_watch_events;
void pick_next_etcd(std::function<void()> cb);
void pick_next_etcd_on_resolve();
void start_etcd_watcher();
void start_etcd_watcher_selected();
void apply_watch_events(const json11::Json & events);
void stop_ws_keepalive();
void start_ws_keepalive();
http_context_t *get_http_ctx();

View File

@@ -678,6 +678,10 @@ void osd_messenger_t::check_peer_config(osd_client_t *cl)
payload["osd_num"] = osd_num;
}
auto features = json11::Json::object{ { "check_sequencing", true } };
if (announce_readonly_check)
{
features["readonly_check"] = true;
}
if (use_proto_checksums)
{
features["proto_checksums"] = use_proto_checksums;

View File

@@ -121,6 +121,7 @@ struct osd_client_t
// Peer feature flags
bool check_sequencing = false;
bool readonly_check = false;
bool enable_pg_locks = false;
bool enable_tombstones = false;
@@ -294,6 +295,8 @@ public:
uint64_t next_client_id = 1;
// osd_num = 0 for client messenger, osd_num > 0 for OSD messenger
osd_num_t osd_num = 0;
// Ask OSDs to reject writes to snapshots with -ESTALE (the client resends them to the successor)
bool announce_readonly_check = false;
uint32_t clean_entry_bitmap_size = 0;
uint32_t bs_block_size = 0;
uint32_t max_write_request_size = 0;

View File

@@ -42,6 +42,7 @@
#define OSD_OP_RECOVERY_RELATED (uint32_t)1
#define OSD_OP_IGNORE_PG_LOCK (uint32_t)2
#define OSD_OP_RETURN_CHAIN (uint32_t)4
#define OSD_OP_IGNORE_INODE_READONLY (uint32_t)8
// Memory alignment for direct I/O (usually 512 bytes)
#ifndef DIRECT_IO_ALIGNMENT
@@ -245,6 +246,7 @@ struct __attribute__((__packed__)) osd_op_rw_t
// OSD_OP_RETURN_CHAIN for chained reads: return parent number in chain for each block
// read_chain size comes after bitmap, takes 0 bytes / 1 byte / 2 byte / 4 byte per each block,
// depending on the number of parent inodes (0 parents = 0 bytes, up to 255 parents = 1 byte, etc)
// OSD_OP_IGNORE_INODE_READONLY for writes and deletes: the write is meant for a read-only inode
uint32_t flags;
// inode metadata revision for chained reads
uint64_t meta_revision;

View File

@@ -55,9 +55,10 @@ static const char* help_text =
"\n"
"vitastor-cli create --snapshot <snapshot> [OPTIONS] <image>\n"
"vitastor-cli snap-create [OPTIONS] <image>@<snapshot>\n"
" Create a snapshot of image <image>. May be used live if only a single writer is active.\n"
" Create a snapshot of image <image>. May be used live, writes are paused while it's being made.\n"
" Options:\n"
" -p|--pool POOL Move image to pool POOL, leaving the snapshot in the old pool.\n"
" --pause-timeout S Give up if OSDs don't pause writes in S seconds (default 10).\n"
" --enc-key random Change image encryption key to a new random AES-256-XTS key.\n"
" --enc-key KEY Change image encryption key to a specified key, Vault key or to an empty key.\n"
" By default, the image retains its old key when taking a snapshot.\n"

View File

@@ -7,6 +7,7 @@
#include "cli.h"
#include "http_client.h"
#include "cluster_client.h"
#include "epoll_manager.h"
#include "str_util.h"
// Create an image, snapshot or clone
@@ -43,6 +44,10 @@ struct image_creator_t
uint64_t new_parent_mod_rev = 0;
inode_config_t cur_cfg;
inode_config_t new_cfg;
uint64_t pause_timeout = 10;
bool pause_done = false;
uint64_t paused_rev = 0;
uint64_t pause_wait_ms = 0;
int state = 0;
cli_result_t result;
@@ -117,7 +122,12 @@ struct image_creator_t
if (new_snap == "")
create_image();
else
create_snapshot();
{
if (state != 8)
create_snapshot();
if (state == 8 || state == 100 && result.err && paused_rev)
resume_writes();
}
}
bool check_pool_permission()
@@ -277,6 +287,10 @@ resume_3:
goto resume_4;
else if (state == 5)
goto resume_5;
else if (state == 6)
goto resume_6;
else if (state == 7)
goto resume_7;
// FIXME: take all info from etcd requests, not mixed with st_cli->inode_config
for (auto & ic: parent->cli->st_cli->inode_config)
{
@@ -323,6 +337,63 @@ resume_3:
{
return;
}
if (!pause_done)
{
// Pause writes and wait until all OSDs reject them, so that the snapshot gets every write
// sent before some moment and none sent after it, even with several clients writing
pause_done = true;
for (auto & st: parent->cli->st_cli->peer_states)
{
if (st.second["primary_enabled"] != false && st.second["config_revision"].is_null())
{
fprintf(stderr, "Warning: OSD %ju can't pause writes, the snapshot may be inconsistent"
" if several clients write to %s\n", st.first, image_name.c_str());
goto skip_pause;
}
}
set_paused(true);
state = 6;
resume_6:
if (parent->waiting > 0)
return;
if (parent->etcd_err.err)
{
result = parent->etcd_err;
state = 100;
return;
}
if (!parent->etcd_result["succeeded"].bool_value())
{
// The image changed, read it again
pause_done = false;
continue;
}
paused_rev = cur_cfg.mod_revision = parent->etcd_result["header"]["revision"].uint64_value();
cur_cfg.paused = true;
state = 7;
resume_7:
if (parent->waiting > 0)
return;
if (osd_num_t osd_num = lagging_osd(paused_rev))
{
if (pause_wait_ms >= pause_timeout*1000)
{
result = (cli_result_t){ .err = ETIMEDOUT, .text = "OSD "+std::to_string(osd_num)+
" didn't pause writes to "+image_name+" in "+std::to_string(pause_timeout)+" s" };
state = 100;
return;
}
pause_wait_ms += 100;
parent->waiting++;
parent->epmgr->tfd->set_timer(100, false, [this](int timer_id)
{
parent->waiting--;
parent->ringloop->wakeup();
});
return;
}
}
skip_pause:
parent->etcd_txn(json11::Json::object {
{ "success", json11::Json::array { get_next_id() } }
});
@@ -382,6 +453,60 @@ resume_5:
state = 100;
}
void set_paused(bool paused)
{
inode_config_t cfg = cur_cfg;
cfg.paused = paused;
std::string key = base64_encode(parent->cli->st_cli->etcd_prefix+"/config/inode/"+
std::to_string(old_pool_id)+"/"+std::to_string(old_id));
parent->etcd_txn(json11::Json::object {
{ "compare", json11::Json::array {
json11::Json::object {
{ "target", "MOD" },
{ "mod_revision", cur_cfg.mod_revision },
{ "key", key },
},
} },
{ "success", json11::Json::array {
json11::Json::object {
{ "request_put", json11::Json::object {
{ "key", key },
{ "value", base64_encode(json11::Json(parent->cli->st_cli->serialize_inode_cfg(&cfg)).dump()) },
} },
},
} },
});
}
// A primary OSD which still accepts writes to the image
osd_num_t lagging_osd(uint64_t rev)
{
for (auto & st: parent->cli->st_cli->peer_states)
{
if (st.second["primary_enabled"] != false && st.second["config_revision"].uint64_value() < rev)
return st.first;
}
return 0;
}
// Don't leave writes paused when the snapshot fails
void resume_writes()
{
if (state == 8)
goto resume_8;
set_paused(false);
state = 8;
resume_8:
if (parent->waiting > 0)
return;
if (parent->etcd_err.err || !parent->etcd_result["succeeded"].bool_value())
{
result.text += ". Writes to "+image_name+" are still paused, repeat the command to make the snapshot";
}
paused_rev = 0;
state = 100;
}
json11::Json::object get_next_id()
{
assert(new_pool_id);
@@ -608,6 +733,8 @@ resume_3:
inode_config_t snap_cfg = cur_cfg;
snap_cfg.name = image_name+"@"+new_snap;
snap_cfg.readonly = true;
snap_cfg.paused = false;
snap_cfg.successor_id = new_cfg.num;
checks.push_back(json11::Json::object {
{ "target", "MOD" },
{ "mod_revision", cur_cfg.mod_revision },
@@ -684,6 +811,8 @@ std::function<bool(cli_result_t &)> cli_tool_t::start_create(json11::Json cfg)
}
image_creator->force = cfg["force"].bool_value();
image_creator->force_size = cfg["force_size"].bool_value();
if (!cfg["pause_timeout"].is_null())
image_creator->pause_timeout = cfg["pause_timeout"].uint64_value();
if (cfg["image_meta"].is_object())
{
image_creator->new_meta = cfg["image_meta"];

View File

@@ -188,6 +188,8 @@ class osd_t
int etcd_failed_attempts = 0;
std::string etcd_lease_id;
json11::Json self_state;
uint64_t config_rev_to_report = 0;
bool reporting_config_rev = false;
bool loading_peer_config = false;
std::set<pool_pg_num_t> pg_state_dirty;
bool etcd_global_config_loaded = false;
@@ -311,6 +313,7 @@ class osd_t
void acquire_lease();
json11::Json get_osd_state();
void create_osd_state();
void report_config_revision(uint64_t rev);
void renew_lease(bool reload);
void print_stats();
void tune_recovery();

View File

@@ -177,6 +177,7 @@ json11::Json osd_t::get_osd_state()
#endif
st["primary_enabled"] = run_primary;
st["blockstore_enabled"] = bs ? true : false;
st["config_revision"] = 0;
return st;
}
@@ -489,6 +490,19 @@ void osd_t::on_change_backfillfull_hook(pool_id_t pool_id)
void osd_t::on_change_etcd_state_hook(std::map<std::string, etcd_kv_t> & changes)
{
uint64_t paused_rev = 0;
for (auto & kv: changes)
{
if (kv.second.value["paused"].bool_value() &&
kv.first.substr(0, st_cli->etcd_prefix.length()+14) == st_cli->etcd_prefix+"/config/inode/")
{
paused_rev = std::max(paused_rev, kv.second.mod_revision);
}
}
if (paused_rev)
{
report_config_revision(paused_rev);
}
if (changes.find(st_cli->etcd_prefix+"/config/global") != changes.end())
{
etcd_global_config = changes[st_cli->etcd_prefix+"/config/global"].value.object_items();
@@ -703,6 +717,49 @@ void osd_t::force_stop(int exitcode)
}
}
// vitastor-cli makes a snapshot only after all OSDs report that they reject writes to the paused inode
void osd_t::report_config_revision(uint64_t rev)
{
if (rev > config_rev_to_report)
config_rev_to_report = rev;
if (reporting_config_rev || config_rev_to_report <= self_state["config_revision"].uint64_value())
return;
// One update at a time, so that an older revision never overwrites a newer one
reporting_config_rev = true;
json11::Json::object st = self_state.object_items();
st["config_revision"] = config_rev_to_report;
json11::Json new_state = st;
std::string state_key = base64_encode(st_cli->etcd_prefix+"/osd/state/"+std::to_string(osd_num));
st_cli->etcd_txn(json11::Json::object {
{ "compare", json11::Json::array {
json11::Json::object {
{ "target", "LEASE" },
{ "lease", etcd_lease_id },
{ "key", state_key },
},
} },
{ "success", json11::Json::array {
json11::Json::object {
{ "request_put", json11::Json::object {
{ "key", state_key },
{ "value", base64_encode(new_state.dump()) },
{ "lease", etcd_lease_id },
} },
},
} },
}, st_cli->etcd_quick_timeout, 0, 0, [this, new_state](std::string err, json11::Json data)
{
reporting_config_rev = false;
if (err != "" || !data["succeeded"].bool_value())
{
printf("Error reporting applied configuration revision: %s\n", err != "" ? err.c_str() : "lease mismatch");
return;
}
self_state = new_state;
report_config_revision(0);
});
}
json11::Json osd_t::on_load_pgs_checks_hook()
{
json11::Json::array checks = {
@@ -725,6 +782,14 @@ void osd_t::on_load_pgs_hook(bool success)
else
{
peering_state &= ~OSD_LOADING_PGS;
for (auto & ic: st_cli->inode_config)
{
if (ic.second.paused)
{
report_config_revision(st_cli->etcd_watch_revision_config);
break;
}
}
apply_no_inode_stats();
if (run_primary)
{

View File

@@ -87,6 +87,23 @@ bool osd_t::prepare_primary_rw(osd_op_t *cur_op)
return false;
}
}
if ((cur_op->req.hdr.opcode == OSD_OP_WRITE || cur_op->req.hdr.opcode == OSD_OP_DELETE) &&
!(cur_op->req.rw.flags & OSD_OP_IGNORE_INODE_READONLY))
{
auto cl_it = msgr.clients.find(cur_op->client_id);
auto inode_it = st_cli->inode_config.find(cur_op->req.rw.inode);
// Snapshots without a successor (made by an older vitastor-cli) still accept such writes:
// the client would have nowhere to resend them
if (cl_it != msgr.clients.end() && cl_it->second->readonly_check &&
inode_it != st_cli->inode_config.end() &&
(inode_it->second.paused || inode_it->second.readonly && inode_it->second.successor_id))
{
// A snapshot is being made, or the client hasn't seen yet that the inode became one.
// The client waits and resends; CAS writes can't be resent to another inode
finish_op(cur_op, cur_op->req.rw.version ? -EROFS : -ESTALE);
return false;
}
}
int stripe_count = (cur_op->req.hdr.opcode == OSD_OP_SCRUB ? 0 :
(pool_cfg.scheme == POOL_SCHEME_REPLICATED ? 1 : pg_it->second.pg_size));
int chain_size = 0;

View File

@@ -385,6 +385,7 @@ void osd_t::exec_show_config(osd_op_t *cur_op)
{
cl->check_sequencing = true;
}
cl->readonly_check = req_json["features"]["readonly_check"].bool_value();
auto features = json11::Json::object{ { "pg_locks", true }, { "tombstones", bs->supports_tombstones() } };
if (msgr.use_proto_checksums)
{

View File

@@ -5445,6 +5445,79 @@ void test_chained_read_through_incomplete_parent()
printf("test_chained_read_through_incomplete_parent passed\n");
}
// A client which announces readonly_check gets -ESTALE (or -EROFS for CAS writes) for writes
// to a snapshot it hasn't seen yet or to an inode paused for a snapshot. Layer maintenance,
// older clients and snapshots without a successor keep the previous behaviour.
void test_readonly_check()
{
printf("test_readonly_check\n");
osd_test_fixture_t f;
f.configure_replicated_pool(1, 2, 1, 1, { { 1, 2 } });
f.start(json11::Json::object {
{ "osd_num", 1 },
{ "etcd_address", "127.0.0.1:2379" },
{ "immediate_commit", "all" },
{ "block_size", 131072 },
{ "bitmap_granularity", 4096 },
});
f.connect_peer(2);
f.complete_peering_empty();
assert(f.pg(1, 1).state & PG_ACTIVE);
f.st_cli->set("/vitastor/config/inode/1/1", json11::Json::object { { "name", "img@s" }, { "readonly", true }, { "successor_id", 2 } });
f.st_cli->set("/vitastor/config/inode/1/2", json11::Json::object { { "name", "img" }, { "parent_id", 1 } });
f.st_cli->set("/vitastor/config/inode/1/3", json11::Json::object { { "name", "old@s" }, { "readonly", true } });
uint64_t checked = f.connect_client();
f.client(checked)->readonly_check = true;
uint64_t unchecked = f.connect_client();
auto write = [&](uint64_t client_id, uint64_t id, inode_t inode, uint64_t offset, uint64_t version, uint32_t flags)
{
auto *op = make_write_op(inode, offset, 4096, 0xab);
op->client_id = client_id;
op->req.rw.header.id = id;
op->req.rw.version = version;
op->req.rw.flags = flags;
f.exec(op);
return op;
};
auto complete_write = [&](osd_op_t *op)
{
f.bs_zero_read_ok(0);
f.bs_write_ok(BS_OP_WRITE_STABLE, 1);
f.peer_write_ok(2, OSD_OP_SEC_WRITE_STABLE, 1);
assert(op->reply.hdr.retval == 4096);
};
// Rejected before touching data: plain writes as stale, CAS writes as read-only
assert(write(checked, 1, INODE_WITH_POOL(1, 1), 0, 0, 0)->reply.hdr.retval == -ESTALE);
assert(write(checked, 2, INODE_WITH_POOL(1, 1), 0, 1, 0)->reply.hdr.retval == -EROFS);
assert(f.bs->queued.empty());
// Layer maintenance and clients which didn't ask for the check go through
complete_write(write(checked, 3, INODE_WITH_POOL(1, 1), 0, 0, OSD_OP_IGNORE_INODE_READONLY));
complete_write(write(unchecked, 4, INODE_WITH_POOL(1, 1), 131072, 0, 0));
// So do writes to a snapshot without a successor, made by an older vitastor-cli
complete_write(write(checked, 5, INODE_WITH_POOL(1, 3), 0, 0, 0));
// An inode paused for a snapshot rejects writes the same way, and the OSD reports
// in its state that it has applied the pause
auto osd_state = [&]()
{
std::string json_err;
return json11::Json::parse(f.etcd_store.data.at("/vitastor/osd/state/1").value, json_err);
};
assert(osd_state()["config_revision"] == 0);
f.st_cli->set("/vitastor/config/inode/1/4", json11::Json::object { { "name", "live" }, { "paused", true } }, 1000);
assert(write(checked, 6, INODE_WITH_POOL(1, 4), 0, 0, 0)->reply.hdr.retval == -ESTALE);
assert(write(checked, 7, INODE_WITH_POOL(1, 4), 0, 1, 0)->reply.hdr.retval == -EROFS);
complete_write(write(unchecked, 8, INODE_WITH_POOL(1, 4), 0, 0, 0));
assert(osd_state()["config_revision"] == 1000);
assert(osd_state()["port"] != json11::Json());
printf("test_readonly_check passed\n");
}
// A primary LIST with min_stripe above max_stripe must be rejected,
// not walk the unclean object lists from lower_bound(min) past upper_bound(max)
void test_primary_list_inverted_range()
@@ -5594,5 +5667,6 @@ int main(int narg, char *args[])
test_tombstone_replicated_roles();
test_tombstone_inline_misplaced();
test_tombstone_forget_counters();
test_readonly_check();
return 0;
}

View File

@@ -21,6 +21,11 @@ public:
}
static void test_vault();
static writeback_cache_t *wb(cluster_client_t *cli)
{
return cli->wb;
}
};
void configure_single_pg_pool(etcd_state_client_mock_t *mock, const char *immediate_commit = "none")
@@ -1343,6 +1348,164 @@ void test_sync_fail_dirty_state_loss()
}
int *test_write_inode(cluster_client_t *cli, inode_t inode, uint64_t flags = 0, uint64_t offset = 0, uint64_t len = 4096)
{
int *r = new int;
*r = -1000;
cluster_op_t *op = new cluster_op_t();
op->opcode = OSD_OP_WRITE;
op->inode = inode;
op->offset = offset;
op->len = len;
op->flags = flags;
op->iov.push_back(malloc_or_die(len), len);
op->callback = [r](cluster_op_t *op)
{
*r = op->retval;
free(op->iov.buf[0].iov_base);
delete op;
};
cli->execute(op);
return r;
}
void test_ignore_readonly_flag()
{
json11::Json config;
timerfd_manager_t *tfd = new timerfd_manager_t([](int fd, bool wr, std::function<void(int, int)> callback){});
etcd_mock_t etcd_store;
etcd_state_client_mock_t *mock = new etcd_state_client_mock_t(etcd_store);
mock->pause();
cluster_client_t *cli = new cluster_client_t(NULL, tfd, config, std::unique_ptr<etcd_state_client_t>(mock));
configure_single_pg_pool(mock);
mock->set("/vitastor/config/inode/1/1", json11::Json::object {
{ "name", "img@s1" },
{ "readonly", true },
{ "successor_id", 2 },
});
mock->set("/vitastor/config/inode/1/2", json11::Json::object {
{ "name", "img" },
{ "parent_id", 1 },
});
mock->resume();
pretend_connected(cli, 1);
assert(cli->st_cli->inode_config.at(0x1000000000001).successor_id == 0x1000000000002);
// Layer maintenance writes go to the read-only layer itself and say so to the OSD
int *r1 = test_write_inode(cli, 0x1000000000001, OSD_OP_IGNORE_READONLY);
osd_op_t *op = cli->msgr->osd_peers.at(1)->sent_ops.begin()->second;
assert(op->req.rw.inode == 0x1000000000001 && op->req.rw.flags == OSD_OP_IGNORE_INODE_READONLY);
pretend_op_completed(cli, op, 0);
assert(*r1 == 4096);
delete r1;
int *r2 = test_write_inode(cli, 0x1000000000002);
op = cli->msgr->osd_peers.at(1)->sent_ops.begin()->second;
assert(op->req.rw.inode == 0x1000000000002 && op->req.rw.flags == 0);
pretend_op_completed(cli, op, 0);
assert(*r2 == 4096);
delete r2;
delete cli;
delete tfd;
printf("[ok] test_ignore_readonly_flag\n");
}
void test_stale_write_follows_successor()
{
json11::Json config;
timerfd_manager_t *tfd = new timerfd_manager_t([](int fd, bool wr, std::function<void(int, int)> callback){});
etcd_mock_t etcd_store;
etcd_state_client_mock_t *mock = new etcd_state_client_mock_t(etcd_store);
mock->pause();
cluster_client_t *cli = new cluster_client_t(NULL, tfd, config, std::unique_ptr<etcd_state_client_t>(mock));
configure_single_pg_pool(mock);
mock->set("/vitastor/config/inode/1/1", json11::Json::object {
{ "name", "img" },
});
mock->set("/vitastor/config/inode/1/3", json11::Json::object {
{ "name", "other" },
});
mock->resume();
pretend_connected(cli, 1);
assert(cli->msgr->announce_readonly_check);
// The client still sees the inode as writable, an OSD already knows it's a snapshot
int *r1 = test_write_inode(cli, 0x1000000000001, 0, 0x1f000, 0x2000);
check_op_count(cli, 1, 2);
pretend_op_completed(cli, find_op(cli, 1, OSD_OP_WRITE, 0x1f000, 0x1000), 0);
pretend_op_completed(cli, find_op(cli, 1, OSD_OP_WRITE, 0x20000, 0x1000), -ESTALE);
assert(*r1 == -1000);
// ...which doesn't break the connection
assert(cli->msgr->osd_peers.find(1) != cli->msgr->osd_peers.end());
// Retried while the client still lags behind
cluster_client_test_t::continue_ops(cli);
check_op_count(cli, 1, 1);
pretend_op_completed(cli, find_op(cli, 1, OSD_OP_WRITE, 0x20000, 0x1000), -ESTALE);
assert(*r1 == -1000);
// ...and while the client sees that writes are paused for the snapshot
mock->set("/vitastor/config/inode/1/1", json11::Json::object {
{ "name", "img" },
{ "paused", true },
});
cluster_client_test_t::continue_ops(cli);
check_op_count(cli, 1, 1);
osd_op_t *paused_op = find_op(cli, 1, OSD_OP_WRITE, 0x20000, 0x1000);
assert(paused_op->req.rw.inode == 0x1000000000001);
pretend_op_completed(cli, paused_op, -ESTALE);
assert(*r1 == -1000);
// Once the client sees the snapshot, the whole write goes to the new head
mock->set("/vitastor/config/inode/1/1", json11::Json::object {
{ "name", "img@s" },
{ "readonly", true },
{ "successor_id", 2 },
});
mock->set("/vitastor/config/inode/1/2", json11::Json::object {
{ "name", "img" },
{ "parent_id", 1 },
});
cluster_client_test_t::continue_ops(cli);
check_op_count(cli, 1, 2);
auto cl = cli->msgr->osd_peers.at(1);
while (cl->sent_ops.size())
{
osd_op_t *op = cl->sent_ops.begin()->second;
assert(op->req.rw.inode == 0x1000000000002);
pretend_op_completed(cli, op, 0);
}
assert(*r1 == 0x2000);
delete r1;
// The copy kept to replay the write after an OSD failure moved with it
auto & dirty = cluster_client_test_t::wb(cli)->dirty_buffers;
assert(dirty.size() && dirty.begin()->first.inode == 0x1000000000002 && dirty.rbegin()->first.inode == 0x1000000000002);
// A stale write to an inode that turns out read-only without a successor fails
int *r2 = test_write_inode(cli, 0x1000000000003);
pretend_op_completed(cli, cl->sent_ops.begin()->second, -ESTALE);
mock->set("/vitastor/config/inode/1/3", json11::Json::object {
{ "name", "other" },
{ "readonly", true },
});
cluster_client_test_t::continue_ops(cli);
assert(*r2 == -EROFS);
delete r2;
// A write to an inode the client already sees as a snapshot isn't redirected
int *r3 = test_write_inode(cli, 0x1000000000001);
assert(*r3 == -EROFS);
delete r3;
check_op_count(cli, 1, 0);
delete cli;
delete tfd;
printf("[ok] test_stale_write_follows_successor\n");
}
// CAS write/delete over two objects must fail with -EINVAL before anything is
// sent: the OSD checks the version of one object only
void test_cas_cross_object()
@@ -1421,5 +1584,7 @@ int main(int narg, char *args[])
test_pg_config_disappears();
test_sync_released_during_continue_ops();
test_snapshot_over_nonexistent_pool();
test_ignore_readonly_flag();
test_stale_write_follows_successor();
return 0;
}

View File

@@ -133,6 +133,8 @@ OLD=1 ./test_corrupt_all.sh
./test_snapshot_pool2.sh
./test_ls_tree.sh
./test_snapshot_read_bitmap.sh
./test_snapshot_switch.sh
IMMEDIATE_COMMIT=1 ./test_snapshot_switch.sh
TEST_NAME=csum_32k_dmj OSD_ARGS="--data_csum_type crc32c --csum_block_size 32k --inmemory_metadata false --inmemory_journal false" OFFSET_ARGS=$OSD_ARGS ./test_heal.sh
TEST_NAME=csum_32k_dj OSD_ARGS="--data_csum_type crc32c --csum_block_size 32k --inmemory_journal false" OFFSET_ARGS=$OSD_ARGS ./test_heal.sh

66
tests/test_snapshot_switch.sh Executable file
View File

@@ -0,0 +1,66 @@
#!/bin/bash -ex
. `dirname $0`/run_3osds.sh
# Two clients keep writing across a snapshot, one of them lagging behind etcd: the writes
# they issue after the snapshot must go to the new image layer, not to the snapshot
$VITASTOR_CLI create -s 16M img -p testpool
$VITASTOR_FIO -bs=1M -direct=1 -iodepth=4 -rw=write -image=img -size=16M \
-mirror_file=./testdata/bin/mirror.bin -randrepeat=0
sed 's/}$/,"etcd_watch_delay_ms":3000}/' $VITASTOR_CFG > ./testdata/lagging.conf
LAGGING_FIO=${VITASTOR_FIO/$VITASTOR_CFG/./testdata/lagging.conf}
RANDWRITE="-bs=4k -direct=1 -iodepth=4 -rw=randwrite -image=img -size=8M -rate_iops=500 -mirror_file=./testdata/bin/mirror.bin -randrepeat=0"
$LAGGING_FIO $RANDWRITE -offset=0 &
LAGGING_PID=$!
$VITASTOR_FIO $RANDWRITE -offset=8M &
FIO_PID=$!
sleep 1
$VITASTOR_CLI snap-create img@s1
$VITASTOR_CLI dd iimg=img@s1 of=./testdata/bin/snap.bin bs=1M iodepth=4
wait $LAGGING_PID
wait $FIO_PID
$VITASTOR_CLI dd iimg=img@s1 of=./testdata/bin/res.bin bs=1M iodepth=4
cmp ./testdata/bin/res.bin ./testdata/bin/snap.bin || format_error "Snapshot s1 changed after it was taken"
$VITASTOR_CLI dd iimg=img of=./testdata/bin/res.bin bs=1M iodepth=4
cmp ./testdata/bin/res.bin ./testdata/bin/mirror.bin || format_error "Image doesn't match written data"
# Now OSDs lag behind etcd too: snap-create must wait until they pause writes. Reading the
# snapshot waits for OSDs to catch up, so the clients write only after snap-create returns:
# they connect first and then wait for data in their input pipes
for i in $(seq 1 $OSD_COUNT); do
eval kill -INT \$OSD${i}_PID
eval wait \$OSD${i}_PID || true
OSD_ARGS="$OSD_ARGS --etcd_watch_delay_ms 3000" start_osd $i
done
wait_up 60
# If OSDs don't pause writes in time, snap-create gives up and resumes writes
$VITASTOR_CLI snap-create --pause-timeout 1 img@s3 && format_error "snap-create didn't time out"
[[ -z "$($ETCDCTL get --print-value-only /vitastor/index/image/img@s3)" ]] || format_error "Snapshot s3 was created"
$ETCDCTL get --prefix --print-value-only /vitastor/config/inode/ | jq -s -e 'map(select(.paused)) | length == 0' || \
format_error "Writes stay paused after snap-create timed out"
dd if=/dev/urandom of=./testdata/bin/new.bin bs=1M count=16
cp ./testdata/bin/mirror.bin ./testdata/bin/snap.bin
mkfifo ./testdata/lagging.pipe ./testdata/normal.pipe
${VITASTOR_CLI/$VITASTOR_CFG/./testdata/lagging.conf} dd if=./testdata/lagging.pipe oimg=img bs=4k &
LAGGING_PID=$!
$VITASTOR_CLI dd if=./testdata/normal.pipe oimg=img bs=4k seek=2048 &
NORMAL_PID=$!
sleep 1
$VITASTOR_CLI snap-create img@s2
head -c 8M ./testdata/bin/new.bin > ./testdata/lagging.pipe &
tail -c 8M ./testdata/bin/new.bin > ./testdata/normal.pipe
wait $LAGGING_PID
wait $NORMAL_PID
$VITASTOR_CLI dd iimg=img@s2 of=./testdata/bin/res.bin bs=1M iodepth=4
cmp ./testdata/bin/res.bin ./testdata/bin/snap.bin || format_error "Snapshot s2 got writes made after it"
$VITASTOR_CLI dd iimg=img of=./testdata/bin/res.bin bs=1M iodepth=4
cmp ./testdata/bin/res.bin ./testdata/bin/new.bin || format_error "Image doesn't match written data"
format_green OK