Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / librbd / LibrbdAdminSocketHook.cc
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3
4 #include "common/errno.h"
5
6 #include "librbd/ImageCtx.h"
7 #include "librbd/LibrbdAdminSocketHook.h"
8 #include "librbd/internal.h"
9
10 #define dout_subsys ceph_subsys_rbd
11 #undef dout_prefix
12 #define dout_prefix *_dout << "librbdadminsocket: "
13
14 namespace librbd {
15
16 class LibrbdAdminSocketCommand {
17 public:
18   virtual ~LibrbdAdminSocketCommand() {}
19   virtual bool call(stringstream *ss) = 0;
20 };
21
22 class FlushCacheCommand : public LibrbdAdminSocketCommand {
23 public:
24   explicit FlushCacheCommand(ImageCtx *ictx) : ictx(ictx) {}
25
26   bool call(stringstream *ss) override {
27     int r = flush(ictx);
28     if (r < 0) {
29       *ss << "flush: " << cpp_strerror(r);
30       return false;
31     }
32     return true;
33   }
34
35 private:
36   ImageCtx *ictx;
37 };
38
39 struct InvalidateCacheCommand : public LibrbdAdminSocketCommand {
40 public:
41   explicit InvalidateCacheCommand(ImageCtx *ictx) : ictx(ictx) {}
42
43   bool call(stringstream *ss) override {
44     int r = invalidate_cache(ictx);
45     if (r < 0) {
46       *ss << "invalidate_cache: " << cpp_strerror(r);
47       return false;
48     }
49     return true;
50   }
51
52 private:
53   ImageCtx *ictx;
54 };
55
56 LibrbdAdminSocketHook::LibrbdAdminSocketHook(ImageCtx *ictx) :
57   admin_socket(ictx->cct->get_admin_socket()) {
58
59   std::string command;
60   std::string imagename;
61   int r;
62
63   imagename = ictx->md_ctx.get_pool_name() + "/" + ictx->name;
64   command = "rbd cache flush " + imagename;
65
66   r = admin_socket->register_command(command, command, this,
67                                      "flush rbd image " + imagename +
68                                      " cache");
69   if (r == 0) {
70     commands[command] = new FlushCacheCommand(ictx);
71   }
72
73   command = "rbd cache invalidate " + imagename;
74   r = admin_socket->register_command(command, command, this,
75                                      "invalidate rbd image " + imagename + 
76                                      " cache");
77   if (r == 0) {
78     commands[command] = new InvalidateCacheCommand(ictx);
79   }
80 }
81
82 LibrbdAdminSocketHook::~LibrbdAdminSocketHook() {
83   for (Commands::const_iterator i = commands.begin(); i != commands.end();
84        ++i) {
85     (void)admin_socket->unregister_command(i->first);
86     delete i->second;
87   }
88 }
89
90 bool LibrbdAdminSocketHook::call(std::string command, cmdmap_t& cmdmap,
91                                  std::string format, bufferlist& out) {
92   Commands::const_iterator i = commands.find(command);
93   assert(i != commands.end());
94   stringstream ss;
95   bool r = i->second->call(&ss);
96   out.append(ss);
97   return r;
98 }
99
100 } // namespace librbd