Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
null
ceph-main/src/messages/MTimeCheck2.h
// -*- 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, Inc. * * 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. * */ #pragma once class MTimeCheck2 final : public Message { public: static constexpr int HEAD_VERSION = 1; static constexpr int COMPAT_VERSION = 1; enum { OP_PING = 1, OP_PONG = 2, OP_REPORT = 3, }; int op = 0; version_t epoch = 0; version_t round = 0; utime_t timestamp; std::map<int, double> skews; std::map<int, double> latencies; MTimeCheck2() : Message{MSG_TIMECHECK2, HEAD_VERSION, COMPAT_VERSION} { } MTimeCheck2(int op) : Message{MSG_TIMECHECK2, HEAD_VERSION, COMPAT_VERSION}, op(op) { } private: ~MTimeCheck2() final { } public: std::string_view get_type_name() const override { return "time_check2"; } const char *get_op_name() const { switch (op) { case OP_PING: return "ping"; case OP_PONG: return "pong"; case OP_REPORT: return "report"; } return "???"; } void print(std::ostream &o) const override { o << "time_check( " << get_op_name() << " e " << epoch << " r " << round; if (op == OP_PONG) { o << " ts " << timestamp; } else if (op == OP_REPORT) { o << " #skews " << skews.size() << " #latencies " << latencies.size(); } o << " )"; } void decode_payload() override { using ceph::decode; auto p = payload.cbegin(); decode(op, p); decode(epoch, p); decode(round, p); decode(timestamp, p); decode(skews, p); decode(latencies, p); } void encode_payload(uint64_t features) override { using ceph::encode; encode(op, payload); encode(epoch, payload); encode(round, payload); encode(timestamp, payload); encode(skews, payload, features); encode(latencies, payload, features); } private: template<class T, typename... Args> friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args); };
2,212
23.318681
75
h
null
ceph-main/src/messages/MWatchNotify.h
// -*- 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. * */ #ifndef CEPH_MWATCHNOTIFY_H #define CEPH_MWATCHNOTIFY_H #include "msg/Message.h" class MWatchNotify final : public Message { private: static constexpr int HEAD_VERSION = 3; static constexpr int COMPAT_VERSION = 1; public: uint64_t cookie; ///< client unique id for this watch or notify uint64_t ver; ///< unused uint64_t notify_id; ///< osd unique id for a notify notification uint8_t opcode; ///< CEPH_WATCH_EVENT_* ceph::buffer::list bl; ///< notify payload (osd->client) errorcode32_t return_code; ///< notify result (osd->client) uint64_t notifier_gid; ///< who sent the notify MWatchNotify() : Message{CEPH_MSG_WATCH_NOTIFY, HEAD_VERSION, COMPAT_VERSION} { } MWatchNotify(uint64_t c, uint64_t v, uint64_t i, uint8_t o, ceph::buffer::list b, uint64_t n=0) : Message{CEPH_MSG_WATCH_NOTIFY, HEAD_VERSION, COMPAT_VERSION}, cookie(c), ver(v), notify_id(i), opcode(o), bl(b), return_code(0), notifier_gid(n) { } private: ~MWatchNotify() final {} public: void decode_payload() override { using ceph::decode; uint8_t msg_ver; auto p = payload.cbegin(); decode(msg_ver, p); decode(opcode, p); decode(cookie, p); decode(ver, p); decode(notify_id, p); if (msg_ver >= 1) decode(bl, p); if (header.version >= 2) decode(return_code, p); else return_code = 0; if (header.version >= 3) decode(notifier_gid, p); else notifier_gid = 0; } void encode_payload(uint64_t features) override { using ceph::encode; uint8_t msg_ver = 1; encode(msg_ver, payload); encode(opcode, payload); encode(cookie, payload); encode(ver, payload); encode(notify_id, payload); encode(bl, payload); encode(return_code, payload); encode(notifier_gid, payload); } std::string_view get_type_name() const override { return "watch-notify"; } void print(std::ostream& out) const override { out << "watch-notify(" << ceph_watch_event_name(opcode) << " (" << (int)opcode << ")" << " cookie " << cookie << " notify " << notify_id << " ret " << return_code << ")"; } private: template<class T, typename... Args> friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args); }; #endif
2,728
26.565657
97
h
null
ceph-main/src/messages/PaxosServiceMessage.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- #ifndef CEPH_PAXOSSERVICEMESSAGE_H #define CEPH_PAXOSSERVICEMESSAGE_H #include "msg/Message.h" #include "mon/Session.h" class PaxosServiceMessage : public Message { public: version_t version; __s16 deprecated_session_mon; uint64_t deprecated_session_mon_tid; // track which epoch the leader received a forwarded request in, so we can // discard forwarded requests appropriately on election boundaries. epoch_t rx_election_epoch; PaxosServiceMessage() : Message{MSG_PAXOS}, version(0), deprecated_session_mon(-1), deprecated_session_mon_tid(0), rx_election_epoch(0) { } PaxosServiceMessage(int type, version_t v, int enc_version=1, int compat_enc_version=0) : Message{type, enc_version, compat_enc_version}, version(v), deprecated_session_mon(-1), deprecated_session_mon_tid(0), rx_election_epoch(0) { } protected: ~PaxosServiceMessage() override {} public: void paxos_encode() { using ceph::encode; encode(version, payload); encode(deprecated_session_mon, payload); encode(deprecated_session_mon_tid, payload); } void paxos_decode(ceph::buffer::list::const_iterator& p ) { using ceph::decode; decode(version, p); decode(deprecated_session_mon, p); decode(deprecated_session_mon_tid, p); } void encode_payload(uint64_t features) override { ceph_abort(); paxos_encode(); } void decode_payload() override { ceph_abort(); auto p = payload.cbegin(); paxos_decode(p); } std::string_view get_type_name() const override { return "PaxosServiceMessage"; } }; #endif
1,661
26.7
89
h
null
ceph-main/src/mgr/ActivePyModule.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 John Spray <[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 "PyFormatter.h" #include "common/debug.h" #include "mon/MonCommand.h" #include "ActivePyModule.h" #include "MgrSession.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr " << __func__ << " " using std::string; using namespace std::literals; int ActivePyModule::load(ActivePyModules *py_modules) { ceph_assert(py_modules); Gil gil(py_module->pMyThreadState, true); // We tell the module how we name it, so that it can be consistent // with us in logging etc. auto pThisPtr = PyCapsule_New(this, nullptr, nullptr); auto pPyModules = PyCapsule_New(py_modules, nullptr, nullptr); auto pModuleName = PyUnicode_FromString(get_name().c_str()); auto pArgs = PyTuple_Pack(3, pModuleName, pPyModules, pThisPtr); pClassInstance = PyObject_CallObject(py_module->pClass, pArgs); Py_DECREF(pModuleName); Py_DECREF(pArgs); if (pClassInstance == nullptr) { derr << "Failed to construct class in '" << get_name() << "'" << dendl; derr << handle_pyerror(true, get_name(), "ActivePyModule::load") << dendl; return -EINVAL; } else { dout(1) << "Constructed class from module: " << get_name() << dendl; } return 0; } void ActivePyModule::notify(const std::string &notify_type, const std::string &notify_id) { if (is_dead()) { dout(5) << "cancelling notify " << notify_type << " " << notify_id << dendl; return; } ceph_assert(pClassInstance != nullptr); Gil gil(py_module->pMyThreadState, true); // Execute auto pValue = PyObject_CallMethod(pClassInstance, const_cast<char*>("notify"), const_cast<char*>("(ss)"), notify_type.c_str(), notify_id.c_str()); if (pValue != NULL) { Py_DECREF(pValue); } else { derr << get_name() << ".notify:" << dendl; derr << handle_pyerror(true, get_name(), "ActivePyModule::notify") << dendl; // FIXME: callers can't be expected to handle a python module // that has spontaneously broken, but Mgr() should provide // a hook to unload misbehaving modules when they have an // error somewhere like this } } void ActivePyModule::notify_clog(const LogEntry &log_entry) { if (is_dead()) { dout(5) << "cancelling notify_clog" << dendl; return; } ceph_assert(pClassInstance != nullptr); Gil gil(py_module->pMyThreadState, true); // Construct python-ized LogEntry PyFormatter f; log_entry.dump(&f); auto py_log_entry = f.get(); // Execute auto pValue = PyObject_CallMethod(pClassInstance, const_cast<char*>("notify"), const_cast<char*>("(sN)"), "clog", py_log_entry); if (pValue != NULL) { Py_DECREF(pValue); } else { derr << get_name() << ".notify_clog:" << dendl; derr << handle_pyerror(true, get_name(), "ActivePyModule::notify_clog") << dendl; // FIXME: callers can't be expected to handle a python module // that has spontaneously broken, but Mgr() should provide // a hook to unload misbehaving modules when they have an // error somewhere like this } } bool ActivePyModule::method_exists(const std::string &method) const { Gil gil(py_module->pMyThreadState, true); auto boundMethod = PyObject_GetAttrString(pClassInstance, method.c_str()); if (boundMethod == nullptr) { return false; } else { Py_DECREF(boundMethod); return true; } } PyObject *ActivePyModule::dispatch_remote( const std::string &method, PyObject *args, PyObject *kwargs, std::string *err) { ceph_assert(err != nullptr); // Rather than serializing arguments, pass the CPython objects. // Works because we happen to know that the subinterpreter // implementation shares a GIL, allocator, deallocator and GC state, so // it's okay to pass the objects between subinterpreters. // But in future this might involve serialization to support a CSP-aware // future Python interpreter a la PEP554 Gil gil(py_module->pMyThreadState, true); // Fire the receiving method auto boundMethod = PyObject_GetAttrString(pClassInstance, method.c_str()); // Caller should have done method_exists check first! ceph_assert(boundMethod != nullptr); dout(20) << "Calling " << py_module->get_name() << "." << method << "..." << dendl; auto remoteResult = PyObject_Call(boundMethod, args, kwargs); Py_DECREF(boundMethod); if (remoteResult == nullptr) { // Because the caller is in a different context, we can't let this // exception bubble up, need to re-raise it from the caller's // context later. std::string caller = "ActivePyModule::dispatch_remote "s + method; *err = handle_pyerror(true, get_name(), caller); } else { dout(20) << "Success calling '" << method << "'" << dendl; } return remoteResult; } void ActivePyModule::config_notify() { if (is_dead()) { dout(5) << "cancelling config_notify" << dendl; return; } Gil gil(py_module->pMyThreadState, true); dout(20) << "Calling " << py_module->get_name() << "._config_notify..." << dendl; auto remoteResult = PyObject_CallMethod(pClassInstance, const_cast<char*>("_config_notify"), (char*)NULL); if (remoteResult != nullptr) { Py_DECREF(remoteResult); } } int ActivePyModule::handle_command( const ModuleCommand& module_command, const MgrSession& session, const cmdmap_t &cmdmap, const bufferlist &inbuf, std::stringstream *ds, std::stringstream *ss) { ceph_assert(ss != nullptr); ceph_assert(ds != nullptr); if (pClassInstance == nullptr) { // Not the friendliest error string, but we could only // hit this in quite niche cases, if at all. *ss << "Module not instantiated"; return -EINVAL; } Gil gil(py_module->pMyThreadState, true); PyFormatter f; TOPNSPC::common::cmdmap_dump(cmdmap, &f); PyObject *py_cmd = f.get(); string instr; inbuf.begin().copy(inbuf.length(), instr); ceph_assert(m_session == nullptr); m_command_perms = module_command.perm; m_session = &session; auto pResult = PyObject_CallMethod(pClassInstance, const_cast<char*>("_handle_command"), const_cast<char*>("s#O"), instr.c_str(), instr.length(), py_cmd); m_command_perms.clear(); m_session = nullptr; Py_DECREF(py_cmd); int r = 0; if (pResult != NULL) { if (PyTuple_Size(pResult) != 3) { derr << "module '" << py_module->get_name() << "' command handler " "returned wrong type!" << dendl; r = -EINVAL; } else { r = PyLong_AsLong(PyTuple_GetItem(pResult, 0)); *ds << PyUnicode_AsUTF8(PyTuple_GetItem(pResult, 1)); *ss << PyUnicode_AsUTF8(PyTuple_GetItem(pResult, 2)); } Py_DECREF(pResult); } else { derr << "module '" << py_module->get_name() << "' command handler " "threw exception: " << peek_pyerror() << dendl; *ds << ""; *ss << handle_pyerror(); r = -EINVAL; } return r; } void ActivePyModule::get_health_checks(health_check_map_t *checks) { if (is_dead()) { dout(5) << "cancelling get_health_checks" << dendl; return; } checks->merge(health_checks); } bool ActivePyModule::is_authorized( const std::map<std::string, std::string>& arguments) const { if (m_session == nullptr) { return false; } // No need to pass command prefix here since that would have already been // tested before command invokation. Instead, only test for service/module // arguments as defined by the module itself. MonCommand mon_command {"", "", "", m_command_perms}; return m_session->caps.is_capable(nullptr, m_session->entity_name, "py", py_module->get_name(), "", arguments, mon_command.requires_perm('r'), mon_command.requires_perm('w'), mon_command.requires_perm('x'), m_session->get_peer_addr()); }
8,359
28.857143
89
cc
null
ceph-main/src/mgr/ActivePyModule.h
// -*- 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 John Spray <[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. */ #pragma once // Python.h comes first because otherwise it clobbers ceph's assert #include "Python.h" #include "common/cmdparse.h" #include "common/LogEntry.h" #include "common/Thread.h" #include "common/Finisher.h" #include "mon/health_check.h" #include "mgr/Gil.h" #include "PyModuleRunner.h" #include "PyModule.h" #include <vector> #include <string> class ActivePyModule; class ActivePyModules; class MgrSession; class ModuleCommand; class ActivePyModule : public PyModuleRunner { private: health_check_map_t health_checks; // Optional, URI exposed by plugins that implement serve() std::string uri; std::string m_command_perms; const MgrSession* m_session = nullptr; std::string fin_thread_name; public: Finisher finisher; // per active module finisher to execute commands public: ActivePyModule(const PyModuleRef &py_module_, LogChannelRef clog_) : PyModuleRunner(py_module_, clog_), fin_thread_name(std::string("m-fin-" + py_module->get_name()).substr(0,15)), finisher(g_ceph_context, thread_name, fin_thread_name) { } int load(ActivePyModules *py_modules); void notify(const std::string &notify_type, const std::string &notify_id); void notify_clog(const LogEntry &le); bool method_exists(const std::string &method) const; PyObject *dispatch_remote( const std::string &method, PyObject *args, PyObject *kwargs, std::string *err); int handle_command( const ModuleCommand& module_command, const MgrSession& session, const cmdmap_t &cmdmap, const bufferlist &inbuf, std::stringstream *ds, std::stringstream *ss); bool set_health_checks(health_check_map_t&& c) { // when health checks change a report is immediately sent to the monitors. // currently modules have static health check details, but this equality // test could be made smarter if too much noise shows up in the future. bool changed = health_checks != c; health_checks = std::move(c); return changed; } void get_health_checks(health_check_map_t *checks); void config_notify(); void set_uri(const std::string &str) { uri = str; } std::string get_uri() const { return uri; } std::string get_fin_thread_name() const { return fin_thread_name; } bool is_authorized(const std::map<std::string, std::string>& arguments) const; };
2,802
23.373913
82
h
null
ceph-main/src/mgr/ActivePyModules.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 John Spray <[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 this first to get python headers earlier #include "Gil.h" #include "ActivePyModules.h" #include <rocksdb/version.h> #include "common/errno.h" #include "include/stringify.h" #include "mon/MonMap.h" #include "osd/OSDMap.h" #include "osd/osd_types.h" #include "mgr/MgrContext.h" #include "mgr/TTLCache.h" #include "mgr/mgr_perf_counters.h" #include "DaemonKey.h" #include "DaemonServer.h" #include "mgr/MgrContext.h" #include "PyFormatter.h" // For ::mgr_store_prefix #include "PyModule.h" #include "PyModuleRegistry.h" #include "PyUtil.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr " << __func__ << " " using std::pair; using std::string; using namespace std::literals; ActivePyModules::ActivePyModules( PyModuleConfig &module_config_, std::map<std::string, std::string> store_data, bool mon_provides_kv_sub, DaemonStateIndex &ds, ClusterState &cs, MonClient &mc, LogChannelRef clog_, LogChannelRef audit_clog_, Objecter &objecter_, Client &client_, Finisher &f, DaemonServer &server, PyModuleRegistry &pmr) : module_config(module_config_), daemon_state(ds), cluster_state(cs), monc(mc), clog(clog_), audit_clog(audit_clog_), objecter(objecter_), client(client_), finisher(f), cmd_finisher(g_ceph_context, "cmd_finisher", "cmdfin"), server(server), py_module_registry(pmr) { store_cache = std::move(store_data); // we can only trust our ConfigMap if the mon cluster has provided // kv sub since our startup. have_local_config_map = mon_provides_kv_sub; _refresh_config_map(); cmd_finisher.start(); } ActivePyModules::~ActivePyModules() = default; void ActivePyModules::dump_server(const std::string &hostname, const DaemonStateCollection &dmc, Formatter *f) { f->dump_string("hostname", hostname); f->open_array_section("services"); std::string ceph_version; for (const auto &[key, state] : dmc) { std::string id; without_gil([&ceph_version, &id, state=state] { std::lock_guard l(state->lock); // TODO: pick the highest version, and make sure that // somewhere else (during health reporting?) we are // indicating to the user if we see mixed versions auto ver_iter = state->metadata.find("ceph_version"); if (ver_iter != state->metadata.end()) { ceph_version = state->metadata.at("ceph_version"); } if (state->metadata.find("id") != state->metadata.end()) { id = state->metadata.at("id"); } }); f->open_object_section("service"); f->dump_string("type", key.type); f->dump_string("id", key.name); f->dump_string("ceph_version", ceph_version); if (!id.empty()) { f->dump_string("name", id); } f->close_section(); } f->close_section(); f->dump_string("ceph_version", ceph_version); } PyObject *ActivePyModules::get_server_python(const std::string &hostname) { const auto dmc = without_gil([&]{ std::lock_guard l(lock); dout(10) << " (" << hostname << ")" << dendl; return daemon_state.get_by_server(hostname); }); PyFormatter f; dump_server(hostname, dmc, &f); return f.get(); } PyObject *ActivePyModules::list_servers_python() { dout(10) << " >" << dendl; without_gil_t no_gil; return daemon_state.with_daemons_by_server([this, &no_gil] (const std::map<std::string, DaemonStateCollection> &all) { no_gil.acquire_gil(); PyFormatter f(false, true); for (const auto &[hostname, daemon_state] : all) { f.open_object_section("server"); dump_server(hostname, daemon_state, &f); f.close_section(); } return f.get(); }); } PyObject *ActivePyModules::get_metadata_python( const std::string &svc_type, const std::string &svc_id) { auto metadata = daemon_state.get(DaemonKey{svc_type, svc_id}); if (metadata == nullptr) { derr << "Requested missing service " << svc_type << "." << svc_id << dendl; Py_RETURN_NONE; } auto l = without_gil([&] { return std::lock_guard(lock); }); PyFormatter f; f.dump_string("hostname", metadata->hostname); for (const auto &[key, val] : metadata->metadata) { f.dump_string(key, val); } return f.get(); } PyObject *ActivePyModules::get_daemon_status_python( const std::string &svc_type, const std::string &svc_id) { auto metadata = daemon_state.get(DaemonKey{svc_type, svc_id}); if (metadata == nullptr) { derr << "Requested missing service " << svc_type << "." << svc_id << dendl; Py_RETURN_NONE; } auto l = without_gil([&] { return std::lock_guard(lock); }); PyFormatter f; for (const auto &[daemon, status] : metadata->service_status) { f.dump_string(daemon, status); } return f.get(); } void ActivePyModules::update_cache_metrics() { auto hit_miss_ratio = ttl_cache.get_hit_miss_ratio(); perfcounter->set(l_mgr_cache_hit, hit_miss_ratio.first); perfcounter->set(l_mgr_cache_miss, hit_miss_ratio.second); } PyObject *ActivePyModules::cacheable_get_python(const std::string &what) { uint64_t ttl_seconds = g_conf().get_val<uint64_t>("mgr_ttl_cache_expire_seconds"); if(ttl_seconds > 0) { ttl_cache.set_ttl(ttl_seconds); try{ PyObject* cached = ttl_cache.get(what); update_cache_metrics(); return cached; } catch (std::out_of_range& e) {} } PyObject *obj = get_python(what); if(ttl_seconds && ttl_cache.is_cacheable(what)) { ttl_cache.insert(what, obj); Py_INCREF(obj); } update_cache_metrics(); return obj; } PyObject *ActivePyModules::get_python(const std::string &what) { uint64_t ttl_seconds = g_conf().get_val<uint64_t>("mgr_ttl_cache_expire_seconds"); PyFormatter pf; PyJSONFormatter jf; // Use PyJSONFormatter if TTL cache is enabled. Formatter &f = ttl_seconds ? (Formatter&)jf : (Formatter&)pf; if (what == "fs_map") { without_gil_t no_gil; cluster_state.with_fsmap([&](const FSMap &fsmap) { no_gil.acquire_gil(); fsmap.dump(&f); }); } else if (what == "osdmap_crush_map_text") { without_gil_t no_gil; bufferlist rdata; cluster_state.with_osdmap([&](const OSDMap &osd_map){ osd_map.crush->encode(rdata, CEPH_FEATURES_SUPPORTED_DEFAULT); }); std::string crush_text = rdata.to_str(); no_gil.acquire_gil(); return PyUnicode_FromString(crush_text.c_str()); } else if (what.substr(0, 7) == "osd_map") { without_gil_t no_gil; cluster_state.with_osdmap([&](const OSDMap &osd_map){ no_gil.acquire_gil(); if (what == "osd_map") { osd_map.dump(&f, g_ceph_context); } else if (what == "osd_map_tree") { osd_map.print_tree(&f, nullptr); } else if (what == "osd_map_crush") { osd_map.crush->dump(&f); } }); } else if (what == "modified_config_options") { without_gil_t no_gil; auto all_daemons = daemon_state.get_all(); set<string> names; for (auto& [key, daemon] : all_daemons) { std::lock_guard l(daemon->lock); for (auto& [name, valmap] : daemon->config) { names.insert(name); } } no_gil.acquire_gil(); f.open_array_section("options"); for (auto& name : names) { f.dump_string("name", name); } f.close_section(); } else if (what.substr(0, 6) == "config") { // We make a copy of the global config to avoid printing // to py formater (which may drop-take GIL) while holding // the global config lock, which might deadlock with other // thread that is holding the GIL and acquiring the global // config lock. ConfigProxy config{g_conf()}; if (what == "config_options") { config.config_options(&f); } else if (what == "config") { config.show_config(&f); } } else if (what == "mon_map") { without_gil_t no_gil; cluster_state.with_monmap([&](const MonMap &monmap) { no_gil.acquire_gil(); monmap.dump(&f); }); } else if (what == "service_map") { without_gil_t no_gil; cluster_state.with_servicemap([&](const ServiceMap &service_map) { no_gil.acquire_gil(); service_map.dump(&f); }); } else if (what == "osd_metadata") { without_gil_t no_gil; auto dmc = daemon_state.get_by_service("osd"); for (const auto &[key, state] : dmc) { std::lock_guard l(state->lock); with_gil(no_gil, [&f, &name=key.name, state=state] { f.open_object_section(name.c_str()); f.dump_string("hostname", state->hostname); for (const auto &[name, val] : state->metadata) { f.dump_string(name.c_str(), val); } f.close_section(); }); } } else if (what == "mds_metadata") { without_gil_t no_gil; auto dmc = daemon_state.get_by_service("mds"); for (const auto &[key, state] : dmc) { std::lock_guard l(state->lock); with_gil(no_gil, [&f, &name=key.name, state=state] { f.open_object_section(name.c_str()); f.dump_string("hostname", state->hostname); for (const auto &[name, val] : state->metadata) { f.dump_string(name.c_str(), val); } f.close_section(); }); } } else if (what == "pg_summary") { without_gil_t no_gil; cluster_state.with_pgmap( [&f, &no_gil](const PGMap &pg_map) { std::map<std::string, std::map<std::string, uint32_t> > osds; std::map<std::string, std::map<std::string, uint32_t> > pools; std::map<std::string, uint32_t> all; for (const auto &i : pg_map.pg_stat) { const auto pool = i.first.m_pool; const std::string state = pg_state_string(i.second.state); // Insert to per-pool map pools[stringify(pool)][state]++; for (const auto &osd_id : i.second.acting) { osds[stringify(osd_id)][state]++; } all[state]++; } no_gil.acquire_gil(); f.open_object_section("by_osd"); for (const auto &i : osds) { f.open_object_section(i.first.c_str()); for (const auto &j : i.second) { f.dump_int(j.first.c_str(), j.second); } f.close_section(); } f.close_section(); f.open_object_section("by_pool"); for (const auto &i : pools) { f.open_object_section(i.first.c_str()); for (const auto &j : i.second) { f.dump_int(j.first.c_str(), j.second); } f.close_section(); } f.close_section(); f.open_object_section("all"); for (const auto &i : all) { f.dump_int(i.first.c_str(), i.second); } f.close_section(); f.open_object_section("pg_stats_sum"); pg_map.pg_sum.dump(&f); f.close_section(); } ); } else if (what == "pg_status") { without_gil_t no_gil; cluster_state.with_pgmap( [&](const PGMap &pg_map) { no_gil.acquire_gil(); pg_map.print_summary(&f, nullptr); } ); } else if (what == "pg_dump") { without_gil_t no_gil; cluster_state.with_pgmap( [&](const PGMap &pg_map) { no_gil.acquire_gil(); pg_map.dump(&f, false); } ); } else if (what == "devices") { without_gil_t no_gil; daemon_state.with_devices2( [&] { with_gil(no_gil, [&] { f.open_array_section("devices"); }); }, [&](const DeviceState &dev) { with_gil(no_gil, [&] { f.dump_object("device", dev); }); }); with_gil(no_gil, [&] { f.close_section(); }); } else if (what.size() > 7 && what.substr(0, 7) == "device ") { without_gil_t no_gil; string devid = what.substr(7); if (!daemon_state.with_device(devid, [&] (const DeviceState& dev) { with_gil_t with_gil{no_gil}; f.dump_object("device", dev); })) { // device not found } } else if (what == "io_rate") { without_gil_t no_gil; cluster_state.with_pgmap( [&](const PGMap &pg_map) { no_gil.acquire_gil(); pg_map.dump_delta(&f); } ); } else if (what == "df") { without_gil_t no_gil; cluster_state.with_osdmap_and_pgmap( [&]( const OSDMap& osd_map, const PGMap &pg_map) { no_gil.acquire_gil(); pg_map.dump_cluster_stats(nullptr, &f, true); pg_map.dump_pool_stats_full(osd_map, nullptr, &f, true); }); } else if (what == "pg_stats") { without_gil_t no_gil; cluster_state.with_pgmap([&](const PGMap &pg_map) { no_gil.acquire_gil(); pg_map.dump_pg_stats(&f, false); }); } else if (what == "pool_stats") { without_gil_t no_gil; cluster_state.with_pgmap([&](const PGMap &pg_map) { no_gil.acquire_gil(); pg_map.dump_pool_stats(&f); }); } else if (what == "pg_ready") { server.dump_pg_ready(&f); } else if (what == "pg_progress") { without_gil_t no_gil; cluster_state.with_pgmap([&](const PGMap &pg_map) { no_gil.acquire_gil(); pg_map.dump_pg_progress(&f); server.dump_pg_ready(&f); }); } else if (what == "osd_stats") { without_gil_t no_gil; cluster_state.with_pgmap([&](const PGMap &pg_map) { no_gil.acquire_gil(); pg_map.dump_osd_stats(&f, false); }); } else if (what == "osd_ping_times") { without_gil_t no_gil; cluster_state.with_pgmap([&](const PGMap &pg_map) { no_gil.acquire_gil(); pg_map.dump_osd_ping_times(&f); }); } else if (what == "osd_pool_stats") { without_gil_t no_gil; int64_t poolid = -ENOENT; cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pg_map) { no_gil.acquire_gil(); f.open_array_section("pool_stats"); for (auto &p : osdmap.get_pools()) { poolid = p.first; pg_map.dump_pool_stats_and_io_rate(poolid, osdmap, &f, nullptr); } f.close_section(); }); } else if (what == "health") { without_gil_t no_gil; cluster_state.with_health([&](const ceph::bufferlist &health_json) { no_gil.acquire_gil(); f.dump_string("json", health_json.to_str()); }); } else if (what == "mon_status") { without_gil_t no_gil; cluster_state.with_mon_status( [&](const ceph::bufferlist &mon_status_json) { no_gil.acquire_gil(); f.dump_string("json", mon_status_json.to_str()); }); } else if (what == "mgr_map") { without_gil_t no_gil; cluster_state.with_mgrmap([&](const MgrMap &mgr_map) { no_gil.acquire_gil(); mgr_map.dump(&f); }); } else if (what == "mgr_ips") { entity_addrvec_t myaddrs = server.get_myaddrs(); f.open_array_section("ips"); std::set<std::string> did; for (auto& i : myaddrs.v) { std::string ip = i.ip_only_to_str(); if (auto [where, inserted] = did.insert(ip); inserted) { f.dump_string("ip", ip); } } f.close_section(); } else if (what == "have_local_config_map") { f.dump_bool("have_local_config_map", have_local_config_map); } else if (what == "active_clean_pgs"){ without_gil_t no_gil; cluster_state.with_pgmap( [&](const PGMap &pg_map) { no_gil.acquire_gil(); f.open_array_section("pg_stats"); for (auto &i : pg_map.pg_stat) { const auto state = i.second.state; const auto pgid_raw = i.first; const auto pgid = stringify(pgid_raw.m_pool) + "." + stringify(pgid_raw.m_seed); const auto reported_epoch = i.second.reported_epoch; if (state & PG_STATE_ACTIVE && state & PG_STATE_CLEAN) { f.open_object_section("pg_stat"); f.dump_string("pgid", pgid); f.dump_string("state", pg_state_string(state)); f.dump_unsigned("reported_epoch", reported_epoch); f.close_section(); } } f.close_section(); const auto num_pg = pg_map.num_pg; f.dump_unsigned("total_num_pgs", num_pg); }); } else { derr << "Python module requested unknown data '" << what << "'" << dendl; Py_RETURN_NONE; } if(ttl_seconds) { return jf.get(); } else { return pf.get(); } } void ActivePyModules::start_one(PyModuleRef py_module) { std::lock_guard l(lock); const auto name = py_module->get_name(); auto active_module = std::make_shared<ActivePyModule>(py_module, clog); pending_modules.insert(name); // Send all python calls down a Finisher to avoid blocking // C++ code, and avoid any potential lock cycles. finisher.queue(new LambdaContext([this, active_module, name](int) { int r = active_module->load(this); std::lock_guard l(lock); pending_modules.erase(name); if (r != 0) { derr << "Failed to run module in active mode ('" << name << "')" << dendl; } else { auto em = modules.emplace(name, active_module); ceph_assert(em.second); // actually inserted dout(4) << "Starting thread for " << name << dendl; active_module->thread.create(active_module->get_thread_name()); dout(4) << "Starting active module " << name <<" finisher thread " << active_module->get_fin_thread_name() << dendl; active_module->finisher.start(); } })); } void ActivePyModules::shutdown() { std::lock_guard locker(lock); // Stop per active module finisher thread for (auto& [name, module] : modules) { dout(4) << "Stopping active module " << name << " finisher thread" << dendl; module->finisher.wait_for_empty(); module->finisher.stop(); } // Signal modules to drop out of serve() and/or tear down resources for (auto& [name, module] : modules) { lock.unlock(); dout(10) << "calling module " << name << " shutdown()" << dendl; module->shutdown(); dout(10) << "module " << name << " shutdown() returned" << dendl; lock.lock(); } // For modules implementing serve(), finish the threads where we // were running that. for (auto& [name, module] : modules) { lock.unlock(); dout(10) << "joining module " << name << dendl; module->thread.join(); dout(10) << "joined module " << name << dendl; lock.lock(); } cmd_finisher.wait_for_empty(); cmd_finisher.stop(); modules.clear(); } void ActivePyModules::notify_all(const std::string &notify_type, const std::string &notify_id) { std::lock_guard l(lock); dout(10) << __func__ << ": notify_all " << notify_type << dendl; for (auto& [name, module] : modules) { if (!py_module_registry.should_notify(name, notify_type)) { continue; } // Send all python calls down a Finisher to avoid blocking // C++ code, and avoid any potential lock cycles. dout(15) << "queuing notify (" << notify_type << ") to " << name << dendl; Finisher& mod_finisher = py_module_registry.get_active_module_finisher(name); // workaround for https://bugs.llvm.org/show_bug.cgi?id=35984 mod_finisher.queue(new LambdaContext([module=module, notify_type, notify_id] (int r){ module->notify(notify_type, notify_id); })); } } void ActivePyModules::notify_all(const LogEntry &log_entry) { std::lock_guard l(lock); dout(10) << __func__ << ": notify_all (clog)" << dendl; for (auto& [name, module] : modules) { if (!py_module_registry.should_notify(name, "clog")) { continue; } // Send all python calls down a Finisher to avoid blocking // C++ code, and avoid any potential lock cycles. // // Note intentional use of non-reference lambda binding on // log_entry: we take a copy because caller's instance is // probably ephemeral. dout(15) << "queuing notify (clog) to " << name << dendl; Finisher& mod_finisher = py_module_registry.get_active_module_finisher(name); // workaround for https://bugs.llvm.org/show_bug.cgi?id=35984 mod_finisher.queue(new LambdaContext([module=module, log_entry](int r){ module->notify_clog(log_entry); })); } } bool ActivePyModules::get_store(const std::string &module_name, const std::string &key, std::string *val) const { without_gil_t no_gil; std::lock_guard l(lock); const std::string global_key = PyModule::mgr_store_prefix + module_name + "/" + key; dout(4) << __func__ << " key: " << global_key << dendl; auto i = store_cache.find(global_key); if (i != store_cache.end()) { *val = i->second; return true; } else { return false; } } PyObject *ActivePyModules::dispatch_remote( const std::string &other_module, const std::string &method, PyObject *args, PyObject *kwargs, std::string *err) { auto mod_iter = modules.find(other_module); ceph_assert(mod_iter != modules.end()); return mod_iter->second->dispatch_remote(method, args, kwargs, err); } bool ActivePyModules::get_config(const std::string &module_name, const std::string &key, std::string *val) const { const std::string global_key = "mgr/" + module_name + "/" + key; dout(20) << " key: " << global_key << dendl; std::lock_guard lock(module_config.lock); auto i = module_config.config.find(global_key); if (i != module_config.config.end()) { *val = i->second; return true; } else { return false; } } PyObject *ActivePyModules::get_typed_config( const std::string &module_name, const std::string &key, const std::string &prefix) const { without_gil_t no_gil; std::string value; std::string final_key; bool found = false; if (prefix.size()) { final_key = prefix + "/" + key; found = get_config(module_name, final_key, &value); } if (!found) { final_key = key; found = get_config(module_name, final_key, &value); } if (found) { PyModuleRef module = py_module_registry.get_module(module_name); no_gil.acquire_gil(); if (!module) { derr << "Module '" << module_name << "' is not available" << dendl; Py_RETURN_NONE; } // removing value to hide sensitive data going into mgr logs // leaving this for debugging purposes // dout(10) << __func__ << " " << final_key << " found: " << value << dendl; dout(10) << __func__ << " " << final_key << " found" << dendl; return module->get_typed_option_value(key, value); } if (prefix.size()) { dout(10) << " [" << prefix << "/]" << key << " not found " << dendl; } else { dout(10) << " " << key << " not found " << dendl; } Py_RETURN_NONE; } PyObject *ActivePyModules::get_store_prefix(const std::string &module_name, const std::string &prefix) const { without_gil_t no_gil; std::lock_guard l(lock); std::lock_guard lock(module_config.lock); no_gil.acquire_gil(); const std::string base_prefix = PyModule::mgr_store_prefix + module_name + "/"; const std::string global_prefix = base_prefix + prefix; dout(4) << __func__ << " prefix: " << global_prefix << dendl; PyFormatter f; for (auto p = store_cache.lower_bound(global_prefix); p != store_cache.end() && p->first.find(global_prefix) == 0; ++p) { f.dump_string(p->first.c_str() + base_prefix.size(), p->second); } return f.get(); } void ActivePyModules::set_store(const std::string &module_name, const std::string &key, const std::optional<std::string>& val) { const std::string global_key = PyModule::mgr_store_prefix + module_name + "/" + key; Command set_cmd; { std::lock_guard l(lock); // NOTE: this isn't strictly necessary since we'll also get an MKVData // update from the mon due to our subscription *before* our command is acked. if (val) { store_cache[global_key] = *val; } else { store_cache.erase(global_key); } std::ostringstream cmd_json; JSONFormatter jf; jf.open_object_section("cmd"); if (val) { jf.dump_string("prefix", "config-key set"); jf.dump_string("key", global_key); jf.dump_string("val", *val); } else { jf.dump_string("prefix", "config-key del"); jf.dump_string("key", global_key); } jf.close_section(); jf.flush(cmd_json); set_cmd.run(&monc, cmd_json.str()); } set_cmd.wait(); if (set_cmd.r != 0) { // config-key set will fail if mgr's auth key has insufficient // permission to set config keys // FIXME: should this somehow raise an exception back into Python land? dout(0) << "`config-key set " << global_key << " " << val << "` failed: " << cpp_strerror(set_cmd.r) << dendl; dout(0) << "mon returned " << set_cmd.r << ": " << set_cmd.outs << dendl; } } std::pair<int, std::string> ActivePyModules::set_config( const std::string &module_name, const std::string &key, const std::optional<std::string>& val) { return module_config.set_config(&monc, module_name, key, val); } std::map<std::string, std::string> ActivePyModules::get_services() const { std::map<std::string, std::string> result; std::lock_guard l(lock); for (const auto& [name, module] : modules) { std::string svc_str = module->get_uri(); if (!svc_str.empty()) { result[name] = svc_str; } } return result; } void ActivePyModules::update_kv_data( const std::string prefix, bool incremental, const map<std::string, std::optional<bufferlist>, std::less<>>& data) { std::lock_guard l(lock); bool do_config = false; if (!incremental) { dout(10) << "full update on " << prefix << dendl; auto p = store_cache.lower_bound(prefix); while (p != store_cache.end() && p->first.find(prefix) == 0) { dout(20) << " rm prior " << p->first << dendl; p = store_cache.erase(p); } } else { dout(10) << "incremental update on " << prefix << dendl; } for (auto& i : data) { if (i.second) { dout(20) << " set " << i.first << " = " << i.second->to_str() << dendl; store_cache[i.first] = i.second->to_str(); } else { dout(20) << " rm " << i.first << dendl; store_cache.erase(i.first); } if (i.first.find("config/") == 0) { do_config = true; } } if (do_config) { _refresh_config_map(); } } void ActivePyModules::_refresh_config_map() { dout(10) << dendl; config_map.clear(); for (auto p = store_cache.lower_bound("config/"); p != store_cache.end() && p->first.find("config/") == 0; ++p) { string key = p->first.substr(7); if (key.find("mgr/") == 0) { // NOTE: for now, we ignore module options. see also ceph_foreign_option_get(). continue; } string value = p->second; string name; string who; config_map.parse_key(key, &name, &who); const Option *opt = g_conf().find_option(name); if (!opt) { config_map.stray_options.push_back( std::unique_ptr<Option>( new Option(name, Option::TYPE_STR, Option::LEVEL_UNKNOWN))); opt = config_map.stray_options.back().get(); } string err; int r = opt->pre_validate(&value, &err); if (r < 0) { dout(10) << __func__ << " pre-validate failed on '" << name << "' = '" << value << "' for " << name << dendl; } MaskedOption mopt(opt); mopt.raw_value = value; string section_name; if (who.size() && !ConfigMap::parse_mask(who, &section_name, &mopt.mask)) { derr << __func__ << " invalid mask for key " << key << dendl; } else if (opt->has_flag(Option::FLAG_NO_MON_UPDATE)) { dout(10) << __func__ << " NO_MON_UPDATE option '" << name << "' = '" << value << "' for " << name << dendl; } else { Section *section = &config_map.global;; if (section_name.size() && section_name != "global") { if (section_name.find('.') != std::string::npos) { section = &config_map.by_id[section_name]; } else { section = &config_map.by_type[section_name]; } } section->options.insert(make_pair(name, std::move(mopt))); } } } PyObject* ActivePyModules::with_perf_counters( std::function<void(PerfCounterInstance& counter_instance, PerfCounterType& counter_type, PyFormatter& f)> fct, const std::string &svc_name, const std::string &svc_id, const std::string &path) const { PyFormatter f; f.open_array_section(path); { without_gil_t no_gil; std::lock_guard l(lock); auto metadata = daemon_state.get(DaemonKey{svc_name, svc_id}); if (metadata) { std::lock_guard l2(metadata->lock); if (metadata->perf_counters.instances.count(path)) { auto counter_instance = metadata->perf_counters.instances.at(path); auto counter_type = metadata->perf_counters.types.at(path); with_gil(no_gil, [&] { fct(counter_instance, counter_type, f); }); } else { dout(4) << "Missing counter: '" << path << "' (" << svc_name << "." << svc_id << ")" << dendl; dout(20) << "Paths are:" << dendl; for (const auto &i : metadata->perf_counters.instances) { dout(20) << i.first << dendl; } } } else { dout(4) << "No daemon state for " << svc_name << "." << svc_id << ")" << dendl; } } f.close_section(); return f.get(); } PyObject* ActivePyModules::get_counter_python( const std::string &svc_name, const std::string &svc_id, const std::string &path) { auto extract_counters = []( PerfCounterInstance& counter_instance, PerfCounterType& counter_type, PyFormatter& f) { if (counter_type.type & PERFCOUNTER_LONGRUNAVG) { const auto &avg_data = counter_instance.get_data_avg(); for (const auto &datapoint : avg_data) { f.open_array_section("datapoint"); f.dump_float("t", datapoint.t); f.dump_unsigned("s", datapoint.s); f.dump_unsigned("c", datapoint.c); f.close_section(); } } else { const auto &data = counter_instance.get_data(); for (const auto &datapoint : data) { f.open_array_section("datapoint"); f.dump_float("t", datapoint.t); f.dump_unsigned("v", datapoint.v); f.close_section(); } } }; return with_perf_counters(extract_counters, svc_name, svc_id, path); } PyObject* ActivePyModules::get_latest_counter_python( const std::string &svc_name, const std::string &svc_id, const std::string &path) { auto extract_latest_counters = []( PerfCounterInstance& counter_instance, PerfCounterType& counter_type, PyFormatter& f) { if (counter_type.type & PERFCOUNTER_LONGRUNAVG) { const auto &datapoint = counter_instance.get_latest_data_avg(); f.dump_float("t", datapoint.t); f.dump_unsigned("s", datapoint.s); f.dump_unsigned("c", datapoint.c); } else { const auto &datapoint = counter_instance.get_latest_data(); f.dump_float("t", datapoint.t); f.dump_unsigned("v", datapoint.v); } }; return with_perf_counters(extract_latest_counters, svc_name, svc_id, path); } PyObject* ActivePyModules::get_perf_schema_python( const std::string &svc_type, const std::string &svc_id) { without_gil_t no_gil; std::lock_guard l(lock); DaemonStateCollection daemons; if (svc_type == "") { daemons = daemon_state.get_all(); } else if (svc_id.empty()) { daemons = daemon_state.get_by_service(svc_type); } else { auto key = DaemonKey{svc_type, svc_id}; // so that the below can be a loop in all cases auto got = daemon_state.get(key); if (got != nullptr) { daemons[key] = got; } } auto f = with_gil(no_gil, [&] { return PyFormatter(); }); if (!daemons.empty()) { for (auto& [key, state] : daemons) { std::lock_guard l(state->lock); with_gil(no_gil, [&, key=ceph::to_string(key), state=state] { f.open_object_section(key.c_str()); for (auto ctr_inst_iter : state->perf_counters.instances) { const auto &counter_name = ctr_inst_iter.first; f.open_object_section(counter_name.c_str()); auto type = state->perf_counters.types[counter_name]; f.dump_string("description", type.description); if (!type.nick.empty()) { f.dump_string("nick", type.nick); } f.dump_unsigned("type", type.type); f.dump_unsigned("priority", type.priority); f.dump_unsigned("units", type.unit); f.close_section(); } f.close_section(); }); } } else { dout(4) << __func__ << ": No daemon state found for " << svc_type << "." << svc_id << ")" << dendl; } return f.get(); } PyObject* ActivePyModules::get_rocksdb_version() { std::string version = std::to_string(ROCKSDB_MAJOR) + "." + std::to_string(ROCKSDB_MINOR) + "." + std::to_string(ROCKSDB_PATCH); return PyUnicode_FromString(version.c_str()); } PyObject *ActivePyModules::get_context() { auto l = without_gil([&] { return std::lock_guard(lock); }); // Construct a capsule containing ceph context. // Not incrementing/decrementing ref count on the context because // it's the global one and it has process lifetime. auto capsule = PyCapsule_New(g_ceph_context, nullptr, nullptr); return capsule; } /** * Helper for our wrapped types that take a capsule in their constructor. */ PyObject *construct_with_capsule( const std::string &module_name, const std::string &clsname, void *wrapped) { // Look up the OSDMap type which we will construct PyObject *module = PyImport_ImportModule(module_name.c_str()); if (!module) { derr << "Failed to import python module:" << dendl; derr << handle_pyerror(true, module_name, "construct_with_capsule "s + module_name + " " + clsname) << dendl; } ceph_assert(module); PyObject *wrapper_type = PyObject_GetAttrString( module, (const char*)clsname.c_str()); if (!wrapper_type) { derr << "Failed to get python type:" << dendl; derr << handle_pyerror(true, module_name, "construct_with_capsule "s + module_name + " " + clsname) << dendl; } ceph_assert(wrapper_type); // Construct a capsule containing an OSDMap. auto wrapped_capsule = PyCapsule_New(wrapped, nullptr, nullptr); ceph_assert(wrapped_capsule); // Construct the python OSDMap auto pArgs = PyTuple_Pack(1, wrapped_capsule); auto wrapper_instance = PyObject_CallObject(wrapper_type, pArgs); if (wrapper_instance == nullptr) { derr << "Failed to construct python OSDMap:" << dendl; derr << handle_pyerror(true, module_name, "construct_with_capsule "s + module_name + " " + clsname) << dendl; } ceph_assert(wrapper_instance != nullptr); Py_DECREF(pArgs); Py_DECREF(wrapped_capsule); Py_DECREF(wrapper_type); Py_DECREF(module); return wrapper_instance; } PyObject *ActivePyModules::get_osdmap() { auto newmap = without_gil([&] { OSDMap *newmap = new OSDMap; cluster_state.with_osdmap([&](const OSDMap& o) { newmap->deepish_copy_from(o); }); return newmap; }); return construct_with_capsule("mgr_module", "OSDMap", (void*)newmap); } PyObject *ActivePyModules::get_foreign_config( const std::string& who, const std::string& name) { dout(10) << "ceph_foreign_option_get " << who << " " << name << dendl; // NOTE: for now this will only work with build-in options, not module options. const Option *opt = g_conf().find_option(name); if (!opt) { dout(4) << "ceph_foreign_option_get " << name << " not found " << dendl; PyErr_Format(PyExc_KeyError, "option not found: %s", name.c_str()); return nullptr; } // If the monitors are not yet running pacific, we cannot rely on our local // ConfigMap if (!have_local_config_map) { dout(20) << "mon cluster wasn't pacific when we started: falling back to 'config get'" << dendl; without_gil_t no_gil; Command cmd; { std::lock_guard l(lock); cmd.run( &monc, "{\"prefix\": \"config get\","s + "\"who\": \""s + who + "\","s + "\"key\": \""s + name + "\"}"); } cmd.wait(); dout(10) << "ceph_foreign_option_get (mon command) " << who << " " << name << " = " << cmd.outbl.to_str() << dendl; no_gil.acquire_gil(); return get_python_typed_option_value(opt->type, cmd.outbl.to_str()); } // mimic the behavor of mon/ConfigMonitor's 'config get' command EntityName entity; if (!entity.from_str(who) && !entity.from_str(who + ".")) { dout(5) << "unrecognized entity '" << who << "'" << dendl; PyErr_Format(PyExc_KeyError, "invalid entity: %s", who.c_str()); return nullptr; } without_gil_t no_gil; lock.lock(); // FIXME: this is super inefficient, since we generate the entire daemon // config just to extract one value from it! std::map<std::string,std::string,std::less<>> config; cluster_state.with_osdmap([&](const OSDMap &osdmap) { map<string,string> crush_location; string device_class; if (entity.is_osd()) { osdmap.crush->get_full_location(who, &crush_location); int id = atoi(entity.get_id().c_str()); const char *c = osdmap.crush->get_item_class(id); if (c) { device_class = c; } dout(10) << __func__ << " crush_location " << crush_location << " class " << device_class << dendl; } std::map<std::string,pair<std::string,const MaskedOption*>> src; config = config_map.generate_entity_map( entity, crush_location, osdmap.crush.get(), device_class, &src); }); // get a single value string value; auto p = config.find(name); if (p != config.end()) { value = p->second; } else { if (!entity.is_client() && opt->daemon_value != Option::value_t{}) { value = Option::to_str(opt->daemon_value); } else { value = Option::to_str(opt->value); } } dout(10) << "ceph_foreign_option_get (configmap) " << who << " " << name << " = " << value << dendl; lock.unlock(); no_gil.acquire_gil(); return get_python_typed_option_value(opt->type, value); } void ActivePyModules::set_health_checks(const std::string& module_name, health_check_map_t&& checks) { bool changed = false; lock.lock(); auto p = modules.find(module_name); if (p != modules.end()) { changed = p->second->set_health_checks(std::move(checks)); } lock.unlock(); // immediately schedule a report to be sent to the monitors with the new // health checks that have changed. This is done asynchronusly to avoid // blocking python land. ActivePyModules::lock needs to be dropped to make // lockdep happy: // // send_report callers: DaemonServer::lock -> PyModuleRegistery::lock // active_start: PyModuleRegistry::lock -> ActivePyModules::lock // // if we don't release this->lock before calling schedule_tick a cycle is // formed with the addition of ActivePyModules::lock -> DaemonServer::lock. // This is still correct as send_report is run asynchronously under // DaemonServer::lock. if (changed) server.schedule_tick(0); } int ActivePyModules::handle_command( const ModuleCommand& module_command, const MgrSession& session, const cmdmap_t &cmdmap, const bufferlist &inbuf, std::stringstream *ds, std::stringstream *ss) { lock.lock(); auto mod_iter = modules.find(module_command.module_name); if (mod_iter == modules.end()) { *ss << "Module '" << module_command.module_name << "' is not available"; lock.unlock(); return -ENOENT; } lock.unlock(); return mod_iter->second->handle_command(module_command, session, cmdmap, inbuf, ds, ss); } void ActivePyModules::get_health_checks(health_check_map_t *checks) { std::lock_guard l(lock); for (auto& [name, module] : modules) { dout(15) << "getting health checks for " << name << dendl; module->get_health_checks(checks); } } void ActivePyModules::update_progress_event( const std::string& evid, const std::string& desc, float progress, bool add_to_ceph_s) { std::lock_guard l(lock); auto& pe = progress_events[evid]; pe.message = desc; pe.progress = progress; pe.add_to_ceph_s = add_to_ceph_s; } void ActivePyModules::complete_progress_event(const std::string& evid) { std::lock_guard l(lock); progress_events.erase(evid); } void ActivePyModules::clear_all_progress_events() { std::lock_guard l(lock); progress_events.clear(); } void ActivePyModules::get_progress_events(std::map<std::string,ProgressEvent> *events) { std::lock_guard l(lock); *events = progress_events; } void ActivePyModules::config_notify() { std::lock_guard l(lock); for (auto& [name, module] : modules) { // Send all python calls down a Finisher to avoid blocking // C++ code, and avoid any potential lock cycles. dout(15) << "notify (config) " << name << dendl; Finisher& mod_finisher = py_module_registry.get_active_module_finisher(name); // workaround for https://bugs.llvm.org/show_bug.cgi?id=35984 mod_finisher.queue(new LambdaContext([module=module](int r){ module->config_notify(); })); } } void ActivePyModules::set_uri(const std::string& module_name, const std::string &uri) { std::lock_guard l(lock); dout(4) << " module " << module_name << " set URI '" << uri << "'" << dendl; modules.at(module_name)->set_uri(uri); } void ActivePyModules::set_device_wear_level(const std::string& devid, float wear_level) { // update mgr state map<string,string> meta; daemon_state.with_device( devid, [wear_level, &meta] (DeviceState& dev) { dev.set_wear_level(wear_level); meta = dev.metadata; }); // tell mon json_spirit::Object json_object; for (auto& i : meta) { json_spirit::Config::add(json_object, i.first, i.second); } bufferlist json; json.append(json_spirit::write(json_object)); const string cmd = "{" "\"prefix\": \"config-key set\", " "\"key\": \"device/" + devid + "\"" "}"; Command set_cmd; set_cmd.run(&monc, cmd, json); set_cmd.wait(); } MetricQueryID ActivePyModules::add_osd_perf_query( const OSDPerfMetricQuery &query, const std::optional<OSDPerfMetricLimit> &limit) { return server.add_osd_perf_query(query, limit); } void ActivePyModules::remove_osd_perf_query(MetricQueryID query_id) { int r = server.remove_osd_perf_query(query_id); if (r < 0) { dout(0) << "remove_osd_perf_query for query_id=" << query_id << " failed: " << cpp_strerror(r) << dendl; } } PyObject *ActivePyModules::get_osd_perf_counters(MetricQueryID query_id) { OSDPerfCollector collector(query_id); int r = server.get_osd_perf_counters(&collector); if (r < 0) { dout(0) << "get_osd_perf_counters for query_id=" << query_id << " failed: " << cpp_strerror(r) << dendl; Py_RETURN_NONE; } PyFormatter f; const std::map<OSDPerfMetricKey, PerformanceCounters> &counters = collector.counters; f.open_array_section("counters"); for (auto &[key, instance_counters] : counters) { f.open_object_section("i"); f.open_array_section("k"); for (auto &sub_key : key) { f.open_array_section("s"); for (size_t i = 0; i < sub_key.size(); i++) { f.dump_string(stringify(i).c_str(), sub_key[i]); } f.close_section(); // s } f.close_section(); // k f.open_array_section("c"); for (auto &c : instance_counters) { f.open_array_section("p"); f.dump_unsigned("0", c.first); f.dump_unsigned("1", c.second); f.close_section(); // p } f.close_section(); // c f.close_section(); // i } f.close_section(); // counters return f.get(); } MetricQueryID ActivePyModules::add_mds_perf_query( const MDSPerfMetricQuery &query, const std::optional<MDSPerfMetricLimit> &limit) { return server.add_mds_perf_query(query, limit); } void ActivePyModules::remove_mds_perf_query(MetricQueryID query_id) { int r = server.remove_mds_perf_query(query_id); if (r < 0) { dout(0) << "remove_mds_perf_query for query_id=" << query_id << " failed: " << cpp_strerror(r) << dendl; } } void ActivePyModules::reregister_mds_perf_queries() { server.reregister_mds_perf_queries(); } PyObject *ActivePyModules::get_mds_perf_counters(MetricQueryID query_id) { MDSPerfCollector collector(query_id); int r = server.get_mds_perf_counters(&collector); if (r < 0) { dout(0) << "get_mds_perf_counters for query_id=" << query_id << " failed: " << cpp_strerror(r) << dendl; Py_RETURN_NONE; } PyFormatter f; const std::map<MDSPerfMetricKey, PerformanceCounters> &counters = collector.counters; f.open_array_section("metrics"); f.open_array_section("delayed_ranks"); f.dump_string("ranks", stringify(collector.delayed_ranks).c_str()); f.close_section(); // delayed_ranks f.open_array_section("counters"); for (auto &[key, instance_counters] : counters) { f.open_object_section("i"); f.open_array_section("k"); for (auto &sub_key : key) { f.open_array_section("s"); for (size_t i = 0; i < sub_key.size(); i++) { f.dump_string(stringify(i).c_str(), sub_key[i]); } f.close_section(); // s } f.close_section(); // k f.open_array_section("c"); for (auto &c : instance_counters) { f.open_array_section("p"); f.dump_unsigned("0", c.first); f.dump_unsigned("1", c.second); f.close_section(); // p } f.close_section(); // c f.close_section(); // i } f.close_section(); // counters f.open_array_section("last_updated"); f.dump_float("last_updated_mono", collector.last_updated_mono); f.close_section(); // last_updated f.close_section(); // metrics return f.get(); } void ActivePyModules::cluster_log(const std::string &channel, clog_type prio, const std::string &message) { std::lock_guard l(lock); auto cl = monc.get_log_client()->create_channel(channel); cl->parse_client_options(g_ceph_context); cl->do_log(prio, message); } void ActivePyModules::register_client(std::string_view name, std::string addrs, bool replace) { entity_addrvec_t addrv; addrv.parse(addrs.data()); dout(7) << "registering msgr client handle " << addrv << " (replace=" << replace << ")" << dendl; py_module_registry.register_client(name, std::move(addrv), replace); } void ActivePyModules::unregister_client(std::string_view name, std::string addrs) { entity_addrvec_t addrv; addrv.parse(addrs.data()); dout(7) << "unregistering msgr client handle " << addrv << dendl; py_module_registry.unregister_client(name, addrv); } PyObject* ActivePyModules::get_daemon_health_metrics() { without_gil_t no_gil; return daemon_state.with_daemons_by_server([&no_gil] (const std::map<std::string, DaemonStateCollection> &all) { no_gil.acquire_gil(); PyFormatter f; for (const auto &[hostname, daemon_state] : all) { for (const auto &[key, state] : daemon_state) { f.open_array_section(ceph::to_string(key)); for (const auto &metric : state->daemon_health_metrics) { f.open_object_section(metric.get_type_name()); f.dump_int("value", metric.get_n1()); f.dump_string("type", metric.get_type_name()); f.close_section(); } f.close_section(); } } return f.get(); }); }
47,637
29.655084
114
cc
null
ceph-main/src/mgr/ActivePyModules.h
// -*- 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 John Spray <[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. */ #pragma once #include "ActivePyModule.h" #include "common/Finisher.h" #include "common/ceph_mutex.h" #include "PyFormatter.h" #include "osdc/Objecter.h" #include "client/Client.h" #include "common/LogClient.h" #include "mon/MgrMap.h" #include "mon/MonCommand.h" #include "mon/mon_types.h" #include "mon/ConfigMap.h" #include "mgr/TTLCache.h" #include "DaemonState.h" #include "ClusterState.h" #include "OSDPerfMetricTypes.h" class health_check_map_t; class DaemonServer; class MgrSession; class ModuleCommand; class PyModuleRegistry; class ActivePyModules { // module class instances not yet created std::set<std::string, std::less<>> pending_modules; // module class instances already created std::map<std::string, std::shared_ptr<ActivePyModule>> modules; PyModuleConfig &module_config; bool have_local_config_map = false; std::map<std::string, std::string> store_cache; ConfigMap config_map; ///< derived from store_cache config/ keys DaemonStateIndex &daemon_state; ClusterState &cluster_state; MonClient &monc; LogChannelRef clog, audit_clog; Objecter &objecter; Client &client; Finisher &finisher; TTLCache<std::string, PyObject*> ttl_cache; public: Finisher cmd_finisher; private: DaemonServer &server; PyModuleRegistry &py_module_registry; std::map<std::string,ProgressEvent> progress_events; mutable ceph::mutex lock = ceph::make_mutex("ActivePyModules::lock"); public: ActivePyModules( PyModuleConfig &module_config, std::map<std::string, std::string> store_data, bool mon_provides_kv_sub, DaemonStateIndex &ds, ClusterState &cs, MonClient &mc, LogChannelRef clog_, LogChannelRef audit_clog_, Objecter &objecter_, Client &client_, Finisher &f, DaemonServer &server, PyModuleRegistry &pmr); ~ActivePyModules(); // FIXME: wrap for send_command? MonClient &get_monc() {return monc;} Objecter &get_objecter() {return objecter;} Client &get_client() {return client;} PyObject *cacheable_get_python(const std::string &what); PyObject *get_python(const std::string &what); PyObject *get_server_python(const std::string &hostname); PyObject *list_servers_python(); PyObject *get_metadata_python( const std::string &svc_type, const std::string &svc_id); PyObject *get_daemon_status_python( const std::string &svc_type, const std::string &svc_id); PyObject *get_counter_python( const std::string &svc_type, const std::string &svc_id, const std::string &path); PyObject *get_latest_counter_python( const std::string &svc_type, const std::string &svc_id, const std::string &path); PyObject *get_perf_schema_python( const std::string &svc_type, const std::string &svc_id); PyObject *get_rocksdb_version(); PyObject *get_context(); PyObject *get_osdmap(); /// @note @c fct is not allowed to acquire locks when holding GIL PyObject *with_perf_counters( std::function<void( PerfCounterInstance& counter_instance, PerfCounterType& counter_type, PyFormatter& f)> fct, const std::string &svc_name, const std::string &svc_id, const std::string &path) const; MetricQueryID add_osd_perf_query( const OSDPerfMetricQuery &query, const std::optional<OSDPerfMetricLimit> &limit); void remove_osd_perf_query(MetricQueryID query_id); PyObject *get_osd_perf_counters(MetricQueryID query_id); MetricQueryID add_mds_perf_query( const MDSPerfMetricQuery &query, const std::optional<MDSPerfMetricLimit> &limit); void remove_mds_perf_query(MetricQueryID query_id); void reregister_mds_perf_queries(); PyObject *get_mds_perf_counters(MetricQueryID query_id); bool get_store(const std::string &module_name, const std::string &key, std::string *val) const; PyObject *get_store_prefix(const std::string &module_name, const std::string &prefix) const; void set_store(const std::string &module_name, const std::string &key, const std::optional<std::string> &val); bool get_config(const std::string &module_name, const std::string &key, std::string *val) const; std::pair<int, std::string> set_config(const std::string &module_name, const std::string &key, const std::optional<std::string> &val); PyObject *get_typed_config(const std::string &module_name, const std::string &key, const std::string &prefix = "") const; PyObject *get_foreign_config( const std::string& who, const std::string& name); void set_health_checks(const std::string& module_name, health_check_map_t&& checks); void get_health_checks(health_check_map_t *checks); void update_progress_event(const std::string& evid, const std::string& desc, float progress, bool add_to_ceph_s); void complete_progress_event(const std::string& evid); void clear_all_progress_events(); void get_progress_events(std::map<std::string,ProgressEvent>* events); void register_client(std::string_view name, std::string addrs, bool replace); void unregister_client(std::string_view name, std::string addrs); void config_notify(); void set_uri(const std::string& module_name, const std::string &uri); void set_device_wear_level(const std::string& devid, float wear_level); int handle_command( const ModuleCommand& module_command, const MgrSession& session, const cmdmap_t &cmdmap, const bufferlist &inbuf, std::stringstream *ds, std::stringstream *ss); std::map<std::string, std::string> get_services() const; void update_kv_data( const std::string prefix, bool incremental, const map<std::string, std::optional<bufferlist>, std::less<>>& data); void _refresh_config_map(); // Public so that MonCommandCompletion can use it // FIXME: for send_command completion notifications, // send it to only the module that sent the command, not everyone void notify_all(const std::string &notify_type, const std::string &notify_id); void notify_all(const LogEntry &log_entry); auto& get_module_finisher(const std::string &name) { return modules.at(name)->finisher; } bool is_pending(std::string_view name) const { return pending_modules.count(name) > 0; } bool module_exists(const std::string &name) const { return modules.count(name) > 0; } bool method_exists( const std::string &module_name, const std::string &method_name) const { return modules.at(module_name)->method_exists(method_name); } PyObject *dispatch_remote( const std::string &other_module, const std::string &method, PyObject *args, PyObject *kwargs, std::string *err); int init(); void shutdown(); void start_one(PyModuleRef py_module); void dump_server(const std::string &hostname, const DaemonStateCollection &dmc, Formatter *f); void cluster_log(const std::string &channel, clog_type prio, const std::string &message); PyObject* get_daemon_health_metrics(); bool inject_python_on() const; void update_cache_metrics(); };
7,526
31.029787
89
h
null
ceph-main/src/mgr/BaseMgrModule.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 John Spray <[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. */ /** * The interface we present to python code that runs within * ceph-mgr. This is implemented as a Python class from which * all modules must inherit -- access to the Ceph state is then * available as methods on that object. */ #include "Python.h" #include "Mgr.h" #include "mon/MonClient.h" #include "common/errno.h" #include "common/version.h" #include "mgr/Types.h" #include "PyUtil.h" #include "BaseMgrModule.h" #include "Gil.h" #include <algorithm> #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #define PLACEHOLDER "" using std::list; using std::string; typedef struct { PyObject_HEAD ActivePyModules *py_modules; ActivePyModule *this_module; } BaseMgrModule; class MonCommandCompletion : public Context { ActivePyModules *py_modules; PyObject *python_completion; const std::string tag; SafeThreadState pThreadState; public: std::string outs; bufferlist outbl; MonCommandCompletion( ActivePyModules *py_modules_, PyObject* ev, const std::string &tag_, PyThreadState *ts_) : py_modules(py_modules_), python_completion(ev), tag(tag_), pThreadState(ts_) { ceph_assert(python_completion != nullptr); Py_INCREF(python_completion); } ~MonCommandCompletion() override { if (python_completion) { // Usually do this in finish(): this path is only for if we're // being destroyed without completing. Gil gil(pThreadState, true); Py_DECREF(python_completion); python_completion = nullptr; } } void finish(int r) override { ceph_assert(python_completion != nullptr); dout(10) << "MonCommandCompletion::finish()" << dendl; { // Scoped so the Gil is released before calling notify_all() // Create new thread state because this is called via the MonClient // Finisher, not the PyModules finisher. Gil gil(pThreadState, true); auto set_fn = PyObject_GetAttrString(python_completion, "complete"); ceph_assert(set_fn != nullptr); auto pyR = PyLong_FromLong(r); auto pyOutBl = PyUnicode_FromString(outbl.to_str().c_str()); auto pyOutS = PyUnicode_FromString(outs.c_str()); auto args = PyTuple_Pack(3, pyR, pyOutBl, pyOutS); Py_DECREF(pyR); Py_DECREF(pyOutBl); Py_DECREF(pyOutS); auto rtn = PyObject_CallObject(set_fn, args); if (rtn != nullptr) { Py_DECREF(rtn); } Py_DECREF(args); Py_DECREF(set_fn); Py_DECREF(python_completion); python_completion = nullptr; } py_modules->notify_all("command", tag); } }; static PyObject* ceph_send_command(BaseMgrModule *self, PyObject *args) { // Like mon, osd, mds char *type = nullptr; // Like "23" for an OSD or "myid" for an MDS char *name = nullptr; char *cmd_json = nullptr; char *tag = nullptr; char *inbuf_ptr = nullptr; Py_ssize_t inbuf_len = 0; bufferlist inbuf = {}; PyObject *completion = nullptr; if (!PyArg_ParseTuple(args, "Ossssz#:ceph_send_command", &completion, &type, &name, &cmd_json, &tag, &inbuf_ptr, &inbuf_len)) { return nullptr; } if (inbuf_ptr) { inbuf.append(inbuf_ptr, (unsigned)inbuf_len); } auto set_fn = PyObject_GetAttrString(completion, "complete"); if (set_fn == nullptr) { ceph_abort(); // TODO raise python exception instead } else { ceph_assert(PyCallable_Check(set_fn)); } Py_DECREF(set_fn); MonCommandCompletion *command_c = new MonCommandCompletion(self->py_modules, completion, tag, PyThreadState_Get()); PyThreadState *tstate = PyEval_SaveThread(); if (std::string(type) == "mon") { // Wait for the latest OSDMap after each command we send to // the mons. This is a heavy-handed hack to make life simpler // for python module authors, so that they know whenever they // run a command they've gt a fresh OSDMap afterwards. // TODO: enhance MCommand interface so that it returns // latest cluster map versions on completion, and callers // can wait for those. auto c = new LambdaContext([command_c, self](int command_r){ self->py_modules->get_objecter().wait_for_latest_osdmap( [command_c, command_r](boost::system::error_code) { command_c->complete(command_r); }); }); self->py_modules->get_monc().start_mon_command( name, {cmd_json}, inbuf, &command_c->outbl, &command_c->outs, new C_OnFinisher(c, &self->py_modules->cmd_finisher)); } else if (std::string(type) == "osd") { std::string err; uint64_t osd_id = strict_strtoll(name, 10, &err); if (!err.empty()) { delete command_c; string msg("invalid osd_id: "); msg.append("\"").append(name).append("\""); PyEval_RestoreThread(tstate); PyErr_SetString(PyExc_ValueError, msg.c_str()); return nullptr; } ceph_tid_t tid; self->py_modules->get_objecter().osd_command( osd_id, {cmd_json}, inbuf, &tid, [command_c, f = &self->py_modules->cmd_finisher] (boost::system::error_code ec, std::string s, ceph::buffer::list bl) { command_c->outs = std::move(s); command_c->outbl = std::move(bl); f->queue(command_c); }); } else if (std::string(type) == "mds") { int r = self->py_modules->get_client().mds_command( name, {cmd_json}, inbuf, &command_c->outbl, &command_c->outs, new C_OnFinisher(command_c, &self->py_modules->cmd_finisher)); if (r != 0) { string msg("failed to send command to mds: "); msg.append(cpp_strerror(r)); PyEval_RestoreThread(tstate); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); return nullptr; } } else if (std::string(type) == "pg") { pg_t pgid; if (!pgid.parse(name)) { delete command_c; string msg("invalid pgid: "); msg.append("\"").append(name).append("\""); PyEval_RestoreThread(tstate); PyErr_SetString(PyExc_ValueError, msg.c_str()); return nullptr; } ceph_tid_t tid; self->py_modules->get_objecter().pg_command( pgid, {cmd_json}, inbuf, &tid, [command_c, f = &self->py_modules->cmd_finisher] (boost::system::error_code ec, std::string s, ceph::buffer::list bl) { command_c->outs = std::move(s); command_c->outbl = std::move(bl); f->queue(command_c); }); PyEval_RestoreThread(tstate); return nullptr; } else { delete command_c; string msg("unknown service type: "); msg.append(type); PyEval_RestoreThread(tstate); PyErr_SetString(PyExc_ValueError, msg.c_str()); return nullptr; } PyEval_RestoreThread(tstate); Py_RETURN_NONE; } static PyObject* ceph_set_health_checks(BaseMgrModule *self, PyObject *args) { PyObject *checks = NULL; if (!PyArg_ParseTuple(args, "O:ceph_set_health_checks", &checks)) { return NULL; } if (!PyDict_Check(checks)) { derr << __func__ << " arg not a dict" << dendl; Py_RETURN_NONE; } PyObject *checksls = PyDict_Items(checks); health_check_map_t out_checks; for (int i = 0; i < PyList_Size(checksls); ++i) { PyObject *kv = PyList_GET_ITEM(checksls, i); char *check_name = nullptr; PyObject *check_info = nullptr; if (!PyArg_ParseTuple(kv, "sO:pair", &check_name, &check_info)) { derr << __func__ << " dict item " << i << " not a size 2 tuple" << dendl; continue; } if (!PyDict_Check(check_info)) { derr << __func__ << " item " << i << " " << check_name << " value not a dict" << dendl; continue; } health_status_t severity = HEALTH_OK; string summary; list<string> detail; int64_t count = 0; PyObject *infols = PyDict_Items(check_info); for (int j = 0; j < PyList_Size(infols); ++j) { PyObject *pair = PyList_GET_ITEM(infols, j); if (!PyTuple_Check(pair)) { derr << __func__ << " item " << i << " pair " << j << " not a tuple" << dendl; continue; } char *k = nullptr; PyObject *v = nullptr; if (!PyArg_ParseTuple(pair, "sO:pair", &k, &v)) { derr << __func__ << " item " << i << " pair " << j << " not a size 2 tuple" << dendl; continue; } string ks(k); if (ks == "severity") { if (!PyUnicode_Check(v)) { derr << __func__ << " check " << check_name << " severity value not string" << dendl; continue; } if (const string vs = PyUnicode_AsUTF8(v); vs == "warning") { severity = HEALTH_WARN; } else if (vs == "error") { severity = HEALTH_ERR; } } else if (ks == "summary") { if (!PyUnicode_Check(v)) { derr << __func__ << " check " << check_name << " summary value not [unicode] string" << dendl; continue; } else { summary = PyUnicode_AsUTF8(v); } } else if (ks == "count") { if (PyLong_Check(v)) { count = PyLong_AsLong(v); } else { derr << __func__ << " check " << check_name << " count value not int" << dendl; continue; } } else if (ks == "detail") { if (!PyList_Check(v)) { derr << __func__ << " check " << check_name << " detail value not list" << dendl; continue; } for (int k = 0; k < PyList_Size(v); ++k) { PyObject *di = PyList_GET_ITEM(v, k); if (!PyUnicode_Check(di)) { derr << __func__ << " check " << check_name << " detail item " << k << " not a [unicode] string" << dendl; continue; } else { detail.push_back(PyUnicode_AsUTF8(di)); } } } else { derr << __func__ << " check " << check_name << " unexpected key " << k << dendl; } } auto& d = out_checks.add(check_name, severity, summary, count); d.detail.swap(detail); } JSONFormatter jf(true); dout(10) << "module " << self->this_module->get_name() << " health checks:\n"; out_checks.dump(&jf); jf.flush(*_dout); *_dout << dendl; without_gil([&] { self->py_modules->set_health_checks(self->this_module->get_name(), std::move(out_checks)); }); Py_RETURN_NONE; } static PyObject* ceph_state_get(BaseMgrModule *self, PyObject *args) { char *what = NULL; if (!PyArg_ParseTuple(args, "s:ceph_state_get", &what)) { return NULL; } return self->py_modules->cacheable_get_python(what); } static PyObject* ceph_get_server(BaseMgrModule *self, PyObject *args) { char *hostname = NULL; if (!PyArg_ParseTuple(args, "z:ceph_get_server", &hostname)) { return NULL; } if (hostname) { return self->py_modules->get_server_python(hostname); } else { return self->py_modules->list_servers_python(); } } static PyObject* ceph_get_mgr_id(BaseMgrModule *self, PyObject *args) { return PyUnicode_FromString(g_conf()->name.get_id().c_str()); } static PyObject* ceph_option_get(BaseMgrModule *self, PyObject *args) { char *what = nullptr; if (!PyArg_ParseTuple(args, "s:ceph_option_get", &what)) { derr << "Invalid args!" << dendl; return nullptr; } const Option *opt = g_conf().find_option(string(what)); if (opt) { std::string value; switch (int r = g_conf().get_val(string(what), &value); r) { case -ENOMEM: PyErr_NoMemory(); return nullptr; case -ENAMETOOLONG: PyErr_SetString(PyExc_ValueError, "value too long"); return nullptr; default: ceph_assert(r == 0); break; } dout(10) << "ceph_option_get " << what << " found: " << value << dendl; return get_python_typed_option_value(opt->type, value); } else { dout(4) << "ceph_option_get " << what << " not found " << dendl; PyErr_Format(PyExc_KeyError, "option not found: %s", what); return nullptr; } } static PyObject* ceph_foreign_option_get(BaseMgrModule *self, PyObject *args) { char *who = nullptr; char *what = nullptr; if (!PyArg_ParseTuple(args, "ss:ceph_foreign_option_get", &who, &what)) { derr << "Invalid args!" << dendl; return nullptr; } return self->py_modules->get_foreign_config(who, what); } static PyObject* ceph_get_module_option(BaseMgrModule *self, PyObject *args) { char *module = nullptr; char *key = nullptr; char *prefix = nullptr; if (!PyArg_ParseTuple(args, "ss|s:ceph_get_module_option", &module, &key, &prefix)) { derr << "Invalid args!" << dendl; return nullptr; } std::string str_prefix; if (prefix) { str_prefix = prefix; } assert(self->this_module->py_module); auto pResult = self->py_modules->get_typed_config(module, key, str_prefix); return pResult; } static PyObject* ceph_store_get_prefix(BaseMgrModule *self, PyObject *args) { char *prefix = nullptr; if (!PyArg_ParseTuple(args, "s:ceph_store_get_prefix", &prefix)) { derr << "Invalid args!" << dendl; return nullptr; } return self->py_modules->get_store_prefix(self->this_module->get_name(), prefix); } static PyObject* ceph_set_module_option(BaseMgrModule *self, PyObject *args) { char *module = nullptr; char *key = nullptr; char *value = nullptr; if (!PyArg_ParseTuple(args, "ssz:ceph_set_module_option", &module, &key, &value)) { derr << "Invalid args!" << dendl; return nullptr; } std::optional<string> val; if (value) { val = value; } auto [ret, msg] = without_gil([&] { return self->py_modules->set_config(module, key, val); }); if (ret) { PyErr_SetString(PyExc_ValueError, msg.c_str()); return nullptr; } Py_RETURN_NONE; } static PyObject* ceph_store_get(BaseMgrModule *self, PyObject *args) { char *what = nullptr; if (!PyArg_ParseTuple(args, "s:ceph_store_get", &what)) { derr << "Invalid args!" << dendl; return nullptr; } std::string value; bool found = self->py_modules->get_store(self->this_module->get_name(), what, &value); if (found) { dout(10) << "ceph_store_get " << what << " found: " << value.c_str() << dendl; return PyUnicode_FromString(value.c_str()); } else { dout(4) << "ceph_store_get " << what << " not found " << dendl; Py_RETURN_NONE; } } static PyObject* ceph_store_set(BaseMgrModule *self, PyObject *args) { char *key = nullptr; char *value = nullptr; if (!PyArg_ParseTuple(args, "sz:ceph_store_set", &key, &value)) { return nullptr; } std::optional<string> val; if (value) { val = value; } without_gil([&] { self->py_modules->set_store(self->this_module->get_name(), key, val); }); Py_RETURN_NONE; } static PyObject* get_metadata(BaseMgrModule *self, PyObject *args) { char *svc_name = NULL; char *svc_id = NULL; if (!PyArg_ParseTuple(args, "ss:get_metadata", &svc_name, &svc_id)) { return nullptr; } return self->py_modules->get_metadata_python(svc_name, svc_id); } static PyObject* get_daemon_status(BaseMgrModule *self, PyObject *args) { char *svc_name = NULL; char *svc_id = NULL; if (!PyArg_ParseTuple(args, "ss:get_daemon_status", &svc_name, &svc_id)) { return nullptr; } return self->py_modules->get_daemon_status_python(svc_name, svc_id); } static PyObject* ceph_log(BaseMgrModule *self, PyObject *args) { char *record = nullptr; if (!PyArg_ParseTuple(args, "s:log", &record)) { return nullptr; } ceph_assert(self->this_module); self->this_module->log(record); Py_RETURN_NONE; } static PyObject* ceph_cluster_log(BaseMgrModule *self, PyObject *args) { int prio = 0; char *channel = nullptr; char *message = nullptr; if (!PyArg_ParseTuple(args, "sis:ceph_cluster_log", &channel, &prio, &message)) { return nullptr; } without_gil([&] { self->py_modules->cluster_log(channel, (clog_type)prio, message); }); Py_RETURN_NONE; } static PyObject * ceph_get_version(BaseMgrModule *self, PyObject *args) { return PyUnicode_FromString(pretty_version_to_str().c_str()); } static PyObject * ceph_get_ceph_conf_path(BaseMgrModule *self, PyObject *args) { return PyUnicode_FromString(g_conf().get_conf_path().c_str()); } static PyObject * ceph_get_release_name(BaseMgrModule *self, PyObject *args) { return PyUnicode_FromString(ceph_release_to_str()); } static PyObject * ceph_lookup_release_name(BaseMgrModule *self, PyObject *args) { int major = 0; if (!PyArg_ParseTuple(args, "i:ceph_lookup_release_name", &major)) { return nullptr; } return PyUnicode_FromString(ceph_release_name(major)); } static PyObject * ceph_get_context(BaseMgrModule *self) { return self->py_modules->get_context(); } static PyObject* get_counter(BaseMgrModule *self, PyObject *args) { char *svc_name = nullptr; char *svc_id = nullptr; char *counter_path = nullptr; if (!PyArg_ParseTuple(args, "sss:get_counter", &svc_name, &svc_id, &counter_path)) { return nullptr; } return self->py_modules->get_counter_python( svc_name, svc_id, counter_path); } static PyObject* get_latest_counter(BaseMgrModule *self, PyObject *args) { char *svc_name = nullptr; char *svc_id = nullptr; char *counter_path = nullptr; if (!PyArg_ParseTuple(args, "sss:get_counter", &svc_name, &svc_id, &counter_path)) { return nullptr; } return self->py_modules->get_latest_counter_python( svc_name, svc_id, counter_path); } static PyObject* get_perf_schema(BaseMgrModule *self, PyObject *args) { char *type_str = nullptr; char *svc_id = nullptr; if (!PyArg_ParseTuple(args, "ss:get_perf_schema", &type_str, &svc_id)) { return nullptr; } return self->py_modules->get_perf_schema_python(type_str, svc_id); } static PyObject* ceph_get_rocksdb_version(BaseMgrModule *self) { return self->py_modules->get_rocksdb_version(); } static PyObject * ceph_get_osdmap(BaseMgrModule *self, PyObject *args) { return self->py_modules->get_osdmap(); } static PyObject* ceph_set_uri(BaseMgrModule *self, PyObject *args) { char *svc_str = nullptr; if (!PyArg_ParseTuple(args, "s:ceph_advertize_service", &svc_str)) { return nullptr; } // We call down into PyModules even though we have a MgrPyModule // reference here, because MgrPyModule's fields are protected // by PyModules' lock. without_gil([&] { self->py_modules->set_uri(self->this_module->get_name(), svc_str); }); Py_RETURN_NONE; } static PyObject* ceph_set_wear_level(BaseMgrModule *self, PyObject *args) { char *devid = nullptr; float wear_level; if (!PyArg_ParseTuple(args, "sf:ceph_set_wear_level", &devid, &wear_level)) { return nullptr; } without_gil([&] { self->py_modules->set_device_wear_level(devid, wear_level); }); Py_RETURN_NONE; } static PyObject* ceph_have_mon_connection(BaseMgrModule *self, PyObject *args) { if (self->py_modules->get_monc().is_connected()) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject* ceph_update_progress_event(BaseMgrModule *self, PyObject *args) { char *evid = nullptr; char *desc = nullptr; float progress = 0.0; bool add_to_ceph_s = false; if (!PyArg_ParseTuple(args, "ssfb:ceph_update_progress_event", &evid, &desc, &progress, &add_to_ceph_s)) { return nullptr; } without_gil([&] { self->py_modules->update_progress_event(evid, desc, progress, add_to_ceph_s); }); Py_RETURN_NONE; } static PyObject* ceph_complete_progress_event(BaseMgrModule *self, PyObject *args) { char *evid = nullptr; if (!PyArg_ParseTuple(args, "s:ceph_complete_progress_event", &evid)) { return nullptr; } without_gil([&] { self->py_modules->complete_progress_event(evid); }); Py_RETURN_NONE; } static PyObject* ceph_clear_all_progress_events(BaseMgrModule *self, PyObject *args) { without_gil([&] { self->py_modules->clear_all_progress_events(); }); Py_RETURN_NONE; } static PyObject * ceph_dispatch_remote(BaseMgrModule *self, PyObject *args) { char *other_module = nullptr; char *method = nullptr; PyObject *remote_args = nullptr; PyObject *remote_kwargs = nullptr; if (!PyArg_ParseTuple(args, "ssOO:ceph_dispatch_remote", &other_module, &method, &remote_args, &remote_kwargs)) { return nullptr; } // Early error handling, because if the module doesn't exist then we // won't be able to use its thread state to set python error state // inside dispatch_remote(). if (!self->py_modules->module_exists(other_module)) { derr << "no module '" << other_module << "'" << dendl; PyErr_SetString(PyExc_ImportError, "Module not found"); return nullptr; } // Drop GIL from calling python thread state, it will be taken // both for checking for method existence and for executing method. PyThreadState *tstate = PyEval_SaveThread(); if (!self->py_modules->method_exists(other_module, method)) { PyEval_RestoreThread(tstate); PyErr_SetString(PyExc_NameError, "Method not found"); return nullptr; } std::string err; auto result = self->py_modules->dispatch_remote(other_module, method, remote_args, remote_kwargs, &err); PyEval_RestoreThread(tstate); if (result == nullptr) { std::stringstream ss; ss << "Remote method threw exception: " << err; PyErr_SetString(PyExc_RuntimeError, ss.str().c_str()); derr << ss.str() << dendl; } return result; } static PyObject* ceph_add_osd_perf_query(BaseMgrModule *self, PyObject *args) { static const std::string NAME_KEY_DESCRIPTOR = "key_descriptor"; static const std::string NAME_COUNTERS_DESCRIPTORS = "performance_counter_descriptors"; static const std::string NAME_LIMIT = "limit"; static const std::string NAME_SUB_KEY_TYPE = "type"; static const std::string NAME_SUB_KEY_REGEX = "regex"; static const std::string NAME_LIMIT_ORDER_BY = "order_by"; static const std::string NAME_LIMIT_MAX_COUNT = "max_count"; static const std::map<std::string, OSDPerfMetricSubKeyType> sub_key_types = { {"client_id", OSDPerfMetricSubKeyType::CLIENT_ID}, {"client_address", OSDPerfMetricSubKeyType::CLIENT_ADDRESS}, {"pool_id", OSDPerfMetricSubKeyType::POOL_ID}, {"namespace", OSDPerfMetricSubKeyType::NAMESPACE}, {"osd_id", OSDPerfMetricSubKeyType::OSD_ID}, {"pg_id", OSDPerfMetricSubKeyType::PG_ID}, {"object_name", OSDPerfMetricSubKeyType::OBJECT_NAME}, {"snap_id", OSDPerfMetricSubKeyType::SNAP_ID}, }; static const std::map<std::string, PerformanceCounterType> counter_types = { {"ops", PerformanceCounterType::OPS}, {"write_ops", PerformanceCounterType::WRITE_OPS}, {"read_ops", PerformanceCounterType::READ_OPS}, {"bytes", PerformanceCounterType::BYTES}, {"write_bytes", PerformanceCounterType::WRITE_BYTES}, {"read_bytes", PerformanceCounterType::READ_BYTES}, {"latency", PerformanceCounterType::LATENCY}, {"write_latency", PerformanceCounterType::WRITE_LATENCY}, {"read_latency", PerformanceCounterType::READ_LATENCY}, }; PyObject *py_query = nullptr; if (!PyArg_ParseTuple(args, "O:ceph_add_osd_perf_query", &py_query)) { derr << "Invalid args!" << dendl; return nullptr; } if (!PyDict_Check(py_query)) { derr << __func__ << " arg not a dict" << dendl; Py_RETURN_NONE; } PyObject *query_params = PyDict_Items(py_query); OSDPerfMetricQuery query; std::optional<OSDPerfMetricLimit> limit; // { // 'key_descriptor': [ // {'type': subkey_type, 'regex': regex_pattern}, // ... // ], // 'performance_counter_descriptors': [ // list, of, descriptor, types // ], // 'limit': {'order_by': performance_counter_type, 'max_count': n}, // } for (int i = 0; i < PyList_Size(query_params); ++i) { PyObject *kv = PyList_GET_ITEM(query_params, i); char *query_param_name = nullptr; PyObject *query_param_val = nullptr; if (!PyArg_ParseTuple(kv, "sO:pair", &query_param_name, &query_param_val)) { derr << __func__ << " dict item " << i << " not a size 2 tuple" << dendl; Py_RETURN_NONE; } if (query_param_name == NAME_KEY_DESCRIPTOR) { if (!PyList_Check(query_param_val)) { derr << __func__ << " " << query_param_name << " not a list" << dendl; Py_RETURN_NONE; } for (int j = 0; j < PyList_Size(query_param_val); j++) { PyObject *sub_key = PyList_GET_ITEM(query_param_val, j); if (!PyDict_Check(sub_key)) { derr << __func__ << " query " << query_param_name << " item " << j << " not a dict" << dendl; Py_RETURN_NONE; } OSDPerfMetricSubKeyDescriptor d; PyObject *sub_key_params = PyDict_Items(sub_key); for (int k = 0; k < PyList_Size(sub_key_params); ++k) { PyObject *pair = PyList_GET_ITEM(sub_key_params, k); if (!PyTuple_Check(pair)) { derr << __func__ << " query " << query_param_name << " item " << j << " pair " << k << " not a tuple" << dendl; Py_RETURN_NONE; } char *param_name = nullptr; PyObject *param_value = nullptr; if (!PyArg_ParseTuple(pair, "sO:pair", &param_name, &param_value)) { derr << __func__ << " query " << query_param_name << " item " << j << " pair " << k << " not a size 2 tuple" << dendl; Py_RETURN_NONE; } if (param_name == NAME_SUB_KEY_TYPE) { if (!PyUnicode_Check(param_value)) { derr << __func__ << " query " << query_param_name << " item " << j << " contains invalid param " << param_name << dendl; Py_RETURN_NONE; } auto type = PyUnicode_AsUTF8(param_value); auto it = sub_key_types.find(type); if (it == sub_key_types.end()) { derr << __func__ << " query " << query_param_name << " item " << j << " contains invalid type " << dendl; Py_RETURN_NONE; } d.type = it->second; } else if (param_name == NAME_SUB_KEY_REGEX) { if (!PyUnicode_Check(param_value)) { derr << __func__ << " query " << query_param_name << " item " << j << " contains invalid param " << param_name << dendl; Py_RETURN_NONE; } d.regex_str = PyUnicode_AsUTF8(param_value); try { d.regex = d.regex_str.c_str(); } catch (const std::regex_error& e) { derr << __func__ << " query " << query_param_name << " item " << j << " contains invalid regex " << d.regex_str << dendl; Py_RETURN_NONE; } if (d.regex.mark_count() == 0) { derr << __func__ << " query " << query_param_name << " item " << j << " regex " << d.regex_str << ": no capturing groups" << dendl; Py_RETURN_NONE; } } else { derr << __func__ << " query " << query_param_name << " item " << j << " contains invalid param " << param_name << dendl; Py_RETURN_NONE; } } if (d.type == static_cast<OSDPerfMetricSubKeyType>(-1) || d.regex_str.empty()) { derr << __func__ << " query " << query_param_name << " item " << i << " invalid" << dendl; Py_RETURN_NONE; } query.key_descriptor.push_back(d); } } else if (query_param_name == NAME_COUNTERS_DESCRIPTORS) { if (!PyList_Check(query_param_val)) { derr << __func__ << " " << query_param_name << " not a list" << dendl; Py_RETURN_NONE; } for (int j = 0; j < PyList_Size(query_param_val); j++) { PyObject *py_type = PyList_GET_ITEM(query_param_val, j); if (!PyUnicode_Check(py_type)) { derr << __func__ << " query " << query_param_name << " item " << j << " not a string" << dendl; Py_RETURN_NONE; } auto type = PyUnicode_AsUTF8(py_type); auto it = counter_types.find(type); if (it == counter_types.end()) { derr << __func__ << " query " << query_param_name << " item " << type << " is not valid type" << dendl; Py_RETURN_NONE; } query.performance_counter_descriptors.push_back(it->second); } } else if (query_param_name == NAME_LIMIT) { if (!PyDict_Check(query_param_val)) { derr << __func__ << " query " << query_param_name << " not a dict" << dendl; Py_RETURN_NONE; } limit = OSDPerfMetricLimit(); PyObject *limit_params = PyDict_Items(query_param_val); for (int j = 0; j < PyList_Size(limit_params); ++j) { PyObject *kv = PyList_GET_ITEM(limit_params, j); char *limit_param_name = nullptr; PyObject *limit_param_val = nullptr; if (!PyArg_ParseTuple(kv, "sO:pair", &limit_param_name, &limit_param_val)) { derr << __func__ << " limit item " << j << " not a size 2 tuple" << dendl; Py_RETURN_NONE; } if (limit_param_name == NAME_LIMIT_ORDER_BY) { if (!PyUnicode_Check(limit_param_val)) { derr << __func__ << " " << limit_param_name << " not a string" << dendl; Py_RETURN_NONE; } auto order_by = PyUnicode_AsUTF8(limit_param_val); auto it = counter_types.find(order_by); if (it == counter_types.end()) { derr << __func__ << " limit " << limit_param_name << " not a valid counter type" << dendl; Py_RETURN_NONE; } limit->order_by = it->second; } else if (limit_param_name == NAME_LIMIT_MAX_COUNT) { if (!PyLong_Check(limit_param_val)) { derr << __func__ << " " << limit_param_name << " not an int" << dendl; Py_RETURN_NONE; } limit->max_count = PyLong_AsLong(limit_param_val); } else { derr << __func__ << " unknown limit param: " << limit_param_name << dendl; Py_RETURN_NONE; } } } else { derr << __func__ << " unknown query param: " << query_param_name << dendl; Py_RETURN_NONE; } } if (query.key_descriptor.empty() || query.performance_counter_descriptors.empty()) { derr << __func__ << " invalid query" << dendl; Py_RETURN_NONE; } if (limit) { auto &ds = query.performance_counter_descriptors; if (std::find(ds.begin(), ds.end(), limit->order_by) == ds.end()) { derr << __func__ << " limit order_by " << limit->order_by << " not in performance_counter_descriptors" << dendl; Py_RETURN_NONE; } } auto query_id = self->py_modules->add_osd_perf_query(query, limit); return PyLong_FromLong(query_id); } static PyObject* ceph_remove_osd_perf_query(BaseMgrModule *self, PyObject *args) { MetricQueryID query_id; if (!PyArg_ParseTuple(args, "i:ceph_remove_osd_perf_query", &query_id)) { derr << "Invalid args!" << dendl; return nullptr; } self->py_modules->remove_osd_perf_query(query_id); Py_RETURN_NONE; } static PyObject* ceph_get_osd_perf_counters(BaseMgrModule *self, PyObject *args) { MetricQueryID query_id; if (!PyArg_ParseTuple(args, "i:ceph_get_osd_perf_counters", &query_id)) { derr << "Invalid args!" << dendl; return nullptr; } return self->py_modules->get_osd_perf_counters(query_id); } // MDS perf query interface -- mostly follows ceph_add_osd_perf_query() // style static PyObject* ceph_add_mds_perf_query(BaseMgrModule *self, PyObject *args) { static const std::string NAME_KEY_DESCRIPTOR = "key_descriptor"; static const std::string NAME_COUNTERS_DESCRIPTORS = "performance_counter_descriptors"; static const std::string NAME_LIMIT = "limit"; static const std::string NAME_SUB_KEY_TYPE = "type"; static const std::string NAME_SUB_KEY_REGEX = "regex"; static const std::string NAME_LIMIT_ORDER_BY = "order_by"; static const std::string NAME_LIMIT_MAX_COUNT = "max_count"; static const std::map<std::string, MDSPerfMetricSubKeyType> sub_key_types = { {"mds_rank", MDSPerfMetricSubKeyType::MDS_RANK}, {"client_id", MDSPerfMetricSubKeyType::CLIENT_ID}, }; static const std::map<std::string, MDSPerformanceCounterType> counter_types = { {"cap_hit", MDSPerformanceCounterType::CAP_HIT_METRIC}, {"read_latency", MDSPerformanceCounterType::READ_LATENCY_METRIC}, {"write_latency", MDSPerformanceCounterType::WRITE_LATENCY_METRIC}, {"metadata_latency", MDSPerformanceCounterType::METADATA_LATENCY_METRIC}, {"dentry_lease", MDSPerformanceCounterType::DENTRY_LEASE_METRIC}, {"opened_files", MDSPerformanceCounterType::OPENED_FILES_METRIC}, {"pinned_icaps", MDSPerformanceCounterType::PINNED_ICAPS_METRIC}, {"opened_inodes", MDSPerformanceCounterType::OPENED_INODES_METRIC}, {"read_io_sizes", MDSPerformanceCounterType::READ_IO_SIZES_METRIC}, {"write_io_sizes", MDSPerformanceCounterType::WRITE_IO_SIZES_METRIC}, {"avg_read_latency", MDSPerformanceCounterType::AVG_READ_LATENCY_METRIC}, {"stdev_read_latency", MDSPerformanceCounterType::STDEV_READ_LATENCY_METRIC}, {"avg_write_latency", MDSPerformanceCounterType::AVG_WRITE_LATENCY_METRIC}, {"stdev_write_latency", MDSPerformanceCounterType::STDEV_WRITE_LATENCY_METRIC}, {"avg_metadata_latency", MDSPerformanceCounterType::AVG_METADATA_LATENCY_METRIC}, {"stdev_metadata_latency", MDSPerformanceCounterType::STDEV_METADATA_LATENCY_METRIC}, }; PyObject *py_query = nullptr; if (!PyArg_ParseTuple(args, "O:ceph_add_mds_perf_query", &py_query)) { derr << "Invalid args!" << dendl; return nullptr; } if (!PyDict_Check(py_query)) { derr << __func__ << " arg not a dict" << dendl; Py_RETURN_NONE; } PyObject *query_params = PyDict_Items(py_query); MDSPerfMetricQuery query; std::optional<MDSPerfMetricLimit> limit; // { // 'key_descriptor': [ // {'type': subkey_type, 'regex': regex_pattern}, // ... // ], // 'performance_counter_descriptors': [ // list, of, descriptor, types // ], // 'limit': {'order_by': performance_counter_type, 'max_count': n}, // } for (int i = 0; i < PyList_Size(query_params); ++i) { PyObject *kv = PyList_GET_ITEM(query_params, i); char *query_param_name = nullptr; PyObject *query_param_val = nullptr; if (!PyArg_ParseTuple(kv, "sO:pair", &query_param_name, &query_param_val)) { derr << __func__ << " dict item " << i << " not a size 2 tuple" << dendl; Py_RETURN_NONE; } if (query_param_name == NAME_KEY_DESCRIPTOR) { if (!PyList_Check(query_param_val)) { derr << __func__ << " " << query_param_name << " not a list" << dendl; Py_RETURN_NONE; } for (int j = 0; j < PyList_Size(query_param_val); j++) { PyObject *sub_key = PyList_GET_ITEM(query_param_val, j); if (!PyDict_Check(sub_key)) { derr << __func__ << " query " << query_param_name << " item " << j << " not a dict" << dendl; Py_RETURN_NONE; } MDSPerfMetricSubKeyDescriptor d; PyObject *sub_key_params = PyDict_Items(sub_key); for (int k = 0; k < PyList_Size(sub_key_params); ++k) { PyObject *pair = PyList_GET_ITEM(sub_key_params, k); if (!PyTuple_Check(pair)) { derr << __func__ << " query " << query_param_name << " item " << j << " pair " << k << " not a tuple" << dendl; Py_RETURN_NONE; } char *param_name = nullptr; PyObject *param_value = nullptr; if (!PyArg_ParseTuple(pair, "sO:pair", &param_name, &param_value)) { derr << __func__ << " query " << query_param_name << " item " << j << " pair " << k << " not a size 2 tuple" << dendl; Py_RETURN_NONE; } if (param_name == NAME_SUB_KEY_TYPE) { if (!PyUnicode_Check(param_value)) { derr << __func__ << " query " << query_param_name << " item " << j << " contains invalid param " << param_name << dendl; Py_RETURN_NONE; } auto type = PyUnicode_AsUTF8(param_value); auto it = sub_key_types.find(type); if (it == sub_key_types.end()) { derr << __func__ << " query " << query_param_name << " item " << j << " contains invalid type " << dendl; Py_RETURN_NONE; } d.type = it->second; } else if (param_name == NAME_SUB_KEY_REGEX) { if (!PyUnicode_Check(param_value)) { derr << __func__ << " query " << query_param_name << " item " << j << " contains invalid param " << param_name << dendl; Py_RETURN_NONE; } d.regex_str = PyUnicode_AsUTF8(param_value); try { d.regex = d.regex_str.c_str(); } catch (const std::regex_error& e) { derr << __func__ << " query " << query_param_name << " item " << j << " contains invalid regex " << d.regex_str << dendl; Py_RETURN_NONE; } if (d.regex.mark_count() == 0) { derr << __func__ << " query " << query_param_name << " item " << j << " regex " << d.regex_str << ": no capturing groups" << dendl; Py_RETURN_NONE; } } else { derr << __func__ << " query " << query_param_name << " item " << j << " contains invalid param " << param_name << dendl; Py_RETURN_NONE; } } if (d.type == static_cast<MDSPerfMetricSubKeyType>(-1) || d.regex_str.empty()) { derr << __func__ << " query " << query_param_name << " item " << i << " invalid" << dendl; Py_RETURN_NONE; } query.key_descriptor.push_back(d); } } else if (query_param_name == NAME_COUNTERS_DESCRIPTORS) { if (!PyList_Check(query_param_val)) { derr << __func__ << " " << query_param_name << " not a list" << dendl; Py_RETURN_NONE; } for (int j = 0; j < PyList_Size(query_param_val); j++) { PyObject *py_type = PyList_GET_ITEM(query_param_val, j); if (!PyUnicode_Check(py_type)) { derr << __func__ << " query " << query_param_name << " item " << j << " not a string" << dendl; Py_RETURN_NONE; } auto type = PyUnicode_AsUTF8(py_type); auto it = counter_types.find(type); if (it == counter_types.end()) { derr << __func__ << " query " << query_param_name << " item " << type << " is not valid type" << dendl; Py_RETURN_NONE; } query.performance_counter_descriptors.push_back(it->second); } } else if (query_param_name == NAME_LIMIT) { if (!PyDict_Check(query_param_val)) { derr << __func__ << " query " << query_param_name << " not a dict" << dendl; Py_RETURN_NONE; } limit = MDSPerfMetricLimit(); PyObject *limit_params = PyDict_Items(query_param_val); for (int j = 0; j < PyList_Size(limit_params); ++j) { PyObject *kv = PyList_GET_ITEM(limit_params, j); char *limit_param_name = nullptr; PyObject *limit_param_val = nullptr; if (!PyArg_ParseTuple(kv, "sO:pair", &limit_param_name, &limit_param_val)) { derr << __func__ << " limit item " << j << " not a size 2 tuple" << dendl; Py_RETURN_NONE; } if (limit_param_name == NAME_LIMIT_ORDER_BY) { if (!PyUnicode_Check(limit_param_val)) { derr << __func__ << " " << limit_param_name << " not a string" << dendl; Py_RETURN_NONE; } auto order_by = PyUnicode_AsUTF8(limit_param_val); auto it = counter_types.find(order_by); if (it == counter_types.end()) { derr << __func__ << " limit " << limit_param_name << " not a valid counter type" << dendl; Py_RETURN_NONE; } limit->order_by = it->second; } else if (limit_param_name == NAME_LIMIT_MAX_COUNT) { if (!PyLong_Check(limit_param_val)) { derr << __func__ << " " << limit_param_name << " not an int" << dendl; Py_RETURN_NONE; } limit->max_count = PyLong_AsLong(limit_param_val); } else { derr << __func__ << " unknown limit param: " << limit_param_name << dendl; Py_RETURN_NONE; } } } else { derr << __func__ << " unknown query param: " << query_param_name << dendl; Py_RETURN_NONE; } } if (query.key_descriptor.empty()) { derr << __func__ << " invalid query" << dendl; Py_RETURN_NONE; } if (limit) { auto &ds = query.performance_counter_descriptors; if (std::find(ds.begin(), ds.end(), limit->order_by) == ds.end()) { derr << __func__ << " limit order_by " << limit->order_by << " not in performance_counter_descriptors" << dendl; Py_RETURN_NONE; } } auto query_id = self->py_modules->add_mds_perf_query(query, limit); return PyLong_FromLong(query_id); } static PyObject* ceph_remove_mds_perf_query(BaseMgrModule *self, PyObject *args) { MetricQueryID query_id; if (!PyArg_ParseTuple(args, "i:ceph_remove_mds_perf_query", &query_id)) { derr << "Invalid args!" << dendl; return nullptr; } self->py_modules->remove_mds_perf_query(query_id); Py_RETURN_NONE; } static PyObject* ceph_reregister_mds_perf_queries(BaseMgrModule *self, PyObject *args) { self->py_modules->reregister_mds_perf_queries(); Py_RETURN_NONE; } static PyObject* ceph_get_mds_perf_counters(BaseMgrModule *self, PyObject *args) { MetricQueryID query_id; if (!PyArg_ParseTuple(args, "i:ceph_get_mds_perf_counters", &query_id)) { derr << "Invalid args!" << dendl; return nullptr; } return self->py_modules->get_mds_perf_counters(query_id); } static PyObject* ceph_is_authorized(BaseMgrModule *self, PyObject *args) { PyObject *args_dict = NULL; if (!PyArg_ParseTuple(args, "O:ceph_is_authorized", &args_dict)) { return nullptr; } if (!PyDict_Check(args_dict)) { derr << __func__ << " arg not a dict" << dendl; Py_RETURN_FALSE; } std::map<std::string, std::string> arguments; PyObject *args_list = PyDict_Items(args_dict); for (int i = 0; i < PyList_Size(args_list); ++i) { PyObject *kv = PyList_GET_ITEM(args_list, i); char *arg_key = nullptr; char *arg_value = nullptr; if (!PyArg_ParseTuple(kv, "ss:pair", &arg_key, &arg_value)) { derr << __func__ << " dict item " << i << " not a size 2 tuple" << dendl; continue; } arguments[arg_key] = arg_value; } bool r = without_gil([&] { return self->this_module->is_authorized(arguments); }); if (r) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyObject* ceph_register_client(BaseMgrModule *self, PyObject *args) { const char* _name = nullptr; char* addrs = nullptr; int replace = 0; if (!PyArg_ParseTuple(args, "zsp:ceph_register_client", &_name, &addrs, &replace)) { return nullptr; } auto name = _name ? std::string(_name) : std::string(self->this_module->get_name()); without_gil([&] { self->py_modules->register_client(name, addrs, replace); }); Py_RETURN_NONE; } static PyObject* ceph_unregister_client(BaseMgrModule *self, PyObject *args) { const char* _name = nullptr; char* addrs = nullptr; if (!PyArg_ParseTuple(args, "zs:ceph_unregister_client", &_name, &addrs)) { return nullptr; } auto name = _name ? std::string(_name) : std::string(self->this_module->get_name()); without_gil([&] { self->py_modules->unregister_client(name, addrs); }); Py_RETURN_NONE; } static PyObject* ceph_get_daemon_health_metrics(BaseMgrModule *self, PyObject *args) { return self->py_modules->get_daemon_health_metrics(); } PyMethodDef BaseMgrModule_methods[] = { {"_ceph_get", (PyCFunction)ceph_state_get, METH_VARARGS, "Get a cluster object"}, {"_ceph_get_server", (PyCFunction)ceph_get_server, METH_VARARGS, "Get a server object"}, {"_ceph_get_metadata", (PyCFunction)get_metadata, METH_VARARGS, "Get a service's metadata"}, {"_ceph_get_daemon_status", (PyCFunction)get_daemon_status, METH_VARARGS, "Get a service's status"}, {"_ceph_send_command", (PyCFunction)ceph_send_command, METH_VARARGS, "Send a mon command"}, {"_ceph_set_health_checks", (PyCFunction)ceph_set_health_checks, METH_VARARGS, "Set health checks for this module"}, {"_ceph_get_mgr_id", (PyCFunction)ceph_get_mgr_id, METH_NOARGS, "Get the name of the Mgr daemon where we are running"}, {"_ceph_get_ceph_conf_path", (PyCFunction)ceph_get_ceph_conf_path, METH_NOARGS, "Get path to ceph.conf"}, {"_ceph_get_option", (PyCFunction)ceph_option_get, METH_VARARGS, "Get a native configuration option value"}, {"_ceph_get_foreign_option", (PyCFunction)ceph_foreign_option_get, METH_VARARGS, "Get a native configuration option value for another entity"}, {"_ceph_get_module_option", (PyCFunction)ceph_get_module_option, METH_VARARGS, "Get a module configuration option value"}, {"_ceph_get_store_prefix", (PyCFunction)ceph_store_get_prefix, METH_VARARGS, "Get all KV store values with a given prefix"}, {"_ceph_set_module_option", (PyCFunction)ceph_set_module_option, METH_VARARGS, "Set a module configuration option value"}, {"_ceph_get_store", (PyCFunction)ceph_store_get, METH_VARARGS, "Get a stored field"}, {"_ceph_set_store", (PyCFunction)ceph_store_set, METH_VARARGS, "Set a stored field"}, {"_ceph_get_counter", (PyCFunction)get_counter, METH_VARARGS, "Get a performance counter"}, {"_ceph_get_latest_counter", (PyCFunction)get_latest_counter, METH_VARARGS, "Get the latest performance counter"}, {"_ceph_get_perf_schema", (PyCFunction)get_perf_schema, METH_VARARGS, "Get the performance counter schema"}, {"_ceph_get_rocksdb_version", (PyCFunction)ceph_get_rocksdb_version, METH_NOARGS, "Get the current RocksDB version number"}, {"_ceph_log", (PyCFunction)ceph_log, METH_VARARGS, "Emit a (local) log message"}, {"_ceph_cluster_log", (PyCFunction)ceph_cluster_log, METH_VARARGS, "Emit a cluster log message"}, {"_ceph_get_version", (PyCFunction)ceph_get_version, METH_NOARGS, "Get the ceph version of this process"}, {"_ceph_get_release_name", (PyCFunction)ceph_get_release_name, METH_NOARGS, "Get the ceph release name of this process"}, {"_ceph_lookup_release_name", (PyCFunction)ceph_lookup_release_name, METH_VARARGS, "Get the ceph release name for a given major number"}, {"_ceph_get_context", (PyCFunction)ceph_get_context, METH_NOARGS, "Get a CephContext* in a python capsule"}, {"_ceph_get_osdmap", (PyCFunction)ceph_get_osdmap, METH_NOARGS, "Get an OSDMap* in a python capsule"}, {"_ceph_set_uri", (PyCFunction)ceph_set_uri, METH_VARARGS, "Advertize a service URI served by this module"}, {"_ceph_set_device_wear_level", (PyCFunction)ceph_set_wear_level, METH_VARARGS, "Set device wear_level value"}, {"_ceph_have_mon_connection", (PyCFunction)ceph_have_mon_connection, METH_NOARGS, "Find out whether this mgr daemon currently has " "a connection to a monitor"}, {"_ceph_update_progress_event", (PyCFunction)ceph_update_progress_event, METH_VARARGS, "Update status of a progress event"}, {"_ceph_complete_progress_event", (PyCFunction)ceph_complete_progress_event, METH_VARARGS, "Complete a progress event"}, {"_ceph_clear_all_progress_events", (PyCFunction)ceph_clear_all_progress_events, METH_NOARGS, "Clear all progress events"}, {"_ceph_dispatch_remote", (PyCFunction)ceph_dispatch_remote, METH_VARARGS, "Dispatch a call to another module"}, {"_ceph_add_osd_perf_query", (PyCFunction)ceph_add_osd_perf_query, METH_VARARGS, "Add an osd perf query"}, {"_ceph_remove_osd_perf_query", (PyCFunction)ceph_remove_osd_perf_query, METH_VARARGS, "Remove an osd perf query"}, {"_ceph_get_osd_perf_counters", (PyCFunction)ceph_get_osd_perf_counters, METH_VARARGS, "Get osd perf counters"}, {"_ceph_add_mds_perf_query", (PyCFunction)ceph_add_mds_perf_query, METH_VARARGS, "Add an mds perf query"}, {"_ceph_remove_mds_perf_query", (PyCFunction)ceph_remove_mds_perf_query, METH_VARARGS, "Remove an mds perf query"}, {"_ceph_reregister_mds_perf_queries", (PyCFunction)ceph_reregister_mds_perf_queries, METH_NOARGS, "Re-register mds perf queries"}, {"_ceph_get_mds_perf_counters", (PyCFunction)ceph_get_mds_perf_counters, METH_VARARGS, "Get mds perf counters"}, {"_ceph_is_authorized", (PyCFunction)ceph_is_authorized, METH_VARARGS, "Verify the current session caps are valid"}, {"_ceph_register_client", (PyCFunction)ceph_register_client, METH_VARARGS, "Register RADOS instance for potential blocklisting"}, {"_ceph_unregister_client", (PyCFunction)ceph_unregister_client, METH_VARARGS, "Unregister RADOS instance for potential blocklisting"}, {"_ceph_get_daemon_health_metrics", (PyCFunction)ceph_get_daemon_health_metrics, METH_VARARGS, "Get health metrics for all daemons"}, {NULL, NULL, 0, NULL} }; static PyObject * BaseMgrModule_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { BaseMgrModule *self; self = (BaseMgrModule *)type->tp_alloc(type, 0); return (PyObject *)self; } static int BaseMgrModule_init(BaseMgrModule *self, PyObject *args, PyObject *kwds) { PyObject *py_modules_capsule = nullptr; PyObject *this_module_capsule = nullptr; static const char *kwlist[] = {"py_modules", "this_module", NULL}; if (! PyArg_ParseTupleAndKeywords(args, kwds, "OO", const_cast<char**>(kwlist), &py_modules_capsule, &this_module_capsule)) { return -1; } self->py_modules = static_cast<ActivePyModules*>(PyCapsule_GetPointer( py_modules_capsule, nullptr)); ceph_assert(self->py_modules); self->this_module = static_cast<ActivePyModule*>(PyCapsule_GetPointer( this_module_capsule, nullptr)); ceph_assert(self->this_module); return 0; } PyTypeObject BaseMgrModuleType = { PyVarObject_HEAD_INIT(NULL, 0) "ceph_module.BaseMgrModule", /* tp_name */ sizeof(BaseMgrModule), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "ceph-mgr Python Plugin", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ BaseMgrModule_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)BaseMgrModule_init, /* tp_init */ 0, /* tp_alloc */ BaseMgrModule_new, /* tp_new */ };
52,834
31.314985
89
cc
null
ceph-main/src/mgr/BaseMgrModule.h
#pragma once #include "Python.h" extern PyTypeObject BaseMgrModuleType;
76
8.625
38
h
null
ceph-main/src/mgr/BaseMgrStandbyModule.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 John Spray <[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 "BaseMgrStandbyModule.h" #include "StandbyPyModules.h" #include "PyFormatter.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr using std::string; typedef struct { PyObject_HEAD StandbyPyModule *this_module; } BaseMgrStandbyModule; static PyObject * BaseMgrStandbyModule_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { BaseMgrStandbyModule *self; self = (BaseMgrStandbyModule *)type->tp_alloc(type, 0); return (PyObject *)self; } static int BaseMgrStandbyModule_init(BaseMgrStandbyModule *self, PyObject *args, PyObject *kwds) { PyObject *this_module_capsule = nullptr; static const char *kwlist[] = {"this_module", NULL}; if (! PyArg_ParseTupleAndKeywords(args, kwds, "O", const_cast<char**>(kwlist), &this_module_capsule)) { return -1; } self->this_module = static_cast<StandbyPyModule*>(PyCapsule_GetPointer( this_module_capsule, nullptr)); ceph_assert(self->this_module); return 0; } static PyObject* ceph_get_mgr_id(BaseMgrStandbyModule *self, PyObject *args) { return PyUnicode_FromString(g_conf()->name.get_id().c_str()); } static PyObject* ceph_get_module_option(BaseMgrStandbyModule *self, PyObject *args) { char *what = nullptr; char *prefix = nullptr; if (!PyArg_ParseTuple(args, "s|s:ceph_get_module_option", &what, &prefix)) { derr << "Invalid args!" << dendl; return nullptr; } PyThreadState *tstate = PyEval_SaveThread(); std::string final_key; std::string value; bool found = false; if (prefix) { final_key = std::string(prefix) + "/" + what; found = self->this_module->get_config(final_key, &value); } if (!found) { final_key = what; found = self->this_module->get_config(final_key, &value); } PyEval_RestoreThread(tstate); if (found) { dout(10) << __func__ << " " << final_key << " found: " << value << dendl; return self->this_module->py_module->get_typed_option_value(what, value); } else { if (prefix) { dout(4) << __func__ << " [" << prefix << "/]" << what << " not found " << dendl; } else { dout(4) << __func__ << " " << what << " not found " << dendl; } Py_RETURN_NONE; } } static PyObject* ceph_option_get(BaseMgrStandbyModule *self, PyObject *args) { char *what = nullptr; if (!PyArg_ParseTuple(args, "s:ceph_option_get", &what)) { derr << "Invalid args!" << dendl; return nullptr; } std::string value; int r = g_conf().get_val(string(what), &value); if (r >= 0) { dout(10) << "ceph_option_get " << what << " found: " << value << dendl; return PyUnicode_FromString(value.c_str()); } else { dout(4) << "ceph_option_get " << what << " not found " << dendl; Py_RETURN_NONE; } } static PyObject* ceph_store_get(BaseMgrStandbyModule *self, PyObject *args) { char *what = nullptr; if (!PyArg_ParseTuple(args, "s:ceph_store_get", &what)) { derr << "Invalid args!" << dendl; return nullptr; } // Drop GIL for blocking mon command execution PyThreadState *tstate = PyEval_SaveThread(); std::string value; bool found = self->this_module->get_store(what, &value); PyEval_RestoreThread(tstate); if (found) { dout(10) << "ceph_store_get " << what << " found: " << value.c_str() << dendl; return PyUnicode_FromString(value.c_str()); } else { dout(4) << "ceph_store_get " << what << " not found " << dendl; Py_RETURN_NONE; } } static PyObject* ceph_get_active_uri(BaseMgrStandbyModule *self, PyObject *args) { return PyUnicode_FromString(self->this_module->get_active_uri().c_str()); } static PyObject* ceph_log(BaseMgrStandbyModule *self, PyObject *args) { char *record = nullptr; if (!PyArg_ParseTuple(args, "s:log", &record)) { return nullptr; } ceph_assert(self->this_module); self->this_module->log(record); Py_RETURN_NONE; } static PyObject* ceph_standby_state_get(BaseMgrStandbyModule *self, PyObject *args) { char *whatc = NULL; if (!PyArg_ParseTuple(args, "s:ceph_state_get", &whatc)) { return NULL; } std::string what(whatc); PyFormatter f; // Drop the GIL, as most of the following blocks will block on // a mutex -- they are all responsible for re-taking the GIL before // touching the PyFormatter instance or returning from the function. without_gil_t no_gil; if (what == "mgr_ips") { entity_addrvec_t myaddrs = self->this_module->get_myaddrs(); with_gil_t with_gil{no_gil}; f.open_array_section("ips"); std::set<std::string> did; for (auto& i : myaddrs.v) { std::string ip = i.ip_only_to_str(); if (auto [where, inserted] = did.insert(ip); inserted) { f.dump_string("ip", ip); } } f.close_section(); return f.get(); } else { derr << "Python module requested unknown data '" << what << "'" << dendl; with_gil_t with_gil{no_gil}; Py_RETURN_NONE; } } PyMethodDef BaseMgrStandbyModule_methods[] = { {"_ceph_get", (PyCFunction)ceph_standby_state_get, METH_VARARGS, "Get a cluster object (standby)"}, {"_ceph_get_mgr_id", (PyCFunction)ceph_get_mgr_id, METH_NOARGS, "Get the name of the Mgr daemon where we are running"}, {"_ceph_get_module_option", (PyCFunction)ceph_get_module_option, METH_VARARGS, "Get a module configuration option value"}, {"_ceph_get_option", (PyCFunction)ceph_option_get, METH_VARARGS, "Get a native configuration option value"}, {"_ceph_get_store", (PyCFunction)ceph_store_get, METH_VARARGS, "Get a KV store value"}, {"_ceph_get_active_uri", (PyCFunction)ceph_get_active_uri, METH_NOARGS, "Get the URI of the active instance of this module, if any"}, {"_ceph_log", (PyCFunction)ceph_log, METH_VARARGS, "Emit a log message"}, {NULL, NULL, 0, NULL} }; PyTypeObject BaseMgrStandbyModuleType = { PyVarObject_HEAD_INIT(NULL, 0) "ceph_module.BaseMgrStandbyModule", /* tp_name */ sizeof(BaseMgrStandbyModule), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "ceph-mgr Standby Python Plugin", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ BaseMgrStandbyModule_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)BaseMgrStandbyModule_init, /* tp_init */ 0, /* tp_alloc */ BaseMgrStandbyModule_new, /* tp_new */ };
8,136
28.915441
85
cc
null
ceph-main/src/mgr/BaseMgrStandbyModule.h
#pragma once #include <Python.h> extern PyTypeObject BaseMgrStandbyModuleType;
82
10.857143
45
h
null
ceph-main/src/mgr/ClusterState.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 John Spray <[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 "messages/MMgrDigest.h" #include "messages/MMonMgrReport.h" #include "messages/MPGStats.h" #include "mgr/ClusterState.h" #include <time.h> #include <boost/range/adaptor/reversed.hpp> #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr " << __func__ << " " using std::ostream; using std::set; using std::string; using std::stringstream; ClusterState::ClusterState( MonClient *monc_, Objecter *objecter_, const MgrMap& mgrmap) : monc(monc_), objecter(objecter_), mgr_map(mgrmap), asok_hook(NULL) {} void ClusterState::set_objecter(Objecter *objecter_) { std::lock_guard l(lock); objecter = objecter_; } void ClusterState::set_fsmap(FSMap const &new_fsmap) { std::lock_guard l(lock); fsmap = new_fsmap; } void ClusterState::set_mgr_map(MgrMap const &new_mgrmap) { std::lock_guard l(lock); mgr_map = new_mgrmap; } void ClusterState::set_service_map(ServiceMap const &new_service_map) { std::lock_guard l(lock); servicemap = new_service_map; } void ClusterState::load_digest(MMgrDigest *m) { std::lock_guard l(lock); health_json = std::move(m->health_json); mon_status_json = std::move(m->mon_status_json); } void ClusterState::ingest_pgstats(ref_t<MPGStats> stats) { std::lock_guard l(lock); const int from = stats->get_orig_source().num(); bool is_in = with_osdmap([from](const OSDMap& osdmap) { return osdmap.is_in(from); }); if (is_in) { pending_inc.update_stat(from, std::move(stats->osd_stat)); } else { osd_stat_t empty_stat; empty_stat.seq = stats->osd_stat.seq; pending_inc.update_stat(from, std::move(empty_stat)); } for (auto p : stats->pg_stat) { pg_t pgid = p.first; const auto &pg_stats = p.second; // In case we're hearing about a PG that according to last // OSDMap update should not exist auto r = existing_pools.find(pgid.pool()); if (r == existing_pools.end()) { dout(15) << " got " << pgid << " reported at " << pg_stats.reported_epoch << ":" << pg_stats.reported_seq << " state " << pg_state_string(pg_stats.state) << " but pool not in " << existing_pools << dendl; continue; } if (pgid.ps() >= r->second) { dout(15) << " got " << pgid << " reported at " << pg_stats.reported_epoch << ":" << pg_stats.reported_seq << " state " << pg_state_string(pg_stats.state) << " but > pg_num " << r->second << dendl; continue; } // In case we already heard about more recent stats from this PG // from another OSD const auto q = pg_map.pg_stat.find(pgid); if (q != pg_map.pg_stat.end() && q->second.get_version_pair() > pg_stats.get_version_pair()) { dout(15) << " had " << pgid << " from " << q->second.reported_epoch << ":" << q->second.reported_seq << dendl; continue; } pending_inc.pg_stat_updates[pgid] = pg_stats; } for (auto p : stats->pool_stat) { pending_inc.pool_statfs_updates[std::make_pair(p.first, from)] = p.second; } } void ClusterState::update_delta_stats() { pending_inc.stamp = ceph_clock_now(); pending_inc.version = pg_map.version + 1; // to make apply_incremental happy dout(10) << " v" << pending_inc.version << dendl; dout(30) << " pg_map before:\n"; JSONFormatter jf(true); jf.dump_object("pg_map", pg_map); jf.flush(*_dout); *_dout << dendl; dout(30) << " incremental:\n"; JSONFormatter jf(true); jf.dump_object("pending_inc", pending_inc); jf.flush(*_dout); *_dout << dendl; pg_map.apply_incremental(g_ceph_context, pending_inc); pending_inc = PGMap::Incremental(); } void ClusterState::notify_osdmap(const OSDMap &osd_map) { assert(ceph_mutex_is_locked(lock)); pending_inc.stamp = ceph_clock_now(); pending_inc.version = pg_map.version + 1; // to make apply_incremental happy dout(10) << " v" << pending_inc.version << dendl; PGMapUpdater::check_osd_map(g_ceph_context, osd_map, pg_map, &pending_inc); // update our list of pools that exist, so that we can filter pg_map updates // in synchrony with this OSDMap. existing_pools.clear(); for (auto& p : osd_map.get_pools()) { existing_pools[p.first] = p.second.get_pg_num(); } // brute force this for now (don't bother being clever by only // checking osds that went up/down) set<int> need_check_down_pg_osds; PGMapUpdater::check_down_pgs(osd_map, pg_map, true, need_check_down_pg_osds, &pending_inc); dout(30) << " pg_map before:\n"; JSONFormatter jf(true); jf.dump_object("pg_map", pg_map); jf.flush(*_dout); *_dout << dendl; dout(30) << " incremental:\n"; JSONFormatter jf(true); jf.dump_object("pending_inc", pending_inc); jf.flush(*_dout); *_dout << dendl; pg_map.apply_incremental(g_ceph_context, pending_inc); pending_inc = PGMap::Incremental(); // TODO: Complete the separation of PG state handling so // that a cut-down set of functionality remains in PGMonitor // while the full-blown PGMap lives only here. } class ClusterSocketHook : public AdminSocketHook { ClusterState *cluster_state; public: explicit ClusterSocketHook(ClusterState *o) : cluster_state(o) {} int call(std::string_view admin_command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& errss, bufferlist& out) override { stringstream outss; int r = 0; try { r = cluster_state->asok_command(admin_command, cmdmap, f, outss); out.append(outss); } catch (const TOPNSPC::common::bad_cmd_get& e) { errss << e.what(); r = -EINVAL; } return r; } }; void ClusterState::final_init() { AdminSocket *admin_socket = g_ceph_context->get_admin_socket(); asok_hook = new ClusterSocketHook(this); int r = admin_socket->register_command( "dump_osd_network name=value,type=CephInt,req=false", asok_hook, "Dump osd heartbeat network ping times"); ceph_assert(r == 0); } void ClusterState::shutdown() { // unregister commands g_ceph_context->get_admin_socket()->unregister_commands(asok_hook); delete asok_hook; asok_hook = NULL; } bool ClusterState::asok_command( std::string_view admin_command, const cmdmap_t& cmdmap, Formatter *f, ostream& ss) { std::lock_guard l(lock); if (admin_command == "dump_osd_network") { int64_t value = 0; // Default to health warning level if nothing specified if (!(TOPNSPC::common::cmd_getval(cmdmap, "value", value))) { // Convert milliseconds to microseconds value = static_cast<int64_t>(g_ceph_context->_conf.get_val<double>("mon_warn_on_slow_ping_time")) * 1000; if (value == 0) { double ratio = g_conf().get_val<double>("mon_warn_on_slow_ping_ratio"); value = g_conf().get_val<int64_t>("osd_heartbeat_grace"); value *= 1000000 * ratio; // Seconds of grace to microseconds at ratio } } else { // Convert user input to microseconds value *= 1000; } if (value < 0) value = 0; struct mgr_ping_time_t { uint32_t pingtime; int from; int to; bool back; std::array<uint32_t,3> times; std::array<uint32_t,3> min; std::array<uint32_t,3> max; uint32_t last; uint32_t last_update; bool operator<(const mgr_ping_time_t& rhs) const { if (pingtime < rhs.pingtime) return true; if (pingtime > rhs.pingtime) return false; if (from < rhs.from) return true; if (from > rhs.from) return false; if (to < rhs.to) return true; if (to > rhs.to) return false; return back; } }; set<mgr_ping_time_t> sorted; utime_t now = ceph_clock_now(); for (auto i : pg_map.osd_stat) { for (auto j : i.second.hb_pingtime) { if (j.second.last_update == 0) continue; auto stale_time = g_ceph_context->_conf.get_val<int64_t>("osd_mon_heartbeat_stat_stale"); if (now.sec() - j.second.last_update > stale_time) { dout(20) << __func__ << " time out heartbeat for osd " << i.first << " last_update " << j.second.last_update << dendl; continue; } mgr_ping_time_t item; item.pingtime = std::max(j.second.back_pingtime[0], j.second.back_pingtime[1]); item.pingtime = std::max(item.pingtime, j.second.back_pingtime[2]); if (!value || item.pingtime >= value) { item.from = i.first; item.to = j.first; item.times[0] = j.second.back_pingtime[0]; item.times[1] = j.second.back_pingtime[1]; item.times[2] = j.second.back_pingtime[2]; item.min[0] = j.second.back_min[0]; item.min[1] = j.second.back_min[1]; item.min[2] = j.second.back_min[2]; item.max[0] = j.second.back_max[0]; item.max[1] = j.second.back_max[1]; item.max[2] = j.second.back_max[2]; item.last = j.second.back_last; item.back = true; item.last_update = j.second.last_update; sorted.emplace(item); } if (j.second.front_last == 0) continue; item.pingtime = std::max(j.second.front_pingtime[0], j.second.front_pingtime[1]); item.pingtime = std::max(item.pingtime, j.second.front_pingtime[2]); if (!value || item.pingtime >= value) { item.from = i.first; item.to = j.first; item.times[0] = j.second.front_pingtime[0]; item.times[1] = j.second.front_pingtime[1]; item.times[2] = j.second.front_pingtime[2]; item.min[0] = j.second.front_min[0]; item.min[1] = j.second.front_min[1]; item.min[2] = j.second.front_min[2]; item.max[0] = j.second.front_max[0]; item.max[1] = j.second.front_max[1]; item.max[2] = j.second.front_max[2]; item.last = j.second.front_last; item.back = false; item.last_update = j.second.last_update; sorted.emplace(item); } } } // Network ping times (1min 5min 15min) f->open_object_section("network_ping_times"); f->dump_int("threshold", value / 1000); f->open_array_section("entries"); for (auto &sitem : boost::adaptors::reverse(sorted)) { ceph_assert(!value || sitem.pingtime >= value); f->open_object_section("entry"); const time_t lu(sitem.last_update); char buffer[26]; string lustr(ctime_r(&lu, buffer)); lustr.pop_back(); // Remove trailing \n auto stale = g_ceph_context->_conf.get_val<int64_t>("osd_heartbeat_stale"); f->dump_string("last update", lustr); f->dump_bool("stale", ceph_clock_now().sec() - sitem.last_update > stale); f->dump_int("from osd", sitem.from); f->dump_int("to osd", sitem.to); f->dump_string("interface", (sitem.back ? "back" : "front")); f->open_object_section("average"); f->dump_format_unquoted("1min", "%s", fixed_u_to_string(sitem.times[0],3).c_str()); f->dump_format_unquoted("5min", "%s", fixed_u_to_string(sitem.times[1],3).c_str()); f->dump_format_unquoted("15min", "%s", fixed_u_to_string(sitem.times[2],3).c_str()); f->close_section(); // average f->open_object_section("min"); f->dump_format_unquoted("1min", "%s", fixed_u_to_string(sitem.min[0],3).c_str()); f->dump_format_unquoted("5min", "%s", fixed_u_to_string(sitem.min[1],3).c_str()); f->dump_format_unquoted("15min", "%s", fixed_u_to_string(sitem.min[2],3).c_str()); f->close_section(); // min f->open_object_section("max"); f->dump_format_unquoted("1min", "%s", fixed_u_to_string(sitem.max[0],3).c_str()); f->dump_format_unquoted("5min", "%s", fixed_u_to_string(sitem.max[1],3).c_str()); f->dump_format_unquoted("15min", "%s", fixed_u_to_string(sitem.max[2],3).c_str()); f->close_section(); // max f->dump_format_unquoted("last", "%s", fixed_u_to_string(sitem.last,3).c_str()); f->close_section(); // entry } f->close_section(); // entries f->close_section(); // network_ping_times } else { ceph_abort_msg("broken asok registration"); } return true; }
12,421
30.688776
111
cc
null
ceph-main/src/mgr/ClusterState.h
// -*- 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 John Spray <[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. */ #ifndef CLUSTER_STATE_H_ #define CLUSTER_STATE_H_ #include "mds/FSMap.h" #include "mon/MgrMap.h" #include "common/ceph_mutex.h" #include "osdc/Objecter.h" #include "mon/MonClient.h" #include "mon/PGMap.h" #include "mgr/ServiceMap.h" class MMgrDigest; class MMonMgrReport; class MPGStats; /** * Cluster-scope state (things like cluster maps) as opposed * to daemon-level state (things like perf counters and smart) */ class ClusterState { protected: MonClient *monc; Objecter *objecter; FSMap fsmap; ServiceMap servicemap; mutable ceph::mutex lock = ceph::make_mutex("ClusterState"); MgrMap mgr_map; std::map<int64_t,unsigned> existing_pools; ///< pools that exist, and pg_num, as of PGMap epoch PGMap pg_map; PGMap::Incremental pending_inc; bufferlist health_json; bufferlist mon_status_json; class ClusterSocketHook *asok_hook; public: void load_digest(MMgrDigest *m); void ingest_pgstats(ceph::ref_t<MPGStats> stats); void update_delta_stats(); ClusterState(MonClient *monc_, Objecter *objecter_, const MgrMap& mgrmap); void set_objecter(Objecter *objecter_); void set_fsmap(FSMap const &new_fsmap); void set_mgr_map(MgrMap const &new_mgrmap); void set_service_map(ServiceMap const &new_service_map); void notify_osdmap(const OSDMap &osd_map); bool have_fsmap() const { std::lock_guard l(lock); return fsmap.get_epoch() > 0; } template<typename Callback, typename...Args> auto with_servicemap(Callback&& cb, Args&&...args) const { std::lock_guard l(lock); return std::forward<Callback>(cb)(servicemap, std::forward<Args>(args)...); } template<typename Callback, typename...Args> auto with_fsmap(Callback&& cb, Args&&...args) const { std::lock_guard l(lock); return std::forward<Callback>(cb)(fsmap, std::forward<Args>(args)...); } template<typename Callback, typename...Args> auto with_mgrmap(Callback&& cb, Args&&...args) const { std::lock_guard l(lock); return std::forward<Callback>(cb)(mgr_map, std::forward<Args>(args)...); } template<typename Callback, typename...Args> auto with_pgmap(Callback&& cb, Args&&...args) const -> decltype(cb(pg_map, std::forward<Args>(args)...)) { std::lock_guard l(lock); return std::forward<Callback>(cb)(pg_map, std::forward<Args>(args)...); } template<typename Callback, typename...Args> auto with_mutable_pgmap(Callback&& cb, Args&&...args) -> decltype(cb(pg_map, std::forward<Args>(args)...)) { std::lock_guard l(lock); return std::forward<Callback>(cb)(pg_map, std::forward<Args>(args)...); } template<typename... Args> auto with_monmap(Args &&... args) const { std::lock_guard l(lock); ceph_assert(monc != nullptr); return monc->with_monmap(std::forward<Args>(args)...); } template<typename... Args> auto with_osdmap(Args &&... args) const -> decltype(objecter->with_osdmap(std::forward<Args>(args)...)) { ceph_assert(objecter != nullptr); return objecter->with_osdmap(std::forward<Args>(args)...); } // call cb(osdmap, pg_map, ...args) with the appropriate locks template <typename Callback, typename ...Args> auto with_osdmap_and_pgmap(Callback&& cb, Args&& ...args) const { ceph_assert(objecter != nullptr); std::lock_guard l(lock); return objecter->with_osdmap( std::forward<Callback>(cb), pg_map, std::forward<Args>(args)...); } template<typename Callback, typename...Args> auto with_health(Callback&& cb, Args&&...args) const { std::lock_guard l(lock); return std::forward<Callback>(cb)(health_json, std::forward<Args>(args)...); } template<typename Callback, typename...Args> auto with_mon_status(Callback&& cb, Args&&...args) const { std::lock_guard l(lock); return std::forward<Callback>(cb)(mon_status_json, std::forward<Args>(args)...); } void final_init(); void shutdown(); bool asok_command(std::string_view admin_command, const cmdmap_t& cmdmap, Formatter *f, std::ostream& ss); }; #endif
4,480
26.323171
97
h
null
ceph-main/src/mgr/DaemonHealthMetric.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <cstdint> #include <ostream> #include "include/denc.h" enum class daemon_metric : uint8_t { SLOW_OPS, PENDING_CREATING_PGS, NONE, }; static inline const char *daemon_metric_name(daemon_metric t) { switch (t) { case daemon_metric::SLOW_OPS: return "SLOW_OPS"; case daemon_metric::PENDING_CREATING_PGS: return "PENDING_CREATING_PGS"; case daemon_metric::NONE: return "NONE"; default: return "???"; } } union daemon_metric_t { struct { uint32_t n1; uint32_t n2; }; uint64_t n; daemon_metric_t(uint32_t x, uint32_t y) : n1(x), n2(y) {} daemon_metric_t(uint64_t x = 0) : n(x) {} }; class DaemonHealthMetric { public: DaemonHealthMetric() = default; DaemonHealthMetric(daemon_metric type_, uint64_t n) : type(type_), value(n) {} DaemonHealthMetric(daemon_metric type_, uint32_t n1, uint32_t n2) : type(type_), value(n1, n2) {} daemon_metric get_type() const { return type; } uint64_t get_n() const { return value.n; } uint32_t get_n1() const { return value.n1; } uint32_t get_n2() const { return value.n2; } DENC(DaemonHealthMetric, v, p) { DENC_START(1, 1, p); denc(v.type, p); denc(v.value.n, p); DENC_FINISH(p); } std::string get_type_name() const { return daemon_metric_name(get_type()); } friend std::ostream& operator<<(std::ostream& out, const DaemonHealthMetric& m) { return out << daemon_metric_name(m.get_type()) << "(" << m.get_n() << "|(" << m.get_n1() << "," << m.get_n2() << "))"; } private: daemon_metric type = daemon_metric::NONE; daemon_metric_t value; }; WRITE_CLASS_DENC(DaemonHealthMetric)
1,782
20.481928
83
h
null
ceph-main/src/mgr/DaemonHealthMetricCollector.cc
#include <fmt/format.h> #include "include/health.h" #include "include/types.h" #include "DaemonHealthMetricCollector.h" namespace { using std::unique_ptr; using std::vector; using std::ostringstream; class SlowOps final : public DaemonHealthMetricCollector { bool _is_relevant(daemon_metric type) const override { return type == daemon_metric::SLOW_OPS; } health_check_t& _get_check(health_check_map_t& cm) const override { return cm.get_or_add("SLOW_OPS", HEALTH_WARN, "", 1); } bool _update(const DaemonKey& daemon, const DaemonHealthMetric& metric) override { auto num_slow = metric.get_n1(); auto blocked_time = metric.get_n2(); value.n1 += num_slow; value.n2 = std::max(value.n2, blocked_time); if (num_slow || blocked_time) { daemons.push_back(daemon); return true; } else { return false; } } void _summarize(health_check_t& check) const override { if (daemons.empty()) { return; } // Note this message format is used in mgr/prometheus, so any change in format // requires a corresponding change in the mgr/prometheus module. ostringstream ss; if (daemons.size() > 1) { if (daemons.size() > 10) { ss << "daemons " << vector<DaemonKey>(daemons.begin(), daemons.begin()+10) << "..." << " have slow ops."; } else { ss << "daemons " << daemons << " have slow ops."; } } else { ss << daemons.front() << " has slow ops"; } check.summary = fmt::format("{} slow ops, oldest one blocked for {} sec, {}", value.n1, value.n2, ss.str()); // No detail } vector<DaemonKey> daemons; }; class PendingPGs final : public DaemonHealthMetricCollector { bool _is_relevant(daemon_metric type) const override { return type == daemon_metric::PENDING_CREATING_PGS; } health_check_t& _get_check(health_check_map_t& cm) const override { return cm.get_or_add("PENDING_CREATING_PGS", HEALTH_WARN, "", 1); } bool _update(const DaemonKey& osd, const DaemonHealthMetric& metric) override { value.n += metric.get_n(); if (metric.get_n()) { osds.push_back(osd); return true; } else { return false; } } void _summarize(health_check_t& check) const override { if (osds.empty()) { return; } check.summary = fmt::format("{} PGs pending on creation", value.n); ostringstream ss; if (osds.size() > 1) { ss << "osds " << osds << " have pending PGs."; } else { ss << osds.front() << " has pending PGs"; } check.detail.push_back(ss.str()); } vector<DaemonKey> osds; }; } // anonymous namespace unique_ptr<DaemonHealthMetricCollector> DaemonHealthMetricCollector::create(daemon_metric m) { switch (m) { case daemon_metric::SLOW_OPS: return std::make_unique<SlowOps>(); case daemon_metric::PENDING_CREATING_PGS: return std::make_unique<PendingPGs>(); default: return {}; } }
3,003
27.339623
82
cc
null
ceph-main/src/mgr/DaemonHealthMetricCollector.h
#pragma once #include <memory> #include <string> #include "DaemonHealthMetric.h" #include "DaemonKey.h" #include "mon/health_check.h" class DaemonHealthMetricCollector { public: static std::unique_ptr<DaemonHealthMetricCollector> create(daemon_metric m); void update(const DaemonKey& daemon, const DaemonHealthMetric& metric) { if (_is_relevant(metric.get_type())) { reported |= _update(daemon, metric); } } void summarize(health_check_map_t& cm) { if (reported) { _summarize(_get_check(cm)); } } virtual ~DaemonHealthMetricCollector() {} private: virtual bool _is_relevant(daemon_metric type) const = 0; virtual health_check_t& _get_check(health_check_map_t& cm) const = 0; virtual bool _update(const DaemonKey& daemon, const DaemonHealthMetric& metric) = 0; virtual void _summarize(health_check_t& check) const = 0; protected: daemon_metric_t value; bool reported = false; };
933
27.30303
86
h
null
ceph-main/src/mgr/DaemonKey.cc
#include "DaemonKey.h" std::pair<DaemonKey, bool> DaemonKey::parse(const std::string& s) { auto p = s.find('.'); if (p == s.npos) { return {{}, false}; } else { return {DaemonKey{s.substr(0, p), s.substr(p + 1)}, true}; } } bool operator<(const DaemonKey& lhs, const DaemonKey& rhs) { if (int cmp = lhs.type.compare(rhs.type); cmp < 0) { return true; } else if (cmp > 0) { return false; } else { return lhs.name < rhs.name; } } std::ostream& operator<<(std::ostream& os, const DaemonKey& key) { return os << key.type << '.' << key.name; } namespace ceph { std::string to_string(const DaemonKey& key) { return key.type + '.' + key.name; } }
685
18.055556
65
cc
null
ceph-main/src/mgr/DaemonKey.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <ostream> #include <string> #include <utility> // Unique reference to a daemon within a cluster struct DaemonKey { std::string type; // service type, like "osd", "mon" std::string name; // service id / name, like "1", "a" static std::pair<DaemonKey, bool> parse(const std::string& s); }; bool operator<(const DaemonKey& lhs, const DaemonKey& rhs); std::ostream& operator<<(std::ostream& os, const DaemonKey& key); namespace ceph { std::string to_string(const DaemonKey& key); }
612
23.52
70
h
null
ceph-main/src/mgr/DaemonServer.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 John Spray <[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 "DaemonServer.h" #include <boost/algorithm/string.hpp> #include "mgr/Mgr.h" #include "include/stringify.h" #include "include/str_list.h" #include "auth/RotatingKeyRing.h" #include "json_spirit/json_spirit_writer.h" #include "mgr/mgr_commands.h" #include "mgr/DaemonHealthMetricCollector.h" #include "mgr/OSDPerfMetricCollector.h" #include "mgr/MDSPerfMetricCollector.h" #include "mon/MonCommand.h" #include "messages/MMgrOpen.h" #include "messages/MMgrUpdate.h" #include "messages/MMgrClose.h" #include "messages/MMgrConfigure.h" #include "messages/MMonMgrReport.h" #include "messages/MCommand.h" #include "messages/MCommandReply.h" #include "messages/MMgrCommand.h" #include "messages/MMgrCommandReply.h" #include "messages/MPGStats.h" #include "messages/MOSDScrub2.h" #include "messages/MOSDForceRecovery.h" #include "common/errno.h" #include "common/pick_address.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr.server " << __func__ << " " using namespace TOPNSPC::common; using std::list; using std::ostringstream; using std::string; using std::stringstream; using std::vector; using std::unique_ptr; namespace { template <typename Map> bool map_compare(Map const &lhs, Map const &rhs) { return lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin(), [] (auto a, auto b) { return a.first == b.first && a.second == b.second; }); } } DaemonServer::DaemonServer(MonClient *monc_, Finisher &finisher_, DaemonStateIndex &daemon_state_, ClusterState &cluster_state_, PyModuleRegistry &py_modules_, LogChannelRef clog_, LogChannelRef audit_clog_) : Dispatcher(g_ceph_context), client_byte_throttler(new Throttle(g_ceph_context, "mgr_client_bytes", g_conf().get_val<Option::size_t>("mgr_client_bytes"))), client_msg_throttler(new Throttle(g_ceph_context, "mgr_client_messages", g_conf().get_val<uint64_t>("mgr_client_messages"))), osd_byte_throttler(new Throttle(g_ceph_context, "mgr_osd_bytes", g_conf().get_val<Option::size_t>("mgr_osd_bytes"))), osd_msg_throttler(new Throttle(g_ceph_context, "mgr_osd_messsages", g_conf().get_val<uint64_t>("mgr_osd_messages"))), mds_byte_throttler(new Throttle(g_ceph_context, "mgr_mds_bytes", g_conf().get_val<Option::size_t>("mgr_mds_bytes"))), mds_msg_throttler(new Throttle(g_ceph_context, "mgr_mds_messsages", g_conf().get_val<uint64_t>("mgr_mds_messages"))), mon_byte_throttler(new Throttle(g_ceph_context, "mgr_mon_bytes", g_conf().get_val<Option::size_t>("mgr_mon_bytes"))), mon_msg_throttler(new Throttle(g_ceph_context, "mgr_mon_messsages", g_conf().get_val<uint64_t>("mgr_mon_messages"))), msgr(nullptr), monc(monc_), finisher(finisher_), daemon_state(daemon_state_), cluster_state(cluster_state_), py_modules(py_modules_), clog(clog_), audit_clog(audit_clog_), pgmap_ready(false), timer(g_ceph_context, lock), shutting_down(false), tick_event(nullptr), osd_perf_metric_collector_listener(this), osd_perf_metric_collector(osd_perf_metric_collector_listener), mds_perf_metric_collector_listener(this), mds_perf_metric_collector(mds_perf_metric_collector_listener) { g_conf().add_observer(this); } DaemonServer::~DaemonServer() { delete msgr; g_conf().remove_observer(this); } int DaemonServer::init(uint64_t gid, entity_addrvec_t client_addrs) { // Initialize Messenger std::string public_msgr_type = g_conf()->ms_public_type.empty() ? g_conf().get_val<std::string>("ms_type") : g_conf()->ms_public_type; msgr = Messenger::create(g_ceph_context, public_msgr_type, entity_name_t::MGR(gid), "mgr", Messenger::get_random_nonce()); msgr->set_default_policy(Messenger::Policy::stateless_server(0)); msgr->set_auth_client(monc); // throttle clients msgr->set_policy_throttlers(entity_name_t::TYPE_CLIENT, client_byte_throttler.get(), client_msg_throttler.get()); // servers msgr->set_policy_throttlers(entity_name_t::TYPE_OSD, osd_byte_throttler.get(), osd_msg_throttler.get()); msgr->set_policy_throttlers(entity_name_t::TYPE_MDS, mds_byte_throttler.get(), mds_msg_throttler.get()); msgr->set_policy_throttlers(entity_name_t::TYPE_MON, mon_byte_throttler.get(), mon_msg_throttler.get()); entity_addrvec_t addrs; int r = pick_addresses(cct, CEPH_PICK_ADDRESS_PUBLIC, &addrs); if (r < 0) { return r; } dout(20) << __func__ << " will bind to " << addrs << dendl; r = msgr->bindv(addrs); if (r < 0) { derr << "unable to bind mgr to " << addrs << dendl; return r; } msgr->set_myname(entity_name_t::MGR(gid)); msgr->set_addr_unknowns(client_addrs); msgr->start(); msgr->add_dispatcher_tail(this); msgr->set_auth_server(monc); monc->set_handle_authentication_dispatcher(this); started_at = ceph_clock_now(); std::lock_guard l(lock); timer.init(); schedule_tick_locked( g_conf().get_val<std::chrono::seconds>("mgr_tick_period").count()); return 0; } entity_addrvec_t DaemonServer::get_myaddrs() const { return msgr->get_myaddrs(); } int DaemonServer::ms_handle_authentication(Connection *con) { auto s = ceph::make_ref<MgrSession>(cct); con->set_priv(s); s->inst.addr = con->get_peer_addr(); s->entity_name = con->peer_name; dout(10) << __func__ << " new session " << s << " con " << con << " entity " << con->peer_name << " addr " << con->get_peer_addrs() << dendl; AuthCapsInfo &caps_info = con->get_peer_caps_info(); if (caps_info.allow_all) { dout(10) << " session " << s << " " << s->entity_name << " allow_all" << dendl; s->caps.set_allow_all(); } else if (caps_info.caps.length() > 0) { auto p = caps_info.caps.cbegin(); string str; try { decode(str, p); } catch (buffer::error& e) { dout(10) << " session " << s << " " << s->entity_name << " failed to decode caps" << dendl; return -EACCES; } if (!s->caps.parse(str)) { dout(10) << " session " << s << " " << s->entity_name << " failed to parse caps '" << str << "'" << dendl; return -EACCES; } dout(10) << " session " << s << " " << s->entity_name << " has caps " << s->caps << " '" << str << "'" << dendl; } if (con->get_peer_type() == CEPH_ENTITY_TYPE_OSD) { std::lock_guard l(lock); s->osd_id = atoi(s->entity_name.get_id().c_str()); dout(10) << "registering osd." << s->osd_id << " session " << s << " con " << con << dendl; osd_cons[s->osd_id].insert(con); } return 1; } bool DaemonServer::ms_handle_reset(Connection *con) { if (con->get_peer_type() == CEPH_ENTITY_TYPE_OSD) { auto priv = con->get_priv(); auto session = static_cast<MgrSession*>(priv.get()); if (!session) { return false; } std::lock_guard l(lock); dout(10) << "unregistering osd." << session->osd_id << " session " << session << " con " << con << dendl; osd_cons[session->osd_id].erase(con); auto iter = daemon_connections.find(con); if (iter != daemon_connections.end()) { daemon_connections.erase(iter); } } return false; } bool DaemonServer::ms_handle_refused(Connection *con) { // do nothing for now return false; } bool DaemonServer::ms_dispatch2(const ref_t<Message>& m) { // Note that we do *not* take ::lock here, in order to avoid // serializing all message handling. It's up to each handler // to take whatever locks it needs. switch (m->get_type()) { case MSG_PGSTATS: cluster_state.ingest_pgstats(ref_cast<MPGStats>(m)); maybe_ready(m->get_source().num()); return true; case MSG_MGR_REPORT: return handle_report(ref_cast<MMgrReport>(m)); case MSG_MGR_OPEN: return handle_open(ref_cast<MMgrOpen>(m)); case MSG_MGR_UPDATE: return handle_update(ref_cast<MMgrUpdate>(m)); case MSG_MGR_CLOSE: return handle_close(ref_cast<MMgrClose>(m)); case MSG_COMMAND: return handle_command(ref_cast<MCommand>(m)); case MSG_MGR_COMMAND: return handle_command(ref_cast<MMgrCommand>(m)); default: dout(1) << "Unhandled message type " << m->get_type() << dendl; return false; }; } void DaemonServer::dump_pg_ready(ceph::Formatter *f) { f->dump_bool("pg_ready", pgmap_ready.load()); } void DaemonServer::maybe_ready(int32_t osd_id) { if (pgmap_ready.load()) { // Fast path: we don't need to take lock because pgmap_ready // is already set } else { std::lock_guard l(lock); if (reported_osds.find(osd_id) == reported_osds.end()) { dout(4) << "initial report from osd " << osd_id << dendl; reported_osds.insert(osd_id); std::set<int32_t> up_osds; cluster_state.with_osdmap([&](const OSDMap& osdmap) { osdmap.get_up_osds(up_osds); }); std::set<int32_t> unreported_osds; std::set_difference(up_osds.begin(), up_osds.end(), reported_osds.begin(), reported_osds.end(), std::inserter(unreported_osds, unreported_osds.begin())); if (unreported_osds.size() == 0) { dout(4) << "all osds have reported, sending PG state to mon" << dendl; pgmap_ready = true; reported_osds.clear(); // Avoid waiting for next tick send_report(); } else { dout(4) << "still waiting for " << unreported_osds.size() << " osds" " to report in before PGMap is ready" << dendl; } } } } void DaemonServer::tick() { dout(10) << dendl; send_report(); adjust_pgs(); schedule_tick_locked( g_conf().get_val<std::chrono::seconds>("mgr_tick_period").count()); } // Currently modules do not set health checks in response to events delivered to // all modules (e.g. notify) so we do not risk a thundering hurd situation here. // if this pattern emerges in the future, this scheduler could be modified to // fire after all modules have had a chance to set their health checks. void DaemonServer::schedule_tick_locked(double delay_sec) { ceph_assert(ceph_mutex_is_locked_by_me(lock)); if (tick_event) { timer.cancel_event(tick_event); tick_event = nullptr; } // on shutdown start rejecting explicit requests to send reports that may // originate from python land which may still be running. if (shutting_down) return; tick_event = timer.add_event_after(delay_sec, new LambdaContext([this](int r) { tick(); })); } void DaemonServer::schedule_tick(double delay_sec) { std::lock_guard l(lock); schedule_tick_locked(delay_sec); } void DaemonServer::handle_osd_perf_metric_query_updated() { dout(10) << dendl; // Send a fresh MMgrConfigure to all clients, so that they can follow // the new policy for transmitting stats finisher.queue(new LambdaContext([this](int r) { std::lock_guard l(lock); for (auto &c : daemon_connections) { if (c->peer_is_osd()) { _send_configure(c); } } })); } void DaemonServer::handle_mds_perf_metric_query_updated() { dout(10) << dendl; // Send a fresh MMgrConfigure to all clients, so that they can follow // the new policy for transmitting stats finisher.queue(new LambdaContext([this](int r) { std::lock_guard l(lock); for (auto &c : daemon_connections) { if (c->peer_is_mds()) { _send_configure(c); } } })); } void DaemonServer::shutdown() { dout(10) << "begin" << dendl; msgr->shutdown(); msgr->wait(); cluster_state.shutdown(); dout(10) << "done" << dendl; std::lock_guard l(lock); shutting_down = true; timer.shutdown(); } static DaemonKey key_from_service( const std::string& service_name, int peer_type, const std::string& daemon_name) { if (!service_name.empty()) { return DaemonKey{service_name, daemon_name}; } else { return DaemonKey{ceph_entity_type_name(peer_type), daemon_name}; } } void DaemonServer::fetch_missing_metadata(const DaemonKey& key, const entity_addr_t& addr) { if (!daemon_state.is_updating(key) && (key.type == "osd" || key.type == "mds" || key.type == "mon")) { std::ostringstream oss; auto c = new MetadataUpdate(daemon_state, key); if (key.type == "osd") { oss << "{\"prefix\": \"osd metadata\", \"id\": " << key.name<< "}"; } else if (key.type == "mds") { c->set_default("addr", stringify(addr)); oss << "{\"prefix\": \"mds metadata\", \"who\": \"" << key.name << "\"}"; } else if (key.type == "mon") { oss << "{\"prefix\": \"mon metadata\", \"id\": \"" << key.name << "\"}"; } else { ceph_abort(); } monc->start_mon_command({oss.str()}, {}, &c->outbl, &c->outs, c); } } bool DaemonServer::handle_open(const ref_t<MMgrOpen>& m) { std::unique_lock l(lock); DaemonKey key = key_from_service(m->service_name, m->get_connection()->get_peer_type(), m->daemon_name); auto con = m->get_connection(); dout(10) << "from " << key << " " << con->get_peer_addr() << dendl; _send_configure(con); DaemonStatePtr daemon; if (daemon_state.exists(key)) { dout(20) << "updating existing DaemonState for " << key << dendl; daemon = daemon_state.get(key); } if (!daemon) { if (m->service_daemon) { dout(4) << "constructing new DaemonState for " << key << dendl; daemon = std::make_shared<DaemonState>(daemon_state.types); daemon->key = key; daemon->service_daemon = true; daemon_state.insert(daemon); } else { /* A normal Ceph daemon has connected but we are or should be waiting on * metadata for it. Close the session so that it tries to reconnect. */ dout(2) << "ignoring open from " << key << " " << con->get_peer_addr() << "; not ready for session (expect reconnect)" << dendl; con->mark_down(); l.unlock(); fetch_missing_metadata(key, m->get_source_addr()); return true; } } if (daemon) { if (m->service_daemon) { // update the metadata through the daemon state index to // ensure it's kept up-to-date daemon_state.update_metadata(daemon, m->daemon_metadata); } std::lock_guard l(daemon->lock); daemon->perf_counters.clear(); daemon->service_daemon = m->service_daemon; if (m->service_daemon) { daemon->service_status = m->daemon_status; utime_t now = ceph_clock_now(); auto [d, added] = pending_service_map.get_daemon(m->service_name, m->daemon_name); if (added || d->gid != (uint64_t)m->get_source().num()) { dout(10) << "registering " << key << " in pending_service_map" << dendl; d->gid = m->get_source().num(); d->addr = m->get_source_addr(); d->start_epoch = pending_service_map.epoch; d->start_stamp = now; d->metadata = m->daemon_metadata; pending_service_map_dirty = pending_service_map.epoch; } } auto p = m->config_bl.cbegin(); if (p != m->config_bl.end()) { decode(daemon->config, p); decode(daemon->ignored_mon_config, p); dout(20) << " got config " << daemon->config << " ignored " << daemon->ignored_mon_config << dendl; } daemon->config_defaults_bl = m->config_defaults_bl; daemon->config_defaults.clear(); dout(20) << " got config_defaults_bl " << daemon->config_defaults_bl.length() << " bytes" << dendl; } if (con->get_peer_type() != entity_name_t::TYPE_CLIENT && m->service_name.empty()) { // Store in set of the daemon/service connections, i.e. those // connections that require an update in the event of stats // configuration changes. daemon_connections.insert(con); } return true; } bool DaemonServer::handle_update(const ref_t<MMgrUpdate>& m) { DaemonKey key; if (!m->service_name.empty()) { key.type = m->service_name; } else { key.type = ceph_entity_type_name(m->get_connection()->get_peer_type()); } key.name = m->daemon_name; dout(10) << "from " << m->get_connection() << " " << key << dendl; if (m->get_connection()->get_peer_type() == entity_name_t::TYPE_CLIENT && m->service_name.empty()) { // Clients should not be sending us update request dout(10) << "rejecting update request from non-daemon client " << m->daemon_name << dendl; clog->warn() << "rejecting report from non-daemon client " << m->daemon_name << " at " << m->get_connection()->get_peer_addrs(); m->get_connection()->mark_down(); return true; } { std::unique_lock locker(lock); DaemonStatePtr daemon; // Look up the DaemonState if (daemon_state.exists(key)) { dout(20) << "updating existing DaemonState for " << key << dendl; daemon = daemon_state.get(key); if (m->need_metadata_update && !m->daemon_metadata.empty()) { daemon_state.update_metadata(daemon, m->daemon_metadata); } } } return true; } bool DaemonServer::handle_close(const ref_t<MMgrClose>& m) { std::lock_guard l(lock); DaemonKey key = key_from_service(m->service_name, m->get_connection()->get_peer_type(), m->daemon_name); dout(4) << "from " << m->get_connection() << " " << key << dendl; if (daemon_state.exists(key)) { DaemonStatePtr daemon = daemon_state.get(key); daemon_state.rm(key); { std::lock_guard l(daemon->lock); if (daemon->service_daemon) { pending_service_map.rm_daemon(m->service_name, m->daemon_name); pending_service_map_dirty = pending_service_map.epoch; } } } // send same message back as a reply m->get_connection()->send_message2(m); return true; } void DaemonServer::update_task_status( DaemonKey key, const std::map<std::string,std::string>& task_status) { dout(10) << "got task status from " << key << dendl; [[maybe_unused]] auto [daemon, added] = pending_service_map.get_daemon(key.type, key.name); if (daemon->task_status != task_status) { daemon->task_status = task_status; pending_service_map_dirty = pending_service_map.epoch; } } bool DaemonServer::handle_report(const ref_t<MMgrReport>& m) { DaemonKey key; if (!m->service_name.empty()) { key.type = m->service_name; } else { key.type = ceph_entity_type_name(m->get_connection()->get_peer_type()); } key.name = m->daemon_name; dout(10) << "from " << m->get_connection() << " " << key << dendl; if (m->get_connection()->get_peer_type() == entity_name_t::TYPE_CLIENT && m->service_name.empty()) { // Clients should not be sending us stats unless they are declaring // themselves to be a daemon for some service. dout(10) << "rejecting report from non-daemon client " << m->daemon_name << dendl; clog->warn() << "rejecting report from non-daemon client " << m->daemon_name << " at " << m->get_connection()->get_peer_addrs(); m->get_connection()->mark_down(); return true; } { std::unique_lock locker(lock); DaemonStatePtr daemon; // Look up the DaemonState if (daemon = daemon_state.get(key); daemon != nullptr) { dout(20) << "updating existing DaemonState for " << key << dendl; } else { locker.unlock(); // we don't know the hostname at this stage, reject MMgrReport here. dout(5) << "rejecting report from " << key << ", since we do not have its metadata now." << dendl; // issue metadata request in background fetch_missing_metadata(key, m->get_source_addr()); locker.lock(); // kill session auto priv = m->get_connection()->get_priv(); auto session = static_cast<MgrSession*>(priv.get()); if (!session) { return false; } m->get_connection()->mark_down(); dout(10) << "unregistering osd." << session->osd_id << " session " << session << " con " << m->get_connection() << dendl; if (osd_cons.find(session->osd_id) != osd_cons.end()) { osd_cons[session->osd_id].erase(m->get_connection()); } auto iter = daemon_connections.find(m->get_connection()); if (iter != daemon_connections.end()) { daemon_connections.erase(iter); } return false; } // Update the DaemonState ceph_assert(daemon != nullptr); { std::lock_guard l(daemon->lock); auto &daemon_counters = daemon->perf_counters; daemon_counters.update(*m.get()); auto p = m->config_bl.cbegin(); if (p != m->config_bl.end()) { decode(daemon->config, p); decode(daemon->ignored_mon_config, p); dout(20) << " got config " << daemon->config << " ignored " << daemon->ignored_mon_config << dendl; } utime_t now = ceph_clock_now(); if (daemon->service_daemon) { if (m->daemon_status) { daemon->service_status_stamp = now; daemon->service_status = *m->daemon_status; } daemon->last_service_beacon = now; } else if (m->daemon_status) { derr << "got status from non-daemon " << key << dendl; } // update task status if (m->task_status) { update_task_status(key, *m->task_status); daemon->last_service_beacon = now; } if (m->get_connection()->peer_is_osd() || m->get_connection()->peer_is_mon()) { // only OSD and MON send health_checks to me now daemon->daemon_health_metrics = std::move(m->daemon_health_metrics); dout(10) << "daemon_health_metrics " << daemon->daemon_health_metrics << dendl; } } } // if there are any schema updates, notify the python modules /* no users currently if (!m->declare_types.empty() || !m->undeclare_types.empty()) { py_modules.notify_all("perf_schema_update", ceph::to_string(key)); } */ if (m->get_connection()->peer_is_osd()) { osd_perf_metric_collector.process_reports(m->osd_perf_metric_reports); } if (m->metric_report_message) { const MetricReportMessage &message = *m->metric_report_message; boost::apply_visitor(HandlePayloadVisitor(this), message.payload); } return true; } void DaemonServer::_generate_command_map( cmdmap_t& cmdmap, map<string,string> &param_str_map) { for (auto p = cmdmap.begin(); p != cmdmap.end(); ++p) { if (p->first == "prefix") continue; if (p->first == "caps") { vector<string> cv; if (cmd_getval(cmdmap, "caps", cv) && cv.size() % 2 == 0) { for (unsigned i = 0; i < cv.size(); i += 2) { string k = string("caps_") + cv[i]; param_str_map[k] = cv[i + 1]; } continue; } } param_str_map[p->first] = cmd_vartype_stringify(p->second); } } const MonCommand *DaemonServer::_get_mgrcommand( const string &cmd_prefix, const std::vector<MonCommand> &cmds) { const MonCommand *this_cmd = nullptr; for (const auto &cmd : cmds) { if (cmd.cmdstring.compare(0, cmd_prefix.size(), cmd_prefix) == 0) { this_cmd = &cmd; break; } } return this_cmd; } bool DaemonServer::_allowed_command( MgrSession *s, const string &service, const string &module, const string &prefix, const cmdmap_t& cmdmap, const map<string,string>& param_str_map, const MonCommand *this_cmd) { if (s->entity_name.is_mon()) { // mon is all-powerful. even when it is forwarding commands on behalf of // old clients; we expect the mon is validating commands before proxying! return true; } bool cmd_r = this_cmd->requires_perm('r'); bool cmd_w = this_cmd->requires_perm('w'); bool cmd_x = this_cmd->requires_perm('x'); bool capable = s->caps.is_capable( g_ceph_context, s->entity_name, service, module, prefix, param_str_map, cmd_r, cmd_w, cmd_x, s->get_peer_addr()); dout(10) << " " << s->entity_name << " " << (capable ? "" : "not ") << "capable" << dendl; return capable; } /** * The working data for processing an MCommand. This lives in * a class to enable passing it into other threads for processing * outside of the thread/locks that called handle_command. */ class CommandContext { public: ceph::ref_t<MCommand> m_tell; ceph::ref_t<MMgrCommand> m_mgr; const std::vector<std::string>& cmd; ///< ref into m_tell or m_mgr const bufferlist& data; ///< ref into m_tell or m_mgr bufferlist odata; cmdmap_t cmdmap; explicit CommandContext(ceph::ref_t<MCommand> m) : m_tell{std::move(m)}, cmd(m_tell->cmd), data(m_tell->get_data()) { } explicit CommandContext(ceph::ref_t<MMgrCommand> m) : m_mgr{std::move(m)}, cmd(m_mgr->cmd), data(m_mgr->get_data()) { } void reply(int r, const std::stringstream &ss) { reply(r, ss.str()); } void reply(int r, const std::string &rs) { // Let the connection drop as soon as we've sent our response ConnectionRef con = m_tell ? m_tell->get_connection() : m_mgr->get_connection(); if (con) { con->mark_disposable(); } if (r == 0) { dout(20) << "success" << dendl; } else { derr << __func__ << " " << cpp_strerror(r) << " " << rs << dendl; } if (con) { if (m_tell) { MCommandReply *reply = new MCommandReply(r, rs); reply->set_tid(m_tell->get_tid()); reply->set_data(odata); con->send_message(reply); } else { MMgrCommandReply *reply = new MMgrCommandReply(r, rs); reply->set_tid(m_mgr->get_tid()); reply->set_data(odata); con->send_message(reply); } } } }; /** * A context for receiving a bufferlist/error string from a background * function and then calling back to a CommandContext when it's done */ class ReplyOnFinish : public Context { std::shared_ptr<CommandContext> cmdctx; public: bufferlist from_mon; string outs; explicit ReplyOnFinish(const std::shared_ptr<CommandContext> &cmdctx_) : cmdctx(cmdctx_) {} void finish(int r) override { cmdctx->odata.claim_append(from_mon); cmdctx->reply(r, outs); } }; bool DaemonServer::handle_command(const ref_t<MCommand>& m) { std::lock_guard l(lock); auto cmdctx = std::make_shared<CommandContext>(m); try { return _handle_command(cmdctx); } catch (const bad_cmd_get& e) { cmdctx->reply(-EINVAL, e.what()); return true; } } bool DaemonServer::handle_command(const ref_t<MMgrCommand>& m) { std::lock_guard l(lock); auto cmdctx = std::make_shared<CommandContext>(m); try { return _handle_command(cmdctx); } catch (const bad_cmd_get& e) { cmdctx->reply(-EINVAL, e.what()); return true; } } void DaemonServer::log_access_denied( std::shared_ptr<CommandContext>& cmdctx, MgrSession* session, std::stringstream& ss) { dout(1) << " access denied" << dendl; audit_clog->info() << "from='" << session->inst << "' " << "entity='" << session->entity_name << "' " << "cmd=" << cmdctx->cmd << ": access denied"; ss << "access denied: does your client key have mgr caps? " "See http://docs.ceph.com/en/latest/mgr/administrator/" "#client-authentication"; } void DaemonServer::_check_offlines_pgs( const set<int>& osds, const OSDMap& osdmap, const PGMap& pgmap, offline_pg_report *report) { // reset output *report = offline_pg_report(); report->osds = osds; for (const auto& q : pgmap.pg_stat) { set<int32_t> pg_acting; // net acting sets (with no missing if degraded) bool found = false; if (q.second.state == 0) { report->unknown.insert(q.first); continue; } if (q.second.state & PG_STATE_DEGRADED) { for (auto& anm : q.second.avail_no_missing) { if (osds.count(anm.osd)) { found = true; continue; } if (anm.osd != CRUSH_ITEM_NONE) { pg_acting.insert(anm.osd); } } } else { for (auto& a : q.second.acting) { if (osds.count(a)) { found = true; continue; } if (a != CRUSH_ITEM_NONE) { pg_acting.insert(a); } } } if (!found) { continue; } const pg_pool_t *pi = osdmap.get_pg_pool(q.first.pool()); bool dangerous = false; if (!pi) { report->bad_no_pool.insert(q.first); // pool is creating or deleting dangerous = true; } if (!(q.second.state & PG_STATE_ACTIVE)) { report->bad_already_inactive.insert(q.first); dangerous = true; } if (pg_acting.size() < pi->min_size) { report->bad_become_inactive.insert(q.first); dangerous = true; } if (dangerous) { report->not_ok.insert(q.first); } else { report->ok.insert(q.first); if (q.second.state & PG_STATE_DEGRADED) { report->ok_become_more_degraded.insert(q.first); } else { report->ok_become_degraded.insert(q.first); } } } dout(20) << osds << " -> " << report->ok.size() << " ok, " << report->not_ok.size() << " not ok, " << report->unknown.size() << " unknown" << dendl; } void DaemonServer::_maximize_ok_to_stop_set( const set<int>& orig_osds, unsigned max, const OSDMap& osdmap, const PGMap& pgmap, offline_pg_report *out_report) { dout(20) << "orig_osds " << orig_osds << " max " << max << dendl; _check_offlines_pgs(orig_osds, osdmap, pgmap, out_report); if (!out_report->ok_to_stop()) { return; } if (orig_osds.size() >= max) { // already at max return; } // semi-arbitrarily start with the first osd in the set offline_pg_report report; set<int> osds = orig_osds; int parent = *osds.begin(); set<int> children; while (true) { // identify the next parent int r = osdmap.crush->get_immediate_parent_id(parent, &parent); if (r < 0) { return; // just go with what we have so far! } // get candidate additions that are beneath this point in the tree children.clear(); r = osdmap.crush->get_all_children(parent, &children); if (r < 0) { return; // just go with what we have so far! } dout(20) << " parent " << parent << " children " << children << dendl; // try adding in more osds int failed = 0; // how many children we failed to add to our set for (auto o : children) { if (o >= 0 && osdmap.is_up(o) && osds.count(o) == 0) { osds.insert(o); _check_offlines_pgs(osds, osdmap, pgmap, &report); if (!report.ok_to_stop()) { osds.erase(o); ++failed; continue; } *out_report = report; if (osds.size() == max) { dout(20) << " hit max" << dendl; return; // yay, we hit the max } } } if (failed) { // we hit some failures; go with what we have dout(20) << " hit some peer failures" << dendl; return; } } } bool DaemonServer::_handle_command( std::shared_ptr<CommandContext>& cmdctx) { MessageRef m; bool admin_socket_cmd = false; if (cmdctx->m_tell) { m = cmdctx->m_tell; // a blank fsid in MCommand signals a legacy client sending a "mon-mgr" CLI // command. admin_socket_cmd = (cmdctx->m_tell->fsid != uuid_d()); } else { m = cmdctx->m_mgr; } auto priv = m->get_connection()->get_priv(); auto session = static_cast<MgrSession*>(priv.get()); if (!session) { return true; } if (session->inst.name == entity_name_t()) { session->inst.name = m->get_source(); } map<string,string> param_str_map; std::stringstream ss; int r = 0; if (!cmdmap_from_json(cmdctx->cmd, &(cmdctx->cmdmap), ss)) { cmdctx->reply(-EINVAL, ss); return true; } string prefix; cmd_getval(cmdctx->cmdmap, "prefix", prefix); dout(10) << "decoded-size=" << cmdctx->cmdmap.size() << " prefix=" << prefix << dendl; boost::scoped_ptr<Formatter> f; { std::string format; if (boost::algorithm::ends_with(prefix, "_json")) { format = "json"; } else { format = cmd_getval_or<string>(cmdctx->cmdmap, "format", "plain"); } f.reset(Formatter::create(format)); } // this is just for mgr commands - admin socket commands will fall // through and use the admin socket version of // get_command_descriptions if (prefix == "get_command_descriptions" && !admin_socket_cmd) { dout(10) << "reading commands from python modules" << dendl; const auto py_commands = py_modules.get_commands(); int cmdnum = 0; JSONFormatter f; f.open_object_section("command_descriptions"); auto dump_cmd = [&cmdnum, &f, m](const MonCommand &mc){ ostringstream secname; secname << "cmd" << std::setfill('0') << std::setw(3) << cmdnum; dump_cmddesc_to_json(&f, m->get_connection()->get_features(), secname.str(), mc.cmdstring, mc.helpstring, mc.module, mc.req_perms, 0); cmdnum++; }; for (const auto &pyc : py_commands) { dump_cmd(pyc); } for (const auto &mgr_cmd : mgr_commands) { dump_cmd(mgr_cmd); } f.close_section(); // command_descriptions f.flush(cmdctx->odata); cmdctx->reply(0, ss); return true; } // lookup command const MonCommand *mgr_cmd = _get_mgrcommand(prefix, mgr_commands); _generate_command_map(cmdctx->cmdmap, param_str_map); bool is_allowed = false; ModuleCommand py_command; if (admin_socket_cmd) { // admin socket commands require all capabilities is_allowed = session->caps.is_allow_all(); } else if (!mgr_cmd) { // Resolve the command to the name of the module that will // handle it (if the command exists) auto py_commands = py_modules.get_py_commands(); for (const auto &pyc : py_commands) { auto pyc_prefix = cmddesc_get_prefix(pyc.cmdstring); if (pyc_prefix == prefix) { py_command = pyc; break; } } MonCommand pyc = {"", "", "py", py_command.perm}; is_allowed = _allowed_command(session, "py", py_command.module_name, prefix, cmdctx->cmdmap, param_str_map, &pyc); } else { // validate user's permissions for requested command is_allowed = _allowed_command(session, mgr_cmd->module, "", prefix, cmdctx->cmdmap, param_str_map, mgr_cmd); } if (!is_allowed) { log_access_denied(cmdctx, session, ss); cmdctx->reply(-EACCES, ss); return true; } audit_clog->debug() << "from='" << session->inst << "' " << "entity='" << session->entity_name << "' " << "cmd=" << cmdctx->cmd << ": dispatch"; if (admin_socket_cmd) { cct->get_admin_socket()->queue_tell_command(cmdctx->m_tell); return true; } // ---------------- // service map commands if (prefix == "service dump") { if (!f) f.reset(Formatter::create("json-pretty")); cluster_state.with_servicemap([&](const ServiceMap &service_map) { f->dump_object("service_map", service_map); }); f->flush(cmdctx->odata); cmdctx->reply(0, ss); return true; } if (prefix == "service status") { if (!f) f.reset(Formatter::create("json-pretty")); // only include state from services that are in the persisted service map f->open_object_section("service_status"); for (auto& [type, service] : pending_service_map.services) { if (ServiceMap::is_normal_ceph_entity(type)) { continue; } f->open_object_section(type.c_str()); for (auto& q : service.daemons) { f->open_object_section(q.first.c_str()); DaemonKey key{type, q.first}; ceph_assert(daemon_state.exists(key)); auto daemon = daemon_state.get(key); std::lock_guard l(daemon->lock); f->dump_stream("status_stamp") << daemon->service_status_stamp; f->dump_stream("last_beacon") << daemon->last_service_beacon; f->open_object_section("status"); for (auto& r : daemon->service_status) { f->dump_string(r.first.c_str(), r.second); } f->close_section(); f->close_section(); } f->close_section(); } f->close_section(); f->flush(cmdctx->odata); cmdctx->reply(0, ss); return true; } if (prefix == "config set") { std::string key; std::string val; cmd_getval(cmdctx->cmdmap, "key", key); cmd_getval(cmdctx->cmdmap, "value", val); r = cct->_conf.set_val(key, val, &ss); if (r == 0) { cct->_conf.apply_changes(nullptr); } cmdctx->reply(0, ss); return true; } // ----------- // PG commands if (prefix == "pg scrub" || prefix == "pg repair" || prefix == "pg deep-scrub") { string scrubop = prefix.substr(3, string::npos); pg_t pgid; spg_t spgid; string pgidstr; cmd_getval(cmdctx->cmdmap, "pgid", pgidstr); if (!pgid.parse(pgidstr.c_str())) { ss << "invalid pgid '" << pgidstr << "'"; cmdctx->reply(-EINVAL, ss); return true; } bool pg_exists = false; cluster_state.with_osdmap([&](const OSDMap& osdmap) { pg_exists = osdmap.pg_exists(pgid); }); if (!pg_exists) { ss << "pg " << pgid << " does not exist"; cmdctx->reply(-ENOENT, ss); return true; } int acting_primary = -1; epoch_t epoch; cluster_state.with_osdmap([&](const OSDMap& osdmap) { epoch = osdmap.get_epoch(); osdmap.get_primary_shard(pgid, &acting_primary, &spgid); }); if (acting_primary == -1) { ss << "pg " << pgid << " has no primary osd"; cmdctx->reply(-EAGAIN, ss); return true; } auto p = osd_cons.find(acting_primary); if (p == osd_cons.end()) { ss << "pg " << pgid << " primary osd." << acting_primary << " is not currently connected"; cmdctx->reply(-EAGAIN, ss); return true; } for (auto& con : p->second) { assert(HAVE_FEATURE(con->get_features(), SERVER_OCTOPUS)); vector<spg_t> pgs = { spgid }; con->send_message(new MOSDScrub2(monc->get_fsid(), epoch, pgs, scrubop == "repair", scrubop == "deep-scrub")); } ss << "instructing pg " << spgid << " on osd." << acting_primary << " to " << scrubop; cmdctx->reply(0, ss); return true; } else if (prefix == "osd scrub" || prefix == "osd deep-scrub" || prefix == "osd repair") { string whostr; cmd_getval(cmdctx->cmdmap, "who", whostr); vector<string> pvec; get_str_vec(prefix, pvec); set<int> osds; if (whostr == "*" || whostr == "all" || whostr == "any") { cluster_state.with_osdmap([&](const OSDMap& osdmap) { for (int i = 0; i < osdmap.get_max_osd(); i++) if (osdmap.is_up(i)) { osds.insert(i); } }); } else { long osd = parse_osd_id(whostr.c_str(), &ss); if (osd < 0) { ss << "invalid osd '" << whostr << "'"; cmdctx->reply(-EINVAL, ss); return true; } cluster_state.with_osdmap([&](const OSDMap& osdmap) { if (osdmap.is_up(osd)) { osds.insert(osd); } }); if (osds.empty()) { ss << "osd." << osd << " is not up"; cmdctx->reply(-EAGAIN, ss); return true; } } set<int> sent_osds, failed_osds; for (auto osd : osds) { vector<spg_t> spgs; epoch_t epoch; cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pgmap) { epoch = osdmap.get_epoch(); auto p = pgmap.pg_by_osd.find(osd); if (p != pgmap.pg_by_osd.end()) { for (auto pgid : p->second) { int primary; spg_t spg; osdmap.get_primary_shard(pgid, &primary, &spg); if (primary == osd) { spgs.push_back(spg); } } } }); auto p = osd_cons.find(osd); if (p == osd_cons.end()) { failed_osds.insert(osd); } else { sent_osds.insert(osd); for (auto& con : p->second) { con->send_message(new MOSDScrub2(monc->get_fsid(), epoch, spgs, pvec.back() == "repair", pvec.back() == "deep-scrub")); } } } if (failed_osds.size() == osds.size()) { ss << "failed to instruct osd(s) " << osds << " to " << pvec.back() << " (not connected)"; r = -EAGAIN; } else { ss << "instructed osd(s) " << sent_osds << " to " << pvec.back(); if (!failed_osds.empty()) { ss << "; osd(s) " << failed_osds << " were not connected"; } r = 0; } cmdctx->reply(0, ss); return true; } else if (prefix == "osd pool scrub" || prefix == "osd pool deep-scrub" || prefix == "osd pool repair") { vector<string> pool_names; cmd_getval(cmdctx->cmdmap, "who", pool_names); if (pool_names.empty()) { ss << "must specify one or more pool names"; cmdctx->reply(-EINVAL, ss); return true; } epoch_t epoch; map<int32_t, vector<pg_t>> pgs_by_primary; // legacy map<int32_t, vector<spg_t>> spgs_by_primary; cluster_state.with_osdmap([&](const OSDMap& osdmap) { epoch = osdmap.get_epoch(); for (auto& pool_name : pool_names) { auto pool_id = osdmap.lookup_pg_pool_name(pool_name); if (pool_id < 0) { ss << "unrecognized pool '" << pool_name << "'"; r = -ENOENT; return; } auto pool_pg_num = osdmap.get_pg_num(pool_id); for (int i = 0; i < pool_pg_num; i++) { pg_t pg(i, pool_id); int primary; spg_t spg; auto got = osdmap.get_primary_shard(pg, &primary, &spg); if (!got) continue; pgs_by_primary[primary].push_back(pg); spgs_by_primary[primary].push_back(spg); } } }); if (r < 0) { cmdctx->reply(r, ss); return true; } for (auto& it : spgs_by_primary) { auto primary = it.first; auto p = osd_cons.find(primary); if (p == osd_cons.end()) { ss << "osd." << primary << " is not currently connected"; cmdctx->reply(-EAGAIN, ss); return true; } for (auto& con : p->second) { con->send_message(new MOSDScrub2(monc->get_fsid(), epoch, it.second, prefix == "osd pool repair", prefix == "osd pool deep-scrub")); } } cmdctx->reply(0, ""); return true; } else if (prefix == "osd reweight-by-pg" || prefix == "osd reweight-by-utilization" || prefix == "osd test-reweight-by-pg" || prefix == "osd test-reweight-by-utilization") { bool by_pg = prefix == "osd reweight-by-pg" || prefix == "osd test-reweight-by-pg"; bool dry_run = prefix == "osd test-reweight-by-pg" || prefix == "osd test-reweight-by-utilization"; int64_t oload = cmd_getval_or<int64_t>(cmdctx->cmdmap, "oload", 120); set<int64_t> pools; vector<string> poolnames; cmd_getval(cmdctx->cmdmap, "pools", poolnames); cluster_state.with_osdmap([&](const OSDMap& osdmap) { for (const auto& poolname : poolnames) { int64_t pool = osdmap.lookup_pg_pool_name(poolname); if (pool < 0) { ss << "pool '" << poolname << "' does not exist"; r = -ENOENT; } pools.insert(pool); } }); if (r) { cmdctx->reply(r, ss); return true; } double max_change = g_conf().get_val<double>("mon_reweight_max_change"); cmd_getval(cmdctx->cmdmap, "max_change", max_change); if (max_change <= 0.0) { ss << "max_change " << max_change << " must be positive"; cmdctx->reply(-EINVAL, ss); return true; } int64_t max_osds = g_conf().get_val<int64_t>("mon_reweight_max_osds"); cmd_getval(cmdctx->cmdmap, "max_osds", max_osds); if (max_osds <= 0) { ss << "max_osds " << max_osds << " must be positive"; cmdctx->reply(-EINVAL, ss); return true; } bool no_increasing = false; cmd_getval_compat_cephbool(cmdctx->cmdmap, "no_increasing", no_increasing); string out_str; mempool::osdmap::map<int32_t, uint32_t> new_weights; r = cluster_state.with_osdmap_and_pgmap([&](const OSDMap &osdmap, const PGMap& pgmap) { return reweight::by_utilization(osdmap, pgmap, oload, max_change, max_osds, by_pg, pools.empty() ? NULL : &pools, no_increasing, &new_weights, &ss, &out_str, f.get()); }); if (r >= 0) { dout(10) << "reweight::by_utilization: finished with " << out_str << dendl; } if (f) { f->flush(cmdctx->odata); } else { cmdctx->odata.append(out_str); } if (r < 0) { ss << "FAILED reweight-by-pg"; cmdctx->reply(r, ss); return true; } else if (r == 0 || dry_run) { ss << "no change"; cmdctx->reply(r, ss); return true; } else { json_spirit::Object json_object; for (const auto& osd_weight : new_weights) { json_spirit::Config::add(json_object, std::to_string(osd_weight.first), std::to_string(osd_weight.second)); } string s = json_spirit::write(json_object); std::replace(begin(s), end(s), '\"', '\''); const string cmd = "{" "\"prefix\": \"osd reweightn\", " "\"weights\": \"" + s + "\"" "}"; auto on_finish = new ReplyOnFinish(cmdctx); monc->start_mon_command({cmd}, {}, &on_finish->from_mon, &on_finish->outs, on_finish); return true; } } else if (prefix == "osd df") { string method, filter; cmd_getval(cmdctx->cmdmap, "output_method", method); cmd_getval(cmdctx->cmdmap, "filter", filter); stringstream rs; r = cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pgmap) { // sanity check filter(s) if (!filter.empty() && osdmap.lookup_pg_pool_name(filter) < 0 && !osdmap.crush->class_exists(filter) && !osdmap.crush->name_exists(filter)) { rs << "'" << filter << "' not a pool, crush node or device class name"; return -EINVAL; } print_osd_utilization(osdmap, pgmap, ss, f.get(), method == "tree", filter); cmdctx->odata.append(ss); return 0; }); cmdctx->reply(r, rs); return true; } else if (prefix == "osd pool stats") { string pool_name; cmd_getval(cmdctx->cmdmap, "pool_name", pool_name); int64_t poolid = -ENOENT; bool one_pool = false; r = cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pg_map) { if (!pool_name.empty()) { poolid = osdmap.lookup_pg_pool_name(pool_name); if (poolid < 0) { ceph_assert(poolid == -ENOENT); ss << "unrecognized pool '" << pool_name << "'"; return -ENOENT; } one_pool = true; } stringstream rs; if (f) f->open_array_section("pool_stats"); else { if (osdmap.get_pools().empty()) { ss << "there are no pools!"; goto stats_out; } } for (auto &p : osdmap.get_pools()) { if (!one_pool) { poolid = p.first; } pg_map.dump_pool_stats_and_io_rate(poolid, osdmap, f.get(), &rs); if (one_pool) { break; } } stats_out: if (f) { f->close_section(); f->flush(cmdctx->odata); } else { cmdctx->odata.append(rs.str()); } return 0; }); if (r != -EOPNOTSUPP) { cmdctx->reply(r, ss); return true; } } else if (prefix == "osd safe-to-destroy" || prefix == "osd destroy" || prefix == "osd purge") { set<int> osds; int r = 0; if (prefix == "osd safe-to-destroy") { vector<string> ids; cmd_getval(cmdctx->cmdmap, "ids", ids); cluster_state.with_osdmap([&](const OSDMap& osdmap) { r = osdmap.parse_osd_id_list(ids, &osds, &ss); }); if (!r && osds.empty()) { ss << "must specify one or more OSDs"; r = -EINVAL; } } else { int64_t id; if (!cmd_getval(cmdctx->cmdmap, "id", id)) { r = -EINVAL; ss << "must specify OSD id"; } else { osds.insert(id); } } if (r < 0) { cmdctx->reply(r, ss); return true; } set<int> active_osds, missing_stats, stored_pgs, safe_to_destroy; int affected_pgs = 0; cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pg_map) { if (pg_map.num_pg_unknown > 0) { ss << pg_map.num_pg_unknown << " pgs have unknown state; cannot draw" << " any conclusions"; r = -EAGAIN; return; } int num_active_clean = 0; for (auto& p : pg_map.num_pg_by_state) { unsigned want = PG_STATE_ACTIVE|PG_STATE_CLEAN; if ((p.first & want) == want) { num_active_clean += p.second; } } for (auto osd : osds) { if (!osdmap.exists(osd)) { safe_to_destroy.insert(osd); continue; // clearly safe to destroy } auto q = pg_map.num_pg_by_osd.find(osd); if (q != pg_map.num_pg_by_osd.end()) { if (q->second.acting > 0 || q->second.up_not_acting > 0) { active_osds.insert(osd); // XXX: For overlapping PGs, this counts them again affected_pgs += q->second.acting + q->second.up_not_acting; continue; } } if (num_active_clean < pg_map.num_pg) { // all pgs aren't active+clean; we need to be careful. auto p = pg_map.osd_stat.find(osd); if (p == pg_map.osd_stat.end() || !osdmap.is_up(osd)) { missing_stats.insert(osd); continue; } else if (p->second.num_pgs > 0) { stored_pgs.insert(osd); continue; } } safe_to_destroy.insert(osd); } }); if (r && prefix == "osd safe-to-destroy") { cmdctx->reply(r, ss); // regardless of formatter return true; } if (!r && (!active_osds.empty() || !missing_stats.empty() || !stored_pgs.empty())) { if (!safe_to_destroy.empty()) { ss << "OSD(s) " << safe_to_destroy << " are safe to destroy without reducing data durability. "; } if (!active_osds.empty()) { ss << "OSD(s) " << active_osds << " have " << affected_pgs << " pgs currently mapped to them. "; } if (!missing_stats.empty()) { ss << "OSD(s) " << missing_stats << " have no reported stats, and not all" << " PGs are active+clean; we cannot draw any conclusions. "; } if (!stored_pgs.empty()) { ss << "OSD(s) " << stored_pgs << " last reported they still store some PG" << " data, and not all PGs are active+clean; we cannot be sure they" << " aren't still needed."; } if (!active_osds.empty() || !stored_pgs.empty()) { r = -EBUSY; } else { r = -EAGAIN; } } if (prefix == "osd safe-to-destroy") { if (!r) { ss << "OSD(s) " << osds << " are safe to destroy without reducing data" << " durability."; } if (f) { f->open_object_section("osd_status"); f->open_array_section("safe_to_destroy"); for (auto i : safe_to_destroy) f->dump_int("osd", i); f->close_section(); f->open_array_section("active"); for (auto i : active_osds) f->dump_int("osd", i); f->close_section(); f->open_array_section("missing_stats"); for (auto i : missing_stats) f->dump_int("osd", i); f->close_section(); f->open_array_section("stored_pgs"); for (auto i : stored_pgs) f->dump_int("osd", i); f->close_section(); f->close_section(); // osd_status f->flush(cmdctx->odata); r = 0; std::stringstream().swap(ss); } cmdctx->reply(r, ss); return true; } if (r) { bool force = false; cmd_getval(cmdctx->cmdmap, "force", force); if (!force) { // Backward compat cmd_getval(cmdctx->cmdmap, "yes_i_really_mean_it", force); } if (!force) { ss << "\nYou can proceed by passing --force, but be warned that" " this will likely mean real, permanent data loss."; } else { r = 0; } } if (r) { cmdctx->reply(r, ss); return true; } const string cmd = "{" "\"prefix\": \"" + prefix + "-actual\", " "\"id\": " + stringify(osds) + ", " "\"yes_i_really_mean_it\": true" "}"; auto on_finish = new ReplyOnFinish(cmdctx); monc->start_mon_command({cmd}, {}, nullptr, &on_finish->outs, on_finish); return true; } else if (prefix == "osd ok-to-stop") { vector<string> ids; cmd_getval(cmdctx->cmdmap, "ids", ids); set<int> osds; int64_t max = 1; cmd_getval(cmdctx->cmdmap, "max", max); int r; cluster_state.with_osdmap([&](const OSDMap& osdmap) { r = osdmap.parse_osd_id_list(ids, &osds, &ss); }); if (!r && osds.empty()) { ss << "must specify one or more OSDs"; r = -EINVAL; } if (max < (int)osds.size()) { max = osds.size(); } if (r < 0) { cmdctx->reply(r, ss); return true; } offline_pg_report out_report; cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pg_map) { _maximize_ok_to_stop_set( osds, max, osdmap, pg_map, &out_report); }); if (!f) { f.reset(Formatter::create("json")); } f->dump_object("ok_to_stop", out_report); f->flush(cmdctx->odata); cmdctx->odata.append("\n"); if (!out_report.unknown.empty()) { ss << out_report.unknown.size() << " pgs have unknown state; " << "cannot draw any conclusions"; cmdctx->reply(-EAGAIN, ss); } if (!out_report.ok_to_stop()) { ss << "unsafe to stop osd(s) at this time (" << out_report.not_ok.size() << " PGs are or would become offline)"; cmdctx->reply(-EBUSY, ss); } else { cmdctx->reply(0, ss); } return true; } else if (prefix == "pg force-recovery" || prefix == "pg force-backfill" || prefix == "pg cancel-force-recovery" || prefix == "pg cancel-force-backfill" || prefix == "osd pool force-recovery" || prefix == "osd pool force-backfill" || prefix == "osd pool cancel-force-recovery" || prefix == "osd pool cancel-force-backfill") { vector<string> vs; get_str_vec(prefix, vs); auto& granularity = vs.front(); auto& forceop = vs.back(); vector<pg_t> pgs; // figure out actual op just once int actual_op = 0; if (forceop == "force-recovery") { actual_op = OFR_RECOVERY; } else if (forceop == "force-backfill") { actual_op = OFR_BACKFILL; } else if (forceop == "cancel-force-backfill") { actual_op = OFR_BACKFILL | OFR_CANCEL; } else if (forceop == "cancel-force-recovery") { actual_op = OFR_RECOVERY | OFR_CANCEL; } set<pg_t> candidates; // deduped if (granularity == "pg") { // covnert pg names to pgs, discard any invalid ones while at it vector<string> pgids; cmd_getval(cmdctx->cmdmap, "pgid", pgids); for (auto& i : pgids) { pg_t pgid; if (!pgid.parse(i.c_str())) { ss << "invlaid pgid '" << i << "'; "; r = -EINVAL; continue; } candidates.insert(pgid); } } else { // per pool vector<string> pool_names; cmd_getval(cmdctx->cmdmap, "who", pool_names); if (pool_names.empty()) { ss << "must specify one or more pool names"; cmdctx->reply(-EINVAL, ss); return true; } cluster_state.with_osdmap([&](const OSDMap& osdmap) { for (auto& pool_name : pool_names) { auto pool_id = osdmap.lookup_pg_pool_name(pool_name); if (pool_id < 0) { ss << "unrecognized pool '" << pool_name << "'"; r = -ENOENT; return; } auto pool_pg_num = osdmap.get_pg_num(pool_id); for (int i = 0; i < pool_pg_num; i++) candidates.insert({(unsigned int)i, (uint64_t)pool_id}); } }); if (r < 0) { cmdctx->reply(r, ss); return true; } } cluster_state.with_pgmap([&](const PGMap& pg_map) { for (auto& i : candidates) { auto it = pg_map.pg_stat.find(i); if (it == pg_map.pg_stat.end()) { ss << "pg " << i << " does not exist; "; r = -ENOENT; continue; } auto state = it->second.state; // discard pgs for which user requests are pointless switch (actual_op) { case OFR_RECOVERY: if ((state & (PG_STATE_DEGRADED | PG_STATE_RECOVERY_WAIT | PG_STATE_RECOVERING)) == 0) { // don't return error, user script may be racing with cluster. // not fatal. ss << "pg " << i << " doesn't require recovery; "; continue; } else if (state & PG_STATE_FORCED_RECOVERY) { ss << "pg " << i << " recovery already forced; "; // return error, as it may be a bug in user script r = -EINVAL; continue; } break; case OFR_BACKFILL: if ((state & (PG_STATE_DEGRADED | PG_STATE_BACKFILL_WAIT | PG_STATE_BACKFILLING)) == 0) { ss << "pg " << i << " doesn't require backfilling; "; continue; } else if (state & PG_STATE_FORCED_BACKFILL) { ss << "pg " << i << " backfill already forced; "; r = -EINVAL; continue; } break; case OFR_BACKFILL | OFR_CANCEL: if ((state & PG_STATE_FORCED_BACKFILL) == 0) { ss << "pg " << i << " backfill not forced; "; continue; } break; case OFR_RECOVERY | OFR_CANCEL: if ((state & PG_STATE_FORCED_RECOVERY) == 0) { ss << "pg " << i << " recovery not forced; "; continue; } break; default: ceph_abort_msg("actual_op value is not supported"); } pgs.push_back(i); } // for }); // respond with error only when no pgs are correct // yes, in case of mixed errors, only the last one will be emitted, // but the message presented will be fine if (pgs.size() != 0) { // clear error to not confuse users/scripts r = 0; } // optimize the command -> messages conversion, use only one // message per distinct OSD cluster_state.with_osdmap([&](const OSDMap& osdmap) { // group pgs to process by osd map<int, vector<spg_t>> osdpgs; for (auto& pgid : pgs) { int primary; spg_t spg; if (osdmap.get_primary_shard(pgid, &primary, &spg)) { osdpgs[primary].push_back(spg); } } for (auto& i : osdpgs) { if (osdmap.is_up(i.first)) { auto p = osd_cons.find(i.first); if (p == osd_cons.end()) { ss << "osd." << i.first << " is not currently connected"; r = -EAGAIN; continue; } for (auto& con : p->second) { con->send_message( new MOSDForceRecovery(monc->get_fsid(), i.second, actual_op)); } ss << "instructing pg(s) " << i.second << " on osd." << i.first << " to " << forceop << "; "; } } }); ss << std::endl; cmdctx->reply(r, ss); return true; } else if (prefix == "config show" || prefix == "config show-with-defaults") { string who; cmd_getval(cmdctx->cmdmap, "who", who); auto [key, valid] = DaemonKey::parse(who); if (!valid) { ss << "invalid daemon name: use <type>.<id>"; cmdctx->reply(-EINVAL, ss); return true; } DaemonStatePtr daemon = daemon_state.get(key); if (!daemon) { ss << "no config state for daemon " << who; cmdctx->reply(-ENOENT, ss); return true; } std::lock_guard l(daemon->lock); int r = 0; string name; if (cmd_getval(cmdctx->cmdmap, "key", name)) { // handle special options if (name == "fsid") { cmdctx->odata.append(stringify(monc->get_fsid()) + "\n"); cmdctx->reply(r, ss); return true; } auto p = daemon->config.find(name); if (p != daemon->config.end() && !p->second.empty()) { cmdctx->odata.append(p->second.rbegin()->second + "\n"); } else { auto& defaults = daemon->_get_config_defaults(); auto q = defaults.find(name); if (q != defaults.end()) { cmdctx->odata.append(q->second + "\n"); } else { r = -ENOENT; } } } else if (daemon->config_defaults_bl.length() > 0) { TextTable tbl; if (f) { f->open_array_section("config"); } else { tbl.define_column("NAME", TextTable::LEFT, TextTable::LEFT); tbl.define_column("VALUE", TextTable::LEFT, TextTable::LEFT); tbl.define_column("SOURCE", TextTable::LEFT, TextTable::LEFT); tbl.define_column("OVERRIDES", TextTable::LEFT, TextTable::LEFT); tbl.define_column("IGNORES", TextTable::LEFT, TextTable::LEFT); } if (prefix == "config show") { // show for (auto& i : daemon->config) { dout(20) << " " << i.first << " -> " << i.second << dendl; if (i.second.empty()) { continue; } if (f) { f->open_object_section("value"); f->dump_string("name", i.first); f->dump_string("value", i.second.rbegin()->second); f->dump_string("source", ceph_conf_level_name( i.second.rbegin()->first)); if (i.second.size() > 1) { f->open_array_section("overrides"); auto j = i.second.rend(); for (--j; j != i.second.rbegin(); --j) { f->open_object_section("value"); f->dump_string("source", ceph_conf_level_name(j->first)); f->dump_string("value", j->second); f->close_section(); } f->close_section(); } if (daemon->ignored_mon_config.count(i.first)) { f->dump_string("ignores", "mon"); } f->close_section(); } else { tbl << i.first; tbl << i.second.rbegin()->second; tbl << ceph_conf_level_name(i.second.rbegin()->first); if (i.second.size() > 1) { list<string> ov; auto j = i.second.rend(); for (--j; j != i.second.rbegin(); --j) { if (j->second == i.second.rbegin()->second) { ov.push_front(string("(") + ceph_conf_level_name(j->first) + string("[") + j->second + string("]") + string(")")); } else { ov.push_front(ceph_conf_level_name(j->first) + string("[") + j->second + string("]")); } } tbl << ov; } else { tbl << ""; } tbl << (daemon->ignored_mon_config.count(i.first) ? "mon" : ""); tbl << TextTable::endrow; } } } else { // show-with-defaults auto& defaults = daemon->_get_config_defaults(); for (auto& i : defaults) { if (f) { f->open_object_section("value"); f->dump_string("name", i.first); } else { tbl << i.first; } auto j = daemon->config.find(i.first); if (j != daemon->config.end() && !j->second.empty()) { // have config if (f) { f->dump_string("value", j->second.rbegin()->second); f->dump_string("source", ceph_conf_level_name( j->second.rbegin()->first)); if (j->second.size() > 1) { f->open_array_section("overrides"); auto k = j->second.rend(); for (--k; k != j->second.rbegin(); --k) { f->open_object_section("value"); f->dump_string("source", ceph_conf_level_name(k->first)); f->dump_string("value", k->second); f->close_section(); } f->close_section(); } if (daemon->ignored_mon_config.count(i.first)) { f->dump_string("ignores", "mon"); } f->close_section(); } else { tbl << j->second.rbegin()->second; tbl << ceph_conf_level_name(j->second.rbegin()->first); if (j->second.size() > 1) { list<string> ov; auto k = j->second.rend(); for (--k; k != j->second.rbegin(); --k) { if (k->second == j->second.rbegin()->second) { ov.push_front(string("(") + ceph_conf_level_name(k->first) + string("[") + k->second + string("]") + string(")")); } else { ov.push_front(ceph_conf_level_name(k->first) + string("[") + k->second + string("]")); } } tbl << ov; } else { tbl << ""; } tbl << (daemon->ignored_mon_config.count(i.first) ? "mon" : ""); tbl << TextTable::endrow; } } else { // only have default if (f) { f->dump_string("value", i.second); f->dump_string("source", ceph_conf_level_name(CONF_DEFAULT)); f->close_section(); } else { tbl << i.second; tbl << ceph_conf_level_name(CONF_DEFAULT); tbl << ""; tbl << ""; tbl << TextTable::endrow; } } } } if (f) { f->close_section(); f->flush(cmdctx->odata); } else { cmdctx->odata.append(stringify(tbl)); } } cmdctx->reply(r, ss); return true; } else if (prefix == "device ls") { set<string> devids; TextTable tbl; if (f) { f->open_array_section("devices"); daemon_state.with_devices([&f](const DeviceState& dev) { f->dump_object("device", dev); }); f->close_section(); f->flush(cmdctx->odata); } else { tbl.define_column("DEVICE", TextTable::LEFT, TextTable::LEFT); tbl.define_column("HOST:DEV", TextTable::LEFT, TextTable::LEFT); tbl.define_column("DAEMONS", TextTable::LEFT, TextTable::LEFT); tbl.define_column("WEAR", TextTable::RIGHT, TextTable::RIGHT); tbl.define_column("LIFE EXPECTANCY", TextTable::LEFT, TextTable::LEFT); auto now = ceph_clock_now(); daemon_state.with_devices([&tbl, now](const DeviceState& dev) { string h; for (auto& i : dev.attachments) { if (h.size()) { h += " "; } h += std::get<0>(i) + ":" + std::get<1>(i); } string d; for (auto& i : dev.daemons) { if (d.size()) { d += " "; } d += to_string(i); } char wear_level_str[16] = {0}; if (dev.wear_level >= 0) { snprintf(wear_level_str, sizeof(wear_level_str)-1, "%d%%", (int)(100.1 * dev.wear_level)); } tbl << dev.devid << h << d << wear_level_str << dev.get_life_expectancy_str(now) << TextTable::endrow; }); cmdctx->odata.append(stringify(tbl)); } cmdctx->reply(0, ss); return true; } else if (prefix == "device ls-by-daemon") { string who; cmd_getval(cmdctx->cmdmap, "who", who); if (auto [k, valid] = DaemonKey::parse(who); !valid) { ss << who << " is not a valid daemon name"; r = -EINVAL; } else { auto dm = daemon_state.get(k); if (dm) { if (f) { f->open_array_section("devices"); for (auto& i : dm->devices) { daemon_state.with_device(i.first, [&f] (const DeviceState& dev) { f->dump_object("device", dev); }); } f->close_section(); f->flush(cmdctx->odata); } else { TextTable tbl; tbl.define_column("DEVICE", TextTable::LEFT, TextTable::LEFT); tbl.define_column("HOST:DEV", TextTable::LEFT, TextTable::LEFT); tbl.define_column("EXPECTED FAILURE", TextTable::LEFT, TextTable::LEFT); auto now = ceph_clock_now(); for (auto& i : dm->devices) { daemon_state.with_device( i.first, [&tbl, now] (const DeviceState& dev) { string h; for (auto& i : dev.attachments) { if (h.size()) { h += " "; } h += std::get<0>(i) + ":" + std::get<1>(i); } tbl << dev.devid << h << dev.get_life_expectancy_str(now) << TextTable::endrow; }); } cmdctx->odata.append(stringify(tbl)); } } else { r = -ENOENT; ss << "daemon " << who << " not found"; } cmdctx->reply(r, ss); } } else if (prefix == "device ls-by-host") { string host; cmd_getval(cmdctx->cmdmap, "host", host); set<string> devids; daemon_state.list_devids_by_server(host, &devids); if (f) { f->open_array_section("devices"); for (auto& devid : devids) { daemon_state.with_device( devid, [&f] (const DeviceState& dev) { f->dump_object("device", dev); }); } f->close_section(); f->flush(cmdctx->odata); } else { TextTable tbl; tbl.define_column("DEVICE", TextTable::LEFT, TextTable::LEFT); tbl.define_column("DEV", TextTable::LEFT, TextTable::LEFT); tbl.define_column("DAEMONS", TextTable::LEFT, TextTable::LEFT); tbl.define_column("EXPECTED FAILURE", TextTable::LEFT, TextTable::LEFT); auto now = ceph_clock_now(); for (auto& devid : devids) { daemon_state.with_device( devid, [&tbl, &host, now] (const DeviceState& dev) { string n; for (auto& j : dev.attachments) { if (std::get<0>(j) == host) { if (n.size()) { n += " "; } n += std::get<1>(j); } } string d; for (auto& i : dev.daemons) { if (d.size()) { d += " "; } d += to_string(i); } tbl << dev.devid << n << d << dev.get_life_expectancy_str(now) << TextTable::endrow; }); } cmdctx->odata.append(stringify(tbl)); } cmdctx->reply(0, ss); return true; } else if (prefix == "device info") { string devid; cmd_getval(cmdctx->cmdmap, "devid", devid); int r = 0; ostringstream rs; if (!daemon_state.with_device(devid, [&f, &rs] (const DeviceState& dev) { if (f) { f->dump_object("device", dev); } else { dev.print(rs); } })) { ss << "device " << devid << " not found"; r = -ENOENT; } else { if (f) { f->flush(cmdctx->odata); } else { cmdctx->odata.append(rs.str()); } } cmdctx->reply(r, ss); return true; } else if (prefix == "device set-life-expectancy") { string devid; cmd_getval(cmdctx->cmdmap, "devid", devid); string from_str, to_str; cmd_getval(cmdctx->cmdmap, "from", from_str); cmd_getval(cmdctx->cmdmap, "to", to_str); utime_t from, to; if (!from.parse(from_str)) { ss << "unable to parse datetime '" << from_str << "'"; r = -EINVAL; cmdctx->reply(r, ss); } else if (to_str.size() && !to.parse(to_str)) { ss << "unable to parse datetime '" << to_str << "'"; r = -EINVAL; cmdctx->reply(r, ss); } else { map<string,string> meta; daemon_state.with_device_create( devid, [from, to, &meta] (DeviceState& dev) { dev.set_life_expectancy(from, to, ceph_clock_now()); meta = dev.metadata; }); json_spirit::Object json_object; for (auto& i : meta) { json_spirit::Config::add(json_object, i.first, i.second); } bufferlist json; json.append(json_spirit::write(json_object)); const string cmd = "{" "\"prefix\": \"config-key set\", " "\"key\": \"device/" + devid + "\"" "}"; auto on_finish = new ReplyOnFinish(cmdctx); monc->start_mon_command({cmd}, json, nullptr, nullptr, on_finish); } return true; } else if (prefix == "device rm-life-expectancy") { string devid; cmd_getval(cmdctx->cmdmap, "devid", devid); map<string,string> meta; if (daemon_state.with_device_write(devid, [&meta] (DeviceState& dev) { dev.rm_life_expectancy(); meta = dev.metadata; })) { string cmd; bufferlist json; if (meta.empty()) { cmd = "{" "\"prefix\": \"config-key rm\", " "\"key\": \"device/" + devid + "\"" "}"; } else { json_spirit::Object json_object; for (auto& i : meta) { json_spirit::Config::add(json_object, i.first, i.second); } json.append(json_spirit::write(json_object)); cmd = "{" "\"prefix\": \"config-key set\", " "\"key\": \"device/" + devid + "\"" "}"; } auto on_finish = new ReplyOnFinish(cmdctx); monc->start_mon_command({cmd}, json, nullptr, nullptr, on_finish); } else { cmdctx->reply(0, ss); } return true; } else { if (!pgmap_ready) { ss << "Warning: due to ceph-mgr restart, some PG states may not be up to date\n"; } if (f) { f->open_object_section("pg_info"); f->dump_bool("pg_ready", pgmap_ready); } // fall back to feeding command to PGMap r = cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pg_map) { return process_pg_map_command(prefix, cmdctx->cmdmap, pg_map, osdmap, f.get(), &ss, &cmdctx->odata); }); if (f) { f->close_section(); } if (r != -EOPNOTSUPP) { if (f) { f->flush(cmdctx->odata); } cmdctx->reply(r, ss); return true; } } // Was the command unfound? if (py_command.cmdstring.empty()) { ss << "No handler found for '" << prefix << "'"; dout(4) << "No handler found for '" << prefix << "'" << dendl; cmdctx->reply(-EINVAL, ss); return true; } // Validate that the module is active auto& mod_name = py_command.module_name; if (!py_modules.is_module_active(mod_name)) { ss << "Module '" << mod_name << "' is not enabled/loaded (required by " "command '" << prefix << "'): use `ceph mgr module enable " << mod_name << "` to enable it"; dout(4) << ss.str() << dendl; cmdctx->reply(-EOPNOTSUPP, ss); return true; } dout(10) << "passing through command '" << prefix << "' size " << cmdctx->cmdmap.size() << dendl; Finisher& mod_finisher = py_modules.get_active_module_finisher(mod_name); mod_finisher.queue(new LambdaContext([this, cmdctx, session, py_command, prefix] (int r_) mutable { std::stringstream ss; dout(10) << "dispatching command '" << prefix << "' size " << cmdctx->cmdmap.size() << dendl; // Validate that the module is enabled auto& py_handler_name = py_command.module_name; PyModuleRef module = py_modules.get_module(py_handler_name); ceph_assert(module); if (!module->is_enabled()) { ss << "Module '" << py_handler_name << "' is not enabled (required by " "command '" << prefix << "'): use `ceph mgr module enable " << py_handler_name << "` to enable it"; dout(4) << ss.str() << dendl; cmdctx->reply(-EOPNOTSUPP, ss); return; } // Hack: allow the self-test method to run on unhealthy modules. // Fix this in future by creating a special path for self test rather // than having the hook be a normal module command. std::string self_test_prefix = py_handler_name + " " + "self-test"; // Validate that the module is healthy bool accept_command; if (module->is_loaded()) { if (module->get_can_run() && !module->is_failed()) { // Healthy module accept_command = true; } else if (self_test_prefix == prefix) { // Unhealthy, but allow because it's a self test command accept_command = true; } else { accept_command = false; ss << "Module '" << py_handler_name << "' has experienced an error and " "cannot handle commands: " << module->get_error_string(); } } else { // Module not loaded accept_command = false; ss << "Module '" << py_handler_name << "' failed to load and " "cannot handle commands: " << module->get_error_string(); } if (!accept_command) { dout(4) << ss.str() << dendl; cmdctx->reply(-EIO, ss); return; } std::stringstream ds; bufferlist inbl = cmdctx->data; int r = py_modules.handle_command(py_command, *session, cmdctx->cmdmap, inbl, &ds, &ss); if (r == -EACCES) { log_access_denied(cmdctx, session, ss); } cmdctx->odata.append(ds); cmdctx->reply(r, ss); dout(10) << " command returned " << r << dendl; })); return true; } void DaemonServer::_prune_pending_service_map() { utime_t cutoff = ceph_clock_now(); cutoff -= g_conf().get_val<double>("mgr_service_beacon_grace"); auto p = pending_service_map.services.begin(); while (p != pending_service_map.services.end()) { auto q = p->second.daemons.begin(); while (q != p->second.daemons.end()) { DaemonKey key{p->first, q->first}; if (!daemon_state.exists(key)) { if (ServiceMap::is_normal_ceph_entity(p->first)) { dout(10) << "daemon " << key << " in service map but not in daemon state " << "index -- force pruning" << dendl; q = p->second.daemons.erase(q); pending_service_map_dirty = pending_service_map.epoch; } else { derr << "missing key " << key << dendl; ++q; } continue; } auto daemon = daemon_state.get(key); std::lock_guard l(daemon->lock); if (daemon->last_service_beacon == utime_t()) { // we must have just restarted; assume they are alive now. daemon->last_service_beacon = ceph_clock_now(); ++q; continue; } if (daemon->last_service_beacon < cutoff) { dout(10) << "pruning stale " << p->first << "." << q->first << " last_beacon " << daemon->last_service_beacon << dendl; q = p->second.daemons.erase(q); pending_service_map_dirty = pending_service_map.epoch; } else { ++q; } } if (p->second.daemons.empty()) { p = pending_service_map.services.erase(p); pending_service_map_dirty = pending_service_map.epoch; } else { ++p; } } } void DaemonServer::send_report() { if (!pgmap_ready) { if (ceph_clock_now() - started_at > g_conf().get_val<int64_t>("mgr_stats_period") * 4.0) { pgmap_ready = true; reported_osds.clear(); dout(1) << "Giving up on OSDs that haven't reported yet, sending " << "potentially incomplete PG state to mon" << dendl; } else { dout(1) << "Not sending PG status to monitor yet, waiting for OSDs" << dendl; return; } } auto m = ceph::make_message<MMonMgrReport>(); m->gid = monc->get_global_id(); py_modules.get_health_checks(&m->health_checks); py_modules.get_progress_events(&m->progress_events); cluster_state.with_mutable_pgmap([&](PGMap& pg_map) { cluster_state.update_delta_stats(); if (pending_service_map.epoch) { _prune_pending_service_map(); if (pending_service_map_dirty >= pending_service_map.epoch) { pending_service_map.modified = ceph_clock_now(); encode(pending_service_map, m->service_map_bl, CEPH_FEATURES_ALL); dout(10) << "sending service_map e" << pending_service_map.epoch << dendl; pending_service_map.epoch++; } } cluster_state.with_osdmap([&](const OSDMap& osdmap) { // FIXME: no easy way to get mon features here. this will do for // now, though, as long as we don't make a backward-incompat change. pg_map.encode_digest(osdmap, m->get_data(), CEPH_FEATURES_ALL); dout(10) << pg_map << dendl; pg_map.get_health_checks(g_ceph_context, osdmap, &m->health_checks); dout(10) << m->health_checks.checks.size() << " health checks" << dendl; dout(20) << "health checks:\n"; JSONFormatter jf(true); jf.dump_object("health_checks", m->health_checks); jf.flush(*_dout); *_dout << dendl; if (osdmap.require_osd_release >= ceph_release_t::luminous) { clog->debug() << "pgmap v" << pg_map.version << ": " << pg_map; } }); }); map<daemon_metric, unique_ptr<DaemonHealthMetricCollector>> accumulated; for (auto service : {"osd", "mon"} ) { auto daemons = daemon_state.get_by_service(service); for (const auto& [key,state] : daemons) { std::lock_guard l{state->lock}; for (const auto& metric : state->daemon_health_metrics) { auto acc = accumulated.find(metric.get_type()); if (acc == accumulated.end()) { auto collector = DaemonHealthMetricCollector::create(metric.get_type()); if (!collector) { derr << __func__ << " " << key << " sent me an unknown health metric: " << std::hex << static_cast<uint8_t>(metric.get_type()) << std::dec << dendl; continue; } tie(acc, std::ignore) = accumulated.emplace(metric.get_type(), std::move(collector)); } acc->second->update(key, metric); } } } for (const auto& acc : accumulated) { acc.second->summarize(m->health_checks); } // TODO? We currently do not notify the PyModules // TODO: respect needs_send, so we send the report only if we are asked to do // so, or the state is updated. monc->send_mon_message(std::move(m)); } void DaemonServer::adjust_pgs() { dout(20) << dendl; unsigned max = std::max<int64_t>(1, g_conf()->mon_osd_max_creating_pgs); double max_misplaced = g_conf().get_val<double>("target_max_misplaced_ratio"); bool aggro = g_conf().get_val<bool>("mgr_debug_aggressive_pg_num_changes"); map<string,unsigned> pg_num_to_set; map<string,unsigned> pgp_num_to_set; set<pg_t> upmaps_to_clear; cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pg_map) { unsigned creating_or_unknown = 0; for (auto& i : pg_map.num_pg_by_state) { if ((i.first & (PG_STATE_CREATING)) || i.first == 0) { creating_or_unknown += i.second; } } unsigned left = max; if (creating_or_unknown >= max) { return; } left -= creating_or_unknown; dout(10) << "creating_or_unknown " << creating_or_unknown << " max_creating " << max << " left " << left << dendl; // FIXME: These checks are fundamentally racy given that adjust_pgs() // can run more frequently than we get updated pg stats from OSDs. We // may make multiple adjustments with stale informaiton. double misplaced_ratio, degraded_ratio; double inactive_pgs_ratio, unknown_pgs_ratio; pg_map.get_recovery_stats(&misplaced_ratio, &degraded_ratio, &inactive_pgs_ratio, &unknown_pgs_ratio); dout(20) << "misplaced_ratio " << misplaced_ratio << " degraded_ratio " << degraded_ratio << " inactive_pgs_ratio " << inactive_pgs_ratio << " unknown_pgs_ratio " << unknown_pgs_ratio << "; target_max_misplaced_ratio " << max_misplaced << dendl; for (auto& i : osdmap.get_pools()) { const pg_pool_t& p = i.second; // adjust pg_num? if (p.get_pg_num_target() != p.get_pg_num()) { dout(20) << "pool " << i.first << " pg_num " << p.get_pg_num() << " target " << p.get_pg_num_target() << dendl; if (p.has_flag(pg_pool_t::FLAG_CREATING)) { dout(10) << "pool " << i.first << " pg_num_target " << p.get_pg_num_target() << " pg_num " << p.get_pg_num() << " - still creating initial pgs" << dendl; } else if (p.get_pg_num_target() < p.get_pg_num()) { // pg_num decrease (merge) pg_t merge_source(p.get_pg_num() - 1, i.first); pg_t merge_target = merge_source.get_parent(); bool ok = true; if (p.get_pg_num() != p.get_pg_num_pending()) { dout(10) << "pool " << i.first << " pg_num_target " << p.get_pg_num_target() << " pg_num " << p.get_pg_num() << " - decrease and pg_num_pending != pg_num, waiting" << dendl; ok = false; } else if (p.get_pg_num() == p.get_pgp_num()) { dout(10) << "pool " << i.first << " pg_num_target " << p.get_pg_num_target() << " pg_num " << p.get_pg_num() << " - decrease blocked by pgp_num " << p.get_pgp_num() << dendl; ok = false; } vector<int32_t> source_acting; for (auto &merge_participant : {merge_source, merge_target}) { bool is_merge_source = merge_participant == merge_source; if (osdmap.have_pg_upmaps(merge_participant)) { dout(10) << "pool " << i.first << " pg_num_target " << p.get_pg_num_target() << " pg_num " << p.get_pg_num() << (is_merge_source ? " - merge source " : " - merge target ") << merge_participant << " has upmap" << dendl; upmaps_to_clear.insert(merge_participant); ok = false; } auto q = pg_map.pg_stat.find(merge_participant); if (q == pg_map.pg_stat.end()) { dout(10) << "pool " << i.first << " pg_num_target " << p.get_pg_num_target() << " pg_num " << p.get_pg_num() << " - no state for " << merge_participant << (is_merge_source ? " (merge source)" : " (merge target)") << dendl; ok = false; } else if ((q->second.state & (PG_STATE_ACTIVE | PG_STATE_CLEAN)) != (PG_STATE_ACTIVE | PG_STATE_CLEAN)) { dout(10) << "pool " << i.first << " pg_num_target " << p.get_pg_num_target() << " pg_num " << p.get_pg_num() << (is_merge_source ? " - merge source " : " - merge target ") << merge_participant << " not clean (" << pg_state_string(q->second.state) << ")" << dendl; ok = false; } if (is_merge_source) { source_acting = q->second.acting; } else if (ok && q->second.acting != source_acting) { dout(10) << "pool " << i.first << " pg_num_target " << p.get_pg_num_target() << " pg_num " << p.get_pg_num() << (is_merge_source ? " - merge source " : " - merge target ") << merge_participant << " acting does not match (source " << source_acting << " != target " << q->second.acting << ")" << dendl; ok = false; } } if (ok) { unsigned target = p.get_pg_num() - 1; dout(10) << "pool " << i.first << " pg_num_target " << p.get_pg_num_target() << " pg_num " << p.get_pg_num() << " -> " << target << " (merging " << merge_source << " and " << merge_target << ")" << dendl; pg_num_to_set[osdmap.get_pool_name(i.first)] = target; continue; } } else if (p.get_pg_num_target() > p.get_pg_num()) { // pg_num increase (split) bool active = true; auto q = pg_map.num_pg_by_pool_state.find(i.first); if (q != pg_map.num_pg_by_pool_state.end()) { for (auto& j : q->second) { if ((j.first & (PG_STATE_ACTIVE|PG_STATE_PEERED)) == 0) { dout(20) << "pool " << i.first << " has " << j.second << " pgs in " << pg_state_string(j.first) << dendl; active = false; break; } } } else { active = false; } unsigned pg_gap = p.get_pg_num() - p.get_pgp_num(); unsigned max_jump = cct->_conf->mgr_max_pg_num_change; if (!active) { dout(10) << "pool " << i.first << " pg_num_target " << p.get_pg_num_target() << " pg_num " << p.get_pg_num() << " - not all pgs active" << dendl; } else if (pg_gap >= max_jump) { dout(10) << "pool " << i.first << " pg_num " << p.get_pg_num() << " - pgp_num " << p.get_pgp_num() << " gap >= max_pg_num_change " << max_jump << " - must scale pgp_num first" << dendl; } else { unsigned add = std::min( std::min(left, max_jump - pg_gap), p.get_pg_num_target() - p.get_pg_num()); unsigned target = p.get_pg_num() + add; left -= add; dout(10) << "pool " << i.first << " pg_num_target " << p.get_pg_num_target() << " pg_num " << p.get_pg_num() << " -> " << target << dendl; pg_num_to_set[osdmap.get_pool_name(i.first)] = target; } } } // adjust pgp_num? unsigned target = std::min(p.get_pg_num_pending(), p.get_pgp_num_target()); if (target != p.get_pgp_num()) { dout(20) << "pool " << i.first << " pgp_num_target " << p.get_pgp_num_target() << " pgp_num " << p.get_pgp_num() << " -> " << target << dendl; if (target > p.get_pgp_num() && p.get_pgp_num() == p.get_pg_num()) { dout(10) << "pool " << i.first << " pgp_num_target " << p.get_pgp_num_target() << " pgp_num " << p.get_pgp_num() << " - increase blocked by pg_num " << p.get_pg_num() << dendl; } else if (!aggro && (inactive_pgs_ratio > 0 || degraded_ratio > 0 || unknown_pgs_ratio > 0)) { dout(10) << "pool " << i.first << " pgp_num_target " << p.get_pgp_num_target() << " pgp_num " << p.get_pgp_num() << " - inactive|degraded|unknown pgs, deferring pgp_num" << " update" << dendl; } else if (!aggro && (misplaced_ratio > max_misplaced)) { dout(10) << "pool " << i.first << " pgp_num_target " << p.get_pgp_num_target() << " pgp_num " << p.get_pgp_num() << " - misplaced_ratio " << misplaced_ratio << " > max " << max_misplaced << ", deferring pgp_num update" << dendl; } else { // NOTE: this calculation assumes objects are // basically uniformly distributed across all PGs // (regardless of pool), which is probably not // perfectly correct, but it's a start. make no // single adjustment that's more than half of the // max_misplaced, to somewhat limit the magnitude of // our potential error here. unsigned next; static constexpr unsigned MAX_NUM_OBJECTS_PER_PG_FOR_LEAP = 1; pool_stat_t s = pg_map.get_pg_pool_sum_stat(i.first); if (aggro || // pool is (virtually) empty; just jump to final pgp_num? (p.get_pgp_num_target() > p.get_pgp_num() && s.stats.sum.num_objects <= (MAX_NUM_OBJECTS_PER_PG_FOR_LEAP * p.get_pgp_num_target()))) { next = target; } else { double room = std::min<double>(max_misplaced - misplaced_ratio, max_misplaced / 2.0); unsigned estmax = std::max<unsigned>( (double)p.get_pg_num() * room, 1u); unsigned next_min = 0; if (p.get_pgp_num() > estmax) { next_min = p.get_pgp_num() - estmax; } next = std::clamp(target, next_min, p.get_pgp_num() + estmax); dout(20) << " room " << room << " estmax " << estmax << " delta " << (target-p.get_pgp_num()) << " next " << next << dendl; if (p.get_pgp_num_target() == p.get_pg_num_target() && p.get_pgp_num_target() < p.get_pg_num()) { // since pgp_num is tracking pg_num, ceph is handling // pgp_num. so, be responsible: don't let pgp_num get // too far out ahead of merges (if we are merging). // this avoids moving lots of unmerged pgs onto a // small number of OSDs where we might blow out the // per-osd pg max. unsigned max_outpace_merges = std::max<unsigned>(8, p.get_pg_num() * max_misplaced); if (next + max_outpace_merges < p.get_pg_num()) { next = p.get_pg_num() - max_outpace_merges; dout(10) << " using next " << next << " to avoid outpacing merges (max_outpace_merges " << max_outpace_merges << ")" << dendl; } } } if (next != p.get_pgp_num()) { dout(10) << "pool " << i.first << " pgp_num_target " << p.get_pgp_num_target() << " pgp_num " << p.get_pgp_num() << " -> " << next << dendl; pgp_num_to_set[osdmap.get_pool_name(i.first)] = next; } } } if (left == 0) { return; } } }); for (auto i : pg_num_to_set) { const string cmd = "{" "\"prefix\": \"osd pool set\", " "\"pool\": \"" + i.first + "\", " "\"var\": \"pg_num_actual\", " "\"val\": \"" + stringify(i.second) + "\"" "}"; monc->start_mon_command({cmd}, {}, nullptr, nullptr, nullptr); } for (auto i : pgp_num_to_set) { const string cmd = "{" "\"prefix\": \"osd pool set\", " "\"pool\": \"" + i.first + "\", " "\"var\": \"pgp_num_actual\", " "\"val\": \"" + stringify(i.second) + "\"" "}"; monc->start_mon_command({cmd}, {}, nullptr, nullptr, nullptr); } for (auto pg : upmaps_to_clear) { const string cmd = "{" "\"prefix\": \"osd rm-pg-upmap\", " "\"pgid\": \"" + stringify(pg) + "\"" "}"; monc->start_mon_command({cmd}, {}, nullptr, nullptr, nullptr); const string cmd2 = "{" "\"prefix\": \"osd rm-pg-upmap-items\", " "\"pgid\": \"" + stringify(pg) + "\"" + "}"; monc->start_mon_command({cmd2}, {}, nullptr, nullptr, nullptr); } } void DaemonServer::got_service_map() { std::lock_guard l(lock); cluster_state.with_servicemap([&](const ServiceMap& service_map) { if (pending_service_map.epoch == 0) { // we just started up dout(10) << "got initial map e" << service_map.epoch << dendl; ceph_assert(pending_service_map_dirty == 0); pending_service_map = service_map; pending_service_map.epoch = service_map.epoch + 1; } else if (pending_service_map.epoch <= service_map.epoch) { // we just started up but got one more not our own map dout(10) << "got newer initial map e" << service_map.epoch << dendl; ceph_assert(pending_service_map_dirty == 0); pending_service_map = service_map; pending_service_map.epoch = service_map.epoch + 1; } else { // we already active and therefore must have persisted it, // which means ours is the same or newer. dout(10) << "got updated map e" << service_map.epoch << dendl; } }); // cull missing daemons, populate new ones std::set<std::string> types; for (auto& [type, service] : pending_service_map.services) { if (ServiceMap::is_normal_ceph_entity(type)) { continue; } types.insert(type); std::set<std::string> names; for (auto& q : service.daemons) { names.insert(q.first); DaemonKey key{type, q.first}; if (!daemon_state.exists(key)) { auto daemon = std::make_shared<DaemonState>(daemon_state.types); daemon->key = key; daemon->set_metadata(q.second.metadata); daemon->service_daemon = true; daemon_state.insert(daemon); dout(10) << "added missing " << key << dendl; } } daemon_state.cull(type, names); } daemon_state.cull_services(types); } void DaemonServer::got_mgr_map() { std::lock_guard l(lock); set<std::string> have; cluster_state.with_mgrmap([&](const MgrMap& mgrmap) { auto md_update = [&] (DaemonKey key) { std::ostringstream oss; auto c = new MetadataUpdate(daemon_state, key); // FIXME remove post-nautilus: include 'id' for luminous mons oss << "{\"prefix\": \"mgr metadata\", \"who\": \"" << key.name << "\", \"id\": \"" << key.name << "\"}"; monc->start_mon_command({oss.str()}, {}, &c->outbl, &c->outs, c); }; if (mgrmap.active_name.size()) { DaemonKey key{"mgr", mgrmap.active_name}; have.insert(mgrmap.active_name); if (!daemon_state.exists(key) && !daemon_state.is_updating(key)) { md_update(key); dout(10) << "triggered addition of " << key << " via metadata update" << dendl; } } for (auto& i : mgrmap.standbys) { DaemonKey key{"mgr", i.second.name}; have.insert(i.second.name); if (!daemon_state.exists(key) && !daemon_state.is_updating(key)) { md_update(key); dout(10) << "triggered addition of " << key << " via metadata update" << dendl; } } }); daemon_state.cull("mgr", have); } const char** DaemonServer::get_tracked_conf_keys() const { static const char *KEYS[] = { "mgr_stats_threshold", "mgr_stats_period", nullptr }; return KEYS; } void DaemonServer::handle_conf_change(const ConfigProxy& conf, const std::set <std::string> &changed) { if (changed.count("mgr_stats_threshold") || changed.count("mgr_stats_period")) { dout(4) << "Updating stats threshold/period on " << daemon_connections.size() << " clients" << dendl; // Send a fresh MMgrConfigure to all clients, so that they can follow // the new policy for transmitting stats finisher.queue(new LambdaContext([this](int r) { std::lock_guard l(lock); for (auto &c : daemon_connections) { _send_configure(c); } })); } } void DaemonServer::_send_configure(ConnectionRef c) { ceph_assert(ceph_mutex_is_locked_by_me(lock)); auto configure = make_message<MMgrConfigure>(); configure->stats_period = g_conf().get_val<int64_t>("mgr_stats_period"); configure->stats_threshold = g_conf().get_val<int64_t>("mgr_stats_threshold"); if (c->peer_is_osd()) { configure->osd_perf_metric_queries = osd_perf_metric_collector.get_queries(); } else if (c->peer_is_mds()) { configure->metric_config_message = MetricConfigMessage(MDSConfigPayload(mds_perf_metric_collector.get_queries())); } c->send_message2(configure); } MetricQueryID DaemonServer::add_osd_perf_query( const OSDPerfMetricQuery &query, const std::optional<OSDPerfMetricLimit> &limit) { return osd_perf_metric_collector.add_query(query, limit); } int DaemonServer::remove_osd_perf_query(MetricQueryID query_id) { return osd_perf_metric_collector.remove_query(query_id); } int DaemonServer::get_osd_perf_counters(OSDPerfCollector *collector) { return osd_perf_metric_collector.get_counters(collector); } MetricQueryID DaemonServer::add_mds_perf_query( const MDSPerfMetricQuery &query, const std::optional<MDSPerfMetricLimit> &limit) { return mds_perf_metric_collector.add_query(query, limit); } int DaemonServer::remove_mds_perf_query(MetricQueryID query_id) { return mds_perf_metric_collector.remove_query(query_id); } void DaemonServer::reregister_mds_perf_queries() { mds_perf_metric_collector.reregister_queries(); } int DaemonServer::get_mds_perf_counters(MDSPerfCollector *collector) { return mds_perf_metric_collector.get_counters(collector); }
98,453
30.354777
118
cc
null
ceph-main/src/mgr/DaemonServer.h
// -*- 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 John Spray <[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. */ #ifndef DAEMON_SERVER_H_ #define DAEMON_SERVER_H_ #include "PyModuleRegistry.h" #include <set> #include <string> #include <boost/variant.hpp> #include "common/ceph_mutex.h" #include "common/LogClient.h" #include "common/Timer.h" #include <msg/Messenger.h> #include <mon/MonClient.h> #include "ServiceMap.h" #include "MgrSession.h" #include "DaemonState.h" #include "MetricCollector.h" #include "OSDPerfMetricCollector.h" #include "MDSPerfMetricCollector.h" class MMgrReport; class MMgrOpen; class MMgrUpdate; class MMgrClose; class MMonMgrReport; class MCommand; class MMgrCommand; struct MonCommand; class CommandContext; struct OSDPerfMetricQuery; struct MDSPerfMetricQuery; struct offline_pg_report { set<int> osds; set<pg_t> ok, not_ok, unknown; set<pg_t> ok_become_degraded, ok_become_more_degraded; // ok set<pg_t> bad_no_pool, bad_already_inactive, bad_become_inactive; // not ok bool ok_to_stop() const { return not_ok.empty() && unknown.empty(); } void dump(Formatter *f) const { f->dump_bool("ok_to_stop", ok_to_stop()); f->open_array_section("osds"); for (auto o : osds) { f->dump_int("osd", o); } f->close_section(); f->dump_unsigned("num_ok_pgs", ok.size()); f->dump_unsigned("num_not_ok_pgs", not_ok.size()); // ambiguous if (!unknown.empty()) { f->open_array_section("unknown_pgs"); for (auto pg : unknown) { f->dump_stream("pg") << pg; } f->close_section(); } // bad news if (!bad_no_pool.empty()) { f->open_array_section("bad_no_pool_pgs"); for (auto pg : bad_no_pool) { f->dump_stream("pg") << pg; } f->close_section(); } if (!bad_already_inactive.empty()) { f->open_array_section("bad_already_inactive"); for (auto pg : bad_already_inactive) { f->dump_stream("pg") << pg; } f->close_section(); } if (!bad_become_inactive.empty()) { f->open_array_section("bad_become_inactive"); for (auto pg : bad_become_inactive) { f->dump_stream("pg") << pg; } f->close_section(); } // informative if (!ok_become_degraded.empty()) { f->open_array_section("ok_become_degraded"); for (auto pg : ok_become_degraded) { f->dump_stream("pg") << pg; } f->close_section(); } if (!ok_become_more_degraded.empty()) { f->open_array_section("ok_become_more_degraded"); for (auto pg : ok_become_more_degraded) { f->dump_stream("pg") << pg; } f->close_section(); } } }; /** * Server used in ceph-mgr to communicate with Ceph daemons like * MDSs and OSDs. */ class DaemonServer : public Dispatcher, public md_config_obs_t { protected: boost::scoped_ptr<Throttle> client_byte_throttler; boost::scoped_ptr<Throttle> client_msg_throttler; boost::scoped_ptr<Throttle> osd_byte_throttler; boost::scoped_ptr<Throttle> osd_msg_throttler; boost::scoped_ptr<Throttle> mds_byte_throttler; boost::scoped_ptr<Throttle> mds_msg_throttler; boost::scoped_ptr<Throttle> mon_byte_throttler; boost::scoped_ptr<Throttle> mon_msg_throttler; Messenger *msgr; MonClient *monc; Finisher &finisher; DaemonStateIndex &daemon_state; ClusterState &cluster_state; PyModuleRegistry &py_modules; LogChannelRef clog, audit_clog; // Connections for daemons, and clients with service names set // (i.e. those MgrClients that are allowed to send MMgrReports) std::set<ConnectionRef> daemon_connections; /// connections for osds ceph::unordered_map<int,std::set<ConnectionRef>> osd_cons; ServiceMap pending_service_map; // uncommitted epoch_t pending_service_map_dirty = 0; ceph::mutex lock = ceph::make_mutex("DaemonServer"); static void _generate_command_map(cmdmap_t& cmdmap, std::map<std::string,std::string> &param_str_map); static const MonCommand *_get_mgrcommand(const std::string &cmd_prefix, const std::vector<MonCommand> &commands); bool _allowed_command( MgrSession *s, const std::string &service, const std::string &module, const std::string &prefix, const cmdmap_t& cmdmap, const std::map<std::string,std::string>& param_str_map, const MonCommand *this_cmd); private: friend class ReplyOnFinish; bool _reply(MCommand* m, int ret, const std::string& s, const bufferlist& payload); void _prune_pending_service_map(); void _check_offlines_pgs( const std::set<int>& osds, const OSDMap& osdmap, const PGMap& pgmap, offline_pg_report *report); void _maximize_ok_to_stop_set( const set<int>& orig_osds, unsigned max, const OSDMap& osdmap, const PGMap& pgmap, offline_pg_report *report); utime_t started_at; std::atomic<bool> pgmap_ready; std::set<int32_t> reported_osds; void maybe_ready(int32_t osd_id); SafeTimer timer; bool shutting_down; Context *tick_event; void tick(); void schedule_tick_locked(double delay_sec); class OSDPerfMetricCollectorListener : public MetricListener { public: OSDPerfMetricCollectorListener(DaemonServer *server) : server(server) { } void handle_query_updated() override { server->handle_osd_perf_metric_query_updated(); } private: DaemonServer *server; }; OSDPerfMetricCollectorListener osd_perf_metric_collector_listener; OSDPerfMetricCollector osd_perf_metric_collector; void handle_osd_perf_metric_query_updated(); class MDSPerfMetricCollectorListener : public MetricListener { public: MDSPerfMetricCollectorListener(DaemonServer *server) : server(server) { } void handle_query_updated() override { server->handle_mds_perf_metric_query_updated(); } private: DaemonServer *server; }; MDSPerfMetricCollectorListener mds_perf_metric_collector_listener; MDSPerfMetricCollector mds_perf_metric_collector; void handle_mds_perf_metric_query_updated(); void handle_metric_payload(const OSDMetricPayload &payload) { osd_perf_metric_collector.process_reports(payload); } void handle_metric_payload(const MDSMetricPayload &payload) { mds_perf_metric_collector.process_reports(payload); } void handle_metric_payload(const UnknownMetricPayload &payload) { ceph_abort(); } struct HandlePayloadVisitor : public boost::static_visitor<void> { DaemonServer *server; HandlePayloadVisitor(DaemonServer *server) : server(server) { } template <typename MetricPayload> inline void operator()(const MetricPayload &payload) const { server->handle_metric_payload(payload); } }; void update_task_status(DaemonKey key, const std::map<std::string,std::string>& task_status); public: int init(uint64_t gid, entity_addrvec_t client_addrs); void shutdown(); entity_addrvec_t get_myaddrs() const; DaemonServer(MonClient *monc_, Finisher &finisher_, DaemonStateIndex &daemon_state_, ClusterState &cluster_state_, PyModuleRegistry &py_modules_, LogChannelRef cl, LogChannelRef auditcl); ~DaemonServer() override; bool ms_dispatch2(const ceph::ref_t<Message>& m) override; int ms_handle_authentication(Connection *con) override; bool ms_handle_reset(Connection *con) override; void ms_handle_remote_reset(Connection *con) override {} bool ms_handle_refused(Connection *con) override; void fetch_missing_metadata(const DaemonKey& key, const entity_addr_t& addr); bool handle_open(const ceph::ref_t<MMgrOpen>& m); bool handle_update(const ceph::ref_t<MMgrUpdate>& m); bool handle_close(const ceph::ref_t<MMgrClose>& m); bool handle_report(const ceph::ref_t<MMgrReport>& m); bool handle_command(const ceph::ref_t<MCommand>& m); bool handle_command(const ceph::ref_t<MMgrCommand>& m); bool _handle_command(std::shared_ptr<CommandContext>& cmdctx); void send_report(); void got_service_map(); void got_mgr_map(); void adjust_pgs(); void _send_configure(ConnectionRef c); MetricQueryID add_osd_perf_query( const OSDPerfMetricQuery &query, const std::optional<OSDPerfMetricLimit> &limit); int remove_osd_perf_query(MetricQueryID query_id); int get_osd_perf_counters(OSDPerfCollector *collector); MetricQueryID add_mds_perf_query(const MDSPerfMetricQuery &query, const std::optional<MDSPerfMetricLimit> &limit); int remove_mds_perf_query(MetricQueryID query_id); void reregister_mds_perf_queries(); int get_mds_perf_counters(MDSPerfCollector *collector); virtual const char** get_tracked_conf_keys() const override; virtual void handle_conf_change(const ConfigProxy& conf, const std::set <std::string> &changed) override; void schedule_tick(double delay_sec); void log_access_denied(std::shared_ptr<CommandContext>& cmdctx, MgrSession* session, std::stringstream& ss); void dump_pg_ready(ceph::Formatter *f); }; #endif
9,430
28.750789
86
h
null
ceph-main/src/mgr/DaemonState.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 John Spray <[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 "DaemonState.h" #include <experimental/iterator> #include "MgrSession.h" #include "include/stringify.h" #include "common/Formatter.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr " << __func__ << " " using std::list; using std::make_pair; using std::map; using std::ostream; using std::ostringstream; using std::string; using std::stringstream; using std::unique_ptr; void DeviceState::set_metadata(map<string,string>&& m) { metadata = std::move(m); auto p = metadata.find("life_expectancy_min"); if (p != metadata.end()) { life_expectancy.first.parse(p->second); } p = metadata.find("life_expectancy_max"); if (p != metadata.end()) { life_expectancy.second.parse(p->second); } p = metadata.find("life_expectancy_stamp"); if (p != metadata.end()) { life_expectancy_stamp.parse(p->second); } p = metadata.find("wear_level"); if (p != metadata.end()) { wear_level = atof(p->second.c_str()); } } void DeviceState::set_life_expectancy(utime_t from, utime_t to, utime_t now) { life_expectancy = make_pair(from, to); life_expectancy_stamp = now; if (from != utime_t()) { metadata["life_expectancy_min"] = stringify(from); } else { metadata["life_expectancy_min"] = ""; } if (to != utime_t()) { metadata["life_expectancy_max"] = stringify(to); } else { metadata["life_expectancy_max"] = ""; } if (now != utime_t()) { metadata["life_expectancy_stamp"] = stringify(now); } else { metadata["life_expectancy_stamp"] = ""; } } void DeviceState::rm_life_expectancy() { life_expectancy = make_pair(utime_t(), utime_t()); life_expectancy_stamp = utime_t(); metadata.erase("life_expectancy_min"); metadata.erase("life_expectancy_max"); metadata.erase("life_expectancy_stamp"); } void DeviceState::set_wear_level(float wear) { wear_level = wear; if (wear >= 0) { metadata["wear_level"] = stringify(wear); } else { metadata.erase("wear_level"); } } string DeviceState::get_life_expectancy_str(utime_t now) const { if (life_expectancy.first == utime_t()) { return string(); } if (now >= life_expectancy.first) { return "now"; } utime_t min = life_expectancy.first - now; utime_t max = life_expectancy.second - now; if (life_expectancy.second == utime_t()) { return string(">") + timespan_str(make_timespan(min)); } string a = timespan_str(make_timespan(min)); string b = timespan_str(make_timespan(max)); if (a == b) { return a; } return a + " to " + b; } void DeviceState::dump(Formatter *f) const { f->dump_string("devid", devid); f->open_array_section("location"); for (auto& i : attachments) { f->open_object_section("attachment"); f->dump_string("host", std::get<0>(i)); f->dump_string("dev", std::get<1>(i)); f->dump_string("path", std::get<2>(i)); f->close_section(); } f->close_section(); f->open_array_section("daemons"); for (auto& i : daemons) { f->dump_stream("daemon") << i; } f->close_section(); if (life_expectancy.first != utime_t()) { f->dump_stream("life_expectancy_min") << life_expectancy.first; f->dump_stream("life_expectancy_max") << life_expectancy.second; f->dump_stream("life_expectancy_stamp") << life_expectancy_stamp; } if (wear_level >= 0) { f->dump_float("wear_level", wear_level); } } void DeviceState::print(ostream& out) const { out << "device " << devid << "\n"; for (auto& i : attachments) { out << "attachment " << std::get<0>(i) << " " << std::get<1>(i) << " " << std::get<2>(i) << "\n"; out << "\n"; } std::copy(std::begin(daemons), std::end(daemons), std::experimental::make_ostream_joiner(out, ",")); out << '\n'; if (life_expectancy.first != utime_t()) { out << "life_expectancy " << life_expectancy.first << " to " << life_expectancy.second << " (as of " << life_expectancy_stamp << ")\n"; } if (wear_level >= 0) { out << "wear_level " << wear_level << "\n"; } } void DaemonState::set_metadata(const std::map<std::string,std::string>& m) { devices.clear(); devices_bypath.clear(); metadata = m; if (auto found = m.find("device_ids"); found != m.end()) { auto& device_ids = found->second; std::map<std::string,std::string> paths; // devname -> id or path if (auto found = m.find("device_paths"); found != m.end()) { get_str_map(found->second, &paths, ",; "); } for_each_pair( device_ids, ",; ", [&paths, this](std::string_view devname, std::string_view id) { // skip blank ids if (id.empty()) { return; } // id -> devname devices.emplace(id, devname); if (auto path = paths.find(std::string(id)); path != paths.end()) { // id -> path devices_bypath.emplace(id, path->second); } }); } if (auto found = m.find("hostname"); found != m.end()) { hostname = found->second; } } const std::map<std::string,std::string>& DaemonState::_get_config_defaults() { if (config_defaults.empty() && config_defaults_bl.length()) { auto p = config_defaults_bl.cbegin(); try { decode(config_defaults, p); } catch (buffer::error& e) { } } return config_defaults; } void DaemonStateIndex::insert(DaemonStatePtr dm) { std::unique_lock l{lock}; _insert(dm); } void DaemonStateIndex::_insert(DaemonStatePtr dm) { if (all.count(dm->key)) { _erase(dm->key); } by_server[dm->hostname][dm->key] = dm; all[dm->key] = dm; for (auto& i : dm->devices) { auto d = _get_or_create_device(i.first); d->daemons.insert(dm->key); auto p = dm->devices_bypath.find(i.first); if (p != dm->devices_bypath.end()) { d->attachments.insert(std::make_tuple(dm->hostname, i.second, p->second)); } else { d->attachments.insert(std::make_tuple(dm->hostname, i.second, std::string())); } } } void DaemonStateIndex::_erase(const DaemonKey& dmk) { ceph_assert(ceph_mutex_is_wlocked(lock)); const auto to_erase = all.find(dmk); ceph_assert(to_erase != all.end()); const auto dm = to_erase->second; for (auto& i : dm->devices) { auto d = _get_or_create_device(i.first); ceph_assert(d->daemons.count(dmk)); d->daemons.erase(dmk); auto p = dm->devices_bypath.find(i.first); if (p != dm->devices_bypath.end()) { d->attachments.erase(make_tuple(dm->hostname, i.second, p->second)); } else { d->attachments.erase(make_tuple(dm->hostname, i.second, std::string())); } if (d->empty()) { _erase_device(d); } } auto &server_collection = by_server[dm->hostname]; server_collection.erase(dm->key); if (server_collection.empty()) { by_server.erase(dm->hostname); } all.erase(to_erase); } DaemonStateCollection DaemonStateIndex::get_by_service( const std::string& svc) const { std::shared_lock l{lock}; DaemonStateCollection result; for (const auto& [key, state] : all) { if (key.type == svc) { result[key] = state; } } return result; } DaemonStateCollection DaemonStateIndex::get_by_server( const std::string &hostname) const { std::shared_lock l{lock}; if (auto found = by_server.find(hostname); found != by_server.end()) { return found->second; } else { return {}; } } bool DaemonStateIndex::exists(const DaemonKey &key) const { std::shared_lock l{lock}; return all.count(key) > 0; } DaemonStatePtr DaemonStateIndex::get(const DaemonKey &key) { std::shared_lock l{lock}; auto iter = all.find(key); if (iter != all.end()) { return iter->second; } else { return nullptr; } } void DaemonStateIndex::rm(const DaemonKey &key) { std::unique_lock l{lock}; _rm(key); } void DaemonStateIndex::_rm(const DaemonKey &key) { if (all.count(key)) { _erase(key); } } void DaemonStateIndex::cull(const std::string& svc_name, const std::set<std::string>& names_exist) { std::vector<string> victims; std::unique_lock l{lock}; auto begin = all.lower_bound({svc_name, ""}); auto end = all.end(); for (auto &i = begin; i != end; ++i) { const auto& daemon_key = i->first; if (daemon_key.type != svc_name) break; if (names_exist.count(daemon_key.name) == 0) { victims.push_back(daemon_key.name); } } for (auto &i : victims) { DaemonKey daemon_key{svc_name, i}; dout(4) << "Removing data for " << daemon_key << dendl; _erase(daemon_key); } } void DaemonStateIndex::cull_services(const std::set<std::string>& types_exist) { std::set<DaemonKey> victims; std::unique_lock l{lock}; for (auto it = all.begin(); it != all.end(); ++it) { const auto& daemon_key = it->first; if (it->second->service_daemon && types_exist.count(daemon_key.type) == 0) { victims.insert(daemon_key); } } for (auto &i : victims) { dout(4) << "Removing data for " << i << dendl; _erase(i); } } void DaemonPerfCounters::update(const MMgrReport& report) { dout(20) << "loading " << report.declare_types.size() << " new types, " << report.undeclare_types.size() << " old types, had " << types.size() << " types, got " << report.packed.length() << " bytes of data" << dendl; // Retrieve session state auto priv = report.get_connection()->get_priv(); auto session = static_cast<MgrSession*>(priv.get()); // Load any newly declared types for (const auto &t : report.declare_types) { types.insert(std::make_pair(t.path, t)); session->declared_types.insert(t.path); } // Remove any old types for (const auto &t : report.undeclare_types) { session->declared_types.erase(t); } const auto now = ceph_clock_now(); // Parse packed data according to declared set of types auto p = report.packed.cbegin(); DECODE_START(1, p); for (const auto &t_path : session->declared_types) { const auto &t = types.at(t_path); auto instances_it = instances.find(t_path); // Always check the instance exists, as we don't prevent yet // multiple sessions from daemons with the same name, and one // session clearing stats created by another on open. if (instances_it == instances.end()) { instances_it = instances.insert({t_path, t.type}).first; } uint64_t val = 0; uint64_t avgcount = 0; uint64_t avgcount2 = 0; decode(val, p); if (t.type & PERFCOUNTER_LONGRUNAVG) { decode(avgcount, p); decode(avgcount2, p); instances_it->second.push_avg(now, val, avgcount); } else { instances_it->second.push(now, val); } } DECODE_FINISH(p); } void PerfCounterInstance::push(utime_t t, uint64_t const &v) { buffer.push_back({t, v}); } void PerfCounterInstance::push_avg(utime_t t, uint64_t const &s, uint64_t const &c) { avg_buffer.push_back({t, s, c}); }
11,285
24.944828
80
cc
null
ceph-main/src/mgr/DaemonState.h
// -*- 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 John Spray <[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. */ #ifndef DAEMON_STATE_H_ #define DAEMON_STATE_H_ #include <map> #include <string> #include <memory> #include <set> #include <boost/circular_buffer.hpp> #include "include/str_map.h" #include "msg/msg_types.h" // For PerfCounterType #include "messages/MMgrReport.h" #include "DaemonKey.h" namespace ceph { class Formatter; } // An instance of a performance counter type, within // a particular daemon. class PerfCounterInstance { class DataPoint { public: utime_t t; uint64_t v; DataPoint(utime_t t_, uint64_t v_) : t(t_), v(v_) {} }; class AvgDataPoint { public: utime_t t; uint64_t s; uint64_t c; AvgDataPoint(utime_t t_, uint64_t s_, uint64_t c_) : t(t_), s(s_), c(c_) {} }; boost::circular_buffer<DataPoint> buffer; boost::circular_buffer<AvgDataPoint> avg_buffer; uint64_t get_current() const; public: const boost::circular_buffer<DataPoint> & get_data() const { return buffer; } const DataPoint& get_latest_data() const { return buffer.back(); } const boost::circular_buffer<AvgDataPoint> & get_data_avg() const { return avg_buffer; } const AvgDataPoint& get_latest_data_avg() const { return avg_buffer.back(); } void push(utime_t t, uint64_t const &v); void push_avg(utime_t t, uint64_t const &s, uint64_t const &c); PerfCounterInstance(enum perfcounter_type_d type) { if (type & PERFCOUNTER_LONGRUNAVG) avg_buffer = boost::circular_buffer<AvgDataPoint>(20); else buffer = boost::circular_buffer<DataPoint>(20); }; }; typedef std::map<std::string, PerfCounterType> PerfCounterTypes; // Performance counters for one daemon class DaemonPerfCounters { public: // The record of perf stat types, shared between daemons PerfCounterTypes &types; explicit DaemonPerfCounters(PerfCounterTypes &types_) : types(types_) {} std::map<std::string, PerfCounterInstance> instances; void update(const MMgrReport& report); void clear() { instances.clear(); } }; // The state that we store about one daemon class DaemonState { public: ceph::mutex lock = ceph::make_mutex("DaemonState::lock"); DaemonKey key; // The hostname where daemon was last seen running (extracted // from the metadata) std::string hostname; // The metadata (hostname, version, etc) sent from the daemon std::map<std::string, std::string> metadata; /// device ids -> devname, derived from metadata[device_ids] std::map<std::string,std::string> devices; /// device ids -> by-path, derived from metadata[device_ids] std::map<std::string,std::string> devices_bypath; // TODO: this can be generalized to other daemons std::vector<DaemonHealthMetric> daemon_health_metrics; // Ephemeral state bool service_daemon = false; utime_t service_status_stamp; std::map<std::string, std::string> service_status; utime_t last_service_beacon; // running config std::map<std::string,std::map<int32_t,std::string>> config; // mon config values we failed to set std::map<std::string,std::string> ignored_mon_config; // compiled-in config defaults (rarely used, so we leave them encoded!) bufferlist config_defaults_bl; std::map<std::string,std::string> config_defaults; // The perf counters received in MMgrReport messages DaemonPerfCounters perf_counters; explicit DaemonState(PerfCounterTypes &types_) : perf_counters(types_) { } void set_metadata(const std::map<std::string,std::string>& m); const std::map<std::string,std::string>& _get_config_defaults(); }; typedef std::shared_ptr<DaemonState> DaemonStatePtr; typedef std::map<DaemonKey, DaemonStatePtr> DaemonStateCollection; struct DeviceState : public RefCountedObject { std::string devid; /// (server,devname,path) std::set<std::tuple<std::string,std::string,std::string>> attachments; std::set<DaemonKey> daemons; std::map<std::string,std::string> metadata; ///< persistent metadata std::pair<utime_t,utime_t> life_expectancy; ///< when device failure is expected utime_t life_expectancy_stamp; ///< when life expectency was recorded float wear_level = -1; ///< SSD wear level (negative if unknown) void set_metadata(std::map<std::string,std::string>&& m); void set_life_expectancy(utime_t from, utime_t to, utime_t now); void rm_life_expectancy(); void set_wear_level(float wear); std::string get_life_expectancy_str(utime_t now) const; /// true of we can be safely forgotten/removed from memory bool empty() const { return daemons.empty() && metadata.empty(); } void dump(Formatter *f) const; void print(std::ostream& out) const; private: FRIEND_MAKE_REF(DeviceState); DeviceState(const std::string& n) : devid(n) {} }; /** * Fuse the collection of per-daemon metadata from Ceph into * a view that can be queried by service type, ID or also * by server (aka fqdn). */ class DaemonStateIndex { private: mutable ceph::shared_mutex lock = ceph::make_shared_mutex("DaemonStateIndex", true, true, true); std::map<std::string, DaemonStateCollection> by_server; DaemonStateCollection all; std::set<DaemonKey> updating; std::map<std::string,ceph::ref_t<DeviceState>> devices; void _erase(const DaemonKey& dmk); ceph::ref_t<DeviceState> _get_or_create_device(const std::string& dev) { auto em = devices.try_emplace(dev, nullptr); auto& d = em.first->second; if (em.second) { d = ceph::make_ref<DeviceState>(dev); } return d; } void _erase_device(const ceph::ref_t<DeviceState>& d) { devices.erase(d->devid); } public: DaemonStateIndex() {} // FIXME: shouldn't really be public, maybe construct DaemonState // objects internally to avoid this. PerfCounterTypes types; void insert(DaemonStatePtr dm); void _insert(DaemonStatePtr dm); bool exists(const DaemonKey &key) const; DaemonStatePtr get(const DaemonKey &key); void rm(const DaemonKey &key); void _rm(const DaemonKey &key); // Note that these return by value rather than reference to avoid // callers needing to stay in lock while using result. Callers must // still take the individual DaemonState::lock on each entry though. DaemonStateCollection get_by_server(const std::string &hostname) const; DaemonStateCollection get_by_service(const std::string &svc_name) const; DaemonStateCollection get_all() const {return all;} template<typename Callback, typename...Args> auto with_daemons_by_server(Callback&& cb, Args&&... args) const -> decltype(cb(by_server, std::forward<Args>(args)...)) { std::shared_lock l{lock}; return std::forward<Callback>(cb)(by_server, std::forward<Args>(args)...); } template<typename Callback, typename...Args> bool with_device(const std::string& dev, Callback&& cb, Args&&... args) const { std::shared_lock l{lock}; auto p = devices.find(dev); if (p == devices.end()) { return false; } std::forward<Callback>(cb)(*p->second, std::forward<Args>(args)...); return true; } template<typename Callback, typename...Args> bool with_device_write(const std::string& dev, Callback&& cb, Args&&... args) { std::unique_lock l{lock}; auto p = devices.find(dev); if (p == devices.end()) { return false; } std::forward<Callback>(cb)(*p->second, std::forward<Args>(args)...); if (p->second->empty()) { _erase_device(p->second); } return true; } template<typename Callback, typename...Args> void with_device_create(const std::string& dev, Callback&& cb, Args&&... args) { std::unique_lock l{lock}; auto d = _get_or_create_device(dev); std::forward<Callback>(cb)(*d, std::forward<Args>(args)...); } template<typename Callback, typename...Args> void with_devices(Callback&& cb, Args&&... args) const { std::shared_lock l{lock}; for (auto& i : devices) { std::forward<Callback>(cb)(*i.second, std::forward<Args>(args)...); } } template<typename CallbackInitial, typename Callback, typename...Args> void with_devices2(CallbackInitial&& cbi, // with lock taken Callback&& cb, // for each device Args&&... args) const { std::shared_lock l{lock}; cbi(); for (auto& i : devices) { std::forward<Callback>(cb)(*i.second, std::forward<Args>(args)...); } } void list_devids_by_server(const std::string& server, std::set<std::string> *ls) { auto m = get_by_server(server); for (auto& i : m) { std::lock_guard l(i.second->lock); for (auto& j : i.second->devices) { ls->insert(j.first); } } } void notify_updating(const DaemonKey &k) { std::unique_lock l{lock}; updating.insert(k); } void clear_updating(const DaemonKey &k) { std::unique_lock l{lock}; updating.erase(k); } bool is_updating(const DaemonKey &k) { std::shared_lock l{lock}; return updating.count(k) > 0; } void update_metadata(DaemonStatePtr state, const std::map<std::string,std::string>& meta) { // remove and re-insert in case the device metadata changed std::unique_lock l{lock}; _rm(state->key); { std::lock_guard l2{state->lock}; state->set_metadata(meta); } _insert(state); } /** * Remove state for all daemons of this type whose names are * not present in `names_exist`. Use this function when you have * a cluster map and want to ensure that anything absent in the map * is also absent in this class. */ void cull(const std::string& svc_name, const std::set<std::string>& names_exist); void cull_services(const std::set<std::string>& types_exist); }; #endif
10,143
26.342318
83
h
null
ceph-main/src/mgr/Gil.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) 2017 SUSE LLC * * 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 "Python.h" #include "common/debug.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr " << __func__ << " " #include "Gil.h" SafeThreadState::SafeThreadState(PyThreadState *ts_) : ts(ts_) { ceph_assert(ts != nullptr); thread = pthread_self(); } Gil::Gil(SafeThreadState &ts, bool new_thread) : pThreadState(ts) { // Acquire the GIL, set the current thread state PyEval_RestoreThread(pThreadState.ts); dout(25) << "GIL acquired for thread state " << pThreadState.ts << dendl; // // If called from a separate OS thread (i.e. a thread not created // by Python, that does't already have a python thread state that // was created when that thread was active), we need to manually // create and switch to a python thread state specifically for this // OS thread. // // Note that instead of requring the caller to set new_thread == true // when calling this from a separate OS thread, we could figure out // if this was necessary automatically, as follows: // // if (pThreadState->thread_id != PyThread_get_thread_ident()) { // // However, this means we're accessing pThreadState->thread_id, but // the Python C API docs say that "The only public data member is // PyInterpreterState *interp", i.e. doing this would violate // something that's meant to be a black box. // if (new_thread) { pNewThreadState = PyThreadState_New(pThreadState.ts->interp); PyThreadState_Swap(pNewThreadState); dout(20) << "Switched to new thread state " << pNewThreadState << dendl; } else { ceph_assert(pthread_self() == pThreadState.thread); } } Gil::~Gil() { if (pNewThreadState != nullptr) { dout(20) << "Destroying new thread state " << pNewThreadState << dendl; PyThreadState_Swap(pThreadState.ts); PyThreadState_Clear(pNewThreadState); PyThreadState_Delete(pNewThreadState); } // Release the GIL, reset the thread state to NULL PyEval_SaveThread(); dout(25) << "GIL released for thread state " << pThreadState.ts << dendl; } without_gil_t::without_gil_t() { assert(PyGILState_Check()); release_gil(); } without_gil_t::~without_gil_t() { if (save) { acquire_gil(); } } void without_gil_t::release_gil() { save = PyEval_SaveThread(); } void without_gil_t::acquire_gil() { assert(save); PyEval_RestoreThread(save); save = nullptr; } with_gil_t::with_gil_t(without_gil_t& allow_threads) : allow_threads{allow_threads} { allow_threads.acquire_gil(); } with_gil_t::~with_gil_t() { allow_threads.release_gil(); }
3,010
25.182609
76
cc
null
ceph-main/src/mgr/Gil.h
// -*- 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) 2017 SUSE LLC * * 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. * */ #pragma once #include <cassert> #include <functional> struct _ts; typedef struct _ts PyThreadState; #include <pthread.h> /** * Wrap PyThreadState to carry a record of which POSIX thread * the thread state relates to. This allows the Gil class to * validate that we're being used from the right thread. */ class SafeThreadState { public: explicit SafeThreadState(PyThreadState *ts_); SafeThreadState() : ts(nullptr), thread(0) { } PyThreadState *ts; pthread_t thread; void set(PyThreadState *ts_) { ts = ts_; thread = pthread_self(); } }; // // Use one of these in any scope in which you need to hold Python's // Global Interpreter Lock. // // Do *not* nest these, as a second GIL acquire will deadlock (see // https://docs.python.org/2/c-api/init.html#c.PyEval_RestoreThread) // // If in doubt, explicitly put a scope around the block of code you // know you need the GIL in. // // See the comment in Gil::Gil for when to set new_thread == true // class Gil { public: Gil(const Gil&) = delete; Gil& operator=(const Gil&) = delete; Gil(SafeThreadState &ts, bool new_thread = false); ~Gil(); private: SafeThreadState &pThreadState; PyThreadState *pNewThreadState = nullptr; }; // because the Python runtime could relinquish the GIL when performing GC // and re-acquire it afterwards, we should enforce following locking policy: // 1. do not acquire locks when holding the GIL, use a without_gil or // without_gil_t to guard the code which acquires non-gil locks. // 2. always hold a GIL when calling python functions, for example, when // constructing a PyFormatter instance. // // a wrapper that provides a convenient RAII-style mechinary for acquiring // and releasing GIL, like the macros of Py_BEGIN_ALLOW_THREADS and // Py_END_ALLOW_THREADS. struct without_gil_t { without_gil_t(); ~without_gil_t(); void release_gil(); void acquire_gil(); private: PyThreadState *save = nullptr; friend struct with_gil_t; }; struct with_gil_t { with_gil_t(without_gil_t& allow_threads); ~with_gil_t(); private: without_gil_t& allow_threads; }; // invoke func with GIL acquired template<typename Func> auto with_gil(without_gil_t& no_gil, Func&& func) { with_gil_t gil{no_gil}; return std::invoke(std::forward<Func>(func)); } template<typename Func> auto without_gil(Func&& func) { without_gil_t no_gil; return std::invoke(std::forward<Func>(func)); }
2,834
23.652174
76
h
null
ceph-main/src/mgr/MDSPerfMetricCollector.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "common/debug.h" #include "common/errno.h" #include "messages/MMgrReport.h" #include "mgr/MDSPerfMetricTypes.h" #include "mgr/MDSPerfMetricCollector.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr.mds_perf_metric_collector " << __func__ << " " MDSPerfMetricCollector::MDSPerfMetricCollector(MetricListener &listener) : MetricCollector<MDSPerfMetricQuery, MDSPerfMetricLimit, MDSPerfMetricKey, MDSPerfMetrics>(listener) { } void MDSPerfMetricCollector::process_reports(const MetricPayload &payload) { const MDSPerfMetricReport &metric_report = boost::get<MDSMetricPayload>(payload).metric_report; std::lock_guard locker(lock); process_reports_generic( metric_report.reports, [](PerformanceCounter *counter, const PerformanceCounter &update) { counter->first = update.first; counter->second = update.second; }); // update delayed rank set delayed_ranks = metric_report.rank_metrics_delayed; dout(20) << ": delayed ranks=[" << delayed_ranks << "]" << dendl; clock_gettime(CLOCK_MONOTONIC_COARSE, &last_updated_mono); } int MDSPerfMetricCollector::get_counters(PerfCollector *collector) { MDSPerfCollector *c = static_cast<MDSPerfCollector *>(collector); std::lock_guard locker(lock); int r = get_counters_generic(c->query_id, &c->counters); if (r != 0) { return r; } get_delayed_ranks(&c->delayed_ranks); get_last_updated(&c->last_updated_mono); return r; } void MDSPerfMetricCollector::get_delayed_ranks(std::set<mds_rank_t> *ranks) { ceph_assert(ceph_mutex_is_locked(lock)); *ranks = delayed_ranks; } void MDSPerfMetricCollector::get_last_updated(utime_t *ts) { ceph_assert(ceph_mutex_is_locked(lock)); *ts = utime_t(last_updated_mono); }
1,965
29.246154
97
cc
null
ceph-main/src/mgr/MDSPerfMetricCollector.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_MGR_MDS_PERF_COLLECTOR_H #define CEPH_MGR_MDS_PERF_COLLECTOR_H #include "mgr/MetricCollector.h" #include "mgr/MDSPerfMetricTypes.h" // MDS performance query class class MDSPerfMetricCollector : public MetricCollector<MDSPerfMetricQuery, MDSPerfMetricLimit, MDSPerfMetricKey, MDSPerfMetrics> { private: std::set<mds_rank_t> delayed_ranks; struct timespec last_updated_mono; void get_delayed_ranks(std::set<mds_rank_t> *ranks); void get_last_updated(utime_t *ts); public: MDSPerfMetricCollector(MetricListener &listener); void process_reports(const MetricPayload &payload) override; int get_counters(PerfCollector *collector) override; }; #endif // CEPH_MGR_MDS_PERF_COLLECTOR_H
838
27.931034
84
h
null
ceph-main/src/mgr/MDSPerfMetricTypes.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <ostream> #include "mgr/MDSPerfMetricTypes.h" std::ostream& operator<<(std::ostream& os, const MDSPerfMetricSubKeyDescriptor &d) { switch (d.type) { case MDSPerfMetricSubKeyType::MDS_RANK: os << "mds_rank"; break; case MDSPerfMetricSubKeyType::CLIENT_ID: os << "client_id"; break; default: os << "unknown (" << static_cast<int>(d.type) << ")"; } return os << "~/" << d.regex_str << "/"; } void MDSPerformanceCounterDescriptor::pack_counter( const PerformanceCounter &c, bufferlist *bl) const { using ceph::encode; encode(c.first, *bl); encode(c.second, *bl); switch(type) { case MDSPerformanceCounterType::CAP_HIT_METRIC: case MDSPerformanceCounterType::READ_LATENCY_METRIC: case MDSPerformanceCounterType::WRITE_LATENCY_METRIC: case MDSPerformanceCounterType::METADATA_LATENCY_METRIC: case MDSPerformanceCounterType::DENTRY_LEASE_METRIC: case MDSPerformanceCounterType::OPENED_FILES_METRIC: case MDSPerformanceCounterType::PINNED_ICAPS_METRIC: case MDSPerformanceCounterType::OPENED_INODES_METRIC: case MDSPerformanceCounterType::READ_IO_SIZES_METRIC: case MDSPerformanceCounterType::WRITE_IO_SIZES_METRIC: case MDSPerformanceCounterType::AVG_READ_LATENCY_METRIC: case MDSPerformanceCounterType::STDEV_READ_LATENCY_METRIC: case MDSPerformanceCounterType::AVG_WRITE_LATENCY_METRIC: case MDSPerformanceCounterType::STDEV_WRITE_LATENCY_METRIC: case MDSPerformanceCounterType::AVG_METADATA_LATENCY_METRIC: case MDSPerformanceCounterType::STDEV_METADATA_LATENCY_METRIC: break; default: ceph_abort_msg("unknown counter type"); } } void MDSPerformanceCounterDescriptor::unpack_counter( bufferlist::const_iterator& bl, PerformanceCounter *c) const { using ceph::decode; decode(c->first, bl); decode(c->second, bl); switch(type) { case MDSPerformanceCounterType::CAP_HIT_METRIC: case MDSPerformanceCounterType::READ_LATENCY_METRIC: case MDSPerformanceCounterType::WRITE_LATENCY_METRIC: case MDSPerformanceCounterType::METADATA_LATENCY_METRIC: case MDSPerformanceCounterType::DENTRY_LEASE_METRIC: case MDSPerformanceCounterType::OPENED_FILES_METRIC: case MDSPerformanceCounterType::PINNED_ICAPS_METRIC: case MDSPerformanceCounterType::OPENED_INODES_METRIC: case MDSPerformanceCounterType::READ_IO_SIZES_METRIC: case MDSPerformanceCounterType::WRITE_IO_SIZES_METRIC: case MDSPerformanceCounterType::AVG_READ_LATENCY_METRIC: case MDSPerformanceCounterType::STDEV_READ_LATENCY_METRIC: case MDSPerformanceCounterType::AVG_WRITE_LATENCY_METRIC: case MDSPerformanceCounterType::STDEV_WRITE_LATENCY_METRIC: case MDSPerformanceCounterType::AVG_METADATA_LATENCY_METRIC: case MDSPerformanceCounterType::STDEV_METADATA_LATENCY_METRIC: break; default: ceph_abort_msg("unknown counter type"); } } std::ostream& operator<<(std::ostream &os, const MDSPerformanceCounterDescriptor &d) { switch(d.type) { case MDSPerformanceCounterType::CAP_HIT_METRIC: os << "cap_hit_metric"; break; case MDSPerformanceCounterType::READ_LATENCY_METRIC: os << "read_latency_metric"; break; case MDSPerformanceCounterType::WRITE_LATENCY_METRIC: os << "write_latency_metric"; break; case MDSPerformanceCounterType::METADATA_LATENCY_METRIC: os << "metadata_latency_metric"; break; case MDSPerformanceCounterType::DENTRY_LEASE_METRIC: os << "dentry_lease_metric"; break; case MDSPerformanceCounterType::OPENED_FILES_METRIC: os << "opened_files_metric"; break; case MDSPerformanceCounterType::PINNED_ICAPS_METRIC: os << "pinned_icaps_metric"; break; case MDSPerformanceCounterType::OPENED_INODES_METRIC: os << "opened_inodes_metric"; break; case MDSPerformanceCounterType::READ_IO_SIZES_METRIC: os << "read_io_sizes_metric"; break; case MDSPerformanceCounterType::WRITE_IO_SIZES_METRIC: os << "write_io_sizes_metric"; break; case MDSPerformanceCounterType::AVG_READ_LATENCY_METRIC: os << "avg_read_latency"; break; case MDSPerformanceCounterType::STDEV_READ_LATENCY_METRIC: os << "stdev_read_latency"; break; case MDSPerformanceCounterType::AVG_WRITE_LATENCY_METRIC: os << "avg_write_latency"; break; case MDSPerformanceCounterType::STDEV_WRITE_LATENCY_METRIC: os << "stdev_write_latency"; break; case MDSPerformanceCounterType::AVG_METADATA_LATENCY_METRIC: os << "avg_metadata_latency"; break; case MDSPerformanceCounterType::STDEV_METADATA_LATENCY_METRIC: os << "stdev_metadata_latency"; break; } return os; } std::ostream &operator<<(std::ostream &os, const MDSPerfMetricLimit &limit) { return os << "[order_by=" << limit.order_by << ", max_count=" << limit.max_count << "]"; } void MDSPerfMetricQuery::pack_counters(const PerformanceCounters &counters, bufferlist *bl) const { auto it = counters.begin(); for (auto &descriptor : performance_counter_descriptors) { if (it == counters.end()) { descriptor.pack_counter(PerformanceCounter(), bl); } else { descriptor.pack_counter(*it, bl); it++; } } } std::ostream &operator<<(std::ostream &os, const MDSPerfMetricQuery &query) { return os << "[key=" << query.key_descriptor << ", counter=" << query.performance_counter_descriptors << "]"; }
5,513
34.805195
90
cc
null
ceph-main/src/mgr/MDSPerfMetricTypes.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_MGR_MDS_PERF_METRIC_TYPES_H #define CEPH_MGR_MDS_PERF_METRIC_TYPES_H #include <regex> #include <vector> #include <iostream> #include "include/denc.h" #include "include/stringify.h" #include "mds/mdstypes.h" #include "mgr/Types.h" typedef std::vector<std::string> MDSPerfMetricSubKey; // array of regex match typedef std::vector<MDSPerfMetricSubKey> MDSPerfMetricKey; enum class MDSPerfMetricSubKeyType : uint8_t { MDS_RANK = 0, CLIENT_ID = 1, }; struct MDSPerfMetricSubKeyDescriptor { MDSPerfMetricSubKeyType type = static_cast<MDSPerfMetricSubKeyType>(-1); std::string regex_str; std::regex regex; bool is_supported() const { switch (type) { case MDSPerfMetricSubKeyType::MDS_RANK: case MDSPerfMetricSubKeyType::CLIENT_ID: return true; default: return false; } } MDSPerfMetricSubKeyDescriptor() { } MDSPerfMetricSubKeyDescriptor(MDSPerfMetricSubKeyType type, const std::string &regex_str) : type(type), regex_str(regex_str) { } bool operator<(const MDSPerfMetricSubKeyDescriptor &other) const { if (type < other.type) { return true; } if (type > other.type) { return false; } return regex_str < other.regex_str; } DENC(MDSPerfMetricSubKeyDescriptor, v, p) { DENC_START(1, 1, p); denc(v.type, p); denc(v.regex_str, p); DENC_FINISH(p); } }; WRITE_CLASS_DENC(MDSPerfMetricSubKeyDescriptor) std::ostream& operator<<(std::ostream& os, const MDSPerfMetricSubKeyDescriptor &d); typedef std::vector<MDSPerfMetricSubKeyDescriptor> MDSPerfMetricKeyDescriptor; template<> struct denc_traits<MDSPerfMetricKeyDescriptor> { static constexpr bool supported = true; static constexpr bool bounded = false; static constexpr bool featured = false; static constexpr bool need_contiguous = true; static void bound_encode(const MDSPerfMetricKeyDescriptor& v, size_t& p) { p += sizeof(uint32_t); const auto size = v.size(); if (size) { size_t per = 0; denc(v.front(), per); p += per * size; } } static void encode(const MDSPerfMetricKeyDescriptor& v, ceph::buffer::list::contiguous_appender& p) { denc_varint(v.size(), p); for (auto& i : v) { denc(i, p); } } static void decode(MDSPerfMetricKeyDescriptor& v, ceph::buffer::ptr::const_iterator& p) { unsigned num; denc_varint(num, p); v.clear(); v.reserve(num); for (unsigned i=0; i < num; ++i) { MDSPerfMetricSubKeyDescriptor d; denc(d, p); if (!d.is_supported()) { v.clear(); return; } try { d.regex = d.regex_str.c_str(); } catch (const std::regex_error& e) { v.clear(); return; } if (d.regex.mark_count() == 0) { v.clear(); return; } v.push_back(std::move(d)); } } }; enum class MDSPerformanceCounterType : uint8_t { CAP_HIT_METRIC = 0, READ_LATENCY_METRIC = 1, WRITE_LATENCY_METRIC = 2, METADATA_LATENCY_METRIC = 3, DENTRY_LEASE_METRIC = 4, OPENED_FILES_METRIC = 5, PINNED_ICAPS_METRIC = 6, OPENED_INODES_METRIC = 7, READ_IO_SIZES_METRIC = 8, WRITE_IO_SIZES_METRIC = 9, AVG_READ_LATENCY_METRIC = 10, STDEV_READ_LATENCY_METRIC = 11, AVG_WRITE_LATENCY_METRIC = 12, STDEV_WRITE_LATENCY_METRIC = 13, AVG_METADATA_LATENCY_METRIC = 14, STDEV_METADATA_LATENCY_METRIC = 15, }; struct MDSPerformanceCounterDescriptor { MDSPerformanceCounterType type = static_cast<MDSPerformanceCounterType>(-1); bool is_supported() const { switch(type) { case MDSPerformanceCounterType::CAP_HIT_METRIC: case MDSPerformanceCounterType::READ_LATENCY_METRIC: case MDSPerformanceCounterType::WRITE_LATENCY_METRIC: case MDSPerformanceCounterType::METADATA_LATENCY_METRIC: case MDSPerformanceCounterType::DENTRY_LEASE_METRIC: case MDSPerformanceCounterType::OPENED_FILES_METRIC: case MDSPerformanceCounterType::PINNED_ICAPS_METRIC: case MDSPerformanceCounterType::OPENED_INODES_METRIC: case MDSPerformanceCounterType::READ_IO_SIZES_METRIC: case MDSPerformanceCounterType::WRITE_IO_SIZES_METRIC: case MDSPerformanceCounterType::AVG_READ_LATENCY_METRIC: case MDSPerformanceCounterType::STDEV_READ_LATENCY_METRIC: case MDSPerformanceCounterType::AVG_WRITE_LATENCY_METRIC: case MDSPerformanceCounterType::STDEV_WRITE_LATENCY_METRIC: case MDSPerformanceCounterType::AVG_METADATA_LATENCY_METRIC: case MDSPerformanceCounterType::STDEV_METADATA_LATENCY_METRIC: return true; default: return false; } } MDSPerformanceCounterDescriptor() { } MDSPerformanceCounterDescriptor(MDSPerformanceCounterType type) : type(type) { } bool operator<(const MDSPerformanceCounterDescriptor &other) const { return type < other.type; } bool operator==(const MDSPerformanceCounterDescriptor &other) const { return type == other.type; } bool operator!=(const MDSPerformanceCounterDescriptor &other) const { return type != other.type; } DENC(MDSPerformanceCounterDescriptor, v, p) { DENC_START(1, 1, p); denc(v.type, p); DENC_FINISH(p); } void pack_counter(const PerformanceCounter &c, ceph::buffer::list *bl) const; void unpack_counter(ceph::buffer::list::const_iterator& bl, PerformanceCounter *c) const; }; WRITE_CLASS_DENC(MDSPerformanceCounterDescriptor) std::ostream& operator<<(std::ostream &os, const MDSPerformanceCounterDescriptor &d); typedef std::vector<MDSPerformanceCounterDescriptor> MDSPerformanceCounterDescriptors; template<> struct denc_traits<MDSPerformanceCounterDescriptors> { static constexpr bool supported = true; static constexpr bool bounded = false; static constexpr bool featured = false; static constexpr bool need_contiguous = true; static void bound_encode(const MDSPerformanceCounterDescriptors& v, size_t& p) { p += sizeof(uint32_t); const auto size = v.size(); if (size) { size_t per = 0; denc(v.front(), per); p += per * size; } } static void encode(const MDSPerformanceCounterDescriptors& v, ceph::buffer::list::contiguous_appender& p) { denc_varint(v.size(), p); for (auto& i : v) { denc(i, p); } } static void decode(MDSPerformanceCounterDescriptors& v, ceph::buffer::ptr::const_iterator& p) { unsigned num; denc_varint(num, p); v.clear(); v.reserve(num); for (unsigned i=0; i < num; ++i) { MDSPerformanceCounterDescriptor d; denc(d, p); if (d.is_supported()) { v.push_back(std::move(d)); } } } }; struct MDSPerfMetricLimit { MDSPerformanceCounterDescriptor order_by; uint64_t max_count; MDSPerfMetricLimit() { } MDSPerfMetricLimit(const MDSPerformanceCounterDescriptor &order_by, uint64_t max_count) : order_by(order_by), max_count(max_count) { } bool operator<(const MDSPerfMetricLimit &other) const { if (order_by != other.order_by) { return order_by < other.order_by; } return max_count < other.max_count; } DENC(MDSPerfMetricLimit, v, p) { DENC_START(1, 1, p); denc(v.order_by, p); denc(v.max_count, p); DENC_FINISH(p); } }; WRITE_CLASS_DENC(MDSPerfMetricLimit) std::ostream &operator<<(std::ostream &os, const MDSPerfMetricLimit &limit); typedef std::set<MDSPerfMetricLimit> MDSPerfMetricLimits; struct MDSPerfMetricQuery { MDSPerfMetricKeyDescriptor key_descriptor; MDSPerformanceCounterDescriptors performance_counter_descriptors; MDSPerfMetricQuery() { } MDSPerfMetricQuery(const MDSPerfMetricKeyDescriptor &key_descriptor, const MDSPerformanceCounterDescriptors &performance_counter_descriptors) : key_descriptor(key_descriptor), performance_counter_descriptors(performance_counter_descriptors) { } bool operator<(const MDSPerfMetricQuery &other) const { if (key_descriptor < other.key_descriptor) { return true; } if (key_descriptor > other.key_descriptor) { return false; } return performance_counter_descriptors < other.performance_counter_descriptors; } template <typename L> bool get_key(L&& get_sub_key, MDSPerfMetricKey *key) const { for (auto &sub_key_descriptor : key_descriptor) { MDSPerfMetricSubKey sub_key; if (!get_sub_key(sub_key_descriptor, &sub_key)) { return false; } key->push_back(sub_key); } return true; } void get_performance_counter_descriptors(MDSPerformanceCounterDescriptors *descriptors) const { *descriptors = performance_counter_descriptors; } template <typename L> void update_counters(L &&update_counter, PerformanceCounters *counters) const { auto it = counters->begin(); for (auto &descriptor : performance_counter_descriptors) { // TODO: optimize if (it == counters->end()) { counters->push_back(PerformanceCounter()); it = std::prev(counters->end()); } update_counter(descriptor, &(*it)); it++; } } DENC(MDSPerfMetricQuery, v, p) { DENC_START(1, 1, p); denc(v.key_descriptor, p); denc(v.performance_counter_descriptors, p); DENC_FINISH(p); } void pack_counters(const PerformanceCounters &counters, ceph::buffer::list *bl) const; }; WRITE_CLASS_DENC(MDSPerfMetricQuery) std::ostream &operator<<(std::ostream &os, const MDSPerfMetricQuery &query); struct MDSPerfCollector : PerfCollector { std::map<MDSPerfMetricKey, PerformanceCounters> counters; std::set<mds_rank_t> delayed_ranks; utime_t last_updated_mono; MDSPerfCollector(MetricQueryID query_id) : PerfCollector(query_id) { } }; struct MDSPerfMetrics { MDSPerformanceCounterDescriptors performance_counter_descriptors; std::map<MDSPerfMetricKey, ceph::buffer::list> group_packed_performance_counters; DENC(MDSPerfMetrics, v, p) { DENC_START(1, 1, p); denc(v.performance_counter_descriptors, p); denc(v.group_packed_performance_counters, p); DENC_FINISH(p); } }; struct MDSPerfMetricReport { std::map<MDSPerfMetricQuery, MDSPerfMetrics> reports; // set of active ranks that have delayed (stale) metrics std::set<mds_rank_t> rank_metrics_delayed; DENC(MDSPerfMetricReport, v, p) { DENC_START(1, 1, p); denc(v.reports, p); denc(v.rank_metrics_delayed, p); DENC_FINISH(p); } }; WRITE_CLASS_DENC(MDSPerfMetrics) WRITE_CLASS_DENC(MDSPerfMetricReport) #endif // CEPH_MGR_MDS_PERF_METRIC_TYPES_H
10,607
27.826087
97
h
null
ceph-main/src/mgr/MetricCollector.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "common/debug.h" #include "common/errno.h" #include "mgr/MetricCollector.h" #include "mgr/OSDPerfMetricTypes.h" #include "mgr/MDSPerfMetricTypes.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr.metric_collector " << __func__ << ": " template <typename Query, typename Limit, typename Key, typename Report> MetricCollector<Query, Limit, Key, Report>::MetricCollector(MetricListener &listener) : listener(listener) { } template <typename Query, typename Limit, typename Key, typename Report> MetricQueryID MetricCollector<Query, Limit, Key, Report>::add_query( const Query &query, const std::optional<Limit> &limit) { dout(20) << "query=" << query << ", limit=" << limit << dendl; uint64_t query_id; bool notify = false; { std::lock_guard locker(lock); query_id = next_query_id++; auto it = queries.find(query); if (it == queries.end()) { it = queries.emplace(query, std::map<MetricQueryID, OptionalLimit>{}).first; notify = true; } else if (is_limited(it->second)) { notify = true; } it->second.emplace(query_id, limit); counters.emplace(query_id, std::map<Key, PerformanceCounters>{}); } dout(10) << query << " " << (limit ? stringify(*limit) : "unlimited") << " query_id=" << query_id << dendl; if (notify) { listener.handle_query_updated(); } return query_id; } template <typename Query, typename Limit, typename Key, typename Report> int MetricCollector<Query, Limit, Key, Report>::remove_query(MetricQueryID query_id) { dout(20) << "query_id=" << query_id << dendl; bool found = false; bool notify = false; { std::lock_guard locker(lock); for (auto it = queries.begin() ; it != queries.end();) { auto iter = it->second.find(query_id); if (iter == it->second.end()) { ++it; continue; } it->second.erase(iter); if (it->second.empty()) { it = queries.erase(it); notify = true; } else if (is_limited(it->second)) { ++it; notify = true; } found = true; break; } counters.erase(query_id); } if (!found) { dout(10) << query_id << " not found" << dendl; return -ENOENT; } dout(10) << query_id << dendl; if (notify) { listener.handle_query_updated(); } return 0; } template <typename Query, typename Limit, typename Key, typename Report> void MetricCollector<Query, Limit, Key, Report>::remove_all_queries() { dout(20) << dendl; bool notify; { std::lock_guard locker(lock); notify = !queries.empty(); queries.clear(); } if (notify) { listener.handle_query_updated(); } } template <typename Query, typename Limit, typename Key, typename Report> void MetricCollector<Query, Limit, Key, Report>::reregister_queries() { dout(20) << dendl; listener.handle_query_updated(); } template <typename Query, typename Limit, typename Key, typename Report> int MetricCollector<Query, Limit, Key, Report>::get_counters_generic( MetricQueryID query_id, std::map<Key, PerformanceCounters> *c) { dout(20) << dendl; ceph_assert(ceph_mutex_is_locked(lock)); auto it = counters.find(query_id); if (it == counters.end()) { dout(10) << "counters for " << query_id << " not found" << dendl; return -ENOENT; } *c = std::move(it->second); it->second.clear(); return 0; } template <typename Query, typename Limit, typename Key, typename Report> void MetricCollector<Query, Limit, Key, Report>::process_reports_generic( const std::map<Query, Report> &reports, UpdateCallback callback) { ceph_assert(ceph_mutex_is_locked(lock)); if (reports.empty()) { return; } for (auto& [query, report] : reports) { dout(10) << "report for " << query << " query: " << report.group_packed_performance_counters.size() << " records" << dendl; for (auto& [key, bl] : report.group_packed_performance_counters) { auto bl_it = bl.cbegin(); for (auto& p : queries[query]) { auto &key_counters = counters[p.first][key]; if (key_counters.empty()) { key_counters.resize(query.performance_counter_descriptors.size(), {0, 0}); } } auto desc_it = report.performance_counter_descriptors.begin(); for (size_t i = 0; i < query.performance_counter_descriptors.size(); i++) { if (desc_it == report.performance_counter_descriptors.end()) { break; } if (*desc_it != query.performance_counter_descriptors[i]) { continue; } PerformanceCounter c; desc_it->unpack_counter(bl_it, &c); dout(20) << "counter " << key << " " << *desc_it << ": " << c << dendl; for (auto& p : queries[query]) { auto &key_counters = counters[p.first][key]; callback(&key_counters[i], c); } desc_it++; } } } } template class MetricCollector<OSDPerfMetricQuery, OSDPerfMetricLimit, OSDPerfMetricKey, OSDPerfMetricReport>; template class MetricCollector<MDSPerfMetricQuery, MDSPerfMetricLimit, MDSPerfMetricKey, MDSPerfMetrics>;
5,334
26.786458
95
cc
null
ceph-main/src/mgr/MetricCollector.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_MGR_METRIC_COLLECTOR_H #define CEPH_MGR_METRIC_COLLECTOR_H #include <map> #include <set> #include <tuple> #include <vector> #include <utility> #include <algorithm> #include "common/ceph_mutex.h" #include "msg/Message.h" #include "mgr/Types.h" #include "mgr/MetricTypes.h" class MMgrReport; template <typename Query, typename Limit, typename Key, typename Report> class MetricCollector { public: virtual ~MetricCollector() { } using Limits = std::set<Limit>; MetricCollector(MetricListener &listener); MetricQueryID add_query(const Query &query, const std::optional<Limit> &limit); int remove_query(MetricQueryID query_id); void remove_all_queries(); void reregister_queries(); std::map<Query, Limits> get_queries() const { std::lock_guard locker(lock); std::map<Query, Limits> result; for (auto& [query, limits] : queries) { auto result_it = result.insert({query, {}}).first; if (is_limited(limits)) { for (auto& limit : limits) { if (limit.second) { result_it->second.insert(*limit.second); } } } } return result; } virtual void process_reports(const MetricPayload &payload) = 0; virtual int get_counters(PerfCollector *collector) = 0; protected: typedef std::optional<Limit> OptionalLimit; typedef std::map<MetricQueryID, OptionalLimit> QueryIDLimit; typedef std::map<Query, QueryIDLimit> Queries; typedef std::map<MetricQueryID, std::map<Key, PerformanceCounters>> Counters; typedef std::function<void(PerformanceCounter *, const PerformanceCounter &)> UpdateCallback; mutable ceph::mutex lock = ceph::make_mutex("mgr::metric::collector::lock"); Queries queries; Counters counters; void process_reports_generic(const std::map<Query, Report> &reports, UpdateCallback callback); int get_counters_generic(MetricQueryID query_id, std::map<Key, PerformanceCounters> *counters); private: MetricListener &listener; MetricQueryID next_query_id = 0; bool is_limited(const std::map<MetricQueryID, OptionalLimit> &limits) const { return std::any_of(begin(limits), end(limits), [](auto &limits) { return limits.second.has_value(); }); } }; #endif // CEPH_MGR_METRIC_COLLECTOR_H
2,367
26.534884
97
h
null
ceph-main/src/mgr/MetricTypes.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_MGR_METRIC_TYPES_H #define CEPH_MGR_METRIC_TYPES_H #include <boost/variant.hpp> #include "include/denc.h" #include "include/ceph_features.h" #include "mgr/OSDPerfMetricTypes.h" #include "mgr/MDSPerfMetricTypes.h" enum class MetricReportType { METRIC_REPORT_TYPE_OSD = 0, METRIC_REPORT_TYPE_MDS = 1, }; struct OSDMetricPayload { static const MetricReportType METRIC_REPORT_TYPE = MetricReportType::METRIC_REPORT_TYPE_OSD; std::map<OSDPerfMetricQuery, OSDPerfMetricReport> report; OSDMetricPayload() { } OSDMetricPayload(const std::map<OSDPerfMetricQuery, OSDPerfMetricReport> &report) : report(report) { } DENC(OSDMetricPayload, v, p) { DENC_START(1, 1, p); denc(v.report, p); DENC_FINISH(p); } }; struct MDSMetricPayload { static const MetricReportType METRIC_REPORT_TYPE = MetricReportType::METRIC_REPORT_TYPE_MDS; MDSPerfMetricReport metric_report; MDSMetricPayload() { } MDSMetricPayload(const MDSPerfMetricReport &metric_report) : metric_report(metric_report) { } DENC(MDSMetricPayload, v, p) { DENC_START(1, 1, p); denc(v.metric_report, p); DENC_FINISH(p); } }; struct UnknownMetricPayload { static const MetricReportType METRIC_REPORT_TYPE = static_cast<MetricReportType>(-1); UnknownMetricPayload() { } DENC(UnknownMetricPayload, v, p) { ceph_abort(); } }; WRITE_CLASS_DENC(OSDMetricPayload) WRITE_CLASS_DENC(MDSMetricPayload) WRITE_CLASS_DENC(UnknownMetricPayload) typedef boost::variant<OSDMetricPayload, MDSMetricPayload, UnknownMetricPayload> MetricPayload; class EncodeMetricPayloadVisitor : public boost::static_visitor<void> { public: explicit EncodeMetricPayloadVisitor(ceph::buffer::list &bl) : m_bl(bl) { } template <typename MetricPayload> inline void operator()(const MetricPayload &payload) const { using ceph::encode; encode(static_cast<uint32_t>(MetricPayload::METRIC_REPORT_TYPE), m_bl); encode(payload, m_bl); } private: ceph::buffer::list &m_bl; }; class DecodeMetricPayloadVisitor : public boost::static_visitor<void> { public: DecodeMetricPayloadVisitor(ceph::buffer::list::const_iterator &iter) : m_iter(iter) { } template <typename MetricPayload> inline void operator()(MetricPayload &payload) const { using ceph::decode; decode(payload, m_iter); } private: ceph::buffer::list::const_iterator &m_iter; }; struct MetricReportMessage { MetricPayload payload; MetricReportMessage(const MetricPayload &payload = UnknownMetricPayload()) : payload(payload) { } bool should_encode(uint64_t features) const { if (!HAVE_FEATURE(features, SERVER_PACIFIC) && boost::get<MDSMetricPayload>(&payload)) { return false; } return true; } void encode(ceph::buffer::list &bl) const { boost::apply_visitor(EncodeMetricPayloadVisitor(bl), payload); } void decode(ceph::buffer::list::const_iterator &iter) { using ceph::decode; uint32_t metric_report_type; decode(metric_report_type, iter); switch (static_cast<MetricReportType>(metric_report_type)) { case MetricReportType::METRIC_REPORT_TYPE_OSD: payload = OSDMetricPayload(); break; case MetricReportType::METRIC_REPORT_TYPE_MDS: payload = MDSMetricPayload(); break; default: payload = UnknownMetricPayload(); break; } boost::apply_visitor(DecodeMetricPayloadVisitor(iter), payload); } }; WRITE_CLASS_ENCODER(MetricReportMessage); // variant for sending configure message to mgr clients enum MetricConfigType { METRIC_CONFIG_TYPE_OSD = 0, METRIC_CONFIG_TYPE_MDS = 1, }; struct OSDConfigPayload { static const MetricConfigType METRIC_CONFIG_TYPE = MetricConfigType::METRIC_CONFIG_TYPE_OSD; std::map<OSDPerfMetricQuery, OSDPerfMetricLimits> config; OSDConfigPayload() { } OSDConfigPayload(const std::map<OSDPerfMetricQuery, OSDPerfMetricLimits> &config) : config(config) { } DENC(OSDConfigPayload, v, p) { DENC_START(1, 1, p); denc(v.config, p); DENC_FINISH(p); } }; struct MDSConfigPayload { static const MetricConfigType METRIC_CONFIG_TYPE = MetricConfigType::METRIC_CONFIG_TYPE_MDS; std::map<MDSPerfMetricQuery, MDSPerfMetricLimits> config; MDSConfigPayload() { } MDSConfigPayload(const std::map<MDSPerfMetricQuery, MDSPerfMetricLimits> &config) : config(config) { } DENC(MDSConfigPayload, v, p) { DENC_START(1, 1, p); denc(v.config, p); DENC_FINISH(p); } }; struct UnknownConfigPayload { static const MetricConfigType METRIC_CONFIG_TYPE = static_cast<MetricConfigType>(-1); UnknownConfigPayload() { } DENC(UnknownConfigPayload, v, p) { ceph_abort(); } }; WRITE_CLASS_DENC(OSDConfigPayload) WRITE_CLASS_DENC(MDSConfigPayload) WRITE_CLASS_DENC(UnknownConfigPayload) typedef boost::variant<OSDConfigPayload, MDSConfigPayload, UnknownConfigPayload> ConfigPayload; class EncodeConfigPayloadVisitor : public boost::static_visitor<void> { public: explicit EncodeConfigPayloadVisitor(ceph::buffer::list &bl) : m_bl(bl) { } template <typename ConfigPayload> inline void operator()(const ConfigPayload &payload) const { using ceph::encode; encode(static_cast<uint32_t>(ConfigPayload::METRIC_CONFIG_TYPE), m_bl); encode(payload, m_bl); } private: ceph::buffer::list &m_bl; }; class DecodeConfigPayloadVisitor : public boost::static_visitor<void> { public: DecodeConfigPayloadVisitor(ceph::buffer::list::const_iterator &iter) : m_iter(iter) { } template <typename ConfigPayload> inline void operator()(ConfigPayload &payload) const { using ceph::decode; decode(payload, m_iter); } private: ceph::buffer::list::const_iterator &m_iter; }; struct MetricConfigMessage { ConfigPayload payload; MetricConfigMessage(const ConfigPayload &payload = UnknownConfigPayload()) : payload(payload) { } bool should_encode(uint64_t features) const { if (!HAVE_FEATURE(features, SERVER_PACIFIC) && boost::get<MDSConfigPayload>(&payload)) { return false; } return true; } void encode(ceph::buffer::list &bl) const { boost::apply_visitor(EncodeConfigPayloadVisitor(bl), payload); } void decode(ceph::buffer::list::const_iterator &iter) { using ceph::decode; uint32_t metric_config_type; decode(metric_config_type, iter); switch (metric_config_type) { case MetricConfigType::METRIC_CONFIG_TYPE_OSD: payload = OSDConfigPayload(); break; case MetricConfigType::METRIC_CONFIG_TYPE_MDS: payload = MDSConfigPayload(); break; default: payload = UnknownConfigPayload(); break; } boost::apply_visitor(DecodeConfigPayloadVisitor(iter), payload); } }; WRITE_CLASS_ENCODER(MetricConfigMessage); #endif // CEPH_MGR_METRIC_TYPES_H
6,982
24.118705
94
h
null
ceph-main/src/mgr/Mgr.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 John Spray <[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 <Python.h> #include "osdc/Objecter.h" #include "client/Client.h" #include "common/errno.h" #include "mon/MonClient.h" #include "include/stringify.h" #include "global/global_context.h" #include "global/signal_handler.h" #ifdef WITH_LIBCEPHSQLITE # include <sqlite3.h> # include "include/libcephsqlite.h" #endif #include "mgr/MgrContext.h" #include "DaemonServer.h" #include "messages/MMgrDigest.h" #include "messages/MCommand.h" #include "messages/MCommandReply.h" #include "messages/MLog.h" #include "messages/MServiceMap.h" #include "messages/MKVData.h" #include "PyModule.h" #include "Mgr.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr " << __func__ << " " using namespace std::literals; using std::map; using std::ostringstream; using std::string; Mgr::Mgr(MonClient *monc_, const MgrMap& mgrmap, PyModuleRegistry *py_module_registry_, Messenger *clientm_, Objecter *objecter_, Client* client_, LogChannelRef clog_, LogChannelRef audit_clog_) : monc(monc_), objecter(objecter_), client(client_), client_messenger(clientm_), finisher(g_ceph_context, "Mgr", "mgr-fin"), digest_received(false), py_module_registry(py_module_registry_), cluster_state(monc, nullptr, mgrmap), server(monc, finisher, daemon_state, cluster_state, *py_module_registry, clog_, audit_clog_), clog(clog_), audit_clog(audit_clog_), initialized(false), initializing(false) { cluster_state.set_objecter(objecter); } Mgr::~Mgr() { } void MetadataUpdate::finish(int r) { daemon_state.clear_updating(key); if (r == 0) { if (key.type == "mds" || key.type == "osd" || key.type == "mgr" || key.type == "mon") { json_spirit::mValue json_result; bool read_ok = json_spirit::read( outbl.to_str(), json_result); if (!read_ok) { dout(1) << "mon returned invalid JSON for " << key << dendl; return; } if (json_result.type() != json_spirit::obj_type) { dout(1) << "mon returned valid JSON " << key << " but not an object: '" << outbl.to_str() << "'" << dendl; return; } dout(4) << "mon returned valid metadata JSON for " << key << dendl; json_spirit::mObject daemon_meta = json_result.get_obj(); // Skip daemon who doesn't have hostname yet if (daemon_meta.count("hostname") == 0) { dout(1) << "Skipping incomplete metadata entry for " << key << dendl; return; } // Apply any defaults for (const auto &i : defaults) { if (daemon_meta.find(i.first) == daemon_meta.end()) { daemon_meta[i.first] = i.second; } } if (daemon_state.exists(key)) { DaemonStatePtr state = daemon_state.get(key); map<string,string> m; { std::lock_guard l(state->lock); state->hostname = daemon_meta.at("hostname").get_str(); if (key.type == "mds" || key.type == "mgr" || key.type == "mon") { daemon_meta.erase("name"); } else if (key.type == "osd") { daemon_meta.erase("id"); } daemon_meta.erase("hostname"); for (const auto &[key, val] : daemon_meta) { m.emplace(key, val.get_str()); } } daemon_state.update_metadata(state, m); } else { auto state = std::make_shared<DaemonState>(daemon_state.types); state->key = key; state->hostname = daemon_meta.at("hostname").get_str(); if (key.type == "mds" || key.type == "mgr" || key.type == "mon") { daemon_meta.erase("name"); } else if (key.type == "osd") { daemon_meta.erase("id"); } daemon_meta.erase("hostname"); map<string,string> m; for (const auto &[key, val] : daemon_meta) { m.emplace(key, val.get_str()); } state->set_metadata(m); daemon_state.insert(state); } } else { ceph_abort(); } } else { dout(1) << "mon failed to return metadata for " << key << ": " << cpp_strerror(r) << dendl; } } void Mgr::background_init(Context *completion) { std::lock_guard l(lock); ceph_assert(!initializing); ceph_assert(!initialized); initializing = true; finisher.start(); finisher.queue(new LambdaContext([this, completion](int r){ init(); completion->complete(0); })); } std::map<std::string, std::string> Mgr::load_store() { ceph_assert(ceph_mutex_is_locked_by_me(lock)); dout(10) << "listing keys" << dendl; JSONCommand cmd; cmd.run(monc, "{\"prefix\": \"config-key ls\"}"); lock.unlock(); cmd.wait(); lock.lock(); ceph_assert(cmd.r == 0); std::map<std::string, std::string> loaded; for (auto &key_str : cmd.json_result.get_array()) { std::string const key = key_str.get_str(); dout(20) << "saw key '" << key << "'" << dendl; const std::string store_prefix = PyModule::mgr_store_prefix; const std::string device_prefix = "device/"; if (key.substr(0, device_prefix.size()) == device_prefix || key.substr(0, store_prefix.size()) == store_prefix) { dout(20) << "fetching '" << key << "'" << dendl; Command get_cmd; std::ostringstream cmd_json; cmd_json << "{\"prefix\": \"config-key get\", \"key\": \"" << key << "\"}"; get_cmd.run(monc, cmd_json.str()); lock.unlock(); get_cmd.wait(); lock.lock(); if (get_cmd.r == 0) { // tolerate racing config-key change loaded[key] = get_cmd.outbl.to_str(); } } } return loaded; } void Mgr::handle_signal(int signum) { ceph_assert(signum == SIGINT || signum == SIGTERM); shutdown(); } static void handle_mgr_signal(int signum) { derr << " *** Got signal " << sig_str(signum) << " ***" << dendl; // The python modules don't reliably shut down, so don't even // try. The mon will blocklist us (and all of our rados/cephfs // clients) anyway. Just exit! _exit(0); // exit with 0 result code, as if we had done an orderly shutdown } void Mgr::init() { std::unique_lock l(lock); ceph_assert(initializing); ceph_assert(!initialized); // Enable signal handlers register_async_signal_handler_oneshot(SIGINT, handle_mgr_signal); register_async_signal_handler_oneshot(SIGTERM, handle_mgr_signal); // Only pacific+ monitors support subscribe to kv updates bool mon_allows_kv_sub = false; monc->with_monmap( [&](const MonMap &monmap) { if (monmap.get_required_features().contains_all( ceph::features::mon::FEATURE_PACIFIC)) { mon_allows_kv_sub = true; } }); if (!mon_allows_kv_sub) { // mons are still pre-pacific. wait long enough to ensure our // next beacon is processed so that our module options are // propagated. See https://tracker.ceph.com/issues/49778 lock.unlock(); dout(10) << "waiting a bit for the pre-pacific mon to process our beacon" << dendl; sleep(g_conf().get_val<std::chrono::seconds>("mgr_tick_period").count() * 3); lock.lock(); } // subscribe to all the maps monc->sub_want("log-info", 0, 0); monc->sub_want("mgrdigest", 0, 0); monc->sub_want("fsmap", 0, 0); monc->sub_want("servicemap", 0, 0); if (mon_allows_kv_sub) { monc->sub_want("kv:config/", 0, 0); monc->sub_want("kv:mgr/", 0, 0); monc->sub_want("kv:device/", 0, 0); } dout(4) << "waiting for OSDMap..." << dendl; // Subscribe to OSDMap update to pass on to ClusterState objecter->maybe_request_map(); // reset the mon session. we get these maps through subscriptions which // are stateful with the connection, so even if *we* don't have them a // previous incarnation sharing the same MonClient may have. monc->reopen_session(); // Start Objecter and wait for OSD map lock.unlock(); // Drop lock because OSDMap dispatch calls into my ms_dispatch epoch_t e; cluster_state.with_mgrmap([&e](const MgrMap& m) { e = m.last_failure_osd_epoch; }); /* wait for any blocklists to be applied to previous mgr instance */ dout(4) << "Waiting for new OSDMap (e=" << e << ") that may blocklist prior active." << dendl; objecter->wait_for_osd_map(e); lock.lock(); // Start communicating with daemons to learn statistics etc int r = server.init(monc->get_global_id(), client_messenger->get_myaddrs()); if (r < 0) { derr << "Initialize server fail: " << cpp_strerror(r) << dendl; // This is typically due to a bind() failure, so let's let // systemd restart us. exit(1); } dout(4) << "Initialized server at " << server.get_myaddrs() << dendl; // Preload all daemon metadata (will subsequently keep this // up to date by watching maps, so do the initial load before // we subscribe to any maps) dout(4) << "Loading daemon metadata..." << dendl; load_all_metadata(); // Populate PGs in ClusterState cluster_state.with_osdmap_and_pgmap([this](const OSDMap &osd_map, const PGMap& pg_map) { cluster_state.notify_osdmap(osd_map); }); // Wait for FSMap dout(4) << "waiting for FSMap..." << dendl; fs_map_cond.wait(l, [this] { return cluster_state.have_fsmap();}); // Wait for MgrDigest... dout(4) << "waiting for MgrDigest..." << dendl; digest_cond.wait(l, [this] { return digest_received; }); if (!mon_allows_kv_sub) { dout(4) << "loading config-key data from pre-pacific mon cluster..." << dendl; pre_init_store = load_store(); } dout(4) << "initializing device state..." << dendl; // Note: we only have to do this during startup because once we are // active the only changes to this state will originate from one of our // own modules. for (auto p = pre_init_store.lower_bound("device/"); p != pre_init_store.end() && p->first.find("device/") == 0; ++p) { string devid = p->first.substr(7); dout(10) << " updating " << devid << dendl; map<string,string> meta; ostringstream ss; int r = get_json_str_map(p->second, ss, &meta, false); if (r < 0) { derr << __func__ << " failed to parse " << p->second << ": " << ss.str() << dendl; } else { daemon_state.with_device_create( devid, [&meta] (DeviceState& dev) { dev.set_metadata(std::move(meta)); }); } } // assume finisher already initialized in background_init dout(4) << "starting python modules..." << dendl; py_module_registry->active_start( daemon_state, cluster_state, pre_init_store, mon_allows_kv_sub, *monc, clog, audit_clog, *objecter, *client, finisher, server); cluster_state.final_init(); AdminSocket *admin_socket = g_ceph_context->get_admin_socket(); r = admin_socket->register_command( "mgr_status", this, "Dump mgr status"); ceph_assert(r == 0); #ifdef WITH_LIBCEPHSQLITE dout(4) << "Using sqlite3 version: " << sqlite3_libversion() << dendl; /* See libcephsqlite.h for rationale of this code. */ sqlite3_auto_extension((void (*)())sqlite3_cephsqlite_init); { sqlite3* db = nullptr; if (int rc = sqlite3_open_v2(":memory:", &db, SQLITE_OPEN_READWRITE, nullptr); rc == SQLITE_OK) { sqlite3_close(db); } else { derr << "could not open sqlite3: " << rc << dendl; ceph_abort(); } } { char *ident = nullptr; if (int rc = cephsqlite_setcct(g_ceph_context, &ident); rc < 0) { derr << "could not set libcephsqlite cct: " << rc << dendl; ceph_abort(); } entity_addrvec_t addrv; addrv.parse(ident); ident = (char*)realloc(ident, 0); py_module_registry->register_client("libcephsqlite", addrv, true); } #endif dout(4) << "Complete." << dendl; initializing = false; initialized = true; } void Mgr::load_all_metadata() { ceph_assert(ceph_mutex_is_locked_by_me(lock)); JSONCommand mds_cmd; mds_cmd.run(monc, "{\"prefix\": \"mds metadata\"}"); JSONCommand osd_cmd; osd_cmd.run(monc, "{\"prefix\": \"osd metadata\"}"); JSONCommand mon_cmd; mon_cmd.run(monc, "{\"prefix\": \"mon metadata\"}"); lock.unlock(); mds_cmd.wait(); osd_cmd.wait(); mon_cmd.wait(); lock.lock(); ceph_assert(mds_cmd.r == 0); ceph_assert(mon_cmd.r == 0); ceph_assert(osd_cmd.r == 0); for (auto &metadata_val : mds_cmd.json_result.get_array()) { json_spirit::mObject daemon_meta = metadata_val.get_obj(); if (daemon_meta.count("hostname") == 0) { dout(1) << "Skipping incomplete metadata entry" << dendl; continue; } DaemonStatePtr dm = std::make_shared<DaemonState>(daemon_state.types); dm->key = DaemonKey{"mds", daemon_meta.at("name").get_str()}; dm->hostname = daemon_meta.at("hostname").get_str(); daemon_meta.erase("name"); daemon_meta.erase("hostname"); for (const auto &[key, val] : daemon_meta) { dm->metadata.emplace(key, val.get_str()); } daemon_state.insert(dm); } for (auto &metadata_val : mon_cmd.json_result.get_array()) { json_spirit::mObject daemon_meta = metadata_val.get_obj(); if (daemon_meta.count("hostname") == 0) { dout(1) << "Skipping incomplete metadata entry" << dendl; continue; } DaemonStatePtr dm = std::make_shared<DaemonState>(daemon_state.types); dm->key = DaemonKey{"mon", daemon_meta.at("name").get_str()}; dm->hostname = daemon_meta.at("hostname").get_str(); daemon_meta.erase("name"); daemon_meta.erase("hostname"); map<string,string> m; for (const auto &[key, val] : daemon_meta) { m.emplace(key, val.get_str()); } dm->set_metadata(m); daemon_state.insert(dm); } for (auto &osd_metadata_val : osd_cmd.json_result.get_array()) { json_spirit::mObject osd_metadata = osd_metadata_val.get_obj(); if (osd_metadata.count("hostname") == 0) { dout(1) << "Skipping incomplete metadata entry" << dendl; continue; } dout(4) << osd_metadata.at("hostname").get_str() << dendl; DaemonStatePtr dm = std::make_shared<DaemonState>(daemon_state.types); dm->key = DaemonKey{"osd", stringify(osd_metadata.at("id").get_int())}; dm->hostname = osd_metadata.at("hostname").get_str(); osd_metadata.erase("id"); osd_metadata.erase("hostname"); map<string,string> m; for (const auto &i : osd_metadata) { m[i.first] = i.second.get_str(); } dm->set_metadata(m); daemon_state.insert(dm); } } void Mgr::shutdown() { dout(10) << "mgr shutdown init" << dendl; finisher.queue(new LambdaContext([&](int) { { std::lock_guard l(lock); // First stop the server so that we're not taking any more incoming // requests server.shutdown(); } // after the messenger is stopped, signal modules to shutdown via finisher py_module_registry->active_shutdown(); })); // Then stop the finisher to ensure its enqueued contexts aren't going // to touch references to the things we're about to tear down finisher.wait_for_empty(); finisher.stop(); } void Mgr::handle_osd_map() { ceph_assert(ceph_mutex_is_locked_by_me(lock)); std::set<std::string> names_exist; /** * When we see a new OSD map, inspect the entity addrs to * see if they have changed (service restart), and if so * reload the metadata. */ cluster_state.with_osdmap_and_pgmap([this, &names_exist](const OSDMap &osd_map, const PGMap &pg_map) { for (int osd_id = 0; osd_id < osd_map.get_max_osd(); ++osd_id) { if (!osd_map.exists(osd_id)) { continue; } // Remember which OSDs exist so that we can cull any that don't names_exist.insert(stringify(osd_id)); // Consider whether to update the daemon metadata (new/restarted daemon) const auto k = DaemonKey{"osd", std::to_string(osd_id)}; if (daemon_state.is_updating(k)) { continue; } bool update_meta = false; if (daemon_state.exists(k)) { if (osd_map.get_up_from(osd_id) == osd_map.get_epoch()) { dout(4) << "Mgr::handle_osd_map: osd." << osd_id << " joined cluster at " << "e" << osd_map.get_epoch() << dendl; update_meta = true; } } else { update_meta = true; } if (update_meta) { auto c = new MetadataUpdate(daemon_state, k); std::ostringstream cmd; cmd << "{\"prefix\": \"osd metadata\", \"id\": " << osd_id << "}"; monc->start_mon_command( {cmd.str()}, {}, &c->outbl, &c->outs, c); } } cluster_state.notify_osdmap(osd_map); }); // TODO: same culling for MonMap daemon_state.cull("osd", names_exist); } void Mgr::handle_log(ref_t<MLog> m) { for (const auto &e : m->entries) { py_module_registry->notify_all(e); } } void Mgr::handle_service_map(ref_t<MServiceMap> m) { dout(10) << "e" << m->service_map.epoch << dendl; monc->sub_got("servicemap", m->service_map.epoch); cluster_state.set_service_map(m->service_map); server.got_service_map(); } void Mgr::handle_mon_map() { dout(20) << __func__ << dendl; assert(ceph_mutex_is_locked_by_me(lock)); std::set<std::string> names_exist; cluster_state.with_monmap([&] (auto &monmap) { for (unsigned int i = 0; i < monmap.size(); i++) { names_exist.insert(monmap.get_name(i)); } }); for (const auto& name : names_exist) { const auto k = DaemonKey{"mon", name}; if (daemon_state.is_updating(k)) { continue; } auto c = new MetadataUpdate(daemon_state, k); constexpr std::string_view cmd = R"({{"prefix": "mon metadata", "id": "{}"}})"; monc->start_mon_command({fmt::format(cmd, name)}, {}, &c->outbl, &c->outs, c); } daemon_state.cull("mon", names_exist); } bool Mgr::ms_dispatch2(const ref_t<Message>& m) { dout(10) << *m << dendl; std::lock_guard l(lock); switch (m->get_type()) { case MSG_MGR_DIGEST: handle_mgr_digest(ref_cast<MMgrDigest>(m)); break; case CEPH_MSG_MON_MAP: py_module_registry->notify_all("mon_map", ""); handle_mon_map(); break; case CEPH_MSG_FS_MAP: py_module_registry->notify_all("fs_map", ""); handle_fs_map(ref_cast<MFSMap>(m)); return false; // I shall let this pass through for Client case CEPH_MSG_OSD_MAP: handle_osd_map(); py_module_registry->notify_all("osd_map", ""); // Continuous subscribe, so that we can generate notifications // for our MgrPyModules objecter->maybe_request_map(); break; case MSG_SERVICE_MAP: handle_service_map(ref_cast<MServiceMap>(m)); //no users: py_module_registry->notify_all("service_map", ""); break; case MSG_LOG: handle_log(ref_cast<MLog>(m)); break; case MSG_KV_DATA: { auto msg = ref_cast<MKVData>(m); monc->sub_got("kv:"s + msg->prefix, msg->version); if (!msg->data.empty()) { if (initialized) { py_module_registry->update_kv_data( msg->prefix, msg->incremental, msg->data ); } else { // before we have created the ActivePyModules, we need to // track the store regions we're monitoring if (!msg->incremental) { dout(10) << "full update on " << msg->prefix << dendl; auto p = pre_init_store.lower_bound(msg->prefix); while (p != pre_init_store.end() && p->first.find(msg->prefix) == 0) { dout(20) << " rm prior " << p->first << dendl; p = pre_init_store.erase(p); } } else { dout(10) << "incremental update on " << msg->prefix << dendl; } for (auto& i : msg->data) { if (i.second) { dout(20) << " set " << i.first << " = " << i.second->to_str() << dendl; pre_init_store[i.first] = i.second->to_str(); } else { dout(20) << " rm " << i.first << dendl; pre_init_store.erase(i.first); } } } } } break; default: return false; } return true; } void Mgr::handle_fs_map(ref_t<MFSMap> m) { ceph_assert(ceph_mutex_is_locked_by_me(lock)); std::set<std::string> names_exist; const FSMap &new_fsmap = m->get_fsmap(); monc->sub_got("fsmap", m->epoch); fs_map_cond.notify_all(); // TODO: callers (e.g. from python land) are potentially going to see // the new fsmap before we've bothered populating all the resulting // daemon_state. Maybe we should block python land while we're making // this kind of update? cluster_state.set_fsmap(new_fsmap); auto mds_info = new_fsmap.get_mds_info(); for (const auto &i : mds_info) { const auto &info = i.second; if (!new_fsmap.gid_exists(i.first)){ continue; } // Remember which MDS exists so that we can cull any that don't names_exist.insert(info.name); const auto k = DaemonKey{"mds", info.name}; if (daemon_state.is_updating(k)) { continue; } bool update = false; if (daemon_state.exists(k)) { auto metadata = daemon_state.get(k); std::lock_guard l(metadata->lock); if (metadata->metadata.empty() || metadata->metadata.count("addr") == 0) { update = true; } else { auto metadata_addrs = metadata->metadata.at("addr"); const auto map_addrs = info.addrs; update = metadata_addrs != stringify(map_addrs); if (update) { dout(4) << "MDS[" << info.name << "] addr change " << metadata_addrs << " != " << stringify(map_addrs) << dendl; } } } else { update = true; } if (update) { auto c = new MetadataUpdate(daemon_state, k); // Older MDS daemons don't have addr in the metadata, so // fake it if the returned metadata doesn't have the field. c->set_default("addr", stringify(info.addrs)); std::ostringstream cmd; cmd << "{\"prefix\": \"mds metadata\", \"who\": \"" << info.name << "\"}"; monc->start_mon_command( {cmd.str()}, {}, &c->outbl, &c->outs, c); } } daemon_state.cull("mds", names_exist); } bool Mgr::got_mgr_map(const MgrMap& m) { std::lock_guard l(lock); dout(10) << m << dendl; set<string> old_modules; cluster_state.with_mgrmap([&](const MgrMap& m) { old_modules = m.modules; }); if (m.modules != old_modules) { derr << "mgrmap module list changed to (" << m.modules << "), respawn" << dendl; return true; } cluster_state.set_mgr_map(m); server.got_mgr_map(); return false; } void Mgr::handle_mgr_digest(ref_t<MMgrDigest> m) { dout(10) << m->mon_status_json.length() << dendl; dout(10) << m->health_json.length() << dendl; cluster_state.load_digest(m.get()); //no users: py_module_registry->notify_all("mon_status", ""); py_module_registry->notify_all("health", ""); // Hack: use this as a tick/opportunity to prompt python-land that // the pgmap might have changed since last time we were here. py_module_registry->notify_all("pg_summary", ""); dout(10) << "done." << dendl; m.reset(); if (!digest_received) { digest_received = true; digest_cond.notify_all(); } } std::map<std::string, std::string> Mgr::get_services() const { std::lock_guard l(lock); return py_module_registry->get_services(); } int Mgr::call( std::string_view admin_command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& errss, bufferlist& out) { try { if (admin_command == "mgr_status") { f->open_object_section("mgr_status"); cluster_state.with_mgrmap( [f](const MgrMap& mm) { f->dump_unsigned("mgrmap_epoch", mm.get_epoch()); }); f->dump_bool("initialized", initialized); f->close_section(); return 0; } else { return -ENOSYS; } } catch (const TOPNSPC::common::bad_cmd_get& e) { errss << e.what(); return -EINVAL; } return 0; }
24,128
27.966387
101
cc
null
ceph-main/src/mgr/Mgr.h
// -*- 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 John Spray <[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. */ #ifndef CEPH_MGR_H_ #define CEPH_MGR_H_ // Python.h comes first because otherwise it clobbers ceph's assert #include <Python.h> #include "mds/FSMap.h" #include "messages/MFSMap.h" #include "msg/Messenger.h" #include "auth/Auth.h" #include "common/Finisher.h" #include "mon/MgrMap.h" #include "DaemonServer.h" #include "PyModuleRegistry.h" #include "DaemonState.h" #include "ClusterState.h" class MCommand; class MMgrDigest; class MLog; class MServiceMap; class Objecter; class Client; class Mgr : public AdminSocketHook { protected: MonClient *monc; Objecter *objecter; Client *client; Messenger *client_messenger; mutable ceph::mutex lock = ceph::make_mutex("Mgr::lock"); Finisher finisher; // Track receipt of initial data during startup ceph::condition_variable fs_map_cond; bool digest_received; ceph::condition_variable digest_cond; PyModuleRegistry *py_module_registry; DaemonStateIndex daemon_state; ClusterState cluster_state; DaemonServer server; LogChannelRef clog; LogChannelRef audit_clog; std::map<std::string, std::string> pre_init_store; void load_all_metadata(); std::map<std::string, std::string> load_store(); void init(); bool initialized; bool initializing; public: Mgr(MonClient *monc_, const MgrMap& mgrmap, PyModuleRegistry *py_module_registry_, Messenger *clientm_, Objecter *objecter_, Client *client_, LogChannelRef clog_, LogChannelRef audit_clog_); ~Mgr(); bool is_initialized() const {return initialized;} entity_addrvec_t get_server_addrs() const { return server.get_myaddrs(); } void handle_mgr_digest(ceph::ref_t<MMgrDigest> m); void handle_fs_map(ceph::ref_t<MFSMap> m); void handle_osd_map(); void handle_log(ceph::ref_t<MLog> m); void handle_service_map(ceph::ref_t<MServiceMap> m); void handle_mon_map(); bool got_mgr_map(const MgrMap& m); bool ms_dispatch2(const ceph::ref_t<Message>& m); void background_init(Context *completion); void shutdown(); void handle_signal(int signum); std::map<std::string, std::string> get_services() const; int call( std::string_view command, const cmdmap_t& cmdmap, const bufferlist& inbl, Formatter *f, std::ostream& errss, ceph::buffer::list& out) override; }; /** * Context for completion of metadata mon commands: take * the result and stash it in DaemonStateIndex */ class MetadataUpdate : public Context { private: DaemonStateIndex &daemon_state; DaemonKey key; std::map<std::string, std::string> defaults; public: bufferlist outbl; std::string outs; MetadataUpdate(DaemonStateIndex &daemon_state_, const DaemonKey &key_) : daemon_state(daemon_state_), key(key_) { daemon_state.notify_updating(key); } void set_default(const std::string &k, const std::string &v) { defaults[k] = v; } void finish(int r) override; }; #endif
3,325
21.937931
72
h
null
ceph-main/src/mgr/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) 2013 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 <boost/algorithm/string/predicate.hpp> #include <boost/config/warning_disable.hpp> #include <boost/fusion/adapted/struct/adapt_struct.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <boost/fusion/include/std_pair.hpp> #include <boost/phoenix.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/qi_uint.hpp> #include "MgrCap.h" #include "include/stringify.h" #include "include/ipaddr.h" #include "common/debug.h" #include "common/Formatter.h" #include <algorithm> #include <regex> #include "include/ceph_assert.h" static inline bool is_not_alnum_space(char c) { return !(isalpha(c) || isdigit(c) || (c == '-') || (c == '_')); } static std::string maybe_quote_string(const std::string& str) { if (find_if(str.begin(), str.end(), is_not_alnum_space) == str.end()) return str; return std::string("\"") + str + std::string("\""); } #define dout_subsys ceph_subsys_mgr std::ostream& operator<<(std::ostream& out, const mgr_rwxa_t& p) { if (p == MGR_CAP_ANY) return out << "*"; if (p & MGR_CAP_R) out << "r"; if (p & MGR_CAP_W) out << "w"; if (p & MGR_CAP_X) out << "x"; return out; } std::ostream& operator<<(std::ostream& out, const MgrCapGrantConstraint& c) { switch (c.match_type) { case MgrCapGrantConstraint::MATCH_TYPE_EQUAL: out << "="; break; case MgrCapGrantConstraint::MATCH_TYPE_PREFIX: out << " prefix "; break; case MgrCapGrantConstraint::MATCH_TYPE_REGEX: out << " regex "; break; default: break; } out << maybe_quote_string(c.value); return out; } std::ostream& operator<<(std::ostream& out, const MgrCapGrant& m) { if (!m.profile.empty()) { out << "profile " << maybe_quote_string(m.profile); } else { out << "allow"; if (!m.service.empty()) { out << " service " << maybe_quote_string(m.service); } else if (!m.module.empty()) { out << " module " << maybe_quote_string(m.module); } else if (!m.command.empty()) { out << " command " << maybe_quote_string(m.command); } } if (!m.arguments.empty()) { out << (!m.profile.empty() ? "" : " with"); for (auto& [key, constraint] : m.arguments) { out << " " << maybe_quote_string(key) << constraint; } } if (m.allow != 0) { out << " " << m.allow; } if (m.network.size()) { out << " network " << m.network; } return out; } // <magic> // fusion lets us easily populate structs via the qi parser. typedef std::map<std::string, MgrCapGrantConstraint> kvmap; BOOST_FUSION_ADAPT_STRUCT(MgrCapGrant, (std::string, service) (std::string, module) (std::string, profile) (std::string, command) (kvmap, arguments) (mgr_rwxa_t, allow) (std::string, network)) BOOST_FUSION_ADAPT_STRUCT(MgrCapGrantConstraint, (MgrCapGrantConstraint::MatchType, match_type) (std::string, value)) // </magic> void MgrCapGrant::parse_network() { network_valid = ::parse_network(network.c_str(), &network_parsed, &network_prefix); } void MgrCapGrant::expand_profile(std::ostream *err) const { // only generate this list once if (!profile_grants.empty()) { return; } if (profile == "read-only") { // grants READ-ONLY caps MGR-wide profile_grants.push_back({{}, {}, {}, {}, {}, mgr_rwxa_t{MGR_CAP_R}}); return; } if (profile == "read-write") { // grants READ-WRITE caps MGR-wide profile_grants.push_back({{}, {}, {}, {}, {}, mgr_rwxa_t{MGR_CAP_R | MGR_CAP_W}}); return; } if (profile == "crash") { profile_grants.push_back({{}, {}, {}, "crash post", {}, {}}); return; } if (profile == "osd") { // this is a documented profile (so we need to accept it as valid), but it // currently doesn't do anything return; } if (profile == "mds") { // this is a documented profile (so we need to accept it as valid), but it // currently doesn't do anything return; } if (profile == "rbd" || profile == "rbd-read-only") { Arguments filtered_arguments; for (auto& [key, constraint] : arguments) { if (key == "pool" || key == "namespace") { filtered_arguments[key] = std::move(constraint); } else { if (err != nullptr) { *err << "profile '" << profile << "' does not recognize key '" << key << "'"; } return; } } mgr_rwxa_t perms = mgr_rwxa_t{MGR_CAP_R}; if (profile == "rbd") { perms = mgr_rwxa_t{MGR_CAP_R | MGR_CAP_W}; } // allow all 'rbd_support' commands (restricted by optional // pool/namespace constraints) profile_grants.push_back({{}, "rbd_support", {}, {}, std::move(filtered_arguments), perms}); return; } if (err != nullptr) { *err << "unrecognized profile '" << profile << "'"; } } bool MgrCapGrant::validate_arguments( const std::map<std::string, std::string>& args) const { for (auto& [key, constraint] : arguments) { auto q = args.find(key); // argument must be present if a constraint exists if (q == args.end()) { return false; } switch (constraint.match_type) { case MgrCapGrantConstraint::MATCH_TYPE_EQUAL: if (constraint.value != q->second) return false; break; case MgrCapGrantConstraint::MATCH_TYPE_PREFIX: if (q->second.find(constraint.value) != 0) return false; break; case MgrCapGrantConstraint::MATCH_TYPE_REGEX: try { std::regex pattern(constraint.value, std::regex::extended); if (!std::regex_match(q->second, pattern)) { return false; } } catch(const std::regex_error&) { return false; } break; default: return false; } } return true; } mgr_rwxa_t MgrCapGrant::get_allowed( CephContext *cct, EntityName name, const std::string& s, const std::string& m, const std::string& c, const std::map<std::string, std::string>& args) const { if (!profile.empty()) { expand_profile(nullptr); mgr_rwxa_t a; for (auto& grant : profile_grants) { a = a | grant.get_allowed(cct, name, s, m, c, args); } return a; } if (!service.empty()) { if (service != s) { return mgr_rwxa_t{}; } return allow; } if (!module.empty()) { if (module != m) { return mgr_rwxa_t{}; } // don't test module arguments when validating a specific command if (c.empty() && !validate_arguments(args)) { return mgr_rwxa_t{}; } return allow; } if (!command.empty()) { if (command != c) { return mgr_rwxa_t{}; } if (!validate_arguments(args)) { return mgr_rwxa_t{}; } return mgr_rwxa_t{MGR_CAP_ANY}; } return allow; } std::ostream& operator<<(std::ostream&out, const MgrCap& m) { bool first = true; for (auto& grant : m.grants) { if (!first) { out << ", "; } first = false; out << grant; } return out; } bool MgrCap::is_allow_all() const { for (auto& grant : grants) { if (grant.is_allow_all()) { return true; } } return false; } void MgrCap::set_allow_all() { grants.clear(); grants.push_back({{}, {}, {}, {}, {}, mgr_rwxa_t{MGR_CAP_ANY}}); text = "allow *"; } bool MgrCap::is_capable( CephContext *cct, EntityName name, const std::string& service, const std::string& module, const std::string& command, const std::map<std::string, std::string>& command_args, bool op_may_read, bool op_may_write, bool op_may_exec, const entity_addr_t& addr) const { if (cct) { ldout(cct, 20) << "is_capable service=" << service << " " << "module=" << module << " " << "command=" << command << (op_may_read ? " read":"") << (op_may_write ? " write":"") << (op_may_exec ? " exec":"") << " addr " << addr << " on cap " << *this << dendl; } mgr_rwxa_t allow; for (auto& grant : grants) { if (cct) ldout(cct, 20) << " allow so far " << allow << ", doing grant " << grant << dendl; if (grant.network.size() && (!grant.network_valid || !network_contains(grant.network_parsed, grant.network_prefix, addr))) { continue; } if (grant.is_allow_all()) { if (cct) { ldout(cct, 20) << " allow all" << dendl; } return true; } // check enumerated caps allow = allow | grant.get_allowed(cct, name, service, module, command, command_args); if ((!op_may_read || (allow & MGR_CAP_R)) && (!op_may_write || (allow & MGR_CAP_W)) && (!op_may_exec || (allow & MGR_CAP_X))) { if (cct) { ldout(cct, 20) << " match" << dendl; } return true; } } return false; } void MgrCap::encode(ceph::buffer::list& bl) const { // remain backwards compatible w/ MgrCap ENCODE_START(4, 4, bl); encode(text, bl); ENCODE_FINISH(bl); } void MgrCap::decode(ceph::buffer::list::const_iterator& bl) { // remain backwards compatible w/ MgrCap std::string s; DECODE_START(4, bl); decode(s, bl); DECODE_FINISH(bl); parse(s, NULL); } void MgrCap::dump(ceph::Formatter *f) const { f->dump_string("text", text); } void MgrCap::generate_test_instances(std::list<MgrCap*>& ls) { ls.push_back(new MgrCap); ls.push_back(new MgrCap); ls.back()->parse("allow *"); ls.push_back(new MgrCap); ls.back()->parse("allow rwx"); ls.push_back(new MgrCap); ls.back()->parse("allow service foo x"); ls.push_back(new MgrCap); ls.back()->parse("allow command bar x"); ls.push_back(new MgrCap); ls.back()->parse("allow service foo r, allow command bar x"); ls.push_back(new MgrCap); ls.back()->parse("allow command bar with k1=v1 x"); ls.push_back(new MgrCap); ls.back()->parse("allow command bar with k1=v1 k2=v2 x"); ls.push_back(new MgrCap); ls.back()->parse("allow module bar with k1=v1 k2=v2 x"); ls.push_back(new MgrCap); ls.back()->parse("profile rbd pool=rbd"); } // grammar namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; template <typename Iterator> struct MgrCapParser : qi::grammar<Iterator, MgrCap()> { MgrCapParser() : MgrCapParser::base_type(mgrcap) { using qi::char_; using qi::int_; using qi::ulong_long; using qi::lexeme; using qi::alnum; using qi::_val; using qi::_1; using qi::_2; using qi::_3; using qi::eps; using qi::lit; quoted_string %= lexeme['"' >> +(char_ - '"') >> '"'] | lexeme['\'' >> +(char_ - '\'') >> '\'']; unquoted_word %= +char_("a-zA-Z0-9_./-"); str %= quoted_string | unquoted_word; network_str %= +char_("/.:a-fA-F0-9]["); spaces = +(lit(' ') | lit('\n') | lit('\t')); // key <=|prefix|regex> value[ ...] str_match = -spaces >> lit('=') >> -spaces >> qi::attr(MgrCapGrantConstraint::MATCH_TYPE_EQUAL) >> str; str_prefix = spaces >> lit("prefix") >> spaces >> qi::attr(MgrCapGrantConstraint::MATCH_TYPE_PREFIX) >> str; str_regex = spaces >> lit("regex") >> spaces >> qi::attr(MgrCapGrantConstraint::MATCH_TYPE_REGEX) >> str; kv_pair = str >> (str_match | str_prefix | str_regex); kv_map %= kv_pair >> *(spaces >> kv_pair); // command := command[=]cmd [k1=v1 k2=v2 ...] command_match = -spaces >> lit("allow") >> spaces >> lit("command") >> (lit('=') | spaces) >> qi::attr(std::string()) >> qi::attr(std::string()) >> qi::attr(std::string()) >> str >> -(spaces >> lit("with") >> spaces >> kv_map) >> qi::attr(0) >> -(spaces >> lit("network") >> spaces >> network_str); // service foo rwxa service_match %= -spaces >> lit("allow") >> spaces >> lit("service") >> (lit('=') | spaces) >> str >> qi::attr(std::string()) >> qi::attr(std::string()) >> qi::attr(std::string()) >> qi::attr(std::map<std::string, MgrCapGrantConstraint>()) >> spaces >> rwxa >> -(spaces >> lit("network") >> spaces >> network_str); // module foo rwxa module_match %= -spaces >> lit("allow") >> spaces >> lit("module") >> (lit('=') | spaces) >> qi::attr(std::string()) >> str >> qi::attr(std::string()) >> qi::attr(std::string()) >> -(spaces >> lit("with") >> spaces >> kv_map) >> spaces >> rwxa >> -(spaces >> lit("network") >> spaces >> network_str); // profile foo profile_match %= -spaces >> -(lit("allow") >> spaces) >> lit("profile") >> (lit('=') | spaces) >> qi::attr(std::string()) >> qi::attr(std::string()) >> str >> qi::attr(std::string()) >> -(spaces >> kv_map) >> qi::attr(0) >> -(spaces >> lit("network") >> spaces >> network_str); // rwxa rwxa_match %= -spaces >> lit("allow") >> spaces >> qi::attr(std::string()) >> qi::attr(std::string()) >> qi::attr(std::string()) >> qi::attr(std::string()) >> qi::attr(std::map<std::string,MgrCapGrantConstraint>()) >> rwxa >> -(spaces >> lit("network") >> spaces >> network_str); // rwxa := * | [r][w][x] rwxa = (lit("*")[_val = MGR_CAP_ANY]) | (lit("all")[_val = MGR_CAP_ANY]) | ( eps[_val = 0] >> ( lit('r')[_val |= MGR_CAP_R] || lit('w')[_val |= MGR_CAP_W] || lit('x')[_val |= MGR_CAP_X] ) ); // grant := allow ... grant = -spaces >> (rwxa_match | profile_match | service_match | module_match | command_match) >> -spaces; // mgrcap := grant [grant ...] grants %= (grant % (*lit(' ') >> (lit(';') | lit(',')) >> *lit(' '))); mgrcap = grants [_val = phoenix::construct<MgrCap>(_1)]; } qi::rule<Iterator> spaces; qi::rule<Iterator, unsigned()> rwxa; qi::rule<Iterator, std::string()> quoted_string; qi::rule<Iterator, std::string()> unquoted_word; qi::rule<Iterator, std::string()> str, network_str; qi::rule<Iterator, MgrCapGrantConstraint()> str_match, str_prefix, str_regex; qi::rule<Iterator, std::pair<std::string, MgrCapGrantConstraint>()> kv_pair; qi::rule<Iterator, std::map<std::string, MgrCapGrantConstraint>()> kv_map; qi::rule<Iterator, MgrCapGrant()> rwxa_match; qi::rule<Iterator, MgrCapGrant()> command_match; qi::rule<Iterator, MgrCapGrant()> service_match; qi::rule<Iterator, MgrCapGrant()> module_match; qi::rule<Iterator, MgrCapGrant()> profile_match; qi::rule<Iterator, MgrCapGrant()> grant; qi::rule<Iterator, std::vector<MgrCapGrant>()> grants; qi::rule<Iterator, MgrCap()> mgrcap; }; bool MgrCap::parse(const std::string& str, std::ostream *err) { auto iter = str.begin(); auto end = str.end(); MgrCapParser<std::string::const_iterator> exp; bool r = qi::parse(iter, end, exp, *this); if (r && iter == end) { text = str; std::stringstream profile_err; for (auto& g : grants) { g.parse_network(); if (!g.profile.empty()) { g.expand_profile(&profile_err); } } if (!profile_err.str().empty()) { if (err != nullptr) { *err << "mgr capability parse failed during profile evaluation: " << profile_err.str(); } return false; } return true; } // Make sure no grants are kept after parsing failed! grants.clear(); if (err) { if (iter != end) *err << "mgr capability parse failed, stopped at '" << std::string(iter, end) << "' of '" << str << "'"; else *err << "mgr capability parse failed, stopped at end of '" << str << "'"; } return false; }
17,285
28.752151
95
cc
null
ceph-main/src/mgr/MgrCap.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_MGRCAP_H #define CEPH_MGRCAP_H #include <iosfwd> #include "include/common_fwd.h" #include "include/types.h" #include "common/entity_name.h" static const __u8 MGR_CAP_R = (1 << 1); // read static const __u8 MGR_CAP_W = (1 << 2); // write static const __u8 MGR_CAP_X = (1 << 3); // execute static const __u8 MGR_CAP_ANY = 0xff; // * struct mgr_rwxa_t { __u8 val = 0U; mgr_rwxa_t() {} explicit mgr_rwxa_t(__u8 v) : val(v) {} mgr_rwxa_t& operator=(__u8 v) { val = v; return *this; } operator __u8() const { return val; } }; std::ostream& operator<<(std::ostream& out, const mgr_rwxa_t& p); struct MgrCapGrantConstraint { enum MatchType { MATCH_TYPE_NONE, MATCH_TYPE_EQUAL, MATCH_TYPE_PREFIX, MATCH_TYPE_REGEX }; MatchType match_type = MATCH_TYPE_NONE; std::string value; MgrCapGrantConstraint() {} MgrCapGrantConstraint(MatchType match_type, std::string value) : match_type(match_type), value(value) { } }; std::ostream& operator<<(std::ostream& out, const MgrCapGrantConstraint& c); struct MgrCapGrant { /* * A grant can come in one of four forms: * * - a blanket allow ('allow rw', 'allow *') * - this will match against any service and the read/write/exec flags * in the mgr code. semantics of what X means are somewhat ad hoc. * * - a service allow ('allow service mds rw') * - this will match against a specific service and the r/w/x flags. * * - a module allow ('allow module rbd_support rw, allow module rbd_support with pool=rbd rw') * - this will match against a specific python add-on module and the r/w/x * flags. * * - a profile ('profile read-only, profile rbd pool=rbd') * - this will match against specific MGR-enforced semantics of what * this type of user should need to do. examples include 'read-write', * 'read-only', 'crash'. * * - a command ('allow command foo', 'allow command bar with arg1=val1 arg2 prefix val2') * this includes the command name (the prefix string) * * The command, module, and profile caps can also accept an optional * key/value map. If not provided, all command arguments and module * meta-arguments are allowed. If a key/value pair is specified, that * argument must be present and must match the provided constraint. */ typedef std::map<std::string, MgrCapGrantConstraint> Arguments; std::string service; std::string module; std::string profile; std::string command; Arguments arguments; // restrict by network std::string network; // these are filled in by parse_network(), called by MgrCap::parse() entity_addr_t network_parsed; unsigned network_prefix = 0; bool network_valid = true; void parse_network(); mgr_rwxa_t allow; // explicit grants that a profile grant expands to; populated as // needed by expand_profile() (via is_match()) and cached here. mutable std::list<MgrCapGrant> profile_grants; void expand_profile(std::ostream *err=nullptr) const; MgrCapGrant() : allow(0) {} MgrCapGrant(std::string&& service, std::string&& module, std::string&& profile, std::string&& command, Arguments&& arguments, mgr_rwxa_t allow) : service(std::move(service)), module(std::move(module)), profile(std::move(profile)), command(std::move(command)), arguments(std::move(arguments)), allow(allow) { } bool validate_arguments( const std::map<std::string, std::string>& arguments) const; /** * check if given request parameters match our constraints * * @param cct context * @param name entity name * @param service service (if any) * @param module module (if any) * @param command command (if any) * @param arguments profile/module/command args (if any) * @return bits we allow */ mgr_rwxa_t get_allowed( CephContext *cct, EntityName name, const std::string& service, const std::string& module, const std::string& command, const std::map<std::string, std::string>& arguments) const; bool is_allow_all() const { return (allow == MGR_CAP_ANY && service.empty() && module.empty() && profile.empty() && command.empty()); } }; std::ostream& operator<<(std::ostream& out, const MgrCapGrant& g); struct MgrCap { std::string text; std::vector<MgrCapGrant> grants; MgrCap() {} explicit MgrCap(const std::vector<MgrCapGrant> &g) : grants(g) {} std::string get_str() const { return text; } bool is_allow_all() const; void set_allow_all(); bool parse(const std::string& str, std::ostream *err=NULL); /** * check if we are capable of something * * This method actually checks a description of a particular operation against * what the capability has specified. * * @param service service name * @param module module name * @param command command id * @param arguments * @param op_may_read whether the operation may need to read * @param op_may_write whether the operation may need to write * @param op_may_exec whether the operation may exec * @return true if the operation is allowed, false otherwise */ bool is_capable(CephContext *cct, EntityName name, const std::string& service, const std::string& module, const std::string& command, const std::map<std::string, std::string>& arguments, bool op_may_read, bool op_may_write, bool op_may_exec, const entity_addr_t& addr) const; void encode(ceph::buffer::list& bl) const; void decode(ceph::buffer::list::const_iterator& bl); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<MgrCap*>& ls); }; WRITE_CLASS_ENCODER(MgrCap) std::ostream& operator<<(std::ostream& out, const MgrCap& cap); #endif // CEPH_MGRCAP_H
6,053
28.970297
97
h
null
ceph-main/src/mgr/MgrClient.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 John Spray <[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 "MgrClient.h" #include "common/perf_counters_key.h" #include "mgr/MgrContext.h" #include "mon/MonMap.h" #include "msg/Messenger.h" #include "messages/MMgrMap.h" #include "messages/MMgrReport.h" #include "messages/MMgrOpen.h" #include "messages/MMgrUpdate.h" #include "messages/MMgrClose.h" #include "messages/MMgrConfigure.h" #include "messages/MCommand.h" #include "messages/MCommandReply.h" #include "messages/MMgrCommand.h" #include "messages/MMgrCommandReply.h" #include "messages/MPGStats.h" using std::string; using std::vector; using ceph::bufferlist; using ceph::make_message; using ceph::ref_cast; using ceph::ref_t; #define dout_subsys ceph_subsys_mgrc #undef dout_prefix #define dout_prefix *_dout << "mgrc " << __func__ << " " MgrClient::MgrClient(CephContext *cct_, Messenger *msgr_, MonMap *monmap_) : Dispatcher(cct_), cct(cct_), msgr(msgr_), monmap(monmap_), timer(cct_, lock) { ceph_assert(cct != nullptr); } void MgrClient::init() { std::lock_guard l(lock); ceph_assert(msgr != nullptr); timer.init(); initialized = true; } void MgrClient::shutdown() { std::unique_lock l(lock); ldout(cct, 10) << dendl; if (connect_retry_callback) { timer.cancel_event(connect_retry_callback); connect_retry_callback = nullptr; } // forget about in-flight commands if we are prematurely shut down // (e.g., by control-C) command_table.clear(); if (service_daemon && session && session->con && HAVE_FEATURE(session->con->get_features(), SERVER_MIMIC)) { ldout(cct, 10) << "closing mgr session" << dendl; auto m = make_message<MMgrClose>(); m->daemon_name = daemon_name; m->service_name = service_name; session->con->send_message2(m); auto timeout = ceph::make_timespan(cct->_conf.get_val<double>( "mgr_client_service_daemon_unregister_timeout")); shutdown_cond.wait_for(l, timeout); } timer.shutdown(); if (session) { session->con->mark_down(); session.reset(); } } bool MgrClient::ms_dispatch2(const ref_t<Message>& m) { std::lock_guard l(lock); switch(m->get_type()) { case MSG_MGR_MAP: return handle_mgr_map(ref_cast<MMgrMap>(m)); case MSG_MGR_CONFIGURE: return handle_mgr_configure(ref_cast<MMgrConfigure>(m)); case MSG_MGR_CLOSE: return handle_mgr_close(ref_cast<MMgrClose>(m)); case MSG_COMMAND_REPLY: if (m->get_source().type() == CEPH_ENTITY_TYPE_MGR) { MCommandReply *c = static_cast<MCommandReply*>(m.get()); handle_command_reply(c->get_tid(), c->get_data(), c->rs, c->r); return true; } else { return false; } case MSG_MGR_COMMAND_REPLY: if (m->get_source().type() == CEPH_ENTITY_TYPE_MGR) { MMgrCommandReply *c = static_cast<MMgrCommandReply*>(m.get()); handle_command_reply(c->get_tid(), c->get_data(), c->rs, c->r); return true; } else { return false; } default: ldout(cct, 30) << "Not handling " << *m << dendl; return false; } } void MgrClient::reconnect() { ceph_assert(ceph_mutex_is_locked_by_me(lock)); if (session) { ldout(cct, 4) << "Terminating session with " << session->con->get_peer_addr() << dendl; session->con->mark_down(); session.reset(); stats_period = 0; if (report_callback != nullptr) { timer.cancel_event(report_callback); report_callback = nullptr; } } if (!map.get_available()) { ldout(cct, 4) << "No active mgr available yet" << dendl; return; } if (!clock_t::is_zero(last_connect_attempt)) { auto now = clock_t::now(); auto when = last_connect_attempt + ceph::make_timespan( cct->_conf.get_val<double>("mgr_connect_retry_interval")); if (now < when) { if (!connect_retry_callback) { connect_retry_callback = timer.add_event_at( when, new LambdaContext([this](int r){ connect_retry_callback = nullptr; reconnect(); })); } ldout(cct, 4) << "waiting to retry connect until " << when << dendl; return; } } if (connect_retry_callback) { timer.cancel_event(connect_retry_callback); connect_retry_callback = nullptr; } ldout(cct, 4) << "Starting new session with " << map.get_active_addrs() << dendl; last_connect_attempt = clock_t::now(); session.reset(new MgrSessionState()); session->con = msgr->connect_to(CEPH_ENTITY_TYPE_MGR, map.get_active_addrs()); if (service_daemon) { daemon_dirty_status = true; } task_dirty_status = true; // Don't send an open if we're just a client (i.e. doing // command-sending, not stats etc) if (msgr->get_mytype() != CEPH_ENTITY_TYPE_CLIENT || service_daemon) { _send_open(); } // resend any pending commands auto p = command_table.get_commands().begin(); while (p != command_table.get_commands().end()) { auto tid = p->first; auto& op = p->second; ldout(cct,10) << "resending " << tid << (op.tell ? " (tell)":" (cli)") << dendl; MessageRef m; if (op.tell) { if (op.name.size() && op.name != map.active_name) { ldout(cct, 10) << "active mgr " << map.active_name << " != target " << op.name << dendl; if (op.on_finish) { op.on_finish->complete(-ENXIO); } ++p; command_table.erase(tid); continue; } // Set fsid argument to signal that this is really a tell message (and // we are not a legacy client sending a non-tell command via MCommand). m = op.get_message(monmap->fsid, false); } else { m = op.get_message( {}, HAVE_FEATURE(map.active_mgr_features, SERVER_OCTOPUS)); } ceph_assert(session); ceph_assert(session->con); session->con->send_message2(std::move(m)); ++p; } } void MgrClient::_send_open() { if (session && session->con) { auto open = make_message<MMgrOpen>(); if (!service_name.empty()) { open->service_name = service_name; open->daemon_name = daemon_name; } else { open->daemon_name = cct->_conf->name.get_id(); } if (service_daemon) { open->service_daemon = service_daemon; open->daemon_metadata = daemon_metadata; } cct->_conf.get_config_bl(0, &open->config_bl, &last_config_bl_version); cct->_conf.get_defaults_bl(&open->config_defaults_bl); session->con->send_message2(open); } } void MgrClient::_send_update() { if (session && session->con) { auto update = make_message<MMgrUpdate>(); if (!service_name.empty()) { update->service_name = service_name; update->daemon_name = daemon_name; } else { update->daemon_name = cct->_conf->name.get_id(); } if (need_metadata_update) { update->daemon_metadata = daemon_metadata; } update->need_metadata_update = need_metadata_update; session->con->send_message2(update); } } bool MgrClient::handle_mgr_map(ref_t<MMgrMap> m) { ceph_assert(ceph_mutex_is_locked_by_me(lock)); ldout(cct, 20) << *m << dendl; map = m->get_map(); ldout(cct, 4) << "Got map version " << map.epoch << dendl; ldout(cct, 4) << "Active mgr is now " << map.get_active_addrs() << dendl; // Reset session? if (!session || session->con->get_peer_addrs() != map.get_active_addrs()) { reconnect(); } return true; } bool MgrClient::ms_handle_reset(Connection *con) { std::lock_guard l(lock); if (session && con == session->con) { ldout(cct, 4) << __func__ << " con " << con << dendl; reconnect(); return true; } return false; } bool MgrClient::ms_handle_refused(Connection *con) { // do nothing for now return false; } void MgrClient::_send_stats() { _send_report(); _send_pgstats(); if (stats_period != 0) { report_callback = timer.add_event_after( stats_period, new LambdaContext([this](int) { _send_stats(); })); } } void MgrClient::_send_report() { ceph_assert(ceph_mutex_is_locked_by_me(lock)); ceph_assert(session); report_callback = nullptr; auto report = make_message<MMgrReport>(); auto pcc = cct->get_perfcounters_collection(); pcc->with_counters([this, report]( const PerfCountersCollectionImpl::CounterMap &by_path) { // Helper for checking whether a counter should be included auto include_counter = [this]( const PerfCounters::perf_counter_data_any_d &ctr, const PerfCounters &perf_counters) { // FIXME: We don't send labeled perf counters to the mgr currently. auto labels = ceph::perf_counters::key_labels(perf_counters.get_name()); if (labels.begin() != labels.end()) { return false; } return perf_counters.get_adjusted_priority(ctr.prio) >= (int)stats_threshold; }; // Helper for cases where we want to forget a counter auto undeclare = [report, this](const std::string &path) { report->undeclare_types.push_back(path); ldout(cct,20) << " undeclare " << path << dendl; session->declared.erase(path); }; ENCODE_START(1, 1, report->packed); // Find counters that no longer exist, and undeclare them for (auto p = session->declared.begin(); p != session->declared.end(); ) { const auto &path = *(p++); if (by_path.count(path) == 0) { undeclare(path); } } for (const auto &i : by_path) { auto& path = i.first; auto& data = *(i.second.data); auto& perf_counters = *(i.second.perf_counters); // Find counters that still exist, but are no longer permitted by // stats_threshold if (!include_counter(data, perf_counters)) { if (session->declared.count(path)) { undeclare(path); } continue; } if (session->declared.count(path) == 0) { ldout(cct, 20) << " declare " << path << dendl; PerfCounterType type; type.path = path; if (data.description) { type.description = data.description; } if (data.nick) { type.nick = data.nick; } type.type = data.type; type.priority = perf_counters.get_adjusted_priority(data.prio); type.unit = data.unit; report->declare_types.push_back(std::move(type)); session->declared.insert(path); } encode(static_cast<uint64_t>(data.u64), report->packed); if (data.type & PERFCOUNTER_LONGRUNAVG) { encode(static_cast<uint64_t>(data.avgcount), report->packed); encode(static_cast<uint64_t>(data.avgcount2), report->packed); } } ENCODE_FINISH(report->packed); ldout(cct, 20) << "sending " << session->declared.size() << " counters (" "of possible " << by_path.size() << "), " << report->declare_types.size() << " new, " << report->undeclare_types.size() << " removed" << dendl; }); ldout(cct, 20) << "encoded " << report->packed.length() << " bytes" << dendl; if (daemon_name.size()) { report->daemon_name = daemon_name; } else { report->daemon_name = cct->_conf->name.get_id(); } report->service_name = service_name; if (daemon_dirty_status) { report->daemon_status = daemon_status; daemon_dirty_status = false; } if (task_dirty_status) { report->task_status = task_status; task_dirty_status = false; } report->daemon_health_metrics = std::move(daemon_health_metrics); cct->_conf.get_config_bl(last_config_bl_version, &report->config_bl, &last_config_bl_version); if (get_perf_report_cb) { report->metric_report_message = MetricReportMessage(get_perf_report_cb()); } session->con->send_message2(report); } void MgrClient::send_pgstats() { std::lock_guard l(lock); _send_pgstats(); } void MgrClient::_send_pgstats() { if (pgstats_cb && session) { session->con->send_message(pgstats_cb()); } } bool MgrClient::handle_mgr_configure(ref_t<MMgrConfigure> m) { ceph_assert(ceph_mutex_is_locked_by_me(lock)); ldout(cct, 20) << *m << dendl; if (!session) { lderr(cct) << "dropping unexpected configure message" << dendl; return true; } ldout(cct, 4) << "stats_period=" << m->stats_period << dendl; if (stats_threshold != m->stats_threshold) { ldout(cct, 4) << "updated stats threshold: " << m->stats_threshold << dendl; stats_threshold = m->stats_threshold; } if (!m->osd_perf_metric_queries.empty()) { handle_config_payload(m->osd_perf_metric_queries); } else if (m->metric_config_message) { const MetricConfigMessage &message = *m->metric_config_message; boost::apply_visitor(HandlePayloadVisitor(this), message.payload); } bool starting = (stats_period == 0) && (m->stats_period != 0); stats_period = m->stats_period; if (starting) { _send_stats(); } return true; } bool MgrClient::handle_mgr_close(ref_t<MMgrClose> m) { service_daemon = false; shutdown_cond.notify_all(); return true; } int MgrClient::start_command(const vector<string>& cmd, const bufferlist& inbl, bufferlist *outbl, string *outs, Context *onfinish) { std::lock_guard l(lock); ldout(cct, 20) << "cmd: " << cmd << dendl; if (map.epoch == 0 && mgr_optional) { ldout(cct,20) << " no MgrMap, assuming EACCES" << dendl; return -EACCES; } auto &op = command_table.start_command(); op.cmd = cmd; op.inbl = inbl; op.outbl = outbl; op.outs = outs; op.on_finish = onfinish; if (session && session->con) { // Leaving fsid argument null because it isn't used historically, and // we can use it as a signal that we are sending a non-tell command. auto m = op.get_message( {}, HAVE_FEATURE(map.active_mgr_features, SERVER_OCTOPUS)); session->con->send_message2(std::move(m)); } else { ldout(cct, 5) << "no mgr session (no running mgr daemon?), waiting" << dendl; } return 0; } int MgrClient::start_tell_command( const string& name, const vector<string>& cmd, const bufferlist& inbl, bufferlist *outbl, string *outs, Context *onfinish) { std::lock_guard l(lock); ldout(cct, 20) << "target: " << name << " cmd: " << cmd << dendl; if (map.epoch == 0 && mgr_optional) { ldout(cct,20) << " no MgrMap, assuming EACCES" << dendl; return -EACCES; } auto &op = command_table.start_command(); op.tell = true; op.name = name; op.cmd = cmd; op.inbl = inbl; op.outbl = outbl; op.outs = outs; op.on_finish = onfinish; if (session && session->con && (name.size() == 0 || map.active_name == name)) { // Set fsid argument to signal that this is really a tell message (and // we are not a legacy client sending a non-tell command via MCommand). auto m = op.get_message(monmap->fsid, false); session->con->send_message2(std::move(m)); } else { ldout(cct, 5) << "no mgr session (no running mgr daemon?), or " << name << " not active mgr, waiting" << dendl; } return 0; } bool MgrClient::handle_command_reply( uint64_t tid, bufferlist& data, const std::string& rs, int r) { ceph_assert(ceph_mutex_is_locked_by_me(lock)); ldout(cct, 20) << "tid " << tid << " r " << r << dendl; if (!command_table.exists(tid)) { ldout(cct, 4) << "handle_command_reply tid " << tid << " not found" << dendl; return true; } auto &op = command_table.get_command(tid); if (op.outbl) { *op.outbl = std::move(data); } if (op.outs) { *(op.outs) = rs; } if (op.on_finish) { op.on_finish->complete(r); } command_table.erase(tid); return true; } int MgrClient::update_daemon_metadata( const std::string& service, const std::string& name, const std::map<std::string,std::string>& metadata) { std::lock_guard l(lock); if (service_daemon) { return -EEXIST; } ldout(cct,1) << service << "." << name << " metadata " << metadata << dendl; service_name = service; daemon_name = name; daemon_metadata = metadata; daemon_dirty_status = true; if (need_metadata_update && !daemon_metadata.empty()) { _send_update(); need_metadata_update = false; } return 0; } int MgrClient::service_daemon_register( const std::string& service, const std::string& name, const std::map<std::string,std::string>& metadata) { std::lock_guard l(lock); if (service_daemon) { return -EEXIST; } ldout(cct,1) << service << "." << name << " metadata " << metadata << dendl; service_daemon = true; service_name = service; daemon_name = name; daemon_metadata = metadata; daemon_dirty_status = true; // late register? if (msgr->get_mytype() == CEPH_ENTITY_TYPE_CLIENT && session && session->con) { _send_open(); } return 0; } int MgrClient::service_daemon_update_status( std::map<std::string,std::string>&& status) { std::lock_guard l(lock); ldout(cct,10) << status << dendl; daemon_status = std::move(status); daemon_dirty_status = true; return 0; } int MgrClient::service_daemon_update_task_status( std::map<std::string,std::string> &&status) { std::lock_guard l(lock); ldout(cct,10) << status << dendl; task_status = std::move(status); task_dirty_status = true; return 0; } void MgrClient::update_daemon_health(std::vector<DaemonHealthMetric>&& metrics) { std::lock_guard l(lock); daemon_health_metrics = std::move(metrics); }
17,653
25.428144
84
cc
null
ceph-main/src/mgr/MgrClient.h
// -*- 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 John Spray <[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. */ #ifndef MGR_CLIENT_H_ #define MGR_CLIENT_H_ #include <boost/variant.hpp> #include "msg/Connection.h" #include "msg/Dispatcher.h" #include "mon/MgrMap.h" #include "mgr/DaemonHealthMetric.h" #include "messages/MMgrReport.h" #include "mgr/MetricTypes.h" #include "common/perf_counters.h" #include "common/Timer.h" #include "common/CommandTable.h" class MMgrMap; class MMgrConfigure; class MMgrClose; class Messenger; class MCommandReply; class MPGStats; class MonMap; class MgrSessionState { public: // Which performance counters have we already transmitted schema for? std::set<std::string> declared; // Our connection to the mgr ConnectionRef con; }; class MgrCommand : public CommandOp { public: std::string name; bool tell = false; explicit MgrCommand(ceph_tid_t t) : CommandOp(t) {} MgrCommand() : CommandOp() {} }; class MgrClient : public Dispatcher { protected: CephContext *cct; MgrMap map; Messenger *msgr; MonMap *monmap; std::unique_ptr<MgrSessionState> session; ceph::mutex lock = ceph::make_mutex("MgrClient::lock"); ceph::condition_variable shutdown_cond; uint32_t stats_period = 0; uint32_t stats_threshold = 0; SafeTimer timer; CommandTable<MgrCommand> command_table; using clock_t = ceph::mono_clock; clock_t::time_point last_connect_attempt; uint64_t last_config_bl_version = 0; Context *report_callback = nullptr; Context *connect_retry_callback = nullptr; // If provided, use this to compose an MPGStats to send with // our reports (hook for use by OSD) std::function<MPGStats*()> pgstats_cb; std::function<void(const ConfigPayload &)> set_perf_queries_cb; std::function<MetricPayload()> get_perf_report_cb; // for service registration and beacon bool service_daemon = false; bool daemon_dirty_status = false; bool task_dirty_status = false; bool need_metadata_update = true; std::string service_name, daemon_name; std::map<std::string,std::string> daemon_metadata; std::map<std::string,std::string> daemon_status; std::map<std::string,std::string> task_status; std::vector<DaemonHealthMetric> daemon_health_metrics; void reconnect(); void _send_open(); void _send_update(); // In pre-luminous clusters, the ceph-mgr service is absent or optional, // so we must not block in start_command waiting for it. bool mgr_optional = false; public: MgrClient(CephContext *cct_, Messenger *msgr_, MonMap *monmap); void set_messenger(Messenger *msgr_) { msgr = msgr_; } void init(); void shutdown(); void set_mgr_optional(bool optional_) {mgr_optional = optional_;} bool ms_dispatch2(const ceph::ref_t<Message>& m) override; bool ms_handle_reset(Connection *con) override; void ms_handle_remote_reset(Connection *con) override {} bool ms_handle_refused(Connection *con) override; bool handle_mgr_map(ceph::ref_t<MMgrMap> m); bool handle_mgr_configure(ceph::ref_t<MMgrConfigure> m); bool handle_mgr_close(ceph::ref_t<MMgrClose> m); bool handle_command_reply( uint64_t tid, ceph::buffer::list& data, const std::string& rs, int r); void set_perf_metric_query_cb( std::function<void(const ConfigPayload &)> cb_set, std::function<MetricPayload()> cb_get) { std::lock_guard l(lock); set_perf_queries_cb = cb_set; get_perf_report_cb = cb_get; } void send_pgstats(); void set_pgstats_cb(std::function<MPGStats*()>&& cb_) { std::lock_guard l(lock); pgstats_cb = std::move(cb_); } int start_command( const std::vector<std::string>& cmd, const ceph::buffer::list& inbl, ceph::buffer::list *outbl, std::string *outs, Context *onfinish); int start_tell_command( const std::string& name, const std::vector<std::string>& cmd, const ceph::buffer::list& inbl, ceph::buffer::list *outbl, std::string *outs, Context *onfinish); int update_daemon_metadata( const std::string& service, const std::string& name, const std::map<std::string,std::string>& metadata); int service_daemon_register( const std::string& service, const std::string& name, const std::map<std::string,std::string>& metadata); int service_daemon_update_status( std::map<std::string,std::string>&& status); int service_daemon_update_task_status( std::map<std::string,std::string> &&task_status); void update_daemon_health(std::vector<DaemonHealthMetric>&& metrics); bool is_initialized() const { return initialized; } private: void handle_config_payload(const OSDConfigPayload &payload) { if (set_perf_queries_cb) { set_perf_queries_cb(payload); } } void handle_config_payload(const MDSConfigPayload &payload) { if (set_perf_queries_cb) { set_perf_queries_cb(payload); } } void handle_config_payload(const UnknownConfigPayload &payload) { ceph_abort(); } struct HandlePayloadVisitor : public boost::static_visitor<void> { MgrClient *mgrc; HandlePayloadVisitor(MgrClient *mgrc) : mgrc(mgrc) { } template <typename ConfigPayload> inline void operator()(const ConfigPayload &payload) const { mgrc->handle_config_payload(payload); } }; void _send_stats(); void _send_pgstats(); void _send_report(); bool initialized = false; }; #endif
5,703
25.407407
74
h
null
ceph-main/src/mgr/MgrCommands.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* no guard; may be included multiple times */ // see MonCommands.h COMMAND("pg stat", "show placement group status.", "pg", "r") COMMAND("pg getmap", "get binary pg map to -o/stdout", "pg", "r") COMMAND("pg dump " \ "name=dumpcontents,type=CephChoices,strings=all|summary|sum|delta|pools|osds|pgs|pgs_brief,n=N,req=false", \ "show human-readable versions of pg map (only 'all' valid with plain)", "pg", "r") COMMAND("pg dump_json " \ "name=dumpcontents,type=CephChoices,strings=all|summary|sum|pools|osds|pgs,n=N,req=false", \ "show human-readable version of pg map in json only",\ "pg", "r") COMMAND("pg dump_pools_json", "show pg pools info in json only",\ "pg", "r") COMMAND("pg ls-by-pool " \ "name=poolstr,type=CephString " \ "name=states,type=CephString,n=N,req=false", \ "list pg with pool = [poolname]", "pg", "r") COMMAND("pg ls-by-primary " \ "name=osd,type=CephOsdName " \ "name=pool,type=CephInt,req=false " \ "name=states,type=CephString,n=N,req=false", \ "list pg with primary = [osd]", "pg", "r") COMMAND("pg ls-by-osd " \ "name=osd,type=CephOsdName " \ "name=pool,type=CephInt,req=false " \ "name=states,type=CephString,n=N,req=false", \ "list pg on osd [osd]", "pg", "r") COMMAND("pg ls " \ "name=pool,type=CephInt,req=false " \ "name=states,type=CephString,n=N,req=false", \ "list pg with specific pool, osd, state", "pg", "r") COMMAND("pg dump_stuck " \ "name=stuckops,type=CephChoices,strings=inactive|unclean|stale|undersized|degraded,n=N,req=false " \ "name=threshold,type=CephInt,req=false", "show information about stuck pgs",\ "pg", "r") COMMAND("pg debug " \ "name=debugop,type=CephChoices,strings=unfound_objects_exist|degraded_pgs_exist", \ "show debug info about pgs", "pg", "r") COMMAND("pg scrub name=pgid,type=CephPgid", "start scrub on <pgid>", \ "pg", "rw") COMMAND("pg deep-scrub name=pgid,type=CephPgid", "start deep-scrub on <pgid>", \ "pg", "rw") COMMAND("pg repair name=pgid,type=CephPgid", "start repair on <pgid>", \ "pg", "rw") COMMAND("pg force-recovery name=pgid,type=CephPgid,n=N", "force recovery of <pgid> first", \ "pg", "rw") COMMAND("pg force-backfill name=pgid,type=CephPgid,n=N", "force backfill of <pgid> first", \ "pg", "rw") COMMAND("pg cancel-force-recovery name=pgid,type=CephPgid,n=N", "restore normal recovery priority of <pgid>", \ "pg", "rw") COMMAND("pg cancel-force-backfill name=pgid,type=CephPgid,n=N", "restore normal backfill priority of <pgid>", \ "pg", "rw") // stuff in osd namespace COMMAND("osd perf", \ "print dump of OSD perf summary stats", \ "osd", \ "r") COMMAND("osd df " \ "name=output_method,type=CephChoices,strings=plain|tree,req=false " \ "name=filter_by,type=CephChoices,strings=class|name,req=false " \ "name=filter,type=CephString,req=false", \ "show OSD utilization", "osd", "r") COMMAND("osd blocked-by", \ "print histogram of which OSDs are blocking their peers", \ "osd", "r") COMMAND("osd pool stats " \ "name=pool_name,type=CephPoolname,req=false", "obtain stats from all pools, or from specified pool", "osd", "r") COMMAND("osd pool scrub " \ "name=who,type=CephPoolname,n=N", \ "initiate scrub on pool <who>", \ "osd", "rw") COMMAND("osd pool deep-scrub " \ "name=who,type=CephPoolname,n=N", \ "initiate deep-scrub on pool <who>", \ "osd", "rw") COMMAND("osd pool repair " \ "name=who,type=CephPoolname,n=N", \ "initiate repair on pool <who>", \ "osd", "rw") COMMAND("osd pool force-recovery " \ "name=who,type=CephPoolname,n=N", \ "force recovery of specified pool <who> first", \ "osd", "rw") COMMAND("osd pool force-backfill " \ "name=who,type=CephPoolname,n=N", \ "force backfill of specified pool <who> first", \ "osd", "rw") COMMAND("osd pool cancel-force-recovery " \ "name=who,type=CephPoolname,n=N", \ "restore normal recovery priority of specified pool <who>", \ "osd", "rw") COMMAND("osd pool cancel-force-backfill " \ "name=who,type=CephPoolname,n=N", \ "restore normal recovery priority of specified pool <who>", \ "osd", "rw") COMMAND("osd reweight-by-utilization " \ "name=oload,type=CephInt,req=false " \ "name=max_change,type=CephFloat,req=false " \ "name=max_osds,type=CephInt,req=false " \ "name=no_increasing,type=CephBool,req=false",\ "reweight OSDs by utilization [overload-percentage-for-consideration, default 120]", \ "osd", "rw") COMMAND("osd test-reweight-by-utilization " \ "name=oload,type=CephInt,req=false " \ "name=max_change,type=CephFloat,req=false " \ "name=max_osds,type=CephInt,req=false " \ "name=no_increasing,type=CephBool,req=false",\ "dry run of reweight OSDs by utilization [overload-percentage-for-consideration, default 120]", \ "osd", "r") COMMAND("osd reweight-by-pg " \ "name=oload,type=CephInt,req=false " \ "name=max_change,type=CephFloat,req=false " \ "name=max_osds,type=CephInt,req=false " \ "name=pools,type=CephPoolname,n=N,req=false", \ "reweight OSDs by PG distribution [overload-percentage-for-consideration, default 120]", \ "osd", "rw") COMMAND("osd test-reweight-by-pg " \ "name=oload,type=CephInt,req=false " \ "name=max_change,type=CephFloat,req=false " \ "name=max_osds,type=CephInt,req=false " \ "name=pools,type=CephPoolname,n=N,req=false", \ "dry run of reweight OSDs by PG distribution [overload-percentage-for-consideration, default 120]", \ "osd", "r") COMMAND("osd destroy " \ "name=id,type=CephOsdName " \ "name=force,type=CephBool,req=false " // backward compat synonym for --force "name=yes_i_really_mean_it,type=CephBool,req=false", \ "mark osd as being destroyed. Keeps the ID intact (allowing reuse), " \ "but removes cephx keys, config-key data and lockbox keys, "\ "rendering data permanently unreadable.", \ "osd", "rw") COMMAND("osd purge " \ "name=id,type=CephOsdName " \ "name=force,type=CephBool,req=false " // backward compat synonym for --force "name=yes_i_really_mean_it,type=CephBool,req=false", \ "purge all osd data from the monitors including the OSD id " \ "and CRUSH position", \ "osd", "rw") COMMAND("osd safe-to-destroy name=ids,type=CephString,n=N", "check whether osd(s) can be safely destroyed without reducing data durability", "osd", "r") COMMAND("osd ok-to-stop name=ids,type=CephString,n=N "\ "name=max,type=CephInt,req=false", "check whether osd(s) can be safely stopped without reducing immediate"\ " data availability", "osd", "r") COMMAND("osd scrub " \ "name=who,type=CephString", \ "initiate scrub on osd <who>, or use <all|any> to scrub all", \ "osd", "rw") COMMAND("osd deep-scrub " \ "name=who,type=CephString", \ "initiate deep scrub on osd <who>, or use <all|any> to deep scrub all", \ "osd", "rw") COMMAND("osd repair " \ "name=who,type=CephString", \ "initiate repair on osd <who>, or use <all|any> to repair all", \ "osd", "rw") COMMAND("service dump", "dump service map", "service", "r") COMMAND("service status", "dump service state", "service", "r") COMMAND("config show " \ "name=who,type=CephString name=key,type=CephString,req=false", "Show running configuration", "mgr", "r") COMMAND("config show-with-defaults " \ "name=who,type=CephString", "Show running configuration (including compiled-in defaults)", "mgr", "r") COMMAND("device ls", "Show devices", "mgr", "r") COMMAND("device info name=devid,type=CephString", "Show information about a device", "mgr", "r") COMMAND("device ls-by-daemon name=who,type=CephString", "Show devices associated with a daemon", "mgr", "r") COMMAND("device ls-by-host name=host,type=CephString", "Show devices on a host", "mgr", "r") COMMAND("device set-life-expectancy name=devid,type=CephString "\ "name=from,type=CephString "\ "name=to,type=CephString,req=false", "Set predicted device life expectancy", "mgr", "rw") COMMAND("device rm-life-expectancy name=devid,type=CephString", "Clear predicted device life expectancy", "mgr", "rw")
8,339
38.339623
111
h
null
ceph-main/src/mgr/MgrContext.h
// -*- 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 John Spray <[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. */ #ifndef MGR_CONTEXT_H_ #define MGR_CONTEXT_H_ #include <memory> #include "common/ceph_json.h" #include "common/Cond.h" #include "mon/MonClient.h" class Command { protected: C_SaferCond cond; public: ceph::buffer::list outbl; std::string outs; int r; void run(MonClient *monc, const std::string &command) { monc->start_mon_command({command}, {}, &outbl, &outs, &cond); } void run(MonClient *monc, const std::string &command, const ceph::buffer::list &inbl) { monc->start_mon_command({command}, inbl, &outbl, &outs, &cond); } virtual void wait() { r = cond.wait(); } virtual ~Command() {} }; class JSONCommand : public Command { public: json_spirit::mValue json_result; void wait() override { Command::wait(); if (r == 0) { bool read_ok = json_spirit::read( outbl.to_str(), json_result); if (!read_ok) { r = -EINVAL; } } } }; #endif
1,379
17.648649
87
h
null
ceph-main/src/mgr/MgrSession.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_MGR_MGRSESSION_H #define CEPH_MGR_MGRSESSION_H #include "common/RefCountedObj.h" #include "common/entity_name.h" #include "msg/msg_types.h" #include "MgrCap.h" /** * Session state associated with the Connection. */ struct MgrSession : public RefCountedObject { uint64_t global_id = 0; EntityName entity_name; entity_inst_t inst; int osd_id = -1; ///< osd id (if an osd) MgrCap caps; std::set<std::string> declared_types; const entity_addr_t& get_peer_addr() const { return inst.addr; } private: FRIEND_MAKE_REF(MgrSession); explicit MgrSession(CephContext *cct) : RefCountedObject(cct) {} ~MgrSession() override = default; }; using MgrSessionRef = ceph::ref_t<MgrSession>; #endif
832
19.317073
70
h
null
ceph-main/src/mgr/MgrStandby.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 John Spray <[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 <Python.h> #include <boost/algorithm/string/replace.hpp> #include "common/errno.h" #include "common/signal.h" #include "include/compat.h" #include "include/stringify.h" #include "global/global_context.h" #include "global/signal_handler.h" #include "mgr/MgrContext.h" #include "mgr/mgr_commands.h" #include "mgr/mgr_perf_counters.h" #include "messages/MMgrBeacon.h" #include "messages/MMgrMap.h" #include "Mgr.h" #include "MgrStandby.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr " << __func__ << " " using std::map; using std::string; using std::vector; MgrStandby::MgrStandby(int argc, const char **argv) : Dispatcher(g_ceph_context), monc{g_ceph_context, poolctx}, client_messenger(Messenger::create( g_ceph_context, cct->_conf.get_val<std::string>("ms_public_type").empty() ? cct->_conf.get_val<std::string>("ms_type") : cct->_conf.get_val<std::string>("ms_public_type"), entity_name_t::MGR(), "mgr", Messenger::get_random_nonce())), objecter{g_ceph_context, client_messenger.get(), &monc, poolctx}, client{client_messenger.get(), &monc, &objecter}, mgrc(g_ceph_context, client_messenger.get(), &monc.monmap), log_client(g_ceph_context, client_messenger.get(), &monc.monmap, LogClient::NO_FLAGS), clog(log_client.create_channel(CLOG_CHANNEL_CLUSTER)), audit_clog(log_client.create_channel(CLOG_CHANNEL_AUDIT)), finisher(g_ceph_context, "MgrStandby", "mgrsb-fin"), timer(g_ceph_context, lock), py_module_registry(clog), active_mgr(nullptr), orig_argc(argc), orig_argv(argv), available_in_map(false) { } MgrStandby::~MgrStandby() = default; const char** MgrStandby::get_tracked_conf_keys() const { static const char* KEYS[] = { // clog & admin clog "clog_to_monitors", "clog_to_syslog", "clog_to_syslog_facility", "clog_to_syslog_level", "clog_to_graylog", "clog_to_graylog_host", "clog_to_graylog_port", "mgr_standby_modules", "host", "fsid", NULL }; return KEYS; } void MgrStandby::handle_conf_change( const ConfigProxy& conf, const std::set <std::string> &changed) { if (changed.count("clog_to_monitors") || changed.count("clog_to_syslog") || changed.count("clog_to_syslog_level") || changed.count("clog_to_syslog_facility") || changed.count("clog_to_graylog") || changed.count("clog_to_graylog_host") || changed.count("clog_to_graylog_port") || changed.count("host") || changed.count("fsid")) { _update_log_config(); } if (changed.count("mgr_standby_modules") && !active_mgr) { if (g_conf().get_val<bool>("mgr_standby_modules") != py_module_registry.have_standby_modules()) { dout(1) << "mgr_standby_modules now " << (int)g_conf().get_val<bool>("mgr_standby_modules") << ", standby modules are " << (py_module_registry.have_standby_modules() ? "":"not ") << "active, respawning" << dendl; respawn(); } } } int MgrStandby::init() { init_async_signal_handler(); register_async_signal_handler(SIGHUP, sighup_handler); cct->_conf.add_observer(this); std::lock_guard l(lock); // Start finisher finisher.start(); // Initialize Messenger client_messenger->add_dispatcher_tail(this); client_messenger->add_dispatcher_head(&objecter); client_messenger->add_dispatcher_tail(&client); client_messenger->start(); poolctx.start(2); // Initialize MonClient if (monc.build_initial_monmap() < 0) { client_messenger->shutdown(); client_messenger->wait(); return -1; } monc.sub_want("mgrmap", 0, 0); monc.set_want_keys(CEPH_ENTITY_TYPE_MON|CEPH_ENTITY_TYPE_OSD |CEPH_ENTITY_TYPE_MDS|CEPH_ENTITY_TYPE_MGR); monc.set_messenger(client_messenger.get()); // We must register our config callback before calling init(), so // that we see the initial configuration message monc.register_config_callback([this](const std::string &k, const std::string &v){ // removing value to hide sensitive data going into mgr logs // leaving this for debugging purposes // dout(10) << "config_callback: " << k << " : " << v << dendl; dout(10) << "config_callback: " << k << " : " << dendl; if (k.substr(0, 4) == "mgr/") { py_module_registry.handle_config(k, v); return true; } return false; }); monc.register_config_notify_callback([this]() { py_module_registry.handle_config_notify(); }); dout(4) << "Registered monc callback" << dendl; int r = monc.init(); if (r < 0) { monc.shutdown(); client_messenger->shutdown(); client_messenger->wait(); return r; } mgrc.init(); client_messenger->add_dispatcher_tail(&mgrc); r = monc.authenticate(); if (r < 0) { derr << "Authentication failed, did you specify a mgr ID with a valid keyring?" << dendl; monc.shutdown(); client_messenger->shutdown(); client_messenger->wait(); return r; } // only forward monmap updates after authentication finishes, otherwise // monc.authenticate() will be waiting for MgrStandy::ms_dispatch() // to acquire the lock forever, as it is already locked in the beginning of // this method. monc.set_passthrough_monmap(); client_t whoami = monc.get_global_id(); client_messenger->set_myname(entity_name_t::MGR(whoami.v)); monc.set_log_client(&log_client); _update_log_config(); objecter.set_client_incarnation(0); objecter.init(); objecter.start(); client.init(); timer.init(); py_module_registry.init(); mgr_perf_start(g_ceph_context); tick(); dout(4) << "Complete." << dendl; return 0; } void MgrStandby::send_beacon() { ceph_assert(ceph_mutex_is_locked_by_me(lock)); dout(20) << state_str() << dendl; auto modules = py_module_registry.get_modules(); // Construct a list of the info about each loaded module // which we will transmit to the monitor. std::vector<MgrMap::ModuleInfo> module_info; for (const auto &module : modules) { MgrMap::ModuleInfo info; info.name = module->get_name(); info.error_string = module->get_error_string(); info.can_run = module->get_can_run(); info.module_options = module->get_options(); module_info.push_back(std::move(info)); } auto clients = py_module_registry.get_clients(); for (const auto& client : clients) { dout(15) << "noting RADOS client for blocklist: " << client << dendl; } // Whether I think I am available (request MgrMonitor to set me // as available in the map) bool available = active_mgr != nullptr && active_mgr->is_initialized(); auto addrs = available ? active_mgr->get_server_addrs() : entity_addrvec_t(); dout(10) << "sending beacon as gid " << monc.get_global_id() << dendl; map<string,string> metadata; metadata["addr"] = client_messenger->get_myaddr_legacy().ip_only_to_str(); metadata["addrs"] = stringify(client_messenger->get_myaddrs()); collect_sys_info(&metadata, g_ceph_context); auto m = ceph::make_message<MMgrBeacon>(monc.get_fsid(), monc.get_global_id(), g_conf()->name.get_id(), addrs, available, std::move(module_info), std::move(metadata), std::move(clients), CEPH_FEATURES_ALL); if (available) { if (!available_in_map) { // We are informing the mon that we are done initializing: inform // it of our command set. This has to happen after init() because // it needs the python modules to have loaded. std::vector<MonCommand> commands = mgr_commands; std::vector<MonCommand> py_commands = py_module_registry.get_commands(); commands.insert(commands.end(), py_commands.begin(), py_commands.end()); if (monc.monmap.min_mon_release < ceph_release_t::quincy) { dout(10) << " stripping out positional=false quincy-ism" << dendl; for (auto& i : commands) { boost::replace_all(i.cmdstring, ",positional=false", ""); } } m->set_command_descs(commands); dout(4) << "going active, including " << m->get_command_descs().size() << " commands in beacon" << dendl; } m->set_services(active_mgr->get_services()); } monc.send_mon_message(std::move(m)); } void MgrStandby::tick() { dout(10) << __func__ << dendl; send_beacon(); timer.add_event_after( g_conf().get_val<std::chrono::seconds>("mgr_tick_period").count(), new LambdaContext([this](int r){ tick(); } )); } void MgrStandby::shutdown() { finisher.queue(new LambdaContext([&](int) { std::lock_guard l(lock); dout(4) << "Shutting down" << dendl; py_module_registry.shutdown(); // stop sending beacon first, I use monc to talk with monitors timer.shutdown(); // client uses monc and objecter client.shutdown(); mgrc.shutdown(); // Stop asio threads, so leftover events won't call into shut down // monclient/objecter. poolctx.finish(); // stop monc, so mon won't be able to instruct me to shutdown/activate after // the active_mgr is stopped monc.shutdown(); if (active_mgr) { active_mgr->shutdown(); } // objecter is used by monc and active_mgr objecter.shutdown(); // client_messenger is used by all of them, so stop it in the end client_messenger->shutdown(); })); // Then stop the finisher to ensure its enqueued contexts aren't going // to touch references to the things we're about to tear down finisher.wait_for_empty(); finisher.stop(); mgr_perf_stop(g_ceph_context); } void MgrStandby::respawn() { // --- WARNING TO FUTURE COPY/PASTERS --- // You must also add a call like // // ceph_pthread_setname(pthread_self(), "ceph-mgr"); // // to main() so that /proc/$pid/stat field 2 contains "(ceph-mgr)" // instead of "(exe)", so that killall (and log rotation) will work. char *new_argv[orig_argc+1]; dout(1) << " e: '" << orig_argv[0] << "'" << dendl; for (int i=0; i<orig_argc; i++) { new_argv[i] = (char *)orig_argv[i]; dout(1) << " " << i << ": '" << orig_argv[i] << "'" << dendl; } new_argv[orig_argc] = NULL; /* Determine the path to our executable, test if Linux /proc/self/exe exists. * This allows us to exec the same executable even if it has since been * unlinked. */ char exe_path[PATH_MAX] = ""; if (readlink(PROCPREFIX "/proc/self/exe", exe_path, PATH_MAX-1) == -1) { /* Print CWD for the user's interest */ char buf[PATH_MAX]; char *cwd = getcwd(buf, sizeof(buf)); ceph_assert(cwd); dout(1) << " cwd " << cwd << dendl; /* Fall back to a best-effort: just running in our CWD */ strncpy(exe_path, orig_argv[0], PATH_MAX-1); } else { dout(1) << "respawning with exe " << exe_path << dendl; strcpy(exe_path, PROCPREFIX "/proc/self/exe"); } dout(1) << " exe_path " << exe_path << dendl; unblock_all_signals(NULL); execv(exe_path, new_argv); derr << "respawn execv " << orig_argv[0] << " failed with " << cpp_strerror(errno) << dendl; ceph_abort(); } void MgrStandby::_update_log_config() { clog->parse_client_options(cct); audit_clog->parse_client_options(cct); } void MgrStandby::handle_mgr_map(ref_t<MMgrMap> mmap) { auto &map = mmap->get_map(); dout(4) << "received map epoch " << map.get_epoch() << dendl; const bool active_in_map = map.active_gid == monc.get_global_id(); dout(4) << "active in map: " << active_in_map << " active is " << map.active_gid << dendl; // PyModuleRegistry may ask us to respawn if it sees that // this MgrMap is changing its set of enabled modules bool need_respawn = py_module_registry.handle_mgr_map(map); if (need_respawn) { dout(1) << "respawning because set of enabled modules changed!" << dendl; respawn(); } if (active_in_map) { if (!active_mgr) { dout(1) << "Activating!" << dendl; active_mgr.reset(new Mgr(&monc, map, &py_module_registry, client_messenger.get(), &objecter, &client, clog, audit_clog)); active_mgr->background_init(new LambdaContext( [this](int r){ // Advertise our active-ness ASAP instead of waiting for // next tick. std::lock_guard l(lock); send_beacon(); })); dout(1) << "I am now activating" << dendl; } else { dout(10) << "I was already active" << dendl; bool need_respawn = active_mgr->got_mgr_map(map); if (need_respawn) { respawn(); } } if (!available_in_map && map.get_available()) { dout(4) << "Map now says I am available" << dendl; available_in_map = true; } } else if (active_mgr != nullptr) { derr << "I was active but no longer am" << dendl; respawn(); } else { if (map.active_gid != 0 && map.active_name != g_conf()->name.get_id()) { // I am the standby and someone else is active, start modules // in standby mode to do redirects if needed if (!py_module_registry.is_standby_running() && g_conf().get_val<bool>("mgr_standby_modules")) { py_module_registry.standby_start(monc, finisher); } } } } bool MgrStandby::ms_dispatch2(const ref_t<Message>& m) { std::lock_guard l(lock); dout(10) << state_str() << " " << *m << dendl; if (m->get_type() == MSG_MGR_MAP) { handle_mgr_map(ref_cast<MMgrMap>(m)); } bool handled = false; if (active_mgr) { auto am = active_mgr; lock.unlock(); handled = am->ms_dispatch2(m); lock.lock(); } if (m->get_type() == MSG_MGR_MAP) { // let this pass through for mgrc handled = false; } return handled; } bool MgrStandby::ms_handle_refused(Connection *con) { // do nothing for now return false; } int MgrStandby::main(vector<const char *> args) { client_messenger->wait(); // Disable signal handlers unregister_async_signal_handler(SIGHUP, sighup_handler); shutdown_async_signal_handler(); return 0; } std::string MgrStandby::state_str() { if (active_mgr == nullptr) { return "standby"; } else if (active_mgr->is_initialized()) { return "active"; } else { return "active (starting)"; } }
14,740
28.840081
101
cc
null
ceph-main/src/mgr/MgrStandby.h
// -*- 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 John Spray <[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. */ #ifndef MGR_STANDBY_H_ #define MGR_STANDBY_H_ #include "auth/Auth.h" #include "common/async/context_pool.h" #include "common/Finisher.h" #include "common/Timer.h" #include "common/LogClient.h" #include "client/Client.h" #include "mon/MonClient.h" #include "osdc/Objecter.h" #include "PyModuleRegistry.h" #include "MgrClient.h" class MMgrMap; class Mgr; class PyModuleConfig; class MgrStandby : public Dispatcher, public md_config_obs_t { public: // config observer bits const char** get_tracked_conf_keys() const override; void handle_conf_change(const ConfigProxy& conf, const std::set <std::string> &changed) override; protected: ceph::async::io_context_pool poolctx; MonClient monc; std::unique_ptr<Messenger> client_messenger; Objecter objecter; Client client; MgrClient mgrc; LogClient log_client; LogChannelRef clog, audit_clog; ceph::mutex lock = ceph::make_mutex("MgrStandby::lock"); Finisher finisher; SafeTimer timer; PyModuleRegistry py_module_registry; std::shared_ptr<Mgr> active_mgr; int orig_argc; const char **orig_argv; std::string state_str(); void handle_mgr_map(ceph::ref_t<MMgrMap> m); void _update_log_config(); void send_beacon(); bool available_in_map; public: MgrStandby(int argc, const char **argv); ~MgrStandby() override; bool ms_dispatch2(const ceph::ref_t<Message>& m) override; bool ms_handle_reset(Connection *con) override { return false; } void ms_handle_remote_reset(Connection *con) override {} bool ms_handle_refused(Connection *con) override; int init(); void shutdown(); void respawn(); int main(std::vector<const char *> args); void tick(); }; #endif
2,111
22.466667
70
h
null
ceph-main/src/mgr/OSDPerfMetricCollector.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "common/debug.h" #include "common/errno.h" #include "messages/MMgrReport.h" #include "OSDPerfMetricCollector.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr.osd_perf_metric_collector " << __func__ << " " OSDPerfMetricCollector::OSDPerfMetricCollector(MetricListener &listener) : MetricCollector<OSDPerfMetricQuery, OSDPerfMetricLimit, OSDPerfMetricKey, OSDPerfMetricReport>(listener) { } void OSDPerfMetricCollector::process_reports(const MetricPayload &payload) { const std::map<OSDPerfMetricQuery, OSDPerfMetricReport> &reports = boost::get<OSDMetricPayload>(payload).report; std::lock_guard locker(lock); process_reports_generic( reports, [](PerformanceCounter *counter, const PerformanceCounter &update) { counter->first += update.first; counter->second += update.second; }); } int OSDPerfMetricCollector::get_counters(PerfCollector *collector) { OSDPerfCollector *c = static_cast<OSDPerfCollector *>(collector); std::lock_guard locker(lock); return get_counters_generic(c->query_id, &c->counters); }
1,299
31.5
81
cc
null
ceph-main/src/mgr/OSDPerfMetricCollector.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef OSD_PERF_METRIC_COLLECTOR_H_ #define OSD_PERF_METRIC_COLLECTOR_H_ #include "mgr/MetricCollector.h" #include "mgr/OSDPerfMetricTypes.h" /** * OSD performance query class. */ class OSDPerfMetricCollector : public MetricCollector<OSDPerfMetricQuery, OSDPerfMetricLimit, OSDPerfMetricKey, OSDPerfMetricReport> { public: OSDPerfMetricCollector(MetricListener &listener); void process_reports(const MetricPayload &payload) override; int get_counters(PerfCollector *collector) override; }; #endif // OSD_PERF_METRIC_COLLECTOR_H_
670
26.958333
84
h
null
ceph-main/src/mgr/OSDPerfMetricTypes.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "mgr/OSDPerfMetricTypes.h" #include <ostream> using ceph::bufferlist; std::ostream& operator<<(std::ostream& os, const OSDPerfMetricSubKeyDescriptor &d) { switch(d.type) { case OSDPerfMetricSubKeyType::CLIENT_ID: os << "client_id"; break; case OSDPerfMetricSubKeyType::CLIENT_ADDRESS: os << "client_address"; break; case OSDPerfMetricSubKeyType::POOL_ID: os << "pool_id"; break; case OSDPerfMetricSubKeyType::NAMESPACE: os << "namespace"; break; case OSDPerfMetricSubKeyType::OSD_ID: os << "osd_id"; break; case OSDPerfMetricSubKeyType::PG_ID: os << "pg_id"; break; case OSDPerfMetricSubKeyType::OBJECT_NAME: os << "object_name"; break; case OSDPerfMetricSubKeyType::SNAP_ID: os << "snap_id"; break; default: os << "unknown (" << static_cast<int>(d.type) << ")"; } return os << "~/" << d.regex_str << "/"; } void PerformanceCounterDescriptor::pack_counter(const PerformanceCounter &c, bufferlist *bl) const { using ceph::encode; encode(c.first, *bl); switch(type) { case PerformanceCounterType::OPS: case PerformanceCounterType::WRITE_OPS: case PerformanceCounterType::READ_OPS: case PerformanceCounterType::BYTES: case PerformanceCounterType::WRITE_BYTES: case PerformanceCounterType::READ_BYTES: break; case PerformanceCounterType::LATENCY: case PerformanceCounterType::WRITE_LATENCY: case PerformanceCounterType::READ_LATENCY: encode(c.second, *bl); break; default: ceph_abort_msg("unknown counter type"); } } void PerformanceCounterDescriptor::unpack_counter( bufferlist::const_iterator& bl, PerformanceCounter *c) const { using ceph::decode; decode(c->first, bl); switch(type) { case PerformanceCounterType::OPS: case PerformanceCounterType::WRITE_OPS: case PerformanceCounterType::READ_OPS: case PerformanceCounterType::BYTES: case PerformanceCounterType::WRITE_BYTES: case PerformanceCounterType::READ_BYTES: break; case PerformanceCounterType::LATENCY: case PerformanceCounterType::WRITE_LATENCY: case PerformanceCounterType::READ_LATENCY: decode(c->second, bl); break; default: ceph_abort_msg("unknown counter type"); } } std::ostream& operator<<(std::ostream& os, const PerformanceCounterDescriptor &d) { switch(d.type) { case PerformanceCounterType::OPS: return os << "ops"; case PerformanceCounterType::WRITE_OPS: return os << "write ops"; case PerformanceCounterType::READ_OPS: return os << "read ops"; case PerformanceCounterType::BYTES: return os << "bytes"; case PerformanceCounterType::WRITE_BYTES: return os << "write bytes"; case PerformanceCounterType::READ_BYTES: return os << "read bytes"; case PerformanceCounterType::LATENCY: return os << "latency"; case PerformanceCounterType::WRITE_LATENCY: return os << "write latency"; case PerformanceCounterType::READ_LATENCY: return os << "read latency"; default: return os << "unknown (" << static_cast<int>(d.type) << ")"; } } std::ostream& operator<<(std::ostream& os, const OSDPerfMetricLimit &limit) { return os << "{order_by=" << limit.order_by << ", max_count=" << limit.max_count << "}"; } void OSDPerfMetricQuery::pack_counters(const PerformanceCounters &counters, bufferlist *bl) const { auto it = counters.begin(); for (auto &descriptor : performance_counter_descriptors) { if (it == counters.end()) { descriptor.pack_counter(PerformanceCounter(), bl); } else { descriptor.pack_counter(*it, bl); it++; } } } std::ostream& operator<<(std::ostream& os, const OSDPerfMetricQuery &query) { return os << "{key=" << query.key_descriptor << ", counters=" << query.performance_counter_descriptors << "}"; }
4,041
28.940741
77
cc
null
ceph-main/src/mgr/OSDPerfMetricTypes.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef OSD_PERF_METRIC_H_ #define OSD_PERF_METRIC_H_ #include "include/denc.h" #include "include/stringify.h" #include "mgr/Types.h" #include <regex> typedef std::vector<std::string> OSDPerfMetricSubKey; // array of regex match typedef std::vector<OSDPerfMetricSubKey> OSDPerfMetricKey; enum class OSDPerfMetricSubKeyType : uint8_t { CLIENT_ID = 0, CLIENT_ADDRESS = 1, POOL_ID = 2, NAMESPACE = 3, OSD_ID = 4, PG_ID = 5, OBJECT_NAME = 6, SNAP_ID = 7, }; struct OSDPerfMetricSubKeyDescriptor { OSDPerfMetricSubKeyType type = static_cast<OSDPerfMetricSubKeyType>(-1); std::string regex_str; std::regex regex; bool is_supported() const { switch (type) { case OSDPerfMetricSubKeyType::CLIENT_ID: case OSDPerfMetricSubKeyType::CLIENT_ADDRESS: case OSDPerfMetricSubKeyType::POOL_ID: case OSDPerfMetricSubKeyType::NAMESPACE: case OSDPerfMetricSubKeyType::OSD_ID: case OSDPerfMetricSubKeyType::PG_ID: case OSDPerfMetricSubKeyType::OBJECT_NAME: case OSDPerfMetricSubKeyType::SNAP_ID: return true; default: return false; } } OSDPerfMetricSubKeyDescriptor() { } OSDPerfMetricSubKeyDescriptor(OSDPerfMetricSubKeyType type, const std::string regex) : type(type), regex_str(regex) { } bool operator<(const OSDPerfMetricSubKeyDescriptor &other) const { if (type < other.type) { return true; } if (type > other.type) { return false; } return regex_str < other.regex_str; } DENC(OSDPerfMetricSubKeyDescriptor, v, p) { DENC_START(1, 1, p); denc(v.type, p); denc(v.regex_str, p); DENC_FINISH(p); } }; WRITE_CLASS_DENC(OSDPerfMetricSubKeyDescriptor) std::ostream& operator<<(std::ostream& os, const OSDPerfMetricSubKeyDescriptor &d); typedef std::vector<OSDPerfMetricSubKeyDescriptor> OSDPerfMetricKeyDescriptor; template<> struct denc_traits<OSDPerfMetricKeyDescriptor> { static constexpr bool supported = true; static constexpr bool bounded = false; static constexpr bool featured = false; static constexpr bool need_contiguous = true; static void bound_encode(const OSDPerfMetricKeyDescriptor& v, size_t& p) { p += sizeof(uint32_t); const auto size = v.size(); if (size) { size_t per = 0; denc(v.front(), per); p += per * size; } } static void encode(const OSDPerfMetricKeyDescriptor& v, ceph::buffer::list::contiguous_appender& p) { denc_varint(v.size(), p); for (auto& i : v) { denc(i, p); } } static void decode(OSDPerfMetricKeyDescriptor& v, ceph::buffer::ptr::const_iterator& p) { unsigned num; denc_varint(num, p); v.clear(); v.reserve(num); for (unsigned i=0; i < num; ++i) { OSDPerfMetricSubKeyDescriptor d; denc(d, p); if (!d.is_supported()) { v.clear(); return; } try { d.regex = d.regex_str.c_str(); } catch (const std::regex_error& e) { v.clear(); return; } if (d.regex.mark_count() == 0) { v.clear(); return; } v.push_back(std::move(d)); } } }; enum class PerformanceCounterType : uint8_t { OPS = 0, WRITE_OPS = 1, READ_OPS = 2, BYTES = 3, WRITE_BYTES = 4, READ_BYTES = 5, LATENCY = 6, WRITE_LATENCY = 7, READ_LATENCY = 8, }; struct PerformanceCounterDescriptor { PerformanceCounterType type = static_cast<PerformanceCounterType>(-1); bool is_supported() const { switch (type) { case PerformanceCounterType::OPS: case PerformanceCounterType::WRITE_OPS: case PerformanceCounterType::READ_OPS: case PerformanceCounterType::BYTES: case PerformanceCounterType::WRITE_BYTES: case PerformanceCounterType::READ_BYTES: case PerformanceCounterType::LATENCY: case PerformanceCounterType::WRITE_LATENCY: case PerformanceCounterType::READ_LATENCY: return true; default: return false; } } PerformanceCounterDescriptor() { } PerformanceCounterDescriptor(PerformanceCounterType type) : type(type) { } bool operator<(const PerformanceCounterDescriptor &other) const { return type < other.type; } bool operator==(const PerformanceCounterDescriptor &other) const { return type == other.type; } bool operator!=(const PerformanceCounterDescriptor &other) const { return type != other.type; } DENC(PerformanceCounterDescriptor, v, p) { DENC_START(1, 1, p); denc(v.type, p); DENC_FINISH(p); } void pack_counter(const PerformanceCounter &c, ceph::buffer::list *bl) const; void unpack_counter(ceph::buffer::list::const_iterator& bl, PerformanceCounter *c) const; }; WRITE_CLASS_DENC(PerformanceCounterDescriptor) std::ostream& operator<<(std::ostream& os, const PerformanceCounterDescriptor &d); typedef std::vector<PerformanceCounterDescriptor> PerformanceCounterDescriptors; template<> struct denc_traits<PerformanceCounterDescriptors> { static constexpr bool supported = true; static constexpr bool bounded = false; static constexpr bool featured = false; static constexpr bool need_contiguous = true; static void bound_encode(const PerformanceCounterDescriptors& v, size_t& p) { p += sizeof(uint32_t); const auto size = v.size(); if (size) { size_t per = 0; denc(v.front(), per); p += per * size; } } static void encode(const PerformanceCounterDescriptors& v, ceph::buffer::list::contiguous_appender& p) { denc_varint(v.size(), p); for (auto& i : v) { denc(i, p); } } static void decode(PerformanceCounterDescriptors& v, ceph::buffer::ptr::const_iterator& p) { unsigned num; denc_varint(num, p); v.clear(); v.reserve(num); for (unsigned i=0; i < num; ++i) { PerformanceCounterDescriptor d; denc(d, p); if (d.is_supported()) { v.push_back(std::move(d)); } } } }; struct OSDPerfMetricLimit { PerformanceCounterDescriptor order_by; uint64_t max_count = 0; OSDPerfMetricLimit() { } OSDPerfMetricLimit(const PerformanceCounterDescriptor &order_by, uint64_t max_count) : order_by(order_by), max_count(max_count) { } bool operator<(const OSDPerfMetricLimit &other) const { if (order_by != other.order_by) { return order_by < other.order_by; } return max_count < other.max_count; } DENC(OSDPerfMetricLimit, v, p) { DENC_START(1, 1, p); denc(v.order_by, p); denc(v.max_count, p); DENC_FINISH(p); } }; WRITE_CLASS_DENC(OSDPerfMetricLimit) std::ostream& operator<<(std::ostream& os, const OSDPerfMetricLimit &limit); typedef std::set<OSDPerfMetricLimit> OSDPerfMetricLimits; struct OSDPerfMetricQuery { bool operator<(const OSDPerfMetricQuery &other) const { if (key_descriptor < other.key_descriptor) { return true; } if (key_descriptor > other.key_descriptor) { return false; } return (performance_counter_descriptors < other.performance_counter_descriptors); } OSDPerfMetricQuery() { } OSDPerfMetricQuery( const OSDPerfMetricKeyDescriptor &key_descriptor, const PerformanceCounterDescriptors &performance_counter_descriptors) : key_descriptor(key_descriptor), performance_counter_descriptors(performance_counter_descriptors) { } template <typename L> bool get_key(L&& get_sub_key, OSDPerfMetricKey *key) const { for (auto &sub_key_descriptor : key_descriptor) { OSDPerfMetricSubKey sub_key; if (!get_sub_key(sub_key_descriptor, &sub_key)) { return false; } key->push_back(sub_key); } return true; } DENC(OSDPerfMetricQuery, v, p) { DENC_START(1, 1, p); denc(v.key_descriptor, p); denc(v.performance_counter_descriptors, p); DENC_FINISH(p); } void get_performance_counter_descriptors( PerformanceCounterDescriptors *descriptors) const { *descriptors = performance_counter_descriptors; } template <typename L> void update_counters(L &&update_counter, PerformanceCounters *counters) const { auto it = counters->begin(); for (auto &descriptor : performance_counter_descriptors) { // TODO: optimize if (it == counters->end()) { counters->push_back(PerformanceCounter()); it = std::prev(counters->end()); } update_counter(descriptor, &(*it)); it++; } } void pack_counters(const PerformanceCounters &counters, ceph::buffer::list *bl) const; OSDPerfMetricKeyDescriptor key_descriptor; PerformanceCounterDescriptors performance_counter_descriptors; }; WRITE_CLASS_DENC(OSDPerfMetricQuery) struct OSDPerfCollector : PerfCollector { std::map<OSDPerfMetricKey, PerformanceCounters> counters; OSDPerfCollector(MetricQueryID query_id) : PerfCollector(query_id) { } }; std::ostream& operator<<(std::ostream& os, const OSDPerfMetricQuery &query); struct OSDPerfMetricReport { PerformanceCounterDescriptors performance_counter_descriptors; std::map<OSDPerfMetricKey, ceph::buffer::list> group_packed_performance_counters; DENC(OSDPerfMetricReport, v, p) { DENC_START(1, 1, p); denc(v.performance_counter_descriptors, p); denc(v.group_packed_performance_counters, p); DENC_FINISH(p); } }; WRITE_CLASS_DENC(OSDPerfMetricReport) #endif // OSD_PERF_METRIC_H_
9,625
25.66482
88
h
null
ceph-main/src/mgr/PyFormatter.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 Red Hat Inc * * Author: John Spray <[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 "PyFormatter.h" #include <fstream> #define LARGE_SIZE 1024 void PyFormatter::open_array_section(std::string_view name) { PyObject *list = PyList_New(0); dump_pyobject(name, list); stack.push(cursor); cursor = list; } void PyFormatter::open_object_section(std::string_view name) { PyObject *dict = PyDict_New(); dump_pyobject(name, dict); stack.push(cursor); cursor = dict; } void PyFormatter::dump_unsigned(std::string_view name, uint64_t u) { PyObject *p = PyLong_FromUnsignedLong(u); ceph_assert(p); dump_pyobject(name, p); } void PyFormatter::dump_int(std::string_view name, int64_t u) { PyObject *p = PyLong_FromLongLong(u); ceph_assert(p); dump_pyobject(name, p); } void PyFormatter::dump_float(std::string_view name, double d) { dump_pyobject(name, PyFloat_FromDouble(d)); } void PyFormatter::dump_string(std::string_view name, std::string_view s) { dump_pyobject(name, PyUnicode_FromString(s.data())); } void PyFormatter::dump_bool(std::string_view name, bool b) { if (b) { Py_INCREF(Py_True); dump_pyobject(name, Py_True); } else { Py_INCREF(Py_False); dump_pyobject(name, Py_False); } } std::ostream& PyFormatter::dump_stream(std::string_view name) { // Give the caller an ostream, construct a PyString, // and remember the association between the two. On flush, // we'll read from the ostream into the PyString auto ps = std::make_shared<PendingStream>(); ps->cursor = cursor; ps->name = name; pending_streams.push_back(ps); return ps->stream; } void PyFormatter::dump_format_va(std::string_view name, const char *ns, bool quoted, const char *fmt, va_list ap) { char buf[LARGE_SIZE]; vsnprintf(buf, LARGE_SIZE, fmt, ap); dump_pyobject(name, PyUnicode_FromString(buf)); } /** * Steals reference to `p` */ void PyFormatter::dump_pyobject(std::string_view name, PyObject *p) { if (PyList_Check(cursor)) { PyList_Append(cursor, p); Py_DECREF(p); } else if (PyDict_Check(cursor)) { PyObject *key = PyUnicode_DecodeUTF8(name.data(), name.size(), nullptr); PyDict_SetItem(cursor, key, p); Py_DECREF(key); Py_DECREF(p); } else { ceph_abort(); } } void PyFormatter::finish_pending_streams() { for (const auto &i : pending_streams) { PyObject *tmp_cur = cursor; cursor = i->cursor; dump_pyobject( i->name.c_str(), PyUnicode_FromString(i->stream.str().c_str())); cursor = tmp_cur; } pending_streams.clear(); } PyObject* PyJSONFormatter::get() { if(json_formatter::stack_size()) { close_section(); } ceph_assert(!json_formatter::stack_size()); std::ostringstream ss; flush(ss); std::string s = ss.str(); PyObject* obj = PyBytes_FromStringAndSize(std::move(s.c_str()), s.size()); return obj; }
3,244
22.014184
113
cc
null
ceph-main/src/mgr/PyFormatter.h
// -*- 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 Red Hat Inc * * Author: John Spray <[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. * */ #ifndef PY_FORMATTER_H_ #define PY_FORMATTER_H_ // Python.h comes first because otherwise it clobbers ceph's assert #include <Python.h> #include <stack> #include <string> #include <string_view> #include <sstream> #include <memory> #include <list> #include "common/Formatter.h" #include "include/ceph_assert.h" class PyFormatter : public ceph::Formatter { public: PyFormatter (const PyFormatter&) = delete; PyFormatter& operator= (const PyFormatter&) = delete; PyFormatter(bool pretty = false, bool array = false) { // It is forbidden to instantiate me outside of the GIL, // because I construct python objects right away // Initialise cursor to an empty dict if (!array) { root = cursor = PyDict_New(); } else { root = cursor = PyList_New(0); } } ~PyFormatter() override { cursor = NULL; Py_DECREF(root); root = NULL; } // Obscure, don't care. void open_array_section_in_ns(std::string_view name, const char *ns) override {ceph_abort();} void open_object_section_in_ns(std::string_view name, const char *ns) override {ceph_abort();} void reset() override { const bool array = PyList_Check(root); Py_DECREF(root); if (array) { root = cursor = PyList_New(0); } else { root = cursor = PyDict_New(); } } void set_status(int status, const char* status_name) override {} void output_header() override {}; void output_footer() override {}; void enable_line_break() override {}; void open_array_section(std::string_view name) override; void open_object_section(std::string_view name) override; void close_section() override { ceph_assert(cursor != root); ceph_assert(!stack.empty()); cursor = stack.top(); stack.pop(); } void dump_bool(std::string_view name, bool b) override; void dump_unsigned(std::string_view name, uint64_t u) override; void dump_int(std::string_view name, int64_t u) override; void dump_float(std::string_view name, double d) override; void dump_string(std::string_view name, std::string_view s) override; std::ostream& dump_stream(std::string_view name) override; void dump_format_va(std::string_view name, const char *ns, bool quoted, const char *fmt, va_list ap) override; void flush(std::ostream& os) override { // This class is not a serializer: this doesn't make sense ceph_abort(); } int get_len() const override { // This class is not a serializer: this doesn't make sense ceph_abort(); return 0; } void write_raw_data(const char *data) override { // This class is not a serializer: this doesn't make sense ceph_abort(); } PyObject *get() { finish_pending_streams(); Py_INCREF(root); return root; } void finish_pending_streams(); private: PyObject *root; PyObject *cursor; std::stack<PyObject *> stack; void dump_pyobject(std::string_view name, PyObject *p); class PendingStream { public: PyObject *cursor; std::string name; std::stringstream stream; }; std::list<std::shared_ptr<PendingStream> > pending_streams; }; class PyJSONFormatter : public JSONFormatter { public: PyObject *get(); PyJSONFormatter (const PyJSONFormatter&) = default; PyJSONFormatter(bool pretty=false, bool is_array=false) : JSONFormatter(pretty) { if(is_array) { open_array_section(""); } else { open_object_section(""); } } private: using json_formatter = JSONFormatter; template <class T> void add_value(std::string_view name, T val); void add_value(std::string_view name, std::string_view val, bool quoted); }; #endif
4,101
24.012195
112
h
null
ceph-main/src/mgr/PyModule.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) 2017 John Spray <[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 "BaseMgrModule.h" #include "BaseMgrStandbyModule.h" #include "PyOSDMap.h" #include "MgrContext.h" #include "PyUtil.h" #include "PyModule.h" #include "include/stringify.h" #include "common/BackTrace.h" #include "global/signal_handler.h" #include "common/debug.h" #include "common/errno.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr[py] " // definition for non-const static member std::string PyModule::mgr_store_prefix = "mgr/"; // Courtesy of http://stackoverflow.com/questions/1418015/how-to-get-python-exception-text #define BOOST_BIND_GLOBAL_PLACEHOLDERS // Boost apparently can't be bothered to fix its own usage of its own // deprecated features. #include <boost/python/extract.hpp> #include <boost/python/import.hpp> #include <boost/python/object.hpp> #undef BOOST_BIND_GLOBAL_PLACEHOLDERS #include <boost/algorithm/string/predicate.hpp> #include "include/ceph_assert.h" // boost clobbers this using std::string; using std::wstring; // decode a Python exception into a string std::string handle_pyerror( bool crash_dump, std::string module, std::string caller) { using namespace boost::python; using namespace boost; PyObject *exc, *val, *tb; object formatted_list, formatted; PyErr_Fetch(&exc, &val, &tb); PyErr_NormalizeException(&exc, &val, &tb); handle<> hexc(exc), hval(allow_null(val)), htb(allow_null(tb)); object traceback(import("traceback")); if (!tb) { object format_exception_only(traceback.attr("format_exception_only")); try { formatted_list = format_exception_only(hexc, hval); } catch (error_already_set const &) { // error while processing exception object // returning only the exception string value PyObject *name_attr = PyObject_GetAttrString(exc, "__name__"); std::stringstream ss; ss << PyUnicode_AsUTF8(name_attr) << ": " << PyUnicode_AsUTF8(val); Py_XDECREF(name_attr); ss << "\nError processing exception object: " << peek_pyerror(); return ss.str(); } } else { object format_exception(traceback.attr("format_exception")); try { formatted_list = format_exception(hexc, hval, htb); } catch (error_already_set const &) { // error while processing exception object // returning only the exception string value PyObject *name_attr = PyObject_GetAttrString(exc, "__name__"); std::stringstream ss; ss << PyUnicode_AsUTF8(name_attr) << ": " << PyUnicode_AsUTF8(val); Py_XDECREF(name_attr); ss << "\nError processing exception object: " << peek_pyerror(); return ss.str(); } } formatted = str("").join(formatted_list); if (!module.empty()) { std::list<std::string> bt_strings; std::map<std::string, std::string> extra; extra["mgr_module"] = module; extra["mgr_module_caller"] = caller; PyObject *name_attr = PyObject_GetAttrString(exc, "__name__"); extra["mgr_python_exception"] = stringify(PyUnicode_AsUTF8(name_attr)); Py_XDECREF(name_attr); PyObject *l = get_managed_object(formatted_list, boost::python::tag); if (PyList_Check(l)) { // skip first line, which is: "Traceback (most recent call last):\n" for (unsigned i = 1; i < PyList_Size(l); ++i) { PyObject *val = PyList_GET_ITEM(l, i); std::string s = PyUnicode_AsUTF8(val); s.resize(s.size() - 1); // strip off newline character bt_strings.push_back(s); } } PyBackTrace bt(bt_strings); char crash_path[PATH_MAX]; generate_crash_dump(crash_path, bt, &extra); } return extract<std::string>(formatted); } /** * Get the single-line exception message, without clearing any * exception state. */ std::string peek_pyerror() { PyObject *ptype, *pvalue, *ptraceback; PyErr_Fetch(&ptype, &pvalue, &ptraceback); ceph_assert(ptype); ceph_assert(pvalue); PyObject *pvalue_str = PyObject_Str(pvalue); std::string exc_msg = PyUnicode_AsUTF8(pvalue_str); Py_DECREF(pvalue_str); PyErr_Restore(ptype, pvalue, ptraceback); return exc_msg; } namespace { PyObject* log_write(PyObject*, PyObject* args) { char* m = nullptr; if (PyArg_ParseTuple(args, "s", &m)) { auto len = strlen(m); if (len && m[len-1] == '\n') { m[len-1] = '\0'; } dout(4) << m << dendl; } Py_RETURN_NONE; } PyObject* log_flush(PyObject*, PyObject*){ Py_RETURN_NONE; } static PyMethodDef log_methods[] = { {"write", log_write, METH_VARARGS, "write stdout and stderr"}, {"flush", log_flush, METH_VARARGS, "flush"}, {nullptr, nullptr, 0, nullptr} }; static PyModuleDef ceph_logger_module = { PyModuleDef_HEAD_INIT, "ceph_logger", nullptr, -1, log_methods, }; } PyModuleConfig::PyModuleConfig() = default; PyModuleConfig::PyModuleConfig(PyModuleConfig &mconfig) : config(mconfig.config) {} PyModuleConfig::~PyModuleConfig() = default; std::pair<int, std::string> PyModuleConfig::set_config( MonClient *monc, const std::string &module_name, const std::string &key, const std::optional<std::string>& val) { const std::string global_key = "mgr/" + module_name + "/" + key; Command set_cmd; { std::ostringstream cmd_json; JSONFormatter jf; jf.open_object_section("cmd"); if (val) { jf.dump_string("prefix", "config set"); jf.dump_string("value", *val); } else { jf.dump_string("prefix", "config rm"); } jf.dump_string("who", "mgr"); jf.dump_string("name", global_key); jf.close_section(); jf.flush(cmd_json); set_cmd.run(monc, cmd_json.str()); } set_cmd.wait(); if (set_cmd.r == 0) { std::lock_guard l(lock); if (val) { config[global_key] = *val; } else { config.erase(global_key); } return {0, ""}; } else { if (val) { dout(0) << "`config set mgr " << global_key << " " << val << "` failed: " << cpp_strerror(set_cmd.r) << dendl; } else { dout(0) << "`config rm mgr " << global_key << "` failed: " << cpp_strerror(set_cmd.r) << dendl; } dout(0) << "mon returned " << set_cmd.r << ": " << set_cmd.outs << dendl; return {set_cmd.r, set_cmd.outs}; } } std::string PyModule::get_site_packages() { std::stringstream site_packages; // CPython doesn't auto-add site-packages dirs to sys.path for us, // but it does provide a module that we can ask for them. auto site_module = PyImport_ImportModule("site"); ceph_assert(site_module); auto site_packages_fn = PyObject_GetAttrString(site_module, "getsitepackages"); if (site_packages_fn != nullptr) { auto site_packages_list = PyObject_CallObject(site_packages_fn, nullptr); ceph_assert(site_packages_list); auto n = PyList_Size(site_packages_list); for (Py_ssize_t i = 0; i < n; ++i) { if (i != 0) { site_packages << ":"; } site_packages << PyUnicode_AsUTF8(PyList_GetItem(site_packages_list, i)); } Py_DECREF(site_packages_list); Py_DECREF(site_packages_fn); } else { // Fall back to generating our own site-packages paths by imitating // what the standard site.py does. This is annoying but it lets us // run inside virtualenvs :-/ auto site_packages_fn = PyObject_GetAttrString(site_module, "addsitepackages"); ceph_assert(site_packages_fn); auto known_paths = PySet_New(nullptr); auto pArgs = PyTuple_Pack(1, known_paths); PyObject_CallObject(site_packages_fn, pArgs); Py_DECREF(pArgs); Py_DECREF(known_paths); Py_DECREF(site_packages_fn); auto sys_module = PyImport_ImportModule("sys"); ceph_assert(sys_module); auto sys_path = PyObject_GetAttrString(sys_module, "path"); ceph_assert(sys_path); dout(1) << "sys.path:" << dendl; auto n = PyList_Size(sys_path); bool first = true; for (Py_ssize_t i = 0; i < n; ++i) { dout(1) << " " << PyUnicode_AsUTF8(PyList_GetItem(sys_path, i)) << dendl; if (first) { first = false; } else { site_packages << ":"; } site_packages << PyUnicode_AsUTF8(PyList_GetItem(sys_path, i)); } Py_DECREF(sys_path); Py_DECREF(sys_module); } Py_DECREF(site_module); return site_packages.str(); } PyObject* PyModule::init_ceph_logger() { auto py_logger = PyModule_Create(&ceph_logger_module); PySys_SetObject("stderr", py_logger); PySys_SetObject("stdout", py_logger); return py_logger; } PyObject* PyModule::init_ceph_module() { static PyMethodDef module_methods[] = { {nullptr, nullptr, 0, nullptr} }; static PyModuleDef ceph_module_def = { PyModuleDef_HEAD_INIT, "ceph_module", nullptr, -1, module_methods, nullptr, nullptr, nullptr, nullptr }; PyObject *ceph_module = PyModule_Create(&ceph_module_def); ceph_assert(ceph_module != nullptr); std::map<const char*, PyTypeObject*> classes{ {{"BaseMgrModule", &BaseMgrModuleType}, {"BaseMgrStandbyModule", &BaseMgrStandbyModuleType}, {"BasePyOSDMap", &BasePyOSDMapType}, {"BasePyOSDMapIncremental", &BasePyOSDMapIncrementalType}, {"BasePyCRUSH", &BasePyCRUSHType}} }; for (auto [name, type] : classes) { type->tp_new = PyType_GenericNew; if (PyType_Ready(type) < 0) { ceph_abort(); } Py_INCREF(type); PyModule_AddObject(ceph_module, name, (PyObject *)type); } return ceph_module; } int PyModule::load(PyThreadState *pMainThreadState) { ceph_assert(pMainThreadState != nullptr); // Configure sub-interpreter { SafeThreadState sts(pMainThreadState); Gil gil(sts); auto thread_state = Py_NewInterpreter(); if (thread_state == nullptr) { derr << "Failed to create python sub-interpreter for '" << module_name << '"' << dendl; return -EINVAL; } else { pMyThreadState.set(thread_state); // Some python modules do not cope with an unpopulated argv, so lets // fake one. This step also picks up site-packages into sys.path. const wchar_t *argv[] = {L"ceph-mgr"}; PySys_SetArgv(1, (wchar_t**)argv); // Configure sys.path to include mgr_module_path string paths = (g_conf().get_val<std::string>("mgr_module_path") + ':' + get_site_packages() + ':'); wstring sys_path(wstring(begin(paths), end(paths)) + Py_GetPath()); PySys_SetPath(const_cast<wchar_t*>(sys_path.c_str())); dout(10) << "Computed sys.path '" << string(begin(sys_path), end(sys_path)) << "'" << dendl; } } // Environment is all good, import the external module { Gil gil(pMyThreadState); int r; r = load_subclass_of("MgrModule", &pClass); if (r) { derr << "Class not found in module '" << module_name << "'" << dendl; return r; } r = load_commands(); if (r != 0) { derr << "Missing or invalid COMMANDS attribute in module '" << module_name << "'" << dendl; error_string = "Missing or invalid COMMANDS attribute"; return r; } register_options(pClass); r = load_options(); if (r != 0) { derr << "Missing or invalid MODULE_OPTIONS attribute in module '" << module_name << "'" << dendl; error_string = "Missing or invalid MODULE_OPTIONS attribute"; return r; } load_notify_types(); // We've imported the module and found a MgrModule subclass, at this // point the module is considered loaded. It might still not be // runnable though, can_run populated later... loaded = true; r = load_subclass_of("MgrStandbyModule", &pStandbyClass); if (!r) { dout(4) << "Standby mode available in module '" << module_name << "'" << dendl; register_options(pStandbyClass); } else { dout(4) << "Standby mode not provided by module '" << module_name << "'" << dendl; } // Populate can_run by interrogating the module's callback that // may check for dependencies etc PyObject *pCanRunTuple = PyObject_CallMethod(pClass, const_cast<char*>("can_run"), const_cast<char*>("()")); if (pCanRunTuple != nullptr) { if (PyTuple_Check(pCanRunTuple) && PyTuple_Size(pCanRunTuple) == 2) { PyObject *pCanRun = PyTuple_GetItem(pCanRunTuple, 0); PyObject *can_run_str = PyTuple_GetItem(pCanRunTuple, 1); if (!PyBool_Check(pCanRun) || !PyUnicode_Check(can_run_str)) { derr << "Module " << get_name() << " returned wrong type in can_run" << dendl; error_string = "wrong type returned from can_run"; can_run = false; } else { can_run = (pCanRun == Py_True); if (!can_run) { error_string = PyUnicode_AsUTF8(can_run_str); dout(4) << "Module " << get_name() << " reported that it cannot run: " << error_string << dendl; } } } else { derr << "Module " << get_name() << " returned wrong type in can_run" << dendl; error_string = "wrong type returned from can_run"; can_run = false; } Py_DECREF(pCanRunTuple); } else { derr << "Exception calling can_run on " << get_name() << dendl; derr << handle_pyerror(true, get_name(), "PyModule::load") << dendl; can_run = false; } } return 0; } int PyModule::walk_dict_list( const std::string &attr_name, std::function<int(PyObject*)> fn) { PyObject *command_list = PyObject_GetAttrString(pClass, attr_name.c_str()); if (command_list == nullptr) { derr << "Module " << get_name() << " has missing " << attr_name << " member" << dendl; return -EINVAL; } if (!PyObject_TypeCheck(command_list, &PyList_Type)) { // Relatively easy mistake for human to make, e.g. defining COMMANDS // as a {} instead of a [] derr << "Module " << get_name() << " has " << attr_name << " member of wrong type (should be a list)" << dendl; return -EINVAL; } // Invoke fn on each item in the list int r = 0; const size_t list_size = PyList_Size(command_list); for (size_t i = 0; i < list_size; ++i) { PyObject *command = PyList_GetItem(command_list, i); ceph_assert(command != nullptr); if (!PyDict_Check(command)) { derr << "Module " << get_name() << " has non-dict entry " << "in " << attr_name << " list" << dendl; return -EINVAL; } r = fn(command); if (r != 0) { break; } } Py_DECREF(command_list); return r; } int PyModule::register_options(PyObject *cls) { PyObject *pRegCmd = PyObject_CallMethod( cls, const_cast<char*>("_register_options"), const_cast<char*>("(s)"), module_name.c_str()); if (pRegCmd != nullptr) { Py_DECREF(pRegCmd); } else { derr << "Exception calling _register_options on " << get_name() << dendl; derr << handle_pyerror(true, module_name, "PyModule::register_options") << dendl; } return 0; } int PyModule::load_notify_types() { PyObject *ls = PyObject_GetAttrString(pClass, "NOTIFY_TYPES"); if (ls == nullptr) { derr << "Module " << get_name() << " has missing NOTIFY_TYPES member" << dendl; return -EINVAL; } if (!PyObject_TypeCheck(ls, &PyList_Type)) { // Relatively easy mistake for human to make, e.g. defining COMMANDS // as a {} instead of a [] derr << "Module " << get_name() << " has NOTIFY_TYPES that is not a list" << dendl; return -EINVAL; } const size_t list_size = PyList_Size(ls); for (size_t i = 0; i < list_size; ++i) { PyObject *notify_type = PyList_GetItem(ls, i); ceph_assert(notify_type != nullptr); if (!PyObject_TypeCheck(notify_type, &PyUnicode_Type)) { derr << "Module " << get_name() << " has non-string entry in NOTIFY_TYPES list" << dendl; return -EINVAL; } notify_types.insert(PyUnicode_AsUTF8(notify_type)); } Py_DECREF(ls); dout(10) << "Module " << get_name() << " notify_types " << notify_types << dendl; return 0; } int PyModule::load_commands() { PyObject *pRegCmd = PyObject_CallMethod(pClass, const_cast<char*>("_register_commands"), const_cast<char*>("(s)"), module_name.c_str()); if (pRegCmd != nullptr) { Py_DECREF(pRegCmd); } else { derr << "Exception calling _register_commands on " << get_name() << dendl; derr << handle_pyerror(true, module_name, "PyModule::load_commands") << dendl; } int r = walk_dict_list("COMMANDS", [this](PyObject *pCommand) -> int { ModuleCommand command; PyObject *pCmd = PyDict_GetItemString(pCommand, "cmd"); ceph_assert(pCmd != nullptr); command.cmdstring = PyUnicode_AsUTF8(pCmd); dout(20) << "loaded command " << command.cmdstring << dendl; PyObject *pDesc = PyDict_GetItemString(pCommand, "desc"); ceph_assert(pDesc != nullptr); command.helpstring = PyUnicode_AsUTF8(pDesc); PyObject *pPerm = PyDict_GetItemString(pCommand, "perm"); ceph_assert(pPerm != nullptr); command.perm = PyUnicode_AsUTF8(pPerm); command.polling = false; if (PyObject *pPoll = PyDict_GetItemString(pCommand, "poll"); pPoll && PyObject_IsTrue(pPoll)) { command.polling = true; } command.module_name = module_name; commands.push_back(std::move(command)); return 0; }); dout(10) << "loaded " << commands.size() << " commands" << dendl; return r; } int PyModule::load_options() { int r = walk_dict_list("MODULE_OPTIONS", [this](PyObject *pOption) -> int { MgrMap::ModuleOption option; PyObject *p; p = PyDict_GetItemString(pOption, "name"); ceph_assert(p != nullptr); option.name = PyUnicode_AsUTF8(p); option.type = Option::TYPE_STR; p = PyDict_GetItemString(pOption, "type"); if (p && PyObject_TypeCheck(p, &PyUnicode_Type)) { std::string s = PyUnicode_AsUTF8(p); int t = Option::str_to_type(s); if (t >= 0) { option.type = t; } } p = PyDict_GetItemString(pOption, "desc"); if (p && PyObject_TypeCheck(p, &PyUnicode_Type)) { option.desc = PyUnicode_AsUTF8(p); } p = PyDict_GetItemString(pOption, "long_desc"); if (p && PyObject_TypeCheck(p, &PyUnicode_Type)) { option.long_desc = PyUnicode_AsUTF8(p); } p = PyDict_GetItemString(pOption, "default"); if (p) { auto q = PyObject_Str(p); option.default_value = PyUnicode_AsUTF8(q); Py_DECREF(q); } p = PyDict_GetItemString(pOption, "min"); if (p) { auto q = PyObject_Str(p); option.min = PyUnicode_AsUTF8(q); Py_DECREF(q); } p = PyDict_GetItemString(pOption, "max"); if (p) { auto q = PyObject_Str(p); option.max = PyUnicode_AsUTF8(q); Py_DECREF(q); } p = PyDict_GetItemString(pOption, "enum_allowed"); if (p && PyObject_TypeCheck(p, &PyList_Type)) { for (Py_ssize_t i = 0; i < PyList_Size(p); ++i) { auto q = PyList_GetItem(p, i); if (q) { auto r = PyObject_Str(q); option.enum_allowed.insert(PyUnicode_AsUTF8(r)); Py_DECREF(r); } } } p = PyDict_GetItemString(pOption, "see_also"); if (p && PyObject_TypeCheck(p, &PyList_Type)) { for (Py_ssize_t i = 0; i < PyList_Size(p); ++i) { auto q = PyList_GetItem(p, i); if (q && PyObject_TypeCheck(q, &PyUnicode_Type)) { option.see_also.insert(PyUnicode_AsUTF8(q)); } } } p = PyDict_GetItemString(pOption, "tags"); if (p && PyObject_TypeCheck(p, &PyList_Type)) { for (Py_ssize_t i = 0; i < PyList_Size(p); ++i) { auto q = PyList_GetItem(p, i); if (q && PyObject_TypeCheck(q, &PyUnicode_Type)) { option.tags.insert(PyUnicode_AsUTF8(q)); } } } p = PyDict_GetItemString(pOption, "runtime"); if (p && PyObject_TypeCheck(p, &PyBool_Type)) { if (p == Py_True) { option.flags |= Option::FLAG_RUNTIME; } if (p == Py_False) { option.flags &= ~Option::FLAG_RUNTIME; } } dout(20) << "loaded module option " << option.name << dendl; options[option.name] = std::move(option); return 0; }); dout(10) << "loaded " << options.size() << " options" << dendl; return r; } bool PyModule::is_option(const std::string &option_name) { std::lock_guard l(lock); return options.count(option_name) > 0; } PyObject *PyModule::get_typed_option_value(const std::string& name, const std::string& value) { // we don't need to hold a lock here because these MODULE_OPTIONS // are set up exactly once during startup. auto p = options.find(name); if (p != options.end()) { return get_python_typed_option_value((Option::type_t)p->second.type, value); } return PyUnicode_FromString(value.c_str()); } int PyModule::load_subclass_of(const char* base_class, PyObject** py_class) { // load the base class PyObject *mgr_module = PyImport_ImportModule("mgr_module"); if (!mgr_module) { error_string = peek_pyerror(); derr << "Module not found: 'mgr_module'" << dendl; derr << handle_pyerror(true, module_name, "PyModule::load_subclass_of") << dendl; return -EINVAL; } auto mgr_module_type = PyObject_GetAttrString(mgr_module, base_class); Py_DECREF(mgr_module); if (!mgr_module_type) { error_string = peek_pyerror(); derr << "Unable to import MgrModule from mgr_module" << dendl; derr << handle_pyerror(true, module_name, "PyModule::load_subclass_of") << dendl; return -EINVAL; } // find the sub class PyObject *plugin_module = PyImport_ImportModule(module_name.c_str()); if (!plugin_module) { error_string = peek_pyerror(); derr << "Module not found: '" << module_name << "'" << dendl; derr << handle_pyerror(true, module_name, "PyModule::load_subclass_of") << dendl; return -ENOENT; } auto locals = PyModule_GetDict(plugin_module); Py_DECREF(plugin_module); PyObject *key, *value; Py_ssize_t pos = 0; *py_class = nullptr; while (PyDict_Next(locals, &pos, &key, &value)) { if (!PyType_Check(value)) { continue; } if (!PyObject_IsSubclass(value, mgr_module_type)) { continue; } if (PyObject_RichCompareBool(value, mgr_module_type, Py_EQ)) { continue; } auto class_name = PyUnicode_AsUTF8(key); if (*py_class) { derr << __func__ << ": ignoring '" << module_name << "." << class_name << "'" << ": only one '" << base_class << "' class is loaded from each plugin" << dendl; continue; } *py_class = value; dout(4) << __func__ << ": found class: '" << module_name << "." << class_name << "'" << dendl; } Py_DECREF(mgr_module_type); return *py_class ? 0 : -EINVAL; } PyModule::~PyModule() { if (pMyThreadState.ts != nullptr) { Gil gil(pMyThreadState, true); Py_XDECREF(pClass); Py_XDECREF(pStandbyClass); } }
23,250
29.117876
93
cc
null
ceph-main/src/mgr/PyModule.h
// -*- 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) 2017 John Spray <[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. */ #pragma once #include <map> #include <memory> #include <string> #include <vector> #include <boost/optional.hpp> #include "common/ceph_mutex.h" #include "Python.h" #include "Gil.h" #include "mon/MgrMap.h" class MonClient; std::string handle_pyerror(bool generate_crash_dump = false, std::string module = {}, std::string caller = {}); std::string peek_pyerror(); /** * A Ceph CLI command description provided from a Python module */ class ModuleCommand { public: std::string cmdstring; std::string helpstring; std::string perm; bool polling; // Call the ActivePyModule of this name to handle the command std::string module_name; }; class PyModule { mutable ceph::mutex lock = ceph::make_mutex("PyModule::lock"); private: const std::string module_name; std::string get_site_packages(); int load_subclass_of(const char* class_name, PyObject** py_class); // Did the MgrMap identify this module as one that should run? bool enabled = false; // Did the MgrMap flag this module as always on? bool always_on = false; // Did we successfully import this python module and look up symbols? // (i.e. is it possible to instantiate a MgrModule subclass instance?) bool loaded = false; // Did the module identify itself as being able to run? // (i.e. should we expect instantiating and calling serve() to work?) bool can_run = false; // Did the module encounter an unexpected error while running? // (e.g. throwing an exception from serve()) bool failed = false; // Populated if loaded, can_run or failed indicates a problem std::string error_string; // Helper for loading MODULE_OPTIONS and COMMANDS members int walk_dict_list( const std::string &attr_name, std::function<int(PyObject*)> fn); int load_commands(); std::vector<ModuleCommand> commands; int register_options(PyObject *cls); int load_options(); std::map<std::string, MgrMap::ModuleOption> options; int load_notify_types(); std::set<std::string> notify_types; public: static std::string mgr_store_prefix; SafeThreadState pMyThreadState; PyObject *pClass = nullptr; PyObject *pStandbyClass = nullptr; explicit PyModule(const std::string &module_name_) : module_name(module_name_) { } ~PyModule(); bool is_option(const std::string &option_name); const std::map<std::string,MgrMap::ModuleOption>& get_options() const { return options; } PyObject *get_typed_option_value( const std::string& option, const std::string& value); int load(PyThreadState *pMainThreadState); static PyObject* init_ceph_logger(); static PyObject* init_ceph_module(); void set_enabled(const bool enabled_) { enabled = enabled_; } void set_always_on(const bool always_on_) { always_on = always_on_; } /** * Extend `out` with the contents of `this->commands` */ void get_commands(std::vector<ModuleCommand> *out) const { std::lock_guard l(lock); ceph_assert(out != nullptr); out->insert(out->end(), commands.begin(), commands.end()); } /** * Mark the module as failed, recording the reason in the error * string. */ void fail(const std::string &reason) { std::lock_guard l(lock); failed = true; error_string = reason; } bool is_enabled() const { std::lock_guard l(lock); return enabled || always_on; } bool is_failed() const { std::lock_guard l(lock) ; return failed; } bool is_loaded() const { std::lock_guard l(lock) ; return loaded; } bool is_always_on() const { std::lock_guard l(lock) ; return always_on; } bool should_notify(const std::string& notify_type) const { return notify_types.count(notify_type); } const std::string &get_name() const { std::lock_guard l(lock) ; return module_name; } const std::string &get_error_string() const { std::lock_guard l(lock) ; return error_string; } bool get_can_run() const { std::lock_guard l(lock) ; return can_run; } }; typedef std::shared_ptr<PyModule> PyModuleRef; class PyModuleConfig { public: mutable ceph::mutex lock = ceph::make_mutex("PyModuleConfig::lock"); std::map<std::string, std::string> config; PyModuleConfig(); PyModuleConfig(PyModuleConfig &mconfig); ~PyModuleConfig(); std::pair<int, std::string> set_config( MonClient *monc, const std::string &module_name, const std::string &key, const std::optional<std::string>& val); };
4,863
24.072165
75
h
null
ceph-main/src/mgr/PyModuleRegistry.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) 2017 John Spray <[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 "PyModuleRegistry.h" #include <filesystem> #include "include/stringify.h" #include "common/errno.h" #include "common/split.h" #include "BaseMgrModule.h" #include "PyOSDMap.h" #include "BaseMgrStandbyModule.h" #include "Gil.h" #include "MgrContext.h" #include "mgr/mgr_commands.h" #include "ActivePyModules.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr[py] " namespace fs = std::filesystem; std::set<std::string> obsolete_modules = { "orchestrator_cli", }; void PyModuleRegistry::init() { std::lock_guard locker(lock); // Set up global python interpreter #define WCHAR(s) L ## #s Py_SetProgramName(const_cast<wchar_t*>(WCHAR(MGR_PYTHON_EXECUTABLE))); #undef WCHAR // Add more modules if (g_conf().get_val<bool>("daemonize")) { PyImport_AppendInittab("ceph_logger", PyModule::init_ceph_logger); } PyImport_AppendInittab("ceph_module", PyModule::init_ceph_module); Py_InitializeEx(0); #if PY_VERSION_HEX < 0x03090000 // Let CPython know that we will be calling it back from other // threads in future. if (! PyEval_ThreadsInitialized()) { PyEval_InitThreads(); } #endif // Drop the GIL and remember the main thread state (current // thread state becomes NULL) pMainThreadState = PyEval_SaveThread(); ceph_assert(pMainThreadState != nullptr); std::list<std::string> failed_modules; const std::string module_path = g_conf().get_val<std::string>("mgr_module_path"); auto module_names = probe_modules(module_path); // Load python code for (const auto& module_name : module_names) { dout(1) << "Loading python module '" << module_name << "'" << dendl; // Everything starts disabled, set enabled flag on module // when we see first MgrMap auto mod = std::make_shared<PyModule>(module_name); int r = mod->load(pMainThreadState); if (r != 0) { // Don't use handle_pyerror() here; we don't have the GIL // or the right thread state (this is deliberate). derr << "Error loading module '" << module_name << "': " << cpp_strerror(r) << dendl; failed_modules.push_back(module_name); // Don't drop out here, load the other modules } // Record the module even if the load failed, so that we can // report its loading error modules[module_name] = std::move(mod); } if (module_names.empty()) { clog->error() << "No ceph-mgr modules found in " << module_path; } if (!failed_modules.empty()) { clog->error() << "Failed to load ceph-mgr modules: " << joinify( failed_modules.begin(), failed_modules.end(), std::string(", ")); } } bool PyModuleRegistry::handle_mgr_map(const MgrMap &mgr_map_) { std::lock_guard l(lock); if (mgr_map.epoch == 0) { mgr_map = mgr_map_; // First time we see MgrMap, set the enabled flags on modules // This should always happen before someone calls standby_start // or active_start for (const auto &[module_name, module] : modules) { const bool enabled = (mgr_map.modules.count(module_name) > 0); module->set_enabled(enabled); const bool always_on = (mgr_map.get_always_on_modules().count(module_name) > 0); module->set_always_on(always_on); } return false; } else { bool modules_changed = mgr_map_.modules != mgr_map.modules || mgr_map_.always_on_modules != mgr_map.always_on_modules; mgr_map = mgr_map_; if (standby_modules != nullptr) { standby_modules->handle_mgr_map(mgr_map_); } return modules_changed; } } void PyModuleRegistry::standby_start(MonClient &mc, Finisher &f) { std::lock_guard l(lock); ceph_assert(active_modules == nullptr); ceph_assert(standby_modules == nullptr); // Must have seen a MgrMap by this point, in order to know // which modules should be enabled ceph_assert(mgr_map.epoch > 0); dout(4) << "Starting modules in standby mode" << dendl; standby_modules.reset(new StandbyPyModules( mgr_map, module_config, clog, mc, f)); std::set<std::string> failed_modules; for (const auto &i : modules) { if (!(i.second->is_enabled() && i.second->get_can_run())) { // report always_on modules with a standby mode that won't run if (i.second->is_always_on() && i.second->pStandbyClass) { failed_modules.insert(i.second->get_name()); } continue; } if (i.second->pStandbyClass) { dout(4) << "starting module " << i.second->get_name() << dendl; standby_modules->start_one(i.second); } else { dout(4) << "skipping module '" << i.second->get_name() << "' because " "it does not implement a standby mode" << dendl; } } if (!failed_modules.empty()) { clog->error() << "Failed to execute ceph-mgr module(s) in standby mode: " << joinify(failed_modules.begin(), failed_modules.end(), std::string(", ")); } } void PyModuleRegistry::active_start( DaemonStateIndex &ds, ClusterState &cs, const std::map<std::string, std::string> &kv_store, bool mon_provides_kv_sub, MonClient &mc, LogChannelRef clog_, LogChannelRef audit_clog_, Objecter &objecter_, Client &client_, Finisher &f, DaemonServer &server) { std::lock_guard locker(lock); dout(4) << "Starting modules in active mode" << dendl; ceph_assert(active_modules == nullptr); // Must have seen a MgrMap by this point, in order to know // which modules should be enabled ceph_assert(mgr_map.epoch > 0); if (standby_modules != nullptr) { standby_modules->shutdown(); standby_modules.reset(); } active_modules.reset( new ActivePyModules( module_config, kv_store, mon_provides_kv_sub, ds, cs, mc, clog_, audit_clog_, objecter_, client_, f, server, *this)); for (const auto &i : modules) { // Anything we're skipping because of !can_run will be flagged // to the user separately via get_health_checks if (!(i.second->is_enabled() && i.second->is_loaded())) { continue; } dout(4) << "Starting " << i.first << dendl; active_modules->start_one(i.second); } } void PyModuleRegistry::active_shutdown() { std::lock_guard locker(lock); if (active_modules != nullptr) { active_modules->shutdown(); active_modules.reset(); } } void PyModuleRegistry::shutdown() { std::lock_guard locker(lock); if (standby_modules != nullptr) { standby_modules->shutdown(); standby_modules.reset(); } // Ideally, now, we'd be able to do this for all modules: // // Py_EndInterpreter(pMyThreadState); // PyThreadState_Swap(pMainThreadState); // // Unfortunately, if the module has any other *python* threads active // at this point, Py_EndInterpreter() will abort with: // // Fatal Python error: Py_EndInterpreter: not the last thread // // This can happen when using CherryPy in a module, becuase CherryPy // runs an extra thread as a timeout monitor, which spends most of its // life inside a time.sleep(60). Unless you are very, very lucky with // the timing calling this destructor, that thread will still be stuck // in a sleep, and Py_EndInterpreter() will abort. // // This could of course also happen with a poorly written module which // made no attempt to clean up any additional threads it created. // // The safest thing to do is just not call Py_EndInterpreter(), and // let Py_Finalize() kill everything after all modules are shut down. modules.clear(); PyEval_RestoreThread(pMainThreadState); Py_Finalize(); } std::vector<std::string> PyModuleRegistry::probe_modules(const std::string &path) const { const auto opt = g_conf().get_val<std::string>("mgr_disabled_modules"); const auto disabled_modules = ceph::split(opt); std::vector<std::string> modules; for (const auto& entry: fs::directory_iterator(path)) { if (!fs::is_directory(entry)) { continue; } const std::string name = entry.path().filename(); if (std::count(disabled_modules.begin(), disabled_modules.end(), name)) { dout(10) << "ignoring disabled module " << name << dendl; continue; } auto module_path = entry.path() / "module.py"; if (fs::exists(module_path)) { modules.push_back(name); } } return modules; } int PyModuleRegistry::handle_command( const ModuleCommand& module_command, const MgrSession& session, const cmdmap_t &cmdmap, const bufferlist &inbuf, std::stringstream *ds, std::stringstream *ss) { if (active_modules) { return active_modules->handle_command(module_command, session, cmdmap, inbuf, ds, ss); } else { // We do not expect to be called before active modules is up, but // it's straightfoward to handle this case so let's do it. return -EAGAIN; } } std::vector<ModuleCommand> PyModuleRegistry::get_py_commands() const { std::lock_guard l(lock); std::vector<ModuleCommand> result; for (const auto& i : modules) { i.second->get_commands(&result); } return result; } std::vector<MonCommand> PyModuleRegistry::get_commands() const { std::vector<ModuleCommand> commands = get_py_commands(); std::vector<MonCommand> result; for (auto &pyc: commands) { uint64_t flags = MonCommand::FLAG_MGR; if (pyc.polling) { flags |= MonCommand::FLAG_POLL; } result.push_back({pyc.cmdstring, pyc.helpstring, "mgr", pyc.perm, flags}); } return result; } void PyModuleRegistry::get_health_checks(health_check_map_t *checks) { std::lock_guard l(lock); // Only the active mgr reports module issues if (active_modules) { active_modules->get_health_checks(checks); std::map<std::string, std::string> dependency_modules; std::map<std::string, std::string> failed_modules; /* * Break up broken modules into two categories: * - can_run=false: the module is working fine but explicitly * telling you that a dependency is missing. Advise the user to * read the message from the module and install what's missing. * - failed=true or loaded=false: something unexpected is broken, * either at runtime (from serve()) or at load time. This indicates * a bug and the user should be guided to inspect the mgr log * to investigate and gather evidence. */ for (const auto &i : modules) { auto module = i.second; if (module->is_enabled() && !module->get_can_run()) { dependency_modules[module->get_name()] = module->get_error_string(); } else if ((module->is_enabled() && !module->is_loaded()) || (module->is_failed() && module->get_can_run())) { // - Unloadable modules are only reported if they're enabled, // to avoid spamming users about modules they don't have the // dependencies installed for because they don't use it. // - Failed modules are only reported if they passed the can_run // checks (to avoid outputting two health messages about a // module that said can_run=false but we tried running it anyway) failed_modules[module->get_name()] = module->get_error_string(); } } // report failed always_on modules as health errors for (const auto& name : mgr_map.get_always_on_modules()) { if (obsolete_modules.count(name)) { continue; } if (active_modules->is_pending(name)) { continue; } if (!active_modules->module_exists(name)) { if (failed_modules.find(name) == failed_modules.end() && dependency_modules.find(name) == dependency_modules.end()) { failed_modules[name] = "Not found or unloadable"; } } } if (!dependency_modules.empty()) { std::ostringstream ss; if (dependency_modules.size() == 1) { auto iter = dependency_modules.begin(); ss << "Module '" << iter->first << "' has failed dependency: " << iter->second; } else if (dependency_modules.size() > 1) { ss << dependency_modules.size() << " mgr modules have failed dependencies"; } auto& d = checks->add("MGR_MODULE_DEPENDENCY", HEALTH_WARN, ss.str(), dependency_modules.size()); for (auto& i : dependency_modules) { std::ostringstream ss; ss << "Module '" << i.first << "' has failed dependency: " << i.second; d.detail.push_back(ss.str()); } } if (!failed_modules.empty()) { std::ostringstream ss; if (failed_modules.size() == 1) { auto iter = failed_modules.begin(); ss << "Module '" << iter->first << "' has failed: " << iter->second; } else if (failed_modules.size() > 1) { ss << failed_modules.size() << " mgr modules have failed"; } auto& d = checks->add("MGR_MODULE_ERROR", HEALTH_ERR, ss.str(), failed_modules.size()); for (auto& i : failed_modules) { std::ostringstream ss; ss << "Module '" << i.first << "' has failed: " << i.second; d.detail.push_back(ss.str()); } } } } void PyModuleRegistry::handle_config(const std::string &k, const std::string &v) { std::lock_guard l(module_config.lock); if (!v.empty()) { // removing value to hide sensitive data going into mgr logs // leaving this for debugging purposes // dout(10) << "Loaded module_config entry " << k << ":" << v << dendl; dout(10) << "Loaded module_config entry " << k << ":" << dendl; module_config.config[k] = v; } else { module_config.config.erase(k); } } void PyModuleRegistry::handle_config_notify() { std::lock_guard l(lock); if (active_modules) { active_modules->config_notify(); } }
14,191
30.608018
87
cc
null
ceph-main/src/mgr/PyModuleRegistry.h
// -*- 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) 2017 John Spray <[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. */ #pragma once // First because it includes Python.h #include "PyModule.h" #include <string> #include <map> #include <set> #include <memory> #include "common/LogClient.h" #include "ActivePyModules.h" #include "StandbyPyModules.h" class MgrSession; /** * This class is responsible for setting up the python runtime environment * and importing the python modules. * * It is *not* responsible for constructing instances of their BaseMgrModule * subclasses: that is the job of ActiveMgrModule, which consumes the class * references that we load here. */ class PyModuleRegistry { private: mutable ceph::mutex lock = ceph::make_mutex("PyModuleRegistry::lock"); LogChannelRef clog; std::map<std::string, PyModuleRef> modules; std::multimap<std::string, entity_addrvec_t> clients; std::unique_ptr<ActivePyModules> active_modules; std::unique_ptr<StandbyPyModules> standby_modules; PyThreadState *pMainThreadState; // We have our own copy of MgrMap, because we are constructed // before ClusterState exists. MgrMap mgr_map; /** * Discover python modules from local disk */ std::vector<std::string> probe_modules(const std::string &path) const; PyModuleConfig module_config; public: void handle_config(const std::string &k, const std::string &v); void handle_config_notify(); void update_kv_data( const std::string prefix, bool incremental, const map<std::string, std::optional<bufferlist>, std::less<>>& data) { ceph_assert(active_modules); active_modules->update_kv_data(prefix, incremental, data); } /** * Get references to all modules (whether they have loaded and/or * errored) or not. */ auto get_modules() const { std::vector<PyModuleRef> modules_out; std::lock_guard l(lock); for (const auto &i : modules) { modules_out.push_back(i.second); } return modules_out; } explicit PyModuleRegistry(LogChannelRef clog_) : clog(clog_) {} /** * @return true if the mgrmap has changed such that the service needs restart */ bool handle_mgr_map(const MgrMap &mgr_map_); bool have_standby_modules() const { return !!standby_modules; } void init(); void upgrade_config( MonClient *monc, const std::map<std::string, std::string> &old_config); void active_start( DaemonStateIndex &ds, ClusterState &cs, const std::map<std::string, std::string> &kv_store, bool mon_provides_kv_sub, MonClient &mc, LogChannelRef clog_, LogChannelRef audit_clog_, Objecter &objecter_, Client &client_, Finisher &f, DaemonServer &server); void standby_start(MonClient &mc, Finisher &f); bool is_standby_running() const { return standby_modules != nullptr; } void active_shutdown(); void shutdown(); std::vector<MonCommand> get_commands() const; std::vector<ModuleCommand> get_py_commands() const; /** * Get the specified module. The module does not have to be * loaded or runnable. * * Returns an empty reference if it does not exist. */ PyModuleRef get_module(const std::string &module_name) { std::lock_guard l(lock); auto module_iter = modules.find(module_name); if (module_iter == modules.end()) { return {}; } return module_iter->second; } /** * Pass through command to the named module for execution. * * The command must exist in the COMMANDS reported by the module. If it * doesn't then this will abort. * * If ActivePyModules has not been instantiated yet then this will * return EAGAIN. */ int handle_command( const ModuleCommand& module_command, const MgrSession& session, const cmdmap_t &cmdmap, const bufferlist &inbuf, std::stringstream *ds, std::stringstream *ss); /** * Pass through health checks reported by modules, and report any * modules that have failed (i.e. unhandled exceptions in serve()) */ void get_health_checks(health_check_map_t *checks); void get_progress_events(map<std::string,ProgressEvent> *events) { if (active_modules) { active_modules->get_progress_events(events); } } // FIXME: breaking interface so that I don't have to go rewrite all // the places that call into these (for now) // >>> void notify_all(const std::string &notify_type, const std::string &notify_id) { if (active_modules) { active_modules->notify_all(notify_type, notify_id); } } void notify_all(const LogEntry &log_entry) { if (active_modules) { active_modules->notify_all(log_entry); } } bool should_notify(const std::string& name, const std::string& notify_type) { return modules.at(name)->should_notify(notify_type); } std::map<std::string, std::string> get_services() const { ceph_assert(active_modules); return active_modules->get_services(); } void register_client(std::string_view name, entity_addrvec_t addrs, bool replace) { std::lock_guard l(lock); auto n = std::string(name); if (replace) { clients.erase(n); } clients.emplace(n, std::move(addrs)); } void unregister_client(std::string_view name, const entity_addrvec_t& addrs) { std::lock_guard l(lock); auto itp = clients.equal_range(std::string(name)); for (auto it = itp.first; it != itp.second; ++it) { if (it->second == addrs) { clients.erase(it); return; } } } auto get_clients() const { std::lock_guard l(lock); return clients; } bool is_module_active(const std::string &name) { ceph_assert(active_modules); return active_modules->module_exists(name); } auto& get_active_module_finisher(const std::string &name) { ceph_assert(active_modules); return active_modules->get_module_finisher(name); } // <<< (end of ActivePyModules cheeky call-throughs) };
6,354
25.045082
83
h
null
ceph-main/src/mgr/PyModuleRunner.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 John Spray <[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. */ // Python.h comes first because otherwise it clobbers ceph's assert #include <Python.h> #include "PyModule.h" #include "common/debug.h" #include "mgr/Gil.h" #include "PyModuleRunner.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr PyModuleRunner::~PyModuleRunner() { Gil gil(py_module->pMyThreadState, true); if (pClassInstance) { Py_XDECREF(pClassInstance); pClassInstance = nullptr; } } int PyModuleRunner::serve() { ceph_assert(pClassInstance != nullptr); // This method is called from a separate OS thread (i.e. a thread not // created by Python), so tell Gil to wrap this in a new thread state. Gil gil(py_module->pMyThreadState, true); auto pValue = PyObject_CallMethod(pClassInstance, const_cast<char*>("serve"), nullptr); int r = 0; if (pValue != NULL) { Py_DECREF(pValue); } else { // This is not a very informative log message because it's an // unknown/unexpected exception that we can't say much about. // Get short exception message for the cluster log, before // dumping the full backtrace to the local log. std::string exc_msg = peek_pyerror(); clog->error() << "Unhandled exception from module '" << get_name() << "' while running on mgr." << g_conf()->name.get_id() << ": " << exc_msg; derr << get_name() << ".serve:" << dendl; derr << handle_pyerror(true, get_name(), "PyModuleRunner::serve") << dendl; py_module->fail(exc_msg); return -EINVAL; } return r; } void PyModuleRunner::shutdown() { ceph_assert(pClassInstance != nullptr); Gil gil(py_module->pMyThreadState, true); auto pValue = PyObject_CallMethod(pClassInstance, const_cast<char*>("shutdown"), nullptr); if (pValue != NULL) { Py_DECREF(pValue); } else { derr << "Failed to invoke shutdown() on " << get_name() << dendl; derr << handle_pyerror(true, get_name(), "PyModuleRunner::shutdown") << dendl; } dead = true; } void PyModuleRunner::log(const std::string &record) { #undef dout_prefix #define dout_prefix *_dout dout(0) << record << dendl; #undef dout_prefix #define dout_prefix *_dout << "mgr " << __func__ << " " } void* PyModuleRunner::PyModuleRunnerThread::entry() { // No need to acquire the GIL here; the module does it. dout(4) << "Entering thread for " << mod->get_name() << dendl; mod->serve(); return nullptr; }
2,846
24.648649
82
cc
null
ceph-main/src/mgr/PyModuleRunner.h
// -*- 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 John Spray <[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. */ #pragma once #include "common/Thread.h" #include "common/LogClient.h" #include "mgr/Gil.h" #include "PyModule.h" /** * Implement the pattern of calling serve() on a module in a thread, * until shutdown() is called. */ class PyModuleRunner { public: // Info about the module we're going to run PyModuleRef py_module; protected: // Populated by descendent class PyObject *pClassInstance = nullptr; LogChannelRef clog; class PyModuleRunnerThread : public Thread { PyModuleRunner *mod; public: explicit PyModuleRunnerThread(PyModuleRunner *mod_) : mod(mod_) {} void *entry() override; }; bool is_dead() const { return dead; } std::string thread_name; public: int serve(); void shutdown(); void log(const std::string &record); const char *get_thread_name() const { return thread_name.c_str(); } PyModuleRunner( const PyModuleRef &py_module_, LogChannelRef clog_) : py_module(py_module_), clog(clog_), thread(this) { // Shortened name for use as thread name, because thread names // required to be <16 chars thread_name = py_module->get_name().substr(0, 15); ceph_assert(py_module != nullptr); } ~PyModuleRunner(); PyModuleRunnerThread thread; std::string const &get_name() const { return py_module->get_name(); } private: bool dead = false; };
1,807
19.088889
71
h
null
ceph-main/src/mgr/PyOSDMap.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "Mgr.h" #include "osd/OSDMap.h" #include "common/errno.h" #include "common/version.h" #include "include/stringify.h" #include "PyOSDMap.h" #include "PyFormatter.h" #include "Gil.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr using std::map; using std::set; using std::string; using std::vector; typedef struct { PyObject_HEAD OSDMap *osdmap; } BasePyOSDMap; typedef struct { PyObject_HEAD OSDMap::Incremental *inc; } BasePyOSDMapIncremental; typedef struct { PyObject_HEAD std::shared_ptr<CrushWrapper> crush; } BasePyCRUSH; // ---------- static PyObject *osdmap_get_epoch(BasePyOSDMap *self, PyObject *obj) { return PyLong_FromLong(self->osdmap->get_epoch()); } static PyObject *osdmap_get_crush_version(BasePyOSDMap* self, PyObject *obj) { return PyLong_FromLong(self->osdmap->get_crush_version()); } static PyObject *osdmap_dump(BasePyOSDMap* self, PyObject *obj) { PyFormatter f; self->osdmap->dump(&f, g_ceph_context); return f.get(); } static PyObject *osdmap_new_incremental(BasePyOSDMap *self, PyObject *obj) { OSDMap::Incremental *inc = new OSDMap::Incremental; inc->fsid = self->osdmap->get_fsid(); inc->epoch = self->osdmap->get_epoch() + 1; // always include latest crush map here... this is okay since we never // actually use this map in the real world (and even if we did it would // be a no-op). self->osdmap->crush->encode(inc->crush, CEPH_FEATURES_ALL); dout(10) << __func__ << " " << inc << dendl; return construct_with_capsule("mgr_module", "OSDMapIncremental", (void*)(inc)); } static PyObject *osdmap_apply_incremental(BasePyOSDMap *self, BasePyOSDMapIncremental *incobj) { if (!PyObject_TypeCheck(incobj, &BasePyOSDMapIncrementalType)) { derr << "Wrong type in osdmap_apply_incremental!" << dendl; return nullptr; } bufferlist bl; self->osdmap->encode(bl, CEPH_FEATURES_ALL|CEPH_FEATURE_RESERVED); OSDMap *next = new OSDMap; next->decode(bl); next->apply_incremental(*(incobj->inc)); dout(10) << __func__ << " map " << self->osdmap << " inc " << incobj->inc << " next " << next << dendl; return construct_with_capsule("mgr_module", "OSDMap", (void*)next); } static PyObject *osdmap_get_crush(BasePyOSDMap* self, PyObject *obj) { return construct_with_capsule("mgr_module", "CRUSHMap", (void*)(&(self->osdmap->crush))); } static PyObject *osdmap_get_pools_by_take(BasePyOSDMap* self, PyObject *args) { int take; if (!PyArg_ParseTuple(args, "i:get_pools_by_take", &take)) { return nullptr; } PyFormatter f; f.open_array_section("pools"); for (auto& p : self->osdmap->get_pools()) { if (self->osdmap->crush->rule_has_take(p.second.crush_rule, take)) { f.dump_int("pool", p.first); } } f.close_section(); return f.get(); } static PyObject *osdmap_calc_pg_upmaps(BasePyOSDMap* self, PyObject *args) { PyObject *pool_list; BasePyOSDMapIncremental *incobj; int max_deviation = 0; int max_iterations = 0; if (!PyArg_ParseTuple(args, "OiiO:calc_pg_upmaps", &incobj, &max_deviation, &max_iterations, &pool_list)) { return nullptr; } if (!PyList_CheckExact(pool_list)) { derr << __func__ << " pool_list not a list" << dendl; return nullptr; } set<int64_t> pools; for (auto i = 0; i < PyList_Size(pool_list); ++i) { PyObject *pool_name = PyList_GET_ITEM(pool_list, i); if (!PyUnicode_Check(pool_name)) { derr << __func__ << " " << pool_name << " not a string" << dendl; return nullptr; } auto pool_id = self->osdmap->lookup_pg_pool_name( PyUnicode_AsUTF8(pool_name)); if (pool_id < 0) { derr << __func__ << " pool '" << PyUnicode_AsUTF8(pool_name) << "' does not exist" << dendl; return nullptr; } pools.insert(pool_id); } dout(10) << __func__ << " osdmap " << self->osdmap << " inc " << incobj->inc << " max_deviation " << max_deviation << " max_iterations " << max_iterations << " pools " << pools << dendl; PyThreadState *tstate = PyEval_SaveThread(); int r = self->osdmap->calc_pg_upmaps(g_ceph_context, max_deviation, max_iterations, pools, incobj->inc); PyEval_RestoreThread(tstate); dout(10) << __func__ << " r = " << r << dendl; return PyLong_FromLong(r); } static PyObject *osdmap_map_pool_pgs_up(BasePyOSDMap* self, PyObject *args) { int poolid; if (!PyArg_ParseTuple(args, "i:map_pool_pgs_up", &poolid)) { return nullptr; } auto pi = self->osdmap->get_pg_pool(poolid); if (!pi) return nullptr; map<pg_t,vector<int>> pm; for (unsigned ps = 0; ps < pi->get_pg_num(); ++ps) { pg_t pgid(ps, poolid); self->osdmap->pg_to_up_acting_osds(pgid, &pm[pgid], nullptr, nullptr, nullptr); } PyFormatter f; for (auto p : pm) { string pg = stringify(p.first); f.open_array_section(pg.c_str()); for (auto o : p.second) { f.dump_int("osd", o); } f.close_section(); } return f.get(); } static int BasePyOSDMap_init(BasePyOSDMap *self, PyObject *args, PyObject *kwds) { PyObject *osdmap_capsule = nullptr; static const char *kwlist[] = {"osdmap_capsule", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", const_cast<char**>(kwlist), &osdmap_capsule)) { return -1; } if (!PyObject_TypeCheck(osdmap_capsule, &PyCapsule_Type)) { PyErr_Format(PyExc_TypeError, "Expected a PyCapsule_Type, not %s", Py_TYPE(osdmap_capsule)->tp_name); return -1; } self->osdmap = (OSDMap*)PyCapsule_GetPointer( osdmap_capsule, nullptr); ceph_assert(self->osdmap); return 0; } static void BasePyOSDMap_dealloc(BasePyOSDMap *self) { if (self->osdmap) { delete self->osdmap; self->osdmap = nullptr; } else { derr << "Destroying improperly initialized BasePyOSDMap " << self << dendl; } Py_TYPE(self)->tp_free(self); } static PyObject *osdmap_pg_to_up_acting_osds(BasePyOSDMap *self, PyObject *args) { int pool_id = 0; int ps = 0; if (!PyArg_ParseTuple(args, "ii:pg_to_up_acting_osds", &pool_id, &ps)) { return nullptr; } std::vector<int> up; int up_primary; std::vector<int> acting; int acting_primary; pg_t pg_id(ps, pool_id); self->osdmap->pg_to_up_acting_osds(pg_id, &up, &up_primary, &acting, &acting_primary); // (Ab)use PyFormatter as a convenient way to generate a dict PyFormatter f; f.dump_int("up_primary", up_primary); f.dump_int("acting_primary", acting_primary); f.open_array_section("up"); for (const auto &i : up) { f.dump_int("osd", i); } f.close_section(); f.open_array_section("acting"); for (const auto &i : acting) { f.dump_int("osd", i); } f.close_section(); return f.get(); } static PyObject *osdmap_pool_raw_used_rate(BasePyOSDMap *self, PyObject *args) { int pool_id = 0; if (!PyArg_ParseTuple(args, "i:pool_raw_used_rate", &pool_id)) { return nullptr; } if (!self->osdmap->have_pg_pool(pool_id)) { return nullptr; } float rate = self->osdmap->pool_raw_used_rate(pool_id); return PyFloat_FromDouble(rate); } static PyObject *osdmap_build_simple(PyObject *cls, PyObject *args, PyObject *kwargs) { static const char *kwlist[] = {"epoch", "uuid", "num_osd", nullptr}; int epoch = 1; char* uuid_str = nullptr; int num_osd = -1; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "izi", const_cast<char**>(kwlist), &epoch, &uuid_str, &num_osd)) { Py_RETURN_NONE; } uuid_d uuid; if (uuid_str) { if (!uuid.parse(uuid_str)) { PyErr_Format(PyExc_ValueError, "bad uuid %s", uuid_str); Py_RETURN_NONE; } } else { uuid.generate_random(); } auto osdmap = without_gil([&] { OSDMap* osdmap = new OSDMap(); // negative osd is allowed, in that case i just count all osds in ceph.conf osdmap->build_simple(g_ceph_context, epoch, uuid, num_osd); return osdmap; }); return construct_with_capsule("mgr_module", "OSDMap", reinterpret_cast<void*>(osdmap)); } PyMethodDef BasePyOSDMap_methods[] = { {"_get_epoch", (PyCFunction)osdmap_get_epoch, METH_NOARGS, "Get OSDMap epoch"}, {"_get_crush_version", (PyCFunction)osdmap_get_crush_version, METH_NOARGS, "Get CRUSH version"}, {"_dump", (PyCFunction)osdmap_dump, METH_NOARGS, "Dump OSDMap::Incremental"}, {"_new_incremental", (PyCFunction)osdmap_new_incremental, METH_NOARGS, "Create OSDMap::Incremental"}, {"_apply_incremental", (PyCFunction)osdmap_apply_incremental, METH_O, "Apply OSDMap::Incremental and return the resulting OSDMap"}, {"_get_crush", (PyCFunction)osdmap_get_crush, METH_NOARGS, "Get CrushWrapper"}, {"_get_pools_by_take", (PyCFunction)osdmap_get_pools_by_take, METH_VARARGS, "Get pools that have CRUSH rules that TAKE the given root"}, {"_calc_pg_upmaps", (PyCFunction)osdmap_calc_pg_upmaps, METH_VARARGS, "Calculate new pg-upmap values"}, {"_map_pool_pgs_up", (PyCFunction)osdmap_map_pool_pgs_up, METH_VARARGS, "Calculate up set mappings for all PGs in a pool"}, {"_pg_to_up_acting_osds", (PyCFunction)osdmap_pg_to_up_acting_osds, METH_VARARGS, "Calculate up+acting OSDs for a PG ID"}, {"_pool_raw_used_rate", (PyCFunction)osdmap_pool_raw_used_rate, METH_VARARGS, "Get raw space to logical space ratio"}, {"_build_simple", (PyCFunction)osdmap_build_simple, METH_VARARGS | METH_CLASS, "Create a simple OSDMap"}, {NULL, NULL, 0, NULL} }; PyTypeObject BasePyOSDMapType = { PyVarObject_HEAD_INIT(NULL, 0) "ceph_module.BasePyOSDMap", /* tp_name */ sizeof(BasePyOSDMap), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)BasePyOSDMap_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Ceph OSDMap", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ BasePyOSDMap_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)BasePyOSDMap_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; // ---------- static int BasePyOSDMapIncremental_init(BasePyOSDMapIncremental *self, PyObject *args, PyObject *kwds) { PyObject *inc_capsule = nullptr; static const char *kwlist[] = {"inc_capsule", NULL}; if (! PyArg_ParseTupleAndKeywords(args, kwds, "O", const_cast<char**>(kwlist), &inc_capsule)) { ceph_abort(); return -1; } ceph_assert(PyObject_TypeCheck(inc_capsule, &PyCapsule_Type)); self->inc = (OSDMap::Incremental*)PyCapsule_GetPointer( inc_capsule, nullptr); ceph_assert(self->inc); return 0; } static void BasePyOSDMapIncremental_dealloc(BasePyOSDMapIncremental *self) { if (self->inc) { delete self->inc; self->inc = nullptr; } else { derr << "Destroying improperly initialized BasePyOSDMap " << self << dendl; } Py_TYPE(self)->tp_free(self); } static PyObject *osdmap_inc_get_epoch(BasePyOSDMapIncremental *self, PyObject *obj) { return PyLong_FromLong(self->inc->epoch); } static PyObject *osdmap_inc_dump(BasePyOSDMapIncremental *self, PyObject *obj) { PyFormatter f; self->inc->dump(&f); return f.get(); } static int get_int_float_map(PyObject *obj, map<int,double> *out) { PyObject *ls = PyDict_Items(obj); for (int j = 0; j < PyList_Size(ls); ++j) { PyObject *pair = PyList_GET_ITEM(ls, j); if (!PyTuple_Check(pair)) { derr << __func__ << " item " << j << " not a tuple" << dendl; Py_DECREF(ls); return -1; } int k; double v; if (!PyArg_ParseTuple(pair, "id:pair", &k, &v)) { derr << __func__ << " item " << j << " not a size 2 tuple" << dendl; Py_DECREF(ls); return -1; } (*out)[k] = v; } Py_DECREF(ls); return 0; } static PyObject *osdmap_inc_set_osd_reweights(BasePyOSDMapIncremental *self, PyObject *weightobj) { map<int,double> wm; if (get_int_float_map(weightobj, &wm) < 0) { return nullptr; } for (auto i : wm) { self->inc->new_weight[i.first] = std::max(0.0, std::min(1.0, i.second)) * 0x10000; } Py_RETURN_NONE; } static PyObject *osdmap_inc_set_compat_weight_set_weights( BasePyOSDMapIncremental *self, PyObject *weightobj) { map<int,double> wm; if (get_int_float_map(weightobj, &wm) < 0) { return nullptr; } CrushWrapper crush; ceph_assert(self->inc->crush.length()); // see new_incremental auto p = self->inc->crush.cbegin(); decode(crush, p); crush.create_choose_args(CrushWrapper::DEFAULT_CHOOSE_ARGS, 1); for (auto i : wm) { crush.choose_args_adjust_item_weightf( g_ceph_context, crush.choose_args_get(CrushWrapper::DEFAULT_CHOOSE_ARGS), i.first, { i.second }, nullptr); } self->inc->crush.clear(); crush.encode(self->inc->crush, CEPH_FEATURES_ALL); Py_RETURN_NONE; } PyMethodDef BasePyOSDMapIncremental_methods[] = { {"_get_epoch", (PyCFunction)osdmap_inc_get_epoch, METH_NOARGS, "Get OSDMap::Incremental epoch"}, {"_dump", (PyCFunction)osdmap_inc_dump, METH_NOARGS, "Dump OSDMap::Incremental"}, {"_set_osd_reweights", (PyCFunction)osdmap_inc_set_osd_reweights, METH_O, "Set osd reweight values"}, {"_set_crush_compat_weight_set_weights", (PyCFunction)osdmap_inc_set_compat_weight_set_weights, METH_O, "Set weight values in the pending CRUSH compat weight-set"}, {NULL, NULL, 0, NULL} }; PyTypeObject BasePyOSDMapIncrementalType = { PyVarObject_HEAD_INIT(NULL, 0) "ceph_module.BasePyOSDMapIncremental", /* tp_name */ sizeof(BasePyOSDMapIncremental), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)BasePyOSDMapIncremental_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Ceph OSDMapIncremental", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ BasePyOSDMapIncremental_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)BasePyOSDMapIncremental_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; // ---------- static int BasePyCRUSH_init(BasePyCRUSH *self, PyObject *args, PyObject *kwds) { PyObject *crush_capsule = nullptr; static const char *kwlist[] = {"crush_capsule", NULL}; if (! PyArg_ParseTupleAndKeywords(args, kwds, "O", const_cast<char**>(kwlist), &crush_capsule)) { ceph_abort(); return -1; } ceph_assert(PyObject_TypeCheck(crush_capsule, &PyCapsule_Type)); auto ptr_ref = (std::shared_ptr<CrushWrapper>*)( PyCapsule_GetPointer(crush_capsule, nullptr)); // We passed a pointer to a shared pointer, which is weird, but // just enough to get it into the constructor: this is a real shared // pointer construction now, and then we throw away that pointer to // the shared pointer. self->crush = *ptr_ref; ceph_assert(self->crush); return 0; } static void BasePyCRUSH_dealloc(BasePyCRUSH *self) { self->crush.reset(); Py_TYPE(self)->tp_free(self); } static PyObject *crush_dump(BasePyCRUSH *self, PyObject *obj) { PyFormatter f; self->crush->dump(&f); return f.get(); } static PyObject *crush_get_item_name(BasePyCRUSH *self, PyObject *args) { int item; if (!PyArg_ParseTuple(args, "i:get_item_name", &item)) { return nullptr; } if (!self->crush->item_exists(item)) { Py_RETURN_NONE; } return PyUnicode_FromString(self->crush->get_item_name(item)); } static PyObject *crush_get_item_weight(BasePyCRUSH *self, PyObject *args) { int item; if (!PyArg_ParseTuple(args, "i:get_item_weight", &item)) { return nullptr; } if (!self->crush->item_exists(item)) { Py_RETURN_NONE; } return PyFloat_FromDouble(self->crush->get_item_weightf(item)); } static PyObject *crush_find_roots(BasePyCRUSH *self) { set<int> roots; self->crush->find_roots(&roots); PyFormatter f; f.open_array_section("roots"); for (auto root : roots) { f.dump_int("root", root); } f.close_section(); return f.get(); } static PyObject *crush_find_takes(BasePyCRUSH *self, PyObject *obj) { set<int> takes; self->crush->find_takes(&takes); PyFormatter f; f.open_array_section("takes"); for (auto root : takes) { f.dump_int("root", root); } f.close_section(); return f.get(); } static PyObject *crush_get_take_weight_osd_map(BasePyCRUSH *self, PyObject *args) { int root; if (!PyArg_ParseTuple(args, "i:get_take_weight_osd_map", &root)) { return nullptr; } map<int,float> wmap; if (!self->crush->item_exists(root)) { return nullptr; } self->crush->get_take_weight_osd_map(root, &wmap); PyFormatter f; f.open_object_section("weights"); for (auto& p : wmap) { string n = stringify(p.first); // ick f.dump_float(n.c_str(), p.second); } f.close_section(); return f.get(); } PyMethodDef BasePyCRUSH_methods[] = { {"_dump", (PyCFunction)crush_dump, METH_NOARGS, "Dump map"}, {"_get_item_name", (PyCFunction)crush_get_item_name, METH_VARARGS, "Get item name"}, {"_get_item_weight", (PyCFunction)crush_get_item_weight, METH_VARARGS, "Get item weight"}, {"_find_roots", (PyCFunction)crush_find_roots, METH_NOARGS, "Find all tree roots"}, {"_find_takes", (PyCFunction)crush_find_takes, METH_NOARGS, "Find distinct TAKE roots"}, {"_get_take_weight_osd_map", (PyCFunction)crush_get_take_weight_osd_map, METH_VARARGS, "Get OSD weight map for a given TAKE root node"}, {NULL, NULL, 0, NULL} }; PyTypeObject BasePyCRUSHType = { PyVarObject_HEAD_INIT(NULL, 0) "ceph_module.BasePyCRUSH", /* tp_name */ sizeof(BasePyCRUSH), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)BasePyCRUSH_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Ceph OSDMapIncremental", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ BasePyCRUSH_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)BasePyCRUSH_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ };
21,990
29.458449
89
cc
null
ceph-main/src/mgr/PyOSDMap.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <Python.h> #include <string> extern PyTypeObject BasePyOSDMapType; extern PyTypeObject BasePyOSDMapIncrementalType; extern PyTypeObject BasePyCRUSHType; PyObject *construct_with_capsule( const std::string &module, const std::string &clsname, void *wrapped);
396
19.894737
70
h
null
ceph-main/src/mgr/PyUtil.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <Python.h> #include "PyUtil.h" PyObject *get_python_typed_option_value( Option::type_t type, const std::string& value) { switch (type) { case Option::TYPE_INT: case Option::TYPE_UINT: case Option::TYPE_SIZE: return PyLong_FromString((char *)value.c_str(), nullptr, 0); case Option::TYPE_SECS: case Option::TYPE_MILLISECS: case Option::TYPE_FLOAT: { PyObject *s = PyUnicode_FromString(value.c_str()); PyObject *f = PyFloat_FromString(s); Py_DECREF(s); return f; } case Option::TYPE_BOOL: if (value == "1" || value == "true" || value == "True" || value == "on" || value == "yes") { Py_INCREF(Py_True); return Py_True; } else { Py_INCREF(Py_False); return Py_False; } case Option::TYPE_STR: case Option::TYPE_ADDR: case Option::TYPE_ADDRVEC: case Option::TYPE_UUID: break; } return PyUnicode_FromString(value.c_str()); }
1,037
23.139535
70
cc
null
ceph-main/src/mgr/PyUtil.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <string> #include <Python.h> #include "common/options.h" PyObject *get_python_typed_option_value( Option::type_t type, const std::string& value);
275
17.4
70
h
null
ceph-main/src/mgr/ServiceMap.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "mgr/ServiceMap.h" #include <fmt/format.h> #include "common/Formatter.h" using ceph::bufferlist; using ceph::Formatter; // Daemon void ServiceMap::Daemon::encode(bufferlist& bl, uint64_t features) const { ENCODE_START(2, 1, bl); encode(gid, bl); encode(addr, bl, features); encode(start_epoch, bl); encode(start_stamp, bl); encode(metadata, bl); encode(task_status, bl); ENCODE_FINISH(bl); } void ServiceMap::Daemon::decode(bufferlist::const_iterator& p) { DECODE_START(2, p); decode(gid, p); decode(addr, p); decode(start_epoch, p); decode(start_stamp, p); decode(metadata, p); if (struct_v >= 2) { decode(task_status, p); } DECODE_FINISH(p); } void ServiceMap::Daemon::dump(Formatter *f) const { f->dump_unsigned("start_epoch", start_epoch); f->dump_stream("start_stamp") << start_stamp; f->dump_unsigned("gid", gid); f->dump_string("addr", addr.get_legacy_str()); f->open_object_section("metadata"); for (auto& p : metadata) { f->dump_string(p.first.c_str(), p.second); } f->close_section(); f->open_object_section("task_status"); for (auto& p : task_status) { f->dump_string(p.first.c_str(), p.second); } f->close_section(); } void ServiceMap::Daemon::generate_test_instances(std::list<Daemon*>& ls) { ls.push_back(new Daemon); ls.push_back(new Daemon); ls.back()->gid = 222; ls.back()->metadata["this"] = "that"; ls.back()->task_status["task1"] = "running"; } // Service std::string ServiceMap::Service::get_summary() const { if (!summary.empty()) { return summary; } if (daemons.empty()) { return "no daemons active"; } // If "daemon_type" is present, this will be used in place of "daemon" when // reporting the count (e.g., "${N} daemons"). // // We will additional break down the count by various groupings, based // on the following keys: // // "hostname" -> host(s) // "zone_id" -> zone(s) // // The `ceph -s` will be something likes: // iscsi: 3 portals active (3 hosts) // rgw: 3 gateways active (3 hosts, 1 zone) std::map<std::string, std::set<std::string>> groupings; std::string type("daemon"); int num = 0; for (auto& d : daemons) { ++num; if (auto p = d.second.metadata.find("daemon_type"); p != d.second.metadata.end()) { type = p->second; } for (auto k : {std::make_pair("zone", "zone_id"), std::make_pair("host", "hostname")}) { auto p = d.second.metadata.find(k.second); if (p != d.second.metadata.end()) { groupings[k.first].insert(p->second); } } } std::ostringstream ss; ss << num << " " << type << (num > 1 ? "s" : "") << " active"; if (groupings.size()) { ss << " ("; for (auto i = groupings.begin(); i != groupings.end(); ++i) { if (i != groupings.begin()) { ss << ", "; } ss << i->second.size() << " " << i->first << (i->second.size() ? "s" : ""); } ss << ")"; } return ss.str(); } bool ServiceMap::Service::has_running_tasks() const { return std::any_of(daemons.begin(), daemons.end(), [](auto& daemon) { return !daemon.second.task_status.empty(); }); } std::string ServiceMap::Service::get_task_summary(const std::string_view task_prefix) const { // contruct a map similar to: // {"service1 status" -> {"service1.0" -> "running"}} // {"service2 status" -> {"service2.0" -> "idle"}, // {"service2.1" -> "running"}} std::map<std::string, std::map<std::string, std::string>> by_task; for (const auto& [service_id, daemon] : daemons) { for (const auto& [task_name, status] : daemon.task_status) { by_task[task_name].emplace(fmt::format("{}.{}", task_prefix, service_id), status); } } std::stringstream ss; for (const auto &[task_name, status_by_service] : by_task) { ss << "\n " << task_name << ":"; for (auto& [service, status] : status_by_service) { ss << "\n " << service << ": " << status; } } return ss.str(); } void ServiceMap::Service::count_metadata(const std::string& field, std::map<std::string,int> *out) const { for (auto& p : daemons) { auto q = p.second.metadata.find(field); if (q == p.second.metadata.end()) { (*out)["unknown"]++; } else { (*out)[q->second]++; } } } void ServiceMap::Service::encode(bufferlist& bl, uint64_t features) const { ENCODE_START(1, 1, bl); encode(daemons, bl, features); encode(summary, bl); ENCODE_FINISH(bl); } void ServiceMap::Service::decode(bufferlist::const_iterator& p) { DECODE_START(1, p); decode(daemons, p); decode(summary, p); DECODE_FINISH(p); } void ServiceMap::Service::dump(Formatter *f) const { f->open_object_section("daemons"); f->dump_string("summary", summary); for (auto& p : daemons) { f->dump_object(p.first.c_str(), p.second); } f->close_section(); } void ServiceMap::Service::generate_test_instances(std::list<Service*>& ls) { ls.push_back(new Service); ls.push_back(new Service); ls.back()->daemons["one"].gid = 1; ls.back()->daemons["two"].gid = 2; } // ServiceMap void ServiceMap::encode(bufferlist& bl, uint64_t features) const { ENCODE_START(1, 1, bl); encode(epoch, bl); encode(modified, bl); encode(services, bl, features); ENCODE_FINISH(bl); } void ServiceMap::decode(bufferlist::const_iterator& p) { DECODE_START(1, p); decode(epoch, p); decode(modified, p); decode(services, p); DECODE_FINISH(p); } void ServiceMap::dump(Formatter *f) const { f->dump_unsigned("epoch", epoch); f->dump_stream("modified") << modified; f->open_object_section("services"); for (auto& p : services) { f->dump_object(p.first.c_str(), p.second); } f->close_section(); } void ServiceMap::generate_test_instances(std::list<ServiceMap*>& ls) { ls.push_back(new ServiceMap); ls.push_back(new ServiceMap); ls.back()->epoch = 123; ls.back()->services["rgw"].daemons["one"].gid = 123; ls.back()->services["rgw"].daemons["two"].gid = 344; ls.back()->services["iscsi"].daemons["foo"].gid = 3222; }
6,178
24.427984
91
cc
null
ceph-main/src/mgr/ServiceMap.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <string> #include <map> #include <list> #include <sstream> #include "include/utime.h" #include "include/buffer.h" #include "msg/msg_types.h" namespace ceph { class Formatter; } struct ServiceMap { struct Daemon { uint64_t gid = 0; entity_addr_t addr; epoch_t start_epoch = 0; ///< epoch first registered utime_t start_stamp; ///< timestamp daemon started/registered std::map<std::string,std::string> metadata; ///< static metadata std::map<std::string,std::string> task_status; ///< running task status void encode(ceph::buffer::list& bl, uint64_t features) const; void decode(ceph::buffer::list::const_iterator& p); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<Daemon*>& ls); }; struct Service { std::map<std::string,Daemon> daemons; std::string summary; ///< summary status std::string for 'ceph -s' void encode(ceph::buffer::list& bl, uint64_t features) const; void decode(ceph::buffer::list::const_iterator& p); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<Service*>& ls); std::string get_summary() const; bool has_running_tasks() const; std::string get_task_summary(const std::string_view task_prefix) const; void count_metadata(const std::string& field, std::map<std::string,int> *out) const; }; epoch_t epoch = 0; utime_t modified; std::map<std::string,Service> services; void encode(ceph::buffer::list& bl, uint64_t features) const; void decode(ceph::buffer::list::const_iterator& p); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<ServiceMap*>& ls); std::pair<Daemon*,bool> get_daemon(const std::string& service, const std::string& daemon) { auto& s = services[service]; auto [d, added] = s.daemons.try_emplace(daemon); return {&d->second, added}; } bool rm_daemon(const std::string& service, const std::string& daemon) { auto p = services.find(service); if (p == services.end()) { return false; } auto q = p->second.daemons.find(daemon); if (q == p->second.daemons.end()) { return false; } p->second.daemons.erase(q); if (p->second.daemons.empty()) { services.erase(p); } return true; } static inline bool is_normal_ceph_entity(std::string_view type) { if (type == "osd" || type == "client" || type == "mon" || type == "mds" || type == "mgr") { return true; } return false; } }; WRITE_CLASS_ENCODER_FEATURES(ServiceMap) WRITE_CLASS_ENCODER_FEATURES(ServiceMap::Service) WRITE_CLASS_ENCODER_FEATURES(ServiceMap::Daemon)
2,838
27.969388
75
h
null
ceph-main/src/mgr/StandbyPyModules.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 John Spray <[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 "StandbyPyModules.h" #include "common/Finisher.h" #include "common/debug.h" #include "common/errno.h" #include "mgr/MgrContext.h" #include "mgr/Gil.h" // For ::mgr_store_prefix #include "PyModuleRegistry.h" #define dout_context g_ceph_context #define dout_subsys ceph_subsys_mgr #undef dout_prefix #define dout_prefix *_dout << "mgr " << __func__ << " " StandbyPyModules::StandbyPyModules( const MgrMap &mgr_map_, PyModuleConfig &module_config, LogChannelRef clog_, MonClient &monc_, Finisher &f) : state(module_config, monc_), clog(clog_), finisher(f) { state.set_mgr_map(mgr_map_); } // FIXME: completely identical to ActivePyModules void StandbyPyModules::shutdown() { std::lock_guard locker(lock); // Signal modules to drop out of serve() and/or tear down resources for (auto &i : modules) { auto module = i.second.get(); const auto& name = i.first; dout(10) << "waiting for module " << name << " to shutdown" << dendl; lock.unlock(); module->shutdown(); lock.lock(); dout(10) << "module " << name << " shutdown" << dendl; } // For modules implementing serve(), finish the threads where we // were running that. for (auto &i : modules) { lock.unlock(); dout(10) << "joining thread for module " << i.first << dendl; i.second->thread.join(); dout(10) << "joined thread for module " << i.first << dendl; lock.lock(); } modules.clear(); } void StandbyPyModules::start_one(PyModuleRef py_module) { std::lock_guard l(lock); const auto name = py_module->get_name(); auto standby_module = new StandbyPyModule(state, py_module, clog); // Send all python calls down a Finisher to avoid blocking // C++ code, and avoid any potential lock cycles. finisher.queue(new LambdaContext([this, standby_module, name](int) { int r = standby_module->load(); if (r != 0) { derr << "Failed to run module in standby mode ('" << name << "')" << dendl; delete standby_module; } else { std::lock_guard l(lock); auto em = modules.emplace(name, standby_module); ceph_assert(em.second); // actually inserted dout(4) << "Starting thread for " << name << dendl; standby_module->thread.create(standby_module->get_thread_name()); } })); } int StandbyPyModule::load() { Gil gil(py_module->pMyThreadState, true); // We tell the module how we name it, so that it can be consistent // with us in logging etc. auto pThisPtr = PyCapsule_New(this, nullptr, nullptr); ceph_assert(pThisPtr != nullptr); auto pModuleName = PyUnicode_FromString(get_name().c_str()); ceph_assert(pModuleName != nullptr); auto pArgs = PyTuple_Pack(2, pModuleName, pThisPtr); Py_DECREF(pThisPtr); Py_DECREF(pModuleName); pClassInstance = PyObject_CallObject(py_module->pStandbyClass, pArgs); Py_DECREF(pArgs); if (pClassInstance == nullptr) { derr << "Failed to construct class in '" << get_name() << "'" << dendl; derr << handle_pyerror(true, get_name(), "StandbyPyModule::load") << dendl; return -EINVAL; } else { dout(1) << "Constructed class from module: " << get_name() << dendl; return 0; } } bool StandbyPyModule::get_config(const std::string &key, std::string *value) const { const std::string global_key = "mgr/" + get_name() + "/" + key; dout(4) << __func__ << " key: " << global_key << dendl; return state.with_config([global_key, value](const PyModuleConfig &config){ if (config.config.count(global_key)) { *value = config.config.at(global_key); return true; } else { return false; } }); } bool StandbyPyModule::get_store(const std::string &key, std::string *value) const { const std::string global_key = PyModule::mgr_store_prefix + get_name() + "/" + key; dout(4) << __func__ << " key: " << global_key << dendl; // Active modules use a cache of store values (kept up to date // as writes pass through the active mgr), but standbys // fetch values synchronously to get an up to date value. // It's an acceptable cost because standby modules should not be // doing a lot. MonClient &monc = state.get_monc(); std::ostringstream cmd_json; cmd_json << "{\"prefix\": \"config-key get\", \"key\": \"" << global_key << "\"}"; bufferlist outbl; std::string outs; C_SaferCond c; monc.start_mon_command( {cmd_json.str()}, {}, &outbl, &outs, &c); int r = c.wait(); if (r == -ENOENT) { return false; } else if (r != 0) { // This is some internal error, not meaningful to python modules, // so let them just see no value. derr << __func__ << " error fetching store key '" << global_key << "': " << cpp_strerror(r) << " " << outs << dendl; return false; } else { *value = outbl.to_str(); return true; } } std::string StandbyPyModule::get_active_uri() const { std::string result; state.with_mgr_map([&result, this](const MgrMap &mgr_map){ auto iter = mgr_map.services.find(get_name()); if (iter != mgr_map.services.end()) { result = iter->second; } }); return result; }
5,657
27.149254
79
cc
null
ceph-main/src/mgr/StandbyPyModules.h
// -*- 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 John Spray <[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. */ #pragma once #include <string> #include <map> #include <Python.h> #include "common/Thread.h" #include "common/ceph_mutex.h" #include "mgr/Gil.h" #include "mon/MonClient.h" #include "mon/MgrMap.h" #include "mgr/PyModuleRunner.h" class Finisher; /** * State that is read by all modules running in standby mode */ class StandbyPyModuleState { mutable ceph::mutex lock = ceph::make_mutex("StandbyPyModuleState::lock"); MgrMap mgr_map; PyModuleConfig &module_config; MonClient &monc; public: StandbyPyModuleState(PyModuleConfig &module_config_, MonClient &monc_) : module_config(module_config_), monc(monc_) {} void set_mgr_map(const MgrMap &mgr_map_) { std::lock_guard l(lock); mgr_map = mgr_map_; } // MonClient does all its own locking so we're happy to hand out // references. MonClient &get_monc() {return monc;}; template<typename Callback, typename...Args> void with_mgr_map(Callback&& cb, Args&&...args) const { std::lock_guard l(lock); std::forward<Callback>(cb)(mgr_map, std::forward<Args>(args)...); } template<typename Callback, typename...Args> auto with_config(Callback&& cb, Args&&... args) const -> decltype(cb(module_config, std::forward<Args>(args)...)) { std::lock_guard l(lock); return std::forward<Callback>(cb)(module_config, std::forward<Args>(args)...); } }; class StandbyPyModule : public PyModuleRunner { StandbyPyModuleState &state; public: StandbyPyModule( StandbyPyModuleState &state_, const PyModuleRef &py_module_, LogChannelRef clog_) : PyModuleRunner(py_module_, clog_), state(state_) { } bool get_config(const std::string &key, std::string *value) const; bool get_store(const std::string &key, std::string *value) const; std::string get_active_uri() const; entity_addrvec_t get_myaddrs() const { return state.get_monc().get_myaddrs(); } int load(); }; class StandbyPyModules { private: mutable ceph::mutex lock = ceph::make_mutex("StandbyPyModules::lock"); std::map<std::string, std::unique_ptr<StandbyPyModule>> modules; StandbyPyModuleState state; LogChannelRef clog; Finisher &finisher; public: StandbyPyModules( const MgrMap &mgr_map_, PyModuleConfig &module_config, LogChannelRef clog_, MonClient &monc, Finisher &f); void start_one(PyModuleRef py_module); void shutdown(); void handle_mgr_map(const MgrMap &mgr_map) { state.set_mgr_map(mgr_map); } };
2,931
20.880597
82
h
null
ceph-main/src/mgr/TTLCache.cc
#include "TTLCache.h" #include <chrono> #include <functional> #include <string> #include "PyUtil.h" template <class Key, class Value> void TTLCacheBase<Key, Value>::insert(Key key, Value value) { auto now = std::chrono::steady_clock::now(); if (!ttl) return; int16_t random_ttl_offset = ttl * ttl_spread_ratio * (2l * rand() / float(RAND_MAX) - 1); // in order not to have spikes of misses we increase or decrease by 25% of // the ttl int16_t spreaded_ttl = ttl + random_ttl_offset; auto expiration_date = now + std::chrono::seconds(spreaded_ttl); cache::insert(key, {value, expiration_date}); } template <class Key, class Value> Value TTLCacheBase<Key, Value>::get(Key key) { if (!exists(key)) { throw_key_not_found(key); } if (expired(key)) { erase(key); throw_key_not_found(key); } Value value = {get_value(key)}; return value; } template <class Key> PyObject* TTLCache<Key, PyObject*>::get(Key key) { if (!this->exists(key)) { this->throw_key_not_found(key); } if (this->expired(key)) { this->erase(key); this->throw_key_not_found(key); } PyObject* cached_value = this->get_value(key); Py_INCREF(cached_value); return cached_value; } template <class Key, class Value> void TTLCacheBase<Key, Value>::erase(Key key) { cache::erase(key); } template <class Key> void TTLCache<Key, PyObject*>::erase(Key key) { Py_DECREF(this->get_value(key, false)); ttl_base::erase(key); } template <class Key, class Value> bool TTLCacheBase<Key, Value>::expired(Key key) { ttl_time_point expiration_date = get_value_time_point(key); auto now = std::chrono::steady_clock::now(); if (now >= expiration_date) { return true; } else { return false; } } template <class Key, class Value> void TTLCacheBase<Key, Value>::clear() { cache::clear(); } template <class Key, class Value> Value TTLCacheBase<Key, Value>::get_value(Key key, bool count_hit) { value_type stored_value = cache::get(key, count_hit); Value value = std::get<0>(stored_value); return value; } template <class Key, class Value> ttl_time_point TTLCacheBase<Key, Value>::get_value_time_point(Key key) { value_type stored_value = cache::get(key, false); ttl_time_point tp = std::get<1>(stored_value); return tp; } template <class Key, class Value> void TTLCacheBase<Key, Value>::set_ttl(uint16_t ttl) { this->ttl = ttl; } template <class Key, class Value> bool TTLCacheBase<Key, Value>::exists(Key key) { return cache::exists(key); } template <class Key, class Value> void TTLCacheBase<Key, Value>::throw_key_not_found(Key key) { cache::throw_key_not_found(key); }
2,639
25.138614
80
cc
null
ceph-main/src/mgr/TTLCache.h
#pragma once #include <atomic> #include <chrono> #include <functional> #include <map> #include <memory> #include <string> #include <vector> #include "PyUtil.h" template <class Key, class Value> class Cache { private: std::atomic<uint64_t> hits, misses; protected: unsigned int capacity; Cache(unsigned int size = UINT16_MAX) : hits{0}, misses{0}, capacity{size} {}; std::map<Key, Value> content; std::vector<std::string> allowed_keys = {"osd_map", "pg_dump", "pg_stats"}; void mark_miss() { misses++; } void mark_hit() { hits++; } unsigned int get_misses() { return misses; } unsigned int get_hits() { return hits; } void throw_key_not_found(Key key) { std::stringstream ss; ss << "Key " << key << " couldn't be found\n"; throw std::out_of_range(ss.str()); } public: void insert(Key key, Value value) { mark_miss(); if (content.size() < capacity) { content.insert({key, value}); } } Value get(Key key, bool count_hit = true) { if (count_hit) { mark_hit(); } return content[key]; } void erase(Key key) { content.erase(content.find(key)); } void clear() { content.clear(); } bool exists(Key key) { return content.find(key) != content.end(); } std::pair<uint64_t, uint64_t> get_hit_miss_ratio() { return std::make_pair(hits.load(), misses.load()); } bool is_cacheable(Key key) { for (auto k : allowed_keys) { if (key == k) return true; } return false; } int size() { return content.size(); } ~Cache(){}; }; using ttl_time_point = std::chrono::time_point<std::chrono::steady_clock>; template <class Key, class Value> class TTLCacheBase : public Cache<Key, std::pair<Value, ttl_time_point>> { private: uint16_t ttl; float ttl_spread_ratio; using value_type = std::pair<Value, ttl_time_point>; using cache = Cache<Key, value_type>; protected: Value get_value(Key key, bool count_hit = true); ttl_time_point get_value_time_point(Key key); bool exists(Key key); bool expired(Key key); void finish_get(Key key); void finish_erase(Key key); void throw_key_not_found(Key key); public: TTLCacheBase(uint16_t ttl_ = 0, uint16_t size = UINT16_MAX, float spread = 0.25) : Cache<Key, value_type>(size), ttl{ttl_}, ttl_spread_ratio{spread} {} ~TTLCacheBase(){}; void insert(Key key, Value value); Value get(Key key); void erase(Key key); void clear(); uint16_t get_ttl() { return ttl; }; void set_ttl(uint16_t ttl); }; template <class Key, class Value> class TTLCache : public TTLCacheBase<Key, Value> { public: TTLCache(uint16_t ttl_ = 0, uint16_t size = UINT16_MAX, float spread = 0.25) : TTLCacheBase<Key, Value>(ttl_, size, spread) {} ~TTLCache(){}; }; template <class Key> class TTLCache<Key, PyObject*> : public TTLCacheBase<Key, PyObject*> { public: TTLCache(uint16_t ttl_ = 0, uint16_t size = UINT16_MAX, float spread = 0.25) : TTLCacheBase<Key, PyObject*>(ttl_, size, spread) {} ~TTLCache(){}; PyObject* get(Key key); void erase(Key key); private: using ttl_base = TTLCacheBase<Key, PyObject*>; }; #include "TTLCache.cc"
3,154
24.650407
80
h
null
ceph-main/src/mgr/Types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_MGR_TYPES_H #define CEPH_MGR_TYPES_H typedef int MetricQueryID; typedef std::pair<uint64_t,uint64_t> PerformanceCounter; typedef std::vector<PerformanceCounter> PerformanceCounters; struct MetricListener { virtual ~MetricListener() { } virtual void handle_query_updated() = 0; }; struct PerfCollector { MetricQueryID query_id; PerfCollector(MetricQueryID query_id) : query_id(query_id) { } }; #endif // CEPH_MGR_TYPES_H
554
19.555556
70
h
null
ceph-main/src/mgr/mgr_commands.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "mgr_commands.h" /* The set of statically defined (C++-handled) commands. This * does not include the Python-defined commands, which are loaded * in PyModules */ const std::vector<MonCommand> mgr_commands = { #define COMMAND(parsesig, helptext, module, perm) \ {parsesig, helptext, module, perm, 0}, #include "MgrCommands.h" #undef COMMAND };
457
29.533333
70
cc
null
ceph-main/src/mgr/mgr_commands.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include "mon/MonCommand.h" #include <vector> extern const std::vector<MonCommand> mgr_commands;
211
20.2
70
h
null
ceph-main/src/mgr/mgr_perf_counters.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #include "mgr_perf_counters.h" #include "common/perf_counters.h" #include "common/ceph_context.h" PerfCounters *perfcounter = NULL; int mgr_perf_start(CephContext *cct) { PerfCountersBuilder plb(cct, "mgr", l_mgr_first, l_mgr_last); plb.set_prio_default(PerfCountersBuilder::PRIO_USEFUL); plb.add_u64_counter(l_mgr_cache_hit, "cache_hit", "Cache hits"); plb.add_u64_counter(l_mgr_cache_miss, "cache_miss", "Cache miss"); perfcounter = plb.create_perf_counters(); cct->get_perfcounters_collection()->add(perfcounter); return 0; } void mgr_perf_stop(CephContext *cct) { ceph_assert(perfcounter); cct->get_perfcounters_collection()->remove(perfcounter); delete perfcounter; }
804
26.758621
70
cc
null
ceph-main/src/mgr/mgr_perf_counters.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab ft=cpp #pragma once #include "include/common_fwd.h" extern PerfCounters* perfcounter; extern int mgr_perf_start(CephContext* cct); extern void mgr_perf_stop(CephContext* cct); enum { l_mgr_first, l_mgr_cache_hit, l_mgr_cache_miss, l_mgr_last, };
359
16.142857
70
h
null
ceph-main/src/mon/AuthMonitor.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 <sstream> #include "mon/AuthMonitor.h" #include "mon/Monitor.h" #include "mon/MonitorDBStore.h" #include "mon/OSDMonitor.h" #include "mon/MDSMonitor.h" #include "mon/ConfigMonitor.h" #include "messages/MMonCommand.h" #include "messages/MAuth.h" #include "messages/MAuthReply.h" #include "messages/MMonGlobalID.h" #include "messages/MMonUsedPendingKeys.h" #include "msg/Messenger.h" #include "auth/AuthServiceHandler.h" #include "auth/KeyRing.h" #include "include/stringify.h" #include "include/ceph_assert.h" #include "mds/MDSAuthCaps.h" #include "mgr/MgrCap.h" #include "osd/OSDCap.h" #define dout_subsys ceph_subsys_mon #undef dout_prefix #define dout_prefix _prefix(_dout, mon, get_last_committed()) using namespace TOPNSPC::common; using std::cerr; using std::cout; using std::dec; using std::hex; using std::list; using std::map; using std::make_pair; using std::ostream; using std::ostringstream; using std::pair; using std::set; using std::setfill; using std::string; using std::stringstream; using std::to_string; using std::vector; using std::unique_ptr; using ceph::bufferlist; using ceph::decode; using ceph::encode; using ceph::Formatter; using ceph::JSONFormatter; using ceph::make_message; using ceph::mono_clock; using ceph::mono_time; using ceph::timespan_str; static ostream& _prefix(std::ostream *_dout, Monitor &mon, version_t v) { return *_dout << "mon." << mon.name << "@" << mon.rank << "(" << mon.get_state_name() << ").auth v" << v << " "; } ostream& operator<<(ostream &out, const AuthMonitor &pm) { return out << "auth"; } bool AuthMonitor::check_rotate() { KeyServerData::Incremental rot_inc; rot_inc.op = KeyServerData::AUTH_INC_SET_ROTATING; if (mon.key_server.prepare_rotating_update(rot_inc.rotating_bl)) { dout(10) << __func__ << " updating rotating" << dendl; push_cephx_inc(rot_inc); return true; } return false; } void AuthMonitor::process_used_pending_keys( const std::map<EntityName,CryptoKey>& used_pending_keys) { for (auto& [name, used_key] : used_pending_keys) { dout(10) << __func__ << " used pending_key for " << name << dendl; KeyServerData::Incremental inc; inc.op = KeyServerData::AUTH_INC_ADD; inc.name = name; mon.key_server.get_auth(name, inc.auth); for (auto& p : pending_auth) { if (p.inc_type == AUTH_DATA) { KeyServerData::Incremental auth_inc; auto q = p.auth_data.cbegin(); decode(auth_inc, q); if (auth_inc.op == KeyServerData::AUTH_INC_ADD && auth_inc.name == name) { dout(10) << __func__ << " starting with pending uncommitted" << dendl; inc.auth = auth_inc.auth; } } } if (stringify(inc.auth.pending_key) == stringify(used_key)) { dout(10) << __func__ << " committing pending_key -> key for " << name << dendl; inc.auth.key = inc.auth.pending_key; inc.auth.pending_key.clear(); push_cephx_inc(inc); } } } /* Tick function to update the map based on performance every N seconds */ void AuthMonitor::tick() { if (!is_active()) return; dout(10) << *this << dendl; // increase global_id? bool propose = false; bool increase; { std::lock_guard l(mon.auth_lock); increase = _should_increase_max_global_id(); } if (increase) { if (mon.is_leader()) { increase_max_global_id(); propose = true; } else { dout(10) << __func__ << "requesting more ids from leader" << dendl; MMonGlobalID *req = new MMonGlobalID(); req->old_max_id = max_global_id; mon.send_mon_message(req, mon.get_leader()); } } if (mon.monmap->min_mon_release >= ceph_release_t::quincy) { auto used_pending_keys = mon.key_server.get_used_pending_keys(); if (!used_pending_keys.empty()) { dout(10) << __func__ << " " << used_pending_keys.size() << " used pending_keys" << dendl; if (mon.is_leader()) { process_used_pending_keys(used_pending_keys); propose = true; } else { MMonUsedPendingKeys *req = new MMonUsedPendingKeys(); req->used_pending_keys = used_pending_keys; mon.send_mon_message(req, mon.get_leader()); } } } if (!mon.is_leader()) { return; } if (check_rotate()) { propose = true; } if (propose) { propose_pending(); } } void AuthMonitor::on_active() { dout(10) << "AuthMonitor::on_active()" << dendl; if (!mon.is_leader()) return; mon.key_server.start_server(); mon.key_server.clear_used_pending_keys(); if (is_writeable()) { bool propose = false; if (check_rotate()) { propose = true; } bool increase; { std::lock_guard l(mon.auth_lock); increase = _should_increase_max_global_id(); } if (increase) { increase_max_global_id(); propose = true; } if (propose) { propose_pending(); } } } bufferlist _encode_cap(const string& cap) { bufferlist bl; encode(cap, bl); return bl; } void AuthMonitor::get_initial_keyring(KeyRing *keyring) { dout(10) << __func__ << dendl; ceph_assert(keyring != nullptr); bufferlist bl; int ret = mon.store->get("mkfs", "keyring", bl); if (ret == -ENOENT) { return; } // fail hard only if there's an error we're not expecting to see ceph_assert(ret == 0); auto p = bl.cbegin(); decode(*keyring, p); } void _generate_bootstrap_keys( list<pair<EntityName,EntityAuth> >* auth_lst) { ceph_assert(auth_lst != nullptr); map<string,map<string,bufferlist> > bootstrap = { { "admin", { { "mon", _encode_cap("allow *") }, { "osd", _encode_cap("allow *") }, { "mds", _encode_cap("allow *") }, { "mgr", _encode_cap("allow *") } } }, { "bootstrap-osd", { { "mon", _encode_cap("allow profile bootstrap-osd") } } }, { "bootstrap-rgw", { { "mon", _encode_cap("allow profile bootstrap-rgw") } } }, { "bootstrap-mds", { { "mon", _encode_cap("allow profile bootstrap-mds") } } }, { "bootstrap-mgr", { { "mon", _encode_cap("allow profile bootstrap-mgr") } } }, { "bootstrap-rbd", { { "mon", _encode_cap("allow profile bootstrap-rbd") } } }, { "bootstrap-rbd-mirror", { { "mon", _encode_cap("allow profile bootstrap-rbd-mirror") } } } }; for (auto &p : bootstrap) { EntityName name; name.from_str("client." + p.first); EntityAuth auth; auth.key.create(g_ceph_context, CEPH_CRYPTO_AES); auth.caps = p.second; auth_lst->push_back(make_pair(name, auth)); } } void AuthMonitor::create_initial_keys(KeyRing *keyring) { dout(10) << __func__ << " with keyring" << dendl; ceph_assert(keyring != nullptr); list<pair<EntityName,EntityAuth> > auth_lst; _generate_bootstrap_keys(&auth_lst); for (auto &p : auth_lst) { if (keyring->exists(p.first)) { continue; } keyring->add(p.first, p.second); } } void AuthMonitor::create_initial() { dout(10) << "create_initial -- creating initial map" << dendl; // initialize rotating keys mon.key_server.clear_secrets(); check_rotate(); ceph_assert(pending_auth.size() == 1); if (mon.is_keyring_required()) { KeyRing keyring; // attempt to obtain an existing mkfs-time keyring get_initial_keyring(&keyring); // create missing keys in the keyring create_initial_keys(&keyring); // import the resulting keyring import_keyring(keyring); } max_global_id = MIN_GLOBAL_ID; Incremental inc; inc.inc_type = GLOBAL_ID; inc.max_global_id = max_global_id; pending_auth.push_back(inc); format_version = 3; } void AuthMonitor::update_from_paxos(bool *need_bootstrap) { dout(10) << __func__ << dendl; load_health(); version_t version = get_last_committed(); version_t keys_ver = mon.key_server.get_ver(); if (version == keys_ver) return; ceph_assert(version > keys_ver); version_t latest_full = get_version_latest_full(); dout(10) << __func__ << " version " << version << " keys ver " << keys_ver << " latest " << latest_full << dendl; if ((latest_full > 0) && (latest_full > keys_ver)) { bufferlist latest_bl; int err = get_version_full(latest_full, latest_bl); ceph_assert(err == 0); ceph_assert(latest_bl.length() != 0); dout(7) << __func__ << " loading summary e " << latest_full << dendl; dout(7) << __func__ << " latest length " << latest_bl.length() << dendl; auto p = latest_bl.cbegin(); __u8 struct_v; decode(struct_v, p); decode(max_global_id, p); decode(mon.key_server, p); mon.key_server.set_ver(latest_full); keys_ver = latest_full; } dout(10) << __func__ << " key server version " << mon.key_server.get_ver() << dendl; // walk through incrementals while (version > keys_ver) { bufferlist bl; int ret = get_version(keys_ver+1, bl); ceph_assert(ret == 0); ceph_assert(bl.length()); // reset if we are moving to initial state. we will normally have // keys in here temporarily for bootstrapping that we need to // clear out. if (keys_ver == 0) mon.key_server.clear_secrets(); dout(20) << __func__ << " walking through version " << (keys_ver+1) << " len " << bl.length() << dendl; auto p = bl.cbegin(); __u8 v; decode(v, p); while (!p.end()) { Incremental inc; decode(inc, p); switch (inc.inc_type) { case GLOBAL_ID: max_global_id = inc.max_global_id; break; case AUTH_DATA: { KeyServerData::Incremental auth_inc; auto iter = inc.auth_data.cbegin(); decode(auth_inc, iter); mon.key_server.apply_data_incremental(auth_inc); break; } } } keys_ver++; mon.key_server.set_ver(keys_ver); if (keys_ver == 1 && mon.is_keyring_required()) { auto t(std::make_shared<MonitorDBStore::Transaction>()); t->erase("mkfs", "keyring"); mon.store->apply_transaction(t); } } { std::lock_guard l(mon.auth_lock); if (last_allocated_id == 0) { last_allocated_id = max_global_id; dout(10) << __func__ << " last_allocated_id initialized to " << max_global_id << dendl; } } dout(10) << __func__ << " max_global_id=" << max_global_id << " format_version " << format_version << dendl; mon.key_server.dump(); } bool AuthMonitor::_should_increase_max_global_id() { ceph_assert(ceph_mutex_is_locked(mon.auth_lock)); auto num_prealloc = g_conf()->mon_globalid_prealloc; if (max_global_id < num_prealloc || (last_allocated_id + 1) >= max_global_id - num_prealloc / 2) { return true; } return false; } void AuthMonitor::increase_max_global_id() { ceph_assert(mon.is_leader()); Incremental inc; inc.inc_type = GLOBAL_ID; inc.max_global_id = max_global_id + g_conf()->mon_globalid_prealloc; dout(10) << "increasing max_global_id to " << inc.max_global_id << dendl; pending_auth.push_back(inc); } bool AuthMonitor::should_propose(double& delay) { return (!pending_auth.empty()); } void AuthMonitor::create_pending() { pending_auth.clear(); dout(10) << "create_pending v " << (get_last_committed() + 1) << dendl; } void AuthMonitor::encode_pending(MonitorDBStore::TransactionRef t) { dout(10) << __func__ << " v " << (get_last_committed() + 1) << dendl; bufferlist bl; __u8 v = 1; encode(v, bl); vector<Incremental>::iterator p; for (p = pending_auth.begin(); p != pending_auth.end(); ++p) p->encode(bl, mon.get_quorum_con_features()); version_t version = get_last_committed() + 1; put_version(t, version, bl); put_last_committed(t, version); // health health_check_map_t next; map<string,list<string>> bad_detail; // entity -> details for (auto i = mon.key_server.secrets_begin(); i != mon.key_server.secrets_end(); ++i) { for (auto& p : i->second.caps) { ostringstream ss; if (!valid_caps(p.first, p.second, &ss)) { ostringstream ss2; ss2 << i->first << " " << ss.str(); bad_detail[i->first.to_str()].push_back(ss2.str()); } } } for (auto& inc : pending_auth) { if (inc.inc_type == AUTH_DATA) { KeyServerData::Incremental auth_inc; auto iter = inc.auth_data.cbegin(); decode(auth_inc, iter); if (auth_inc.op == KeyServerData::AUTH_INC_DEL) { bad_detail.erase(auth_inc.name.to_str()); } else if (auth_inc.op == KeyServerData::AUTH_INC_ADD) { for (auto& p : auth_inc.auth.caps) { ostringstream ss; if (!valid_caps(p.first, p.second, &ss)) { ostringstream ss2; ss2 << auth_inc.name << " " << ss.str(); bad_detail[auth_inc.name.to_str()].push_back(ss2.str()); } } } } } if (bad_detail.size()) { ostringstream ss; ss << bad_detail.size() << " auth entities have invalid capabilities"; health_check_t *check = &next.add("AUTH_BAD_CAPS", HEALTH_ERR, ss.str(), bad_detail.size()); for (auto& i : bad_detail) { for (auto& j : i.second) { check->detail.push_back(j); } } } encode_health(next, t); } void AuthMonitor::encode_full(MonitorDBStore::TransactionRef t) { version_t version = mon.key_server.get_ver(); // do not stash full version 0 as it will never be removed nor read if (version == 0) return; dout(10) << __func__ << " auth v " << version << dendl; ceph_assert(get_last_committed() == version); bufferlist full_bl; std::scoped_lock l{mon.key_server.get_lock()}; dout(20) << __func__ << " key server has " << (mon.key_server.has_secrets() ? "" : "no ") << "secrets!" << dendl; __u8 v = 1; encode(v, full_bl); encode(max_global_id, full_bl); encode(mon.key_server, full_bl); put_version_full(t, version, full_bl); put_version_latest_full(t, version); } version_t AuthMonitor::get_trim_to() const { unsigned max = g_conf()->paxos_max_join_drift * 2; version_t version = get_last_committed(); if (mon.is_leader() && (version > max)) return version - max; return 0; } bool AuthMonitor::preprocess_query(MonOpRequestRef op) { auto m = op->get_req<PaxosServiceMessage>(); dout(10) << "preprocess_query " << *m << " from " << m->get_orig_source_inst() << dendl; switch (m->get_type()) { case MSG_MON_COMMAND: try { return preprocess_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); return true; } case CEPH_MSG_AUTH: return prep_auth(op, false); case MSG_MON_GLOBAL_ID: return false; case MSG_MON_USED_PENDING_KEYS: return false; default: ceph_abort(); return true; } } bool AuthMonitor::prepare_update(MonOpRequestRef op) { auto m = op->get_req<PaxosServiceMessage>(); dout(10) << "prepare_update " << *m << " from " << m->get_orig_source_inst() << dendl; switch (m->get_type()) { case MSG_MON_COMMAND: try { return prepare_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); return true; } case MSG_MON_GLOBAL_ID: return prepare_global_id(op); case MSG_MON_USED_PENDING_KEYS: return prepare_used_pending_keys(op); case CEPH_MSG_AUTH: return prep_auth(op, true); default: ceph_abort(); return false; } } void AuthMonitor::_set_mon_num_rank(int num, int rank) { dout(10) << __func__ << " num " << num << " rank " << rank << dendl; ceph_assert(ceph_mutex_is_locked(mon.auth_lock)); mon_num = num; mon_rank = rank; } uint64_t AuthMonitor::_assign_global_id() { ceph_assert(ceph_mutex_is_locked(mon.auth_lock)); if (mon_num < 1 || mon_rank < 0) { dout(10) << __func__ << " inactive (num_mon " << mon_num << " rank " << mon_rank << ")" << dendl; return 0; } if (!last_allocated_id) { dout(10) << __func__ << " last_allocated_id == 0" << dendl; return 0; } uint64_t id = last_allocated_id + 1; int remainder = id % mon_num; if (remainder) { remainder = mon_num - remainder; } id += remainder + mon_rank; if (id >= max_global_id) { dout(10) << __func__ << " failed (max " << max_global_id << ")" << dendl; return 0; } last_allocated_id = id; dout(10) << __func__ << " " << id << " (max " << max_global_id << ")" << dendl; return id; } uint64_t AuthMonitor::assign_global_id(bool should_increase_max) { uint64_t id; { std::lock_guard l(mon.auth_lock); id =_assign_global_id(); if (should_increase_max) { should_increase_max = _should_increase_max_global_id(); } } if (mon.is_leader() && should_increase_max) { increase_max_global_id(); } return id; } bool AuthMonitor::prep_auth(MonOpRequestRef op, bool paxos_writable) { auto m = op->get_req<MAuth>(); dout(10) << "prep_auth() blob_size=" << m->get_auth_payload().length() << dendl; MonSession *s = op->get_session(); if (!s) { dout(10) << "no session, dropping" << dendl; return true; } int ret = 0; MAuthReply *reply; bufferlist response_bl; auto indata = m->auth_payload.cbegin(); __u32 proto = m->protocol; bool start = false; bool finished = false; EntityName entity_name; bool is_new_global_id = false; // set up handler? if (m->protocol == 0 && !s->auth_handler) { set<__u32> supported; try { __u8 struct_v = 1; decode(struct_v, indata); decode(supported, indata); decode(entity_name, indata); decode(s->con->peer_global_id, indata); } catch (const ceph::buffer::error &e) { dout(10) << "failed to decode initial auth message" << dendl; ret = -EINVAL; goto reply; } // do we require cephx signatures? if (!m->get_connection()->has_feature(CEPH_FEATURE_MSG_AUTH)) { if (entity_name.get_type() == CEPH_ENTITY_TYPE_MON || entity_name.get_type() == CEPH_ENTITY_TYPE_OSD || entity_name.get_type() == CEPH_ENTITY_TYPE_MDS || entity_name.get_type() == CEPH_ENTITY_TYPE_MGR) { if (g_conf()->cephx_cluster_require_signatures || g_conf()->cephx_require_signatures) { dout(1) << m->get_source_inst() << " supports cephx but not signatures and" << " 'cephx [cluster] require signatures = true';" << " disallowing cephx" << dendl; supported.erase(CEPH_AUTH_CEPHX); } } else { if (g_conf()->cephx_service_require_signatures || g_conf()->cephx_require_signatures) { dout(1) << m->get_source_inst() << " supports cephx but not signatures and" << " 'cephx [service] require signatures = true';" << " disallowing cephx" << dendl; supported.erase(CEPH_AUTH_CEPHX); } } } else if (!m->get_connection()->has_feature(CEPH_FEATURE_CEPHX_V2)) { if (entity_name.get_type() == CEPH_ENTITY_TYPE_MON || entity_name.get_type() == CEPH_ENTITY_TYPE_OSD || entity_name.get_type() == CEPH_ENTITY_TYPE_MDS || entity_name.get_type() == CEPH_ENTITY_TYPE_MGR) { if (g_conf()->cephx_cluster_require_version >= 2 || g_conf()->cephx_require_version >= 2) { dout(1) << m->get_source_inst() << " supports cephx but not v2 and" << " 'cephx [cluster] require version >= 2';" << " disallowing cephx" << dendl; supported.erase(CEPH_AUTH_CEPHX); } } else { if (g_conf()->cephx_service_require_version >= 2 || g_conf()->cephx_require_version >= 2) { dout(1) << m->get_source_inst() << " supports cephx but not v2 and" << " 'cephx [service] require version >= 2';" << " disallowing cephx" << dendl; supported.erase(CEPH_AUTH_CEPHX); } } } int type; if (entity_name.get_type() == CEPH_ENTITY_TYPE_MON || entity_name.get_type() == CEPH_ENTITY_TYPE_OSD || entity_name.get_type() == CEPH_ENTITY_TYPE_MDS || entity_name.get_type() == CEPH_ENTITY_TYPE_MGR) type = mon.auth_cluster_required.pick(supported); else type = mon.auth_service_required.pick(supported); s->auth_handler = get_auth_service_handler(type, g_ceph_context, &mon.key_server); if (!s->auth_handler) { dout(1) << "client did not provide supported auth type" << dendl; ret = -ENOTSUP; goto reply; } start = true; proto = type; } else if (!s->auth_handler) { dout(10) << "protocol specified but no s->auth_handler" << dendl; ret = -EINVAL; goto reply; } /* assign a new global_id? we assume this should only happen on the first request. If a client tries to send it later, it'll screw up its auth session */ if (!s->con->peer_global_id) { s->con->peer_global_id = assign_global_id(paxos_writable); if (!s->con->peer_global_id) { delete s->auth_handler; s->auth_handler = NULL; if (mon.is_leader() && paxos_writable) { dout(10) << "increasing global id, waitlisting message" << dendl; wait_for_active(op, new C_RetryMessage(this, op)); goto done; } if (!mon.is_leader()) { dout(10) << "not the leader, requesting more ids from leader" << dendl; int leader = mon.get_leader(); MMonGlobalID *req = new MMonGlobalID(); req->old_max_id = max_global_id; mon.send_mon_message(req, leader); wait_for_finished_proposal(op, new C_RetryMessage(this, op)); return true; } ceph_assert(!paxos_writable); return false; } is_new_global_id = true; } try { if (start) { // new session ret = s->auth_handler->start_session(entity_name, s->con->peer_global_id, is_new_global_id, &response_bl, &s->con->peer_caps_info); } else { // request ret = s->auth_handler->handle_request( indata, 0, // no connection_secret needed &response_bl, &s->con->peer_caps_info, nullptr, nullptr); } if (ret == -EIO) { wait_for_active(op, new C_RetryMessage(this,op)); goto done; } if (ret > 0) { if (!s->authenticated && mon.ms_handle_authentication(s->con.get()) > 0) { finished = true; } ret = 0; } } catch (const ceph::buffer::error &err) { ret = -EINVAL; dout(0) << "caught error when trying to handle auth request, probably malformed request" << dendl; } reply: reply = new MAuthReply(proto, &response_bl, ret, s->con->peer_global_id); mon.send_reply(op, reply); if (finished) { // always send the latest monmap. if (m->monmap_epoch < mon.monmap->get_epoch()) mon.send_latest_monmap(m->get_connection().get()); mon.configmon()->check_sub(s); } done: return true; } bool AuthMonitor::preprocess_command(MonOpRequestRef op) { auto m = op->get_req<MMonCommand>(); int r = -1; bufferlist rdata; stringstream ss, ds; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { // ss has reason for failure string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, rdata, get_last_committed()); return true; } string prefix; cmd_getval(cmdmap, "prefix", prefix); if (prefix == "auth add" || prefix == "auth del" || prefix == "auth rm" || prefix == "auth get-or-create" || prefix == "auth get-or-create-key" || prefix == "auth get-or-create-pending" || prefix == "auth clear-pending" || prefix == "auth commit-pending" || prefix == "fs authorize" || prefix == "auth import" || prefix == "auth caps") { return false; } MonSession *session = op->get_session(); if (!session) { mon.reply_command(op, -EACCES, "access denied", rdata, get_last_committed()); return true; } // entity might not be supplied, but if it is, it should be valid string entity_name; cmd_getval(cmdmap, "entity", entity_name); EntityName entity; if (!entity_name.empty() && !entity.from_str(entity_name)) { ss << "invalid entity_auth " << entity_name; mon.reply_command(op, -EINVAL, ss.str(), get_last_committed()); return true; } string format = cmd_getval_or<string>(cmdmap, "format", "plain"); boost::scoped_ptr<Formatter> f(Formatter::create(format)); if (prefix == "auth export") { KeyRing keyring; export_keyring(keyring); if (!entity_name.empty()) { EntityAuth eauth; if (keyring.get_auth(entity, eauth)) { _encode_auth(entity, eauth, rdata, f.get()); r = 0; } else { ss << "no key for " << eauth; r = -ENOENT; } } else { if (f) keyring.encode_formatted("auth", f.get(), rdata); else keyring.encode_plaintext(rdata); r = 0; } } else if (prefix == "auth get" && !entity_name.empty()) { EntityAuth entity_auth; if (!mon.key_server.get_auth(entity, entity_auth)) { ss << "failed to find " << entity_name << " in keyring"; r = -ENOENT; } else { _encode_auth(entity, entity_auth, rdata, f.get()); r = 0; } } else if (prefix == "auth print-key" || prefix == "auth print_key" || prefix == "auth get-key") { EntityAuth auth; if (!mon.key_server.get_auth(entity, auth)) { ss << "don't have " << entity; r = -ENOENT; goto done; } if (f) { auth.key.encode_formatted("auth", f.get(), rdata); } else { auth.key.encode_plaintext(rdata); } r = 0; } else if (prefix == "auth list" || prefix == "auth ls") { if (f) { mon.key_server.encode_formatted("auth", f.get(), rdata); } else { mon.key_server.encode_plaintext(rdata); } r = 0; goto done; } else { ss << "invalid command"; r = -EINVAL; } done: rdata.append(ds); string rs; getline(ss, rs, '\0'); mon.reply_command(op, r, rs, rdata, get_last_committed()); return true; } void AuthMonitor::export_keyring(KeyRing& keyring) { mon.key_server.export_keyring(keyring); } int AuthMonitor::import_keyring(KeyRing& keyring) { dout(10) << __func__ << " " << keyring.size() << " keys" << dendl; for (map<EntityName, EntityAuth>::iterator p = keyring.get_keys().begin(); p != keyring.get_keys().end(); ++p) { if (p->second.caps.empty()) { dout(0) << "import: no caps supplied" << dendl; return -EINVAL; } int err = add_entity(p->first, p->second); ceph_assert(err == 0); } return 0; } int AuthMonitor::remove_entity(const EntityName &entity) { dout(10) << __func__ << " " << entity << dendl; if (!mon.key_server.contains(entity)) return -ENOENT; KeyServerData::Incremental auth_inc; auth_inc.name = entity; auth_inc.op = KeyServerData::AUTH_INC_DEL; push_cephx_inc(auth_inc); return 0; } bool AuthMonitor::entity_is_pending(EntityName& entity) { // are we about to have it? for (auto& p : pending_auth) { if (p.inc_type == AUTH_DATA) { KeyServerData::Incremental inc; auto q = p.auth_data.cbegin(); decode(inc, q); if (inc.op == KeyServerData::AUTH_INC_ADD && inc.name == entity) { return true; } } } return false; } int AuthMonitor::exists_and_matches_entity( const auth_entity_t& entity, bool has_secret, stringstream& ss) { return exists_and_matches_entity(entity.name, entity.auth, entity.auth.caps, has_secret, ss); } int AuthMonitor::exists_and_matches_entity( const EntityName& name, const EntityAuth& auth, const map<string,bufferlist>& caps, bool has_secret, stringstream& ss) { dout(20) << __func__ << " entity " << name << " auth " << auth << " caps " << caps << " has_secret " << has_secret << dendl; EntityAuth existing_auth; // does entry already exist? if (mon.key_server.get_auth(name, existing_auth)) { // key match? if (has_secret) { if (existing_auth.key.get_secret().cmp(auth.key.get_secret())) { ss << "entity " << name << " exists but key does not match"; return -EEXIST; } } // caps match? if (caps.size() != existing_auth.caps.size()) { ss << "entity " << name << " exists but caps do not match"; return -EINVAL; } for (auto& it : caps) { if (existing_auth.caps.count(it.first) == 0 || !existing_auth.caps[it.first].contents_equal(it.second)) { ss << "entity " << name << " exists but cap " << it.first << " does not match"; return -EINVAL; } } // they match, no-op return 0; } return -ENOENT; } int AuthMonitor::add_entity( const EntityName& name, const EntityAuth& auth) { // okay, add it. KeyServerData::Incremental auth_inc; auth_inc.op = KeyServerData::AUTH_INC_ADD; auth_inc.name = name; auth_inc.auth = auth; dout(10) << " add auth entity " << auth_inc.name << dendl; dout(30) << " " << auth_inc.auth << dendl; push_cephx_inc(auth_inc); return 0; } int AuthMonitor::validate_osd_destroy( int32_t id, const uuid_d& uuid, EntityName& cephx_entity, EntityName& lockbox_entity, stringstream& ss) { ceph_assert(paxos.is_plugged()); dout(10) << __func__ << " id " << id << " uuid " << uuid << dendl; string cephx_str = "osd." + stringify(id); string lockbox_str = "client.osd-lockbox." + stringify(uuid); if (!cephx_entity.from_str(cephx_str)) { dout(10) << __func__ << " invalid cephx entity '" << cephx_str << "'" << dendl; ss << "invalid cephx key entity '" << cephx_str << "'"; return -EINVAL; } if (!lockbox_entity.from_str(lockbox_str)) { dout(10) << __func__ << " invalid lockbox entity '" << lockbox_str << "'" << dendl; ss << "invalid lockbox key entity '" << lockbox_str << "'"; return -EINVAL; } if (!mon.key_server.contains(cephx_entity) && !mon.key_server.contains(lockbox_entity)) { return -ENOENT; } return 0; } int AuthMonitor::do_osd_destroy( const EntityName& cephx_entity, const EntityName& lockbox_entity) { ceph_assert(paxos.is_plugged()); dout(10) << __func__ << " cephx " << cephx_entity << " lockbox " << lockbox_entity << dendl; bool removed = false; int err = remove_entity(cephx_entity); if (err == -ENOENT) { dout(10) << __func__ << " " << cephx_entity << " does not exist" << dendl; } else { removed = true; } err = remove_entity(lockbox_entity); if (err == -ENOENT) { dout(10) << __func__ << " " << lockbox_entity << " does not exist" << dendl; } else { removed = true; } if (!removed) { dout(10) << __func__ << " entities do not exist -- no-op." << dendl; return 0; } // given we have paxos plugged, this will not result in a proposal // being triggered, but it will still be needed so that we get our // pending state encoded into the paxos' pending transaction. propose_pending(); return 0; } int _create_auth( EntityAuth& auth, const string& key, const map<string,bufferlist>& caps) { if (key.empty()) return -EINVAL; try { auth.key.decode_base64(key); } catch (ceph::buffer::error& e) { return -EINVAL; } auth.caps = caps; return 0; } int AuthMonitor::validate_osd_new( int32_t id, const uuid_d& uuid, const string& cephx_secret, const string& lockbox_secret, auth_entity_t& cephx_entity, auth_entity_t& lockbox_entity, stringstream& ss) { dout(10) << __func__ << " osd." << id << " uuid " << uuid << dendl; map<string,bufferlist> cephx_caps = { { "osd", _encode_cap("allow *") }, { "mon", _encode_cap("allow profile osd") }, { "mgr", _encode_cap("allow profile osd") } }; map<string,bufferlist> lockbox_caps = { { "mon", _encode_cap("allow command \"config-key get\" " "with key=\"dm-crypt/osd/" + stringify(uuid) + "/luks\"") } }; bool has_lockbox = !lockbox_secret.empty(); string cephx_name = "osd." + stringify(id); string lockbox_name = "client.osd-lockbox." + stringify(uuid); if (!cephx_entity.name.from_str(cephx_name)) { dout(10) << __func__ << " invalid cephx entity '" << cephx_name << "'" << dendl; ss << "invalid cephx key entity '" << cephx_name << "'"; return -EINVAL; } if (has_lockbox) { if (!lockbox_entity.name.from_str(lockbox_name)) { dout(10) << __func__ << " invalid cephx lockbox entity '" << lockbox_name << "'" << dendl; ss << "invalid cephx lockbox entity '" << lockbox_name << "'"; return -EINVAL; } } if (entity_is_pending(cephx_entity.name) || (has_lockbox && entity_is_pending(lockbox_entity.name))) { // If we have pending entities for either the cephx secret or the // lockbox secret, then our safest bet is to retry the command at // a later time. These entities may be pending because an `osd new` // command has been run (which is unlikely, due to the nature of // the operation, which will force a paxos proposal), or (more likely) // because a competing client created those entities before we handled // the `osd new` command. Regardless, let's wait and see. return -EAGAIN; } if (!is_valid_cephx_key(cephx_secret)) { ss << "invalid cephx secret."; return -EINVAL; } if (has_lockbox && !is_valid_cephx_key(lockbox_secret)) { ss << "invalid cephx lockbox secret."; return -EINVAL; } int err = _create_auth(cephx_entity.auth, cephx_secret, cephx_caps); ceph_assert(0 == err); bool cephx_is_idempotent = false, lockbox_is_idempotent = false; err = exists_and_matches_entity(cephx_entity, true, ss); if (err != -ENOENT) { if (err < 0) { return err; } ceph_assert(0 == err); cephx_is_idempotent = true; } if (has_lockbox) { err = _create_auth(lockbox_entity.auth, lockbox_secret, lockbox_caps); ceph_assert(err == 0); err = exists_and_matches_entity(lockbox_entity, true, ss); if (err != -ENOENT) { if (err < 0) { return err; } ceph_assert(0 == err); lockbox_is_idempotent = true; } } if (cephx_is_idempotent && (!has_lockbox || lockbox_is_idempotent)) { return EEXIST; } return 0; } int AuthMonitor::do_osd_new( const auth_entity_t& cephx_entity, const auth_entity_t& lockbox_entity, bool has_lockbox) { ceph_assert(paxos.is_plugged()); dout(10) << __func__ << " cephx " << cephx_entity.name << " lockbox "; if (has_lockbox) { *_dout << lockbox_entity.name; } else { *_dout << "n/a"; } *_dout << dendl; // we must have validated before reaching this point. // if keys exist, then this means they also match; otherwise we would // have failed before calling this function. bool cephx_exists = mon.key_server.contains(cephx_entity.name); if (!cephx_exists) { int err = add_entity(cephx_entity.name, cephx_entity.auth); ceph_assert(0 == err); } if (has_lockbox && !mon.key_server.contains(lockbox_entity.name)) { int err = add_entity(lockbox_entity.name, lockbox_entity.auth); ceph_assert(0 == err); } // given we have paxos plugged, this will not result in a proposal // being triggered, but it will still be needed so that we get our // pending state encoded into the paxos' pending transaction. propose_pending(); return 0; } template<typename CAP_ENTITY_CLASS> bool AuthMonitor::_was_parsing_fine(const string& entity, const string& caps, ostream* out) { CAP_ENTITY_CLASS cap; if (!cap.parse(caps, out)) { dout(20) << "Parsing " << entity << " caps failed. " << entity << " cap: " << caps << dendl; return false; } return true; } bool AuthMonitor::valid_caps(const string& entity, const string& caps, ostream *out) { if (entity == "mon") { return _was_parsing_fine<MonCap>(entity, caps, out); } if (!g_conf().get_val<bool>("mon_auth_validate_all_caps")) { return true; } if (entity == "mgr") { return _was_parsing_fine<MgrCap>(entity, caps, out); } else if (entity == "osd") { return _was_parsing_fine<OSDCap>(entity, caps, out); } else if (entity == "mds") { return _was_parsing_fine<MDSAuthCaps>(entity, caps, out); } else { if (out) { *out << "unknown cap type '" << entity << "'"; } return false; } return true; } bool AuthMonitor::valid_caps(const map<string, string>& caps, ostream *out) { for (const auto& kv : caps) { if (!valid_caps(kv.first, kv.second, out)) { return false; } } return true; } bool AuthMonitor::prepare_command(MonOpRequestRef op) { auto m = op->get_req<MMonCommand>(); stringstream ss, ds; bufferlist rdata; // holds data that'll be printed on client's stdout string rs; int err = -EINVAL; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { // ss has reason for failure string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, rdata, get_last_committed()); return true; } string prefix; vector<string> caps_vec; map<string, string> ceph_caps; string entity_name; EntityName entity; cmd_getval(cmdmap, "prefix", prefix); string format = cmd_getval_or<string>(cmdmap, "format", "plain"); boost::scoped_ptr<Formatter> f(Formatter::create(format)); MonSession *session = op->get_session(); if (!session) { mon.reply_command(op, -EACCES, "access denied", rdata, get_last_committed()); return true; } cmd_getval(cmdmap, "caps", caps_vec); // fs authorize command's can have odd number of caps arguments if (prefix != "fs authorize") { if ((caps_vec.size() % 2) != 0) { ss << "bad capabilities request; odd number of arguments"; err = -EINVAL; goto done; } else { for (size_t i = 0; i < caps_vec.size(); i += 2) { ceph_caps.insert({caps_vec[i], caps_vec[i + 1]}); } } } cmd_getval(cmdmap, "entity", entity_name); if (!entity_name.empty() && !entity.from_str(entity_name)) { ss << "bad entity name"; err = -EINVAL; goto done; } if (prefix == "auth import") { bufferlist bl = m->get_data(); if (bl.length() == 0) { ss << "auth import: no data supplied"; getline(ss, rs); mon.reply_command(op, -EINVAL, rs, get_last_committed()); return true; } auto iter = bl.cbegin(); KeyRing keyring; try { decode(keyring, iter); } catch (const ceph::buffer::error &ex) { ss << "error decoding keyring" << " " << ex.what(); err = -EINVAL; goto done; } err = import_keyring(keyring); if (err < 0) { ss << "auth import: no caps supplied"; getline(ss, rs); mon.reply_command(op, -EINVAL, rs, get_last_committed()); return true; } err = 0; wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs, get_last_committed() + 1)); return true; } else if (prefix == "auth add" && !entity_name.empty()) { /* expected behavior: * - if command reproduces current state, return 0. * - if command adds brand new entity, handle it. * - if command adds new state to existing entity, return error. */ KeyServerData::Incremental auth_inc; auth_inc.name = entity; bufferlist bl = m->get_data(); bool has_keyring = (bl.length() > 0); KeyRing new_keyring; if (has_keyring) { auto iter = bl.cbegin(); try { decode(new_keyring, iter); } catch (const ceph::buffer::error &ex) { ss << "error decoding keyring"; err = -EINVAL; goto done; } } map<string, bufferlist> encoded_caps; if (err = _check_and_encode_caps(ceph_caps, encoded_caps, ss); err < 0) { goto done; } // are we about to have it? if (entity_is_pending(entity)) { wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs, get_last_committed() + 1)); return true; } // pull info out of provided keyring EntityAuth new_inc; if (has_keyring) { if (!new_keyring.get_auth(auth_inc.name, new_inc)) { ss << "key for " << auth_inc.name << " not found in provided keyring"; err = -EINVAL; goto done; } if (!encoded_caps.empty() && !new_inc.caps.empty()) { ss << "caps cannot be specified both in keyring and in command"; err = -EINVAL; goto done; } if (encoded_caps.empty()) { encoded_caps = new_inc.caps; } } err = exists_and_matches_entity(auth_inc.name, new_inc, encoded_caps, has_keyring, ss); // if entity/key/caps do not exist in the keyring, just fall through // and add the entity; otherwise, make sure everything matches (in // which case it's a no-op), because if not we must fail. if (err != -ENOENT) { if (err < 0) { goto done; } // no-op. ceph_assert(err == 0); goto done; } err = 0; // okay, add it. if (!has_keyring) { dout(10) << "AuthMonitor::prepare_command generating random key for " << auth_inc.name << dendl; new_inc.key.create(g_ceph_context, CEPH_CRYPTO_AES); } new_inc.caps = encoded_caps; err = add_entity(auth_inc.name, new_inc); ceph_assert(err == 0); ss << "added key for " << auth_inc.name; getline(ss, rs); wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs, get_last_committed() + 1)); return true; } else if ((prefix == "auth get-or-create-pending" || prefix == "auth clear-pending" || prefix == "auth commit-pending")) { if (mon.monmap->min_mon_release < ceph_release_t::quincy) { err = -EPERM; ss << "pending_keys are not available until after upgrading to quincy"; goto done; } EntityAuth entity_auth; if (!mon.key_server.get_auth(entity, entity_auth)) { ss << "entity " << entity << " does not exist"; err = -ENOENT; goto done; } // is there an uncommitted pending_key? (or any change for this entity) for (auto& p : pending_auth) { if (p.inc_type == AUTH_DATA) { KeyServerData::Incremental auth_inc; auto q = p.auth_data.cbegin(); decode(auth_inc, q); if (auth_inc.op == KeyServerData::AUTH_INC_ADD && auth_inc.name == entity) { wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs, get_last_committed() + 1)); return true; } } } if (prefix == "auth get-or-create-pending") { KeyRing kr; bool exists = false; if (!entity_auth.pending_key.empty()) { kr.add(entity, entity_auth.key, entity_auth.pending_key); err = 0; exists = true; } else { KeyServerData::Incremental auth_inc; auth_inc.op = KeyServerData::AUTH_INC_ADD; auth_inc.name = entity; auth_inc.auth = entity_auth; auth_inc.auth.pending_key.create(g_ceph_context, CEPH_CRYPTO_AES); push_cephx_inc(auth_inc); kr.add(entity, auth_inc.auth.key, auth_inc.auth.pending_key); push_cephx_inc(auth_inc); } if (f) { kr.encode_formatted("auth", f.get(), rdata); } else { kr.encode_plaintext(rdata); } if (exists) { goto done; } } else if (prefix == "auth clear-pending") { if (entity_auth.pending_key.empty()) { err = 0; goto done; } KeyServerData::Incremental auth_inc; auth_inc.op = KeyServerData::AUTH_INC_ADD; auth_inc.name = entity; auth_inc.auth = entity_auth; auth_inc.auth.pending_key.clear(); push_cephx_inc(auth_inc); } else if (prefix == "auth commit-pending") { if (entity_auth.pending_key.empty()) { err = 0; ss << "no pending key"; goto done; } KeyServerData::Incremental auth_inc; auth_inc.op = KeyServerData::AUTH_INC_ADD; auth_inc.name = entity; auth_inc.auth = entity_auth; auth_inc.auth.key = auth_inc.auth.pending_key; auth_inc.auth.pending_key.clear(); push_cephx_inc(auth_inc); } wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs, rdata, get_last_committed() + 1)); return true; } else if ((prefix == "auth get-or-create-key" || prefix == "auth get-or-create") && !entity_name.empty()) { // auth get-or-create <name> [mon osdcapa osd osdcapb ...] map<string, bufferlist> wanted_caps; if (err = _check_and_encode_caps(ceph_caps, wanted_caps, ss); err < 0) { goto done; } // do we have it? EntityAuth entity_auth; if (mon.key_server.get_auth(entity, entity_auth)) { for (const auto &sys_cap : wanted_caps) { if (entity_auth.caps.count(sys_cap.first) == 0 || !entity_auth.caps[sys_cap.first].contents_equal(sys_cap.second)) { ss << "key for " << entity << " exists but cap " << sys_cap.first << " does not match"; err = -EINVAL; goto done; } } if (prefix == "auth get-or-create-key") { if (f) { entity_auth.key.encode_formatted("auth", f.get(), rdata); } else { ds << entity_auth.key; } } else { _encode_key(entity, entity_auth, rdata, f.get(), true, &entity_auth.caps); } err = 0; goto done; } // ...or are we about to? for (vector<Incremental>::iterator p = pending_auth.begin(); p != pending_auth.end(); ++p) { if (p->inc_type == AUTH_DATA) { KeyServerData::Incremental auth_inc; auto q = p->auth_data.cbegin(); decode(auth_inc, q); if (auth_inc.op == KeyServerData::AUTH_INC_ADD && auth_inc.name == entity) { wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs, get_last_committed() + 1)); return true; } } } // create it KeyServerData::Incremental auth_inc; auth_inc.op = KeyServerData::AUTH_INC_ADD; auth_inc.name = entity; auth_inc.auth.key.create(g_ceph_context, CEPH_CRYPTO_AES); auth_inc.auth.caps = wanted_caps; push_cephx_inc(auth_inc); if (prefix == "auth get-or-create-key") { if (f) { auth_inc.auth.key.encode_formatted("auth", f.get(), rdata); } else { ds << auth_inc.auth.key; } } else { _encode_key(entity, auth_inc.auth, rdata, f.get(), false, &wanted_caps); } rdata.append(ds); getline(ss, rs); wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs, rdata, get_last_committed() + 1)); return true; } else if (prefix == "fs authorize") { string filesystem; cmd_getval(cmdmap, "filesystem", filesystem); string mon_cap_string = "allow r"; string mds_cap_string, osd_cap_string; string osd_cap_wanted = "r"; std::shared_ptr<const Filesystem> fs; if (filesystem != "*" && filesystem != "all") { fs = mon.mdsmon()->get_fsmap().get_filesystem(filesystem); if (fs == nullptr) { ss << "filesystem " << filesystem << " does not exist."; err = -EINVAL; goto done; } else { mon_cap_string += " fsname=" + std::string(fs->mds_map.get_fs_name()); } } for (auto it = caps_vec.begin(); it != caps_vec.end() && (it + 1) != caps_vec.end(); it += 2) { const string &path = *it; const string &cap = *(it + 1); bool root_squash = false; if ((it + 2) != caps_vec.end() && *(it + 2) == "root_squash") { root_squash = true; ++it; } if (cap != "r" && cap.compare(0, 2, "rw")) { ss << "Permission flags must start with 'r' or 'rw'."; err = -EINVAL; goto done; } if (cap.compare(0, 2, "rw") == 0) osd_cap_wanted = "rw"; char last='\0'; for (size_t i = 2; i < cap.size(); ++i) { char c = cap.at(i); if (last >= c) { ss << "Permission flags (except 'rw') must be specified in alphabetical order."; err = -EINVAL; goto done; } switch (c) { case 'p': break; case 's': break; default: ss << "Unknown permission flag '" << c << "'."; err = -EINVAL; goto done; } } mds_cap_string += mds_cap_string.empty() ? "" : ", "; mds_cap_string += "allow " + cap; if (filesystem != "*" && filesystem != "all" && fs != nullptr) { mds_cap_string += " fsname=" + std::string(fs->mds_map.get_fs_name()); } if (path != "/") { mds_cap_string += " path=" + path; } if (root_squash) { mds_cap_string += " root_squash"; } } osd_cap_string += osd_cap_string.empty() ? "" : ", "; osd_cap_string += "allow " + osd_cap_wanted + " tag " + pg_pool_t::APPLICATION_NAME_CEPHFS + " data=" + filesystem; map<string, bufferlist> encoded_caps; map<string, string> wanted_caps = { {"mon", mon_cap_string}, {"osd", osd_cap_string}, {"mds", mds_cap_string} }; if (err = _check_and_encode_caps(wanted_caps, encoded_caps, ss); err < 0) { goto done; } EntityAuth entity_auth; if (mon.key_server.get_auth(entity, entity_auth)) { for (const auto &sys_cap : encoded_caps) { if (entity_auth.caps.count(sys_cap.first) == 0 || !entity_auth.caps[sys_cap.first].contents_equal(sys_cap.second)) { ss << entity << " already has fs capabilities that differ from " << "those supplied. To generate a new auth key for " << entity << ", first remove " << entity << " from configuration files, " << "execute 'ceph auth rm " << entity << "', then execute this " << "command again."; err = -EINVAL; goto done; } } _encode_key(entity, entity_auth, rdata, f.get(), false, &encoded_caps); err = 0; goto done; } err = _create_entity(entity, wanted_caps, op, ds, &rdata, f.get()); if (err == 0) { return true; } else { goto done; } } else if (prefix == "auth caps" && !entity_name.empty()) { err = _update_caps(entity, ceph_caps, op, ds, &rdata, f.get()); if (err == 0) { return true; } else { goto done; } } else if ((prefix == "auth del" || prefix == "auth rm") && !entity_name.empty()) { KeyServerData::Incremental auth_inc; auth_inc.name = entity; if (!mon.key_server.contains(auth_inc.name)) { err = 0; goto done; } auth_inc.op = KeyServerData::AUTH_INC_DEL; push_cephx_inc(auth_inc); wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs, get_last_committed() + 1)); return true; } done: rdata.append(ds); getline(ss, rs, '\0'); mon.reply_command(op, err, rs, rdata, get_last_committed()); return false; } void AuthMonitor::_encode_keyring(KeyRing& kr, const EntityName& entity, bufferlist& rdata, Formatter* fmtr, map<string, bufferlist>* caps) { if (not fmtr) { kr.encode_plaintext(rdata); } else { if (caps != nullptr) { kr.set_caps(entity, *caps); } kr.encode_formatted("auth", fmtr, rdata); } } void AuthMonitor::_encode_auth(const EntityName& entity, const EntityAuth& eauth, bufferlist& rdata, Formatter* fmtr, bool pending_key, map<string, bufferlist>* caps) { KeyRing kr; if (not pending_key) { kr.add(entity, eauth); } else { kr.add(entity, eauth.key, eauth.pending_key); } _encode_keyring(kr, entity, rdata, fmtr, caps); } void AuthMonitor::_encode_key(const EntityName& entity, const EntityAuth& eauth, bufferlist& rdata, Formatter* fmtr, bool pending_key, map<string, bufferlist>* caps) { KeyRing kr; if (not pending_key) { kr.add(entity, eauth.key); } else { kr.add(entity, eauth.key, eauth.pending_key); } _encode_keyring(kr, entity, rdata, fmtr, caps); } int AuthMonitor::_check_and_encode_caps(const map<string, string>& caps, map<string, bufferlist>& encoded_caps, stringstream& ss) { if (!valid_caps(caps, &ss)) { return -EINVAL; } for (const auto& kv : caps) { bufferlist cap; encode(kv.second, cap); encoded_caps[kv.first] = cap; } return 0; } /* Pass both, rdata as well as fmtr, to enable printing of the key after * update and set create to True to allow authorizing a new entity instead * of updating its caps. */ int AuthMonitor::_update_or_create_entity(const EntityName& entity, const map<string, string>& caps, MonOpRequestRef op, stringstream& ds, bufferlist* rdata, Formatter* fmtr, bool create_entity) { stringstream ss; KeyServerData::Incremental auth_inc; auth_inc.name = entity; if (!create_entity && !mon.key_server.get_auth(auth_inc.name, auth_inc.auth)) { ss << "couldn't find entry " << auth_inc.name; return -ENOENT; } map<string, bufferlist> encoded_caps; if (auto err = _check_and_encode_caps(caps, encoded_caps, ss); err < 0) { return err; } auth_inc.op = KeyServerData::AUTH_INC_ADD; auth_inc.auth.caps = encoded_caps; if (create_entity) { auth_inc.auth.key.create(g_ceph_context, CEPH_CRYPTO_AES); } push_cephx_inc(auth_inc); if (!create_entity) { ss << "updated caps for " << auth_inc.name; } if (rdata != nullptr) { _encode_auth(entity, auth_inc.auth, *rdata, fmtr, false, &encoded_caps); rdata->append(ds); } string rs; getline(ss, rs); wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs, *rdata, get_last_committed() + 1)); return 0; } int AuthMonitor::_update_caps(const EntityName& entity, const map<string, string>& caps, MonOpRequestRef op, stringstream& ds, bufferlist* rdata, Formatter* fmtr) { return _update_or_create_entity(entity, caps, op, ds, rdata, fmtr, false); } int AuthMonitor::_create_entity(const EntityName& entity, const map<string, string>& caps, MonOpRequestRef op, stringstream& ds, bufferlist* rdata, Formatter* fmtr) { return _update_or_create_entity(entity, caps, op, ds, rdata, fmtr, true); } bool AuthMonitor::prepare_global_id(MonOpRequestRef op) { dout(10) << "AuthMonitor::prepare_global_id" << dendl; increase_max_global_id(); return true; } bool AuthMonitor::prepare_used_pending_keys(MonOpRequestRef op) { dout(10) << __func__ << " " << op << dendl; auto m = op->get_req<MMonUsedPendingKeys>(); process_used_pending_keys(m->used_pending_keys); return true; } bool AuthMonitor::_upgrade_format_to_dumpling() { dout(1) << __func__ << " upgrading from format 0 to 1" << dendl; ceph_assert(format_version == 0); bool changed = false; map<EntityName, EntityAuth>::iterator p; for (p = mon.key_server.secrets_begin(); p != mon.key_server.secrets_end(); ++p) { // grab mon caps, if any string mon_caps; if (p->second.caps.count("mon") == 0) continue; try { auto it = p->second.caps["mon"].cbegin(); decode(mon_caps, it); } catch (const ceph::buffer::error&) { dout(10) << __func__ << " unable to parse mon cap for " << p->first << dendl; continue; } string n = p->first.to_str(); string new_caps; // set daemon profiles if ((p->first.is_osd() || p->first.is_mds()) && mon_caps == "allow rwx") { new_caps = string("allow profile ") + std::string(p->first.get_type_name()); } // update bootstrap keys if (n == "client.bootstrap-osd") { new_caps = "allow profile bootstrap-osd"; } if (n == "client.bootstrap-mds") { new_caps = "allow profile bootstrap-mds"; } if (new_caps.length() > 0) { dout(5) << __func__ << " updating " << p->first << " mon cap from " << mon_caps << " to " << new_caps << dendl; bufferlist bl; encode(new_caps, bl); KeyServerData::Incremental auth_inc; auth_inc.name = p->first; auth_inc.auth = p->second; auth_inc.auth.caps["mon"] = bl; auth_inc.op = KeyServerData::AUTH_INC_ADD; push_cephx_inc(auth_inc); changed = true; } } return changed; } bool AuthMonitor::_upgrade_format_to_luminous() { dout(1) << __func__ << " upgrading from format 1 to 2" << dendl; ceph_assert(format_version == 1); bool changed = false; map<EntityName, EntityAuth>::iterator p; for (p = mon.key_server.secrets_begin(); p != mon.key_server.secrets_end(); ++p) { string n = p->first.to_str(); string newcap; if (n == "client.admin") { // admin gets it all newcap = "allow *"; } else if (n.find("osd.") == 0 || n.find("mds.") == 0 || n.find("mon.") == 0) { // daemons follow their profile string type = n.substr(0, 3); newcap = "allow profile " + type; } else if (p->second.caps.count("mon")) { // if there are any mon caps, give them 'r' mgr caps newcap = "allow r"; } if (newcap.length() > 0) { dout(5) << " giving " << n << " mgr '" << newcap << "'" << dendl; bufferlist bl; encode(newcap, bl); EntityAuth auth = p->second; auth.caps["mgr"] = bl; add_entity(p->first, auth); changed = true; } if (n.find("mgr.") == 0 && p->second.caps.count("mon")) { // the kraken [email protected] set the mon cap to 'allow *'. auto blp = p->second.caps["mon"].cbegin(); string oldcaps; decode(oldcaps, blp); if (oldcaps == "allow *") { dout(5) << " fixing " << n << " mon cap to 'allow profile mgr'" << dendl; bufferlist bl; encode("allow profile mgr", bl); EntityAuth auth = p->second; auth.caps["mon"] = bl; add_entity(p->first, p->second); changed = true; } } } // add bootstrap key if it does not already exist // (might have already been get-or-create'd by // ceph-create-keys) EntityName bootstrap_mgr_name; int r = bootstrap_mgr_name.from_str("client.bootstrap-mgr"); ceph_assert(r); if (!mon.key_server.contains(bootstrap_mgr_name)) { EntityName name = bootstrap_mgr_name; EntityAuth auth; encode("allow profile bootstrap-mgr", auth.caps["mon"]); auth.key.create(g_ceph_context, CEPH_CRYPTO_AES); add_entity(name, auth); changed = true; } return changed; } bool AuthMonitor::_upgrade_format_to_mimic() { dout(1) << __func__ << " upgrading from format 2 to 3" << dendl; ceph_assert(format_version == 2); list<pair<EntityName,EntityAuth> > auth_lst; _generate_bootstrap_keys(&auth_lst); bool changed = false; for (auto &p : auth_lst) { if (mon.key_server.contains(p.first)) { continue; } int err = add_entity(p.first, p.second); ceph_assert(err == 0); changed = true; } return changed; } void AuthMonitor::upgrade_format() { constexpr unsigned int FORMAT_NONE = 0; constexpr unsigned int FORMAT_DUMPLING = 1; constexpr unsigned int FORMAT_LUMINOUS = 2; constexpr unsigned int FORMAT_MIMIC = 3; // when upgrading from the current format to a new format, ensure that // the new format doesn't break the older format. I.e., if a given format N // changes or adds something, ensure that when upgrading from N-1 to N+1, we // still observe the changes for format N if those have not been superseded // by N+1. unsigned int current = FORMAT_MIMIC; if (!mon.get_quorum_mon_features().contains_all( ceph::features::mon::FEATURE_LUMINOUS)) { // pre-luminous quorum current = FORMAT_DUMPLING; } else if (!mon.get_quorum_mon_features().contains_all( ceph::features::mon::FEATURE_MIMIC)) { // pre-mimic quorum current = FORMAT_LUMINOUS; } if (format_version >= current) { dout(20) << __func__ << " format " << format_version << " is current" << dendl; return; } // perform a rolling upgrade of the new format, if necessary. // i.e., if we are moving from format NONE to MIMIC, we will first upgrade // to DUMPLING, then to LUMINOUS, and finally to MIMIC, in several different // proposals. bool changed = false; if (format_version == FORMAT_NONE) { changed = _upgrade_format_to_dumpling(); } else if (format_version == FORMAT_DUMPLING) { changed = _upgrade_format_to_luminous(); } else if (format_version == FORMAT_LUMINOUS) { changed = _upgrade_format_to_mimic(); } if (changed) { // note new format dout(10) << __func__ << " proposing update from format " << format_version << " -> " << current << dendl; format_version = current; propose_pending(); } } void AuthMonitor::dump_info(Formatter *f) { /*** WARNING: do not include any privileged information here! ***/ f->open_object_section("auth"); f->dump_unsigned("first_committed", get_first_committed()); f->dump_unsigned("last_committed", get_last_committed()); f->dump_unsigned("num_secrets", mon.key_server.get_num_secrets()); f->close_section(); }
60,827
26.636529
102
cc
null
ceph-main/src/mon/AuthMonitor.h
// -*- 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. * */ #ifndef CEPH_AUTHMONITOR_H #define CEPH_AUTHMONITOR_H #include <map> #include <set> #include "global/global_init.h" #include "include/ceph_features.h" #include "include/types.h" #include "mon/PaxosService.h" #include "mon/MonitorDBStore.h" class MAuth; class KeyRing; class Monitor; #define MIN_GLOBAL_ID 0x1000 class AuthMonitor : public PaxosService { public: enum IncType { GLOBAL_ID, AUTH_DATA, }; struct Incremental { IncType inc_type; uint64_t max_global_id; uint32_t auth_type; ceph::buffer::list auth_data; Incremental() : inc_type(GLOBAL_ID), max_global_id(0), auth_type(0) {} void encode(ceph::buffer::list& bl, uint64_t features=-1) const { using ceph::encode; ENCODE_START(2, 2, bl); __u32 _type = (__u32)inc_type; encode(_type, bl); if (_type == GLOBAL_ID) { encode(max_global_id, bl); } else { encode(auth_type, bl); encode(auth_data, bl); } ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, bl); __u32 _type; decode(_type, bl); inc_type = (IncType)_type; ceph_assert(inc_type >= GLOBAL_ID && inc_type <= AUTH_DATA); if (_type == GLOBAL_ID) { decode(max_global_id, bl); } else { decode(auth_type, bl); decode(auth_data, bl); } DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const { f->dump_int("type", inc_type); f->dump_int("max_global_id", max_global_id); f->dump_int("auth_type", auth_type); f->dump_int("auth_data_len", auth_data.length()); } static void generate_test_instances(std::list<Incremental*>& ls) { ls.push_back(new Incremental); ls.push_back(new Incremental); ls.back()->inc_type = GLOBAL_ID; ls.back()->max_global_id = 1234; ls.push_back(new Incremental); ls.back()->inc_type = AUTH_DATA; ls.back()->auth_type = 12; ls.back()->auth_data.append("foo"); } }; struct auth_entity_t { EntityName name; EntityAuth auth; }; private: std::vector<Incremental> pending_auth; uint64_t max_global_id; uint64_t last_allocated_id; // these are protected by mon->auth_lock int mon_num = 0, mon_rank = 0; bool _upgrade_format_to_dumpling(); bool _upgrade_format_to_luminous(); bool _upgrade_format_to_mimic(); void upgrade_format() override; void export_keyring(KeyRing& keyring); int import_keyring(KeyRing& keyring); void push_cephx_inc(KeyServerData::Incremental& auth_inc) { Incremental inc; inc.inc_type = AUTH_DATA; encode(auth_inc, inc.auth_data); inc.auth_type = CEPH_AUTH_CEPHX; pending_auth.push_back(inc); } template<typename CAP_ENTITY_CLASS> bool _was_parsing_fine(const std::string& entity, const std::string& caps, std::ostream* out); /* validate mon/osd/mgr/mds caps; fail on unrecognized service/type */ bool valid_caps(const std::string& entity, const std::string& caps, std::ostream *out); bool valid_caps(const std::string& type, const ceph::buffer::list& bl, std::ostream *out) { auto p = bl.begin(); std::string v; try { using ceph::decode; decode(v, p); } catch (ceph::buffer::error& e) { *out << "corrupt capability encoding"; return false; } return valid_caps(type, v, out); } bool valid_caps(const std::map<std::string, std::string>& caps, std::ostream *out); void on_active() override; bool should_propose(double& delay) override; void get_initial_keyring(KeyRing *keyring); void create_initial_keys(KeyRing *keyring); void create_initial() override; void update_from_paxos(bool *need_bootstrap) override; void create_pending() override; // prepare a new pending bool prepare_global_id(MonOpRequestRef op); bool _should_increase_max_global_id(); ///< called under mon->auth_lock void increase_max_global_id(); uint64_t assign_global_id(bool should_increase_max); public: uint64_t _assign_global_id(); ///< called under mon->auth_lock void _set_mon_num_rank(int num, int rank); ///< called under mon->auth_lock private: bool prepare_used_pending_keys(MonOpRequestRef op); // propose pending update to peers void encode_pending(MonitorDBStore::TransactionRef t) override; void encode_full(MonitorDBStore::TransactionRef t) override; version_t get_trim_to() const override; bool preprocess_query(MonOpRequestRef op) override; // true if processed. bool prepare_update(MonOpRequestRef op) override; bool prep_auth(MonOpRequestRef op, bool paxos_writable); bool preprocess_command(MonOpRequestRef op); bool prepare_command(MonOpRequestRef op); void _encode_keyring(KeyRing& kr, const EntityName& entity, bufferlist& rdata, Formatter* fmtr, std::map<std::string, bufferlist>* wanted_caps=nullptr); void _encode_auth(const EntityName& entity, const EntityAuth& eauth, bufferlist& rdata, Formatter* fmtr, bool pending_key=false, std::map<std::string, bufferlist>* caps=nullptr); void _encode_key(const EntityName& entity, const EntityAuth& eauth, bufferlist& rdata, Formatter* fmtr, bool pending_key=false, std::map<std::string, bufferlist>* caps=nullptr); int _check_and_encode_caps(const std::map<std::string, std::string>& caps, std::map<std::string, bufferlist>& encoded_caps, std::stringstream& ss); int _update_or_create_entity(const EntityName& entity, const std::map<std::string, std::string>& caps, MonOpRequestRef op, std::stringstream& ds, bufferlist* rdata=nullptr, Formatter* fmtr=nullptr, bool create_entity=false); int _create_entity(const EntityName& entity, const std::map<std::string, std::string>& caps, MonOpRequestRef op, std::stringstream& ds, bufferlist* rdata, Formatter* fmtr); int _update_caps(const EntityName& entity, const std::map<std::string, std::string>& caps, MonOpRequestRef op, std::stringstream& ds, bufferlist* rdata, Formatter* fmtr); bool check_rotate(); void process_used_pending_keys(const std::map<EntityName,CryptoKey>& keys); bool entity_is_pending(EntityName& entity); int exists_and_matches_entity( const auth_entity_t& entity, bool has_secret, std::stringstream& ss); int exists_and_matches_entity( const EntityName& name, const EntityAuth& auth, const std::map<std::string,ceph::buffer::list>& caps, bool has_secret, std::stringstream& ss); int remove_entity(const EntityName &entity); int add_entity( const EntityName& name, const EntityAuth& auth); public: AuthMonitor(Monitor &mn, Paxos &p, const std::string& service_name) : PaxosService(mn, p, service_name), max_global_id(0), last_allocated_id(0) {} void pre_auth(MAuth *m); void tick() override; // check state, take actions int validate_osd_destroy( int32_t id, const uuid_d& uuid, EntityName& cephx_entity, EntityName& lockbox_entity, std::stringstream& ss); int do_osd_destroy( const EntityName& cephx_entity, const EntityName& lockbox_entity); int do_osd_new( const auth_entity_t& cephx_entity, const auth_entity_t& lockbox_entity, bool has_lockbox); int validate_osd_new( int32_t id, const uuid_d& uuid, const std::string& cephx_secret, const std::string& lockbox_secret, auth_entity_t& cephx_entity, auth_entity_t& lockbox_entity, std::stringstream& ss); void dump_info(ceph::Formatter *f); bool is_valid_cephx_key(const std::string& k) { if (k.empty()) return false; EntityAuth ea; try { ea.key.decode_base64(k); return true; } catch (ceph::buffer::error& e) { /* fallthrough */ } return false; } }; WRITE_CLASS_ENCODER_FEATURES(AuthMonitor::Incremental) #endif
8,296
29.72963
93
h
null
ceph-main/src/mon/CommandHandler.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) 2019 Red Hat Ltd * * 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 "CommandHandler.h" #include "common/strtol.h" #include "include/ceph_assert.h" #include <ostream> #include <string> #include <string_view> int CommandHandler::parse_bool(std::string_view str, bool* result, std::ostream& ss) { ceph_assert(result != nullptr); std::string interr; int64_t n = strict_strtoll(str.data(), 10, &interr); if (str == "false" || str == "no" || (interr.length() == 0 && n == 0)) { *result = false; return 0; } else if (str == "true" || str == "yes" || (interr.length() == 0 && n == 1)) { *result = true; return 0; } else { ss << "value must be false|no|0 or true|yes|1"; return -EINVAL; } }
1,083
23.636364
84
cc
null
ceph-main/src/mon/CommandHandler.h
// -*- 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) 2019 Red Hat Ltd * * 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. * */ #ifndef COMMAND_HANDLER_H_ #define COMMAND_HANDLER_H_ #include <ostream> #include <string_view> class CommandHandler { public: /** * Parse true|yes|1 style boolean string from `bool_str` * `result` must be non-null. * `ss` will be populated with error message on error. * * @return 0 on success, else -EINVAL */ int parse_bool(std::string_view str, bool* result, std::ostream& ss); }; #endif
823
21.888889
71
h
null
ceph-main/src/mon/ConfigMap.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <boost/algorithm/string/split.hpp> #include "ConfigMap.h" #include "crush/CrushWrapper.h" #include "common/entity_name.h" using namespace std::literals; using std::cerr; using std::cout; using std::dec; using std::hex; using std::list; using std::map; using std::make_pair; using std::ostream; using std::ostringstream; using std::pair; using std::set; using std::setfill; using std::string; using std::stringstream; using std::to_string; using std::vector; using std::unique_ptr; using ceph::bufferlist; using ceph::decode; using ceph::encode; using ceph::Formatter; using ceph::JSONFormatter; using ceph::mono_clock; using ceph::mono_time; using ceph::timespan_str; int MaskedOption::get_precision(const CrushWrapper *crush) { // 0 = most precise if (mask.location_type.size()) { int r = crush->get_type_id(mask.location_type); if (r >= 0) { return r; } // bad type name, ignore it } int num_types = crush->get_num_type_names(); if (mask.device_class.size()) { return num_types; } return num_types + 1; } void OptionMask::dump(Formatter *f) const { if (location_type.size()) { f->dump_string("location_type", location_type); f->dump_string("location_value", location_value); } if (device_class.size()) { f->dump_string("device_class", device_class); } } void MaskedOption::dump(Formatter *f) const { f->dump_string("name", opt->name); f->dump_string("value", raw_value); f->dump_string("level", Option::level_to_str(opt->level)); f->dump_bool("can_update_at_runtime", opt->can_update_at_runtime()); f->dump_string("mask", mask.to_str()); mask.dump(f); } ostream& operator<<(ostream& out, const MaskedOption& o) { out << o.opt->name; if (o.mask.location_type.size()) { out << "@" << o.mask.location_type << '=' << o.mask.location_value; } if (o.mask.device_class.size()) { out << "@class=" << o.mask.device_class; } return out; } // ---------- void Section::dump(Formatter *f) const { for (auto& i : options) { f->dump_object(i.first.c_str(), i.second); } } std::string Section::get_minimal_conf() const { std::string r; for (auto& i : options) { if (i.second.opt->has_flag(Option::FLAG_NO_MON_UPDATE) || i.second.opt->has_flag(Option::FLAG_MINIMAL_CONF)) { if (i.second.mask.empty()) { r += "\t"s + i.first + " = " + i.second.raw_value + "\n"; } else { r += "\t# masked option excluded: " + i.first + " = " + i.second.raw_value + "\n"; } } } return r; } // ------------ void ConfigMap::dump(Formatter *f) const { f->dump_object("global", global); f->open_object_section("by_type"); for (auto& i : by_type) { f->dump_object(i.first.c_str(), i.second); } f->close_section(); f->open_object_section("by_id"); for (auto& i : by_id) { f->dump_object(i.first.c_str(), i.second); } f->close_section(); } std::map<std::string,std::string,std::less<>> ConfigMap::generate_entity_map( const EntityName& name, const map<std::string,std::string>& crush_location, const CrushWrapper *crush, const std::string& device_class, std::map<std::string,pair<std::string,const MaskedOption*>> *src) { // global, then by type, then by name prefix component(s), then name. // name prefix components are .-separated, // e.g. client.a.b.c -> [global, client, client.a, client.a.b, client.a.b.c] vector<pair<string,Section*>> sections = { make_pair("global", &global) }; auto p = by_type.find(name.get_type_name()); if (p != by_type.end()) { sections.emplace_back(name.get_type_name(), &p->second); } vector<std::string> name_bits; boost::split(name_bits, name.to_str(), [](char c){ return c == '.'; }); std::string tname; for (unsigned p = 0; p < name_bits.size(); ++p) { if (p) { tname += '.'; } tname += name_bits[p]; auto q = by_id.find(tname); if (q != by_id.end()) { sections.push_back(make_pair(tname, &q->second)); } } std::map<std::string,std::string,std::less<>> out; MaskedOption *prev = nullptr; for (auto s : sections) { for (auto& i : s.second->options) { auto& o = i.second; // match against crush location, class if (o.mask.device_class.size() && o.mask.device_class != device_class) { continue; } if (o.mask.location_type.size()) { auto p = crush_location.find(o.mask.location_type); if (p == crush_location.end() || p->second != o.mask.location_value) { continue; } } if (prev && prev->opt->name != i.first) { prev = nullptr; } if (prev && prev->get_precision(crush) < o.get_precision(crush)) { continue; } out[i.first] = o.raw_value; if (src) { (*src)[i.first] = make_pair(s.first, &o); } prev = &o; } } return out; } bool ConfigMap::parse_mask( const std::string& who, std::string *section, OptionMask *mask) { vector<std::string> split; boost::split(split, who, [](char c){ return c == '/'; }); for (unsigned j = 0; j < split.size(); ++j) { auto& i = split[j]; if (i == "global") { *section = "global"; continue; } size_t delim = i.find(':'); if (delim != std::string::npos) { string k = i.substr(0, delim); if (k == "class") { mask->device_class = i.substr(delim + 1); } else { mask->location_type = k; mask->location_value = i.substr(delim + 1); } continue; } string type, id; auto dotpos = i.find('.'); if (dotpos != std::string::npos) { type = i.substr(0, dotpos); id = i.substr(dotpos + 1); } else { type = i; } if (EntityName::str_to_ceph_entity_type(type) == CEPH_ENTITY_TYPE_ANY) { return false; } *section = i; } return true; } void ConfigMap::parse_key( const std::string& key, std::string *name, std::string *who) { auto last_slash = key.rfind('/'); if (last_slash == std::string::npos) { *name = key; } else if (auto mgrpos = key.find("/mgr/"); mgrpos != std::string::npos) { *name = key.substr(mgrpos + 1); *who = key.substr(0, mgrpos); } else { *name = key.substr(last_slash + 1); *who = key.substr(0, last_slash); } } // -------------- void ConfigChangeSet::dump(Formatter *f) const { f->dump_int("version", version); f->dump_stream("timestamp") << stamp; f->dump_string("name", name); f->open_array_section("changes"); for (auto& i : diff) { f->open_object_section("change"); f->dump_string("name", i.first); if (i.second.first) { f->dump_string("previous_value", *i.second.first); } if (i.second.second) { f->dump_string("new_value", *i.second.second); } f->close_section(); } f->close_section(); } void ConfigChangeSet::print(ostream& out) const { out << "--- " << version << " --- " << stamp; if (name.size()) { out << " --- " << name; } out << " ---\n"; for (auto& i : diff) { if (i.second.first) { out << "- " << i.first << " = " << *i.second.first << "\n"; } if (i.second.second) { out << "+ " << i.first << " = " << *i.second.second << "\n"; } } }
7,234
23.777397
78
cc
null
ceph-main/src/mon/ConfigMap.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <map> #include <optional> #include <ostream> #include <string> #include "include/utime.h" #include "common/options.h" #include "common/entity_name.h" class CrushWrapper; // the precedence is thus: // // global // crush location (coarse to fine, ordered by type id) // daemon type (e.g., osd) // device class (osd only) // crush location (coarse to fine, ordered by type id) // daemon name (e.g., mds.foo) // // Note that this means that if we have // // config/host:foo/a = 1 // config/osd/rack:foo/a = 2 // // then we get a = 2. The osd-level config wins, even though rack // is less precise than host, because the crush limiters are only // resolved within a section (global, per-daemon, per-instance). struct OptionMask { std::string location_type, location_value; ///< matches crush_location std::string device_class; ///< matches device class bool empty() const { return location_type.size() == 0 && location_value.size() == 0 && device_class.size() == 0; } std::string to_str() const { std::string r; if (location_type.size()) { r += location_type + ":" + location_value; } if (device_class.size()) { if (r.size()) { r += "/"; } r += "class:" + device_class; } return r; } void dump(ceph::Formatter *f) const; }; struct MaskedOption { std::string raw_value; ///< raw, unparsed, unvalidated value const Option *opt; ///< the option OptionMask mask; std::unique_ptr<const Option> unknown_opt; ///< if fabricated for an unknown option MaskedOption(const Option *o, bool fab=false) : opt(o) { if (fab) { unknown_opt.reset(o); } } MaskedOption(MaskedOption&& o) { raw_value = std::move(o.raw_value); opt = o.opt; mask = std::move(o.mask); unknown_opt = std::move(o.unknown_opt); } const MaskedOption& operator=(const MaskedOption& o) = delete; const MaskedOption& operator=(MaskedOption&& o) = delete; /// return a precision metric (smaller is more precise) int get_precision(const CrushWrapper *crush); friend std::ostream& operator<<(std::ostream& out, const MaskedOption& o); void dump(ceph::Formatter *f) const; }; struct Section { std::multimap<std::string,MaskedOption> options; void clear() { options.clear(); } void dump(ceph::Formatter *f) const; std::string get_minimal_conf() const; }; struct ConfigMap { Section global; std::map<std::string,Section, std::less<>> by_type; std::map<std::string,Section, std::less<>> by_id; std::list<std::unique_ptr<Option>> stray_options; Section *find_section(const std::string& name) { if (name == "global") { return &global; } auto i = by_type.find(name); if (i != by_type.end()) { return &i->second; } i = by_id.find(name); if (i != by_id.end()) { return &i->second; } return nullptr; } void clear() { global.clear(); by_type.clear(); by_id.clear(); stray_options.clear(); } void dump(ceph::Formatter *f) const; std::map<std::string,std::string,std::less<>> generate_entity_map( const EntityName& name, const std::map<std::string,std::string>& crush_location, const CrushWrapper *crush, const std::string& device_class, std::map<std::string,std::pair<std::string,const MaskedOption*>> *src=0); void parse_key( const std::string& key, std::string *name, std::string *who); static bool parse_mask( const std::string& in, std::string *section, OptionMask *mask); }; struct ConfigChangeSet { version_t version; utime_t stamp; std::string name; // key -> (old value, new value) std::map<std::string,std::pair<std::optional<std::string>,std::optional<std::string>>> diff; void dump(ceph::Formatter *f) const; void print(std::ostream& out) const; };
3,994
24.774194
94
h
null
ceph-main/src/mon/ConfigMonitor.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include <boost/algorithm/string/predicate.hpp> #include "mon/Monitor.h" #include "mon/ConfigMonitor.h" #include "mon/KVMonitor.h" #include "mon/MgrMonitor.h" #include "mon/OSDMonitor.h" #include "messages/MConfig.h" #include "messages/MGetConfig.h" #include "messages/MMonCommand.h" #include "common/Formatter.h" #include "common/TextTable.h" #include "common/cmdparse.h" #include "include/stringify.h" #define dout_subsys ceph_subsys_mon #undef dout_prefix #define dout_prefix _prefix(_dout, mon, this) using namespace TOPNSPC::common; using namespace std::literals; using std::cerr; using std::cout; using std::dec; using std::hex; using std::list; using std::map; using std::make_pair; using std::ostream; using std::ostringstream; using std::pair; using std::set; using std::setfill; using std::string; using std::stringstream; using std::to_string; using std::vector; using std::unique_ptr; using ceph::bufferlist; using ceph::decode; using ceph::encode; using ceph::Formatter; using ceph::JSONFormatter; using ceph::mono_clock; using ceph::mono_time; using ceph::timespan_str; static ostream& _prefix(std::ostream *_dout, const Monitor &mon, const ConfigMonitor *hmon) { return *_dout << "mon." << mon.name << "@" << mon.rank << "(" << mon.get_state_name() << ").config "; } const string KEY_PREFIX("config/"); const string HISTORY_PREFIX("config-history/"); ConfigMonitor::ConfigMonitor(Monitor &m, Paxos &p, const string& service_name) : PaxosService(m, p, service_name) { } void ConfigMonitor::init() { dout(10) << __func__ << dendl; } void ConfigMonitor::create_initial() { dout(10) << __func__ << dendl; version = 0; pending.clear(); } void ConfigMonitor::update_from_paxos(bool *need_bootstrap) { if (version == get_last_committed()) { return; } version = get_last_committed(); dout(10) << __func__ << " " << version << dendl; load_config(); check_all_subs(); } void ConfigMonitor::create_pending() { dout(10) << " " << version << dendl; pending.clear(); pending_description.clear(); } void ConfigMonitor::encode_pending(MonitorDBStore::TransactionRef t) { dout(10) << " " << (version+1) << dendl; put_last_committed(t, version+1); // NOTE: caller should have done encode_pending_to_kvmon() and // kvmon->propose_pending() to commit the actual config changes. } void ConfigMonitor::encode_pending_to_kvmon() { // we need to pass our data through KVMonitor so that it is properly // versioned and shared with subscribers. for (auto& [key, value] : pending_cleanup) { if (pending.count(key) == 0) { derr << __func__ << " repair: adjusting config key '" << key << "'" << dendl; pending[key] = value; } } pending_cleanup.clear(); // TODO: record changed sections (osd, mds.foo, rack:bar, ...) string history = HISTORY_PREFIX + stringify(version+1) + "/"; { bufferlist metabl; ::encode(ceph_clock_now(), metabl); ::encode(pending_description, metabl); mon.kvmon()->enqueue_set(history, metabl); } for (auto& p : pending) { string key = KEY_PREFIX + p.first; auto q = current.find(p.first); if (q != current.end()) { if (p.second && *p.second == q->second) { continue; } mon.kvmon()->enqueue_set(history + "-" + p.first, q->second); } else if (!p.second) { continue; } if (p.second) { dout(20) << __func__ << " set " << key << dendl; mon.kvmon()->enqueue_set(key, *p.second); mon.kvmon()->enqueue_set(history + "+" + p.first, *p.second); } else { dout(20) << __func__ << " rm " << key << dendl; mon.kvmon()->enqueue_rm(key); } } } version_t ConfigMonitor::get_trim_to() const { // we don't actually need *any* old states, but keep a few. if (version > 5) { return version - 5; } return 0; } bool ConfigMonitor::preprocess_query(MonOpRequestRef op) { switch (op->get_req()->get_type()) { case MSG_MON_COMMAND: try { return preprocess_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); return true; } } return false; } bool ConfigMonitor::preprocess_command(MonOpRequestRef op) { auto m = op->get_req<MMonCommand>(); std::stringstream ss; int err = 0; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, get_last_committed()); return true; } string format = cmd_getval_or<string>(cmdmap, "format", "plain"); boost::scoped_ptr<Formatter> f(Formatter::create(format)); string prefix; cmd_getval(cmdmap, "prefix", prefix); bufferlist odata; if (prefix == "config help") { stringstream ss; string name; cmd_getval(cmdmap, "key", name); name = ConfFile::normalize_key_name(name); const Option *opt = g_conf().find_option(name); if (!opt) { opt = mon.mgrmon()->find_module_option(name); } if (opt) { if (f) { f->dump_object("option", *opt); } else { opt->print(&ss); } } else { ss << "configuration option '" << name << "' not recognized"; err = -ENOENT; goto reply; } if (f) { f->flush(odata); } else { odata.append(ss.str()); } } else if (prefix == "config ls") { ostringstream ss; if (f) { f->open_array_section("options"); } for (auto& i : ceph_options) { if (f) { f->dump_string("option", i.name); } else { ss << i.name << "\n"; } } for (auto& i : mon.mgrmon()->get_mgr_module_options()) { if (f) { f->dump_string("option", i.first); } else { ss << i.first << "\n"; } } if (f) { f->close_section(); f->flush(odata); } else { odata.append(ss.str()); } } else if (prefix == "config dump") { list<pair<string,Section*>> sections = { make_pair("global", &config_map.global) }; for (string type : { "mon", "mgr", "osd", "mds", "client" }) { auto i = config_map.by_type.find(type); if (i != config_map.by_type.end()) { sections.push_back(make_pair(i->first, &i->second)); } auto j = config_map.by_id.lower_bound(type); while (j != config_map.by_id.end() && j->first.find(type) == 0) { sections.push_back(make_pair(j->first, &j->second)); ++j; } } TextTable tbl; if (!f) { tbl.define_column("WHO", TextTable::LEFT, TextTable::LEFT); tbl.define_column("MASK", TextTable::LEFT, TextTable::LEFT); tbl.define_column("LEVEL", TextTable::LEFT, TextTable::LEFT); tbl.define_column("OPTION", TextTable::LEFT, TextTable::LEFT); tbl.define_column("VALUE", TextTable::LEFT, TextTable::LEFT); tbl.define_column("RO", TextTable::LEFT, TextTable::LEFT); } else { f->open_array_section("config"); } for (auto s : sections) { for (auto& i : s.second->options) { if (!f) { tbl << s.first; tbl << i.second.mask.to_str(); tbl << Option::level_to_str(i.second.opt->level); tbl << i.first; tbl << i.second.raw_value; tbl << (i.second.opt->can_update_at_runtime() ? "" : "*"); tbl << TextTable::endrow; } else { f->open_object_section("option"); f->dump_string("section", s.first); i.second.dump(f.get()); f->close_section(); } } } if (!f) { odata.append(stringify(tbl)); } else { f->close_section(); f->flush(odata); } } else if (prefix == "config get") { string who, name; cmd_getval(cmdmap, "who", who); EntityName entity; if (!entity.from_str(who) && !entity.from_str(who + ".")) { ss << "unrecognized entity '" << who << "'"; err = -EINVAL; goto reply; } map<string,string> crush_location; string device_class; if (entity.is_osd()) { mon.osdmon()->osdmap.crush->get_full_location(who, &crush_location); int id = atoi(entity.get_id().c_str()); const char *c = mon.osdmon()->osdmap.crush->get_item_class(id); if (c) { device_class = c; } dout(10) << __func__ << " crush_location " << crush_location << " class " << device_class << dendl; } std::map<std::string,pair<std::string,const MaskedOption*>> src; auto config = config_map.generate_entity_map( entity, crush_location, mon.osdmon()->osdmap.crush.get(), device_class, &src); if (cmd_getval(cmdmap, "key", name)) { name = ConfFile::normalize_key_name(name); const Option *opt = g_conf().find_option(name); if (!opt) { opt = mon.mgrmon()->find_module_option(name); } if (!opt) { ss << "unrecognized key '" << name << "'"; err = -ENOENT; goto reply; } if (opt->has_flag(Option::FLAG_NO_MON_UPDATE)) { // handle special options if (name == "fsid") { odata.append(stringify(mon.monmap->get_fsid())); odata.append("\n"); goto reply; } err = -EINVAL; ss << name << " is special and cannot be stored by the mon"; goto reply; } // get a single value auto p = config.find(name); if (p != config.end()) { odata.append(p->second); odata.append("\n"); goto reply; } if (!entity.is_client() && opt->daemon_value != Option::value_t{}) { odata.append(Option::to_str(opt->daemon_value)); } else { odata.append(Option::to_str(opt->value)); } odata.append("\n"); } else { // dump all (non-default) values for this entity TextTable tbl; if (!f) { tbl.define_column("WHO", TextTable::LEFT, TextTable::LEFT); tbl.define_column("MASK", TextTable::LEFT, TextTable::LEFT); tbl.define_column("LEVEL", TextTable::LEFT, TextTable::LEFT); tbl.define_column("OPTION", TextTable::LEFT, TextTable::LEFT); tbl.define_column("VALUE", TextTable::LEFT, TextTable::LEFT); tbl.define_column("RO", TextTable::LEFT, TextTable::LEFT); } else { f->open_object_section("config"); } auto p = config.begin(); auto q = src.begin(); for (; p != config.end(); ++p, ++q) { if (name.size() && p->first != name) { continue; } if (!f) { tbl << q->second.first; tbl << q->second.second->mask.to_str(); tbl << Option::level_to_str(q->second.second->opt->level); tbl << p->first; tbl << p->second; tbl << (q->second.second->opt->can_update_at_runtime() ? "" : "*"); tbl << TextTable::endrow; } else { f->open_object_section(p->first.c_str()); f->dump_string("value", p->second); f->dump_string("section", q->second.first); f->dump_object("mask", q->second.second->mask); f->dump_bool("can_update_at_runtime", q->second.second->opt->can_update_at_runtime()); f->close_section(); } } if (!f) { odata.append(stringify(tbl)); } else { f->close_section(); f->flush(odata); } } } else if (prefix == "config log") { int64_t num = 10; cmd_getval(cmdmap, "num", num); ostringstream ds; if (f) { f->open_array_section("changesets"); } for (version_t v = version; v > version - std::min(version, (version_t)num); --v) { ConfigChangeSet ch; load_changeset(v, &ch); if (f) { f->dump_object("changeset", ch); } else { ch.print(ds); } } if (f) { f->close_section(); f->flush(odata); } else { odata.append(ds.str()); } } else if (prefix == "config generate-minimal-conf") { ostringstream conf; conf << "# minimal ceph.conf for " << mon.monmap->get_fsid() << "\n"; // the basics conf << "[global]\n"; conf << "\tfsid = " << mon.monmap->get_fsid() << "\n"; conf << "\tmon_host = "; for (auto i = mon.monmap->mon_info.begin(); i != mon.monmap->mon_info.end(); ++i) { if (i != mon.monmap->mon_info.begin()) { conf << " "; } if (i->second.public_addrs.size() == 1 && i->second.public_addrs.front().is_legacy() && i->second.public_addrs.front().get_port() == CEPH_MON_PORT_LEGACY) { // if this is a legacy addr on the legacy default port, then // use the legacy-compatible formatting so that old clients // can use this config. new code will see the :6789 and correctly // interpret this as a v1 address. conf << i->second.public_addrs.get_legacy_str(); } else { conf << i->second.public_addrs; } } conf << "\n"; conf << config_map.global.get_minimal_conf(); for (auto m : { &config_map.by_type, &config_map.by_id }) { for (auto& i : *m) { auto s = i.second.get_minimal_conf(); if (s.size()) { conf << "\n[" << i.first << "]\n" << s; } } } odata.append(conf.str()); err = 0; } else { return false; } reply: mon.reply_command(op, err, ss.str(), odata, get_last_committed()); return true; } void ConfigMonitor::handle_get_config(MonOpRequestRef op) { auto m = op->get_req<MGetConfig>(); dout(10) << __func__ << " " << m->name << " host " << m->host << dendl; const OSDMap& osdmap = mon.osdmon()->osdmap; map<string,string> crush_location; osdmap.crush->get_full_location(m->host, &crush_location); auto out = config_map.generate_entity_map( m->name, crush_location, osdmap.crush.get(), m->device_class); dout(20) << " config is " << out << dendl; m->get_connection()->send_message(new MConfig{std::move(out)}); } bool ConfigMonitor::prepare_update(MonOpRequestRef op) { Message *m = op->get_req(); dout(7) << "prepare_update " << *m << " from " << m->get_orig_source_inst() << dendl; switch (m->get_type()) { case MSG_MON_COMMAND: try { return prepare_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); return true; } } return false; } bool ConfigMonitor::prepare_command(MonOpRequestRef op) { auto m = op->get_req<MMonCommand>(); std::stringstream ss; int err = -EINVAL; // make sure kv is writeable. if (!mon.kvmon()->is_writeable()) { dout(10) << __func__ << " waiting for kv mon to be writeable" << dendl; mon.kvmon()->wait_for_writeable(op, new C_RetryMessage(this, op)); return false; } cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, get_last_committed()); return true; } string prefix; cmd_getval(cmdmap, "prefix", prefix); bufferlist odata; if (prefix == "config set" || prefix == "config rm") { string who; string name, value; bool force = false; cmd_getval(cmdmap, "who", who); cmd_getval(cmdmap, "name", name); cmd_getval(cmdmap, "value", value); cmd_getval(cmdmap, "force", force); name = ConfFile::normalize_key_name(name); if (prefix == "config set" && !force) { const Option *opt = g_conf().find_option(name); if (!opt) { opt = mon.mgrmon()->find_module_option(name); } if (!opt) { ss << "unrecognized config option '" << name << "'"; err = -EINVAL; goto reply; } Option::value_t real_value; string errstr; err = opt->parse_value(value, &real_value, &errstr, &value); if (err < 0) { ss << "error parsing value: " << errstr; goto reply; } if (opt->has_flag(Option::FLAG_NO_MON_UPDATE)) { err = -EINVAL; ss << name << " is special and cannot be stored by the mon"; goto reply; } } string section; OptionMask mask; if (!ConfigMap::parse_mask(who, &section, &mask)) { ss << "unrecognized config target '" << who << "'"; err = -EINVAL; goto reply; } string key; if (section.size()) { key += section + "/"; } else { key += "global/"; } string mask_str = mask.to_str(); if (mask_str.size()) { key += mask_str + "/"; } key += name; if (prefix == "config set") { bufferlist bl; bl.append(value); pending[key] = bl; } else { pending[key].reset(); } goto update; } else if (prefix == "config reset") { int64_t revert_to = -1; cmd_getval(cmdmap, "num", revert_to); if (revert_to < 0 || revert_to > (int64_t)version) { err = -EINVAL; ss << "must specify a valid historical version to revert to; " << "see 'ceph config log' for a list of avialable configuration " << "historical versions"; goto reply; } if (revert_to == (int64_t)version) { err = 0; goto reply; } for (int64_t v = version; v > revert_to; --v) { ConfigChangeSet ch; load_changeset(v, &ch); for (auto& i : ch.diff) { if (i.second.first) { bufferlist bl; bl.append(*i.second.first); pending[i.first] = bl; } else if (i.second.second) { pending[i.first].reset(); } } } pending_description = string("reset to ") + stringify(revert_to); goto update; } else if (prefix == "config assimilate-conf") { ConfFile cf; bufferlist bl = m->get_data(); err = cf.parse_bufferlist(&bl, &ss); if (err < 0) { goto reply; } bool updated = false; ostringstream newconf; for (auto& [section, s] : cf) { dout(20) << __func__ << " [" << section << "]" << dendl; bool did_section = false; for (auto& [key, val] : s) { Option::value_t real_value; string value; string errstr; if (key.empty()) { continue; } // a known and worthy option? const Option *o = g_conf().find_option(key); if (!o) { o = mon.mgrmon()->find_module_option(key); } if (!o || (o->flags & Option::FLAG_NO_MON_UPDATE) || (o->flags & Option::FLAG_CLUSTER_CREATE)) { goto skip; } // normalize err = o->parse_value(val, &real_value, &errstr, &value); if (err < 0) { dout(20) << __func__ << " failed to parse " << key << " = '" << val << "'" << dendl; goto skip; } // does it conflict with an existing value? { const Section *s = config_map.find_section(section); if (s) { auto k = s->options.find(key); if (k != s->options.end()) { if (value != k->second.raw_value) { dout(20) << __func__ << " have " << key << " = " << k->second.raw_value << " (not " << value << ")" << dendl; goto skip; } dout(20) << __func__ << " already have " << key << " = " << k->second.raw_value << dendl; continue; } } } dout(20) << __func__ << " add " << key << " = " << value << " (" << val << ")" << dendl; { bufferlist bl; bl.append(value); pending[section + "/" + key] = bl; updated = true; } continue; skip: dout(20) << __func__ << " skip " << key << " = " << value << " (" << val << ")" << dendl; if (!did_section) { newconf << "\n[" << section << "]\n"; did_section = true; } newconf << "\t" << key << " = " << val << "\n"; } } odata.append(newconf.str()); if (updated) { goto update; } } else { ss << "unknown command " << prefix; err = -EINVAL; } reply: mon.reply_command(op, err, ss.str(), odata, get_last_committed()); return false; update: // see if there is an actual change auto p = pending.begin(); while (p != pending.end()) { auto q = current.find(p->first); if (p->second && q != current.end() && *p->second == q->second) { // set to same value p = pending.erase(p); } else if (!p->second && q == current.end()) { // erasing non-existent value p = pending.erase(p); } else { ++p; } } if (pending.empty()) { err = 0; goto reply; } // immediately propose *with* KV mon encode_pending_to_kvmon(); paxos.plug(); mon.kvmon()->propose_pending(); paxos.unplug(); force_immediate_propose(); wait_for_finished_proposal( op, new Monitor::C_Command( mon, op, 0, ss.str(), odata, get_last_committed() + 1)); return true; } void ConfigMonitor::tick() { if (!is_active() || !mon.is_leader()) { return; } dout(10) << __func__ << dendl; bool changed = false; if (!pending_cleanup.empty()) { changed = true; } if (changed && mon.kvmon()->is_writeable()) { paxos.plug(); encode_pending_to_kvmon(); mon.kvmon()->propose_pending(); paxos.unplug(); propose_pending(); } } void ConfigMonitor::on_active() { } void ConfigMonitor::load_config() { std::map<std::string,std::string> renamed_pacific = { { "mon_osd_blacklist_default_expire", "mon_osd_blocklist_default_expire" }, { "mon_mds_blacklist_interval", "mon_mds_blocklist_interval" }, { "mon_mgr_blacklist_interval", "mon_mgr_blocklist_interval" }, { "rbd_blacklist_on_break_lock", "rbd_blocklist_on_break_lock" }, { "rbd_blacklist_expire_seconds", "rbd_blocklist_expire_seconds" }, { "mds_session_blacklist_on_timeout", "mds_session_blocklist_on_timeout" }, { "mds_session_blacklist_on_evict", "mds_session_blocklist_on_evict" }, }; unsigned num = 0; KeyValueDB::Iterator it = mon.store->get_iterator(KV_PREFIX); it->lower_bound(KEY_PREFIX); config_map.clear(); current.clear(); pending_cleanup.clear(); while (it->valid() && it->key().compare(0, KEY_PREFIX.size(), KEY_PREFIX) == 0) { string key = it->key().substr(KEY_PREFIX.size()); string value = it->value().to_str(); current[key] = it->value(); string name; string who; config_map.parse_key(key, &name, &who); // has this option been renamed? { auto p = renamed_pacific.find(name); if (p != renamed_pacific.end()) { if (mon.monmap->min_mon_release >= ceph_release_t::pacific) { // schedule a cleanup pending_cleanup[key].reset(); pending_cleanup[who + "/" + p->second] = it->value(); } // continue loading under the new name name = p->second; } } const Option *opt = g_conf().find_option(name); if (!opt) { opt = mon.mgrmon()->find_module_option(name); } if (!opt) { dout(10) << __func__ << " unrecognized option '" << name << "'" << dendl; config_map.stray_options.push_back( std::unique_ptr<Option>( new Option(name, Option::TYPE_STR, Option::LEVEL_UNKNOWN))); opt = config_map.stray_options.back().get(); } string err; int r = opt->pre_validate(&value, &err); if (r < 0) { dout(10) << __func__ << " pre-validate failed on '" << name << "' = '" << value << "' for " << name << dendl; } MaskedOption mopt(opt); mopt.raw_value = value; string section_name; if (who.size() && !ConfigMap::parse_mask(who, &section_name, &mopt.mask)) { derr << __func__ << " invalid mask for key " << key << dendl; pending_cleanup[key].reset(); } else if (opt->has_flag(Option::FLAG_NO_MON_UPDATE)) { dout(10) << __func__ << " NO_MON_UPDATE option '" << name << "' = '" << value << "' for " << name << dendl; pending_cleanup[key].reset(); } else { if (section_name.empty()) { // we prefer global/$option instead of just $option derr << __func__ << " adding global/ prefix to key '" << key << "'" << dendl; pending_cleanup[key].reset(); pending_cleanup["global/"s + key] = it->value(); } Section *section = &config_map.global;; if (section_name.size() && section_name != "global") { if (section_name.find('.') != std::string::npos) { section = &config_map.by_id[section_name]; } else { section = &config_map.by_type[section_name]; } } section->options.insert(make_pair(name, std::move(mopt))); ++num; } it->next(); } dout(10) << __func__ << " got " << num << " keys" << dendl; // refresh our own config { const OSDMap& osdmap = mon.osdmon()->osdmap; map<string,string> crush_location; osdmap.crush->get_full_location(g_conf()->host, &crush_location); auto out = config_map.generate_entity_map( g_conf()->name, crush_location, osdmap.crush.get(), string{}); // no device class g_conf().set_mon_vals(g_ceph_context, out, nullptr); } } void ConfigMonitor::load_changeset(version_t v, ConfigChangeSet *ch) { ch->version = v; string prefix = HISTORY_PREFIX + stringify(v) + "/"; KeyValueDB::Iterator it = mon.store->get_iterator(KV_PREFIX); it->lower_bound(prefix); while (it->valid() && it->key().find(prefix) == 0) { if (it->key() == prefix) { bufferlist bl = it->value(); auto p = bl.cbegin(); try { decode(ch->stamp, p); decode(ch->name, p); } catch (ceph::buffer::error& e) { derr << __func__ << " failure decoding changeset " << v << dendl; } } else { char op = it->key()[prefix.length()]; string key = it->key().substr(prefix.length() + 1); if (op == '-') { ch->diff[key].first = it->value().to_str(); } else if (op == '+') { ch->diff[key].second = it->value().to_str(); } } it->next(); } } bool ConfigMonitor::refresh_config(MonSession *s) { const OSDMap& osdmap = mon.osdmon()->osdmap; map<string,string> crush_location; if (s->remote_host.size()) { osdmap.crush->get_full_location(s->remote_host, &crush_location); dout(10) << __func__ << " crush_location for remote_host " << s->remote_host << " is " << crush_location << dendl; } string device_class; if (s->name.is_osd()) { osdmap.crush->get_full_location(s->entity_name.to_str(), &crush_location); const char *c = osdmap.crush->get_item_class(s->name.num()); if (c) { device_class = c; dout(10) << __func__ << " device_class " << device_class << dendl; } } dout(20) << __func__ << " " << s->entity_name << " crush " << crush_location << " device_class " << device_class << dendl; auto out = config_map.generate_entity_map( s->entity_name, crush_location, osdmap.crush.get(), device_class); if (out == s->last_config && s->any_config) { dout(20) << __func__ << " no change, " << out << dendl; return false; } // removing this to hide sensitive data going into logs // leaving this for debugging purposes // dout(20) << __func__ << " " << out << dendl; s->last_config = std::move(out); s->any_config = true; return true; } bool ConfigMonitor::maybe_send_config(MonSession *s) { bool changed = refresh_config(s); dout(10) << __func__ << " to " << s->name << " " << (changed ? "(changed)" : "(unchanged)") << dendl; if (changed) { send_config(s); } return changed; } void ConfigMonitor::send_config(MonSession *s) { dout(10) << __func__ << " to " << s->name << dendl; auto m = new MConfig(s->last_config); s->con->send_message(m); } void ConfigMonitor::check_sub(MonSession *s) { if (!s->authenticated) { dout(20) << __func__ << " not authenticated " << s->entity_name << dendl; return; } auto p = s->sub_map.find("config"); if (p != s->sub_map.end()) { check_sub(p->second); } } void ConfigMonitor::check_sub(Subscription *sub) { dout(10) << __func__ << " next " << sub->next << " have " << version << dendl; if (sub->next <= version) { maybe_send_config(sub->session); if (sub->onetime) { mon.with_session_map([sub](MonSessionMap& session_map) { session_map.remove_sub(sub); }); } else { sub->next = version + 1; } } } void ConfigMonitor::check_all_subs() { dout(10) << __func__ << dendl; auto subs = mon.session_map.subs.find("config"); if (subs == mon.session_map.subs.end()) { return; } int updated = 0, total = 0; auto p = subs->second->begin(); while (!p.end()) { auto sub = *p; ++p; ++total; if (maybe_send_config(sub->session)) { ++updated; } } dout(10) << __func__ << " updated " << updated << " / " << total << dendl; }
27,839
26.347741
87
cc
null
ceph-main/src/mon/ConfigMonitor.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <optional> #include "ConfigMap.h" #include "mon/PaxosService.h" class MonSession; class ConfigMonitor : public PaxosService { version_t version = 0; ConfigMap config_map; std::map<std::string,std::optional<ceph::buffer::list>> pending; std::string pending_description; std::map<std::string,std::optional<ceph::buffer::list>> pending_cleanup; std::map<std::string,ceph::buffer::list> current; void encode_pending_to_kvmon(); public: ConfigMonitor(Monitor &m, Paxos &p, const std::string& service_name); void init() override; void load_config(); void load_changeset(version_t v, ConfigChangeSet *ch); bool preprocess_query(MonOpRequestRef op) override; bool prepare_update(MonOpRequestRef op) override; bool preprocess_command(MonOpRequestRef op); bool prepare_command(MonOpRequestRef op); void handle_get_config(MonOpRequestRef op); void create_initial() override; void update_from_paxos(bool *need_bootstrap) override; void create_pending() override; void encode_pending(MonitorDBStore::TransactionRef t) override; version_t get_trim_to() const override; void encode_full(MonitorDBStore::TransactionRef t) override { } void on_active() override; void tick() override; bool refresh_config(MonSession *s); bool maybe_send_config(MonSession *s); void send_config(MonSession *s); void check_sub(MonSession *s); void check_sub(Subscription *sub); void check_all_subs(); };
1,565
25.542373
74
h
null
ceph-main/src/mon/ConnectionTracker.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) 2019 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 "ConnectionTracker.h" #include "common/Formatter.h" #include "common/dout.h" #include "include/ceph_assert.h" #define dout_subsys ceph_subsys_mon #undef dout_prefix #define dout_prefix _prefix(_dout, rank, epoch, version) static std::ostream& _prefix(std::ostream *_dout, int rank, epoch_t epoch, uint64_t version) { return *_dout << "rank: " << rank << " version: "<< version << " ConnectionTracker(" << epoch << ") "; } std::ostream& operator<<(std::ostream&o, const ConnectionReport& c) { o << "rank=" << c.rank << ",epoch=" << c.epoch << ",version=" << c.epoch_version << ", current links: " << c.current << ", history: " << c.history; return o; } std::ostream& operator<<(std::ostream& o, const ConnectionTracker& c) { o << "rank=" << c.rank << ", epoch=" << c.epoch << ", version=" << c.version << ", half_life=" << c.half_life << ", reports: " << c.peer_reports; return o; } ConnectionReport *ConnectionTracker::reports(int p) { auto i = peer_reports.find(p); if (i == peer_reports.end()) { ceph_assert(p != rank); auto[j,k] = peer_reports.insert(std::pair<int,ConnectionReport>(p,ConnectionReport())); i = j; } return &i->second; } const ConnectionReport *ConnectionTracker::reports(int p) const { auto i = peer_reports.find(p); if (i == peer_reports.end()) { return NULL; } return &i->second; } void ConnectionTracker::receive_peer_report(const ConnectionTracker& o) { ldout(cct, 30) << __func__ << dendl; for (auto& i : o.peer_reports) { const ConnectionReport& report = i.second; if (i.first == rank) continue; ConnectionReport& existing = *reports(i.first); if (report.epoch > existing.epoch || (report.epoch == existing.epoch && report.epoch_version > existing.epoch_version)) { ldout(cct, 30) << " new peer_report is more updated" << dendl; ldout(cct, 30) << "existing: " << existing << dendl; ldout(cct, 30) << "new: " << report << dendl; existing = report; } } encoding.clear(); } bool ConnectionTracker::increase_epoch(epoch_t e) { ldout(cct, 30) << __func__ << " to " << e << dendl; if (e > epoch) { my_reports.epoch_version = version = 0; my_reports.epoch = epoch = e; peer_reports[rank] = my_reports; encoding.clear(); return true; } return false; } void ConnectionTracker::increase_version() { ldout(cct, 30) << __func__ << " to " << version+1 << dendl; encoding.clear(); ++version; my_reports.epoch_version = version; peer_reports[rank] = my_reports; if ((version % persist_interval) == 0 ) { ldout(cct, 30) << version << " % " << persist_interval << " == 0" << dendl; owner->persist_connectivity_scores(); } } void ConnectionTracker::report_live_connection(int peer_rank, double units_alive) { ldout(cct, 30) << __func__ << " peer_rank: " << peer_rank << " units_alive: " << units_alive << dendl; ldout(cct, 30) << "my_reports before: " << my_reports << dendl; if (peer_rank == rank) { lderr(cct) << "Got a report from my own rank, hopefully this is startup weirdness, dropping" << dendl; return; } // we need to "auto-initialize" to 1, do shenanigans auto i = my_reports.history.find(peer_rank); if (i == my_reports.history.end()) { ldout(cct, 30) << "couldn't find: " << peer_rank << " in my_reports.history" << "... inserting: " << "(" << peer_rank << ", 1" << dendl; auto[j,k] = my_reports.history.insert(std::pair<int,double>(peer_rank,1.0)); i = j; } double& pscore = i->second; ldout(cct, 30) << "adding new pscore to my_reports" << dendl; pscore = pscore * (1 - units_alive / (2 * half_life)) + (units_alive / (2 * half_life)); pscore = std::min(pscore, 1.0); my_reports.current[peer_rank] = true; increase_version(); ldout(cct, 30) << "my_reports after: " << my_reports << dendl; } void ConnectionTracker::report_dead_connection(int peer_rank, double units_dead) { ldout(cct, 30) << __func__ << " peer_rank: " << peer_rank << " units_dead: " << units_dead << dendl; ldout(cct, 30) << "my_reports before: " << my_reports << dendl; if (peer_rank == rank) { lderr(cct) << "Got a report from my own rank, hopefully this is startup weirdness, dropping" << dendl; return; } // we need to "auto-initialize" to 1, do shenanigans auto i = my_reports.history.find(peer_rank); if (i == my_reports.history.end()) { ldout(cct, 30) << "couldn't find: " << peer_rank << " in my_reports.history" << "... inserting: " << "(" << peer_rank << ", 1" << dendl; auto[j,k] = my_reports.history.insert(std::pair<int,double>(peer_rank,1.0)); i = j; } double& pscore = i->second; ldout(cct, 30) << "adding new pscore to my_reports" << dendl; pscore = pscore * (1 - units_dead / (2 * half_life)) - (units_dead / (2*half_life)); pscore = std::max(pscore, 0.0); my_reports.current[peer_rank] = false; increase_version(); ldout(cct, 30) << "my_reports after: " << my_reports << dendl; } void ConnectionTracker::get_total_connection_score(int peer_rank, double *rating, int *live_count) const { ldout(cct, 30) << __func__ << dendl; *rating = 0; *live_count = 0; double rate = 0; int live = 0; for (const auto& i : peer_reports) { // loop through all the scores if (i.first == peer_rank) { // ... except the ones it has for itself, of course! continue; } const auto& report = i.second; auto score_i = report.history.find(peer_rank); auto live_i = report.current.find(peer_rank); if (score_i != report.history.end()) { if (live_i->second) { rate += score_i->second; ++live; } } } *rating = rate; *live_count = live; } void ConnectionTracker::notify_rank_changed(int new_rank) { ldout(cct, 20) << __func__ << " to " << new_rank << dendl; if (new_rank == rank) return; ldout(cct, 20) << "peer_reports before: " << peer_reports << dendl; peer_reports.erase(rank); peer_reports.erase(new_rank); my_reports.rank = new_rank; rank = new_rank; encoding.clear(); ldout(cct, 20) << "peer_reports after: " << peer_reports << dendl; increase_version(); } void ConnectionTracker::notify_rank_removed(int rank_removed, int new_rank) { ldout(cct, 20) << __func__ << " " << rank_removed << " new_rank: " << new_rank << dendl; ldout(cct, 20) << "my_reports before: " << my_reports << dendl; ldout(cct, 20) << "peer_reports before: " << peer_reports << dendl; ldout(cct, 20) << "my rank before: " << rank << dendl; encoding.clear(); size_t starting_size_current = my_reports.current.size(); // Lets adjust everything in my report. my_reports.current.erase(rank_removed); my_reports.history.erase(rank_removed); auto ci = my_reports.current.upper_bound(rank_removed); auto hi = my_reports.history.upper_bound(rank_removed); while (ci != my_reports.current.end()) { ceph_assert(ci->first == hi->first); my_reports.current[ci->first - 1] = ci->second; my_reports.history[hi->first - 1] = hi->second; my_reports.current.erase(ci++); my_reports.history.erase(hi++); } ceph_assert((my_reports.current.size() == starting_size_current) || (my_reports.current.size() + 1 == starting_size_current)); size_t starting_size = peer_reports.size(); auto pi = peer_reports.upper_bound(rank_removed); // Remove the target rank and adjust everything that comes after. // Note that we don't adjust current and history for our peer_reports // because it is better to rely on our peers on that information. peer_reports.erase(rank_removed); while (pi != peer_reports.end()) { peer_reports[pi->first - 1] = pi->second; // copy content of next rank to ourself. peer_reports.erase(pi++); // destroy our next rank and move on. } ceph_assert((peer_reports.size() == starting_size) || (peer_reports.size() + 1 == starting_size)); if (rank_removed < rank) { // if the rank removed is lower than us, we need to adjust. --rank; my_reports.rank = rank; // also adjust my_reports.rank. } ldout(cct, 20) << "my rank after: " << rank << dendl; ldout(cct, 20) << "peer_reports after: " << peer_reports << dendl; ldout(cct, 20) << "my_reports after: " << my_reports << dendl; //check if the new_rank from monmap is equal to our adjusted rank. ceph_assert(rank == new_rank); increase_version(); } bool ConnectionTracker::is_clean(int mon_rank, int monmap_size) { ldout(cct, 30) << __func__ << dendl; // check consistency between our rank according // to monmap and our rank according to our report. if (rank != mon_rank || my_reports.rank != mon_rank) { return false; } else if (!peer_reports.empty()){ // if peer_report max rank is greater than monmap max rank // then there is a problem. if (peer_reports.rbegin()->first > monmap_size - 1) return false; } return true; } void ConnectionTracker::encode(bufferlist &bl) const { ENCODE_START(1, 1, bl); encode(rank, bl); encode(epoch, bl); encode(version, bl); encode(half_life, bl); encode(peer_reports, bl); ENCODE_FINISH(bl); } void ConnectionTracker::decode(bufferlist::const_iterator& bl) { clear_peer_reports(); encoding.clear(); DECODE_START(1, bl); decode(rank, bl); decode(epoch, bl); decode(version, bl); decode(half_life, bl); decode(peer_reports, bl); DECODE_FINISH(bl); if (rank >=0) my_reports = peer_reports[rank]; } const bufferlist& ConnectionTracker::get_encoded_bl() { if (!encoding.length()) { encode(encoding); } return encoding; } void ConnectionReport::dump(ceph::Formatter *f) const { f->dump_int("rank", rank); f->dump_int("epoch", epoch); f->dump_int("version", epoch_version); f->open_object_section("peer_scores"); for (auto i : history) { f->open_object_section("peer"); f->dump_int("peer_rank", i.first); f->dump_float("peer_score", i.second); f->dump_bool("peer_alive", current.find(i.first)->second); f->close_section(); } f->close_section(); // peer scores } void ConnectionReport::generate_test_instances(std::list<ConnectionReport*>& o) { o.push_back(new ConnectionReport); o.push_back(new ConnectionReport); o.back()->rank = 1; o.back()->epoch = 2; o.back()->epoch_version = 3; o.back()->current[0] = true; o.back()->history[0] = .4; } void ConnectionTracker::dump(ceph::Formatter *f) const { f->dump_int("rank", rank); f->dump_int("epoch", epoch); f->dump_int("version", version); f->dump_float("half_life", half_life); f->dump_int("persist_interval", persist_interval); f->open_object_section("reports"); for (const auto& i : peer_reports) { f->open_object_section("report"); i.second.dump(f); f->close_section(); } f->close_section(); // reports } void ConnectionTracker::generate_test_instances(std::list<ConnectionTracker*>& o) { o.push_back(new ConnectionTracker); o.push_back(new ConnectionTracker); ConnectionTracker *e = o.back(); e->rank = 2; e->epoch = 3; e->version = 4; e->peer_reports[0]; e->peer_reports[1]; e->my_reports = e->peer_reports[2]; }
11,500
30.770718
106
cc
null
ceph-main/src/mon/ConnectionTracker.h
// -*- 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) 2019 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. * */ #pragma once #include "include/types.h" struct ConnectionReport { int rank = -1; // mon rank this state belongs to std::map<int, bool> current; // true if connected to the other mon std::map<int, double> history; // [0-1]; the connection reliability epoch_t epoch = 0; // the (local) election epoch the ConnectionReport came from uint64_t epoch_version = 0; // version of the ConnectionReport within the epoch void encode(bufferlist& bl) const { ENCODE_START(1, 1, bl); encode(rank, bl); encode(current, bl); encode(history, bl); encode(epoch, bl); encode(epoch_version, bl); ENCODE_FINISH(bl); } void decode(bufferlist::const_iterator& bl) { DECODE_START(1, bl); decode(rank, bl); decode(current, bl); decode(history, bl); decode(epoch, bl); decode(epoch_version, bl); DECODE_FINISH(bl); } bool operator==(const ConnectionReport& o) const { return o.rank == rank && o.current == current && o.history == history && o.epoch == epoch && o.epoch_version == epoch_version; } friend std::ostream& operator<<(std::ostream&o, const ConnectionReport& c); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<ConnectionReport*>& o); }; WRITE_CLASS_ENCODER(ConnectionReport); class RankProvider { public: /** * Get the rank of the running daemon. * It can be -1, meaning unknown/invalid, or it * can be >1. * You should not invoke the function get_total_connection_score() * with an unknown rank. */ virtual int get_my_rank() const = 0; /** * Asks our owner to encode us and persist it to disk. * Presently we do this every tenth update. */ virtual void persist_connectivity_scores() = 0; virtual ~RankProvider() {} }; class ConnectionTracker { public: /** * Receive a report from a peer and update our internal state * if the peer has newer data. */ void receive_peer_report(const ConnectionTracker& o); /** * Bump up the epoch to the specified number. * Validates that it is > current epoch and resets * version to 0; returns false if not. */ bool increase_epoch(epoch_t e); /** * Bump up the version within our epoch. * If the new version is a multiple of ten, we also persist it. */ void increase_version(); /** * Report a connection to a peer rank has been considered alive for * the given time duration. We assume the units_alive is <= the time * since the previous reporting call. * (Or, more precisely, we assume that the total amount of time * passed in is less than or equal to the time which has actually * passed -- you can report a 10-second death immediately followed * by reporting 5 seconds of liveness if your metrics are delayed.) */ void report_live_connection(int peer_rank, double units_alive); /** * Report a connection to a peer rank has been considered dead for * the given time duration, analogous to that above. */ void report_dead_connection(int peer_rank, double units_dead); /** * Set the half-life for dropping connection state * out of the ongoing score. * Whenever you add a new data point: * new_score = old_score * ( 1 - units / (2d)) + (units/(2d)) * where units is the units reported alive (for dead, you subtract them). */ void set_half_life(double d) { half_life = d; } /** * Get the total connection score of a rank across * all peers, and the count of how many electors think it's alive. * For this summation, if a rank reports a peer as down its score is zero. */ void get_total_connection_score(int peer_rank, double *rating, int *live_count) const; /** * Check if our ranks are clean and make * sure there are no extra peer_report lingering. * In the future we also want to check the reports * current and history of each peer_report. */ bool is_clean(int mon_rank, int monmap_size); /** * Encode this ConnectionTracker. Useful both for storing on disk * and for sending off to peers for decoding and import * with receive_peer_report() above. */ void encode(bufferlist &bl) const; void decode(bufferlist::const_iterator& bl); /** * Get a bufferlist containing the ConnectionTracker. * This is like encode() but holds a copy so it * doesn't re-encode on every invocation. */ const bufferlist& get_encoded_bl(); private: epoch_t epoch; uint64_t version; std::map<int,ConnectionReport> peer_reports; ConnectionReport my_reports; double half_life; RankProvider *owner; int rank; int persist_interval; bufferlist encoding; CephContext *cct; int get_my_rank() const { return rank; } ConnectionReport *reports(int p); const ConnectionReport *reports(int p) const; void clear_peer_reports() { encoding.clear(); peer_reports.clear(); my_reports = ConnectionReport(); my_reports.rank = rank; } public: ConnectionTracker() : epoch(0), version(0), half_life(12*60*60), owner(NULL), rank(-1), persist_interval(10) { } ConnectionTracker(RankProvider *o, int rank, double hl, int persist_i, CephContext *c) : epoch(0), version(0), half_life(hl), owner(o), rank(rank), persist_interval(persist_i), cct(c) { my_reports.rank = rank; } ConnectionTracker(const bufferlist& bl, CephContext *c) : epoch(0), version(0), half_life(0), owner(NULL), rank(-1), persist_interval(10), cct(c) { auto bi = bl.cbegin(); decode(bi); } ConnectionTracker(const ConnectionTracker& o) : epoch(o.epoch), version(o.version), half_life(o.half_life), owner(o.owner), rank(o.rank), persist_interval(o.persist_interval), cct(o.cct) { peer_reports = o.peer_reports; my_reports = o.my_reports; } void notify_reset() { clear_peer_reports(); } void set_rank(int new_rank) { rank = new_rank; my_reports.rank = rank; } void notify_rank_changed(int new_rank); void notify_rank_removed(int rank_removed, int new_rank); friend std::ostream& operator<<(std::ostream& o, const ConnectionTracker& c); friend ConnectionReport *get_connection_reports(ConnectionTracker& ct); friend std::map<int,ConnectionReport> *get_peer_reports(ConnectionTracker& ct); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<ConnectionTracker*>& o); }; WRITE_CLASS_ENCODER(ConnectionTracker);
6,799
32.009709
81
h
null
ceph-main/src/mon/CreatingPGs.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <map> #include <set> #include <vector> #include "include/encoding.h" #include "include/utime.h" #include "osd/osd_types.h" struct creating_pgs_t { epoch_t last_scan_epoch = 0; struct pg_create_info { epoch_t create_epoch; utime_t create_stamp; // NOTE: pre-octopus instances of this class will have a // zeroed-out history std::vector<int> up; int up_primary = -1; std::vector<int> acting; int acting_primary = -1; pg_history_t history; PastIntervals past_intervals; void encode(ceph::buffer::list& bl, uint64_t features) const { using ceph::encode; if (!HAVE_FEATURE(features, SERVER_OCTOPUS)) { // was pair<epoch_t,utime_t> prior to octopus encode(create_epoch, bl); encode(create_stamp, bl); return; } ENCODE_START(1, 1, bl); encode(create_epoch, bl); encode(create_stamp, bl); encode(up, bl); encode(up_primary, bl); encode(acting, bl); encode(acting_primary, bl); encode(history, bl); encode(past_intervals, bl); ENCODE_FINISH(bl); } void decode_legacy(ceph::buffer::list::const_iterator& p) { using ceph::decode; decode(create_epoch, p); decode(create_stamp, p); } void decode(ceph::buffer::list::const_iterator& p) { using ceph::decode; DECODE_START(1, p); decode(create_epoch, p); decode(create_stamp, p); decode(up, p); decode(up_primary, p); decode(acting, p); decode(acting_primary, p); decode(history, p); decode(past_intervals, p); DECODE_FINISH(p); } void dump(ceph::Formatter *f) const { f->dump_unsigned("create_epoch", create_epoch); f->dump_stream("create_stamp") << create_stamp; f->open_array_section("up"); for (auto& i : up) { f->dump_unsigned("osd", i); } f->close_section(); f->dump_int("up_primary", up_primary); f->open_array_section("acting"); for (auto& i : acting) { f->dump_unsigned("osd", i); } f->close_section(); f->dump_int("acting_primary", up_primary); f->dump_object("pg_history", history); f->dump_object("past_intervals", past_intervals); } pg_create_info() {} pg_create_info(epoch_t e, utime_t t) : create_epoch(e), create_stamp(t) { // NOTE: we don't initialize the other fields here; see // OSDMonitor::update_pending_pgs() } }; /// pgs we are currently creating std::map<pg_t, pg_create_info> pgs; struct pool_create_info { epoch_t created; utime_t modified; uint64_t start = 0; uint64_t end = 0; bool done() const { return start >= end; } void encode(ceph::buffer::list& bl) const { using ceph::encode; encode(created, bl); encode(modified, bl); encode(start, bl); encode(end, bl); } void decode(ceph::buffer::list::const_iterator& p) { using ceph::decode; decode(created, p); decode(modified, p); decode(start, p); decode(end, p); } }; /// queue of pgs we still need to create (poolid -> <created, set of ps>) std::map<int64_t,pool_create_info> queue; /// pools that exist in the osdmap for which at least one pg has been created std::set<int64_t> created_pools; bool still_creating_pool(int64_t poolid) { for (auto& i : pgs) { if (i.first.pool() == poolid) { return true; } } if (queue.count(poolid)) { return true; } return false; } void create_pool(int64_t poolid, uint32_t pg_num, epoch_t created, utime_t modified) { ceph_assert(created_pools.count(poolid) == 0); auto& c = queue[poolid]; c.created = created; c.modified = modified; c.end = pg_num; created_pools.insert(poolid); } unsigned remove_pool(int64_t removed_pool) { const unsigned total = pgs.size(); auto first = pgs.lower_bound(pg_t{0, (uint64_t)removed_pool}); auto last = pgs.lower_bound(pg_t{0, (uint64_t)removed_pool + 1}); pgs.erase(first, last); created_pools.erase(removed_pool); queue.erase(removed_pool); return total - pgs.size(); } void encode(ceph::buffer::list& bl, uint64_t features) const { unsigned v = 3; if (!HAVE_FEATURE(features, SERVER_OCTOPUS)) { v = 2; } ENCODE_START(v, 1, bl); encode(last_scan_epoch, bl); encode(pgs, bl, features); encode(created_pools, bl); encode(queue, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(3, bl); decode(last_scan_epoch, bl); if (struct_v >= 3) { decode(pgs, bl); } else { // legacy pg encoding pgs.clear(); uint32_t num; decode(num, bl); while (num--) { pg_t pgid; decode(pgid, bl); pgs[pgid].decode_legacy(bl); } } decode(created_pools, bl); if (struct_v >= 2) decode(queue, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const { f->dump_unsigned("last_scan_epoch", last_scan_epoch); f->open_array_section("creating_pgs"); for (auto& pg : pgs) { f->open_object_section("pg"); f->dump_stream("pgid") << pg.first; f->dump_object("pg_create_info", pg.second); f->close_section(); } f->close_section(); f->open_array_section("queue"); for (auto& p : queue) { f->open_object_section("pool"); f->dump_unsigned("pool", p.first); f->dump_unsigned("created", p.second.created); f->dump_stream("modified") << p.second.modified; f->dump_unsigned("ps_start", p.second.start); f->dump_unsigned("ps_end", p.second.end); f->close_section(); } f->close_section(); f->open_array_section("created_pools"); for (auto pool : created_pools) { f->dump_unsigned("pool", pool); } f->close_section(); } static void generate_test_instances(std::list<creating_pgs_t*>& o) { auto c = new creating_pgs_t; c->last_scan_epoch = 17; c->pgs.emplace(pg_t{42, 2}, pg_create_info(31, utime_t{891, 113})); c->pgs.emplace(pg_t{44, 2}, pg_create_info(31, utime_t{891, 113})); c->created_pools = {0, 1}; o.push_back(c); c = new creating_pgs_t; c->last_scan_epoch = 18; c->pgs.emplace(pg_t{42, 3}, pg_create_info(31, utime_t{891, 113})); c->created_pools = {}; o.push_back(c); } }; WRITE_CLASS_ENCODER_FEATURES(creating_pgs_t::pg_create_info) WRITE_CLASS_ENCODER(creating_pgs_t::pool_create_info) WRITE_CLASS_ENCODER_FEATURES(creating_pgs_t)
6,662
27.353191
79
h
null
ceph-main/src/mon/ElectionLogic.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 "ElectionLogic.h" #include "include/ceph_assert.h" #include "common/dout.h" #define dout_subsys ceph_subsys_mon #undef dout_prefix #define dout_prefix _prefix(_dout, epoch, elector) using std::cerr; using std::cout; using std::dec; using std::hex; using std::list; using std::map; using std::make_pair; using std::ostream; using std::ostringstream; using std::pair; using std::set; using std::setfill; using std::string; using std::stringstream; using std::to_string; using std::vector; using std::unique_ptr; using ceph::bufferlist; using ceph::decode; using ceph::encode; using ceph::Formatter; using ceph::JSONFormatter; using ceph::mono_clock; using ceph::mono_time; using ceph::timespan_str; static ostream& _prefix(std::ostream *_dout, epoch_t epoch, ElectionOwner* elector) { return *_dout << "paxos." << elector->get_my_rank() << ").electionLogic(" << epoch << ") "; } void ElectionLogic::init() { epoch = elector->read_persisted_epoch(); if (!epoch) { ldout(cct, 1) << "init, first boot, initializing epoch at 1 " << dendl; epoch = 1; } else if (epoch % 2) { ldout(cct, 1) << "init, last seen epoch " << epoch << ", mid-election, bumping" << dendl; ++epoch; elector->persist_epoch(epoch); } else { ldout(cct, 1) << "init, last seen epoch " << epoch << dendl; } } void ElectionLogic::bump_epoch(epoch_t e) { ldout(cct, 10) << __func__ << " to " << e << dendl; ceph_assert(epoch <= e); epoch = e; peer_tracker->increase_epoch(e); elector->persist_epoch(epoch); // clear up some state electing_me = false; acked_me.clear(); elector->notify_bump_epoch(); } void ElectionLogic::declare_standalone_victory() { assert(elector->paxos_size() == 1 && elector->get_my_rank() == 0); init(); bump_epoch(epoch+1); } void ElectionLogic::clear_live_election_state() { leader_acked = -1; electing_me = false; reset_stable_tracker(); leader_peer_tracker.reset(); } void ElectionLogic::reset_stable_tracker() { stable_peer_tracker.reset(new ConnectionTracker(*peer_tracker)); } void ElectionLogic::connectivity_bump_epoch_in_election(epoch_t mepoch) { ldout(cct, 30) << __func__ << " to " << mepoch << dendl; ceph_assert(mepoch > epoch); bump_epoch(mepoch); reset_stable_tracker(); double lscore, my_score; my_score = connectivity_election_score(elector->get_my_rank()); lscore = connectivity_election_score(leader_acked); if (my_score > lscore) { leader_acked = -1; leader_peer_tracker.reset(); } } void ElectionLogic::start() { if (!participating) { ldout(cct, 0) << "not starting new election -- not participating" << dendl; return; } ldout(cct, 5) << "start -- can i be leader?" << dendl; acked_me.clear(); init(); // start by trying to elect me if (epoch % 2 == 0) { bump_epoch(epoch+1); // odd == election cycle } else { elector->validate_store(); } acked_me.insert(elector->get_my_rank()); clear_live_election_state(); reset_stable_tracker(); electing_me = true; bufferlist bl; if (strategy == CONNECTIVITY) { stable_peer_tracker->encode(bl); } elector->propose_to_peers(epoch, bl); elector->_start(); } void ElectionLogic::defer(int who) { if (strategy == CLASSIC) { ldout(cct, 5) << "defer to " << who << dendl; ceph_assert(who < elector->get_my_rank()); } else { ldout(cct, 5) << "defer to " << who << ", disallowed_leaders=" << elector->get_disallowed_leaders() << dendl; ceph_assert(!elector->get_disallowed_leaders().count(who)); } if (electing_me) { // drop out acked_me.clear(); electing_me = false; } // ack them leader_acked = who; elector->_defer_to(who); } void ElectionLogic::end_election_period() { ldout(cct, 5) << "election period ended" << dendl; // did i win? if (electing_me && acked_me.size() > (elector->paxos_size() / 2)) { // i win declare_victory(); } else { // whoever i deferred to didn't declare victory quickly enough. if (elector->ever_participated()) start(); else elector->reset_election(); } } void ElectionLogic::declare_victory() { ldout(cct, 5) << "I win! acked_me=" << acked_me << dendl; last_election_winner = elector->get_my_rank(); last_voted_for = last_election_winner; clear_live_election_state(); set<int> new_quorum; new_quorum.swap(acked_me); ceph_assert(epoch % 2 == 1); // election bump_epoch(epoch+1); // is over! elector->message_victory(new_quorum); } bool ElectionLogic::propose_classic_prefix(int from, epoch_t mepoch) { if (mepoch > epoch) { bump_epoch(mepoch); } else if (mepoch < epoch) { // got an "old" propose, if (epoch % 2 == 0 && // in a non-election cycle !elector->is_current_member(from)) { // from someone outside the quorum // a mon just started up, call a new election so they can rejoin! ldout(cct, 5) << " got propose from old epoch, " << from << " must have just started" << dendl; // we may be active; make sure we reset things in the monitor appropriately. elector->trigger_new_election(); } else { ldout(cct, 5) << " ignoring old propose" << dendl; } return true; } return false; } void ElectionLogic::receive_propose(int from, epoch_t mepoch, const ConnectionTracker *ct) { ldout(cct, 20) << __func__ << " from " << from << dendl; if (from == elector->get_my_rank()) { lderr(cct) << "I got a propose from my own rank, hopefully this is startup weirdness,dropping" << dendl; return; } switch (strategy) { case CLASSIC: propose_classic_handler(from, mepoch); break; case DISALLOW: propose_disallow_handler(from, mepoch); break; case CONNECTIVITY: propose_connectivity_handler(from, mepoch, ct); break; default: ceph_assert(0 == "how did election strategy become an invalid value?"); } } void ElectionLogic::propose_disallow_handler(int from, epoch_t mepoch) { if (propose_classic_prefix(from, mepoch)) { return; } const set<int>& disallowed_leaders = elector->get_disallowed_leaders(); int my_rank = elector->get_my_rank(); bool me_disallowed = disallowed_leaders.count(my_rank); bool from_disallowed = disallowed_leaders.count(from); bool my_win = !me_disallowed && // we are allowed to lead (my_rank < from || from_disallowed); // we are a better choice than them bool their_win = !from_disallowed && // they are allowed to lead (my_rank > from || me_disallowed) && // they are a better choice than us (leader_acked < 0 || leader_acked >= from); // they are a better choice than our previously-acked choice if (my_win) { // i would win over them. if (leader_acked >= 0) { // we already acked someone ceph_assert(leader_acked < from || from_disallowed); // and they still win, of course ldout(cct, 5) << "no, we already acked " << leader_acked << dendl; } else { // wait, i should win! if (!electing_me) { elector->trigger_new_election(); } } } else { // they would win over me if (their_win) { defer(from); } else { // ignore them! ldout(cct, 5) << "no, we already acked " << leader_acked << dendl; } } } void ElectionLogic::propose_classic_handler(int from, epoch_t mepoch) { if (propose_classic_prefix(from, mepoch)) { return; } if (elector->get_my_rank() < from) { // i would win over them. if (leader_acked >= 0) { // we already acked someone ceph_assert(leader_acked < from); // and they still win, of course ldout(cct, 5) << "no, we already acked " << leader_acked << dendl; } else { // wait, i should win! if (!electing_me) { elector->trigger_new_election(); } } } else { // they would win over me if (leader_acked < 0 || // haven't acked anyone yet, or leader_acked > from || // they would win over who you did ack, or leader_acked == from) { // this is the guy we're already deferring to defer(from); } else { // ignore them! ldout(cct, 5) << "no, we already acked " << leader_acked << dendl; } } } double ElectionLogic::connectivity_election_score(int rank) { ldout(cct, 30) << __func__ << " of " << rank << dendl; if (elector->get_disallowed_leaders().count(rank)) { return -1; } double score; int liveness; if (stable_peer_tracker) { ldout(cct, 30) << "stable_peer_tracker exists so using that ..." << dendl; stable_peer_tracker->get_total_connection_score(rank, &score, &liveness); } else { ldout(cct, 30) << "stable_peer_tracker does not exists, using peer_tracker ..." << dendl; peer_tracker->get_total_connection_score(rank, &score, &liveness); } return score; } void ElectionLogic::propose_connectivity_handler(int from, epoch_t mepoch, const ConnectionTracker *ct) { ldout(cct, 10) << __func__ << " from " << from << " mepoch: " << mepoch << " epoch: " << epoch << dendl; ldout(cct, 30) << "last_election_winner: " << last_election_winner << dendl; if ((epoch % 2 == 0) && last_election_winner != elector->get_my_rank() && !elector->is_current_member(from)) { // To prevent election flapping, peons ignore proposals from out-of-quorum // peers unless their vote would materially change from the last election ldout(cct, 30) << "Lets see if this out-of-quorum peer is worth it " << dendl; int best_scorer = 0; double best_score = 0; double last_voted_for_score = 0; ldout(cct, 30) << "elector->paxos_size(): " << elector->paxos_size() << dendl; for (unsigned i = 0; i < elector->paxos_size(); ++i) { double score = connectivity_election_score(i); if (score > best_score) { best_scorer = i; best_score = score; } if (last_voted_for >= 0 && i == static_cast<unsigned>(last_voted_for)) { last_voted_for_score = score; } } ldout(cct, 30) << "best_scorer: " << best_scorer << " best_score: " << best_score << " last_voted_for: " << last_voted_for << " last_voted_for_score: " << last_voted_for_score << dendl; if (best_scorer == last_voted_for || (best_score - last_voted_for_score < ignore_propose_margin)) { // drop this message; it won't change our vote so we defer to leader ldout(cct, 30) << "drop this message; it won't change our vote so we defer to leader " << dendl; return; } } if (mepoch > epoch) { ldout(cct, 20) << "mepoch > epoch" << dendl; connectivity_bump_epoch_in_election(mepoch); } else if (mepoch < epoch) { // got an "old" propose, if (epoch % 2 == 0 && // in a non-election cycle !elector->is_current_member(from)) { // from someone outside the quorum // a mon just started up, call a new election so they can rejoin! ldout(cct, 5) << " got propose from old epoch, " << from << " must have just started" << dendl; ldout(cct, 10) << "triggering new election" << dendl; // we may be active; make sure we reset things in the monitor appropriately. elector->trigger_new_election(); } else { ldout(cct, 5) << " ignoring old propose" << dendl; } return; } int my_rank = elector->get_my_rank(); double my_score = connectivity_election_score(my_rank); double from_score = connectivity_election_score(from); double leader_score = -1; if (leader_acked >= 0) { leader_score = connectivity_election_score(leader_acked); } ldout(cct, 20) << "propose from rank=" << from << ", tracker: " << (stable_peer_tracker ? *stable_peer_tracker : *peer_tracker) << dendl; ldout(cct, 10) << "propose from rank=" << from << ",from_score=" << from_score << "; my score=" << my_score << "; currently acked " << leader_acked << ",leader_score=" << leader_score << dendl; bool my_win = (my_score >= 0) && // My score is non-zero; I am allowed to lead ((my_rank < from && my_score >= from_score) || // We have same scores and I have lower rank, or (my_score > from_score)); // my score is higher bool their_win = (from_score >= 0) && // Their score is non-zero; they're allowed to lead, AND ((from < my_rank && from_score >= my_score) || // Either they have lower rank and same score, or (from_score > my_score)) && // their score is higher, AND ((from <= leader_acked && from_score >= leader_score) || // same conditions compared to leader, or IS leader (from_score > leader_score)); if (my_win) { ldout(cct, 10) << " conditionally I win" << dendl; // i would win over them. if (leader_acked >= 0) { // we already acked someone ceph_assert(leader_score >= from_score); // and they still win, of course ldout(cct, 5) << "no, we already acked " << leader_acked << dendl; } else { // wait, i should win! if (!electing_me) { ldout(cct, 10) << " wait, i should win! triggering new election ..." << dendl; elector->trigger_new_election(); } } } else { ldout(cct, 10) << " conditionally they win" << dendl; // they would win over me if (their_win || from == leader_acked) { if (leader_acked >= 0 && from != leader_acked) { // we have to make sure our acked leader will ALSO defer to them, or else // we can't, to maintain guarantees! ldout(cct, 10) << " make sure acked leader defer to: " << from << dendl; double leader_from_score; int leader_from_liveness; leader_peer_tracker-> get_total_connection_score(from, &leader_from_score, &leader_from_liveness); double leader_leader_score; int leader_leader_liveness; leader_peer_tracker-> get_total_connection_score(leader_acked, &leader_leader_score, &leader_leader_liveness); if ((from < leader_acked && leader_from_score >= leader_leader_score) || (leader_from_score > leader_leader_score)) { ldout(cct, 10) << "defering to " << from << dendl; defer(from); leader_peer_tracker.reset(new ConnectionTracker(*ct)); } else { // we can't defer to them *this* round even though they should win... double cur_leader_score, cur_from_score; int cur_leader_live, cur_from_live; peer_tracker->get_total_connection_score(leader_acked, &cur_leader_score, &cur_leader_live); peer_tracker->get_total_connection_score(from, &cur_from_score, &cur_from_live); if ((from < leader_acked && cur_from_score >= cur_leader_score) || (cur_from_score > cur_leader_score)) { ldout(cct, 5) << "Bumping epoch and starting new election; acked " << leader_acked << " should defer to " << from << " but there is score disagreement!" << dendl; bump_epoch(epoch+1); start(); } else { ldout(cct, 5) << "no, we already acked " << leader_acked << " and it won't defer to " << from << " despite better round scores" << dendl; } } } else { ldout(cct, 10) << "defering to " << from << dendl; defer(from); leader_peer_tracker.reset(new ConnectionTracker(*ct)); } } else { // ignore them! ldout(cct, 5) << "no, we already acked " << leader_acked << " with score >=" << from_score << dendl; } } } void ElectionLogic::receive_ack(int from, epoch_t from_epoch) { ceph_assert(from_epoch % 2 == 1); // sender in an election epoch if (from_epoch > epoch) { ldout(cct, 5) << "woah, that's a newer epoch, i must have rebooted. bumping and re-starting!" << dendl; bump_epoch(from_epoch); start(); return; } // is that _everyone_? if (electing_me) { acked_me.insert(from); if (acked_me.size() == elector->paxos_size()) { // if yes, shortcut to election finish declare_victory(); } } else { // ignore, i'm deferring already. ceph_assert(leader_acked >= 0); } } bool ElectionLogic::victory_makes_sense(int from) { bool makes_sense = false; switch (strategy) { case CLASSIC: makes_sense = (from < elector->get_my_rank()); break; case DISALLOW: makes_sense = (from < elector->get_my_rank()) || elector->get_disallowed_leaders().count(elector->get_my_rank()); break; case CONNECTIVITY: double my_score, leader_score; my_score = connectivity_election_score(elector->get_my_rank()); leader_score = connectivity_election_score(from); ldout(cct, 5) << "victory from " << from << " makes sense? lscore:" << leader_score << "; my score:" << my_score << dendl; makes_sense = (leader_score >= my_score); break; default: ceph_assert(0 == "how did you get a nonsense election strategy assigned?"); } return makes_sense; } bool ElectionLogic::receive_victory_claim(int from, epoch_t from_epoch) { bool election_okay = victory_makes_sense(from); last_election_winner = from; last_voted_for = leader_acked; clear_live_election_state(); if (!election_okay) { ceph_assert(strategy == CONNECTIVITY); ldout(cct, 1) << "I should have been elected over this leader; bumping and restarting!" << dendl; bump_epoch(from_epoch); start(); return false; } // i should have seen this election if i'm getting the victory. if (from_epoch != epoch + 1) { ldout(cct, 5) << "woah, that's a funny epoch, i must have rebooted. bumping and re-starting!" << dendl; bump_epoch(from_epoch); start(); return false; } bump_epoch(from_epoch); // they win return true; }
17,811
30.978456
113
cc
null
ceph-main/src/mon/ElectionLogic.h
// -*- 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. * */ #ifndef CEPH_ELECTIONLOGIC_H #define CEPH_ELECTIONLOGIC_H #include <map> #include <set> #include "include/types.h" #include "ConnectionTracker.h" class ElectionOwner { public: /** * Write down the given epoch in persistent storage, such that it * can later be retrieved by read_persisted_epoch even across process * or machine restarts. * * @param e The epoch to write */ virtual void persist_epoch(epoch_t e) = 0; /** * Retrieve the most-previously-persisted epoch. * * @returns The latest epoch passed to persist_epoch() */ virtual epoch_t read_persisted_epoch() const = 0; /** * Validate that the persistent store is working by committing * to it. (There is no interface for retrieving the value; this * tests local functionality before doing things like triggering * elections to try and join a quorum.) */ virtual void validate_store() = 0; /** * Notify the ElectionOwner that ElectionLogic has increased its * election epoch. This resets an election (either on local loss or victory, * or when trying a new election round) and the ElectionOwner * should reset any tracking of its own to match. (The ElectionLogic * will further trigger sending election messages if that is * appropriate.) */ virtual void notify_bump_epoch() = 0; /** * Notify the ElectionOwner we must start a new election. */ virtual void trigger_new_election() = 0; /** * Retrieve this Paxos instance's rank. */ virtual int get_my_rank() const = 0; /** * Send a PROPOSE message to all our peers. This happens when * we have started a new election (which may mean attempting to * override a current one). * * @param e The election epoch of our proposal. * @param bl A bufferlist containing data the logic wishes to share */ virtual void propose_to_peers(epoch_t e, bufferlist& bl) = 0; /** * The election has failed and we aren't sure what the state of the * quorum is, so reset the entire system as if from scratch. */ virtual void reset_election() = 0; /** * Ask the ElectionOwner if we-the-Monitor have ever participated in the * quorum (including across process restarts!). * * @returns true if we have participated, false otherwise */ virtual bool ever_participated() const = 0; /** * Ask the ElectionOwner for the size of the Paxos set. This includes * those monitors which may not be in the current quorum! * The value returned by this function can change between elections, * but not during them. (In practical terms, it can be updated * by making a paxos commit, but not by injecting values while * an election is ongoing.) */ virtual unsigned paxos_size() const = 0; /** * Retrieve a set of ranks which are not allowed to become the leader. * Like paxos_size(), This set can change between elections, but not * during them. */ virtual const std::set<int>& get_disallowed_leaders() const = 0; /** * Tell the ElectionOwner we have started a new election. * * The ElectionOwner is responsible for timing out the election (by invoking * end_election_period()) if it takes too long (as defined by the ElectionOwner). * This function is the opportunity to do that and to clean up any other external * election state it may be maintaining. */ virtual void _start() = 0; /** * Tell the ElectionOwner to defer to the identified peer. Tell that peer * we have deferred to it. * * @post we sent an ack message to @p who */ virtual void _defer_to(int who) = 0; /** * We have won an election, so have the ElectionOwner message that to * our new quorum! * * @param quorum The ranks of our peers which deferred to us and * must be told of our victory */ virtual void message_victory(const std::set<int>& quorum) = 0; /** * Query the ElectionOwner about if a given rank is in the * currently active quorum. * @param rank the Paxos rank whose status we are checking * @returns true if the rank is in our current quorum, false otherwise. */ virtual bool is_current_member(int rank) const = 0; virtual ~ElectionOwner() {} }; /** * This class maintains local state for running an election * between Paxos instances. It receives input requests * and calls back out to its ElectionOwner to do persistence * and message other entities. */ class ElectionLogic { ElectionOwner *elector; ConnectionTracker *peer_tracker; CephContext *cct; /** * Latest epoch we've seen. * * @remarks if its value is odd, we're electing; if it's even, then we're * stable. */ epoch_t epoch = 0; /** * The last rank which won an election we participated in */ int last_election_winner = -1; /** * Only used in the connectivity handler. * The rank we voted for in the last election we voted in. */ int last_voted_for = -1; double ignore_propose_margin = 0.0001; /** * Only used in the connectivity handler. * Points at a stable copy of the peer_tracker we use to keep scores * throughout an election period. */ std::unique_ptr<ConnectionTracker> stable_peer_tracker; std::unique_ptr<ConnectionTracker> leader_peer_tracker; /** * Indicates who we have acked */ int leader_acked; public: enum election_strategy { // Keep in sync with MonMap.h! CLASSIC = 1, // the original rank-based one DISALLOW = 2, // disallow a set from being leader CONNECTIVITY = 3 // includes DISALLOW, extends to prefer stronger connections }; election_strategy strategy; /** * Indicates if we are participating in the quorum. * * @remarks By default, we are created as participating. We may stop * participating if something explicitly sets our value * false, though. If that happens, it will * have to set participating=true and invoke start() for us to resume * participating in the quorum. */ bool participating; /** * Indicates if we are the ones being elected. * * We always attempt to be the one being elected if we are the ones starting * the election. If we are not the ones that started it, we will only attempt * to be elected if we think we might have a chance (i.e., the other guy's * rank is lower than ours). */ bool electing_me; /** * Set containing all those that acked our proposal to become the Leader. * * If we are acked by ElectionOwner::paxos_size() peers, we will declare * victory. */ std::set<int> acked_me; ElectionLogic(ElectionOwner *e, election_strategy es, ConnectionTracker *t, double ipm, CephContext *c) : elector(e), peer_tracker(t), cct(c), last_election_winner(-1), last_voted_for(-1), ignore_propose_margin(ipm), stable_peer_tracker(), leader_peer_tracker(), leader_acked(-1), strategy(es), participating(true), electing_me(false) {} /** * Set the election strategy to use. If this is not consistent across the * electing cluster, you're going to have a bad time. * Defaults to CLASSIC. */ void set_election_strategy(election_strategy es) { strategy = es; } /** * If there are no other peers in this Paxos group, ElectionOwner * can simply declare victory and we will make it so. * * @pre paxos_size() is 1 * @pre get_my_rank is 0 */ void declare_standalone_victory(); /** * Start a new election by proposing ourselves as the new Leader. * * Basically, send propose messages to all the peers. * * @pre participating is true * @post epoch is an odd value * @post electing_me is true * @post We have invoked propose_to_peers() on our ElectionOwner * @post We have invoked _start() on our ElectionOwner */ void start(); /** * ElectionOwner has decided the election has taken too long and expired. * * This will happen when no one declared victory or started a new election * during the allowed time span. * * When the election expires, we will check if we were the ones who won, and * if so we will declare victory. If that is not the case, then we assume * that the one we deferred to didn't declare victory quickly enough (in fact, * as far as we know, it may even be dead); so, just propose ourselves as the * Leader. */ void end_election_period(); /** * Handle a proposal from some other node proposing asking to become * the Leader. * * If the message appears to be old (i.e., its epoch is lower than our epoch), * then we may take one of two actions: * * @li Ignore it because it's nothing more than an old proposal * @li Start new elections if we verify that it was sent by a monitor from * outside the quorum; given its old state, it's fair to assume it just * started, so we should start new elections so it may rejoin. (Some * handlers may choose to ignore even these, if they think it's flapping.) * * We pass the propose off to a propose_*_handler function based * on the election strategy we're using. * Only the Connectivity strategy cares about the ConnectionTracker; it should * be NULL if other strategies are in use. Otherwise, it will take ownership * of the underlying data and delete it as needed. * * @pre Message epoch is from the current or a newer epoch * @param mepoch The epoch of the proposal * @param from The rank proposing itself as leader * @param ct Any incoming ConnectionTracker data sent with the message. * Callers are responsible for deleting this -- we will copy it if we want * to keep the data. */ void receive_propose(int from, epoch_t mepoch, const ConnectionTracker *ct); /** * Handle a message from some other participant Acking us as the Leader. * * When we receive such a message, one of three thing may be happening: * @li We received a message with a newer epoch, which means we must have * somehow lost track of what was going on (maybe we rebooted), thus we * will start a new election * @li We consider ourselves in the run for the Leader (i.e., @p electing_me * is true), and we are actually being Acked by someone; thus simply add * the one acking us to the @p acked_me set. If we do now have acks from * all the participants, then we can declare victory * @li We already deferred the election to somebody else, so we will just * ignore this message * * @pre Message epoch is from the current or a newer epoch * @post Election is on-going if we deferred to somebody else * @post Election is on-going if we are still waiting for further Acks * @post Election is not on-going if we are victorious * @post Election is not on-going if we must start a new one * * @param from The rank which acked us * @param from_epoch The election epoch the ack belongs to */ void receive_ack(int from, epoch_t from_epoch); /** * Handle a message from some other participant declaring Victory. * * We just got a message from someone declaring themselves Victorious, thus * the new Leader. * * However, if the message's epoch happens to be different from our epoch+1, * then it means we lost track of something and we must start a new election. * * If that is not the case, then we will simply update our epoch to the one * in the message and invoke start() to reset the quorum. * * @pre from_epoch is the current or a newer epoch * @post Election is not on-going * @post Updated @p epoch * @post We are a peon in a new quorum if we lost the election * * @param from The victory-claiming rank * @param from_epoch The election epoch in which they claim victory */ bool receive_victory_claim(int from, epoch_t from_epoch); /** * Obtain our epoch * * @returns Our current epoch number */ epoch_t get_epoch() const { return epoch; } int get_election_winner() { return last_election_winner; } private: /** * Initiate the ElectionLogic class. * * Basically, we will simply read whatever epoch value we have in our stable * storage, or consider it to be 1 if none is read. * * @post @p epoch is set to 1 or higher. */ void init(); /** * Update our epoch. * * If we come across a higher epoch, we simply update ours, also making * sure we are no longer being elected (even though we could have been, * we no longer are since we no longer are on that old epoch). * * @pre Our epoch is not larger than @p e * @post Our epoch equals @p e * * @param e Epoch to which we will update our epoch */ void bump_epoch(epoch_t e); /** * If the incoming proposal is newer, bump our own epoch; if * it comes from an out-of-quorum peer, trigger a new eleciton. * @returns true if you should drop this proposal, false otherwise. */ bool propose_classic_prefix(int from, epoch_t mepoch); /** * Handle a proposal from another rank using the classic strategy. * We will take one of the following actions: * * @li Ignore it because we already acked another node with higher rank * @li Ignore it and start a new election because we outrank it * @li Defer to it because it outranks us and the node we previously * acked, if any */ void propose_classic_handler(int from, epoch_t mepoch); /** * Handle a proposal from another rank using our disallow strategy. * This is the same as the classic strategy except we also disallow * certain ranks from becoming the leader. */ void propose_disallow_handler(int from, epoch_t mepoch); /** * Handle a proposal from another rank using the connectivity strategy. * We will choose to defer or not based on the ordered criteria: * * @li Whether the other monitor (or ourself) is on the disallow list * @li Whether the other monitor or ourself has the most connectivity to peers * @li Whether the other monitor or ourself has the lower rank */ void propose_connectivity_handler(int from, epoch_t mepoch, const ConnectionTracker *ct); /** * Helper function for connectivity handler. Combines the disallowed list * with ConnectionTracker scores. */ double connectivity_election_score(int rank); /** * Defer the current election to some other monitor. * * This means that we will ack some other monitor and drop out from the run * to become the Leader. We will only defer an election if the monitor we * are deferring to outranks us. * * @pre @p who outranks us (i.e., who < our rank) * @pre @p who outranks any other monitor we have deferred to in the past * @post electing_me is false * @post leader_acked equals @p who * @post we triggered ElectionOwner's _defer_to() on @p who * * @param who Some other monitor's numeric identifier. */ void defer(int who); /** * Declare Victory. * * We won. Or at least we believe we won, but for all intents and purposes * that does not matter. What matters is that we Won. * * That said, we must now bump our epoch to reflect that the election is over * and then we must let everybody in the quorum know we are their brand new * Leader. * * Actually, the quorum will be now defined as the group of monitors that * acked us during the election process. * * @pre Election is on-going * @pre electing_me is true * @post electing_me is false * @post epoch is bumped up into an even value * @post Election is not on-going * @post We have a quorum, composed of the monitors that acked us * @post We invoked message_victory() on the ElectionOwner */ void declare_victory(); /** * This is just a helper function to validate that the victory claim we * get from another rank makes any sense. */ bool victory_makes_sense(int from); /** * Reset some data members which we only care about while we are in an election * or need to be set consistently during stable states. */ void clear_live_election_state(); void reset_stable_tracker(); /** * Only for the connectivity handler, Bump the epoch * when we get a message from a newer one and clear * out leader and stable tracker * data so that we can switch our allegiance. */ void connectivity_bump_epoch_in_election(epoch_t mepoch); }; #endif
16,840
35.531453
91
h
null
ceph-main/src/mon/Elector.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 "Elector.h" #include "Monitor.h" #include "common/Timer.h" #include "MonitorDBStore.h" #include "messages/MMonElection.h" #include "messages/MMonPing.h" #include "common/config.h" #include "include/ceph_assert.h" #define dout_subsys ceph_subsys_mon #undef dout_prefix #define dout_prefix _prefix(_dout, mon, get_epoch()) using std::cerr; using std::cout; using std::dec; using std::hex; using std::list; using std::map; using std::make_pair; using std::ostream; using std::ostringstream; using std::pair; using std::set; using std::setfill; using std::string; using std::stringstream; using std::to_string; using std::vector; using std::unique_ptr; using ceph::bufferlist; using ceph::decode; using ceph::encode; using ceph::Formatter; using ceph::JSONFormatter; using ceph::mono_clock; using ceph::mono_time; using ceph::timespan_str; static ostream& _prefix(std::ostream *_dout, Monitor *mon, epoch_t epoch) { return *_dout << "mon." << mon->name << "@" << mon->rank << "(" << mon->get_state_name() << ").elector(" << epoch << ") "; } Elector::Elector(Monitor *m, int strategy) : logic(this, static_cast<ElectionLogic::election_strategy>(strategy), &peer_tracker, m->cct->_conf.get_val<double>("mon_elector_ignore_propose_margin"), m->cct), peer_tracker(this, m->rank, m->cct->_conf.get_val<uint64_t>("mon_con_tracker_score_halflife"), m->cct->_conf.get_val<uint64_t>("mon_con_tracker_persist_interval"), m->cct), ping_timeout(m->cct->_conf.get_val<double>("mon_elector_ping_timeout")), PING_DIVISOR(m->cct->_conf.get_val<uint64_t>("mon_elector_ping_divisor")), mon(m), elector(this) { bufferlist bl; mon->store->get(Monitor::MONITOR_NAME, "connectivity_scores", bl); if (bl.length()) { bufferlist::const_iterator bi = bl.begin(); peer_tracker.decode(bi); } } void Elector::persist_epoch(epoch_t e) { auto t(std::make_shared<MonitorDBStore::Transaction>()); t->put(Monitor::MONITOR_NAME, "election_epoch", e); t->put(Monitor::MONITOR_NAME, "connectivity_scores", peer_tracker.get_encoded_bl()); mon->store->apply_transaction(t); } void Elector::persist_connectivity_scores() { dout(20) << __func__ << dendl; auto t(std::make_shared<MonitorDBStore::Transaction>()); t->put(Monitor::MONITOR_NAME, "connectivity_scores", peer_tracker.get_encoded_bl()); mon->store->apply_transaction(t); } epoch_t Elector::read_persisted_epoch() const { return mon->store->get(Monitor::MONITOR_NAME, "election_epoch"); } void Elector::validate_store() { auto t(std::make_shared<MonitorDBStore::Transaction>()); t->put(Monitor::MONITOR_NAME, "election_writeable_test", rand()); int r = mon->store->apply_transaction(t); ceph_assert(r >= 0); } bool Elector::is_current_member(int rank) const { return mon->quorum.count(rank); } void Elector::trigger_new_election() { mon->start_election(); } int Elector::get_my_rank() const { return mon->rank; } void Elector::reset_election() { mon->bootstrap(); } bool Elector::ever_participated() const { return mon->has_ever_joined; } unsigned Elector::paxos_size() const { return mon->monmap->size(); } void Elector::shutdown() { cancel_timer(); } void Elector::notify_bump_epoch() { mon->join_election(); } void Elector::propose_to_peers(epoch_t e, bufferlist& logic_bl) { // bcast to everyone else for (unsigned i=0; i<mon->monmap->size(); ++i) { if ((int)i == mon->rank) continue; MMonElection *m = new MMonElection(MMonElection::OP_PROPOSE, e, peer_tracker.get_encoded_bl(), logic.strategy, mon->monmap); m->sharing_bl = logic_bl; m->mon_features = ceph::features::mon::get_supported(); m->mon_release = ceph_release(); mon->send_mon_message(m, i); } } void Elector::_start() { peer_info.clear(); peer_info[mon->rank].cluster_features = CEPH_FEATURES_ALL; peer_info[mon->rank].mon_release = ceph_release(); peer_info[mon->rank].mon_features = ceph::features::mon::get_supported(); mon->collect_metadata(&peer_info[mon->rank].metadata); reset_timer(); } void Elector::_defer_to(int who) { MMonElection *m = new MMonElection(MMonElection::OP_ACK, get_epoch(), peer_tracker.get_encoded_bl(), logic.strategy, mon->monmap); m->mon_features = ceph::features::mon::get_supported(); m->mon_release = ceph_release(); mon->collect_metadata(&m->metadata); mon->send_mon_message(m, who); // set a timer reset_timer(1.0); // give the leader some extra time to declare victory } void Elector::reset_timer(double plus) { // set the timer cancel_timer(); /** * This class is used as the callback when the expire_event timer fires up. * * If the expire_event is fired, then it means that we had an election going, * either started by us or by some other participant, but it took too long, * thus expiring. * * When the election expires, we will check if we were the ones who won, and * if so we will declare victory. If that is not the case, then we assume * that the one we defered to didn't declare victory quickly enough (in fact, * as far as we know, we may even be dead); so, just propose ourselves as the * Leader. */ expire_event = mon->timer.add_event_after( g_conf()->mon_election_timeout + plus, new C_MonContext{mon, [this](int) { logic.end_election_period(); }}); } void Elector::cancel_timer() { if (expire_event) { mon->timer.cancel_event(expire_event); expire_event = 0; } } void Elector::assimilate_connection_reports(const bufferlist& tbl) { dout(10) << __func__ << dendl; ConnectionTracker pct(tbl, mon->cct); peer_tracker.receive_peer_report(pct); } void Elector::message_victory(const std::set<int>& quorum) { uint64_t cluster_features = CEPH_FEATURES_ALL; mon_feature_t mon_features = ceph::features::mon::get_supported(); map<int,Metadata> metadata; ceph_release_t min_mon_release{ceph_release_t::unknown}; for (auto id : quorum) { auto i = peer_info.find(id); ceph_assert(i != peer_info.end()); auto& info = i->second; cluster_features &= info.cluster_features; mon_features &= info.mon_features; metadata[id] = info.metadata; if (min_mon_release == ceph_release_t::unknown || info.mon_release < min_mon_release) { min_mon_release = info.mon_release; } } cancel_timer(); // tell everyone! for (set<int>::iterator p = quorum.begin(); p != quorum.end(); ++p) { if (*p == mon->rank) continue; MMonElection *m = new MMonElection(MMonElection::OP_VICTORY, get_epoch(), peer_tracker.get_encoded_bl(), logic.strategy, mon->monmap); m->quorum = quorum; m->quorum_features = cluster_features; m->mon_features = mon_features; m->sharing_bl = mon->get_local_commands_bl(mon_features); m->mon_release = min_mon_release; mon->send_mon_message(m, *p); } // tell monitor mon->win_election(get_epoch(), quorum, cluster_features, mon_features, min_mon_release, metadata); } void Elector::handle_propose(MonOpRequestRef op) { op->mark_event("elector:handle_propose"); auto m = op->get_req<MMonElection>(); dout(5) << "handle_propose from " << m->get_source() << dendl; int from = m->get_source().num(); ceph_assert(m->epoch % 2 == 1); // election uint64_t required_features = mon->get_required_features(); mon_feature_t required_mon_features = mon->get_required_mon_features(); dout(10) << __func__ << " required features " << required_features << " " << required_mon_features << ", peer features " << m->get_connection()->get_features() << " " << m->mon_features << dendl; if ((required_features ^ m->get_connection()->get_features()) & required_features) { dout(5) << " ignoring propose from mon" << from << " without required features" << dendl; nak_old_peer(op); return; } else if (mon->monmap->min_mon_release > m->mon_release) { dout(5) << " ignoring propose from mon" << from << " release " << (int)m->mon_release << " < min_mon_release " << (int)mon->monmap->min_mon_release << dendl; nak_old_peer(op); return; } else if (!m->mon_features.contains_all(required_mon_features)) { // all the features in 'required_mon_features' not in 'm->mon_features' mon_feature_t missing = required_mon_features.diff(m->mon_features); dout(5) << " ignoring propose from mon." << from << " without required mon_features " << missing << dendl; nak_old_peer(op); } ConnectionTracker *oct = NULL; if (m->sharing_bl.length()) { oct = new ConnectionTracker(m->sharing_bl, mon->cct); } logic.receive_propose(from, m->epoch, oct); delete oct; } void Elector::handle_ack(MonOpRequestRef op) { op->mark_event("elector:handle_ack"); auto m = op->get_req<MMonElection>(); dout(5) << "handle_ack from " << m->get_source() << dendl; int from = m->get_source().num(); ceph_assert(m->epoch == get_epoch()); uint64_t required_features = mon->get_required_features(); if ((required_features ^ m->get_connection()->get_features()) & required_features) { dout(5) << " ignoring ack from mon" << from << " without required features" << dendl; return; } mon_feature_t required_mon_features = mon->get_required_mon_features(); if (!m->mon_features.contains_all(required_mon_features)) { mon_feature_t missing = required_mon_features.diff(m->mon_features); dout(5) << " ignoring ack from mon." << from << " without required mon_features " << missing << dendl; return; } if (logic.electing_me) { // thanks peer_info[from].cluster_features = m->get_connection()->get_features(); peer_info[from].mon_features = m->mon_features; peer_info[from].mon_release = m->mon_release; peer_info[from].metadata = m->metadata; dout(5) << " so far i have {"; for (auto q = logic.acked_me.begin(); q != logic.acked_me.end(); ++q) { auto p = peer_info.find(*q); ceph_assert(p != peer_info.end()); if (q != logic.acked_me.begin()) *_dout << ","; *_dout << " mon." << p->first << ":" << " features " << p->second.cluster_features << " " << p->second.mon_features; } *_dout << " }" << dendl; } logic.receive_ack(from, m->epoch); } void Elector::handle_victory(MonOpRequestRef op) { op->mark_event("elector:handle_victory"); auto m = op->get_req<MMonElection>(); dout(5) << "handle_victory from " << m->get_source() << " quorum_features " << m->quorum_features << " " << m->mon_features << dendl; int from = m->get_source().num(); bool accept_victory = logic.receive_victory_claim(from, m->epoch); if (!accept_victory) { return; } mon->lose_election(get_epoch(), m->quorum, from, m->quorum_features, m->mon_features, m->mon_release); // cancel my timer cancel_timer(); // stash leader's commands ceph_assert(m->sharing_bl.length()); vector<MonCommand> new_cmds; auto bi = m->sharing_bl.cbegin(); MonCommand::decode_vector(new_cmds, bi); mon->set_leader_commands(new_cmds); } void Elector::nak_old_peer(MonOpRequestRef op) { op->mark_event("elector:nak_old_peer"); auto m = op->get_req<MMonElection>(); uint64_t supported_features = m->get_connection()->get_features(); uint64_t required_features = mon->get_required_features(); mon_feature_t required_mon_features = mon->get_required_mon_features(); dout(10) << "sending nak to peer " << m->get_source() << " supports " << supported_features << " " << m->mon_features << ", required " << required_features << " " << required_mon_features << ", release " << (int)m->mon_release << " vs required " << (int)mon->monmap->min_mon_release << dendl; MMonElection *reply = new MMonElection(MMonElection::OP_NAK, m->epoch, peer_tracker.get_encoded_bl(), logic.strategy, mon->monmap); reply->quorum_features = required_features; reply->mon_features = required_mon_features; reply->mon_release = mon->monmap->min_mon_release; mon->features.encode(reply->sharing_bl); m->get_connection()->send_message(reply); } void Elector::handle_nak(MonOpRequestRef op) { op->mark_event("elector:handle_nak"); auto m = op->get_req<MMonElection>(); dout(1) << "handle_nak from " << m->get_source() << " quorum_features " << m->quorum_features << " " << m->mon_features << " min_mon_release " << (int)m->mon_release << dendl; if (m->mon_release > ceph_release()) { derr << "Shutting down because I am release " << (int)ceph_release() << " < min_mon_release " << (int)m->mon_release << dendl; } else { CompatSet other; auto bi = m->sharing_bl.cbegin(); other.decode(bi); CompatSet diff = Monitor::get_supported_features().unsupported(other); mon_feature_t mon_supported = ceph::features::mon::get_supported(); // all features in 'm->mon_features' not in 'mon_supported' mon_feature_t mon_diff = m->mon_features.diff(mon_supported); derr << "Shutting down because I lack required monitor features: { " << diff << " } " << mon_diff << dendl; } exit(0); // the end! } void Elector::begin_peer_ping(int peer) { dout(20) << __func__ << " against " << peer << dendl; if (live_pinging.count(peer)) { dout(20) << peer << " already in live_pinging ... return " << dendl; return; } if (!mon->get_quorum_mon_features().contains_all( ceph::features::mon::FEATURE_PINGING)) { return; } peer_tracker.report_live_connection(peer, 0); // init this peer as existing live_pinging.insert(peer); dead_pinging.erase(peer); peer_acked_ping[peer] = ceph_clock_now(); if (!send_peer_ping(peer)) return; mon->timer.add_event_after(ping_timeout / PING_DIVISOR, new C_MonContext{mon, [this, peer](int) { ping_check(peer); }}); } bool Elector::send_peer_ping(int peer, const utime_t *n) { dout(10) << __func__ << " to peer " << peer << dendl; if (peer >= ssize(mon->monmap->ranks)) { // Monitor no longer exists in the monmap, // therefore, we shouldn't ping this monitor // since we cannot lookup the address! dout(5) << "peer: " << peer << " >= ranks_size: " << ssize(mon->monmap->ranks) << " ... dropping to prevent " << "https://tracker.ceph.com/issues/50089" << dendl; live_pinging.erase(peer); return false; } utime_t now; if (n != NULL) { now = *n; } else { now = ceph_clock_now(); } MMonPing *ping = new MMonPing(MMonPing::PING, now, peer_tracker.get_encoded_bl()); mon->messenger->send_to_mon(ping, mon->monmap->get_addrs(peer)); peer_sent_ping[peer] = now; return true; } void Elector::ping_check(int peer) { dout(20) << __func__ << " to peer " << peer << dendl; if (!live_pinging.count(peer) && !dead_pinging.count(peer)) { dout(20) << __func__ << peer << " is no longer marked for pinging" << dendl; return; } utime_t now = ceph_clock_now(); utime_t& acked_ping = peer_acked_ping[peer]; utime_t& newest_ping = peer_sent_ping[peer]; if (!acked_ping.is_zero() && acked_ping < now - ping_timeout) { peer_tracker.report_dead_connection(peer, now - acked_ping); acked_ping = now; begin_dead_ping(peer); return; } if (acked_ping == newest_ping) { if (!send_peer_ping(peer, &now)) return; } mon->timer.add_event_after(ping_timeout / PING_DIVISOR, new C_MonContext{mon, [this, peer](int) { ping_check(peer); }}); } void Elector::begin_dead_ping(int peer) { dout(20) << __func__ << " to peer " << peer << dendl; if (dead_pinging.count(peer)) { return; } live_pinging.erase(peer); dead_pinging.insert(peer); mon->timer.add_event_after(ping_timeout, new C_MonContext{mon, [this, peer](int) { dead_ping(peer); }}); } void Elector::dead_ping(int peer) { dout(20) << __func__ << " to peer " << peer << dendl; if (!dead_pinging.count(peer)) { dout(20) << __func__ << peer << " is no longer marked for dead pinging" << dendl; return; } ceph_assert(!live_pinging.count(peer)); utime_t now = ceph_clock_now(); utime_t& acked_ping = peer_acked_ping[peer]; peer_tracker.report_dead_connection(peer, now - acked_ping); acked_ping = now; mon->timer.add_event_after(ping_timeout, new C_MonContext{mon, [this, peer](int) { dead_ping(peer); }}); } void Elector::handle_ping(MonOpRequestRef op) { MMonPing *m = static_cast<MMonPing*>(op->get_req()); int prank = mon->monmap->get_rank(m->get_source_addr()); dout(20) << __func__ << " from: " << prank << dendl; begin_peer_ping(prank); assimilate_connection_reports(m->tracker_bl); switch(m->op) { case MMonPing::PING: { MMonPing *reply = new MMonPing(MMonPing::PING_REPLY, m->stamp, peer_tracker.get_encoded_bl()); m->get_connection()->send_message(reply); } break; case MMonPing::PING_REPLY: const utime_t& previous_acked = peer_acked_ping[prank]; const utime_t& newest = peer_sent_ping[prank]; if (m->stamp > newest && !newest.is_zero()) { derr << "dropping PING_REPLY stamp " << m->stamp << " as it is newer than newest sent " << newest << dendl; return; } if (m->stamp > previous_acked) { dout(20) << "m->stamp > previous_acked" << dendl; peer_tracker.report_live_connection(prank, m->stamp - previous_acked); peer_acked_ping[prank] = m->stamp; } else{ dout(20) << "m->stamp <= previous_acked .. we don't report_live_connection" << dendl; } utime_t now = ceph_clock_now(); dout(30) << "now: " << now << " m->stamp: " << m->stamp << " ping_timeout: " << ping_timeout << " PING_DIVISOR: " << PING_DIVISOR << dendl; if (now - m->stamp > ping_timeout / PING_DIVISOR) { if (!send_peer_ping(prank, &now)) return; } break; } } void Elector::dispatch(MonOpRequestRef op) { op->mark_event("elector:dispatch"); ceph_assert(op->is_type_election_or_ping()); switch (op->get_req()->get_type()) { case MSG_MON_ELECTION: { if (!logic.participating) { return; } if (op->get_req()->get_source().num() >= mon->monmap->size()) { dout(5) << " ignoring bogus election message with bad mon rank " << op->get_req()->get_source() << dendl; return; } auto em = op->get_req<MMonElection>(); dout(20) << __func__ << " from: " << mon->monmap->get_rank(em->get_source_addr()) << dendl; // assume an old message encoding would have matched if (em->fsid != mon->monmap->fsid) { dout(0) << " ignoring election msg fsid " << em->fsid << " != " << mon->monmap->fsid << dendl; return; } if (!mon->monmap->contains(em->get_source_addr())) { dout(1) << "discarding election message: " << em->get_source_addr() << " not in my monmap " << *mon->monmap << dendl; return; } MonMap peermap; peermap.decode(em->monmap_bl); if (peermap.epoch > mon->monmap->epoch) { dout(0) << em->get_source_inst() << " has newer monmap epoch " << peermap.epoch << " > my epoch " << mon->monmap->epoch << ", taking it" << dendl; mon->monmap->decode(em->monmap_bl); auto t(std::make_shared<MonitorDBStore::Transaction>()); t->put("monmap", mon->monmap->epoch, em->monmap_bl); t->put("monmap", "last_committed", mon->monmap->epoch); mon->store->apply_transaction(t); //mon->monmon()->paxos->stash_latest(mon->monmap->epoch, em->monmap_bl); cancel_timer(); mon->notify_new_monmap(false); mon->bootstrap(); return; } if (peermap.epoch < mon->monmap->epoch) { dout(0) << em->get_source_inst() << " has older monmap epoch " << peermap.epoch << " < my epoch " << mon->monmap->epoch << dendl; } if (em->strategy != logic.strategy) { dout(5) << __func__ << " somehow got an Election message with different strategy " << em->strategy << " from local " << logic.strategy << "; dropping for now to let race resolve" << dendl; return; } if (em->scoring_bl.length()) { assimilate_connection_reports(em->scoring_bl); } begin_peer_ping(mon->monmap->get_rank(em->get_source_addr())); switch (em->op) { case MMonElection::OP_PROPOSE: handle_propose(op); return; } if (em->epoch < get_epoch()) { dout(5) << "old epoch, dropping" << dendl; break; } switch (em->op) { case MMonElection::OP_ACK: handle_ack(op); return; case MMonElection::OP_VICTORY: handle_victory(op); return; case MMonElection::OP_NAK: handle_nak(op); return; default: ceph_abort(); } } break; case MSG_MON_PING: handle_ping(op); break; default: ceph_abort(); } } void Elector::start_participating() { logic.participating = true; } bool Elector::peer_tracker_is_clean() { return peer_tracker.is_clean(mon->rank, paxos_size()); } void Elector::notify_clear_peer_state() { dout(10) << __func__ << dendl; dout(20) << " peer_tracker before: " << peer_tracker << dendl; peer_tracker.notify_reset(); peer_tracker.set_rank(mon->rank); dout(20) << " peer_tracker after: " << peer_tracker << dendl; } void Elector::notify_rank_changed(int new_rank) { dout(10) << __func__ << " to " << new_rank << dendl; peer_tracker.notify_rank_changed(new_rank); live_pinging.erase(new_rank); dead_pinging.erase(new_rank); } void Elector::notify_rank_removed(unsigned rank_removed, unsigned new_rank) { dout(10) << __func__ << ": " << rank_removed << dendl; peer_tracker.notify_rank_removed(rank_removed, new_rank); /* we have to clean up the pinging state, which is annoying because it's not indexed anywhere (and adding indexing would also be annoying). In the case where we are removing any rank that is not the higest, we start with the removed rank and examine the state of the surrounding ranks. Everybody who remains with larger rank gets a new rank one lower than before, and we have to figure out the remaining scheduled ping contexts. So, starting one past with the removed rank, we: * check if the current rank is alive or dead * examine our new rank (one less than before, initially the removed rank) * * erase it if it's in the wrong set * * start pinging it if we're not already * check if the next rank is in the same pinging set, and delete * ourselves if not. In the case where we are removing the highest rank, we erase the removed rank from all sets. */ if (rank_removed < paxos_size()) { for (unsigned i = rank_removed + 1; i <= paxos_size() ; ++i) { if (live_pinging.count(i)) { dead_pinging.erase(i-1); if (!live_pinging.count(i-1)) { begin_peer_ping(i-1); } if (!live_pinging.count(i+1)) { live_pinging.erase(i); } } else if (dead_pinging.count(i)) { live_pinging.erase(i-1); if (!dead_pinging.count(i-1)) { begin_dead_ping(i-1); } if (!dead_pinging.count(i+1)) { dead_pinging.erase(i); } } else { // we aren't pinging rank i at all if (i-1 == (unsigned)rank_removed) { // so we special case to make sure we // actually nuke the removed rank dead_pinging.erase(rank_removed); live_pinging.erase(rank_removed); } } } } else { if (live_pinging.count(rank_removed)) { live_pinging.erase(rank_removed); } if (dead_pinging.count(rank_removed)) { dead_pinging.erase(rank_removed); } } } void Elector::notify_strategy_maybe_changed(int strategy) { logic.set_election_strategy(static_cast<ElectionLogic::election_strategy>(strategy)); }
24,459
29.272277
113
cc
null
ceph-main/src/mon/Elector.h
// -*- 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. * */ #ifndef CEPH_MON_ELECTOR_H #define CEPH_MON_ELECTOR_H #include <map> #include "include/types.h" #include "include/Context.h" #include "mon/MonOpRequest.h" #include "mon/mon_types.h" #include "mon/ElectionLogic.h" #include "mon/ConnectionTracker.h" class Monitor; /** * This class is responsible for handling messages and maintaining * an ElectionLogic which holds the local state when electing * a new Leader. We may win or we may lose. If we win, it means we became the * Leader; if we lose, it means we are a Peon. */ class Elector : public ElectionOwner, RankProvider { /** * @defgroup Elector_h_class Elector * @{ */ ElectionLogic logic; // connectivity validation and scoring ConnectionTracker peer_tracker; std::map<int, utime_t> peer_acked_ping; // rank -> last ping stamp they acked std::map<int, utime_t> peer_sent_ping; // rank -> last ping stamp we sent std::set<int> live_pinging; // ranks which we are currently pinging std::set<int> dead_pinging; // ranks which didn't answer (degrading scores) double ping_timeout; // the timeout after which we consider a ping to be dead int PING_DIVISOR = 2; // we time out pings /** * @defgroup Elector_h_internal_types Internal Types * @{ */ /** * This struct will hold the features from a given peer. * Features may both be the cluster's (in the form of a uint64_t), or * mon-specific features. Instead of keeping maps to hold them both, or * a pair, which would be weird, a struct to keep them seems appropriate. */ struct elector_info_t { uint64_t cluster_features = 0; mon_feature_t mon_features; ceph_release_t mon_release{0}; std::map<std::string,std::string> metadata; }; /** * @} */ /** * The Monitor instance associated with this class. */ Monitor *mon; /** * Event callback responsible for dealing with an expired election once a * timer runs out and fires up. */ Context *expire_event = nullptr; /** * Resets the expire_event timer, by cancelling any existing one and * scheduling a new one. * * @remarks This function assumes as a default firing value the duration of * the monitor's lease interval, and adds to it the value specified * in @e plus * * @post expire_event is set * * @param plus The amount of time to be added to the default firing value. */ void reset_timer(double plus=0.0); /** * Cancel the expire_event timer, if it is defined. * * @post expire_event is not set */ void cancel_timer(); // electing me /** * @defgroup Elector_h_electing_me_vars We are being elected * @{ */ /** * Map containing info of all those that acked our proposal to become the Leader. * Note each peer's info. */ std::map<int, elector_info_t> peer_info; /** * @} */ /** * Handle a message from some other node proposing itself to become it * the Leader. * * We validate that the sending Monitor is allowed to participate based on * its supported features, then pass the request to our ElectionLogic. * * @invariant The received message is an operation of type OP_PROPOSE * * @pre Message epoch is from the current or a newer epoch * * @param m A message sent by another participant in the quorum. */ void handle_propose(MonOpRequestRef op); /** * Handle a message from some other participant Acking us as the Leader. * * We validate that the sending Monitor is allowed to participate based on * its supported features, add it to peer_info, and pass the ack to our * ElectionLogic. * * @pre Message epoch is from the current or a newer epoch * * @param m A message with an operation type of OP_ACK */ void handle_ack(MonOpRequestRef op); /** * Handle a message from some other participant declaring Victory. * * We just got a message from someone declaring themselves Victorious, thus * the new Leader. * * We pass the Victory to our ElectionLogic, and if it confirms the * victory we lose the election and start following this Leader. Otherwise, * drop the message. * * @pre Message epoch is from the current or a newer epoch * @post Election is not on-going * @post Updated @p epoch * @post We have a new quorum if we lost the election * * @param m A message with an operation type of OP_VICTORY */ void handle_victory(MonOpRequestRef op); /** * Send a nak to a peer who's out of date, containing information about why. * * If we get a message from a peer who can't support the required quorum * features, we have to ignore them. This function will at least send * them a message about *why* they're being ignored -- if they're new * enough to support such a message. * * @param m A message from a monitor not supporting required features. We * take ownership of the reference. */ void nak_old_peer(MonOpRequestRef op); /** * Handle a message from some other participant declaring * we cannot join the quorum. * * Apparently the quorum requires some feature that we do not implement. Shut * down gracefully. * * @pre Election is on-going. * @post We've shut down. * * @param m A message with an operation type of OP_NAK */ void handle_nak(MonOpRequestRef op); /** * Send a ping to the specified peer. * @n optional time that we will use instead of calling ceph_clock_now() */ bool send_peer_ping(int peer, const utime_t *n=NULL); /** * Check the state of pinging the specified peer. This is our * "tick" for heartbeating; scheduled by itself and begin_peer_ping(). */ void ping_check(int peer); /** * Move the peer out of live_pinging into dead_pinging set * and schedule dead_ping()ing on it. */ void begin_dead_ping(int peer); /** * Checks that the peer is still marked for dead pinging, * and then marks it as dead for the appropriate interval. */ void dead_ping(int peer); /** * Handle a ping from another monitor and assimilate the data it contains. */ void handle_ping(MonOpRequestRef op); /** * Update our view of everybody else's connectivity based on the provided * tracker bufferlist */ void assimilate_connection_reports(const bufferlist& bl); public: /** * @defgroup Elector_h_ElectionOwner Functions from the ElectionOwner interface * @{ */ /* Commit the given epoch to our MonStore. * We also take the opportunity to persist our peer_tracker. */ void persist_epoch(epoch_t e); /* Read the epoch out of our MonStore */ epoch_t read_persisted_epoch() const; /* Write a nonsense key "election_writeable_test" to our MonStore */ void validate_store(); /* Reset my tracking. Currently, just call Monitor::join_election() */ void notify_bump_epoch(); /* Call a new election: Invoke Monitor::start_election() */ void trigger_new_election(); /* Retrieve rank from the Monitor */ int get_my_rank() const; /* Send MMonElection OP_PROPOSE to every monitor in the map. */ void propose_to_peers(epoch_t e, bufferlist &bl); /* bootstrap() the Monitor */ void reset_election(); /* Retrieve the Monitor::has_ever_joined member */ bool ever_participated() const; /* Retrieve monmap->size() */ unsigned paxos_size() const; /* Right now we don't disallow anybody */ std::set<int> disallowed_leaders; const std::set<int>& get_disallowed_leaders() const { return disallowed_leaders; } /** * Reset the expire_event timer so we can limit the amount of time we * will be electing. Clean up our peer_info. * * @post we reset the expire_event timer */ void _start(); /** * Send an MMonElection message deferring to the identified monitor. We * also increase the election timeout so the monitor we defer to * has some time to gather deferrals and actually win. (FIXME: necessary to protocol?) * * @post we sent an ack message to @p who * @post we reset the expire_event timer * * @param who Some other monitor's numeric identifier. */ void _defer_to(int who); /** * Our ElectionLogic told us we won an election! Identify the quorum * features, tell our new peons we've won, and invoke Monitor::win_election(). */ void message_victory(const std::set<int>& quorum); /* Check if rank is in mon->quorum */ bool is_current_member(int rank) const; /* * @} */ /** * Persist our peer_tracker to disk. */ void persist_connectivity_scores(); Elector *elector; /** * Create an Elector class * * @param m A Monitor instance * @param strategy The election strategy to use, defined in MonMap/ElectionLogic */ explicit Elector(Monitor *m, int strategy); virtual ~Elector() {} /** * Inform this class it is supposed to shutdown. * * We will simply cancel the @p expire_event if any exists. * * @post @p expire_event is cancelled */ void shutdown(); /** * Obtain our epoch from ElectionLogic. * * @returns Our current epoch number */ epoch_t get_epoch() { return logic.get_epoch(); } /** * If the Monitor knows there are no Paxos peers (so * we are rank 0 and there are no others) we can declare victory. */ void declare_standalone_victory() { logic.declare_standalone_victory(); } /** * Tell the Elector to start pinging a given peer. * Do this when you discover a peer and it has a rank assigned. * We do it ourselves on receipt of pings and when receiving other messages. */ void begin_peer_ping(int peer); /** * Handle received messages. * * We will ignore all messages that are not of type @p MSG_MON_ELECTION * (i.e., messages whose interface is not of type @p MMonElection). All of * those that are will then be dispatched to their operation-specific * functions. * * @param m A received message */ void dispatch(MonOpRequestRef op); /** * Call an election. * * This function simply calls ElectionLogic::start. */ void call_election() { logic.start(); } /** * Stop participating in subsequent Elections. * * @post @p participating is false */ void stop_participating() { logic.participating = false; } /** * Start participating in Elections. * * If we are already participating (i.e., @p participating is true), then * calling this function is moot. * * However, if we are not participating (i.e., @p participating is false), * then we will start participating by setting @p participating to true and * we will call for an Election. * * @post @p participating is true */ void start_participating(); /** * Check if our peer_tracker is self-consistent, not suffering from * https://tracker.ceph.com/issues/58049 */ bool peer_tracker_is_clean(); /** * Forget everything about our peers. :( */ void notify_clear_peer_state(); /** * Notify that our local rank has changed * and we may need to update internal data structures. */ void notify_rank_changed(int new_rank); /** * A peer has been removed so we should clean up state related to it. * This is safe to call even if we haven't joined or are currently * in a quorum. */ void notify_rank_removed(unsigned rank_removed, unsigned new_rank); void notify_strategy_maybe_changed(int strategy); /** * Set the disallowed leaders. * * If you call this and the new disallowed set * contains your current leader, you are * responsible for calling an election! * * @returns false if the set is unchanged, * true if the set changed */ bool set_disallowed_leaders(const std::set<int>& dl) { if (dl == disallowed_leaders) return false; disallowed_leaders = dl; return true; } void dump_connection_scores(Formatter *f) { f->open_object_section("connection scores"); peer_tracker.dump(f); f->close_section(); } /** * @} */ }; #endif
12,433
29.550369
88
h
null
ceph-main/src/mon/FSCommands.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) 2017 Red Hat Ltd * * 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 "OSDMonitor.h" #include "FSCommands.h" #include "MDSMonitor.h" #include "MgrStatMonitor.h" #include "mds/cephfs_features.h" using TOPNSPC::common::cmd_getval; using std::dec; using std::hex; using std::list; using std::map; using std::make_pair; using std::pair; using std::set; using std::string; using std::to_string; using std::vector; using ceph::bufferlist; using ceph::decode; using ceph::encode; using ceph::ErasureCodeInterfaceRef; using ceph::ErasureCodeProfile; using ceph::Formatter; using ceph::JSONFormatter; using ceph::make_message; using ceph::mono_clock; using ceph::mono_time; class FlagSetHandler : public FileSystemCommandHandler { public: FlagSetHandler() : FileSystemCommandHandler("fs flag set") { } int handle( Monitor *mon, FSMap& fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { string flag_name; cmd_getval(cmdmap, "flag_name", flag_name); string flag_val; cmd_getval(cmdmap, "val", flag_val); bool sure = false; cmd_getval(cmdmap, "yes_i_really_mean_it", sure); if (flag_name == "enable_multiple") { bool flag_bool = false; int r = parse_bool(flag_val, &flag_bool, ss); if (r != 0) { ss << "Invalid boolean value '" << flag_val << "'"; return r; } fsmap.set_enable_multiple(flag_bool); return 0; } else { ss << "Unknown flag '" << flag_name << "'"; return -EINVAL; } } }; class FailHandler : public FileSystemCommandHandler { public: FailHandler() : FileSystemCommandHandler("fs fail") { } int handle( Monitor* mon, FSMap& fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream& ss) override { if (!mon->osdmon()->is_writeable()) { // not allowed to write yet, so retry when we can mon->osdmon()->wait_for_writeable(op, new PaxosService::C_RetryMessage(mon->mdsmon(), op)); return -EAGAIN; } std::string fs_name; if (!cmd_getval(cmdmap, "fs_name", fs_name) || fs_name.empty()) { ss << "Missing filesystem name"; return -EINVAL; } auto fs = fsmap.get_filesystem(fs_name); auto f = [](auto fs) { fs->mds_map.set_flag(CEPH_MDSMAP_NOT_JOINABLE); }; fsmap.modify_filesystem(fs->fscid, std::move(f)); std::vector<mds_gid_t> to_fail; for (const auto& p : fs->mds_map.get_mds_info()) { to_fail.push_back(p.first); } for (const auto& gid : to_fail) { mon->mdsmon()->fail_mds_gid(fsmap, gid); } if (!to_fail.empty()) { mon->osdmon()->propose_pending(); } ss << fs_name; ss << " marked not joinable; MDS cannot join the cluster. All MDS ranks marked failed."; return 0; } }; class FsNewHandler : public FileSystemCommandHandler { public: explicit FsNewHandler(Paxos *paxos) : FileSystemCommandHandler("fs new"), m_paxos(paxos) { } int handle( Monitor *mon, FSMap& fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { ceph_assert(m_paxos->is_plugged()); string metadata_name; cmd_getval(cmdmap, "metadata", metadata_name); int64_t metadata = mon->osdmon()->osdmap.lookup_pg_pool_name(metadata_name); if (metadata < 0) { ss << "pool '" << metadata_name << "' does not exist"; return -ENOENT; } string data_name; cmd_getval(cmdmap, "data", data_name); int64_t data = mon->osdmon()->osdmap.lookup_pg_pool_name(data_name); if (data < 0) { ss << "pool '" << data_name << "' does not exist"; return -ENOENT; } if (data == 0) { ss << "pool '" << data_name << "' has id 0, which CephFS does not allow. Use another pool or recreate it to get a non-zero pool id."; return -EINVAL; } string fs_name; cmd_getval(cmdmap, "fs_name", fs_name); if (fs_name.empty()) { // Ensure fs name is not empty so that we can implement // commmands that refer to FS by name in future. ss << "Filesystem name may not be empty"; return -EINVAL; } if (fsmap.get_filesystem(fs_name)) { auto fs = fsmap.get_filesystem(fs_name); if (*(fs->mds_map.get_data_pools().begin()) == data && fs->mds_map.get_metadata_pool() == metadata) { // Identical FS created already, this is a no-op ss << "filesystem '" << fs_name << "' already exists"; return 0; } else { ss << "filesystem already exists with name '" << fs_name << "'"; return -EINVAL; } } bool force = false; cmd_getval(cmdmap, "force", force); const pool_stat_t *stat = mon->mgrstatmon()->get_pool_stat(metadata); if (stat) { int64_t metadata_num_objects = stat->stats.sum.num_objects; if (!force && metadata_num_objects > 0) { ss << "pool '" << metadata_name << "' already contains some objects. Use an empty pool instead."; return -EINVAL; } } if (fsmap.filesystem_count() > 0 && !fsmap.get_enable_multiple()) { ss << "Creation of multiple filesystems is disabled. To enable " "this experimental feature, use 'ceph fs flag set enable_multiple " "true'"; return -EINVAL; } bool allow_overlay = false; cmd_getval(cmdmap, "allow_dangerous_metadata_overlay", allow_overlay); for (auto& fs : fsmap.get_filesystems()) { const std::vector<int64_t> &data_pools = fs->mds_map.get_data_pools(); if ((std::find(data_pools.begin(), data_pools.end(), data) != data_pools.end() || fs->mds_map.get_metadata_pool() == metadata) && !allow_overlay) { ss << "Filesystem '" << fs_name << "' is already using one of the specified RADOS pools. This should ONLY be done in emergencies and after careful reading of the documentation. Pass --allow-dangerous-metadata-overlay to permit this."; return -EINVAL; } } int64_t fscid = FS_CLUSTER_ID_NONE; if (cmd_getval(cmdmap, "fscid", fscid)) { if (!force) { ss << "Pass --force to create a file system with a specific ID"; return -EINVAL; } if (fsmap.filesystem_exists(fscid)) { ss << "filesystem already exists with id '" << fscid << "'"; return -EINVAL; } } pg_pool_t const *data_pool = mon->osdmon()->osdmap.get_pg_pool(data); ceph_assert(data_pool != NULL); // Checked it existed above pg_pool_t const *metadata_pool = mon->osdmon()->osdmap.get_pg_pool(metadata); ceph_assert(metadata_pool != NULL); // Checked it existed above int r = _check_pool(mon->osdmon()->osdmap, data, POOL_DATA_DEFAULT, force, &ss, allow_overlay); if (r < 0) { return r; } r = _check_pool(mon->osdmon()->osdmap, metadata, POOL_METADATA, force, &ss, allow_overlay); if (r < 0) { return r; } if (!mon->osdmon()->is_writeable()) { // not allowed to write yet, so retry when we can mon->osdmon()->wait_for_writeable(op, new PaxosService::C_RetryMessage(mon->mdsmon(), op)); return -EAGAIN; } mon->osdmon()->do_application_enable(data, pg_pool_t::APPLICATION_NAME_CEPHFS, "data", fs_name, true); mon->osdmon()->do_application_enable(metadata, pg_pool_t::APPLICATION_NAME_CEPHFS, "metadata", fs_name, true); mon->osdmon()->do_set_pool_opt(metadata, pool_opts_t::RECOVERY_PRIORITY, static_cast<int64_t>(5)); mon->osdmon()->do_set_pool_opt(metadata, pool_opts_t::PG_NUM_MIN, static_cast<int64_t>(16)); mon->osdmon()->do_set_pool_opt(metadata, pool_opts_t::PG_AUTOSCALE_BIAS, static_cast<double>(4.0)); mon->osdmon()->propose_pending(); bool recover = false; cmd_getval(cmdmap, "recover", recover); // All checks passed, go ahead and create. auto&& fs = fsmap.create_filesystem(fs_name, metadata, data, mon->get_quorum_con_features(), fscid, recover); ss << "new fs with metadata pool " << metadata << " and data pool " << data; if (recover) { return 0; } // assign a standby to rank 0 to avoid health warnings auto info = fsmap.find_replacement_for({fs->fscid, 0}); if (info) { mon->clog->info() << info->human_name() << " assigned to filesystem " << fs_name << " as rank 0"; fsmap.promote(info->global_id, *fs, 0); } return 0; } private: Paxos *m_paxos; }; class SetHandler : public FileSystemCommandHandler { public: SetHandler() : FileSystemCommandHandler("fs set") {} int handle( Monitor *mon, FSMap& fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { std::string fs_name; if (!cmd_getval(cmdmap, "fs_name", fs_name) || fs_name.empty()) { ss << "Missing filesystem name"; return -EINVAL; } auto fs = fsmap.get_filesystem(fs_name); string var; if (!cmd_getval(cmdmap, "var", var) || var.empty()) { ss << "Invalid variable"; return -EINVAL; } string val; string interr; int64_t n = 0; if (!cmd_getval(cmdmap, "val", val)) { return -EINVAL; } // we got a string. see if it contains an int. n = strict_strtoll(val.c_str(), 10, &interr); if (var == "max_mds") { // NOTE: see also "mds set_max_mds", which can modify the same field. if (interr.length()) { ss << interr; return -EINVAL; } if (n <= 0) { ss << "You must specify at least one MDS"; return -EINVAL; } if (n > 1 && n > fs->mds_map.get_max_mds()) { if (fs->mds_map.was_snaps_ever_allowed() && !fs->mds_map.allows_multimds_snaps()) { ss << "multi-active MDS is not allowed while there are snapshots possibly created by pre-mimic MDS"; return -EINVAL; } } if (n > MAX_MDS) { ss << "may not have more than " << MAX_MDS << " MDS ranks"; return -EINVAL; } fsmap.modify_filesystem( fs->fscid, [n](std::shared_ptr<Filesystem> fs) { fs->mds_map.clear_flag(CEPH_MDSMAP_NOT_JOINABLE); fs->mds_map.set_max_mds(n); }); } else if (var == "inline_data") { bool enable_inline = false; int r = parse_bool(val, &enable_inline, ss); if (r != 0) { return r; } if (enable_inline) { bool confirm = false; cmd_getval(cmdmap, "yes_i_really_really_mean_it", confirm); if (!confirm) { ss << "Inline data support is deprecated and will be removed in a future release. " << "Add --yes-i-really-really-mean-it if you are certain you want this enabled."; return -EPERM; } ss << "inline data enabled"; fsmap.modify_filesystem( fs->fscid, [](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_inline_data_enabled(true); }); } else { ss << "inline data disabled"; fsmap.modify_filesystem( fs->fscid, [](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_inline_data_enabled(false); }); } } else if (var == "balancer") { if (val.empty()) { ss << "unsetting the metadata load balancer"; } else { ss << "setting the metadata load balancer to " << val; } fsmap.modify_filesystem( fs->fscid, [val](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_balancer(val); }); return true; } else if (var == "bal_rank_mask") { if (val.empty()) { ss << "bal_rank_mask may not be empty"; return -EINVAL; } if (fs->mds_map.check_special_bal_rank_mask(val, MDSMap::BAL_RANK_MASK_TYPE_ANY) == false) { std::string bin_string; int r = fs->mds_map.hex2bin(val, bin_string, MAX_MDS, ss); if (r != 0) { return r; } } ss << "setting the metadata balancer rank mask to " << val; fsmap.modify_filesystem( fs->fscid, [val](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_bal_rank_mask(val); }); return true; } else if (var == "max_file_size") { if (interr.length()) { ss << var << " requires an integer value"; return -EINVAL; } if (n < CEPH_MIN_STRIPE_UNIT) { ss << var << " must at least " << CEPH_MIN_STRIPE_UNIT; return -ERANGE; } fsmap.modify_filesystem( fs->fscid, [n](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_max_filesize(n); }); } else if (var == "max_xattr_size") { if (interr.length()) { ss << var << " requires an integer value"; return -EINVAL; } fsmap.modify_filesystem( fs->fscid, [n](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_max_xattr_size(n); }); } else if (var == "allow_new_snaps") { bool enable_snaps = false; int r = parse_bool(val, &enable_snaps, ss); if (r != 0) { return r; } if (!enable_snaps) { fsmap.modify_filesystem( fs->fscid, [](std::shared_ptr<Filesystem> fs) { fs->mds_map.clear_snaps_allowed(); }); ss << "disabled new snapshots"; } else { fsmap.modify_filesystem( fs->fscid, [](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_snaps_allowed(); }); ss << "enabled new snapshots"; } } else if (var == "allow_multimds") { ss << "Multiple MDS is always enabled. Use the max_mds" << " parameter to control the number of active MDSs" << " allowed. This command is DEPRECATED and will be" << " REMOVED from future releases."; } else if (var == "allow_multimds_snaps") { bool enable = false; int r = parse_bool(val, &enable, ss); if (r != 0) { return r; } string confirm; if (!cmd_getval(cmdmap, "confirm", confirm) || confirm != "--yes-i-am-really-a-mds") { ss << "Warning! This command is for MDS only. Do not run it manually"; return -EPERM; } if (enable) { ss << "enabled multimds with snapshot"; fsmap.modify_filesystem( fs->fscid, [](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_multimds_snaps_allowed(); }); } else { ss << "disabled multimds with snapshot"; fsmap.modify_filesystem( fs->fscid, [](std::shared_ptr<Filesystem> fs) { fs->mds_map.clear_multimds_snaps_allowed(); }); } } else if (var == "allow_dirfrags") { ss << "Directory fragmentation is now permanently enabled." << " This command is DEPRECATED and will be REMOVED from future releases."; } else if (var == "down") { bool is_down = false; int r = parse_bool(val, &is_down, ss); if (r != 0) { return r; } ss << fs->mds_map.get_fs_name(); fsmap.modify_filesystem( fs->fscid, [is_down](std::shared_ptr<Filesystem> fs) { if (is_down) { if (fs->mds_map.get_max_mds() > 0) { fs->mds_map.set_old_max_mds(); fs->mds_map.set_max_mds(0); } /* else already down! */ } else { mds_rank_t oldmax = fs->mds_map.get_old_max_mds(); fs->mds_map.set_max_mds(oldmax ? oldmax : 1); } }); if (is_down) { ss << " marked down. "; } else { ss << " marked up, max_mds = " << fs->mds_map.get_max_mds(); } } else if (var == "cluster_down" || var == "joinable") { bool joinable = true; int r = parse_bool(val, &joinable, ss); if (r != 0) { return r; } if (var == "cluster_down") { joinable = !joinable; } ss << fs->mds_map.get_fs_name(); fsmap.modify_filesystem( fs->fscid, [joinable](std::shared_ptr<Filesystem> fs) { if (joinable) { fs->mds_map.clear_flag(CEPH_MDSMAP_NOT_JOINABLE); } else { fs->mds_map.set_flag(CEPH_MDSMAP_NOT_JOINABLE); } }); if (joinable) { ss << " marked joinable; MDS may join as newly active."; } else { ss << " marked not joinable; MDS cannot join as newly active."; } if (var == "cluster_down") { ss << " WARNING: cluster_down flag is deprecated and will be" << " removed in a future version. Please use \"joinable\"."; } } else if (var == "standby_count_wanted") { if (interr.length()) { ss << var << " requires an integer value"; return -EINVAL; } if (n < 0) { ss << var << " must be non-negative"; return -ERANGE; } fsmap.modify_filesystem( fs->fscid, [n](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_standby_count_wanted(n); }); } else if (var == "session_timeout") { if (interr.length()) { ss << var << " requires an integer value"; return -EINVAL; } if (n < 30) { ss << var << " must be at least 30s"; return -ERANGE; } fsmap.modify_filesystem( fs->fscid, [n](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_session_timeout((uint32_t)n); }); } else if (var == "session_autoclose") { if (interr.length()) { ss << var << " requires an integer value"; return -EINVAL; } if (n < 30) { ss << var << " must be at least 30s"; return -ERANGE; } fsmap.modify_filesystem( fs->fscid, [n](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_session_autoclose((uint32_t)n); }); } else if (var == "allow_standby_replay") { bool allow = false; int r = parse_bool(val, &allow, ss); if (r != 0) { return r; } if (!allow) { if (!mon->osdmon()->is_writeable()) { // not allowed to write yet, so retry when we can mon->osdmon()->wait_for_writeable(op, new PaxosService::C_RetryMessage(mon->mdsmon(), op)); return -EAGAIN; } std::vector<mds_gid_t> to_fail; for (const auto& [gid, info]: fs->mds_map.get_mds_info()) { if (info.state == MDSMap::STATE_STANDBY_REPLAY) { to_fail.push_back(gid); } } for (const auto& gid : to_fail) { mon->mdsmon()->fail_mds_gid(fsmap, gid); } if (!to_fail.empty()) { mon->osdmon()->propose_pending(); } } auto f = [allow](auto& fs) { if (allow) { fs->mds_map.set_standby_replay_allowed(); } else { fs->mds_map.clear_standby_replay_allowed(); } }; fsmap.modify_filesystem(fs->fscid, std::move(f)); } else if (var == "min_compat_client") { auto vno = ceph_release_from_name(val.c_str()); if (!vno) { ss << "version " << val << " is not recognized"; return -EINVAL; } ss << "WARNING: setting min_compat_client is deprecated" " and may not do what you want.\n" "The oldest release to set is octopus.\n" "Please migrate to `ceph fs required_client_features ...`."; auto f = [vno](auto&& fs) { fs->mds_map.set_min_compat_client(vno); }; fsmap.modify_filesystem(fs->fscid, std::move(f)); } else if (var == "refuse_client_session") { bool refuse_session = false; int r = parse_bool(val, &refuse_session, ss); if (r != 0) { return r; } if (refuse_session) { if (!(fs->mds_map.test_flag(CEPH_MDSMAP_REFUSE_CLIENT_SESSION))) { fsmap.modify_filesystem( fs->fscid, [](std::shared_ptr<Filesystem> fs) { fs->mds_map.set_flag(CEPH_MDSMAP_REFUSE_CLIENT_SESSION); }); ss << "client(s) blocked from establishing new session(s)"; } else { ss << "client(s) already blocked from establishing new session(s)"; } } else { if (fs->mds_map.test_flag(CEPH_MDSMAP_REFUSE_CLIENT_SESSION)) { fsmap.modify_filesystem( fs->fscid, [](std::shared_ptr<Filesystem> fs) { fs->mds_map.clear_flag(CEPH_MDSMAP_REFUSE_CLIENT_SESSION); }); ss << "client(s) allowed to establish new session(s)"; } else { ss << "client(s) already allowed to establish new session(s)"; } } } else { ss << "unknown variable " << var; return -EINVAL; } return 0; } }; class CompatSetHandler : public FileSystemCommandHandler { public: CompatSetHandler() : FileSystemCommandHandler("fs compat") { } int handle( Monitor *mon, FSMap &fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { static const std::set<std::string> subops = {"rm_incompat", "rm_compat", "add_incompat", "add_compat"}; std::string fs_name; if (!cmd_getval(cmdmap, "fs_name", fs_name) || fs_name.empty()) { ss << "Missing filesystem name"; return -EINVAL; } auto fs = fsmap.get_filesystem(fs_name); if (fs == nullptr) { ss << "Not found: '" << fs_name << "'"; return -ENOENT; } string subop; if (!cmd_getval(cmdmap, "subop", subop) || subops.count(subop) == 0) { ss << "subop `" << subop << "' not recognized. Must be one of: " << subops; return -EINVAL; } int64_t feature; if (!cmd_getval(cmdmap, "feature", feature) || feature <= 0) { ss << "Invalid feature"; return -EINVAL; } if (fs->mds_map.get_num_up_mds() > 0) { ss << "file system must be failed or down; use `ceph fs fail` to bring down"; return -EBUSY; } CompatSet cs = fs->mds_map.compat; if (subop == "rm_compat") { if (cs.compat.contains(feature)) { ss << "removed compat feature " << feature; cs.compat.remove(feature); } else { ss << "already removed compat feature " << feature; } } else if (subop == "rm_incompat") { if (cs.incompat.contains(feature)) { ss << "removed incompat feature " << feature; cs.incompat.remove(feature); } else { ss << "already removed incompat feature " << feature; } } else if (subop == "add_compat" || subop == "add_incompat") { string feature_str; if (!cmd_getval(cmdmap, "feature_str", feature_str) || feature_str.empty()) { ss << "adding a feature requires a feature string"; return -EINVAL; } auto f = CompatSet::Feature(feature, feature_str); if (subop == "add_compat") { if (cs.compat.contains(feature)) { auto name = cs.compat.get_name(feature); if (name == feature_str) { ss << "feature already exists"; } else { ss << "feature with differing name `" << name << "' exists"; return -EEXIST; } } else { cs.compat.insert(f); ss << "added compat feature " << f; } } else if (subop == "add_incompat") { if (cs.incompat.contains(feature)) { auto name = cs.incompat.get_name(feature); if (name == feature_str) { ss << "feature already exists"; } else { ss << "feature with differing name `" << name << "' exists"; return -EEXIST; } } else { cs.incompat.insert(f); ss << "added incompat feature " << f; } } else ceph_assert(0); } else ceph_assert(0); auto modifyf = [cs = std::move(cs)](auto&& fs) { fs->mds_map.compat = cs; }; fsmap.modify_filesystem(fs->fscid, std::move(modifyf)); return 0; } }; class RequiredClientFeaturesHandler : public FileSystemCommandHandler { public: RequiredClientFeaturesHandler() : FileSystemCommandHandler("fs required_client_features") { } int handle( Monitor *mon, FSMap &fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { std::string fs_name; if (!cmd_getval(cmdmap, "fs_name", fs_name) || fs_name.empty()) { ss << "Missing filesystem name"; return -EINVAL; } auto fs = fsmap.get_filesystem(fs_name); if (fs == nullptr) { ss << "Not found: '" << fs_name << "'"; return -ENOENT; } string subop; if (!cmd_getval(cmdmap, "subop", subop) || (subop != "add" && subop != "rm")) { ss << "Must either add or rm a feature; " << subop << " is not recognized"; return -EINVAL; } string val; if (!cmd_getval(cmdmap, "val", val) || val.empty()) { ss << "Missing feature id/name"; return -EINVAL; } int feature = cephfs_feature_from_name(val); if (feature < 0) { string err; feature = strict_strtol(val.c_str(), 10, &err); if (err.length()) { ss << "Invalid feature name: " << val; return -EINVAL; } if (feature < 0 || feature > CEPHFS_FEATURE_MAX) { ss << "Invalid feature id: " << feature; return -EINVAL; } } if (subop == "add") { bool ret = false; fsmap.modify_filesystem( fs->fscid, [feature, &ret](auto&& fs) { if (fs->mds_map.get_required_client_features().test(feature)) return; fs->mds_map.add_required_client_feature(feature); ret = true; }); if (ret) { ss << "added feature '" << cephfs_feature_name(feature) << "' to required_client_features"; } else { ss << "feature '" << cephfs_feature_name(feature) << "' is already set"; } } else { bool ret = false; fsmap.modify_filesystem( fs->fscid, [feature, &ret](auto&& fs) { if (!fs->mds_map.get_required_client_features().test(feature)) return; fs->mds_map.remove_required_client_feature(feature); ret = true; }); if (ret) { ss << "removed feature '" << cephfs_feature_name(feature) << "' from required_client_features"; } else { ss << "feature '" << cephfs_feature_name(feature) << "' is already unset"; } } return 0; } }; class AddDataPoolHandler : public FileSystemCommandHandler { public: explicit AddDataPoolHandler(Paxos *paxos) : FileSystemCommandHandler("fs add_data_pool"), m_paxos(paxos) {} int handle( Monitor *mon, FSMap& fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { ceph_assert(m_paxos->is_plugged()); string poolname; cmd_getval(cmdmap, "pool", poolname); std::string fs_name; if (!cmd_getval(cmdmap, "fs_name", fs_name) || fs_name.empty()) { ss << "Missing filesystem name"; return -EINVAL; } int64_t poolid = mon->osdmon()->osdmap.lookup_pg_pool_name(poolname); if (poolid < 0) { string err; poolid = strict_strtol(poolname.c_str(), 10, &err); if (err.length()) { ss << "pool '" << poolname << "' does not exist"; return -ENOENT; } } int r = _check_pool(mon->osdmon()->osdmap, poolid, POOL_DATA_EXTRA, false, &ss); if (r != 0) { return r; } auto fs = fsmap.get_filesystem(fs_name); // no-op when the data_pool already on fs if (fs->mds_map.is_data_pool(poolid)) { ss << "data pool " << poolid << " is already on fs " << fs_name; return 0; } if (!mon->osdmon()->is_writeable()) { // not allowed to write yet, so retry when we can mon->osdmon()->wait_for_writeable(op, new PaxosService::C_RetryMessage(mon->mdsmon(), op)); return -EAGAIN; } mon->osdmon()->do_application_enable(poolid, pg_pool_t::APPLICATION_NAME_CEPHFS, "data", fs_name, true); mon->osdmon()->propose_pending(); fsmap.modify_filesystem( fs->fscid, [poolid](std::shared_ptr<Filesystem> fs) { fs->mds_map.add_data_pool(poolid); }); ss << "added data pool " << poolid << " to fsmap"; return 0; } private: Paxos *m_paxos; }; class SetDefaultHandler : public FileSystemCommandHandler { public: SetDefaultHandler() : FileSystemCommandHandler("fs set-default") {} int handle( Monitor *mon, FSMap& fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { std::string fs_name; cmd_getval(cmdmap, "fs_name", fs_name); auto fs = fsmap.get_filesystem(fs_name); if (fs == nullptr) { ss << "filesystem '" << fs_name << "' does not exist"; return -ENOENT; } fsmap.set_legacy_client_fscid(fs->fscid); return 0; } }; class RemoveFilesystemHandler : public FileSystemCommandHandler { public: RemoveFilesystemHandler() : FileSystemCommandHandler("fs rm") {} int handle( Monitor *mon, FSMap& fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { /* We may need to blocklist ranks. */ if (!mon->osdmon()->is_writeable()) { // not allowed to write yet, so retry when we can mon->osdmon()->wait_for_writeable(op, new PaxosService::C_RetryMessage(mon->mdsmon(), op)); return -EAGAIN; } // Check caller has correctly named the FS to delete // (redundant while there is only one FS, but command // syntax should apply to multi-FS future) string fs_name; cmd_getval(cmdmap, "fs_name", fs_name); auto fs = fsmap.get_filesystem(fs_name); if (fs == nullptr) { // Consider absence success to make deletes idempotent ss << "filesystem '" << fs_name << "' does not exist"; return 0; } // Check that no MDS daemons are active if (fs->mds_map.get_num_up_mds() > 0) { ss << "all MDS daemons must be inactive/failed before removing filesystem. See `ceph fs fail`."; return -EINVAL; } // Check for confirmation flag bool sure = false; cmd_getval(cmdmap, "yes_i_really_mean_it", sure); if (!sure) { ss << "this is a DESTRUCTIVE operation and will make data in your filesystem permanently" \ " inaccessible. Add --yes-i-really-mean-it if you are sure you wish to continue."; return -EPERM; } if (fsmap.get_legacy_client_fscid() == fs->fscid) { fsmap.set_legacy_client_fscid(FS_CLUSTER_ID_NONE); } std::vector<mds_gid_t> to_fail; // There may be standby_replay daemons left here for (const auto &i : fs->mds_map.get_mds_info()) { ceph_assert(i.second.state == MDSMap::STATE_STANDBY_REPLAY); to_fail.push_back(i.first); } for (const auto &gid : to_fail) { // Standby replays don't write, so it isn't important to // wait for an osdmap propose here: ignore return value. mon->mdsmon()->fail_mds_gid(fsmap, gid); } if (!to_fail.empty()) { mon->osdmon()->propose_pending(); /* maybe new blocklists */ } fsmap.erase_filesystem(fs->fscid); return 0; } }; class ResetFilesystemHandler : public FileSystemCommandHandler { public: ResetFilesystemHandler() : FileSystemCommandHandler("fs reset") {} int handle( Monitor *mon, FSMap& fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { string fs_name; cmd_getval(cmdmap, "fs_name", fs_name); auto fs = fsmap.get_filesystem(fs_name); if (fs == nullptr) { ss << "filesystem '" << fs_name << "' does not exist"; // Unlike fs rm, we consider this case an error return -ENOENT; } // Check that no MDS daemons are active if (fs->mds_map.get_num_up_mds() > 0) { ss << "all MDS daemons must be inactive before resetting filesystem: set the cluster_down flag" " and use `ceph mds fail` to make this so"; return -EINVAL; } // Check for confirmation flag bool sure = false; cmd_getval(cmdmap, "yes_i_really_mean_it", sure); if (!sure) { ss << "this is a potentially destructive operation, only for use by experts in disaster recovery. " "Add --yes-i-really-mean-it if you are sure you wish to continue."; return -EPERM; } fsmap.reset_filesystem(fs->fscid); return 0; } }; class RenameFilesystemHandler : public FileSystemCommandHandler { public: explicit RenameFilesystemHandler(Paxos *paxos) : FileSystemCommandHandler("fs rename"), m_paxos(paxos) { } int handle( Monitor *mon, FSMap& fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { ceph_assert(m_paxos->is_plugged()); string fs_name; cmd_getval(cmdmap, "fs_name", fs_name); auto fs = fsmap.get_filesystem(fs_name); string new_fs_name; cmd_getval(cmdmap, "new_fs_name", new_fs_name); auto new_fs = fsmap.get_filesystem(new_fs_name); if (fs == nullptr) { if (new_fs) { // make 'fs rename' idempotent ss << "File system may already have been renamed. Desired file system '" << new_fs_name << "' exists."; return 0; } else { ss << "File system '" << fs_name << "' does not exist"; return -ENOENT; } } if (new_fs) { ss << "Desired file system name '" << new_fs_name << "' already in use"; return -EINVAL; } if (fs->mirror_info.mirrored) { ss << "Mirroring is enabled on file system '"<< fs_name << "'. Disable mirroring on the " "file system after ensuring it's OK to do so, and then retry to rename."; return -EPERM; } // Check for confirmation flag bool sure = false; cmd_getval(cmdmap, "yes_i_really_mean_it", sure); if (!sure) { ss << "this is a potentially disruptive operation, clients' cephx credentials need reauthorized " "to access the file system and its pools with the new name. " "Add --yes-i-really-mean-it if you are sure you wish to continue."; return -EPERM; } if (!mon->osdmon()->is_writeable()) { // not allowed to write yet, so retry when we can mon->osdmon()->wait_for_writeable(op, new PaxosService::C_RetryMessage(mon->mdsmon(), op)); return -EAGAIN; } for (const auto p : fs->mds_map.get_data_pools()) { mon->osdmon()->do_application_enable(p, pg_pool_t::APPLICATION_NAME_CEPHFS, "data", new_fs_name, true); } mon->osdmon()->do_application_enable(fs->mds_map.get_metadata_pool(), pg_pool_t::APPLICATION_NAME_CEPHFS, "metadata", new_fs_name, true); mon->osdmon()->propose_pending(); auto f = [new_fs_name](auto fs) { fs->mds_map.set_fs_name(new_fs_name); }; fsmap.modify_filesystem(fs->fscid, std::move(f)); ss << "File system is renamed. cephx credentials authorized to " "old file system name need to be reauthorized to new file " "system name."; return 0; } private: Paxos *m_paxos; }; class RemoveDataPoolHandler : public FileSystemCommandHandler { public: RemoveDataPoolHandler() : FileSystemCommandHandler("fs rm_data_pool") {} int handle( Monitor *mon, FSMap& fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { string poolname; cmd_getval(cmdmap, "pool", poolname); std::string fs_name; if (!cmd_getval(cmdmap, "fs_name", fs_name) || fs_name.empty()) { ss << "Missing filesystem name"; return -EINVAL; } int64_t poolid = mon->osdmon()->osdmap.lookup_pg_pool_name(poolname); if (poolid < 0) { string err; poolid = strict_strtol(poolname.c_str(), 10, &err); if (err.length()) { ss << "pool '" << poolname << "' does not exist"; return -ENOENT; } else if (poolid < 0) { ss << "invalid pool id '" << poolid << "'"; return -EINVAL; } } ceph_assert(poolid >= 0); // Checked by parsing code above auto fs = fsmap.get_filesystem(fs_name); if (fs->mds_map.get_first_data_pool() == poolid) { ss << "cannot remove default data pool"; return -EINVAL; } int r = 0; fsmap.modify_filesystem(fs->fscid, [&r, poolid](std::shared_ptr<Filesystem> fs) { r = fs->mds_map.remove_data_pool(poolid); }); if (r == -ENOENT) { // It was already removed, succeed in silence return 0; } else if (r == 0) { // We removed it, succeed ss << "removed data pool " << poolid << " from fsmap"; return 0; } else { // Unexpected error, bubble up return r; } } }; /** * For commands with an alternative prefix */ template<typename T> class AliasHandler : public T { std::string alias_prefix; public: explicit AliasHandler(const std::string &new_prefix) : T() { alias_prefix = new_prefix; } std::string const &get_prefix() const override {return alias_prefix;} int handle( Monitor *mon, FSMap& fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { return T::handle(mon, fsmap, op, cmdmap, ss); } }; class MirrorHandlerEnable : public FileSystemCommandHandler { public: MirrorHandlerEnable() : FileSystemCommandHandler("fs mirror enable") {} int handle(Monitor *mon, FSMap &fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { std::string fs_name; if (!cmd_getval(cmdmap, "fs_name", fs_name) || fs_name.empty()) { ss << "Missing filesystem name"; return -EINVAL; } auto fs = fsmap.get_filesystem(fs_name); if (fs == nullptr) { ss << "Filesystem '" << fs_name << "' not found"; return -ENOENT; } if (fs->mirror_info.is_mirrored()) { return 0; } auto f = [](auto &&fs) { fs->mirror_info.enable_mirroring(); }; fsmap.modify_filesystem(fs->fscid, std::move(f)); return 0; } }; class MirrorHandlerDisable : public FileSystemCommandHandler { public: MirrorHandlerDisable() : FileSystemCommandHandler("fs mirror disable") {} int handle(Monitor *mon, FSMap &fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { std::string fs_name; if (!cmd_getval(cmdmap, "fs_name", fs_name) || fs_name.empty()) { ss << "Missing filesystem name"; return -EINVAL; } auto fs = fsmap.get_filesystem(fs_name); if (fs == nullptr) { ss << "Filesystem '" << fs_name << "' not found"; return -ENOENT; } if (!fs->mirror_info.is_mirrored()) { return 0; } auto f = [](auto &&fs) { fs->mirror_info.disable_mirroring(); }; fsmap.modify_filesystem(fs->fscid, std::move(f)); return 0; } }; class MirrorHandlerAddPeer : public FileSystemCommandHandler { public: MirrorHandlerAddPeer() : FileSystemCommandHandler("fs mirror peer_add") {} boost::optional<std::pair<string, string>> extract_remote_cluster_conf(const std::string &spec) { auto pos = spec.find("@"); if (pos == std::string_view::npos) { return boost::optional<std::pair<string, string>>(); } auto client = spec.substr(0, pos); auto cluster = spec.substr(pos+1); return std::make_pair(client, cluster); } bool peer_add(FSMap &fsmap, Filesystem::const_ref &&fs, const cmdmap_t &cmdmap, std::ostream &ss) { string peer_uuid; string remote_spec; string remote_fs_name; cmd_getval(cmdmap, "uuid", peer_uuid); cmd_getval(cmdmap, "remote_cluster_spec", remote_spec); cmd_getval(cmdmap, "remote_fs_name", remote_fs_name); // verify (and extract) remote cluster specification auto remote_conf = extract_remote_cluster_conf(remote_spec); if (!remote_conf) { ss << "invalid remote cluster spec -- should be <client>@<cluster>"; return false; } if (fs->mirror_info.has_peer(peer_uuid)) { ss << "peer already exists"; return true; } if (fs->mirror_info.has_peer((*remote_conf).first, (*remote_conf).second, remote_fs_name)) { ss << "peer already exists"; return true; } auto f = [peer_uuid, remote_conf, remote_fs_name](auto &&fs) { fs->mirror_info.peer_add(peer_uuid, (*remote_conf).first, (*remote_conf).second, remote_fs_name); }; fsmap.modify_filesystem(fs->fscid, std::move(f)); return true; } int handle(Monitor *mon, FSMap &fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { std::string fs_name; if (!cmd_getval(cmdmap, "fs_name", fs_name) || fs_name.empty()) { ss << "Missing filesystem name"; return -EINVAL; } auto fs = fsmap.get_filesystem(fs_name); if (fs == nullptr) { ss << "Filesystem '" << fs_name << "' not found"; return -ENOENT; } if (!fs->mirror_info.is_mirrored()) { ss << "Mirroring not enabled for filesystem '" << fs_name << "'"; return -EINVAL; } auto res = peer_add(fsmap, std::move(fs), cmdmap, ss); if (!res) { return -EINVAL; } return 0; } }; class MirrorHandlerRemovePeer : public FileSystemCommandHandler { public: MirrorHandlerRemovePeer() : FileSystemCommandHandler("fs mirror peer_remove") {} bool peer_remove(FSMap &fsmap, Filesystem::const_ref &&fs, const cmdmap_t &cmdmap, std::ostream &ss) { string peer_uuid; cmd_getval(cmdmap, "uuid", peer_uuid); if (!fs->mirror_info.has_peer(peer_uuid)) { ss << "cannot find peer with uuid: " << peer_uuid; return true; } auto f = [peer_uuid](auto &&fs) { fs->mirror_info.peer_remove(peer_uuid); }; fsmap.modify_filesystem(fs->fscid, std::move(f)); return true; } int handle(Monitor *mon, FSMap &fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) override { std::string fs_name; if (!cmd_getval(cmdmap, "fs_name", fs_name) || fs_name.empty()) { ss << "Missing filesystem name"; return -EINVAL; } auto fs = fsmap.get_filesystem(fs_name); if (fs == nullptr) { ss << "Filesystem '" << fs_name << "' not found"; return -ENOENT; } if (!fs->mirror_info.is_mirrored()) { ss << "Mirroring not enabled for filesystem '" << fs_name << "'"; return -EINVAL; } auto res = peer_remove(fsmap, std::move(fs), cmdmap, ss); if (!res) { return -EINVAL; } return 0; } }; std::list<std::shared_ptr<FileSystemCommandHandler> > FileSystemCommandHandler::load(Paxos *paxos) { std::list<std::shared_ptr<FileSystemCommandHandler> > handlers; handlers.push_back(std::make_shared<SetHandler>()); handlers.push_back(std::make_shared<FailHandler>()); handlers.push_back(std::make_shared<FlagSetHandler>()); handlers.push_back(std::make_shared<CompatSetHandler>()); handlers.push_back(std::make_shared<RequiredClientFeaturesHandler>()); handlers.push_back(std::make_shared<AddDataPoolHandler>(paxos)); handlers.push_back(std::make_shared<RemoveDataPoolHandler>()); handlers.push_back(std::make_shared<FsNewHandler>(paxos)); handlers.push_back(std::make_shared<RemoveFilesystemHandler>()); handlers.push_back(std::make_shared<ResetFilesystemHandler>()); handlers.push_back(std::make_shared<RenameFilesystemHandler>(paxos)); handlers.push_back(std::make_shared<SetDefaultHandler>()); handlers.push_back(std::make_shared<AliasHandler<SetDefaultHandler> >( "fs set_default")); handlers.push_back(std::make_shared<MirrorHandlerEnable>()); handlers.push_back(std::make_shared<MirrorHandlerDisable>()); handlers.push_back(std::make_shared<MirrorHandlerAddPeer>()); handlers.push_back(std::make_shared<MirrorHandlerRemovePeer>()); return handlers; } int FileSystemCommandHandler::_check_pool( OSDMap &osd_map, const int64_t pool_id, int type, bool force, std::ostream *ss, bool allow_overlay) const { ceph_assert(ss != NULL); const pg_pool_t *pool = osd_map.get_pg_pool(pool_id); if (!pool) { *ss << "pool id '" << pool_id << "' does not exist"; return -ENOENT; } if (pool->has_snaps()) { *ss << "pool(" << pool_id <<") already has mon-managed snaps; " "can't attach pool to fs"; return -EOPNOTSUPP; } const string& pool_name = osd_map.get_pool_name(pool_id); auto app_map = pool->application_metadata; if (!allow_overlay && !force && !app_map.empty()) { auto app = app_map.find(pg_pool_t::APPLICATION_NAME_CEPHFS); if (app != app_map.end()) { auto& [app_name, app_metadata] = *app; auto itr = app_metadata.find("data"); if (itr == app_metadata.end()) { itr = app_metadata.find("metadata"); } if (itr != app_metadata.end()) { auto& [type, filesystem] = *itr; *ss << "RADOS pool '" << pool_name << "' is already used by filesystem '" << filesystem << "' as a '" << type << "' pool for application '" << app_name << "'"; return -EINVAL; } } else { *ss << "RADOS pool '" << pool_name << "' has another non-CephFS application enabled."; return -EINVAL; } } if (pool->is_erasure()) { if (type == POOL_METADATA) { *ss << "pool '" << pool_name << "' (id '" << pool_id << "')" << " is an erasure-coded pool. Use of erasure-coded pools" << " for CephFS metadata is not permitted"; return -EINVAL; } else if (type == POOL_DATA_DEFAULT && !force) { *ss << "pool '" << pool_name << "' (id '" << pool_id << "')" " is an erasure-coded pool." " Use of an EC pool for the default data pool is discouraged;" " see the online CephFS documentation for more information." " Use --force to override."; return -EINVAL; } else if (!pool->allows_ecoverwrites()) { // non-overwriteable EC pools are only acceptable with a cache tier overlay if (!pool->has_tiers() || !pool->has_read_tier() || !pool->has_write_tier()) { *ss << "pool '" << pool_name << "' (id '" << pool_id << "')" << " is an erasure-coded pool, with no overwrite support"; return -EINVAL; } // That cache tier overlay must be writeback, not readonly (it's the // write operations like modify+truncate we care about support for) const pg_pool_t *write_tier = osd_map.get_pg_pool( pool->write_tier); ceph_assert(write_tier != NULL); // OSDMonitor shouldn't allow DNE tier if (write_tier->cache_mode == pg_pool_t::CACHEMODE_FORWARD || write_tier->cache_mode == pg_pool_t::CACHEMODE_READONLY) { *ss << "EC pool '" << pool_name << "' has a write tier (" << osd_map.get_pool_name(pool->write_tier) << ") that is configured " "to forward writes. Use a cache mode such as 'writeback' for " "CephFS"; return -EINVAL; } } } if (pool->is_tier()) { *ss << " pool '" << pool_name << "' (id '" << pool_id << "') is already in use as a cache tier."; return -EINVAL; } if (!force && !pool->application_metadata.empty() && pool->application_metadata.count( pg_pool_t::APPLICATION_NAME_CEPHFS) == 0) { *ss << " pool '" << pool_name << "' (id '" << pool_id << "') has a non-CephFS application enabled."; return -EINVAL; } // Nothing special about this pool, so it is permissible return 0; } int FileSystemCommandHandler::is_op_allowed( const MonOpRequestRef& op, const FSMap& fsmap, const cmdmap_t& cmdmap, std::ostream &ss) const { string fs_name; cmd_getval(cmdmap, "fs_name", fs_name); // so that fsmap can filtered and the original copy is untouched. FSMap fsmap_copy = fsmap; fsmap_copy.filter(op->get_session()->get_allowed_fs_names()); auto fs = fsmap_copy.get_filesystem(fs_name); if (fs == nullptr) { auto prefix = get_prefix(); /* let "fs rm" and "fs rename" handle idempotent cases where file systems do not exist */ if (!(prefix == "fs rm" || prefix == "fs rename") && fsmap.get_filesystem(fs_name) == nullptr) { ss << "Filesystem not found: '" << fs_name << "'"; return -ENOENT; } } if (!op->get_session()->fs_name_capable(fs_name, MON_CAP_W)) { ss << "Permission denied: '" << fs_name << "'"; return -EPERM; } return 1; }
49,127
28.001181
206
cc
null
ceph-main/src/mon/FSCommands.h
// -*- 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) 2017 Red Hat Ltd * * 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. * */ #ifndef FS_COMMANDS_H_ #define FS_COMMANDS_H_ #include "Monitor.h" #include "CommandHandler.h" #include "osd/OSDMap.h" #include "mds/FSMap.h" #include <string> #include <ostream> class FileSystemCommandHandler : protected CommandHandler { protected: std::string prefix; enum { POOL_METADATA, POOL_DATA_DEFAULT, POOL_DATA_EXTRA, }; /** * Return 0 if the pool is suitable for use with CephFS, or * in case of errors return a negative error code, and populate * the passed ostream with an explanation. * * @param metadata whether the pool will be for metadata (stricter checks) */ int _check_pool( OSDMap &osd_map, const int64_t pool_id, int type, bool force, std::ostream *ss, bool allow_overlay = false) const; virtual std::string const &get_prefix() const {return prefix;} public: FileSystemCommandHandler(const std::string &prefix_) : prefix(prefix_) {} virtual ~FileSystemCommandHandler() {} int is_op_allowed(const MonOpRequestRef& op, const FSMap& fsmap, const cmdmap_t& cmdmap, std::ostream &ss) const; int can_handle(std::string const &prefix_, MonOpRequestRef& op, FSMap& fsmap, const cmdmap_t& cmdmap, std::ostream &ss) const { if (get_prefix() != prefix_) { return 0; } if (get_prefix() == "fs new" || get_prefix() == "fs flag set") { return 1; } return is_op_allowed(op, fsmap, cmdmap, ss); } static std::list<std::shared_ptr<FileSystemCommandHandler> > load(Paxos *paxos); virtual int handle( Monitor *mon, FSMap &fsmap, MonOpRequestRef op, const cmdmap_t& cmdmap, std::ostream &ss) = 0; }; #endif
2,100
22.087912
82
h
null
ceph-main/src/mon/HealthMonitor.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) 2013 Inktank, Inc * * 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 <limits.h> #include <sstream> #include <regex> #include <time.h> #include <iterator> #include "include/ceph_assert.h" #include "include/common_fwd.h" #include "include/stringify.h" #include "mon/Monitor.h" #include "mon/HealthMonitor.h" #include "messages/MMonHealthChecks.h" #include "common/Formatter.h" #define dout_subsys ceph_subsys_mon #undef dout_prefix #define dout_prefix _prefix(_dout, mon, this) using namespace TOPNSPC::common; using namespace std::literals; using std::cerr; using std::cout; using std::dec; using std::hex; using std::list; using std::map; using std::make_pair; using std::ostream; using std::ostringstream; using std::pair; using std::set; using std::setfill; using std::string; using std::stringstream; using std::to_string; using std::vector; using std::unique_ptr; using ceph::bufferlist; using ceph::decode; using ceph::encode; using ceph::Formatter; using ceph::JSONFormatter; using ceph::mono_clock; using ceph::mono_time; using ceph::parse_timespan; using ceph::timespan_str; static ostream& _prefix(std::ostream *_dout, const Monitor &mon, const HealthMonitor *hmon) { return *_dout << "mon." << mon.name << "@" << mon.rank << "(" << mon.get_state_name() << ").health "; } HealthMonitor::HealthMonitor(Monitor &m, Paxos &p, const string& service_name) : PaxosService(m, p, service_name) { } void HealthMonitor::init() { dout(10) << __func__ << dendl; } void HealthMonitor::create_initial() { dout(10) << __func__ << dendl; } void HealthMonitor::update_from_paxos(bool *need_bootstrap) { version = get_last_committed(); dout(10) << __func__ << dendl; load_health(); bufferlist qbl; mon.store->get(service_name, "quorum", qbl); if (qbl.length()) { auto p = qbl.cbegin(); decode(quorum_checks, p); } else { quorum_checks.clear(); } bufferlist lbl; mon.store->get(service_name, "leader", lbl); if (lbl.length()) { auto p = lbl.cbegin(); decode(leader_checks, p); } else { leader_checks.clear(); } { bufferlist bl; mon.store->get(service_name, "mutes", bl); if (bl.length()) { auto p = bl.cbegin(); decode(mutes, p); } else { mutes.clear(); } } dout(20) << "dump:"; JSONFormatter jf(true); jf.open_object_section("health"); jf.open_object_section("quorum_health"); for (auto& p : quorum_checks) { string s = string("mon.") + stringify(p.first); jf.dump_object(s.c_str(), p.second); } jf.close_section(); jf.dump_object("leader_health", leader_checks); jf.close_section(); jf.flush(*_dout); *_dout << dendl; } void HealthMonitor::create_pending() { dout(10) << " " << version << dendl; pending_mutes = mutes; } void HealthMonitor::encode_pending(MonitorDBStore::TransactionRef t) { ++version; dout(10) << " " << version << dendl; put_last_committed(t, version); bufferlist qbl; encode(quorum_checks, qbl); t->put(service_name, "quorum", qbl); bufferlist lbl; encode(leader_checks, lbl); t->put(service_name, "leader", lbl); { bufferlist bl; encode(pending_mutes, bl); t->put(service_name, "mutes", bl); } health_check_map_t pending_health; // combine per-mon details carefully... map<string,set<string>> names; // code -> <mon names> for (auto p : quorum_checks) { for (auto q : p.second.checks) { names[q.first].insert(mon.monmap->get_name(p.first)); } pending_health.merge(p.second); } for (auto &p : pending_health.checks) { p.second.summary = std::regex_replace( p.second.summary, std::regex("%hasorhave%"), names[p.first].size() > 1 ? "have" : "has"); p.second.summary = std::regex_replace( p.second.summary, std::regex("%names%"), stringify(names[p.first])); p.second.summary = std::regex_replace( p.second.summary, std::regex("%plurals%"), names[p.first].size() > 1 ? "s" : ""); p.second.summary = std::regex_replace( p.second.summary, std::regex("%isorare%"), names[p.first].size() > 1 ? "are" : "is"); } pending_health.merge(leader_checks); encode_health(pending_health, t); } version_t HealthMonitor::get_trim_to() const { // we don't actually need *any* old states, but keep a few. if (version > 5) { return version - 5; } return 0; } bool HealthMonitor::preprocess_query(MonOpRequestRef op) { auto m = op->get_req<PaxosServiceMessage>(); switch (m->get_type()) { case MSG_MON_COMMAND: return preprocess_command(op); case MSG_MON_HEALTH_CHECKS: return false; default: mon.no_reply(op); derr << "Unhandled message type " << m->get_type() << dendl; return true; } } bool HealthMonitor::prepare_update(MonOpRequestRef op) { Message *m = op->get_req(); dout(7) << "prepare_update " << *m << " from " << m->get_orig_source_inst() << dendl; switch (m->get_type()) { case MSG_MON_HEALTH_CHECKS: return prepare_health_checks(op); case MSG_MON_COMMAND: return prepare_command(op); default: return false; } } bool HealthMonitor::preprocess_command(MonOpRequestRef op) { auto m = op->get_req<MMonCommand>(); std::stringstream ss; bufferlist rdata; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, rdata, get_last_committed()); return true; } MonSession *session = op->get_session(); if (!session) { mon.reply_command(op, -EACCES, "access denied", rdata, get_last_committed()); return true; } // more sanity checks try { string format; cmd_getval(cmdmap, "format", format); string prefix; cmd_getval(cmdmap, "prefix", prefix); } catch (const bad_cmd_get& e) { mon.reply_command(op, -EINVAL, e.what(), rdata, get_last_committed()); return true; } return false; } bool HealthMonitor::prepare_command(MonOpRequestRef op) { auto m = op->get_req<MMonCommand>(); std::stringstream ss; bufferlist rdata; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, rdata, get_last_committed()); return true; } MonSession *session = op->get_session(); if (!session) { mon.reply_command(op, -EACCES, "access denied", rdata, get_last_committed()); return true; } string format = cmd_getval_or<string>(cmdmap, "format", "plain"); boost::scoped_ptr<Formatter> f(Formatter::create(format)); string prefix; cmd_getval(cmdmap, "prefix", prefix); int r = 0; if (prefix == "health mute") { string code; bool sticky = false; if (!cmd_getval(cmdmap, "code", code) || code == "") { r = -EINVAL; ss << "must specify an alert code to mute"; goto out; } cmd_getval(cmdmap, "sticky", sticky); string ttl_str; utime_t ttl; std::chrono::seconds secs; if (cmd_getval(cmdmap, "ttl", ttl_str)) { try { secs = parse_timespan(ttl_str); if (secs == 0s) { throw std::invalid_argument("timespan = 0"); } } catch (const std::invalid_argument& e) { ss << "invalid duration: " << ttl_str << " (" << e.what() << ")"; r = -EINVAL; goto out; } ttl = ceph_clock_now(); ttl += std::chrono::duration<double>(secs).count(); } health_check_map_t all; gather_all_health_checks(&all); string summary; int64_t count = 0; if (!sticky) { auto p = all.checks.find(code); if (p == all.checks.end()) { r = -ENOENT; ss << "health alert " << code << " is not currently raised"; goto out; } count = p->second.count; summary = p->second.summary; } auto& m = pending_mutes[code]; m.code = code; m.ttl = ttl; m.sticky = sticky; m.summary = summary; m.count = count; } else if (prefix == "health unmute") { string code; if (cmd_getval(cmdmap, "code", code)) { pending_mutes.erase(code); } else { pending_mutes.clear(); } } else { ss << "Command '" << prefix << "' not implemented!"; r = -ENOSYS; } out: dout(4) << __func__ << " done, r=" << r << dendl; /* Compose response */ string rs; getline(ss, rs); if (r >= 0) { // success.. delay reply wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, r, rs, get_last_committed() + 1)); return true; } else { // reply immediately mon.reply_command(op, r, rs, rdata, get_last_committed()); return false; } } bool HealthMonitor::prepare_health_checks(MonOpRequestRef op) { auto m = op->get_req<MMonHealthChecks>(); // no need to check if it's changed, the peon has done so quorum_checks[m->get_source().num()] = std::move(m->health_checks); return true; } void HealthMonitor::tick() { if (!is_active()) { return; } dout(10) << __func__ << dendl; bool changed = false; if (check_member_health()) { changed = true; } if (!mon.is_leader()) { return; } if (check_leader_health()) { changed = true; } if (check_mutes()) { changed = true; } if (changed) { propose_pending(); } } bool HealthMonitor::check_mutes() { bool changed = true; auto now = ceph_clock_now(); health_check_map_t all; gather_all_health_checks(&all); auto p = pending_mutes.begin(); while (p != pending_mutes.end()) { if (p->second.ttl != utime_t() && p->second.ttl <= now) { mon.clog->info() << "Health alert mute " << p->first << " cleared (passed TTL " << p->second.ttl << ")"; p = pending_mutes.erase(p); changed = true; continue; } if (!p->second.sticky) { auto q = all.checks.find(p->first); if (q == all.checks.end()) { mon.clog->info() << "Health alert mute " << p->first << " cleared (health alert cleared)"; p = pending_mutes.erase(p); changed = true; continue; } if (p->second.count) { // count-based mute if (q->second.count > p->second.count) { mon.clog->info() << "Health alert mute " << p->first << " cleared (count increased from " << p->second.count << " to " << q->second.count << ")"; p = pending_mutes.erase(p); changed = true; continue; } if (q->second.count < p->second.count) { // rachet down the mute dout(10) << __func__ << " mute " << p->first << " count " << p->second.count << " -> " << q->second.count << dendl; p->second.count = q->second.count; changed = true; } } else { // summary-based mute if (p->second.summary != q->second.summary) { mon.clog->info() << "Health alert mute " << p->first << " cleared (summary changed)"; p = pending_mutes.erase(p); changed = true; continue; } } } ++p; } return changed; } void HealthMonitor::gather_all_health_checks(health_check_map_t *all) { for (auto& svc : mon.paxos_service) { all->merge(svc->get_health_checks()); } } health_status_t HealthMonitor::get_health_status( bool want_detail, Formatter *f, std::string *plain, const char *sep1, const char *sep2) { health_check_map_t all; gather_all_health_checks(&all); health_status_t r = HEALTH_OK; for (auto& p : all.checks) { if (!mutes.count(p.first)) { if (r > p.second.severity) { r = p.second.severity; } } } if (f) { f->open_object_section("health"); f->dump_stream("status") << r; f->open_object_section("checks"); for (auto& p : all.checks) { f->open_object_section(p.first.c_str()); p.second.dump(f, want_detail); f->dump_bool("muted", mutes.count(p.first)); f->close_section(); } f->close_section(); f->open_array_section("mutes"); for (auto& p : mutes) { f->dump_object("mute", p.second); } f->close_section(); f->close_section(); } else { auto now = ceph_clock_now(); // one-liner: HEALTH_FOO[ thing1[; thing2 ...]] string summary; for (auto& p : all.checks) { if (!mutes.count(p.first)) { if (!summary.empty()) { summary += sep2; } summary += p.second.summary; } } *plain = stringify(r); if (summary.size()) { *plain += sep1; *plain += summary; } if (!mutes.empty()) { if (summary.size()) { *plain += sep2; } else { *plain += sep1; } *plain += "(muted:"; for (auto& p : mutes) { *plain += " "; *plain += p.first; if (p.second.ttl) { if (p.second.ttl > now) { auto left = p.second.ttl; left -= now; *plain += "("s + utimespan_str(left) + ")"; } else { *plain += "(0s)"; } } } *plain += ")"; } *plain += "\n"; // detail if (want_detail) { for (auto& p : all.checks) { auto q = mutes.find(p.first); if (q != mutes.end()) { *plain += "(MUTED"; if (q->second.ttl != utime_t()) { if (q->second.ttl > now) { auto left = q->second.ttl; left -= now; *plain += " ttl "; *plain += utimespan_str(left); } else { *plain += "0s"; } } if (q->second.sticky) { *plain += ", STICKY"; } *plain += ") "; } *plain += "["s + short_health_string(p.second.severity) + "] " + p.first + ": " + p.second.summary + "\n"; for (auto& d : p.second.detail) { *plain += " "; *plain += d; *plain += "\n"; } } } } return r; } bool HealthMonitor::check_member_health() { dout(20) << __func__ << dendl; bool changed = false; const auto max = g_conf().get_val<uint64_t>("mon_health_max_detail"); // snapshot of usage DataStats stats; get_fs_stats(stats.fs_stats, g_conf()->mon_data.c_str()); map<string,uint64_t> extra; uint64_t store_size = mon.store->get_estimated_size(extra); ceph_assert(store_size > 0); stats.store_stats.bytes_total = store_size; stats.store_stats.bytes_sst = extra["sst"]; stats.store_stats.bytes_log = extra["log"]; stats.store_stats.bytes_misc = extra["misc"]; stats.last_update = ceph_clock_now(); dout(10) << __func__ << " avail " << stats.fs_stats.avail_percent << "%" << " total " << byte_u_t(stats.fs_stats.byte_total) << ", used " << byte_u_t(stats.fs_stats.byte_used) << ", avail " << byte_u_t(stats.fs_stats.byte_avail) << dendl; // MON_DISK_{LOW,CRIT,BIG} health_check_map_t next; if (stats.fs_stats.avail_percent <= g_conf()->mon_data_avail_crit) { stringstream ss, ss2; ss << "mon%plurals% %names% %isorare% very low on available space"; auto& d = next.add("MON_DISK_CRIT", HEALTH_ERR, ss.str(), 1); ss2 << "mon." << mon.name << " has " << stats.fs_stats.avail_percent << "% avail"; d.detail.push_back(ss2.str()); } else if (stats.fs_stats.avail_percent <= g_conf()->mon_data_avail_warn) { stringstream ss, ss2; ss << "mon%plurals% %names% %isorare% low on available space"; auto& d = next.add("MON_DISK_LOW", HEALTH_WARN, ss.str(), 1); ss2 << "mon." << mon.name << " has " << stats.fs_stats.avail_percent << "% avail"; d.detail.push_back(ss2.str()); } if (stats.store_stats.bytes_total >= g_conf()->mon_data_size_warn) { stringstream ss, ss2; ss << "mon%plurals% %names% %isorare% using a lot of disk space"; auto& d = next.add("MON_DISK_BIG", HEALTH_WARN, ss.str(), 1); ss2 << "mon." << mon.name << " is " << byte_u_t(stats.store_stats.bytes_total) << " >= mon_data_size_warn (" << byte_u_t(g_conf()->mon_data_size_warn) << ")"; d.detail.push_back(ss2.str()); } // OSD_NO_DOWN_OUT_INTERVAL { // Warn if 'mon_osd_down_out_interval' is set to zero. // Having this option set to zero on the leader acts much like the // 'noout' flag. It's hard to figure out what's going wrong with clusters // without the 'noout' flag set but acting like that just the same, so // we report a HEALTH_WARN in case this option is set to zero. // This is an ugly hack to get the warning out, but until we find a way // to spread global options throughout the mon cluster and have all mons // using a base set of the same options, we need to work around this sort // of things. // There's also the obvious drawback that if this is set on a single // monitor on a 3-monitor cluster, this warning will only be shown every // third monitor connection. if (g_conf()->mon_warn_on_osd_down_out_interval_zero && g_conf()->mon_osd_down_out_interval == 0) { ostringstream ss, ds; ss << "mon%plurals% %names% %hasorhave% mon_osd_down_out_interval set to 0"; auto& d = next.add("OSD_NO_DOWN_OUT_INTERVAL", HEALTH_WARN, ss.str(), 1); ds << "mon." << mon.name << " has mon_osd_down_out_interval set to 0"; d.detail.push_back(ds.str()); } } // AUTH_INSECURE_GLOBAL_ID_RECLAIM if (g_conf().get_val<bool>("mon_warn_on_insecure_global_id_reclaim") && g_conf().get_val<bool>("auth_allow_insecure_global_id_reclaim")) { // Warn if there are any clients that are insecurely renewing their global_id std::lock_guard l(mon.session_map_lock); list<std::string> detail; for (auto p = mon.session_map.sessions.begin(); p != mon.session_map.sessions.end(); ++p) { if ((*p)->global_id_status == global_id_status_t::RECLAIM_INSECURE) { ostringstream ds; ds << (*p)->entity_name << " at " << (*p)->addrs << " is using insecure global_id reclaim"; detail.push_back(ds.str()); if (detail.size() >= max) { detail.push_back("..."); break; } } } if (!detail.empty()) { ostringstream ss; ss << "client%plurals% %isorare% using insecure global_id reclaim"; auto& d = next.add("AUTH_INSECURE_GLOBAL_ID_RECLAIM", HEALTH_WARN, ss.str(), detail.size()); d.detail.swap(detail); } } // AUTH_INSECURE_GLOBAL_ID_RECLAIM_ALLOWED if (g_conf().get_val<bool>("mon_warn_on_insecure_global_id_reclaim_allowed") && g_conf().get_val<bool>("auth_allow_insecure_global_id_reclaim")) { ostringstream ss, ds; ss << "mon%plurals% %isorare% allowing insecure global_id reclaim"; auto& d = next.add("AUTH_INSECURE_GLOBAL_ID_RECLAIM_ALLOWED", HEALTH_WARN, ss.str(), 1); ds << "mon." << mon.name << " has auth_allow_insecure_global_id_reclaim set to true"; d.detail.push_back(ds.str()); } auto p = quorum_checks.find(mon.rank); if (p == quorum_checks.end()) { if (next.empty()) { return false; } } else { if (p->second == next) { return false; } } if (mon.is_leader()) { // prepare to propose quorum_checks[mon.rank] = next; changed = true; } else { // tell the leader mon.send_mon_message(new MMonHealthChecks(next), mon.get_leader()); } return changed; } bool HealthMonitor::check_leader_health() { dout(20) << __func__ << dendl; bool changed = false; // prune quorum_health { auto& qset = mon.get_quorum(); auto p = quorum_checks.begin(); while (p != quorum_checks.end()) { if (qset.count(p->first) == 0) { p = quorum_checks.erase(p); changed = true; } else { ++p; } } } health_check_map_t next; // DAEMON_OLD_VERSION if (g_conf().get_val<bool>("mon_warn_on_older_version")) { check_for_older_version(&next); } // MON_DOWN check_for_mon_down(&next); // MON_CLOCK_SKEW check_for_clock_skew(&next); // MON_MSGR2_NOT_ENABLED if (g_conf().get_val<bool>("mon_warn_on_msgr2_not_enabled")) { check_if_msgr2_enabled(&next); } if (next != leader_checks) { changed = true; leader_checks = next; } return changed; } void HealthMonitor::check_for_older_version(health_check_map_t *checks) { static ceph::coarse_mono_time old_version_first_time = ceph::coarse_mono_clock::zero(); auto now = ceph::coarse_mono_clock::now(); if (ceph::coarse_mono_clock::is_zero(old_version_first_time)) { old_version_first_time = now; } const auto warn_delay = g_conf().get_val<std::chrono::seconds>("mon_warn_older_version_delay"); if (now - old_version_first_time > warn_delay) { std::map<string, std::list<string> > all_versions; mon.get_all_versions(all_versions); if (all_versions.size() > 1) { dout(20) << __func__ << " all_versions=" << all_versions << dendl; // The last entry has the largest version dout(20) << __func__ << " highest version daemon count " << all_versions.rbegin()->second.size() << dendl; // Erase last element (the highest version running) all_versions.erase(all_versions.rbegin()->first); ceph_assert(all_versions.size() > 0); ostringstream ss; unsigned daemon_count = 0; for (auto& g : all_versions) { daemon_count += g.second.size(); } int ver_count = all_versions.size(); ceph_assert(!(daemon_count == 1 && ver_count != 1)); ss << "There " << (daemon_count == 1 ? "is a daemon" : "are daemons") << " running " << (ver_count > 1 ? "multiple old versions" : "an older version") << " of ceph"; health_status_t status; if (ver_count > 1) status = HEALTH_ERR; else status = HEALTH_WARN; auto& d = checks->add("DAEMON_OLD_VERSION", status, ss.str(), all_versions.size()); for (auto& g : all_versions) { ostringstream ds; for (auto& i : g.second) { // Daemon list ds << i << " "; } ds << (g.second.size() == 1 ? "is" : "are") << " running an older version of ceph: " << g.first; d.detail.push_back(ds.str()); } } else { old_version_first_time = ceph::coarse_mono_clock::zero(); } } } void HealthMonitor::check_for_mon_down(health_check_map_t *checks) { int max = mon.monmap->size(); int actual = mon.get_quorum().size(); const auto now = ceph::real_clock::now(); if (actual < max && now > mon.monmap->created.to_real_time() + g_conf().get_val<std::chrono::seconds>("mon_down_mkfs_grace")) { ostringstream ss; ss << (max-actual) << "/" << max << " mons down, quorum " << mon.get_quorum_names(); auto& d = checks->add("MON_DOWN", HEALTH_WARN, ss.str(), max - actual); set<int> q = mon.get_quorum(); for (int i=0; i<max; i++) { if (q.count(i) == 0) { ostringstream ss; ss << "mon." << mon.monmap->get_name(i) << " (rank " << i << ") addr " << mon.monmap->get_addrs(i) << " is down (out of quorum)"; d.detail.push_back(ss.str()); } } } } void HealthMonitor::check_for_clock_skew(health_check_map_t *checks) { if (!mon.timecheck_skews.empty()) { list<string> warns; list<string> details; for (auto& i : mon.timecheck_skews) { double skew = i.second; double latency = mon.timecheck_latencies[i.first]; string name = mon.monmap->get_name(i.first); ostringstream tcss; health_status_t tcstatus = mon.timecheck_status(tcss, skew, latency); if (tcstatus != HEALTH_OK) { warns.push_back(name); ostringstream tmp_ss; tmp_ss << "mon." << name << " " << tcss.str() << " (latency " << latency << "s)"; details.push_back(tmp_ss.str()); } } if (!warns.empty()) { ostringstream ss; ss << "clock skew detected on"; while (!warns.empty()) { ss << " mon." << warns.front(); warns.pop_front(); if (!warns.empty()) ss << ","; } auto& d = checks->add("MON_CLOCK_SKEW", HEALTH_WARN, ss.str(), details.size()); d.detail.swap(details); } } } void HealthMonitor::check_if_msgr2_enabled(health_check_map_t *checks) { if (g_conf().get_val<bool>("ms_bind_msgr2") && mon.monmap->get_required_features().contains_all( ceph::features::mon::FEATURE_NAUTILUS)) { list<string> details; for (auto& i : mon.monmap->mon_info) { if (!i.second.public_addrs.has_msgr2()) { ostringstream ds; ds << "mon." << i.first << " is not bound to a msgr2 port, only " << i.second.public_addrs; details.push_back(ds.str()); } } if (!details.empty()) { ostringstream ss; ss << details.size() << " monitors have not enabled msgr2"; auto &d = checks->add("MON_MSGR2_NOT_ENABLED", HEALTH_WARN, ss.str(), details.size()); d.detail.swap(details); } } }
24,509
26.757644
113
cc
null
ceph-main/src/mon/HealthMonitor.h
// -*- 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) 2013 Inktank, Inc * * 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. * */ #ifndef CEPH_HEALTH_MONITOR_H #define CEPH_HEALTH_MONITOR_H #include "mon/PaxosService.h" class HealthMonitor : public PaxosService { version_t version = 0; std::map<int,health_check_map_t> quorum_checks; // for each quorum member health_check_map_t leader_checks; // leader only std::map<std::string,health_mute_t> mutes; std::map<std::string,health_mute_t> pending_mutes; public: HealthMonitor(Monitor &m, Paxos &p, const std::string& service_name); /** * @defgroup HealthMonitor_Inherited_h Inherited abstract methods * @{ */ void init() override; bool preprocess_query(MonOpRequestRef op) override; bool prepare_update(MonOpRequestRef op) override; void create_initial() override; void update_from_paxos(bool *need_bootstrap) override; void create_pending() override; void encode_pending(MonitorDBStore::TransactionRef t) override; version_t get_trim_to() const override; void encode_full(MonitorDBStore::TransactionRef t) override { } void tick() override; void gather_all_health_checks(health_check_map_t *all); health_status_t get_health_status( bool want_detail, ceph::Formatter *f, std::string *plain, const char *sep1 = " ", const char *sep2 = "; "); /** * @} // HealthMonitor_Inherited_h */ private: bool preprocess_command(MonOpRequestRef op); bool prepare_command(MonOpRequestRef op); bool prepare_health_checks(MonOpRequestRef op); void check_for_older_version(health_check_map_t *checks); void check_for_mon_down(health_check_map_t *checks); void check_for_clock_skew(health_check_map_t *checks); void check_if_msgr2_enabled(health_check_map_t *checks); bool check_leader_health(); bool check_member_health(); bool check_mutes(); }; #endif // CEPH_HEALTH_MONITOR_H
2,202
27.986842
76
h
null
ceph-main/src/mon/KVMonitor.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "mon/Monitor.h" #include "mon/KVMonitor.h" #include "include/stringify.h" #include "messages/MKVData.h" #define dout_subsys ceph_subsys_mon #undef dout_prefix #define dout_prefix _prefix(_dout, mon, this) using std::ostream; using std::ostringstream; using std::set; using std::string; using std::stringstream; static ostream& _prefix(std::ostream *_dout, const Monitor &mon, const KVMonitor *hmon) { return *_dout << "mon." << mon.name << "@" << mon.rank << "(" << mon.get_state_name() << ").kv "; } const string KV_PREFIX = "mon_config_key"; const int MAX_HISTORY = 50; static bool is_binary_string(const string& s) { for (auto c : s) { // \n and \t are escaped in JSON; other control characters are not. if ((c < 0x20 && c != '\n' && c != '\t') || c >= 0x7f) { return true; } } return false; } KVMonitor::KVMonitor(Monitor &m, Paxos &p, const string& service_name) : PaxosService(m, p, service_name) { } void KVMonitor::init() { dout(10) << __func__ << dendl; } void KVMonitor::create_initial() { dout(10) << __func__ << dendl; version = 0; pending.clear(); } void KVMonitor::update_from_paxos(bool *need_bootstrap) { if (version == get_last_committed()) { return; } version = get_last_committed(); dout(10) << __func__ << " " << version << dendl; check_all_subs(); } void KVMonitor::create_pending() { dout(10) << " " << version << dendl; pending.clear(); } void KVMonitor::encode_pending(MonitorDBStore::TransactionRef t) { dout(10) << " " << (version+1) << dendl; put_last_committed(t, version+1); // record the delta for this commit point bufferlist bl; encode(pending, bl); put_version(t, version+1, bl); // make actual changes for (auto& p : pending) { string key = p.first; if (p.second) { dout(20) << __func__ << " set " << key << dendl; t->put(KV_PREFIX, key, *p.second); } else { dout(20) << __func__ << " rm " << key << dendl; t->erase(KV_PREFIX, key); } } } version_t KVMonitor::get_trim_to() const { // we don't need that many old states, but keep a few if (version > MAX_HISTORY) { return version - MAX_HISTORY; } return 0; } void KVMonitor::get_store_prefixes(set<string>& s) const { s.insert(service_name); s.insert(KV_PREFIX); } void KVMonitor::tick() { if (!is_active() || !mon.is_leader()) { return; } dout(10) << __func__ << dendl; } void KVMonitor::on_active() { } bool KVMonitor::preprocess_query(MonOpRequestRef op) { switch (op->get_req()->get_type()) { case MSG_MON_COMMAND: try { return preprocess_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); return true; } } return false; } bool KVMonitor::preprocess_command(MonOpRequestRef op) { auto m = op->get_req<MMonCommand>(); std::stringstream ss; int err = 0; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, get_last_committed()); return true; } string format = cmd_getval_or<string>(cmdmap, "format", "plain"); boost::scoped_ptr<Formatter> f(Formatter::create(format)); string prefix; cmd_getval(cmdmap, "prefix", prefix); string key; cmd_getval(cmdmap, "key", key); bufferlist odata; if (prefix == "config-key get") { err = mon.store->get(KV_PREFIX, key, odata); } else if (prefix == "config-key exists") { bool exists = mon.store->exists(KV_PREFIX, key); ss << "key '" << key << "'"; if (exists) { ss << " exists"; err = 0; } else { ss << " doesn't exist"; err = -ENOENT; } } else if (prefix == "config-key list" || prefix == "config-key ls") { if (!f) { f.reset(Formatter::create("json-pretty")); } KeyValueDB::Iterator iter = mon.store->get_iterator(KV_PREFIX); f->open_array_section("keys"); while (iter->valid()) { string key(iter->key()); f->dump_string("key", key); iter->next(); } f->close_section(); stringstream tmp_ss; f->flush(tmp_ss); odata.append(tmp_ss); err = 0; } else if (prefix == "config-key dump") { if (!f) { f.reset(Formatter::create("json-pretty")); } KeyValueDB::Iterator iter = mon.store->get_iterator(KV_PREFIX); if (key.size()) { iter->lower_bound(key); } f->open_object_section("config-key store"); while (iter->valid()) { if (key.size() && iter->key().find(key) != 0) { break; } string s = iter->value().to_str(); if (is_binary_string(s)) { ostringstream ss; ss << "<<< binary blob of length " << s.size() << " >>>"; f->dump_string(iter->key().c_str(), ss.str()); } else { f->dump_string(iter->key().c_str(), s); } iter->next(); } f->close_section(); stringstream tmp_ss; f->flush(tmp_ss); odata.append(tmp_ss); err = 0; } else { return false; } mon.reply_command(op, err, ss.str(), odata, get_last_committed()); return true; } bool KVMonitor::prepare_update(MonOpRequestRef op) { Message *m = op->get_req(); dout(7) << "prepare_update " << *m << " from " << m->get_orig_source_inst() << dendl; switch (m->get_type()) { case MSG_MON_COMMAND: try { return prepare_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); return true; } } return false; } bool KVMonitor::prepare_command(MonOpRequestRef op) { auto m = op->get_req<MMonCommand>(); std::stringstream ss; int err = 0; bufferlist odata; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, get_last_committed()); return true; } string prefix; cmd_getval(cmdmap, "prefix", prefix); string key; if (!cmd_getval(cmdmap, "key", key)) { err = -EINVAL; ss << "must specify a key"; goto reply; } if (prefix == "config-key set" || prefix == "config-key put") { bufferlist data; string val; if (cmd_getval(cmdmap, "val", val)) { // they specified a value in the command instead of a file data.append(val); } else if (m->get_data_len() > 0) { // they specified '-i <file>' data = m->get_data(); } if (data.length() > (size_t) g_conf()->mon_config_key_max_entry_size) { err = -EFBIG; // File too large ss << "error: entry size limited to " << g_conf()->mon_config_key_max_entry_size << " bytes. " << "Use 'mon config key max entry size' to manually adjust"; goto reply; } ss << "set " << key; pending[key] = data; goto update; } else if (prefix == "config-key del" || prefix == "config-key rm") { ss << "key deleted"; pending[key].reset(); goto update; } else { ss << "unknown command " << prefix; err = -EINVAL; } reply: mon.reply_command(op, err, ss.str(), odata, get_last_committed()); return false; update: // see if there is an actual change if (pending.empty()) { err = 0; goto reply; } force_immediate_propose(); // faster response wait_for_finished_proposal( op, new Monitor::C_Command( mon, op, 0, ss.str(), odata, get_last_committed() + 1)); return true; } static string _get_dmcrypt_prefix(const uuid_d& uuid, const string k) { return "dm-crypt/osd/" + stringify(uuid) + "/" + k; } bool KVMonitor::_have_prefix(const string &prefix) { KeyValueDB::Iterator iter = mon.store->get_iterator(KV_PREFIX); while (iter->valid()) { string key(iter->key()); size_t p = key.find(prefix); if (p != string::npos && p == 0) { return true; } iter->next(); } return false; } int KVMonitor::validate_osd_destroy( const int32_t id, const uuid_d& uuid) { string dmcrypt_prefix = _get_dmcrypt_prefix(uuid, ""); string daemon_prefix = "daemon-private/osd." + stringify(id) + "/"; if (!_have_prefix(dmcrypt_prefix) && !_have_prefix(daemon_prefix)) { return -ENOENT; } return 0; } void KVMonitor::do_osd_destroy(int32_t id, uuid_d& uuid) { string dmcrypt_prefix = _get_dmcrypt_prefix(uuid, ""); string daemon_prefix = "daemon-private/osd." + stringify(id) + "/"; for (auto& prefix : { dmcrypt_prefix, daemon_prefix }) { KeyValueDB::Iterator iter = mon.store->get_iterator(KV_PREFIX); iter->lower_bound(prefix); if (iter->key().find(prefix) != 0) { break; } pending[iter->key()].reset(); } propose_pending(); } int KVMonitor::validate_osd_new( const uuid_d& uuid, const string& dmcrypt_key, stringstream& ss) { string dmcrypt_prefix = _get_dmcrypt_prefix(uuid, "luks"); bufferlist value; value.append(dmcrypt_key); if (mon.store->exists(KV_PREFIX, dmcrypt_prefix)) { bufferlist existing_value; int err = mon.store->get(KV_PREFIX, dmcrypt_prefix, existing_value); if (err < 0) { dout(10) << __func__ << " unable to get dm-crypt key from store (r = " << err << ")" << dendl; return err; } if (existing_value.contents_equal(value)) { // both values match; this will be an idempotent op. return EEXIST; } ss << "dm-crypt key already exists and does not match"; return -EEXIST; } return 0; } void KVMonitor::do_osd_new( const uuid_d& uuid, const string& dmcrypt_key) { ceph_assert(paxos.is_plugged()); string dmcrypt_key_prefix = _get_dmcrypt_prefix(uuid, "luks"); bufferlist dmcrypt_key_value; dmcrypt_key_value.append(dmcrypt_key); pending[dmcrypt_key_prefix] = dmcrypt_key_value; propose_pending(); } void KVMonitor::check_sub(MonSession *s) { if (!s->authenticated) { dout(20) << __func__ << " not authenticated " << s->entity_name << dendl; return; } for (auto& p : s->sub_map) { if (p.first.find("kv:") == 0) { check_sub(p.second); } } } void KVMonitor::check_sub(Subscription *sub) { dout(10) << __func__ << " next " << sub->next << " have " << version << dendl; if (sub->next <= version) { maybe_send_update(sub); if (sub->onetime) { mon.with_session_map([sub](MonSessionMap& session_map) { session_map.remove_sub(sub); }); } } } void KVMonitor::check_all_subs() { dout(10) << __func__ << dendl; int updated = 0, total = 0; for (auto& i : mon.session_map.subs) { if (i.first.find("kv:") == 0) { auto p = i.second->begin(); while (!p.end()) { auto sub = *p; ++p; ++total; if (maybe_send_update(sub)) { ++updated; } } } } dout(10) << __func__ << " updated " << updated << " / " << total << dendl; } bool KVMonitor::maybe_send_update(Subscription *sub) { if (sub->next > version) { return false; } auto m = new MKVData; m->prefix = sub->type.substr(3); m->version = version; if (sub->next && sub->next > get_first_committed()) { // incremental m->incremental = true; for (version_t cur = sub->next; cur <= version; ++cur) { bufferlist bl; int err = get_version(cur, bl); ceph_assert(err == 0); std::map<std::string,std::optional<ceph::buffer::list>> pending; auto p = bl.cbegin(); ceph::decode(pending, p); for (auto& i : pending) { if (i.first.find(m->prefix) == 0) { m->data[i.first] = i.second; } } } dout(10) << __func__ << " incremental keys for " << m->prefix << ", v " << sub->next << ".." << version << ", " << m->data.size() << " keys" << dendl; } else { m->incremental = false; KeyValueDB::Iterator iter = mon.store->get_iterator(KV_PREFIX); iter->lower_bound(m->prefix); while (iter->valid() && iter->key().find(m->prefix) == 0) { m->data[iter->key()] = iter->value(); iter->next(); } dout(10) << __func__ << " sending full dump of " << m->prefix << ", " << m->data.size() << " keys" << dendl; } sub->session->con->send_message(m); sub->next = version + 1; return true; }
12,289
22.145009
77
cc
null
ceph-main/src/mon/KVMonitor.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <optional> #include "mon/PaxosService.h" class MonSession; extern const std::string KV_PREFIX; class KVMonitor : public PaxosService { version_t version = 0; std::map<std::string,std::optional<ceph::buffer::list>> pending; bool _have_prefix(const std::string &prefix); public: KVMonitor(Monitor &m, Paxos &p, const std::string& service_name); void init() override; void get_store_prefixes(std::set<std::string>& s) const override; bool preprocess_command(MonOpRequestRef op); bool prepare_command(MonOpRequestRef op); bool preprocess_query(MonOpRequestRef op) override; bool prepare_update(MonOpRequestRef op) override; void create_initial() override; void update_from_paxos(bool *need_bootstrap) override; void create_pending() override; void encode_pending(MonitorDBStore::TransactionRef t) override; version_t get_trim_to() const override; void encode_full(MonitorDBStore::TransactionRef t) override { } void on_active() override; void tick() override; int validate_osd_destroy(const int32_t id, const uuid_d& uuid); void do_osd_destroy(int32_t id, uuid_d& uuid); int validate_osd_new( const uuid_d& uuid, const std::string& dmcrypt_key, std::stringstream& ss); void do_osd_new(const uuid_d& uuid, const std::string& dmcrypt_key); void check_sub(MonSession *s); void check_sub(Subscription *sub); void check_all_subs(); bool maybe_send_update(Subscription *sub); // used by other services to adjust kv content; note that callers MUST ensure that // propose_pending() is called and a commit is forced to provide atomicity and // proper subscriber notifications. void enqueue_set(const std::string& key, bufferlist &v) { pending[key] = v; } void enqueue_rm(const std::string& key) { pending[key].reset(); } };
1,945
26.8
84
h
null
ceph-main/src/mon/LogMonitor.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. * */ /* -- Storage scheme -- Pre-quincy: - LogSummary contains last N entries for every channel - LogSummary (as "full") written on every commit - LogSummary contains "keys" which LogEntryKey hash_set for the same set of entries (for deduping) Quincy+: - LogSummary contains, for each channel, - start seq - end seq (last written seq + 1) - LogSummary contains an LRUSet for tracking dups - LogSummary written every N commits - each LogEntry written in a separate key - "%s/%08x" % (channel, seq) -> LogEntry - per-commit record includes channel -> begin (trim bounds) - 'external_log_to' meta records version to which we have logged externally */ #include <boost/algorithm/string/predicate.hpp> #include <iterator> #include <sstream> #include <syslog.h> #include "LogMonitor.h" #include "Monitor.h" #include "MonitorDBStore.h" #include "messages/MMonCommand.h" #include "messages/MLog.h" #include "messages/MLogAck.h" #include "common/Graylog.h" #include "common/Journald.h" #include "common/errno.h" #include "common/strtol.h" #include "include/ceph_assert.h" #include "include/str_list.h" #include "include/str_map.h" #include "include/compat.h" #include "include/utime_fmt.h" #define dout_subsys ceph_subsys_mon using namespace TOPNSPC::common; using std::cerr; using std::cout; using std::dec; using std::hex; using std::list; using std::map; using std::make_pair; using std::multimap; using std::ostream; using std::ostringstream; using std::pair; using std::set; using std::setfill; using std::string; using std::stringstream; using std::to_string; using std::vector; using std::unique_ptr; using ceph::bufferlist; using ceph::decode; using ceph::encode; using ceph::Formatter; using ceph::JSONFormatter; using ceph::make_message; using ceph::mono_clock; using ceph::mono_time; using ceph::timespan_str; string LogMonitor::log_channel_info::get_log_file(const string &channel) { dout(25) << __func__ << " for channel '" << channel << "'" << dendl; if (expanded_log_file.count(channel) == 0) { string fname = expand_channel_meta( get_str_map_key(log_file, channel, &CLOG_CONFIG_DEFAULT_KEY), channel); expanded_log_file[channel] = fname; dout(20) << __func__ << " for channel '" << channel << "' expanded to '" << fname << "'" << dendl; } return expanded_log_file[channel]; } void LogMonitor::log_channel_info::expand_channel_meta(map<string,string> &m) { dout(20) << __func__ << " expand map: " << m << dendl; for (map<string,string>::iterator p = m.begin(); p != m.end(); ++p) { m[p->first] = expand_channel_meta(p->second, p->first); } dout(20) << __func__ << " expanded map: " << m << dendl; } string LogMonitor::log_channel_info::expand_channel_meta( const string &input, const string &change_to) { size_t pos = string::npos; string s(input); while ((pos = s.find(LOG_META_CHANNEL)) != string::npos) { string tmp = s.substr(0, pos) + change_to; if (pos+LOG_META_CHANNEL.length() < s.length()) tmp += s.substr(pos+LOG_META_CHANNEL.length()); s = tmp; } dout(20) << __func__ << " from '" << input << "' to '" << s << "'" << dendl; return s; } bool LogMonitor::log_channel_info::do_log_to_syslog(const string &channel) { string v = get_str_map_key(log_to_syslog, channel, &CLOG_CONFIG_DEFAULT_KEY); // We expect booleans, but they are in k/v pairs, kept // as strings, in 'log_to_syslog'. We must ensure // compatibility with existing boolean handling, and so // we are here using a modified version of how // md_config_t::set_val_raw() handles booleans. We will // accept both 'true' and 'false', but will also check for // '1' and '0'. The main distiction between this and the // original code is that we will assume everything not '1', // '0', 'true' or 'false' to be 'false'. bool ret = false; if (boost::iequals(v, "false")) { ret = false; } else if (boost::iequals(v, "true")) { ret = true; } else { std::string err; int b = strict_strtol(v.c_str(), 10, &err); ret = (err.empty() && b == 1); } return ret; } ceph::logging::Graylog::Ref LogMonitor::log_channel_info::get_graylog( const string &channel) { dout(25) << __func__ << " for channel '" << channel << "'" << dendl; if (graylogs.count(channel) == 0) { auto graylog(std::make_shared<ceph::logging::Graylog>("mon")); graylog->set_fsid(g_conf().get_val<uuid_d>("fsid")); graylog->set_hostname(g_conf()->host); graylog->set_destination(get_str_map_key(log_to_graylog_host, channel, &CLOG_CONFIG_DEFAULT_KEY), atoi(get_str_map_key(log_to_graylog_port, channel, &CLOG_CONFIG_DEFAULT_KEY).c_str())); graylogs[channel] = graylog; dout(20) << __func__ << " for channel '" << channel << "' to graylog host '" << log_to_graylog_host[channel] << ":" << log_to_graylog_port[channel] << "'" << dendl; } return graylogs[channel]; } ceph::logging::JournaldClusterLogger &LogMonitor::log_channel_info::get_journald() { dout(25) << __func__ << dendl; if (!journald) { journald = std::make_unique<ceph::logging::JournaldClusterLogger>(); } return *journald; } void LogMonitor::log_channel_info::clear() { log_to_syslog.clear(); syslog_level.clear(); syslog_facility.clear(); log_file.clear(); expanded_log_file.clear(); log_file_level.clear(); log_to_graylog.clear(); log_to_graylog_host.clear(); log_to_graylog_port.clear(); log_to_journald.clear(); graylogs.clear(); journald.reset(); } LogMonitor::log_channel_info::log_channel_info() = default; LogMonitor::log_channel_info::~log_channel_info() = default; #undef dout_prefix #define dout_prefix _prefix(_dout, mon, get_last_committed()) static ostream& _prefix(std::ostream *_dout, Monitor &mon, version_t v) { return *_dout << "mon." << mon.name << "@" << mon.rank << "(" << mon.get_state_name() << ").log v" << v << " "; } ostream& operator<<(ostream &out, const LogMonitor &pm) { return out << "log"; } /* Tick function to update the map based on performance every N seconds */ void LogMonitor::tick() { if (!is_active()) return; dout(10) << *this << dendl; } void LogMonitor::create_initial() { dout(10) << "create_initial -- creating initial map" << dendl; LogEntry e; e.name = g_conf()->name; e.rank = entity_name_t::MON(mon.rank); e.addrs = mon.messenger->get_myaddrs(); e.stamp = ceph_clock_now(); e.prio = CLOG_INFO; e.channel = CLOG_CHANNEL_CLUSTER; std::stringstream ss; ss << "mkfs " << mon.monmap->get_fsid(); e.msg = ss.str(); e.seq = 0; pending_log.insert(pair<utime_t,LogEntry>(e.stamp, e)); } void LogMonitor::update_from_paxos(bool *need_bootstrap) { dout(10) << __func__ << dendl; version_t version = get_last_committed(); dout(10) << __func__ << " version " << version << " summary v " << summary.version << dendl; log_external_backlog(); if (version == summary.version) return; ceph_assert(version >= summary.version); version_t latest_full = get_version_latest_full(); dout(10) << __func__ << " latest full " << latest_full << dendl; if ((latest_full > 0) && (latest_full > summary.version)) { bufferlist latest_bl; get_version_full(latest_full, latest_bl); ceph_assert(latest_bl.length() != 0); dout(7) << __func__ << " loading summary e" << latest_full << dendl; auto p = latest_bl.cbegin(); decode(summary, p); dout(7) << __func__ << " loaded summary e" << summary.version << dendl; } // walk through incrementals while (version > summary.version) { bufferlist bl; int err = get_version(summary.version+1, bl); ceph_assert(err == 0); ceph_assert(bl.length()); auto p = bl.cbegin(); __u8 struct_v; decode(struct_v, p); if (struct_v == 1) { // legacy pre-quincy commits while (!p.end()) { LogEntry le; le.decode(p); dout(7) << "update_from_paxos applying incremental log " << summary.version+1 << " " << le << dendl; summary.add_legacy(le); } } else { uint32_t num; decode(num, p); while (num--) { LogEntry le; le.decode(p); dout(7) << "update_from_paxos applying incremental log " << summary.version+1 << " " << le << dendl; summary.recent_keys.insert(le.key()); summary.channel_info[le.channel].second++; // we may have logged past the (persisted) summary in a prior quorum if (version > external_log_to) { log_external(le); } } map<string,version_t> prune_channels_to; decode(prune_channels_to, p); for (auto& [channel, prune_to] : prune_channels_to) { dout(20) << __func__ << " channel " << channel << " pruned to " << prune_to << dendl; summary.channel_info[channel].first = prune_to; } // zero out pre-quincy fields (encode_pending needs this to reliably detect // upgrade) summary.tail_by_channel.clear(); summary.keys.clear(); } summary.version++; summary.prune(g_conf()->mon_log_max_summary); } dout(10) << " summary.channel_info " << summary.channel_info << dendl; external_log_to = version; mon.store->write_meta("external_log_to", stringify(external_log_to)); check_subs(); } void LogMonitor::log_external(const LogEntry& le) { string channel = le.channel; if (channel.empty()) { // keep retrocompatibility channel = CLOG_CHANNEL_CLUSTER; } if (channels.do_log_to_syslog(channel)) { string level = channels.get_level(channel); string facility = channels.get_facility(channel); if (level.empty() || facility.empty()) { derr << __func__ << " unable to log to syslog -- level or facility" << " not defined (level: " << level << ", facility: " << facility << ")" << dendl; } else { le.log_to_syslog(channels.get_level(channel), channels.get_facility(channel)); } } if (channels.do_log_to_graylog(channel)) { ceph::logging::Graylog::Ref graylog = channels.get_graylog(channel); if (graylog) { graylog->log_log_entry(&le); } dout(7) << "graylog: " << channel << " " << graylog << " host:" << channels.log_to_graylog_host << dendl; } if (channels.do_log_to_journald(channel)) { auto &journald = channels.get_journald(); journald.log_log_entry(le); dout(7) << "journald: " << channel << dendl; } bool do_stderr = g_conf().get_val<bool>("mon_cluster_log_to_stderr"); int fd = -1; if (g_conf()->mon_cluster_log_to_file) { if (this->log_rotated.exchange(false)) { this->log_external_close_fds(); } auto p = channel_fds.find(channel); if (p == channel_fds.end()) { string log_file = channels.get_log_file(channel); dout(20) << __func__ << " logging for channel '" << channel << "' to file '" << log_file << "'" << dendl; if (!log_file.empty()) { fd = ::open(log_file.c_str(), O_WRONLY|O_APPEND|O_CREAT|O_CLOEXEC, 0600); if (fd < 0) { int err = -errno; dout(1) << "unable to write to '" << log_file << "' for channel '" << channel << "': " << cpp_strerror(err) << dendl; } else { channel_fds[channel] = fd; } } } else { fd = p->second; } } if (do_stderr || fd >= 0) { fmt::format_to(std::back_inserter(log_buffer), "{}\n", le); if (fd >= 0) { int err = safe_write(fd, log_buffer.data(), log_buffer.size()); if (err < 0) { dout(1) << "error writing to '" << channels.get_log_file(channel) << "' for channel '" << channel << ": " << cpp_strerror(err) << dendl; ::close(fd); channel_fds.erase(channel); } } if (do_stderr) { fmt::print(std::cerr, "{} {}", channel, std::string_view(log_buffer.data(), log_buffer.size())); } log_buffer.clear(); } } void LogMonitor::log_external_close_fds() { for (auto& [channel, fd] : channel_fds) { if (fd >= 0) { dout(10) << __func__ << " closing " << channel << " (" << fd << ")" << dendl; ::close(fd); } } channel_fds.clear(); } /// catch external logs up to summary.version void LogMonitor::log_external_backlog() { if (!external_log_to) { std::string cur_str; int r = mon.store->read_meta("external_log_to", &cur_str); if (r == 0) { external_log_to = std::stoull(cur_str); dout(10) << __func__ << " initialized external_log_to = " << external_log_to << " (recorded log_to position)" << dendl; } else { // pre-quincy, we assumed that anything through summary.version was // logged externally. assert(r == -ENOENT); external_log_to = summary.version; dout(10) << __func__ << " initialized external_log_to = " << external_log_to << " (summary v " << summary.version << ")" << dendl; } } // we may have logged ahead of summary.version, but never ahead of paxos if (external_log_to > get_last_committed()) { derr << __func__ << " rewinding external_log_to from " << external_log_to << " -> " << get_last_committed() << " (sync_force? mon rebuild?)" << dendl; external_log_to = get_last_committed(); } if (external_log_to >= summary.version) { return; } if (auto first = get_first_committed(); external_log_to < first) { derr << __func__ << " local logs at " << external_log_to << ", skipping to " << first << dendl; external_log_to = first; // FIXME: write marker in each channel log file? } for (; external_log_to < summary.version; ++external_log_to) { bufferlist bl; int err = get_version(external_log_to+1, bl); ceph_assert(err == 0); ceph_assert(bl.length()); auto p = bl.cbegin(); __u8 v; decode(v, p); int32_t num = -2; if (v >= 2) { decode(num, p); } while ((num == -2 && !p.end()) || (num >= 0 && num--)) { LogEntry le; le.decode(p); log_external(le); } } mon.store->write_meta("external_log_to", stringify(external_log_to)); } void LogMonitor::create_pending() { pending_log.clear(); pending_keys.clear(); dout(10) << "create_pending v " << (get_last_committed() + 1) << dendl; } void LogMonitor::generate_logentry_key( const std::string& channel, version_t v, std::string *out) { out->append(channel); out->append("/"); char vs[10]; snprintf(vs, sizeof(vs), "%08llx", (unsigned long long)v); out->append(vs); } void LogMonitor::encode_pending(MonitorDBStore::TransactionRef t) { version_t version = get_last_committed() + 1; bufferlist bl; dout(10) << __func__ << " v" << version << dendl; if (mon.monmap->min_mon_release < ceph_release_t::quincy) { // legacy encoding for pre-quincy quorum __u8 struct_v = 1; encode(struct_v, bl); for (auto& p : pending_log) { p.second.encode(bl, mon.get_quorum_con_features()); } put_version(t, version, bl); put_last_committed(t, version); return; } __u8 struct_v = 2; encode(struct_v, bl); // first commit after upgrading to quincy? if (!summary.tail_by_channel.empty()) { // include past log entries for (auto& p : summary.tail_by_channel) { for (auto& q : p.second) { pending_log.emplace(make_pair(q.second.stamp, q.second)); } } } // record new entries auto pending_channel_info = summary.channel_info; uint32_t num = pending_log.size(); encode(num, bl); dout(20) << __func__ << " writing " << num << " entries" << dendl; for (auto& p : pending_log) { bufferlist ebl; p.second.encode(ebl, mon.get_quorum_con_features()); auto& bounds = pending_channel_info[p.second.channel]; version_t v = bounds.second++; std::string key; generate_logentry_key(p.second.channel, v, &key); t->put(get_service_name(), key, ebl); bl.claim_append(ebl); } // prune log entries? map<string,version_t> prune_channels_to; for (auto& [channel, info] : summary.channel_info) { if (info.second - info.first > g_conf()->mon_log_max) { const version_t from = info.first; const version_t to = info.second - g_conf()->mon_log_max; dout(10) << __func__ << " pruning channel " << channel << " " << from << " -> " << to << dendl; prune_channels_to[channel] = to; pending_channel_info[channel].first = to; for (version_t v = from; v < to; ++v) { std::string key; generate_logentry_key(channel, v, &key); t->erase(get_service_name(), key); } } } dout(20) << __func__ << " prune_channels_to " << prune_channels_to << dendl; encode(prune_channels_to, bl); put_version(t, version, bl); put_last_committed(t, version); } bool LogMonitor::should_stash_full() { if (mon.monmap->min_mon_release < ceph_release_t::quincy) { // commit a LogSummary on every commit return true; } // store periodic summary auto period = std::min<uint64_t>( g_conf()->mon_log_full_interval, g_conf()->mon_max_log_epochs ); return (get_last_committed() - get_version_latest_full() > period); } void LogMonitor::encode_full(MonitorDBStore::TransactionRef t) { dout(10) << __func__ << " log v " << summary.version << dendl; ceph_assert(get_last_committed() == summary.version); bufferlist summary_bl; encode(summary, summary_bl, mon.get_quorum_con_features()); put_version_full(t, summary.version, summary_bl); put_version_latest_full(t, summary.version); } version_t LogMonitor::get_trim_to() const { if (!mon.is_leader()) return 0; unsigned max = g_conf()->mon_max_log_epochs; version_t version = get_last_committed(); if (version > max) return version - max; return 0; } bool LogMonitor::preprocess_query(MonOpRequestRef op) { op->mark_logmon_event("preprocess_query"); auto m = op->get_req<PaxosServiceMessage>(); dout(10) << "preprocess_query " << *m << " from " << m->get_orig_source_inst() << dendl; switch (m->get_type()) { case MSG_MON_COMMAND: try { return preprocess_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); return true; } case MSG_LOG: return preprocess_log(op); default: ceph_abort(); return true; } } bool LogMonitor::prepare_update(MonOpRequestRef op) { op->mark_logmon_event("prepare_update"); auto m = op->get_req<PaxosServiceMessage>(); dout(10) << "prepare_update " << *m << " from " << m->get_orig_source_inst() << dendl; switch (m->get_type()) { case MSG_MON_COMMAND: try { return prepare_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); return true; } case MSG_LOG: return prepare_log(op); default: ceph_abort(); return false; } } bool LogMonitor::preprocess_log(MonOpRequestRef op) { op->mark_logmon_event("preprocess_log"); auto m = op->get_req<MLog>(); dout(10) << "preprocess_log " << *m << " from " << m->get_orig_source() << dendl; int num_new = 0; MonSession *session = op->get_session(); if (!session) goto done; if (!session->is_capable("log", MON_CAP_W)) { dout(0) << "preprocess_log got MLog from entity with insufficient privileges " << session->caps << dendl; goto done; } for (auto p = m->entries.begin(); p != m->entries.end(); ++p) { if (!summary.contains(p->key())) num_new++; } if (!num_new) { dout(10) << " nothing new" << dendl; goto done; } return false; done: mon.no_reply(op); return true; } struct LogMonitor::C_Log : public C_MonOp { LogMonitor *logmon; C_Log(LogMonitor *p, MonOpRequestRef o) : C_MonOp(o), logmon(p) {} void _finish(int r) override { if (r == -ECANCELED) { return; } logmon->_updated_log(op); } }; bool LogMonitor::prepare_log(MonOpRequestRef op) { op->mark_logmon_event("prepare_log"); auto m = op->get_req<MLog>(); dout(10) << "prepare_log " << *m << " from " << m->get_orig_source() << dendl; if (m->fsid != mon.monmap->fsid) { dout(0) << "handle_log on fsid " << m->fsid << " != " << mon.monmap->fsid << dendl; return false; } for (auto p = m->entries.begin(); p != m->entries.end(); ++p) { dout(10) << " logging " << *p << dendl; if (!summary.contains(p->key()) && !pending_keys.count(p->key())) { pending_keys.insert(p->key()); pending_log.insert(pair<utime_t,LogEntry>(p->stamp, *p)); } } wait_for_finished_proposal(op, new C_Log(this, op)); return true; } void LogMonitor::_updated_log(MonOpRequestRef op) { auto m = op->get_req<MLog>(); dout(7) << "_updated_log for " << m->get_orig_source_inst() << dendl; mon.send_reply(op, new MLogAck(m->fsid, m->entries.rbegin()->seq)); } bool LogMonitor::should_propose(double& delay) { // commit now if we have a lot of pending events if (g_conf()->mon_max_log_entries_per_event > 0 && pending_log.size() >= (unsigned)g_conf()->mon_max_log_entries_per_event) return true; // otherwise fall back to generic policy return PaxosService::should_propose(delay); } bool LogMonitor::preprocess_command(MonOpRequestRef op) { op->mark_logmon_event("preprocess_command"); auto m = op->get_req<MMonCommand>(); int r = -EINVAL; bufferlist rdata; stringstream ss; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, get_last_committed()); return true; } MonSession *session = op->get_session(); if (!session) { mon.reply_command(op, -EACCES, "access denied", get_last_committed()); return true; } string prefix; cmd_getval(cmdmap, "prefix", prefix); string format = cmd_getval_or<string>(cmdmap, "format", "plain"); boost::scoped_ptr<Formatter> f(Formatter::create(format)); if (prefix == "log last") { int64_t num = 20; cmd_getval(cmdmap, "num", num); if (f) { f->open_array_section("tail"); } std::string level_str; clog_type level; if (cmd_getval(cmdmap, "level", level_str)) { level = LogEntry::str_to_level(level_str); if (level == CLOG_UNKNOWN) { ss << "Invalid severity '" << level_str << "'"; mon.reply_command(op, -EINVAL, ss.str(), get_last_committed()); return true; } } else { level = CLOG_INFO; } std::string channel; if (!cmd_getval(cmdmap, "channel", channel)) { channel = CLOG_CHANNEL_DEFAULT; } // We'll apply this twice, once while counting out lines // and once while outputting them. auto match = [level](const LogEntry &entry) { return entry.prio >= level; }; ostringstream ss; if (!summary.tail_by_channel.empty()) { // pre-quincy compat // Decrement operation that sets to container end when hitting rbegin if (channel == "*") { list<LogEntry> full_tail; summary.build_ordered_tail_legacy(&full_tail); auto rp = full_tail.rbegin(); for (; num > 0 && rp != full_tail.rend(); ++rp) { if (match(*rp)) { num--; } } if (rp == full_tail.rend()) { --rp; } // Decrement a reverse iterator such that going past rbegin() // sets it to rend(). This is for writing a for() loop that // goes up to (and including) rbegin() auto dec = [&rp, &full_tail] () { if (rp == full_tail.rbegin()) { rp = full_tail.rend(); } else { --rp; } }; // Move forward to the end of the container (decrement the reverse // iterator). for (; rp != full_tail.rend(); dec()) { if (!match(*rp)) { continue; } if (f) { f->dump_object("entry", *rp); } else { ss << *rp << "\n"; } } } else { auto p = summary.tail_by_channel.find(channel); if (p != summary.tail_by_channel.end()) { auto rp = p->second.rbegin(); for (; num > 0 && rp != p->second.rend(); ++rp) { if (match(rp->second)) { num--; } } if (rp == p->second.rend()) { --rp; } // Decrement a reverse iterator such that going past rbegin() // sets it to rend(). This is for writing a for() loop that // goes up to (and including) rbegin() auto dec = [&rp, &p] () { if (rp == p->second.rbegin()) { rp = p->second.rend(); } else { --rp; } }; // Move forward to the end of the container (decrement the reverse // iterator). for (; rp != p->second.rend(); dec()) { if (!match(rp->second)) { continue; } if (f) { f->dump_object("entry", rp->second); } else { ss << rp->second << "\n"; } } } } } else { // quincy+ if (channel == "*") { // tail all channels; we need to mix by timestamp multimap<utime_t,LogEntry> entries; // merge+sort all channels by timestamp for (auto& p : summary.channel_info) { version_t from = p.second.first; version_t to = p.second.second; version_t start; if (to > (version_t)num) { start = std::max(to - num, from); } else { start = from; } dout(10) << __func__ << " channel " << p.first << " from " << from << " to " << to << dendl; for (version_t v = start; v < to; ++v) { bufferlist ebl; string key; generate_logentry_key(p.first, v, &key); int r = mon.store->get(get_service_name(), key, ebl); if (r < 0) { derr << __func__ << " missing key " << key << dendl; continue; } LogEntry le; auto p = ebl.cbegin(); decode(le, p); entries.insert(make_pair(le.stamp, le)); } } while ((int)entries.size() > num) { entries.erase(entries.begin()); } for (auto& p : entries) { if (!match(p.second)) { continue; } if (f) { f->dump_object("entry", p.second); } else { ss << p.second << "\n"; } } } else { // tail one channel auto p = summary.channel_info.find(channel); if (p != summary.channel_info.end()) { version_t from = p->second.first; version_t to = p->second.second; version_t start; if (to > (version_t)num) { start = std::max(to - num, from); } else { start = from; } dout(10) << __func__ << " from " << from << " to " << to << dendl; for (version_t v = start; v < to; ++v) { bufferlist ebl; string key; generate_logentry_key(channel, v, &key); int r = mon.store->get(get_service_name(), key, ebl); if (r < 0) { derr << __func__ << " missing key " << key << dendl; continue; } LogEntry le; auto p = ebl.cbegin(); decode(le, p); if (match(le)) { if (f) { f->dump_object("entry", le); } else { ss << le << "\n"; } } } } } } if (f) { f->close_section(); f->flush(rdata); } else { rdata.append(ss.str()); } r = 0; } else { return false; } string rs; getline(ss, rs); mon.reply_command(op, r, rs, rdata, get_last_committed()); return true; } bool LogMonitor::prepare_command(MonOpRequestRef op) { op->mark_logmon_event("prepare_command"); auto m = op->get_req<MMonCommand>(); stringstream ss; string rs; int err = -EINVAL; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { // ss has reason for failure string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, get_last_committed()); return true; } string prefix; cmd_getval(cmdmap, "prefix", prefix); MonSession *session = op->get_session(); if (!session) { mon.reply_command(op, -EACCES, "access denied", get_last_committed()); return true; } if (prefix == "log") { vector<string> logtext; cmd_getval(cmdmap, "logtext", logtext); LogEntry le; le.rank = m->get_orig_source(); le.addrs.v.push_back(m->get_orig_source_addr()); le.name = session->entity_name; le.stamp = m->get_recv_stamp(); le.seq = 0; string level_str = cmd_getval_or<string>(cmdmap, "level", "info"); le.prio = LogEntry::str_to_level(level_str); le.channel = CLOG_CHANNEL_DEFAULT; le.msg = str_join(logtext, " "); pending_keys.insert(le.key()); pending_log.insert(pair<utime_t,LogEntry>(le.stamp, le)); wait_for_finished_proposal(op, new Monitor::C_Command( mon, op, 0, string(), get_last_committed() + 1)); return true; } getline(ss, rs); mon.reply_command(op, err, rs, get_last_committed()); return false; } void LogMonitor::dump_info(Formatter *f) { f->dump_unsigned("logm_first_committed", get_first_committed()); f->dump_unsigned("logm_last_committed", get_last_committed()); } int LogMonitor::sub_name_to_id(const string& n) { if (n.substr(0, 4) == "log-" && n.size() > 4) { return LogEntry::str_to_level(n.substr(4)); } else { return CLOG_UNKNOWN; } } void LogMonitor::check_subs() { dout(10) << __func__ << dendl; for (map<string, xlist<Subscription*>*>::iterator i = mon.session_map.subs.begin(); i != mon.session_map.subs.end(); ++i) { for (xlist<Subscription*>::iterator j = i->second->begin(); !j.end(); ++j) { if (sub_name_to_id((*j)->type) >= 0) check_sub(*j); } } } void LogMonitor::check_sub(Subscription *s) { dout(10) << __func__ << " client wants " << s->type << " ver " << s->next << dendl; int sub_level = sub_name_to_id(s->type); ceph_assert(sub_level >= 0); version_t summary_version = summary.version; if (s->next > summary_version) { dout(10) << __func__ << " client " << s->session->name << " requested version (" << s->next << ") is greater than ours (" << summary_version << "), which means we already sent him" << " everything we have." << dendl; return; } MLog *mlog = new MLog(mon.monmap->fsid); if (s->next == 0) { /* First timer, heh? */ _create_sub_incremental(mlog, sub_level, get_last_committed()); } else { /* let us send you an incremental log... */ _create_sub_incremental(mlog, sub_level, s->next); } dout(10) << __func__ << " sending message to " << s->session->name << " with " << mlog->entries.size() << " entries" << " (version " << mlog->version << ")" << dendl; if (!mlog->entries.empty()) { s->session->con->send_message(mlog); } else { mlog->put(); } if (s->onetime) mon.session_map.remove_sub(s); else s->next = summary_version+1; } /** * Create an incremental log message from version \p sv to \p summary.version * * @param mlog Log message we'll send to the client with the messages received * since version \p sv, inclusive. * @param level The max log level of the messages the client is interested in. * @param sv The version the client is looking for. */ void LogMonitor::_create_sub_incremental(MLog *mlog, int level, version_t sv) { dout(10) << __func__ << " level " << level << " ver " << sv << " cur summary ver " << summary.version << dendl; if (sv < get_first_committed()) { dout(10) << __func__ << " skipped from " << sv << " to first_committed " << get_first_committed() << dendl; LogEntry le; le.stamp = ceph_clock_now(); le.prio = CLOG_WARN; ostringstream ss; ss << "skipped log messages from " << sv << " to " << get_first_committed(); le.msg = ss.str(); mlog->entries.push_back(le); sv = get_first_committed(); } version_t summary_ver = summary.version; while (sv && sv <= summary_ver) { bufferlist bl; int err = get_version(sv, bl); ceph_assert(err == 0); ceph_assert(bl.length()); auto p = bl.cbegin(); __u8 v; decode(v, p); int32_t num = -2; if (v >= 2) { decode(num, p); dout(20) << __func__ << " sv " << sv << " has " << num << " entries" << dendl; } while ((num == -2 && !p.end()) || (num >= 0 && num--)) { LogEntry le; le.decode(p); if (le.prio < level) { dout(20) << __func__ << " requested " << level << ", skipping " << le << dendl; continue; } mlog->entries.push_back(le); } mlog->version = sv++; } dout(10) << __func__ << " incremental message ready (" << mlog->entries.size() << " entries)" << dendl; } void LogMonitor::update_log_channels() { ostringstream oss; channels.clear(); int r = get_conf_str_map_helper( g_conf().get_val<string>("mon_cluster_log_to_syslog"), oss, &channels.log_to_syslog, CLOG_CONFIG_DEFAULT_KEY); if (r < 0) { derr << __func__ << " error parsing 'mon_cluster_log_to_syslog'" << dendl; return; } r = get_conf_str_map_helper( g_conf().get_val<string>("mon_cluster_log_to_syslog_level"), oss, &channels.syslog_level, CLOG_CONFIG_DEFAULT_KEY); if (r < 0) { derr << __func__ << " error parsing 'mon_cluster_log_to_syslog_level'" << dendl; return; } r = get_conf_str_map_helper( g_conf().get_val<string>("mon_cluster_log_to_syslog_facility"), oss, &channels.syslog_facility, CLOG_CONFIG_DEFAULT_KEY); if (r < 0) { derr << __func__ << " error parsing 'mon_cluster_log_to_syslog_facility'" << dendl; return; } r = get_conf_str_map_helper( g_conf().get_val<string>("mon_cluster_log_file"), oss, &channels.log_file, CLOG_CONFIG_DEFAULT_KEY); if (r < 0) { derr << __func__ << " error parsing 'mon_cluster_log_file'" << dendl; return; } r = get_conf_str_map_helper( g_conf().get_val<string>("mon_cluster_log_file_level"), oss, &channels.log_file_level, CLOG_CONFIG_DEFAULT_KEY); if (r < 0) { derr << __func__ << " error parsing 'mon_cluster_log_file_level'" << dendl; return; } r = get_conf_str_map_helper( g_conf().get_val<string>("mon_cluster_log_to_graylog"), oss, &channels.log_to_graylog, CLOG_CONFIG_DEFAULT_KEY); if (r < 0) { derr << __func__ << " error parsing 'mon_cluster_log_to_graylog'" << dendl; return; } r = get_conf_str_map_helper( g_conf().get_val<string>("mon_cluster_log_to_graylog_host"), oss, &channels.log_to_graylog_host, CLOG_CONFIG_DEFAULT_KEY); if (r < 0) { derr << __func__ << " error parsing 'mon_cluster_log_to_graylog_host'" << dendl; return; } r = get_conf_str_map_helper( g_conf().get_val<string>("mon_cluster_log_to_graylog_port"), oss, &channels.log_to_graylog_port, CLOG_CONFIG_DEFAULT_KEY); if (r < 0) { derr << __func__ << " error parsing 'mon_cluster_log_to_graylog_port'" << dendl; return; } r = get_conf_str_map_helper( g_conf().get_val<string>("mon_cluster_log_to_journald"), oss, &channels.log_to_journald, CLOG_CONFIG_DEFAULT_KEY); if (r < 0) { derr << __func__ << " error parsing 'mon_cluster_log_to_journald'" << dendl; return; } channels.expand_channel_meta(); log_external_close_fds(); } void LogMonitor::handle_conf_change(const ConfigProxy& conf, const std::set<std::string> &changed) { if (changed.count("mon_cluster_log_to_syslog") || changed.count("mon_cluster_log_to_syslog_level") || changed.count("mon_cluster_log_to_syslog_facility") || changed.count("mon_cluster_log_file") || changed.count("mon_cluster_log_file_level") || changed.count("mon_cluster_log_to_graylog") || changed.count("mon_cluster_log_to_graylog_host") || changed.count("mon_cluster_log_to_graylog_port") || changed.count("mon_cluster_log_to_journald") || changed.count("mon_cluster_log_to_file")) { update_log_channels(); } }
35,988
26.81221
102
cc
null
ceph-main/src/mon/LogMonitor.h
// -*- 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. * */ #ifndef CEPH_LOGMONITOR_H #define CEPH_LOGMONITOR_H #include <atomic> #include <map> #include <set> #include <fmt/format.h> #include <fmt/ostream.h> #include "include/types.h" #include "PaxosService.h" #include "common/config_fwd.h" #include "common/LogEntry.h" #include "include/str_map.h" class MLog; static const std::string LOG_META_CHANNEL = "$channel"; namespace ceph { namespace logging { class Graylog; class JournaldClusterLogger; } } class LogMonitor : public PaxosService, public md_config_obs_t { private: std::multimap<utime_t,LogEntry> pending_log; unordered_set<LogEntryKey> pending_keys; LogSummary summary; version_t external_log_to = 0; std::map<std::string, int> channel_fds; fmt::memory_buffer log_buffer; std::atomic<bool> log_rotated = false; struct log_channel_info { std::map<std::string,std::string> log_to_syslog; std::map<std::string,std::string> syslog_level; std::map<std::string,std::string> syslog_facility; std::map<std::string,std::string> log_file; std::map<std::string,std::string> expanded_log_file; std::map<std::string,std::string> log_file_level; std::map<std::string,std::string> log_to_graylog; std::map<std::string,std::string> log_to_graylog_host; std::map<std::string,std::string> log_to_graylog_port; std::map<std::string,std::string> log_to_journald; std::map<std::string, std::shared_ptr<ceph::logging::Graylog>> graylogs; std::unique_ptr<ceph::logging::JournaldClusterLogger> journald; uuid_d fsid; std::string host; log_channel_info(); ~log_channel_info(); void clear(); /** expands $channel meta variable on all maps *EXCEPT* log_file * * We won't expand the log_file map meta variables here because we * intend to do that selectively during get_log_file() */ void expand_channel_meta() { expand_channel_meta(log_to_syslog); expand_channel_meta(syslog_level); expand_channel_meta(syslog_facility); expand_channel_meta(log_file_level); } void expand_channel_meta(std::map<std::string,std::string> &m); std::string expand_channel_meta(const std::string &input, const std::string &change_to); bool do_log_to_syslog(const std::string &channel); std::string get_facility(const std::string &channel) { return get_str_map_key(syslog_facility, channel, &CLOG_CONFIG_DEFAULT_KEY); } std::string get_level(const std::string &channel) { return get_str_map_key(syslog_level, channel, &CLOG_CONFIG_DEFAULT_KEY); } std::string get_log_file(const std::string &channel); std::string get_log_file_level(const std::string &channel) { return get_str_map_key(log_file_level, channel, &CLOG_CONFIG_DEFAULT_KEY); } bool do_log_to_graylog(const std::string &channel) { return (get_str_map_key(log_to_graylog, channel, &CLOG_CONFIG_DEFAULT_KEY) == "true"); } std::shared_ptr<ceph::logging::Graylog> get_graylog(const std::string &channel); bool do_log_to_journald(const std::string &channel) { return (get_str_map_key(log_to_journald, channel, &CLOG_CONFIG_DEFAULT_KEY) == "true"); } ceph::logging::JournaldClusterLogger &get_journald(); } channels; void update_log_channels(); void create_initial() override; void update_from_paxos(bool *need_bootstrap) override; void create_pending() override; // prepare a new pending // propose pending update to peers void generate_logentry_key(const std::string& channel, version_t v, std::string *out); void encode_pending(MonitorDBStore::TransactionRef t) override; void encode_full(MonitorDBStore::TransactionRef t) override; version_t get_trim_to() const override; bool preprocess_query(MonOpRequestRef op) override; // true if processed. bool prepare_update(MonOpRequestRef op) override; bool preprocess_log(MonOpRequestRef op); bool prepare_log(MonOpRequestRef op); void _updated_log(MonOpRequestRef op); bool should_propose(double& delay) override; bool should_stash_full() override; struct C_Log; bool preprocess_command(MonOpRequestRef op); bool prepare_command(MonOpRequestRef op); void _create_sub_incremental(MLog *mlog, int level, version_t sv); public: LogMonitor(Monitor &mn, Paxos &p, const std::string& service_name) : PaxosService(mn, p, service_name) { } void init() override { generic_dout(10) << "LogMonitor::init" << dendl; g_conf().add_observer(this); update_log_channels(); } void tick() override; // check state, take actions void dump_info(Formatter *f); void check_subs(); void check_sub(Subscription *s); void reopen_logs() { this->log_rotated.store(true); } void log_external_close_fds(); void log_external(const LogEntry& le); void log_external_backlog(); /** * translate log sub name ('log-info') to integer id * * @param n name * @return id, or -1 if unrecognized */ int sub_name_to_id(const std::string& n); void on_shutdown() override { g_conf().remove_observer(this); } const char **get_tracked_conf_keys() const override { static const char* KEYS[] = { "mon_cluster_log_to_syslog", "mon_cluster_log_to_syslog_level", "mon_cluster_log_to_syslog_facility", "mon_cluster_log_file", "mon_cluster_log_file_level", "mon_cluster_log_to_graylog", "mon_cluster_log_to_graylog_host", "mon_cluster_log_to_graylog_port", "mon_cluster_log_to_journald", NULL }; return KEYS; } void handle_conf_change(const ConfigProxy& conf, const std::set<std::string> &changed) override; }; #endif
6,236
28.559242
88
h
null
ceph-main/src/mon/MDSMonitor.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 <regex> #include <sstream> #include <boost/utility.hpp> #include "MDSMonitor.h" #include "FSCommands.h" #include "Monitor.h" #include "MonitorDBStore.h" #include "OSDMonitor.h" #include "common/strtol.h" #include "common/perf_counters.h" #include "common/config.h" #include "common/cmdparse.h" #include "messages/MMDSMap.h" #include "messages/MFSMap.h" #include "messages/MFSMapUser.h" #include "messages/MMDSLoadTargets.h" #include "messages/MMonCommand.h" #include "messages/MGenericMessage.h" #include "include/ceph_assert.h" #include "include/str_list.h" #include "include/stringify.h" #include "mds/mdstypes.h" #include "Session.h" using namespace TOPNSPC::common; using std::dec; using std::hex; using std::list; using std::map; using std::make_pair; using std::ostream; using std::ostringstream; using std::pair; using std::set; using std::string; using std::string_view; using std::stringstream; using std::to_string; using std::vector; using ceph::bufferlist; using ceph::decode; using ceph::encode; using ceph::ErasureCodeInterfaceRef; using ceph::ErasureCodeProfile; using ceph::Formatter; using ceph::JSONFormatter; using ceph::make_message; using ceph::mono_clock; using ceph::mono_time; #define dout_subsys ceph_subsys_mon #undef dout_prefix #define dout_prefix _prefix(_dout, mon, get_fsmap()) static ostream& _prefix(std::ostream *_dout, Monitor &mon, const FSMap& fsmap) { return *_dout << "mon." << mon.name << "@" << mon.rank << "(" << mon.get_state_name() << ").mds e" << fsmap.get_epoch() << " "; } static const string MDS_METADATA_PREFIX("mds_metadata"); static const string MDS_HEALTH_PREFIX("mds_health"); /* * Specialized implementation of cmd_getval to allow us to parse * out strongly-typedef'd types */ namespace TOPNSPC::common { template<> bool cmd_getval(const cmdmap_t& cmdmap, std::string_view k, mds_gid_t &val) { return cmd_getval(cmdmap, k, (int64_t&)val); } template<> bool cmd_getval(const cmdmap_t& cmdmap, std::string_view k, mds_rank_t &val) { return cmd_getval(cmdmap, k, (int64_t&)val); } template<> bool cmd_getval(const cmdmap_t& cmdmap, std::string_view k, MDSMap::DaemonState &val) { return cmd_getval(cmdmap, k, (int64_t&)val); } } // my methods template <int dblV> void MDSMonitor::print_map(const FSMap& m) { dout(dblV) << "print_map\n"; m.print(*_dout); *_dout << dendl; } // service methods void MDSMonitor::create_initial() { dout(10) << "create_initial" << dendl; } void MDSMonitor::get_store_prefixes(std::set<string>& s) const { s.insert(service_name); s.insert(MDS_METADATA_PREFIX); s.insert(MDS_HEALTH_PREFIX); } void MDSMonitor::update_from_paxos(bool *need_bootstrap) { version_t version = get_last_committed(); if (version == get_fsmap().epoch) return; dout(10) << __func__ << " version " << version << ", my e " << get_fsmap().epoch << dendl; ceph_assert(version > get_fsmap().epoch); load_health(); // read and decode bufferlist fsmap_bl; fsmap_bl.clear(); int err = get_version(version, fsmap_bl); ceph_assert(err == 0); ceph_assert(fsmap_bl.length() > 0); dout(10) << __func__ << " got " << version << dendl; try { PaxosFSMap::decode(fsmap_bl); } catch (const ceph::buffer::malformed_input& e) { derr << "unable to decode FSMap: " << e.what() << dendl; throw; } // new map dout(0) << "new map" << dendl; print_map<0>(get_fsmap()); if (!g_conf()->mon_mds_skip_sanity) { get_fsmap().sanity(); } check_subs(); } void MDSMonitor::init() { (void)load_metadata(pending_metadata); } void MDSMonitor::create_pending() { auto &fsmap = PaxosFSMap::create_pending(); if (mon.osdmon()->is_readable()) { const auto &osdmap = mon.osdmon()->osdmap; fsmap.sanitize([&osdmap](int64_t pool){return osdmap.have_pg_pool(pool);}); } dout(10) << "create_pending e" << fsmap.epoch << dendl; } void MDSMonitor::encode_pending(MonitorDBStore::TransactionRef t) { auto &pending = get_pending_fsmap_writeable(); auto &epoch = pending.epoch; dout(10) << "encode_pending e" << epoch << dendl; // print map iff 'debug mon = 30' or higher print_map<30>(pending); if (!g_conf()->mon_mds_skip_sanity) { pending.sanity(true); } // Set 'modified' on maps modified this epoch for (auto &p : pending.filesystems) { if (p.second->mds_map.epoch == epoch) { p.second->mds_map.modified = ceph_clock_now(); } } // apply to paxos ceph_assert(get_last_committed() + 1 == pending.epoch); bufferlist pending_bl; pending.encode(pending_bl, mon.get_quorum_con_features()); /* put everything in the transaction */ put_version(t, pending.epoch, pending_bl); put_last_committed(t, pending.epoch); // Encode MDSHealth data for (std::map<uint64_t, MDSHealth>::iterator i = pending_daemon_health.begin(); i != pending_daemon_health.end(); ++i) { bufferlist bl; i->second.encode(bl); t->put(MDS_HEALTH_PREFIX, stringify(i->first), bl); } for (std::set<uint64_t>::iterator i = pending_daemon_health_rm.begin(); i != pending_daemon_health_rm.end(); ++i) { t->erase(MDS_HEALTH_PREFIX, stringify(*i)); } pending_daemon_health_rm.clear(); remove_from_metadata(pending, t); // health health_check_map_t new_checks; const auto &info_map = pending.get_mds_info(); for (const auto &i : info_map) { const auto &gid = i.first; const auto &info = i.second; if (pending_daemon_health_rm.count(gid)) { continue; } MDSHealth health; auto p = pending_daemon_health.find(gid); if (p != pending_daemon_health.end()) { health = p->second; } else { bufferlist bl; mon.store->get(MDS_HEALTH_PREFIX, stringify(gid), bl); if (!bl.length()) { derr << "Missing health data for MDS " << gid << dendl; continue; } auto bl_i = bl.cbegin(); health.decode(bl_i); } for (const auto &metric : health.metrics) { if (metric.type == MDS_HEALTH_DUMMY) { continue; } const auto rank = info.rank; health_check_t *check = &new_checks.get_or_add( mds_metric_name(metric.type), metric.sev, mds_metric_summary(metric.type), 1); ostringstream ss; ss << "mds." << info.name << "(mds." << rank << "): " << metric.message; bool first = true; for (auto &p : metric.metadata) { if (first) { ss << " "; } else { ss << ", "; } ss << p.first << ": " << p.second; first = false; } check->detail.push_back(ss.str()); } } pending.get_health_checks(&new_checks); for (auto& p : new_checks.checks) { p.second.summary = std::regex_replace( p.second.summary, std::regex("%num%"), stringify(p.second.detail.size())); p.second.summary = std::regex_replace( p.second.summary, std::regex("%plurals%"), p.second.detail.size() > 1 ? "s" : ""); p.second.summary = std::regex_replace( p.second.summary, std::regex("%isorare%"), p.second.detail.size() > 1 ? "are" : "is"); p.second.summary = std::regex_replace( p.second.summary, std::regex("%hasorhave%"), p.second.detail.size() > 1 ? "have" : "has"); } encode_health(new_checks, t); } version_t MDSMonitor::get_trim_to() const { version_t floor = 0; if (g_conf()->mon_mds_force_trim_to > 0 && g_conf()->mon_mds_force_trim_to <= (int)get_last_committed()) { floor = g_conf()->mon_mds_force_trim_to; dout(10) << __func__ << " explicit mon_mds_force_trim_to = " << floor << dendl; } unsigned max = g_conf()->mon_max_mdsmap_epochs; version_t last = get_last_committed(); if (last - get_first_committed() > max && floor < last - max) { floor = last-max; } dout(20) << __func__ << " = " << floor << dendl; return floor; } bool MDSMonitor::preprocess_query(MonOpRequestRef op) { op->mark_mdsmon_event(__func__); auto m = op->get_req<PaxosServiceMessage>(); dout(10) << "preprocess_query " << *m << " from " << m->get_orig_source() << " " << m->get_orig_source_addrs() << dendl; switch (m->get_type()) { case MSG_MDS_BEACON: return preprocess_beacon(op); case MSG_MON_COMMAND: try { return preprocess_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); return true; } case MSG_MDS_OFFLOAD_TARGETS: return preprocess_offload_targets(op); default: ceph_abort(); return true; } } void MDSMonitor::_note_beacon(MMDSBeacon *m) { mds_gid_t gid = mds_gid_t(m->get_global_id()); version_t seq = m->get_seq(); dout(5) << "_note_beacon " << *m << " noting time" << dendl; auto &beacon = last_beacon[gid]; beacon.stamp = mono_clock::now(); beacon.seq = seq; } bool MDSMonitor::preprocess_beacon(MonOpRequestRef op) { op->mark_mdsmon_event(__func__); auto m = op->get_req<MMDSBeacon>(); MDSMap::DaemonState state = m->get_state(); mds_gid_t gid = m->get_global_id(); version_t seq = m->get_seq(); MDSMap::mds_info_t info; epoch_t effective_epoch = 0; const auto &fsmap = get_fsmap(); // check privileges, ignore if fails MonSession *session = op->get_session(); if (!session) goto ignore; if (!session->is_capable("mds", MON_CAP_X)) { dout(0) << "preprocess_beacon got MMDSBeacon from entity with insufficient privileges " << session->caps << dendl; goto ignore; } if (m->get_fsid() != mon.monmap->fsid) { dout(0) << "preprocess_beacon on fsid " << m->get_fsid() << " != " << mon.monmap->fsid << dendl; goto ignore; } dout(5) << "preprocess_beacon " << *m << " from " << m->get_orig_source() << " " << m->get_orig_source_addrs() << " " << m->get_compat() << dendl; // make sure the address has a port if (m->get_orig_source_addr().get_port() == 0) { dout(1) << " ignoring boot message without a port" << dendl; goto ignore; } // fw to leader? if (!is_leader()) return false; // booted, but not in map? if (!fsmap.gid_exists(gid)) { if (state != MDSMap::STATE_BOOT) { dout(7) << "mds_beacon " << *m << " is not in fsmap (state " << ceph_mds_state_name(state) << ")" << dendl; /* We can't send an MDSMap this MDS was a part of because we no longer * know which FS it was part of. Nor does this matter. Sending an empty * MDSMap is sufficient for getting the MDS to respawn. */ auto m = make_message<MMDSMap>(mon.monmap->fsid, MDSMap::create_null_mdsmap()); mon.send_reply(op, m.detach()); return true; } else { /* check if we've already recorded its entry in pending */ const auto& pending = get_pending_fsmap(); if (pending.gid_exists(gid)) { /* MDS is already booted. */ goto ignore; } else { return false; // not booted yet. } } } dout(10) << __func__ << ": GID exists in map: " << gid << dendl; info = fsmap.get_info_gid(gid); if (state == MDSMap::STATE_DNE) { return false; } // old seq? if (info.state_seq > seq) { dout(7) << "mds_beacon " << *m << " has old seq, ignoring" << dendl; goto ignore; } // Work out the latest epoch that this daemon should have seen { fs_cluster_id_t fscid = fsmap.mds_roles.at(gid); if (fscid == FS_CLUSTER_ID_NONE) { effective_epoch = fsmap.standby_epochs.at(gid); } else { effective_epoch = fsmap.get_filesystem(fscid)->mds_map.epoch; } if (effective_epoch != m->get_last_epoch_seen()) { dout(10) << "mds_beacon " << *m << " ignoring requested state, because mds hasn't seen latest map" << dendl; goto reply; } } if (info.laggy()) { _note_beacon(m); return false; // no longer laggy, need to update map. } if (state == MDSMap::STATE_BOOT) { // ignore, already booted. goto ignore; } // did the join_fscid change if (m->get_fs().size()) { fs_cluster_id_t fscid = FS_CLUSTER_ID_NONE; auto f = fsmap.get_filesystem(m->get_fs()); if (f) { fscid = f->fscid; } if (info.join_fscid != fscid) { dout(10) << __func__ << " standby mds_join_fs changed to " << fscid << " (" << m->get_fs() << ")" << dendl; _note_beacon(m); return false; } } else { if (info.join_fscid != FS_CLUSTER_ID_NONE) { dout(10) << __func__ << " standby mds_join_fs was cleared" << dendl; _note_beacon(m); return false; } } // is there a state change here? if (info.state != state) { _note_beacon(m); return false; } // Comparing known daemon health with m->get_health() // and return false (i.e. require proposal) if they // do not match, to update our stored if (!(pending_daemon_health[gid] == m->get_health())) { dout(10) << __func__ << " health metrics for gid " << gid << " were updated" << dendl; _note_beacon(m); return false; } reply: // note time and reply ceph_assert(effective_epoch > 0); _note_beacon(m); { auto beacon = make_message<MMDSBeacon>(mon.monmap->fsid, m->get_global_id(), m->get_name(), effective_epoch, state, seq, CEPH_FEATURES_SUPPORTED_DEFAULT); mon.send_reply(op, beacon.detach()); } return true; ignore: // I won't reply this beacon, drop it. mon.no_reply(op); return true; } bool MDSMonitor::preprocess_offload_targets(MonOpRequestRef op) { op->mark_mdsmon_event(__func__); auto m = op->get_req<MMDSLoadTargets>(); dout(10) << "preprocess_offload_targets " << *m << " from " << m->get_orig_source() << dendl; const auto &fsmap = get_fsmap(); // check privileges, ignore message if fails MonSession *session = op->get_session(); if (!session) goto ignore; if (!session->is_capable("mds", MON_CAP_X)) { dout(0) << "preprocess_offload_targets got MMDSLoadTargets from entity with insufficient caps " << session->caps << dendl; goto ignore; } if (fsmap.gid_exists(m->global_id) && m->targets == fsmap.get_info_gid(m->global_id).export_targets) goto ignore; return false; ignore: mon.no_reply(op); return true; } bool MDSMonitor::prepare_update(MonOpRequestRef op) { op->mark_mdsmon_event(__func__); auto m = op->get_req<PaxosServiceMessage>(); dout(7) << "prepare_update " << *m << dendl; bool r = false; /* batch any changes to pending with any changes to osdmap */ paxos.plug(); switch (m->get_type()) { case MSG_MDS_BEACON: r = prepare_beacon(op); break; case MSG_MON_COMMAND: try { r = prepare_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); r = false; } break; case MSG_MDS_OFFLOAD_TARGETS: r = prepare_offload_targets(op); break; default: ceph_abort(); break; } paxos.unplug(); return r; } bool MDSMonitor::prepare_beacon(MonOpRequestRef op) { op->mark_mdsmon_event(__func__); auto m = op->get_req<MMDSBeacon>(); // -- this is an update -- dout(12) << "prepare_beacon " << *m << " from " << m->get_orig_source() << " " << m->get_orig_source_addrs() << dendl; entity_addrvec_t addrs = m->get_orig_source_addrs(); mds_gid_t gid = m->get_global_id(); MDSMap::DaemonState state = m->get_state(); version_t seq = m->get_seq(); auto &pending = get_pending_fsmap_writeable(); dout(15) << __func__ << " got health from gid " << gid << " with " << m->get_health().metrics.size() << " metrics." << dendl; // Calculate deltas of health metrics created and removed // Do this by type rather than MDSHealthMetric equality, because messages can // change a lot when they include e.g. a number of items. const auto &old_health = pending_daemon_health[gid].metrics; const auto &new_health = m->get_health().metrics; std::set<mds_metric_t> old_types; for (const auto &i : old_health) { old_types.insert(i.type); } std::set<mds_metric_t> new_types; for (const auto &i : new_health) { if (i.type == MDS_HEALTH_DUMMY) { continue; } new_types.insert(i.type); } for (const auto &new_metric: new_health) { if (new_metric.type == MDS_HEALTH_DUMMY) { continue; } if (old_types.count(new_metric.type) == 0) { dout(10) << "MDS health message (" << m->get_orig_source() << "): " << new_metric.sev << " " << new_metric.message << dendl; } } // Log the disappearance of health messages at INFO for (const auto &old_metric : old_health) { if (new_types.count(old_metric.type) == 0) { mon.clog->info() << "MDS health message cleared (" << m->get_orig_source() << "): " << old_metric.message; } } // Store health pending_daemon_health[gid] = m->get_health(); const auto& cs = m->get_compat(); if (state == MDSMap::STATE_BOOT) { // zap previous instance of this name? if (g_conf()->mds_enforce_unique_name) { bool failed_mds = false; while (mds_gid_t existing = pending.find_mds_gid_by_name(m->get_name())) { if (!mon.osdmon()->is_writeable()) { mon.osdmon()->wait_for_writeable(op, new C_RetryMessage(this, op)); return false; } const auto& existing_info = pending.get_info_gid(existing); mon.clog->info() << existing_info.human_name() << " restarted"; fail_mds_gid(pending, existing); failed_mds = true; } if (failed_mds) { ceph_assert(mon.osdmon()->is_writeable()); request_proposal(mon.osdmon()); } } // Add this daemon to the map if (pending.mds_roles.count(gid) == 0) { MDSMap::mds_info_t new_info; new_info.global_id = gid; new_info.name = m->get_name(); new_info.addrs = addrs; new_info.mds_features = m->get_mds_features(); new_info.state = MDSMap::STATE_STANDBY; new_info.state_seq = seq; new_info.compat = cs; if (m->get_fs().size()) { fs_cluster_id_t fscid = FS_CLUSTER_ID_NONE; auto f = pending.get_filesystem(m->get_fs()); if (f) { fscid = f->fscid; } new_info.join_fscid = fscid; } pending.insert(new_info); } // initialize the beacon timer auto &beacon = last_beacon[gid]; beacon.stamp = mono_clock::now(); beacon.seq = seq; update_metadata(m->get_global_id(), m->get_sys_info()); } else { // state update if (!pending.gid_exists(gid)) { /* gid has been removed from pending, send null map */ dout(5) << "mds_beacon " << *m << " is not in fsmap (state " << ceph_mds_state_name(state) << ")" << dendl; /* We can't send an MDSMap this MDS was a part of because we no longer * know which FS it was part of. Nor does this matter. Sending an empty * MDSMap is sufficient for getting the MDS to respawn. */ goto null; } const auto& info = pending.get_info_gid(gid); // did the reported compat change? That's illegal! if (cs.compare(info.compat) != 0) { if (!mon.osdmon()->is_writeable()) { mon.osdmon()->wait_for_writeable(op, new C_RetryMessage(this, op)); return false; } mon.clog->warn() << info.human_name() << " compat changed unexpectedly"; fail_mds_gid(pending, gid); request_proposal(mon.osdmon()); return true; } if (state == MDSMap::STATE_DNE) { dout(1) << __func__ << ": DNE from " << info << dendl; goto evict; } // legal state change? if ((info.state == MDSMap::STATE_STANDBY && state != info.state) || (info.state == MDSMap::STATE_STANDBY_REPLAY && state != info.state && state != MDSMap::STATE_DAMAGED)) { // Standby daemons should never modify their own state. // Except that standby-replay can indicate the rank is damaged due to failure to replay. // Reject any attempts to do so. derr << "standby " << gid << " attempted to change state to " << ceph_mds_state_name(state) << ", rejecting" << dendl; goto evict; } else if (info.state != MDSMap::STATE_STANDBY && state != info.state && !MDSMap::state_transition_valid(info.state, state)) { // Validate state transitions for daemons that hold a rank derr << "daemon " << gid << " (rank " << info.rank << ") " << "reported invalid state transition " << ceph_mds_state_name(info.state) << " -> " << ceph_mds_state_name(state) << dendl; goto evict; } if (info.laggy()) { dout(1) << "prepare_beacon clearing laggy flag on " << addrs << dendl; pending.modify_daemon(info.global_id, [](auto& info) { info.clear_laggy(); } ); } dout(5) << "prepare_beacon mds." << info.rank << " " << ceph_mds_state_name(info.state) << " -> " << ceph_mds_state_name(state) << dendl; fs_cluster_id_t fscid = FS_CLUSTER_ID_NONE; if (m->get_fs().size()) { auto f = pending.get_filesystem(m->get_fs()); if (f) { fscid = f->fscid; } } pending.modify_daemon(gid, [fscid](auto& info) { info.join_fscid = fscid; }); if (state == MDSMap::STATE_STOPPED) { const auto fscid = pending.mds_roles.at(gid); const auto &fs = pending.get_filesystem(fscid); mon.clog->info() << info.human_name() << " finished " << "stopping rank " << info.rank << " in filesystem " << fs->mds_map.fs_name << " (now has " << fs->mds_map.get_num_in_mds() - 1 << " ranks)"; auto erased = pending.stop(gid); erased.push_back(gid); for (const auto& erased_gid : erased) { last_beacon.erase(erased_gid); if (pending_daemon_health.count(erased_gid)) { pending_daemon_health.erase(erased_gid); pending_daemon_health_rm.insert(erased_gid); } } } else if (state == MDSMap::STATE_DAMAGED) { if (!mon.osdmon()->is_writeable()) { dout(1) << __func__ << ": DAMAGED from rank " << info.rank << " waiting for osdmon writeable to blocklist it" << dendl; mon.osdmon()->wait_for_writeable(op, new C_RetryMessage(this, op)); return false; } auto rank = info.rank; // Record this MDS rank as damaged, so that other daemons // won't try to run it. dout(0) << __func__ << ": marking rank " << rank << " damaged" << dendl; auto fs = pending.get_filesystem(gid); auto rankgid = fs->mds_map.get_gid(rank); auto rankinfo = pending.get_info_gid(rankgid); auto followergid = fs->mds_map.get_standby_replay(rank); ceph_assert(gid == rankgid || gid == followergid); utime_t until = ceph_clock_now(); until += g_conf().get_val<double>("mon_mds_blocklist_interval"); const auto blocklist_epoch = mon.osdmon()->blocklist(rankinfo.addrs, until); if (followergid != MDS_GID_NONE) { fail_mds_gid(pending, followergid); last_beacon.erase(followergid); } request_proposal(mon.osdmon()); force_immediate_propose(); pending.damaged(rankgid, blocklist_epoch); last_beacon.erase(rankgid); /* MDS expects beacon reply back */ } else { if (info.state != MDSMap::STATE_ACTIVE && state == MDSMap::STATE_ACTIVE) { const auto &fscid = pending.mds_roles.at(gid); const auto &fs = pending.get_filesystem(fscid); mon.clog->info() << info.human_name() << " is now active in " << "filesystem " << fs->mds_map.fs_name << " as rank " << info.rank; } // Made it through special cases and validations, record the // daemon's reported state to the FSMap. pending.modify_daemon(gid, [state, seq](auto& info) { info.state = state; info.state_seq = seq; }); } } dout(5) << "prepare_beacon pending map now:" << dendl; print_map(pending); wait_for_finished_proposal(op, new LambdaContext([op, this](int r){ if (r >= 0) _updated(op); // success else if (r == -ECANCELED) { mon.no_reply(op); } else { dispatch(op); // try again } })); return true; evict: if (!mon.osdmon()->is_writeable()) { dout(1) << __func__ << ": waiting for writeable OSDMap to evict" << dendl; mon.osdmon()->wait_for_writeable(op, new C_RetryMessage(this, op)); return false; } fail_mds_gid(pending, gid); request_proposal(mon.osdmon()); dout(5) << __func__ << ": pending map now:" << dendl; print_map(pending); goto null; null: wait_for_finished_proposal(op, new LambdaContext([op, this](int r){ if (r >= 0) { auto m = make_message<MMDSMap>(mon.monmap->fsid, MDSMap::create_null_mdsmap()); mon.send_reply(op, m.detach()); } else { dispatch(op); // try again } })); return true; } bool MDSMonitor::prepare_offload_targets(MonOpRequestRef op) { auto &pending = get_pending_fsmap_writeable(); bool propose = false; op->mark_mdsmon_event(__func__); auto m = op->get_req<MMDSLoadTargets>(); mds_gid_t gid = m->global_id; if (pending.gid_has_rank(gid)) { dout(10) << "prepare_offload_targets " << gid << " " << m->targets << dendl; pending.update_export_targets(gid, m->targets); propose = true; } else { dout(10) << "prepare_offload_targets " << gid << " not in map" << dendl; } mon.no_reply(op); return propose; } bool MDSMonitor::should_propose(double& delay) { // delegate to PaxosService to assess whether we should propose return PaxosService::should_propose(delay); } void MDSMonitor::_updated(MonOpRequestRef op) { const auto &fsmap = get_fsmap(); op->mark_mdsmon_event(__func__); auto m = op->get_req<MMDSBeacon>(); dout(10) << "_updated " << m->get_orig_source() << " " << *m << dendl; mon.clog->debug() << m->get_orig_source() << " " << m->get_orig_source_addrs() << " " << ceph_mds_state_name(m->get_state()); if (m->get_state() == MDSMap::STATE_STOPPED) { // send the map manually (they're out of the map, so they won't get it automatic) auto m = make_message<MMDSMap>(mon.monmap->fsid, MDSMap::create_null_mdsmap()); mon.send_reply(op, m.detach()); } else { auto beacon = make_message<MMDSBeacon>(mon.monmap->fsid, m->get_global_id(), m->get_name(), fsmap.get_epoch(), m->get_state(), m->get_seq(), CEPH_FEATURES_SUPPORTED_DEFAULT); mon.send_reply(op, beacon.detach()); } } void MDSMonitor::on_active() { tick(); if (is_leader()) { mon.clog->debug() << "fsmap " << get_fsmap(); } } void MDSMonitor::dump_info(Formatter *f) { f->open_object_section("fsmap"); get_fsmap().dump(f); f->close_section(); f->dump_unsigned("mdsmap_first_committed", get_first_committed()); f->dump_unsigned("mdsmap_last_committed", get_last_committed()); } bool MDSMonitor::preprocess_command(MonOpRequestRef op) { op->mark_mdsmon_event(__func__); auto m = op->get_req<MMonCommand>(); int r = -1; bufferlist rdata; stringstream ss, ds; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { // ss has reason for failure string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, rdata, get_last_committed()); return true; } string prefix; cmd_getval(cmdmap, "prefix", prefix); string format = cmd_getval_or<string>(cmdmap, "format", "plain"); std::unique_ptr<Formatter> f(Formatter::create(format)); MonSession *session = op->get_session(); if (!session) { mon.reply_command(op, -EACCES, "access denied", rdata, get_last_committed()); return true; } // to use const qualifier filter fsmap beforehand FSMap _fsmap_copy = get_fsmap(); _fsmap_copy.filter(session->get_allowed_fs_names()); const auto& fsmap = _fsmap_copy; if (prefix == "mds stat") { if (f) { f->open_object_section("mds_stat"); dump_info(f.get()); f->close_section(); f->flush(ds); } else { ds << fsmap; } r = 0; } else if (prefix == "mds ok-to-stop") { vector<string> ids; if (!cmd_getval(cmdmap, "ids", ids)) { r = -EINVAL; ss << "must specify mds id"; goto out; } if (fsmap.is_any_degraded()) { ss << "one or more filesystems is currently degraded"; r = -EBUSY; goto out; } set<mds_gid_t> stopping; for (auto& id : ids) { ostringstream ess; mds_gid_t gid = gid_from_arg(fsmap, id, ess); if (gid == MDS_GID_NONE) { // the mds doesn't exist, but no file systems are unhappy, so losing it // can't have any effect. continue; } stopping.insert(gid); } set<mds_gid_t> active; set<mds_gid_t> standby; for (auto gid : stopping) { if (fsmap.gid_has_rank(gid)) { // ignore standby-replay daemons (at this level) if (!fsmap.is_standby_replay(gid)) { auto standby = fsmap.get_standby_replay(gid); if (standby == MDS_GID_NONE || stopping.count(standby)) { // no standby-replay, or we're also stopping the standby-replay // for this mds active.insert(gid); } } } else { // net loss of a standby standby.insert(gid); } } if (fsmap.get_num_standby() - standby.size() < active.size()) { r = -EBUSY; ss << "insufficent standby MDS daemons to stop active gids " << stringify(active) << " and/or standby gids " << stringify(standby);; goto out; } r = 0; ss << "should be safe to stop " << ids; } else if (prefix == "fs dump") { int64_t epocharg; epoch_t epoch; const FSMap *fsmapp = &fsmap; FSMap dummy; if (cmd_getval(cmdmap, "epoch", epocharg)) { epoch = epocharg; bufferlist b; int err = get_version(epoch, b); if (err == -ENOENT) { r = -ENOENT; goto out; } else { ceph_assert(err == 0); ceph_assert(b.length()); dummy.decode(b); fsmapp = &dummy; } } stringstream ds; if (f != NULL) { f->open_object_section("fsmap"); fsmapp->dump(f.get()); f->close_section(); f->flush(ds); r = 0; } else { fsmapp->print(ds); r = 0; } rdata.append(ds); ss << "dumped fsmap epoch " << fsmapp->get_epoch(); } else if (prefix == "mds metadata") { if (!f) f.reset(Formatter::create("json-pretty")); string who; bool all = !cmd_getval(cmdmap, "who", who); dout(1) << "all = " << all << dendl; if (all) { r = 0; // Dump all MDSs' metadata const auto all_info = fsmap.get_mds_info(); f->open_array_section("mds_metadata"); for(const auto &i : all_info) { const auto &info = i.second; f->open_object_section("mds"); f->dump_string("name", info.name); std::ostringstream get_err; r = dump_metadata(fsmap, info.name, f.get(), get_err); if (r == -EINVAL || r == -ENOENT) { // Drop error, list what metadata we do have dout(1) << get_err.str() << dendl; r = 0; } else if (r != 0) { derr << "Unexpected error reading metadata: " << cpp_strerror(r) << dendl; ss << get_err.str(); f->close_section(); break; } f->close_section(); } f->close_section(); } else { // Dump a single daemon's metadata f->open_object_section("mds_metadata"); r = dump_metadata(fsmap, who, f.get(), ss); f->close_section(); } f->flush(ds); } else if (prefix == "mds versions") { if (!f) f.reset(Formatter::create("json-pretty")); count_metadata("ceph_version", f.get()); f->flush(ds); r = 0; } else if (prefix == "mds count-metadata") { if (!f) f.reset(Formatter::create("json-pretty")); string field; cmd_getval(cmdmap, "property", field); count_metadata(field, f.get()); f->flush(ds); r = 0; } else if (prefix == "fs compat show") { string fs_name; cmd_getval(cmdmap, "fs_name", fs_name); const auto &fs = fsmap.get_filesystem(fs_name); if (fs == nullptr) { ss << "filesystem '" << fs_name << "' not found"; r = -ENOENT; goto out; } if (f) { f->open_object_section("mds_compat"); fs->mds_map.compat.dump(f.get()); f->close_section(); f->flush(ds); } else { ds << fs->mds_map.compat; } r = 0; } else if (prefix == "mds compat show") { if (f) { f->open_object_section("mds_compat"); fsmap.default_compat.dump(f.get()); f->close_section(); f->flush(ds); } else { ds << fsmap.default_compat; } r = 0; } else if (prefix == "fs get") { string fs_name; cmd_getval(cmdmap, "fs_name", fs_name); const auto &fs = fsmap.get_filesystem(fs_name); if (fs == nullptr) { ss << "filesystem '" << fs_name << "' not found"; r = -ENOENT; } else { if (f != nullptr) { f->open_object_section("filesystem"); fs->dump(f.get()); f->close_section(); f->flush(ds); r = 0; } else { fs->print(ds); r = 0; } } } else if (prefix == "fs ls") { if (f) { f->open_array_section("filesystems"); for (const auto &p : fsmap.filesystems) { const auto &fs = p.second; f->open_object_section("filesystem"); { const MDSMap &mds_map = fs->mds_map; f->dump_string("name", mds_map.fs_name); /* Output both the names and IDs of pools, for use by * humans and machines respectively */ f->dump_string("metadata_pool", mon.osdmon()->osdmap.get_pool_name( mds_map.metadata_pool)); f->dump_int("metadata_pool_id", mds_map.metadata_pool); f->open_array_section("data_pool_ids"); for (const auto &id : mds_map.data_pools) { f->dump_int("data_pool_id", id); } f->close_section(); f->open_array_section("data_pools"); for (const auto &id : mds_map.data_pools) { const auto &name = mon.osdmon()->osdmap.get_pool_name(id); f->dump_string("data_pool", name); } f->close_section(); } f->close_section(); } f->close_section(); f->flush(ds); } else { for (const auto &p : fsmap.filesystems) { const auto &fs = p.second; const MDSMap &mds_map = fs->mds_map; const string &md_pool_name = mon.osdmon()->osdmap.get_pool_name( mds_map.metadata_pool); ds << "name: " << mds_map.fs_name << ", metadata pool: " << md_pool_name << ", data pools: ["; for (const auto &id : mds_map.data_pools) { const string &pool_name = mon.osdmon()->osdmap.get_pool_name(id); ds << pool_name << " "; } ds << "]" << std::endl; } if (fsmap.filesystems.empty()) { ds << "No filesystems enabled" << std::endl; } } r = 0; } else if (prefix == "fs feature ls") { if (f) { f->open_array_section("cephfs_features"); for (size_t i = 0; i <= CEPHFS_FEATURE_MAX; ++i) { f->open_object_section("feature"); f->dump_int("index", i); f->dump_string("name", cephfs_feature_name(i)); f->close_section(); } f->close_section(); f->flush(ds); } else { for (size_t i = 0; i <= CEPHFS_FEATURE_MAX; ++i) { ds << i << " " << cephfs_feature_name(i) << std::endl; } } r = 0; } else if (prefix == "fs lsflags") { string fs_name; cmd_getval(cmdmap, "fs_name", fs_name); const auto &fs = fsmap.get_filesystem(fs_name); if (!fs) { ss << "filesystem '" << fs_name << "' not found"; r = -ENOENT; } else { const MDSMap &mds_map = fs->mds_map; if (f) { mds_map.dump_flags_state(f.get()); f->flush(ds); } else { mds_map.print_flags(ds); } r = 0; } } out: if (r != -1) { rdata.append(ds); string rs; getline(ss, rs); mon.reply_command(op, r, rs, rdata, get_last_committed()); return true; } else return false; } bool MDSMonitor::fail_mds_gid(FSMap &fsmap, mds_gid_t gid) { const auto& info = fsmap.get_info_gid(gid); dout(1) << "fail_mds_gid " << gid << " mds." << info.name << " role " << info.rank << dendl; ceph_assert(mon.osdmon()->is_writeable()); epoch_t blocklist_epoch = 0; if (info.rank >= 0 && info.state != MDSMap::STATE_STANDBY_REPLAY) { utime_t until = ceph_clock_now(); until += g_conf().get_val<double>("mon_mds_blocklist_interval"); blocklist_epoch = mon.osdmon()->blocklist(info.addrs, until); /* do not delay when we are evicting an MDS */ force_immediate_propose(); } fsmap.erase(gid, blocklist_epoch); last_beacon.erase(gid); if (pending_daemon_health.count(gid)) { pending_daemon_health.erase(gid); pending_daemon_health_rm.insert(gid); } return blocklist_epoch != 0; } mds_gid_t MDSMonitor::gid_from_arg(const FSMap &fsmap, const std::string &arg, std::ostream &ss) { // Try parsing as a role mds_role_t role; std::ostringstream ignore_err; // Don't spam 'ss' with parse_role errors int r = fsmap.parse_role(arg, &role, ignore_err); if (r == 0) { // See if a GID is assigned to this role const auto &fs = fsmap.get_filesystem(role.fscid); ceph_assert(fs != nullptr); // parse_role ensures it exists if (fs->mds_map.is_up(role.rank)) { dout(10) << __func__ << ": validated rank/GID " << role << " as a rank" << dendl; return fs->mds_map.get_mds_info(role.rank).global_id; } } // Try parsing as a gid std::string err; unsigned long long maybe_gid = strict_strtoll(arg.c_str(), 10, &err); if (!err.empty()) { // Not a role or a GID, try as a daemon name const MDSMap::mds_info_t *mds_info = fsmap.find_by_name(arg); if (!mds_info) { ss << "MDS named '" << arg << "' does not exist, or is not up"; return MDS_GID_NONE; } dout(10) << __func__ << ": resolved MDS name '" << arg << "' to GID " << mds_info->global_id << dendl; return mds_info->global_id; } else { // Not a role, but parses as a an integer, might be a GID dout(10) << __func__ << ": treating MDS reference '" << arg << "' as an integer " << maybe_gid << dendl; if (fsmap.gid_exists(mds_gid_t(maybe_gid))) { return mds_gid_t(maybe_gid); } } dout(1) << __func__ << ": rank/GID " << arg << " not a existent rank or GID" << dendl; return MDS_GID_NONE; } int MDSMonitor::fail_mds(FSMap &fsmap, std::ostream &ss, const std::string &arg, MDSMap::mds_info_t *failed_info) { ceph_assert(failed_info != nullptr); mds_gid_t gid = gid_from_arg(fsmap, arg, ss); if (gid == MDS_GID_NONE) { return 0; } if (!mon.osdmon()->is_writeable()) { return -EAGAIN; } // Take a copy of the info before removing the MDS from the map, // so that the caller knows which mds (if any) they ended up removing. *failed_info = fsmap.get_info_gid(gid); fail_mds_gid(fsmap, gid); ss << "failed mds gid " << gid; ceph_assert(mon.osdmon()->is_writeable()); request_proposal(mon.osdmon()); return 0; } bool MDSMonitor::prepare_command(MonOpRequestRef op) { op->mark_mdsmon_event(__func__); auto m = op->get_req<MMonCommand>(); int r = -EINVAL; stringstream ss; bufferlist rdata; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, rdata, get_last_committed()); return false; } string prefix; cmd_getval(cmdmap, "prefix", prefix); /* Refuse access if message not associated with a valid session */ MonSession *session = op->get_session(); if (!session) { mon.reply_command(op, -EACCES, "access denied", rdata, get_last_committed()); return false; } auto &pending = get_pending_fsmap_writeable(); for (const auto &h : handlers) { r = h->can_handle(prefix, op, pending, cmdmap, ss); if (r == 1) { ; // pass, since we got the right handler. } else if (r == 0) { continue; } else { goto out; } r = h->handle(&mon, pending, op, cmdmap, ss); if (r == -EAGAIN) { // message has been enqueued for retry; return. dout(4) << __func__ << " enqueue for retry by prepare_command" << dendl; return false; } else { if (r == 0) { // On successful updates, print the updated map print_map(pending); } // Successful or not, we're done: respond. goto out; } } r = filesystem_command(pending, op, prefix, cmdmap, ss); if (r >= 0) { goto out; } else if (r == -EAGAIN) { // Do not reply, the message has been enqueued for retry dout(4) << __func__ << " enqueue for retry by filesystem_command" << dendl; return false; } else if (r != -ENOSYS) { goto out; } if (r == -ENOSYS && ss.str().empty()) { ss << "unrecognized command"; } out: dout(4) << __func__ << " done, r=" << r << dendl; /* Compose response */ string rs; getline(ss, rs); if (r >= 0) { // success.. delay reply wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, r, rs, get_last_committed() + 1)); return true; } else { // reply immediately mon.reply_command(op, r, rs, rdata, get_last_committed()); return false; } } int MDSMonitor::filesystem_command( FSMap &fsmap, MonOpRequestRef op, std::string const &prefix, const cmdmap_t& cmdmap, std::stringstream &ss) { dout(4) << __func__ << " prefix='" << prefix << "'" << dendl; op->mark_mdsmon_event(__func__); int r = 0; string whostr; cmd_getval(cmdmap, "role", whostr); if (prefix == "mds set_state") { mds_gid_t gid; if (!cmd_getval(cmdmap, "gid", gid)) { ss << "error parsing 'gid' value '" << cmd_vartype_stringify(cmdmap.at("gid")) << "'"; return -EINVAL; } MDSMap::DaemonState state; if (!cmd_getval(cmdmap, "state", state)) { ss << "error parsing 'state' string value '" << cmd_vartype_stringify(cmdmap.at("state")) << "'"; return -EINVAL; } if (fsmap.gid_exists(gid, op->get_session()->get_allowed_fs_names())) { fsmap.modify_daemon(gid, [state](auto& info) { info.state = state; }); ss << "set mds gid " << gid << " to state " << state << " " << ceph_mds_state_name(state); return 0; } } else if (prefix == "mds fail") { string who; cmd_getval(cmdmap, "role_or_gid", who); MDSMap::mds_info_t failed_info; mds_gid_t gid = gid_from_arg(fsmap, who, ss); if (gid == MDS_GID_NONE) { ss << "MDS named '" << who << "' does not exist, is not up or you " << "lack the permission to see."; return 0; } if(!fsmap.gid_exists(gid, op->get_session()->get_allowed_fs_names())) { ss << "MDS named '" << who << "' does not exist, is not up or you " << "lack the permission to see."; return -EINVAL; } string_view fs_name = fsmap.fs_name_from_gid(gid); if (!op->get_session()->fs_name_capable(fs_name, MON_CAP_W)) { ss << "Permission denied."; return -EPERM; } r = fail_mds(fsmap, ss, who, &failed_info); if (r < 0 && r == -EAGAIN) { mon.osdmon()->wait_for_writeable(op, new C_RetryMessage(this, op)); return -EAGAIN; // don't propose yet; wait for message to be retried } else if (r == 0) { // Only log if we really did something (not when was already gone) if (failed_info.global_id != MDS_GID_NONE) { mon.clog->info() << failed_info.human_name() << " marked failed by " << op->get_session()->entity_name; } } } else if (prefix == "mds rm") { mds_gid_t gid; if (!cmd_getval(cmdmap, "gid", gid)) { ss << "error parsing 'gid' value '" << cmd_vartype_stringify(cmdmap.at("gid")) << "'"; return -EINVAL; } if (!fsmap.gid_exists(gid, op->get_session()->get_allowed_fs_names())) { ss << "mds gid " << gid << " does not exist"; return 0; } string_view fs_name = fsmap.fs_name_from_gid(gid); if (!op->get_session()->fs_name_capable(fs_name, MON_CAP_W)) { ss << "Permission denied."; return -EPERM; } const auto &info = fsmap.get_info_gid(gid); MDSMap::DaemonState state = info.state; if (state > 0) { ss << "cannot remove active mds." << info.name << " rank " << info.rank; return -EBUSY; } else { fsmap.erase(gid, {}); ss << "removed mds gid " << gid; return 0; } } else if (prefix == "mds rmfailed") { bool confirm = false; cmd_getval(cmdmap, "yes_i_really_mean_it", confirm); if (!confirm) { ss << "WARNING: this can make your filesystem inaccessible! " "Add --yes-i-really-mean-it if you are sure you wish to continue."; return -EPERM; } std::string role_str; cmd_getval(cmdmap, "role", role_str); mds_role_t role; const auto fs_names = op->get_session()->get_allowed_fs_names(); int r = fsmap.parse_role(role_str, &role, ss, fs_names); if (r < 0) { ss << "invalid role '" << role_str << "'"; return -EINVAL; } string_view fs_name = fsmap.get_filesystem(role.fscid)->mds_map.get_fs_name(); if (!op->get_session()->fs_name_capable(fs_name, MON_CAP_W)) { ss << "Permission denied."; return -EPERM; } fsmap.modify_filesystem( role.fscid, [role](std::shared_ptr<Filesystem> fs) { fs->mds_map.failed.erase(role.rank); }); ss << "removed failed mds." << role; return 0; /* TODO: convert to fs commands to update defaults */ } else if (prefix == "mds compat rm_compat") { int64_t f; if (!cmd_getval(cmdmap, "feature", f)) { ss << "error parsing feature value '" << cmd_vartype_stringify(cmdmap.at("feature")) << "'"; return -EINVAL; } if (fsmap.default_compat.compat.contains(f)) { ss << "removing compat feature " << f; fsmap.default_compat.compat.remove(f); } else { ss << "compat feature " << f << " not present in " << fsmap.default_compat; } r = 0; } else if (prefix == "mds compat rm_incompat") { int64_t f; if (!cmd_getval(cmdmap, "feature", f)) { ss << "error parsing feature value '" << cmd_vartype_stringify(cmdmap.at("feature")) << "'"; return -EINVAL; } if (fsmap.default_compat.incompat.contains(f)) { ss << "removing incompat feature " << f; fsmap.default_compat.incompat.remove(f); } else { ss << "incompat feature " << f << " not present in " << fsmap.default_compat; } r = 0; } else if (prefix == "mds repaired") { std::string role_str; cmd_getval(cmdmap, "role", role_str); mds_role_t role; const auto fs_names = op->get_session()->get_allowed_fs_names(); r = fsmap.parse_role(role_str, &role, ss, fs_names); if (r < 0) { return r; } string_view fs_name = fsmap.get_filesystem(role.fscid)->mds_map.get_fs_name(); if (!op->get_session()->fs_name_capable(fs_name, MON_CAP_W)) { ss << "Permission denied."; return -EPERM; } bool modified = fsmap.undamaged(role.fscid, role.rank); if (modified) { ss << "repaired: restoring rank " << role; } else { ss << "nothing to do: rank is not damaged"; } r = 0; } else if (prefix == "mds freeze") { std::string who; cmd_getval(cmdmap, "role_or_gid", who); mds_gid_t gid = gid_from_arg(fsmap, who, ss); if (gid == MDS_GID_NONE) { return -EINVAL; } string_view fs_name = fsmap.fs_name_from_gid(gid); if (!op->get_session()->fs_name_capable(fs_name, MON_CAP_W)) { ss << "Permission denied."; return -EPERM; } bool freeze = false; { std::string str; cmd_getval(cmdmap, "val", str); if ((r = parse_bool(str, &freeze, ss)) != 0) { return r; } } auto f = [freeze,gid,&ss](auto& info) { if (freeze) { ss << "freezing mds." << gid; info.freeze(); } else { ss << "unfreezing mds." << gid; info.unfreeze(); } }; fsmap.modify_daemon(gid, f); r = 0; } else { return -ENOSYS; } return r; } void MDSMonitor::check_subs() { // Subscriptions may be to "mdsmap" (MDS and legacy clients), // "mdsmap.<namespace>", or to "fsmap" for the full state of all // filesystems. Build a list of all the types we service // subscriptions for. std::vector<std::string> types = { "fsmap", "fsmap.user", "mdsmap", }; for (const auto &p : get_fsmap().filesystems) { const auto &fscid = p.first; CachedStackStringStream cos; *cos << "mdsmap." << fscid; types.push_back(std::string(cos->strv())); } for (const auto &type : types) { auto& subs = mon.session_map.subs; auto subs_it = subs.find(type); if (subs_it == subs.end()) continue; auto sub_it = subs_it->second->begin(); while (!sub_it.end()) { auto sub = *sub_it; ++sub_it; // N.B. check_sub may remove sub! check_sub(sub); } } } void MDSMonitor::check_sub(Subscription *sub) { dout(20) << __func__ << ": " << sub->type << dendl; // to use const qualifier filter fsmap beforehand FSMap _fsmap_copy = get_fsmap(); _fsmap_copy.filter(sub->session->get_allowed_fs_names()); const auto& fsmap = _fsmap_copy; if (sub->next > fsmap.get_epoch()) { return; } if (sub->type == "fsmap") { sub->session->con->send_message(new MFSMap(mon.monmap->fsid, fsmap)); if (sub->onetime) { mon.session_map.remove_sub(sub); } else { sub->next = fsmap.get_epoch() + 1; } } else if (sub->type == "fsmap.user") { FSMapUser fsmap_u; fsmap_u.epoch = fsmap.get_epoch(); fsmap_u.legacy_client_fscid = fsmap.legacy_client_fscid; for (const auto &p : fsmap.filesystems) { FSMapUser::fs_info_t& fs_info = fsmap_u.filesystems[p.second->fscid]; fs_info.cid = p.second->fscid; fs_info.name = p.second->mds_map.fs_name; } sub->session->con->send_message(new MFSMapUser(mon.monmap->fsid, fsmap_u)); if (sub->onetime) { mon.session_map.remove_sub(sub); } else { sub->next = fsmap.get_epoch() + 1; } } else if (sub->type.compare(0, 6, "mdsmap") == 0) { const bool is_mds = sub->session->name.is_mds(); mds_gid_t mds_gid = MDS_GID_NONE; fs_cluster_id_t fscid = FS_CLUSTER_ID_NONE; if (is_mds) { // What (if any) namespace are you assigned to? auto mds_info = fsmap.get_mds_info(); for (const auto &p : mds_info) { if (p.second.addrs == sub->session->addrs) { mds_gid = p.first; fscid = fsmap.mds_roles.at(mds_gid); } } } else { // You're a client. Did you request a particular // namespace? if (sub->type.compare(0, 7, "mdsmap.") == 0) { auto namespace_id_str = sub->type.substr(std::string("mdsmap.").size()); dout(10) << __func__ << ": namespace_id " << namespace_id_str << dendl; std::string err; fscid = strict_strtoll(namespace_id_str.c_str(), 10, &err); if (!err.empty()) { // Client asked for a non-existent namespace, send them nothing dout(1) << "Invalid client subscription '" << sub->type << "'" << dendl; return; } } else { // Unqualified request for "mdsmap": give it the one marked // for use by legacy clients. if (fsmap.legacy_client_fscid != FS_CLUSTER_ID_NONE) { fscid = fsmap.legacy_client_fscid; } else { dout(1) << "Client subscribed for legacy filesystem but " "none is configured" << dendl; return; } } if (!fsmap.filesystem_exists(fscid)) { // Client asked for a non-existent namespace, send them nothing // TODO: something more graceful for when a client has a filesystem // mounted, and the fileysstem is deleted. Add a "shut down you fool" // flag to MMDSMap? dout(1) << "Client subscribed to non-existent namespace '" << fscid << "'" << dendl; return; } } dout(10) << __func__ << ": is_mds=" << is_mds << ", fscid=" << fscid << dendl; // Work out the effective latest epoch const MDSMap *mds_map = nullptr; MDSMap null_map = MDSMap::create_null_mdsmap(); if (fscid == FS_CLUSTER_ID_NONE) { // For a client, we should have already dropped out ceph_assert(is_mds); auto it = fsmap.standby_daemons.find(mds_gid); if (it != fsmap.standby_daemons.end()) { // For an MDS, we need to feed it an MDSMap with its own state in null_map.mds_info[mds_gid] = it->second; null_map.epoch = fsmap.standby_epochs.at(mds_gid); } else { null_map.epoch = fsmap.epoch; } mds_map = &null_map; } else { // Check the effective epoch mds_map = &fsmap.get_filesystem(fscid)->mds_map; } ceph_assert(mds_map != nullptr); dout(10) << __func__ << " selected MDS map epoch " << mds_map->epoch << " for namespace " << fscid << " for subscriber " << sub->session->name << " who wants epoch " << sub->next << dendl; if (sub->next > mds_map->epoch) { return; } auto msg = make_message<MMDSMap>(mon.monmap->fsid, *mds_map); sub->session->con->send_message(msg.detach()); if (sub->onetime) { mon.session_map.remove_sub(sub); } else { sub->next = mds_map->get_epoch() + 1; } } } void MDSMonitor::update_metadata(mds_gid_t gid, const map<string, string>& metadata) { dout(20) << __func__ << ": mds." << gid << ": " << metadata << dendl; if (metadata.empty()) { dout(5) << __func__ << ": mds." << gid << ": no metadata!" << dendl; return; } pending_metadata[gid] = metadata; MonitorDBStore::TransactionRef t = paxos.get_pending_transaction(); bufferlist bl; encode(pending_metadata, bl); t->put(MDS_METADATA_PREFIX, "last_metadata", bl); } void MDSMonitor::remove_from_metadata(const FSMap &fsmap, MonitorDBStore::TransactionRef t) { bool update = false; for (auto it = pending_metadata.begin(); it != pending_metadata.end(); ) { if (!fsmap.gid_exists(it->first)) { it = pending_metadata.erase(it); update = true; } else { ++it; } } if (!update) return; bufferlist bl; encode(pending_metadata, bl); t->put(MDS_METADATA_PREFIX, "last_metadata", bl); } int MDSMonitor::load_metadata(map<mds_gid_t, Metadata>& m) { bufferlist bl; int r = mon.store->get(MDS_METADATA_PREFIX, "last_metadata", bl); if (r) { dout(5) << "Unable to load 'last_metadata'" << dendl; return r; } auto it = bl.cbegin(); ceph::decode(m, it); return 0; } void MDSMonitor::count_metadata(const std::string &field, map<string,int> *out) { map<mds_gid_t,Metadata> meta; load_metadata(meta); for (auto& p : meta) { auto q = p.second.find(field); if (q == p.second.end()) { (*out)["unknown"]++; } else { (*out)[q->second]++; } } } void MDSMonitor::count_metadata(const std::string &field, Formatter *f) { map<string,int> by_val; count_metadata(field, &by_val); f->open_object_section(field.c_str()); for (auto& p : by_val) { f->dump_int(p.first.c_str(), p.second); } f->close_section(); } void MDSMonitor::get_versions(std::map<string, list<string> > &versions) { map<mds_gid_t,Metadata> meta; load_metadata(meta); const auto &fsmap = get_fsmap(); std::map<mds_gid_t, mds_info_t> map = fsmap.get_mds_info(); dout(10) << __func__ << " mds meta=" << meta << dendl; for (auto& p : meta) { auto q = p.second.find("ceph_version_short"); if (q == p.second.end()) continue; versions[q->second].push_back(string("mds.") + map[p.first].name); } } int MDSMonitor::dump_metadata(const FSMap& fsmap, const std::string &who, Formatter *f, ostream& err) { ceph_assert(f); mds_gid_t gid = gid_from_arg(fsmap, who, err); if (gid == MDS_GID_NONE) { return -EINVAL; } map<mds_gid_t, Metadata> metadata; if (int r = load_metadata(metadata)) { err << "Unable to load 'last_metadata'"; return r; } if (!metadata.count(gid)) { return -ENOENT; } const Metadata& m = metadata[gid]; for (Metadata::const_iterator p = m.begin(); p != m.end(); ++p) { f->dump_string(p->first.c_str(), p->second); } return 0; } int MDSMonitor::print_nodes(Formatter *f) { ceph_assert(f); const auto &fsmap = get_fsmap(); map<mds_gid_t, Metadata> metadata; if (int r = load_metadata(metadata)) { return r; } map<string, list<string> > mdses; // hostname => mds for (const auto &p : metadata) { const mds_gid_t& gid = p.first; const Metadata& m = p.second; Metadata::const_iterator hostname = m.find("hostname"); if (hostname == m.end()) { // not likely though continue; } if (!fsmap.gid_exists(gid)) { dout(5) << __func__ << ": GID " << gid << " not existent" << dendl; continue; } const MDSMap::mds_info_t& mds_info = fsmap.get_info_gid(gid); mdses[hostname->second].push_back(mds_info.name); } dump_services(f, mdses, "mds"); return 0; } /** * If a cluster is undersized (with respect to max_mds), then * attempt to find daemons to grow it. If the cluster is oversized * (with respect to max_mds) then shrink it by stopping its highest rank. */ bool MDSMonitor::maybe_resize_cluster(FSMap &fsmap, fs_cluster_id_t fscid) { auto&& fs = fsmap.get_filesystem(fscid); auto &mds_map = fs->mds_map; int in = mds_map.get_num_in_mds(); int max = mds_map.get_max_mds(); dout(20) << __func__ << " in " << in << " max " << max << dendl; /* Check that both the current epoch mds_map is resizeable as well as the * current batch of changes in pending. This is important if an MDS is * becoming active in the next epoch. */ if (!get_fsmap().filesystem_exists(fscid) || !get_fsmap().get_filesystem(fscid)->mds_map.is_resizeable() || !mds_map.is_resizeable()) { dout(5) << __func__ << " mds_map is not currently resizeable" << dendl; return false; } if (in < max && !mds_map.test_flag(CEPH_MDSMAP_NOT_JOINABLE)) { mds_rank_t mds = mds_rank_t(0); while (mds_map.is_in(mds)) { mds++; } auto info = fsmap.find_replacement_for({fscid, mds}); if (!info) { return false; } dout(1) << "assigned standby " << info->addrs << " as mds." << mds << dendl; mon.clog->info() << info->human_name() << " assigned to " "filesystem " << mds_map.fs_name << " as rank " << mds << " (now has " << mds_map.get_num_in_mds() + 1 << " ranks)"; fsmap.promote(info->global_id, *fs, mds); return true; } else if (in > max) { mds_rank_t target = in - 1; const auto &info = mds_map.get_info(target); if (mds_map.is_active(target)) { dout(1) << "stopping " << target << dendl; mon.clog->info() << "stopping " << info.human_name(); auto f = [](auto& info) { info.state = MDSMap::STATE_STOPPING; }; fsmap.modify_daemon(info.global_id, f); return true; } else { dout(20) << "skipping stop of " << target << dendl; return false; } } return false; } /** * Fail a daemon and replace it with a suitable standby. */ bool MDSMonitor::drop_mds(FSMap &fsmap, mds_gid_t gid, const mds_info_t* rep_info, bool *osd_propose) { ceph_assert(osd_propose != nullptr); const auto fscid = fsmap.mds_roles.at(gid); const auto& info = fsmap.get_info_gid(gid); const auto rank = info.rank; const auto state = info.state; if (info.is_frozen()) { return false; } else if (state == MDSMap::STATE_STANDBY_REPLAY || state == MDSMap::STATE_STANDBY) { dout(1) << " failing and removing standby " << gid << " " << info.addrs << " mds." << rank << "." << info.inc << " " << ceph_mds_state_name(state) << dendl; *osd_propose |= fail_mds_gid(fsmap, gid); return true; } else if (rank >= 0 && rep_info) { auto fs = fsmap.filesystems.at(fscid); if (fs->mds_map.test_flag(CEPH_MDSMAP_NOT_JOINABLE)) { return false; } // are we in? // and is there a non-laggy standby that can take over for us? dout(1) << " replacing " << gid << " " << info.addrs << " mds." << rank << "." << info.inc << " " << ceph_mds_state_name(state) << " with " << rep_info->global_id << "/" << rep_info->name << " " << rep_info->addrs << dendl; mon.clog->warn() << "Replacing " << info.human_name() << " as rank " << rank << " with standby " << rep_info->human_name(); // Remove the old one *osd_propose |= fail_mds_gid(fsmap, gid); // Promote the replacement fsmap.promote(rep_info->global_id, *fs, rank); return true; } return false; } bool MDSMonitor::check_health(FSMap& fsmap, bool* propose_osdmap) { bool do_propose = false; const auto now = mono_clock::now(); const bool osdmap_writeable = mon.osdmon()->is_writeable(); const auto mds_beacon_grace = g_conf().get_val<double>("mds_beacon_grace"); const auto mds_beacon_interval = g_conf().get_val<double>("mds_beacon_interval"); if (mono_clock::is_zero(last_tick)) { last_tick = now; } { auto since_last = std::chrono::duration<double>(now-last_tick); if (since_last.count() > (mds_beacon_grace-mds_beacon_interval)) { // This case handles either local slowness (calls being delayed // for whatever reason) or cluster election slowness (a long gap // between calls while an election happened) dout(1) << __func__ << ": resetting beacon timeouts due to mon delay " "(slow election?) of " << since_last.count() << " seconds" << dendl; for (auto& p : last_beacon) { p.second.stamp = now; } } } // make sure last_beacon is fully populated for (auto& p : fsmap.mds_roles) { auto& gid = p.first; last_beacon.emplace(std::piecewise_construct, std::forward_as_tuple(gid), std::forward_as_tuple(now, 0)); } // We will only take decisive action (replacing/removing a daemon) // if we have some indication that some other daemon(s) are successfully // getting beacons through recently. mono_time latest_beacon = mono_clock::zero(); for (const auto& p : last_beacon) { latest_beacon = std::max(p.second.stamp, latest_beacon); } auto since = std::chrono::duration<double>(now-latest_beacon); const bool may_replace = since.count() < std::max(g_conf()->mds_beacon_interval, g_conf()->mds_beacon_grace * 0.5); // check beacon timestamps std::vector<mds_gid_t> to_remove; const bool mon_down = mon.is_mon_down(); const auto mds_beacon_mon_down_grace = g_conf().get_val<std::chrono::seconds>("mds_beacon_mon_down_grace"); const auto quorum_age = std::chrono::seconds(mon.quorum_age()); const bool new_quorum = quorum_age < mds_beacon_mon_down_grace; for (auto it = last_beacon.begin(); it != last_beacon.end(); ) { auto& [gid, beacon_info] = *it; auto since_last = std::chrono::duration<double>(now-beacon_info.stamp); if (!fsmap.gid_exists(gid)) { // gid no longer exists, remove from tracked beacons it = last_beacon.erase(it); continue; } if (since_last.count() >= g_conf()->mds_beacon_grace) { auto& info = fsmap.get_info_gid(gid); dout(1) << "no beacon from mds." << info.rank << "." << info.inc << " (gid: " << gid << " addr: " << info.addrs << " state: " << ceph_mds_state_name(info.state) << ")" << " since " << since_last.count() << dendl; if ((mon_down || new_quorum) && since_last < mds_beacon_mon_down_grace) { /* The MDS may be sending beacons to a monitor not yet in quorum or * temporarily partitioned. Hold off on removal for a little longer... */ dout(10) << "deferring removal for mds_beacon_mon_down_grace during MON_DOWN" << dendl; ++it; continue; } // If the OSDMap is writeable, we can blocklist things, so we can // try failing any laggy MDS daemons. Consider each one for failure. if (!info.laggy()) { dout(1) << " marking " << gid << " " << info.addrs << " mds." << info.rank << "." << info.inc << " " << ceph_mds_state_name(info.state) << " laggy" << dendl; fsmap.modify_daemon(info.global_id, [](auto& info) { info.laggy_since = ceph_clock_now(); }); do_propose = true; } if (osdmap_writeable && may_replace) { to_remove.push_back(gid); // drop_mds may invalidate iterator } } ++it; } for (const auto& gid : to_remove) { auto info = fsmap.get_info_gid(gid); const mds_info_t* rep_info = nullptr; if (info.rank >= 0) { auto fscid = fsmap.fscid_from_gid(gid); rep_info = fsmap.find_replacement_for({fscid, info.rank}); } bool dropped = drop_mds(fsmap, gid, rep_info, propose_osdmap); if (dropped) { mon.clog->info() << "MDS " << info.human_name() << " is removed because it is dead or otherwise unavailable."; do_propose = true; } } if (osdmap_writeable) { for (auto& [fscid, fs] : fsmap.filesystems) { if (!fs->mds_map.test_flag(CEPH_MDSMAP_NOT_JOINABLE) && fs->mds_map.is_resizeable()) { // Check if a rank or standby-replay should be replaced with a stronger // affinity standby. This looks at ranks and standby-replay: for (const auto& [gid, info] : fs->mds_map.get_mds_info()) { const auto join_fscid = info.join_fscid; if (join_fscid == fscid) continue; const auto rank = info.rank; const auto state = info.state; const mds_info_t* rep_info = nullptr; if (state == MDSMap::STATE_STANDBY_REPLAY) { rep_info = fsmap.get_available_standby(*fs); } else if (state == MDSMap::STATE_ACTIVE) { rep_info = fsmap.find_replacement_for({fscid, rank}); } else { /* N.B. !is_degraded() */ ceph_abort_msg("invalid state in MDSMap"); } if (!rep_info) { break; } bool better_affinity = false; if (join_fscid == FS_CLUSTER_ID_NONE) { better_affinity = (rep_info->join_fscid == fscid); } else { better_affinity = (rep_info->join_fscid == fscid) || (rep_info->join_fscid == FS_CLUSTER_ID_NONE); } if (better_affinity) { if (state == MDSMap::STATE_STANDBY_REPLAY) { mon.clog->info() << "Dropping low affinity standby-replay " << info.human_name() << " in favor of higher affinity standby."; *propose_osdmap |= fail_mds_gid(fsmap, gid); /* Now let maybe_promote_standby do the promotion. */ } else { mon.clog->info() << "Dropping low affinity active " << info.human_name() << " in favor of higher affinity standby."; do_propose |= drop_mds(fsmap, gid, rep_info, propose_osdmap); } break; /* don't replace more than one per tick per fs */ } } } } } return do_propose; } bool MDSMonitor::maybe_promote_standby(FSMap &fsmap, Filesystem& fs) { if (fs.mds_map.test_flag(CEPH_MDSMAP_NOT_JOINABLE)) { return false; } bool do_propose = false; // have a standby take over? set<mds_rank_t> failed; fs.mds_map.get_failed_mds_set(failed); for (const auto& rank : failed) { auto info = fsmap.find_replacement_for({fs.fscid, rank}); if (info) { dout(1) << " taking over failed mds." << rank << " with " << info->global_id << "/" << info->name << " " << info->addrs << dendl; mon.clog->info() << "Standby " << info->human_name() << " assigned to filesystem " << fs.mds_map.fs_name << " as rank " << rank; fsmap.promote(info->global_id, fs, rank); do_propose = true; } } if (fs.mds_map.is_resizeable() && fs.mds_map.allows_standby_replay()) { // There were no failures to replace, so try using any available standbys // as standby-replay daemons. Don't do this when the cluster is degraded // as a standby-replay daemon may try to read a journal being migrated. for (;;) { auto info = fsmap.get_available_standby(fs); if (!info) break; dout(20) << "standby available mds." << info->global_id << dendl; bool changed = false; for (const auto& rank : fs.mds_map.in) { dout(20) << "examining " << rank << dendl; if (fs.mds_map.is_followable(rank)) { dout(1) << " setting mds." << info->global_id << " to follow mds rank " << rank << dendl; fsmap.assign_standby_replay(info->global_id, fs.fscid, rank); do_propose = true; changed = true; break; } } if (!changed) break; } } return do_propose; } void MDSMonitor::tick() { if (!is_active() || !is_leader()) return; auto &pending = get_pending_fsmap_writeable(); /* batch any changes to pending with any changes to osdmap */ paxos.plug(); bool do_propose = false; bool propose_osdmap = false; if (check_fsmap_struct_version) { /* Allow time for trimming otherwise PaxosService::is_writeable will always * be false. */ auto now = clock::now(); auto elapsed = now - last_fsmap_struct_flush; if (elapsed > std::chrono::seconds(30)) { FSMap fsmap; bufferlist bl; auto v = get_first_committed(); int err = get_version(v, bl); if (err) { derr << "could not get version " << v << dendl; ceph_abort(); } try { fsmap.decode(bl); } catch (const ceph::buffer::malformed_input& e) { dout(5) << "flushing old fsmap struct because unable to decode FSMap: " << e.what() << dendl; } /* N.B. FSMap::is_struct_old is also true for undecoded (failed to decode) FSMap */ if (fsmap.is_struct_old()) { dout(5) << "fsmap struct is too old; proposing to flush out old versions" << dendl; do_propose = true; last_fsmap_struct_flush = now; } else { dout(20) << "struct is recent" << dendl; check_fsmap_struct_version = false; } } } do_propose |= pending.check_health(); /* Check health and affinity of ranks */ do_propose |= check_health(pending, &propose_osdmap); /* Resize the cluster according to max_mds. */ for (auto& p : pending.filesystems) { do_propose |= maybe_resize_cluster(pending, p.second->fscid); } /* Replace any failed ranks. */ for (auto& p : pending.filesystems) { do_propose |= maybe_promote_standby(pending, *p.second); } if (propose_osdmap) { request_proposal(mon.osdmon()); } /* allow MDSMonitor::propose_pending() to push the proposal through */ paxos.unplug(); if (do_propose) { propose_pending(); } last_tick = mono_clock::now(); } MDSMonitor::MDSMonitor(Monitor &mn, Paxos &p, string service_name) : PaxosService(mn, p, service_name) { handlers = FileSystemCommandHandler::load(&p); } void MDSMonitor::on_restart() { // Clear out the leader-specific state. last_tick = mono_clock::now(); last_beacon.clear(); }
72,593
29.222315
127
cc
null
ceph-main/src/mon/MDSMonitor.h
// -*- 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. * */ /* Metadata Server Monitor */ #ifndef CEPH_MDSMONITOR_H #define CEPH_MDSMONITOR_H #include <map> #include <set> #include "include/types.h" #include "PaxosFSMap.h" #include "PaxosService.h" #include "msg/Messenger.h" #include "messages/MMDSBeacon.h" #include "CommandHandler.h" class FileSystemCommandHandler; class MDSMonitor : public PaxosService, public PaxosFSMap, protected CommandHandler { public: using clock = ceph::coarse_mono_clock; using time = ceph::coarse_mono_time; MDSMonitor(Monitor &mn, Paxos &p, std::string service_name); // service methods void create_initial() override; void get_store_prefixes(std::set<std::string>& s) const override; void update_from_paxos(bool *need_bootstrap) override; void init() override; void create_pending() override; void encode_pending(MonitorDBStore::TransactionRef t) override; // we don't require full versions; don't encode any. void encode_full(MonitorDBStore::TransactionRef t) override { } version_t get_trim_to() const override; bool preprocess_query(MonOpRequestRef op) override; // true if processed. bool prepare_update(MonOpRequestRef op) override; bool should_propose(double& delay) override; bool should_print_status() const { auto& fs = get_fsmap(); auto fs_count = fs.filesystem_count(); auto standby_count = fs.get_num_standby(); return fs_count > 0 || standby_count > 0; } void on_active() override; void on_restart() override; void check_subs(); void check_sub(Subscription *sub); void dump_info(ceph::Formatter *f); int print_nodes(ceph::Formatter *f); /** * Return true if a blocklist was done (i.e. OSD propose needed) */ bool fail_mds_gid(FSMap &fsmap, mds_gid_t gid); bool is_leader() const override { return mon.is_leader(); } protected: using mds_info_t = MDSMap::mds_info_t; // my helpers template<int dblV = 7> void print_map(const FSMap &m); void _updated(MonOpRequestRef op); void _note_beacon(class MMDSBeacon *m); bool preprocess_beacon(MonOpRequestRef op); bool prepare_beacon(MonOpRequestRef op); bool preprocess_offload_targets(MonOpRequestRef op); bool prepare_offload_targets(MonOpRequestRef op); int fail_mds(FSMap &fsmap, std::ostream &ss, const std::string &arg, mds_info_t *failed_info); bool preprocess_command(MonOpRequestRef op); bool prepare_command(MonOpRequestRef op); int filesystem_command( FSMap &fsmap, MonOpRequestRef op, std::string const &prefix, const cmdmap_t& cmdmap, std::stringstream &ss); // beacons struct beacon_info_t { ceph::mono_time stamp = ceph::mono_clock::zero(); uint64_t seq = 0; beacon_info_t() {} beacon_info_t(ceph::mono_time stamp, uint64_t seq) : stamp(stamp), seq(seq) {} }; std::map<mds_gid_t, beacon_info_t> last_beacon; std::list<std::shared_ptr<FileSystemCommandHandler> > handlers; bool maybe_promote_standby(FSMap& fsmap, Filesystem& fs); bool maybe_resize_cluster(FSMap &fsmap, fs_cluster_id_t fscid); bool drop_mds(FSMap &fsmap, mds_gid_t gid, const mds_info_t* rep_info, bool* osd_propose); bool check_health(FSMap &fsmap, bool* osd_propose); void tick() override; // check state, take actions int dump_metadata(const FSMap &fsmap, const std::string &who, ceph::Formatter *f, std::ostream& err); void update_metadata(mds_gid_t gid, const Metadata& metadata); void remove_from_metadata(const FSMap &fsmap, MonitorDBStore::TransactionRef t); int load_metadata(std::map<mds_gid_t, Metadata>& m); void count_metadata(const std::string& field, ceph::Formatter *f); public: void print_fs_summary(std::ostream& out) { get_fsmap().print_fs_summary(out); } void count_metadata(const std::string& field, std::map<std::string,int> *out); void get_versions(std::map<std::string, std::list<std::string>> &versions); protected: // MDS daemon GID to latest health state from that GID std::map<uint64_t, MDSHealth> pending_daemon_health; std::set<uint64_t> pending_daemon_health_rm; std::map<mds_gid_t, Metadata> pending_metadata; mds_gid_t gid_from_arg(const FSMap &fsmap, const std::string &arg, std::ostream& err); // When did the mon last call into our tick() method? Used for detecting // when the mon was not updating us for some period (e.g. during slow // election) to reset last_beacon timeouts ceph::mono_time last_tick = ceph::mono_clock::zero(); private: time last_fsmap_struct_flush = clock::zero(); bool check_fsmap_struct_version = true; }; #endif
4,982
30.339623
92
h
null
ceph-main/src/mon/MgrMap.h
// -*- 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 John Spray <[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. */ #ifndef MGR_MAP_H_ #define MGR_MAP_H_ #include <sstream> #include <set> #include "msg/msg_types.h" #include "include/encoding.h" #include "include/utime.h" #include "common/Formatter.h" #include "common/ceph_releases.h" #include "common/version.h" #include "common/options.h" #include "common/Clock.h" class MgrMap { public: struct ModuleOption { std::string name; uint8_t type = Option::TYPE_STR; // Option::type_t TYPE_* uint8_t level = Option::LEVEL_ADVANCED; // Option::level_t LEVEL_* uint32_t flags = 0; // Option::flag_t FLAG_* std::string default_value; std::string min, max; std::set<std::string> enum_allowed; std::string desc, long_desc; std::set<std::string> tags; std::set<std::string> see_also; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(name, bl); encode(type, bl); encode(level, bl); encode(flags, bl); encode(default_value, bl); encode(min, bl); encode(max, bl); encode(enum_allowed, bl); encode(desc, bl); encode(long_desc, bl); encode(tags, bl); encode(see_also, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& p) { DECODE_START(1, p); decode(name, p); decode(type, p); decode(level, p); decode(flags, p); decode(default_value, p); decode(min, p); decode(max, p); decode(enum_allowed, p); decode(desc, p); decode(long_desc, p); decode(tags, p); decode(see_also, p); DECODE_FINISH(p); } void dump(ceph::Formatter *f) const { f->dump_string("name", name); f->dump_string("type", Option::type_to_str( static_cast<Option::type_t>(type))); f->dump_string("level", Option::level_to_str( static_cast<Option::level_t>(level))); f->dump_unsigned("flags", flags); f->dump_string("default_value", default_value); f->dump_string("min", min); f->dump_string("max", max); f->open_array_section("enum_allowed"); for (auto& i : enum_allowed) { f->dump_string("value", i); } f->close_section(); f->dump_string("desc", desc); f->dump_string("long_desc", long_desc); f->open_array_section("tags"); for (auto& i : tags) { f->dump_string("tag", i); } f->close_section(); f->open_array_section("see_also"); for (auto& i : see_also) { f->dump_string("option", i); } f->close_section(); } }; class ModuleInfo { public: std::string name; bool can_run = true; std::string error_string; std::map<std::string,ModuleOption> module_options; // We do not include the module's `failed` field in the beacon, // because it is exposed via health checks. void encode(ceph::buffer::list &bl) const { ENCODE_START(2, 1, bl); encode(name, bl); encode(can_run, bl); encode(error_string, bl); encode(module_options, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode(name, bl); decode(can_run, bl); decode(error_string, bl); if (struct_v >= 2) { decode(module_options, bl); } DECODE_FINISH(bl); } bool operator==(const ModuleInfo &rhs) const { return (name == rhs.name) && (can_run == rhs.can_run); } void dump(ceph::Formatter *f) const { f->open_object_section("module"); f->dump_string("name", name); f->dump_bool("can_run", can_run); f->dump_string("error_string", error_string); f->open_object_section("module_options"); for (auto& i : module_options) { f->dump_object(i.first.c_str(), i.second); } f->close_section(); f->close_section(); } }; class StandbyInfo { public: uint64_t gid = 0; std::string name; std::vector<ModuleInfo> available_modules; uint64_t mgr_features = 0; StandbyInfo(uint64_t gid_, const std::string &name_, const std::vector<ModuleInfo>& am, uint64_t feat) : gid(gid_), name(name_), available_modules(am), mgr_features(feat) {} StandbyInfo() {} void encode(ceph::buffer::list& bl) const { ENCODE_START(4, 1, bl); encode(gid, bl); encode(name, bl); std::set<std::string> old_available_modules; for (const auto &i : available_modules) { old_available_modules.insert(i.name); } encode(old_available_modules, bl); // version 2 encode(available_modules, bl); // version 3 encode(mgr_features, bl); // v4 ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& p) { DECODE_START(4, p); decode(gid, p); decode(name, p); if (struct_v >= 2) { std::set<std::string> old_available_modules; decode(old_available_modules, p); if (struct_v < 3) { for (const auto &name : old_available_modules) { MgrMap::ModuleInfo info; info.name = name; available_modules.push_back(std::move(info)); } } } if (struct_v >= 3) { decode(available_modules, p); } if (struct_v >= 4) { decode(mgr_features, p); } DECODE_FINISH(p); } bool have_module(const std::string &module_name) const { auto it = std::find_if(available_modules.begin(), available_modules.end(), [module_name](const ModuleInfo &m) -> bool { return m.name == module_name; }); return it != available_modules.end(); } }; epoch_t epoch = 0; epoch_t last_failure_osd_epoch = 0; /// global_id of the ceph-mgr instance selected as a leader uint64_t active_gid = 0; /// server address reported by the leader once it is active entity_addrvec_t active_addrs; /// whether the nominated leader is active (i.e. has initialized its server) bool available = false; /// the name (foo in mgr.<foo>) of the active daemon std::string active_name; /// when the active mgr became active, or we lost the active mgr utime_t active_change; /// features uint64_t active_mgr_features = 0; std::multimap<std::string, entity_addrvec_t> clients; // for blocklist std::map<uint64_t, StandbyInfo> standbys; // Modules which are enabled std::set<std::string> modules; // Modules which should always be enabled. A manager daemon will enable // modules from the union of this set and the `modules` set above, latest // active version. std::map<uint32_t, std::set<std::string>> always_on_modules; // Modules which are reported to exist std::vector<ModuleInfo> available_modules; // Map of module name to URI, indicating services exposed by // running modules on the active mgr daemon. std::map<std::string, std::string> services; static MgrMap create_null_mgrmap() { MgrMap null_map; /* Use the largest epoch so it's always bigger than whatever the mgr has. */ null_map.epoch = std::numeric_limits<decltype(epoch)>::max(); return null_map; } epoch_t get_epoch() const { return epoch; } epoch_t get_last_failure_osd_epoch() const { return last_failure_osd_epoch; } const entity_addrvec_t& get_active_addrs() const { return active_addrs; } uint64_t get_active_gid() const { return active_gid; } bool get_available() const { return available; } const std::string &get_active_name() const { return active_name; } const utime_t& get_active_change() const { return active_change; } int get_num_standby() const { return standbys.size(); } bool all_support_module(const std::string& module) { if (!have_module(module)) { return false; } for (auto& p : standbys) { if (!p.second.have_module(module)) { return false; } } return true; } bool have_module(const std::string &module_name) const { for (const auto &i : available_modules) { if (i.name == module_name) { return true; } } return false; } const ModuleInfo *get_module_info(const std::string &module_name) const { for (const auto &i : available_modules) { if (i.name == module_name) { return &i; } } return nullptr; } bool can_run_module(const std::string &module_name, std::string *error) const { for (const auto &i : available_modules) { if (i.name == module_name) { *error = i.error_string; return i.can_run; } } std::ostringstream oss; oss << "Module '" << module_name << "' does not exist"; throw std::logic_error(oss.str()); } bool module_enabled(const std::string& module_name) const { return modules.find(module_name) != modules.end(); } bool any_supports_module(const std::string& module) const { if (have_module(module)) { return true; } for (auto& p : standbys) { if (p.second.have_module(module)) { return true; } } return false; } bool have_name(const std::string& name) const { if (active_name == name) { return true; } for (auto& p : standbys) { if (p.second.name == name) { return true; } } return false; } std::set<std::string> get_all_names() const { std::set<std::string> ls; if (active_name.size()) { ls.insert(active_name); } for (auto& p : standbys) { ls.insert(p.second.name); } return ls; } std::set<std::string> get_always_on_modules() const { unsigned rnum = to_integer<uint32_t>(ceph_release()); auto it = always_on_modules.find(rnum); if (it == always_on_modules.end()) { // ok, try the most recent release if (always_on_modules.empty()) { return {}; // ugh } --it; if (it->first < rnum) { return it->second; } return {}; // wth } return it->second; } void encode(ceph::buffer::list& bl, uint64_t features) const { if (!HAVE_FEATURE(features, SERVER_NAUTILUS)) { ENCODE_START(5, 1, bl); encode(epoch, bl); encode(active_addrs.legacy_addr(), bl, features); encode(active_gid, bl); encode(available, bl); encode(active_name, bl); encode(standbys, bl); encode(modules, bl); // Pre-version 4 std::string std::list of available modules // (replaced by direct encode of ModuleInfo below) std::set<std::string> old_available_modules; for (const auto &i : available_modules) { old_available_modules.insert(i.name); } encode(old_available_modules, bl); encode(services, bl); encode(available_modules, bl); ENCODE_FINISH(bl); return; } ENCODE_START(12, 6, bl); encode(epoch, bl); encode(active_addrs, bl, features); encode(active_gid, bl); encode(available, bl); encode(active_name, bl); encode(standbys, bl); encode(modules, bl); encode(services, bl); encode(available_modules, bl); encode(active_change, bl); encode(always_on_modules, bl); encode(active_mgr_features, bl); encode(last_failure_osd_epoch, bl); std::vector<std::string> clients_names; std::vector<entity_addrvec_t> clients_addrs; for (const auto& i : clients) { clients_names.push_back(i.first); clients_addrs.push_back(i.second); } // The address vector needs to be encoded first to produce a // backwards compatible messsage for older monitors. encode(clients_addrs, bl, features); encode(clients_names, bl, features); ENCODE_FINISH(bl); return; } void decode(ceph::buffer::list::const_iterator& p) { DECODE_START(12, p); decode(epoch, p); decode(active_addrs, p); decode(active_gid, p); decode(available, p); decode(active_name, p); decode(standbys, p); if (struct_v >= 2) { decode(modules, p); if (struct_v < 6) { // Reconstitute ModuleInfos from names std::set<std::string> module_name_list; decode(module_name_list, p); // Only need to unpack this field if we won't have the full // MgrMap::ModuleInfo structures added in v4 if (struct_v < 4) { for (const auto &i : module_name_list) { MgrMap::ModuleInfo info; info.name = i; available_modules.push_back(std::move(info)); } } } } if (struct_v >= 3) { decode(services, p); } if (struct_v >= 4) { decode(available_modules, p); } if (struct_v >= 7) { decode(active_change, p); } else { active_change = {}; } if (struct_v >= 8) { decode(always_on_modules, p); } if (struct_v >= 9) { decode(active_mgr_features, p); } if (struct_v >= 10) { decode(last_failure_osd_epoch, p); } if (struct_v >= 11) { std::vector<entity_addrvec_t> clients_addrs; decode(clients_addrs, p); clients.clear(); if (struct_v >= 12) { std::vector<std::string> clients_names; decode(clients_names, p); if (clients_names.size() != clients_addrs.size()) { throw ceph::buffer::malformed_input( "clients_names.size() != clients_addrs.size()"); } auto cn = clients_names.begin(); auto ca = clients_addrs.begin(); for(; cn != clients_names.end(); ++cn, ++ca) { clients.emplace(*cn, *ca); } } else { for (const auto& i : clients_addrs) { clients.emplace("", i); } } } DECODE_FINISH(p); } void dump(ceph::Formatter *f) const { f->dump_int("epoch", epoch); f->dump_int("active_gid", get_active_gid()); f->dump_string("active_name", get_active_name()); f->dump_object("active_addrs", active_addrs); f->dump_stream("active_addr") << active_addrs.get_legacy_str(); f->dump_stream("active_change") << active_change; f->dump_unsigned("active_mgr_features", active_mgr_features); f->dump_bool("available", available); f->open_array_section("standbys"); for (const auto &i : standbys) { f->open_object_section("standby"); f->dump_int("gid", i.second.gid); f->dump_string("name", i.second.name); f->dump_unsigned("mgr_features", i.second.mgr_features); f->open_array_section("available_modules"); for (const auto& j : i.second.available_modules) { j.dump(f); } f->close_section(); f->close_section(); } f->close_section(); f->open_array_section("modules"); for (auto& i : modules) { f->dump_string("module", i); } f->close_section(); f->open_array_section("available_modules"); for (const auto& j : available_modules) { j.dump(f); } f->close_section(); f->open_object_section("services"); for (const auto &i : services) { f->dump_string(i.first.c_str(), i.second); } f->close_section(); f->open_object_section("always_on_modules"); for (auto& v : always_on_modules) { f->open_array_section(ceph_release_name(v.first)); for (auto& m : v.second) { f->dump_string("module", m); } f->close_section(); } f->close_section(); // always_on_modules f->dump_int("last_failure_osd_epoch", last_failure_osd_epoch); f->open_array_section("active_clients"); for (const auto& i : clients) { f->open_object_section("client"); f->dump_string("name", i.first); i.second.dump(f); f->close_section(); } f->close_section(); // active_clients } static void generate_test_instances(std::list<MgrMap*> &l) { l.push_back(new MgrMap); } void print_summary(ceph::Formatter *f, std::ostream *ss) const { // One or the other, not both ceph_assert((ss != nullptr) != (f != nullptr)); if (f) { f->dump_bool("available", available); f->dump_int("num_standbys", standbys.size()); f->open_array_section("modules"); for (auto& i : modules) { f->dump_string("module", i); } f->close_section(); f->open_object_section("services"); for (const auto &i : services) { f->dump_string(i.first.c_str(), i.second); } f->close_section(); } else { utime_t now = ceph_clock_now(); if (get_active_gid() != 0) { *ss << get_active_name(); if (!available) { // If the daemon hasn't gone active yet, indicate that. *ss << "(active, starting"; } else { *ss << "(active"; } if (active_change) { *ss << ", since " << utimespan_str(now - active_change); } *ss << ")"; } else { *ss << "no daemons active"; if (active_change) { *ss << " (since " << utimespan_str(now - active_change) << ")"; } } if (standbys.size()) { *ss << ", standbys: "; bool first = true; for (const auto &i : standbys) { if (!first) { *ss << ", "; } *ss << i.second.name; first = false; } } } } friend std::ostream& operator<<(std::ostream& out, const MgrMap& m) { std::ostringstream ss; m.print_summary(nullptr, &ss); return out << ss.str(); } friend std::ostream& operator<<(std::ostream& out, const std::vector<ModuleInfo>& mi) { for (const auto &i : mi) { out << i.name << " "; } return out; } }; WRITE_CLASS_ENCODER_FEATURES(MgrMap) WRITE_CLASS_ENCODER(MgrMap::StandbyInfo) WRITE_CLASS_ENCODER(MgrMap::ModuleInfo); WRITE_CLASS_ENCODER(MgrMap::ModuleOption); #endif
17,803
26.81875
89
h
null
ceph-main/src/mon/MgrMonitor.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 John Spray <[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 <boost/tokenizer.hpp> #include "messages/MMgrBeacon.h" #include "messages/MMgrMap.h" #include "messages/MMgrDigest.h" #include "include/stringify.h" #include "mgr/MgrContext.h" #include "mgr/mgr_commands.h" #include "OSDMonitor.h" #include "ConfigMonitor.h" #include "HealthMonitor.h" #include "common/TextTable.h" #include "include/stringify.h" #include "MgrMonitor.h" #define MGR_METADATA_PREFIX "mgr_metadata" #define dout_subsys ceph_subsys_mon #undef dout_prefix #define dout_prefix _prefix(_dout, mon, map) using namespace TOPNSPC::common; using std::dec; using std::hex; using std::list; using std::map; using std::make_pair; using std::ostream; using std::ostringstream; using std::pair; using std::set; using std::string; using std::stringstream; using std::to_string; using std::vector; using ceph::bufferlist; using ceph::decode; using ceph::encode; using ceph::ErasureCodeInterfaceRef; using ceph::ErasureCodeProfile; using ceph::Formatter; using ceph::JSONFormatter; using ceph::make_message; using ceph::mono_clock; using ceph::mono_time; static ostream& _prefix(std::ostream *_dout, Monitor &mon, const MgrMap& mgrmap) { return *_dout << "mon." << mon.name << "@" << mon.rank << "(" << mon.get_state_name() << ").mgr e" << mgrmap.get_epoch() << " "; } // the system treats always_on_modules as if they provide built-in functionality // by ensuring that they are always enabled. const static std::map<uint32_t, std::set<std::string>> always_on_modules = { { CEPH_RELEASE_OCTOPUS, { "crash", "status", "progress", "balancer", "devicehealth", "orchestrator", "rbd_support", "volumes", "pg_autoscaler", "telemetry", } }, { CEPH_RELEASE_PACIFIC, { "crash", "status", "progress", "balancer", "devicehealth", "orchestrator", "rbd_support", "volumes", "pg_autoscaler", "telemetry", } }, { CEPH_RELEASE_QUINCY, { "crash", "status", "progress", "balancer", "devicehealth", "orchestrator", "rbd_support", "volumes", "pg_autoscaler", "telemetry", } }, { CEPH_RELEASE_REEF, { "crash", "status", "progress", "balancer", "devicehealth", "orchestrator", "rbd_support", "volumes", "pg_autoscaler", "telemetry", } }, }; // Prefix for mon store of active mgr's command descriptions const static std::string command_descs_prefix = "mgr_command_descs"; const Option *MgrMonitor::find_module_option(const string& name) { // we have two forms of names: "mgr/$module/$option" and // localized "mgr/$module/$instance/$option". normalize to the // former by stripping out $instance. string real_name; if (name.substr(0, 4) != "mgr/") { return nullptr; } auto second_slash = name.find('/', 5); if (second_slash == std::string::npos) { return nullptr; } auto third_slash = name.find('/', second_slash + 1); if (third_slash != std::string::npos) { // drop the $instance part between the second and third slash real_name = name.substr(0, second_slash) + name.substr(third_slash); } else { real_name = name; } auto p = mgr_module_options.find(real_name); if (p != mgr_module_options.end()) { return &p->second; } return nullptr; } version_t MgrMonitor::get_trim_to() const { int64_t max = g_conf().get_val<int64_t>("mon_max_mgrmap_epochs"); if (map.epoch > max) { return map.epoch - max; } return 0; } void MgrMonitor::create_initial() { // Take a local copy of initial_modules for tokenizer to iterate over. auto initial_modules = g_conf().get_val<std::string>("mgr_initial_modules"); boost::tokenizer<> tok(initial_modules); for (auto& m : tok) { pending_map.modules.insert(m); } pending_map.always_on_modules = always_on_modules; pending_command_descs = mgr_commands; dout(10) << __func__ << " initial modules " << pending_map.modules << ", always on modules " << pending_map.get_always_on_modules() << ", " << pending_command_descs.size() << " commands" << dendl; } void MgrMonitor::get_store_prefixes(std::set<string>& s) const { s.insert(service_name); s.insert(command_descs_prefix); s.insert(MGR_METADATA_PREFIX); } void MgrMonitor::update_from_paxos(bool *need_bootstrap) { version_t version = get_last_committed(); if (version != map.epoch) { dout(4) << "loading version " << version << dendl; bufferlist bl; int err = get_version(version, bl); ceph_assert(err == 0); bool old_available = map.get_available(); uint64_t old_gid = map.get_active_gid(); auto p = bl.cbegin(); map.decode(p); dout(4) << "active server: " << map.active_addrs << "(" << map.active_gid << ")" << dendl; ever_had_active_mgr = get_value("ever_had_active_mgr"); load_health(); if (map.available) { first_seen_inactive = utime_t(); } else { first_seen_inactive = ceph_clock_now(); } check_subs(); if (version == 1 || command_descs.empty() || (map.get_available() && (!old_available || old_gid != map.get_active_gid()))) { dout(4) << "mkfs or daemon transitioned to available, loading commands" << dendl; bufferlist loaded_commands; int r = mon.store->get(command_descs_prefix, "", loaded_commands); if (r < 0) { derr << "Failed to load mgr commands: " << cpp_strerror(r) << dendl; } else { auto p = loaded_commands.cbegin(); decode(command_descs, p); } } } // populate module options mgr_module_options.clear(); misc_option_strings.clear(); for (auto& i : map.available_modules) { for (auto& j : i.module_options) { string name = string("mgr/") + i.name + "/" + j.second.name; auto p = mgr_module_options.emplace( name, Option(name, static_cast<Option::type_t>(j.second.type), static_cast<Option::level_t>(j.second.level))); Option& opt = p.first->second; opt.set_flags(static_cast<Option::flag_t>(j.second.flags)); opt.set_flag(Option::FLAG_MGR); opt.set_description(j.second.desc.c_str()); opt.set_long_description(j.second.long_desc.c_str()); for (auto& k : j.second.tags) { opt.add_tag(k.c_str()); } for (auto& k : j.second.see_also) { if (i.module_options.count(k)) { // it's another module option misc_option_strings.push_back(string("mgr/") + i.name + "/" + k); opt.add_see_also(misc_option_strings.back().c_str()); } else { // it's a native option opt.add_see_also(k.c_str()); } } Option::value_t v, v2; std::string err; if (j.second.default_value.size() && !opt.parse_value(j.second.default_value, &v, &err)) { opt.set_default(v); } if (j.second.min.size() && j.second.max.size() && !opt.parse_value(j.second.min, &v, &err) && !opt.parse_value(j.second.max, &v2, &err)) { opt.set_min_max(v, v2); } std::vector<const char *> enum_allowed; for (auto& k : j.second.enum_allowed) { enum_allowed.push_back(k.c_str()); } opt.set_enum_allowed(enum_allowed); } } // force ConfigMonitor to refresh, since it uses const Option * // pointers into our mgr_module_options (which we just rebuilt). mon.configmon()->load_config(); if (!mon.is_init()) { // feed our pet MgrClient, unless we are in Monitor::[pre]init() prime_mgr_client(); } } void MgrMonitor::prime_mgr_client() { dout(10) << __func__ << dendl; mon.mgr_client.ms_dispatch2(make_message<MMgrMap>(map)); } void MgrMonitor::create_pending() { pending_map = map; pending_map.epoch++; } health_status_t MgrMonitor::should_warn_about_mgr_down() { utime_t now = ceph_clock_now(); // we warn if we have osds AND we've exceeded the grace period // which means a new mon cluster and be HEALTH_OK indefinitely as long as // no OSDs are ever created. if (mon.osdmon()->osdmap.get_num_osds() > 0 && now > mon.monmap->created + g_conf().get_val<int64_t>("mon_mgr_mkfs_grace")) { health_status_t level = HEALTH_WARN; if (first_seen_inactive != utime_t() && now - first_seen_inactive > g_conf().get_val<int64_t>("mon_mgr_inactive_grace")) { level = HEALTH_ERR; } return level; } return HEALTH_OK; } void MgrMonitor::post_paxos_update() { // are we handling digest subscribers? if (digest_event) { bool send = false; if (prev_health_checks.empty()) { prev_health_checks.resize(mon.paxos_service.size()); send = true; } ceph_assert(prev_health_checks.size() == mon.paxos_service.size()); for (auto i = 0u; i < prev_health_checks.size(); i++) { const auto& curr = mon.paxos_service[i]->get_health_checks(); if (!send && curr != prev_health_checks[i]) { send = true; } prev_health_checks[i] = curr; } if (send) { if (is_active()) { send_digests(); } else { cancel_timer(); wait_for_active_ctx(new C_MonContext{&mon, [this](int) { send_digests(); }}); } } } } void MgrMonitor::encode_pending(MonitorDBStore::TransactionRef t) { dout(10) << __func__ << " " << pending_map << dendl; bufferlist bl; pending_map.encode(bl, mon.get_quorum_con_features()); put_version(t, pending_map.epoch, bl); put_last_committed(t, pending_map.epoch); for (auto& p : pending_metadata) { dout(10) << __func__ << " set metadata for " << p.first << dendl; t->put(MGR_METADATA_PREFIX, p.first, p.second); } for (auto& name : pending_metadata_rm) { dout(10) << __func__ << " rm metadata for " << name << dendl; t->erase(MGR_METADATA_PREFIX, name); } pending_metadata.clear(); pending_metadata_rm.clear(); health_check_map_t next; if (pending_map.active_gid == 0) { auto level = should_warn_about_mgr_down(); if (level != HEALTH_OK) { next.add("MGR_DOWN", level, "no active mgr", 0); } else { dout(10) << __func__ << " no health warning (never active and new cluster)" << dendl; } } else { put_value(t, "ever_had_active_mgr", 1); } encode_health(next, t); if (pending_command_descs.size()) { dout(4) << __func__ << " encoding " << pending_command_descs.size() << " command_descs" << dendl; for (auto& p : pending_command_descs) { p.set_flag(MonCommand::FLAG_MGR); } bufferlist bl; encode(pending_command_descs, bl); t->put(command_descs_prefix, "", bl); pending_command_descs.clear(); } } bool MgrMonitor::check_caps(MonOpRequestRef op, const uuid_d& fsid) { // check permissions MonSession *session = op->get_session(); if (!session) return false; if (!session->is_capable("mgr", MON_CAP_X)) { dout(1) << __func__ << " insufficient caps " << session->caps << dendl; return false; } if (fsid != mon.monmap->fsid) { dout(1) << __func__ << " op fsid " << fsid << " != " << mon.monmap->fsid << dendl; return false; } return true; } bool MgrMonitor::preprocess_query(MonOpRequestRef op) { auto m = op->get_req<PaxosServiceMessage>(); switch (m->get_type()) { case MSG_MGR_BEACON: return preprocess_beacon(op); case MSG_MON_COMMAND: try { return preprocess_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); return true; } default: mon.no_reply(op); derr << "Unhandled message type " << m->get_type() << dendl; return true; } } bool MgrMonitor::prepare_update(MonOpRequestRef op) { auto m = op->get_req<PaxosServiceMessage>(); switch (m->get_type()) { case MSG_MGR_BEACON: return prepare_beacon(op); case MSG_MON_COMMAND: try { return prepare_command(op); } catch (const bad_cmd_get& e) { bufferlist bl; mon.reply_command(op, -EINVAL, e.what(), bl, get_last_committed()); return false; /* nothing to propose! */ } default: mon.no_reply(op); derr << "Unhandled message type " << m->get_type() << dendl; return false; /* nothing to propose! */ } } class C_Updated : public Context { MgrMonitor *mm; MonOpRequestRef op; public: C_Updated(MgrMonitor *a, MonOpRequestRef c) : mm(a), op(c) {} void finish(int r) override { if (r >= 0) { // Success } else if (r == -ECANCELED) { mm->mon.no_reply(op); } else { mm->dispatch(op); // try again } } }; bool MgrMonitor::preprocess_beacon(MonOpRequestRef op) { auto m = op->get_req<MMgrBeacon>(); mon.no_reply(op); // we never reply to beacons dout(4) << "beacon from " << m->get_gid() << dendl; if (!check_caps(op, m->get_fsid())) { // drop it on the floor return true; } // always send this to the leader's prepare_beacon() return false; } bool MgrMonitor::prepare_beacon(MonOpRequestRef op) { auto m = op->get_req<MMgrBeacon>(); dout(4) << "beacon from " << m->get_gid() << dendl; // Track whether we modified pending_map bool updated = false; bool plugged = false; // See if we are seeing same name, new GID for the active daemon if (m->get_name() == pending_map.active_name && m->get_gid() != pending_map.active_gid) { dout(4) << "Active daemon restart (mgr." << m->get_name() << ")" << dendl; mon.clog->info() << "Active manager daemon " << m->get_name() << " restarted"; if (!mon.osdmon()->is_writeable()) { dout(1) << __func__ << ": waiting for osdmon writeable to" " blocklist old instance." << dendl; mon.osdmon()->wait_for_writeable(op, new C_RetryMessage(this, op)); return false; } plugged |= drop_active(); updated = true; } // See if we are seeing same name, new GID for any standbys for (const auto &i : pending_map.standbys) { const MgrMap::StandbyInfo &s = i.second; if (s.name == m->get_name() && s.gid != m->get_gid()) { dout(4) << "Standby daemon restart (mgr." << m->get_name() << ")" << dendl; mon.clog->debug() << "Standby manager daemon " << m->get_name() << " restarted"; drop_standby(i.first); updated = true; break; } } last_beacon[m->get_gid()] = ceph::coarse_mono_clock::now(); if (pending_map.active_gid == m->get_gid()) { if (pending_map.services != m->get_services()) { dout(4) << "updated services from mgr." << m->get_name() << ": " << m->get_services() << dendl; pending_map.services = m->get_services(); updated = true; } // A beacon from the currently active daemon if (pending_map.active_addrs != m->get_server_addrs()) { dout(4) << "learned address " << m->get_server_addrs() << " (was " << pending_map.active_addrs << ")" << dendl; pending_map.active_addrs = m->get_server_addrs(); updated = true; } if (pending_map.get_available() != m->get_available()) { dout(4) << "available " << m->get_gid() << dendl; mon.clog->info() << "Manager daemon " << pending_map.active_name << " is now available"; // This beacon should include command descriptions pending_command_descs = m->get_command_descs(); if (pending_command_descs.empty()) { // This should not happen, but it also isn't fatal: we just // won't successfully update our list of commands. dout(4) << "First available beacon from " << pending_map.active_name << "(" << m->get_gid() << ") does not include command descs" << dendl; } else { dout(4) << "First available beacon from " << pending_map.active_name << "(" << m->get_gid() << ") includes " << pending_command_descs.size() << " command descs" << dendl; } pending_map.available = m->get_available(); updated = true; } if (pending_map.available_modules != m->get_available_modules()) { dout(4) << "available_modules " << m->get_available_modules() << " (was " << pending_map.available_modules << ")" << dendl; pending_map.available_modules = m->get_available_modules(); updated = true; } const auto& clients = m->get_clients(); if (pending_map.clients != clients) { dout(4) << "active's RADOS clients " << clients << " (was " << pending_map.clients << ")" << dendl; pending_map.clients = clients; updated = true; } } else if (m->get_available()) { dout(4) << "mgr thinks it is active but it is not, dropping!" << dendl; auto m = make_message<MMgrMap>(MgrMap::create_null_mgrmap()); mon.send_reply(op, m.detach()); goto out; } else if (pending_map.active_gid == 0) { // There is no currently active daemon, select this one. if (pending_map.standbys.count(m->get_gid())) { drop_standby(m->get_gid(), false); } dout(4) << "selecting new active " << m->get_gid() << " " << m->get_name() << " (was " << pending_map.active_gid << " " << pending_map.active_name << ")" << dendl; pending_map.active_gid = m->get_gid(); pending_map.active_name = m->get_name(); pending_map.active_change = ceph_clock_now(); pending_map.active_mgr_features = m->get_mgr_features(); pending_map.available_modules = m->get_available_modules(); encode(m->get_metadata(), pending_metadata[m->get_name()]); pending_metadata_rm.erase(m->get_name()); mon.clog->info() << "Activating manager daemon " << pending_map.active_name; updated = true; } else { if (pending_map.standbys.count(m->get_gid()) > 0) { dout(10) << "from existing standby " << m->get_gid() << dendl; if (pending_map.standbys[m->get_gid()].available_modules != m->get_available_modules()) { dout(10) << "existing standby " << m->get_gid() << " available_modules " << m->get_available_modules() << " (was " << pending_map.standbys[m->get_gid()].available_modules << ")" << dendl; pending_map.standbys[m->get_gid()].available_modules = m->get_available_modules(); updated = true; } } else { dout(10) << "new standby " << m->get_gid() << dendl; mon.clog->debug() << "Standby manager daemon " << m->get_name() << " started"; pending_map.standbys[m->get_gid()] = {m->get_gid(), m->get_name(), m->get_available_modules(), m->get_mgr_features()}; encode(m->get_metadata(), pending_metadata[m->get_name()]); pending_metadata_rm.erase(m->get_name()); updated = true; } } if (updated) { dout(4) << "updating map" << dendl; wait_for_finished_proposal(op, new C_Updated(this, op)); } else { dout(10) << "no change" << dendl; } out: if (plugged) { paxos.unplug(); } return updated; } void MgrMonitor::check_subs() { const std::string type = "mgrmap"; if (mon.session_map.subs.count(type) == 0) return; for (auto sub : *(mon.session_map.subs[type])) { check_sub(sub); } } void MgrMonitor::check_sub(Subscription *sub) { if (sub->type == "mgrmap") { if (sub->next <= map.get_epoch()) { dout(20) << "Sending map to subscriber " << sub->session->con << " " << sub->session->con->get_peer_addr() << dendl; sub->session->con->send_message2(make_message<MMgrMap>(map)); if (sub->onetime) { mon.session_map.remove_sub(sub); } else { sub->next = map.get_epoch() + 1; } } } else { ceph_assert(sub->type == "mgrdigest"); if (sub->next == 0) { // new registration; cancel previous timer cancel_timer(); } if (digest_event == nullptr) { send_digests(); } } } /** * Handle digest subscriptions separately (outside of check_sub) because * they are going to be periodic rather than version-driven. */ void MgrMonitor::send_digests() { cancel_timer(); const std::string type = "mgrdigest"; if (mon.session_map.subs.count(type) == 0) { prev_health_checks.clear(); return; } if (!is_active()) { // if paxos is currently not active, don't send a digest but reenable timer goto timer; } dout(10) << __func__ << dendl; for (auto sub : *(mon.session_map.subs[type])) { dout(10) << __func__ << " sending digest to subscriber " << sub->session->con << " " << sub->session->con->get_peer_addr() << dendl; auto mdigest = make_message<MMgrDigest>(); JSONFormatter f; mon.healthmon()->get_health_status(true, &f, nullptr, nullptr, nullptr); f.flush(mdigest->health_json); f.reset(); mon.get_mon_status(&f); f.flush(mdigest->mon_status_json); f.reset(); sub->session->con->send_message2(mdigest); } timer: digest_event = mon.timer.add_event_after( g_conf().get_val<int64_t>("mon_mgr_digest_period"), new C_MonContext{&mon, [this](int) { send_digests(); }}); } void MgrMonitor::cancel_timer() { if (digest_event) { mon.timer.cancel_event(digest_event); digest_event = nullptr; } } void MgrMonitor::on_active() { if (!mon.is_leader()) { return; } mon.clog->debug() << "mgrmap e" << map.epoch << ": " << map; assert(HAVE_FEATURE(mon.get_quorum_con_features(), SERVER_NAUTILUS)); if (pending_map.always_on_modules == always_on_modules) { return; } dout(4) << "always on modules changed, pending " << pending_map.always_on_modules << " != wanted " << always_on_modules << dendl; pending_map.always_on_modules = always_on_modules; propose_pending(); } void MgrMonitor::tick() { if (!is_active() || !mon.is_leader()) return; const auto now = ceph::coarse_mono_clock::now(); const auto mgr_beacon_grace = g_conf().get_val<std::chrono::seconds>("mon_mgr_beacon_grace"); // Note that this is the mgr daemon's tick period, not ours (the // beacon is sent with this period). const auto mgr_tick_period = g_conf().get_val<std::chrono::seconds>("mgr_tick_period"); if (last_tick != ceph::coarse_mono_clock::time_point::min() && (now - last_tick > (mgr_beacon_grace - mgr_tick_period))) { // This case handles either local slowness (calls being delayed // for whatever reason) or cluster election slowness (a long gap // between calls while an election happened) dout(4) << __func__ << ": resetting beacon timeouts due to mon delay " "(slow election?) of " << now - last_tick << " seconds" << dendl; for (auto &i : last_beacon) { i.second = now; } } last_tick = now; // Populate any missing beacons (i.e. no beacon since MgrMonitor // instantiation) with the current time, so that they will // eventually look laggy if they fail to give us a beacon. if (pending_map.active_gid != 0 && last_beacon.count(pending_map.active_gid) == 0) { last_beacon[pending_map.active_gid] = now; } for (auto s : pending_map.standbys) { if (last_beacon.count(s.first) == 0) { last_beacon[s.first] = now; } } // Cull standbys first so that any remaining standbys // will be eligible to take over from the active if we cull him. std::list<uint64_t> dead_standbys; const auto cutoff = now - mgr_beacon_grace; for (const auto &i : pending_map.standbys) { auto last_beacon_time = last_beacon.at(i.first); if (last_beacon_time < cutoff) { dead_standbys.push_back(i.first); } } bool propose = false; bool plugged = false; for (auto i : dead_standbys) { dout(4) << "Dropping laggy standby " << i << dendl; drop_standby(i); propose = true; } if (pending_map.active_gid != 0 && last_beacon.at(pending_map.active_gid) < cutoff && mon.osdmon()->is_writeable()) { const std::string old_active_name = pending_map.active_name; plugged |= drop_active(); propose = true; dout(4) << "Dropping active" << pending_map.active_gid << dendl; if (promote_standby()) { dout(4) << "Promoted standby " << pending_map.active_gid << dendl; mon.clog->info() << "Manager daemon " << old_active_name << " is unresponsive, replacing it with standby" << " daemon " << pending_map.active_name; } else { dout(4) << "Active is laggy but have no standbys to replace it" << dendl; mon.clog->info() << "Manager daemon " << old_active_name << " is unresponsive. No standby daemons available."; } } else if (pending_map.active_gid == 0) { if (promote_standby()) { dout(4) << "Promoted standby " << pending_map.active_gid << dendl; mon.clog->info() << "Activating manager daemon " << pending_map.active_name; propose = true; } } if (!pending_map.available && !ever_had_active_mgr && should_warn_about_mgr_down() != HEALTH_OK) { dout(10) << " exceeded mon_mgr_mkfs_grace " << g_conf().get_val<int64_t>("mon_mgr_mkfs_grace") << " seconds" << dendl; propose = true; } // obsolete modules? if (mon.monmap->min_mon_release >= ceph_release_t::octopus && pending_map.module_enabled("orchestrator_cli")) { dout(10) << " disabling obsolete/renamed 'orchestrator_cli'" << dendl; // we don't need to enable 'orchestrator' because it's now always-on pending_map.modules.erase("orchestrator_cli"); propose = true; } if (propose) { propose_pending(); } if (plugged) { paxos.unplug(); ceph_assert(propose); paxos.trigger_propose(); } } void MgrMonitor::on_restart() { // Clear out the leader-specific state. last_beacon.clear(); last_tick = ceph::coarse_mono_clock::now(); } bool MgrMonitor::promote_standby() { ceph_assert(pending_map.active_gid == 0); if (pending_map.standbys.size()) { // Promote a replacement (arbitrary choice of standby) auto replacement_gid = pending_map.standbys.begin()->first; pending_map.active_gid = replacement_gid; pending_map.active_name = pending_map.standbys.at(replacement_gid).name; pending_map.available_modules = pending_map.standbys.at(replacement_gid).available_modules; pending_map.active_mgr_features = pending_map.standbys.at(replacement_gid).mgr_features; pending_map.available = false; pending_map.active_addrs = entity_addrvec_t(); pending_map.active_change = ceph_clock_now(); drop_standby(replacement_gid, false); return true; } else { return false; } } bool MgrMonitor::drop_active() { ceph_assert(mon.osdmon()->is_writeable()); bool plugged = false; if (!paxos.is_plugged()) { paxos.plug(); plugged = true; } if (last_beacon.count(pending_map.active_gid) > 0) { last_beacon.erase(pending_map.active_gid); } ceph_assert(pending_map.active_gid > 0); auto until = ceph_clock_now(); until += g_conf().get_val<double>("mon_mgr_blocklist_interval"); dout(5) << "blocklisting previous mgr." << pending_map.active_name << "." << pending_map.active_gid << " (" << pending_map.active_addrs << ")" << dendl; auto blocklist_epoch = mon.osdmon()->blocklist(pending_map.active_addrs, until); /* blocklist RADOS clients in use by the mgr */ for (const auto& a : pending_map.clients) { mon.osdmon()->blocklist(a.second, until); } request_proposal(mon.osdmon()); pending_metadata_rm.insert(pending_map.active_name); pending_metadata.erase(pending_map.active_name); pending_map.active_name = ""; pending_map.active_gid = 0; pending_map.active_change = ceph_clock_now(); pending_map.active_mgr_features = 0; pending_map.available = false; pending_map.active_addrs = entity_addrvec_t(); pending_map.services.clear(); pending_map.clients.clear(); pending_map.last_failure_osd_epoch = blocklist_epoch; /* If we are dropping the active, we need to notify clients immediately. * Additionally, avoid logical races with ::prepare_beacon which cannot * accurately determine if a mgr is a standby or an old active. */ force_immediate_propose(); // So that when new active mgr subscribes to mgrdigest, it will // get an immediate response instead of waiting for next timer cancel_timer(); return plugged; } void MgrMonitor::drop_standby(uint64_t gid, bool drop_meta) { if (drop_meta) { pending_metadata_rm.insert(pending_map.standbys[gid].name); pending_metadata.erase(pending_map.standbys[gid].name); } pending_map.standbys.erase(gid); if (last_beacon.count(gid) > 0) { last_beacon.erase(gid); } } bool MgrMonitor::preprocess_command(MonOpRequestRef op) { auto m = op->get_req<MMonCommand>(); std::stringstream ss; bufferlist rdata; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, rdata, get_last_committed()); return true; } MonSession *session = op->get_session(); if (!session) { mon.reply_command(op, -EACCES, "access denied", rdata, get_last_committed()); return true; } string format = cmd_getval_or<string>(cmdmap, "format", "plain"); boost::scoped_ptr<Formatter> f(Formatter::create(format)); string prefix; cmd_getval(cmdmap, "prefix", prefix); int r = 0; if (prefix == "mgr stat") { if (!f) { f.reset(Formatter::create(format, "json-pretty", "json-pretty")); } f->open_object_section("stat"); f->dump_unsigned("epoch", map.get_epoch()); f->dump_bool("available", map.get_available()); f->dump_string("active_name", map.get_active_name()); f->dump_unsigned("num_standby", map.get_num_standby()); f->close_section(); f->flush(rdata); } else if (prefix == "mgr dump") { if (!f) { f.reset(Formatter::create(format, "json-pretty", "json-pretty")); } int64_t epoch = cmd_getval_or<int64_t>(cmdmap, "epoch", map.get_epoch()); if (epoch == (int64_t)map.get_epoch()) { f->dump_object("mgrmap", map); } else { bufferlist bl; int err = get_version(epoch, bl); if (err == -ENOENT) { r = -ENOENT; ss << "there is no map for epoch " << epoch; goto reply; } MgrMap m; auto p = bl.cbegin(); m.decode(p); f->dump_object("mgrmap", m); } f->flush(rdata); } else if (prefix == "mgr module ls") { if (f) { f->open_object_section("modules"); { f->open_array_section("always_on_modules"); for (auto& p : map.get_always_on_modules()) { f->dump_string("module", p); } f->close_section(); f->open_array_section("enabled_modules"); for (auto& p : map.modules) { if (map.get_always_on_modules().count(p) > 0) continue; // We only show the name for enabled modules. The any errors // etc will show up as a health checks. f->dump_string("module", p); } f->close_section(); f->open_array_section("disabled_modules"); for (auto& p : map.available_modules) { if (map.modules.count(p.name) == 0 && map.get_always_on_modules().count(p.name) == 0) { // For disabled modules, we show the full info if the detail // parameter is enabled, to give a hint about whether enabling it will work p.dump(f.get()); } } f->close_section(); } f->close_section(); f->flush(rdata); } else { TextTable tbl; tbl.define_column("MODULE", TextTable::LEFT, TextTable::LEFT); tbl.define_column(" ", TextTable::LEFT, TextTable::LEFT); for (auto& p : map.get_always_on_modules()) { tbl << p; tbl << "on (always on)"; tbl << TextTable::endrow; } for (auto& p : map.modules) { if (map.get_always_on_modules().count(p) > 0) continue; tbl << p; tbl << "on"; tbl << TextTable::endrow; } for (auto& p : map.available_modules) { if (map.modules.count(p.name) == 0 && map.get_always_on_modules().count(p.name) == 0) { tbl << p.name; tbl << "-"; tbl << TextTable::endrow; } } rdata.append(stringify(tbl)); } } else if (prefix == "mgr services") { if (!f) { f.reset(Formatter::create(format, "json-pretty", "json-pretty")); } f->open_object_section("services"); for (const auto &i : map.services) { f->dump_string(i.first.c_str(), i.second); } f->close_section(); f->flush(rdata); } else if (prefix == "mgr metadata") { if (!f) { f.reset(Formatter::create(format, "json-pretty", "json-pretty")); } string name; cmd_getval(cmdmap, "who", name); if (name.size() > 0 && !map.have_name(name)) { ss << "mgr." << name << " does not exist"; r = -ENOENT; goto reply; } if (name.size()) { f->open_object_section("mgr_metadata"); f->dump_string("name", name); r = dump_metadata(name, f.get(), &ss); if (r < 0) goto reply; f->close_section(); } else { r = 0; f->open_array_section("mgr_metadata"); for (auto& i : map.get_all_names()) { f->open_object_section("mgr"); f->dump_string("name", i); r = dump_metadata(i, f.get(), NULL); if (r == -EINVAL || r == -ENOENT) { // Drop error, continue to get other daemons' metadata dout(4) << "No metadata for mgr." << i << dendl; r = 0; } else if (r < 0) { // Unexpected error goto reply; } f->close_section(); } f->close_section(); } f->flush(rdata); } else if (prefix == "mgr versions") { if (!f) { f.reset(Formatter::create(format, "json-pretty", "json-pretty")); } count_metadata("ceph_version", f.get()); f->flush(rdata); r = 0; } else if (prefix == "mgr count-metadata") { if (!f) { f.reset(Formatter::create(format, "json-pretty", "json-pretty")); } string field; cmd_getval(cmdmap, "property", field); count_metadata(field, f.get()); f->flush(rdata); r = 0; } else { return false; } reply: string rs; getline(ss, rs); mon.reply_command(op, r, rs, rdata, get_last_committed()); return true; } bool MgrMonitor::prepare_command(MonOpRequestRef op) { auto m = op->get_req<MMonCommand>(); std::stringstream ss; bufferlist rdata; cmdmap_t cmdmap; if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) { string rs = ss.str(); mon.reply_command(op, -EINVAL, rs, rdata, get_last_committed()); return true; } MonSession *session = op->get_session(); if (!session) { mon.reply_command(op, -EACCES, "access denied", rdata, get_last_committed()); return true; } string format = cmd_getval_or<string>(cmdmap, "format", "plain"); boost::scoped_ptr<Formatter> f(Formatter::create(format)); const auto prefix = cmd_getval_or<string>(cmdmap, "prefix", string{}); int r = 0; bool plugged = false; if (prefix == "mgr fail") { string who; if (!cmd_getval(cmdmap, "who", who)) { if (!map.active_gid) { ss << "Currently no active mgr"; goto out; } who = map.active_name; } std::string err; uint64_t gid = strict_strtol(who.c_str(), 10, &err); bool changed = false; if (!err.empty()) { // Does not parse as a gid, treat it as a name if (pending_map.active_name == who) { if (!mon.osdmon()->is_writeable()) { mon.osdmon()->wait_for_writeable(op, new C_RetryMessage(this, op)); return false; } plugged |= drop_active(); changed = true; } else { gid = 0; for (const auto &i : pending_map.standbys) { if (i.second.name == who) { gid = i.first; break; } } if (gid != 0) { drop_standby(gid); changed = true; } else { ss << "Daemon not found '" << who << "', already failed?"; } } } else { if (pending_map.active_gid == gid) { if (!mon.osdmon()->is_writeable()) { mon.osdmon()->wait_for_writeable(op, new C_RetryMessage(this, op)); return false; } plugged |= drop_active(); changed = true; } else if (pending_map.standbys.count(gid) > 0) { drop_standby(gid); changed = true; } else { ss << "Daemon not found '" << gid << "', already failed?"; } } if (changed && pending_map.active_gid == 0) { promote_standby(); } } else if (prefix == "mgr module enable") { string module; cmd_getval(cmdmap, "module", module); if (module.empty()) { r = -EINVAL; goto out; } if (pending_map.get_always_on_modules().count(module) > 0) { ss << "module '" << module << "' is already enabled (always-on)"; goto out; } bool force = false; cmd_getval_compat_cephbool(cmdmap, "force", force); if (!pending_map.all_support_module(module) && !force) { ss << "all mgr daemons do not support module '" << module << "', pass " << "--force to force enablement"; r = -ENOENT; goto out; } std::string can_run_error; if (!force && !pending_map.can_run_module(module, &can_run_error)) { ss << "module '" << module << "' reports that it cannot run on the active " "manager daemon: " << can_run_error << " (pass --force to force " "enablement)"; r = -ENOENT; goto out; } if (pending_map.module_enabled(module)) { ss << "module '" << module << "' is already enabled"; r = 0; goto out; } pending_map.modules.insert(module); } else if (prefix == "mgr module disable") { string module; cmd_getval(cmdmap, "module", module); if (module.empty()) { r = -EINVAL; goto out; } if (pending_map.get_always_on_modules().count(module) > 0) { ss << "module '" << module << "' cannot be disabled (always-on)"; r = -EINVAL; goto out; } if (!pending_map.module_enabled(module)) { ss << "module '" << module << "' is already disabled"; r = 0; goto out; } if (!pending_map.modules.count(module)) { ss << "module '" << module << "' is not enabled"; } pending_map.modules.erase(module); } else { ss << "Command '" << prefix << "' not implemented!"; r = -ENOSYS; } out: dout(4) << __func__ << " done, r=" << r << dendl; /* Compose response */ string rs; getline(ss, rs); if (r >= 0) { // success.. delay reply wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, r, rs, get_last_committed() + 1)); } else { // reply immediately mon.reply_command(op, r, rs, rdata, get_last_committed()); } if (plugged) { paxos.unplug(); } return r >= 0; } void MgrMonitor::init() { if (digest_event == nullptr) { send_digests(); // To get it to schedule its own event } } void MgrMonitor::on_shutdown() { cancel_timer(); } int MgrMonitor::load_metadata(const string& name, std::map<string, string>& m, ostream *err) const { bufferlist bl; int r = mon.store->get(MGR_METADATA_PREFIX, name, bl); if (r < 0) return r; try { auto p = bl.cbegin(); decode(m, p); } catch (ceph::buffer::error& e) { if (err) *err << "mgr." << name << " metadata is corrupt"; return -EIO; } return 0; } void MgrMonitor::count_metadata(const string& field, std::map<string,int> *out) { std::set<string> ls = map.get_all_names(); for (auto& name : ls) { std::map<string,string> meta; load_metadata(name, meta, nullptr); auto p = meta.find(field); if (p == meta.end()) { (*out)["unknown"]++; } else { (*out)[p->second]++; } } } void MgrMonitor::count_metadata(const string& field, Formatter *f) { std::map<string,int> by_val; count_metadata(field, &by_val); f->open_object_section(field.c_str()); for (auto& p : by_val) { f->dump_int(p.first.c_str(), p.second); } f->close_section(); } void MgrMonitor::get_versions(std::map<string, list<string> > &versions) { std::set<string> ls = map.get_all_names(); for (auto& name : ls) { std::map<string,string> meta; load_metadata(name, meta, nullptr); auto p = meta.find("ceph_version_short"); if (p == meta.end()) continue; versions[p->second].push_back(string("mgr.") + name); } } int MgrMonitor::dump_metadata(const string& name, Formatter *f, ostream *err) { std::map<string,string> m; if (int r = load_metadata(name, m, err)) return r; for (auto& p : m) { f->dump_string(p.first.c_str(), p.second); } return 0; } void MgrMonitor::print_nodes(Formatter *f) const { ceph_assert(f); std::map<string, list<string> > mgrs; // hostname => mgr auto ls = map.get_all_names(); for (auto& name : ls) { std::map<string,string> meta; if (load_metadata(name, meta, nullptr)) { continue; } auto hostname = meta.find("hostname"); if (hostname == meta.end()) { // not likely though continue; } mgrs[hostname->second].push_back(name); } dump_services(f, mgrs, "mgr"); } const std::vector<MonCommand> &MgrMonitor::get_command_descs() const { if (command_descs.empty()) { // must have just upgraded; fallback to static commands return mgr_commands; } else { return command_descs; } }
42,009
27.992409
87
cc
null
ceph-main/src/mon/MgrMonitor.h
// -*- 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 John Spray <[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. */ #ifndef CEPH_MGRMONITOR_H #define CEPH_MGRMONITOR_H #include <map> #include <set> #include "include/Context.h" #include "MgrMap.h" #include "PaxosService.h" #include "MonCommand.h" class MgrMonitor: public PaxosService { MgrMap map; MgrMap pending_map; bool ever_had_active_mgr = false; std::map<std::string, ceph::buffer::list> pending_metadata; std::set<std::string> pending_metadata_rm; std::map<std::string,Option> mgr_module_options; std::list<std::string> misc_option_strings; utime_t first_seen_inactive; std::map<uint64_t, ceph::coarse_mono_clock::time_point> last_beacon; /** * If a standby is available, make it active, given that * there is currently no active daemon. * * @return true if a standby was promoted */ bool promote_standby(); /** * Drop the active daemon from the MgrMap. No promotion is performed. * * @return whether PAXOS was plugged by this method */ bool drop_active(); /** * Remove this gid from the list of standbys. By default, * also remove metadata (i.e. forget the daemon entirely). * * Set `drop_meta` to false if you would like to keep * the daemon's metadata, for example if you're dropping * it as a standby before reinstating it as the active daemon. */ void drop_standby(uint64_t gid, bool drop_meta=true); Context *digest_event = nullptr; void cancel_timer(); std::vector<health_check_map_t> prev_health_checks; bool check_caps(MonOpRequestRef op, const uuid_d& fsid); health_status_t should_warn_about_mgr_down(); // Command descriptions we've learned from the active mgr std::vector<MonCommand> command_descs; std::vector<MonCommand> pending_command_descs; public: MgrMonitor(Monitor &mn, Paxos &p, const std::string& service_name) : PaxosService(mn, p, service_name) {} ~MgrMonitor() override {} void init() override; void on_shutdown() override; const MgrMap &get_map() const { return map; } const std::map<std::string,Option>& get_mgr_module_options() { return mgr_module_options; } const Option *find_module_option(const std::string& name); bool in_use() const { return map.epoch > 0; } version_t get_trim_to() const override; void prime_mgr_client(); void create_initial() override; void get_store_prefixes(std::set<std::string>& s) const override; void update_from_paxos(bool *need_bootstrap) override; void post_paxos_update() override; void create_pending() override; void encode_pending(MonitorDBStore::TransactionRef t) override; bool preprocess_query(MonOpRequestRef op) override; bool prepare_update(MonOpRequestRef op) override; bool preprocess_command(MonOpRequestRef op); bool prepare_command(MonOpRequestRef op); void encode_full(MonitorDBStore::TransactionRef t) override { } bool preprocess_beacon(MonOpRequestRef op); bool prepare_beacon(MonOpRequestRef op); void check_sub(Subscription *sub); void check_subs(); void send_digests(); void on_active() override; void on_restart() override; void tick() override; void print_summary(ceph::Formatter *f, std::ostream *ss) const; const std::vector<MonCommand> &get_command_descs() const; int load_metadata(const std::string& name, std::map<std::string, std::string>& m, std::ostream *err) const; int dump_metadata(const std::string& name, ceph::Formatter *f, std::ostream *err); void print_nodes(ceph::Formatter *f) const; void count_metadata(const std::string& field, ceph::Formatter *f); void count_metadata(const std::string& field, std::map<std::string,int> *out); void get_versions(std::map<std::string, std::list<std::string>> &versions); // When did the mon last call into our tick() method? Used for detecting // when the mon was not updating us for some period (e.g. during slow // election) to reset last_beacon timeouts ceph::coarse_mono_clock::time_point last_tick; }; #endif
4,350
28.598639
84
h
null
ceph-main/src/mon/MgrStatMonitor.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "MgrStatMonitor.h" #include "mon/OSDMonitor.h" #include "mon/MgrMonitor.h" #include "mon/PGMap.h" #include "messages/MGetPoolStats.h" #include "messages/MGetPoolStatsReply.h" #include "messages/MMonMgrReport.h" #include "messages/MStatfs.h" #include "messages/MStatfsReply.h" #include "messages/MServiceMap.h" #include "include/ceph_assert.h" // re-clobber assert #define dout_subsys ceph_subsys_mon #undef dout_prefix #define dout_prefix _prefix(_dout, mon) using std::dec; using std::hex; using std::list; using std::map; using std::make_pair; using std::ostream; using std::ostringstream; using std::pair; using std::set; using std::string; using std::stringstream; using std::to_string; using std::vector; using ceph::bufferlist; using ceph::decode; using ceph::encode; using ceph::ErasureCodeInterfaceRef; using ceph::ErasureCodeProfile; using ceph::Formatter; using ceph::JSONFormatter; using ceph::make_message; using ceph::mono_clock; using ceph::mono_time; static ostream& _prefix(std::ostream *_dout, Monitor &mon) { return *_dout << "mon." << mon.name << "@" << mon.rank << "(" << mon.get_state_name() << ").mgrstat "; } MgrStatMonitor::MgrStatMonitor(Monitor &mn, Paxos &p, const string& service_name) : PaxosService(mn, p, service_name) { } MgrStatMonitor::~MgrStatMonitor() = default; void MgrStatMonitor::create_initial() { dout(10) << __func__ << dendl; version = 0; service_map.epoch = 1; service_map.modified = ceph_clock_now(); pending_service_map_bl.clear(); encode(service_map, pending_service_map_bl, CEPH_FEATURES_ALL); } void MgrStatMonitor::update_from_paxos(bool *need_bootstrap) { version = get_last_committed(); dout(10) << " " << version << dendl; load_health(); bufferlist bl; get_version(version, bl); if (version) { ceph_assert(bl.length()); try { auto p = bl.cbegin(); decode(digest, p); decode(service_map, p); if (!p.end()) { decode(progress_events, p); } dout(10) << __func__ << " v" << version << " service_map e" << service_map.epoch << " " << progress_events.size() << " progress events" << dendl; } catch (ceph::buffer::error& e) { derr << "failed to decode mgrstat state; luminous dev version? " << e.what() << dendl; } } check_subs(); update_logger(); mon.osdmon()->notify_new_pg_digest(); } void MgrStatMonitor::update_logger() { dout(20) << __func__ << dendl; mon.cluster_logger->set(l_cluster_osd_bytes, digest.osd_sum.statfs.total); mon.cluster_logger->set(l_cluster_osd_bytes_used, digest.osd_sum.statfs.get_used_raw()); mon.cluster_logger->set(l_cluster_osd_bytes_avail, digest.osd_sum.statfs.available); mon.cluster_logger->set(l_cluster_num_pool, digest.pg_pool_sum.size()); uint64_t num_pg = 0; for (auto i : digest.num_pg_by_pool) { num_pg += i.second; } mon.cluster_logger->set(l_cluster_num_pg, num_pg); unsigned active = 0, active_clean = 0, peering = 0; for (auto p = digest.num_pg_by_state.begin(); p != digest.num_pg_by_state.end(); ++p) { if (p->first & PG_STATE_ACTIVE) { active += p->second; if (p->first & PG_STATE_CLEAN) active_clean += p->second; } if (p->first & PG_STATE_PEERING) peering += p->second; } mon.cluster_logger->set(l_cluster_num_pg_active_clean, active_clean); mon.cluster_logger->set(l_cluster_num_pg_active, active); mon.cluster_logger->set(l_cluster_num_pg_peering, peering); mon.cluster_logger->set(l_cluster_num_object, digest.pg_sum.stats.sum.num_objects); mon.cluster_logger->set(l_cluster_num_object_degraded, digest.pg_sum.stats.sum.num_objects_degraded); mon.cluster_logger->set(l_cluster_num_object_misplaced, digest.pg_sum.stats.sum.num_objects_misplaced); mon.cluster_logger->set(l_cluster_num_object_unfound, digest.pg_sum.stats.sum.num_objects_unfound); mon.cluster_logger->set(l_cluster_num_bytes, digest.pg_sum.stats.sum.num_bytes); } void MgrStatMonitor::create_pending() { dout(10) << " " << version << dendl; pending_digest = digest; pending_health_checks = get_health_checks(); pending_service_map_bl.clear(); encode(service_map, pending_service_map_bl, mon.get_quorum_con_features()); } void MgrStatMonitor::encode_pending(MonitorDBStore::TransactionRef t) { ++version; dout(10) << " " << version << dendl; bufferlist bl; encode(pending_digest, bl, mon.get_quorum_con_features()); ceph_assert(pending_service_map_bl.length()); bl.append(pending_service_map_bl); encode(pending_progress_events, bl); put_version(t, version, bl); put_last_committed(t, version); encode_health(pending_health_checks, t); } version_t MgrStatMonitor::get_trim_to() const { // we don't actually need *any* old states, but keep a few. if (version > 5) { return version - 5; } return 0; } void MgrStatMonitor::on_active() { update_logger(); } void MgrStatMonitor::tick() { } bool MgrStatMonitor::preprocess_query(MonOpRequestRef op) { auto m = op->get_req<PaxosServiceMessage>(); switch (m->get_type()) { case CEPH_MSG_STATFS: return preprocess_statfs(op); case MSG_MON_MGR_REPORT: return preprocess_report(op); case MSG_GETPOOLSTATS: return preprocess_getpoolstats(op); default: mon.no_reply(op); derr << "Unhandled message type " << m->get_type() << dendl; return true; } } bool MgrStatMonitor::prepare_update(MonOpRequestRef op) { auto m = op->get_req<PaxosServiceMessage>(); switch (m->get_type()) { case MSG_MON_MGR_REPORT: return prepare_report(op); default: mon.no_reply(op); derr << "Unhandled message type " << m->get_type() << dendl; return true; } } bool MgrStatMonitor::preprocess_report(MonOpRequestRef op) { auto m = op->get_req<MMonMgrReport>(); mon.no_reply(op); if (m->gid && m->gid != mon.mgrmon()->get_map().get_active_gid()) { dout(10) << "ignoring report from non-active mgr " << m->gid << dendl; return true; } return false; } bool MgrStatMonitor::prepare_report(MonOpRequestRef op) { auto m = op->get_req<MMonMgrReport>(); bufferlist bl = m->get_data(); auto p = bl.cbegin(); decode(pending_digest, p); pending_health_checks.swap(m->health_checks); if (m->service_map_bl.length()) { pending_service_map_bl.swap(m->service_map_bl); } pending_progress_events.swap(m->progress_events); dout(10) << __func__ << " " << pending_digest << ", " << pending_health_checks.checks.size() << " health checks, " << progress_events.size() << " progress events" << dendl; dout(20) << "pending_digest:\n"; JSONFormatter jf(true); jf.open_object_section("pending_digest"); pending_digest.dump(&jf); jf.close_section(); jf.flush(*_dout); *_dout << dendl; dout(20) << "health checks:\n"; JSONFormatter jf(true); jf.open_object_section("health_checks"); pending_health_checks.dump(&jf); jf.close_section(); jf.flush(*_dout); *_dout << dendl; dout(20) << "progress events:\n"; JSONFormatter jf(true); jf.open_object_section("progress_events"); for (auto& i : pending_progress_events) { jf.dump_object(i.first.c_str(), i.second); } jf.close_section(); jf.flush(*_dout); *_dout << dendl; return true; } bool MgrStatMonitor::preprocess_getpoolstats(MonOpRequestRef op) { op->mark_pgmon_event(__func__); auto m = op->get_req<MGetPoolStats>(); auto session = op->get_session(); if (!session) return true; if (!session->is_capable("pg", MON_CAP_R)) { dout(0) << "MGetPoolStats received from entity with insufficient caps " << session->caps << dendl; return true; } if (m->fsid != mon.monmap->fsid) { dout(0) << __func__ << " on fsid " << m->fsid << " != " << mon.monmap->fsid << dendl; return true; } epoch_t ver = get_last_committed(); auto reply = new MGetPoolStatsReply(m->fsid, m->get_tid(), ver); reply->per_pool = digest.use_per_pool_stats(); for (const auto& pool_name : m->pools) { const auto pool_id = mon.osdmon()->osdmap.lookup_pg_pool_name(pool_name); if (pool_id == -ENOENT) continue; auto pool_stat = get_pool_stat(pool_id); if (!pool_stat) continue; reply->pool_stats[pool_name] = *pool_stat; } mon.send_reply(op, reply); return true; } bool MgrStatMonitor::preprocess_statfs(MonOpRequestRef op) { op->mark_pgmon_event(__func__); auto statfs = op->get_req<MStatfs>(); auto session = op->get_session(); if (!session) return true; if (!session->is_capable("pg", MON_CAP_R)) { dout(0) << "MStatfs received from entity with insufficient privileges " << session->caps << dendl; return true; } if (statfs->fsid != mon.monmap->fsid) { dout(0) << __func__ << " on fsid " << statfs->fsid << " != " << mon.monmap->fsid << dendl; return true; } const auto& pool = statfs->data_pool; if (pool && !mon.osdmon()->osdmap.have_pg_pool(*pool)) { // There's no error field for MStatfsReply so just ignore the request. // This is known to happen when a client is still accessing a removed fs. dout(1) << __func__ << " on removed pool " << *pool << dendl; return true; } dout(10) << __func__ << " " << *statfs << " from " << statfs->get_orig_source() << dendl; epoch_t ver = get_last_committed(); auto reply = new MStatfsReply(statfs->fsid, statfs->get_tid(), ver); reply->h.st = get_statfs(mon.osdmon()->osdmap, pool); mon.send_reply(op, reply); return true; } void MgrStatMonitor::check_sub(Subscription *sub) { dout(10) << __func__ << " next " << sub->next << " vs service_map.epoch " << service_map.epoch << dendl; if (sub->next <= service_map.epoch) { auto m = new MServiceMap(service_map); sub->session->con->send_message(m); if (sub->onetime) { mon.with_session_map([sub](MonSessionMap& session_map) { session_map.remove_sub(sub); }); } else { sub->next = service_map.epoch + 1; } } } void MgrStatMonitor::check_subs() { dout(10) << __func__ << dendl; if (!service_map.epoch) { return; } auto subs = mon.session_map.subs.find("servicemap"); if (subs == mon.session_map.subs.end()) { return; } auto p = subs->second->begin(); while (!p.end()) { auto sub = *p; ++p; check_sub(sub); } }
10,479
27.478261
105
cc
null
ceph-main/src/mon/MgrStatMonitor.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include "include/Context.h" #include "PaxosService.h" #include "mon/PGMap.h" #include "mgr/ServiceMap.h" class MgrStatMonitor : public PaxosService { // live version version_t version = 0; PGMapDigest digest; ServiceMap service_map; std::map<std::string,ProgressEvent> progress_events; // pending commit PGMapDigest pending_digest; health_check_map_t pending_health_checks; std::map<std::string,ProgressEvent> pending_progress_events; ceph::buffer::list pending_service_map_bl; public: MgrStatMonitor(Monitor &mn, Paxos &p, const std::string& service_name); ~MgrStatMonitor() override; void init() override {} void on_shutdown() override {} void create_initial() override; void update_from_paxos(bool *need_bootstrap) override; void create_pending() override; void encode_pending(MonitorDBStore::TransactionRef t) override; version_t get_trim_to() const override; bool definitely_converted_snapsets() const { return digest.definitely_converted_snapsets(); } bool preprocess_query(MonOpRequestRef op) override; bool prepare_update(MonOpRequestRef op) override; void encode_full(MonitorDBStore::TransactionRef t) override { } bool preprocess_report(MonOpRequestRef op); bool prepare_report(MonOpRequestRef op); bool preprocess_getpoolstats(MonOpRequestRef op); bool preprocess_statfs(MonOpRequestRef op); void check_sub(Subscription *sub); void check_subs(); void send_digests(); void on_active() override; void tick() override; uint64_t get_last_osd_stat_seq(int osd) { return digest.get_last_osd_stat_seq(osd); } void update_logger(); const ServiceMap& get_service_map() const { return service_map; } const std::map<std::string,ProgressEvent>& get_progress_events() { return progress_events; } // pg stat access const pool_stat_t* get_pool_stat(int64_t poolid) const { auto i = digest.pg_pool_sum.find(poolid); if (i != digest.pg_pool_sum.end()) { return &i->second; } return nullptr; } const PGMapDigest& get_digest() { return digest; } ceph_statfs get_statfs(OSDMap& osdmap, std::optional<int64_t> data_pool) const { return digest.get_statfs(osdmap, data_pool); } void print_summary(ceph::Formatter *f, std::ostream *out) const { digest.print_summary(f, out); } void dump_info(ceph::Formatter *f) const { digest.dump(f); f->dump_object("servicemap", get_service_map()); f->dump_unsigned("mgrstat_first_committed", get_first_committed()); f->dump_unsigned("mgrstat_last_committed", get_last_committed()); } void dump_cluster_stats(std::stringstream *ss, ceph::Formatter *f, bool verbose) const { digest.dump_cluster_stats(ss, f, verbose); } void dump_pool_stats(const OSDMap& osdm, std::stringstream *ss, ceph::Formatter *f, bool verbose) const { digest.dump_pool_stats_full(osdm, ss, f, verbose); } };
3,045
26.690909
85
h
null
ceph-main/src/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) 2013 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 <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi_uint.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/fusion/include/std_pair.hpp> #include <boost/phoenix.hpp> #include <boost/fusion/adapted/struct/adapt_struct.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <boost/algorithm/string/predicate.hpp> #include "MonCap.h" #include "include/stringify.h" #include "include/ipaddr.h" #include "common/debug.h" #include "common/Formatter.h" #include <algorithm> #include <regex> #include "include/ceph_assert.h" #define dout_subsys ceph_subsys_mon #undef dout_prefix #define dout_prefix *_dout << "MonCap " using std::list; using std::map; using std::ostream; using std::pair; using std::string; using std::vector; using ceph::bufferlist; using ceph::Formatter; static inline bool is_not_alnum_space(char c) { return !(isalpha(c) || isdigit(c) || (c == '-') || (c == '_')); } static std::string maybe_quote_string(const std::string& str) { if (find_if(str.begin(), str.end(), is_not_alnum_space) == str.end()) return str; return string("\"") + str + string("\""); } #define dout_subsys ceph_subsys_mon ostream& operator<<(ostream& out, const mon_rwxa_t& p) { if (p == MON_CAP_ANY) return out << "*"; if (p & MON_CAP_R) out << "r"; if (p & MON_CAP_W) out << "w"; if (p & MON_CAP_X) out << "x"; return out; } ostream& operator<<(ostream& out, const StringConstraint& c) { switch (c.match_type) { case StringConstraint::MATCH_TYPE_EQUAL: return out << "value " << c.value; case StringConstraint::MATCH_TYPE_PREFIX: return out << "prefix " << c.value; case StringConstraint::MATCH_TYPE_REGEX: return out << "regex " << c.value; default: break; } return out; } ostream& operator<<(ostream& out, const MonCapGrant& m) { out << "allow"; if (m.service.length()) { out << " service " << maybe_quote_string(m.service); } if (m.command.length()) { out << " command " << maybe_quote_string(m.command); if (!m.command_args.empty()) { out << " with"; for (auto p = m.command_args.begin(); p != m.command_args.end(); ++p) { switch (p->second.match_type) { case StringConstraint::MATCH_TYPE_EQUAL: out << " " << maybe_quote_string(p->first) << "=" << maybe_quote_string(p->second.value); break; case StringConstraint::MATCH_TYPE_PREFIX: out << " " << maybe_quote_string(p->first) << " prefix " << maybe_quote_string(p->second.value); break; case StringConstraint::MATCH_TYPE_REGEX: out << " " << maybe_quote_string(p->first) << " regex " << maybe_quote_string(p->second.value); break; default: break; } } } } if (m.profile.length()) { out << " profile " << maybe_quote_string(m.profile); } if (m.allow != 0) out << " " << m.allow; if (m.network.size()) out << " network " << m.network; return out; } // <magic> // fusion lets us easily populate structs via the qi parser. typedef map<string,StringConstraint> kvmap; BOOST_FUSION_ADAPT_STRUCT(MonCapGrant, (std::string, service) (std::string, profile) (std::string, command) (kvmap, command_args) (mon_rwxa_t, allow) (std::string, network) (std::string, fs_name)) BOOST_FUSION_ADAPT_STRUCT(StringConstraint, (StringConstraint::MatchType, match_type) (std::string, value)) // </magic> void MonCapGrant::parse_network() { network_valid = ::parse_network(network.c_str(), &network_parsed, &network_prefix); } void MonCapGrant::expand_profile(const EntityName& name) const { // only generate this list once if (!profile_grants.empty()) return; if (profile == "read-only") { // grants READ-ONLY caps monitor-wide // 'auth' requires MON_CAP_X even for RO, which we do not grant here. profile_grants.push_back(mon_rwxa_t(MON_CAP_R)); return; } if (profile == "read-write") { // grants READ-WRITE caps monitor-wide // 'auth' requires MON_CAP_X for all operations, which we do not grant. profile_grants.push_back(mon_rwxa_t(MON_CAP_R | MON_CAP_W)); return; } if (profile == "mon") { profile_grants.push_back(MonCapGrant("mon", MON_CAP_ALL)); profile_grants.push_back(MonCapGrant("log", MON_CAP_ALL)); } if (profile == "osd") { profile_grants.push_back(MonCapGrant("osd", MON_CAP_ALL)); profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); profile_grants.push_back(MonCapGrant("pg", MON_CAP_R | MON_CAP_W)); profile_grants.push_back(MonCapGrant("log", MON_CAP_W)); StringConstraint constraint(StringConstraint::MATCH_TYPE_REGEX, string("osd_mclock_max_capacity_iops_(hdd|ssd)")); profile_grants.push_back(MonCapGrant("config set", "name", constraint)); constraint = StringConstraint(StringConstraint::MATCH_TYPE_REGEX, string("^(osd_max_backfills|") + string("osd_recovery_max_active(.*)|") + string("osd_mclock_scheduler_(.*))")); profile_grants.push_back(MonCapGrant("config rm", "name", constraint)); } if (profile == "mds") { profile_grants.push_back(MonCapGrant("mds", MON_CAP_ALL)); profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); profile_grants.push_back(MonCapGrant("osd", MON_CAP_R)); // This command grant is checked explicitly in MRemoveSnaps handling profile_grants.push_back(MonCapGrant("osd pool rmsnap")); profile_grants.push_back(MonCapGrant("osd blocklist")); profile_grants.push_back(MonCapGrant("osd blacklist")); // for compat profile_grants.push_back(MonCapGrant("log", MON_CAP_W)); } if (profile == "mgr") { profile_grants.push_back(MonCapGrant("mgr", MON_CAP_ALL)); profile_grants.push_back(MonCapGrant("log", MON_CAP_R | MON_CAP_W)); profile_grants.push_back(MonCapGrant("mon", MON_CAP_R | MON_CAP_W)); profile_grants.push_back(MonCapGrant("mds", MON_CAP_R | MON_CAP_W)); profile_grants.push_back(MonCapGrant("fs", MON_CAP_R | MON_CAP_W)); profile_grants.push_back(MonCapGrant("osd", MON_CAP_R | MON_CAP_W)); profile_grants.push_back(MonCapGrant("auth", MON_CAP_R | MON_CAP_W | MON_CAP_X)); profile_grants.push_back(MonCapGrant("config-key", MON_CAP_R | MON_CAP_W)); profile_grants.push_back(MonCapGrant("config", MON_CAP_R | MON_CAP_W)); // cephadm orchestrator provisions new daemon keys and updates caps profile_grants.push_back(MonCapGrant("auth get-or-create")); profile_grants.push_back(MonCapGrant("auth caps")); profile_grants.push_back(MonCapGrant("auth rm")); // tell commands (this is a bit of a kludge) profile_grants.push_back(MonCapGrant("smart")); // allow the Telemetry module to gather heap and mempool metrics profile_grants.push_back(MonCapGrant("heap")); profile_grants.push_back(MonCapGrant("dump_mempools")); } if (profile == "osd" || profile == "mds" || profile == "mon" || profile == "mgr") { StringConstraint constraint(StringConstraint::MATCH_TYPE_PREFIX, string("daemon-private/") + stringify(name) + string("/")); std::string prefix = string("daemon-private/") + stringify(name) + string("/"); profile_grants.push_back(MonCapGrant("config-key get", "key", constraint)); profile_grants.push_back(MonCapGrant("config-key put", "key", constraint)); profile_grants.push_back(MonCapGrant("config-key set", "key", constraint)); profile_grants.push_back(MonCapGrant("config-key exists", "key", constraint)); profile_grants.push_back(MonCapGrant("config-key delete", "key", constraint)); } if (profile == "bootstrap-osd") { profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); // read monmap profile_grants.push_back(MonCapGrant("osd", MON_CAP_R)); // read osdmap profile_grants.push_back(MonCapGrant("mon getmap")); profile_grants.push_back(MonCapGrant("osd new")); profile_grants.push_back(MonCapGrant("osd purge-new")); } if (profile == "bootstrap-mds") { profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); // read monmap profile_grants.push_back(MonCapGrant("osd", MON_CAP_R)); // read osdmap profile_grants.push_back(MonCapGrant("mon getmap")); profile_grants.push_back(MonCapGrant("auth get-or-create")); // FIXME: this can expose other mds keys profile_grants.back().command_args["entity"] = StringConstraint( StringConstraint::MATCH_TYPE_PREFIX, "mds."); profile_grants.back().command_args["caps_mon"] = StringConstraint( StringConstraint::MATCH_TYPE_EQUAL, "allow profile mds"); profile_grants.back().command_args["caps_osd"] = StringConstraint( StringConstraint::MATCH_TYPE_EQUAL, "allow rwx"); profile_grants.back().command_args["caps_mds"] = StringConstraint( StringConstraint::MATCH_TYPE_EQUAL, "allow"); } if (profile == "bootstrap-mgr") { profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); // read monmap profile_grants.push_back(MonCapGrant("osd", MON_CAP_R)); // read osdmap profile_grants.push_back(MonCapGrant("mon getmap")); profile_grants.push_back(MonCapGrant("auth get-or-create")); // FIXME: this can expose other mgr keys profile_grants.back().command_args["entity"] = StringConstraint( StringConstraint::MATCH_TYPE_PREFIX, "mgr."); profile_grants.back().command_args["caps_mon"] = StringConstraint( StringConstraint::MATCH_TYPE_EQUAL, "allow profile mgr"); } if (profile == "bootstrap-rgw") { profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); // read monmap profile_grants.push_back(MonCapGrant("osd", MON_CAP_R)); // read osdmap profile_grants.push_back(MonCapGrant("mon getmap")); profile_grants.push_back(MonCapGrant("auth get-or-create")); // FIXME: this can expose other mds keys profile_grants.back().command_args["entity"] = StringConstraint( StringConstraint::MATCH_TYPE_PREFIX, "client.rgw."); profile_grants.back().command_args["caps_mon"] = StringConstraint( StringConstraint::MATCH_TYPE_EQUAL, "allow rw"); profile_grants.back().command_args["caps_osd"] = StringConstraint( StringConstraint::MATCH_TYPE_EQUAL, "allow rwx"); } if (profile == "bootstrap-rbd" || profile == "bootstrap-rbd-mirror") { profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); // read monmap profile_grants.push_back(MonCapGrant("auth get-or-create")); // FIXME: this can expose other rbd keys profile_grants.back().command_args["entity"] = StringConstraint( StringConstraint::MATCH_TYPE_PREFIX, "client."); profile_grants.back().command_args["caps_mon"] = StringConstraint( StringConstraint::MATCH_TYPE_EQUAL, (profile == "bootstrap-rbd-mirror" ? "profile rbd-mirror" : "profile rbd")); profile_grants.back().command_args["caps_osd"] = StringConstraint( StringConstraint::MATCH_TYPE_REGEX, "^([ ,]*profile(=|[ ]+)['\"]?rbd[^ ,'\"]*['\"]?([ ]+pool(=|[ ]+)['\"]?[^,'\"]+['\"]?)?)+$"); } if (profile == "fs-client") { profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); profile_grants.push_back(MonCapGrant("mds", MON_CAP_R)); profile_grants.push_back(MonCapGrant("osd", MON_CAP_R)); profile_grants.push_back(MonCapGrant("pg", MON_CAP_R)); } if (profile == "simple-rados-client") { profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); profile_grants.push_back(MonCapGrant("osd", MON_CAP_R)); profile_grants.push_back(MonCapGrant("pg", MON_CAP_R)); } if (profile == "simple-rados-client-with-blocklist") { profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); profile_grants.push_back(MonCapGrant("osd", MON_CAP_R)); profile_grants.push_back(MonCapGrant("pg", MON_CAP_R)); profile_grants.push_back(MonCapGrant("osd blocklist")); profile_grants.back().command_args["blocklistop"] = StringConstraint( StringConstraint::MATCH_TYPE_EQUAL, "add"); profile_grants.back().command_args["addr"] = StringConstraint( StringConstraint::MATCH_TYPE_REGEX, "^[^/]+/[0-9]+$"); } if (boost::starts_with(profile, "rbd")) { profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); profile_grants.push_back(MonCapGrant("osd", MON_CAP_R)); profile_grants.push_back(MonCapGrant("pg", MON_CAP_R)); // exclusive lock dead-client blocklisting (IP+nonce required) profile_grants.push_back(MonCapGrant("osd blocklist")); profile_grants.back().command_args["blocklistop"] = StringConstraint( StringConstraint::MATCH_TYPE_EQUAL, "add"); profile_grants.back().command_args["addr"] = StringConstraint( StringConstraint::MATCH_TYPE_REGEX, "^[^/]+/[0-9]+$"); // for compat, profile_grants.push_back(MonCapGrant("osd blacklist")); profile_grants.back().command_args["blacklistop"] = StringConstraint( StringConstraint::MATCH_TYPE_EQUAL, "add"); profile_grants.back().command_args["addr"] = StringConstraint( StringConstraint::MATCH_TYPE_REGEX, "^[^/]+/[0-9]+$"); } if (profile == "rbd-mirror") { StringConstraint constraint(StringConstraint::MATCH_TYPE_PREFIX, "rbd/mirror/"); profile_grants.push_back(MonCapGrant("config-key get", "key", constraint)); } else if (profile == "rbd-mirror-peer") { StringConstraint constraint(StringConstraint::MATCH_TYPE_REGEX, "rbd/mirror/[^/]+"); profile_grants.push_back(MonCapGrant("config-key get", "key", constraint)); constraint = StringConstraint(StringConstraint::MATCH_TYPE_PREFIX, "rbd/mirror/peer/"); profile_grants.push_back(MonCapGrant("config-key set", "key", constraint)); } else if (profile == "crash") { // TODO: we could limit this to getting the monmap and mgrmap... profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); } if (profile == "cephfs-mirror") { profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); profile_grants.push_back(MonCapGrant("mds", MON_CAP_R)); profile_grants.push_back(MonCapGrant("osd", MON_CAP_R)); profile_grants.push_back(MonCapGrant("pg", MON_CAP_R)); StringConstraint constraint(StringConstraint::MATCH_TYPE_PREFIX, "cephfs/mirror/peer/"); profile_grants.push_back(MonCapGrant("config-key get", "key", constraint)); } if (profile == "role-definer") { // grants ALL caps to the auth subsystem, read-only on the // monitor subsystem and nothing else. profile_grants.push_back(MonCapGrant("mon", MON_CAP_R)); profile_grants.push_back(MonCapGrant("auth", MON_CAP_ALL)); } } mon_rwxa_t MonCapGrant::get_allowed(CephContext *cct, EntityName name, const std::string& s, const std::string& c, const map<string,string>& c_args) const { if (profile.length()) { expand_profile(name); mon_rwxa_t a; for (auto p = profile_grants.begin(); p != profile_grants.end(); ++p) a = a | p->get_allowed(cct, name, s, c, c_args); return a; } if (service.length()) { if (service != s) return 0; return allow; } if (command.length()) { if (command != c) return 0; for (map<string,StringConstraint>::const_iterator p = command_args.begin(); p != command_args.end(); ++p) { map<string,string>::const_iterator q = c_args.find(p->first); // argument must be present if a constraint exists if (q == c_args.end()) return 0; switch (p->second.match_type) { case StringConstraint::MATCH_TYPE_EQUAL: if (p->second.value != q->second) return 0; break; case StringConstraint::MATCH_TYPE_PREFIX: if (q->second.find(p->second.value) != 0) return 0; break; case StringConstraint::MATCH_TYPE_REGEX: try { std::regex pattern( p->second.value, std::regex::extended); if (!std::regex_match(q->second, pattern)) return 0; } catch(const std::regex_error&) { return 0; } break; default: break; } } return MON_CAP_ALL; } // we don't allow config-key service to be accessed with blanket caps other // than '*' (i.e., 'any'), and that should have been checked by the caller // via 'is_allow_all()'. if (s == "config-key") { return 0; } return allow; } ostream& operator<<(ostream&out, const MonCap& m) { for (vector<MonCapGrant>::const_iterator p = m.grants.begin(); p != m.grants.end(); ++p) { if (p != m.grants.begin()) out << ", "; out << *p; } return out; } bool MonCap::is_allow_all() const { for (vector<MonCapGrant>::const_iterator p = grants.begin(); p != grants.end(); ++p) if (p->is_allow_all()) return true; return false; } void MonCap::set_allow_all() { grants.clear(); grants.push_back(MonCapGrant(MON_CAP_ANY)); text = "allow *"; } bool MonCap::is_capable( CephContext *cct, EntityName name, const string& service, const string& command, const map<string,string>& command_args, bool op_may_read, bool op_may_write, bool op_may_exec, const entity_addr_t& addr) const { if (cct) ldout(cct, 20) << "is_capable service=" << service << " command=" << command << (op_may_read ? " read":"") << (op_may_write ? " write":"") << (op_may_exec ? " exec":"") << " addr " << addr << " on cap " << *this << dendl; mon_rwxa_t allow = 0; for (vector<MonCapGrant>::const_iterator p = grants.begin(); p != grants.end(); ++p) { if (cct) ldout(cct, 20) << " allow so far " << allow << ", doing grant " << *p << dendl; if (p->network.size() && (!p->network_valid || !network_contains(p->network_parsed, p->network_prefix, addr))) { continue; } if (p->is_allow_all()) { if (cct) ldout(cct, 20) << " allow all" << dendl; return true; } // check enumerated caps allow = allow | p->get_allowed(cct, name, service, command, command_args); if ((!op_may_read || (allow & MON_CAP_R)) && (!op_may_write || (allow & MON_CAP_W)) && (!op_may_exec || (allow & MON_CAP_X))) { if (cct) ldout(cct, 20) << " match" << dendl; return true; } } return false; } void MonCap::encode(bufferlist& bl) const { ENCODE_START(4, 4, bl); // legacy MonCaps was 3, 3 encode(text, bl); ENCODE_FINISH(bl); } void MonCap::decode(bufferlist::const_iterator& bl) { std::string s; DECODE_START(4, bl); decode(s, bl); DECODE_FINISH(bl); parse(s, NULL); } void MonCap::dump(Formatter *f) const { f->dump_string("text", text); } void MonCap::generate_test_instances(list<MonCap*>& ls) { ls.push_back(new MonCap); ls.push_back(new MonCap); ls.back()->parse("allow *"); ls.push_back(new MonCap); ls.back()->parse("allow rwx"); ls.push_back(new MonCap); ls.back()->parse("allow service foo x"); ls.push_back(new MonCap); ls.back()->parse("allow command bar x"); ls.push_back(new MonCap); ls.back()->parse("allow service foo r, allow command bar x"); ls.push_back(new MonCap); ls.back()->parse("allow command bar with k1=v1 x"); ls.push_back(new MonCap); ls.back()->parse("allow command bar with k1=v1 k2=v2 x"); } // grammar namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; template <typename Iterator> struct MonCapParser : qi::grammar<Iterator, MonCap()> { MonCapParser() : MonCapParser::base_type(moncap) { using qi::char_; using qi::int_; using qi::ulong_long; using qi::lexeme; using qi::alnum; using qi::_val; using qi::_1; using qi::_2; using qi::_3; using qi::eps; using qi::lit; quoted_string %= lexeme['"' >> +(char_ - '"') >> '"'] | lexeme['\'' >> +(char_ - '\'') >> '\'']; unquoted_word %= +char_("a-zA-Z0-9_./-"); str %= quoted_string | unquoted_word; network_str %= +char_("/.:a-fA-F0-9]["); fs_name_str %= +char_("a-zA-Z0-9_.-"); spaces = +(lit(' ') | lit('\n') | lit('\t')); // command := command[=]cmd [k1=v1 k2=v2 ...] str_match = '=' >> qi::attr(StringConstraint::MATCH_TYPE_EQUAL) >> str; str_prefix = spaces >> lit("prefix") >> spaces >> qi::attr(StringConstraint::MATCH_TYPE_PREFIX) >> str; str_regex = spaces >> lit("regex") >> spaces >> qi::attr(StringConstraint::MATCH_TYPE_REGEX) >> str; kv_pair = str >> (str_match | str_prefix | str_regex); kv_map %= kv_pair >> *(spaces >> kv_pair); command_match = -spaces >> lit("allow") >> spaces >> lit("command") >> (lit('=') | spaces) >> qi::attr(string()) >> qi::attr(string()) >> str >> -(spaces >> lit("with") >> spaces >> kv_map) >> qi::attr(0) >> -(spaces >> lit("network") >> spaces >> network_str); // service foo rwxa service_match %= -spaces >> lit("allow") >> spaces >> lit("service") >> (lit('=') | spaces) >> str >> qi::attr(string()) >> qi::attr(string()) >> qi::attr(map<string,StringConstraint>()) >> spaces >> rwxa >> -(spaces >> lit("network") >> spaces >> network_str); // profile foo profile_match %= -spaces >> -(lit("allow") >> spaces) >> lit("profile") >> (lit('=') | spaces) >> qi::attr(string()) >> str >> qi::attr(string()) >> qi::attr(map<string,StringConstraint>()) >> qi::attr(0) >> -(spaces >> lit("network") >> spaces >> network_str); // rwxa rwxa_match %= -spaces >> lit("allow") >> spaces >> qi::attr(string()) >> qi::attr(string()) >> qi::attr(string()) >> qi::attr(map<string,StringConstraint>()) >> rwxa >> -(spaces >> lit("network") >> spaces >> network_str) >> -(spaces >> lit("fsname") >> (lit('=') | spaces) >> fs_name_str); // rwxa := * | [r][w][x] rwxa = (lit("*")[_val = MON_CAP_ANY]) | (lit("all")[_val = MON_CAP_ANY]) | ( eps[_val = 0] >> ( lit('r')[_val |= MON_CAP_R] || lit('w')[_val |= MON_CAP_W] || lit('x')[_val |= MON_CAP_X] ) ); // grant := allow ... grant = -spaces >> (rwxa_match | profile_match | service_match | command_match) >> -spaces; // moncap := grant [grant ...] grants %= (grant % (*lit(' ') >> (lit(';') | lit(',')) >> *lit(' '))); moncap = grants [_val = phoenix::construct<MonCap>(_1)]; } qi::rule<Iterator> spaces; qi::rule<Iterator, unsigned()> rwxa; qi::rule<Iterator, string()> quoted_string; qi::rule<Iterator, string()> unquoted_word; qi::rule<Iterator, string()> str, network_str; qi::rule<Iterator, string()> fs_name_str; qi::rule<Iterator, StringConstraint()> str_match, str_prefix, str_regex; qi::rule<Iterator, pair<string, StringConstraint>()> kv_pair; qi::rule<Iterator, map<string, StringConstraint>()> kv_map; qi::rule<Iterator, MonCapGrant()> rwxa_match; qi::rule<Iterator, MonCapGrant()> command_match; qi::rule<Iterator, MonCapGrant()> service_match; qi::rule<Iterator, MonCapGrant()> profile_match; qi::rule<Iterator, MonCapGrant()> grant; qi::rule<Iterator, std::vector<MonCapGrant>()> grants; qi::rule<Iterator, MonCap()> moncap; }; bool MonCap::parse(const string& str, ostream *err) { auto iter = str.begin(); auto end = str.end(); MonCapParser<string::const_iterator> exp; bool r = qi::parse(iter, end, exp, *this); if (r && iter == end) { text = str; for (auto& g : grants) { g.parse_network(); } return true; } // Make sure no grants are kept after parsing failed! grants.clear(); if (err) { if (iter != end) *err << "mon capability parse failed, stopped at '" << std::string(iter, end) << "' of '" << str << "'"; else *err << "mon capability parse failed, stopped at end of '" << str << "'"; } return false; }
24,531
34.399711
111
cc