1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
4 #include "tools/rbd/ArgumentTypes.h"
5 #include "tools/rbd/Shell.h"
6 #include "tools/rbd/Utils.h"
7 #include "include/rbd_types.h"
8 #include "common/errno.h"
10 #include <boost/program_options.hpp>
16 namespace at = argument_types;
17 namespace po = boost::program_options;
19 class RbdWatchCtx : public librados::WatchCtx2 {
21 RbdWatchCtx(librados::IoCtx& io_ctx, const char *image_name,
22 std::string header_oid)
23 : m_io_ctx(io_ctx), m_image_name(image_name), m_header_oid(header_oid)
27 ~RbdWatchCtx() override {}
29 void handle_notify(uint64_t notify_id,
32 bufferlist& bl) override {
33 std::cout << m_image_name << " received notification: notify_id="
34 << notify_id << ", cookie=" << cookie << ", notifier_id="
35 << notifier_id << ", bl.length=" << bl.length() << std::endl;
37 m_io_ctx.notify_ack(m_header_oid, notify_id, cookie, reply);
40 void handle_error(uint64_t cookie, int err) override {
41 std::cerr << m_image_name << " received error: cookie=" << cookie << ", "
42 << "err=" << cpp_strerror(err) << std::endl;
45 librados::IoCtx m_io_ctx;
46 const char *m_image_name;
47 std::string m_header_oid;
50 static int do_watch(librados::IoCtx& pp, librbd::Image &image,
54 int r = image.old_format(&old_format);
56 std::cerr << "failed to query format" << std::endl;
60 std::string header_oid;
61 if (old_format != 0) {
62 header_oid = std::string(imgname) + RBD_SUFFIX;
65 r = image.get_id(&id);
70 header_oid = RBD_HEADER_PREFIX + id;
74 RbdWatchCtx ctx(pp, imgname, header_oid);
75 r = pp.watch2(header_oid, &cookie, &ctx);
77 std::cerr << "rbd: watch failed" << std::endl;
81 std::cout << "press enter to exit..." << std::endl;
84 r = pp.unwatch2(cookie);
86 std::cerr << "rbd: unwatch failed" << std::endl;
92 void get_arguments(po::options_description *positional,
93 po::options_description *options) {
94 at::add_image_spec_options(positional, options, at::ARGUMENT_MODIFIER_NONE);
97 int execute(const po::variables_map &vm) {
99 std::string pool_name;
100 std::string image_name;
101 std::string snap_name;
102 int r = utils::get_pool_image_snapshot_names(
103 vm, at::ARGUMENT_MODIFIER_NONE, &arg_index, &pool_name, &image_name,
104 &snap_name, utils::SNAPSHOT_PRESENCE_NONE, utils::SPEC_VALIDATION_NONE);
109 librados::Rados rados;
110 librados::IoCtx io_ctx;
112 r = utils::init_and_open_image(pool_name, image_name, "", "", true, &rados,
118 r = do_watch(io_ctx, image, image_name.c_str());
120 std::cerr << "rbd: watch failed: " << cpp_strerror(r) << std::endl;
126 Shell::Action action(
127 {"watch"}, {}, "Watch events on image.", "", &get_arguments, &execute);
130 } // namespace action