repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
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.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.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.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.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.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_MONCAP_H #define CEPH_MONCAP_H #include <ostream> #include "include/common_fwd.h" #include "include/types.h" #include "common/entity_name.h" #include "mds/mdstypes.h" static const __u8 MON_CAP_R = (1 << 1); // read static const __u8 MON_CAP_W = (1 << 2); // write static const __u8 MON_CAP_X = (1 << 3); // execute static const __u8 MON_CAP_ALL = MON_CAP_R | MON_CAP_W | MON_CAP_X; static const __u8 MON_CAP_ANY = 0xff; // * struct mon_rwxa_t { __u8 val; // cppcheck-suppress noExplicitConstructor mon_rwxa_t(__u8 v = 0) : val(v) {} mon_rwxa_t& operator=(__u8 v) { val = v; return *this; } operator __u8() const { return val; } }; std::ostream& operator<<(std::ostream& out, const mon_rwxa_t& p); struct StringConstraint { enum MatchType { MATCH_TYPE_NONE, MATCH_TYPE_EQUAL, MATCH_TYPE_PREFIX, MATCH_TYPE_REGEX }; MatchType match_type = MATCH_TYPE_NONE; std::string value; StringConstraint() {} StringConstraint(MatchType match_type, std::string value) : match_type(match_type), value(value) { } }; std::ostream& operator<<(std::ostream& out, const StringConstraint& c); struct MonCapGrant { /* * A grant can come in one of five forms: * * - a blanket allow ('allow rw', 'allow *') * - this will match against any service and the read/write/exec flags * in the mon 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 profile ('allow profile osd') * - this will match against specific monitor-enforced semantics of what * this type of user should need to do. examples include 'osd', 'mds', * 'bootstrap-osd'. * * - a command ('allow command foo', 'allow command bar with arg1=val1 arg2 prefix val2') * this includes the command name (the prefix string), and a set * of key/value pairs that constrain use of that command. if no pairs * are specified, any arguments are allowed; if a pair is specified, that * argument must be present and equal or match a prefix. * * - an fs name ('allow fsname foo') * - this will restrict access to MDSMaps in the FSMap to the provided * fs name. */ std::string service; std::string profile; std::string command; std::map<std::string, StringConstraint> command_args; std::string fs_name; // restrict by network std::string network; // these are filled in by parse_network(), called by MonCap::parse() entity_addr_t network_parsed; unsigned network_prefix = 0; bool network_valid = true; void parse_network(); mon_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<MonCapGrant> profile_grants; void expand_profile(const EntityName& name) const; MonCapGrant() : allow(0) {} // cppcheck-suppress noExplicitConstructor MonCapGrant(mon_rwxa_t a) : allow(a) {} MonCapGrant(std::string s, mon_rwxa_t a) : service(std::move(s)), allow(a) {} // cppcheck-suppress noExplicitConstructor MonCapGrant(std::string c) : command(std::move(c)) {} MonCapGrant(std::string c, std::string a, StringConstraint co) : command(std::move(c)) { command_args[a] = co; } MonCapGrant(mon_rwxa_t a, std::string fsname) : fs_name(fsname), allow(a) {} /** * check if given request parameters match our constraints * * @param cct context * @param name entity name * @param service service (if any) * @param command command (if any) * @param command_args command args (if any) * @return bits we allow */ mon_rwxa_t get_allowed(CephContext *cct, EntityName name, const std::string& service, const std::string& command, const std::map<std::string, std::string>& command_args) const; bool is_allow_all() const { return allow == MON_CAP_ANY && service.length() == 0 && profile.length() == 0 && command.length() == 0 && fs_name.empty(); } }; std::ostream& operator<<(std::ostream& out, const MonCapGrant& g); struct MonCap { std::string text; std::vector<MonCapGrant> grants; MonCap() {} explicit MonCap(const std::vector<MonCapGrant> &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 command command id * @param command_args * @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& 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; 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<MonCap*>& ls); std::vector<std::string> allowed_fs_names() const { std::vector<std::string> ret; for (auto& g : grants) { if (not g.fs_name.empty()) { ret.push_back(g.fs_name); } else { return {}; } } return ret; } bool fs_name_capable(const EntityName& ename, std::string_view fs_name, __u8 mask) { for (auto& g : grants) { if (g.is_allow_all()) { return true; } if ((g.fs_name.empty() || g.fs_name == fs_name) && (mask & g.allow)) { return true; } g.expand_profile(ename); for (auto& pg : g.profile_grants) { if ((pg.service == "fs" || pg.service == "mds") && (pg.fs_name.empty() || pg.fs_name == fs_name) && (pg.allow & mask)) { return true; } } } return false; } }; WRITE_CLASS_ENCODER(MonCap) std::ostream& operator<<(std::ostream& out, const MonCap& cap); #endif
6,560
27.776316
92
h
null
ceph-main/src/mon/MonClient.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_MONCLIENT_H #define CEPH_MONCLIENT_H #include <functional> #include <list> #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "msg/Messenger.h" #include "MonMap.h" #include "MonSub.h" #include "common/admin_socket.h" #include "common/async/completion.h" #include "common/Timer.h" #include "common/config.h" #include "messages/MMonGetVersion.h" #include "auth/AuthClient.h" #include "auth/AuthServer.h" class MMonMap; class MConfig; class MMonGetVersionReply; class MMonCommandAck; class LogClient; class AuthClientHandler; class AuthRegistry; class KeyRing; class RotatingKeyRing; class MonConnection { public: MonConnection(CephContext *cct, ConnectionRef conn, uint64_t global_id, AuthRegistry *auth_registry); ~MonConnection(); MonConnection(MonConnection&& rhs) = default; MonConnection& operator=(MonConnection&&) = default; MonConnection(const MonConnection& rhs) = delete; MonConnection& operator=(const MonConnection&) = delete; int handle_auth(MAuthReply *m, const EntityName& entity_name, uint32_t want_keys, RotatingKeyRing* keyring); int authenticate(MAuthReply *m); void start(epoch_t epoch, const EntityName& entity_name); bool have_session() const; uint64_t get_global_id() const { return global_id; } ConnectionRef get_con() { return con; } std::unique_ptr<AuthClientHandler>& get_auth() { return auth; } int get_auth_request( uint32_t *method, std::vector<uint32_t> *preferred_modes, ceph::buffer::list *out, const EntityName& entity_name, uint32_t want_keys, RotatingKeyRing* keyring); int handle_auth_reply_more( AuthConnectionMeta *auth_meta, const ceph::buffer::list& bl, ceph::buffer::list *reply); int handle_auth_done( AuthConnectionMeta *auth_meta, uint64_t global_id, const ceph::buffer::list& bl, CryptoKey *session_key, std::string *connection_secret); int handle_auth_bad_method( uint32_t old_auth_method, int result, const std::vector<uint32_t>& allowed_methods, const std::vector<uint32_t>& allowed_modes); bool is_con(Connection *c) const { return con.get() == c; } void queue_command(Message *m) { pending_tell_command = m; } private: int _negotiate(MAuthReply *m, const EntityName& entity_name, uint32_t want_keys, RotatingKeyRing* keyring); int _init_auth(uint32_t method, const EntityName& entity_name, uint32_t want_keys, RotatingKeyRing* keyring, bool msgr2); private: CephContext *cct; enum class State { NONE, NEGOTIATING, // v1 only AUTHENTICATING, // v1 and v2 HAVE_SESSION, }; State state = State::NONE; ConnectionRef con; int auth_method = -1; utime_t auth_start; std::unique_ptr<AuthClientHandler> auth; uint64_t global_id; MessageRef pending_tell_command; AuthRegistry *auth_registry; }; struct MonClientPinger : public Dispatcher, public AuthClient { ceph::mutex lock = ceph::make_mutex("MonClientPinger::lock"); ceph::condition_variable ping_recvd_cond; std::string *result; bool done; RotatingKeyRing *keyring; std::unique_ptr<MonConnection> mc; MonClientPinger(CephContext *cct_, RotatingKeyRing *keyring, std::string *res_) : Dispatcher(cct_), result(res_), done(false), keyring(keyring) { } int wait_for_reply(double timeout = 0.0) { std::unique_lock locker{lock}; if (timeout <= 0) { timeout = std::chrono::duration<double>(cct->_conf.get_val<std::chrono::seconds>("client_mount_timeout")).count(); } done = false; if (ping_recvd_cond.wait_for(locker, ceph::make_timespan(timeout), [this] { return done; })) { return 0; } else { return ETIMEDOUT; } } bool ms_dispatch(Message *m) override { using ceph::decode; std::lock_guard l(lock); if (m->get_type() != CEPH_MSG_PING) return false; ceph::buffer::list &payload = m->get_payload(); if (result && payload.length() > 0) { auto p = std::cbegin(payload); decode(*result, p); } done = true; ping_recvd_cond.notify_all(); m->put(); return true; } bool ms_handle_reset(Connection *con) override { std::lock_guard l(lock); done = true; ping_recvd_cond.notify_all(); return true; } void ms_handle_remote_reset(Connection *con) override {} bool ms_handle_refused(Connection *con) override { return false; } // AuthClient int get_auth_request( Connection *con, AuthConnectionMeta *auth_meta, uint32_t *auth_method, std::vector<uint32_t> *preferred_modes, ceph::buffer::list *bl) override { return mc->get_auth_request(auth_method, preferred_modes, bl, cct->_conf->name, 0, keyring); } int handle_auth_reply_more( Connection *con, AuthConnectionMeta *auth_meta, const ceph::buffer::list& bl, ceph::buffer::list *reply) override { return mc->handle_auth_reply_more(auth_meta, bl, reply); } int handle_auth_done( Connection *con, AuthConnectionMeta *auth_meta, uint64_t global_id, uint32_t con_mode, const ceph::buffer::list& bl, CryptoKey *session_key, std::string *connection_secret) override { return mc->handle_auth_done(auth_meta, global_id, bl, session_key, connection_secret); } int handle_auth_bad_method( Connection *con, AuthConnectionMeta *auth_meta, uint32_t old_auth_method, int result, const std::vector<uint32_t>& allowed_methods, const std::vector<uint32_t>& allowed_modes) override { return mc->handle_auth_bad_method(old_auth_method, result, allowed_methods, allowed_modes); } }; const boost::system::error_category& monc_category() noexcept; enum class monc_errc { shutting_down = 1, // Command failed due to MonClient shutting down session_reset, // Monitor session was reset rank_dne, // Requested monitor rank does not exist mon_dne, // Requested monitor does not exist timed_out, // Monitor operation timed out mon_unavailable // Monitor unavailable }; namespace boost::system { template<> struct is_error_code_enum<::monc_errc> { static const bool value = true; }; } // implicit conversion: inline boost::system::error_code make_error_code(monc_errc e) noexcept { return { static_cast<int>(e), monc_category() }; } // explicit conversion: inline boost::system::error_condition make_error_condition(monc_errc e) noexcept { return { static_cast<int>(e), monc_category() }; } const boost::system::error_category& monc_category() noexcept; class MonClient : public Dispatcher, public AuthClient, public AuthServer, /* for mgr, osd, mds */ public AdminSocketHook { static constexpr auto dout_subsys = ceph_subsys_monc; public: // Error, Newest, Oldest using VersionSig = void(boost::system::error_code, version_t, version_t); using VersionCompletion = ceph::async::Completion<VersionSig>; using CommandSig = void(boost::system::error_code, std::string, ceph::buffer::list); using CommandCompletion = ceph::async::Completion<CommandSig>; MonMap monmap; std::map<std::string,std::string> config_mgr; private: Messenger *messenger; std::unique_ptr<MonConnection> active_con; std::map<entity_addrvec_t, MonConnection> pending_cons; std::set<unsigned> tried; EntityName entity_name; mutable ceph::mutex monc_lock = ceph::make_mutex("MonClient::monc_lock"); SafeTimer timer; boost::asio::io_context& service; boost::asio::io_context::strand finish_strand{service}; bool initialized; bool stopping = false; LogClient *log_client; bool more_log_pending; void send_log(bool flush = false); bool ms_dispatch(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 { return false; } void handle_monmap(MMonMap *m); void handle_config(MConfig *m); void handle_auth(MAuthReply *m); int call( std::string_view command, const cmdmap_t& cmdmap, const ceph::buffer::list &inbl, ceph::Formatter *f, std::ostream& errss, ceph::buffer::list& out) override; // monitor session utime_t last_keepalive; utime_t last_send_log; void tick(); void schedule_tick(); // monclient bool want_monmap; ceph::condition_variable map_cond; bool passthrough_monmap = false; bool want_bootstrap_config = false; ceph::ref_t<MConfig> bootstrap_config; // authenticate std::unique_ptr<AuthClientHandler> auth; uint32_t want_keys = 0; uint64_t global_id = 0; ceph::condition_variable auth_cond; int authenticate_err = 0; bool authenticated = false; std::list<MessageRef> waiting_for_session; utime_t last_rotating_renew_sent; bool had_a_connection; double reopen_interval_multiplier; Dispatcher *handle_authentication_dispatcher = nullptr; bool _opened() const; bool _hunting() const; void _start_hunting(); void _finish_hunting(int auth_err); void _finish_auth(int auth_err); void _reopen_session(int rank = -1); void _add_conn(unsigned rank); void _add_conns(); void _un_backoff(); void _send_mon_message(MessageRef m); std::map<entity_addrvec_t, MonConnection>::iterator _find_pending_con( const ConnectionRef& con) { for (auto i = pending_cons.begin(); i != pending_cons.end(); ++i) { if (i->second.get_con() == con) { return i; } } return pending_cons.end(); } public: // AuthClient int get_auth_request( Connection *con, AuthConnectionMeta *auth_meta, uint32_t *method, std::vector<uint32_t> *preferred_modes, ceph::buffer::list *bl) override; int handle_auth_reply_more( Connection *con, AuthConnectionMeta *auth_meta, const ceph::buffer::list& bl, ceph::buffer::list *reply) override; int handle_auth_done( Connection *con, AuthConnectionMeta *auth_meta, uint64_t global_id, uint32_t con_mode, const ceph::buffer::list& bl, CryptoKey *session_key, std::string *connection_secret) override; int handle_auth_bad_method( Connection *con, AuthConnectionMeta *auth_meta, uint32_t old_auth_method, int result, const std::vector<uint32_t>& allowed_methods, const std::vector<uint32_t>& allowed_modes) override; // AuthServer int handle_auth_request( Connection *con, AuthConnectionMeta *auth_meta, bool more, uint32_t auth_method, const ceph::buffer::list& bl, ceph::buffer::list *reply) override; void set_entity_name(EntityName name) { entity_name = name; } void set_handle_authentication_dispatcher(Dispatcher *d) { handle_authentication_dispatcher = d; } int _check_auth_tickets(); int _check_auth_rotating(); int wait_auth_rotating(double timeout); int authenticate(double timeout=0.0); bool is_authenticated() const {return authenticated;} bool is_connected() const { return active_con != nullptr; } /** * Try to flush as many log messages as we can in a single * message. Use this before shutting down to transmit your * last message. */ void flush_log(); private: // mon subscriptions MonSub sub; void _renew_subs(); void handle_subscribe_ack(MMonSubscribeAck* m); public: void renew_subs() { std::lock_guard l(monc_lock); _renew_subs(); } bool sub_want(std::string what, version_t start, unsigned flags) { std::lock_guard l(monc_lock); return sub.want(what, start, flags); } void sub_got(std::string what, version_t have) { std::lock_guard l(monc_lock); sub.got(what, have); } void sub_unwant(std::string what) { std::lock_guard l(monc_lock); sub.unwant(what); } bool sub_want_increment(std::string what, version_t start, unsigned flags) { std::lock_guard l(monc_lock); return sub.inc_want(what, start, flags); } std::unique_ptr<KeyRing> keyring; std::unique_ptr<RotatingKeyRing> rotating_secrets; public: MonClient(CephContext *cct_, boost::asio::io_context& service); MonClient(const MonClient &) = delete; MonClient& operator=(const MonClient &) = delete; ~MonClient() override; int init(); void shutdown(); void set_log_client(LogClient *clog) { log_client = clog; } LogClient *get_log_client() { return log_client; } int build_initial_monmap(); int get_monmap(); int get_monmap_and_config(); /** * If you want to see MonMap messages, set this and * the MonClient will tell the Messenger it hasn't * dealt with it. * Note that if you do this, *you* are of course responsible for * putting the message reference! */ void set_passthrough_monmap() { std::lock_guard l(monc_lock); passthrough_monmap = true; } void unset_passthrough_monmap() { std::lock_guard l(monc_lock); passthrough_monmap = false; } /** * Ping monitor with ID @p mon_id and record the resulting * reply in @p result_reply. * * @param[in] mon_id Target monitor's ID * @param[out] result_reply reply from mon.ID, if param != NULL * @returns 0 in case of success; < 0 in case of error, * -ETIMEDOUT if monitor didn't reply before timeout * expired (default: conf->client_mount_timeout). */ int ping_monitor(const std::string &mon_id, std::string *result_reply); void send_mon_message(Message *m) { send_mon_message(MessageRef{m, false}); } void send_mon_message(MessageRef m); void reopen_session() { std::lock_guard l(monc_lock); _reopen_session(); } const uuid_d& get_fsid() const { return monmap.fsid; } entity_addrvec_t get_mon_addrs(unsigned i) const { std::lock_guard l(monc_lock); if (i < monmap.size()) return monmap.get_addrs(i); return entity_addrvec_t(); } int get_num_mon() const { std::lock_guard l(monc_lock); return monmap.size(); } uint64_t get_global_id() const { std::lock_guard l(monc_lock); return global_id; } void set_messenger(Messenger *m) { messenger = m; } entity_addrvec_t get_myaddrs() const { return messenger->get_myaddrs(); } AuthAuthorizer* build_authorizer(int service_id) const; void set_want_keys(uint32_t want) { want_keys = want; } // admin commands private: uint64_t last_mon_command_tid; struct MonCommand { // for tell only std::string target_name; int target_rank = -1; ConnectionRef target_con; std::unique_ptr<MonConnection> target_session; unsigned send_attempts = 0; ///< attempt count for legacy mons utime_t last_send_attempt; uint64_t tid; std::vector<std::string> cmd; ceph::buffer::list inbl; std::unique_ptr<CommandCompletion> onfinish; std::optional<boost::asio::steady_timer> cancel_timer; MonCommand(MonClient& monc, uint64_t t, std::unique_ptr<CommandCompletion> onfinish) : tid(t), onfinish(std::move(onfinish)) { auto timeout = monc.cct->_conf.get_val<std::chrono::seconds>("rados_mon_op_timeout"); if (timeout.count() > 0) { cancel_timer.emplace(monc.service, timeout); cancel_timer->async_wait( [this, &monc](boost::system::error_code ec) { if (ec) return; std::scoped_lock l(monc.monc_lock); monc._cancel_mon_command(tid); }); } } bool is_tell() const { return target_name.size() || target_rank >= 0; } }; friend MonCommand; std::map<uint64_t,MonCommand*> mon_commands; void _send_command(MonCommand *r); void _check_tell_commands(); void _resend_mon_commands(); int _cancel_mon_command(uint64_t tid); void _finish_command(MonCommand *r, boost::system::error_code ret, std::string_view rs, bufferlist&& bl); void _finish_auth(); void handle_mon_command_ack(MMonCommandAck *ack); void handle_command_reply(MCommandReply *reply); public: template<typename CompletionToken> auto start_mon_command(const std::vector<std::string>& cmd, const ceph::buffer::list& inbl, CompletionToken&& token) { ldout(cct,10) << __func__ << " cmd=" << cmd << dendl; boost::asio::async_completion<CompletionToken, CommandSig> init(token); { std::scoped_lock l(monc_lock); auto h = CommandCompletion::create(service.get_executor(), std::move(init.completion_handler)); if (!initialized || stopping) { ceph::async::post(std::move(h), monc_errc::shutting_down, std::string{}, bufferlist{}); } else { auto r = new MonCommand(*this, ++last_mon_command_tid, std::move(h)); r->cmd = cmd; r->inbl = inbl; mon_commands.emplace(r->tid, r); _send_command(r); } } return init.result.get(); } template<typename CompletionToken> auto start_mon_command(int mon_rank, const std::vector<std::string>& cmd, const ceph::buffer::list& inbl, CompletionToken&& token) { ldout(cct,10) << __func__ << " cmd=" << cmd << dendl; boost::asio::async_completion<CompletionToken, CommandSig> init(token); { std::scoped_lock l(monc_lock); auto h = CommandCompletion::create(service.get_executor(), std::move(init.completion_handler)); if (!initialized || stopping) { ceph::async::post(std::move(h), monc_errc::shutting_down, std::string{}, bufferlist{}); } else { auto r = new MonCommand(*this, ++last_mon_command_tid, std::move(h)); r->target_rank = mon_rank; r->cmd = cmd; r->inbl = inbl; mon_commands.emplace(r->tid, r); _send_command(r); } } return init.result.get(); } template<typename CompletionToken> auto start_mon_command(const std::string& mon_name, const std::vector<std::string>& cmd, const ceph::buffer::list& inbl, CompletionToken&& token) { ldout(cct,10) << __func__ << " cmd=" << cmd << dendl; boost::asio::async_completion<CompletionToken, CommandSig> init(token); { std::scoped_lock l(monc_lock); auto h = CommandCompletion::create(service.get_executor(), std::move(init.completion_handler)); if (!initialized || stopping) { ceph::async::post(std::move(h), monc_errc::shutting_down, std::string{}, bufferlist{}); } else { auto r = new MonCommand(*this, ++last_mon_command_tid, std::move(h)); // detect/tolerate mon *rank* passed as a string std::string err; int rank = strict_strtoll(mon_name.c_str(), 10, &err); if (err.size() == 0 && rank >= 0) { ldout(cct,10) << __func__ << " interpreting name '" << mon_name << "' as rank " << rank << dendl; r->target_rank = rank; } else { r->target_name = mon_name; } r->cmd = cmd; r->inbl = inbl; mon_commands.emplace(r->tid, r); _send_command(r); } } return init.result.get(); } class ContextVerter { std::string* outs; ceph::bufferlist* outbl; Context* onfinish; public: ContextVerter(std::string* outs, ceph::bufferlist* outbl, Context* onfinish) : outs(outs), outbl(outbl), onfinish(onfinish) {} ~ContextVerter() = default; ContextVerter(const ContextVerter&) = default; ContextVerter& operator =(const ContextVerter&) = default; ContextVerter(ContextVerter&&) = default; ContextVerter& operator =(ContextVerter&&) = default; void operator()(boost::system::error_code e, std::string s, ceph::bufferlist bl) { if (outs) *outs = std::move(s); if (outbl) *outbl = std::move(bl); if (onfinish) onfinish->complete(ceph::from_error_code(e)); } }; void start_mon_command(const std::vector<std::string>& cmd, const bufferlist& inbl, bufferlist *outbl, std::string *outs, Context *onfinish) { start_mon_command(cmd, inbl, ContextVerter(outs, outbl, onfinish)); } void start_mon_command(int mon_rank, const std::vector<std::string>& cmd, const bufferlist& inbl, bufferlist *outbl, std::string *outs, Context *onfinish) { start_mon_command(mon_rank, cmd, inbl, ContextVerter(outs, outbl, onfinish)); } void start_mon_command(const std::string &mon_name, ///< mon name, with mon. prefix const std::vector<std::string>& cmd, const bufferlist& inbl, bufferlist *outbl, std::string *outs, Context *onfinish) { start_mon_command(mon_name, cmd, inbl, ContextVerter(outs, outbl, onfinish)); } // version requests public: /** * get latest known version(s) of cluster map * * @param map string name of map (e.g., 'osdmap') * @param token context that will be triggered on completion * @return (via Completion) {} on success, * boost::system::errc::resource_unavailable_try_again if we need to * resubmit our request */ template<typename CompletionToken> auto get_version(std::string&& map, CompletionToken&& token) { boost::asio::async_completion<CompletionToken, VersionSig> init(token); { std::scoped_lock l(monc_lock); auto m = ceph::make_message<MMonGetVersion>(); m->what = std::move(map); m->handle = ++version_req_id; version_requests.emplace(m->handle, VersionCompletion::create( service.get_executor(), std::move(init.completion_handler))); _send_mon_message(m); } return init.result.get(); } /** * Run a callback within our lock, with a reference * to the MonMap */ template<typename Callback, typename...Args> auto with_monmap(Callback&& cb, Args&&...args) const -> decltype(cb(monmap, std::forward<Args>(args)...)) { std::lock_guard l(monc_lock); return std::forward<Callback>(cb)(monmap, std::forward<Args>(args)...); } void register_config_callback(md_config_t::config_callback fn); void register_config_notify_callback(std::function<void(void)> f) { config_notify_cb = f; } md_config_t::config_callback get_config_callback(); private: std::map<ceph_tid_t, std::unique_ptr<VersionCompletion>> version_requests; ceph_tid_t version_req_id; void handle_get_version_reply(MMonGetVersionReply* m); md_config_t::config_callback config_cb; std::function<void(void)> config_notify_cb; }; #endif
22,553
27.73121
120
h
null
ceph-main/src/mon/MonCommand.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 <string> #include "include/encoding.h" struct MonCommand { std::string cmdstring; std::string helpstring; std::string module; std::string req_perms; uint64_t flags; // MonCommand flags static const uint64_t FLAG_NONE = 0; static const uint64_t FLAG_NOFORWARD = 1 << 0; static const uint64_t FLAG_OBSOLETE = 1 << 1; static const uint64_t FLAG_DEPRECATED = 1 << 2; static const uint64_t FLAG_MGR = 1 << 3; static const uint64_t FLAG_POLL = 1 << 4; static const uint64_t FLAG_HIDDEN = 1 << 5; // asok and tell commands are not forwarded, and they should not be listed // in --help output. static const uint64_t FLAG_TELL = (FLAG_NOFORWARD | FLAG_HIDDEN); bool has_flag(uint64_t flag) const { return (flags & flag) == flag; } void set_flag(uint64_t flag) { flags |= flag; } void unset_flag(uint64_t flag) { flags &= ~flag; } void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode_bare(bl); encode(flags, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(1, bl); decode_bare(bl); decode(flags, bl); DECODE_FINISH(bl); } /** * Unversioned encoding for use within encode_array. */ void encode_bare(ceph::buffer::list &bl) const { using ceph::encode; encode(cmdstring, bl); encode(helpstring, bl); encode(module, bl); encode(req_perms, bl); std::string availability = "cli,rest"; // Removed field, for backward compat encode(availability, bl); } void decode_bare(ceph::buffer::list::const_iterator &bl) { using ceph::decode; decode(cmdstring, bl); decode(helpstring, bl); decode(module, bl); decode(req_perms, bl); std::string availability; // Removed field, for backward compat decode(availability, bl); } bool is_compat(const MonCommand* o) const { return cmdstring == o->cmdstring && module == o->module && req_perms == o->req_perms; } bool is_tell() const { return has_flag(MonCommand::FLAG_TELL); } bool is_noforward() const { return has_flag(MonCommand::FLAG_NOFORWARD); } bool is_obsolete() const { return has_flag(MonCommand::FLAG_OBSOLETE); } bool is_deprecated() const { return has_flag(MonCommand::FLAG_DEPRECATED); } bool is_mgr() const { return has_flag(MonCommand::FLAG_MGR); } bool is_hidden() const { return has_flag(MonCommand::FLAG_HIDDEN); } static void encode_array(const MonCommand *cmds, int size, ceph::buffer::list &bl) { ENCODE_START(2, 1, bl); uint16_t s = size; encode(s, bl); for (int i = 0; i < size; ++i) { cmds[i].encode_bare(bl); } for (int i = 0; i < size; i++) { encode(cmds[i].flags, bl); } ENCODE_FINISH(bl); } static void decode_array(MonCommand **cmds, int *size, ceph::buffer::list::const_iterator &bl) { DECODE_START(2, bl); uint16_t s = 0; decode(s, bl); *size = s; *cmds = new MonCommand[*size]; for (int i = 0; i < *size; ++i) { (*cmds)[i].decode_bare(bl); } if (struct_v >= 2) { for (int i = 0; i < *size; i++) decode((*cmds)[i].flags, bl); } else { for (int i = 0; i < *size; i++) (*cmds)[i].flags = 0; } DECODE_FINISH(bl); } // this uses a u16 for the count, so we need a special encoder/decoder. static void encode_vector(const std::vector<MonCommand>& cmds, ceph::buffer::list &bl) { ENCODE_START(2, 1, bl); uint16_t s = cmds.size(); encode(s, bl); for (unsigned i = 0; i < s; ++i) { cmds[i].encode_bare(bl); } for (unsigned i = 0; i < s; i++) { encode(cmds[i].flags, bl); } ENCODE_FINISH(bl); } static void decode_vector(std::vector<MonCommand> &cmds, ceph::buffer::list::const_iterator &bl) { DECODE_START(2, bl); uint16_t s = 0; decode(s, bl); cmds.resize(s); for (unsigned i = 0; i < s; ++i) { cmds[i].decode_bare(bl); } if (struct_v >= 2) { for (unsigned i = 0; i < s; i++) decode(cmds[i].flags, bl); } else { for (unsigned i = 0; i < s; i++) cmds[i].flags = 0; } DECODE_FINISH(bl); } bool requires_perm(char p) const { return (req_perms.find(p) != std::string::npos); } }; WRITE_CLASS_ENCODER(MonCommand)
4,823
26.409091
86
h
null
ceph-main/src/mon/MonMap.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_MONMAP_H #define CEPH_MONMAP_H #ifdef WITH_SEASTAR #include <seastar/core/future.hh> #endif #include "common/config_fwd.h" #include "common/ceph_releases.h" #include "include/err.h" #include "include/types.h" #include "mon/mon_types.h" #include "msg/Message.h" class health_check_map_t; #ifdef WITH_SEASTAR namespace crimson::common { class ConfigProxy; } #endif namespace ceph { class Formatter; } struct mon_info_t { /** * monitor name * * i.e., 'foo' in 'mon.foo' */ std::string name; /** * monitor's public address(es) * * public facing address(es), used to communicate with all clients * and with other monitors. */ entity_addrvec_t public_addrs; /** * the priority of the mon, the lower value the more preferred */ uint16_t priority{0}; uint16_t weight{0}; /** * The location of the monitor, in CRUSH hierarchy terms */ std::map<std::string,std::string> crush_loc; // <REMOVE ME> mon_info_t(const std::string& n, const entity_addr_t& p_addr, uint16_t p) : name(n), public_addrs(p_addr), priority(p) {} // </REMOVE ME> mon_info_t(const std::string& n, const entity_addrvec_t& p_addrs, uint16_t p, uint16_t w) : name(n), public_addrs(p_addrs), priority(p), weight(w) {} mon_info_t(const std::string &n, const entity_addrvec_t& p_addrs) : name(n), public_addrs(p_addrs) { } mon_info_t() { } void encode(ceph::buffer::list& bl, uint64_t features) const; void decode(ceph::buffer::list::const_iterator& p); void print(std::ostream& out) const; }; WRITE_CLASS_ENCODER_FEATURES(mon_info_t) inline std::ostream& operator<<(std::ostream& out, const mon_info_t& mon) { mon.print(out); return out; } class MonMap { public: epoch_t epoch; // what epoch/version of the monmap uuid_d fsid; utime_t last_changed; utime_t created; std::map<std::string, mon_info_t> mon_info; std::map<entity_addr_t, std::string> addr_mons; std::vector<std::string> ranks; /* ranks which were removed when this map took effect. There should only be one at a time, but leave support for arbitrary numbers just to be safe. */ std::set<unsigned> removed_ranks; /** * Persistent Features are all those features that once set on a * monmap cannot, and should not, be removed. These will define the * non-negotiable features that a given monitor must support to * properly operate in a given quorum. * * Should be reserved for features that we really want to make sure * are sticky, and are important enough to tolerate not being able * to downgrade a monitor. */ mon_feature_t persistent_features; /** * Optional Features are all those features that can be enabled or * disabled following a given criteria -- e.g., user-mandated via the * cli --, and act much like indicators of what the cluster currently * supports. * * They are by no means "optional" in the sense that monitors can * ignore them. Just that they are not persistent. */ mon_feature_t optional_features; /** * Returns the set of features required by this monmap. * * The features required by this monmap is the union of all the * currently set persistent features and the currently set optional * features. * * @returns the set of features required by this monmap */ mon_feature_t get_required_features() const { return (persistent_features | optional_features); } // upgrade gate ceph_release_t min_mon_release{ceph_release_t::unknown}; void _add_ambiguous_addr(const std::string& name, entity_addr_t addr, int priority, int weight, bool for_mkfs); enum election_strategy { // Keep in sync with ElectionLogic.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 = CLASSIC; std::set<std::string> disallowed_leaders; // can't be leader under CONNECTIVITY/DISALLOW bool stretch_mode_enabled = false; std::string tiebreaker_mon; std::set<std::string> stretch_marked_down_mons; // can't be leader until fully recovered public: void calc_legacy_ranks(); void calc_addr_mons() { // populate addr_mons addr_mons.clear(); for (auto& p : mon_info) { for (auto& a : p.second.public_addrs.v) { addr_mons[a] = p.first; } } } MonMap() : epoch(0) { } uuid_d& get_fsid() { return fsid; } unsigned size() const { return mon_info.size(); } unsigned min_quorum_size(unsigned total_mons=0) const { if (total_mons == 0) { total_mons = size(); } return total_mons / 2 + 1; } epoch_t get_epoch() const { return epoch; } void set_epoch(epoch_t e) { epoch = e; } /** * Obtain list of public facing addresses * * @param ls list to populate with the monitors' addresses */ void list_addrs(std::list<entity_addr_t>& ls) const { for (auto& i : mon_info) { for (auto& j : i.second.public_addrs.v) { ls.push_back(j); } } } /** * Add new monitor to the monmap * * @param m monitor info of the new monitor */ void add(const mon_info_t& m) { ceph_assert(mon_info.count(m.name) == 0); for (auto& a : m.public_addrs.v) { ceph_assert(addr_mons.count(a) == 0); } mon_info[m.name] = m; if (get_required_features().contains_all( ceph::features::mon::FEATURE_NAUTILUS)) { ranks.push_back(m.name); ceph_assert(ranks.size() == mon_info.size()); } else { calc_legacy_ranks(); } calc_addr_mons(); } /** * Add new monitor to the monmap * * @param name Monitor name (i.e., 'foo' in 'mon.foo') * @param addr Monitor's public address */ void add(const std::string &name, const entity_addrvec_t &addrv, uint16_t priority=0, uint16_t weight=0) { add(mon_info_t(name, addrv, priority, weight)); } /** * Remove monitor from the monmap * * @param name Monitor name (i.e., 'foo' in 'mon.foo') */ void remove(const std::string &name) { // this must match what we do in ConnectionTracker::notify_rank_removed ceph_assert(mon_info.count(name)); int rank = get_rank(name); mon_info.erase(name); disallowed_leaders.erase(name); ceph_assert(mon_info.count(name) == 0); if (rank >= 0 ) { removed_ranks.insert(rank); } if (get_required_features().contains_all( ceph::features::mon::FEATURE_NAUTILUS)) { ranks.erase(std::find(ranks.begin(), ranks.end(), name)); ceph_assert(ranks.size() == mon_info.size()); } else { calc_legacy_ranks(); } calc_addr_mons(); } /** * Rename monitor from @p oldname to @p newname * * @param oldname monitor's current name (i.e., 'foo' in 'mon.foo') * @param newname monitor's new name (i.e., 'bar' in 'mon.bar') */ void rename(std::string oldname, std::string newname) { ceph_assert(contains(oldname)); ceph_assert(!contains(newname)); mon_info[newname] = mon_info[oldname]; mon_info.erase(oldname); mon_info[newname].name = newname; if (get_required_features().contains_all( ceph::features::mon::FEATURE_NAUTILUS)) { *std::find(ranks.begin(), ranks.end(), oldname) = newname; ceph_assert(ranks.size() == mon_info.size()); } else { calc_legacy_ranks(); } calc_addr_mons(); } int set_rank(const std::string& name, int rank) { int oldrank = get_rank(name); if (oldrank < 0) { return -ENOENT; } if (rank < 0 || rank >= (int)ranks.size()) { return -EINVAL; } if (oldrank != rank) { ranks.erase(ranks.begin() + oldrank); ranks.insert(ranks.begin() + rank, name); } return 0; } bool contains(const std::string& name) const { return mon_info.count(name); } /** * Check if monmap contains a monitor with address @p a * * @note checks for all addresses a monitor may have, public or otherwise. * * @param a monitor address * @returns true if monmap contains a monitor with address @p; * false otherwise. */ bool contains(const entity_addr_t &a, std::string *name=nullptr) const { for (auto& i : mon_info) { for (auto& j : i.second.public_addrs.v) { if (j == a) { if (name) { *name = i.first; } return true; } } } return false; } bool contains(const entity_addrvec_t &av, std::string *name=nullptr) const { for (auto& i : mon_info) { for (auto& j : i.second.public_addrs.v) { for (auto& k : av.v) { if (j == k) { if (name) { *name = i.first; } return true; } } } } return false; } std::string get_name(unsigned n) const { ceph_assert(n < ranks.size()); return ranks[n]; } std::string get_name(const entity_addr_t& a) const { std::map<entity_addr_t, std::string>::const_iterator p = addr_mons.find(a); if (p == addr_mons.end()) return std::string(); else return p->second; } std::string get_name(const entity_addrvec_t& av) const { for (auto& i : av.v) { std::map<entity_addr_t, std::string>::const_iterator p = addr_mons.find(i); if (p != addr_mons.end()) return p->second; } return std::string(); } int get_rank(const std::string& n) const { if (auto found = std::find(ranks.begin(), ranks.end(), n); found != ranks.end()) { return std::distance(ranks.begin(), found); } else { return -1; } } int get_rank(const entity_addr_t& a) const { std::string n = get_name(a); if (!n.empty()) { return get_rank(n); } return -1; } int get_rank(const entity_addrvec_t& av) const { std::string n = get_name(av); if (!n.empty()) { return get_rank(n); } return -1; } bool get_addr_name(const entity_addr_t& a, std::string& name) { if (addr_mons.count(a) == 0) return false; name = addr_mons[a]; return true; } const entity_addrvec_t& get_addrs(const std::string& n) const { ceph_assert(mon_info.count(n)); std::map<std::string,mon_info_t>::const_iterator p = mon_info.find(n); return p->second.public_addrs; } const entity_addrvec_t& get_addrs(unsigned m) const { ceph_assert(m < ranks.size()); return get_addrs(ranks[m]); } void set_addrvec(const std::string& n, const entity_addrvec_t& a) { ceph_assert(mon_info.count(n)); mon_info[n].public_addrs = a; calc_addr_mons(); } uint16_t get_priority(const std::string& n) const { auto it = mon_info.find(n); ceph_assert(it != mon_info.end()); return it->second.priority; } uint16_t get_weight(const std::string& n) const { auto it = mon_info.find(n); ceph_assert(it != mon_info.end()); return it->second.weight; } void set_weight(const std::string& n, uint16_t v) { auto it = mon_info.find(n); ceph_assert(it != mon_info.end()); it->second.weight = v; } void encode(ceph::buffer::list& blist, uint64_t con_features) const; void decode(ceph::buffer::list& blist) { auto p = std::cbegin(blist); decode(p); } void decode(ceph::buffer::list::const_iterator& p); void generate_fsid() { fsid.generate_random(); } // read from/write to a file int write(const char *fn); int read(const char *fn); /** * build an initial bootstrap monmap from conf * * Build an initial bootstrap monmap from the config. This will * try, in this order: * * 1 monmap -- an explicitly provided monmap * 2 mon_host -- list of monitors * 3 config [mon.*] sections, and 'mon addr' fields in those sections * * @param cct context (and associated config) * @param errout std::ostream to send error messages too */ #ifdef WITH_SEASTAR seastar::future<> build_initial(const crimson::common::ConfigProxy& conf, bool for_mkfs); #else int build_initial(CephContext *cct, bool for_mkfs, std::ostream& errout); #endif /** * filter monmap given a set of initial members. * * Remove mons that aren't in the initial_members list. Add missing * mons and give them dummy IPs (blank IPv4, with a non-zero * nonce). If the name matches my_name, then my_addr will be used in * place of a dummy addr. * * @param initial_members list of initial member names * @param my_name name of self, can be blank * @param my_addr my addr * @param removed optional pointer to set to insert removed mon addrs to */ void set_initial_members(CephContext *cct, std::list<std::string>& initial_members, std::string my_name, const entity_addrvec_t& my_addrs, std::set<entity_addrvec_t> *removed); void print(std::ostream& out) const; void print_summary(std::ostream& out) const; void dump(ceph::Formatter *f) const; void dump_summary(ceph::Formatter *f) const; void check_health(health_check_map_t *checks) const; static void generate_test_instances(std::list<MonMap*>& o); protected: /** * build a monmap from a list of entity_addrvec_t's * * Give mons dummy names. * * @param addrs list of entity_addrvec_t's * @param prefix prefix to prepend to generated mon names */ void init_with_addrs(const std::vector<entity_addrvec_t>& addrs, bool for_mkfs, std::string_view prefix); /** * build a monmap from a list of ips * * Give mons dummy names. * * @param hosts list of ips, space or comma separated * @param prefix prefix to prepend to generated mon names * @return 0 for success, -errno on error */ int init_with_ips(const std::string& ips, bool for_mkfs, std::string_view prefix); /** * build a monmap from a list of hostnames * * Give mons dummy names. * * @param hosts list of ips, space or comma separated * @param prefix prefix to prepend to generated mon names * @return 0 for success, -errno on error */ int init_with_hosts(const std::string& hostlist, bool for_mkfs, std::string_view prefix); int init_with_config_file(const ConfigProxy& conf, std::ostream& errout); #if WITH_SEASTAR seastar::future<> read_monmap(const std::string& monmap); /// try to build monmap with different settings, like /// mon_host, mon* sections, and mon_dns_srv_name seastar::future<> build_monmap(const crimson::common::ConfigProxy& conf, bool for_mkfs); /// initialize monmap by resolving given service name seastar::future<> init_with_dns_srv(bool for_mkfs, const std::string& name); /// initialize monmap with `mon_host` or `mon_host_override` bool maybe_init_with_mon_host(const std::string& mon_host, bool for_mkfs); #else /// read from encoded monmap file int init_with_monmap(const std::string& monmap, std::ostream& errout); int init_with_dns_srv(CephContext* cct, std::string srv_name, bool for_mkfs, std::ostream& errout); #endif }; WRITE_CLASS_ENCODER_FEATURES(MonMap) inline std::ostream& operator<<(std::ostream &out, const MonMap &m) { m.print_summary(out); return out; } #endif
15,679
27.56102
91
h
null
ceph-main/src/mon/MonOpRequest.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 <[email protected]> * Copyright (C) 2015 SUSE LINUX GmbH * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. */ #ifndef MON_OPREQUEST_H_ #define MON_OPREQUEST_H_ #include <iosfwd> #include <stdint.h> #include "common/TrackedOp.h" #include "mon/Session.h" #include "msg/Message.h" struct MonOpRequest : public TrackedOp { friend class OpTracker; void mark_dispatch() { mark_event("monitor_dispatch"); } void mark_wait_for_quorum() { mark_event("wait_for_quorum"); } void mark_zap() { mark_event("monitor_zap"); } void mark_forwarded() { mark_event("forwarded"); forwarded_to_leader = true; } void mark_svc_event(const std::string &service, const std::string &event) { std::string s = service; s.append(":").append(event); mark_event(s); } void mark_logmon_event(const std::string &event) { mark_svc_event("logm", event); } void mark_osdmon_event(const std::string &event) { mark_svc_event("osdmap", event); } void mark_pgmon_event(const std::string &event) { mark_svc_event("pgmap", event); } void mark_mdsmon_event(const std::string &event) { mark_svc_event("mdsmap", event); } void mark_authmon_event(const std::string &event) { mark_svc_event("auth", event); } void mark_paxos_event(const std::string &event) { mark_svc_event("paxos", event); } enum op_type_t { OP_TYPE_NONE = 0, ///< no type defined (default) OP_TYPE_SERVICE, ///< belongs to a Paxos Service or similar OP_TYPE_MONITOR, ///< belongs to the Monitor class OP_TYPE_ELECTION, ///< belongs to the Elector class OP_TYPE_PAXOS, ///< refers to Paxos messages OP_TYPE_COMMAND, ///< is a command }; MonOpRequest(const MonOpRequest &other) = delete; MonOpRequest & operator = (const MonOpRequest &other) = delete; private: Message *request; utime_t dequeued_time; RefCountedPtr session; ConnectionRef con; bool forwarded_to_leader; op_type_t op_type; MonOpRequest(Message *req, OpTracker *tracker) : TrackedOp(tracker, req->get_recv_stamp().is_zero() ? ceph_clock_now() : req->get_recv_stamp()), request(req), con(NULL), forwarded_to_leader(false), op_type(OP_TYPE_NONE) { if (req) { con = req->get_connection(); if (con) { session = con->get_priv(); } } } void _dump(ceph::Formatter *f) const override { { f->open_array_section("events"); std::lock_guard l(lock); for (auto i = events.begin(); i != events.end(); ++i) { f->open_object_section("event"); f->dump_string("event", i->str); f->dump_stream("time") << i->stamp; auto i_next = i + 1; if (i_next < events.end()) { f->dump_float("duration", i_next->stamp - i->stamp); } else { f->dump_float("duration", events.rbegin()->stamp - get_initiated()); } f->close_section(); } f->close_section(); f->open_object_section("info"); f->dump_int("seq", seq); f->dump_bool("src_is_mon", is_src_mon()); f->dump_stream("source") << request->get_source_inst(); f->dump_bool("forwarded_to_leader", forwarded_to_leader); f->close_section(); } } protected: void _dump_op_descriptor_unlocked(std::ostream& stream) const override { get_req()->print(stream); } public: ~MonOpRequest() override { request->put(); } MonSession *get_session() const { return static_cast<MonSession*>(session.get()); } template<class T> T *get_req() const { return static_cast<T*>(request); } Message *get_req() const { return get_req<Message>(); } int get_req_type() const { if (!request) return 0; return request->get_type(); } ConnectionRef get_connection() { return con; } void set_session(MonSession *s) { session.reset(s); } bool is_src_mon() const { return (con && con->get_peer_type() & CEPH_ENTITY_TYPE_MON); } typedef boost::intrusive_ptr<MonOpRequest> Ref; void set_op_type(op_type_t t) { op_type = t; } void set_type_service() { set_op_type(OP_TYPE_SERVICE); } void set_type_monitor() { set_op_type(OP_TYPE_MONITOR); } void set_type_paxos() { set_op_type(OP_TYPE_PAXOS); } void set_type_election_or_ping() { set_op_type(OP_TYPE_ELECTION); } void set_type_command() { set_op_type(OP_TYPE_COMMAND); } op_type_t get_op_type() { return op_type; } bool is_type_service() { return (get_op_type() == OP_TYPE_SERVICE); } bool is_type_monitor() { return (get_op_type() == OP_TYPE_MONITOR); } bool is_type_paxos() { return (get_op_type() == OP_TYPE_PAXOS); } bool is_type_election_or_ping() { return (get_op_type() == OP_TYPE_ELECTION); } bool is_type_command() { return (get_op_type() == OP_TYPE_COMMAND); } }; typedef MonOpRequest::Ref MonOpRequestRef; struct C_MonOp : public Context { MonOpRequestRef op; explicit C_MonOp(MonOpRequestRef o) : op(o) { } void finish(int r) override { if (op && r == -ECANCELED) { op->mark_event("callback canceled"); } else if (op && r == -EAGAIN) { op->mark_event("callback retry"); } else if (op && r == 0) { op->mark_event("callback finished"); } _finish(r); } void mark_op_event(const std::string &event) { if (op) op->mark_event(event); } virtual void _finish(int r) = 0; }; #endif /* MON_OPREQUEST_H_ */
5,825
23.376569
77
h
null
ceph-main/src/mon/MonSub.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 <string> #include "common/ceph_time.h" #include "include/types.h" // mon subscriptions class MonSub { public: // @returns true if there is any "new" subscriptions bool have_new() const; auto get_subs() const { return sub_new; } bool need_renew() const; // change the status of "new" subscriptions to "sent" void renewed(); // the peer acked the subscription request void acked(uint32_t interval); void got(const std::string& what, version_t version); // revert the status of subscriptions from "sent" to "new" // @returns true if there is any pending "new" subscriptions bool reload(); // add a new subscription bool want(const std::string& what, version_t start, unsigned flags); // increment the requested subscription start point. If you do increase // the value, apply the passed-in flags as well; otherwise do nothing. bool inc_want(const std::string& what, version_t start, unsigned flags); // cancel a subscription void unwant(const std::string& what); private: // my subs, and current versions std::map<std::string,ceph_mon_subscribe_item> sub_sent; // unsent new subs std::map<std::string,ceph_mon_subscribe_item> sub_new; using time_point = ceph::coarse_mono_time; using clock = typename time_point::clock; time_point renew_sent; time_point renew_after; };
1,466
30.212766
74
h
null
ceph-main/src/mon/MonitorDBStore.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. */ #ifndef CEPH_MONITOR_DB_STORE_H #define CEPH_MONITOR_DB_STORE_H #include "include/types.h" #include "include/buffer.h" #include <set> #include <map> #include <string> #include <boost/scoped_ptr.hpp> #include <sstream> #include <fstream> #include "kv/KeyValueDB.h" #include "include/ceph_assert.h" #include "common/Formatter.h" #include "common/Finisher.h" #include "common/errno.h" #include "common/debug.h" #include "common/safe_io.h" #include "common/blkdev.h" #include "common/PriorityCache.h" #define dout_context g_ceph_context class MonitorDBStore { std::string path; boost::scoped_ptr<KeyValueDB> db; bool do_dump; int dump_fd_binary; std::ofstream dump_fd_json; ceph::JSONFormatter dump_fmt; Finisher io_work; bool is_open; public: std::string get_devname() { char devname[4096] = {0}, partition[4096]; get_device_by_path(path.c_str(), partition, devname, sizeof(devname)); return devname; } std::string get_path() { return path; } std::shared_ptr<PriorityCache::PriCache> get_priority_cache() const { return db->get_priority_cache(); } struct Op { uint8_t type; std::string prefix; std::string key, endkey; ceph::buffer::list bl; Op() : type(0) { } Op(int t, const std::string& p, const std::string& k) : type(t), prefix(p), key(k) { } Op(int t, const std::string& p, const std::string& k, const ceph::buffer::list& b) : type(t), prefix(p), key(k), bl(b) { } Op(int t, const std::string& p, const std::string& start, const std::string& end) : type(t), prefix(p), key(start), endkey(end) { } void encode(ceph::buffer::list& encode_bl) const { ENCODE_START(2, 1, encode_bl); encode(type, encode_bl); encode(prefix, encode_bl); encode(key, encode_bl); encode(bl, encode_bl); encode(endkey, encode_bl); ENCODE_FINISH(encode_bl); } void decode(ceph::buffer::list::const_iterator& decode_bl) { DECODE_START(2, decode_bl); decode(type, decode_bl); decode(prefix, decode_bl); decode(key, decode_bl); decode(bl, decode_bl); if (struct_v >= 2) decode(endkey, decode_bl); DECODE_FINISH(decode_bl); } void dump(ceph::Formatter *f) const { f->dump_int("type", type); f->dump_string("prefix", prefix); f->dump_string("key", key); if (endkey.length()) { f->dump_string("endkey", endkey); } } int approx_size() const { return 6 + 1 + 4 + prefix.size() + 4 + key.size() + 4 + endkey.size() + 4 + bl.length(); } static void generate_test_instances(std::list<Op*>& ls) { ls.push_back(new Op); // we get coverage here from the Transaction instances } }; struct Transaction; typedef std::shared_ptr<Transaction> TransactionRef; struct Transaction { std::list<Op> ops; uint64_t bytes, keys; Transaction() : bytes(6 + 4 + 8*2), keys(0) {} enum { OP_PUT = 1, OP_ERASE = 2, OP_COMPACT = 3, OP_ERASE_RANGE = 4, }; void put(const std::string& prefix, const std::string& key, const ceph::buffer::list& bl) { ops.push_back(Op(OP_PUT, prefix, key, bl)); ++keys; bytes += ops.back().approx_size(); } void put(const std::string& prefix, version_t ver, const ceph::buffer::list& bl) { std::ostringstream os; os << ver; put(prefix, os.str(), bl); } void put(const std::string& prefix, const std::string& key, version_t ver) { using ceph::encode; ceph::buffer::list bl; encode(ver, bl); put(prefix, key, bl); } void erase(const std::string& prefix, const std::string& key) { ops.push_back(Op(OP_ERASE, prefix, key)); ++keys; bytes += ops.back().approx_size(); } void erase(const std::string& prefix, version_t ver) { std::ostringstream os; os << ver; erase(prefix, os.str()); } void erase_range(const std::string& prefix, const std::string& begin, const std::string& end) { ops.push_back(Op(OP_ERASE_RANGE, prefix, begin, end)); ++keys; bytes += ops.back().approx_size(); } void compact_prefix(const std::string& prefix) { ops.push_back(Op(OP_COMPACT, prefix, {})); } void compact_range(const std::string& prefix, const std::string& start, const std::string& end) { ops.push_back(Op(OP_COMPACT, prefix, start, end)); } void encode(ceph::buffer::list& bl) const { ENCODE_START(2, 1, bl); encode(ops, bl); encode(bytes, bl); encode(keys, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { DECODE_START(2, bl); decode(ops, bl); if (struct_v >= 2) { decode(bytes, bl); decode(keys, bl); } DECODE_FINISH(bl); } static void generate_test_instances(std::list<Transaction*>& ls) { ls.push_back(new Transaction); ls.push_back(new Transaction); ceph::buffer::list bl; bl.append("value"); ls.back()->put("prefix", "key", bl); ls.back()->erase("prefix2", "key2"); ls.back()->erase_range("prefix3", "key3", "key4"); ls.back()->compact_prefix("prefix3"); ls.back()->compact_range("prefix4", "from", "to"); } void append(TransactionRef other) { ops.splice(ops.end(), other->ops); keys += other->keys; bytes += other->bytes; } void append_from_encoded(ceph::buffer::list& bl) { auto other(std::make_shared<Transaction>()); auto it = bl.cbegin(); other->decode(it); append(other); } bool empty() { return (size() == 0); } size_t size() const { return ops.size(); } uint64_t get_keys() const { return keys; } uint64_t get_bytes() const { return bytes; } void dump(ceph::Formatter *f, bool dump_val=false) const { f->open_object_section("transaction"); f->open_array_section("ops"); int op_num = 0; for (auto it = ops.begin(); it != ops.end(); ++it) { const Op& op = *it; f->open_object_section("op"); f->dump_int("op_num", op_num++); switch (op.type) { case OP_PUT: { f->dump_string("type", "PUT"); f->dump_string("prefix", op.prefix); f->dump_string("key", op.key); f->dump_unsigned("length", op.bl.length()); if (dump_val) { std::ostringstream os; op.bl.hexdump(os); f->dump_string("bl", os.str()); } } break; case OP_ERASE: { f->dump_string("type", "ERASE"); f->dump_string("prefix", op.prefix); f->dump_string("key", op.key); } break; case OP_ERASE_RANGE: { f->dump_string("type", "ERASE_RANGE"); f->dump_string("prefix", op.prefix); f->dump_string("start", op.key); f->dump_string("end", op.endkey); } break; case OP_COMPACT: { f->dump_string("type", "COMPACT"); f->dump_string("prefix", op.prefix); f->dump_string("start", op.key); f->dump_string("end", op.endkey); } break; default: { f->dump_string("type", "unknown"); f->dump_unsigned("op_code", op.type); break; } } f->close_section(); } f->close_section(); f->dump_unsigned("num_keys", keys); f->dump_unsigned("num_bytes", bytes); f->close_section(); } }; int apply_transaction(MonitorDBStore::TransactionRef t) { KeyValueDB::Transaction dbt = db->get_transaction(); if (do_dump) { if (!g_conf()->mon_debug_dump_json) { ceph::buffer::list bl; t->encode(bl); bl.write_fd(dump_fd_binary); } else { t->dump(&dump_fmt, true); dump_fmt.flush(dump_fd_json); dump_fd_json.flush(); } } std::list<std::pair<std::string, std::pair<std::string,std::string>>> compact; for (auto it = t->ops.begin(); it != t->ops.end(); ++it) { const Op& op = *it; switch (op.type) { case Transaction::OP_PUT: dbt->set(op.prefix, op.key, op.bl); break; case Transaction::OP_ERASE: dbt->rmkey(op.prefix, op.key); break; case Transaction::OP_ERASE_RANGE: dbt->rm_range_keys(op.prefix, op.key, op.endkey); break; case Transaction::OP_COMPACT: compact.push_back(make_pair(op.prefix, make_pair(op.key, op.endkey))); break; default: derr << __func__ << " unknown op type " << op.type << dendl; ceph_abort(); break; } } int r = db->submit_transaction_sync(dbt); if (r >= 0) { while (!compact.empty()) { if (compact.front().second.first == std::string() && compact.front().second.second == std::string()) db->compact_prefix_async(compact.front().first); else db->compact_range_async(compact.front().first, compact.front().second.first, compact.front().second.second); compact.pop_front(); } } else { ceph_abort_msg("failed to write to db"); } return r; } struct C_DoTransaction : public Context { MonitorDBStore *store; MonitorDBStore::TransactionRef t; Context *oncommit; C_DoTransaction(MonitorDBStore *s, MonitorDBStore::TransactionRef t, Context *f) : store(s), t(t), oncommit(f) {} void finish(int r) override { /* The store serializes writes. Each transaction is handled * sequentially by the io_work Finisher. If a transaction takes longer * to apply its state to permanent storage, then no other transaction * will be handled meanwhile. * * We will now randomly inject random delays. We can safely sleep prior * to applying the transaction as it won't break the model. */ double delay_prob = g_conf()->mon_inject_transaction_delay_probability; if (delay_prob && (rand() % 10000 < delay_prob * 10000.0)) { utime_t delay; double delay_max = g_conf()->mon_inject_transaction_delay_max; delay.set_from_double(delay_max * (double)(rand() % 10000) / 10000.0); lsubdout(g_ceph_context, mon, 1) << "apply_transaction will be delayed for " << delay << " seconds" << dendl; delay.sleep(); } int ret = store->apply_transaction(t); oncommit->complete(ret); } }; /** * queue transaction * * Queue a transaction to commit asynchronously. Trigger a context * on completion (without any locks held). */ void queue_transaction(MonitorDBStore::TransactionRef t, Context *oncommit) { io_work.queue(new C_DoTransaction(this, t, oncommit)); } /** * block and flush all io activity */ void flush() { io_work.wait_for_empty(); } class StoreIteratorImpl { protected: bool done; std::pair<std::string,std::string> last_key; ceph::buffer::list crc_bl; StoreIteratorImpl() : done(false) { } virtual ~StoreIteratorImpl() { } virtual bool _is_valid() = 0; public: __u32 crc() { if (g_conf()->mon_sync_debug) return crc_bl.crc32c(0); return 0; } std::pair<std::string,std::string> get_last_key() { return last_key; } virtual bool has_next_chunk() { return !done && _is_valid(); } virtual void get_chunk_tx(TransactionRef tx, uint64_t max_bytes, uint64_t max_keys) = 0; virtual std::pair<std::string,std::string> get_next_key() = 0; }; typedef std::shared_ptr<StoreIteratorImpl> Synchronizer; class WholeStoreIteratorImpl : public StoreIteratorImpl { KeyValueDB::WholeSpaceIterator iter; std::set<std::string> sync_prefixes; public: WholeStoreIteratorImpl(KeyValueDB::WholeSpaceIterator iter, std::set<std::string> &prefixes) : StoreIteratorImpl(), iter(iter), sync_prefixes(prefixes) { } ~WholeStoreIteratorImpl() override { } /** * Obtain a chunk of the store * * @param bl Encoded transaction that will recreate the chunk * @param first_key Pair containing the first key to obtain, and that * will contain the first key in the chunk (that may * differ from the one passed on to the function) * @param last_key[out] Last key in the chunk */ void get_chunk_tx(TransactionRef tx, uint64_t max_bytes, uint64_t max_keys) override { using ceph::encode; ceph_assert(done == false); ceph_assert(iter->valid() == true); while (iter->valid()) { std::string prefix(iter->raw_key().first); std::string key(iter->raw_key().second); if (sync_prefixes.count(prefix)) { ceph::buffer::list value = iter->value(); if (tx->empty() || (tx->get_bytes() + value.length() + key.size() + prefix.size() < max_bytes && tx->get_keys() < max_keys)) { // NOTE: putting every key in a separate transaction is // questionable as far as efficiency goes auto tmp(std::make_shared<Transaction>()); tmp->put(prefix, key, value); tx->append(tmp); if (g_conf()->mon_sync_debug) { encode(prefix, crc_bl); encode(key, crc_bl); encode(value, crc_bl); } } else { last_key.first = prefix; last_key.second = key; return; } } iter->next(); } ceph_assert(iter->valid() == false); done = true; } std::pair<std::string,std::string> get_next_key() override { ceph_assert(iter->valid()); for (; iter->valid(); iter->next()) { std::pair<std::string,std::string> r = iter->raw_key(); if (sync_prefixes.count(r.first) > 0) { iter->next(); return r; } } return std::pair<std::string,std::string>(); } bool _is_valid() override { return iter->valid(); } }; Synchronizer get_synchronizer(std::pair<std::string,std::string> &key, std::set<std::string> &prefixes) { KeyValueDB::WholeSpaceIterator iter; iter = db->get_wholespace_iterator(); if (!key.first.empty() && !key.second.empty()) iter->upper_bound(key.first, key.second); else iter->seek_to_first(); return std::shared_ptr<StoreIteratorImpl>( new WholeStoreIteratorImpl(iter, prefixes) ); } KeyValueDB::Iterator get_iterator(const std::string &prefix) { ceph_assert(!prefix.empty()); KeyValueDB::Iterator iter = db->get_iterator(prefix); iter->seek_to_first(); return iter; } KeyValueDB::WholeSpaceIterator get_iterator() { KeyValueDB::WholeSpaceIterator iter; iter = db->get_wholespace_iterator(); iter->seek_to_first(); return iter; } int get(const std::string& prefix, const std::string& key, ceph::buffer::list& bl) { ceph_assert(bl.length() == 0); return db->get(prefix, key, &bl); } int get(const std::string& prefix, const version_t ver, ceph::buffer::list& bl) { std::ostringstream os; os << ver; return get(prefix, os.str(), bl); } version_t get(const std::string& prefix, const std::string& key) { using ceph::decode; ceph::buffer::list bl; int err = get(prefix, key, bl); if (err < 0) { if (err == -ENOENT) // if key doesn't exist, assume its value is 0 return 0; // we're not expecting any other negative return value, and we can't // just return a negative value if we're returning a version_t generic_dout(0) << "MonitorDBStore::get() error obtaining" << " (" << prefix << ":" << key << "): " << cpp_strerror(err) << dendl; ceph_abort_msg("error obtaining key"); } ceph_assert(bl.length()); version_t ver; auto p = bl.cbegin(); decode(ver, p); return ver; } bool exists(const std::string& prefix, const std::string& key) { KeyValueDB::Iterator it = db->get_iterator(prefix); int err = it->lower_bound(key); if (err < 0) return false; return (it->valid() && it->key() == key); } bool exists(const std::string& prefix, version_t ver) { std::ostringstream os; os << ver; return exists(prefix, os.str()); } std::string combine_strings(const std::string& prefix, const std::string& value) { std::string out = prefix; out.push_back('_'); out.append(value); return out; } std::string combine_strings(const std::string& prefix, const version_t ver) { std::ostringstream os; os << ver; return combine_strings(prefix, os.str()); } void clear(std::set<std::string>& prefixes) { KeyValueDB::Transaction dbt = db->get_transaction(); for (auto iter = prefixes.begin(); iter != prefixes.end(); ++iter) { dbt->rmkeys_by_prefix((*iter)); } int r = db->submit_transaction_sync(dbt); ceph_assert(r >= 0); } void _open(const std::string& kv_type) { int pos = 0; for (auto rit = path.rbegin(); rit != path.rend(); ++rit, ++pos) { if (*rit != '/') break; } std::ostringstream os; os << path.substr(0, path.size() - pos) << "/store.db"; std::string full_path = os.str(); KeyValueDB *db_ptr = KeyValueDB::create(g_ceph_context, kv_type, full_path); if (!db_ptr) { derr << __func__ << " error initializing " << kv_type << " db back storage in " << full_path << dendl; ceph_abort_msg("MonitorDBStore: error initializing keyvaluedb back storage"); } db.reset(db_ptr); if (g_conf()->mon_debug_dump_transactions) { if (!g_conf()->mon_debug_dump_json) { dump_fd_binary = ::open( g_conf()->mon_debug_dump_location.c_str(), O_CREAT|O_APPEND|O_WRONLY|O_CLOEXEC, 0644); if (dump_fd_binary < 0) { dump_fd_binary = -errno; derr << "Could not open log file, got " << cpp_strerror(dump_fd_binary) << dendl; } } else { dump_fmt.reset(); dump_fmt.open_array_section("dump"); dump_fd_json.open(g_conf()->mon_debug_dump_location.c_str()); } do_dump = true; } if (kv_type == "rocksdb") db->init(g_conf()->mon_rocksdb_options); else db->init(); } int open(std::ostream &out) { std::string kv_type; int r = read_meta("kv_backend", &kv_type); if (r < 0 || kv_type.empty()) { // assume old monitors that did not mark the type were RocksDB. kv_type = "rocksdb"; r = write_meta("kv_backend", kv_type); if (r < 0) return r; } _open(kv_type); r = db->open(out); if (r < 0) return r; // Monitors are few in number, so the resource cost of exposing // very detailed stats is low: ramp up the priority of all the // KV store's perf counters. Do this after open, because backend may // not have constructed PerfCounters earlier. if (db->get_perf_counters()) { db->get_perf_counters()->set_prio_adjust( PerfCountersBuilder::PRIO_USEFUL - PerfCountersBuilder::PRIO_DEBUGONLY); } io_work.start(); is_open = true; return 0; } int create_and_open(std::ostream &out) { // record the type before open std::string kv_type; int r = read_meta("kv_backend", &kv_type); if (r < 0) { kv_type = g_conf()->mon_keyvaluedb; r = write_meta("kv_backend", kv_type); if (r < 0) return r; } _open(kv_type); r = db->create_and_open(out); if (r < 0) return r; io_work.start(); is_open = true; return 0; } void close() { // there should be no work queued! io_work.stop(); is_open = false; db.reset(NULL); } void compact() { db->compact(); } void compact_async() { db->compact_async(); } void compact_prefix(const std::string& prefix) { db->compact_prefix(prefix); } uint64_t get_estimated_size(std::map<std::string, uint64_t> &extras) { return db->get_estimated_size(extras); } /** * write_meta - write a simple configuration key out-of-band * * Write a simple key/value pair for basic store configuration * (e.g., a uuid or magic number) to an unopened/unmounted store. * The default implementation writes this to a plaintext file in the * path. * * A newline is appended. * * @param key key name (e.g., "fsid") * @param value value (e.g., a uuid rendered as a string) * @returns 0 for success, or an error code */ int write_meta(const std::string& key, const std::string& value) const { std::string v = value; v += "\n"; int r = safe_write_file(path.c_str(), key.c_str(), v.c_str(), v.length(), 0600); if (r < 0) return r; return 0; } /** * read_meta - read a simple configuration key out-of-band * * Read a simple key value to an unopened/mounted store. * * Trailing whitespace is stripped off. * * @param key key name * @param value pointer to value string * @returns 0 for success, or an error code */ int read_meta(const std::string& key, std::string *value) const { char buf[4096]; int r = safe_read_file(path.c_str(), key.c_str(), buf, sizeof(buf)); if (r <= 0) return r; // drop trailing newlines while (r && isspace(buf[r-1])) { --r; } *value = std::string(buf, r); return 0; } explicit MonitorDBStore(const std::string& path) : path(path), db(0), do_dump(false), dump_fd_binary(-1), dump_fmt(true), io_work(g_ceph_context, "monstore", "fn_monstore"), is_open(false) { } ~MonitorDBStore() { ceph_assert(!is_open); if (do_dump) { if (!g_conf()->mon_debug_dump_json) { ::close(dump_fd_binary); } else { dump_fmt.close_section(); dump_fmt.flush(dump_fd_json); dump_fd_json.flush(); dump_fd_json.close(); } } } }; WRITE_CLASS_ENCODER(MonitorDBStore::Op) WRITE_CLASS_ENCODER(MonitorDBStore::Transaction) #endif /* CEPH_MONITOR_DB_STORE_H */
22,224
26.269939
111
h
null
ceph-main/src/mon/MonmapMonitor.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) 2009 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. * */ /* * The Monmap Monitor is used to track the monitors in the cluster. */ #ifndef CEPH_MONMAPMONITOR_H #define CEPH_MONMAPMONITOR_H #include <map> #include <set> #include "include/types.h" #include "msg/Messenger.h" #include "PaxosService.h" #include "MonMap.h" #include "MonitorDBStore.h" class MonmapMonitor : public PaxosService { public: MonmapMonitor(Monitor &mn, Paxos &p, const std::string& service_name) : PaxosService(mn, p, service_name) { } MonMap pending_map; //the pending map awaiting passage void create_initial() override; void update_from_paxos(bool *need_bootstrap) override; void create_pending() override; void encode_pending(MonitorDBStore::TransactionRef t) override; // we always encode the full map; we have no use for full versions void encode_full(MonitorDBStore::TransactionRef t) override { } void on_active() override; void apply_mon_features(const mon_feature_t& features, ceph_release_t min_mon_release); void dump_info(ceph::Formatter *f); bool preprocess_query(MonOpRequestRef op) override; bool prepare_update(MonOpRequestRef op) override; bool preprocess_join(MonOpRequestRef op); bool prepare_join(MonOpRequestRef op); bool preprocess_command(MonOpRequestRef op); bool prepare_command(MonOpRequestRef op); int get_monmap(ceph::buffer::list &bl); /* * Since monitors are pretty * important, this implementation will just write 0.0. */ bool should_propose(double& delay) override; void check_sub(Subscription *sub); void tick() override; private: void check_subs(); ceph::buffer::list monmap_bl; /** * Check validity of inputs and monitor state to * engage stretch mode. Designed to be used with * OSDMonitor::try_enable_stretch_mode() where we call both twice, * first with commit=false to validate. * @param ss: a stringstream to write errors into * @param okay: Filled to true if okay, false if validation fails * @param errcode: filled with -errno if there's a problem * @param commit: true if we should commit the change, false if just testing * @param tiebreaker_mon: the name of the monitor to declare tiebreaker * @param dividing_bucket: the bucket type (eg 'dc') that divides the cluster */ void try_enable_stretch_mode(std::stringstream& ss, bool *okay, int *errcode, bool commit, const std::string& tiebreaker_mon, const std::string& dividing_bucket); public: /** * Set us to degraded stretch mode. Put the dead_mons in * the MonMap. */ void trigger_degraded_stretch_mode(const std::set<std::string>& dead_mons); /** * Set us to healthy stretch mode: clear out the * down list to allow any non-tiebreaker mon to be the leader again. */ void trigger_healthy_stretch_mode(); }; #endif
3,239
27.928571
79
h
null
ceph-main/src/mon/PGMap.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. * */ /* * Placement Group Map. Placement Groups are logical sets of objects * that are replicated by the same set of devices. pgid=(r,hash(o)&m) * where & is a bit-wise AND and m=2^k-1 */ #ifndef CEPH_PGMAP_H #define CEPH_PGMAP_H #include "include/health.h" #include "common/debug.h" #include "common/TextTable.h" #include "osd/osd_types.h" #include "include/mempool.h" #include "mon/health_check.h" #include <sstream> namespace ceph { class Formatter; } class PGMapDigest { public: MEMPOOL_CLASS_HELPERS(); virtual ~PGMapDigest() {} mempool::pgmap::vector<uint64_t> osd_last_seq; mutable std::map<int, int64_t> avail_space_by_rule; // aggregate state, populated by PGMap child int64_t num_pg = 0, num_osd = 0; int64_t num_pg_active = 0; int64_t num_pg_unknown = 0; mempool::pgmap::unordered_map<int32_t,pool_stat_t> pg_pool_sum; mempool::pgmap::map<int64_t,int64_t> num_pg_by_pool; pool_stat_t pg_sum; osd_stat_t osd_sum; mempool::pgmap::map<std::string,osd_stat_t> osd_sum_by_class; mempool::pgmap::unordered_map<uint64_t,int32_t> num_pg_by_state; struct pg_count { int32_t acting = 0; int32_t up_not_acting = 0; int32_t primary = 0; void encode(ceph::buffer::list& bl) const { using ceph::encode; encode(acting, bl); encode(up_not_acting, bl); encode(primary, bl); } void decode(ceph::buffer::list::const_iterator& p) { using ceph::decode; decode(acting, p); decode(up_not_acting, p); decode(primary, p); } }; mempool::pgmap::unordered_map<int32_t,pg_count> num_pg_by_osd; mempool::pgmap::map<int64_t,interval_set<snapid_t>> purged_snaps; bool use_per_pool_stats() const { return osd_sum.num_osds == osd_sum.num_per_pool_osds; } bool use_per_pool_omap_stats() const { return osd_sum.num_osds == osd_sum.num_per_pool_omap_osds; } // recent deltas, and summation /** * keep track of last deltas for each pool, calculated using * @p pg_pool_sum as baseline. */ mempool::pgmap::unordered_map<int64_t, mempool::pgmap::list<std::pair<pool_stat_t, utime_t> > > per_pool_sum_deltas; /** * keep track of per-pool timestamp deltas, according to last update on * each pool. */ mempool::pgmap::unordered_map<int64_t, utime_t> per_pool_sum_deltas_stamps; /** * keep track of sum deltas, per-pool, taking into account any previous * deltas existing in @p per_pool_sum_deltas. The utime_t as second member * of the pair is the timestamp referring to the last update (i.e., the first * member of the pair) for a given pool. */ mempool::pgmap::unordered_map<int64_t, std::pair<pool_stat_t,utime_t> > per_pool_sum_delta; pool_stat_t pg_sum_delta; utime_t stamp_delta; void get_recovery_stats( double *misplaced_ratio, double *degraded_ratio, double *inactive_ratio, double *unknown_pgs_ratio) const; void print_summary(ceph::Formatter *f, std::ostream *out) const; void print_oneline_summary(ceph::Formatter *f, std::ostream *out) const; void recovery_summary(ceph::Formatter *f, std::list<std::string> *psl, const pool_stat_t& pool_sum) const; void overall_recovery_summary(ceph::Formatter *f, std::list<std::string> *psl) const; void pool_recovery_summary(ceph::Formatter *f, std::list<std::string> *psl, uint64_t poolid) const; void recovery_rate_summary(ceph::Formatter *f, std::ostream *out, const pool_stat_t& delta_sum, utime_t delta_stamp) const; void overall_recovery_rate_summary(ceph::Formatter *f, std::ostream *out) const; void pool_recovery_rate_summary(ceph::Formatter *f, std::ostream *out, uint64_t poolid) const; /** * Obtain a formatted/plain output for client I/O, source from stats for a * given @p delta_sum pool over a given @p delta_stamp period of time. */ void client_io_rate_summary(ceph::Formatter *f, std::ostream *out, const pool_stat_t& delta_sum, utime_t delta_stamp) const; /** * Obtain a formatted/plain output for the overall client I/O, which is * calculated resorting to @p pg_sum_delta and @p stamp_delta. */ void overall_client_io_rate_summary(ceph::Formatter *f, std::ostream *out) const; /** * Obtain a formatted/plain output for client I/O over a given pool * with id @p pool_id. We will then obtain pool-specific data * from @p per_pool_sum_delta. */ void pool_client_io_rate_summary(ceph::Formatter *f, std::ostream *out, uint64_t poolid) const; /** * Obtain a formatted/plain output for cache tier IO, source from stats for a * given @p delta_sum pool over a given @p delta_stamp period of time. */ void cache_io_rate_summary(ceph::Formatter *f, std::ostream *out, const pool_stat_t& delta_sum, utime_t delta_stamp) const; /** * Obtain a formatted/plain output for the overall cache tier IO, which is * calculated resorting to @p pg_sum_delta and @p stamp_delta. */ void overall_cache_io_rate_summary(ceph::Formatter *f, std::ostream *out) const; /** * Obtain a formatted/plain output for cache tier IO over a given pool * with id @p pool_id. We will then obtain pool-specific data * from @p per_pool_sum_delta. */ void pool_cache_io_rate_summary(ceph::Formatter *f, std::ostream *out, uint64_t poolid) const; /** * Return the number of additional bytes that can be stored in this * pool before the first OSD fills up, accounting for PG overhead. */ int64_t get_pool_free_space(const OSDMap &osd_map, int64_t poolid) const; /** * Dump pool usage and io ops/bytes, used by "ceph df" command */ virtual void dump_pool_stats_full(const OSDMap &osd_map, std::stringstream *ss, ceph::Formatter *f, bool verbose) const; void dump_cluster_stats(std::stringstream *ss, ceph::Formatter *f, bool verbose) const; static void dump_object_stat_sum(TextTable &tbl, ceph::Formatter *f, const pool_stat_t &pool_stat, uint64_t avail, float raw_used_rate, bool verbose, bool per_pool, bool per_pool_omap, const pg_pool_t *pool); size_t get_num_pg_by_osd(int osd) const { auto p = num_pg_by_osd.find(osd); if (p == num_pg_by_osd.end()) return 0; else return p->second.acting; } int get_num_primary_pg_by_osd(int osd) const { auto p = num_pg_by_osd.find(osd); if (p == num_pg_by_osd.end()) return 0; else return p->second.primary; } ceph_statfs get_statfs(OSDMap &osdmap, std::optional<int64_t> data_pool) const; int64_t get_rule_avail(int ruleno) const { auto i = avail_space_by_rule.find(ruleno); if (i != avail_space_by_rule.end()) return avail_space_by_rule[ruleno]; else return 0; } // kill me post-mimic or -nautilus bool definitely_converted_snapsets() const { // false negative is okay; false positive is not! return num_pg && num_pg_unknown == 0 && pg_sum.stats.sum.num_legacy_snapsets == 0; } uint64_t get_last_osd_stat_seq(int osd) { if (osd < (int)osd_last_seq.size()) return osd_last_seq[osd]; return 0; } 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<PGMapDigest*>& ls); }; WRITE_CLASS_ENCODER(PGMapDigest::pg_count); WRITE_CLASS_ENCODER_FEATURES(PGMapDigest); class PGMap : public PGMapDigest { public: MEMPOOL_CLASS_HELPERS(); // the map version_t version; epoch_t last_osdmap_epoch; // last osdmap epoch i applied to the pgmap epoch_t last_pg_scan; // osdmap epoch mempool::pgmap::unordered_map<int32_t,osd_stat_t> osd_stat; mempool::pgmap::unordered_map<pg_t,pg_stat_t> pg_stat; typedef mempool::pgmap::map< std::pair<int64_t, int>, // <pool, osd> store_statfs_t> per_osd_pool_statfs_t; per_osd_pool_statfs_t pool_statfs; class Incremental { public: MEMPOOL_CLASS_HELPERS(); version_t version; mempool::pgmap::map<pg_t,pg_stat_t> pg_stat_updates; epoch_t osdmap_epoch; epoch_t pg_scan; // osdmap epoch mempool::pgmap::set<pg_t> pg_remove; utime_t stamp; per_osd_pool_statfs_t pool_statfs_updates; private: mempool::pgmap::map<int32_t,osd_stat_t> osd_stat_updates; mempool::pgmap::set<int32_t> osd_stat_rm; public: const mempool::pgmap::map<int32_t, osd_stat_t> &get_osd_stat_updates() const { return osd_stat_updates; } const mempool::pgmap::set<int32_t> &get_osd_stat_rm() const { return osd_stat_rm; } template<typename OsdStat> void update_stat(int32_t osd, OsdStat&& stat) { osd_stat_updates[osd] = std::forward<OsdStat>(stat); } void stat_osd_out(int32_t osd) { osd_stat_updates[osd] = osd_stat_t(); } void stat_osd_down_up(int32_t osd, const PGMap& pg_map) { // 0 the op_queue_age_hist for this osd auto p = osd_stat_updates.find(osd); if (p != osd_stat_updates.end()) { p->second.op_queue_age_hist.clear(); return; } auto q = pg_map.osd_stat.find(osd); if (q != pg_map.osd_stat.end()) { osd_stat_t& t = osd_stat_updates[osd] = q->second; t.op_queue_age_hist.clear(); } } void rm_stat(int32_t osd) { osd_stat_rm.insert(osd); osd_stat_updates.erase(osd); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<Incremental*>& o); Incremental() : version(0), osdmap_epoch(0), pg_scan(0) {} }; // aggregate stats (soft state), generated by calc_stats() mempool::pgmap::unordered_map<int,std::set<pg_t> > pg_by_osd; mempool::pgmap::unordered_map<int,int> blocked_by_sum; mempool::pgmap::list<std::pair<pool_stat_t, utime_t> > pg_sum_deltas; mempool::pgmap::unordered_map<int64_t,mempool::pgmap::unordered_map<uint64_t,int32_t>> num_pg_by_pool_state; utime_t stamp; void update_pool_deltas( CephContext *cct, const utime_t ts, const mempool::pgmap::unordered_map<int32_t, pool_stat_t>& pg_pool_sum_old); void clear_delta(); void deleted_pool(int64_t pool) { for (auto i = pool_statfs.begin(); i != pool_statfs.end();) { if (i->first.first == pool) { i = pool_statfs.erase(i); } else { ++i; } } pg_pool_sum.erase(pool); num_pg_by_pool_state.erase(pool); num_pg_by_pool.erase(pool); per_pool_sum_deltas.erase(pool); per_pool_sum_deltas_stamps.erase(pool); per_pool_sum_delta.erase(pool); } private: void update_delta( CephContext *cct, const utime_t ts, const pool_stat_t& old_pool_sum, utime_t *last_ts, const pool_stat_t& current_pool_sum, pool_stat_t *result_pool_delta, utime_t *result_ts_delta, mempool::pgmap::list<std::pair<pool_stat_t,utime_t> > *delta_avg_list); void update_one_pool_delta(CephContext *cct, const utime_t ts, const int64_t pool, const pool_stat_t& old_pool_sum); public: mempool::pgmap::set<pg_t> creating_pgs; mempool::pgmap::map<int,std::map<epoch_t,std::set<pg_t> > > creating_pgs_by_osd_epoch; // Bits that use to be enum StuckPG static const int STUCK_INACTIVE = (1<<0); static const int STUCK_UNCLEAN = (1<<1); static const int STUCK_UNDERSIZED = (1<<2); static const int STUCK_DEGRADED = (1<<3); static const int STUCK_STALE = (1<<4); PGMap() : version(0), last_osdmap_epoch(0), last_pg_scan(0) {} version_t get_version() const { return version; } void set_version(version_t v) { version = v; } epoch_t get_last_osdmap_epoch() const { return last_osdmap_epoch; } void set_last_osdmap_epoch(epoch_t e) { last_osdmap_epoch = e; } epoch_t get_last_pg_scan() const { return last_pg_scan; } void set_last_pg_scan(epoch_t e) { last_pg_scan = e; } utime_t get_stamp() const { return stamp; } void set_stamp(utime_t s) { stamp = s; } pool_stat_t get_pg_pool_sum_stat(int64_t pool) const { auto p = pg_pool_sum.find(pool); if (p != pg_pool_sum.end()) return p->second; return pool_stat_t(); } osd_stat_t get_osd_sum(const std::set<int>& osds) const { if (osds.empty()) // all return osd_sum; osd_stat_t sum; for (auto i : osds) { auto os = get_osd_stat(i); if (os) sum.add(*os); } return sum; } const osd_stat_t *get_osd_stat(int osd) const { auto i = osd_stat.find(osd); if (i == osd_stat.end()) { return nullptr; } return &i->second; } void apply_incremental(CephContext *cct, const Incremental& inc); void calc_stats(); void stat_pg_add(const pg_t &pgid, const pg_stat_t &s, bool sameosds=false); bool stat_pg_sub(const pg_t &pgid, const pg_stat_t &s, bool sameosds=false); void calc_purged_snaps(); void calc_osd_sum_by_class(const OSDMap& osdmap); void stat_osd_add(int osd, const osd_stat_t &s); void stat_osd_sub(int osd, const osd_stat_t &s); void encode(ceph::buffer::list &bl, uint64_t features=-1) const; void decode(ceph::buffer::list::const_iterator &bl); /// encode subset of our data to a PGMapDigest void encode_digest(const OSDMap& osdmap, ceph::buffer::list& bl, uint64_t features); int64_t get_rule_avail(const OSDMap& osdmap, int ruleno) const; void get_rules_avail(const OSDMap& osdmap, std::map<int,int64_t> *avail_map) const; void dump(ceph::Formatter *f, bool with_net = true) const; void dump_basic(ceph::Formatter *f) const; void dump_pg_stats(ceph::Formatter *f, bool brief) const; void dump_pg_progress(ceph::Formatter *f) const; void dump_pool_stats(ceph::Formatter *f) const; void dump_osd_stats(ceph::Formatter *f, bool with_net = true) const; void dump_osd_ping_times(ceph::Formatter *f) const; void dump_delta(ceph::Formatter *f) const; void dump_filtered_pg_stats(ceph::Formatter *f, std::set<pg_t>& pgs) const; void dump_pool_stats_full(const OSDMap &osd_map, std::stringstream *ss, ceph::Formatter *f, bool verbose) const override { get_rules_avail(osd_map, &avail_space_by_rule); PGMapDigest::dump_pool_stats_full(osd_map, ss, f, verbose); } /* * Dump client io rate, recovery io rate, cache io rate and recovery information. * this function is used by "ceph osd pool stats" command */ void dump_pool_stats_and_io_rate(int64_t poolid, const OSDMap &osd_map, ceph::Formatter *f, std::stringstream *ss) const; static void dump_pg_stats_plain( std::ostream& ss, const mempool::pgmap::unordered_map<pg_t, pg_stat_t>& pg_stats, bool brief); void get_stuck_stats( int types, const utime_t cutoff, mempool::pgmap::unordered_map<pg_t, pg_stat_t>& stuck_pgs) const; void dump_stuck(ceph::Formatter *f, int types, utime_t cutoff) const; void dump_stuck_plain(std::ostream& ss, int types, utime_t cutoff) const; int dump_stuck_pg_stats(std::stringstream &ds, ceph::Formatter *f, int threshold, std::vector<std::string>& args) const; void dump(std::ostream& ss) const; void dump_basic(std::ostream& ss) const; void dump_pg_stats(std::ostream& ss, bool brief) const; void dump_pg_sum_stats(std::ostream& ss, bool header) const; void dump_pool_stats(std::ostream& ss, bool header) const; void dump_osd_stats(std::ostream& ss) const; void dump_osd_sum_stats(std::ostream& ss) const; void dump_filtered_pg_stats(std::ostream& ss, std::set<pg_t>& pgs) const; void dump_osd_perf_stats(ceph::Formatter *f) const; void print_osd_perf_stats(std::ostream *ss) const; void dump_osd_blocked_by_stats(ceph::Formatter *f) const; void print_osd_blocked_by_stats(std::ostream *ss) const; void get_filtered_pg_stats(uint64_t state, int64_t poolid, int64_t osdid, bool primary, std::set<pg_t>& pgs) const; std::set<std::string> osd_parentage(const OSDMap& osdmap, int id) const; void get_health_checks( CephContext *cct, const OSDMap& osdmap, health_check_map_t *checks) const; void print_summary(ceph::Formatter *f, std::ostream *out) const; static void generate_test_instances(std::list<PGMap*>& o); }; WRITE_CLASS_ENCODER_FEATURES(PGMap) inline std::ostream& operator<<(std::ostream& out, const PGMapDigest& m) { m.print_oneline_summary(NULL, &out); return out; } int process_pg_map_command( const std::string& prefix, const cmdmap_t& cmdmap, const PGMap& pg_map, const OSDMap& osdmap, ceph::Formatter *f, std::stringstream *ss, ceph::buffer::list *odata); class PGMapUpdater { public: static void check_osd_map( CephContext *cct, const OSDMap &osdmap, const PGMap& pg_map, PGMap::Incremental *pending_inc); // mark pg's state stale if its acting primary osd is down static void check_down_pgs( const OSDMap &osd_map, const PGMap &pg_map, bool check_all, const std::set<int>& need_check_down_pg_osds, PGMap::Incremental *pending_inc); }; namespace reweight { /* Assign a lower weight to overloaded OSDs. * * The osds that will get a lower weight are those with with a utilization * percentage 'oload' percent greater than the average utilization. */ int by_utilization(const OSDMap &osd_map, const PGMap &pg_map, int oload, double max_changef, int max_osds, bool by_pg, const std::set<int64_t> *pools, bool no_increasing, mempool::osdmap::map<int32_t, uint32_t>* new_weights, std::stringstream *ss, std::string *out_str, ceph::Formatter *f); } #endif
18,391
31.960573
118
h
null
ceph-main/src/mon/PaxosFSMap.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_PAXOS_FSMAP_H #define CEPH_PAXOS_FSMAP_H #include "mds/FSMap.h" #include "mds/MDSMap.h" #include "include/ceph_assert.h" class PaxosFSMap { public: virtual ~PaxosFSMap() {} const FSMap &get_pending_fsmap() const { ceph_assert(is_leader()); return pending_fsmap; } const FSMap &get_fsmap() const { return fsmap; } virtual bool is_leader() const = 0; protected: FSMap &get_pending_fsmap_writeable() { ceph_assert(is_leader()); return pending_fsmap; } FSMap &create_pending() { ceph_assert(is_leader()); pending_fsmap = fsmap; pending_fsmap.epoch++; return pending_fsmap; } void decode(ceph::buffer::list &bl) { fsmap.decode(bl); pending_fsmap = FSMap(); /* nuke it to catch invalid access */ } private: /* Keep these PRIVATE to prevent unprotected manipulation. */ FSMap fsmap; /* the current epoch */ FSMap pending_fsmap; /* the next epoch */ }; #endif
1,350
23.563636
92
h
null
ceph-main/src/mon/Session.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_SESSION_H #define CEPH_MON_SESSION_H #include <string> #include <string_view> #include "include/utime.h" #include "include/xlist.h" #include "global/global_context.h" #include "msg/msg_types.h" #include "mon/mon_types.h" #include "auth/AuthServiceHandler.h" #include "osd/OSDMap.h" #include "MonCap.h" struct MonSession; struct Subscription { MonSession *session; std::string type; xlist<Subscription*>::item type_item; version_t next; bool onetime; bool incremental_onetime; // has CEPH_FEATURE_INCSUBOSDMAP Subscription(MonSession *s, const std::string& t) : session(s), type(t), type_item(this), next(0), onetime(false), incremental_onetime(false) {} }; struct MonSession : public RefCountedObject { ConnectionRef con; int con_type = 0; uint64_t con_features = 0; // zero if AnonConnection entity_name_t name; entity_addrvec_t addrs; entity_addr_t socket_addr; utime_t session_timeout; bool closed = false; xlist<MonSession*>::item item; std::set<uint64_t> routed_request_tids; MonCap caps; bool validated_stretch_connection = false; bool authenticated = false; ///< true if auth handshake is complete std::map<std::string, Subscription*> sub_map; epoch_t osd_epoch = 0; ///< the osdmap epoch sent to the mon client AuthServiceHandler *auth_handler = nullptr; EntityName entity_name; uint64_t global_id = 0; global_id_status_t global_id_status = global_id_status_t::NONE; ConnectionRef proxy_con; uint64_t proxy_tid = 0; std::string remote_host; ///< remote host name std::map<std::string,std::string,std::less<>> last_config; ///< most recently shared config bool any_config = false; MonSession(Connection *c) : RefCountedObject(g_ceph_context), con(c), item(this) { } void _ident(const entity_name_t& n, const entity_addrvec_t& av) { con_type = con->get_peer_type(); name = n; addrs = av; socket_addr = con->get_peer_socket_addr(); if (con->get_messenger()) { // only fill in features if this is a non-anonymous connection con_features = con->get_features(); } } ~MonSession() override { //generic_dout(0) << "~MonSession " << this << dendl; // we should have been removed before we get destructed; see MonSessionMap::remove_session() ceph_assert(!item.is_on_list()); ceph_assert(sub_map.empty()); delete auth_handler; } bool is_capable(std::string service, int mask) { std::map<std::string,std::string> args; return caps.is_capable( g_ceph_context, entity_name, service, "", args, mask & MON_CAP_R, mask & MON_CAP_W, mask & MON_CAP_X, get_peer_socket_addr()); } std::vector<std::string> get_allowed_fs_names() const { return caps.allowed_fs_names(); } bool fs_name_capable(std::string_view fsname, __u8 mask) { return caps.fs_name_capable(entity_name, fsname, mask); } const entity_addr_t& get_peer_socket_addr() { return socket_addr; } void dump(ceph::Formatter *f) const { f->dump_stream("name") << name; f->dump_stream("entity_name") << entity_name; f->dump_object("addrs", addrs); f->dump_object("socket_addr", socket_addr); f->dump_string("con_type", ceph_entity_type_name(con_type)); f->dump_unsigned("con_features", con_features); f->dump_stream("con_features_hex") << std::hex << con_features << std::dec; f->dump_string("con_features_release", ceph_release_name(ceph_release_from_features(con_features))); f->dump_bool("open", !closed); f->dump_object("caps", caps); f->dump_bool("authenticated", authenticated); f->dump_unsigned("global_id", global_id); f->dump_stream("global_id_status") << global_id_status; f->dump_unsigned("osd_epoch", osd_epoch); f->dump_string("remote_host", remote_host); } }; struct MonSessionMap { xlist<MonSession*> sessions; std::map<std::string, xlist<Subscription*>* > subs; std::multimap<int, MonSession*> by_osd; FeatureMap feature_map; // type -> features -> count MonSessionMap() {} ~MonSessionMap() { while (!subs.empty()) { ceph_assert(subs.begin()->second->empty()); delete subs.begin()->second; subs.erase(subs.begin()); } } unsigned get_size() const { return sessions.size(); } void remove_session(MonSession *s) { ceph_assert(!s->closed); for (std::map<std::string,Subscription*>::iterator p = s->sub_map.begin(); p != s->sub_map.end(); ++p) { p->second->type_item.remove_myself(); delete p->second; } s->sub_map.clear(); s->item.remove_myself(); if (s->name.is_osd() && s->name.num() >= 0) { for (auto p = by_osd.find(s->name.num()); p->first == s->name.num(); ++p) if (p->second == s) { by_osd.erase(p); break; } } if (s->con_features) { feature_map.rm(s->con_type, s->con_features); } s->closed = true; s->put(); } MonSession *new_session(const entity_name_t& n, const entity_addrvec_t& av, Connection *c) { MonSession *s = new MonSession(c); ceph_assert(s); s->_ident(n, av); add_session(s); return s; } void add_session(MonSession *s) { s->session_timeout = ceph_clock_now(); s->session_timeout += g_conf()->mon_session_timeout; sessions.push_back(&s->item); s->get(); if (s->name.is_osd() && s->name.num() >= 0) { by_osd.insert(std::pair<int,MonSession*>(s->name.num(), s)); } if (s->con_features) { feature_map.add(s->con_type, s->con_features); } } MonSession *get_random_osd_session(OSDMap *osdmap) { // ok, this isn't actually random, but close enough. if (by_osd.empty()) return 0; int n = by_osd.rbegin()->first + 1; int r = rand() % n; auto p = by_osd.lower_bound(r); if (p == by_osd.end()) --p; if (!osdmap) { return p->second; } MonSession *s = NULL; auto b = p; auto f = p; bool backward = true, forward = true; while (backward || forward) { if (backward) { if (osdmap->is_up(b->first) && osdmap->get_addrs(b->first) == b->second->con->get_peer_addrs()) { s = b->second; break; } if (b != by_osd.begin()) --b; else backward = false; } forward = (f != by_osd.end()); if (forward) { if (osdmap->is_up(f->first)) { s = f->second; break; } ++f; } } return s; } void add_update_sub(MonSession *s, const std::string& what, version_t start, bool onetime, bool incremental_onetime) { Subscription *sub = 0; if (s->sub_map.count(what)) { sub = s->sub_map[what]; } else { sub = new Subscription(s, what); s->sub_map[what] = sub; if (!subs.count(what)) subs[what] = new xlist<Subscription*>; subs[what]->push_back(&sub->type_item); } sub->next = start; sub->onetime = onetime; sub->incremental_onetime = onetime && incremental_onetime; } void remove_sub(Subscription *sub) { sub->session->sub_map.erase(sub->type); sub->type_item.remove_myself(); delete sub; } }; inline std::ostream& operator<<(std::ostream& out, const MonSession& s) { out << "MonSession(" << s.name << " " << s.addrs << " is " << (s.closed ? "closed" : "open") << " " << s.caps << ", features 0x" << std::hex << s.con_features << std::dec << " (" << ceph_release_name(ceph_release_from_features(s.con_features)) << "))"; return out; } #endif
8,043
26.175676
120
h
null
ceph-main/src/mon/error_code.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 <[email protected]> * Author: Adam C. Emerson <[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 <boost/system/error_code.hpp> #include "include/rados.h" const boost::system::error_category& mon_category() noexcept; // The Monitor, like the OSD, mostly replies with POSIX error codes. enum class mon_errc { }; namespace boost::system { template<> struct is_error_code_enum<::mon_errc> { static const bool value = true; }; template<> struct is_error_condition_enum<::mon_errc> { static const bool value = false; }; } // explicit conversion: inline boost::system::error_code make_error_code(mon_errc e) noexcept { return { static_cast<int>(e), mon_category() }; } // implicit conversion: inline boost::system::error_condition make_error_condition(mon_errc e) noexcept { return { static_cast<int>(e), mon_category() }; }
1,230
23.62
81
h
null
ceph-main/src/mon/health_check.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 "include/health.h" #include "include/utime.h" #include "common/Formatter.h" struct health_check_t { health_status_t severity; std::string summary; std::list<std::string> detail; int64_t count = 0; DENC(health_check_t, v, p) { DENC_START(2, 1, p); denc(v.severity, p); denc(v.summary, p); denc(v.detail, p); if (struct_v >= 2) { denc(v.count, p); } DENC_FINISH(p); } friend bool operator==(const health_check_t& l, const health_check_t& r) { return l.severity == r.severity && l.summary == r.summary && l.detail == r.detail && l.count == r.count; } friend bool operator!=(const health_check_t& l, const health_check_t& r) { return !(l == r); } void dump(ceph::Formatter *f, bool want_detail=true) const { f->dump_stream("severity") << severity; f->open_object_section("summary"); f->dump_string("message", summary); f->dump_int("count", count); f->close_section(); if (want_detail) { f->open_array_section("detail"); for (auto& p : detail) { f->open_object_section("detail_item"); f->dump_string("message", p); f->close_section(); } f->close_section(); } } static void generate_test_instances(std::list<health_check_t*>& ls) { ls.push_back(new health_check_t); ls.push_back(new health_check_t); ls.back()->severity = HEALTH_ERR; ls.back()->summary = "summarization"; ls.back()->detail = {"one", "two", "three"}; ls.back()->count = 42; } }; WRITE_CLASS_DENC(health_check_t) struct health_mute_t { std::string code; utime_t ttl; bool sticky = false; std::string summary; int64_t count; DENC(health_mute_t, v, p) { DENC_START(1, 1, p); denc(v.code, p); denc(v.ttl, p); denc(v.sticky, p); denc(v.summary, p); denc(v.count, p); DENC_FINISH(p); } void dump(ceph::Formatter *f) const { f->dump_string("code", code); if (ttl != utime_t()) { f->dump_stream("ttl") << ttl; } f->dump_bool("sticky", sticky); f->dump_string("summary", summary); f->dump_int("count", count); } static void generate_test_instances(std::list<health_mute_t*>& ls) { ls.push_back(new health_mute_t); ls.push_back(new health_mute_t); ls.back()->code = "OSD_DOWN"; ls.back()->ttl = utime_t(1, 2); ls.back()->sticky = true; ls.back()->summary = "foo bar"; ls.back()->count = 2; } }; WRITE_CLASS_DENC(health_mute_t) struct health_check_map_t { std::map<std::string,health_check_t> checks; DENC(health_check_map_t, v, p) { DENC_START(1, 1, p); denc(v.checks, p); DENC_FINISH(p); } void dump(ceph::Formatter *f) const { for (auto& [code, check] : checks) { f->dump_object(code, check); } } static void generate_test_instances(std::list<health_check_map_t*>& ls) { ls.push_back(new health_check_map_t); ls.push_back(new health_check_map_t); { auto& d = ls.back()->add("FOO", HEALTH_WARN, "foo", 2); d.detail.push_back("a"); d.detail.push_back("b"); } { auto& d = ls.back()->add("BAR", HEALTH_ERR, "bar!", 3); d.detail.push_back("c"); d.detail.push_back("d"); d.detail.push_back("e"); } } void clear() { checks.clear(); } bool empty() const { return checks.empty(); } void swap(health_check_map_t& other) { checks.swap(other.checks); } health_check_t& add(const std::string& code, health_status_t severity, const std::string& summary, int64_t count) { ceph_assert(checks.count(code) == 0); health_check_t& r = checks[code]; r.severity = severity; r.summary = summary; r.count = count; return r; } health_check_t& get_or_add(const std::string& code, health_status_t severity, const std::string& summary, int64_t count) { health_check_t& r = checks[code]; r.severity = severity; r.summary = summary; r.count += count; return r; } void merge(const health_check_map_t& o) { for (auto& [code, check] : o.checks) { auto [it, new_check] = checks.try_emplace(code, check); if (!new_check) { // merge details, and hope the summary matches! it->second.detail.insert( it->second.detail.end(), check.detail.begin(), check.detail.end()); it->second.count += check.count; } } } friend bool operator==(const health_check_map_t& l, const health_check_map_t& r) { return l.checks == r.checks; } friend bool operator!=(const health_check_map_t& l, const health_check_map_t& r) { return !(l == r); } }; WRITE_CLASS_DENC(health_check_map_t)
4,875
23.502513
75
h
null
ceph-main/src/mon/mon_types.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_TYPES_H #define CEPH_MON_TYPES_H #include <map> #include "include/Context.h" #include "include/util.h" #include "include/utime.h" #include "common/Formatter.h" #include "common/bit_str.h" #include "common/ceph_releases.h" // use as paxos_service index enum { PAXOS_MDSMAP, PAXOS_OSDMAP, PAXOS_LOG, PAXOS_MONMAP, PAXOS_AUTH, PAXOS_MGR, PAXOS_MGRSTAT, PAXOS_HEALTH, PAXOS_CONFIG, PAXOS_KV, PAXOS_NUM }; #define CEPH_MON_ONDISK_MAGIC "ceph mon volume v012" // map of entity_type -> features -> count struct FeatureMap { std::map<uint32_t,std::map<uint64_t,uint64_t>> m; void add(uint32_t type, uint64_t features) { if (type == CEPH_ENTITY_TYPE_MON) { return; } m[type][features]++; } void add_mon(uint64_t features) { m[CEPH_ENTITY_TYPE_MON][features]++; } void rm(uint32_t type, uint64_t features) { if (type == CEPH_ENTITY_TYPE_MON) { return; } auto p = m.find(type); ceph_assert(p != m.end()); auto q = p->second.find(features); ceph_assert(q != p->second.end()); if (--q->second == 0) { p->second.erase(q); if (p->second.empty()) { m.erase(p); } } } FeatureMap& operator+=(const FeatureMap& o) { for (auto& p : o.m) { auto &v = m[p.first]; for (auto& q : p.second) { v[q.first] += q.second; } } return *this; } void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(m, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& p) { DECODE_START(1, p); decode(m, p); DECODE_FINISH(p); } void dump(ceph::Formatter *f) const { for (auto& p : m) { f->open_array_section(ceph_entity_type_name(p.first)); for (auto& q : p.second) { f->open_object_section("group"); std::stringstream ss; ss << "0x" << std::hex << q.first << std::dec; f->dump_string("features", ss.str()); f->dump_string("release", ceph_release_name( ceph_release_from_features(q.first))); f->dump_unsigned("num", q.second); f->close_section(); } f->close_section(); } } }; WRITE_CLASS_ENCODER(FeatureMap) /** * monitor db store stats */ struct MonitorDBStoreStats { uint64_t bytes_total; uint64_t bytes_sst; uint64_t bytes_log; uint64_t bytes_misc; utime_t last_update; MonitorDBStoreStats() : bytes_total(0), bytes_sst(0), bytes_log(0), bytes_misc(0) {} void dump(ceph::Formatter *f) const { ceph_assert(f != NULL); f->dump_int("bytes_total", bytes_total); f->dump_int("bytes_sst", bytes_sst); f->dump_int("bytes_log", bytes_log); f->dump_int("bytes_misc", bytes_misc); f->dump_stream("last_updated") << last_update; } void encode(ceph::buffer::list &bl) const { ENCODE_START(1, 1, bl); encode(bytes_total, bl); encode(bytes_sst, bl); encode(bytes_log, bl); encode(bytes_misc, bl); encode(last_update, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &p) { DECODE_START(1, p); decode(bytes_total, p); decode(bytes_sst, p); decode(bytes_log, p); decode(bytes_misc, p); decode(last_update, p); DECODE_FINISH(p); } static void generate_test_instances(std::list<MonitorDBStoreStats*>& ls) { ls.push_back(new MonitorDBStoreStats); ls.push_back(new MonitorDBStoreStats); ls.back()->bytes_total = 1024*1024; ls.back()->bytes_sst = 512*1024; ls.back()->bytes_log = 256*1024; ls.back()->bytes_misc = 256*1024; ls.back()->last_update = utime_t(); } }; WRITE_CLASS_ENCODER(MonitorDBStoreStats) // data stats struct DataStats { ceph_data_stats_t fs_stats; // data dir utime_t last_update; MonitorDBStoreStats store_stats; void dump(ceph::Formatter *f) const { ceph_assert(f != NULL); f->dump_int("kb_total", (fs_stats.byte_total/1024)); f->dump_int("kb_used", (fs_stats.byte_used/1024)); f->dump_int("kb_avail", (fs_stats.byte_avail/1024)); f->dump_int("avail_percent", fs_stats.avail_percent); f->dump_stream("last_updated") << last_update; f->open_object_section("store_stats"); store_stats.dump(f); f->close_section(); } void encode(ceph::buffer::list &bl) const { ENCODE_START(3, 1, bl); encode(fs_stats.byte_total, bl); encode(fs_stats.byte_used, bl); encode(fs_stats.byte_avail, bl); encode(fs_stats.avail_percent, bl); encode(last_update, bl); encode(store_stats, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &p) { DECODE_START(1, p); // we moved from having fields in kb to fields in byte if (struct_v > 2) { decode(fs_stats.byte_total, p); decode(fs_stats.byte_used, p); decode(fs_stats.byte_avail, p); } else { uint64_t t; decode(t, p); fs_stats.byte_total = t*1024; decode(t, p); fs_stats.byte_used = t*1024; decode(t, p); fs_stats.byte_avail = t*1024; } decode(fs_stats.avail_percent, p); decode(last_update, p); if (struct_v > 1) decode(store_stats, p); DECODE_FINISH(p); } }; WRITE_CLASS_ENCODER(DataStats) struct ScrubResult { std::map<std::string,uint32_t> prefix_crc; ///< prefix -> crc std::map<std::string,uint64_t> prefix_keys; ///< prefix -> key count bool operator!=(const ScrubResult& other) { return prefix_crc != other.prefix_crc || prefix_keys != other.prefix_keys; } void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(prefix_crc, bl); encode(prefix_keys, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& p) { DECODE_START(1, p); decode(prefix_crc, p); decode(prefix_keys, p); DECODE_FINISH(p); } void dump(ceph::Formatter *f) const { f->open_object_section("crc"); for (auto p = prefix_crc.begin(); p != prefix_crc.end(); ++p) f->dump_unsigned(p->first.c_str(), p->second); f->close_section(); f->open_object_section("keys"); for (auto p = prefix_keys.begin(); p != prefix_keys.end(); ++p) f->dump_unsigned(p->first.c_str(), p->second); f->close_section(); } static void generate_test_instances(std::list<ScrubResult*>& ls) { ls.push_back(new ScrubResult); ls.push_back(new ScrubResult); ls.back()->prefix_crc["foo"] = 123; ls.back()->prefix_keys["bar"] = 456; } }; WRITE_CLASS_ENCODER(ScrubResult) inline std::ostream& operator<<(std::ostream& out, const ScrubResult& r) { return out << "ScrubResult(keys " << r.prefix_keys << " crc " << r.prefix_crc << ")"; } /// for information like os, kernel, hostname, memory info, cpu model. typedef std::map<std::string, std::string> Metadata; namespace ceph { namespace features { namespace mon { /** * Get a feature's name based on its value. * * @param b raw feature value * * @remarks * Consumers should not assume this interface will never change. * @remarks * As the number of features increase, so may the internal representation * of the raw features. When this happens, this interface will change * accordingly. So should consumers of this interface. */ static inline const char *get_feature_name(uint64_t b); } } } inline const char *ceph_mon_feature_name(uint64_t b) { return ceph::features::mon::get_feature_name(b); }; class mon_feature_t { static constexpr int HEAD_VERSION = 1; static constexpr int COMPAT_VERSION = 1; // mon-specific features uint64_t features; public: explicit constexpr mon_feature_t(const uint64_t f) : features(f) { } mon_feature_t() : features(0) { } constexpr mon_feature_t(const mon_feature_t &o) : features(o.features) { } mon_feature_t& operator&=(const mon_feature_t other) { features &= other.features; return (*this); } /** * Obtain raw features * * @remarks * Consumers should not assume this interface will never change. * @remarks * As the number of features increase, so may the internal representation * of the raw features. When this happens, this interface will change * accordingly. So should consumers of this interface. */ uint64_t get_raw() const { return features; } constexpr friend mon_feature_t operator&(const mon_feature_t a, const mon_feature_t b) { return mon_feature_t(a.features & b.features); } mon_feature_t& operator|=(const mon_feature_t other) { features |= other.features; return (*this); } constexpr friend mon_feature_t operator|(const mon_feature_t a, const mon_feature_t b) { return mon_feature_t(a.features | b.features); } constexpr friend mon_feature_t operator^(const mon_feature_t a, const mon_feature_t b) { return mon_feature_t(a.features ^ b.features); } mon_feature_t& operator^=(const mon_feature_t other) { features ^= other.features; return (*this); } bool operator==(const mon_feature_t other) const { return (features == other.features); } bool operator!=(const mon_feature_t other) const { return (features != other.features); } bool empty() const { return features == 0; } /** * Set difference of our features in respect to @p other * * Returns all the elements in our features that are not in @p other * * @returns all the features not in @p other */ mon_feature_t diff(const mon_feature_t other) const { return mon_feature_t((features ^ other.features) & features); } /** * Set intersection of our features and @p other * * Returns all the elements common to both our features and the * features of @p other * * @returns the features common to @p other and us */ mon_feature_t intersection(const mon_feature_t other) const { return mon_feature_t((features & other.features)); } /** * Checks whether we have all the features in @p other * * Returns true if we have all the features in @p other * * @returns true if we contain all the features in @p other * @returns false if we do not contain some of the features in @p other */ bool contains_all(const mon_feature_t other) const { mon_feature_t d = intersection(other); return d == other; } /** * Checks whether we contain any of the features in @p other. * * @returns true if we contain any of the features in @p other * @returns false if we don't contain any of the features in @p other */ bool contains_any(const mon_feature_t other) const { mon_feature_t d = intersection(other); return !d.empty(); } void set_feature(const mon_feature_t f) { features |= f.features; } void unset_feature(const mon_feature_t f) { features &= ~(f.features); } void print(std::ostream& out) const { out << "["; print_bit_str(features, out, ceph::features::mon::get_feature_name); out << "]"; } void print_with_value(std::ostream& out) const { out << "["; print_bit_str(features, out, ceph::features::mon::get_feature_name, true); out << "]"; } void dump(ceph::Formatter *f, const char *sec_name = NULL) const { f->open_array_section((sec_name ? sec_name : "features")); dump_bit_str(features, f, ceph::features::mon::get_feature_name); f->close_section(); } void dump_with_value(ceph::Formatter *f, const char *sec_name = NULL) const { f->open_array_section((sec_name ? sec_name : "features")); dump_bit_str(features, f, ceph::features::mon::get_feature_name, true); f->close_section(); } void encode(ceph::buffer::list& bl) const { ENCODE_START(HEAD_VERSION, COMPAT_VERSION, bl); encode(features, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& p) { DECODE_START(COMPAT_VERSION, p); decode(features, p); DECODE_FINISH(p); } }; WRITE_CLASS_ENCODER(mon_feature_t) namespace ceph { namespace features { namespace mon { constexpr mon_feature_t FEATURE_KRAKEN( (1ULL << 0)); constexpr mon_feature_t FEATURE_LUMINOUS( (1ULL << 1)); constexpr mon_feature_t FEATURE_MIMIC( (1ULL << 2)); constexpr mon_feature_t FEATURE_OSDMAP_PRUNE (1ULL << 3); constexpr mon_feature_t FEATURE_NAUTILUS( (1ULL << 4)); constexpr mon_feature_t FEATURE_OCTOPUS( (1ULL << 5)); constexpr mon_feature_t FEATURE_PACIFIC( (1ULL << 6)); // elector pinging and CONNECTIVITY mode: constexpr mon_feature_t FEATURE_PINGING( (1ULL << 7)); constexpr mon_feature_t FEATURE_QUINCY( (1ULL << 8)); constexpr mon_feature_t FEATURE_REEF( (1ULL << 9)); constexpr mon_feature_t FEATURE_RESERVED( (1ULL << 63)); constexpr mon_feature_t FEATURE_NONE( (0ULL)); /** * All the features this monitor supports * * If there's a feature above, it should be OR'ed to this list. */ constexpr mon_feature_t get_supported() { return ( FEATURE_KRAKEN | FEATURE_LUMINOUS | FEATURE_MIMIC | FEATURE_OSDMAP_PRUNE | FEATURE_NAUTILUS | FEATURE_OCTOPUS | FEATURE_PACIFIC | FEATURE_PINGING | FEATURE_QUINCY | FEATURE_REEF | FEATURE_NONE ); } /** * All the features that, once set, cannot be removed. * * Features should only be added to this list if you want to make * sure downgrades are not possible after a quorum supporting all * these features has been formed. * * Any feature in this list will be automatically set on the monmap's * features once all the monitors in the quorum support it. */ constexpr mon_feature_t get_persistent() { return ( FEATURE_KRAKEN | FEATURE_LUMINOUS | FEATURE_MIMIC | FEATURE_NAUTILUS | FEATURE_OSDMAP_PRUNE | FEATURE_OCTOPUS | FEATURE_PACIFIC | FEATURE_PINGING | FEATURE_QUINCY | FEATURE_REEF | FEATURE_NONE ); } constexpr mon_feature_t get_optional() { return ( FEATURE_OSDMAP_PRUNE | FEATURE_NONE ); } static inline mon_feature_t get_feature_by_name(const std::string &n); } } } static inline ceph_release_t infer_ceph_release_from_mon_features(mon_feature_t f) { if (f.contains_all(ceph::features::mon::FEATURE_REEF)) { return ceph_release_t::reef; } if (f.contains_all(ceph::features::mon::FEATURE_QUINCY)) { return ceph_release_t::quincy; } if (f.contains_all(ceph::features::mon::FEATURE_PACIFIC)) { return ceph_release_t::pacific; } if (f.contains_all(ceph::features::mon::FEATURE_OCTOPUS)) { return ceph_release_t::octopus; } if (f.contains_all(ceph::features::mon::FEATURE_NAUTILUS)) { return ceph_release_t::nautilus; } if (f.contains_all(ceph::features::mon::FEATURE_MIMIC)) { return ceph_release_t::mimic; } if (f.contains_all(ceph::features::mon::FEATURE_LUMINOUS)) { return ceph_release_t::luminous; } if (f.contains_all(ceph::features::mon::FEATURE_KRAKEN)) { return ceph_release_t::kraken; } return ceph_release_t::unknown; } static inline const char *ceph::features::mon::get_feature_name(uint64_t b) { mon_feature_t f(b); if (f == FEATURE_KRAKEN) { return "kraken"; } else if (f == FEATURE_LUMINOUS) { return "luminous"; } else if (f == FEATURE_MIMIC) { return "mimic"; } else if (f == FEATURE_OSDMAP_PRUNE) { return "osdmap-prune"; } else if (f == FEATURE_NAUTILUS) { return "nautilus"; } else if (f == FEATURE_PINGING) { return "elector-pinging"; } else if (f == FEATURE_OCTOPUS) { return "octopus"; } else if (f == FEATURE_PACIFIC) { return "pacific"; } else if (f == FEATURE_QUINCY) { return "quincy"; } else if (f == FEATURE_REEF) { return "reef"; } else if (f == FEATURE_RESERVED) { return "reserved"; } return "unknown"; } inline mon_feature_t ceph::features::mon::get_feature_by_name(const std::string &n) { if (n == "kraken") { return FEATURE_KRAKEN; } else if (n == "luminous") { return FEATURE_LUMINOUS; } else if (n == "mimic") { return FEATURE_MIMIC; } else if (n == "osdmap-prune") { return FEATURE_OSDMAP_PRUNE; } else if (n == "nautilus") { return FEATURE_NAUTILUS; } else if (n == "feature-pinging") { return FEATURE_PINGING; } else if (n == "octopus") { return FEATURE_OCTOPUS; } else if (n == "pacific") { return FEATURE_PACIFIC; } else if (n == "quincy") { return FEATURE_QUINCY; } else if (n == "reef") { return FEATURE_REEF; } else if (n == "reserved") { return FEATURE_RESERVED; } return FEATURE_NONE; } inline std::ostream& operator<<(std::ostream& out, const mon_feature_t& f) { out << "mon_feature_t("; f.print(out); out << ")"; return out; } struct ProgressEvent { std::string message; ///< event description float progress; ///< [0..1] bool add_to_ceph_s; void encode(ceph::buffer::list& bl) const { ENCODE_START(2, 1, bl); encode(message, bl); encode(progress, bl); encode(add_to_ceph_s, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& p) { DECODE_START(2, p); decode(message, p); decode(progress, p); if (struct_v >= 2){ decode(add_to_ceph_s, p); } else { if (!message.empty()) { add_to_ceph_s = true; } } DECODE_FINISH(p); } void dump(ceph::Formatter *f) const { f->dump_string("message", message); f->dump_float("progress", progress); f->dump_bool("add_to_ceph_s", add_to_ceph_s); } }; WRITE_CLASS_ENCODER(ProgressEvent) #endif
18,274
26.034024
87
h
null
ceph-main/src/mount/canonicalize.c
/* * canonicalize.c -- canonicalize pathname by removing symlinks * Copyright (C) 1993 Rick Sladkey <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library Public License for more details. * */ /* * This routine is part of libc. We include it nevertheless, * since the libc version has some security flaws. * * TODO: use canonicalize_file_name() when exist in glibc */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <limits.h> #ifndef MAXSYMLINKS # define MAXSYMLINKS 256 #endif static char * myrealpath(const char *path, char *resolved_path, int maxreslth) { int readlinks = 0; char *npath; char *link_path; int n; char *buf = NULL; npath = resolved_path; /* If it's a relative pathname use getcwd for starters. */ if (*path != '/') { if (!getcwd(npath, maxreslth-2)) return NULL; npath += strlen(npath); if (npath[-1] != '/') *npath++ = '/'; } else { *npath++ = '/'; path++; } /* Expand each slash-separated pathname component. */ link_path = malloc(PATH_MAX+1); if (!link_path) return NULL; while (*path != '\0') { /* Ignore stray "/" */ if (*path == '/') { path++; continue; } if (*path == '.' && (path[1] == '\0' || path[1] == '/')) { /* Ignore "." */ path++; continue; } if (*path == '.' && path[1] == '.' && (path[2] == '\0' || path[2] == '/')) { /* Backup for ".." */ path += 2; while (npath > resolved_path+1 && (--npath)[-1] != '/') ; continue; } /* Safely copy the next pathname component. */ while (*path != '\0' && *path != '/') { if (npath-resolved_path > maxreslth-2) { errno = ENAMETOOLONG; goto err; } *npath++ = *path++; } /* Protect against infinite loops. */ if (readlinks++ > MAXSYMLINKS) { errno = ELOOP; goto err; } /* See if last pathname component is a symlink. */ *npath = '\0'; n = readlink(resolved_path, link_path, PATH_MAX); if (n < 0) { /* EINVAL means the file exists but isn't a symlink. */ if (errno != EINVAL) goto err; } else { int m; char *newbuf; /* Note: readlink doesn't add the null byte. */ link_path[n] = '\0'; if (*link_path == '/') /* Start over for an absolute symlink. */ npath = resolved_path; else /* Otherwise back up over this component. */ while (*(--npath) != '/') ; /* Insert symlink contents into path. */ m = strlen(path); newbuf = malloc(m + n + 1); if (!newbuf) goto err; memcpy(newbuf, link_path, n); memcpy(newbuf + n, path, m + 1); free(buf); path = buf = newbuf; } *npath++ = '/'; } /* Delete trailing slash but don't whomp a lone slash. */ if (npath != resolved_path+1 && npath[-1] == '/') npath--; /* Make sure it's null terminated. */ *npath = '\0'; free(link_path); free(buf); return resolved_path; err: free(link_path); free(buf); return NULL; } /* * Converts private "dm-N" names to "/dev/mapper/<name>" * * Since 2.6.29 (patch 784aae735d9b0bba3f8b9faef4c8b30df3bf0128) kernel sysfs * provides the real DM device names in /sys/block/<ptname>/dm/name */ char * canonicalize_dm_name(const char *ptname) { FILE *f; size_t sz; char path[268], name[256], *res = NULL; snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname); if (!(f = fopen(path, "r"))) return NULL; /* read "<name>\n" from sysfs */ if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) { name[sz - 1] = '\0'; snprintf(path, sizeof(path), "/dev/mapper/%s", name); res = strdup(path); } fclose(f); return res; } char * canonicalize_path(const char *path) { char *canonical; char *p; if (path == NULL) return NULL; canonical = malloc(PATH_MAX+2); if (!canonical) return NULL; if (!myrealpath(path, canonical, PATH_MAX+1)) { free(canonical); return strdup(path); } p = strrchr(canonical, '/'); if (p && strncmp(p, "/dm-", 4) == 0 && isdigit(*(p + 4))) { p = canonicalize_dm_name(p+1); if (p) { free(canonical); return p; } } return canonical; }
4,505
21.088235
77
c
null
ceph-main/src/mount/mount.ceph.h
#ifndef _SRC_MOUNT_MOUNT_CEPH_H #define _SRC_MOUNT_MOUNT_CEPH_H #ifdef __cplusplus extern "C" { #endif /* * See class CryptoKey * * 2 (for the type of secret) + * 8 (for the timestamp) + * 2 (for the length of secret) + * 16 (for an AES-128 key) */ #define MAX_RAW_SECRET_LEN (2 + 8 + 2 + 16) /* Max length of base64 encoded secret. 4/3 original size (rounded up) */ #define MAX_SECRET_LEN ((MAX_RAW_SECRET_LEN + (3 - 1)) * 4 / 3) /* Max Including null terminator */ #define SECRET_BUFSIZE (MAX_SECRET_LEN + 1) /* 2k should be enough for anyone? */ #define MON_LIST_BUFSIZE 2048 #define CLUSTER_FSID_LEN 37 void mount_ceph_debug(const char *fmt, ...); struct ceph_config_info { char cci_secret[SECRET_BUFSIZE]; // auth secret char cci_mons[MON_LIST_BUFSIZE]; // monitor addrs char cci_fsid[CLUSTER_FSID_LEN]; // cluster fsid }; void mount_ceph_get_config_info(const char *config_file, const char *name, bool v2_addrs, struct ceph_config_info *cci); #ifdef __cplusplus } #endif #endif /* _SRC_MOUNT_MOUNT_CEPH_H */
1,049
22.333333
74
h
null
ceph-main/src/mount/mtab.c
/* * this code lifted from util-linux-ng, licensed GPLv2+, * * git://git.kernel.org/pub/scm/utils/util-linux-ng/util-linux-ng.git * * whoever decided that each special mount program is responsible * for updating /etc/mtab should be spanked. * * <[email protected]> */ #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/vfs.h> #include <time.h> #include <mntent.h> #include <stdarg.h> #include "mount/canonicalize.c" /* Updating mtab ----------------------------------------------*/ /* Flag for already existing lock file. */ static int we_created_lockfile = 0; static int lockfile_fd = -1; /* Flag to indicate that signals have been set up. */ static int signals_have_been_setup = 0; /* Ensure that the lock is released if we are interrupted. */ extern char *strsignal(int sig); /* not always in <string.h> */ static void setlkw_timeout (int sig) { /* nothing, fcntl will fail anyway */ } #define _PATH_MOUNTED "/etc/mtab" #define _PATH_MOUNTED_LOCK "/etc/mtab~" #define PROC_SUPER_MAGIC 0x9fa0 /* exit status - bits below are ORed */ #define EX_USAGE 1 /* incorrect invocation or permission */ #define EX_SYSERR 2 /* out of memory, cannot fork, ... */ #define EX_SOFTWARE 4 /* internal mount bug or wrong version */ #define EX_USER 8 /* user interrupt */ #define EX_FILEIO 16 /* problems writing, locking, ... mtab/fstab */ #define EX_FAIL 32 /* mount failure */ #define EX_SOMEOK 64 /* some mount succeeded */ int die(int err, const char *fmt, ...) { va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); exit(err); } static void handler (int sig) { die(EX_USER, "%s", strsignal(sig)); } /* Remove lock file. */ void unlock_mtab (void) { if (we_created_lockfile) { close(lockfile_fd); lockfile_fd = -1; unlink (_PATH_MOUNTED_LOCK); we_created_lockfile = 0; } } /* Create the lock file. The lock file will be removed if we catch a signal or when we exit. */ /* The old code here used flock on a lock file /etc/mtab~ and deleted this lock file afterwards. However, as rgooch remarks, that has a race: a second mount may be waiting on the lock and proceed as soon as the lock file is deleted by the first mount, and immediately afterwards a third mount comes, creates a new /etc/mtab~, applies flock to that, and also proceeds, so that the second and third mount now both are scribbling in /etc/mtab. The new code uses a link() instead of a creat(), where we proceed only if it was us that created the lock, and hence we always have to delete the lock afterwards. Now the use of flock() is in principle superfluous, but avoids an arbitrary sleep(). */ /* Where does the link point to? Obvious choices are mtab and mtab~~. HJLu points out that the latter leads to races. Right now we use mtab~.<pid> instead. Use 20 as upper bound for the length of %d. */ #define MOUNTLOCK_LINKTARGET _PATH_MOUNTED_LOCK "%d" #define MOUNTLOCK_LINKTARGET_LTH (sizeof(_PATH_MOUNTED_LOCK)+20) /* * The original mount locking code has used sleep(1) between attempts and * maximal number of attempts has been 5. * * There was very small number of attempts and extremely long waiting (1s) * that is useless on machines with large number of concurret mount processes. * * Now we wait few thousand microseconds between attempts and we have global * time limit (30s) rather than limit for number of attempts. The advantage * is that this method also counts time which we spend in fcntl(F_SETLKW) and * number of attempts is not so much restricted. * * -- [email protected] [2007-Mar-2007] */ /* maximum seconds between first and last attempt */ #define MOUNTLOCK_MAXTIME 30 /* sleep time (in microseconds, max=999999) between attempts */ #define MOUNTLOCK_WAITTIME 5000 void lock_mtab (void) { int i; struct timespec waittime; struct timeval maxtime; char linktargetfile[MOUNTLOCK_LINKTARGET_LTH]; if (!signals_have_been_setup) { int sig = 0; struct sigaction sa; sa.sa_handler = handler; sa.sa_flags = 0; sigfillset (&sa.sa_mask); while (sigismember (&sa.sa_mask, ++sig) != -1 && sig != SIGCHLD) { if (sig == SIGALRM) sa.sa_handler = setlkw_timeout; else sa.sa_handler = handler; sigaction (sig, &sa, (struct sigaction *) 0); } signals_have_been_setup = 1; } snprintf(linktargetfile, sizeof(linktargetfile), MOUNTLOCK_LINKTARGET, getpid ()); i = open (linktargetfile, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR); if (i < 0) { int errsv = errno; /* linktargetfile does not exist (as a file) and we cannot create it. Read-only filesystem? Too many files open in the system? Filesystem full? */ die (EX_FILEIO, "can't create lock file %s: %s " "(use -n flag to override)", linktargetfile, strerror (errsv)); } close(i); gettimeofday(&maxtime, NULL); maxtime.tv_sec += MOUNTLOCK_MAXTIME; waittime.tv_sec = 0; waittime.tv_nsec = (1000 * MOUNTLOCK_WAITTIME); /* Repeat until it was us who made the link */ while (!we_created_lockfile) { struct timeval now; struct flock flock; int errsv, j; j = link(linktargetfile, _PATH_MOUNTED_LOCK); errsv = errno; if (j == 0) we_created_lockfile = 1; if (j < 0 && errsv != EEXIST) { (void) unlink(linktargetfile); die (EX_FILEIO, "can't link lock file %s: %s " "(use -n flag to override)", _PATH_MOUNTED_LOCK, strerror (errsv)); } lockfile_fd = open (_PATH_MOUNTED_LOCK, O_WRONLY); if (lockfile_fd < 0) { /* Strange... Maybe the file was just deleted? */ int errsv = errno; gettimeofday(&now, NULL); if (errno == ENOENT && now.tv_sec < maxtime.tv_sec) { we_created_lockfile = 0; continue; } (void) unlink(linktargetfile); die (EX_FILEIO, "can't open lock file %s: %s " "(use -n flag to override)", _PATH_MOUNTED_LOCK, strerror (errsv)); } flock.l_type = F_WRLCK; flock.l_whence = SEEK_SET; flock.l_start = 0; flock.l_len = 0; if (j == 0) { /* We made the link. Now claim the lock. */ if (fcntl (lockfile_fd, F_SETLK, &flock) == -1) { /* proceed, since it was us who created the lockfile anyway */ } (void) unlink(linktargetfile); } else { /* Someone else made the link. Wait. */ gettimeofday(&now, NULL); if (now.tv_sec < maxtime.tv_sec) { alarm(maxtime.tv_sec - now.tv_sec); if (fcntl (lockfile_fd, F_SETLKW, &flock) == -1) { int errsv = errno; (void) unlink(linktargetfile); die (EX_FILEIO, "can't lock lock file %s: %s", _PATH_MOUNTED_LOCK, (errno == EINTR) ? "timed out" : strerror (errsv)); } alarm(0); nanosleep(&waittime, NULL); } else { (void) unlink(linktargetfile); die (EX_FILEIO, "Cannot create link %s\n" "Perhaps there is a stale lock file?\n", _PATH_MOUNTED_LOCK); } close(lockfile_fd); } } } static void update_mtab_entry(const char *spec, const char *node, const char *type, const char *opts, int flags, int freq, int pass) { struct statfs buf; int err = statfs(_PATH_MOUNTED, &buf); if (err) { printf("mount: can't statfs %s: %s", _PATH_MOUNTED, strerror (err)); return; } /* /etc/mtab is symbol link to /proc/self/mounts? */ if (buf.f_type == PROC_SUPER_MAGIC) return; if (!opts) opts = "rw"; struct mntent mnt; mnt.mnt_fsname = strdup(spec); mnt.mnt_dir = canonicalize_path(node); mnt.mnt_type = strdup(type); mnt.mnt_opts = strdup(opts); mnt.mnt_freq = freq; mnt.mnt_passno = pass; FILE *fp; lock_mtab(); fp = setmntent(_PATH_MOUNTED, "a+"); if (fp == NULL) { int errsv = errno; printf("mount: can't open %s: %s", _PATH_MOUNTED, strerror (errsv)); } else { if ((addmntent (fp, &mnt)) == 1) { int errsv = errno; printf("mount: error writing %s: %s", _PATH_MOUNTED, strerror (errsv)); } } endmntent(fp); unlock_mtab(); free(mnt.mnt_fsname); free(mnt.mnt_dir); free(mnt.mnt_type); free(mnt.mnt_opts); }
8,269
27.033898
79
c
null
ceph-main/src/msg/Connection.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_CONNECTION_H #define CEPH_CONNECTION_H #include <stdlib.h> #include <ostream> #include "auth/Auth.h" #include "common/RefCountedObj.h" #include "common/config.h" #include "common/debug.h" #include "common/ref.h" #include "common/ceph_mutex.h" #include "include/ceph_assert.h" // Because intusive_ptr clobbers our assert... #include "include/buffer.h" #include "include/types.h" #include "common/item_history.h" #include "msg/MessageRef.h" // ====================================================== // abstract Connection, for keeping per-connection state class Messenger; #ifdef UNIT_TESTS_BUILT class Interceptor; #endif struct Connection : public RefCountedObjectSafe { mutable ceph::mutex lock = ceph::make_mutex("Connection::lock"); Messenger *msgr; RefCountedPtr priv; int peer_type = -1; int64_t peer_id = -1; // [msgr2 only] the 0 of osd.0, 4567 or client.4567 safe_item_history<entity_addrvec_t> peer_addrs; utime_t last_keepalive, last_keepalive_ack; bool anon = false; ///< anonymous outgoing connection private: uint64_t features = 0; public: bool is_loopback = false; bool failed = false; // true if we are a lossy connection that has failed. int rx_buffers_version = 0; std::map<ceph_tid_t,std::pair<ceph::buffer::list, int>> rx_buffers; // authentication state // FIXME make these private after ms_handle_authorizer is removed public: AuthCapsInfo peer_caps_info; EntityName peer_name; uint64_t peer_global_id = 0; #ifdef UNIT_TESTS_BUILT Interceptor *interceptor; #endif public: void set_priv(const RefCountedPtr& o) { std::lock_guard l{lock}; priv = o; } RefCountedPtr get_priv() { std::lock_guard l{lock}; return priv; } void clear_priv() { std::lock_guard l{lock}; priv.reset(nullptr); } /** * Used to judge whether this connection is ready to send. Usually, the * implementation need to build a own shakehand or sesson then it can be * ready to send. * * @return true if ready to send, or false otherwise */ virtual bool is_connected() = 0; virtual bool is_msgr2() const { return false; } bool is_anon() const { return anon; } Messenger *get_messenger() { return msgr; } /** * Queue the given Message to send out on the given Connection. * Success in this function does not guarantee Message delivery, only * success in queueing the Message. Other guarantees may be provided based * on the Connection policy. * * @param m The Message to send. The Messenger consumes a single reference * when you pass it in. * * @return 0 on success, or -errno on failure. */ virtual int send_message(Message *m) = 0; virtual int send_message2(MessageRef m) { return send_message(m.detach()); /* send_message(Message *m) consumes a reference */ } /** * Send a "keepalive" ping along the given Connection, if it's working. * If the underlying connection has broken, this function does nothing. * * @return 0, or implementation-defined error numbers. */ virtual void send_keepalive() = 0; /** * Mark down the given Connection. * * This will cause us to discard its outgoing queue, and if reset * detection is enabled in the policy and the endpoint tries to * reconnect they will discard their queue when we inform them of * the session reset. * * It does not generate any notifications to the Dispatcher. */ virtual void mark_down() = 0; /** * Mark a Connection as "disposable", setting it to lossy * (regardless of initial Policy). This does not immediately close * the Connection once Messages have been delivered, so as long as * there are no errors you can continue to receive responses; but it * will not attempt to reconnect for message delivery or preserve * your old delivery semantics, either. * * TODO: There's some odd stuff going on in our SimpleMessenger * implementation during connect that looks unused; is there * more of a contract that that's enforcing? */ virtual void mark_disposable() = 0; // WARNING / FIXME: this is not populated for loopback connections AuthCapsInfo& get_peer_caps_info() { return peer_caps_info; } const EntityName& get_peer_entity_name() { return peer_name; } uint64_t get_peer_global_id() { return peer_global_id; } int get_peer_type() const { return peer_type; } void set_peer_type(int t) { peer_type = t; } // peer_id is only defined for msgr2 int64_t get_peer_id() const { return peer_id; } void set_peer_id(int64_t t) { peer_id = t; } bool peer_is_mon() const { return peer_type == CEPH_ENTITY_TYPE_MON; } bool peer_is_mgr() const { return peer_type == CEPH_ENTITY_TYPE_MGR; } bool peer_is_mds() const { return peer_type == CEPH_ENTITY_TYPE_MDS; } bool peer_is_osd() const { return peer_type == CEPH_ENTITY_TYPE_OSD; } bool peer_is_client() const { return peer_type == CEPH_ENTITY_TYPE_CLIENT; } /// which of the peer's addrs is actually in use for this connection virtual entity_addr_t get_peer_socket_addr() const = 0; entity_addr_t get_peer_addr() const { return peer_addrs->front(); } const entity_addrvec_t& get_peer_addrs() const { return *peer_addrs; } void set_peer_addr(const entity_addr_t& a) { peer_addrs = entity_addrvec_t(a); } void set_peer_addrs(const entity_addrvec_t& av) { peer_addrs = av; } uint64_t get_features() const { return features; } bool has_feature(uint64_t f) const { return features & f; } bool has_features(uint64_t f) const { return (features & f) == f; } void set_features(uint64_t f) { features = f; } void set_feature(uint64_t f) { features |= f; } virtual int get_con_mode() const { return CEPH_CON_MODE_CRC; } void post_rx_buffer(ceph_tid_t tid, ceph::buffer::list& bl) { #if 0 std::lock_guard l{lock}; ++rx_buffers_version; rx_buffers[tid] = pair<bufferlist,int>(bl, rx_buffers_version); #endif } void revoke_rx_buffer(ceph_tid_t tid) { #if 0 std::lock_guard l{lock}; rx_buffers.erase(tid); #endif } utime_t get_last_keepalive() const { std::lock_guard l{lock}; return last_keepalive; } void set_last_keepalive(utime_t t) { std::lock_guard l{lock}; last_keepalive = t; } utime_t get_last_keepalive_ack() const { std::lock_guard l{lock}; return last_keepalive_ack; } void set_last_keepalive_ack(utime_t t) { std::lock_guard l{lock}; last_keepalive_ack = t; } bool is_blackhole() const; protected: Connection(CephContext *cct, Messenger *m) : RefCountedObjectSafe(cct), msgr(m) {} ~Connection() override { //generic_dout(0) << "~Connection " << this << dendl; } }; using ConnectionRef = ceph::ref_t<Connection>; #endif /* CEPH_CONNECTION_H */
7,256
27.237354
88
h
null
ceph-main/src/msg/DispatchQueue.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_DISPATCHQUEUE_H #define CEPH_DISPATCHQUEUE_H #include <atomic> #include <map> #include <queue> #include <boost/intrusive_ptr.hpp> #include "include/ceph_assert.h" #include "include/common_fwd.h" #include "common/Throttle.h" #include "common/ceph_mutex.h" #include "common/Thread.h" #include "common/PrioritizedQueue.h" #include "Message.h" class Messenger; struct Connection; /** * The DispatchQueue contains all the connections which have Messages * they want to be dispatched, carefully organized by Message priority * and permitted to deliver in a round-robin fashion. * See Messenger::dispatch_entry for details. */ class DispatchQueue { class QueueItem { int type; ConnectionRef con; ceph::ref_t<Message> m; public: explicit QueueItem(const ceph::ref_t<Message>& m) : type(-1), con(0), m(m) {} QueueItem(int type, Connection *con) : type(type), con(con), m(0) {} bool is_code() const { return type != -1; } int get_code () const { ceph_assert(is_code()); return type; } const ceph::ref_t<Message>& get_message() { ceph_assert(!is_code()); return m; } Connection *get_connection() { ceph_assert(is_code()); return con.get(); } }; CephContext *cct; Messenger *msgr; mutable ceph::mutex lock; ceph::condition_variable cond; PrioritizedQueue<QueueItem, uint64_t> mqueue; std::set<std::pair<double, ceph::ref_t<Message>>> marrival; std::map<ceph::ref_t<Message>, decltype(marrival)::iterator> marrival_map; void add_arrival(const ceph::ref_t<Message>& m) { marrival_map.insert( make_pair( m, marrival.insert(std::make_pair(m->get_recv_stamp(), m)).first ) ); } void remove_arrival(const ceph::ref_t<Message>& m) { auto it = marrival_map.find(m); ceph_assert(it != marrival_map.end()); marrival.erase(it->second); marrival_map.erase(it); } std::atomic<uint64_t> next_id; enum { D_CONNECT = 1, D_ACCEPT, D_BAD_REMOTE_RESET, D_BAD_RESET, D_CONN_REFUSED, D_NUM_CODES }; /** * The DispatchThread runs dispatch_entry to empty out the dispatch_queue. */ class DispatchThread : public Thread { DispatchQueue *dq; public: explicit DispatchThread(DispatchQueue *dq) : dq(dq) {} void *entry() override { dq->entry(); return 0; } } dispatch_thread; ceph::mutex local_delivery_lock; ceph::condition_variable local_delivery_cond; bool stop_local_delivery; std::queue<std::pair<ceph::ref_t<Message>, int>> local_messages; class LocalDeliveryThread : public Thread { DispatchQueue *dq; public: explicit LocalDeliveryThread(DispatchQueue *dq) : dq(dq) {} void *entry() override { dq->run_local_delivery(); return 0; } } local_delivery_thread; uint64_t pre_dispatch(const ceph::ref_t<Message>& m); void post_dispatch(const ceph::ref_t<Message>& m, uint64_t msize); public: /// Throttle preventing us from building up a big backlog waiting for dispatch Throttle dispatch_throttler; bool stop; void local_delivery(const ceph::ref_t<Message>& m, int priority); void local_delivery(Message* m, int priority) { return local_delivery(ceph::ref_t<Message>(m, false), priority); /* consume ref */ } void run_local_delivery(); double get_max_age(utime_t now) const; int get_queue_len() const { std::lock_guard l{lock}; return mqueue.length(); } /** * Release memory accounting back to the dispatch throttler. * * @param msize The amount of memory to release. */ void dispatch_throttle_release(uint64_t msize); void queue_connect(Connection *con) { std::lock_guard l{lock}; if (stop) return; mqueue.enqueue_strict( 0, CEPH_MSG_PRIO_HIGHEST, QueueItem(D_CONNECT, con)); cond.notify_all(); } void queue_accept(Connection *con) { std::lock_guard l{lock}; if (stop) return; mqueue.enqueue_strict( 0, CEPH_MSG_PRIO_HIGHEST, QueueItem(D_ACCEPT, con)); cond.notify_all(); } void queue_remote_reset(Connection *con) { std::lock_guard l{lock}; if (stop) return; mqueue.enqueue_strict( 0, CEPH_MSG_PRIO_HIGHEST, QueueItem(D_BAD_REMOTE_RESET, con)); cond.notify_all(); } void queue_reset(Connection *con) { std::lock_guard l{lock}; if (stop) return; mqueue.enqueue_strict( 0, CEPH_MSG_PRIO_HIGHEST, QueueItem(D_BAD_RESET, con)); cond.notify_all(); } void queue_refused(Connection *con) { std::lock_guard l{lock}; if (stop) return; mqueue.enqueue_strict( 0, CEPH_MSG_PRIO_HIGHEST, QueueItem(D_CONN_REFUSED, con)); cond.notify_all(); } bool can_fast_dispatch(const ceph::cref_t<Message> &m) const; void fast_dispatch(const ceph::ref_t<Message>& m); void fast_dispatch(Message* m) { return fast_dispatch(ceph::ref_t<Message>(m, false)); /* consume ref */ } void fast_preprocess(const ceph::ref_t<Message>& m); void enqueue(const ceph::ref_t<Message>& m, int priority, uint64_t id); void enqueue(Message* m, int priority, uint64_t id) { return enqueue(ceph::ref_t<Message>(m, false), priority, id); /* consume ref */ } void discard_queue(uint64_t id); void discard_local(); uint64_t get_id() { return next_id++; } void start(); void entry(); void wait(); void shutdown(); bool is_started() const {return dispatch_thread.is_started();} DispatchQueue(CephContext *cct, Messenger *msgr, std::string &name) : cct(cct), msgr(msgr), lock(ceph::make_mutex("Messenger::DispatchQueue::lock" + name)), mqueue(cct->_conf->ms_pq_max_tokens_per_priority, cct->_conf->ms_pq_min_cost), next_id(1), dispatch_thread(this), local_delivery_lock(ceph::make_mutex("Messenger::DispatchQueue::local_delivery_lock" + name)), stop_local_delivery(false), local_delivery_thread(this), dispatch_throttler(cct, std::string("msgr_dispatch_throttler-") + name, cct->_conf->ms_dispatch_throttle_bytes), stop(false) {} ~DispatchQueue() { ceph_assert(mqueue.empty()); ceph_assert(marrival.empty()); ceph_assert(local_messages.empty()); } }; #endif
6,715
26.63786
100
h
null
ceph-main/src/msg/Dispatcher.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_DISPATCHER_H #define CEPH_DISPATCHER_H #include <memory> #include "include/buffer_fwd.h" #include "include/ceph_assert.h" #include "include/common_fwd.h" #include "msg/MessageRef.h" class Messenger; class Connection; class CryptoKey; class KeyStore; class Dispatcher { public: explicit Dispatcher(CephContext *cct_) : cct(cct_) { } virtual ~Dispatcher() { } /** * The Messenger calls this function to query if you are capable * of "fast dispatch"ing a message. Indicating that you can fast * dispatch it requires that you: * 1) Handle the Message quickly and without taking long-term contended * locks. (This function is likely to be called in-line with message * receipt.) * 2) Be able to accept the Message even if you have not yet received * an ms_handle_accept() notification for the Connection it is associated * with, and even if you *have* called mark_down() or received an * ms_handle_reset() (or similar) call on the Connection. You will * not receive more than one dead "message" (and should generally be * prepared for that circumstance anyway, since the normal dispatch can begin, * then trigger Connection failure before it's percolated through your system). * We provide ms_handle_fast_[connect|accept] calls if you need them, under * similar speed and state constraints as fast_dispatch itself. * 3) Be able to make a determination on fast_dispatch without relying * on particular system state -- the ms_can_fast_dispatch() call might * be called multiple times on a single message; the state might change between * calling ms_can_fast_dispatch and ms_fast_dispatch; etc. * * @param m The message we want to fast dispatch. * @returns True if the message can be fast dispatched; false otherwise. */ virtual bool ms_can_fast_dispatch(const Message *m) const { return false; } virtual bool ms_can_fast_dispatch2(const MessageConstRef& m) const { return ms_can_fast_dispatch(m.get()); } /** * This function determines if a dispatcher is included in the * list of fast-dispatch capable Dispatchers. * @returns True if the Dispatcher can handle any messages via * fast dispatch; false otherwise. */ virtual bool ms_can_fast_dispatch_any() const { return false; } /** * Perform a "fast dispatch" on a given message. See * ms_can_fast_dispatch() for the requirements. * * @param m The Message to fast dispatch. */ virtual void ms_fast_dispatch(Message *m) { ceph_abort(); } /* ms_fast_dispatch2 because otherwise the child must define both */ virtual void ms_fast_dispatch2(const MessageRef &m) { /* allow old style dispatch handling that expects a Message * with a floating ref */ return ms_fast_dispatch(MessageRef(m).detach()); /* XXX N.B. always consumes ref */ } /** * Let the Dispatcher preview a Message before it is dispatched. This * function is called on *every* Message, prior to the fast/regular dispatch * decision point, but it is only used on fast-dispatch capable systems. An * implementation of ms_fast_preprocess must be essentially lock-free in the * same way as the ms_fast_dispatch function is (in particular, ms_fast_preprocess * may be called while the Messenger holds internal locks that prevent progress from * other threads, so any locks it takes must be at the very bottom of the hierarchy). * Messages are delivered in receipt order within a single Connection, but there are * no guarantees across Connections. This makes it useful for some limited * coordination between Messages which can be fast_dispatch'ed and those which must * go through normal dispatch. * * @param m A message which has been received */ virtual void ms_fast_preprocess(Message *m) {} /* ms_fast_preprocess2 because otherwise the child must define both */ virtual void ms_fast_preprocess2(const MessageRef &m) { /* allow old style dispatch handling that expects a Message* */ return ms_fast_preprocess(m.get()); } /** * The Messenger calls this function to deliver a single message. * * @param m The message being delivered. You (the Dispatcher) * are given a single reference count on it. */ virtual bool ms_dispatch(Message *m) { ceph_abort(); } /* ms_dispatch2 because otherwise the child must define both */ virtual bool ms_dispatch2(const MessageRef &m) { /* allow old style dispatch handling that expects a Message * with a floating ref */ MessageRef mr(m); if (ms_dispatch(mr.get())) { mr.detach(); /* dispatcher consumed ref */ return true; } return false; } /** * This function will be called whenever a Connection is newly-created * or reconnects in the Messenger. * * @param con The new Connection which has been established. You are not * granted a reference to it -- take one if you need one! */ virtual void ms_handle_connect(Connection *con) {} /** * This function will be called synchronously whenever a Connection is * newly-created or reconnects in the Messenger, if you support fast * dispatch. It is guaranteed to be called before any messages are * dispatched. * * @param con The new Connection which has been established. You are not * granted a reference to it -- take one if you need one! */ virtual void ms_handle_fast_connect(Connection *con) {} /** * Callback indicating we have accepted an incoming connection. * * @param con The (new or existing) Connection associated with the session */ virtual void ms_handle_accept(Connection *con) {} /** * Callback indicating we have accepted an incoming connection, if you * support fast dispatch. It is guaranteed to be called before any messages * are dispatched. * * @param con The (new or existing) Connection associated with the session */ virtual void ms_handle_fast_accept(Connection *con) {} /* * this indicates that the ordered+reliable delivery semantics have * been violated. Messages may have been lost due to a fault * in the network connection. * Only called on lossy Connections. * * @param con The Connection which broke. You are not granted * a reference to it. */ virtual bool ms_handle_reset(Connection *con) = 0; /** * This indicates that the ordered+reliable delivery semantics * have been violated because the remote somehow reset. * It implies that incoming messages were dropped, and * probably some of our previous outgoing messages were too. * * @param con The Connection which broke. You are not granted * a reference to it. */ virtual void ms_handle_remote_reset(Connection *con) = 0; /** * This indicates that the connection is both broken and further * connection attempts are failing because other side refuses * it. * * @param con The Connection which broke. You are not granted * a reference to it. */ virtual bool ms_handle_refused(Connection *con) = 0; /** * @defgroup Authentication * @{ */ /** * handle successful authentication (msgr2) * * Authenticated result/state will be attached to the Connection. * * return 1 for success * return 0 for no action (let another Dispatcher handle it) * return <0 for failure (failure to parse caps, for instance) */ virtual int ms_handle_authentication(Connection *con) { return 0; } /** * @} //Authentication */ protected: CephContext *cct; private: explicit Dispatcher(const Dispatcher &rhs); Dispatcher& operator=(const Dispatcher &rhs); }; #endif
8,062
34.209607
88
h
null
ceph-main/src/msg/Message.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_MESSAGE_H #define CEPH_MESSAGE_H #include <concepts> #include <cstdlib> #include <ostream> #include <string_view> #include <boost/intrusive/list.hpp> #if FMT_VERSION >= 90000 #include <fmt/ostream.h> #endif #include "include/Context.h" #include "common/RefCountedObj.h" #include "common/ThrottleInterface.h" #include "common/config.h" #include "common/ref.h" #include "common/debug.h" #include "common/zipkin_trace.h" #include "include/ceph_assert.h" // Because intrusive_ptr clobbers our assert... #include "include/buffer.h" #include "include/types.h" #include "msg/Connection.h" #include "msg/MessageRef.h" #include "msg_types.h" // monitor internal #define MSG_MON_SCRUB 64 #define MSG_MON_ELECTION 65 #define MSG_MON_PAXOS 66 #define MSG_MON_PROBE 67 #define MSG_MON_JOIN 68 #define MSG_MON_SYNC 69 #define MSG_MON_PING 140 /* monitor <-> mon admin tool */ #define MSG_MON_COMMAND 50 #define MSG_MON_COMMAND_ACK 51 #define MSG_LOG 52 #define MSG_LOGACK 53 #define MSG_GETPOOLSTATS 58 #define MSG_GETPOOLSTATSREPLY 59 #define MSG_MON_GLOBAL_ID 60 #define MSG_MON_USED_PENDING_KEYS 141 #define MSG_ROUTE 47 #define MSG_FORWARD 46 #define MSG_PAXOS 40 #define MSG_CONFIG 62 #define MSG_GET_CONFIG 63 #define MSG_KV_DATA 54 #define MSG_MON_GET_PURGED_SNAPS 76 #define MSG_MON_GET_PURGED_SNAPS_REPLY 77 // osd internal #define MSG_OSD_PING 70 #define MSG_OSD_BOOT 71 #define MSG_OSD_FAILURE 72 #define MSG_OSD_ALIVE 73 #define MSG_OSD_MARK_ME_DOWN 74 #define MSG_OSD_FULL 75 #define MSG_OSD_MARK_ME_DEAD 123 // removed right after luminous //#define MSG_OSD_SUBOP 76 //#define MSG_OSD_SUBOPREPLY 77 #define MSG_OSD_PGTEMP 78 #define MSG_OSD_BEACON 79 #define MSG_OSD_PG_NOTIFY 80 #define MSG_OSD_PG_NOTIFY2 130 #define MSG_OSD_PG_QUERY 81 #define MSG_OSD_PG_QUERY2 131 #define MSG_OSD_PG_LOG 83 #define MSG_OSD_PG_REMOVE 84 #define MSG_OSD_PG_INFO 85 #define MSG_OSD_PG_INFO2 132 #define MSG_OSD_PG_TRIM 86 #define MSG_PGSTATS 87 #define MSG_PGSTATSACK 88 #define MSG_OSD_PG_CREATE 89 #define MSG_REMOVE_SNAPS 90 #define MSG_OSD_SCRUB 91 #define MSG_OSD_SCRUB_RESERVE 92 // previous PG_MISSING #define MSG_OSD_REP_SCRUB 93 #define MSG_OSD_PG_SCAN 94 #define MSG_OSD_PG_BACKFILL 95 #define MSG_OSD_PG_BACKFILL_REMOVE 96 #define MSG_COMMAND 97 #define MSG_COMMAND_REPLY 98 #define MSG_OSD_BACKFILL_RESERVE 99 #define MSG_OSD_RECOVERY_RESERVE 150 #define MSG_OSD_FORCE_RECOVERY 151 #define MSG_OSD_PG_PUSH 105 #define MSG_OSD_PG_PULL 106 #define MSG_OSD_PG_PUSH_REPLY 107 #define MSG_OSD_EC_WRITE 108 #define MSG_OSD_EC_WRITE_REPLY 109 #define MSG_OSD_EC_READ 110 #define MSG_OSD_EC_READ_REPLY 111 #define MSG_OSD_REPOP 112 #define MSG_OSD_REPOPREPLY 113 #define MSG_OSD_PG_UPDATE_LOG_MISSING 114 #define MSG_OSD_PG_UPDATE_LOG_MISSING_REPLY 115 #define MSG_OSD_PG_CREATED 116 #define MSG_OSD_REP_SCRUBMAP 117 #define MSG_OSD_PG_RECOVERY_DELETE 118 #define MSG_OSD_PG_RECOVERY_DELETE_REPLY 119 #define MSG_OSD_PG_CREATE2 120 #define MSG_OSD_SCRUB2 121 #define MSG_OSD_PG_READY_TO_MERGE 122 #define MSG_OSD_PG_LEASE 133 #define MSG_OSD_PG_LEASE_ACK 134 // *** MDS *** #define MSG_MDS_BEACON 100 // to monitor #define MSG_MDS_PEER_REQUEST 101 #define MSG_MDS_TABLE_REQUEST 102 #define MSG_MDS_SCRUB 135 // 150 already in use (MSG_OSD_RECOVERY_RESERVE) #define MSG_MDS_RESOLVE 0x200 // 0x2xx are for mdcache of mds #define MSG_MDS_RESOLVEACK 0x201 #define MSG_MDS_CACHEREJOIN 0x202 #define MSG_MDS_DISCOVER 0x203 #define MSG_MDS_DISCOVERREPLY 0x204 #define MSG_MDS_INODEUPDATE 0x205 #define MSG_MDS_DIRUPDATE 0x206 #define MSG_MDS_CACHEEXPIRE 0x207 #define MSG_MDS_DENTRYUNLINK 0x208 #define MSG_MDS_FRAGMENTNOTIFY 0x209 #define MSG_MDS_OFFLOAD_TARGETS 0x20a #define MSG_MDS_DENTRYLINK 0x20c #define MSG_MDS_FINDINO 0x20d #define MSG_MDS_FINDINOREPLY 0x20e #define MSG_MDS_OPENINO 0x20f #define MSG_MDS_OPENINOREPLY 0x210 #define MSG_MDS_SNAPUPDATE 0x211 #define MSG_MDS_FRAGMENTNOTIFYACK 0x212 #define MSG_MDS_DENTRYUNLINK_ACK 0x213 #define MSG_MDS_LOCK 0x300 // 0x3xx are for locker of mds #define MSG_MDS_INODEFILECAPS 0x301 #define MSG_MDS_EXPORTDIRDISCOVER 0x449 // 0x4xx are for migrator of mds #define MSG_MDS_EXPORTDIRDISCOVERACK 0x450 #define MSG_MDS_EXPORTDIRCANCEL 0x451 #define MSG_MDS_EXPORTDIRPREP 0x452 #define MSG_MDS_EXPORTDIRPREPACK 0x453 #define MSG_MDS_EXPORTDIRWARNING 0x454 #define MSG_MDS_EXPORTDIRWARNINGACK 0x455 #define MSG_MDS_EXPORTDIR 0x456 #define MSG_MDS_EXPORTDIRACK 0x457 #define MSG_MDS_EXPORTDIRNOTIFY 0x458 #define MSG_MDS_EXPORTDIRNOTIFYACK 0x459 #define MSG_MDS_EXPORTDIRFINISH 0x460 #define MSG_MDS_EXPORTCAPS 0x470 #define MSG_MDS_EXPORTCAPSACK 0x471 #define MSG_MDS_GATHERCAPS 0x472 #define MSG_MDS_HEARTBEAT 0x500 // for mds load balancer #define MSG_MDS_METRICS 0x501 // for mds metric aggregator #define MSG_MDS_PING 0x502 // for mds pinger #define MSG_MDS_SCRUB_STATS 0x503 // for mds scrub stack // *** generic *** #define MSG_TIMECHECK 0x600 #define MSG_MON_HEALTH 0x601 // *** Message::encode() crcflags bits *** #define MSG_CRC_DATA (1 << 0) #define MSG_CRC_HEADER (1 << 1) #define MSG_CRC_ALL (MSG_CRC_DATA | MSG_CRC_HEADER) // Special #define MSG_NOP 0x607 #define MSG_MON_HEALTH_CHECKS 0x608 #define MSG_TIMECHECK2 0x609 // *** ceph-mgr <-> OSD/MDS daemons *** #define MSG_MGR_OPEN 0x700 #define MSG_MGR_CONFIGURE 0x701 #define MSG_MGR_REPORT 0x702 // *** ceph-mgr <-> ceph-mon *** #define MSG_MGR_BEACON 0x703 // *** ceph-mon(MgrMonitor) -> OSD/MDS daemons *** #define MSG_MGR_MAP 0x704 // *** ceph-mon(MgrMonitor) -> ceph-mgr #define MSG_MGR_DIGEST 0x705 // *** cephmgr -> ceph-mon #define MSG_MON_MGR_REPORT 0x706 #define MSG_SERVICE_MAP 0x707 #define MSG_MGR_CLOSE 0x708 #define MSG_MGR_COMMAND 0x709 #define MSG_MGR_COMMAND_REPLY 0x70a // *** ceph-mgr <-> MON daemons *** #define MSG_MGR_UPDATE 0x70b // ====================================================== // abstract Message class class Message : public RefCountedObject { public: #ifdef WITH_SEASTAR // In crimson, conn is independently maintained outside Message. using ConnectionRef = void*; #else using ConnectionRef = ::ConnectionRef; #endif protected: ceph_msg_header header; // headerelope ceph_msg_footer footer; ceph::buffer::list payload; // "front" unaligned blob ceph::buffer::list middle; // "middle" unaligned blob ceph::buffer::list data; // data payload (page-alignment will be preserved where possible) /* recv_stamp is set when the Messenger starts reading the * Message off the wire */ utime_t recv_stamp; /* dispatch_stamp is set when the Messenger starts calling dispatch() on * its endpoints */ utime_t dispatch_stamp; /* throttle_stamp is the point at which we got throttle */ utime_t throttle_stamp; /* time at which message was fully read */ utime_t recv_complete_stamp; ConnectionRef connection; uint32_t magic = 0; boost::intrusive::list_member_hook<> dispatch_q; public: // zipkin tracing ZTracer::Trace trace; void encode_trace(ceph::buffer::list &bl, uint64_t features) const; void decode_trace(ceph::buffer::list::const_iterator &p, bool create = false); class CompletionHook : public Context { protected: Message *m; friend class Message; public: explicit CompletionHook(Message *_m) : m(_m) {} virtual void set_message(Message *_m) { m = _m; } }; typedef boost::intrusive::list<Message, boost::intrusive::member_hook< Message, boost::intrusive::list_member_hook<>, &Message::dispatch_q>> Queue; ceph::mono_time queue_start; protected: CompletionHook* completion_hook = nullptr; // owned by Messenger // release our size in bytes back to this throttler when our payload // is adjusted or when we are destroyed. ThrottleInterface *byte_throttler = nullptr; // release a count back to this throttler when we are destroyed ThrottleInterface *msg_throttler = nullptr; // keep track of how big this message was when we reserved space in // the msgr dispatch_throttler, so that we can properly release it // later. this is necessary because messages can enter the dispatch // queue locally (not via read_message()), and those are not // currently throttled. uint64_t dispatch_throttle_size = 0; friend class Messenger; public: Message() { memset(&header, 0, sizeof(header)); memset(&footer, 0, sizeof(footer)); } Message(int t, int version=1, int compat_version=0) { memset(&header, 0, sizeof(header)); header.type = t; header.version = version; header.compat_version = compat_version; memset(&footer, 0, sizeof(footer)); } Message *get() { return static_cast<Message *>(RefCountedObject::get()); } protected: ~Message() override { if (byte_throttler) byte_throttler->put(payload.length() + middle.length() + data.length()); release_message_throttle(); trace.event("message destructed"); /* call completion hooks (if any) */ if (completion_hook) completion_hook->complete(0); } public: const ConnectionRef& get_connection() const { #ifdef WITH_SEASTAR ceph_abort("In crimson, conn is independently maintained outside Message"); #endif return connection; } void set_connection(ConnectionRef c) { #ifdef WITH_SEASTAR // In crimson, conn is independently maintained outside Message. ceph_assert(c == nullptr); #endif connection = std::move(c); } CompletionHook* get_completion_hook() { return completion_hook; } void set_completion_hook(CompletionHook *hook) { completion_hook = hook; } void set_byte_throttler(ThrottleInterface *t) { byte_throttler = t; } void set_message_throttler(ThrottleInterface *t) { msg_throttler = t; } void set_dispatch_throttle_size(uint64_t s) { dispatch_throttle_size = s; } uint64_t get_dispatch_throttle_size() const { return dispatch_throttle_size; } const ceph_msg_header &get_header() const { return header; } ceph_msg_header &get_header() { return header; } void set_header(const ceph_msg_header &e) { header = e; } void set_footer(const ceph_msg_footer &e) { footer = e; } const ceph_msg_footer &get_footer() const { return footer; } ceph_msg_footer &get_footer() { return footer; } void set_src(const entity_name_t& src) { header.src = src; } uint32_t get_magic() const { return magic; } void set_magic(int _magic) { magic = _magic; } /* * If you use get_[data, middle, payload] you shouldn't * use it to change those ceph::buffer::lists unless you KNOW * there is no throttle being used. The other * functions are throttling-aware as appropriate. */ void clear_payload() { if (byte_throttler) { byte_throttler->put(payload.length() + middle.length()); } payload.clear(); middle.clear(); } virtual void clear_buffers() {} void clear_data() { if (byte_throttler) byte_throttler->put(data.length()); data.clear(); clear_buffers(); // let subclass drop buffers as well } void release_message_throttle() { if (msg_throttler) msg_throttler->put(); msg_throttler = nullptr; } bool empty_payload() const { return payload.length() == 0; } ceph::buffer::list& get_payload() { return payload; } const ceph::buffer::list& get_payload() const { return payload; } void set_payload(ceph::buffer::list& bl) { if (byte_throttler) byte_throttler->put(payload.length()); payload = std::move(bl); if (byte_throttler) byte_throttler->take(payload.length()); } void set_middle(ceph::buffer::list& bl) { if (byte_throttler) byte_throttler->put(middle.length()); middle = std::move(bl); if (byte_throttler) byte_throttler->take(middle.length()); } ceph::buffer::list& get_middle() { return middle; } void set_data(const ceph::buffer::list &bl) { if (byte_throttler) byte_throttler->put(data.length()); data.share(bl); if (byte_throttler) byte_throttler->take(data.length()); } const ceph::buffer::list& get_data() const { return data; } ceph::buffer::list& get_data() { return data; } void claim_data(ceph::buffer::list& bl) { if (byte_throttler) byte_throttler->put(data.length()); bl = std::move(data); } uint32_t get_data_len() const { return data.length(); } void set_recv_stamp(utime_t t) { recv_stamp = t; } const utime_t& get_recv_stamp() const { return recv_stamp; } void set_dispatch_stamp(utime_t t) { dispatch_stamp = t; } const utime_t& get_dispatch_stamp() const { return dispatch_stamp; } void set_throttle_stamp(utime_t t) { throttle_stamp = t; } const utime_t& get_throttle_stamp() const { return throttle_stamp; } void set_recv_complete_stamp(utime_t t) { recv_complete_stamp = t; } const utime_t& get_recv_complete_stamp() const { return recv_complete_stamp; } void calc_header_crc() { header.crc = ceph_crc32c(0, (unsigned char*)&header, sizeof(header) - sizeof(header.crc)); } void calc_front_crc() { footer.front_crc = payload.crc32c(0); footer.middle_crc = middle.crc32c(0); } void calc_data_crc() { footer.data_crc = data.crc32c(0); } virtual int get_cost() const { return data.length(); } // type int get_type() const { return header.type; } void set_type(int t) { header.type = t; } uint64_t get_tid() const { return header.tid; } void set_tid(uint64_t t) { header.tid = t; } uint64_t get_seq() const { return header.seq; } void set_seq(uint64_t s) { header.seq = s; } unsigned get_priority() const { return header.priority; } void set_priority(__s16 p) { header.priority = p; } // source/dest entity_inst_t get_source_inst() const { return entity_inst_t(get_source(), get_source_addr()); } entity_name_t get_source() const { return entity_name_t(header.src); } entity_addr_t get_source_addr() const { #ifdef WITH_SEASTAR ceph_abort("In crimson, conn is independently maintained outside Message"); #else if (connection) return connection->get_peer_addr(); #endif return entity_addr_t(); } entity_addrvec_t get_source_addrs() const { #ifdef WITH_SEASTAR ceph_abort("In crimson, conn is independently maintained outside Message"); #else if (connection) return connection->get_peer_addrs(); #endif return entity_addrvec_t(); } // forwarded? entity_inst_t get_orig_source_inst() const { return get_source_inst(); } entity_name_t get_orig_source() const { return get_source(); } entity_addr_t get_orig_source_addr() const { return get_source_addr(); } entity_addrvec_t get_orig_source_addrs() const { return get_source_addrs(); } // virtual bits virtual void decode_payload() = 0; virtual void encode_payload(uint64_t features) = 0; virtual std::string_view get_type_name() const = 0; virtual void print(std::ostream& out) const { out << get_type_name() << " magic: " << magic; } virtual void dump(ceph::Formatter *f) const; void encode(uint64_t features, int crcflags, bool skip_header_crc = false); }; extern Message *decode_message(CephContext *cct, int crcflags, ceph_msg_header& header, ceph_msg_footer& footer, ceph::buffer::list& front, ceph::buffer::list& middle, ceph::buffer::list& data, Message::ConnectionRef conn); inline std::ostream& operator<<(std::ostream& out, const Message& m) { m.print(out); if (m.get_header().version) out << " v" << m.get_header().version; return out; } extern void encode_message(Message *m, uint64_t features, ceph::buffer::list& bl); extern Message *decode_message(CephContext *cct, int crcflags, ceph::buffer::list::const_iterator& bl); /// this is a "safe" version of Message. it does not allow calling get/put /// methods on its derived classes. This is intended to prevent some accidental /// reference leaks by forcing . Instead, you must either cast the derived class to a /// RefCountedObject to do the get/put or detach a temporary reference. class SafeMessage : public Message { public: using Message::Message; bool is_a_client() const { #ifdef WITH_SEASTAR ceph_abort("In crimson, conn is independently maintained outside Message"); #else return get_connection()->get_peer_type() == CEPH_ENTITY_TYPE_CLIENT; #endif } private: using RefCountedObject::get; using RefCountedObject::put; }; namespace ceph { template<class T, typename... Args> ceph::ref_t<T> make_message(Args&&... args) { return {new T(std::forward<Args>(args)...), false}; } } namespace crimson { template<class T, typename... Args> MURef<T> make_message(Args&&... args) { return {new T(std::forward<Args>(args)...), TOPNSPC::common::UniquePtrDeleter{}}; } } template <std::derived_from<Message> M> struct fmt::formatter<M> { constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const M& m, FormatContext& ctx) const { std::ostringstream oss; m.print(oss); if (auto ver = m.get_header().version; ver) { return fmt::format_to(ctx.out(), "{} v{}", oss.str(), ver); } else { return fmt::format_to(ctx.out(), "{}", oss.str()); } } }; #endif
18,899
29.983607
102
h
null
ceph-main/src/msg/MessageRef.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) 2018 Red Hat, Inc. <[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_MESSAGEREF_H #define CEPH_MESSAGEREF_H #include <boost/intrusive_ptr.hpp> #include "common/RefCountedObj.h" template<typename T> using MRef = boost::intrusive_ptr<T>; template<typename T> using MConstRef = boost::intrusive_ptr<T const>; template<typename T> using MURef = std::unique_ptr<T, TOPNSPC::common::UniquePtrDeleter>; using MessageRef = MRef<class Message>; using MessageConstRef = MConstRef<class Message>; using MessageURef = MURef<class Message>; /* cd src/messages/ && for f in *; do printf 'class '; basename "$f" .h | tr -d '\n'; printf ';\n'; done >> ../msg/MessageRef.h */ class MAuth; class MAuthReply; class MBackfillReserve; class MCacheExpire; class MClientCapRelease; class MClientCaps; class MClientLease; class MClientQuota; class MClientReclaim; class MClientReclaimReply; class MClientReconnect; class MClientReply; class MClientRequestForward; class MClientRequest; class MClientSession; class MClientSnap; class MCommand; class MCommandReply; class MConfig; class MDentryLink; class MDentryUnlink; class MDirUpdate; class MDiscover; class MDiscoverReply; class MExportCapsAck; class MExportCaps; class MExportDirAck; class MExportDirCancel; class MExportDirDiscoverAck; class MExportDirDiscover; class MExportDirFinish; class MExportDir; class MExportDirNotifyAck; class MExportDirNotify; class MExportDirPrepAck; class MExportDirPrep; class MForward; class MFSMap; class MFSMapUser; class MGatherCaps; class MGenericMessage; class MGetConfig; class MGetPoolStats; class MGetPoolStatsReply; class MHeartbeat; class MInodeFileCaps; class MLock; class MLogAck; class MLog; class MMDSBeacon; class MMDSCacheRejoin; class MMDSFindIno; class MMDSFindInoReply; class MMDSFragmentNotifyAck; class MMDSFragmentNotify; class MMDSLoadTargets; class MMDSMap; class MMDSOpenIno; class MMDSOpenInoReply; class MMDSResolveAck; class MMDSResolve; class MMDSPeerRequest; class MMDSSnapUpdate; class MMDSTableRequest; class MMgrBeacon; class MMgrClose; class MMgrConfigure; class MMgrDigest; class MMgrMap; class MMgrOpen; class MMgrUpdate; class MMgrReport; class MMonCommandAck; class MMonCommand; class MMonElection; class MMonGetMap; class MMonGetOSDMap; class MMonGetVersion; class MMonGetVersionReply; class MMonGlobalID; class MMonHealthChecks; class MMonHealth; class MMonJoin; class MMonMap; class MMonMetadata; class MMonMgrReport; class MMonPaxos; class MMonProbe; class MMonQuorumService; class MMonScrub; class MMonSubscribeAck; class MMonSubscribe; class MMonSync; class MOSDAlive; class MOSDBackoff; class MOSDBeacon; class MOSDBoot; class MOSDECSubOpRead; class MOSDECSubOpReadReply; class MOSDECSubOpWrite; class MOSDECSubOpWriteReply; class MOSDFailure; class MOSDFastDispatchOp; class MOSDForceRecovery; class MOSDFull; class MOSDMap; class MOSDMarkMeDown; class MOSDPeeringOp; class MOSDPGBackfill; class MOSDPGBackfillRemove; class MOSDPGCreate2; class MOSDPGCreated; class MOSDPGInfo; class MOSDPGLog; class MOSDPGNotify; class MOSDPGPull; class MOSDPGPush; class MOSDPGPushReply; class MOSDPGQuery; class MOSDPGReadyToMerge; class MOSDPGRecoveryDelete; class MOSDPGRecoveryDeleteReply; class MOSDPGRemove; class MOSDPGScan; class MOSDPGTemp; class MOSDPGTrim; class MOSDPGUpdateLogMissing; class MOSDPGUpdateLogMissingReply; class MOSDPing; class MOSDRepOp; class MOSDRepOpReply; class MOSDRepScrub; class MOSDRepScrubMap; class MOSDScrub2; class MOSDScrubReserve; class MPGStatsAck; class MPGStats; class MPing; class MPoolOp; class MPoolOpReply; class MRecoveryReserve; class MRemoveSnaps; class MRoute; class MServiceMap; class MStatfs; class MStatfsReply; class MTimeCheck2; class MTimeCheck; class MWatchNotify; class PaxosServiceMessage; #endif
4,134
21.231183
130
h
null
ceph-main/src/msg/Messenger.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_MESSENGER_H #define CEPH_MESSENGER_H #include <deque> #include <map> #include <optional> #include <errno.h> #include <sstream> #include <memory> #include "Message.h" #include "Dispatcher.h" #include "Policy.h" #include "common/Throttle.h" #include "include/Context.h" #include "include/types.h" #include "include/ceph_features.h" #include "auth/Crypto.h" #include "common/item_history.h" #include "auth/AuthRegistry.h" #include "compressor_registry.h" #include "include/ceph_assert.h" #include <errno.h> #include <sstream> #include <signal.h> #define SOCKET_PRIORITY_MIN_DELAY 6 class Timer; class AuthClient; class AuthServer; #ifdef UNIT_TESTS_BUILT struct Interceptor { std::mutex lock; std::condition_variable cond_var; enum ACTION : uint32_t { CONTINUE = 0, FAIL, STOP }; enum STEP { START_CLIENT_BANNER_EXCHANGE = 1, START_SERVER_BANNER_EXCHANGE, BANNER_EXCHANGE_BANNER_CONNECTING, BANNER_EXCHANGE, HANDLE_PEER_BANNER_BANNER_CONNECTING, HANDLE_PEER_BANNER, HANDLE_PEER_BANNER_PAYLOAD_HELLO_CONNECTING, HANDLE_PEER_BANNER_PAYLOAD, SEND_AUTH_REQUEST, HANDLE_AUTH_REQUEST_ACCEPTING_SIGN, SEND_CLIENT_IDENTITY, SEND_SERVER_IDENTITY, SEND_RECONNECT, SEND_RECONNECT_OK, READY, HANDLE_MESSAGE, READ_MESSAGE_COMPLETE, SESSION_RETRY, SEND_COMPRESSION_REQUEST, HANDLE_COMPRESSION_REQUEST }; virtual ~Interceptor() {} virtual ACTION intercept(Connection *conn, uint32_t step) = 0; }; #endif class Messenger { private: std::deque<Dispatcher*> dispatchers; std::deque<Dispatcher*> fast_dispatchers; ZTracer::Endpoint trace_endpoint; protected: void set_endpoint_addr(const entity_addr_t& a, const entity_name_t &name); protected: /// the "name" of the local daemon. eg client.99 entity_name_t my_name; /// my addr safe_item_history<entity_addrvec_t> my_addrs; int default_send_priority; /// std::set to true once the Messenger has started, and std::set to false on shutdown bool started; uint32_t magic; int socket_priority; public: AuthClient *auth_client = 0; AuthServer *auth_server = 0; #ifdef UNIT_TESTS_BUILT Interceptor *interceptor = nullptr; #endif /** * The CephContext this Messenger uses. Many other components initialize themselves * from this value. */ CephContext *cct; int crcflags; using Policy = ceph::net::Policy<Throttle>; public: // allow unauthenticated connections. This is needed for // compatibility with pre-nautilus OSDs, which do not authenticate // the heartbeat sessions. bool require_authorizer = true; protected: // for authentication AuthRegistry auth_registry; public: /** * Messenger constructor. Call this from your implementation. * Messenger users should construct full implementations directly, * or use the create() function. */ Messenger(CephContext *cct_, entity_name_t w); virtual ~Messenger() {} /** * create a new messenger * * Create a new messenger instance, with whatever implementation is * available or specified via the configuration in cct. * * @param cct context * @param type name of messenger type * @param name entity name to register * @param lname logical name of the messenger in this process (e.g., "client") * @param nonce nonce value to uniquely identify this instance on the current host */ static Messenger *create(CephContext *cct, const std::string &type, entity_name_t name, std::string lname, uint64_t nonce); static uint64_t get_random_nonce(); /** * create a new messenger * * Create a new messenger instance. * Same as the above, but a slightly simpler interface for clients: * - Generate a random nonce * - get the messenger type from cct * - use the client entity_type * * @param cct context * @param lname logical name of the messenger in this process (e.g., "client") */ static Messenger *create_client_messenger(CephContext *cct, std::string lname); /** * @defgroup Accessors * @{ */ int get_mytype() const { return my_name.type(); } /** * Retrieve the Messenger's name * * @return A const reference to the name this Messenger * currently believes to be its own. */ const entity_name_t& get_myname() { return my_name; } /** * Retrieve the Messenger's address. * * @return A const reference to the address this Messenger * currently believes to be its own. */ const entity_addrvec_t& get_myaddrs() { return *my_addrs; } /** * get legacy addr for myself, suitable for protocol v1 * * Note that myaddrs might be a proper addrvec with v1 in it, or it might be an * ANY addr (if i am a pure client). */ entity_addr_t get_myaddr_legacy() { return my_addrs->as_legacy_addr(); } /** * std::set messenger's instance */ uint32_t get_magic() { return magic; } void set_magic(int _magic) { magic = _magic; } void set_auth_client(AuthClient *ac) { auth_client = ac; } void set_auth_server(AuthServer *as) { auth_server = as; } // for compression CompressorRegistry comp_registry; protected: /** * std::set messenger's address */ virtual void set_myaddrs(const entity_addrvec_t& a) { my_addrs = a; set_endpoint_addr(a.front(), my_name); } public: /** * @return the zipkin trace endpoint */ const ZTracer::Endpoint* get_trace_endpoint() const { return &trace_endpoint; } /** * set the name of the local entity. The name is reported to others and * can be changed while the system is running, but doing so at incorrect * times may have bad results. * * @param m The name to std::set. */ void set_myname(const entity_name_t& m) { my_name = m; } /** * set the unknown address components for this Messenger. * This is useful if the Messenger doesn't know its full address just by * binding, but another Messenger on the same interface has already learned * its full address. This function does not fill in known address elements, * cause a rebind, or do anything of that sort. * * @param addr The address to use as a template. */ virtual bool set_addr_unknowns(const entity_addrvec_t &addrs) = 0; /// Get the default send priority. int get_default_send_priority() { return default_send_priority; } /** * Get the number of Messages which the Messenger has received * but not yet dispatched. */ virtual int get_dispatch_queue_len() = 0; /** * Get age of oldest undelivered message * (0 if the queue is empty) */ virtual double get_dispatch_queue_max_age(utime_t now) = 0; /** * @} // Accessors */ /** * @defgroup Configuration * @{ */ /** * set the cluster protocol in use by this daemon. * This is an init-time function and cannot be called after calling * start() or bind(). * * @param p The cluster protocol to use. Defined externally. */ virtual void set_cluster_protocol(int p) = 0; /** * set a policy which is applied to all peers who do not have a type-specific * Policy. * This is an init-time function and cannot be called after calling * start() or bind(). * * @param p The Policy to apply. */ virtual void set_default_policy(Policy p) = 0; /** * set a policy which is applied to all peers of the given type. * This is an init-time function and cannot be called after calling * start() or bind(). * * @param type The peer type this policy applies to. * @param p The policy to apply. */ virtual void set_policy(int type, Policy p) = 0; /** * set the Policy associated with a type of peer. * * This can be called either on initial setup, or after connections * are already established. However, the policies for existing * connections will not be affected; the new policy will only apply * to future connections. * * @param t The peer type to get the default policy for. * @return A const Policy reference. */ virtual Policy get_policy(int t) = 0; /** * Get the default Policy * * @return A const Policy reference. */ virtual Policy get_default_policy() = 0; /** * set Throttlers applied to all Messages from the given type of peer * * This is an init-time function and cannot be called after calling * start() or bind(). * * @param type The peer type the Throttlers will apply to. * @param bytes The Throttle for the number of bytes carried by the message * @param msgs The Throttle for the number of messages for this @p type * @note The Messenger does not take ownership of the Throttle pointers, but * you must not destroy them before you destroy the Messenger. */ virtual void set_policy_throttlers(int type, Throttle *bytes, Throttle *msgs=NULL) = 0; /** * set the default send priority * * This is an init-time function and must be called *before* calling * start(). * * @param p The cluster protocol to use. Defined externally. */ void set_default_send_priority(int p) { ceph_assert(!started); default_send_priority = p; } /** * set the priority(SO_PRIORITY) for all packets to be sent on this socket. * * Linux uses this value to order the networking queues: packets with a higher * priority may be processed first depending on the selected device queueing * discipline. * * @param prio The priority. Setting a priority outside the range 0 to 6 * requires the CAP_NET_ADMIN capability. */ void set_socket_priority(int prio) { socket_priority = prio; } /** * Get the socket priority * * @return the socket priority */ int get_socket_priority() { return socket_priority; } /** * Add a new Dispatcher to the front of the list. If you add * a Dispatcher which is already included, it will get a duplicate * entry. This will reduce efficiency but not break anything. * * @param d The Dispatcher to insert into the list. */ void add_dispatcher_head(Dispatcher *d) { bool first = dispatchers.empty(); dispatchers.push_front(d); if (d->ms_can_fast_dispatch_any()) fast_dispatchers.push_front(d); if (first) ready(); } /** * Add a new Dispatcher to the end of the list. If you add * a Dispatcher which is already included, it will get a duplicate * entry. This will reduce efficiency but not break anything. * * @param d The Dispatcher to insert into the list. */ void add_dispatcher_tail(Dispatcher *d) { bool first = dispatchers.empty(); dispatchers.push_back(d); if (d->ms_can_fast_dispatch_any()) fast_dispatchers.push_back(d); if (first) ready(); } /** * Bind the Messenger to a specific address. If bind_addr * is not completely filled in the system will use the * valid portions and cycle through the unset ones (eg, the port) * in an unspecified order. * * @param bind_addr The address to bind to. * @patam public_addrs The addresses to announce over the network * @return 0 on success, or -1 on error, or -errno if * we can be more specific about the failure. */ virtual int bind(const entity_addr_t& bind_addr, std::optional<entity_addrvec_t> public_addrs=std::nullopt) = 0; virtual int bindv(const entity_addrvec_t& bind_addrs, std::optional<entity_addrvec_t> public_addrs=std::nullopt); /** * This function performs a full restart of the Messenger component, * whatever that means. Other entities who connect to this * Messenger post-rebind() should perceive it as a new entity which * they have not previously contacted, and it MUST bind to a * different address than it did previously. * * @param avoid_ports Additional port to avoid binding to. */ virtual int rebind(const std::set<int>& avoid_ports) { return -EOPNOTSUPP; } /** * Bind the 'client' Messenger to a specific address.Messenger will bind * the address before connect to others when option ms_bind_before_connect * is true. * @param bind_addr The address to bind to. * @return 0 on success, or -1 on error, or -errno if * we can be more specific about the failure. */ virtual int client_bind(const entity_addr_t& bind_addr) = 0; /** * reset the 'client' Messenger. Mark all the existing Connections down * and update 'nonce'. */ virtual int client_reset() = 0; virtual bool should_use_msgr2() { return false; } /** * @} // Configuration */ /** * @defgroup Startup/Shutdown * @{ */ /** * Perform any resource allocation, thread startup, etc * that is required before attempting to connect to other * Messengers or transmit messages. * Once this function completes, started shall be set to true. * * @return 0 on success; -errno on failure. */ virtual int start() { started = true; return 0; } // shutdown /** * Block until the Messenger has finished shutting down (according * to the shutdown() function). * It is valid to call this after calling shutdown(), but it must * be called before deleting the Messenger. */ virtual void wait() = 0; /** * Initiate a shutdown of the Messenger. * * @return 0 on success, -errno otherwise. */ virtual int shutdown() { started = false; return 0; } /** * @} // Startup/Shutdown */ /** * @defgroup Messaging * @{ */ /** * Queue the given Message for the given entity. * Success in this function does not guarantee Message delivery, only * success in queueing the Message. Other guarantees may be provided based * on the Connection policy associated with the dest. * * @param m The Message to send. The Messenger consumes a single reference * when you pass it in. * @param dest The entity to send the Message to. * * DEPRECATED: please do not use this interface for any new code; * use the Connection* variant. * * @return 0 on success, or -errno on failure. */ virtual int send_to( Message *m, int type, const entity_addrvec_t& addr) = 0; int send_to_mon( Message *m, const entity_addrvec_t& addrs) { return send_to(m, CEPH_ENTITY_TYPE_MON, addrs); } int send_to_mds( Message *m, const entity_addrvec_t& addrs) { return send_to(m, CEPH_ENTITY_TYPE_MDS, addrs); } /** * @} // Messaging */ /** * @defgroup Connection Management * @{ */ /** * Get the Connection object associated with a given entity. If a * Connection does not exist, create one and establish a logical connection. * The caller owns a reference when this returns. Call ->put() when you're * done! * * @param dest The entity to get a connection for. */ virtual ConnectionRef connect_to( int type, const entity_addrvec_t& dest, bool anon=false, bool not_local_dest=false) = 0; ConnectionRef connect_to_mon(const entity_addrvec_t& dest, bool anon=false, bool not_local_dest=false) { return connect_to(CEPH_ENTITY_TYPE_MON, dest, anon, not_local_dest); } ConnectionRef connect_to_mds(const entity_addrvec_t& dest, bool anon=false, bool not_local_dest=false) { return connect_to(CEPH_ENTITY_TYPE_MDS, dest, anon, not_local_dest); } ConnectionRef connect_to_osd(const entity_addrvec_t& dest, bool anon=false, bool not_local_dest=false) { return connect_to(CEPH_ENTITY_TYPE_OSD, dest, anon, not_local_dest); } ConnectionRef connect_to_mgr(const entity_addrvec_t& dest, bool anon=false, bool not_local_dest=false) { return connect_to(CEPH_ENTITY_TYPE_MGR, dest, anon, not_local_dest); } /** * Get the Connection object associated with ourselves. */ virtual ConnectionRef get_loopback_connection() = 0; /** * Mark down a Connection to a remote. * * This will cause us to discard our outgoing queue for them, and if * reset detection is enabled in the policy and the endpoint tries * to reconnect they will discard their queue when we inform them of * the session reset. * * If there is no Connection to the given dest, it is a no-op. * * This generates a RESET notification to the Dispatcher. * * DEPRECATED: please do not use this interface for any new code; * use the Connection* variant. * * @param a The address to mark down. */ virtual void mark_down(const entity_addr_t& a) = 0; virtual void mark_down_addrs(const entity_addrvec_t& a) { mark_down(a.legacy_addr()); } /** * Mark all the existing Connections down. This is equivalent * to iterating over all Connections and calling mark_down() * on each. * * This will generate a RESET event for each closed connections. */ virtual void mark_down_all() = 0; /** * @} // Connection Management */ protected: /** * @defgroup Subclass Interfacing * @{ */ /** * A courtesy function for Messenger implementations which * will be called when we receive our first Dispatcher. */ virtual void ready() { } /** * @} // Subclass Interfacing */ public: #ifdef CEPH_USE_SIGPIPE_BLOCKER /** * We need to disable SIGPIPE on all platforms, and if they * don't give us a better mechanism (read: are on Solaris) that * means blocking the signal whenever we do a send or sendmsg... * That means any implementations must invoke MSGR_SIGPIPE_STOPPER in-scope * whenever doing so. On most systems that's blank, but on systems where * it's needed we construct an RAII object to plug and un-plug the SIGPIPE. * See http://www.microhowto.info/howto/ignore_sigpipe_without_affecting_other_threads_in_a_process.html */ struct sigpipe_stopper { bool blocked; sigset_t existing_mask; sigset_t pipe_mask; sigpipe_stopper() { sigemptyset(&pipe_mask); sigaddset(&pipe_mask, SIGPIPE); sigset_t signals; sigemptyset(&signals); sigpending(&signals); if (sigismember(&signals, SIGPIPE)) { blocked = false; } else { blocked = true; int r = pthread_sigmask(SIG_BLOCK, &pipe_mask, &existing_mask); ceph_assert(r == 0); } } ~sigpipe_stopper() { if (blocked) { struct timespec nowait{0}; int r = sigtimedwait(&pipe_mask, 0, &nowait); ceph_assert(r == EAGAIN || r == 0); r = pthread_sigmask(SIG_SETMASK, &existing_mask, 0); ceph_assert(r == 0); } } }; # define MSGR_SIGPIPE_STOPPER Messenger::sigpipe_stopper stopper(); #else # define MSGR_SIGPIPE_STOPPER #endif /** * @defgroup Dispatcher Interfacing * @{ */ /** * Determine whether a message can be fast-dispatched. We will * query each Dispatcher in sequence to determine if they are * capable of handling a particular message via "fast dispatch". * * @param m The Message we are testing. */ bool ms_can_fast_dispatch(const ceph::cref_t<Message>& m) { for (const auto &dispatcher : fast_dispatchers) { if (dispatcher->ms_can_fast_dispatch2(m)) return true; } return false; } /** * Deliver a single Message via "fast dispatch". * * @param m The Message we are fast dispatching. * If none of our Dispatchers can handle it, ceph_abort(). */ void ms_fast_dispatch(const ceph::ref_t<Message> &m) { m->set_dispatch_stamp(ceph_clock_now()); for (const auto &dispatcher : fast_dispatchers) { if (dispatcher->ms_can_fast_dispatch2(m)) { dispatcher->ms_fast_dispatch2(m); return; } } ceph_abort(); } void ms_fast_dispatch(Message *m) { return ms_fast_dispatch(ceph::ref_t<Message>(m, false)); /* consume ref */ } /** * */ void ms_fast_preprocess(const ceph::ref_t<Message> &m) { for (const auto &dispatcher : fast_dispatchers) { dispatcher->ms_fast_preprocess2(m); } } /** * Deliver a single Message. Send it to each Dispatcher * in sequence until one of them handles it. * If none of our Dispatchers can handle it, ceph_abort(). * * @param m The Message to deliver. */ void ms_deliver_dispatch(const ceph::ref_t<Message> &m) { m->set_dispatch_stamp(ceph_clock_now()); for (const auto &dispatcher : dispatchers) { if (dispatcher->ms_dispatch2(m)) return; } lsubdout(cct, ms, 0) << "ms_deliver_dispatch: unhandled message " << m << " " << *m << " from " << m->get_source_inst() << dendl; ceph_assert(!cct->_conf->ms_die_on_unhandled_msg); } void ms_deliver_dispatch(Message *m) { return ms_deliver_dispatch(ceph::ref_t<Message>(m, false)); /* consume ref */ } /** * Notify each Dispatcher of a new Connection. Call * this function whenever a new Connection is initiated or * reconnects. * * @param con Pointer to the new Connection. */ void ms_deliver_handle_connect(Connection *con) { for (const auto& dispatcher : dispatchers) { dispatcher->ms_handle_connect(con); } } /** * Notify each fast Dispatcher of a new Connection. Call * this function whenever a new Connection is initiated or * reconnects. * * @param con Pointer to the new Connection. */ void ms_deliver_handle_fast_connect(Connection *con) { for (const auto& dispatcher : fast_dispatchers) { dispatcher->ms_handle_fast_connect(con); } } /** * Notify each Dispatcher of a new incoming Connection. Call * this function whenever a new Connection is accepted. * * @param con Pointer to the new Connection. */ void ms_deliver_handle_accept(Connection *con) { for (const auto& dispatcher : dispatchers) { dispatcher->ms_handle_accept(con); } } /** * Notify each fast Dispatcher of a new incoming Connection. Call * this function whenever a new Connection is accepted. * * @param con Pointer to the new Connection. */ void ms_deliver_handle_fast_accept(Connection *con) { for (const auto& dispatcher : fast_dispatchers) { dispatcher->ms_handle_fast_accept(con); } } /** * Notify each Dispatcher of a Connection which may have lost * Messages. Call this function whenever you detect that a lossy Connection * has been disconnected. * * @param con Pointer to the broken Connection. */ void ms_deliver_handle_reset(Connection *con) { for (const auto& dispatcher : dispatchers) { if (dispatcher->ms_handle_reset(con)) return; } } /** * Notify each Dispatcher of a Connection which has been "forgotten" about * by the remote end, implying that messages have probably been lost. * Call this function whenever you detect a reset. * * @param con Pointer to the broken Connection. */ void ms_deliver_handle_remote_reset(Connection *con) { for (const auto& dispatcher : dispatchers) { dispatcher->ms_handle_remote_reset(con); } } /** * Notify each Dispatcher of a Connection for which reconnection * attempts are being refused. Call this function whenever you * detect that a lossy Connection has been disconnected and it's * impossible to reconnect. * * @param con Pointer to the broken Connection. */ void ms_deliver_handle_refused(Connection *con) { for (const auto& dispatcher : dispatchers) { if (dispatcher->ms_handle_refused(con)) return; } } void set_require_authorizer(bool b) { require_authorizer = b; } /** * @} // Dispatcher Interfacing */ }; #endif
23,947
27.957678
106
h
null
ceph-main/src/msg/Policy.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include "include/ceph_features.h" namespace ceph::net { using peer_type_t = int; /** * A Policy describes the rules of a Connection. Is there a limit on how * much data this Connection can have locally? When the underlying connection * experiences an error, does the Connection disappear? Can this Messenger * re-establish the underlying connection? */ template<class ThrottleType> struct Policy { /// If true, the Connection is tossed out on errors. bool lossy; /// If true, the underlying connection can't be re-established from this end. bool server; /// If true, we will standby when idle bool standby; /// If true, we will try to detect session resets bool resetcheck; /// Server: register lossy client connections. bool register_lossy_clients = true; // The net result of this is that a given client can only have one // open connection with the server. If a new connection is made, // the old (registered) one is closed by the messenger during the accept // process. /** * The throttler is used to limit how much data is held by Messages from * the associated Connection(s). When reading in a new Message, the Messenger * will call throttler->throttle() for the size of the new Message. */ ThrottleType* throttler_bytes; ThrottleType* throttler_messages; /// Specify features supported locally by the endpoint. #ifdef MSG_POLICY_UNIT_TESTING uint64_t features_supported{CEPH_FEATURES_SUPPORTED_DEFAULT}; #else static constexpr uint64_t features_supported{CEPH_FEATURES_SUPPORTED_DEFAULT}; #endif /// Specify features any remotes must have to talk to this endpoint. uint64_t features_required; Policy() : lossy(false), server(false), standby(false), resetcheck(true), throttler_bytes(NULL), throttler_messages(NULL), features_required(0) {} private: Policy(bool l, bool s, bool st, bool r, bool rlc, uint64_t req) : lossy(l), server(s), standby(st), resetcheck(r), register_lossy_clients(rlc), throttler_bytes(NULL), throttler_messages(NULL), features_required(req) {} public: static Policy stateful_server(uint64_t req) { return Policy(false, true, true, true, true, req); } static Policy stateless_registered_server(uint64_t req) { return Policy(true, true, false, false, true, req); } static Policy stateless_server(uint64_t req) { return Policy(true, true, false, false, false, req); } static Policy lossless_peer(uint64_t req) { return Policy(false, false, true, false, true, req); } static Policy lossless_peer_reuse(uint64_t req) { return Policy(false, false, true, true, true, req); } static Policy lossy_client(uint64_t req) { return Policy(true, false, false, false, true, req); } static Policy lossless_client(uint64_t req) { return Policy(false, false, false, true, true, req); } }; template<class ThrottleType> class PolicySet { using policy_t = Policy<ThrottleType> ; /// the default Policy we use for Pipes policy_t default_policy; /// map specifying different Policies for specific peer types std::map<int, policy_t> policy_map; // entity_name_t::type -> Policy public: const policy_t& get(peer_type_t peer_type) const { if (auto found = policy_map.find(peer_type); found != policy_map.end()) { return found->second; } else { return default_policy; } } policy_t& get(peer_type_t peer_type) { if (auto found = policy_map.find(peer_type); found != policy_map.end()) { return found->second; } else { return default_policy; } } void set(peer_type_t peer_type, const policy_t& p) { policy_map[peer_type] = p; } const policy_t& get_default() const { return default_policy; } void set_default(const policy_t& p) { default_policy = p; } void set_throttlers(peer_type_t peer_type, ThrottleType* byte_throttle, ThrottleType* msg_throttle) { auto& policy = get(peer_type); policy.throttler_bytes = byte_throttle; policy.throttler_messages = msg_throttle; } }; }
4,232
30.827068
80
h
null
ceph-main/src/msg/SimplePolicyMessenger.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]> * Portions Copyright (C) 2013 CohortFS, 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. * */ #ifndef SIMPLE_POLICY_MESSENGER_H #define SIMPLE_POLICY_MESSENGER_H #include "Messenger.h" #include "Policy.h" class SimplePolicyMessenger : public Messenger { private: /// lock protecting policy ceph::mutex policy_lock = ceph::make_mutex("SimplePolicyMessenger::policy_lock"); // entity_name_t::type -> Policy ceph::net::PolicySet<Throttle> policy_set; public: SimplePolicyMessenger(CephContext *cct, entity_name_t name) : Messenger(cct, name) { } /** * Get the Policy associated with a type of peer. * @param t The peer type to get the default policy for. * * @return A const Policy reference. */ Policy get_policy(int t) override { std::lock_guard l{policy_lock}; return policy_set.get(t); } Policy get_default_policy() override { std::lock_guard l{policy_lock}; return policy_set.get_default(); } /** * Set a policy which is applied to all peers who do not have a type-specific * Policy. * This is an init-time function and cannot be called after calling * start() or bind(). * * @param p The Policy to apply. */ void set_default_policy(Policy p) override { std::lock_guard l{policy_lock}; policy_set.set_default(p); } /** * Set a policy which is applied to all peers of the given type. * This is an init-time function and cannot be called after calling * start() or bind(). * * @param type The peer type this policy applies to. * @param p The policy to apply. */ void set_policy(int type, Policy p) override { std::lock_guard l{policy_lock}; policy_set.set(type, p); } /** * Set a Throttler which is applied to all Messages from the given * type of peer. * This is an init-time function and cannot be called after calling * start() or bind(). * * @param type The peer type this Throttler will apply to. * @param t The Throttler to apply. The messenger does not take * ownership of this pointer, but you must not destroy it before * you destroy messenger. */ void set_policy_throttlers(int type, Throttle* byte_throttle, Throttle* msg_throttle) override { std::lock_guard l{policy_lock}; policy_set.set_throttlers(type, byte_throttle, msg_throttle); } }; /* SimplePolicyMessenger */ #endif /* SIMPLE_POLICY_MESSENGER_H */
2,806
27.07
79
h
null
ceph-main/src/msg/compressor_registry.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 <vector> #include "compressor/Compressor.h" #include "common/ceph_mutex.h" #include "common/ceph_context.h" #include "common/config_cacher.h" class CompressorRegistry : public md_config_obs_t { public: CompressorRegistry(CephContext *cct); ~CompressorRegistry(); void refresh_config() { std::scoped_lock l(lock); _refresh_config(); } const char** get_tracked_conf_keys() const override; void handle_conf_change(const ConfigProxy& conf, const std::set<std::string>& changed) override; TOPNSPC::Compressor::CompressionAlgorithm pick_method(uint32_t peer_type, const std::vector<uint32_t>& preferred_methods); TOPNSPC::Compressor::CompressionMode get_mode(uint32_t peer_type, bool is_secure); const std::vector<uint32_t> get_methods(uint32_t peer_type) { std::scoped_lock l(lock); switch (peer_type) { case CEPH_ENTITY_TYPE_OSD: return ms_osd_compression_methods; default: return {}; } } uint64_t get_min_compression_size(uint32_t peer_type) const { std::scoped_lock l(lock); switch (peer_type) { case CEPH_ENTITY_TYPE_OSD: return ms_osd_compress_min_size; default: return 0; } } bool get_is_compress_secure() const { std::scoped_lock l(lock); return ms_compress_secure; } private: CephContext *cct; mutable ceph::mutex lock = ceph::make_mutex("CompressorRegistry::lock"); uint32_t ms_osd_compress_mode; bool ms_compress_secure; std::uint64_t ms_osd_compress_min_size; std::vector<uint32_t> ms_osd_compression_methods; void _refresh_config(); std::vector<uint32_t> _parse_method_list(const std::string& s); };
1,838
25.271429
84
h
null
ceph-main/src/msg/msg_fmt.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once /** * \file fmtlib formatters for some msg_types.h classes */ #include <fmt/format.h> #include "msg/msg_types.h" template <> struct fmt::formatter<entity_name_t> { constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const entity_name_t& addr, FormatContext& ctx) { if (addr.is_new() || addr.num() < 0) { return fmt::format_to(ctx.out(), "{}.?", addr.type_str()); } return fmt::format_to(ctx.out(), "{}.{}", addr.type_str(), addr.num()); } };
654
24.192308
75
h
null
ceph-main/src/msg/msg_types.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_MSG_TYPES_H #define CEPH_MSG_TYPES_H #include <sstream> #include <netinet/in.h> #include <fmt/format.h> #if FMT_VERSION >= 90000 #include <fmt/ostream.h> #endif #include "include/ceph_features.h" #include "include/types.h" #include "include/blobhash.h" #include "include/encoding.h" #define MAX_PORT_NUMBER 65535 #ifdef _WIN32 // ceph_sockaddr_storage matches the Linux format. #define AF_INET6_LINUX 10 #endif namespace ceph { class Formatter; } std::ostream& operator<<(std::ostream& out, const sockaddr_storage &ss); std::ostream& operator<<(std::ostream& out, const sockaddr *sa); typedef uint8_t entity_type_t; class entity_name_t { public: entity_type_t _type; int64_t _num; public: static const int TYPE_MON = CEPH_ENTITY_TYPE_MON; static const int TYPE_MDS = CEPH_ENTITY_TYPE_MDS; static const int TYPE_OSD = CEPH_ENTITY_TYPE_OSD; static const int TYPE_CLIENT = CEPH_ENTITY_TYPE_CLIENT; static const int TYPE_MGR = CEPH_ENTITY_TYPE_MGR; static const int64_t NEW = -1; // cons entity_name_t() : _type(0), _num(0) { } entity_name_t(int t, int64_t n) : _type(t), _num(n) { } explicit entity_name_t(const ceph_entity_name &n) : _type(n.type), _num(n.num) { } // static cons static entity_name_t MON(int64_t i=NEW) { return entity_name_t(TYPE_MON, i); } static entity_name_t MDS(int64_t i=NEW) { return entity_name_t(TYPE_MDS, i); } static entity_name_t OSD(int64_t i=NEW) { return entity_name_t(TYPE_OSD, i); } static entity_name_t CLIENT(int64_t i=NEW) { return entity_name_t(TYPE_CLIENT, i); } static entity_name_t MGR(int64_t i=NEW) { return entity_name_t(TYPE_MGR, i); } int64_t num() const { return _num; } int type() const { return _type; } const char *type_str() const { return ceph_entity_type_name(type()); } bool is_new() const { return num() < 0; } bool is_client() const { return type() == TYPE_CLIENT; } bool is_mds() const { return type() == TYPE_MDS; } bool is_osd() const { return type() == TYPE_OSD; } bool is_mon() const { return type() == TYPE_MON; } bool is_mgr() const { return type() == TYPE_MGR; } operator ceph_entity_name() const { ceph_entity_name n = { _type, ceph_le64(_num) }; return n; } bool parse(std::string_view s); DENC(entity_name_t, v, p) { denc(v._type, p); denc(v._num, p); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<entity_name_t*>& o); }; WRITE_CLASS_DENC(entity_name_t) inline bool operator== (const entity_name_t& l, const entity_name_t& r) { return (l.type() == r.type()) && (l.num() == r.num()); } inline bool operator!= (const entity_name_t& l, const entity_name_t& r) { return (l.type() != r.type()) || (l.num() != r.num()); } inline bool operator< (const entity_name_t& l, const entity_name_t& r) { return (l.type() < r.type()) || (l.type() == r.type() && l.num() < r.num()); } inline std::ostream& operator<<(std::ostream& out, const entity_name_t& addr) { //if (addr.is_namer()) return out << "namer"; if (addr.is_new() || addr.num() < 0) return out << addr.type_str() << ".?"; else return out << addr.type_str() << '.' << addr.num(); } inline std::ostream& operator<<(std::ostream& out, const ceph_entity_name& addr) { return out << entity_name_t{addr.type, static_cast<int64_t>(addr.num)}; } namespace std { template<> struct hash< entity_name_t > { size_t operator()( const entity_name_t &m ) const { return rjhash32(m.type() ^ m.num()); } }; } // namespace std // define a wire format for sockaddr that matches Linux's. struct ceph_sockaddr_storage { ceph_le16 ss_family; __u8 __ss_padding[128 - sizeof(ceph_le16)]; void encode(ceph::buffer::list& bl) const { struct ceph_sockaddr_storage ss = *this; ss.ss_family = htons(ss.ss_family); ceph::encode_raw(ss, bl); } void decode(ceph::buffer::list::const_iterator& bl) { struct ceph_sockaddr_storage ss; ceph::decode_raw(ss, bl); ss.ss_family = ntohs(ss.ss_family); *this = ss; } } __attribute__ ((__packed__)); WRITE_CLASS_ENCODER(ceph_sockaddr_storage) /* * encode sockaddr.ss_family as network byte order */ static inline void encode(const sockaddr_storage& a, ceph::buffer::list& bl) { #if defined(__linux__) struct sockaddr_storage ss = a; ss.ss_family = htons(ss.ss_family); ceph::encode_raw(ss, bl); #elif defined(__FreeBSD__) || defined(__APPLE__) ceph_sockaddr_storage ss{}; auto src = (unsigned char const *)&a; auto dst = (unsigned char *)&ss; src += sizeof(a.ss_len); ss.ss_family = a.ss_family; src += sizeof(a.ss_family); dst += sizeof(ss.ss_family); const auto copy_size = std::min((unsigned char*)(&a + 1) - src, (unsigned char*)(&ss + 1) - dst); ::memcpy(dst, src, copy_size); encode(ss, bl); #elif defined(_WIN32) ceph_sockaddr_storage ss{}; ::memcpy(&ss, &a, std::min(sizeof(ss), sizeof(a))); // The Windows AF_INET6 definition doesn't match the Linux one. if (a.ss_family == AF_INET6) { ss.ss_family = AF_INET6_LINUX; } encode(ss, bl); #else ceph_sockaddr_storage ss; ::memset(&ss, '\0', sizeof(ss)); ::memcpy(&ss, &a, std::min(sizeof(ss), sizeof(a))); encode(ss, bl); #endif } static inline void decode(sockaddr_storage& a, ceph::buffer::list::const_iterator& bl) { #if defined(__linux__) ceph::decode_raw(a, bl); a.ss_family = ntohs(a.ss_family); #elif defined(__FreeBSD__) || defined(__APPLE__) ceph_sockaddr_storage ss{}; decode(ss, bl); auto src = (unsigned char const *)&ss; auto dst = (unsigned char *)&a; a.ss_len = 0; dst += sizeof(a.ss_len); a.ss_family = ss.ss_family; src += sizeof(ss.ss_family); dst += sizeof(a.ss_family); auto const copy_size = std::min((unsigned char*)(&ss + 1) - src, (unsigned char*)(&a + 1) - dst); ::memcpy(dst, src, copy_size); #elif defined(_WIN32) ceph_sockaddr_storage ss{}; decode(ss, bl); ::memcpy(&a, &ss, std::min(sizeof(ss), sizeof(a))); if (a.ss_family == AF_INET6_LINUX) { a.ss_family = AF_INET6; } #else ceph_sockaddr_storage ss{}; decode(ss, bl); ::memcpy(&a, &ss, std::min(sizeof(ss), sizeof(a))); #endif } /* * an entity's network address. * includes a random value that prevents it from being reused. * thus identifies a particular process instance. * * This also happens to work to support cidr ranges, in which * case the nonce contains the netmask. It's great! */ struct entity_addr_t { typedef enum { TYPE_NONE = 0, TYPE_LEGACY = 1, ///< legacy msgr1 protocol (ceph jewel and older) TYPE_MSGR2 = 2, ///< msgr2 protocol (new in ceph kraken) TYPE_ANY = 3, ///< ambiguous TYPE_CIDR = 4, } type_t; static const type_t TYPE_DEFAULT = TYPE_MSGR2; static std::string_view get_type_name(int t) { switch (t) { case TYPE_NONE: return "none"; case TYPE_LEGACY: return "v1"; case TYPE_MSGR2: return "v2"; case TYPE_ANY: return "any"; case TYPE_CIDR: return "cidr"; default: return "???"; } }; __u32 type; __u32 nonce; union { sockaddr sa; sockaddr_in sin; sockaddr_in6 sin6; } u; entity_addr_t() : type(0), nonce(0) { memset(&u, 0, sizeof(u)); } entity_addr_t(__u32 _type, __u32 _nonce) : type(_type), nonce(_nonce) { memset(&u, 0, sizeof(u)); } explicit entity_addr_t(const ceph_entity_addr &o) { type = o.type; nonce = o.nonce; memcpy(&u, &o.in_addr, sizeof(u)); #if !defined(__FreeBSD__) u.sa.sa_family = ntohs(u.sa.sa_family); #endif } uint32_t get_type() const { return type; } void set_type(uint32_t t) { type = t; } bool is_legacy() const { return type == TYPE_LEGACY; } bool is_msgr2() const { return type == TYPE_MSGR2; } bool is_any() const { return type == TYPE_ANY; } // this isn't a guarantee; some client addrs will match it bool maybe_cidr() const { return get_port() == 0 && nonce != 0; } __u32 get_nonce() const { return nonce; } void set_nonce(__u32 n) { nonce = n; } int get_family() const { return u.sa.sa_family; } void set_family(int f) { u.sa.sa_family = f; } bool is_ipv4() const { return u.sa.sa_family == AF_INET; } bool is_ipv6() const { return u.sa.sa_family == AF_INET6; } sockaddr_in &in4_addr() { return u.sin; } const sockaddr_in &in4_addr() const{ return u.sin; } sockaddr_in6 &in6_addr(){ return u.sin6; } const sockaddr_in6 &in6_addr() const{ return u.sin6; } const sockaddr *get_sockaddr() const { return &u.sa; } size_t get_sockaddr_len() const { switch (u.sa.sa_family) { case AF_INET: return sizeof(u.sin); case AF_INET6: return sizeof(u.sin6); } return sizeof(u); } bool set_sockaddr(const struct sockaddr *sa) { switch (sa->sa_family) { case AF_INET: // pre-zero, since we're only copying a portion of the source memset(&u, 0, sizeof(u)); memcpy(&u.sin, sa, sizeof(u.sin)); break; case AF_INET6: // pre-zero, since we're only copying a portion of the source memset(&u, 0, sizeof(u)); memcpy(&u.sin6, sa, sizeof(u.sin6)); break; case AF_UNSPEC: memset(&u, 0, sizeof(u)); break; default: return false; } return true; } sockaddr_storage get_sockaddr_storage() const { sockaddr_storage ss; memcpy(&ss, &u, sizeof(u)); memset((char*)&ss + sizeof(u), 0, sizeof(ss) - sizeof(u)); return ss; } void set_in4_quad(int pos, int val) { u.sin.sin_family = AF_INET; unsigned char *ipq = (unsigned char*)&u.sin.sin_addr.s_addr; ipq[pos] = val; } void set_port(int port) { switch (u.sa.sa_family) { case AF_INET: u.sin.sin_port = htons(port); break; case AF_INET6: u.sin6.sin6_port = htons(port); break; default: ceph_abort(); } } int get_port() const { switch (u.sa.sa_family) { case AF_INET: return ntohs(u.sin.sin_port); case AF_INET6: return ntohs(u.sin6.sin6_port); } return 0; } operator ceph_entity_addr() const { ceph_entity_addr a; a.type = 0; a.nonce = nonce; a.in_addr = get_sockaddr_storage(); #if !defined(__FreeBSD__) a.in_addr.ss_family = htons(a.in_addr.ss_family); #endif return a; } bool probably_equals(const entity_addr_t &o) const { if (get_port() != o.get_port()) return false; if (get_nonce() != o.get_nonce()) return false; if (is_blank_ip() || o.is_blank_ip()) return true; if (memcmp(&u, &o.u, sizeof(u)) == 0) return true; return false; } bool is_same_host(const entity_addr_t &o) const { if (u.sa.sa_family != o.u.sa.sa_family) return false; if (u.sa.sa_family == AF_INET) return u.sin.sin_addr.s_addr == o.u.sin.sin_addr.s_addr; if (u.sa.sa_family == AF_INET6) return memcmp(u.sin6.sin6_addr.s6_addr, o.u.sin6.sin6_addr.s6_addr, sizeof(u.sin6.sin6_addr.s6_addr)) == 0; return false; } bool is_blank_ip() const { switch (u.sa.sa_family) { case AF_INET: return u.sin.sin_addr.s_addr == INADDR_ANY; case AF_INET6: return memcmp(&u.sin6.sin6_addr, &in6addr_any, sizeof(in6addr_any)) == 0; default: return true; } } bool is_ip() const { switch (u.sa.sa_family) { case AF_INET: case AF_INET6: return true; default: return false; } } std::string ip_only_to_str() const; std::string ip_n_port_to_str() const; std::string get_legacy_str() const { std::ostringstream ss; ss << get_sockaddr() << "/" << get_nonce(); return ss.str(); } bool parse(const std::string_view s, int default_type=TYPE_DEFAULT); bool parse(const char *s, const char **end = 0, int default_type=TYPE_DEFAULT); void decode_legacy_addr_after_marker(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 marker; __u16 rest; decode(marker, bl); decode(rest, bl); decode(nonce, bl); sockaddr_storage ss; decode(ss, bl); set_sockaddr((sockaddr*)&ss); if (get_family() == AF_UNSPEC) { type = TYPE_NONE; } else { type = TYPE_LEGACY; } } // Right now, these only deal with sockaddr_storage that have only family and content. // Apparently on BSD there is also an ss_len that we need to handle; this requires // broader study void encode(ceph::buffer::list& bl, uint64_t features) const { using ceph::encode; if ((features & CEPH_FEATURE_MSG_ADDR2) == 0) { encode((__u32)0, bl); encode(nonce, bl); sockaddr_storage ss = get_sockaddr_storage(); encode(ss, bl); return; } encode((__u8)1, bl); ENCODE_START(1, 1, bl); if (HAVE_FEATURE(features, SERVER_NAUTILUS)) { encode(type, bl); } else { // map any -> legacy for old clients. this is primary for the benefit // of OSDMap's blocklist, but is reasonable in general since any: is // meaningless for pre-nautilus clients or daemons. auto t = type; if (t == TYPE_ANY) { t = TYPE_LEGACY; } encode(t, bl); } encode(nonce, bl); __u32 elen = get_sockaddr_len(); #if (__FreeBSD__) || defined(__APPLE__) elen -= sizeof(u.sa.sa_len); #endif encode(elen, bl); if (elen) { uint16_t ss_family = u.sa.sa_family; #if defined(_WIN32) if (ss_family == AF_INET6) { ss_family = AF_INET6_LINUX; } #endif encode(ss_family, bl); elen -= sizeof(u.sa.sa_family); bl.append(u.sa.sa_data, elen); } ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; __u8 marker; decode(marker, bl); if (marker == 0) { decode_legacy_addr_after_marker(bl); return; } if (marker != 1) throw ceph::buffer::malformed_input("entity_addr_t marker != 1"); DECODE_START(1, bl); decode(type, bl); decode(nonce, bl); __u32 elen; decode(elen, bl); if (elen) { #if defined(__FreeBSD__) || defined(__APPLE__) u.sa.sa_len = 0; #endif uint16_t ss_family; if (elen < sizeof(ss_family)) { throw ceph::buffer::malformed_input("elen smaller than family len"); } decode(ss_family, bl); #if defined(_WIN32) if (ss_family == AF_INET6_LINUX) { ss_family = AF_INET6; } #endif u.sa.sa_family = ss_family; elen -= sizeof(ss_family); if (elen > get_sockaddr_len() - sizeof(u.sa.sa_family)) { throw ceph::buffer::malformed_input("elen exceeds sockaddr len"); } bl.copy(elen, u.sa.sa_data); } DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<entity_addr_t*>& o); }; WRITE_CLASS_ENCODER_FEATURES(entity_addr_t) std::ostream& operator<<(std::ostream& out, const entity_addr_t &addr); #if FMT_VERSION >= 90000 template <> struct fmt::formatter<entity_addr_t> : fmt::ostream_formatter {}; #endif inline bool operator==(const entity_addr_t& a, const entity_addr_t& b) { return memcmp(&a, &b, sizeof(a)) == 0; } inline bool operator!=(const entity_addr_t& a, const entity_addr_t& b) { return memcmp(&a, &b, sizeof(a)) != 0; } inline bool operator<(const entity_addr_t& a, const entity_addr_t& b) { return memcmp(&a, &b, sizeof(a)) < 0; } inline bool operator<=(const entity_addr_t& a, const entity_addr_t& b) { return memcmp(&a, &b, sizeof(a)) <= 0; } inline bool operator>(const entity_addr_t& a, const entity_addr_t& b) { return memcmp(&a, &b, sizeof(a)) > 0; } inline bool operator>=(const entity_addr_t& a, const entity_addr_t& b) { return memcmp(&a, &b, sizeof(a)) >= 0; } namespace std { template<> struct hash<entity_addr_t> { size_t operator()( const entity_addr_t& x ) const { static blobhash H; return H(&x, sizeof(x)); } }; } // namespace std struct entity_addrvec_t { std::vector<entity_addr_t> v; entity_addrvec_t() {} explicit entity_addrvec_t(const entity_addr_t& a) : v({ a }) {} unsigned size() const { return v.size(); } bool empty() const { return v.empty(); } entity_addr_t legacy_addr() const { return addr_of_type(entity_addr_t::TYPE_LEGACY); } entity_addr_t as_legacy_addr() const { for (auto& a : v) { if (a.is_legacy()) { return a; } if (a.is_any()) { auto b = a; b.set_type(entity_addr_t::TYPE_LEGACY); return b; } } // hrm... lie! auto a = front(); a.set_type(entity_addr_t::TYPE_LEGACY); return a; } entity_addr_t front() const { if (!v.empty()) { return v.front(); } return entity_addr_t(); } entity_addr_t legacy_or_front_addr() const { for (auto& a : v) { if (a.type == entity_addr_t::TYPE_LEGACY) { return a; } } return front(); } std::string get_legacy_str() const { return legacy_or_front_addr().get_legacy_str(); } entity_addr_t msgr2_addr() const { return addr_of_type(entity_addr_t::TYPE_MSGR2); } bool has_msgr2() const { for (auto& a : v) { if (a.is_msgr2()) { return true; } } return false; } entity_addr_t pick_addr(uint32_t type) const { entity_addr_t picked_addr; switch (type) { case entity_addr_t::TYPE_LEGACY: [[fallthrough]]; case entity_addr_t::TYPE_MSGR2: picked_addr = addr_of_type(type); break; case entity_addr_t::TYPE_ANY: return front(); default: return {}; } if (!picked_addr.is_blank_ip()) { return picked_addr; } else { return addr_of_type(entity_addr_t::TYPE_ANY); } } entity_addr_t addr_of_type(uint32_t type) const { for (auto &a : v) { if (a.type == type) { return a; } } return entity_addr_t(); } bool parse(const char *s, const char **end = 0); void get_ports(std::set<int> *ports) const { for (auto& a : v) { ports->insert(a.get_port()); } } std::set<int> get_ports() const { std::set<int> r; get_ports(&r); return r; } void encode(ceph::buffer::list& bl, uint64_t features) const; void decode(ceph::buffer::list::const_iterator& bl); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<entity_addrvec_t*>& ls); bool legacy_equals(const entity_addrvec_t& o) const { if (v == o.v) { return true; } if (v.size() == 1 && front().is_legacy() && front() == o.legacy_addr()) { return true; } if (o.v.size() == 1 && o.front().is_legacy() && o.front() == legacy_addr()) { return true; } return false; } bool probably_equals(const entity_addrvec_t& o) const { for (unsigned i = 0; i < v.size(); ++i) { if (!v[i].probably_equals(o.v[i])) { return false; } } return true; } bool contains(const entity_addr_t& a) const { for (auto& i : v) { if (a == i) { return true; } } return false; } bool is_same_host(const entity_addr_t& a) const { for (auto& i : v) { if (i.is_same_host(a)) { return true; } } return false; } friend std::ostream& operator<<(std::ostream& out, const entity_addrvec_t& av) { if (av.v.empty()) { return out; } else if (av.v.size() == 1) { return out << av.v[0]; } else { return out << av.v; } } friend bool operator==(const entity_addrvec_t& l, const entity_addrvec_t& r) { return l.v == r.v; } friend bool operator!=(const entity_addrvec_t& l, const entity_addrvec_t& r) { return l.v != r.v; } friend bool operator<(const entity_addrvec_t& l, const entity_addrvec_t& r) { return l.v < r.v; // see lexicographical_compare() } friend bool operator>(const entity_addrvec_t& l, const entity_addrvec_t& r) { return l.v > r.v; // see lexicographical_compare() } }; WRITE_CLASS_ENCODER_FEATURES(entity_addrvec_t); #if FMT_VERSION >= 90000 template <> struct fmt::formatter<entity_addrvec_t> : fmt::ostream_formatter {}; #endif namespace std { template<> struct hash<entity_addrvec_t> { size_t operator()( const entity_addrvec_t& x) const { static blobhash H; size_t r = 0; for (auto& i : x.v) { r += H((const char*)&i, sizeof(i)); } return r; } }; } // namespace std /* * a particular entity instance */ struct entity_inst_t { entity_name_t name; entity_addr_t addr; entity_inst_t() {} entity_inst_t(entity_name_t n, const entity_addr_t& a) : name(n), addr(a) {} // cppcheck-suppress noExplicitConstructor entity_inst_t(const ceph_entity_inst& i) : name(i.name), addr(i.addr) { } entity_inst_t(const ceph_entity_name& n, const ceph_entity_addr &a) : name(n), addr(a) {} operator ceph_entity_inst() { ceph_entity_inst i = {name, addr}; return i; } void encode(ceph::buffer::list& bl, uint64_t features) const { using ceph::encode; encode(name, bl); encode(addr, bl, features); } void decode(ceph::buffer::list::const_iterator& bl) { using ceph::decode; decode(name, bl); decode(addr, bl); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<entity_inst_t*>& o); }; WRITE_CLASS_ENCODER_FEATURES(entity_inst_t) inline bool operator==(const entity_inst_t& a, const entity_inst_t& b) { return a.name == b.name && a.addr == b.addr; } inline bool operator!=(const entity_inst_t& a, const entity_inst_t& b) { return a.name != b.name || a.addr != b.addr; } inline bool operator<(const entity_inst_t& a, const entity_inst_t& b) { return a.name < b.name || (a.name == b.name && a.addr < b.addr); } inline bool operator<=(const entity_inst_t& a, const entity_inst_t& b) { return a.name < b.name || (a.name == b.name && a.addr <= b.addr); } inline bool operator>(const entity_inst_t& a, const entity_inst_t& b) { return b < a; } inline bool operator>=(const entity_inst_t& a, const entity_inst_t& b) { return b <= a; } namespace std { template<> struct hash< entity_inst_t > { size_t operator()( const entity_inst_t& x ) const { static hash< entity_name_t > H; static hash< entity_addr_t > I; return H(x.name) ^ I(x.addr); } }; } // namespace std inline std::ostream& operator<<(std::ostream& out, const entity_inst_t &i) { return out << i.name << " " << i.addr; } inline std::ostream& operator<<(std::ostream& out, const ceph_entity_inst &i) { entity_inst_t n = i; return out << n; } #endif
22,865
26.417266
113
h
null
ceph-main/src/msg/async/AsyncConnection.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 UnitedStack <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_MSG_ASYNCCONNECTION_H #define CEPH_MSG_ASYNCCONNECTION_H #include <atomic> #include <pthread.h> #include <climits> #include <list> #include <mutex> #include <map> #include <functional> #include <optional> #include "auth/AuthSessionHandler.h" #include "common/ceph_time.h" #include "common/perf_counters.h" #include "include/buffer.h" #include "msg/Connection.h" #include "msg/Messenger.h" #include "Event.h" #include "Stack.h" class AsyncMessenger; class DispatchQueue; class Worker; class Protocol; static const int ASYNC_IOV_MAX = (IOV_MAX >= 1024 ? IOV_MAX / 4 : IOV_MAX); /* * AsyncConnection maintains a logic session between two endpoints. In other * word, a pair of addresses can find the only AsyncConnection. AsyncConnection * will handle with network fault or read/write transactions. If one file * descriptor broken, AsyncConnection will maintain the message queue and * sequence, try to reconnect peer endpoint. */ class AsyncConnection : public Connection { ssize_t read(unsigned len, char *buffer, std::function<void(char *, ssize_t)> callback); ssize_t read_until(unsigned needed, char *p); ssize_t read_bulk(char *buf, unsigned len); ssize_t write(ceph::buffer::list &bl, std::function<void(ssize_t)> callback, bool more=false); ssize_t _try_send(bool more=false); void _connect(); void _stop(); void fault(); void inject_delay(); bool inject_network_congestion() const; bool is_queued() const; void shutdown_socket(); /** * The DelayedDelivery is for injecting delays into Message delivery off * the socket. It is only enabled if delays are requested, and if they * are then it pulls Messages off the DelayQueue and puts them into the * AsyncMessenger event queue. */ class DelayedDelivery : public EventCallback { std::set<uint64_t> register_time_events; // need to delete it if stop std::deque<Message*> delay_queue; std::mutex delay_lock; AsyncMessenger *msgr; EventCenter *center; DispatchQueue *dispatch_queue; uint64_t conn_id; std::atomic_bool stop_dispatch; public: explicit DelayedDelivery(AsyncMessenger *omsgr, EventCenter *c, DispatchQueue *q, uint64_t cid) : msgr(omsgr), center(c), dispatch_queue(q), conn_id(cid), stop_dispatch(false) { } ~DelayedDelivery() override { ceph_assert(register_time_events.empty()); ceph_assert(delay_queue.empty()); } void set_center(EventCenter *c) { center = c; } void do_request(uint64_t id) override; void queue(double delay_period, Message *m) { std::lock_guard<std::mutex> l(delay_lock); delay_queue.push_back(m); register_time_events.insert(center->create_time_event(delay_period*1000000, this)); } void discard(); bool ready() const { return !stop_dispatch && delay_queue.empty() && register_time_events.empty(); } void flush(); } *delay_state; private: FRIEND_MAKE_REF(AsyncConnection); AsyncConnection(CephContext *cct, AsyncMessenger *m, DispatchQueue *q, Worker *w, bool is_msgr2, bool local); ~AsyncConnection() override; bool unregistered = false; public: void maybe_start_delay_thread(); std::ostream& _conn_prefix(std::ostream *_dout); bool is_connected() override; // Only call when AsyncConnection first construct void connect(const entity_addrvec_t& addrs, int type, entity_addr_t& target); // Only call when AsyncConnection first construct void accept(ConnectedSocket socket, const entity_addr_t &listen_addr, const entity_addr_t &peer_addr); int send_message(Message *m) override; void send_keepalive() override; void mark_down() override; void mark_disposable() override { std::lock_guard<std::mutex> l(lock); policy.lossy = true; } entity_addr_t get_peer_socket_addr() const override { return target_addr; } int get_con_mode() const override; bool is_unregistered() const { return unregistered; } void unregister() { unregistered = true; } private: enum { STATE_NONE, STATE_CONNECTING, STATE_CONNECTING_RE, STATE_ACCEPTING, STATE_CONNECTION_ESTABLISHED, STATE_CLOSED }; static const uint32_t TCP_PREFETCH_MIN_SIZE; static const char *get_state_name(int state) { const char* const statenames[] = {"STATE_NONE", "STATE_CONNECTING", "STATE_CONNECTING_RE", "STATE_ACCEPTING", "STATE_CONNECTION_ESTABLISHED", "STATE_CLOSED"}; return statenames[state]; } AsyncMessenger *async_msgr; uint64_t conn_id; PerfCounters *logger; PerfCounters *labeled_logger; int state; ConnectedSocket cs; int port; public: Messenger::Policy policy; private: DispatchQueue *dispatch_queue; // lockfree, only used in own thread ceph::buffer::list outgoing_bl; bool open_write = false; std::mutex write_lock; std::mutex lock; EventCallbackRef read_handler; EventCallbackRef write_handler; EventCallbackRef write_callback_handler; EventCallbackRef wakeup_handler; EventCallbackRef tick_handler; char *recv_buf; uint32_t recv_max_prefetch; uint32_t recv_start; uint32_t recv_end; std::set<uint64_t> register_time_events; // need to delete it if stop ceph::coarse_mono_clock::time_point last_connect_started; ceph::coarse_mono_clock::time_point last_active; ceph::mono_clock::time_point recv_start_time; uint64_t last_tick_id = 0; const uint64_t connect_timeout_us; const uint64_t inactive_timeout_us; // Tis section are temp variables used by state transition // Accepting state bool msgr2 = false; entity_addr_t socket_addr; ///< local socket addr entity_addr_t target_addr; ///< which of the peer_addrs we're connecting to (as clienet) or should reconnect to (as peer) entity_addr_t _infer_target_addr(const entity_addrvec_t& av); // used only by "read_until" uint64_t state_offset; Worker *worker; EventCenter *center; std::unique_ptr<Protocol> protocol; std::optional<std::function<void(ssize_t)>> writeCallback; std::function<void(char *, ssize_t)> readCallback; std::optional<unsigned> pendingReadLen; char *read_buffer; public: // used by eventcallback void handle_write(); void handle_write_callback(); void process(); void wakeup_from(uint64_t id); void tick(uint64_t id); void stop(bool queue_reset); void cleanup(); PerfCounters *get_perf_counter() { return logger; } bool is_msgr2() const override; friend class Protocol; friend class ProtocolV1; friend class ProtocolV2; }; /* AsyncConnection */ using AsyncConnectionRef = ceph::ref_t<AsyncConnection>; #endif
7,342
27.909449
124
h
null
ceph-main/src/msg/async/AsyncMessenger.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 UnitedStack <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_ASYNCMESSENGER_H #define CEPH_ASYNCMESSENGER_H #include <map> #include <optional> #include "include/types.h" #include "include/xlist.h" #include "include/spinlock.h" #include "include/unordered_map.h" #include "include/unordered_set.h" #include "common/ceph_mutex.h" #include "common/Cond.h" #include "common/Thread.h" #include "msg/SimplePolicyMessenger.h" #include "msg/DispatchQueue.h" #include "AsyncConnection.h" #include "Event.h" #include "include/ceph_assert.h" class AsyncMessenger; /** * If the Messenger binds to a specific address, the Processor runs * and listens for incoming connections. */ class Processor { AsyncMessenger *msgr; ceph::NetHandler net; Worker *worker; std::vector<ServerSocket> listen_sockets; EventCallbackRef listen_handler; class C_processor_accept; public: Processor(AsyncMessenger *r, Worker *w, CephContext *c); ~Processor() { delete listen_handler; }; void stop(); int bind(const entity_addrvec_t &bind_addrs, const std::set<int>& avoid_ports, entity_addrvec_t* bound_addrs); void start(); void accept(); }; /* * AsyncMessenger is represented for maintaining a set of asynchronous connections, * it may own a bind address and the accepted connections will be managed by * AsyncMessenger. * */ class AsyncMessenger : public SimplePolicyMessenger { // First we have the public Messenger interface implementation... public: /** * Initialize the AsyncMessenger! * * @param cct The CephContext to use * @param name The name to assign ourselves * _nonce A unique ID to use for this AsyncMessenger. It should not * be a value that will be repeated if the daemon restarts. */ AsyncMessenger(CephContext *cct, entity_name_t name, const std::string &type, std::string mname, uint64_t _nonce); /** * Destroy the AsyncMessenger. Pretty simple since all the work is done * elsewhere. */ ~AsyncMessenger() override; /** @defgroup Accessors * @{ */ bool set_addr_unknowns(const entity_addrvec_t &addr) override; int get_dispatch_queue_len() override { return dispatch_queue.get_queue_len(); } double get_dispatch_queue_max_age(utime_t now) override { return dispatch_queue.get_max_age(now); } /** @} Accessors */ /** * @defgroup Configuration functions * @{ */ void set_cluster_protocol(int p) override { ceph_assert(!started && !did_bind); cluster_protocol = p; } int bind(const entity_addr_t& bind_addr, std::optional<entity_addrvec_t> public_addrs=std::nullopt) override; int rebind(const std::set<int>& avoid_ports) override; int bindv(const entity_addrvec_t& bind_addrs, std::optional<entity_addrvec_t> public_addrs=std::nullopt) override; int client_bind(const entity_addr_t& bind_addr) override; int client_reset() override; bool should_use_msgr2() override; /** @} Configuration functions */ /** * @defgroup Startup/Shutdown * @{ */ int start() override; void wait() override; int shutdown() override; /** @} // Startup/Shutdown */ /** * @defgroup Messaging * @{ */ int send_to(Message *m, int type, const entity_addrvec_t& addrs) override; /** @} // Messaging */ /** * @defgroup Connection Management * @{ */ ConnectionRef connect_to(int type, const entity_addrvec_t& addrs, bool anon, bool not_local_dest=false) override; ConnectionRef get_loopback_connection() override; void mark_down(const entity_addr_t& addr) override { mark_down_addrs(entity_addrvec_t(addr)); } void mark_down_addrs(const entity_addrvec_t& addrs) override; void mark_down_all() override { shutdown_connections(true); } /** @} // Connection Management */ /** * @defgroup Inner classes * @{ */ /** * @} // Inner classes */ protected: /** * @defgroup Messenger Interfaces * @{ */ /** * Start up the DispatchQueue thread once we have somebody to dispatch to. */ void ready() override; /** @} // Messenger Interfaces */ private: /** * @defgroup Utility functions * @{ */ /** * Create a connection associated with the given entity (of the given type). * Initiate the connection. (This function returning does not guarantee * connection success.) * * @param addrs The address(es) of the entity to connect to. * @param type The peer type of the entity at the address. * * @return a pointer to the newly-created connection. Caller does not own a * reference; take one if you need it. */ AsyncConnectionRef create_connect(const entity_addrvec_t& addrs, int type, bool anon); void _finish_bind(const entity_addrvec_t& bind_addrs, const entity_addrvec_t& listen_addrs); entity_addrvec_t _filter_addrs(const entity_addrvec_t& addrs); private: NetworkStack *stack; std::vector<Processor*> processors; friend class Processor; DispatchQueue dispatch_queue; // the worker run messenger's cron jobs Worker *local_worker; std::string ms_type; /// overall lock used for AsyncMessenger data structures ceph::mutex lock = ceph::make_mutex("AsyncMessenger::lock"); // AsyncMessenger stuff /// approximately unique ID set by the Constructor for use in entity_addr_t uint64_t nonce; /// true, specifying we haven't learned our addr; set false when we find it. // maybe this should be protected by the lock? bool need_addr = true; /** * set to bind addresses if bind or bindv were called before NetworkStack * was ready to bind */ entity_addrvec_t pending_bind_addrs; /** * set to public addresses (those announced by the msgr's protocols). * they are stored to handle the cases when either: * a) bind or bindv were called before NetworkStack was ready to bind, * b) rebind is called down the road. */ std::optional<entity_addrvec_t> saved_public_addrs; /** * false; set to true if a pending bind exists */ bool pending_bind = false; /** * The following aren't lock-protected since you shouldn't be able to race * the only writers. */ /** * false; set to true if the AsyncMessenger bound to a specific address; * and set false again by Accepter::stop(). */ bool did_bind = false; /// counter for the global seq our connection protocol uses __u32 global_seq = 0; /// lock to protect the global_seq ceph::spinlock global_seq_lock; /** * hash map of addresses to Asyncconnection * * NOTE: a Asyncconnection* with state CLOSED may still be in the map but is considered * invalid and can be replaced by anyone holding the msgr lock */ ceph::unordered_map<entity_addrvec_t, AsyncConnectionRef> conns; /** * list of connection are in the process of accepting * * These are not yet in the conns map. */ std::set<AsyncConnectionRef> accepting_conns; /// anonymous outgoing connections std::set<AsyncConnectionRef> anon_conns; /** * list of connection are closed which need to be clean up * * Because AsyncMessenger and AsyncConnection follow a lock rule that * we can lock AsyncMesenger::lock firstly then lock AsyncConnection::lock * but can't reversed. This rule is aimed to avoid dead lock. * So if AsyncConnection want to unregister itself from AsyncMessenger, * we pick up this idea that just queue itself to this set and do lazy * deleted for AsyncConnection. "_lookup_conn" must ensure not return a * AsyncConnection in this set. */ ceph::mutex deleted_lock = ceph::make_mutex("AsyncMessenger::deleted_lock"); std::set<AsyncConnectionRef> deleted_conns; EventCallbackRef reap_handler; /// internal cluster protocol version, if any, for talking to entities of the same type. int cluster_protocol = 0; ceph::condition_variable stop_cond; bool stopped = true; /* You must hold this->lock for the duration of use! */ const auto& _lookup_conn(const entity_addrvec_t& k) { static const AsyncConnectionRef nullref; ceph_assert(ceph_mutex_is_locked(lock)); auto p = conns.find(k); if (p == conns.end()) { return nullref; } // lazy delete, see "deleted_conns" // don't worry omit, Connection::send_message can handle this case. if (p->second->is_unregistered()) { std::lock_guard l{deleted_lock}; if (deleted_conns.erase(p->second)) { p->second->get_perf_counter()->dec(l_msgr_active_connections); conns.erase(p); return nullref; } } return p->second; } void _init_local_connection() { ceph_assert(ceph_mutex_is_locked(lock)); local_connection->peer_addrs = *my_addrs; local_connection->peer_type = my_name.type(); local_connection->set_features(CEPH_FEATURES_ALL); ms_deliver_handle_fast_connect(local_connection.get()); } void shutdown_connections(bool queue_reset); public: /// con used for sending messages to ourselves AsyncConnectionRef local_connection; /** * @defgroup AsyncMessenger internals * @{ */ /** * This wraps _lookup_conn. */ AsyncConnectionRef lookup_conn(const entity_addrvec_t& k) { std::lock_guard l{lock}; return _lookup_conn(k); /* make new ref! */ } int accept_conn(const AsyncConnectionRef& conn); bool learned_addr(const entity_addr_t &peer_addr_for_me); void add_accept(Worker *w, ConnectedSocket cli_socket, const entity_addr_t &listen_addr, const entity_addr_t &peer_addr); NetworkStack *get_stack() { return stack; } uint64_t get_nonce() const { return nonce; } /** * Increment the global sequence for this AsyncMessenger and return it. * This is for the connect protocol, although it doesn't hurt if somebody * else calls it. * * @return a global sequence ID that nobody else has seen. */ __u32 get_global_seq(__u32 old=0) { std::lock_guard<ceph::spinlock> lg(global_seq_lock); if (old > global_seq) global_seq = old; __u32 ret = ++global_seq; return ret; } /** * Get the protocol version we support for the given peer type: either * a peer protocol (if it matches our own), the protocol version for the * peer (if we're connecting), or our protocol version (if we're accepting). */ int get_proto_version(int peer_type, bool connect) const; /** * Fill in the address and peer type for the local connection, which * is used for delivering messages back to ourself. */ void init_local_connection() { std::lock_guard l{lock}; local_connection->is_loopback = true; _init_local_connection(); } /** * Unregister connection from `conns` * * See "deleted_conns" */ void unregister_conn(const AsyncConnectionRef& conn) { std::lock_guard l{deleted_lock}; deleted_conns.emplace(std::move(conn)); conn->unregister(); if (deleted_conns.size() >= cct->_conf->ms_async_reap_threshold) { local_worker->center.dispatch_event_external(reap_handler); } } /** * Reap dead connection from `deleted_conns` * * @return the number of dead connections * * See "deleted_conns" */ void reap_dead(); /** * @} // AsyncMessenger Internals */ } ; #endif /* CEPH_ASYNCMESSENGER_H */
11,699
25.958525
90
h
null
ceph-main/src/msg/async/Event.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 UnitedStack <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_MSG_EVENT_H #define CEPH_MSG_EVENT_H #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif // We use epoll, kqueue, evport, select in descending order by performance. #if defined(__linux__) #define HAVE_EPOLL 1 #endif #if (defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined (__NetBSD__) #define HAVE_KQUEUE 1 #endif #ifdef _WIN32 #define HAVE_POLL 1 #endif #ifdef __sun #include <sys/feature_tests.h> #ifdef _DTRACE_VERSION #define HAVE_EVPORT 1 #endif #endif #include <atomic> #include <mutex> #include <condition_variable> #include "common/ceph_time.h" #include "common/dout.h" #include "net_handler.h" #define EVENT_NONE 0 #define EVENT_READABLE 1 #define EVENT_WRITABLE 2 class EventCenter; class EventCallback { public: virtual void do_request(uint64_t fd_or_id) = 0; virtual ~EventCallback() {} // we want a virtual destructor!!! }; typedef EventCallback* EventCallbackRef; struct FiredFileEvent { int fd; int mask; }; /* * EventDriver is a wrap of event mechanisms depends on different OS. * For example, Linux will use epoll(2), BSD will use kqueue(2) and select will * be used for worst condition. */ class EventDriver { public: virtual ~EventDriver() {} // we want a virtual destructor!!! virtual int init(EventCenter *center, int nevent) = 0; virtual int add_event(int fd, int cur_mask, int mask) = 0; virtual int del_event(int fd, int cur_mask, int del_mask) = 0; virtual int event_wait(std::vector<FiredFileEvent> &fired_events, struct timeval *tp) = 0; virtual int resize_events(int newsize) = 0; virtual bool need_wakeup() { return true; } }; /* * EventCenter maintain a set of file descriptor and handle registered events. */ class EventCenter { public: // should be enough; static const int MAX_EVENTCENTER = 24; private: using clock_type = ceph::coarse_mono_clock; struct AssociatedCenters { EventCenter *centers[MAX_EVENTCENTER]; AssociatedCenters() { // FIPS zeroization audit 20191115: this memset is not security related. memset(centers, 0, MAX_EVENTCENTER * sizeof(EventCenter*)); } }; struct FileEvent { int mask; EventCallbackRef read_cb; EventCallbackRef write_cb; FileEvent(): mask(0), read_cb(NULL), write_cb(NULL) {} }; struct TimeEvent { uint64_t id; EventCallbackRef time_cb; TimeEvent(): id(0), time_cb(NULL) {} }; public: /** * A Poller object is invoked once each time through the dispatcher's * inner polling loop. */ class Poller { public: explicit Poller(EventCenter* center, const std::string& pollerName); virtual ~Poller(); /** * This method is defined by a subclass and invoked once by the * center during each pass through its inner polling loop. * * \return * 1 means that this poller did useful work during this call. * 0 means that the poller found no work to do. */ virtual int poll() = 0; private: /// The EventCenter object that owns this Poller. NULL means the /// EventCenter has been deleted. EventCenter* owner; /// Human-readable string name given to the poller to make it /// easy to identify for debugging. For most pollers just passing /// in the subclass name probably makes sense. std::string poller_name; /// Index of this Poller in EventCenter::pollers. Allows deletion /// without having to scan all the entries in pollers. -1 means /// this poller isn't currently in EventCenter::pollers (happens /// after EventCenter::reset). int slot; }; private: CephContext *cct; std::string type; int nevent; // Used only to external event pthread_t owner = 0; std::mutex external_lock; std::atomic_ulong external_num_events; std::deque<EventCallbackRef> external_events; std::vector<FileEvent> file_events; EventDriver *driver; std::multimap<clock_type::time_point, TimeEvent> time_events; // Keeps track of all of the pollers currently defined. We don't // use an intrusive list here because it isn't reentrant: we need // to add/remove elements while the center is traversing the list. std::vector<Poller*> pollers; std::map<uint64_t, std::multimap<clock_type::time_point, TimeEvent>::iterator> event_map; uint64_t time_event_next_id; int notify_receive_fd; int notify_send_fd; ceph::NetHandler net; EventCallbackRef notify_handler; unsigned center_id; AssociatedCenters *global_centers = nullptr; int process_time_events(); FileEvent *_get_file_event(int fd) { ceph_assert(fd < nevent); return &file_events[fd]; } public: explicit EventCenter(CephContext *c): cct(c), nevent(0), external_num_events(0), driver(NULL), time_event_next_id(1), notify_receive_fd(-1), notify_send_fd(-1), net(c), notify_handler(NULL), center_id(0) { } ~EventCenter(); std::ostream& _event_prefix(std::ostream *_dout); int init(int nevent, unsigned center_id, const std::string &type); void set_owner(); pthread_t get_owner() const { return owner; } unsigned get_id() const { return center_id; } EventDriver *get_driver() { return driver; } // Used by internal thread int create_file_event(int fd, int mask, EventCallbackRef ctxt); uint64_t create_time_event(uint64_t milliseconds, EventCallbackRef ctxt); void delete_file_event(int fd, int mask); void delete_time_event(uint64_t id); int process_events(unsigned timeout_microseconds, ceph::timespan *working_dur = nullptr); void wakeup(); // Used by external thread void dispatch_event_external(EventCallbackRef e); inline bool in_thread() const { return pthread_equal(pthread_self(), owner); } private: template <typename func> class C_submit_event : public EventCallback { std::mutex lock; std::condition_variable cond; bool done = false; func f; bool nonwait; public: C_submit_event(func &&_f, bool nowait) : f(std::move(_f)), nonwait(nowait) {} void do_request(uint64_t id) override { f(); lock.lock(); cond.notify_all(); done = true; bool del = nonwait; lock.unlock(); if (del) delete this; } void wait() { ceph_assert(!nonwait); std::unique_lock<std::mutex> l(lock); while (!done) cond.wait(l); } }; public: template <typename func> void submit_to(int i, func &&f, bool always_async = false) { ceph_assert(i < MAX_EVENTCENTER && global_centers); EventCenter *c = global_centers->centers[i]; ceph_assert(c); if (always_async) { C_submit_event<func> *event = new C_submit_event<func>(std::move(f), true); c->dispatch_event_external(event); } else if (c->in_thread()) { f(); return; } else { C_submit_event<func> event(std::move(f), false); c->dispatch_event_external(&event); event.wait(); } }; }; #endif
7,469
26.666667
130
h
null
ceph-main/src/msg/async/EventEpoll.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 UnitedStack <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_MSG_EVENTEPOLL_H #define CEPH_MSG_EVENTEPOLL_H #include <unistd.h> #include <sys/epoll.h> #include "Event.h" class EpollDriver : public EventDriver { int epfd; struct epoll_event *events; CephContext *cct; int nevent; public: explicit EpollDriver(CephContext *c): epfd(-1), events(NULL), cct(c), nevent(0) {} ~EpollDriver() override { if (epfd != -1) close(epfd); if (events) free(events); } int init(EventCenter *c, int nevent) override; int add_event(int fd, int cur_mask, int add_mask) override; int del_event(int fd, int cur_mask, int del_mask) override; int resize_events(int newsize) override; int event_wait(std::vector<FiredFileEvent> &fired_events, struct timeval *tp) override; }; #endif
1,244
23.9
84
h
null
ceph-main/src/msg/async/EventKqueue.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 UnitedStack <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_MSG_EVENTKQUEUE_H #define CEPH_MSG_EVENTKQUEUE_H #include <sys/types.h> #include <sys/event.h> #include <unistd.h> #include "Event.h" class KqueueDriver : public EventDriver { int kqfd; pthread_t mythread; struct kevent *res_events; CephContext *cct; int size; // Keep what we set on the kqfd struct SaveEvent{ int fd; int mask; }; struct SaveEvent *sav_events; int sav_max; int restore_events(); int test_kqfd(); int test_thread_change(const char* funcname); public: explicit KqueueDriver(CephContext *c): kqfd(-1), res_events(NULL), cct(c), size(0), sav_max(0) {} virtual ~KqueueDriver() { if (kqfd != -1) close(kqfd); if (res_events) free(res_events); size = 0; if (sav_events) free(sav_events); sav_max = 0; } int init(EventCenter *c, int nevent) override; int add_event(int fd, int cur_mask, int add_mask) override; int del_event(int fd, int cur_mask, int del_mask) override; int resize_events(int newsize) override; int event_wait(std::vector<FiredFileEvent> &fired_events, struct timeval *tp) override; }; #endif
1,614
22.75
77
h
null
ceph-main/src/msg/async/EventPoll.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) 2022 Rafael Lopez <[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_MSG_EVENTPOLL_H #define CEPH_MSG_EVENTPOLL_H #ifdef _WIN32 #include <winsock2.h> #else #include <poll.h> #endif #include "Event.h" typedef struct pollfd POLLFD; class PollDriver : public EventDriver { int max_pfds; int hard_max_pfds; POLLFD *pfds; CephContext *cct; private: int poll_ctl(int, int, int); public: explicit PollDriver(CephContext *c): cct(c) {} ~PollDriver() override {} int init(EventCenter *c, int nevent) override; int add_event(int fd, int cur_mask, int add_mask) override; int del_event(int fd, int cur_mask, int del_mask) override; int resize_events(int newsize) override; int event_wait(std::vector<FiredFileEvent> &fired_events, struct timeval *tp) override; }; #endif
1,177
22.098039
71
h
null
ceph-main/src/msg/async/EventSelect.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 UnitedStack <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_MSG_EVENTSELECT_H #define CEPH_MSG_EVENTSELECT_H #include "Event.h" class SelectDriver : public EventDriver { fd_set rfds, wfds; /* We need to have a copy of the fd sets as it's not safe to reuse * FD sets after select(). */ fd_set _rfds, _wfds; int max_fd; CephContext *cct; public: explicit SelectDriver(CephContext *c): max_fd(0), cct(c) {} ~SelectDriver() override {} int init(EventCenter *c, int nevent) override; int add_event(int fd, int cur_mask, int add_mask) override; int del_event(int fd, int cur_mask, int del_mask) override; int resize_events(int newsize) override; int event_wait(std::vector<FiredFileEvent> &fired_events, struct timeval *tp) override; }; #endif
1,205
27.046512
71
h
null
ceph-main/src/msg/async/PosixStack.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 XSKY <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_MSG_ASYNC_POSIXSTACK_H #define CEPH_MSG_ASYNC_POSIXSTACK_H #include <thread> #include "msg/msg_types.h" #include "msg/async/net_handler.h" #include "Stack.h" class PosixWorker : public Worker { ceph::NetHandler net; void initialize() override; public: PosixWorker(CephContext *c, unsigned i) : Worker(c, i), net(c) {} int listen(entity_addr_t &sa, unsigned addr_slot, const SocketOptions &opt, ServerSocket *socks) override; int connect(const entity_addr_t &addr, const SocketOptions &opts, ConnectedSocket *socket) override; }; class PosixNetworkStack : public NetworkStack { std::vector<std::thread> threads; virtual Worker* create_worker(CephContext *c, unsigned worker_id) override { return new PosixWorker(c, worker_id); } public: explicit PosixNetworkStack(CephContext *c); void spawn_worker(std::function<void ()> &&func) override { threads.emplace_back(std::move(func)); } void join_worker(unsigned i) override { ceph_assert(threads.size() > i && threads[i].joinable()); threads[i].join(); } }; #endif //CEPH_MSG_ASYNC_POSIXSTACK_H
1,594
25.583333
102
h
null
ceph-main/src/msg/async/Protocol.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef _MSG_ASYNC_PROTOCOL_ #define _MSG_ASYNC_PROTOCOL_ #include <list> #include <map> #include "AsyncConnection.h" #include "include/buffer.h" #include "include/msgr.h" /* * Continuation Helper Classes */ #include <memory> #include <tuple> template <class C> class Ct { public: virtual ~Ct() {} virtual Ct<C> *call(C *foo) const = 0; }; template <class C, typename... Args> class CtFun : public Ct<C> { private: using fn_t = Ct<C> *(C::*)(Args...); fn_t _f; std::tuple<Args...> _params; template <std::size_t... Is> inline Ct<C> *_call(C *foo, std::index_sequence<Is...>) const { return (foo->*_f)(std::get<Is>(_params)...); } public: CtFun(fn_t f) : _f(f) {} inline void setParams(Args... args) { _params = std::make_tuple(args...); } inline Ct<C> *call(C *foo) const override { return _call(foo, std::index_sequence_for<Args...>()); } }; using rx_buffer_t = std::unique_ptr<ceph::buffer::ptr_node, ceph::buffer::ptr_node::disposer>; template <class C> class CtRxNode : public Ct<C> { using fn_t = Ct<C> *(C::*)(rx_buffer_t&&, int r); fn_t _f; public: mutable rx_buffer_t node; int r; CtRxNode(fn_t f) : _f(f) {} void setParams(rx_buffer_t &&node, int r) { this->node = std::move(node); this->r = r; } inline Ct<C> *call(C *foo) const override { return (foo->*_f)(std::move(node), r); } }; template <class C> using CONTINUATION_TYPE = CtFun<C>; template <class C> using CONTINUATION_TX_TYPE = CtFun<C, int>; template <class C> using CONTINUATION_RX_TYPE = CtFun<C, char*, int>; template <class C> using CONTINUATION_RXBPTR_TYPE = CtRxNode<C>; #define CONTINUATION_DECL(C, F, ...) \ CtFun<C, ##__VA_ARGS__> F##_cont { (&C::F) }; #define CONTINUATION(F) F##_cont #define CONTINUE(F, ...) (F##_cont.setParams(__VA_ARGS__), &F##_cont) #define CONTINUATION_RUN(CT) \ { \ Ct<std::remove_reference<decltype(*this)>::type> *_cont = &CT;\ do { \ _cont = _cont->call(this); \ } while (_cont); \ } #define READ_HANDLER_CONTINUATION_DECL(C, F) \ CONTINUATION_DECL(C, F, char *, int) #define READ_BPTR_HANDLER_CONTINUATION_DECL(C, F) \ CtRxNode<C> F##_cont { (&C::F) }; #define WRITE_HANDLER_CONTINUATION_DECL(C, F) CONTINUATION_DECL(C, F, int) ////////////////////////////////////////////////////////////////////// class AsyncMessenger; class Protocol { public: const int proto_type; protected: AsyncConnection *connection; AsyncMessenger *messenger; CephContext *cct; public: std::shared_ptr<AuthConnectionMeta> auth_meta; public: Protocol(int type, AsyncConnection *connection); virtual ~Protocol(); // prepare protocol for connecting to peer virtual void connect() = 0; // prepare protocol for accepting peer connections virtual void accept() = 0; // true -> protocol is ready for sending messages virtual bool is_connected() = 0; // stop connection virtual void stop() = 0; // signal and handle connection failure virtual void fault() = 0; // send message virtual void send_message(Message *m) = 0; // send keepalive virtual void send_keepalive() = 0; virtual void read_event() = 0; virtual void write_event() = 0; virtual bool is_queued() = 0; int get_con_mode() const { return auth_meta->con_mode; } }; #endif /* _MSG_ASYNC_PROTOCOL_ */
3,665
25
77
h
null
ceph-main/src/msg/async/ProtocolV1.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef _MSG_ASYNC_PROTOCOL_V1_ #define _MSG_ASYNC_PROTOCOL_V1_ #include "Protocol.h" class ProtocolV1; using CtPtr = Ct<ProtocolV1>*; class ProtocolV1 : public Protocol { /* * ProtocolV1 State Machine * send_server_banner send_client_banner | | v v wait_client_banner wait_server_banner | | | v v handle_server_banner_and_identify wait_connect_message <---------\ | | | | v | wait_connect_message_auth | send_connect_message <----------\ | | | | | v v | | | handle_connect_message_2 | v | | | | wait_connect_reply | v v | | | | replace -> send_connect_message_reply | V | | | wait_connect_reply_auth | | | | | v v v | open ---\ handle_connect_reply_2 --------/ | | | | v v | wait_seq wait_ack_seq | | | v v v server_ready client_ready | | \------------------> wait_message <------------/ | ^ | ^ /------------------------/ | | | | | | \----------------- ------------\ v /----------/ v | handle_keepalive2 | handle_message_header read_message_footer handle_keepalive2_ack | | ^ handle_tag_ack | v | | | throttle_message read_message_data \----------------/ | ^ v | read_message_front --> read_message_middle --/ */ protected: enum State { NONE = 0, START_CONNECT, CONNECTING, CONNECTING_WAIT_BANNER_AND_IDENTIFY, CONNECTING_SEND_CONNECT_MSG, START_ACCEPT, ACCEPTING, ACCEPTING_WAIT_CONNECT_MSG_AUTH, ACCEPTING_HANDLED_CONNECT_MSG, OPENED, THROTTLE_MESSAGE, THROTTLE_BYTES, THROTTLE_DISPATCH_QUEUE, READ_MESSAGE_FRONT, READ_FOOTER_AND_DISPATCH, CLOSED, WAIT, STANDBY }; static const char *get_state_name(int state) { const char *const statenames[] = {"NONE", "START_CONNECT", "CONNECTING", "CONNECTING_WAIT_BANNER_AND_IDENTIFY", "CONNECTING_SEND_CONNECT_MSG", "START_ACCEPT", "ACCEPTING", "ACCEPTING_WAIT_CONNECT_MSG_AUTH", "ACCEPTING_HANDLED_CONNECT_MSG", "OPENED", "THROTTLE_MESSAGE", "THROTTLE_BYTES", "THROTTLE_DISPATCH_QUEUE", "READ_MESSAGE_FRONT", "READ_FOOTER_AND_DISPATCH", "CLOSED", "WAIT", "STANDBY"}; return statenames[state]; } char *temp_buffer; enum class WriteStatus { NOWRITE, REPLACING, CANWRITE, CLOSED }; std::atomic<WriteStatus> can_write; std::list<Message *> sent; // the first ceph::buffer::list need to inject seq // priority queue for outbound msgs std::map<int, std::list<std::pair<ceph::buffer::list, Message *>>> out_q; bool keepalive; bool write_in_progress = false; __u32 connect_seq, peer_global_seq; std::atomic<uint64_t> in_seq{0}; std::atomic<uint64_t> out_seq{0}; std::atomic<uint64_t> ack_left{0}; std::shared_ptr<AuthSessionHandler> session_security; // Open state ceph_msg_connect connect_msg; ceph_msg_connect_reply connect_reply; ceph::buffer::list authorizer_buf; // auth(orizer) payload read off the wire ceph::buffer::list authorizer_more; // connect-side auth retry (we added challenge) utime_t backoff; // backoff time utime_t recv_stamp; utime_t throttle_stamp; unsigned msg_left; uint64_t cur_msg_size; ceph_msg_header current_header; ceph::buffer::list data_buf; ceph::buffer::list::iterator data_blp; ceph::buffer::list front, middle, data; bool replacing; // when replacing process happened, we will reply connect // side with RETRY tag and accept side will clear replaced // connection. So when connect side reissue connect_msg, // there won't exists conflicting connection so we use // "replacing" to skip RESETSESSION to avoid detect wrong // presentation bool is_reset_from_peer; bool once_ready; State state; void run_continuation(CtPtr pcontinuation); CtPtr read(CONTINUATION_RX_TYPE<ProtocolV1> &next, int len, char *buffer = nullptr); CtPtr write(CONTINUATION_TX_TYPE<ProtocolV1> &next,ceph::buffer::list &bl); inline CtPtr _fault() { // helper fault method that stops continuation fault(); return nullptr; } CONTINUATION_DECL(ProtocolV1, wait_message); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_message); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_keepalive2); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_keepalive2_ack); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_tag_ack); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_message_header); CONTINUATION_DECL(ProtocolV1, throttle_message); CONTINUATION_DECL(ProtocolV1, throttle_bytes); CONTINUATION_DECL(ProtocolV1, throttle_dispatch_queue); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_message_front); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_message_middle); CONTINUATION_DECL(ProtocolV1, read_message_data); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_message_data); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_message_footer); CtPtr ready(); CtPtr wait_message(); CtPtr handle_message(char *buffer, int r); CtPtr handle_keepalive2(char *buffer, int r); void append_keepalive_or_ack(bool ack = false, utime_t *t = nullptr); CtPtr handle_keepalive2_ack(char *buffer, int r); CtPtr handle_tag_ack(char *buffer, int r); CtPtr handle_message_header(char *buffer, int r); CtPtr throttle_message(); CtPtr throttle_bytes(); CtPtr throttle_dispatch_queue(); CtPtr read_message_front(); CtPtr handle_message_front(char *buffer, int r); CtPtr read_message_middle(); CtPtr handle_message_middle(char *buffer, int r); CtPtr read_message_data_prepare(); CtPtr read_message_data(); CtPtr handle_message_data(char *buffer, int r); CtPtr read_message_footer(); CtPtr handle_message_footer(char *buffer, int r); void session_reset(); void randomize_out_seq(); Message *_get_next_outgoing(ceph::buffer::list *bl); void prepare_send_message(uint64_t features, Message *m, ceph::buffer::list &bl); ssize_t write_message(Message *m, ceph::buffer::list &bl, bool more); void requeue_sent(); uint64_t discard_requeued_up_to(uint64_t out_seq, uint64_t seq); void discard_out_queue(); void reset_recv_state(); void reset_security(); std::ostream& _conn_prefix(std::ostream *_dout); public: ProtocolV1(AsyncConnection *connection); virtual ~ProtocolV1(); virtual void connect() override; virtual void accept() override; virtual bool is_connected() override; virtual void stop() override; virtual void fault() override; virtual void send_message(Message *m) override; virtual void send_keepalive() override; virtual void read_event() override; virtual void write_event() override; virtual bool is_queued() override; // Client Protocol private: int global_seq; CONTINUATION_DECL(ProtocolV1, send_client_banner); WRITE_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_client_banner_write); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_server_banner_and_identify); WRITE_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_my_addr_write); CONTINUATION_DECL(ProtocolV1, send_connect_message); WRITE_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_connect_message_write); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_connect_reply_1); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_connect_reply_auth); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_ack_seq); WRITE_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_in_seq_write); CtPtr send_client_banner(); CtPtr handle_client_banner_write(int r); CtPtr wait_server_banner(); CtPtr handle_server_banner_and_identify(char *buffer, int r); CtPtr handle_my_addr_write(int r); CtPtr send_connect_message(); CtPtr handle_connect_message_write(int r); CtPtr wait_connect_reply(); CtPtr handle_connect_reply_1(char *buffer, int r); CtPtr wait_connect_reply_auth(); CtPtr handle_connect_reply_auth(char *buffer, int r); CtPtr handle_connect_reply_2(); CtPtr wait_ack_seq(); CtPtr handle_ack_seq(char *buffer, int r); CtPtr handle_in_seq_write(int r); CtPtr client_ready(); // Server Protocol protected: bool wait_for_seq; CONTINUATION_DECL(ProtocolV1, send_server_banner); WRITE_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_server_banner_write); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_client_banner); CONTINUATION_DECL(ProtocolV1, wait_connect_message); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_connect_message_1); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_connect_message_auth); WRITE_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_connect_message_reply_write); WRITE_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_ready_connect_message_reply_write); READ_HANDLER_CONTINUATION_DECL(ProtocolV1, handle_seq); CtPtr send_server_banner(); CtPtr handle_server_banner_write(int r); CtPtr wait_client_banner(); CtPtr handle_client_banner(char *buffer, int r); CtPtr wait_connect_message(); CtPtr handle_connect_message_1(char *buffer, int r); CtPtr wait_connect_message_auth(); CtPtr handle_connect_message_auth(char *buffer, int r); CtPtr handle_connect_message_2(); CtPtr send_connect_message_reply(char tag, ceph_msg_connect_reply &reply, ceph::buffer::list &authorizer_reply); CtPtr handle_connect_message_reply_write(int r); CtPtr replace(const AsyncConnectionRef& existing, ceph_msg_connect_reply &reply, ceph::buffer::list &authorizer_reply); CtPtr open(ceph_msg_connect_reply &reply, ceph::buffer::list &authorizer_reply); CtPtr handle_ready_connect_message_reply_write(int r); CtPtr wait_seq(); CtPtr handle_seq(char *buffer, int r); CtPtr server_ready(); }; class LoopbackProtocolV1 : public ProtocolV1 { public: LoopbackProtocolV1(AsyncConnection *connection) : ProtocolV1(connection) { this->can_write = WriteStatus::CANWRITE; } }; #endif /* _MSG_ASYNC_PROTOCOL_V1_ */
12,449
39.953947
86
h
null
ceph-main/src/msg/async/ProtocolV2.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef _MSG_ASYNC_PROTOCOL_V2_ #define _MSG_ASYNC_PROTOCOL_V2_ #include "Protocol.h" #include "crypto_onwire.h" #include "compression_meta.h" #include "compression_onwire.h" #include "frames_v2.h" class ProtocolV2 : public Protocol { private: enum State { NONE, START_CONNECT, BANNER_CONNECTING, HELLO_CONNECTING, AUTH_CONNECTING, AUTH_CONNECTING_SIGN, COMPRESSION_CONNECTING, SESSION_CONNECTING, SESSION_RECONNECTING, START_ACCEPT, BANNER_ACCEPTING, HELLO_ACCEPTING, AUTH_ACCEPTING, AUTH_ACCEPTING_MORE, AUTH_ACCEPTING_SIGN, COMPRESSION_ACCEPTING, SESSION_ACCEPTING, READY, THROTTLE_MESSAGE, THROTTLE_BYTES, THROTTLE_DISPATCH_QUEUE, THROTTLE_DONE, READ_MESSAGE_COMPLETE, STANDBY, WAIT, CLOSED }; static const char *get_state_name(int state) { const char *const statenames[] = {"NONE", "START_CONNECT", "BANNER_CONNECTING", "HELLO_CONNECTING", "AUTH_CONNECTING", "AUTH_CONNECTING_SIGN", "COMPRESSION_CONNECTING", "SESSION_CONNECTING", "SESSION_RECONNECTING", "START_ACCEPT", "BANNER_ACCEPTING", "HELLO_ACCEPTING", "AUTH_ACCEPTING", "AUTH_ACCEPTING_MORE", "AUTH_ACCEPTING_SIGN", "COMPRESSION_ACCEPTING", "SESSION_ACCEPTING", "READY", "THROTTLE_MESSAGE", "THROTTLE_BYTES", "THROTTLE_DISPATCH_QUEUE", "THROTTLE_DONE", "READ_MESSAGE_COMPLETE", "STANDBY", "WAIT", "CLOSED"}; return statenames[state]; } // TODO: move into auth_meta? ceph::crypto::onwire::rxtx_t session_stream_handlers; ceph::compression::onwire::rxtx_t session_compression_handlers; private: entity_name_t peer_name; State state; uint64_t peer_supported_features; // CEPH_MSGR2_FEATURE_* uint64_t client_cookie; uint64_t server_cookie; uint64_t global_seq; uint64_t connect_seq; uint64_t peer_global_seq; uint64_t message_seq; bool reconnecting; bool replacing; bool can_write; struct out_queue_entry_t { bool is_prepared {false}; Message* m {nullptr}; }; std::map<int, std::list<out_queue_entry_t>> out_queue; std::list<Message *> sent; std::atomic<uint64_t> out_seq{0}; std::atomic<uint64_t> in_seq{0}; std::atomic<uint64_t> ack_left{0}; using ProtFuncPtr = void (ProtocolV2::*)(); Ct<ProtocolV2> *bannerExchangeCallback; ceph::msgr::v2::FrameAssembler tx_frame_asm; ceph::msgr::v2::FrameAssembler rx_frame_asm; ceph::bufferlist rx_preamble; ceph::bufferlist rx_epilogue; ceph::msgr::v2::segment_bls_t rx_segments_data; ceph::msgr::v2::Tag next_tag; utime_t backoff; // backoff time utime_t recv_stamp; utime_t throttle_stamp; struct { ceph::bufferlist rxbuf; ceph::bufferlist txbuf; bool enabled {true}; } pre_auth; bool keepalive; bool write_in_progress = false; CompConnectionMeta comp_meta; std::ostream& _conn_prefix(std::ostream *_dout); void run_continuation(Ct<ProtocolV2> *pcontinuation); void run_continuation(Ct<ProtocolV2> &continuation); Ct<ProtocolV2> *read(CONTINUATION_RXBPTR_TYPE<ProtocolV2> &next, rx_buffer_t&& buffer); template <class F> Ct<ProtocolV2> *write(const std::string &desc, CONTINUATION_TYPE<ProtocolV2> &next, F &frame); Ct<ProtocolV2> *write(const std::string &desc, CONTINUATION_TYPE<ProtocolV2> &next, ceph::bufferlist &buffer); template <class F> bool append_frame(F& frame); void requeue_sent(); uint64_t discard_requeued_up_to(uint64_t out_seq, uint64_t seq); void reset_recv_state(); void reset_security(); void reset_throttle(); Ct<ProtocolV2> *_fault(); void discard_out_queue(); void reset_session(); void prepare_send_message(uint64_t features, Message *m); out_queue_entry_t _get_next_outgoing(); ssize_t write_message(Message *m, bool more); void handle_message_ack(uint64_t seq); void reset_compression(); CONTINUATION_DECL(ProtocolV2, _wait_for_peer_banner); READ_BPTR_HANDLER_CONTINUATION_DECL(ProtocolV2, _handle_peer_banner); READ_BPTR_HANDLER_CONTINUATION_DECL(ProtocolV2, _handle_peer_banner_payload); Ct<ProtocolV2> *_banner_exchange(Ct<ProtocolV2> &callback); Ct<ProtocolV2> *_wait_for_peer_banner(); Ct<ProtocolV2> *_handle_peer_banner(rx_buffer_t &&buffer, int r); Ct<ProtocolV2> *_handle_peer_banner_payload(rx_buffer_t &&buffer, int r); Ct<ProtocolV2> *handle_hello(ceph::bufferlist &payload); CONTINUATION_DECL(ProtocolV2, read_frame); CONTINUATION_DECL(ProtocolV2, finish_auth); READ_BPTR_HANDLER_CONTINUATION_DECL(ProtocolV2, handle_read_frame_preamble_main); READ_BPTR_HANDLER_CONTINUATION_DECL(ProtocolV2, handle_read_frame_segment); READ_BPTR_HANDLER_CONTINUATION_DECL(ProtocolV2, handle_read_frame_epilogue_main); CONTINUATION_DECL(ProtocolV2, throttle_message); CONTINUATION_DECL(ProtocolV2, throttle_bytes); CONTINUATION_DECL(ProtocolV2, throttle_dispatch_queue); CONTINUATION_DECL(ProtocolV2, finish_compression); Ct<ProtocolV2> *read_frame(); Ct<ProtocolV2> *finish_auth(); Ct<ProtocolV2> *finish_client_auth(); Ct<ProtocolV2> *finish_server_auth(); Ct<ProtocolV2> *handle_read_frame_preamble_main(rx_buffer_t &&buffer, int r); Ct<ProtocolV2> *read_frame_segment(); Ct<ProtocolV2> *handle_read_frame_segment(rx_buffer_t &&rx_buffer, int r); Ct<ProtocolV2> *_handle_read_frame_segment(); Ct<ProtocolV2> *handle_read_frame_epilogue_main(rx_buffer_t &&buffer, int r); Ct<ProtocolV2> *_handle_read_frame_epilogue_main(); Ct<ProtocolV2> *handle_read_frame_dispatch(); Ct<ProtocolV2> *handle_frame_payload(); Ct<ProtocolV2> *finish_compression(); Ct<ProtocolV2> *ready(); Ct<ProtocolV2> *handle_message(); Ct<ProtocolV2> *throttle_message(); Ct<ProtocolV2> *throttle_bytes(); Ct<ProtocolV2> *throttle_dispatch_queue(); Ct<ProtocolV2> *handle_keepalive2(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_keepalive2_ack(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_message_ack(ceph::bufferlist &payload); public: uint64_t connection_features; ProtocolV2(AsyncConnection *connection); virtual ~ProtocolV2(); virtual void connect() override; virtual void accept() override; virtual bool is_connected() override; virtual void stop() override; virtual void fault() override; virtual void send_message(Message *m) override; virtual void send_keepalive() override; virtual void read_event() override; virtual void write_event() override; virtual bool is_queued() override; private: // Client Protocol CONTINUATION_DECL(ProtocolV2, start_client_banner_exchange); CONTINUATION_DECL(ProtocolV2, post_client_banner_exchange); Ct<ProtocolV2> *start_client_banner_exchange(); Ct<ProtocolV2> *post_client_banner_exchange(); inline Ct<ProtocolV2> *send_auth_request() { std::vector<uint32_t> empty; return send_auth_request(empty); } Ct<ProtocolV2> *send_auth_request(std::vector<uint32_t> &allowed_methods); Ct<ProtocolV2> *handle_auth_bad_method(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_auth_reply_more(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_auth_done(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_auth_signature(ceph::bufferlist &payload); Ct<ProtocolV2> *start_session_connect(); Ct<ProtocolV2> *send_client_ident(); Ct<ProtocolV2> *send_reconnect(); Ct<ProtocolV2> *handle_ident_missing_features(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_session_reset(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_session_retry(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_session_retry_global(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_wait(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_reconnect_ok(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_server_ident(ceph::bufferlist &payload); Ct<ProtocolV2> *send_compression_request(); Ct<ProtocolV2> *handle_compression_done(ceph::bufferlist &payload); // Server Protocol CONTINUATION_DECL(ProtocolV2, start_server_banner_exchange); CONTINUATION_DECL(ProtocolV2, post_server_banner_exchange); CONTINUATION_DECL(ProtocolV2, server_ready); Ct<ProtocolV2> *start_server_banner_exchange(); Ct<ProtocolV2> *post_server_banner_exchange(); Ct<ProtocolV2> *handle_auth_request(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_auth_request_more(ceph::bufferlist &payload); Ct<ProtocolV2> *_handle_auth_request(ceph::bufferlist& auth_payload, bool more); Ct<ProtocolV2> *_auth_bad_method(int r); Ct<ProtocolV2> *handle_client_ident(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_ident_missing_features_write(int r); Ct<ProtocolV2> *handle_reconnect(ceph::bufferlist &payload); Ct<ProtocolV2> *handle_existing_connection(const AsyncConnectionRef& existing); Ct<ProtocolV2> *reuse_connection(const AsyncConnectionRef& existing, ProtocolV2 *exproto); Ct<ProtocolV2> *send_server_ident(); Ct<ProtocolV2> *send_reconnect_ok(); Ct<ProtocolV2> *server_ready(); Ct<ProtocolV2> *handle_compression_request(ceph::bufferlist &payload); size_t get_current_msg_size() const; }; #endif /* _MSG_ASYNC_PROTOCOL_V2_ */
10,197
35.815884
83
h
null
ceph-main/src/msg/async/compression_meta.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #include "compressor/Compressor.h" struct CompConnectionMeta { TOPNSPC::Compressor::CompressionMode con_mode = TOPNSPC::Compressor::COMP_NONE; // negotiated mode TOPNSPC::Compressor::CompressionAlgorithm con_method = TOPNSPC::Compressor::COMP_ALG_NONE; // negotiated method bool is_compress() const { return con_mode != TOPNSPC::Compressor::COMP_NONE; } TOPNSPC::Compressor::CompressionAlgorithm get_method() const { return con_method; } TOPNSPC::Compressor::CompressionMode get_mode() const { return con_mode; } };
654
28.772727
70
h
null
ceph-main/src/msg/async/compression_onwire.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_COMPRESSION_ONWIRE_H #define CEPH_COMPRESSION_ONWIRE_H #include <cstdint> #include <optional> #include "compressor/Compressor.h" #include "include/buffer.h" class CompConnectionMeta; namespace ceph::compression::onwire { using Compressor = TOPNSPC::Compressor; using CompressorRef = TOPNSPC::CompressorRef; class Handler { public: Handler(CephContext* const cct, CompressorRef compressor) : m_cct(cct), m_compressor(compressor) {} protected: CephContext* const m_cct; CompressorRef m_compressor; }; class RxHandler final : private Handler { public: RxHandler(CephContext* const cct, CompressorRef compressor) : Handler(cct, compressor) {} ~RxHandler() {}; /** * Decompresses a bufferlist * * @param input compressed bufferlist * @param out decompressed bufferlist * * @returns true on success, false on failure */ std::optional<ceph::bufferlist> decompress(const ceph::bufferlist &input); }; class TxHandler final : private Handler { public: TxHandler(CephContext* const cct, CompressorRef compressor, int mode, std::uint64_t min_size) : Handler(cct, compressor), m_min_size(min_size), m_mode(static_cast<Compressor::CompressionMode>(mode)) {} ~TxHandler() {} void reset_handler(int num_segments, uint64_t size) { m_init_onwire_size = size; m_compress_potential = size; m_onwire_size = 0; } void done(); /** * Compresses a bufferlist * * @param input bufferlist to compress * @param out compressed bufferlist * * @returns true on success, false on failure */ std::optional<ceph::bufferlist> compress(const ceph::bufferlist &input); double get_ratio() const { return get_initial_size() / (double) get_final_size(); } uint64_t get_initial_size() const { return m_init_onwire_size; } uint64_t get_final_size() const { return m_onwire_size; } private: uint64_t m_min_size; Compressor::CompressionMode m_mode; uint64_t m_init_onwire_size; uint64_t m_onwire_size; uint64_t m_compress_potential; }; struct rxtx_t { std::unique_ptr<RxHandler> rx; std::unique_ptr<TxHandler> tx; static rxtx_t create_handler_pair( CephContext* ctx, const CompConnectionMeta& comp_meta, std::uint64_t compress_min_size); }; } #endif // CEPH_COMPRESSION_ONWIRE_H
2,561
23.169811
97
h
null
ceph-main/src/msg/async/crypto_onwire.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-2009 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_CRYPTO_ONWIRE_H #define CEPH_CRYPTO_ONWIRE_H #include <cstdint> #include <memory> #include "auth/Auth.h" #include "include/buffer.h" namespace ceph::math { // TODO template <typename T> class always_aligned_t { T val; template <class... Args> always_aligned_t(Args&&... args) : val(std::forward<Args>(args)...) { } }; } // namespace ceph::math namespace ceph::crypto::onwire { struct MsgAuthError : public std::runtime_error { MsgAuthError() : runtime_error("message signature mismatch") { } }; struct TxHandlerError : public std::runtime_error { TxHandlerError(const char* what) : std::runtime_error(std::string("tx handler error: ") + what) {} }; struct TxHandler { virtual ~TxHandler() = default; // Instance of TxHandler must be reset before doing any encrypt-update // step. This applies also to situation when encrypt-final was already // called and another round of update-...-update-final will take place. // // The input parameter informs implementation how the -update sequence // is fragmented and allows to make concious decision about allocation // or reusage of provided memory. One implementation could do in-place // encryption while other might prefer one huge output buffer. // // It's undefined what will happen if client doesn't follow the order. // // TODO: switch to always_aligned_t virtual void reset_tx_handler(const uint32_t* first, const uint32_t* last) = 0; void reset_tx_handler(std::initializer_list<uint32_t> update_size_sequence) { if (update_size_sequence.size() > 0) { const uint32_t* first = &*update_size_sequence.begin(); reset_tx_handler(first, first + update_size_sequence.size()); } else { reset_tx_handler(nullptr, nullptr); } } // Perform encryption. Client gives full ownership right to provided // bufferlist. The method MUST NOT be called after _final() if there // was no call to _reset(). virtual void authenticated_encrypt_update( const ceph::bufferlist& plaintext) = 0; // Generates authentication signature and returns bufferlist crafted // basing on plaintext from preceding call to _update(). virtual ceph::bufferlist authenticated_encrypt_final() = 0; }; class RxHandler { public: virtual ~RxHandler() = default; // Transmitter can append extra bytes of ciphertext at the -final step. // This method return how much was added, and thus let client translate // plaintext size into ciphertext size to grab from wire. virtual std::uint32_t get_extra_size_at_final() = 0; // Instance of RxHandler must be reset before doing any decrypt-update // step. This applies also to situation when decrypt-final was already // called and another round of update-...-update-final will take place. virtual void reset_rx_handler() = 0; // Perform decryption ciphertext must be ALWAYS aligned to 16 bytes. virtual void authenticated_decrypt_update(ceph::bufferlist& bl) = 0; // Perform decryption of last cipertext's portion and verify signature // for overall decryption sequence. // Throws on integrity/authenticity checks virtual void authenticated_decrypt_update_final(ceph::bufferlist& bl) = 0; }; struct rxtx_t { //rxtx_t(rxtx_t&& r) : rx(std::move(rx)), tx(std::move(tx)) {} // Each peer can use different handlers. // Hmm, isn't that too much flexbility? std::unique_ptr<RxHandler> rx; std::unique_ptr<TxHandler> tx; static rxtx_t create_handler_pair( CephContext* ctx, const class AuthConnectionMeta& auth_meta, bool new_nonce_format, bool crossed); }; } // namespace ceph::crypto::onwire #endif // CEPH_CRYPTO_ONWIRE_H
4,123
30.480916
79
h
null
ceph-main/src/msg/async/net_handler.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 UnitedStack <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_COMMON_NET_UTILS_H #define CEPH_COMMON_NET_UTILS_H #include "common/config.h" namespace ceph { class NetHandler { int generic_connect(const entity_addr_t& addr, const entity_addr_t& bind_addr, bool nonblock); CephContext *cct; public: int create_socket(int domain, bool reuse_addr=false); explicit NetHandler(CephContext *c): cct(c) {} int set_nonblock(int sd); int set_socket_options(int sd, bool nodelay, int size); int connect(const entity_addr_t &addr, const entity_addr_t& bind_addr); /** * Try to reconnect the socket. * * @return 0 success * > 0 just break, and wait for event * < 0 need to goto fail */ int reconnect(const entity_addr_t &addr, int sd); int nonblock_connect(const entity_addr_t &addr, const entity_addr_t& bind_addr); void set_priority(int sd, int priority, int domain); }; } #endif
1,432
29.489362
98
h
null
ceph-main/src/msg/async/dpdk/ARP.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. * */ #ifndef CEPH_MSG_ARP_H_ #define CEPH_MSG_ARP_H_ #include <errno.h> #include <unordered_map> #include <functional> #include "msg/async/Event.h" #include "ethernet.h" #include "circular_buffer.h" #include "ip_types.h" #include "net.h" #include "Packet.h" class arp; template <typename L3> class arp_for; class arp_for_protocol { protected: arp& _arp; uint16_t _proto_num; public: arp_for_protocol(arp& a, uint16_t proto_num); virtual ~arp_for_protocol(); virtual int received(Packet p) = 0; virtual bool forward(forward_hash& out_hash_data, Packet& p, size_t off) { return false; } }; class interface; class arp { interface* _netif; l3_protocol _proto; subscription<Packet, ethernet_address> _rx_packets; std::unordered_map<uint16_t, arp_for_protocol*> _arp_for_protocol; circular_buffer<l3_protocol::l3packet> _packetq; private: struct arp_hdr { uint16_t htype; uint16_t ptype; arp_hdr ntoh() { arp_hdr hdr = *this; hdr.htype = ::ntoh(htype); hdr.ptype = ::ntoh(ptype); return hdr; } arp_hdr hton() { arp_hdr hdr = *this; hdr.htype = ::hton(htype); hdr.ptype = ::hton(ptype); return hdr; } }; public: explicit arp(interface* netif); void add(uint16_t proto_num, arp_for_protocol* afp); void del(uint16_t proto_num); private: ethernet_address l2self() { return _netif->hw_address(); } int process_packet(Packet p, ethernet_address from); bool forward(forward_hash& out_hash_data, Packet& p, size_t off); std::optional<l3_protocol::l3packet> get_packet(); template <class l3_proto> friend class arp_for; }; template <typename L3> class arp_for : public arp_for_protocol { public: using l2addr = ethernet_address; using l3addr = typename L3::address_type; private: static constexpr auto max_waiters = 512; enum oper { op_request = 1, op_reply = 2, }; struct arp_hdr { uint16_t htype; uint16_t ptype; uint8_t hlen; uint8_t plen; uint16_t oper; l2addr sender_hwaddr; l3addr sender_paddr; l2addr target_hwaddr; l3addr target_paddr; arp_hdr ntoh() { arp_hdr hdr = *this; hdr.htype = ::ntoh(htype); hdr.ptype = ::ntoh(ptype); hdr.oper = ::ntoh(oper); hdr.sender_hwaddr = sender_hwaddr.ntoh(); hdr.sender_paddr = sender_paddr.ntoh(); hdr.target_hwaddr = target_hwaddr.ntoh(); hdr.target_paddr = target_paddr.ntoh(); return hdr; } arp_hdr hton() { arp_hdr hdr = *this; hdr.htype = ::hton(htype); hdr.ptype = ::hton(ptype); hdr.oper = ::hton(oper); hdr.sender_hwaddr = sender_hwaddr.hton(); hdr.sender_paddr = sender_paddr.hton(); hdr.target_hwaddr = target_hwaddr.hton(); hdr.target_paddr = target_paddr.hton(); return hdr; } }; struct resolution { std::vector<std::pair<resolution_cb, Packet>> _waiters; uint64_t timeout_fd; }; class C_handle_arp_timeout : public EventCallback { arp_for *arp; l3addr paddr; bool first_request; public: C_handle_arp_timeout(arp_for *a, l3addr addr, bool first): arp(a), paddr(addr), first_request(first) {} void do_request(uint64_t r) { arp->send_query(paddr); auto &res = arp->_in_progress[paddr]; for (auto& p : res._waiters) { p.first(ethernet_address(), std::move(p.second), -ETIMEDOUT); } res._waiters.clear(); res.timeout_fd = arp->center->create_time_event( 1*1000*1000, this); } }; friend class C_handle_arp_timeout; private: CephContext *cct; EventCenter *center; l3addr _l3self = L3::broadcast_address(); std::unordered_map<l3addr, l2addr> _table; std::unordered_map<l3addr, resolution> _in_progress; private: Packet make_query_packet(l3addr paddr); virtual int received(Packet p) override; int handle_request(arp_hdr* ah); l2addr l2self() { return _arp.l2self(); } void send(l2addr to, Packet &&p); public: void send_query(const l3addr& paddr); explicit arp_for(CephContext *c, arp& a, EventCenter *cen) : arp_for_protocol(a, L3::arp_protocol_type()), cct(c), center(cen) { _table[L3::broadcast_address()] = ethernet::broadcast_address(); } ~arp_for() { for (auto && p : _in_progress) center->delete_time_event(p.second.timeout_fd); } void wait(const l3addr& addr, Packet p, resolution_cb cb); void learn(l2addr l2, l3addr l3); void run(); void set_self_addr(l3addr addr) { _table.erase(_l3self); _table[addr] = l2self(); _l3self = addr; } friend class arp; }; template <typename L3> void arp_for<L3>::send(l2addr to, Packet &&p) { _arp._packetq.push_back(l3_protocol::l3packet{eth_protocol_num::arp, to, std::move(p)}); } template <typename L3> Packet arp_for<L3>::make_query_packet(l3addr paddr) { arp_hdr hdr; hdr.htype = ethernet::arp_hardware_type(); hdr.ptype = L3::arp_protocol_type(); hdr.hlen = sizeof(l2addr); hdr.plen = sizeof(l3addr); hdr.oper = op_request; hdr.sender_hwaddr = l2self(); hdr.sender_paddr = _l3self; hdr.target_hwaddr = ethernet::broadcast_address(); hdr.target_paddr = paddr; hdr = hdr.hton(); return Packet(reinterpret_cast<char*>(&hdr), sizeof(hdr)); } template <typename L3> void arp_for<L3>::send_query(const l3addr& paddr) { send(ethernet::broadcast_address(), make_query_packet(paddr)); } template <typename L3> void arp_for<L3>::learn(l2addr hwaddr, l3addr paddr) { _table[paddr] = hwaddr; auto i = _in_progress.find(paddr); if (i != _in_progress.end()) { auto& res = i->second; center->delete_time_event(res.timeout_fd); for (auto &&p : res._waiters) { p.first(hwaddr, std::move(p.second), 0); } _in_progress.erase(i); } } template <typename L3> void arp_for<L3>::wait(const l3addr& paddr, Packet p, resolution_cb cb) { auto i = _table.find(paddr); if (i != _table.end()) { cb(i->second, std::move(p), 0); return ; } auto j = _in_progress.find(paddr); auto first_request = j == _in_progress.end(); auto& res = first_request ? _in_progress[paddr] : j->second; if (first_request) { res.timeout_fd = center->create_time_event( 1*1000*1000, new C_handle_arp_timeout(this, paddr, first_request)); send_query(paddr); } if (res._waiters.size() >= max_waiters) { cb(ethernet_address(), std::move(p), -EBUSY); return ; } res._waiters.emplace_back(cb, std::move(p)); return ; } template <typename L3> int arp_for<L3>::received(Packet p) { auto ah = p.get_header<arp_hdr>(); if (!ah) { return 0; } auto h = ah->ntoh(); if (h.hlen != sizeof(l2addr) || h.plen != sizeof(l3addr)) { return 0; } switch (h.oper) { case op_request: return handle_request(&h); case op_reply: _arp._netif->arp_learn(h.sender_hwaddr, h.sender_paddr); return 0; default: return 0; } } template <typename L3> int arp_for<L3>::handle_request(arp_hdr* ah) { if (ah->target_paddr == _l3self && _l3self != L3::broadcast_address()) { ah->oper = op_reply; ah->target_hwaddr = ah->sender_hwaddr; ah->target_paddr = ah->sender_paddr; ah->sender_hwaddr = l2self(); ah->sender_paddr = _l3self; *ah = ah->hton(); send(ah->target_hwaddr, Packet(reinterpret_cast<char*>(ah), sizeof(*ah))); } return 0; } #endif /* CEPH_MSG_ARP_H_ */
8,248
26.31457
92
h
null
ceph-main/src/msg/async/dpdk/DPDKStack.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * Ceph - scalable distributed file system * * Copyright (C) 2015 XSky <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_MSG_DPDKSTACK_H #define CEPH_MSG_DPDKSTACK_H #include <functional> #include <optional> #include "common/ceph_context.h" #include "msg/async/Stack.h" #include "net.h" #include "const.h" #include "IP.h" #include "Packet.h" #include "dpdk_rte.h" class interface; template <typename Protocol> class NativeConnectedSocketImpl; // DPDKServerSocketImpl template <typename Protocol> class DPDKServerSocketImpl : public ServerSocketImpl { typename Protocol::listener _listener; public: DPDKServerSocketImpl(Protocol& proto, uint16_t port, const SocketOptions &opt, int type, unsigned addr_slot); int listen() { return _listener.listen(); } virtual int accept(ConnectedSocket *s, const SocketOptions &opts, entity_addr_t *out, Worker *w) override; virtual void abort_accept() override; virtual int fd() const override { return _listener.fd(); } virtual void set_priority(int sd, int prio, int domain) override {} }; // NativeConnectedSocketImpl template <typename Protocol> class NativeConnectedSocketImpl : public ConnectedSocketImpl { typename Protocol::connection _conn; uint32_t _cur_frag = 0; uint32_t _cur_off = 0; std::optional<Packet> _buf; std::optional<bufferptr> _cache_ptr; public: explicit NativeConnectedSocketImpl(typename Protocol::connection conn) : _conn(std::move(conn)) {} NativeConnectedSocketImpl(NativeConnectedSocketImpl &&rhs) : _conn(std::move(rhs._conn)), _buf(std::move(rhs.buf)) {} virtual int is_connected() override { return _conn.is_connected(); } virtual ssize_t read(char *buf, size_t len) override { size_t left = len; ssize_t r = 0; size_t off = 0; while (left > 0) { if (!_cache_ptr) { _cache_ptr.emplace(); r = zero_copy_read(*_cache_ptr); if (r <= 0) { _cache_ptr.reset(); if (r == -EAGAIN) break; return r; } } if (_cache_ptr->length() <= left) { _cache_ptr->copy_out(0, _cache_ptr->length(), buf+off); left -= _cache_ptr->length(); off += _cache_ptr->length(); _cache_ptr.reset(); } else { _cache_ptr->copy_out(0, left, buf+off); _cache_ptr->set_offset(_cache_ptr->offset() + left); _cache_ptr->set_length(_cache_ptr->length() - left); left = 0; break; } } return len - left ? len - left : -EAGAIN; } private: ssize_t zero_copy_read(bufferptr &data) { auto err = _conn.get_errno(); if (err <= 0) return err; if (!_buf) { _buf = std::move(_conn.read()); if (!_buf) return -EAGAIN; } fragment &f = _buf->frag(_cur_frag); Packet p = _buf->share(_cur_off, f.size); auto del = std::bind( [](Packet &p) {}, std::move(p)); data = buffer::claim_buffer( f.size, f.base, make_deleter(std::move(del))); if (++_cur_frag == _buf->nr_frags()) { _cur_frag = 0; _cur_off = 0; _buf.reset(); } else { _cur_off += f.size; } ceph_assert(data.length()); return data.length(); } virtual ssize_t send(bufferlist &bl, bool more) override { auto err = _conn.get_errno(); if (err < 0) return (ssize_t)err; size_t available = _conn.peek_sent_available(); if (available == 0) { return 0; } std::vector<fragment> frags; auto pb = bl.buffers().begin(); uint64_t len = 0; uint64_t seglen = 0; while (len < available && pb != bl.buffers().end()) { seglen = pb->length(); // Buffer length is zero, no need to send, so skip it if (seglen == 0) { ++pb; continue; } if (len + seglen > available) { // don't continue if we enough at least 1 fragment since no available // space for next ptr. if (len > 0) break; seglen = std::min(seglen, available); } len += seglen; frags.push_back(fragment{(char*)pb->c_str(), seglen}); ++pb; } if (len != bl.length()) { bufferlist swapped; bl.splice(0, len, &swapped); auto del = std::bind( [](bufferlist &bl) {}, std::move(swapped)); return _conn.send(Packet(std::move(frags), make_deleter(std::move(del)))); } else { auto del = std::bind( [](bufferlist &bl) {}, std::move(bl)); return _conn.send(Packet(std::move(frags), make_deleter(std::move(del)))); } } public: virtual void shutdown() override { _conn.close_write(); } // FIXME need to impl close virtual void close() override { _conn.close_write(); } virtual int fd() const override { return _conn.fd(); } }; template <typename Protocol> DPDKServerSocketImpl<Protocol>::DPDKServerSocketImpl( Protocol& proto, uint16_t port, const SocketOptions &opt, int type, unsigned addr_slot) : ServerSocketImpl(type, addr_slot), _listener(proto.listen(port)) {} template <typename Protocol> int DPDKServerSocketImpl<Protocol>::accept(ConnectedSocket *s, const SocketOptions &options, entity_addr_t *out, Worker *w) { if (_listener.get_errno() < 0) return _listener.get_errno(); auto c = _listener.accept(); if (!c) return -EAGAIN; if (out) { *out = c->remote_addr(); out->set_type(addr_type); } std::unique_ptr<NativeConnectedSocketImpl<Protocol>> csi( new NativeConnectedSocketImpl<Protocol>(std::move(*c))); *s = ConnectedSocket(std::move(csi)); return 0; } template <typename Protocol> void DPDKServerSocketImpl<Protocol>::abort_accept() { _listener.abort_accept(); } class DPDKWorker : public Worker { struct Impl { unsigned id; interface _netif; std::shared_ptr<DPDKDevice> _dev; ipv4 _inet; Impl(CephContext *cct, unsigned i, EventCenter *c, std::shared_ptr<DPDKDevice> dev); ~Impl(); }; std::unique_ptr<Impl> _impl; virtual void initialize() override; void set_ipv4_packet_filter(ip_packet_filter* filter) { _impl->_inet.set_packet_filter(filter); } using tcp4 = tcp<ipv4_traits>; public: explicit DPDKWorker(CephContext *c, unsigned i): Worker(c, i) {} virtual int listen(entity_addr_t &addr, unsigned addr_slot, const SocketOptions &opts, ServerSocket *) override; virtual int connect(const entity_addr_t &addr, const SocketOptions &opts, ConnectedSocket *socket) override; void arp_learn(ethernet_address l2, ipv4_address l3) { _impl->_inet.learn(l2, l3); } virtual void destroy() override { _impl.reset(); } friend class DPDKServerSocketImpl<tcp4>; }; using namespace dpdk; class DPDKStack : public NetworkStack { std::vector<std::function<void()> > funcs; virtual Worker* create_worker(CephContext *c, unsigned worker_id) override { return new DPDKWorker(c, worker_id); } virtual void rename_thread(unsigned id) override {} public: explicit DPDKStack(CephContext *cct): NetworkStack(cct), eal(cct) { funcs.reserve(cct->_conf->ms_async_op_threads); } virtual bool support_local_listen_table() const override { return true; } virtual void spawn_worker(std::function<void ()> &&func) override; virtual void join_worker(unsigned i) override; private: dpdk::eal eal; }; #endif
7,675
27.117216
125
h
null
ceph-main/src/msg/async/dpdk/EventDPDK.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * Ceph - scalable distributed file system * * Copyright (C) 2015 XSky <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_EVENTDPDK_H #define CEPH_EVENTDPDK_H #include "msg/async/Event.h" #include "msg/async/Stack.h" #include "UserspaceEvent.h" class DPDKDriver : public EventDriver { CephContext *cct; public: UserspaceEventManager manager; explicit DPDKDriver(CephContext *c): cct(c), manager(c) {} virtual ~DPDKDriver() { } int init(EventCenter *c, int nevent) override; int add_event(int fd, int cur_mask, int add_mask) override; int del_event(int fd, int cur_mask, int del_mask) override; int resize_events(int newsize) override; int event_wait(std::vector<FiredFileEvent> &fired_events, struct timeval *tp) override; bool need_wakeup() override { return false; } }; #endif //CEPH_EVENTDPDK_H
1,152
27.121951
89
h
null
ceph-main/src/msg/async/dpdk/IP.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. * */ #ifndef CEPH_MSG_IP_H_ #define CEPH_MSG_IP_H_ #include <arpa/inet.h> #include <unordered_map> #include <cstdint> #include <array> #include <map> #include <list> #include <chrono> #include "msg/async/Event.h" #include "common/Throttle.h" #include "array_map.h" #include "ARP.h" #include "IPChecksum.h" #include "ip_types.h" #include "const.h" #include "net.h" #include "PacketUtil.h" #include "toeplitz.h" class ipv4; template <ip_protocol_num ProtoNum> class ipv4_l4; template <typename InetTraits> class tcp; struct ipv4_traits { using address_type = ipv4_address; using inet_type = ipv4_l4<ip_protocol_num::tcp>; struct l4packet { ipv4_address to; Packet p; ethernet_address e_dst; ip_protocol_num proto_num; }; using packet_provider_type = std::function<std::optional<l4packet> ()>; static void tcp_pseudo_header_checksum(checksummer& csum, ipv4_address src, ipv4_address dst, uint16_t len) { csum.sum_many(src.ip, dst.ip, uint8_t(0), uint8_t(ip_protocol_num::tcp), len); } static constexpr uint8_t ip_hdr_len_min = ipv4_hdr_len_min; }; template <ip_protocol_num ProtoNum> class ipv4_l4 { public: ipv4& _inet; public: ipv4_l4(ipv4& inet) : _inet(inet) {} void register_packet_provider(ipv4_traits::packet_provider_type func); void wait_l2_dst_address(ipv4_address to, Packet p, resolution_cb cb); }; class ip_protocol { public: virtual ~ip_protocol() {} virtual void received(Packet p, ipv4_address from, ipv4_address to) = 0; virtual bool forward(forward_hash& out_hash_data, Packet& p, size_t off) { return true; } }; template <typename InetTraits> struct l4connid { using ipaddr = typename InetTraits::address_type; using inet_type = typename InetTraits::inet_type; struct connid_hash; ipaddr local_ip; ipaddr foreign_ip; uint16_t local_port; uint16_t foreign_port; bool operator==(const l4connid& x) const { return local_ip == x.local_ip && foreign_ip == x.foreign_ip && local_port == x.local_port && foreign_port == x.foreign_port; } uint32_t hash(const rss_key_type& rss_key) { forward_hash hash_data; hash_data.push_back(hton(foreign_ip.ip)); hash_data.push_back(hton(local_ip.ip)); hash_data.push_back(hton(foreign_port)); hash_data.push_back(hton(local_port)); return toeplitz_hash(rss_key, hash_data); } }; class ipv4_tcp final : public ip_protocol { ipv4_l4<ip_protocol_num::tcp> _inet_l4; std::unique_ptr<tcp<ipv4_traits>> _tcp; public: ipv4_tcp(ipv4& inet, EventCenter *c); ~ipv4_tcp(); virtual void received(Packet p, ipv4_address from, ipv4_address to) override; virtual bool forward(forward_hash& out_hash_data, Packet& p, size_t off) override; friend class ipv4; }; class icmp { public: using ipaddr = ipv4_address; using inet_type = ipv4_l4<ip_protocol_num::icmp>; explicit icmp(CephContext *c, inet_type& inet) : cct(c), _inet(inet), _queue_space(c, "DPDK::icmp::_queue_space", 212992) { _inet.register_packet_provider([this] { std::optional<ipv4_traits::l4packet> l4p; if (!_packetq.empty()) { l4p = std::move(_packetq.front()); _packetq.pop_front(); _queue_space.put(l4p->p.len()); } return l4p; }); } void received(Packet p, ipaddr from, ipaddr to); private: CephContext *cct; // ipv4_l4<ip_protocol_num::icmp> inet_type& _inet; circular_buffer<ipv4_traits::l4packet> _packetq; Throttle _queue_space; }; class ipv4_icmp final : public ip_protocol { CephContext *cct; ipv4_l4<ip_protocol_num::icmp> _inet_l4; icmp _icmp; public: ipv4_icmp(CephContext *c, ipv4& inet) : cct(c), _inet_l4(inet), _icmp(c, _inet_l4) {} virtual void received(Packet p, ipv4_address from, ipv4_address to) override { _icmp.received(std::move(p), from, to); } friend class ipv4; }; struct ip_hdr; struct ip_packet_filter { virtual ~ip_packet_filter() {}; virtual void handle(Packet& p, ip_hdr* iph, ethernet_address from, bool & handled) = 0; }; struct ipv4_frag_id { struct hash; ipv4_address src_ip; ipv4_address dst_ip; uint16_t identification; uint8_t protocol; bool operator==(const ipv4_frag_id& x) const { return src_ip == x.src_ip && dst_ip == x.dst_ip && identification == x.identification && protocol == x.protocol; } }; struct ipv4_frag_id::hash : private std::hash<ipv4_address>, private std::hash<uint16_t>, private std::hash<uint8_t> { size_t operator()(const ipv4_frag_id& id) const noexcept { using h1 = std::hash<ipv4_address>; using h2 = std::hash<uint16_t>; using h3 = std::hash<uint8_t>; return h1::operator()(id.src_ip) ^ h1::operator()(id.dst_ip) ^ h2::operator()(id.identification) ^ h3::operator()(id.protocol); } }; struct ipv4_tag {}; using ipv4_packet_merger = packet_merger<uint32_t, ipv4_tag>; class interface; class ipv4 { public: using address_type = ipv4_address; using proto_type = uint16_t; static address_type broadcast_address() { return ipv4_address(0xffffffff); } static proto_type arp_protocol_type() { return proto_type(eth_protocol_num::ipv4); } CephContext *cct; EventCenter *center; private: interface* _netif; std::vector<ipv4_traits::packet_provider_type> _pkt_providers; std::optional<uint64_t> frag_timefd; EventCallbackRef frag_handler; arp _global_arp; arp_for<ipv4> _arp; ipv4_address _host_address; ipv4_address _gw_address; ipv4_address _netmask; l3_protocol _l3; subscription<Packet, ethernet_address> _rx_packets; ipv4_tcp _tcp; ipv4_icmp _icmp; array_map<ip_protocol*, 256> _l4; ip_packet_filter *_packet_filter; struct frag { Packet header; ipv4_packet_merger data; utime_t rx_time; uint32_t mem_size = 0; // fragment with MF == 0 inidates it is the last fragment bool last_frag_received = false; Packet get_assembled_packet(ethernet_address from, ethernet_address to); int32_t merge(ip_hdr &h, uint16_t offset, Packet p); bool is_complete(); }; std::unordered_map<ipv4_frag_id, frag, ipv4_frag_id::hash> _frags; std::list<ipv4_frag_id> _frags_age; static utime_t _frag_timeout; static constexpr uint32_t _frag_low_thresh{3 * 1024 * 1024}; static constexpr uint32_t _frag_high_thresh{4 * 1024 * 1024}; uint32_t _frag_mem = 0; circular_buffer<l3_protocol::l3packet> _packetq; unsigned _pkt_provider_idx = 0; PerfCounters *perf_logger; private: int handle_received_packet(Packet p, ethernet_address from); bool forward(forward_hash& out_hash_data, Packet& p, size_t off); std::optional<l3_protocol::l3packet> get_packet(); bool in_my_netmask(ipv4_address a) const { return !((a.ip ^ _host_address.ip) & _netmask.ip); } void frag_limit_mem(); void frag_drop(ipv4_frag_id frag_id, uint32_t dropped_size) { _frags.erase(frag_id); _frag_mem -= dropped_size; } void frag_arm(utime_t now) { auto tp = now + _frag_timeout; frag_timefd = center->create_time_event(tp.to_nsec() / 1000, frag_handler); } void frag_arm() { auto now = ceph_clock_now(); frag_timefd = center->create_time_event(now.to_nsec() / 1000, frag_handler); } public: void frag_timeout(); public: explicit ipv4(CephContext *c, EventCenter *cen, interface* netif); ~ipv4() { delete frag_handler; } void set_host_address(ipv4_address ip) { _host_address = ip; _arp.set_self_addr(ip); } ipv4_address host_address() { return _host_address; } void set_gw_address(ipv4_address ip) { _gw_address = ip; } ipv4_address gw_address() const { return _gw_address; } void set_netmask_address(ipv4_address ip) { _netmask = ip; } ipv4_address netmask_address() const { return _netmask; } interface *netif() const { return _netif; } // TODO or something. Should perhaps truly be a list // of filters. With ordering. And blackjack. Etc. // But for now, a simple single raw pointer suffices void set_packet_filter(ip_packet_filter *f) { _packet_filter = f; } ip_packet_filter * packet_filter() const { return _packet_filter; } void send(ipv4_address to, ip_protocol_num proto_num, Packet p, ethernet_address e_dst); tcp<ipv4_traits>& get_tcp() { return *_tcp._tcp; } void register_l4(proto_type id, ip_protocol* handler); const hw_features& get_hw_features() const; static bool needs_frag(Packet& p, ip_protocol_num proto_num, hw_features hw_features) { if (p.len() + ipv4_hdr_len_min <= hw_features.mtu) return false; if ((proto_num == ip_protocol_num::tcp && hw_features.tx_tso)) return false; return true; } void learn(ethernet_address l2, ipv4_address l3) { _arp.learn(l2, l3); } void register_packet_provider(ipv4_traits::packet_provider_type&& func) { _pkt_providers.push_back(std::move(func)); } void wait_l2_dst_address(ipv4_address to, Packet p, resolution_cb cb); }; template <ip_protocol_num ProtoNum> inline void ipv4_l4<ProtoNum>::register_packet_provider( ipv4_traits::packet_provider_type func) { _inet.register_packet_provider([func] { auto l4p = func(); if (l4p) { (*l4p).proto_num = ProtoNum; } return l4p; }); } template <ip_protocol_num ProtoNum> inline void ipv4_l4<ProtoNum>::wait_l2_dst_address(ipv4_address to, Packet p, resolution_cb cb) { _inet.wait_l2_dst_address(to, std::move(p), std::move(cb)); } struct ip_hdr { uint8_t ihl : 4; uint8_t ver : 4; uint8_t dscp : 6; uint8_t ecn : 2; uint16_t len; uint16_t id; uint16_t frag; enum class frag_bits : uint8_t { mf = 13, df = 14, reserved = 15, offset_shift = 3 }; uint8_t ttl; uint8_t ip_proto; uint16_t csum; ipv4_address src_ip; ipv4_address dst_ip; uint8_t options[0]; ip_hdr hton() { ip_hdr hdr = *this; hdr.len = ::hton(len); hdr.id = ::hton(id); hdr.frag = ::hton(frag); hdr.csum = ::hton(csum); hdr.src_ip.ip = ::hton(src_ip.ip); hdr.dst_ip.ip = ::hton(dst_ip.ip); return hdr; } ip_hdr ntoh() { ip_hdr hdr = *this; hdr.len = ::ntoh(len); hdr.id = ::ntoh(id); hdr.frag = ::ntoh(frag); hdr.csum = ::ntoh(csum); hdr.src_ip = src_ip.ntoh(); hdr.dst_ip = dst_ip.ntoh(); return hdr; } bool mf() { return frag & (1 << uint8_t(frag_bits::mf)); } bool df() { return frag & (1 << uint8_t(frag_bits::df)); } uint16_t offset() { return frag << uint8_t(frag_bits::offset_shift); } } __attribute__((packed)); template <typename InetTraits> struct l4connid<InetTraits>::connid_hash : private std::hash<ipaddr>, private std::hash<uint16_t> { size_t operator()(const l4connid<InetTraits>& id) const noexcept { using h1 = std::hash<ipaddr>; using h2 = std::hash<uint16_t>; return h1::operator()(id.local_ip) ^ h1::operator()(id.foreign_ip) ^ h2::operator()(id.local_port) ^ h2::operator()(id.foreign_port); } }; #endif /* CEPH_MSG_IP_H */
11,881
28.410891
111
h
null
ceph-main/src/msg/async/dpdk/IPChecksum.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_MSG_CHECKSUM_H_ #define CEPH_MSG_CHECKSUM_H_ #include <cstdint> #include <cstddef> #include <arpa/inet.h> #include "Packet.h" uint16_t ip_checksum(const void* data, size_t len); struct checksummer { __int128 csum = 0; bool odd = false; void sum(const char* data, size_t len); void sum(const Packet& p); void sum(uint8_t data) { if (!odd) { csum += data << 8; } else { csum += data; } odd = !odd; } void sum(uint16_t data) { if (odd) { sum(uint8_t(data >> 8)); sum(uint8_t(data)); } else { csum += data; } } void sum(uint32_t data) { if (odd) { sum(uint16_t(data)); sum(uint16_t(data >> 16)); } else { csum += data; } } void sum_many() {} template <typename T0, typename... T> void sum_many(T0 data, T... rest) { sum(data); sum_many(rest...); } uint16_t get() const; }; #endif /* CEPH_MSG_CHECKSUM_H_ */
1,807
23.767123
79
h
null
ceph-main/src/msg/async/dpdk/Packet.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_MSG_PACKET_H_ #define CEPH_MSG_PACKET_H_ #include <vector> #include <algorithm> #include <iosfwd> #include "include/types.h" #include "common/deleter.h" #include "msg/async/Event.h" #include "const.h" struct fragment { char* base; size_t size; }; struct offload_info { ip_protocol_num protocol = ip_protocol_num::unused; bool needs_csum = false; uint8_t ip_hdr_len = 20; uint8_t tcp_hdr_len = 20; uint8_t udp_hdr_len = 8; bool needs_ip_csum = false; bool reassembled = false; uint16_t tso_seg_size = 0; // HW stripped VLAN header (CPU order) std::optional<uint16_t> vlan_tci; }; // Zero-copy friendly packet class // // For implementing zero-copy, we need a flexible destructor that can // destroy packet data in different ways: decrementing a reference count, // or calling a free()-like function. // // Moreover, we need different destructors for each set of fragments within // a single fragment. For example, a header and trailer might need delete[] // to be called, while the internal data needs a reference count to be // released. Matters are complicated in that fragments can be split // (due to virtual/physical translation). // // To implement this, we associate each packet with a single destructor, // but allow composing a packet from another packet plus a fragment to // be added, with its own destructor, causing the destructors to be chained. // // The downside is that the data needed for the destructor is duplicated, // if it is already available in the fragment itself. // // As an optimization, when we allocate small fragments, we allocate some // extra space, so prepending to the packet does not require extra // allocations. This is useful when adding headers. // class Packet { // enough for lots of headers, not quite two cache lines: static constexpr size_t internal_data_size = 128 - 16; static constexpr size_t default_nr_frags = 4; struct pseudo_vector { fragment* _start; fragment* _finish; pseudo_vector(fragment* start, size_t nr) : _start(start), _finish(_start + nr) {} fragment* begin() { return _start; } fragment* end() { return _finish; } fragment& operator[](size_t idx) { return _start[idx]; } }; struct impl { // when destroyed, virtual destructor will reclaim resources deleter _deleter; unsigned _len = 0; uint16_t _nr_frags = 0; uint16_t _allocated_frags; offload_info _offload_info; std::optional<uint32_t> rss_hash; char data[internal_data_size]; // only frags[0] may use unsigned headroom = internal_data_size; // in data // FIXME: share data/frags space fragment frags[]; explicit impl(size_t nr_frags = default_nr_frags); impl(const impl&) = delete; impl(fragment frag, size_t nr_frags = default_nr_frags); pseudo_vector fragments() { return { frags, _nr_frags }; } static std::unique_ptr<impl> allocate(size_t nr_frags) { nr_frags = std::max(nr_frags, default_nr_frags); return std::unique_ptr<impl>(new (nr_frags) impl(nr_frags)); } static std::unique_ptr<impl> copy(impl* old, size_t nr) { auto n = allocate(nr); n->_deleter = std::move(old->_deleter); n->_len = old->_len; n->_nr_frags = old->_nr_frags; n->headroom = old->headroom; n->_offload_info = old->_offload_info; n->rss_hash = old->rss_hash; std::copy(old->frags, old->frags + old->_nr_frags, n->frags); old->copy_internal_fragment_to(n.get()); return n; } static std::unique_ptr<impl> copy(impl* old) { return copy(old, old->_nr_frags); } static std::unique_ptr<impl> allocate_if_needed(std::unique_ptr<impl> old, size_t extra_frags) { if (old->_allocated_frags >= old->_nr_frags + extra_frags) { return old; } return copy(old.get(), std::max<size_t>(old->_nr_frags + extra_frags, 2 * old->_nr_frags)); } void* operator new(size_t size, size_t nr_frags = default_nr_frags) { ceph_assert(nr_frags == uint16_t(nr_frags)); return ::operator new(size + nr_frags * sizeof(fragment)); } // Matching the operator new above void operator delete(void* ptr, size_t nr_frags) { return ::operator delete(ptr); } // Since the above "placement delete" hides the global one, expose it void operator delete(void* ptr) { return ::operator delete(ptr); } bool using_internal_data() const { return _nr_frags && frags[0].base >= data && frags[0].base < data + internal_data_size; } void unuse_internal_data() { if (!using_internal_data()) { return; } auto buf = static_cast<char*>(::malloc(frags[0].size)); if (!buf) { throw std::bad_alloc(); } deleter d = make_free_deleter(buf); std::copy(frags[0].base, frags[0].base + frags[0].size, buf); frags[0].base = buf; _deleter.append(std::move(d)); headroom = internal_data_size; } void copy_internal_fragment_to(impl* to) { if (!using_internal_data()) { return; } to->frags[0].base = to->data + headroom; std::copy(frags[0].base, frags[0].base + frags[0].size, to->frags[0].base); } }; explicit Packet(std::unique_ptr<impl>&& impl) : _impl(std::move(impl)) {} std::unique_ptr<impl> _impl; public: static Packet from_static_data(const char* data, size_t len) { return {fragment{const_cast<char*>(data), len}, deleter()}; } // build empty Packet Packet(); // build empty Packet with nr_frags allocated explicit Packet(size_t nr_frags); // move existing Packet Packet(Packet&& x) noexcept; // copy data into Packet Packet(const char* data, size_t len); // copy data into Packet explicit Packet(fragment frag); // zero-copy single fragment Packet(fragment frag, deleter del); // zero-copy multiple fragments Packet(std::vector<fragment> frag, deleter del); // build Packet with iterator template <typename Iterator> Packet(Iterator begin, Iterator end, deleter del); // append fragment (copying new fragment) Packet(Packet&& x, fragment frag); // prepend fragment (copying new fragment, with header optimization) Packet(fragment frag, Packet&& x); // prepend fragment (zero-copy) Packet(fragment frag, deleter del, Packet&& x); // append fragment (zero-copy) Packet(Packet&& x, fragment frag, deleter d); // append deleter Packet(Packet&& x, deleter d); Packet& operator=(Packet&& x) { if (this != &x) { this->~Packet(); new (this) Packet(std::move(x)); } return *this; } unsigned len() const { return _impl->_len; } unsigned memory() const { return len() + sizeof(Packet::impl); } fragment frag(unsigned idx) const { return _impl->frags[idx]; } fragment& frag(unsigned idx) { return _impl->frags[idx]; } unsigned nr_frags() const { return _impl->_nr_frags; } pseudo_vector fragments() const { return { _impl->frags, _impl->_nr_frags }; } fragment* fragment_array() const { return _impl->frags; } // share Packet data (reference counted, non COW) Packet share(); Packet share(size_t offset, size_t len); void append(Packet&& p); void trim_front(size_t how_much); void trim_back(size_t how_much); // get a header pointer, linearizing if necessary template <typename Header> Header* get_header(size_t offset = 0); // get a header pointer, linearizing if necessary char* get_header(size_t offset, size_t size); // prepend a header (default-initializing it) template <typename Header> Header* prepend_header(size_t extra_size = 0); // prepend a header (uninitialized!) char* prepend_uninitialized_header(size_t size); Packet free_on_cpu(EventCenter *c, std::function<void()> cb = []{}); void linearize() { return linearize(0, len()); } void reset() { _impl.reset(); } void reserve(int n_frags) { if (n_frags > _impl->_nr_frags) { auto extra = n_frags - _impl->_nr_frags; _impl = impl::allocate_if_needed(std::move(_impl), extra); } } std::optional<uint32_t> rss_hash() { return _impl->rss_hash; } void set_rss_hash(uint32_t hash) { _impl->rss_hash = hash; } private: void linearize(size_t at_frag, size_t desired_size); bool allocate_headroom(size_t size); public: class offload_info offload_info() const { return _impl->_offload_info; } class offload_info& offload_info_ref() { return _impl->_offload_info; } void set_offload_info(class offload_info oi) { _impl->_offload_info = oi; } }; std::ostream& operator<<(std::ostream& os, const Packet& p); inline Packet::Packet(Packet&& x) noexcept : _impl(std::move(x._impl)) { } inline Packet::impl::impl(size_t nr_frags) : _len(0), _allocated_frags(nr_frags) { } inline Packet::impl::impl(fragment frag, size_t nr_frags) : _len(frag.size), _allocated_frags(nr_frags) { ceph_assert(_allocated_frags > _nr_frags); if (frag.size <= internal_data_size) { headroom -= frag.size; frags[0] = { data + headroom, frag.size }; } else { auto buf = static_cast<char*>(::malloc(frag.size)); if (!buf) { throw std::bad_alloc(); } deleter d = make_free_deleter(buf); frags[0] = { buf, frag.size }; _deleter.append(std::move(d)); } std::copy(frag.base, frag.base + frag.size, frags[0].base); ++_nr_frags; } inline Packet::Packet(): _impl(impl::allocate(1)) { } inline Packet::Packet(size_t nr_frags): _impl(impl::allocate(nr_frags)) { } inline Packet::Packet(fragment frag): _impl(new impl(frag)) { } inline Packet::Packet(const char* data, size_t size): Packet(fragment{const_cast<char*>(data), size}) { } inline Packet::Packet(fragment frag, deleter d) : _impl(impl::allocate(1)) { _impl->_deleter = std::move(d); _impl->frags[_impl->_nr_frags++] = frag; _impl->_len = frag.size; } inline Packet::Packet(std::vector<fragment> frag, deleter d) : _impl(impl::allocate(frag.size())) { _impl->_deleter = std::move(d); std::copy(frag.begin(), frag.end(), _impl->frags); _impl->_nr_frags = frag.size(); _impl->_len = 0; for (auto&& f : _impl->fragments()) { _impl->_len += f.size; } } template <typename Iterator> inline Packet::Packet(Iterator begin, Iterator end, deleter del) { unsigned nr_frags = 0, len = 0; nr_frags = std::distance(begin, end); std::for_each(begin, end, [&] (fragment& frag) { len += frag.size; }); _impl = impl::allocate(nr_frags); _impl->_deleter = std::move(del); _impl->_len = len; _impl->_nr_frags = nr_frags; std::copy(begin, end, _impl->frags); } inline Packet::Packet(Packet&& x, fragment frag) : _impl(impl::allocate_if_needed(std::move(x._impl), 1)) { _impl->_len += frag.size; char* buf = new char[frag.size]; std::copy(frag.base, frag.base + frag.size, buf); _impl->frags[_impl->_nr_frags++] = {buf, frag.size}; _impl->_deleter = make_deleter(std::move(_impl->_deleter), [buf] { delete[] buf; }); } inline bool Packet::allocate_headroom(size_t size) { if (_impl->headroom >= size) { _impl->_len += size; if (!_impl->using_internal_data()) { _impl = impl::allocate_if_needed(std::move(_impl), 1); std::copy_backward(_impl->frags, _impl->frags + _impl->_nr_frags, _impl->frags + _impl->_nr_frags + 1); _impl->frags[0] = { _impl->data + internal_data_size, 0 }; ++_impl->_nr_frags; } _impl->headroom -= size; _impl->frags[0].base -= size; _impl->frags[0].size += size; return true; } else { return false; } } inline Packet::Packet(fragment frag, Packet&& x) : _impl(std::move(x._impl)) { // try to prepend into existing internal fragment if (allocate_headroom(frag.size)) { std::copy(frag.base, frag.base + frag.size, _impl->frags[0].base); return; } else { // didn't work out, allocate and copy _impl->unuse_internal_data(); _impl = impl::allocate_if_needed(std::move(_impl), 1); _impl->_len += frag.size; char *buf = new char[frag.size]; std::copy(frag.base, frag.base + frag.size, buf); std::copy_backward(_impl->frags, _impl->frags + _impl->_nr_frags, _impl->frags + _impl->_nr_frags + 1); ++_impl->_nr_frags; _impl->frags[0] = {buf, frag.size}; _impl->_deleter = make_deleter( std::move(_impl->_deleter), [buf] { delete []buf; }); } } inline Packet::Packet(Packet&& x, fragment frag, deleter d) : _impl(impl::allocate_if_needed(std::move(x._impl), 1)) { _impl->_len += frag.size; _impl->frags[_impl->_nr_frags++] = frag; d.append(std::move(_impl->_deleter)); _impl->_deleter = std::move(d); } inline Packet::Packet(Packet&& x, deleter d): _impl(std::move(x._impl)) { _impl->_deleter.append(std::move(d)); } inline void Packet::append(Packet&& p) { if (!_impl->_len) { *this = std::move(p); return; } _impl = impl::allocate_if_needed(std::move(_impl), p._impl->_nr_frags); _impl->_len += p._impl->_len; p._impl->unuse_internal_data(); std::copy(p._impl->frags, p._impl->frags + p._impl->_nr_frags, _impl->frags + _impl->_nr_frags); _impl->_nr_frags += p._impl->_nr_frags; p._impl->_deleter.append(std::move(_impl->_deleter)); _impl->_deleter = std::move(p._impl->_deleter); } inline char* Packet::get_header(size_t offset, size_t size) { if (offset + size > _impl->_len) { return nullptr; } size_t i = 0; while (i != _impl->_nr_frags && offset >= _impl->frags[i].size) { offset -= _impl->frags[i++].size; } if (i == _impl->_nr_frags) { return nullptr; } if (offset + size > _impl->frags[i].size) { linearize(i, offset + size); } return _impl->frags[i].base + offset; } template <typename Header> inline Header* Packet::get_header(size_t offset) { return reinterpret_cast<Header*>(get_header(offset, sizeof(Header))); } inline void Packet::trim_front(size_t how_much) { ceph_assert(how_much <= _impl->_len); _impl->_len -= how_much; size_t i = 0; while (how_much && how_much >= _impl->frags[i].size) { how_much -= _impl->frags[i++].size; } std::copy(_impl->frags + i, _impl->frags + _impl->_nr_frags, _impl->frags); _impl->_nr_frags -= i; if (!_impl->using_internal_data()) { _impl->headroom = internal_data_size; } if (how_much) { if (_impl->using_internal_data()) { _impl->headroom += how_much; } _impl->frags[0].base += how_much; _impl->frags[0].size -= how_much; } } inline void Packet::trim_back(size_t how_much) { ceph_assert(how_much <= _impl->_len); _impl->_len -= how_much; size_t i = _impl->_nr_frags - 1; while (how_much && how_much >= _impl->frags[i].size) { how_much -= _impl->frags[i--].size; } _impl->_nr_frags = i + 1; if (how_much) { _impl->frags[i].size -= how_much; if (i == 0 && _impl->using_internal_data()) { _impl->headroom += how_much; } } } template <typename Header> Header* Packet::prepend_header(size_t extra_size) { auto h = prepend_uninitialized_header(sizeof(Header) + extra_size); return new (h) Header{}; } // prepend a header (uninitialized!) inline char* Packet::prepend_uninitialized_header(size_t size) { if (!allocate_headroom(size)) { // didn't work out, allocate and copy _impl->unuse_internal_data(); // try again, after unuse_internal_data we may have space after all if (!allocate_headroom(size)) { // failed _impl->_len += size; _impl = impl::allocate_if_needed(std::move(_impl), 1); char *buf = new char[size]; std::copy_backward(_impl->frags, _impl->frags + _impl->_nr_frags, _impl->frags + _impl->_nr_frags + 1); ++_impl->_nr_frags; _impl->frags[0] = {buf, size}; _impl->_deleter = make_deleter(std::move(_impl->_deleter), [buf] { delete []buf; }); } } return _impl->frags[0].base; } inline Packet Packet::share() { return share(0, _impl->_len); } inline Packet Packet::share(size_t offset, size_t len) { _impl->unuse_internal_data(); // FIXME: eliminate? Packet n; n._impl = impl::allocate_if_needed(std::move(n._impl), _impl->_nr_frags); size_t idx = 0; while (offset > 0 && offset >= _impl->frags[idx].size) { offset -= _impl->frags[idx++].size; } while (n._impl->_len < len) { auto& f = _impl->frags[idx++]; auto fsize = std::min(len - n._impl->_len, f.size - offset); n._impl->frags[n._impl->_nr_frags++] = { f.base + offset, fsize }; n._impl->_len += fsize; offset = 0; } n._impl->_offload_info = _impl->_offload_info; ceph_assert(!n._impl->_deleter); n._impl->_deleter = _impl->_deleter.share(); return n; } #endif /* CEPH_MSG_PACKET_H_ */
17,562
30.932727
100
h
null
ceph-main/src/msg/async/dpdk/PacketUtil.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_MSG_PACKET_UTIL_H_ #define CEPH_MSG_PACKET_UTIL_H_ #include <map> #include <iostream> #include "Packet.h" template <typename Offset, typename Tag> class packet_merger { private: static uint64_t& linearizations_ref() { static thread_local uint64_t linearization_count; return linearization_count; } public: std::map<Offset, Packet> map; static uint64_t linearizations() { return linearizations_ref(); } void merge(Offset offset, Packet p) { bool insert = true; auto beg = offset; auto end = beg + p.len(); // First, try to merge the packet with existing segment for (auto it = map.begin(); it != map.end();) { auto& seg_pkt = it->second; auto seg_beg = it->first; auto seg_end = seg_beg + seg_pkt.len(); // There are 6 cases: if (seg_beg <= beg && end <= seg_end) { // 1) seg_beg beg end seg_end // We already have data in this packet return; } else if (beg <= seg_beg && seg_end <= end) { // 2) beg seg_beg seg_end end // The new segment contains more data than this old segment // Delete the old one, insert the new one it = map.erase(it); insert = true; break; } else if (beg < seg_beg && seg_beg <= end && end <= seg_end) { // 3) beg seg_beg end seg_end // Merge two segments, trim front of old segment auto trim = end - seg_beg; seg_pkt.trim_front(trim); p.append(std::move(seg_pkt)); // Delete the old one, insert the new one it = map.erase(it); insert = true; break; } else if (seg_beg <= beg && beg <= seg_end && seg_end < end) { // 4) seg_beg beg seg_end end // Merge two segments, trim front of new segment auto trim = seg_end - beg; p.trim_front(trim); // Append new data to the old segment, keep the old segment seg_pkt.append(std::move(p)); seg_pkt.linearize(); ++linearizations_ref(); insert = false; break; } else { // 5) beg end < seg_beg seg_end // or // 6) seg_beg seg_end < beg end // Can not merge with this segment, keep looking it++; insert = true; } } if (insert) { p.linearize(); ++linearizations_ref(); map.emplace(beg, std::move(p)); } // Second, merge adjacent segments after this packet has been merged, // because this packet might fill a "whole" and make two adjacent // segments mergable for (auto it = map.begin(); it != map.end();) { // The first segment auto& seg_pkt = it->second; auto seg_beg = it->first; auto seg_end = seg_beg + seg_pkt.len(); // The second segment auto it_next = it; it_next++; if (it_next == map.end()) { break; } auto& p = it_next->second; auto beg = it_next->first; auto end = beg + p.len(); // Merge the the second segment into first segment if possible if (seg_beg <= beg && beg <= seg_end && seg_end < end) { // Merge two segments, trim front of second segment auto trim = seg_end - beg; p.trim_front(trim); // Append new data to the first segment, keep the first segment seg_pkt.append(std::move(p)); // Delete the second segment map.erase(it_next); // Keep merging this first segment with its new next packet // So we do not update the iterator: it continue; } else if (end <= seg_end) { // The first segment has all the data in the second segment // Delete the second segment map.erase(it_next); continue; } else if (seg_end < beg) { // Can not merge first segment with second segment it = it_next; continue; } else { // If we reach here, we have a bug with merge. std::cout << "packet_merger: merge error\n"; abort(); } } } }; #endif
4,892
30.567742
79
h
null
ceph-main/src/msg/async/dpdk/TCP-Stack.h
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ // tcp/network-stack integration #ifndef CEPH_MSG_DPDK_TCP_STACK_H #define CEPH_MSG_DPDK_TCP_STACK_H class ServerSocket; class ConnectedSocket; class ipv4_traits; template <typename InetTraits> class tcp; int tcpv4_listen(tcp<ipv4_traits>& tcpv4, uint16_t port, const SocketOptions &opts, int type, unsigned addr_slot, ServerSocket *sa); int tcpv4_connect(tcp<ipv4_traits>& tcpv4, const entity_addr_t &addr, ConnectedSocket *sa); #endif
1,266
29.902439
83
h
null
ceph-main/src/msg/async/dpdk/UserspaceEvent.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * Ceph - scalable distributed file system * * Copyright (C) 2015 XSky <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_USERSPACEEVENT_H #define CEPH_USERSPACEEVENT_H #include <cstddef> #include <errno.h> #include <string.h> #include <list> #include <optional> #include <vector> #include "include/ceph_assert.h" #include "include/int_types.h" class CephContext; class UserspaceEventManager { struct UserspaceFDImpl { uint32_t waiting_idx = 0; int16_t read_errno = 0; int16_t write_errno = 0; int8_t listening_mask = 0; int8_t activating_mask = 0; uint32_t magic = 4921; }; CephContext *cct; int max_fd = 0; uint32_t max_wait_idx = 0; std::vector<std::optional<UserspaceFDImpl> > fds; std::vector<int> waiting_fds; std::list<uint32_t> unused_fds; public: explicit UserspaceEventManager(CephContext *c): cct(c) { waiting_fds.resize(1024); } int get_eventfd(); int listen(int fd, int mask) { if ((size_t)fd >= fds.size()) return -ENOENT; std::optional<UserspaceFDImpl> &impl = fds[fd]; if (!impl) return -ENOENT; impl->listening_mask |= mask; if (impl->activating_mask & impl->listening_mask && !impl->waiting_idx) { if (waiting_fds.size() <= max_wait_idx) waiting_fds.resize(waiting_fds.size()*2); impl->waiting_idx = ++max_wait_idx; waiting_fds[max_wait_idx] = fd; } return 0; } int unlisten(int fd, int mask) { if ((size_t)fd >= fds.size()) return -ENOENT; std::optional<UserspaceFDImpl> &impl = fds[fd]; if (!impl) return -ENOENT; impl->listening_mask &= (~mask); if (!(impl->activating_mask & impl->listening_mask) && impl->waiting_idx) { if (waiting_fds[max_wait_idx] == fd) { ceph_assert(impl->waiting_idx == max_wait_idx); --max_wait_idx; } waiting_fds[impl->waiting_idx] = -1; impl->waiting_idx = 0; } return 0; } int notify(int fd, int mask); void close(int fd); int poll(int *events, int *masks, int num_events, struct timeval *tp); bool check() { for (auto &&m : fds) { if (m && m->magic != 4921) return false; } return true; } }; #endif //CEPH_USERSPACEEVENT_H
2,557
22.906542
79
h
null
ceph-main/src/msg/async/dpdk/align.h
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_MSG_DPDK_ALIGN_HH_ #define CEPH_MSG_DPDK_ALIGN_HH_ #include <cstdint> #include <cstdlib> template <typename T> inline constexpr T align_up(T v, T align) { return (v + align - 1) & ~(align - 1); } template <typename T> inline constexpr T* align_up(T* v, size_t align) { static_assert(sizeof(T) == 1, "align byte pointers only"); return reinterpret_cast<T*>(align_up(reinterpret_cast<uintptr_t>(v), align)); } template <typename T> inline constexpr T align_down(T v, T align) { return v & ~(align - 1); } template <typename T> inline constexpr T* align_down(T* v, size_t align) { static_assert(sizeof(T) == 1, "align byte pointers only"); return reinterpret_cast<T*>(align_down(reinterpret_cast<uintptr_t>(v), align)); } #endif /* CEPH_MSG_DPDK_ALIGN_HH_ */
1,575
29.901961
81
h
null
ceph-main/src/msg/async/dpdk/array_map.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_ARRAY_MAP_HH_ #define CEPH_ARRAY_MAP_HH_ #include <array> // unordered_map implemented as a simple array template <typename Value, size_t Max> class array_map { std::array<Value, Max> _a {}; public: array_map(std::initializer_list<std::pair<size_t, Value>> i) { for (auto kv : i) { _a[kv.first] = kv.second; } } Value& operator[](size_t key) { return _a[key]; } const Value& operator[](size_t key) const { return _a[key]; } Value& at(size_t key) { if (key >= Max) { throw std::out_of_range(std::to_string(key) + " >= " + std::to_string(Max)); } return _a[key]; } }; #endif /* ARRAY_MAP_HH_ */
1,518
28.784314
82
h
null
ceph-main/src/msg/async/dpdk/byteorder.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_MSG_BYTEORDER_H_ #define CEPH_MSG_BYTEORDER_H_ #include <arpa/inet.h> // for ntohs() and friends #include <iosfwd> #include <utility> inline uint64_t ntohq(uint64_t v) { return __builtin_bswap64(v); } inline uint64_t htonq(uint64_t v) { return __builtin_bswap64(v); } inline void ntoh() {} inline void hton() {} inline uint8_t ntoh(uint8_t x) { return x; } inline uint8_t hton(uint8_t x) { return x; } inline uint16_t ntoh(uint16_t x) { return ntohs(x); } inline uint16_t hton(uint16_t x) { return htons(x); } inline uint32_t ntoh(uint32_t x) { return ntohl(x); } inline uint32_t hton(uint32_t x) { return htonl(x); } inline uint64_t ntoh(uint64_t x) { return ntohq(x); } inline uint64_t hton(uint64_t x) { return htonq(x); } inline int8_t ntoh(int8_t x) { return x; } inline int8_t hton(int8_t x) { return x; } inline int16_t ntoh(int16_t x) { return ntohs(x); } inline int16_t hton(int16_t x) { return htons(x); } inline int32_t ntoh(int32_t x) { return ntohl(x); } inline int32_t hton(int32_t x) { return htonl(x); } inline int64_t ntoh(int64_t x) { return ntohq(x); } inline int64_t hton(int64_t x) { return htonq(x); } #endif /* CEPH_MSG_BYTEORDER_H_ */
2,043
33.644068
79
h
null
ceph-main/src/msg/async/dpdk/capture.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * Ceph - scalable distributed file system * * Copyright (C) 2015 XSky <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_MSG_DPDK_CAPTURE_H #define CEPH_MSG_DPDK_CAPTURE_H #include <utility> template <typename T, typename F> class capture_impl { T x; F f; public: capture_impl(capture_impl &) = delete; capture_impl( T && x, F && f ) : x{std::forward<T>(x)}, f{std::forward<F>(f)} {} template <typename ...Ts> auto operator()( Ts&&...args ) -> decltype(f( x, std::forward<Ts>(args)... )) { return f( x, std::forward<Ts>(args)... ); } template <typename ...Ts> auto operator()( Ts&&...args ) const -> decltype(f( x, std::forward<Ts>(args)... )) { return f( x, std::forward<Ts>(args)... ); } }; template <typename T, typename F> capture_impl<T,F> capture( T && x, F && f ) { return capture_impl<T,F>( std::forward<T>(x), std::forward<F>(f) ); } #endif //CEPH_MSG_DPDK_CAPTURE_H
1,259
23.705882
70
h
null
ceph-main/src/msg/async/dpdk/circular_buffer.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_CIRCULAR_BUFFER_HH_ #define CEPH_CIRCULAR_BUFFER_HH_ // A growable double-ended queue container that can be efficiently // extended (and shrunk) from both ends. Implementation is a single // storage vector. // // Similar to libstdc++'s std::deque, except that it uses a single level // store, and so is more efficient for simple stored items. // Similar to boost::circular_buffer_space_optimized, except it uses // uninitialized storage for unoccupied elements (and thus move/copy // constructors instead of move/copy assignments, which are less efficient). #include <memory> #include <algorithm> #include "transfer.h" template <typename T, typename Alloc = std::allocator<T>> class circular_buffer { struct impl : Alloc { T* storage = nullptr; // begin, end interpreted (mod capacity) size_t begin = 0; size_t end = 0; size_t capacity = 0; }; impl _impl; public: using value_type = T; using size_type = size_t; using reference = T&; using pointer = T*; using const_reference = const T&; using const_pointer = const T*; public: circular_buffer() = default; circular_buffer(circular_buffer&& X); circular_buffer(const circular_buffer& X) = delete; ~circular_buffer(); circular_buffer& operator=(const circular_buffer&) = delete; circular_buffer& operator=(circular_buffer&&) = delete; void push_front(const T& data); void push_front(T&& data); template <typename... A> void emplace_front(A&&... args); void push_back(const T& data); void push_back(T&& data); template <typename... A> void emplace_back(A&&... args); T& front(); T& back(); void pop_front(); void pop_back(); bool empty() const; size_t size() const; size_t capacity() const; T& operator[](size_t idx); template <typename Func> void for_each(Func func); // access an element, may return wrong or destroyed element // only useful if you do not rely on data accuracy (e.g. prefetch) T& access_element_unsafe(size_t idx); private: void expand(); void maybe_expand(size_t nr = 1); size_t mask(size_t idx) const; template<typename CB, typename ValueType> struct cbiterator : std::iterator<std::random_access_iterator_tag, ValueType> { typedef std::iterator<std::random_access_iterator_tag, ValueType> super_t; ValueType& operator*() const { return cb->_impl.storage[cb->mask(idx)]; } ValueType* operator->() const { return &cb->_impl.storage[cb->mask(idx)]; } // prefix cbiterator<CB, ValueType>& operator++() { idx++; return *this; } // postfix cbiterator<CB, ValueType> operator++(int unused) { auto v = *this; idx++; return v; } // prefix cbiterator<CB, ValueType>& operator--() { idx--; return *this; } // postfix cbiterator<CB, ValueType> operator--(int unused) { auto v = *this; idx--; return v; } cbiterator<CB, ValueType> operator+(typename super_t::difference_type n) const { return cbiterator<CB, ValueType>(cb, idx + n); } cbiterator<CB, ValueType> operator-(typename super_t::difference_type n) const { return cbiterator<CB, ValueType>(cb, idx - n); } cbiterator<CB, ValueType>& operator+=(typename super_t::difference_type n) { idx += n; return *this; } cbiterator<CB, ValueType>& operator-=(typename super_t::difference_type n) { idx -= n; return *this; } bool operator==(const cbiterator<CB, ValueType>& rhs) const { return idx == rhs.idx; } bool operator!=(const cbiterator<CB, ValueType>& rhs) const { return idx != rhs.idx; } bool operator<(const cbiterator<CB, ValueType>& rhs) const { return idx < rhs.idx; } bool operator>(const cbiterator<CB, ValueType>& rhs) const { return idx > rhs.idx; } bool operator>=(const cbiterator<CB, ValueType>& rhs) const { return idx >= rhs.idx; } bool operator<=(const cbiterator<CB, ValueType>& rhs) const { return idx <= rhs.idx; } typename super_t::difference_type operator-(const cbiterator<CB, ValueType>& rhs) const { return idx - rhs.idx; } private: CB* cb; size_t idx; cbiterator<CB, ValueType>(CB* b, size_t i) : cb(b), idx(i) {} friend class circular_buffer; }; friend class iterator; public: typedef cbiterator<circular_buffer, T> iterator; typedef cbiterator<const circular_buffer, const T> const_iterator; iterator begin() { return iterator(this, _impl.begin); } const_iterator begin() const { return const_iterator(this, _impl.begin); } iterator end() { return iterator(this, _impl.end); } const_iterator end() const { return const_iterator(this, _impl.end); } const_iterator cbegin() const { return const_iterator(this, _impl.begin); } const_iterator cend() const { return const_iterator(this, _impl.end); } }; template <typename T, typename Alloc> inline size_t circular_buffer<T, Alloc>::mask(size_t idx) const { return idx & (_impl.capacity - 1); } template <typename T, typename Alloc> inline bool circular_buffer<T, Alloc>::empty() const { return _impl.begin == _impl.end; } template <typename T, typename Alloc> inline size_t circular_buffer<T, Alloc>::size() const { return _impl.end - _impl.begin; } template <typename T, typename Alloc> inline size_t circular_buffer<T, Alloc>::capacity() const { return _impl.capacity; } template <typename T, typename Alloc> inline circular_buffer<T, Alloc>::circular_buffer(circular_buffer&& x) : _impl(std::move(x._impl)) { x._impl = {}; } template <typename T, typename Alloc> template <typename Func> inline void circular_buffer<T, Alloc>::for_each(Func func) { auto s = _impl.storage; auto m = _impl.capacity - 1; for (auto i = _impl.begin; i != _impl.end; ++i) { func(s[i & m]); } } template <typename T, typename Alloc> inline circular_buffer<T, Alloc>::~circular_buffer() { for_each([this] (T& obj) { _impl.destroy(&obj); }); _impl.deallocate(_impl.storage, _impl.capacity); } template <typename T, typename Alloc> void circular_buffer<T, Alloc>::expand() { auto new_cap = std::max<size_t>(_impl.capacity * 2, 1); auto new_storage = _impl.allocate(new_cap); auto p = new_storage; try { for_each([this, &p] (T& obj) { transfer_pass1(_impl, &obj, p); p++; }); } catch (...) { while (p != new_storage) { _impl.destroy(--p); } _impl.deallocate(new_storage, new_cap); throw; } p = new_storage; for_each([this, &p] (T& obj) { transfer_pass2(_impl, &obj, p++); }); std::swap(_impl.storage, new_storage); std::swap(_impl.capacity, new_cap); _impl.begin = 0; _impl.end = p - _impl.storage; _impl.deallocate(new_storage, new_cap); } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::maybe_expand(size_t nr) { if (_impl.end - _impl.begin + nr > _impl.capacity) { expand(); } } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_front(const T& data) { maybe_expand(); auto p = &_impl.storage[mask(_impl.begin - 1)]; _impl.construct(p, data); --_impl.begin; } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_front(T&& data) { maybe_expand(); auto p = &_impl.storage[mask(_impl.begin - 1)]; _impl.construct(p, std::move(data)); --_impl.begin; } template <typename T, typename Alloc> template <typename... Args> inline void circular_buffer<T, Alloc>::emplace_front(Args&&... args) { maybe_expand(); auto p = &_impl.storage[mask(_impl.begin - 1)]; _impl.construct(p, std::forward<Args>(args)...); --_impl.begin; } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_back(const T& data) { maybe_expand(); auto p = &_impl.storage[mask(_impl.end)]; _impl.construct(p, data); ++_impl.end; } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_back(T&& data) { maybe_expand(); auto p = &_impl.storage[mask(_impl.end)]; _impl.construct(p, std::move(data)); ++_impl.end; } template <typename T, typename Alloc> template <typename... Args> inline void circular_buffer<T, Alloc>::emplace_back(Args&&... args) { maybe_expand(); auto p = &_impl.storage[mask(_impl.end)]; _impl.construct(p, std::forward<Args>(args)...); ++_impl.end; } template <typename T, typename Alloc> inline T& circular_buffer<T, Alloc>::front() { return _impl.storage[mask(_impl.begin)]; } template <typename T, typename Alloc> inline T& circular_buffer<T, Alloc>::back() { return _impl.storage[mask(_impl.end - 1)]; } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::pop_front() { _impl.destroy(&front()); ++_impl.begin; } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::pop_back() { _impl.destroy(&back()); --_impl.end; } template <typename T, typename Alloc> inline T& circular_buffer<T, Alloc>::operator[](size_t idx) { return _impl.storage[mask(_impl.begin + idx)]; } template <typename T, typename Alloc> inline T& circular_buffer<T, Alloc>::access_element_unsafe(size_t idx) { return _impl.storage[mask(_impl.begin + idx)]; } #endif /* CEPH_CIRCULAR_BUFFER_HH_ */
10,157
28.189655
93
h
null
ceph-main/src/msg/async/dpdk/const.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_MSG_CONST_H_ #define CEPH_MSG_CONST_H_ #include <stdint.h> enum class ip_protocol_num : uint8_t { icmp = 1, tcp = 6, unused = 255 }; enum class eth_protocol_num : uint16_t { ipv4 = 0x0800, arp = 0x0806, ipv6 = 0x86dd }; const uint8_t eth_hdr_len = 14; const uint8_t tcp_hdr_len_min = 20; const uint8_t ipv4_hdr_len_min = 20; const uint8_t ipv6_hdr_len_min = 40; const uint16_t ip_packet_len_max = 65535; #endif
1,293
29.093023
79
h
null
ceph-main/src/msg/async/dpdk/dpdk_rte.h
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef CEPH_DPDK_RTE_H_ #define CEPH_DPDK_RTE_H_ #include <condition_variable> #include <mutex> #include <thread> #include <bitset> #include <rte_config.h> #include <rte_version.h> #include <boost/program_options.hpp> /*********************** Compat section ***************************************/ // We currently support only versions 2.0 and above. #if (RTE_VERSION < RTE_VERSION_NUM(2,0,0,0)) #error "DPDK version above 2.0.0 is required" #endif #if defined(RTE_MBUF_REFCNT_ATOMIC) #warning "CONFIG_RTE_MBUF_REFCNT_ATOMIC should be disabled in DPDK's " \ "config/common_linuxapp" #endif /******************************************************************************/ namespace dpdk { // DPDK Environment Abstraction Layer class eal { public: using cpuset = std::bitset<RTE_MAX_LCORE>; explicit eal(CephContext *cct) : cct(cct) {} int start(); void stop(); void execute_on_master(std::function<void()> &&f) { bool done = false; std::unique_lock<std::mutex> l(lock); funcs.emplace_back([&]() { f(); done = true; }); cond.notify_all(); while (!done) cond.wait(l); } /** * Returns the amount of memory needed for DPDK * @param num_cpus Number of CPUs the application is going to use * * @return */ size_t mem_size(int num_cpus); static bool rte_initialized; private: CephContext *cct; bool initialized = false; bool stopped = false; std::thread t; std::mutex lock; std::condition_variable cond; std::list<std::function<void()>> funcs; }; } // namespace dpdk #endif // CEPH_DPDK_RTE_H_
2,314
27.9375
80
h
null
ceph-main/src/msg/async/dpdk/ethernet.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_MSG_ETHERNET_H_ #define CEPH_MSG_ETHERNET_H_ #include <array> #include <sstream> #include "include/ceph_assert.h" #include "byteorder.h" struct ethernet_address { ethernet_address() {} ethernet_address(const uint8_t *eaddr) { std::copy(eaddr, eaddr + 6, mac.begin()); } ethernet_address(std::initializer_list<uint8_t> eaddr) { ceph_assert(eaddr.size() == mac.size()); std::copy(eaddr.begin(), eaddr.end(), mac.begin()); } ethernet_address ntoh() { return *this; } ethernet_address hton() { return *this; } std::array<uint8_t, 6> mac; } __attribute__((packed)); inline bool operator==(const ethernet_address& a, const ethernet_address& b) { return a.mac == b.mac; } std::ostream& operator<<(std::ostream& os, const ethernet_address& ea); struct ethernet { using address = ethernet_address; static address broadcast_address() { return {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; } static constexpr uint16_t arp_hardware_type() { return 1; } }; struct eth_hdr { ethernet_address dst_mac; ethernet_address src_mac; uint16_t eth_proto; eth_hdr hton() { eth_hdr hdr = *this; hdr.eth_proto = ::hton(eth_proto); return hdr; } eth_hdr ntoh() { eth_hdr hdr = *this; hdr.eth_proto = ::ntoh(eth_proto); return hdr; } } __attribute__((packed)); ethernet_address parse_ethernet_address(std::string addr); #endif /* CEPH_MSG_ETHERNET_H_ */
2,297
26.035294
79
h
null
ceph-main/src/msg/async/dpdk/ip_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. * */ /* * Ceph - scalable distributed file system * * Copyright (C) 2015 XSky <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_IP_TYPES_H_H #define CEPH_IP_TYPES_H_H #include <boost/asio/ip/address_v4.hpp> #include <string> class Packet; class ethernet_address; using resolution_cb = std::function<void (const ethernet_address&, Packet, int)>; struct ipv4_addr { uint32_t ip; uint16_t port; ipv4_addr() : ip(0), port(0) {} ipv4_addr(uint32_t ip, uint16_t port) : ip(ip), port(port) {} ipv4_addr(uint16_t port) : ip(0), port(port) {} ipv4_addr(const std::string &addr); ipv4_addr(const std::string &addr, uint16_t port); ipv4_addr(const entity_addr_t &ad) { ip = ntoh(ad.in4_addr().sin_addr.s_addr); port = ad.get_port(); } ipv4_addr(entity_addr_t &&addr) : ipv4_addr(addr) {} }; struct ipv4_address { ipv4_address() : ip(0) {} explicit ipv4_address(uint32_t ip) : ip(ip) {} explicit ipv4_address(const std::string& addr) { ip = static_cast<uint32_t>(boost::asio::ip::address_v4::from_string(addr).to_ulong()); } ipv4_address(ipv4_addr addr) { ip = addr.ip; } uint32_t ip; ipv4_address hton() { ipv4_address addr; addr.ip = ::hton(ip); return addr; } ipv4_address ntoh() { ipv4_address addr; addr.ip = ::ntoh(ip); return addr; } friend bool operator==(ipv4_address x, ipv4_address y) { return x.ip == y.ip; } friend bool operator!=(ipv4_address x, ipv4_address y) { return x.ip != y.ip; } } __attribute__((packed)); static inline bool is_unspecified(ipv4_address addr) { return addr.ip == 0; } std::ostream& operator<<(std::ostream& os, const ipv4_address& a); namespace std { template <> struct hash<ipv4_address> { size_t operator()(ipv4_address a) const { return a.ip; } }; } #endif //CEPH_IP_TYPES_H_H
2,941
25.745455
90
h
null
ceph-main/src/msg/async/dpdk/net.h
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_MSG_DPDK_NET_H #define CEPH_MSG_DPDK_NET_H #include "const.h" #include "ethernet.h" #include "Packet.h" #include "stream.h" #include "toeplitz.h" struct hw_features { // Enable tx ip header checksum offload bool tx_csum_ip_offload = false; // Enable tx l4 (TCP or UDP) checksum offload bool tx_csum_l4_offload = false; // Enable rx checksum offload bool rx_csum_offload = false; // LRO is enabled bool rx_lro = false; // Enable tx TCP segment offload bool tx_tso = false; // Enable tx UDP fragmentation offload bool tx_ufo = false; // Maximum Transmission Unit uint16_t mtu = 1500; // Maximun packet len when TCP/UDP offload is enabled uint16_t max_packet_len = ip_packet_len_max - eth_hdr_len; }; class forward_hash { uint8_t data[64]; size_t end_idx = 0; public: size_t size() const { return end_idx; } void push_back(uint8_t b) { ceph_assert(end_idx < sizeof(data)); data[end_idx++] = b; } void push_back(uint16_t b) { push_back(uint8_t(b)); push_back(uint8_t(b >> 8)); } void push_back(uint32_t b) { push_back(uint16_t(b)); push_back(uint16_t(b >> 16)); } const uint8_t& operator[](size_t idx) const { return data[idx]; } }; class interface; class l3_protocol { public: struct l3packet { eth_protocol_num proto_num; ethernet_address to; Packet p; }; using packet_provider_type = std::function<std::optional<l3packet> ()>; private: interface* _netif; eth_protocol_num _proto_num; public: explicit l3_protocol(interface* netif, eth_protocol_num proto_num, packet_provider_type func); subscription<Packet, ethernet_address> receive( std::function<int (Packet, ethernet_address)> rx_fn, std::function<bool (forward_hash &h, Packet &p, size_t s)> forward); private: friend class interface; }; class DPDKDevice; struct ipv4_address; class interface { CephContext *cct; struct l3_rx_stream { stream<Packet, ethernet_address> packet_stream; std::function<bool (forward_hash&, Packet&, size_t)> forward; bool ready() { return packet_stream.started(); } explicit l3_rx_stream(std::function<bool (forward_hash&, Packet&, size_t)>&& fw) : forward(fw) {} }; std::unordered_map<uint16_t, l3_rx_stream> _proto_map; std::shared_ptr<DPDKDevice> _dev; subscription<Packet> _rx; ethernet_address _hw_address; struct hw_features _hw_features; std::vector<l3_protocol::packet_provider_type> _pkt_providers; private: int dispatch_packet(EventCenter *c, Packet p); public: explicit interface(CephContext *cct, std::shared_ptr<DPDKDevice> dev, EventCenter *center); ethernet_address hw_address() { return _hw_address; } const struct hw_features& get_hw_features() const { return _hw_features; } subscription<Packet, ethernet_address> register_l3( eth_protocol_num proto_num, std::function<int (Packet, ethernet_address)> next, std::function<bool (forward_hash&, Packet&, size_t)> forward); void forward(EventCenter *source, unsigned target, Packet p); unsigned hash2cpu(uint32_t hash); void register_packet_provider(l3_protocol::packet_provider_type func) { _pkt_providers.push_back(std::move(func)); } const rss_key_type& rss_key() const; uint16_t hw_queues_count() const; void arp_learn(ethernet_address l2, ipv4_address l3); friend class l3_protocol; }; #endif //CEPH_MSG_DPDK_NET_H
4,196
29.194245
101
h
null
ceph-main/src/msg/async/dpdk/queue.h
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_MSG_DPDK_QUEUE_H_ #define CEPH_MSG_DPDK_QUEUE_H_ #include <queue> #include "circular_buffer.h" template <typename T> class queue { std::queue<T, circular_buffer<T>> _q; size_t _max; public: explicit queue(size_t size): _max(size) {} // Push an item. // // Returns false if the queue was full and the item was not pushed. bool push(T&& a); // pops an item. T pop(); // Consumes items from the queue, passing them to @func, until @func // returns false or the queue it empty // // Returns false if func returned false. template <typename Func> bool consume(Func&& func); // Returns true when the queue is empty. bool empty() const; // Returns true when the queue is full. bool full() const; size_t size() const { return _q.size(); } // Destroy any items in the queue void clear() { while (!_q.empty()) { _q.pop(); } } }; template <typename T> inline bool queue<T>::push(T&& data) { if (_q.size() < _max) { _q.push(std::move(data)); notify_not_empty(); return true; } else { return false; } } template <typename T> inline T queue<T>::pop() { T data = std::move(_q.front()); _q.pop(); return data; } template <typename T> inline bool queue<T>::empty() const { return _q.empty(); } template <typename T> inline bool queue<T>::full() const { return _q.size() == _max; } #endif /* CEPH_MSG_DPDK_QUEUE_H_ */
2,210
21.793814
79
h
null
ceph-main/src/msg/async/dpdk/shared_ptr.h
// -*- mode:C++; tab-width:8; c-basic-offset:4; indent-tabs-mode:nil -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_LW_SHARED_PTR_H_ #define CEPH_LW_SHARED_PTR_H_ #include <utility> #include <type_traits> #include <functional> #include <iostream> // This header defines a shared pointer facility, lw_shared_ptr<>, // modeled after std::shared_ptr<>. // // Unlike std::shared_ptr<>, this implementation is thread // safe, and two pointers sharing the same object must not be used in // different threads. // // lw_shared_ptr<> is the more lightweight variant, with a lw_shared_ptr<> // occupying just one machine word, and adding just one word to the shared // object. However, it does not support polymorphism. // // It supports shared_from_this() via enable_shared_from_this<> // and lw_enable_shared_from_this<>(). // template <typename T> class lw_shared_ptr; template <typename T> class enable_lw_shared_from_this; template <typename T> class enable_shared_from_this; template <typename T, typename... A> lw_shared_ptr<T> make_lw_shared(A&&... a); template <typename T> lw_shared_ptr<T> make_lw_shared(T&& a); template <typename T> lw_shared_ptr<T> make_lw_shared(T& a); struct lw_shared_ptr_counter_base { long _count = 0; }; namespace internal { template <class T, class U> struct lw_shared_ptr_accessors; template <class T> struct lw_shared_ptr_accessors_esft; template <class T> struct lw_shared_ptr_accessors_no_esft; } // We want to support two use cases for shared_ptr<T>: // // 1. T is any type (primitive or class type) // // 2. T is a class type that inherits from enable_shared_from_this<T>. // // In the first case, we must wrap T in an object containing the counter, // since T may be a primitive type and cannot be a base class. // // In the second case, we want T to reach the counter through its // enable_shared_from_this<> base class, so that we can implement // shared_from_this(). // // To implement those two conflicting requirements (T alongside its counter; // T inherits from an object containing the counter) we use std::conditional<> // and some accessor functions to select between two implementations. // CRTP from this to enable shared_from_this: template <typename T> class enable_lw_shared_from_this : private lw_shared_ptr_counter_base { using ctor = T; protected: enable_lw_shared_from_this() noexcept {} enable_lw_shared_from_this(enable_lw_shared_from_this&&) noexcept {} enable_lw_shared_from_this(const enable_lw_shared_from_this&) noexcept {} enable_lw_shared_from_this& operator=(const enable_lw_shared_from_this&) noexcept { return *this; } enable_lw_shared_from_this& operator=(enable_lw_shared_from_this&&) noexcept { return *this; } public: lw_shared_ptr<T> shared_from_this(); lw_shared_ptr<const T> shared_from_this() const; template <typename X> friend class lw_shared_ptr; template <typename X> friend class ::internal::lw_shared_ptr_accessors_esft; template <typename X, class Y> friend class ::internal::lw_shared_ptr_accessors; }; template <typename T> struct shared_ptr_no_esft : private lw_shared_ptr_counter_base { T _value; shared_ptr_no_esft() = default; shared_ptr_no_esft(const T& x) : _value(x) {} shared_ptr_no_esft(T&& x) : _value(std::move(x)) {} template <typename... A> shared_ptr_no_esft(A&&... a) : _value(std::forward<A>(a)...) {} template <typename X> friend class lw_shared_ptr; template <typename X> friend class ::internal::lw_shared_ptr_accessors_no_esft; template <typename X, class Y> friend class ::internal::lw_shared_ptr_accessors; }; /// Extension point: the user may override this to change how \ref lw_shared_ptr objects are destroyed, /// primarily so that incomplete classes can be used. /// /// Customizing the deleter requires that \c T be derived from \c enable_lw_shared_from_this<T>. /// The specialization must be visible for all uses of \c lw_shared_ptr<T>. /// /// To customize, the template must have a `static void dispose(T*)` operator that disposes of /// the object. template <typename T> struct lw_shared_ptr_deleter; // No generic implementation namespace internal { template <typename T> struct lw_shared_ptr_accessors_esft { using concrete_type = std::remove_const_t<T>; static T* to_value(lw_shared_ptr_counter_base* counter) { return static_cast<T*>(counter); } static void dispose(lw_shared_ptr_counter_base* counter) { delete static_cast<T*>(counter); } static void instantiate_to_value(lw_shared_ptr_counter_base* p) { // since to_value() is defined above, we don't need to do anything special // to force-instantiate it } }; template <typename T> struct lw_shared_ptr_accessors_no_esft { using concrete_type = shared_ptr_no_esft<T>; static T* to_value(lw_shared_ptr_counter_base* counter) { return &static_cast<concrete_type*>(counter)->_value; } static void dispose(lw_shared_ptr_counter_base* counter) { delete static_cast<concrete_type*>(counter); } static void instantiate_to_value(lw_shared_ptr_counter_base* p) { // since to_value() is defined above, we don't need to do anything special // to force-instantiate it } }; // Generic case: lw_shared_ptr_deleter<T> is not specialized, select // implementation based on whether T inherits from enable_lw_shared_from_this<T>. template <typename T, typename U = void> struct lw_shared_ptr_accessors : std::conditional_t< std::is_base_of<enable_lw_shared_from_this<T>, T>::value, lw_shared_ptr_accessors_esft<T>, lw_shared_ptr_accessors_no_esft<T>> { }; // Overload when lw_shared_ptr_deleter<T> specialized template <typename T> struct lw_shared_ptr_accessors<T, std::void_t<decltype(lw_shared_ptr_deleter<T>{})>> { using concrete_type = T; static T* to_value(lw_shared_ptr_counter_base* counter); static void dispose(lw_shared_ptr_counter_base* counter) { lw_shared_ptr_deleter<T>::dispose(to_value(counter)); } static void instantiate_to_value(lw_shared_ptr_counter_base* p) { // instantiate to_value(); must be defined by shared_ptr_incomplete.hh to_value(p); } }; } template <typename T> class lw_shared_ptr { using accessors = ::internal::lw_shared_ptr_accessors<std::remove_const_t<T>>; using concrete_type = typename accessors::concrete_type; mutable lw_shared_ptr_counter_base* _p = nullptr; private: lw_shared_ptr(lw_shared_ptr_counter_base* p) noexcept : _p(p) { if (_p) { ++_p->_count; } } template <typename... A> static lw_shared_ptr make(A&&... a) { auto p = new concrete_type(std::forward<A>(a)...); accessors::instantiate_to_value(p); return lw_shared_ptr(p); } public: using element_type = T; lw_shared_ptr() noexcept = default; lw_shared_ptr(std::nullptr_t) noexcept : lw_shared_ptr() {} lw_shared_ptr(const lw_shared_ptr& x) noexcept : _p(x._p) { if (_p) { ++_p->_count; } } lw_shared_ptr(lw_shared_ptr&& x) noexcept : _p(x._p) { x._p = nullptr; } [[gnu::always_inline]] ~lw_shared_ptr() { if (_p && !--_p->_count) { accessors::dispose(_p); } } lw_shared_ptr& operator=(const lw_shared_ptr& x) noexcept { if (_p != x._p) { this->~lw_shared_ptr(); new (this) lw_shared_ptr(x); } return *this; } lw_shared_ptr& operator=(lw_shared_ptr&& x) noexcept { if (_p != x._p) { this->~lw_shared_ptr(); new (this) lw_shared_ptr(std::move(x)); } return *this; } lw_shared_ptr& operator=(std::nullptr_t) noexcept { return *this = lw_shared_ptr(); } lw_shared_ptr& operator=(T&& x) noexcept { this->~lw_shared_ptr(); new (this) lw_shared_ptr(make_lw_shared<T>(std::move(x))); return *this; } T& operator*() const noexcept { return *accessors::to_value(_p); } T* operator->() const noexcept { return accessors::to_value(_p); } T* get() const noexcept { if (_p) { return accessors::to_value(_p); } else { return nullptr; } } long int use_count() const noexcept { if (_p) { return _p->_count; } else { return 0; } } operator lw_shared_ptr<const T>() const noexcept { return lw_shared_ptr<const T>(_p); } explicit operator bool() const noexcept { return _p; } bool owned() const noexcept { return _p->_count == 1; } bool operator==(const lw_shared_ptr<const T>& x) const { return _p == x._p; } bool operator!=(const lw_shared_ptr<const T>& x) const { return !operator==(x); } bool operator==(const lw_shared_ptr<std::remove_const_t<T>>& x) const { return _p == x._p; } bool operator!=(const lw_shared_ptr<std::remove_const_t<T>>& x) const { return !operator==(x); } bool operator<(const lw_shared_ptr<const T>& x) const { return _p < x._p; } bool operator<(const lw_shared_ptr<std::remove_const_t<T>>& x) const { return _p < x._p; } template <typename U> friend class lw_shared_ptr; template <typename X, typename... A> friend lw_shared_ptr<X> make_lw_shared(A&&...); template <typename U> friend lw_shared_ptr<U> make_lw_shared(U&&); template <typename U> friend lw_shared_ptr<U> make_lw_shared(U&); template <typename U> friend class enable_lw_shared_from_this; }; template <typename T, typename... A> inline lw_shared_ptr<T> make_lw_shared(A&&... a) { return lw_shared_ptr<T>::make(std::forward<A>(a)...); } template <typename T> inline lw_shared_ptr<T> make_lw_shared(T&& a) { return lw_shared_ptr<T>::make(std::move(a)); } template <typename T> inline lw_shared_ptr<T> make_lw_shared(T& a) { return lw_shared_ptr<T>::make(a); } template <typename T> inline lw_shared_ptr<T> enable_lw_shared_from_this<T>::shared_from_this() { return lw_shared_ptr<T>(this); } template <typename T> inline lw_shared_ptr<const T> enable_lw_shared_from_this<T>::shared_from_this() const { return lw_shared_ptr<const T>(const_cast<enable_lw_shared_from_this*>(this)); } template <typename T> static inline std::ostream& operator<<(std::ostream& out, const lw_shared_ptr<T>& p) { if (!p) { return out << "null"; } return out << *p; } namespace std { template <typename T> struct hash<lw_shared_ptr<T>> : private hash<T*> { size_t operator()(const lw_shared_ptr<T>& p) const { return hash<T*>::operator()(p.get()); } }; } #endif /* CEPH_LW_SHARED_PTR_H_ */
11,638
28.691327
103
h
null
ceph-main/src/msg/async/dpdk/stream.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_MSG_STREAM_H_ #define CEPH_MSG_STREAM_H_ #include <exception> #include <cassert> // A stream<> is the producer side. It may call produce() as long // as the returned from the previous invocation is ready. // To signify no more data is available, call close(). // // A subscription<> is the consumer side. It is created by a call // to stream::listen(). Calling subscription::start(), // which registers the data processing callback, starts processing // events. It may register for end-of-stream notifications by // return the when_done() future, which also delivers error // events (as exceptions). // // The consumer can pause generation of new data by returning // positive integer; when it becomes ready, the producer // will resume processing. template <typename... T> class subscription; template <typename... T> class stream { subscription<T...>* _sub = nullptr; int done; bool ready; public: using next_fn = std::function<int (T...)>; stream() = default; stream(const stream&) = delete; stream(stream&&) = delete; ~stream() { if (_sub) { _sub->_stream = nullptr; } } void operator=(const stream&) = delete; void operator=(stream&&) = delete; // Returns a subscription that reads value from this // stream. subscription<T...> listen() { return subscription<T...>(this); } // Returns a subscription that reads value from this // stream, and also sets up the listen function. subscription<T...> listen(next_fn next) { auto sub = subscription<T...>(this); sub.start(std::move(next)); return sub; } // Becomes ready when the listener is ready to accept // values. Call only once, when beginning to produce // values. bool started() { return ready; } // Produce a value. Call only after started(), and after // a previous produce() is ready. int produce(T... data) { return _sub->_next(std::move(data)...); } // End the stream. Call only after started(), and after // a previous produce() is ready. No functions may be called // after this. void close() { done = 1; } // Signal an error. Call only after started(), and after // a previous produce() is ready. No functions may be called // after this. void set_exception(int error) { done = error; } private: void start(); friend class subscription<T...>; }; template <typename... T> class subscription { public: using next_fn = typename stream<T...>::next_fn; private: stream<T...>* _stream; next_fn _next; private: explicit subscription(stream<T...>* s): _stream(s) { ceph_assert(!_stream->_sub); _stream->_sub = this; } public: subscription(subscription&& x) : _stream(x._stream), _next(std::move(x._next)) { x._stream = nullptr; if (_stream) { _stream->_sub = this; } } ~subscription() { if (_stream) { _stream->_sub = nullptr; } } /// \brief Start receiving events from the stream. /// /// \param next Callback to call for each event void start(std::function<int (T...)> next) { _next = std::move(next); _stream->ready = true; } // Becomes ready when the stream is empty, or when an error // happens (in that case, an exception is held). int done() { return _stream->done; } friend class stream<T...>; }; #endif /* CEPH_MSG_STREAM_H_ */
4,223
26.076923
79
h
null
ceph-main/src/msg/async/dpdk/toeplitz.h
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*- * Copyright (c) 2010 David Malone <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef CEPH_MSG_TOEPLITZ_H_ #define CEPH_MSG_TOEPLITZ_H_ #include <vector> using rss_key_type = std::vector<uint8_t>; // Mellanox Linux's driver key static const rss_key_type default_rsskey_40bytes = { 0xd1, 0x81, 0xc6, 0x2c, 0xf7, 0xf4, 0xdb, 0x5b, 0x19, 0x83, 0xa2, 0xfc, 0x94, 0x3e, 0x1a, 0xdb, 0xd9, 0x38, 0x9e, 0x6b, 0xd1, 0x03, 0x9c, 0x2c, 0xa7, 0x44, 0x99, 0xad, 0x59, 0x3d, 0x56, 0xd9, 0xf3, 0x25, 0x3c, 0x06, 0x2a, 0xdc, 0x1f, 0xfc }; // Intel's i40e PMD default RSS key static const rss_key_type default_rsskey_52bytes = { 0x44, 0x39, 0x79, 0x6b, 0xb5, 0x4c, 0x50, 0x23, 0xb6, 0x75, 0xea, 0x5b, 0x12, 0x4f, 0x9f, 0x30, 0xb8, 0xa2, 0xc0, 0x3d, 0xdf, 0xdc, 0x4d, 0x02, 0xa0, 0x8c, 0x9b, 0x33, 0x4a, 0xf6, 0x4a, 0x4c, 0x05, 0xc6, 0xfa, 0x34, 0x39, 0x58, 0xd8, 0x55, 0x7d, 0x99, 0x58, 0x3a, 0xe1, 0x38, 0xc9, 0x2e, 0x81, 0x15, 0x03, 0x66 }; template<typename T> static inline uint32_t toeplitz_hash(const rss_key_type& key, const T& data) { uint32_t hash = 0, v; u_int i, b; /* XXXRW: Perhaps an assertion about key length vs. data length? */ v = (key[0]<<24) + (key[1]<<16) + (key[2] <<8) + key[3]; for (i = 0; i < data.size(); i++) { for (b = 0; b < 8; b++) { if (data[i] & (1<<(7-b))) hash ^= v; v <<= 1; if ((i + 4) < key.size() && (key[i+4] & (1<<(7-b)))) v |= 1; } } return (hash); } #endif
3,507
36.72043
79
h
null
ceph-main/src/msg/async/dpdk/transfer.h
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CEPH_TRANSFER_H_ #define CEPH_TRANSFER_H_ // Helper functions for copying or moving multiple objects in an exception // safe manner, then destroying the sources. // // To transfer, call transfer_pass1(allocator, &from, &to) on all object pairs, // (this copies the object from @from to @to). If no exceptions are encountered, // call transfer_pass2(allocator, &from, &to). This destroys the object at the // origin. If exceptions were encountered, simply destroy all copied objects. // // As an optimization, if the objects are moveable without throwing (noexcept) // transfer_pass1() simply moves the objects and destroys the source, and // transfer_pass2() does nothing. #include <type_traits> #include <utility> template <typename T, typename Alloc> inline void transfer_pass1(Alloc& a, T* from, T* to, typename std::enable_if<std::is_nothrow_move_constructible<T>::value>::type* = nullptr) { a.construct(to, std::move(*from)); a.destroy(from); } template <typename T, typename Alloc> inline void transfer_pass2(Alloc& a, T* from, T* to, typename std::enable_if<std::is_nothrow_move_constructible<T>::value>::type* = nullptr) { } template <typename T, typename Alloc> inline void transfer_pass1(Alloc& a, T* from, T* to, typename std::enable_if<!std::is_nothrow_move_constructible<T>::value>::type* = nullptr) { a.construct(to, *from); } template <typename T, typename Alloc> inline void transfer_pass2(Alloc& a, T* from, T* to, typename std::enable_if<!std::is_nothrow_move_constructible<T>::value>::type* = nullptr) { a.destroy(from); } #endif /* CEPH_TRANSFER_H_ */
2,478
37.138462
116
h
null
ceph-main/src/msg/async/rdma/RDMAStack.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 XSKY <[email protected]> * * Author: Haomai Wang <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_MSG_RDMASTACK_H #define CEPH_MSG_RDMASTACK_H #include <sys/eventfd.h> #include <list> #include <vector> #include <thread> #include "common/ceph_context.h" #include "common/debug.h" #include "common/errno.h" #include "msg/async/Stack.h" #include "Infiniband.h" class RDMAConnectedSocketImpl; class RDMAServerSocketImpl; class RDMAStack; class RDMAWorker; class RDMADispatcher { typedef Infiniband::MemoryManager::Chunk Chunk; typedef Infiniband::QueuePair QueuePair; std::thread t; CephContext *cct; std::shared_ptr<Infiniband> ib; Infiniband::CompletionQueue* tx_cq = nullptr; Infiniband::CompletionQueue* rx_cq = nullptr; Infiniband::CompletionChannel *tx_cc = nullptr, *rx_cc = nullptr; bool done = false; std::atomic<uint64_t> num_qp_conn = {0}; // protect `qp_conns`, `dead_queue_pairs` ceph::mutex lock = ceph::make_mutex("RDMADispatcher::lock"); // qp_num -> InfRcConnection // The main usage of `qp_conns` is looking up connection by qp_num, // so the lifecycle of element in `qp_conns` is the lifecycle of qp. //// make qp queue into dead state /** * 1. Connection call mark_down * 2. Move the Queue Pair into the Error state(QueuePair::to_dead) * 3. Post a beacon * 4. Wait for beacon which indicates queues are drained * 5. Destroy the QP by calling ibv_destroy_qp() * * @param qp The qp needed to dead */ ceph::unordered_map<uint32_t, std::pair<QueuePair*, RDMAConnectedSocketImpl*> > qp_conns; /// if a queue pair is closed when transmit buffers are active /// on it, the transmit buffers never get returned via tx_cq. To /// work around this problem, don't delete queue pairs immediately. Instead, /// save them in this vector and delete them at a safe time, when there are /// no outstanding transmit buffers to be lost. std::vector<QueuePair*> dead_queue_pairs; std::atomic<uint64_t> num_pending_workers = {0}; // protect pending workers ceph::mutex w_lock = ceph::make_mutex("RDMADispatcher::for worker pending list"); // fixme: lockfree std::list<RDMAWorker*> pending_workers; void enqueue_dead_qp_lockless(uint32_t qp); void enqueue_dead_qp(uint32_t qpn); public: PerfCounters *perf_logger; explicit RDMADispatcher(CephContext* c, std::shared_ptr<Infiniband>& ib); virtual ~RDMADispatcher(); void handle_async_event(); void polling_start(); void polling_stop(); void polling(); void register_qp(QueuePair *qp, RDMAConnectedSocketImpl* csi); void make_pending_worker(RDMAWorker* w) { std::lock_guard l{w_lock}; auto it = std::find(pending_workers.begin(), pending_workers.end(), w); if (it != pending_workers.end()) return; pending_workers.push_back(w); ++num_pending_workers; } RDMAConnectedSocketImpl* get_conn_lockless(uint32_t qp); QueuePair* get_qp_lockless(uint32_t qp); QueuePair* get_qp(uint32_t qp); void schedule_qp_destroy(uint32_t qp); Infiniband::CompletionQueue* get_tx_cq() const { return tx_cq; } Infiniband::CompletionQueue* get_rx_cq() const { return rx_cq; } void notify_pending_workers(); void handle_tx_event(ibv_wc *cqe, int n); void post_tx_buffer(std::vector<Chunk*> &chunks); void handle_rx_event(ibv_wc *cqe, int rx_number); std::atomic<uint64_t> inflight = {0}; void post_chunk_to_pool(Chunk* chunk); int post_chunks_to_rq(int num, QueuePair *qp = nullptr); }; class RDMAWorker : public Worker { typedef Infiniband::CompletionQueue CompletionQueue; typedef Infiniband::CompletionChannel CompletionChannel; typedef Infiniband::MemoryManager::Chunk Chunk; typedef Infiniband::MemoryManager MemoryManager; typedef std::vector<Chunk*>::iterator ChunkIter; std::shared_ptr<Infiniband> ib; EventCallbackRef tx_handler; std::list<RDMAConnectedSocketImpl*> pending_sent_conns; std::shared_ptr<RDMADispatcher> dispatcher; ceph::mutex lock = ceph::make_mutex("RDMAWorker::lock"); class C_handle_cq_tx : public EventCallback { RDMAWorker *worker; public: explicit C_handle_cq_tx(RDMAWorker *w): worker(w) {} void do_request(uint64_t fd) { worker->handle_pending_message(); } }; public: PerfCounters *perf_logger; explicit RDMAWorker(CephContext *c, unsigned i); virtual ~RDMAWorker(); virtual int listen(entity_addr_t &addr, unsigned addr_slot, const SocketOptions &opts, ServerSocket *) override; virtual int connect(const entity_addr_t &addr, const SocketOptions &opts, ConnectedSocket *socket) override; virtual void initialize() override; int get_reged_mem(RDMAConnectedSocketImpl *o, std::vector<Chunk*> &c, size_t bytes); void remove_pending_conn(RDMAConnectedSocketImpl *o) { ceph_assert(center.in_thread()); pending_sent_conns.remove(o); } void handle_pending_message(); void set_dispatcher(std::shared_ptr<RDMADispatcher>& dispatcher) { this->dispatcher = dispatcher; } void set_ib(std::shared_ptr<Infiniband> &ib) {this->ib = ib;} void notify_worker() { center.dispatch_event_external(tx_handler); } }; struct RDMACMInfo { RDMACMInfo(rdma_cm_id *cid, rdma_event_channel *cm_channel_, uint32_t qp_num_) : cm_id(cid), cm_channel(cm_channel_), qp_num(qp_num_) {} rdma_cm_id *cm_id; rdma_event_channel *cm_channel; uint32_t qp_num; }; class RDMAConnectedSocketImpl : public ConnectedSocketImpl { public: typedef Infiniband::MemoryManager::Chunk Chunk; typedef Infiniband::CompletionChannel CompletionChannel; typedef Infiniband::CompletionQueue CompletionQueue; protected: CephContext *cct; Infiniband::QueuePair *qp; uint32_t peer_qpn = 0; uint32_t local_qpn = 0; int connected; int error; std::shared_ptr<Infiniband> ib; std::shared_ptr<RDMADispatcher> dispatcher; RDMAWorker* worker; std::vector<Chunk*> buffers; int notify_fd = -1; ceph::buffer::list pending_bl; ceph::mutex lock = ceph::make_mutex("RDMAConnectedSocketImpl::lock"); std::vector<ibv_wc> wc; bool is_server; EventCallbackRef read_handler; EventCallbackRef established_handler; int tcp_fd = -1; bool active;// qp is active ? bool pending; int post_backlog = 0; void notify(); void buffer_prefetch(void); ssize_t read_buffers(char* buf, size_t len); int post_work_request(std::vector<Chunk*>&); size_t tx_copy_chunk(std::vector<Chunk*> &tx_buffers, size_t req_copy_len, decltype(std::cbegin(pending_bl.buffers()))& start, const decltype(std::cbegin(pending_bl.buffers()))& end); public: RDMAConnectedSocketImpl(CephContext *cct, std::shared_ptr<Infiniband>& ib, std::shared_ptr<RDMADispatcher>& rdma_dispatcher, RDMAWorker *w); virtual ~RDMAConnectedSocketImpl(); void pass_wc(std::vector<ibv_wc> &&v); void get_wc(std::vector<ibv_wc> &w); virtual int is_connected() override { return connected; } virtual ssize_t read(char* buf, size_t len) override; virtual ssize_t send(ceph::buffer::list &bl, bool more) override; virtual void shutdown() override; virtual void close() override; virtual int fd() const override { return notify_fd; } virtual void set_priority(int sd, int prio, int domain) override; void fault(); const char* get_qp_state() { return Infiniband::qp_state_string(qp->get_state()); } uint32_t get_peer_qpn () const { return peer_qpn; } uint32_t get_local_qpn () const { return local_qpn; } Infiniband::QueuePair* get_qp () const { return qp; } ssize_t submit(bool more); int activate(); void fin(); void handle_connection(); int handle_connection_established(bool need_set_fault = true); void cleanup(); void set_accept_fd(int sd); virtual int try_connect(const entity_addr_t&, const SocketOptions &opt); bool is_pending() {return pending;} void set_pending(bool val) {pending = val;} void post_chunks_to_rq(int num); void update_post_backlog(); }; enum RDMA_CM_STATUS { IDLE = 1, RDMA_ID_CREATED, CHANNEL_FD_CREATED, RESOURCE_ALLOCATED, ADDR_RESOLVED, ROUTE_RESOLVED, CONNECTED, DISCONNECTED, ERROR }; class RDMAIWARPConnectedSocketImpl : public RDMAConnectedSocketImpl { public: RDMAIWARPConnectedSocketImpl(CephContext *cct, std::shared_ptr<Infiniband>& ib, std::shared_ptr<RDMADispatcher>& rdma_dispatcher, RDMAWorker *w, RDMACMInfo *info = nullptr); ~RDMAIWARPConnectedSocketImpl(); virtual int try_connect(const entity_addr_t&, const SocketOptions &opt) override; virtual void close() override; virtual void shutdown() override; virtual void handle_cm_connection(); void activate(); int alloc_resource(); void close_notify(); private: rdma_cm_id *cm_id = nullptr; rdma_event_channel *cm_channel = nullptr; EventCallbackRef cm_con_handler; std::mutex close_mtx; std::condition_variable close_condition; bool closed = false; RDMA_CM_STATUS status = IDLE; class C_handle_cm_connection : public EventCallback { RDMAIWARPConnectedSocketImpl *csi; public: C_handle_cm_connection(RDMAIWARPConnectedSocketImpl *w): csi(w) {} void do_request(uint64_t fd) { csi->handle_cm_connection(); } }; }; class RDMAServerSocketImpl : public ServerSocketImpl { protected: CephContext *cct; ceph::NetHandler net; int server_setup_socket; std::shared_ptr<Infiniband> ib; std::shared_ptr<RDMADispatcher> dispatcher; RDMAWorker *worker; entity_addr_t sa; public: RDMAServerSocketImpl(CephContext *cct, std::shared_ptr<Infiniband>& ib, std::shared_ptr<RDMADispatcher>& rdma_dispatcher, RDMAWorker *w, entity_addr_t& a, unsigned slot); virtual int listen(entity_addr_t &sa, const SocketOptions &opt); virtual int accept(ConnectedSocket *s, const SocketOptions &opts, entity_addr_t *out, Worker *w) override; virtual void abort_accept() override; virtual int fd() const override { return server_setup_socket; } }; class RDMAIWARPServerSocketImpl : public RDMAServerSocketImpl { public: RDMAIWARPServerSocketImpl( CephContext *cct, std::shared_ptr<Infiniband>& ib, std::shared_ptr<RDMADispatcher>& rdma_dispatcher, RDMAWorker* w, entity_addr_t& addr, unsigned addr_slot); virtual int listen(entity_addr_t &sa, const SocketOptions &opt) override; virtual int accept(ConnectedSocket *s, const SocketOptions &opts, entity_addr_t *out, Worker *w) override; virtual void abort_accept() override; private: rdma_cm_id *cm_id = nullptr; rdma_event_channel *cm_channel = nullptr; }; class RDMAStack : public NetworkStack { std::vector<std::thread> threads; PerfCounters *perf_counter; std::shared_ptr<Infiniband> ib; std::shared_ptr<RDMADispatcher> rdma_dispatcher; std::atomic<bool> fork_finished = {false}; virtual Worker* create_worker(CephContext *c, unsigned worker_id) override; public: explicit RDMAStack(CephContext *cct); virtual ~RDMAStack(); virtual bool nonblock_connect_need_writable_event() const override { return false; } virtual void spawn_worker(std::function<void ()> &&func) override; virtual void join_worker(unsigned i) override; virtual bool is_ready() override { return fork_finished.load(); }; virtual void ready() override { fork_finished = true; }; }; #endif
11,697
32.907246
110
h
null
ceph-main/src/neorados/RADOSImpl.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-2012 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_NEORADOS_RADOSIMPL_H #define CEPH_NEORADOS_RADOSIMPL_H #include <functional> #include <memory> #include <string> #include <boost/asio.hpp> #include <boost/intrusive_ptr.hpp> #include "common/ceph_context.h" #include "common/ceph_mutex.h" #include "librados/RadosClient.h" #include "mon/MonClient.h" #include "mgr/MgrClient.h" #include "osdc/Objecter.h" namespace neorados { class RADOS; namespace detail { class NeoClient; class RADOS : public Dispatcher { friend ::neorados::RADOS; friend NeoClient; boost::asio::io_context& ioctx; boost::intrusive_ptr<CephContext> cct; ceph::mutex lock = ceph::make_mutex("RADOS_unleashed::_::RADOSImpl"); int instance_id = -1; std::unique_ptr<Messenger> messenger; MonClient monclient; MgrClient mgrclient; std::unique_ptr<Objecter> objecter; public: RADOS(boost::asio::io_context& ioctx, boost::intrusive_ptr<CephContext> cct); ~RADOS(); bool ms_dispatch(Message *m) override; void ms_handle_connect(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; mon_feature_t get_required_monitor_features() const { return monclient.with_monmap(std::mem_fn(&MonMap::get_required_features)); } }; class Client { public: Client(boost::asio::io_context& ioctx, boost::intrusive_ptr<CephContext> cct, MonClient& monclient, Objecter* objecter) : ioctx(ioctx), cct(cct), monclient(monclient), objecter(objecter) { } virtual ~Client() {} Client(const Client&) = delete; Client& operator=(const Client&) = delete; boost::asio::io_context& ioctx; boost::intrusive_ptr<CephContext> cct; MonClient& monclient; Objecter* objecter; mon_feature_t get_required_monitor_features() const { return monclient.with_monmap(std::mem_fn(&MonMap::get_required_features)); } virtual int get_instance_id() const = 0; }; class NeoClient : public Client { public: NeoClient(std::unique_ptr<RADOS>&& rados) : Client(rados->ioctx, rados->cct, rados->monclient, rados->objecter.get()), rados(std::move(rados)) { } int get_instance_id() const override { return rados->instance_id; } private: std::unique_ptr<RADOS> rados; }; class RadosClient : public Client { public: RadosClient(librados::RadosClient* rados_client) : Client(rados_client->poolctx, {rados_client->cct}, rados_client->monclient, rados_client->objecter), rados_client(rados_client) { } int get_instance_id() const override { return rados_client->instance_id; } public: librados::RadosClient* rados_client; }; } // namespace detail } // namespace neorados #endif
3,189
22.455882
79
h
null
ceph-main/src/objclass/objclass.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_OBJCLASS_H #define CEPH_OBJCLASS_H #ifdef __cplusplus #include "../include/types.h" #include "msg/msg_types.h" #include "common/hobject.h" #include "common/ceph_time.h" #include "common/ceph_releases.h" #include "include/rados/objclass.h" struct obj_list_watch_response_t; class PGLSFilter; class object_info_t; extern "C" { #endif #define CLS_METHOD_PUBLIC 0x4 /// unused typedef void *cls_filter_handle_t; typedef int (*cls_method_call_t)(cls_method_context_t ctx, char *indata, int datalen, char **outdata, int *outdatalen); typedef struct { const char *name; const char *ver; } cls_deps_t; /* class utils */ extern void *cls_alloc(size_t size); extern void cls_free(void *p); extern int cls_read(cls_method_context_t hctx, int ofs, int len, char **outdata, int *outdatalen); extern int cls_call(cls_method_context_t hctx, const char *cls, const char *method, char *indata, int datalen, char **outdata, int *outdatalen); extern int cls_getxattr(cls_method_context_t hctx, const char *name, char **outdata, int *outdatalen); extern int cls_setxattr(cls_method_context_t hctx, const char *name, const char *value, int val_len); /** This will fill in the passed origin pointer with the origin of the * request which activated your class call. */ extern int cls_get_request_origin(cls_method_context_t hctx, entity_inst_t *origin); /* class registration api */ extern int cls_unregister(cls_handle_t); extern int cls_register_method(cls_handle_t hclass, const char *method, int flags, cls_method_call_t class_call, cls_method_handle_t *handle); extern int cls_unregister_method(cls_method_handle_t handle); extern void cls_unregister_filter(cls_filter_handle_t handle); /* triggers */ #define OBJ_READ 0x1 #define OBJ_WRITE 0x2 typedef int cls_trigger_t; extern int cls_link(cls_method_handle_t handle, int priority, cls_trigger_t trigger); extern int cls_unlink(cls_method_handle_t handle); /* should be defined by the class implementation defined here inorder to get it compiled without C++ mangling */ extern void class_init(void); extern void class_fini(void); #ifdef __cplusplus } // Classes expose a filter constructor that returns a subclass of PGLSFilter typedef PGLSFilter* (*cls_cxx_filter_factory_t)(); extern int cls_register_cxx_filter(cls_handle_t hclass, const std::string &filter_name, cls_cxx_filter_factory_t fn, cls_filter_handle_t *handle=NULL); extern int cls_cxx_stat2(cls_method_context_t hctx, uint64_t *size, ceph::real_time *mtime); extern int cls_cxx_read2(cls_method_context_t hctx, int ofs, int len, ceph::buffer::list *bl, uint32_t op_flags); extern int cls_cxx_write2(cls_method_context_t hctx, int ofs, int len, ceph::buffer::list *bl, uint32_t op_flags); extern int cls_cxx_write_full(cls_method_context_t hctx, ceph::buffer::list *bl); extern int cls_cxx_getxattrs(cls_method_context_t hctx, std::map<std::string, ceph::buffer::list> *attrset); extern int cls_cxx_replace(cls_method_context_t hctx, int ofs, int len, ceph::buffer::list *bl); extern int cls_cxx_truncate(cls_method_context_t hctx, int ofs); extern int cls_cxx_write_zero(cls_method_context_t hctx, int ofs, int len); extern int cls_cxx_snap_revert(cls_method_context_t hctx, snapid_t snapid); extern int cls_cxx_map_clear(cls_method_context_t hctx); extern int cls_cxx_map_get_all_vals(cls_method_context_t hctx, std::map<std::string, ceph::buffer::list> *vals, bool *more); extern int cls_cxx_map_get_keys(cls_method_context_t hctx, const std::string &start_after, uint64_t max_to_get, std::set<std::string> *keys, bool *more); extern int cls_cxx_map_get_vals(cls_method_context_t hctx, const std::string& start_after, const std::string& filter_prefix, uint64_t max_to_get, std::map<std::string, ceph::buffer::list> *vals, bool *more); extern int cls_cxx_map_get_val(cls_method_context_t hctx, const std::string &key, bufferlist *outbl); extern int cls_cxx_map_get_vals_by_keys(cls_method_context_t hctx, const std::set<std::string> &keys, std::map<std::string, bufferlist> *map); extern int cls_cxx_map_read_header(cls_method_context_t hctx, ceph::buffer::list *outbl); extern int cls_cxx_map_set_vals(cls_method_context_t hctx, const std::map<std::string, ceph::buffer::list> *map); extern int cls_cxx_map_write_header(cls_method_context_t hctx, ceph::buffer::list *inbl); extern int cls_cxx_map_remove_key(cls_method_context_t hctx, const std::string &key); /* remove keys in the range [key_begin, key_end) */ extern int cls_cxx_map_remove_range(cls_method_context_t hctx, const std::string& key_begin, const std::string& key_end); extern int cls_cxx_map_update(cls_method_context_t hctx, ceph::buffer::list *inbl); extern int cls_cxx_list_watchers(cls_method_context_t hctx, obj_list_watch_response_t *watchers); /* utility functions */ extern int cls_gen_random_bytes(char *buf, int size); extern int cls_gen_rand_base64(char *dest, int size); /* size should be the required string size + 1 */ /* environment */ extern uint64_t cls_current_version(cls_method_context_t hctx); extern int cls_current_subop_num(cls_method_context_t hctx); extern uint64_t cls_get_features(cls_method_context_t hctx); extern uint64_t cls_get_client_features(cls_method_context_t hctx); extern ceph_release_t cls_get_required_osd_release(cls_method_context_t hctx); extern ceph_release_t cls_get_min_compatible_client(cls_method_context_t hctx); extern const ConfigProxy& cls_get_config(cls_method_context_t hctx); extern const object_info_t& cls_get_object_info(cls_method_context_t hctx); /* helpers */ extern void cls_cxx_subop_version(cls_method_context_t hctx, std::string *s); extern int cls_get_snapset_seq(cls_method_context_t hctx, uint64_t *snap_seq); /* gather */ extern int cls_cxx_gather(cls_method_context_t hctx, const std::set<std::string> &src_objs, const std::string& pool, const char *cls, const char *method, bufferlist& inbl); extern int cls_cxx_get_gathered_data(cls_method_context_t hctx, std::map<std::string, bufferlist> *results); /* These are also defined in rados.h and librados.h. Keep them in sync! */ #define CEPH_OSD_TMAP_HDR 'h' #define CEPH_OSD_TMAP_SET 's' #define CEPH_OSD_TMAP_CREATE 'c' #define CEPH_OSD_TMAP_RM 'r' int cls_cxx_chunk_write_and_set(cls_method_context_t hctx, int ofs, int len, ceph::buffer::list *write_inbl, uint32_t op_flags, ceph::buffer::list *set_inbl, int set_len); int cls_get_manifest_ref_count(cls_method_context_t hctx, std::string fp_oid); extern uint64_t cls_get_osd_min_alloc_size(cls_method_context_t hctx); extern uint64_t cls_get_pool_stripe_width(cls_method_context_t hctx); #endif #endif
7,686
42.429379
116
h
null
ceph-main/src/os/DBObjectMap.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- #ifndef DBOBJECTMAP_DB_H #define DBOBJECTMAP_DB_H #include "include/buffer_fwd.h" #include <set> #include <map> #include <string> #include <vector> #include <boost/scoped_ptr.hpp> #include "os/ObjectMap.h" #include "kv/KeyValueDB.h" #include "osd/osd_types.h" #include "common/ceph_mutex.h" #include "common/simple_cache.hpp" #include <boost/optional/optional_io.hpp> #include "SequencerPosition.h" /** * DBObjectMap: Implements ObjectMap in terms of KeyValueDB * * Prefix space structure: * * @see complete_prefix * @see user_prefix * @see sys_prefix * * - HOBJECT_TO_SEQ: Contains leaf mapping from ghobject_t->header.seq and * corresponding omap header * - SYS_PREFIX: GLOBAL_STATE_KEY - contains next seq number * @see State * @see write_state * @see init * @see generate_new_header * - USER_PREFIX + header_key(header->seq) + USER_PREFIX * : key->value for header->seq * - USER_PREFIX + header_key(header->seq) + COMPLETE_PREFIX: see below * - USER_PREFIX + header_key(header->seq) + XATTR_PREFIX: xattrs * - USER_PREFIX + header_key(header->seq) + SYS_PREFIX * : USER_HEADER_KEY - omap header for header->seq * : HEADER_KEY - encoding of header for header->seq * * For each node (represented by a header), we * store three mappings: the key mapping, the complete mapping, and the parent. * The complete mapping (COMPLETE_PREFIX space) is key->key. Each x->y entry in * this mapping indicates that the key mapping contains all entries on [x,y). * Note, max std::string is represented by "", so ""->"" indicates that the parent * is unnecessary (@see rm_keys). When looking up a key not contained in the * the complete std::set, we have to check the parent if we don't find it in the * key std::set. During rm_keys, we copy keys from the parent and update the * complete std::set to reflect the change @see rm_keys. */ class DBObjectMap : public ObjectMap { public: KeyValueDB *get_db() override { return db.get(); } /** * Serializes access to next_seq as well as the in_use std::set */ ceph::mutex header_lock = ceph::make_mutex("DBOBjectMap"); ceph::condition_variable header_cond; ceph::condition_variable map_header_cond; /** * Std::Set of headers currently in use */ std::set<uint64_t> in_use; std::set<ghobject_t> map_header_in_use; /** * Takes the map_header_in_use entry in constructor, releases in * destructor */ class MapHeaderLock { DBObjectMap *db; boost::optional<ghobject_t> locked; MapHeaderLock(const MapHeaderLock &); MapHeaderLock &operator=(const MapHeaderLock &); public: explicit MapHeaderLock(DBObjectMap *db) : db(db) {} MapHeaderLock(DBObjectMap *db, const ghobject_t &oid) : db(db), locked(oid) { std::unique_lock l{db->header_lock}; db->map_header_cond.wait(l, [db, this] { return !db->map_header_in_use.count(*locked); }); db->map_header_in_use.insert(*locked); } const ghobject_t &get_locked() const { ceph_assert(locked); return *locked; } void swap(MapHeaderLock &o) { ceph_assert(db == o.db); // centos6's boost optional doesn't seem to have swap :( boost::optional<ghobject_t> _locked = o.locked; o.locked = locked; locked = _locked; } ~MapHeaderLock() { if (locked) { std::lock_guard l{db->header_lock}; ceph_assert(db->map_header_in_use.count(*locked)); db->map_header_cond.notify_all(); db->map_header_in_use.erase(*locked); } } }; DBObjectMap(CephContext* cct, KeyValueDB *db) : ObjectMap(cct, db), caches(cct->_conf->filestore_omap_header_cache_size) {} int set_keys( const ghobject_t &oid, const std::map<std::string, ceph::buffer::list> &set, const SequencerPosition *spos=0 ) override; int set_header( const ghobject_t &oid, const ceph::buffer::list &bl, const SequencerPosition *spos=0 ) override; int get_header( const ghobject_t &oid, ceph::buffer::list *bl ) override; int clear( const ghobject_t &oid, const SequencerPosition *spos=0 ) override; int clear_keys_header( const ghobject_t &oid, const SequencerPosition *spos=0 ) override; int rm_keys( const ghobject_t &oid, const std::set<std::string> &to_clear, const SequencerPosition *spos=0 ) override; int get( const ghobject_t &oid, ceph::buffer::list *header, std::map<std::string, ceph::buffer::list> *out ) override; int get_keys( const ghobject_t &oid, std::set<std::string> *keys ) override; int get_values( const ghobject_t &oid, const std::set<std::string> &keys, std::map<std::string, ceph::buffer::list> *out ) override; int check_keys( const ghobject_t &oid, const std::set<std::string> &keys, std::set<std::string> *out ) override; int get_xattrs( const ghobject_t &oid, const std::set<std::string> &to_get, std::map<std::string, ceph::buffer::list> *out ) override; int get_all_xattrs( const ghobject_t &oid, std::set<std::string> *out ) override; int set_xattrs( const ghobject_t &oid, const std::map<std::string, ceph::buffer::list> &to_set, const SequencerPosition *spos=0 ) override; int remove_xattrs( const ghobject_t &oid, const std::set<std::string> &to_remove, const SequencerPosition *spos=0 ) override; int clone( const ghobject_t &oid, const ghobject_t &target, const SequencerPosition *spos=0 ) override; int rename( const ghobject_t &from, const ghobject_t &to, const SequencerPosition *spos=0 ) override; int legacy_clone( const ghobject_t &oid, const ghobject_t &target, const SequencerPosition *spos=0 ) override; /// Read initial state from backing store int get_state(); /// Write current state settings to DB void set_state(); /// Read initial state and upgrade or initialize state int init(bool upgrade = false); /// Upgrade store to current version int upgrade_to_v2(); /// Consistency check, debug, there must be no parallel writes int check(std::ostream &out, bool repair = false, bool force = false) override; /// Ensure that all previous operations are durable int sync(const ghobject_t *oid=0, const SequencerPosition *spos=0) override; void compact() override { ceph_assert(db); db->compact(); } /// Util, get all objects, there must be no other concurrent access int list_objects(std::vector<ghobject_t> *objs ///< [out] objects ); struct _Header; // Util, get all object headers, there must be no other concurrent access int list_object_headers(std::vector<_Header> *out ///< [out] headers ); ObjectMapIterator get_iterator(const ghobject_t &oid) override; static const std::string USER_PREFIX; static const std::string XATTR_PREFIX; static const std::string SYS_PREFIX; static const std::string COMPLETE_PREFIX; static const std::string HEADER_KEY; static const std::string USER_HEADER_KEY; static const std::string GLOBAL_STATE_KEY; static const std::string HOBJECT_TO_SEQ; /// Legacy static const std::string LEAF_PREFIX; static const std::string REVERSE_LEAF_PREFIX; /// persistent state for store @see generate_header struct State { static const __u8 CUR_VERSION = 3; __u8 v; uint64_t seq; // legacy is false when complete regions never used bool legacy; State() : v(0), seq(1), legacy(false) {} explicit State(uint64_t seq) : v(0), seq(seq), legacy(false) {} void encode(ceph::buffer::list &bl) const { ENCODE_START(3, 1, bl); encode(v, bl); encode(seq, bl); encode(legacy, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { DECODE_START(3, bl); if (struct_v >= 2) decode(v, bl); else v = 0; decode(seq, bl); if (struct_v >= 3) decode(legacy, bl); else legacy = false; DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const { f->dump_unsigned("v", v); f->dump_unsigned("seq", seq); f->dump_bool("legacy", legacy); } static void generate_test_instances(std::list<State*> &o) { o.push_back(new State(0)); o.push_back(new State(20)); } } state; struct _Header { uint64_t seq; uint64_t parent; uint64_t num_children; ghobject_t oid; SequencerPosition spos; void encode(ceph::buffer::list &bl) const { coll_t unused; ENCODE_START(2, 1, bl); encode(seq, bl); encode(parent, bl); encode(num_children, bl); encode(unused, bl); encode(oid, bl); encode(spos, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator &bl) { coll_t unused; DECODE_START(2, bl); decode(seq, bl); decode(parent, bl); decode(num_children, bl); decode(unused, bl); decode(oid, bl); if (struct_v >= 2) decode(spos, bl); DECODE_FINISH(bl); } void dump(ceph::Formatter *f) const { f->dump_unsigned("seq", seq); f->dump_unsigned("parent", parent); f->dump_unsigned("num_children", num_children); f->dump_stream("oid") << oid; } static void generate_test_instances(std::list<_Header*> &o) { o.push_back(new _Header); o.push_back(new _Header); o.back()->parent = 20; o.back()->seq = 30; } size_t length() { return sizeof(_Header); } _Header() : seq(0), parent(0), num_children(1) {} }; /// Std::String munging (public for testing) static std::string ghobject_key(const ghobject_t &oid); static std::string ghobject_key_v0(coll_t c, const ghobject_t &oid); static int is_buggy_ghobject_key_v1(CephContext* cct, const std::string &in); private: /// Implicit lock on Header->seq typedef std::shared_ptr<_Header> Header; ceph::mutex cache_lock = ceph::make_mutex("DBObjectMap::CacheLock"); SimpleLRU<ghobject_t, _Header> caches; std::string map_header_key(const ghobject_t &oid); std::string header_key(uint64_t seq); std::string complete_prefix(Header header); std::string user_prefix(Header header); std::string sys_prefix(Header header); std::string xattr_prefix(Header header); std::string sys_parent_prefix(_Header header); std::string sys_parent_prefix(Header header) { return sys_parent_prefix(*header); } class EmptyIteratorImpl : public ObjectMapIteratorImpl { public: int seek_to_first() override { return 0; } int seek_to_last() { return 0; } int upper_bound(const std::string &after) override { return 0; } int lower_bound(const std::string &to) override { return 0; } bool valid() override { return false; } int next() override { ceph_abort(); return 0; } std::string key() override { ceph_abort(); return ""; } ceph::buffer::list value() override { ceph_abort(); return ceph::buffer::list(); } int status() override { return 0; } }; /// Iterator class DBObjectMapIteratorImpl : public ObjectMapIteratorImpl { public: DBObjectMap *map; /// NOTE: implicit lock hlock->get_locked() when returned out of the class MapHeaderLock hlock; /// NOTE: implicit lock on header->seq AND for all ancestors Header header; /// parent_iter == NULL iff no parent std::shared_ptr<DBObjectMapIteratorImpl> parent_iter; KeyValueDB::Iterator key_iter; KeyValueDB::Iterator complete_iter; /// cur_iter points to currently valid iterator std::shared_ptr<ObjectMapIteratorImpl> cur_iter; int r; /// init() called, key_iter, complete_iter, parent_iter filled in bool ready; /// past end bool invalid; DBObjectMapIteratorImpl(DBObjectMap *map, Header header) : map(map), hlock(map), header(header), r(0), ready(false), invalid(true) {} int seek_to_first() override; int seek_to_last(); int upper_bound(const std::string &after) override; int lower_bound(const std::string &to) override; bool valid() override; int next() override; std::string key() override; ceph::buffer::list value() override; int status() override; bool on_parent() { return cur_iter == parent_iter; } /// skips to next valid parent entry int next_parent(); /// first parent() >= to int lower_bound_parent(const std::string &to); /** * Tests whether to_test is in complete region * * postcondition: complete_iter will be max s.t. complete_iter->value > to_test */ int in_complete_region(const std::string &to_test, ///< [in] key to test std::string *begin, ///< [out] beginning of region std::string *end ///< [out] end of region ); ///< @returns true if to_test is in the complete region, else false private: int init(); bool valid_parent(); int adjust(); }; typedef std::shared_ptr<DBObjectMapIteratorImpl> DBObjectMapIterator; DBObjectMapIterator _get_iterator(Header header) { return std::make_shared<DBObjectMapIteratorImpl>(this, header); } /// sys /// Removes node corresponding to header void clear_header(Header header, KeyValueDB::Transaction t); /// Std::Set node containing input to new contents void set_header(Header input, KeyValueDB::Transaction t); /// Remove leaf node corresponding to oid in c void remove_map_header( const MapHeaderLock &l, const ghobject_t &oid, Header header, KeyValueDB::Transaction t); /// Std::Set leaf node for c and oid to the value of header void set_map_header( const MapHeaderLock &l, const ghobject_t &oid, _Header header, KeyValueDB::Transaction t); /// Std::Set leaf node for c and oid to the value of header bool check_spos(const ghobject_t &oid, Header header, const SequencerPosition *spos); /// Lookup or create header for c oid Header lookup_create_map_header( const MapHeaderLock &l, const ghobject_t &oid, KeyValueDB::Transaction t); /** * Generate new header for c oid with new seq number * * Has the side effect of synchronously saving the new DBObjectMap state */ Header _generate_new_header(const ghobject_t &oid, Header parent); Header generate_new_header(const ghobject_t &oid, Header parent) { std::lock_guard l{header_lock}; return _generate_new_header(oid, parent); } /// Lookup leaf header for c oid Header _lookup_map_header( const MapHeaderLock &l, const ghobject_t &oid); Header lookup_map_header( const MapHeaderLock &l2, const ghobject_t &oid) { std::lock_guard l{header_lock}; return _lookup_map_header(l2, oid); } /// Lookup header node for input Header lookup_parent(Header input); /// Helpers int _get_header(Header header, ceph::buffer::list *bl); /// Scan keys in header into out_keys and out_values (if nonnull) int scan(Header header, const std::set<std::string> &in_keys, std::set<std::string> *out_keys, std::map<std::string, ceph::buffer::list> *out_values); /// Remove header and all related prefixes int _clear(Header header, KeyValueDB::Transaction t); /* Scan complete region bumping *begin to the beginning of any * containing region and adding all complete region keys between * the updated begin and end to the complete_keys_to_remove std::set */ int merge_new_complete(DBObjectMapIterator &iter, std::string *begin, const std::string &end, std::set<std::string> *complete_keys_to_remove); /// Writes out State (mainly next_seq) int write_state(KeyValueDB::Transaction _t = KeyValueDB::Transaction()); /// Copies header entry from parent @see rm_keys int copy_up_header(Header header, KeyValueDB::Transaction t); /// Sets header @see set_header void _set_header(Header header, const ceph::buffer::list &bl, KeyValueDB::Transaction t); /** * Removes header seq lock and possibly object lock * once Header is out of scope * @see lookup_parent * @see generate_new_header */ class RemoveOnDelete { public: DBObjectMap *db; explicit RemoveOnDelete(DBObjectMap *db) : db(db) {} void operator() (_Header *header) { std::lock_guard l{db->header_lock}; ceph_assert(db->in_use.count(header->seq)); db->in_use.erase(header->seq); db->header_cond.notify_all(); delete header; } }; friend class RemoveOnDelete; }; WRITE_CLASS_ENCODER(DBObjectMap::_Header) WRITE_CLASS_ENCODER(DBObjectMap::State) std::ostream& operator<<(std::ostream& out, const DBObjectMap::_Header& h); #endif
16,954
27.982906
86
h
null
ceph-main/src/os/ObjectMap.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 OS_KEYVALUESTORE_H #define OS_KEYVALUESTORE_H #include <memory> #include <string> #include <vector> #include "kv/KeyValueDB.h" #include "common/hobject.h" class SequencerPosition; /** * Encapsulates the FileStore key value store * * Implementations of this interface will be used to implement TMAP */ class ObjectMap { public: CephContext* cct; boost::scoped_ptr<KeyValueDB> db; /// std::Set keys and values from specified map virtual int set_keys( const ghobject_t &oid, ///< [in] object containing map const std::map<std::string, ceph::buffer::list> &set, ///< [in] key to value map to set const SequencerPosition *spos=0 ///< [in] sequencer position ) = 0; /// std::Set header virtual int set_header( const ghobject_t &oid, ///< [in] object containing map const ceph::buffer::list &bl, ///< [in] header to set const SequencerPosition *spos=0 ///< [in] sequencer position ) = 0; /// Retrieve header virtual int get_header( const ghobject_t &oid, ///< [in] object containing map ceph::buffer::list *bl ///< [out] header to set ) = 0; /// Clear all map keys and values from oid virtual int clear( const ghobject_t &oid, ///< [in] object containing map const SequencerPosition *spos=0 ///< [in] sequencer position ) = 0; /// Clear all map keys and values in to_clear from oid virtual int rm_keys( const ghobject_t &oid, ///< [in] object containing map const std::set<std::string> &to_clear, ///< [in] Keys to clear const SequencerPosition *spos=0 ///< [in] sequencer position ) = 0; /// Clear all omap keys and the header virtual int clear_keys_header( const ghobject_t &oid, ///< [in] oid to clear const SequencerPosition *spos=0 ///< [in] sequencer position ) = 0; /// Get all keys and values virtual int get( const ghobject_t &oid, ///< [in] object containing map ceph::buffer::list *header, ///< [out] Returned Header std::map<std::string, ceph::buffer::list> *out ///< [out] Returned keys and values ) = 0; /// Get values for supplied keys virtual int get_keys( const ghobject_t &oid, ///< [in] object containing map std::set<std::string> *keys ///< [out] Keys defined on oid ) = 0; /// Get values for supplied keys virtual int get_values( const ghobject_t &oid, ///< [in] object containing map const std::set<std::string> &keys, ///< [in] Keys to get std::map<std::string, ceph::buffer::list> *out ///< [out] Returned keys and values ) = 0; /// Check key existence virtual int check_keys( const ghobject_t &oid, ///< [in] object containing map const std::set<std::string> &keys, ///< [in] Keys to check std::set<std::string> *out ///< [out] Subset of keys defined on oid ) = 0; /// Get xattrs virtual int get_xattrs( const ghobject_t &oid, ///< [in] object const std::set<std::string> &to_get, ///< [in] keys to get std::map<std::string, ceph::buffer::list> *out ///< [out] subset of attrs/vals defined ) = 0; /// Get all xattrs virtual int get_all_xattrs( const ghobject_t &oid, ///< [in] object std::set<std::string> *out ///< [out] attrs and values ) = 0; /// std::set xattrs in to_set virtual int set_xattrs( const ghobject_t &oid, ///< [in] object const std::map<std::string, ceph::buffer::list> &to_set,///< [in] attrs/values to set const SequencerPosition *spos=0 ///< [in] sequencer position ) = 0; /// remove xattrs in to_remove virtual int remove_xattrs( const ghobject_t &oid, ///< [in] object const std::set<std::string> &to_remove, ///< [in] attrs to remove const SequencerPosition *spos=0 ///< [in] sequencer position ) = 0; /// Clone keys from oid map to target map virtual int clone( const ghobject_t &oid, ///< [in] object containing map const ghobject_t &target, ///< [in] target of clone const SequencerPosition *spos=0 ///< [in] sequencer position ) { return 0; } /// Rename map because of name change virtual int rename( const ghobject_t &from, ///< [in] object containing map const ghobject_t &to, ///< [in] new name const SequencerPosition *spos=0 ///< [in] sequencer position ) { return 0; } /// For testing clone keys from oid map to target map using faster but more complex method virtual int legacy_clone( const ghobject_t &oid, ///< [in] object containing map const ghobject_t &target, ///< [in] target of clone const SequencerPosition *spos=0 ///< [in] sequencer position ) { return 0; } /// Ensure all previous writes are durable virtual int sync( const ghobject_t *oid=0, ///< [in] object const SequencerPosition *spos=0 ///< [in] Sequencer ) { return 0; } virtual int check(std::ostream &out, bool repair = false, bool force = false) { return 0; } virtual void compact() {} typedef KeyValueDB::SimplestIteratorImpl ObjectMapIteratorImpl; typedef std::shared_ptr<ObjectMapIteratorImpl> ObjectMapIterator; virtual ObjectMapIterator get_iterator(const ghobject_t &oid) { return ObjectMapIterator(); } virtual KeyValueDB *get_db() { return nullptr; } ObjectMap(CephContext* cct, KeyValueDB *db) : cct(cct), db(db) {} virtual ~ObjectMap() {} }; #endif
6,174
34.693642
96
h
null
ceph-main/src/os/SequencerPosition.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef __CEPH_OS_SEQUENCERPOSITION_H #define __CEPH_OS_SEQUENCERPOSITION_H #include "include/types.h" #include "include/encoding.h" #include "common/Formatter.h" #include <ostream> /** * transaction and op offset */ struct SequencerPosition { uint64_t seq; ///< seq uint32_t trans; ///< transaction in that seq (0-based) uint32_t op; ///< op in that transaction (0-based) SequencerPosition(uint64_t s=0, int32_t t=0, int32_t o=0) : seq(s), trans(t), op(o) {} auto operator<=>(const SequencerPosition&) const = default; void encode(ceph::buffer::list& bl) const { ENCODE_START(1, 1, bl); encode(seq, bl); encode(trans, bl); encode(op, bl); ENCODE_FINISH(bl); } void decode(ceph::buffer::list::const_iterator& p) { DECODE_START(1, p); decode(seq, p); decode(trans, p); decode(op, p); DECODE_FINISH(p); } void dump(ceph::Formatter *f) const { f->dump_unsigned("seq", seq); f->dump_unsigned("trans", trans); f->dump_unsigned("op", op); } static void generate_test_instances(std::list<SequencerPosition*>& o) { o.push_back(new SequencerPosition); o.push_back(new SequencerPosition(1, 2, 3)); o.push_back(new SequencerPosition(4, 5, 6)); } }; WRITE_CLASS_ENCODER(SequencerPosition) inline std::ostream& operator<<(std::ostream& out, const SequencerPosition& t) { return out << t.seq << "." << t.trans << "." << t.op; } #endif
1,526
25.789474
88
h
null
ceph-main/src/os/bluestore/Allocator.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 * * 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_OS_BLUESTORE_ALLOCATOR_H #define CEPH_OS_BLUESTORE_ALLOCATOR_H #include <functional> #include <ostream> #include "include/ceph_assert.h" #include "bluestore_types.h" class Allocator { public: Allocator(std::string_view name, int64_t _capacity, int64_t _block_size); virtual ~Allocator(); /* * returns allocator type name as per names in config */ virtual const char* get_type() const = 0; /* * Allocate required number of blocks in n number of extents. * Min and Max number of extents are limited by: * a. alloc unit * b. max_alloc_size. * as no extent can be lesser than block_size and greater than max_alloc size. * Apart from that extents can vary between these lower and higher limits according * to free block search algorithm and availability of contiguous space. */ virtual int64_t allocate(uint64_t want_size, uint64_t block_size, uint64_t max_alloc_size, int64_t hint, PExtentVector *extents) = 0; int64_t allocate(uint64_t want_size, uint64_t block_size, int64_t hint, PExtentVector *extents) { return allocate(want_size, block_size, want_size, hint, extents); } /* Bulk release. Implementations may override this method to handle the whole * set at once. This could save e.g. unnecessary mutex dance. */ virtual void release(const interval_set<uint64_t>& release_set) = 0; void release(const PExtentVector& release_set); virtual void dump() = 0; virtual void foreach( std::function<void(uint64_t offset, uint64_t length)> notify) = 0; virtual void init_add_free(uint64_t offset, uint64_t length) = 0; virtual void init_rm_free(uint64_t offset, uint64_t length) = 0; virtual uint64_t get_free() = 0; virtual double get_fragmentation() { return 0.0; } virtual double get_fragmentation_score(); virtual void shutdown() = 0; static Allocator *create( CephContext* cct, std::string_view type, int64_t size, int64_t block_size, int64_t zone_size = 0, int64_t firs_sequential_zone = 0, const std::string_view name = "" ); const std::string& get_name() const; int64_t get_capacity() const { return device_size; } int64_t get_block_size() const { return block_size; } private: class SocketHook; SocketHook* asok_hook = nullptr; protected: const int64_t device_size = 0; const int64_t block_size = 0; }; #endif
2,780
26.81
85
h
null
ceph-main/src/os/bluestore/AvlAllocator.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <mutex> #include <boost/intrusive/avl_set.hpp> #include "Allocator.h" #include "os/bluestore/bluestore_types.h" #include "include/mempool.h" struct range_seg_t { MEMPOOL_CLASS_HELPERS(); ///< memory monitoring uint64_t start; ///< starting offset of this segment uint64_t end; ///< ending offset (non-inclusive) range_seg_t(uint64_t start, uint64_t end) : start{start}, end{end} {} // Tree is sorted by offset, greater offsets at the end of the tree. struct before_t { template<typename KeyLeft, typename KeyRight> bool operator()(const KeyLeft& lhs, const KeyRight& rhs) const { return lhs.end <= rhs.start; } }; boost::intrusive::avl_set_member_hook<> offset_hook; // Tree is sorted by size, larger sizes at the end of the tree. struct shorter_t { template<typename KeyType> bool operator()(const range_seg_t& lhs, const KeyType& rhs) const { auto lhs_size = lhs.end - lhs.start; auto rhs_size = rhs.end - rhs.start; if (lhs_size < rhs_size) { return true; } else if (lhs_size > rhs_size) { return false; } else { return lhs.start < rhs.start; } } }; inline uint64_t length() const { return end - start; } boost::intrusive::avl_set_member_hook<> size_hook; }; class AvlAllocator : public Allocator { struct dispose_rs { void operator()(range_seg_t* p) { delete p; } }; protected: /* * ctor intended for the usage from descendant class(es) which * provides handling for spilled over entries * (when entry count >= max_entries) */ AvlAllocator(CephContext* cct, int64_t device_size, int64_t block_size, uint64_t max_mem, std::string_view name); public: AvlAllocator(CephContext* cct, int64_t device_size, int64_t block_size, std::string_view name); ~AvlAllocator(); const char* get_type() const override { return "avl"; } int64_t allocate( uint64_t want, uint64_t unit, uint64_t max_alloc_size, int64_t hint, PExtentVector *extents) override; void release(const interval_set<uint64_t>& release_set) override; uint64_t get_free() override; double get_fragmentation() override; void dump() override; void foreach( std::function<void(uint64_t offset, uint64_t length)> notify) override; void init_add_free(uint64_t offset, uint64_t length) override; void init_rm_free(uint64_t offset, uint64_t length) override; void shutdown() override; private: // pick a range by search from cursor forward uint64_t _pick_block_after( uint64_t *cursor, uint64_t size, uint64_t align); // pick a range with exactly the same size or larger uint64_t _pick_block_fits( uint64_t size, uint64_t align); int _allocate( uint64_t size, uint64_t unit, uint64_t *offset, uint64_t *length); using range_tree_t = boost::intrusive::avl_set< range_seg_t, boost::intrusive::compare<range_seg_t::before_t>, boost::intrusive::member_hook< range_seg_t, boost::intrusive::avl_set_member_hook<>, &range_seg_t::offset_hook>>; range_tree_t range_tree; ///< main range tree /* * The range_size_tree should always contain the * same number of segments as the range_tree. * The only difference is that the range_size_tree * is ordered by segment sizes. */ using range_size_tree_t = boost::intrusive::avl_multiset< range_seg_t, boost::intrusive::compare<range_seg_t::shorter_t>, boost::intrusive::member_hook< range_seg_t, boost::intrusive::avl_set_member_hook<>, &range_seg_t::size_hook>, boost::intrusive::constant_time_size<true>>; range_size_tree_t range_size_tree; uint64_t num_free = 0; ///< total bytes in freelist /* * This value defines the number of elements in the ms_lbas array. * The value of 64 was chosen as it covers all power of 2 buckets * up to UINT64_MAX. * This is the equivalent of highest-bit of UINT64_MAX. */ static constexpr unsigned MAX_LBAS = 64; uint64_t lbas[MAX_LBAS] = {0}; /* * Minimum size which forces the dynamic allocator to change * it's allocation strategy. Once the allocator cannot satisfy * an allocation of this size then it switches to using more * aggressive strategy (i.e search by size rather than offset). */ uint64_t range_size_alloc_threshold = 0; /* * The minimum free space, in percent, which must be available * in allocator to continue allocations in a first-fit fashion. * Once the allocator's free space drops below this level we dynamically * switch to using best-fit allocations. */ int range_size_alloc_free_pct = 0; /* * Maximum number of segments to check in the first-fit mode, without this * limit, fragmented device can see lots of iterations and _block_picker() * becomes the performance limiting factor on high-performance storage. */ const uint32_t max_search_count; /* * Maximum distance to search forward from the last offset, without this * limit, fragmented device can see lots of iterations and _block_picker() * becomes the performance limiting factor on high-performance storage. */ const uint32_t max_search_bytes; /* * Max amount of range entries allowed. 0 - unlimited */ uint64_t range_count_cap = 0; void _range_size_tree_rm(range_seg_t& r) { ceph_assert(num_free >= r.length()); num_free -= r.length(); range_size_tree.erase(r); } void _range_size_tree_try_insert(range_seg_t& r) { if (_try_insert_range(r.start, r.end)) { range_size_tree.insert(r); num_free += r.length(); } else { range_tree.erase_and_dispose(r, dispose_rs{}); } } bool _try_insert_range(uint64_t start, uint64_t end, range_tree_t::iterator* insert_pos = nullptr) { bool res = !range_count_cap || range_size_tree.size() < range_count_cap; bool remove_lowest = false; if (!res) { if (end - start > _lowest_size_available()) { remove_lowest = true; res = true; } } if (!res) { _spillover_range(start, end); } else { // NB: we should do insertion before the following removal // to avoid potential iterator disposal insertion might depend on. if (insert_pos) { auto new_rs = new range_seg_t{ start, end }; range_tree.insert_before(*insert_pos, *new_rs); range_size_tree.insert(*new_rs); num_free += new_rs->length(); } if (remove_lowest) { auto r = range_size_tree.begin(); _range_size_tree_rm(*r); _spillover_range(r->start, r->end); range_tree.erase_and_dispose(*r, dispose_rs{}); } } return res; } virtual void _spillover_range(uint64_t start, uint64_t end) { // this should be overriden when range count cap is present, // i.e. (range_count_cap > 0) ceph_assert(false); } protected: // called when extent to be released/marked free virtual void _add_to_tree(uint64_t start, uint64_t size); protected: CephContext* cct; std::mutex lock; double _get_fragmentation() const { auto free_blocks = p2align(num_free, (uint64_t)block_size) / block_size; if (free_blocks <= 1) { return .0; } return (static_cast<double>(range_tree.size() - 1) / (free_blocks - 1)); } void _dump() const; void _foreach(std::function<void(uint64_t offset, uint64_t length)>) const; uint64_t _lowest_size_available() { auto rs = range_size_tree.begin(); return rs != range_size_tree.end() ? rs->length() : 0; } int64_t _allocate( uint64_t want, uint64_t unit, uint64_t max_alloc_size, int64_t hint, PExtentVector *extents); void _release(const interval_set<uint64_t>& release_set); void _release(const PExtentVector& release_set); void _shutdown(); void _process_range_removal(uint64_t start, uint64_t end, range_tree_t::iterator& rs); void _remove_from_tree(uint64_t start, uint64_t size); void _try_remove_from_tree(uint64_t start, uint64_t size, std::function<void(uint64_t offset, uint64_t length, bool found)> cb); uint64_t _get_free() const { return num_free; } };
8,339
29.661765
88
h
null
ceph-main/src/os/bluestore/BitmapAllocator.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_OS_BLUESTORE_BITMAPFASTALLOCATOR_H #define CEPH_OS_BLUESTORE_BITMAPFASTALLOCATOR_H #include <mutex> #include "Allocator.h" #include "os/bluestore/bluestore_types.h" #include "fastbmap_allocator_impl.h" #include "include/mempool.h" #include "common/debug.h" class BitmapAllocator : public Allocator, public AllocatorLevel02<AllocatorLevel01Loose> { CephContext* cct; public: BitmapAllocator(CephContext* _cct, int64_t capacity, int64_t alloc_unit, std::string_view name); ~BitmapAllocator() override { } const char* get_type() const override { return "bitmap"; } int64_t allocate( uint64_t want_size, uint64_t alloc_unit, uint64_t max_alloc_size, int64_t hint, PExtentVector *extents) override; void release( const interval_set<uint64_t>& release_set) override; using Allocator::release; uint64_t get_free() override { return get_available(); } void dump() override; void foreach( std::function<void(uint64_t offset, uint64_t length)> notify) override { foreach_internal(notify); } double get_fragmentation() override { return get_fragmentation_internal(); } void init_add_free(uint64_t offset, uint64_t length) override; void init_rm_free(uint64_t offset, uint64_t length) override; void shutdown() override; }; #endif
1,428
22.42623
74
h
null
ceph-main/src/os/bluestore/BitmapFreelistManager.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_OS_BLUESTORE_BITMAPFREELISTMANAGER_H #define CEPH_OS_BLUESTORE_BITMAPFREELISTMANAGER_H #include "FreelistManager.h" #include <string> #include <mutex> #include "common/ceph_mutex.h" #include "include/buffer.h" #include "kv/KeyValueDB.h" class BitmapFreelistManager : public FreelistManager { std::string meta_prefix, bitmap_prefix; std::shared_ptr<KeyValueDB::MergeOperator> merge_op; ceph::mutex lock = ceph::make_mutex("BitmapFreelistManager::lock"); uint64_t size; ///< size of device (bytes) uint64_t bytes_per_block; ///< bytes per block (bdev_block_size) uint64_t blocks_per_key; ///< blocks (bits) per key/value pair uint64_t bytes_per_key; ///< bytes per key/value pair uint64_t blocks; ///< size of device (blocks, size rounded up) uint64_t block_mask; ///< mask to convert byte offset to block offset uint64_t key_mask; ///< mask to convert offset to key offset ceph::buffer::list all_set_bl; KeyValueDB::Iterator enumerate_p; uint64_t enumerate_offset; ///< logical offset; position ceph::buffer::list enumerate_bl; ///< current key at enumerate_offset int enumerate_bl_pos; ///< bit position in enumerate_bl uint64_t _get_offset(uint64_t key_off, int bit) { return key_off + bit * bytes_per_block; } void _init_misc(); void _xor( uint64_t offset, uint64_t length, KeyValueDB::Transaction txn); int _read_cfg( std::function<int(const std::string&, std::string*)> cfg_reader); int _expand(uint64_t new_size, KeyValueDB* db); uint64_t size_2_block_count(uint64_t target_size) const; int read_size_meta_from_db(KeyValueDB* kvdb, uint64_t* res); void _sync(KeyValueDB* kvdb, bool read_only); void _load_from_db(KeyValueDB* kvdb); public: BitmapFreelistManager(CephContext* cct, std::string meta_prefix, std::string bitmap_prefix); static void setup_merge_operator(KeyValueDB *db, std::string prefix); int create(uint64_t size, uint64_t granularity, uint64_t zone_size, uint64_t first_sequential_zone, KeyValueDB::Transaction txn) override; int init(KeyValueDB *kvdb, bool db_in_read_only, std::function<int(const std::string&, std::string*)> cfg_reader) override; void shutdown() override; void sync(KeyValueDB* kvdb) override; void dump(KeyValueDB *kvdb) override; void enumerate_reset() override; bool enumerate_next(KeyValueDB *kvdb, uint64_t *offset, uint64_t *length) override; void allocate( uint64_t offset, uint64_t length, KeyValueDB::Transaction txn) override; void release( uint64_t offset, uint64_t length, KeyValueDB::Transaction txn) override; inline uint64_t get_size() const override { return size; } inline uint64_t get_alloc_units() const override { return size / bytes_per_block; } inline uint64_t get_alloc_size() const override { return bytes_per_block; } void get_meta(uint64_t target_size, std::vector<std::pair<std::string, std::string>>*) const override; }; #endif
3,122
29.920792
85
h
null
ceph-main/src/os/bluestore/BlueFS.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_OS_BLUESTORE_BLUEFS_H #define CEPH_OS_BLUESTORE_BLUEFS_H #include <atomic> #include <mutex> #include <limits> #include "bluefs_types.h" #include "blk/BlockDevice.h" #include "common/RefCountedObj.h" #include "common/ceph_context.h" #include "global/global_context.h" #include "include/common_fwd.h" #include "boost/intrusive/list.hpp" #include "boost/dynamic_bitset.hpp" class Allocator; enum { l_bluefs_first = 732600, l_bluefs_db_total_bytes, l_bluefs_db_used_bytes, l_bluefs_wal_total_bytes, l_bluefs_wal_used_bytes, l_bluefs_slow_total_bytes, l_bluefs_slow_used_bytes, l_bluefs_num_files, l_bluefs_log_bytes, l_bluefs_log_compactions, l_bluefs_log_write_count, l_bluefs_logged_bytes, l_bluefs_files_written_wal, l_bluefs_files_written_sst, l_bluefs_write_count_wal, l_bluefs_write_count_sst, l_bluefs_bytes_written_wal, l_bluefs_bytes_written_sst, l_bluefs_bytes_written_slow, l_bluefs_max_bytes_wal, l_bluefs_max_bytes_db, l_bluefs_max_bytes_slow, l_bluefs_main_alloc_unit, l_bluefs_db_alloc_unit, l_bluefs_wal_alloc_unit, l_bluefs_read_random_count, l_bluefs_read_random_bytes, l_bluefs_read_random_disk_count, l_bluefs_read_random_disk_bytes, l_bluefs_read_random_disk_bytes_wal, l_bluefs_read_random_disk_bytes_db, l_bluefs_read_random_disk_bytes_slow, l_bluefs_read_random_buffer_count, l_bluefs_read_random_buffer_bytes, l_bluefs_read_count, l_bluefs_read_bytes, l_bluefs_read_disk_count, l_bluefs_read_disk_bytes, l_bluefs_read_disk_bytes_wal, l_bluefs_read_disk_bytes_db, l_bluefs_read_disk_bytes_slow, l_bluefs_read_prefetch_count, l_bluefs_read_prefetch_bytes, l_bluefs_write_count, l_bluefs_write_disk_count, l_bluefs_write_bytes, l_bluefs_compaction_lat, l_bluefs_compaction_lock_lat, l_bluefs_alloc_shared_dev_fallbacks, l_bluefs_alloc_shared_size_fallbacks, l_bluefs_read_zeros_candidate, l_bluefs_read_zeros_errors, l_bluefs_last, }; class BlueFSVolumeSelector { public: typedef std::vector<std::pair<std::string, uint64_t>> paths; virtual ~BlueFSVolumeSelector() { } virtual void* get_hint_for_log() const = 0; virtual void* get_hint_by_dir(std::string_view dirname) const = 0; virtual void add_usage(void* file_hint, const bluefs_fnode_t& fnode) = 0; virtual void sub_usage(void* file_hint, const bluefs_fnode_t& fnode) = 0; virtual void add_usage(void* file_hint, uint64_t fsize) = 0; virtual void sub_usage(void* file_hint, uint64_t fsize) = 0; virtual uint8_t select_prefer_bdev(void* hint) = 0; virtual void get_paths(const std::string& base, paths& res) const = 0; virtual void dump(std::ostream& sout) = 0; /* used for sanity checking of vselector */ virtual BlueFSVolumeSelector* clone_empty() const { return nullptr; } virtual bool compare(BlueFSVolumeSelector* other) { return true; }; }; struct bluefs_shared_alloc_context_t { bool need_init = false; Allocator* a = nullptr; uint64_t alloc_unit = 0; std::atomic<uint64_t> bluefs_used = 0; void set(Allocator* _a, uint64_t _au) { a = _a; alloc_unit = _au; need_init = true; bluefs_used = 0; } void reset() { a = nullptr; alloc_unit = 0; } }; class BlueFS { public: CephContext* cct; static constexpr unsigned MAX_BDEV = 5; static constexpr unsigned BDEV_WAL = 0; static constexpr unsigned BDEV_DB = 1; static constexpr unsigned BDEV_SLOW = 2; static constexpr unsigned BDEV_NEWWAL = 3; static constexpr unsigned BDEV_NEWDB = 4; enum { WRITER_UNKNOWN, WRITER_WAL, WRITER_SST, }; struct File : public RefCountedObject { MEMPOOL_CLASS_HELPERS(); bluefs_fnode_t fnode; int refs; uint64_t dirty_seq; bool locked; bool deleted; bool is_dirty; boost::intrusive::list_member_hook<> dirty_item; std::atomic_int num_readers, num_writers; std::atomic_int num_reading; void* vselector_hint = nullptr; /* lock protects fnode and other the parts that can be modified during read & write operations. Does not protect values that are fixed Does not need to be taken when doing one-time operations: _replay, device_migrate_to_existing, device_migrate_to_new */ ceph::mutex lock = ceph::make_mutex("BlueFS::File::lock"); private: FRIEND_MAKE_REF(File); File() : refs(0), dirty_seq(0), locked(false), deleted(false), is_dirty(false), num_readers(0), num_writers(0), num_reading(0), vselector_hint(nullptr) {} ~File() override { ceph_assert(num_readers.load() == 0); ceph_assert(num_writers.load() == 0); ceph_assert(num_reading.load() == 0); ceph_assert(!locked); } }; using FileRef = ceph::ref_t<File>; typedef boost::intrusive::list< File, boost::intrusive::member_hook< File, boost::intrusive::list_member_hook<>, &File::dirty_item> > dirty_file_list_t; struct Dir : public RefCountedObject { MEMPOOL_CLASS_HELPERS(); mempool::bluefs::map<std::string, FileRef, std::less<>> file_map; private: FRIEND_MAKE_REF(Dir); Dir() = default; }; using DirRef = ceph::ref_t<Dir>; struct FileWriter { MEMPOOL_CLASS_HELPERS(); FileRef file; uint64_t pos = 0; ///< start offset for buffer private: ceph::buffer::list buffer; ///< new data to write (at end of file) ceph::buffer::list tail_block; ///< existing partial block at end of file, if any public: unsigned get_buffer_length() const { return buffer.length(); } ceph::bufferlist flush_buffer( CephContext* cct, const bool partial, const unsigned length, const bluefs_super_t& super); ceph::buffer::list::page_aligned_appender buffer_appender; //< for const char* only public: int writer_type = 0; ///< WRITER_* int write_hint = WRITE_LIFE_NOT_SET; ceph::mutex lock = ceph::make_mutex("BlueFS::FileWriter::lock"); std::array<IOContext*,MAX_BDEV> iocv; ///< for each bdev std::array<bool, MAX_BDEV> dirty_devs; FileWriter(FileRef f) : file(std::move(f)), buffer_appender(buffer.get_page_aligned_appender( g_conf()->bluefs_alloc_size / CEPH_PAGE_SIZE)) { ++file->num_writers; iocv.fill(nullptr); dirty_devs.fill(false); if (file->fnode.ino == 1) { write_hint = WRITE_LIFE_MEDIUM; } } // NOTE: caller must call BlueFS::close_writer() ~FileWriter() { --file->num_writers; } // note: BlueRocksEnv uses this append exclusively, so it's safe // to use buffer_appender exclusively here (e.g., its notion of // offset will remain accurate). void append(const char *buf, size_t len) { uint64_t l0 = get_buffer_length(); ceph_assert(l0 + len <= std::numeric_limits<unsigned>::max()); buffer_appender.append(buf, len); } void append(const std::byte *buf, size_t len) { // allow callers to use byte type instead of char* as we simply pass byte array append((const char*)buf, len); } // note: used internally only, for ino 1 or 0. void append(ceph::buffer::list& bl) { uint64_t l0 = get_buffer_length(); ceph_assert(l0 + bl.length() <= std::numeric_limits<unsigned>::max()); buffer.claim_append(bl); } void append_zero(size_t len) { uint64_t l0 = get_buffer_length(); ceph_assert(l0 + len <= std::numeric_limits<unsigned>::max()); buffer_appender.append_zero(len); } uint64_t get_effective_write_pos() { return pos + buffer.length(); } }; struct FileReaderBuffer { MEMPOOL_CLASS_HELPERS(); uint64_t bl_off = 0; ///< prefetch buffer logical offset ceph::buffer::list bl; ///< prefetch buffer uint64_t pos = 0; ///< current logical offset uint64_t max_prefetch; ///< max allowed prefetch explicit FileReaderBuffer(uint64_t mpf) : max_prefetch(mpf) {} uint64_t get_buf_end() const { return bl_off + bl.length(); } uint64_t get_buf_remaining(uint64_t p) const { if (p >= bl_off && p < bl_off + bl.length()) return bl_off + bl.length() - p; return 0; } void skip(size_t n) { pos += n; } // For the sake of simplicity, we invalidate completed rather than // for the provided extent void invalidate_cache(uint64_t offset, uint64_t length) { if (offset >= bl_off && offset < get_buf_end()) { bl.clear(); bl_off = 0; } } }; struct FileReader { MEMPOOL_CLASS_HELPERS(); FileRef file; FileReaderBuffer buf; bool random; bool ignore_eof; ///< used when reading our log file ceph::shared_mutex lock { ceph::make_shared_mutex(std::string(), false, false, false) }; FileReader(FileRef f, uint64_t mpf, bool rand, bool ie) : file(f), buf(mpf), random(rand), ignore_eof(ie) { ++file->num_readers; } ~FileReader() { --file->num_readers; } }; struct FileLock { MEMPOOL_CLASS_HELPERS(); FileRef file; explicit FileLock(FileRef f) : file(std::move(f)) {} }; private: PerfCounters *logger = nullptr; uint64_t max_bytes[MAX_BDEV] = {0}; uint64_t max_bytes_pcounters[MAX_BDEV] = { l_bluefs_max_bytes_wal, l_bluefs_max_bytes_db, l_bluefs_max_bytes_slow, l_bluefs_max_bytes_wal, l_bluefs_max_bytes_db, }; // cache struct { ceph::mutex lock = ceph::make_mutex("BlueFS::nodes.lock"); mempool::bluefs::map<std::string, DirRef, std::less<>> dir_map; ///< dirname -> Dir mempool::bluefs::unordered_map<uint64_t, FileRef> file_map; ///< ino -> File } nodes; bluefs_super_t super; ///< latest superblock (as last written) uint64_t ino_last = 0; ///< last assigned ino (this one is in use) struct { ceph::mutex lock = ceph::make_mutex("BlueFS::log.lock"); uint64_t seq_live = 1; //seq that log is currently writing to; mirrors dirty.seq_live FileWriter *writer = 0; bluefs_transaction_t t; } log; struct { ceph::mutex lock = ceph::make_mutex("BlueFS::dirty.lock"); uint64_t seq_stable = 0; //seq that is now stable on disk uint64_t seq_live = 1; //seq that is ongoing and dirty files will be written to // map of dirty files, files of same dirty_seq are grouped into list. std::map<uint64_t, dirty_file_list_t> files; std::vector<interval_set<uint64_t>> pending_release; ///< extents to release // TODO: it should be examined what makes pending_release immune to // eras in a way similar to dirty_files. Hints: // 1) we have actually only 2 eras: log_seq and log_seq+1 // 2) we usually not remove extents from files. And when we do, we force log-syncing. } dirty; ceph::condition_variable log_cond; ///< used for state control between log flush / log compaction std::atomic<bool> log_is_compacting{false}; ///< signals that bluefs log is already ongoing compaction std::atomic<bool> log_forbidden_to_expand{false}; ///< used to signal that async compaction is in state /// that prohibits expansion of bluefs log /* * There are up to 3 block devices: * * BDEV_DB db/ - the primary db device * BDEV_WAL db.wal/ - a small, fast device, specifically for the WAL * BDEV_SLOW db.slow/ - a big, slow device, to spill over to as BDEV_DB fills */ std::vector<BlockDevice*> bdev; ///< block devices we can use std::vector<IOContext*> ioc; ///< IOContexts for bdevs std::vector<uint64_t> block_reserved; ///< starting reserve extent per device std::vector<Allocator*> alloc; ///< allocators for bdevs std::vector<uint64_t> alloc_size; ///< alloc size for each device //std::vector<interval_set<uint64_t>> block_unused_too_granular; BlockDevice::aio_callback_t discard_cb[3]; //discard callbacks for each dev std::unique_ptr<BlueFSVolumeSelector> vselector; bluefs_shared_alloc_context_t* shared_alloc = nullptr; unsigned shared_alloc_id = unsigned(-1); inline bool is_shared_alloc(unsigned id) const { return id == shared_alloc_id; } std::atomic<int64_t> cooldown_deadline = 0; class SocketHook; SocketHook* asok_hook = nullptr; // used to trigger zeros into read (debug / verify) std::atomic<uint64_t> inject_read_zeros{0}; void _init_logger(); void _shutdown_logger(); void _update_logger_stats(); void _init_alloc(); void _stop_alloc(); ///< pad ceph::buffer::list to max(block size, pad_size) w/ zeros void _pad_bl(ceph::buffer::list& bl, uint64_t pad_size = 0); uint64_t _get_used(unsigned id) const; uint64_t _get_total(unsigned id) const; FileRef _get_file(uint64_t ino); void _drop_link_D(FileRef f); unsigned _get_slow_device_id() { return bdev[BDEV_SLOW] ? BDEV_SLOW : BDEV_DB; } const char* get_device_name(unsigned id); int _allocate(uint8_t bdev, uint64_t len, uint64_t alloc_unit, bluefs_fnode_t* node, size_t alloc_attempts = 0, bool permit_dev_fallback = true); /* signal replay log to include h->file in nearest log flush */ int _signal_dirty_to_log_D(FileWriter *h); int _flush_range_F(FileWriter *h, uint64_t offset, uint64_t length); int _flush_data(FileWriter *h, uint64_t offset, uint64_t length, bool buffered); int _flush_F(FileWriter *h, bool force, bool *flushed = nullptr); uint64_t _flush_special(FileWriter *h); int _fsync(FileWriter *h); #ifdef HAVE_LIBAIO void _claim_completed_aios(FileWriter *h, std::list<aio_t> *ls); void _wait_for_aio(FileWriter *h); // safe to call without a lock #endif int64_t _maybe_extend_log(); void _extend_log(); uint64_t _log_advance_seq(); void _consume_dirty(uint64_t seq); void _clear_dirty_set_stable_D(uint64_t seq_stable); void _release_pending_allocations(std::vector<interval_set<uint64_t>>& to_release); void _flush_and_sync_log_core(int64_t available_runway); int _flush_and_sync_log_jump_D(uint64_t jump_to, int64_t available_runway); int _flush_and_sync_log_LD(uint64_t want_seq = 0); uint64_t _estimate_transaction_size(bluefs_transaction_t* t); uint64_t _make_initial_transaction(uint64_t start_seq, bluefs_fnode_t& fnode, uint64_t expected_final_size, bufferlist* out); uint64_t _estimate_log_size_N(); bool _should_start_compact_log_L_N(); enum { REMOVE_DB = 1, REMOVE_WAL = 2, RENAME_SLOW2DB = 4, RENAME_DB2SLOW = 8, }; void _compact_log_dump_metadata_NF(uint64_t start_seq, bluefs_transaction_t *t, int flags, uint64_t capture_before_seq); void _compact_log_sync_LNF_LD(); void _compact_log_async_LD_LNF_D(); void _rewrite_log_and_layout_sync_LNF_LD(bool permit_dev_fallback, int super_dev, int log_dev, int new_log_dev, int flags, std::optional<bluefs_layout_t> layout); //void _aio_finish(void *priv); void _flush_bdev(FileWriter *h, bool check_mutex_locked = true); void _flush_bdev(); // this is safe to call without a lock void _flush_bdev(std::array<bool, MAX_BDEV>& dirty_bdevs); // this is safe to call without a lock int _preallocate(FileRef f, uint64_t off, uint64_t len); int _truncate(FileWriter *h, uint64_t off); int64_t _read( FileReader *h, ///< [in] read from here uint64_t offset, ///< [in] offset size_t len, ///< [in] this many bytes ceph::buffer::list *outbl, ///< [out] optional: reference the result here char *out); ///< [out] optional: or copy it here int64_t _read_random( FileReader *h, ///< [in] read from here uint64_t offset, ///< [in] offset uint64_t len, ///< [in] this many bytes char *out); ///< [out] optional: or copy it here int _open_super(); int _write_super(int dev); int _check_allocations(const bluefs_fnode_t& fnode, boost::dynamic_bitset<uint64_t>* used_blocks, bool is_alloc, //true when allocating, false when deallocating const char* op_name); int _verify_alloc_granularity( __u8 id, uint64_t offset, uint64_t length, uint64_t alloc_unit, const char *op); int _replay(bool noop, bool to_stdout = false); ///< replay journal FileWriter *_create_writer(FileRef f); void _drain_writer(FileWriter *h); void _close_writer(FileWriter *h); // always put the super in the second 4k block. FIXME should this be // block size independent? unsigned get_super_offset() { return 4096; } unsigned get_super_length() { return 4096; } void _maybe_check_vselector_LNF() { if (cct->_conf->bluefs_check_volume_selector_often) { _check_vselector_LNF(); } } public: BlueFS(CephContext* cct); ~BlueFS(); // the super is always stored on bdev 0 int mkfs(uuid_d osd_uuid, const bluefs_layout_t& layout); int mount(); int maybe_verify_layout(const bluefs_layout_t& layout) const; void umount(bool avoid_compact = false); int prepare_new_device(int id, const bluefs_layout_t& layout); int log_dump(); void collect_metadata(std::map<std::string,std::string> *pm, unsigned skip_bdev_id); void get_devices(std::set<std::string> *ls); uint64_t get_alloc_size(int id) { return alloc_size[id]; } int fsck(); int device_migrate_to_new( CephContext *cct, const std::set<int>& devs_source, int dev_target, const bluefs_layout_t& layout); int device_migrate_to_existing( CephContext *cct, const std::set<int>& devs_source, int dev_target, const bluefs_layout_t& layout); uint64_t get_used(); uint64_t get_total(unsigned id); uint64_t get_free(unsigned id); uint64_t get_used(unsigned id); void dump_perf_counters(ceph::Formatter *f); void dump_block_extents(std::ostream& out); /// get current extents that we own for given block device void foreach_block_extents( unsigned id, std::function<void(uint64_t, uint32_t)> cb); int open_for_write( std::string_view dir, std::string_view file, FileWriter **h, bool overwrite); int open_for_read( std::string_view dir, std::string_view file, FileReader **h, bool random = false); // data added after last fsync() is lost void close_writer(FileWriter *h); int rename(std::string_view old_dir, std::string_view old_file, std::string_view new_dir, std::string_view new_file); int readdir(std::string_view dirname, std::vector<std::string> *ls); int unlink(std::string_view dirname, std::string_view filename); int mkdir(std::string_view dirname); int rmdir(std::string_view dirname); bool wal_is_rotational(); bool db_is_rotational(); bool dir_exists(std::string_view dirname); int stat(std::string_view dirname, std::string_view filename, uint64_t *size, utime_t *mtime); int lock_file(std::string_view dirname, std::string_view filename, FileLock **p); int unlock_file(FileLock *l); void compact_log(); /// sync any uncommitted state to disk void sync_metadata(bool avoid_compact); void set_volume_selector(BlueFSVolumeSelector* s) { vselector.reset(s); } void dump_volume_selector(std::ostream& sout) { vselector->dump(sout); } void get_vselector_paths(const std::string& base, BlueFSVolumeSelector::paths& res) const { return vselector->get_paths(base, res); } int add_block_device(unsigned bdev, const std::string& path, bool trim, uint64_t reserved, bluefs_shared_alloc_context_t* _shared_alloc = nullptr); bool bdev_support_label(unsigned id); uint64_t get_block_device_size(unsigned bdev) const; // handler for discard event void handle_discard(unsigned dev, interval_set<uint64_t>& to_release); void flush(FileWriter *h, bool force = false); void append_try_flush(FileWriter *h, const char* buf, size_t len); void flush_range(FileWriter *h, uint64_t offset, uint64_t length); int fsync(FileWriter *h); int64_t read(FileReader *h, uint64_t offset, size_t len, ceph::buffer::list *outbl, char *out) { // no need to hold the global lock here; we only touch h and // h->file, and read vs write or delete is already protected (via // atomics and asserts). return _read(h, offset, len, outbl, out); } int64_t read_random(FileReader *h, uint64_t offset, size_t len, char *out) { // no need to hold the global lock here; we only touch h and // h->file, and read vs write or delete is already protected (via // atomics and asserts). return _read_random(h, offset, len, out); } void invalidate_cache(FileRef f, uint64_t offset, uint64_t len); int preallocate(FileRef f, uint64_t offset, uint64_t len); int truncate(FileWriter *h, uint64_t offset); size_t probe_alloc_avail(int dev, uint64_t alloc_size); /// test purpose methods const PerfCounters* get_perf_counters() const { return logger; } uint64_t debug_get_dirty_seq(FileWriter *h); bool debug_get_is_dev_dirty(FileWriter *h, uint8_t dev); private: // Wrappers for BlockDevice::read(...) and BlockDevice::read_random(...) // They are used for checking if read values are all 0, and reread if so. int _read_and_check(uint8_t ndev, uint64_t off, uint64_t len, ceph::buffer::list *pbl, IOContext *ioc, bool buffered); int _read_random_and_check(uint8_t ndev, uint64_t off, uint64_t len, char *buf, bool buffered); int _bdev_read(uint8_t ndev, uint64_t off, uint64_t len, ceph::buffer::list* pbl, IOContext* ioc, bool buffered); int _bdev_read_random(uint8_t ndev, uint64_t off, uint64_t len, char* buf, bool buffered); /// test and compact log, if necessary void _maybe_compact_log_LNF_NF_LD_D(); int _do_replay_recovery_read(FileReader *log, size_t log_pos, size_t read_offset, size_t read_len, bufferlist* bl); void _check_vselector_LNF(); }; class OriginalVolumeSelector : public BlueFSVolumeSelector { uint64_t wal_total; uint64_t db_total; uint64_t slow_total; public: OriginalVolumeSelector( uint64_t _wal_total, uint64_t _db_total, uint64_t _slow_total) : wal_total(_wal_total), db_total(_db_total), slow_total(_slow_total) {} void* get_hint_for_log() const override; void* get_hint_by_dir(std::string_view dirname) const override; void add_usage(void* hint, const bluefs_fnode_t& fnode) override { // do nothing return; } void sub_usage(void* hint, const bluefs_fnode_t& fnode) override { // do nothing return; } void add_usage(void* hint, uint64_t fsize) override { // do nothing return; } void sub_usage(void* hint, uint64_t fsize) override { // do nothing return; } uint8_t select_prefer_bdev(void* hint) override; void get_paths(const std::string& base, paths& res) const override; void dump(std::ostream& sout) override; }; class FitToFastVolumeSelector : public OriginalVolumeSelector { public: FitToFastVolumeSelector( uint64_t _wal_total, uint64_t _db_total, uint64_t _slow_total) : OriginalVolumeSelector(_wal_total, _db_total, _slow_total) {} void get_paths(const std::string& base, paths& res) const override; }; /** * Directional graph of locks. * Vertices - Locks. Edges (directed) - locking progression. * Edge A->B exist if last taken lock was A and next taken lock is B. * * Row represents last lock taken. * Column represents next lock taken. * * > | W | L | N | D | F * -------------|---|---|---|---|--- * FileWriter W | | > | > | > | > * log L | | > | > | > * nodes N | | > | > * dirty D | | | > * File F | * * Claim: Deadlock is possible IFF graph contains cycles. */ #endif
24,167
30.509778
127
h
null
ceph-main/src/os/bluestore/BlueRocksEnv.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_OS_BLUESTORE_BLUEROCKSENV_H #define CEPH_OS_BLUESTORE_BLUEROCKSENV_H #include <memory> #include <string> #include "rocksdb/options.h" #include "rocksdb/status.h" #include "rocksdb/utilities/env_mirror.h" #include "include/ceph_assert.h" #include "kv/RocksDBStore.h" class BlueFS; class BlueRocksEnv : public rocksdb::EnvWrapper { public: // Create a brand new sequentially-readable file with the specified name. // On success, stores a pointer to the new file in *result and returns OK. // On failure, stores nullptr in *result and returns non-OK. If the file does // not exist, returns a non-OK status. // // The returned file will only be accessed by one thread at a time. rocksdb::Status NewSequentialFile( const std::string& fname, std::unique_ptr<rocksdb::SequentialFile>* result, const rocksdb::EnvOptions& options) override; // Create a brand new random access read-only file with the // specified name. On success, stores a pointer to the new file in // *result and returns OK. On failure, stores nullptr in *result and // returns non-OK. If the file does not exist, returns a non-OK // status. // // The returned file may be concurrently accessed by multiple threads. rocksdb::Status NewRandomAccessFile( const std::string& fname, std::unique_ptr<rocksdb::RandomAccessFile>* result, const rocksdb::EnvOptions& options) override; // Create an object that writes to a new file with the specified // name. Deletes any existing file with the same name and creates a // new file. On success, stores a pointer to the new file in // *result and returns OK. On failure, stores nullptr in *result and // returns non-OK. // // The returned file will only be accessed by one thread at a time. rocksdb::Status NewWritableFile( const std::string& fname, std::unique_ptr<rocksdb::WritableFile>* result, const rocksdb::EnvOptions& options) override; // Reuse an existing file by renaming it and opening it as writable. rocksdb::Status ReuseWritableFile( const std::string& fname, const std::string& old_fname, std::unique_ptr<rocksdb::WritableFile>* result, const rocksdb::EnvOptions& options) override; // Create an object that represents a directory. Will fail if directory // doesn't exist. If the directory exists, it will open the directory // and create a new Directory object. // // On success, stores a pointer to the new Directory in // *result and returns OK. On failure stores nullptr in *result and // returns non-OK. rocksdb::Status NewDirectory( const std::string& name, std::unique_ptr<rocksdb::Directory>* result) override; // Returns OK if the named file exists. // NotFound if the named file does not exist, // the calling process does not have permission to determine // whether this file exists, or if the path is invalid. // IOError if an IO Error was encountered rocksdb::Status FileExists(const std::string& fname) override; // Store in *result the names of the children of the specified directory. // The names are relative to "dir". // Original contents of *results are dropped. rocksdb::Status GetChildren(const std::string& dir, std::vector<std::string>* result) override; // Delete the named file. rocksdb::Status DeleteFile(const std::string& fname) override; // Create the specified directory. Returns error if directory exists. rocksdb::Status CreateDir(const std::string& dirname) override; // Create directory if missing. Return Ok if it exists, or successful in // Creating. rocksdb::Status CreateDirIfMissing(const std::string& dirname) override; // Delete the specified directory. rocksdb::Status DeleteDir(const std::string& dirname) override; // Store the size of fname in *file_size. rocksdb::Status GetFileSize(const std::string& fname, uint64_t* file_size) override; // Store the last modification time of fname in *file_mtime. rocksdb::Status GetFileModificationTime(const std::string& fname, uint64_t* file_mtime) override; // Rename file src to target. rocksdb::Status RenameFile(const std::string& src, const std::string& target) override; // Hard Link file src to target. rocksdb::Status LinkFile(const std::string& src, const std::string& target) override; // Tell if two files are identical rocksdb::Status AreFilesSame(const std::string& first, const std::string& second, bool* res) override; // Lock the specified file. Used to prevent concurrent access to // the same db by multiple processes. On failure, stores nullptr in // *lock and returns non-OK. // // On success, stores a pointer to the object that represents the // acquired lock in *lock and returns OK. The caller should call // UnlockFile(*lock) to release the lock. If the process exits, // the lock will be automatically released. // // If somebody else already holds the lock, finishes immediately // with a failure. I.e., this call does not wait for existing locks // to go away. // // May create the named file if it does not already exist. rocksdb::Status LockFile(const std::string& fname, rocksdb::FileLock** lock) override; // Release the lock acquired by a previous successful call to LockFile. // REQUIRES: lock was returned by a successful LockFile() call // REQUIRES: lock has not already been unlocked. rocksdb::Status UnlockFile(rocksdb::FileLock* lock) override; // *path is set to a temporary directory that can be used for testing. It may // or may not have just been created. The directory may or may not differ // between runs of the same process, but subsequent calls will return the // same directory. rocksdb::Status GetTestDirectory(std::string* path) override; // Create and return a log file for storing informational messages. rocksdb::Status NewLogger( const std::string& fname, std::shared_ptr<rocksdb::Logger>* result) override; // Get full directory name for this db. rocksdb::Status GetAbsolutePath(const std::string& db_path, std::string* output_path) override; explicit BlueRocksEnv(BlueFS *f); private: BlueFS *fs; }; #endif
6,431
39.968153
88
h
null
ceph-main/src/os/bluestore/BtreeAllocator.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:nil -*- // vim: ts=8 sw=2 smarttab #pragma once #include <mutex> #include "include/cpp-btree/btree_map.h" #include "include/cpp-btree/btree_set.h" #include "Allocator.h" #include "os/bluestore/bluestore_types.h" #include "include/mempool.h" class BtreeAllocator : public Allocator { struct range_seg_t { uint64_t start; ///< starting offset of this segment uint64_t end; ///< ending offset (non-inclusive) range_seg_t(uint64_t start, uint64_t end) : start{start}, end{end} {} inline uint64_t length() const { return end - start; } }; struct range_value_t { uint64_t size; uint64_t start; range_value_t(uint64_t start, uint64_t end) : size{end - start}, start{start} {} range_value_t(const range_seg_t& rs) : size{rs.length()}, start{rs.start} {} }; // do the radix sort struct compare_range_value_t { int operator()(const range_value_t& lhs, const range_value_t& rhs) const noexcept { if (lhs.size < rhs.size) { return -1; } else if (lhs.size > rhs.size) { return 1; } if (lhs.start < rhs.start) { return -1; } else if (lhs.start > rhs.start) { return 1; } else { return 0; } } }; protected: /* * ctor intended for the usage from descendant class(es) which * provides handling for spilled over entries * (when entry count >= max_entries) */ BtreeAllocator(CephContext* cct, int64_t device_size, int64_t block_size, uint64_t max_mem, std::string_view name); public: BtreeAllocator(CephContext* cct, int64_t device_size, int64_t block_size, std::string_view name); ~BtreeAllocator(); const char* get_type() const override { return "btree"; } int64_t allocate( uint64_t want, uint64_t unit, uint64_t max_alloc_size, int64_t hint, PExtentVector *extents) override; void release(const interval_set<uint64_t>& release_set) override; uint64_t get_free() override; double get_fragmentation() override; void dump() override; void foreach( std::function<void(uint64_t offset, uint64_t length)> notify) override; void init_add_free(uint64_t offset, uint64_t length) override; void init_rm_free(uint64_t offset, uint64_t length) override; void shutdown() override; private: // pick a range by search from cursor forward uint64_t _pick_block_after( uint64_t *cursor, uint64_t size, uint64_t align); // pick a range with exactly the same size or larger uint64_t _pick_block_fits( uint64_t size, uint64_t align); int _allocate( uint64_t size, uint64_t unit, uint64_t *offset, uint64_t *length); template<class T> using pool_allocator = mempool::bluestore_alloc::pool_allocator<T>; using range_tree_t = btree::btree_map< uint64_t /* start */, uint64_t /* end */, std::less<uint64_t>, pool_allocator<std::pair<uint64_t, uint64_t>>>; range_tree_t range_tree; ///< main range tree /* * The range_size_tree should always contain the * same number of segments as the range_tree. * The only difference is that the range_size_tree * is ordered by segment sizes. */ using range_size_tree_t = btree::btree_set< range_value_t /* size, start */, compare_range_value_t, pool_allocator<range_value_t>>; range_size_tree_t range_size_tree; uint64_t num_free = 0; ///< total bytes in freelist /* * This value defines the number of elements in the ms_lbas array. * The value of 64 was chosen as it covers all power of 2 buckets * up to UINT64_MAX. * This is the equivalent of highest-bit of UINT64_MAX. */ static constexpr unsigned MAX_LBAS = 64; uint64_t lbas[MAX_LBAS] = {0}; /* * Minimum size which forces the dynamic allocator to change * it's allocation strategy. Once the allocator cannot satisfy * an allocation of this size then it switches to using more * aggressive strategy (i.e search by size rather than offset). */ uint64_t range_size_alloc_threshold = 0; /* * The minimum free space, in percent, which must be available * in allocator to continue allocations in a first-fit fashion. * Once the allocator's free space drops below this level we dynamically * switch to using best-fit allocations. */ int range_size_alloc_free_pct = 0; /* * Max amount of range entries allowed. 0 - unlimited */ int64_t range_count_cap = 0; private: CephContext* cct; std::mutex lock; double _get_fragmentation() const { auto free_blocks = p2align(num_free, (uint64_t)block_size) / block_size; if (free_blocks <= 1) { return .0; } return (static_cast<double>(range_tree.size() - 1) / (free_blocks - 1)); } void _dump() const; uint64_t _lowest_size_available() const { auto rs = range_size_tree.begin(); return rs != range_size_tree.end() ? rs->size : 0; } int64_t _allocate( uint64_t want, uint64_t unit, uint64_t max_alloc_size, int64_t hint, PExtentVector *extents); void _release(const interval_set<uint64_t>& release_set); void _release(const PExtentVector& release_set); void _shutdown(); // called when extent to be released/marked free void _add_to_tree(uint64_t start, uint64_t size); void _process_range_removal(uint64_t start, uint64_t end, range_tree_t::iterator& rs); void _remove_from_tree(uint64_t start, uint64_t size); void _try_remove_from_tree(uint64_t start, uint64_t size, std::function<void(uint64_t offset, uint64_t length, bool found)> cb); uint64_t _get_free() const { return num_free; } };
5,779
27.756219
88
h
null
ceph-main/src/os/bluestore/FreelistManager.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_OS_BLUESTORE_FREELISTMANAGER_H #define CEPH_OS_BLUESTORE_FREELISTMANAGER_H #include <string> #include <vector> #include <mutex> #include <ostream> #include "kv/KeyValueDB.h" #include "bluestore_types.h" class FreelistManager { bool null_manager = false; public: CephContext* cct; explicit FreelistManager(CephContext* cct) : cct(cct) {} virtual ~FreelistManager() {} static FreelistManager *create( CephContext* cct, std::string type, std::string prefix); static void setup_merge_operators(KeyValueDB *db, const std::string &type); virtual int create(uint64_t size, uint64_t granularity, uint64_t zone_size, uint64_t first_sequential_zone, KeyValueDB::Transaction txn) = 0; virtual int init(KeyValueDB *kvdb, bool db_in_read_only, std::function<int(const std::string&, std::string*)> cfg_reader) = 0; virtual void sync(KeyValueDB* kvdb) = 0; virtual void shutdown() = 0; virtual void dump(KeyValueDB *kvdb) = 0; virtual void enumerate_reset() = 0; virtual bool enumerate_next(KeyValueDB *kvdb, uint64_t *offset, uint64_t *length) = 0; virtual void allocate( uint64_t offset, uint64_t length, KeyValueDB::Transaction txn) = 0; virtual void release( uint64_t offset, uint64_t length, KeyValueDB::Transaction txn) = 0; virtual uint64_t get_size() const = 0; virtual uint64_t get_alloc_units() const = 0; virtual uint64_t get_alloc_size() const = 0; virtual void get_meta(uint64_t target_size, std::vector<std::pair<std::string, std::string>>*) const = 0; void set_null_manager() { null_manager = true; } bool is_null_manager() const { return null_manager; } }; #endif
1,801
26.30303
88
h
null
ceph-main/src/os/bluestore/HybridAllocator.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #pragma once #include <mutex> #include "AvlAllocator.h" #include "BitmapAllocator.h" class HybridAllocator : public AvlAllocator { BitmapAllocator* bmap_alloc = nullptr; public: HybridAllocator(CephContext* cct, int64_t device_size, int64_t _block_size, uint64_t max_mem, std::string_view name) : AvlAllocator(cct, device_size, _block_size, max_mem, name) { } const char* get_type() const override { return "hybrid"; } int64_t allocate( uint64_t want, uint64_t unit, uint64_t max_alloc_size, int64_t hint, PExtentVector *extents) override; void release(const interval_set<uint64_t>& release_set) override; uint64_t get_free() override; double get_fragmentation() override; void dump() override; void foreach( std::function<void(uint64_t offset, uint64_t length)> notify) override; void init_rm_free(uint64_t offset, uint64_t length) override; void shutdown() override; protected: // intended primarily for UT BitmapAllocator* get_bmap() { return bmap_alloc; } const BitmapAllocator* get_bmap() const { return bmap_alloc; } private: void _spillover_range(uint64_t start, uint64_t end) override; // called when extent to be released/marked free void _add_to_tree(uint64_t start, uint64_t size) override; };
1,427
25.444444
77
h
null
ceph-main/src/os/bluestore/StupidAllocator.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_OS_BLUESTORE_STUPIDALLOCATOR_H #define CEPH_OS_BLUESTORE_STUPIDALLOCATOR_H #include <mutex> #include "Allocator.h" #include "include/btree_map.h" #include "include/interval_set.h" #include "os/bluestore/bluestore_types.h" #include "include/mempool.h" #include "common/ceph_mutex.h" class StupidAllocator : public Allocator { CephContext* cct; ceph::mutex lock = ceph::make_mutex("StupidAllocator::lock"); int64_t num_free; ///< total bytes in freelist template <typename K, typename V> using allocator_t = mempool::bluestore_alloc::pool_allocator<std::pair<const K, V>>; template <typename K, typename V> using btree_map_t = btree::btree_map<K, V, std::less<K>, allocator_t<K, V>>; using interval_set_t = interval_set<uint64_t, btree_map_t>; std::vector<interval_set_t> free; ///< leading-edge copy uint64_t last_alloc = 0; unsigned _choose_bin(uint64_t len); void _insert_free(uint64_t offset, uint64_t len); uint64_t _aligned_len( interval_set_t::iterator p, uint64_t alloc_unit); public: StupidAllocator(CephContext* cct, int64_t size, int64_t block_size, std::string_view name); ~StupidAllocator() override; const char* get_type() const override { return "stupid"; } int64_t allocate( uint64_t want_size, uint64_t alloc_unit, uint64_t max_alloc_size, int64_t hint, PExtentVector *extents) override; int64_t allocate_int( uint64_t want_size, uint64_t alloc_unit, int64_t hint, uint64_t *offset, uint32_t *length); void release( const interval_set<uint64_t>& release_set) override; uint64_t get_free() override; double get_fragmentation() override; void dump() override; void foreach(std::function<void(uint64_t offset, uint64_t length)> notify) override; void init_add_free(uint64_t offset, uint64_t length) override; void init_rm_free(uint64_t offset, uint64_t length) override; void shutdown() override; }; #endif
2,085
27.575342
86
h
null
ceph-main/src/os/bluestore/ZonedAllocator.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab // // A simple allocator that just hands out space from the next empty zone. This // is temporary, just to get the simplest append-only write workload to work. // // Copyright (C) 2020 Abutalib Aghayev // #ifndef CEPH_OS_BLUESTORE_ZONEDALLOCATOR_H #define CEPH_OS_BLUESTORE_ZONEDALLOCATOR_H #include <mutex> #include "Allocator.h" #include "common/ceph_mutex.h" #include "include/btree_map.h" #include "include/interval_set.h" #include "include/mempool.h" #include "bluestore_types.h" #include "zoned_types.h" class ZonedAllocator : public Allocator { CephContext* cct; // Currently only one thread at a time calls into ZonedAllocator due to // atomic_alloc_and_submit_lock in BlueStore.cc, but we do locking anyway // because eventually ZONE_APPEND support will land and // atomic_alloc_and_submit_lock will be removed. ceph::mutex lock = ceph::make_mutex("ZonedAllocator::lock"); uint64_t size; uint64_t conventional_size, sequential_size; std::atomic<int64_t> num_sequential_free; ///< total bytes in freelist uint64_t block_size; uint64_t zone_size; uint64_t first_seq_zone_num; uint64_t starting_zone_num; uint64_t num_zones; std::atomic<uint32_t> cleaning_zone = -1; std::vector<zone_state_t> zone_states; inline uint64_t get_offset(uint64_t zone_num) const { return zone_num * zone_size + get_write_pointer(zone_num); } public: inline uint64_t get_write_pointer(uint64_t zone_num) const { return zone_states[zone_num].get_write_pointer(); } private: inline uint64_t get_remaining_space(uint64_t zone_num) const { return zone_size - get_write_pointer(zone_num); } inline void increment_write_pointer(uint64_t zone_num, uint64_t want_size) { zone_states[zone_num].increment_write_pointer(want_size); } inline void increment_num_dead_bytes(uint64_t zone_num, uint64_t length) { zone_states[zone_num].increment_num_dead_bytes(length); } inline bool fits(uint64_t want_size, uint64_t zone_num) const { return want_size <= get_remaining_space(zone_num); } public: ZonedAllocator(CephContext* cct, int64_t size, int64_t block_size, int64_t _zone_size, int64_t _first_sequential_zone, std::string_view name); ~ZonedAllocator() override; const char *get_type() const override { return "zoned"; } uint64_t get_dead_bytes(uint32_t zone) { return zone_states[zone].num_dead_bytes; } uint64_t get_live_bytes(uint32_t zone) { std::scoped_lock l(lock); return zone_states[zone].write_pointer - zone_states[zone].num_dead_bytes; } int64_t allocate( uint64_t want_size, uint64_t alloc_unit, uint64_t max_alloc_size, int64_t hint, PExtentVector *extents) override; void release(const interval_set<uint64_t>& release_set) override; uint64_t get_free() override; void dump() override; void foreach( std::function<void(uint64_t offset, uint64_t length)> notify) override; int64_t pick_zone_to_clean(float min_score, uint64_t min_saved); void set_cleaning_zone(uint32_t zone) { cleaning_zone = zone; } void clear_cleaning_zone(uint32_t zone) { cleaning_zone = -1; } void reset_zone(uint32_t zone); void init_from_zone_pointers( std::vector<zone_state_t> &&_zone_states); void init_add_free(uint64_t offset, uint64_t length) override {} void init_rm_free(uint64_t offset, uint64_t length) override {} void shutdown() override; private: bool low_on_space(void); }; #endif
3,557
28.404959
79
h
null
ceph-main/src/os/bluestore/ZonedFreelistManager.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab // // A freelist manager for zoned devices. // // Copyright (C) 2020 Abutalib Aghayev // #ifndef CEPH_OS_BLUESTORE_ZONEDFREELISTMANAGER_H #define CEPH_OS_BLUESTORE_ZONEDFREELISTMANAGER_H #include "FreelistManager.h" #include <string> #include <mutex> #include "common/ceph_mutex.h" #include "include/buffer.h" #include "kv/KeyValueDB.h" #include "zoned_types.h" using cfg_reader_t = std::function<int(const std::string&, std::string*)>; class ZonedFreelistManager : public FreelistManager { std::string meta_prefix; ///< device size, zone size, etc. std::string info_prefix; ///< per zone write pointer, dead bytes mutable ceph::mutex lock = ceph::make_mutex("ZonedFreelistManager::lock"); uint64_t size; ///< size of sequential region (bytes) uint64_t bytes_per_block; ///< bytes per allocation unit (bytes) uint64_t zone_size; ///< size of a single zone (bytes) uint64_t num_zones; ///< number of sequential zones uint64_t starting_zone_num; ///< the first sequential zone number KeyValueDB::Iterator enumerate_p; uint64_t enumerate_zone_num; void write_zone_state_delta_to_db(uint64_t zone_num, const zone_state_t &zone_state, KeyValueDB::Transaction txn); void write_zone_state_reset_to_db(uint64_t zone_num, const zone_state_t &zone_state, KeyValueDB::Transaction txn); void load_zone_state_from_db(uint64_t zone_num, zone_state_t &zone_state, KeyValueDB::Iterator &it) const; void init_zone_states(KeyValueDB::Transaction txn); void increment_write_pointer( uint64_t zone, uint64_t length, KeyValueDB::Transaction txn); void increment_num_dead_bytes( uint64_t zone, uint64_t num_bytes, KeyValueDB::Transaction txn); int _read_cfg(cfg_reader_t cfg_reader); public: ZonedFreelistManager(CephContext* cct, std::string meta_prefix, std::string info_prefix); static void setup_merge_operator(KeyValueDB *db, std::string prefix); int create(uint64_t size, uint64_t granularity, uint64_t zone_size, uint64_t first_sequential_zone, KeyValueDB::Transaction txn) override; int init(KeyValueDB *kvdb, bool db_in_read_only, cfg_reader_t cfg_reader) override; void shutdown() override; void sync(KeyValueDB* kvdb) override; void dump(KeyValueDB *kvdb) override; void enumerate_reset() override; bool enumerate_next(KeyValueDB *kvdb, uint64_t *offset, uint64_t *length) override; void allocate(uint64_t offset, uint64_t length, KeyValueDB::Transaction txn) override; void release(uint64_t offset, uint64_t length, KeyValueDB::Transaction txn) override; inline uint64_t get_size() const override { return size; } inline uint64_t get_alloc_units() const override { return size / bytes_per_block; } inline uint64_t get_alloc_size() const override { return bytes_per_block; } void get_meta(uint64_t target_size, std::vector<std::pair<std::string, std::string>>*) const override; std::vector<zone_state_t> get_zone_states(KeyValueDB *kvdb) const; void mark_zone_to_clean_free(uint64_t zone, KeyValueDB *kvdb); }; #endif
3,307
28.017544
76
h
null
ceph-main/src/os/bluestore/bluefs_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_OS_BLUESTORE_BLUEFS_TYPES_H #define CEPH_OS_BLUESTORE_BLUEFS_TYPES_H #include <optional> #include "bluestore_types.h" #include "include/utime.h" #include "include/encoding.h" #include "include/denc.h" class bluefs_extent_t { public: uint64_t offset = 0; uint32_t length = 0; uint8_t bdev; bluefs_extent_t(uint8_t b = 0, uint64_t o = 0, uint32_t l = 0) : offset(o), length(l), bdev(b) {} uint64_t end() const { return offset + length; } DENC(bluefs_extent_t, v, p) { DENC_START(1, 1, p); denc_lba(v.offset, p); denc_varint_lowz(v.length, p); denc(v.bdev, p); DENC_FINISH(p); } void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<bluefs_extent_t*>&); }; WRITE_CLASS_DENC(bluefs_extent_t) std::ostream& operator<<(std::ostream& out, const bluefs_extent_t& e); struct bluefs_fnode_delta_t { uint64_t ino; uint64_t size; utime_t mtime; uint64_t offset; // Contains offset in file of extents. // Equal to 'allocated' when created. // Used for consistency checking. mempool::bluefs::vector<bluefs_extent_t> extents; DENC(bluefs_fnode_delta_t, v, p) { DENC_START(1, 1, p); denc_varint(v.ino, p); denc_varint(v.size, p); denc(v.mtime, p); denc(v.offset, p); denc(v.extents, p); DENC_FINISH(p); } }; WRITE_CLASS_DENC(bluefs_fnode_delta_t) std::ostream& operator<<(std::ostream& out, const bluefs_fnode_delta_t& delta); struct bluefs_fnode_t { uint64_t ino; uint64_t size; utime_t mtime; uint8_t __unused__ = 0; // was prefer_bdev mempool::bluefs::vector<bluefs_extent_t> extents; // precalculated logical offsets for extents vector entries // allows fast lookup for extent index by the offset value via upper_bound() mempool::bluefs::vector<uint64_t> extents_index; uint64_t allocated; uint64_t allocated_commited; bluefs_fnode_t() : ino(0), size(0), allocated(0), allocated_commited(0) {} bluefs_fnode_t(uint64_t _ino, uint64_t _size, utime_t _mtime) : ino(_ino), size(_size), mtime(_mtime), allocated(0), allocated_commited(0) {} bluefs_fnode_t(const bluefs_fnode_t& other) : ino(other.ino), size(other.size), mtime(other.mtime), allocated(other.allocated), allocated_commited(other.allocated_commited) { clone_extents(other); } uint64_t get_allocated() const { return allocated; } void recalc_allocated() { allocated = 0; extents_index.reserve(extents.size()); for (auto& p : extents) { extents_index.emplace_back(allocated); allocated += p.length; } allocated_commited = allocated; } DENC_HELPERS void bound_encode(size_t& p) const { _denc_friend(*this, p); } void encode(ceph::buffer::list::contiguous_appender& p) const { DENC_DUMP_PRE(bluefs_fnode_t); _denc_friend(*this, p); } void decode(ceph::buffer::ptr::const_iterator& p) { _denc_friend(*this, p); recalc_allocated(); } template<typename T, typename P> friend std::enable_if_t<std::is_same_v<bluefs_fnode_t, std::remove_const_t<T>>> _denc_friend(T& v, P& p) { DENC_START(1, 1, p); denc_varint(v.ino, p); denc_varint(v.size, p); denc(v.mtime, p); denc(v.__unused__, p); denc(v.extents, p); DENC_FINISH(p); } void reset_delta() { allocated_commited = allocated; } void clone_extents(const bluefs_fnode_t& fnode) { for (const auto& p : fnode.extents) { append_extent(p); } } void claim_extents(mempool::bluefs::vector<bluefs_extent_t>& extents) { for (const auto& p : extents) { append_extent(p); } extents.clear(); } void append_extent(const bluefs_extent_t& ext) { if (!extents.empty() && extents.back().end() == ext.offset && extents.back().bdev == ext.bdev && (uint64_t)extents.back().length + (uint64_t)ext.length < 0xffffffff) { extents.back().length += ext.length; } else { extents_index.emplace_back(allocated); extents.push_back(ext); } allocated += ext.length; } void pop_front_extent() { auto it = extents.begin(); allocated -= it->length; extents_index.erase(extents_index.begin()); for (auto& i: extents_index) { i -= it->length; } extents.erase(it); } void swap(bluefs_fnode_t& other) { std::swap(ino, other.ino); std::swap(size, other.size); std::swap(mtime, other.mtime); swap_extents(other); } void swap_extents(bluefs_fnode_t& other) { other.extents.swap(extents); other.extents_index.swap(extents_index); std::swap(allocated, other.allocated); std::swap(allocated_commited, other.allocated_commited); } void clear_extents() { extents_index.clear(); extents.clear(); allocated = 0; allocated_commited = 0; } mempool::bluefs::vector<bluefs_extent_t>::iterator seek( uint64_t off, uint64_t *x_off); bluefs_fnode_delta_t* make_delta(bluefs_fnode_delta_t* delta); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<bluefs_fnode_t*>& ls); }; WRITE_CLASS_DENC(bluefs_fnode_t) std::ostream& operator<<(std::ostream& out, const bluefs_fnode_t& file); struct bluefs_layout_t { unsigned shared_bdev = 0; ///< which bluefs bdev we are sharing bool dedicated_db = false; ///< whether block.db is present bool dedicated_wal = false; ///< whether block.wal is present bool single_shared_device() const { return !dedicated_db && !dedicated_wal; } bool operator==(const bluefs_layout_t& other) const { return shared_bdev == other.shared_bdev && dedicated_db == other.dedicated_db && dedicated_wal == other.dedicated_wal; } void encode(ceph::buffer::list& bl) const; void decode(ceph::buffer::list::const_iterator& p); void dump(ceph::Formatter *f) const; }; WRITE_CLASS_ENCODER(bluefs_layout_t) struct bluefs_super_t { uuid_d uuid; ///< unique to this bluefs instance uuid_d osd_uuid; ///< matches the osd that owns us uint64_t version; uint32_t block_size; bluefs_fnode_t log_fnode; std::optional<bluefs_layout_t> memorized_layout; bluefs_super_t() : version(0), block_size(4096) { } uint64_t block_mask() const { return ~((uint64_t)block_size - 1); } void encode(ceph::buffer::list& bl) const; void decode(ceph::buffer::list::const_iterator& p); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<bluefs_super_t*>& ls); }; WRITE_CLASS_ENCODER(bluefs_super_t) std::ostream& operator<<(std::ostream&, const bluefs_super_t& s); struct bluefs_transaction_t { typedef enum { OP_NONE = 0, OP_INIT, ///< initial (empty) file system marker OP_ALLOC_ADD, ///< OBSOLETE: add extent to available block storage (extent) OP_ALLOC_RM, ///< OBSOLETE: remove extent from available block storage (extent) OP_DIR_LINK, ///< (re)set a dir entry (dirname, filename, ino) OP_DIR_UNLINK, ///< remove a dir entry (dirname, filename) OP_DIR_CREATE, ///< create a dir (dirname) OP_DIR_REMOVE, ///< remove a dir (dirname) OP_FILE_UPDATE, ///< set/update file metadata (file) OP_FILE_REMOVE, ///< remove file (ino) OP_JUMP, ///< jump the seq # and offset OP_JUMP_SEQ, ///< jump the seq # OP_FILE_UPDATE_INC, ///< incremental update file metadata (file) } op_t; uuid_d uuid; ///< fs uuid uint64_t seq; ///< sequence number ceph::buffer::list op_bl; ///< encoded transaction ops bluefs_transaction_t() : seq(0) {} void clear() { *this = bluefs_transaction_t(); } bool empty() const { return op_bl.length() == 0; } void op_init() { using ceph::encode; encode((__u8)OP_INIT, op_bl); } void op_dir_create(std::string_view dir) { using ceph::encode; encode((__u8)OP_DIR_CREATE, op_bl); encode(dir, op_bl); } void op_dir_remove(std::string_view dir) { using ceph::encode; encode((__u8)OP_DIR_REMOVE, op_bl); encode(dir, op_bl); } void op_dir_link(std::string_view dir, std::string_view file, uint64_t ino) { using ceph::encode; encode((__u8)OP_DIR_LINK, op_bl); encode(dir, op_bl); encode(file, op_bl); encode(ino, op_bl); } void op_dir_unlink(std::string_view dir, std::string_view file) { using ceph::encode; encode((__u8)OP_DIR_UNLINK, op_bl); encode(dir, op_bl); encode(file, op_bl); } void op_file_update(bluefs_fnode_t& file) { using ceph::encode; encode((__u8)OP_FILE_UPDATE, op_bl); encode(file, op_bl); file.reset_delta(); } /* streams update to bufferlist and clears update state */ void op_file_update_inc(bluefs_fnode_t& file) { using ceph::encode; bluefs_fnode_delta_t delta; file.make_delta(&delta); encode((__u8)OP_FILE_UPDATE_INC, op_bl); encode(delta, op_bl); file.reset_delta(); } void op_file_remove(uint64_t ino) { using ceph::encode; encode((__u8)OP_FILE_REMOVE, op_bl); encode(ino, op_bl); } void op_jump(uint64_t next_seq, uint64_t offset) { using ceph::encode; encode((__u8)OP_JUMP, op_bl); encode(next_seq, op_bl); encode(offset, op_bl); } void op_jump_seq(uint64_t next_seq) { using ceph::encode; encode((__u8)OP_JUMP_SEQ, op_bl); encode(next_seq, op_bl); } void claim_ops(bluefs_transaction_t& from) { op_bl.claim_append(from.op_bl); } void encode(ceph::buffer::list& bl) const; void decode(ceph::buffer::list::const_iterator& p); void dump(ceph::Formatter *f) const; static void generate_test_instances(std::list<bluefs_transaction_t*>& ls); }; WRITE_CLASS_ENCODER(bluefs_transaction_t) std::ostream& operator<<(std::ostream& out, const bluefs_transaction_t& t); #endif
9,900
28.120588
86
h
null
ceph-main/src/os/bluestore/bluestore_common.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 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. * */ #ifndef CEPH_OSD_BLUESTORE_COMMON_H #define CEPH_OSD_BLUESTORE_COMMON_H #include "include/intarith.h" #include "include/ceph_assert.h" #include "kv/KeyValueDB.h" template <class Bitset, class Func> void apply_for_bitset_range(uint64_t off, uint64_t len, uint64_t granularity, Bitset &bitset, Func f) { auto end = round_up_to(off + len, granularity) / granularity; ceph_assert(end <= bitset.size()); uint64_t pos = off / granularity; while (pos < end) { f(pos, bitset); pos++; } } // merge operators struct Int64ArrayMergeOperator : public KeyValueDB::MergeOperator { void merge_nonexistent( const char *rdata, size_t rlen, std::string *new_value) override { *new_value = std::string(rdata, rlen); } void merge( const char *ldata, size_t llen, const char *rdata, size_t rlen, std::string *new_value) override { ceph_assert(llen == rlen); ceph_assert((rlen % 8) == 0); new_value->resize(rlen); const ceph_le64* lv = (const ceph_le64*)ldata; const ceph_le64* rv = (const ceph_le64*)rdata; ceph_le64* nv = &(ceph_le64&)new_value->at(0); for (size_t i = 0; i < rlen >> 3; ++i) { nv[i] = lv[i] + rv[i]; } } // We use each operator name and each prefix to construct the // overall RocksDB operator name for consistency check at open time. const char *name() const override { return "int64_array"; } }; #endif
1,810
26.439394
70
h
null
ceph-main/src/os/bluestore/fastbmap_allocator_impl.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Bitmap based in-memory allocator implementation. * Author: Igor Fedotov, [email protected] * */ #ifndef __FAST_BITMAP_ALLOCATOR_IMPL_H #define __FAST_BITMAP_ALLOCATOR_IMPL_H #include "include/intarith.h" #include <bit> #include <vector> #include <algorithm> #include <mutex> typedef uint64_t slot_t; #ifdef NON_CEPH_BUILD #include <assert.h> struct interval_t { uint64_t offset = 0; uint64_t length = 0; interval_t() {} interval_t(uint64_t o, uint64_t l) : offset(o), length(l) {} interval_t(const interval_t &ext) : offset(ext.offset), length(ext.length) {} }; typedef std::vector<interval_t> interval_vector_t; typedef std::vector<slot_t> slot_vector_t; #else #include "include/ceph_assert.h" #include "common/likely.h" #include "os/bluestore/bluestore_types.h" #include "include/mempool.h" #include "common/ceph_mutex.h" typedef bluestore_interval_t<uint64_t, uint64_t> interval_t; typedef PExtentVector interval_vector_t; typedef mempool::bluestore_alloc::vector<slot_t> slot_vector_t; #endif // fitting into cache line on x86_64 static const size_t slots_per_slotset = 8; // 8 slots per set static const size_t slotset_bytes = sizeof(slot_t) * slots_per_slotset; static const size_t bits_per_slot = sizeof(slot_t) * 8; static const size_t bits_per_slotset = slotset_bytes * 8; static const slot_t all_slot_set = 0xffffffffffffffff; static const slot_t all_slot_clear = 0; inline size_t find_next_set_bit(slot_t slot_val, size_t start_pos) { #ifdef __GNUC__ if (start_pos == 0) { start_pos = __builtin_ffsll(slot_val); return start_pos ? start_pos - 1 : bits_per_slot; } #endif slot_t mask = slot_t(1) << start_pos; while (start_pos < bits_per_slot && !(slot_val & mask)) { mask <<= 1; ++start_pos; } return start_pos; } class AllocatorLevel { protected: virtual uint64_t _children_per_slot() const = 0; virtual uint64_t _level_granularity() const = 0; public: static uint64_t l0_dives; static uint64_t l0_iterations; static uint64_t l0_inner_iterations; static uint64_t alloc_fragments; static uint64_t alloc_fragments_fast; static uint64_t l2_allocs; virtual ~AllocatorLevel() {} virtual void collect_stats( std::map<size_t, size_t>& bins_overall) = 0; }; class AllocatorLevel01 : public AllocatorLevel { protected: slot_vector_t l0; // set bit means free entry slot_vector_t l1; uint64_t l0_granularity = 0; // space per entry uint64_t l1_granularity = 0; // space per entry size_t partial_l1_count = 0; size_t unalloc_l1_count = 0; double get_fragmentation() const { double res = 0.0; auto total = unalloc_l1_count + partial_l1_count; if (total) { res = double(partial_l1_count) / double(total); } return res; } uint64_t _level_granularity() const override { return l1_granularity; } inline bool _is_slot_fully_allocated(uint64_t idx) const { return l1[idx] == all_slot_clear; } public: inline uint64_t get_min_alloc_size() const { return l0_granularity; } }; template <class T> class AllocatorLevel02; class AllocatorLevel01Loose : public AllocatorLevel01 { enum { L1_ENTRY_WIDTH = 2, L1_ENTRY_MASK = (1 << L1_ENTRY_WIDTH) - 1, L1_ENTRY_FULL = 0x00, L1_ENTRY_PARTIAL = 0x01, L1_ENTRY_NOT_USED = 0x02, L1_ENTRY_FREE = 0x03, L1_ENTRIES_PER_SLOT = bits_per_slot / L1_ENTRY_WIDTH, //32 L0_ENTRIES_PER_SLOT = bits_per_slot, // 64 }; uint64_t _children_per_slot() const override { return L1_ENTRIES_PER_SLOT; } interval_t _get_longest_from_l0(uint64_t pos0, uint64_t pos1, uint64_t min_length, interval_t* tail) const; inline void _fragment_and_emplace(uint64_t max_length, uint64_t offset, uint64_t len, interval_vector_t* res) { auto it = res->rbegin(); if (max_length) { if (it != res->rend() && it->offset + it->length == offset) { auto l = max_length - it->length; if (l >= len) { it->length += len; return; } else { offset += l; len -= l; it->length += l; } } while (len > max_length) { res->emplace_back(offset, max_length); offset += max_length; len -= max_length; } res->emplace_back(offset, len); return; } if (it != res->rend() && it->offset + it->length == offset) { it->length += len; } else { res->emplace_back(offset, len); } } bool _allocate_l0(uint64_t length, uint64_t max_length, uint64_t l0_pos0, uint64_t l0_pos1, uint64_t* allocated, interval_vector_t* res) { uint64_t d0 = L0_ENTRIES_PER_SLOT; ++l0_dives; ceph_assert(l0_pos0 < l0_pos1); ceph_assert(length > *allocated); ceph_assert(0 == (l0_pos0 % (slots_per_slotset * d0))); ceph_assert(0 == (l0_pos1 % (slots_per_slotset * d0))); ceph_assert(((length - *allocated) % l0_granularity) == 0); uint64_t need_entries = (length - *allocated) / l0_granularity; for (auto idx = l0_pos0 / d0; (idx < l0_pos1 / d0) && (length > *allocated); ++idx) { ++l0_iterations; slot_t& slot_val = l0[idx]; auto base = idx * d0; if (slot_val == all_slot_clear) { continue; } else if (slot_val == all_slot_set) { uint64_t to_alloc = std::min(need_entries, d0); *allocated += to_alloc * l0_granularity; ++alloc_fragments; need_entries -= to_alloc; _fragment_and_emplace(max_length, base * l0_granularity, to_alloc * l0_granularity, res); if (to_alloc == d0) { slot_val = all_slot_clear; } else { _mark_alloc_l0(base, base + to_alloc); } continue; } auto free_pos = find_next_set_bit(slot_val, 0); ceph_assert(free_pos < bits_per_slot); auto next_pos = free_pos + 1; while (next_pos < bits_per_slot && (next_pos - free_pos) < need_entries) { ++l0_inner_iterations; if (0 == (slot_val & (slot_t(1) << next_pos))) { auto to_alloc = (next_pos - free_pos); *allocated += to_alloc * l0_granularity; ++alloc_fragments; need_entries -= to_alloc; _fragment_and_emplace(max_length, (base + free_pos) * l0_granularity, to_alloc * l0_granularity, res); _mark_alloc_l0(base + free_pos, base + next_pos); free_pos = find_next_set_bit(slot_val, next_pos + 1); next_pos = free_pos + 1; } else { ++next_pos; } } if (need_entries && free_pos < bits_per_slot) { auto to_alloc = std::min(need_entries, d0 - free_pos); *allocated += to_alloc * l0_granularity; ++alloc_fragments; need_entries -= to_alloc; _fragment_and_emplace(max_length, (base + free_pos) * l0_granularity, to_alloc * l0_granularity, res); _mark_alloc_l0(base + free_pos, base + free_pos + to_alloc); } } return _is_empty_l0(l0_pos0, l0_pos1); } protected: friend class AllocatorLevel02<AllocatorLevel01Loose>; void _init(uint64_t capacity, uint64_t _alloc_unit, bool mark_as_free = true) { l0_granularity = _alloc_unit; // 512 bits at L0 mapped to L1 entry l1_granularity = l0_granularity * bits_per_slotset; // capacity to have slot alignment at l1 auto aligned_capacity = p2roundup((int64_t)capacity, int64_t(l1_granularity * slots_per_slotset * _children_per_slot())); size_t slot_count = aligned_capacity / l1_granularity / _children_per_slot(); // we use set bit(s) as a marker for (partially) free entry l1.resize(slot_count, mark_as_free ? all_slot_set : all_slot_clear); // l0 slot count size_t slot_count_l0 = aligned_capacity / _alloc_unit / bits_per_slot; // we use set bit(s) as a marker for (partially) free entry l0.resize(slot_count_l0, mark_as_free ? all_slot_set : all_slot_clear); partial_l1_count = unalloc_l1_count = 0; if (mark_as_free) { unalloc_l1_count = slot_count * _children_per_slot(); auto l0_pos_no_use = p2roundup((int64_t)capacity, (int64_t)l0_granularity) / l0_granularity; _mark_alloc_l1_l0(l0_pos_no_use, aligned_capacity / l0_granularity); } } struct search_ctx_t { size_t partial_count = 0; size_t free_count = 0; uint64_t free_l1_pos = 0; uint64_t min_affordable_len = 0; uint64_t min_affordable_offs = 0; uint64_t affordable_len = 0; uint64_t affordable_offs = 0; bool fully_processed = false; void reset() { *this = search_ctx_t(); } }; enum { NO_STOP, STOP_ON_EMPTY, STOP_ON_PARTIAL, }; void _analyze_partials(uint64_t pos_start, uint64_t pos_end, uint64_t length, uint64_t min_length, int mode, search_ctx_t* ctx); void _mark_l1_on_l0(int64_t l0_pos, int64_t l0_pos_end); void _mark_alloc_l0(int64_t l0_pos_start, int64_t l0_pos_end); uint64_t _claim_free_to_left_l0(int64_t l0_pos_start); uint64_t _claim_free_to_right_l0(int64_t l0_pos_start); void _mark_alloc_l1_l0(int64_t l0_pos_start, int64_t l0_pos_end) { _mark_alloc_l0(l0_pos_start, l0_pos_end); l0_pos_start = p2align(l0_pos_start, int64_t(bits_per_slotset)); l0_pos_end = p2roundup(l0_pos_end, int64_t(bits_per_slotset)); _mark_l1_on_l0(l0_pos_start, l0_pos_end); } void _mark_free_l0(int64_t l0_pos_start, int64_t l0_pos_end) { auto d0 = L0_ENTRIES_PER_SLOT; auto pos = l0_pos_start; slot_t bits = (slot_t)1 << (l0_pos_start % d0); slot_t* val_s = &l0[pos / d0]; int64_t pos_e = std::min(l0_pos_end, p2roundup<int64_t>(l0_pos_start + 1, d0)); while (pos < pos_e) { *val_s |= bits; bits <<= 1; pos++; } pos_e = std::min(l0_pos_end, p2align<int64_t>(l0_pos_end, d0)); while (pos < pos_e) { *(++val_s) = all_slot_set; pos += d0; } bits = 1; ++val_s; while (pos < l0_pos_end) { *val_s |= bits; bits <<= 1; pos++; } } void _mark_free_l1_l0(int64_t l0_pos_start, int64_t l0_pos_end) { _mark_free_l0(l0_pos_start, l0_pos_end); l0_pos_start = p2align(l0_pos_start, int64_t(bits_per_slotset)); l0_pos_end = p2roundup(l0_pos_end, int64_t(bits_per_slotset)); _mark_l1_on_l0(l0_pos_start, l0_pos_end); } bool _is_empty_l0(uint64_t l0_pos, uint64_t l0_pos_end) { bool no_free = true; uint64_t d = slots_per_slotset * L0_ENTRIES_PER_SLOT; ceph_assert(0 == (l0_pos % d)); ceph_assert(0 == (l0_pos_end % d)); auto idx = l0_pos / L0_ENTRIES_PER_SLOT; auto idx_end = l0_pos_end / L0_ENTRIES_PER_SLOT; while (idx < idx_end && no_free) { no_free = l0[idx] == all_slot_clear; ++idx; } return no_free; } bool _is_empty_l1(uint64_t l1_pos, uint64_t l1_pos_end) { bool no_free = true; uint64_t d = slots_per_slotset * _children_per_slot(); ceph_assert(0 == (l1_pos % d)); ceph_assert(0 == (l1_pos_end % d)); auto idx = l1_pos / L1_ENTRIES_PER_SLOT; auto idx_end = l1_pos_end / L1_ENTRIES_PER_SLOT; while (idx < idx_end && no_free) { no_free = _is_slot_fully_allocated(idx); ++idx; } return no_free; } interval_t _allocate_l1_contiguous(uint64_t length, uint64_t min_length, uint64_t max_length, uint64_t pos_start, uint64_t pos_end); bool _allocate_l1(uint64_t length, uint64_t min_length, uint64_t max_length, uint64_t l1_pos_start, uint64_t l1_pos_end, uint64_t* allocated, interval_vector_t* res); uint64_t _mark_alloc_l1(uint64_t offset, uint64_t length) { uint64_t l0_pos_start = offset / l0_granularity; uint64_t l0_pos_end = p2roundup(offset + length, l0_granularity) / l0_granularity; _mark_alloc_l1_l0(l0_pos_start, l0_pos_end); return l0_granularity * (l0_pos_end - l0_pos_start); } uint64_t _free_l1(uint64_t offs, uint64_t len) { uint64_t l0_pos_start = offs / l0_granularity; uint64_t l0_pos_end = p2roundup(offs + len, l0_granularity) / l0_granularity; _mark_free_l1_l0(l0_pos_start, l0_pos_end); return l0_granularity * (l0_pos_end - l0_pos_start); } uint64_t claim_free_to_left_l1(uint64_t offs) { uint64_t l0_pos_end = offs / l0_granularity; uint64_t l0_pos_start = _claim_free_to_left_l0(l0_pos_end); if (l0_pos_start < l0_pos_end) { _mark_l1_on_l0( p2align(l0_pos_start, uint64_t(bits_per_slotset)), p2roundup(l0_pos_end, uint64_t(bits_per_slotset))); return l0_granularity * (l0_pos_end - l0_pos_start); } return 0; } uint64_t claim_free_to_right_l1(uint64_t offs) { uint64_t l0_pos_start = offs / l0_granularity; uint64_t l0_pos_end = _claim_free_to_right_l0(l0_pos_start); if (l0_pos_start < l0_pos_end) { _mark_l1_on_l0( p2align(l0_pos_start, uint64_t(bits_per_slotset)), p2roundup(l0_pos_end, uint64_t(bits_per_slotset))); return l0_granularity * (l0_pos_end - l0_pos_start); } return 0; } public: uint64_t debug_get_allocated(uint64_t pos0 = 0, uint64_t pos1 = 0) { if (pos1 == 0) { pos1 = l1.size() * L1_ENTRIES_PER_SLOT; } auto avail = debug_get_free(pos0, pos1); return (pos1 - pos0) * l1_granularity - avail; } uint64_t debug_get_free(uint64_t l1_pos0 = 0, uint64_t l1_pos1 = 0) { ceph_assert(0 == (l1_pos0 % L1_ENTRIES_PER_SLOT)); ceph_assert(0 == (l1_pos1 % L1_ENTRIES_PER_SLOT)); auto idx0 = l1_pos0 * slots_per_slotset; auto idx1 = l1_pos1 * slots_per_slotset; if (idx1 == 0) { idx1 = l0.size(); } uint64_t res = 0; for (uint64_t i = idx0; i < idx1; ++i) { auto v = l0[i]; if (v == all_slot_set) { res += L0_ENTRIES_PER_SLOT; } else if (v != all_slot_clear) { size_t cnt = 0; #ifdef __GNUC__ cnt = __builtin_popcountll(v); #else // Kernighan's Alg to count set bits while (v) { v &= (v - 1); cnt++; } #endif res += cnt; } } return res * l0_granularity; } void collect_stats( std::map<size_t, size_t>& bins_overall) override; static inline ssize_t count_0s(slot_t slot_val, size_t start_pos); static inline ssize_t count_1s(slot_t slot_val, size_t start_pos); void foreach_internal(std::function<void(uint64_t offset, uint64_t length)> notify); }; class AllocatorLevel01Compact : public AllocatorLevel01 { uint64_t _children_per_slot() const override { return 8; } public: void collect_stats( std::map<size_t, size_t>& bins_overall) override { // not implemented } }; template <class L1> class AllocatorLevel02 : public AllocatorLevel { public: uint64_t debug_get_free(uint64_t pos0 = 0, uint64_t pos1 = 0) { std::lock_guard l(lock); return l1.debug_get_free(pos0 * l1._children_per_slot() * bits_per_slot, pos1 * l1._children_per_slot() * bits_per_slot); } uint64_t debug_get_allocated(uint64_t pos0 = 0, uint64_t pos1 = 0) { std::lock_guard l(lock); return l1.debug_get_allocated(pos0 * l1._children_per_slot() * bits_per_slot, pos1 * l1._children_per_slot() * bits_per_slot); } uint64_t get_available() { std::lock_guard l(lock); return available; } inline uint64_t get_min_alloc_size() const { return l1.get_min_alloc_size(); } void collect_stats( std::map<size_t, size_t>& bins_overall) override { std::lock_guard l(lock); l1.collect_stats(bins_overall); } uint64_t claim_free_to_left(uint64_t offset) { std::lock_guard l(lock); auto allocated = l1.claim_free_to_left_l1(offset); ceph_assert(available >= allocated); available -= allocated; uint64_t l2_pos = (offset - allocated) / l2_granularity; uint64_t l2_pos_end = p2roundup(int64_t(offset), int64_t(l2_granularity)) / l2_granularity; _mark_l2_on_l1(l2_pos, l2_pos_end); return allocated; } uint64_t claim_free_to_right(uint64_t offset) { std::lock_guard l(lock); auto allocated = l1.claim_free_to_right_l1(offset); ceph_assert(available >= allocated); available -= allocated; uint64_t l2_pos = (offset) / l2_granularity; int64_t end = offset + allocated; uint64_t l2_pos_end = p2roundup(end, int64_t(l2_granularity)) / l2_granularity; _mark_l2_on_l1(l2_pos, l2_pos_end); return allocated; } void foreach_internal( std::function<void(uint64_t offset, uint64_t length)> notify) { size_t alloc_size = get_min_alloc_size(); auto multiply_by_alloc_size = [alloc_size, notify](size_t off, size_t len) { notify(off * alloc_size, len * alloc_size); }; std::lock_guard l(lock); l1.foreach_internal(multiply_by_alloc_size); } double get_fragmentation_internal() { std::lock_guard l(lock); return l1.get_fragmentation(); } protected: ceph::mutex lock = ceph::make_mutex("AllocatorLevel02::lock"); L1 l1; slot_vector_t l2; uint64_t l2_granularity = 0; // space per entry uint64_t available = 0; uint64_t last_pos = 0; enum { L1_ENTRIES_PER_SLOT = bits_per_slot, // 64 }; uint64_t _children_per_slot() const override { return L1_ENTRIES_PER_SLOT; } uint64_t _level_granularity() const override { return l2_granularity; } void _init(uint64_t capacity, uint64_t _alloc_unit, bool mark_as_free = true) { ceph_assert(std::has_single_bit(_alloc_unit)); l1._init(capacity, _alloc_unit, mark_as_free); l2_granularity = l1._level_granularity() * l1._children_per_slot() * slots_per_slotset; // capacity to have slot alignment at l2 auto aligned_capacity = p2roundup((int64_t)capacity, (int64_t)l2_granularity * L1_ENTRIES_PER_SLOT); size_t elem_count = aligned_capacity / l2_granularity / L1_ENTRIES_PER_SLOT; // we use set bit(s) as a marker for (partially) free entry l2.resize(elem_count, mark_as_free ? all_slot_set : all_slot_clear); if (mark_as_free) { // capacity to have slotset alignment at l1 auto l2_pos_no_use = p2roundup((int64_t)capacity, (int64_t)l2_granularity) / l2_granularity; _mark_l2_allocated(l2_pos_no_use, aligned_capacity / l2_granularity); available = p2align(capacity, _alloc_unit); } else { available = 0; } } void _mark_l2_allocated(int64_t l2_pos, int64_t l2_pos_end) { auto d = L1_ENTRIES_PER_SLOT; ceph_assert(0 <= l2_pos_end); ceph_assert((int64_t)l2.size() >= (l2_pos_end / d)); while (l2_pos < l2_pos_end) { l2[l2_pos / d] &= ~(slot_t(1) << (l2_pos % d)); ++l2_pos; } } void _mark_l2_free(int64_t l2_pos, int64_t l2_pos_end) { auto d = L1_ENTRIES_PER_SLOT; ceph_assert(0 <= l2_pos_end); ceph_assert((int64_t)l2.size() >= (l2_pos_end / d)); while (l2_pos < l2_pos_end) { l2[l2_pos / d] |= (slot_t(1) << (l2_pos % d)); ++l2_pos; } } void _mark_l2_on_l1(int64_t l2_pos, int64_t l2_pos_end) { auto d = L1_ENTRIES_PER_SLOT; ceph_assert(0 <= l2_pos_end); ceph_assert((int64_t)l2.size() >= (l2_pos_end / d)); auto idx = l2_pos * slots_per_slotset; auto idx_end = l2_pos_end * slots_per_slotset; bool all_allocated = true; while (idx < idx_end) { if (!l1._is_slot_fully_allocated(idx)) { all_allocated = false; idx = p2roundup(int64_t(++idx), int64_t(slots_per_slotset)); } else { ++idx; } if ((idx % slots_per_slotset) == 0) { if (all_allocated) { l2[l2_pos / d] &= ~(slot_t(1) << (l2_pos % d)); } else { l2[l2_pos / d] |= (slot_t(1) << (l2_pos % d)); } all_allocated = true; ++l2_pos; } } } void _allocate_l2(uint64_t length, uint64_t min_length, uint64_t max_length, uint64_t hint, uint64_t* allocated, interval_vector_t* res) { uint64_t prev_allocated = *allocated; uint64_t d = L1_ENTRIES_PER_SLOT; ceph_assert(min_length <= l2_granularity); ceph_assert(max_length == 0 || max_length >= min_length); ceph_assert(max_length == 0 || (max_length % min_length) == 0); ceph_assert(length >= min_length); ceph_assert((length % min_length) == 0); uint64_t cap = 1ull << 31; if (max_length == 0 || max_length >= cap) { max_length = cap; } uint64_t l1_w = slots_per_slotset * l1._children_per_slot(); std::lock_guard l(lock); if (available < min_length) { return; } if (hint != 0) { last_pos = (hint / (d * l2_granularity)) < l2.size() ? p2align(hint / l2_granularity, d) : 0; } auto l2_pos = last_pos; auto last_pos0 = last_pos; auto pos = last_pos / d; auto pos_end = l2.size(); // outer loop below is intended to optimize the performance by // avoiding 'modulo' operations inside the internal loop. // Looks like they have negative impact on the performance for (auto i = 0; i < 2; ++i) { for(; length > *allocated && pos < pos_end; ++pos) { slot_t& slot_val = l2[pos]; size_t free_pos = 0; bool all_set = false; if (slot_val == all_slot_clear) { l2_pos += d; last_pos = l2_pos; continue; } else if (slot_val == all_slot_set) { free_pos = 0; all_set = true; } else { free_pos = find_next_set_bit(slot_val, 0); ceph_assert(free_pos < bits_per_slot); } do { ceph_assert(length > *allocated); bool empty = l1._allocate_l1(length, min_length, max_length, (l2_pos + free_pos) * l1_w, (l2_pos + free_pos + 1) * l1_w, allocated, res); if (empty) { slot_val &= ~(slot_t(1) << free_pos); } if (length <= *allocated || slot_val == all_slot_clear) { break; } ++free_pos; if (!all_set) { free_pos = find_next_set_bit(slot_val, free_pos); } } while (free_pos < bits_per_slot); last_pos = l2_pos; l2_pos += d; } l2_pos = 0; pos = 0; pos_end = last_pos0 / d; } ++l2_allocs; auto allocated_here = *allocated - prev_allocated; ceph_assert(available >= allocated_here); available -= allocated_here; } #ifndef NON_CEPH_BUILD // to provide compatibility with BlueStore's allocator interface void _free_l2(const interval_set<uint64_t> & rr) { uint64_t released = 0; std::lock_guard l(lock); for (auto r : rr) { released += l1._free_l1(r.first, r.second); uint64_t l2_pos = r.first / l2_granularity; uint64_t l2_pos_end = p2roundup(int64_t(r.first + r.second), int64_t(l2_granularity)) / l2_granularity; _mark_l2_free(l2_pos, l2_pos_end); } available += released; } #endif template <typename T> void _free_l2(const T& rr) { uint64_t released = 0; std::lock_guard l(lock); for (auto r : rr) { released += l1._free_l1(r.offset, r.length); uint64_t l2_pos = r.offset / l2_granularity; uint64_t l2_pos_end = p2roundup(int64_t(r.offset + r.length), int64_t(l2_granularity)) / l2_granularity; _mark_l2_free(l2_pos, l2_pos_end); } available += released; } void _mark_allocated(uint64_t o, uint64_t len) { uint64_t l2_pos = o / l2_granularity; uint64_t l2_pos_end = p2roundup(int64_t(o + len), int64_t(l2_granularity)) / l2_granularity; std::lock_guard l(lock); auto allocated = l1._mark_alloc_l1(o, len); ceph_assert(available >= allocated); available -= allocated; _mark_l2_on_l1(l2_pos, l2_pos_end); } void _mark_free(uint64_t o, uint64_t len) { uint64_t l2_pos = o / l2_granularity; uint64_t l2_pos_end = p2roundup(int64_t(o + len), int64_t(l2_granularity)) / l2_granularity; std::lock_guard l(lock); available += l1._free_l1(o, len); _mark_l2_free(l2_pos, l2_pos_end); } void _shutdown() { last_pos = 0; } }; #endif
23,826
27.131051
110
h
null
ceph-main/src/os/bluestore/simple_bitmap.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 * * Author: Gabriel BenHanokh <[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 <cstdint> #include <iostream> #include <string> #include <cstring> #include <cmath> #include <iomanip> #include "include/ceph_assert.h" struct extent_t { uint64_t offset; uint64_t length; bool operator==(const extent_t& other) const { return (this->offset == other.offset && this->length == other.length); } }; class SimpleBitmap { public: SimpleBitmap(CephContext *_cct, uint64_t num_bits); ~SimpleBitmap(); SimpleBitmap(const SimpleBitmap&) = delete; SimpleBitmap& operator=(const SimpleBitmap&) = delete; // set a bit range range of @length starting at @offset bool set(uint64_t offset, uint64_t length); // clear a bit range range of @length starting at @offset bool clr(uint64_t offset, uint64_t length); // returns a copy of the next set extent starting at @offset extent_t get_next_set_extent(uint64_t offset); // returns a copy of the next clear extent starting at @offset extent_t get_next_clr_extent(uint64_t offset); //---------------------------------------------------------------------------- inline uint64_t get_size() { return m_num_bits; } //---------------------------------------------------------------------------- // clears all bits in the bitmap inline void clear_all() { std::memset(m_arr, 0, words_to_bytes(m_word_count)); } //---------------------------------------------------------------------------- // sets all bits in the bitmap inline void set_all() { std::memset(m_arr, 0xFF, words_to_bytes(m_word_count)); // clear bits in the last word past the last legal bit uint64_t incomplete_word_bit_offset = (m_num_bits & BITS_IN_WORD_MASK); if (incomplete_word_bit_offset) { uint64_t clr_mask = ~(FULL_MASK << incomplete_word_bit_offset); m_arr[m_word_count - 1] &= clr_mask; } } //---------------------------------------------------------------------------- bool bit_is_set(uint64_t offset) { if (offset < m_num_bits) { auto [word_index, bit_offset] = split(offset); uint64_t mask = 1ULL << bit_offset; return (m_arr[word_index] & mask); } else { ceph_assert(offset < m_num_bits); return false; } } //---------------------------------------------------------------------------- bool bit_is_clr(uint64_t offset) { if (offset < m_num_bits) { auto [word_index, bit_offset] = split(offset); uint64_t mask = 1ULL << bit_offset; return ( (m_arr[word_index] & mask) == 0 ); } else { ceph_assert(offset < m_num_bits); return false; } } private: //---------------------------------------------------------------------------- static inline std::pair<uint64_t, uint64_t> split(uint64_t offset) { return { offset_to_index(offset), (offset & BITS_IN_WORD_MASK) }; } //--------------------------------------------------------------------------- static inline uint64_t offset_to_index(uint64_t offset) { return offset >> BITS_IN_WORD_SHIFT; } //--------------------------------------------------------------------------- static inline uint64_t index_to_offset(uint64_t index) { return index << BITS_IN_WORD_SHIFT; } //--------------------------------------------------------------------------- static inline uint64_t bits_to_words(uint64_t bit_count) { return bit_count >> BITS_IN_WORD_SHIFT; } //--------------------------------------------------------------------------- static inline uint64_t words_to_bits(uint64_t words_count) { return words_count << BITS_IN_WORD_SHIFT; } //--------------------------------------------------------------------------- static inline uint64_t bytes_to_words(uint64_t byte_count) { return byte_count >> BYTES_IN_WORD_SHIFT; } //--------------------------------------------------------------------------- static inline uint64_t words_to_bytes(uint64_t words_count) { return (words_count << BYTES_IN_WORD_SHIFT); } constexpr static uint64_t BYTES_IN_WORD = sizeof(uint64_t); constexpr static uint64_t BYTES_IN_WORD_SHIFT = 3; constexpr static uint64_t BITS_IN_WORD = (BYTES_IN_WORD * 8); constexpr static uint64_t BITS_IN_WORD_MASK = (BITS_IN_WORD - 1); constexpr static uint64_t BITS_IN_WORD_SHIFT = 6; constexpr static uint64_t FULL_MASK = (~((uint64_t)0)); CephContext *cct; uint64_t *m_arr; uint64_t m_num_bits; uint64_t m_word_count; };
4,928
32.530612
80
h
null
ceph-main/src/os/bluestore/zoned_types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_OS_BLUESTORE_ZONED_TYPES_H #define CEPH_OS_BLUESTORE_ZONED_TYPES_H #include "include/types.h" #include "kv/KeyValueDB.h" #include "os/kv.h" // Tracks two bits of information about the state of a zone: (1) number of dead // bytes in a zone and (2) the write pointer. We use the existing // Int64ArrayMergeOperator for merge and avoid the cost of point queries. // // We use the same struct for an on-disk and in-memory representation of the // state. struct zone_state_t { uint64_t num_dead_bytes = 0; ///< dead bytes deallocated (behind the write pointer) uint64_t write_pointer = 0; ///< relative offset within the zone void encode(ceph::buffer::list &bl) const { using ceph::encode; encode(write_pointer, bl); encode(num_dead_bytes, bl); } void decode(ceph::buffer::list::const_iterator &p) { using ceph::decode; decode(write_pointer, p); decode(num_dead_bytes, p); } void reset() { write_pointer = 0; num_dead_bytes = 0; } uint64_t get_num_dead_bytes() const { return num_dead_bytes; } uint64_t get_num_live_bytes() const { return write_pointer - num_dead_bytes; } uint64_t get_write_pointer() const { return write_pointer; } void increment_num_dead_bytes(uint64_t num_bytes) { num_dead_bytes += num_bytes; } void increment_write_pointer(uint64_t num_bytes) { write_pointer += num_bytes; } friend std::ostream& operator<<( std::ostream& out, const zone_state_t& zone_state) { return out << std::hex << " dead bytes: 0x" << zone_state.get_num_dead_bytes() << " write pointer: 0x" << zone_state.get_write_pointer() << " " << std::dec; } }; #endif
1,803
25.925373
86
h
null
ceph-main/src/os/fs/FS.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 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. * */ #ifndef CEPH_OS_FS_H #define CEPH_OS_FS_H #include <errno.h> #include <time.h> #include <string> #include "include/types.h" #include "common/Cond.h" class FS { public: virtual ~FS() { } static FS *create(uint64_t f_type); static FS *create_by_fd(int fd); virtual const char *get_name() { return "generic"; } virtual int set_alloc_hint(int fd, uint64_t hint); virtual int get_handle(int fd, std::string *h); virtual int open_handle(int mount_fd, const std::string& h, int flags); virtual int copy_file_range(int to_fd, uint64_t to_offset, int from_fd, uint64_t from_offset, uint64_t from_len); virtual int zero(int fd, uint64_t offset, uint64_t length); // -- aio -- }; #endif
1,130
21.176471
73
h
null
ceph-main/src/os/fs/XFS.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 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. * */ #ifndef CEPH_OS_XFS_H #define CEPH_OS_XFS_H #include "FS.h" # ifndef XFS_SUPER_MAGIC #define XFS_SUPER_MAGIC 0x58465342 # endif class XFS : public FS { const char *get_name() override { return "xfs"; } int set_alloc_hint(int fd, uint64_t hint) override; }; #endif
677
20.1875
70
h
null
ceph-main/src/os/fs/ZFS.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_ZFS_H #define CEPH_ZFS_H // Simple wrapper to hide libzfs.h. (it conflicts with standard linux headers) class ZFS { void *g_zfs; public: static const int TYPE_FILESYSTEM; static const int TYPE_SNAPSHOT; static const int TYPE_VOLUME; static const int TYPE_POOL; static const int TYPE_DATASET; typedef void Handle; typedef int (*iter_func)(Handle *, void *); static const char *get_name(Handle *); ZFS() : g_zfs(NULL) {} ~ZFS(); int init(); Handle *open(const char *, int); void close(Handle *); Handle *path_to_zhandle(const char *, int); int create(const char *, int); int snapshot(const char *, bool); int rollback(Handle *, Handle *, bool); int destroy_snaps(Handle *, const char *, bool); int iter_snapshots_sorted(Handle *, iter_func, void *); int mount(Handle *, const char *, int); int umount(Handle *, const char *, int); bool is_mounted(Handle *, char **); }; #endif
1,039
25
78
h
null
ceph-main/src/os/fs/btrfs_ioctl.h
/* * Copyright (C) 2007 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #ifndef __IOCTL_ #define __IOCTL_ #if defined(__linux__) #include <linux/ioctl.h> #elif defined(__FreeBSD__) #include <sys/ioctl.h> #endif #define BTRFS_IOCTL_MAGIC 0x94 #define BTRFS_VOL_NAME_MAX 255 /* this should be 4k */ #define BTRFS_PATH_NAME_MAX 4087 struct btrfs_ioctl_vol_args { __s64 fd; char name[BTRFS_PATH_NAME_MAX + 1]; }; #define BTRFS_SUBVOL_CREATE_ASYNC (1ULL << 0) #define BTRFS_SUBVOL_NAME_MAX 4039 struct btrfs_ioctl_vol_args_v2 { __s64 fd; __u64 transid; __u64 flags; __u64 unused[4]; char name[BTRFS_SUBVOL_NAME_MAX + 1]; }; #define BTRFS_INO_LOOKUP_PATH_MAX 4080 struct btrfs_ioctl_ino_lookup_args { __u64 treeid; __u64 objectid; char name[BTRFS_INO_LOOKUP_PATH_MAX]; }; struct btrfs_ioctl_search_key { /* which root are we searching. 0 is the tree of tree roots */ __u64 tree_id; /* keys returned will be >= min and <= max */ __u64 min_objectid; __u64 max_objectid; /* keys returned will be >= min and <= max */ __u64 min_offset; __u64 max_offset; /* max and min transids to search for */ __u64 min_transid; __u64 max_transid; /* keys returned will be >= min and <= max */ __u32 min_type; __u32 max_type; /* * how many items did userland ask for, and how many are we * returning */ __u32 nr_items; /* align to 64 bits */ __u32 unused; /* some extra for later */ __u64 unused1; __u64 unused2; __u64 unused3; __u64 unused4; }; struct btrfs_ioctl_search_header { __u64 transid; __u64 objectid; __u64 offset; __u32 type; __u32 len; }; #define BTRFS_SEARCH_ARGS_BUFSIZE (4096 - sizeof(struct btrfs_ioctl_search_key)) /* * the buf is an array of search headers where * each header is followed by the actual item * the type field is expanded to 32 bits for alignment */ struct btrfs_ioctl_search_args { struct btrfs_ioctl_search_key key; char buf[BTRFS_SEARCH_ARGS_BUFSIZE]; }; struct btrfs_ioctl_clone_range_args { __s64 src_fd; __u64 src_offset, src_length; __u64 dest_offset; }; /* flags for the defrag range ioctl */ #define BTRFS_DEFRAG_RANGE_COMPRESS 1 #define BTRFS_DEFRAG_RANGE_START_IO 2 struct btrfs_ioctl_defrag_range_args { /* start of the defrag operation */ __u64 start; /* number of bytes to defrag, use (u64)-1 to say all */ __u64 len; /* * flags for the operation, which can include turning * on compression for this one defrag */ __u64 flags; /* * any extent bigger than this will be considered * already defragged. Use 0 to take the kernel default * Use 1 to say every single extent must be rewritten */ __u32 extent_thresh; /* spare for later */ __u32 unused[5]; }; struct btrfs_ioctl_space_info { __u64 flags; __u64 total_bytes; __u64 used_bytes; }; struct btrfs_ioctl_space_args { __u64 space_slots; __u64 total_spaces; struct btrfs_ioctl_space_info spaces[0]; }; #define BTRFS_IOC_SNAP_CREATE _IOW(BTRFS_IOCTL_MAGIC, 1, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_DEFRAG _IOW(BTRFS_IOCTL_MAGIC, 2, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_RESIZE _IOW(BTRFS_IOCTL_MAGIC, 3, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_SCAN_DEV _IOW(BTRFS_IOCTL_MAGIC, 4, \ struct btrfs_ioctl_vol_args) /* trans start and trans end are dangerous, and only for * use by applications that know how to avoid the * resulting deadlocks */ #define BTRFS_IOC_TRANS_START _IO(BTRFS_IOCTL_MAGIC, 6) #define BTRFS_IOC_TRANS_END _IO(BTRFS_IOCTL_MAGIC, 7) #define BTRFS_IOC_SYNC _IO(BTRFS_IOCTL_MAGIC, 8) #define BTRFS_IOC_CLONE _IOW(BTRFS_IOCTL_MAGIC, 9, int) #define BTRFS_IOC_ADD_DEV _IOW(BTRFS_IOCTL_MAGIC, 10, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_RM_DEV _IOW(BTRFS_IOCTL_MAGIC, 11, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_BALANCE _IOW(BTRFS_IOCTL_MAGIC, 12, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_CLONE_RANGE _IOW(BTRFS_IOCTL_MAGIC, 13, \ struct btrfs_ioctl_clone_range_args) #define BTRFS_IOC_SUBVOL_CREATE _IOW(BTRFS_IOCTL_MAGIC, 14, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_SNAP_DESTROY _IOW(BTRFS_IOCTL_MAGIC, 15, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_DEFRAG_RANGE _IOW(BTRFS_IOCTL_MAGIC, 16, \ struct btrfs_ioctl_defrag_range_args) #define BTRFS_IOC_TREE_SEARCH _IOWR(BTRFS_IOCTL_MAGIC, 17, \ struct btrfs_ioctl_search_args) #define BTRFS_IOC_INO_LOOKUP _IOWR(BTRFS_IOCTL_MAGIC, 18, \ struct btrfs_ioctl_ino_lookup_args) #define BTRFS_IOC_DEFAULT_SUBVOL _IOW(BTRFS_IOCTL_MAGIC, 19, u64) #define BTRFS_IOC_SPACE_INFO _IOWR(BTRFS_IOCTL_MAGIC, 20, \ struct btrfs_ioctl_space_args) #define BTRFS_IOC_START_SYNC _IOR(BTRFS_IOCTL_MAGIC, 24, __u64) #define BTRFS_IOC_WAIT_SYNC _IOW(BTRFS_IOCTL_MAGIC, 22, __u64) #define BTRFS_IOC_SNAP_CREATE_V2 _IOW(BTRFS_IOCTL_MAGIC, 23, \ struct btrfs_ioctl_vol_args_v2) #endif
5,542
26.440594
80
h