repo
stringlengths 1
152
⌀ | file
stringlengths 15
205
| code
stringlengths 0
41.6M
| file_length
int64 0
41.6M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 90
values |
---|---|---|---|---|---|---|
null | ceph-main/src/messages/MMonPing.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/**
* This is used to send pings between monitors for
* heartbeat purposes. We include a timestamp and distinguish between
* outgoing pings and responses to those. If you set the
* min_message in the constructor, the message will inflate itself
* to the specified size -- this is good for dealing with network
* issues with jumbo frames. See http://tracker.ceph.com/issues/20087
*
*/
#ifndef CEPH_MMONPING_H
#define CEPH_MMONPING_H
#include "common/Clock.h"
#include "msg/Message.h"
#include "mon/ConnectionTracker.h"
class MMonPing final : public Message {
private:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
public:
enum {
PING = 1,
PING_REPLY = 2,
};
const char *get_op_name(int op) const {
switch (op) {
case PING: return "ping";
case PING_REPLY: return "ping_reply";
default: return "???";
}
}
__u8 op = 0;
utime_t stamp;
bufferlist tracker_bl;
uint32_t min_message_size = 0;
MMonPing(__u8 o, utime_t s, const bufferlist& tbl,
uint32_t min_message)
: Message{MSG_MON_PING, HEAD_VERSION, COMPAT_VERSION},
op(o), stamp(s), tracker_bl(tbl), min_message_size(min_message)
{}
MMonPing(__u8 o, utime_t s, const bufferlist& tbl)
: Message{MSG_MON_PING, HEAD_VERSION, COMPAT_VERSION},
op(o), stamp(s), tracker_bl(tbl) {}
MMonPing()
: Message{MSG_MON_PING, HEAD_VERSION, COMPAT_VERSION}
{}
private:
~MMonPing() final {}
public:
void decode_payload() override {
auto p = payload.cbegin();
decode(op, p);
decode(stamp, p);
decode(tracker_bl, p);
int payload_mid_length = p.get_off();
uint32_t size;
decode(size, p);
p += size;
min_message_size = size + payload_mid_length;
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(op, payload);
encode(stamp, payload);
encode(tracker_bl, payload);
size_t s = 0;
if (min_message_size > payload.length()) {
s = min_message_size - payload.length();
}
encode((uint32_t)s, payload);
if (s) {
// this should be big enough for normal min_message padding sizes. since
// we are targeting jumbo ethernet frames around 9000 bytes, 16k should
// be more than sufficient! the compiler will statically zero this so
// that at runtime we are only adding a bufferptr reference to it.
static char zeros[16384] = {};
while (s > sizeof(zeros)) {
payload.append(buffer::create_static(sizeof(zeros), zeros));
s -= sizeof(zeros);
}
if (s) {
payload.append(buffer::create_static(s, zeros));
}
}
}
std::string_view get_type_name() const override { return "mon_ping"; }
void print(std::ostream& out) const override {
out << "mon_ping(" << get_op_name(op)
<< " stamp " << stamp
<< ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 3,080 | 27.009091 | 78 | h |
null | ceph-main/src/messages/MMonProbe.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_MMONPROBE_H
#define CEPH_MMONPROBE_H
#include "include/ceph_features.h"
#include "common/ceph_releases.h"
#include "msg/Message.h"
#include "mon/MonMap.h"
class MMonProbe final : public Message {
public:
static constexpr int HEAD_VERSION = 8;
static constexpr int COMPAT_VERSION = 5;
enum {
OP_PROBE = 1,
OP_REPLY = 2,
OP_SLURP = 3,
OP_SLURP_LATEST = 4,
OP_DATA = 5,
OP_MISSING_FEATURES = 6,
};
static const char *get_opname(int o) {
switch (o) {
case OP_PROBE: return "probe";
case OP_REPLY: return "reply";
case OP_SLURP: return "slurp";
case OP_SLURP_LATEST: return "slurp_latest";
case OP_DATA: return "data";
case OP_MISSING_FEATURES: return "missing_features";
default: ceph_abort(); return 0;
}
}
uuid_d fsid;
int32_t op = 0;
std::string name;
std::set<int32_t> quorum;
int leader = -1;
ceph::buffer::list monmap_bl;
version_t paxos_first_version = 0;
version_t paxos_last_version = 0;
bool has_ever_joined = 0;
uint64_t required_features = 0;
ceph_release_t mon_release{ceph_release_t::unknown};
MMonProbe()
: Message{MSG_MON_PROBE, HEAD_VERSION, COMPAT_VERSION} {}
MMonProbe(const uuid_d& f, int o, const std::string& n, bool hej, ceph_release_t mr)
: Message{MSG_MON_PROBE, HEAD_VERSION, COMPAT_VERSION},
fsid(f),
op(o),
name(n),
paxos_first_version(0),
paxos_last_version(0),
has_ever_joined(hej),
required_features(0),
mon_release{mr} {}
private:
~MMonProbe() final {}
public:
std::string_view get_type_name() const override { return "mon_probe"; }
void print(std::ostream& out) const override {
out << "mon_probe(" << get_opname(op) << " " << fsid << " name " << name;
if (quorum.size())
out << " quorum " << quorum;
out << " leader " << leader;
if (op == OP_REPLY) {
out << " paxos("
<< " fc " << paxos_first_version
<< " lc " << paxos_last_version
<< " )";
}
if (!has_ever_joined)
out << " new";
if (required_features)
out << " required_features " << required_features;
if (mon_release != ceph_release_t::unknown)
out << " mon_release " << mon_release;
out << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
if (monmap_bl.length() &&
((features & CEPH_FEATURE_MONENC) == 0 ||
(features & CEPH_FEATURE_MSG_ADDR2) == 0)) {
// reencode old-format monmap
MonMap t;
t.decode(monmap_bl);
monmap_bl.clear();
t.encode(monmap_bl, features);
}
encode(fsid, payload);
encode(op, payload);
encode(name, payload);
encode(quorum, payload);
encode(monmap_bl, payload);
encode(has_ever_joined, payload);
encode(paxos_first_version, payload);
encode(paxos_last_version, payload);
encode(required_features, payload);
encode(mon_release, payload);
encode(leader, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(fsid, p);
decode(op, p);
decode(name, p);
decode(quorum, p);
decode(monmap_bl, p);
decode(has_ever_joined, p);
decode(paxos_first_version, p);
decode(paxos_last_version, p);
if (header.version >= 6)
decode(required_features, p);
else
required_features = 0;
if (header.version >= 7)
decode(mon_release, p);
else
mon_release = ceph_release_t::unknown;
if (header.version >= 8) {
decode(leader, p);
} else if (quorum.size()) {
leader = *quorum.begin();
}
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 4,154 | 25.980519 | 86 | h |
null | ceph-main/src/messages/MMonQuorumService.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_MMON_QUORUM_SERVICE_H
#define CEPH_MMON_QUORUM_SERVICE_H
#include "msg/Message.h"
class MMonQuorumService : public Message {
public:
epoch_t epoch = 0;
version_t round = 0;
protected:
MMonQuorumService(int type, int head)
: Message{type, head, 1}
{}
~MMonQuorumService() override {}
public:
void set_epoch(epoch_t e) {
epoch = e;
}
void set_round(version_t r) {
round = r;
}
epoch_t get_epoch() const {
return epoch;
}
version_t get_round() const {
return round;
}
void service_encode() {
using ceph::encode;
encode(epoch, payload);
encode(round, payload);
}
void service_decode(ceph::buffer::list::const_iterator &p) {
using ceph::decode;
decode(epoch, p);
decode(round, p);
}
void encode_payload(uint64_t features) override {
ceph_abort_msg("MMonQuorumService message must always be a base class");
}
void decode_payload() override {
ceph_abort_msg("MMonQuorumService message must always be a base class");
}
std::string_view get_type_name() const override { return "quorum_service"; }
};
#endif /* CEPH_MMON_QUORUM_SERVICE_H */
| 1,557 | 20.943662 | 78 | h |
null | ceph-main/src/messages/MMonScrub.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Inktank, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#ifndef CEPH_MMONSCRUB_H
#define CEPH_MMONSCRUB_H
#include "msg/Message.h"
#include "mon/mon_types.h"
class MMonScrub : public Message {
private:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 2;
public:
typedef enum {
OP_SCRUB = 1, // leader->peon: scrub (a range of) keys
OP_RESULT = 2, // peon->leader: result of a scrub
} op_type_t;
static const char *get_opname(op_type_t op) {
switch (op) {
case OP_SCRUB: return "scrub";
case OP_RESULT: return "result";
default: ceph_abort_msg("unknown op type"); return NULL;
}
}
op_type_t op = OP_SCRUB;
version_t version = 0;
ScrubResult result;
int32_t num_keys;
std::pair<std::string,std::string> key;
MMonScrub()
: Message{MSG_MON_SCRUB, HEAD_VERSION, COMPAT_VERSION},
num_keys(-1)
{ }
MMonScrub(op_type_t op, version_t v, int32_t num_keys)
: Message{MSG_MON_SCRUB, HEAD_VERSION, COMPAT_VERSION},
op(op), version(v), num_keys(num_keys)
{ }
std::string_view get_type_name() const override { return "mon_scrub"; }
void print(std::ostream& out) const override {
out << "mon_scrub(" << get_opname((op_type_t)op);
out << " v " << version;
if (op == OP_RESULT)
out << " " << result;
out << " num_keys " << num_keys;
out << " key (" << key << ")";
out << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
uint8_t o = op;
encode(o, payload);
encode(version, payload);
encode(result, payload);
encode(num_keys, payload);
encode(key, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
uint8_t o;
decode(o, p);
op = (op_type_t)o;
decode(version, p);
decode(result, p);
decode(num_keys, p);
decode(key, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif /* CEPH_MMONSCRUB_H */
| 2,395 | 24.763441 | 73 | h |
null | ceph-main/src/messages/MMonSubscribe.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_MMONSUBSCRIBE_H
#define CEPH_MMONSUBSCRIBE_H
#include "msg/Message.h"
#include "include/ceph_features.h"
/*
* compatibility with old crap
*/
struct ceph_mon_subscribe_item_old {
ceph_le64 unused;
ceph_le64 have;
__u8 onetime;
} __attribute__ ((packed));
WRITE_RAW_ENCODER(ceph_mon_subscribe_item_old)
class MMonSubscribe final : public Message {
public:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 1;
std::string hostname;
std::map<std::string, ceph_mon_subscribe_item> what;
MMonSubscribe() : Message{CEPH_MSG_MON_SUBSCRIBE, HEAD_VERSION, COMPAT_VERSION} { }
private:
~MMonSubscribe() final {}
public:
void sub_want(const char *w, version_t start, unsigned flags) {
what[w].start = start;
what[w].flags = flags;
}
std::string_view get_type_name() const override { return "mon_subscribe"; }
void print(std::ostream& o) const override {
o << "mon_subscribe(" << what << ")";
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
if (header.version < 2) {
std::map<std::string, ceph_mon_subscribe_item_old> oldwhat;
decode(oldwhat, p);
what.clear();
for (auto q = oldwhat.begin(); q != oldwhat.end(); q++) {
if (q->second.have)
what[q->first].start = q->second.have + 1;
else
what[q->first].start = 0;
what[q->first].flags = 0;
if (q->second.onetime)
what[q->first].flags |= CEPH_SUBSCRIBE_ONETIME;
}
return;
}
decode(what, p);
if (header.version >= 3) {
decode(hostname, p);
}
}
void encode_payload(uint64_t features) override {
using ceph::encode;
if ((features & CEPH_FEATURE_SUBSCRIBE2) == 0) {
header.version = 0;
std::map<std::string, ceph_mon_subscribe_item_old> oldwhat;
for (auto q = what.begin(); q != what.end(); q++) {
if (q->second.start)
// warning: start=1 -> have=0, which was ambiguous
oldwhat[q->first].have = q->second.start - 1;
else
oldwhat[q->first].have = 0;
oldwhat[q->first].onetime = q->second.flags & CEPH_SUBSCRIBE_ONETIME;
}
encode(oldwhat, payload);
return;
}
header.version = HEAD_VERSION;
encode(what, payload);
encode(hostname, payload);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,812 | 26.048077 | 85 | h |
null | ceph-main/src/messages/MMonSubscribeAck.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_MMONSUBSCRIBEACK_H
#define CEPH_MMONSUBSCRIBEACK_H
#include "msg/Message.h"
class MMonSubscribeAck final : public Message {
public:
__u32 interval;
uuid_d fsid;
MMonSubscribeAck() : Message{CEPH_MSG_MON_SUBSCRIBE_ACK},
interval(0) {
}
MMonSubscribeAck(uuid_d& f, int i) : Message{CEPH_MSG_MON_SUBSCRIBE_ACK},
interval(i), fsid(f) { }
private:
~MMonSubscribeAck() final {}
public:
std::string_view get_type_name() const override { return "mon_subscribe_ack"; }
void print(std::ostream& o) const override {
o << "mon_subscribe_ack(" << interval << "s)";
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(interval, p);
decode(fsid, p);
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(interval, payload);
encode(fsid, payload);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 1,450 | 24.910714 | 81 | h |
null | ceph-main/src/messages/MMonSync.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_MMONSYNC_H
#define CEPH_MMONSYNC_H
#include "msg/Message.h"
class MMonSync : public Message {
private:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 2;
public:
/**
* Operation types
*/
enum {
OP_GET_COOKIE_FULL = 1, // -> start a session (full scan)
OP_GET_COOKIE_RECENT = 2, // -> start a session (only recent paxos events)
OP_COOKIE = 3, // <- pass the iterator cookie, or
OP_GET_CHUNK = 4, // -> get some keys
OP_CHUNK = 5, // <- return some keys
OP_LAST_CHUNK = 6, // <- return the last set of keys
OP_NO_COOKIE = 8, // <- sorry, no cookie
};
/**
* Obtain a string corresponding to the operation type @p op
*
* @param op Operation type
* @returns A string
*/
static const char *get_opname(int op) {
switch (op) {
case OP_GET_COOKIE_FULL: return "get_cookie_full";
case OP_GET_COOKIE_RECENT: return "get_cookie_recent";
case OP_COOKIE: return "cookie";
case OP_GET_CHUNK: return "get_chunk";
case OP_CHUNK: return "chunk";
case OP_LAST_CHUNK: return "last_chunk";
case OP_NO_COOKIE: return "no_cookie";
default: ceph_abort_msg("unknown op type"); return NULL;
}
}
uint32_t op = 0;
uint64_t cookie = 0;
version_t last_committed = 0;
std::pair<std::string,std::string> last_key;
ceph::buffer::list chunk_bl;
entity_inst_t reply_to;
MMonSync()
: Message{MSG_MON_SYNC, HEAD_VERSION, COMPAT_VERSION}
{ }
MMonSync(uint32_t op, uint64_t c = 0)
: Message{MSG_MON_SYNC, HEAD_VERSION, COMPAT_VERSION},
op(op),
cookie(c),
last_committed(0)
{ }
std::string_view get_type_name() const override { return "mon_sync"; }
void print(std::ostream& out) const override {
out << "mon_sync(" << get_opname(op);
if (cookie)
out << " cookie " << cookie;
if (last_committed > 0)
out << " lc " << last_committed;
if (chunk_bl.length())
out << " bl " << chunk_bl.length() << " bytes";
if (!last_key.first.empty() || !last_key.second.empty())
out << " last_key " << last_key.first << "," << last_key.second;
out << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(op, payload);
encode(cookie, payload);
encode(last_committed, payload);
encode(last_key.first, payload);
encode(last_key.second, payload);
encode(chunk_bl, payload);
encode(reply_to, payload, features);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(op, p);
decode(cookie, p);
decode(last_committed, p);
decode(last_key.first, p);
decode(last_key.second, p);
decode(chunk_bl, p);
decode(reply_to, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif /* CEPH_MMONSYNC_H */
| 3,336 | 27.521368 | 78 | h |
null | ceph-main/src/messages/MMonUsedPendingKeys.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.
*
*/
#pragma once
#include "messages/PaxosServiceMessage.h"
class MMonUsedPendingKeys final : public PaxosServiceMessage {
public:
std::map<EntityName,CryptoKey> used_pending_keys;
MMonUsedPendingKeys() : PaxosServiceMessage{MSG_MON_USED_PENDING_KEYS, 0}
{}
private:
~MMonUsedPendingKeys() final {}
public:
std::string_view get_type_name() const override { return "used_pending_keys"; }
void print(std::ostream& out) const override {
out << "used_pending_keys(" << used_pending_keys.size() << " keys)";
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(used_pending_keys, p);
}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
encode(used_pending_keys, payload);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 1,362 | 26.816327 | 81 | h |
null | ceph-main/src/messages/MOSDAlive.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_MOSDALIVE_H
#define CEPH_MOSDALIVE_H
#include "messages/PaxosServiceMessage.h"
class MOSDAlive final : public PaxosServiceMessage {
public:
epoch_t want = 0;
MOSDAlive(epoch_t h, epoch_t w) : PaxosServiceMessage{MSG_OSD_ALIVE, h}, want(w) {}
MOSDAlive() : MOSDAlive{0, 0} {}
private:
~MOSDAlive() final {}
public:
void encode_payload(uint64_t features) override {
paxos_encode();
using ceph::encode;
encode(want, payload);
}
void decode_payload() override {
auto p = payload.cbegin();
paxos_decode(p);
using ceph::decode;
decode(want, p);
}
std::string_view get_type_name() const override { return "osd_alive"; }
void print(std::ostream &out) const override {
out << "osd_alive(want up_thru " << want << " have " << version << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 1,364 | 24.277778 | 85 | h |
null | ceph-main/src/messages/MOSDBackoff.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2017 Red Hat
*
* 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_MOSDBACKOFF_H
#define CEPH_MOSDBACKOFF_H
#include "MOSDFastDispatchOp.h"
#include "osd/osd_types.h"
class MOSDBackoff : public MOSDFastDispatchOp {
public:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
spg_t pgid;
epoch_t map_epoch = 0;
uint8_t op = 0; ///< CEPH_OSD_BACKOFF_OP_*
uint64_t id = 0; ///< unique id within this session
hobject_t begin, end; ///< [) range to block, unless ==, block single obj
spg_t get_spg() const override {
return pgid;
}
epoch_t get_map_epoch() const override {
return map_epoch;
}
MOSDBackoff()
: MOSDFastDispatchOp{CEPH_MSG_OSD_BACKOFF, HEAD_VERSION, COMPAT_VERSION} {}
MOSDBackoff(spg_t pgid_, epoch_t ep, uint8_t op_, uint64_t id_,
hobject_t begin_, hobject_t end_)
: MOSDFastDispatchOp{CEPH_MSG_OSD_BACKOFF, HEAD_VERSION, COMPAT_VERSION},
pgid(pgid_),
map_epoch(ep),
op(op_),
id(id_),
begin(begin_),
end(end_) { }
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid, payload);
encode(map_epoch, payload);
encode(op, payload);
encode(id, payload);
encode(begin, payload);
encode(end, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid, p);
decode(map_epoch, p);
decode(op, p);
decode(id, p);
decode(begin, p);
decode(end, p);
}
std::string_view get_type_name() const override { return "osd_backoff"; }
void print(std::ostream& out) const override {
out << "osd_backoff(" << pgid << " " << ceph_osd_backoff_op_name(op)
<< " id " << id
<< " [" << begin << "," << end << ")"
<< " e" << map_epoch << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,295 | 25.390805 | 79 | h |
null | ceph-main/src/messages/MOSDBeacon.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "PaxosServiceMessage.h"
class MOSDBeacon : public PaxosServiceMessage {
private:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 1;
public:
std::vector<pg_t> pgs;
epoch_t min_last_epoch_clean = 0;
utime_t last_purged_snaps_scrub;
int osd_beacon_report_interval = 0;
MOSDBeacon()
: PaxosServiceMessage{MSG_OSD_BEACON, 0,
HEAD_VERSION, COMPAT_VERSION}
{}
MOSDBeacon(epoch_t e, epoch_t min_lec, utime_t ls, int interval)
: PaxosServiceMessage{MSG_OSD_BEACON, e,
HEAD_VERSION, COMPAT_VERSION},
min_last_epoch_clean(min_lec),
last_purged_snaps_scrub(ls),
osd_beacon_report_interval(interval)
{}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
encode(pgs, payload);
encode(min_last_epoch_clean, payload);
encode(last_purged_snaps_scrub, payload);
encode(osd_beacon_report_interval, payload);
}
void decode_payload() override {
auto p = payload.cbegin();
using ceph::decode;
paxos_decode(p);
decode(pgs, p);
decode(min_last_epoch_clean, p);
if (header.version >= 2) {
decode(last_purged_snaps_scrub, p);
}
if (header.version >= 3) {
decode(osd_beacon_report_interval, p);
} else {
osd_beacon_report_interval = 0;
}
}
std::string_view get_type_name() const override { return "osd_beacon"; }
void print(std::ostream &out) const {
out << get_type_name()
<< "(pgs " << pgs
<< " lec " << min_last_epoch_clean
<< " last_purged_snaps_scrub " << last_purged_snaps_scrub
<< " osd_beacon_report_interval " << osd_beacon_report_interval
<< " v" << version << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 1,954 | 29.076923 | 74 | h |
null | ceph-main/src/messages/MOSDBoot.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_MOSDBOOT_H
#define CEPH_MOSDBOOT_H
#include "messages/PaxosServiceMessage.h"
#include "include/ceph_features.h"
#include "include/types.h"
#include "osd/osd_types.h"
class MOSDBoot final : public PaxosServiceMessage {
private:
static constexpr int HEAD_VERSION = 7;
static constexpr int COMPAT_VERSION = 7;
public:
OSDSuperblock sb;
entity_addrvec_t hb_back_addrs, hb_front_addrs;
entity_addrvec_t cluster_addrs;
epoch_t boot_epoch; // last epoch this daemon was added to the map (if any)
std::map<std::string,std::string> metadata; ///< misc metadata about this osd
uint64_t osd_features;
MOSDBoot()
: PaxosServiceMessage{MSG_OSD_BOOT, 0, HEAD_VERSION, COMPAT_VERSION},
boot_epoch(0), osd_features(0)
{ }
MOSDBoot(const OSDSuperblock& s, epoch_t e, epoch_t be,
const entity_addrvec_t& hb_back_addr_ref,
const entity_addrvec_t& hb_front_addr_ref,
const entity_addrvec_t& cluster_addr_ref,
uint64_t feat)
: PaxosServiceMessage{MSG_OSD_BOOT, e, HEAD_VERSION, COMPAT_VERSION},
sb(s),
hb_back_addrs(hb_back_addr_ref),
hb_front_addrs(hb_front_addr_ref),
cluster_addrs(cluster_addr_ref),
boot_epoch(be),
osd_features(feat)
{ }
private:
~MOSDBoot() final { }
public:
std::string_view get_type_name() const override { return "osd_boot"; }
void print(std::ostream& out) const override {
out << "osd_boot(osd." << sb.whoami << " booted " << boot_epoch
<< " features " << osd_features
<< " v" << version << ")";
}
void encode_payload(uint64_t features) override {
header.version = HEAD_VERSION;
header.compat_version = COMPAT_VERSION;
using ceph::encode;
paxos_encode();
assert(HAVE_FEATURE(features, SERVER_NAUTILUS));
encode(sb, payload);
encode(hb_back_addrs, payload, features);
encode(cluster_addrs, payload, features);
encode(boot_epoch, payload);
encode(hb_front_addrs, payload, features);
encode(metadata, payload);
encode(osd_features, payload);
}
void decode_payload() override {
auto p = payload.cbegin();
using ceph::decode;
paxos_decode(p);
assert(header.version >= 7);
decode(sb, p);
decode(hb_back_addrs, p);
decode(cluster_addrs, p);
decode(boot_epoch, p);
decode(hb_front_addrs, p);
decode(metadata, p);
decode(osd_features, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,929 | 28.59596 | 79 | h |
null | ceph-main/src/messages/MOSDECSubOpRead.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Inktank Storage, 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 MOSDECSUBOPREAD_H
#define MOSDECSUBOPREAD_H
#include "MOSDFastDispatchOp.h"
#include "osd/ECMsgTypes.h"
class MOSDECSubOpRead : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 1;
public:
spg_t pgid;
epoch_t map_epoch = 0, min_epoch = 0;
ECSubRead op;
int get_cost() const override {
return 0;
}
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDECSubOpRead()
: MOSDFastDispatchOp{MSG_OSD_EC_READ, HEAD_VERSION, COMPAT_VERSION}
{}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid, p);
decode(map_epoch, p);
decode(op, p);
if (header.version >= 3) {
decode(min_epoch, p);
decode_trace(p);
} else {
min_epoch = map_epoch;
}
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid, payload);
encode(map_epoch, payload);
encode(op, payload, features);
encode(min_epoch, payload);
encode_trace(payload, features);
}
std::string_view get_type_name() const override { return "MOSDECSubOpRead"; }
void print(std::ostream& out) const override {
out << "MOSDECSubOpRead(" << pgid
<< " " << map_epoch << "/" << min_epoch
<< " " << op;
out << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,005 | 22.6 | 79 | h |
null | ceph-main/src/messages/MOSDECSubOpReadReply.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Inktank Storage, 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 MOSDECSUBOPREADREPLY_H
#define MOSDECSUBOPREADREPLY_H
#include "MOSDFastDispatchOp.h"
#include "osd/ECMsgTypes.h"
class MOSDECSubOpReadReply : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 1;
public:
spg_t pgid;
epoch_t map_epoch = 0, min_epoch = 0;
ECSubReadReply op;
int get_cost() const override {
return 0;
}
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDECSubOpReadReply()
: MOSDFastDispatchOp{MSG_OSD_EC_READ_REPLY, HEAD_VERSION, COMPAT_VERSION}
{}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid, p);
decode(map_epoch, p);
decode(op, p);
if (header.version >= 2) {
decode(min_epoch, p);
decode_trace(p);
} else {
min_epoch = map_epoch;
}
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid, payload);
encode(map_epoch, payload);
encode(op, payload);
encode(min_epoch, payload);
encode_trace(payload, features);
}
std::string_view get_type_name() const override { return "MOSDECSubOpReadReply"; }
void print(std::ostream& out) const override {
out << "MOSDECSubOpReadReply(" << pgid
<< " " << map_epoch << "/" << min_epoch
<< " " << op;
out << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,036 | 22.964706 | 84 | h |
null | ceph-main/src/messages/MOSDECSubOpWrite.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Inktank Storage, 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 MOSDECSUBOPWRITE_H
#define MOSDECSUBOPWRITE_H
#include "MOSDFastDispatchOp.h"
#include "osd/ECMsgTypes.h"
class MOSDECSubOpWrite : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 1;
public:
spg_t pgid;
epoch_t map_epoch = 0, min_epoch = 0;
ECSubWrite op;
int get_cost() const override {
return 0;
}
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDECSubOpWrite()
: MOSDFastDispatchOp{MSG_OSD_EC_WRITE, HEAD_VERSION, COMPAT_VERSION}
{}
MOSDECSubOpWrite(ECSubWrite &in_op)
: MOSDFastDispatchOp{MSG_OSD_EC_WRITE, HEAD_VERSION, COMPAT_VERSION} {
op.claim(in_op);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid, p);
decode(map_epoch, p);
decode(op, p);
if (header.version >= 2) {
decode(min_epoch, p);
decode_trace(p);
} else {
min_epoch = map_epoch;
}
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid, payload);
encode(map_epoch, payload);
encode(op, payload);
encode(min_epoch, payload);
encode_trace(payload, features);
}
std::string_view get_type_name() const override { return "MOSDECSubOpWrite"; }
void print(std::ostream& out) const override {
out << "MOSDECSubOpWrite(" << pgid
<< " " << map_epoch << "/" << min_epoch
<< " " << op;
out << ")";
}
void clear_buffers() override {
op.t = ObjectStore::Transaction();
op.log_entries.clear();
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,247 | 22.914894 | 80 | h |
null | ceph-main/src/messages/MOSDECSubOpWriteReply.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Inktank Storage, 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 MOSDECSUBOPWRITEREPLY_H
#define MOSDECSUBOPWRITEREPLY_H
#include "MOSDFastDispatchOp.h"
#include "osd/ECMsgTypes.h"
class MOSDECSubOpWriteReply : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 1;
public:
spg_t pgid;
epoch_t map_epoch = 0, min_epoch = 0;
ECSubWriteReply op;
int get_cost() const override {
return 0;
}
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDECSubOpWriteReply()
: MOSDFastDispatchOp{MSG_OSD_EC_WRITE_REPLY, HEAD_VERSION, COMPAT_VERSION}
{}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid, p);
decode(map_epoch, p);
decode(op, p);
if (header.version >= 2) {
decode(min_epoch, p);
decode_trace(p);
} else {
min_epoch = map_epoch;
}
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid, payload);
encode(map_epoch, payload);
encode(op, payload);
encode(min_epoch, payload);
encode_trace(payload, features);
}
std::string_view get_type_name() const override { return "MOSDECSubOpWriteReply"; }
void print(std::ostream& out) const override {
out << "MOSDECSubOpWriteReply(" << pgid
<< " " << map_epoch << "/" << min_epoch
<< " " << op;
out << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,042 | 23.035294 | 85 | h |
null | ceph-main/src/messages/MOSDFailure.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_MOSDFAILURE_H
#define CEPH_MOSDFAILURE_H
#include "messages/PaxosServiceMessage.h"
class MOSDFailure final : public PaxosServiceMessage {
private:
static constexpr int HEAD_VERSION = 4;
static constexpr int COMPAT_VERSION = 4;
public:
enum {
FLAG_ALIVE = 0, // use this on its own to mark as "I'm still alive"
FLAG_FAILED = 1, // if set, failure; if not, recovery
FLAG_IMMEDIATE = 2, // known failure, not a timeout
};
uuid_d fsid;
int32_t target_osd;
entity_addrvec_t target_addrs;
__u8 flags = 0;
epoch_t epoch = 0;
int32_t failed_for = 0; // known to be failed since at least this long
MOSDFailure() : PaxosServiceMessage(MSG_OSD_FAILURE, 0, HEAD_VERSION) { }
MOSDFailure(const uuid_d &fs, int osd, const entity_addrvec_t& av,
int duration, epoch_t e)
: PaxosServiceMessage(MSG_OSD_FAILURE, e, HEAD_VERSION, COMPAT_VERSION),
fsid(fs),
target_osd(osd),
target_addrs(av),
flags(FLAG_FAILED),
epoch(e), failed_for(duration) { }
MOSDFailure(const uuid_d &fs, int osd, const entity_addrvec_t& av,
int duration,
epoch_t e, __u8 extra_flags)
: PaxosServiceMessage(MSG_OSD_FAILURE, e, HEAD_VERSION, COMPAT_VERSION),
fsid(fs),
target_osd(osd),
target_addrs(av),
flags(extra_flags),
epoch(e), failed_for(duration) { }
private:
~MOSDFailure() final {}
public:
int get_target_osd() { return target_osd; }
const entity_addrvec_t& get_target_addrs() { return target_addrs; }
bool if_osd_failed() const {
return flags & FLAG_FAILED;
}
bool is_immediate() const {
return flags & FLAG_IMMEDIATE;
}
epoch_t get_epoch() const { return epoch; }
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(fsid, p);
assert(header.version >= 4);
decode(target_osd, p);
decode(target_addrs, p);
decode(epoch, p);
decode(flags, p);
decode(failed_for, p);
}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
assert(HAVE_FEATURE(features, SERVER_NAUTILUS));
header.version = HEAD_VERSION;
header.compat_version = COMPAT_VERSION;
encode(fsid, payload);
encode(target_osd, payload, features);
encode(target_addrs, payload, features);
encode(epoch, payload);
encode(flags, payload);
encode(failed_for, payload);
}
std::string_view get_type_name() const override { return "osd_failure"; }
void print(std::ostream& out) const override {
out << "osd_failure("
<< (if_osd_failed() ? "failed " : "recovered ")
<< (is_immediate() ? "immediate " : "timeout ")
<< "osd." << target_osd << " " << target_addrs
<< " for " << failed_for << "sec e" << epoch
<< " v" << version << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 3,391 | 28.495652 | 76 | h |
null | ceph-main/src/messages/MOSDFastDispatchOp.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_MOSDFASTDISPATCHOP_H
#define CEPH_MOSDFASTDISPATCHOP_H
#include "msg/Message.h"
#include "osd/osd_types.h"
class MOSDFastDispatchOp : public Message {
public:
MOSDFastDispatchOp(int t, int version, int compat_version)
: Message{t, version, compat_version}
{}
virtual epoch_t get_map_epoch() const = 0;
virtual epoch_t get_min_epoch() const {
return get_map_epoch();
}
virtual spg_t get_spg() const = 0;
};
#endif
| 548 | 22.869565 | 70 | h |
null | ceph-main/src/messages/MOSDForceRecovery.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 OVH
*
* 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_MOSDFORCERECOVERY_H
#define CEPH_MOSDFORCERECOVERY_H
#include "msg/Message.h"
/*
* instruct an OSD to boost/unboost recovery/backfill priority of some or all pg(s)
*/
// boost priority of recovery
static const int OFR_RECOVERY = 1;
// boost priority of backfill
static const int OFR_BACKFILL = 2;
// cancel priority boost, requeue if necessary
static const int OFR_CANCEL = 4;
class MOSDForceRecovery final : public Message {
public:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 2;
uuid_d fsid;
std::vector<spg_t> forced_pgs;
uint8_t options = 0;
MOSDForceRecovery() : Message{MSG_OSD_FORCE_RECOVERY, HEAD_VERSION, COMPAT_VERSION} {}
MOSDForceRecovery(const uuid_d& f, char opts) :
Message{MSG_OSD_FORCE_RECOVERY, HEAD_VERSION, COMPAT_VERSION},
fsid(f), options(opts) {}
MOSDForceRecovery(const uuid_d& f, std::vector<spg_t>& pgs, char opts) :
Message{MSG_OSD_FORCE_RECOVERY, HEAD_VERSION, COMPAT_VERSION},
fsid(f), forced_pgs(pgs), options(opts) {}
private:
~MOSDForceRecovery() final {}
public:
std::string_view get_type_name() const { return "force_recovery"; }
void print(std::ostream& out) const {
out << "force_recovery(";
if (forced_pgs.empty())
out << "osd";
else
out << forced_pgs;
if (options & OFR_RECOVERY)
out << " recovery";
if (options & OFR_BACKFILL)
out << " backfill";
if (options & OFR_CANCEL)
out << " cancel";
out << ")";
}
void encode_payload(uint64_t features) {
using ceph::encode;
if (!HAVE_FEATURE(features, SERVER_MIMIC)) {
header.version = 1;
header.compat_version = 1;
std::vector<pg_t> pgs;
for (auto pgid : forced_pgs) {
pgs.push_back(pgid.pgid);
}
encode(fsid, payload);
encode(pgs, payload);
encode(options, payload);
return;
}
header.version = HEAD_VERSION;
header.compat_version = COMPAT_VERSION;
encode(fsid, payload);
encode(forced_pgs, payload);
encode(options, payload);
}
void decode_payload() {
using ceph::decode;
auto p = payload.cbegin();
if (header.version == 1) {
std::vector<pg_t> pgs;
decode(fsid, p);
decode(pgs, p);
decode(options, p);
for (auto pg : pgs) {
// note: this only works with replicated pools. if a pre-mimic mon
// tries to force a mimic+ osd on an ec pool it will not work.
forced_pgs.push_back(spg_t(pg));
}
return;
}
decode(fsid, p);
decode(forced_pgs, p);
decode(options, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif /* CEPH_MOSDFORCERECOVERY_H_ */
| 3,127 | 26.2 | 88 | h |
null | ceph-main/src/messages/MOSDFull.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_MOSDFULL_H
#define CEPH_MOSDFULL_H
#include "messages/PaxosServiceMessage.h"
#include "osd/OSDMap.h"
// tell the mon to update the full/nearfull bits. note that in the
// future this message could be generalized to other state bits, but
// for now name it for its sole application.
class MOSDFull final : public PaxosServiceMessage {
public:
epoch_t map_epoch = 0;
uint32_t state = 0;
private:
~MOSDFull() final {}
public:
MOSDFull(epoch_t e, unsigned s)
: PaxosServiceMessage{MSG_OSD_FULL, e}, map_epoch(e), state(s) { }
MOSDFull()
: PaxosServiceMessage{MSG_OSD_FULL, 0} {}
public:
void encode_payload(uint64_t features) {
using ceph::encode;
paxos_encode();
encode(map_epoch, payload);
encode(state, payload);
}
void decode_payload() {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(map_epoch, p);
decode(state, p);
}
std::string_view get_type_name() const { return "osd_full"; }
void print(std::ostream &out) const {
std::set<std::string> states;
OSDMap::calc_state_set(state, states);
out << "osd_full(e" << map_epoch << " " << states << " v" << version << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 1,419 | 24.818182 | 80 | h |
null | ceph-main/src/messages/MOSDMap.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_MOSDMAP_H
#define CEPH_MOSDMAP_H
#include "msg/Message.h"
#include "osd/OSDMap.h"
#include "include/ceph_features.h"
class MOSDMap final : public Message {
private:
static constexpr int HEAD_VERSION = 4;
static constexpr int COMPAT_VERSION = 3;
public:
uuid_d fsid;
uint64_t encode_features = 0;
std::map<epoch_t, ceph::buffer::list> maps;
std::map<epoch_t, ceph::buffer::list> incremental_maps;
/**
* cluster_osdmap_trim_lower_bound
*
* Encodes a lower bound on the monitor's osdmap trim bound. Recipients
* can safely trim up to this bound. The sender stores maps back to
* cluster_osdmap_trim_lower_bound.
*
* This field was formerly named oldest_map and encoded the oldest map
* stored by the sender. The primary usage of this field, however, was to
* allow the recipient to trim. The secondary usage was to inform the
* recipient of how many maps the sender stored in case it needed to request
* more. For both purposes, it should be safe for an older OSD to interpret
* this field as oldest_map, and it should be safe for a new osd to interpret
* the oldest_map field sent by an older osd as
* cluster_osdmap_trim_lower_bound.
* See bug https://tracker.ceph.com/issues/49689
*/
epoch_t cluster_osdmap_trim_lower_bound = 0;
epoch_t newest_map = 0;
epoch_t get_first() const {
epoch_t e = 0;
auto i = maps.cbegin();
if (i != maps.cend()) e = i->first;
i = incremental_maps.begin();
if (i != incremental_maps.end() &&
(e == 0 || i->first < e)) e = i->first;
return e;
}
epoch_t get_last() const {
epoch_t e = 0;
auto i = maps.crbegin();
if (i != maps.crend()) e = i->first;
i = incremental_maps.rbegin();
if (i != incremental_maps.rend() &&
(e == 0 || i->first > e)) e = i->first;
return e;
}
MOSDMap() : Message{CEPH_MSG_OSD_MAP, HEAD_VERSION, COMPAT_VERSION} { }
MOSDMap(const uuid_d &f, const uint64_t features)
: Message{CEPH_MSG_OSD_MAP, HEAD_VERSION, COMPAT_VERSION},
fsid(f), encode_features(features),
cluster_osdmap_trim_lower_bound(0), newest_map(0) { }
private:
~MOSDMap() final {}
public:
// marshalling
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(fsid, p);
decode(incremental_maps, p);
decode(maps, p);
if (header.version >= 2) {
decode(cluster_osdmap_trim_lower_bound, p);
decode(newest_map, p);
} else {
cluster_osdmap_trim_lower_bound = 0;
newest_map = 0;
}
if (header.version >= 4) {
// removed in octopus
mempool::osdmap::map<int64_t,snap_interval_set_t> gap_removed_snaps;
decode(gap_removed_snaps, p);
}
}
void encode_payload(uint64_t features) override {
using ceph::encode;
header.version = HEAD_VERSION;
header.compat_version = COMPAT_VERSION;
encode(fsid, payload);
if (OSDMap::get_significant_features(encode_features) !=
OSDMap::get_significant_features(features)) {
if ((features & CEPH_FEATURE_PGID64) == 0 ||
(features & CEPH_FEATURE_PGPOOL3) == 0) {
header.version = 1; // old old_client version
header.compat_version = 1;
} else if ((features & CEPH_FEATURE_OSDENC) == 0) {
header.version = 2; // old pg_pool_t
header.compat_version = 2;
}
// reencode maps using old format
//
// FIXME: this can probably be done more efficiently higher up
// the stack, or maybe replaced with something that only
// includes the pools the client cares about.
for (auto p = incremental_maps.begin(); p != incremental_maps.end(); ++p) {
OSDMap::Incremental inc;
auto q = p->second.cbegin();
inc.decode(q);
// always encode with subset of osdmaps canonical features
uint64_t f = inc.encode_features & features;
p->second.clear();
if (inc.fullmap.length()) {
// embedded full std::map?
OSDMap m;
m.decode(inc.fullmap);
inc.fullmap.clear();
m.encode(inc.fullmap, f | CEPH_FEATURE_RESERVED);
}
if (inc.crush.length()) {
// embedded crush std::map
CrushWrapper c;
auto p = inc.crush.cbegin();
c.decode(p);
inc.crush.clear();
c.encode(inc.crush, f);
}
inc.encode(p->second, f | CEPH_FEATURE_RESERVED);
}
for (auto p = maps.begin(); p != maps.end(); ++p) {
OSDMap m;
m.decode(p->second);
// always encode with subset of osdmaps canonical features
uint64_t f = m.get_encoding_features() & features;
p->second.clear();
m.encode(p->second, f | CEPH_FEATURE_RESERVED);
}
}
encode(incremental_maps, payload);
encode(maps, payload);
if (header.version >= 2) {
encode(cluster_osdmap_trim_lower_bound, payload);
encode(newest_map, payload);
}
if (header.version >= 4) {
encode((uint32_t)0, payload);
}
}
std::string_view get_type_name() const override { return "osdmap"; }
void print(std::ostream& out) const override {
out << "osd_map(" << get_first() << ".." << get_last();
if (cluster_osdmap_trim_lower_bound || newest_map)
out << " src has " << cluster_osdmap_trim_lower_bound
<< ".." << newest_map;
out << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 5,746 | 31.106145 | 81 | h |
null | ceph-main/src/messages/MOSDMarkMeDead.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "messages/PaxosServiceMessage.h"
class MOSDMarkMeDead final : public PaxosServiceMessage {
private:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
public:
uuid_d fsid;
int32_t target_osd;
epoch_t epoch = 0;
MOSDMarkMeDead()
: PaxosServiceMessage{MSG_OSD_MARK_ME_DEAD, 0,
HEAD_VERSION, COMPAT_VERSION} { }
MOSDMarkMeDead(const uuid_d &fs, int osd,
epoch_t e)
: PaxosServiceMessage{MSG_OSD_MARK_ME_DEAD, e,
HEAD_VERSION, COMPAT_VERSION},
fsid(fs), target_osd(osd),
epoch(e) {}
private:
~MOSDMarkMeDead() final {}
public:
epoch_t get_epoch() const { return epoch; }
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(fsid, p);
decode(target_osd, p);
decode(epoch, p);
}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
header.version = HEAD_VERSION;
header.compat_version = COMPAT_VERSION;
encode(fsid, payload);
encode(target_osd, payload, features);
encode(epoch, payload);
}
std::string_view get_type_name() const override { return "MOSDMarkMeDead"; }
void print(std::ostream& out) const override {
out << "MOSDMarkMeDead("
<< "osd." << target_osd
<< ", epoch " << epoch
<< ", fsid=" << fsid
<< ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 1,600 | 24.015625 | 78 | h |
null | ceph-main/src/messages/MOSDMarkMeDown.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Inktank Storage, 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_MOSDMARKMEDOWN_H
#define CEPH_MOSDMARKMEDOWN_H
#include "messages/PaxosServiceMessage.h"
class MOSDMarkMeDown final : public PaxosServiceMessage {
private:
static constexpr int HEAD_VERSION = 4;
static constexpr int COMPAT_VERSION = 3;
public:
uuid_d fsid;
int32_t target_osd;
entity_addrvec_t target_addrs;
epoch_t epoch = 0;
bool request_ack = false; // ack requested
bool down_and_dead = false; // mark down and dead
MOSDMarkMeDown()
: PaxosServiceMessage{MSG_OSD_MARK_ME_DOWN, 0,
HEAD_VERSION, COMPAT_VERSION} { }
MOSDMarkMeDown(const uuid_d &fs, int osd, const entity_addrvec_t& av,
epoch_t e, bool request_ack)
: PaxosServiceMessage{MSG_OSD_MARK_ME_DOWN, e,
HEAD_VERSION, COMPAT_VERSION},
fsid(fs), target_osd(osd), target_addrs(av),
epoch(e), request_ack(request_ack) {}
MOSDMarkMeDown(const uuid_d &fs, int osd, const entity_addrvec_t& av,
epoch_t e, bool request_ack, bool down_and_dead)
: PaxosServiceMessage{MSG_OSD_MARK_ME_DOWN, e,
HEAD_VERSION, COMPAT_VERSION},
fsid(fs), target_osd(osd), target_addrs(av),
epoch(e), request_ack(request_ack), down_and_dead(down_and_dead) {}
private:
~MOSDMarkMeDown() final {}
public:
epoch_t get_epoch() const { return epoch; }
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
assert(header.version >= 3);
decode(fsid, p);
decode(target_osd, p);
decode(target_addrs, p);
decode(epoch, p);
decode(request_ack, p);
if(header.version >= 4)
decode(down_and_dead, p);
}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
assert(HAVE_FEATURE(features, SERVER_NAUTILUS));
header.version = HEAD_VERSION;
header.compat_version = COMPAT_VERSION;
encode(fsid, payload);
encode(target_osd, payload, features);
encode(target_addrs, payload, features);
encode(epoch, payload);
encode(request_ack, payload);
encode(down_and_dead, payload);
}
std::string_view get_type_name() const override { return "MOSDMarkMeDown"; }
void print(std::ostream& out) const override {
out << "MOSDMarkMeDown("
<< "request_ack=" << request_ack
<< ", down_and_dead=" << down_and_dead
<< ", osd." << target_osd
<< ", " << target_addrs
<< ", fsid=" << fsid
<< ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,937 | 28.979592 | 78 | h |
null | ceph-main/src/messages/MOSDOp.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_MOSDOP_H
#define CEPH_MOSDOP_H
#include <atomic>
#include "MOSDFastDispatchOp.h"
#include "include/ceph_features.h"
#include "common/hobject.h"
/*
* OSD op
*
* oid - object id
* op - OSD_OP_DELETE, etc.
*
*/
class MOSDOpReply;
namespace _mosdop {
template<typename V>
class MOSDOp final : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 8;
static constexpr int COMPAT_VERSION = 3;
private:
uint32_t client_inc = 0;
__u32 osdmap_epoch = 0;
__u32 flags = 0;
utime_t mtime;
int32_t retry_attempt = -1; // 0 is first attempt. -1 if we don't know.
hobject_t hobj;
spg_t pgid;
ceph::buffer::list::const_iterator p;
// Decoding flags. Decoding is only needed for messages caught by pipe reader.
// Transition from true -> false without locks being held
// Can never see final_decode_needed == false and partial_decode_needed == true
std::atomic<bool> partial_decode_needed;
std::atomic<bool> final_decode_needed;
//
public:
V ops;
private:
snapid_t snap_seq;
std::vector<snapid_t> snaps;
uint64_t features;
bool bdata_encode;
osd_reqid_t reqid; // reqid explicitly set by sender
public:
friend MOSDOpReply;
ceph_tid_t get_client_tid() { return header.tid; }
void set_snapid(const snapid_t& s) {
hobj.snap = s;
}
void set_snaps(const std::vector<snapid_t>& i) {
snaps = i;
}
void set_snap_seq(const snapid_t& s) { snap_seq = s; }
void set_reqid(const osd_reqid_t rid) {
reqid = rid;
}
void set_spg(spg_t p) {
pgid = p;
}
// Fields decoded in partial decoding
pg_t get_pg() const {
ceph_assert(!partial_decode_needed);
return pgid.pgid;
}
spg_t get_spg() const override {
ceph_assert(!partial_decode_needed);
return pgid;
}
pg_t get_raw_pg() const {
ceph_assert(!partial_decode_needed);
return pg_t(hobj.get_hash(), pgid.pgid.pool());
}
epoch_t get_map_epoch() const override {
ceph_assert(!partial_decode_needed);
return osdmap_epoch;
}
int get_flags() const {
ceph_assert(!partial_decode_needed);
return flags;
}
osd_reqid_t get_reqid() const {
ceph_assert(!partial_decode_needed);
if (reqid.name != entity_name_t() || reqid.tid != 0) {
return reqid;
} else {
if (!final_decode_needed)
ceph_assert(reqid.inc == (int32_t)client_inc); // decode() should have done this
return osd_reqid_t(get_orig_source(),
reqid.inc,
header.tid);
}
}
// Fields decoded in final decoding
int get_client_inc() const {
ceph_assert(!final_decode_needed);
return client_inc;
}
utime_t get_mtime() const {
ceph_assert(!final_decode_needed);
return mtime;
}
object_locator_t get_object_locator() const {
ceph_assert(!final_decode_needed);
if (hobj.oid.name.empty())
return object_locator_t(hobj.pool, hobj.nspace, hobj.get_hash());
else
return object_locator_t(hobj);
}
const object_t& get_oid() const {
ceph_assert(!final_decode_needed);
return hobj.oid;
}
const hobject_t &get_hobj() const {
return hobj;
}
snapid_t get_snapid() const {
ceph_assert(!final_decode_needed);
return hobj.snap;
}
const snapid_t& get_snap_seq() const {
ceph_assert(!final_decode_needed);
return snap_seq;
}
const std::vector<snapid_t> &get_snaps() const {
ceph_assert(!final_decode_needed);
return snaps;
}
/**
* get retry attempt
*
* 0 is the first attempt.
*
* @return retry attempt, or -1 if we don't know
*/
int get_retry_attempt() const {
return retry_attempt;
}
uint64_t get_features() const {
if (features)
return features;
#ifdef WITH_SEASTAR
ceph_abort("In crimson, conn is independently maintained outside Message");
#else
return get_connection()->get_features();
#endif
}
MOSDOp()
: MOSDFastDispatchOp(CEPH_MSG_OSD_OP, HEAD_VERSION, COMPAT_VERSION),
partial_decode_needed(true),
final_decode_needed(true),
bdata_encode(false) { }
MOSDOp(int inc, long tid, const hobject_t& ho, spg_t& _pgid,
epoch_t _osdmap_epoch,
int _flags, uint64_t feat)
: MOSDFastDispatchOp(CEPH_MSG_OSD_OP, HEAD_VERSION, COMPAT_VERSION),
client_inc(inc),
osdmap_epoch(_osdmap_epoch), flags(_flags), retry_attempt(-1),
hobj(ho),
pgid(_pgid),
partial_decode_needed(false),
final_decode_needed(false),
features(feat),
bdata_encode(false) {
set_tid(tid);
// also put the client_inc in reqid.inc, so that get_reqid() can
// be used before the full message is decoded.
reqid.inc = inc;
}
private:
~MOSDOp() final {}
public:
void set_mtime(utime_t mt) { mtime = mt; }
void set_mtime(ceph::real_time mt) {
mtime = ceph::real_clock::to_timespec(mt);
}
// ops
void add_simple_op(int o, uint64_t off, uint64_t len) {
OSDOp osd_op;
osd_op.op.op = o;
osd_op.op.extent.offset = off;
osd_op.op.extent.length = len;
ops.push_back(osd_op);
}
void write(uint64_t off, uint64_t len, ceph::buffer::list& bl) {
add_simple_op(CEPH_OSD_OP_WRITE, off, len);
data = std::move(bl);
header.data_off = off;
}
void writefull(ceph::buffer::list& bl) {
add_simple_op(CEPH_OSD_OP_WRITEFULL, 0, bl.length());
data = std::move(bl);
header.data_off = 0;
}
void zero(uint64_t off, uint64_t len) {
add_simple_op(CEPH_OSD_OP_ZERO, off, len);
}
void truncate(uint64_t off) {
add_simple_op(CEPH_OSD_OP_TRUNCATE, off, 0);
}
void remove() {
add_simple_op(CEPH_OSD_OP_DELETE, 0, 0);
}
void read(uint64_t off, uint64_t len) {
add_simple_op(CEPH_OSD_OP_READ, off, len);
}
void stat() {
add_simple_op(CEPH_OSD_OP_STAT, 0, 0);
}
bool has_flag(__u32 flag) const { return flags & flag; };
bool is_retry_attempt() const { return flags & CEPH_OSD_FLAG_RETRY; }
void set_retry_attempt(unsigned a) {
if (a)
flags |= CEPH_OSD_FLAG_RETRY;
else
flags &= ~CEPH_OSD_FLAG_RETRY;
retry_attempt = a;
}
// marshalling
void encode_payload(uint64_t features) override {
using ceph::encode;
if( false == bdata_encode ) {
OSDOp::merge_osd_op_vector_in_data(ops, data);
bdata_encode = true;
}
if ((features & CEPH_FEATURE_OBJECTLOCATOR) == 0) {
// here is the old structure we are encoding to: //
#if 0
struct ceph_osd_request_head {
ceph_le32 client_inc; /* client incarnation */
struct ceph_object_layout layout; /* pgid */
ceph_le32 osdmap_epoch; /* client's osdmap epoch */
ceph_le32 flags;
struct ceph_timespec mtime; /* for mutations only */
struct ceph_eversion reassert_version; /* if we are replaying op */
ceph_le32 object_len; /* length of object name */
ceph_le64 snapid; /* snapid to read */
ceph_le64 snap_seq; /* writer's snap context */
ceph_le32 num_snaps;
ceph_le16 num_ops;
struct ceph_osd_op ops[]; /* followed by ops[], obj, ticket, snaps */
} __attribute__ ((packed));
#endif
header.version = 1;
encode(client_inc, payload);
__u32 su = 0;
encode(get_raw_pg(), payload);
encode(su, payload);
encode(osdmap_epoch, payload);
encode(flags, payload);
encode(mtime, payload);
encode(eversion_t(), payload); // reassert_version
__u32 oid_len = hobj.oid.name.length();
encode(oid_len, payload);
encode(hobj.snap, payload);
encode(snap_seq, payload);
__u32 num_snaps = snaps.size();
encode(num_snaps, payload);
//::encode(ops, payload);
__u16 num_ops = ops.size();
encode(num_ops, payload);
for (unsigned i = 0; i < ops.size(); i++)
encode(ops[i].op, payload);
ceph::encode_nohead(hobj.oid.name, payload);
ceph::encode_nohead(snaps, payload);
} else if ((features & CEPH_FEATURE_NEW_OSDOP_ENCODING) == 0) {
header.version = 6;
encode(client_inc, payload);
encode(osdmap_epoch, payload);
encode(flags, payload);
encode(mtime, payload);
encode(eversion_t(), payload); // reassert_version
encode(get_object_locator(), payload);
encode(get_raw_pg(), payload);
encode(hobj.oid, payload);
__u16 num_ops = ops.size();
encode(num_ops, payload);
for (unsigned i = 0; i < ops.size(); i++)
encode(ops[i].op, payload);
encode(hobj.snap, payload);
encode(snap_seq, payload);
encode(snaps, payload);
encode(retry_attempt, payload);
encode(features, payload);
if (reqid.name != entity_name_t() || reqid.tid != 0) {
encode(reqid, payload);
} else {
// don't include client_inc in the reqid for the legacy v6
// encoding or else we'll confuse older peers.
encode(osd_reqid_t(), payload);
}
} else if (!HAVE_FEATURE(features, RESEND_ON_SPLIT)) {
// reordered, v7 message encoding
header.version = 7;
encode(get_raw_pg(), payload);
encode(osdmap_epoch, payload);
encode(flags, payload);
encode(eversion_t(), payload); // reassert_version
encode(reqid, payload);
encode(client_inc, payload);
encode(mtime, payload);
encode(get_object_locator(), payload);
encode(hobj.oid, payload);
__u16 num_ops = ops.size();
encode(num_ops, payload);
for (unsigned i = 0; i < ops.size(); i++)
encode(ops[i].op, payload);
encode(hobj.snap, payload);
encode(snap_seq, payload);
encode(snaps, payload);
encode(retry_attempt, payload);
encode(features, payload);
} else {
// latest v8 encoding with hobject_t hash separate from pgid, no
// reassert version
header.version = HEAD_VERSION;
encode(pgid, payload);
encode(hobj.get_hash(), payload);
encode(osdmap_epoch, payload);
encode(flags, payload);
encode(reqid, payload);
encode_trace(payload, features);
// -- above decoded up front; below decoded post-dispatch thread --
encode(client_inc, payload);
encode(mtime, payload);
encode(get_object_locator(), payload);
encode(hobj.oid, payload);
__u16 num_ops = ops.size();
encode(num_ops, payload);
for (unsigned i = 0; i < ops.size(); i++)
encode(ops[i].op, payload);
encode(hobj.snap, payload);
encode(snap_seq, payload);
encode(snaps, payload);
encode(retry_attempt, payload);
encode(features, payload);
}
}
void decode_payload() override {
using ceph::decode;
ceph_assert(partial_decode_needed && final_decode_needed);
p = std::cbegin(payload);
// Always keep here the newest version of decoding order/rule
if (header.version == HEAD_VERSION) {
decode(pgid, p); // actual pgid
uint32_t hash;
decode(hash, p); // raw hash value
hobj.set_hash(hash);
decode(osdmap_epoch, p);
decode(flags, p);
decode(reqid, p);
decode_trace(p);
} else if (header.version == 7) {
decode(pgid.pgid, p); // raw pgid
hobj.set_hash(pgid.pgid.ps());
decode(osdmap_epoch, p);
decode(flags, p);
eversion_t reassert_version;
decode(reassert_version, p);
decode(reqid, p);
} else if (header.version < 2) {
// old decode
decode(client_inc, p);
old_pg_t opgid;
ceph::decode_raw(opgid, p);
pgid.pgid = opgid;
__u32 su;
decode(su, p);
decode(osdmap_epoch, p);
decode(flags, p);
decode(mtime, p);
eversion_t reassert_version;
decode(reassert_version, p);
__u32 oid_len;
decode(oid_len, p);
decode(hobj.snap, p);
decode(snap_seq, p);
__u32 num_snaps;
decode(num_snaps, p);
//::decode(ops, p);
__u16 num_ops;
decode(num_ops, p);
ops.resize(num_ops);
for (unsigned i = 0; i < num_ops; i++)
decode(ops[i].op, p);
ceph::decode_nohead(oid_len, hobj.oid.name, p);
ceph::decode_nohead(num_snaps, snaps, p);
// recalculate pgid hash value
pgid.pgid.set_ps(ceph_str_hash(CEPH_STR_HASH_RJENKINS,
hobj.oid.name.c_str(),
hobj.oid.name.length()));
hobj.pool = pgid.pgid.pool();
hobj.set_hash(pgid.pgid.ps());
retry_attempt = -1;
features = 0;
OSDOp::split_osd_op_vector_in_data(ops, data);
// we did the full decode
final_decode_needed = false;
// put client_inc in reqid.inc for get_reqid()'s benefit
reqid = osd_reqid_t();
reqid.inc = client_inc;
} else if (header.version < 7) {
decode(client_inc, p);
decode(osdmap_epoch, p);
decode(flags, p);
decode(mtime, p);
eversion_t reassert_version;
decode(reassert_version, p);
object_locator_t oloc;
decode(oloc, p);
if (header.version < 3) {
old_pg_t opgid;
ceph::decode_raw(opgid, p);
pgid.pgid = opgid;
} else {
decode(pgid.pgid, p);
}
decode(hobj.oid, p);
//::decode(ops, p);
__u16 num_ops;
decode(num_ops, p);
ops.resize(num_ops);
for (unsigned i = 0; i < num_ops; i++)
decode(ops[i].op, p);
decode(hobj.snap, p);
decode(snap_seq, p);
decode(snaps, p);
if (header.version >= 4)
decode(retry_attempt, p);
else
retry_attempt = -1;
if (header.version >= 5)
decode(features, p);
else
features = 0;
if (header.version >= 6)
decode(reqid, p);
else
reqid = osd_reqid_t();
hobj.pool = pgid.pgid.pool();
hobj.set_key(oloc.key);
hobj.nspace = oloc.nspace;
hobj.set_hash(pgid.pgid.ps());
OSDOp::split_osd_op_vector_in_data(ops, data);
// we did the full decode
final_decode_needed = false;
// put client_inc in reqid.inc for get_reqid()'s benefit
if (reqid.name == entity_name_t() && reqid.tid == 0)
reqid.inc = client_inc;
}
partial_decode_needed = false;
}
bool finish_decode() {
using ceph::decode;
ceph_assert(!partial_decode_needed); // partial decoding required
if (!final_decode_needed)
return false; // Message is already final decoded
ceph_assert(header.version >= 7);
decode(client_inc, p);
decode(mtime, p);
object_locator_t oloc;
decode(oloc, p);
decode(hobj.oid, p);
__u16 num_ops;
decode(num_ops, p);
ops.resize(num_ops);
for (unsigned i = 0; i < num_ops; i++)
decode(ops[i].op, p);
decode(hobj.snap, p);
decode(snap_seq, p);
decode(snaps, p);
decode(retry_attempt, p);
decode(features, p);
hobj.pool = pgid.pgid.pool();
hobj.set_key(oloc.key);
hobj.nspace = oloc.nspace;
OSDOp::split_osd_op_vector_in_data(ops, data);
final_decode_needed = false;
return true;
}
void clear_buffers() override {
OSDOp::clear_data(ops);
bdata_encode = false;
}
std::string_view get_type_name() const override { return "osd_op"; }
void print(std::ostream& out) const override {
out << "osd_op(";
if (!partial_decode_needed) {
out << get_reqid() << ' ';
out << pgid;
if (!final_decode_needed) {
out << ' ';
out << hobj
<< " " << ops
<< " snapc " << get_snap_seq() << "=" << snaps;
if (is_retry_attempt())
out << " RETRY=" << get_retry_attempt();
} else {
out << " " << get_raw_pg() << " (undecoded)";
}
out << " " << ceph_osd_flag_string(get_flags());
out << " e" << osdmap_epoch;
}
out << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
}
using MOSDOp = _mosdop::MOSDOp<std::vector<OSDOp>>;
#endif
| 16,164 | 25.37031 | 82 | h |
null | ceph-main/src/messages/MOSDOpReply.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_MOSDOPREPLY_H
#define CEPH_MOSDOPREPLY_H
#include "msg/Message.h"
#include "MOSDOp.h"
#include "common/errno.h"
/*
* OSD op reply
*
* oid - object id
* op - OSD_OP_DELETE, etc.
*
*/
class MOSDOpReply final : public Message {
private:
static constexpr int HEAD_VERSION = 8;
static constexpr int COMPAT_VERSION = 2;
object_t oid;
pg_t pgid;
std::vector<OSDOp> ops;
bool bdata_encode;
int64_t flags = 0;
errorcode32_t result;
eversion_t bad_replay_version;
eversion_t replay_version;
version_t user_version = 0;
epoch_t osdmap_epoch = 0;
int32_t retry_attempt = -1;
bool do_redirect;
request_redirect_t redirect;
public:
const object_t& get_oid() const { return oid; }
const pg_t& get_pg() const { return pgid; }
int get_flags() const { return flags; }
bool is_ondisk() const { return get_flags() & CEPH_OSD_FLAG_ONDISK; }
bool is_onnvram() const { return get_flags() & CEPH_OSD_FLAG_ONNVRAM; }
int get_result() const { return result; }
const eversion_t& get_replay_version() const { return replay_version; }
const version_t& get_user_version() const { return user_version; }
void set_result(int r) { result = r; }
void set_reply_versions(eversion_t v, version_t uv) {
replay_version = v;
user_version = uv;
/* We go through some shenanigans here for backwards compatibility
* with old clients, who do not look at our replay_version and
* user_version but instead see what we now call the
* bad_replay_version. On pools without caching
* the user_version infrastructure is a slightly-laggy copy of
* the regular pg version/at_version infrastructure; the difference
* being it is not updated on watch ops like that is -- but on updates
* it is set equal to at_version. This means that for non-watch write ops
* on classic pools, all three of replay_version, user_version, and
* bad_replay_version are identical. But for watch ops the replay_version
* has been updated, while the user_at_version has not, and the semantics
* we promised old clients are that the version they see is not an update.
* So set the bad_replay_version to be the same as the user_at_version. */
bad_replay_version = v;
if (uv) {
bad_replay_version.version = uv;
}
}
/* Don't fill in replay_version for non-write ops */
void set_enoent_reply_versions(const eversion_t& v, const version_t& uv) {
user_version = uv;
bad_replay_version = v;
}
void set_redirect(const request_redirect_t& redir) { redirect = redir; }
const request_redirect_t& get_redirect() const { return redirect; }
bool is_redirect_reply() const { return do_redirect; }
void add_flags(int f) { flags |= f; }
void claim_op_out_data(std::vector<OSDOp>& o) {
ceph_assert(ops.size() == o.size());
for (unsigned i = 0; i < o.size(); i++) {
ops[i].outdata = std::move(o[i].outdata);
}
}
void claim_ops(std::vector<OSDOp>& o) {
o.swap(ops);
bdata_encode = false;
}
void set_op_returns(const std::vector<pg_log_op_return_item_t>& op_returns) {
if (op_returns.size()) {
ceph_assert(ops.empty() || ops.size() == op_returns.size());
ops.resize(op_returns.size());
for (unsigned i = 0; i < op_returns.size(); ++i) {
ops[i].rval = op_returns[i].rval;
ops[i].outdata = op_returns[i].bl;
}
}
}
/**
* get retry attempt
*
* If we don't know the attempt (because the server is old), return -1.
*/
int get_retry_attempt() const {
return retry_attempt;
}
// osdmap
epoch_t get_map_epoch() const { return osdmap_epoch; }
/*osd_reqid_t get_reqid() { return osd_reqid_t(get_dest(),
head.client_inc,
head.tid); }
*/
public:
MOSDOpReply()
: Message{CEPH_MSG_OSD_OPREPLY, HEAD_VERSION, COMPAT_VERSION},
bdata_encode(false) {
do_redirect = false;
}
MOSDOpReply(const MOSDOp *req, int r, epoch_t e, int acktype,
bool ignore_out_data)
: Message{CEPH_MSG_OSD_OPREPLY, HEAD_VERSION, COMPAT_VERSION},
oid(req->hobj.oid), pgid(req->pgid.pgid), ops(req->ops),
bdata_encode(false) {
set_tid(req->get_tid());
result = r;
flags =
(req->flags & ~(CEPH_OSD_FLAG_ONDISK|CEPH_OSD_FLAG_ONNVRAM|CEPH_OSD_FLAG_ACK)) | acktype;
osdmap_epoch = e;
user_version = 0;
retry_attempt = req->get_retry_attempt();
do_redirect = false;
for (unsigned i = 0; i < ops.size(); i++) {
// zero out input data
ops[i].indata.clear();
if (ignore_out_data) {
// original request didn't set the RETURNVEC flag
ops[i].outdata.clear();
}
}
}
private:
~MOSDOpReply() final {}
public:
void encode_payload(uint64_t features) override {
using ceph::encode;
if(false == bdata_encode) {
OSDOp::merge_osd_op_vector_out_data(ops, data);
bdata_encode = true;
}
if ((features & CEPH_FEATURE_PGID64) == 0) {
header.version = 1;
ceph_osd_reply_head head;
memset(&head, 0, sizeof(head));
head.layout.ol_pgid = pgid.get_old_pg().v;
head.flags = flags;
head.osdmap_epoch = osdmap_epoch;
head.reassert_version = bad_replay_version;
head.result = result;
head.num_ops = ops.size();
head.object_len = oid.name.length();
encode(head, payload);
for (unsigned i = 0; i < head.num_ops; i++) {
encode(ops[i].op, payload);
}
ceph::encode_nohead(oid.name, payload);
} else {
header.version = HEAD_VERSION;
encode(oid, payload);
encode(pgid, payload);
encode(flags, payload);
encode(result, payload);
encode(bad_replay_version, payload);
encode(osdmap_epoch, payload);
__u32 num_ops = ops.size();
encode(num_ops, payload);
for (unsigned i = 0; i < num_ops; i++)
encode(ops[i].op, payload);
encode(retry_attempt, payload);
for (unsigned i = 0; i < num_ops; i++)
encode(ops[i].rval, payload);
encode(replay_version, payload);
encode(user_version, payload);
if ((features & CEPH_FEATURE_NEW_OSDOPREPLY_ENCODING) == 0) {
header.version = 6;
encode(redirect, payload);
} else {
do_redirect = !redirect.empty();
encode(do_redirect, payload);
if (do_redirect) {
encode(redirect, payload);
}
}
encode_trace(payload, features);
}
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
// Always keep here the newest version of decoding order/rule
if (header.version == HEAD_VERSION) {
decode(oid, p);
decode(pgid, p);
decode(flags, p);
decode(result, p);
decode(bad_replay_version, p);
decode(osdmap_epoch, p);
__u32 num_ops = ops.size();
decode(num_ops, p);
ops.resize(num_ops);
for (unsigned i = 0; i < num_ops; i++)
decode(ops[i].op, p);
decode(retry_attempt, p);
for (unsigned i = 0; i < num_ops; ++i)
decode(ops[i].rval, p);
OSDOp::split_osd_op_vector_out_data(ops, data);
decode(replay_version, p);
decode(user_version, p);
decode(do_redirect, p);
if (do_redirect)
decode(redirect, p);
decode_trace(p);
} else if (header.version < 2) {
ceph_osd_reply_head head;
decode(head, p);
ops.resize(head.num_ops);
for (unsigned i = 0; i < head.num_ops; i++) {
decode(ops[i].op, p);
}
ceph::decode_nohead(head.object_len, oid.name, p);
pgid = pg_t(head.layout.ol_pgid);
result = (int32_t)head.result;
flags = head.flags;
replay_version = head.reassert_version;
user_version = replay_version.version;
osdmap_epoch = head.osdmap_epoch;
retry_attempt = -1;
} else {
decode(oid, p);
decode(pgid, p);
decode(flags, p);
decode(result, p);
decode(bad_replay_version, p);
decode(osdmap_epoch, p);
__u32 num_ops = ops.size();
decode(num_ops, p);
ops.resize(num_ops);
for (unsigned i = 0; i < num_ops; i++)
decode(ops[i].op, p);
if (header.version >= 3)
decode(retry_attempt, p);
else
retry_attempt = -1;
if (header.version >= 4) {
for (unsigned i = 0; i < num_ops; ++i)
decode(ops[i].rval, p);
OSDOp::split_osd_op_vector_out_data(ops, data);
}
if (header.version >= 5) {
decode(replay_version, p);
decode(user_version, p);
} else {
replay_version = bad_replay_version;
user_version = replay_version.version;
}
if (header.version == 6) {
decode(redirect, p);
do_redirect = !redirect.empty();
}
if (header.version >= 7) {
decode(do_redirect, p);
if (do_redirect) {
decode(redirect, p);
}
}
if (header.version >= 8) {
decode_trace(p);
}
}
}
std::string_view get_type_name() const override { return "osd_op_reply"; }
void print(std::ostream& out) const override {
out << "osd_op_reply(" << get_tid()
<< " " << oid << " " << ops
<< " v" << get_replay_version()
<< " uv" << get_user_version();
if (is_ondisk())
out << " ondisk";
else if (is_onnvram())
out << " onnvram";
else
out << " ack";
out << " = " << get_result();
if (get_result() < 0) {
out << " (" << cpp_strerror(get_result()) << ")";
}
if (is_redirect_reply()) {
out << " redirect: { " << redirect << " }";
}
out << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 10,058 | 27.415254 | 95 | h |
null | ceph-main/src/messages/MOSDPGBackfill.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_MOSDPGBACKFILL_H
#define CEPH_MOSDPGBACKFILL_H
#include "MOSDFastDispatchOp.h"
class MOSDPGBackfill final : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 3;
public:
enum {
OP_BACKFILL_PROGRESS = 2,
OP_BACKFILL_FINISH = 3,
OP_BACKFILL_FINISH_ACK = 4,
};
const char *get_op_name(int o) const {
switch (o) {
case OP_BACKFILL_PROGRESS: return "progress";
case OP_BACKFILL_FINISH: return "finish";
case OP_BACKFILL_FINISH_ACK: return "finish_ack";
default: return "???";
}
}
__u32 op = 0;
epoch_t map_epoch = 0, query_epoch = 0;
spg_t pgid;
hobject_t last_backfill;
pg_stat_t stats;
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return query_epoch;
}
spg_t get_spg() const override {
return pgid;
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(op, p);
decode(map_epoch, p);
decode(query_epoch, p);
decode(pgid.pgid, p);
decode(last_backfill, p);
// For compatibility with version 1
decode(stats.stats, p);
decode(stats, p);
// Handle hobject_t format change
if (!last_backfill.is_max() &&
last_backfill.pool == -1)
last_backfill.pool = pgid.pool();
decode(pgid.shard, p);
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(op, payload);
encode(map_epoch, payload);
encode(query_epoch, payload);
encode(pgid.pgid, payload);
encode(last_backfill, payload);
// For compatibility with version 1
encode(stats.stats, payload);
encode(stats, payload);
encode(pgid.shard, payload);
}
MOSDPGBackfill()
: MOSDFastDispatchOp{MSG_OSD_PG_BACKFILL, HEAD_VERSION, COMPAT_VERSION} {}
MOSDPGBackfill(__u32 o, epoch_t e, epoch_t qe, spg_t p)
: MOSDFastDispatchOp{MSG_OSD_PG_BACKFILL, HEAD_VERSION, COMPAT_VERSION},
op(o),
map_epoch(e), query_epoch(e),
pgid(p) {}
private:
~MOSDPGBackfill() final {}
public:
std::string_view get_type_name() const override { return "pg_backfill"; }
void print(std::ostream& out) const override {
out << "pg_backfill(" << get_op_name(op)
<< " " << pgid
<< " e " << map_epoch << "/" << query_epoch
<< " lb " << last_backfill
<< ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,955 | 24.050847 | 78 | h |
null | ceph-main/src/messages/MOSDPGBackfillRemove.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 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_MOSDPGBACKFILLREMOVE_H
#define CEPH_MOSDPGBACKFILLREMOVE_H
#include "MOSDFastDispatchOp.h"
/*
* instruct non-primary to remove some objects during backfill
*/
class MOSDPGBackfillRemove final : public MOSDFastDispatchOp {
public:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
spg_t pgid; ///< target spg_t
epoch_t map_epoch = 0;
std::list<std::pair<hobject_t,eversion_t>> ls; ///< objects to remove
epoch_t get_map_epoch() const override {
return map_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDPGBackfillRemove()
: MOSDFastDispatchOp{MSG_OSD_PG_BACKFILL_REMOVE, HEAD_VERSION,
COMPAT_VERSION}
{}
MOSDPGBackfillRemove(spg_t pgid, epoch_t map_epoch)
: MOSDFastDispatchOp{MSG_OSD_PG_BACKFILL_REMOVE, HEAD_VERSION,
COMPAT_VERSION},
pgid(pgid),
map_epoch(map_epoch) {}
private:
~MOSDPGBackfillRemove() final {}
public:
std::string_view get_type_name() const override { return "backfill_remove"; }
void print(std::ostream& out) const override {
out << "backfill_remove(" << pgid << " e" << map_epoch
<< " " << ls << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid, payload);
encode(map_epoch, payload);
encode(ls, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid, p);
decode(map_epoch, p);
decode(ls, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,051 | 24.333333 | 79 | h |
null | ceph-main/src/messages/MOSDPGCreate2.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "msg/Message.h"
#include "osd/osd_types.h"
/*
* PGCreate2 - instruct an OSD to create some pgs
*/
class MOSDPGCreate2 final : public Message {
public:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 1;
epoch_t epoch = 0;
std::map<spg_t,std::pair<epoch_t,utime_t>> pgs;
std::map<spg_t,std::pair<pg_history_t,PastIntervals>> pg_extra;
MOSDPGCreate2()
: Message{MSG_OSD_PG_CREATE2, HEAD_VERSION, COMPAT_VERSION} {}
MOSDPGCreate2(epoch_t e)
: Message{MSG_OSD_PG_CREATE2, HEAD_VERSION, COMPAT_VERSION},
epoch(e) { }
private:
~MOSDPGCreate2() final {}
public:
std::string_view get_type_name() const override {
return "pg_create2";
}
void print(std::ostream& out) const override {
out << "pg_create2(e" << epoch << " " << pgs << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(epoch, payload);
encode(pgs, payload);
encode(pg_extra, payload);
}
void decode_payload() override {
auto p = payload.cbegin();
using ceph::decode;
decode(epoch, p);
decode(pgs, p);
if (header.version >= 2) {
decode(pg_extra, p);
}
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 1,418 | 23.894737 | 70 | h |
null | ceph-main/src/messages/MOSDPGCreated.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "osd/osd_types.h"
#include "messages/PaxosServiceMessage.h"
class MOSDPGCreated : public PaxosServiceMessage {
public:
pg_t pgid;
MOSDPGCreated()
: PaxosServiceMessage{MSG_OSD_PG_CREATED, 0}
{}
MOSDPGCreated(pg_t pgid)
: PaxosServiceMessage{MSG_OSD_PG_CREATED, 0},
pgid(pgid)
{}
std::string_view get_type_name() const override { return "pg_created"; }
void print(std::ostream& out) const override {
out << "osd_pg_created(" << pgid << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
encode(pgid, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(pgid, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 981 | 24.842105 | 74 | h |
null | ceph-main/src/messages/MOSDPGInfo.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_MOSDPGINFO_H
#define CEPH_MOSDPGINFO_H
#include "msg/Message.h"
#include "osd/osd_types.h"
class MOSDPGInfo final : public Message {
private:
static constexpr int HEAD_VERSION = 6;
static constexpr int COMPAT_VERSION = 6;
epoch_t epoch = 0;
public:
using pg_list_t = std::vector<pg_notify_t>;
pg_list_t pg_list;
epoch_t get_epoch() const { return epoch; }
MOSDPGInfo()
: MOSDPGInfo{0, {}}
{}
MOSDPGInfo(epoch_t mv)
: MOSDPGInfo(mv, {})
{}
MOSDPGInfo(epoch_t mv, pg_list_t&& l)
: Message{MSG_OSD_PG_INFO, HEAD_VERSION, COMPAT_VERSION},
epoch{mv},
pg_list{std::move(l)}
{
set_priority(CEPH_MSG_PRIO_HIGH);
}
private:
~MOSDPGInfo() final {}
public:
std::string_view get_type_name() const override { return "pg_info"; }
void print(std::ostream& out) const override {
out << "pg_info(";
for (auto i = pg_list.begin();
i != pg_list.end();
++i) {
if (i != pg_list.begin())
out << " ";
out << *i;
}
out << " epoch " << epoch
<< ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
header.version = HEAD_VERSION;
encode(epoch, payload);
assert(HAVE_FEATURE(features, SERVER_OCTOPUS));
encode(pg_list, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(epoch, p);
decode(pg_list, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 1,980 | 22.305882 | 71 | h |
null | ceph-main/src/messages/MOSDPGInfo2.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "messages/MOSDPeeringOp.h"
#include "osd/PGPeeringEvent.h"
class MOSDPGInfo2 final : public MOSDPeeringOp {
private:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
public:
spg_t spgid;
epoch_t epoch_sent;
epoch_t min_epoch;
pg_info_t info;
std::optional<pg_lease_t> lease;
std::optional<pg_lease_ack_t> lease_ack;
spg_t get_spg() const override {
return spgid;
}
epoch_t get_map_epoch() const override {
return epoch_sent;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
PGPeeringEvent *get_event() override {
return new PGPeeringEvent(
epoch_sent,
min_epoch,
MInfoRec(
pg_shard_t(get_source().num(), info.pgid.shard),
info,
epoch_sent,
lease,
lease_ack));
}
MOSDPGInfo2() : MOSDPeeringOp{MSG_OSD_PG_INFO2,
HEAD_VERSION, COMPAT_VERSION} {
set_priority(CEPH_MSG_PRIO_HIGH);
}
MOSDPGInfo2(
spg_t s,
pg_info_t q,
epoch_t sent,
epoch_t min,
std::optional<pg_lease_t> l,
std::optional<pg_lease_ack_t> la)
: MOSDPeeringOp{MSG_OSD_PG_INFO2, HEAD_VERSION, COMPAT_VERSION},
spgid(s),
epoch_sent(sent),
min_epoch(min),
info(q),
lease(l),
lease_ack(la) {
set_priority(CEPH_MSG_PRIO_HIGH);
}
private:
~MOSDPGInfo2() final {}
public:
std::string_view get_type_name() const override {
return "pg_info2";
}
void inner_print(std::ostream& out) const override {
out << spgid << " " << info;
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(spgid, payload);
encode(epoch_sent, payload);
encode(min_epoch, payload);
encode(info, payload);
encode(lease, payload);
encode(lease_ack, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(spgid, p);
decode(epoch_sent, p);
decode(min_epoch, p);
decode(info, p);
decode(lease, p);
decode(lease_ack, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 2,246 | 21.69697 | 70 | h |
null | ceph-main/src/messages/MOSDPGLease.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "msg/Message.h"
#include "osd/osd_types.h"
class MOSDPGLease final : public MOSDPeeringOp {
private:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
epoch_t epoch = 0;
spg_t spgid;
pg_lease_t lease;
public:
spg_t get_spg() const {
return spgid;
}
epoch_t get_map_epoch() const {
return epoch;
}
epoch_t get_min_epoch() const {
return epoch;
}
PGPeeringEvent *get_event() override {
return new PGPeeringEvent(
epoch,
epoch,
MLease(epoch, get_source().num(), lease));
}
MOSDPGLease() : MOSDPeeringOp{MSG_OSD_PG_LEASE,
HEAD_VERSION, COMPAT_VERSION} {}
MOSDPGLease(version_t mv, spg_t p, pg_lease_t lease) :
MOSDPeeringOp{MSG_OSD_PG_LEASE,
HEAD_VERSION, COMPAT_VERSION},
epoch(mv),
spgid(p),
lease(lease) { }
private:
~MOSDPGLease() final {}
public:
std::string_view get_type_name() const override { return "pg_lease"; }
void inner_print(std::ostream& out) const override {
out << lease;
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(epoch, payload);
encode(spgid, payload);
encode(lease, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(epoch, p);
decode(spgid, p);
decode(lease, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 1,589 | 22.043478 | 72 | h |
null | ceph-main/src/messages/MOSDPGLeaseAck.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "msg/Message.h"
#include "osd/osd_types.h"
class MOSDPGLeaseAck final : public MOSDPeeringOp {
private:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
epoch_t epoch = 0;
spg_t spgid;
pg_lease_ack_t lease_ack;
public:
spg_t get_spg() const {
return spgid;
}
epoch_t get_map_epoch() const {
return epoch;
}
epoch_t get_min_epoch() const {
return epoch;
}
PGPeeringEvent *get_event() override {
return new PGPeeringEvent(
epoch,
epoch,
MLeaseAck(epoch, get_source().num(), lease_ack));
}
MOSDPGLeaseAck() : MOSDPeeringOp{MSG_OSD_PG_LEASE_ACK,
HEAD_VERSION, COMPAT_VERSION} {}
MOSDPGLeaseAck(version_t mv, spg_t p, pg_lease_ack_t lease_ack) :
MOSDPeeringOp{MSG_OSD_PG_LEASE_ACK,
HEAD_VERSION, COMPAT_VERSION},
epoch(mv),
spgid(p),
lease_ack(lease_ack) { }
private:
~MOSDPGLeaseAck() final {}
public:
std::string_view get_type_name() const override { return "pg_lease_ack"; }
void inner_print(std::ostream& out) const override {
out << lease_ack;
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(epoch, payload);
encode(spgid, payload);
encode(lease_ack, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(epoch, p);
decode(spgid, p);
decode(lease_ack, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 1,659 | 23.057971 | 76 | h |
null | ceph-main/src/messages/MOSDPGLog.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_MOSDPGLOG_H
#define CEPH_MOSDPGLOG_H
#include "messages/MOSDPeeringOp.h"
#include "osd/PGPeeringEvent.h"
class MOSDPGLog final : public MOSDPeeringOp {
private:
static constexpr int HEAD_VERSION = 6;
static constexpr int COMPAT_VERSION = 6;
epoch_t epoch = 0;
/// query_epoch is the epoch of the query being responded to, or
/// the current epoch if this is not being sent in response to a
/// query. This allows the recipient to disregard responses to old
/// queries.
epoch_t query_epoch = 0;
public:
shard_id_t to;
shard_id_t from;
pg_info_t info;
pg_log_t log;
pg_missing_t missing;
PastIntervals past_intervals;
std::optional<pg_lease_t> lease;
epoch_t get_epoch() const { return epoch; }
spg_t get_pgid() const { return spg_t(info.pgid.pgid, to); }
epoch_t get_query_epoch() const { return query_epoch; }
spg_t get_spg() const override {
return spg_t(info.pgid.pgid, to);
}
epoch_t get_map_epoch() const override {
return epoch;
}
epoch_t get_min_epoch() const override {
return query_epoch;
}
PGPeeringEvent *get_event() override {
return new PGPeeringEvent(
epoch, query_epoch,
MLogRec(pg_shard_t(get_source().num(), from),
this),
true,
new PGCreateInfo(
get_spg(),
query_epoch,
info.history,
past_intervals,
false));
}
MOSDPGLog() : MOSDPeeringOp{MSG_OSD_PG_LOG, HEAD_VERSION, COMPAT_VERSION} {
set_priority(CEPH_MSG_PRIO_HIGH);
}
MOSDPGLog(shard_id_t to, shard_id_t from,
version_t mv, const pg_info_t& i, epoch_t query_epoch)
: MOSDPeeringOp{MSG_OSD_PG_LOG, HEAD_VERSION, COMPAT_VERSION},
epoch(mv), query_epoch(query_epoch),
to(to), from(from),
info(i) {
set_priority(CEPH_MSG_PRIO_HIGH);
}
private:
~MOSDPGLog() final {}
public:
std::string_view get_type_name() const override { return "PGlog"; }
void inner_print(std::ostream& out) const override {
// NOTE: log is not const, but operator<< doesn't touch fields
// swapped out by OSD code.
out << "log " << log
<< " pi " << past_intervals;
if (lease) {
out << " " << *lease;
}
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(epoch, payload);
encode(info, payload);
encode(log, payload);
encode(missing, payload, features);
assert(HAVE_FEATURE(features, SERVER_NAUTILUS));
encode(query_epoch, payload);
encode(past_intervals, payload);
encode(to, payload);
encode(from, payload);
encode(lease, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(epoch, p);
decode(info, p);
log.decode(p, info.pgid.pool());
missing.decode(p, info.pgid.pool());
decode(query_epoch, p);
decode(past_intervals, p);
decode(to, p);
decode(from, p);
assert(header.version >= 6);
decode(lease, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 3,482 | 25.587786 | 77 | h |
null | ceph-main/src/messages/MOSDPGNotify.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_MOSDPGPEERNOTIFY_H
#define CEPH_MOSDPGPEERNOTIFY_H
#include "msg/Message.h"
#include "osd/osd_types.h"
/*
* PGNotify - notify primary of my PGs and versions.
*/
class MOSDPGNotify final : public Message {
private:
static constexpr int HEAD_VERSION = 7;
static constexpr int COMPAT_VERSION = 7;
epoch_t epoch = 0;
/// query_epoch is the epoch of the query being responded to, or
/// the current epoch if this is not being sent in response to a
/// query. This allows the recipient to disregard responses to old
/// queries.
using pg_list_t = std::vector<pg_notify_t>;
pg_list_t pg_list;
public:
version_t get_epoch() const { return epoch; }
const pg_list_t& get_pg_list() const {
return pg_list;
}
MOSDPGNotify()
: MOSDPGNotify(0, {})
{}
MOSDPGNotify(epoch_t e, pg_list_t&& l)
: Message{MSG_OSD_PG_NOTIFY, HEAD_VERSION, COMPAT_VERSION},
epoch(e),
pg_list(std::move(l)) {
set_priority(CEPH_MSG_PRIO_HIGH);
}
private:
~MOSDPGNotify() final {}
public:
std::string_view get_type_name() const override { return "PGnot"; }
void encode_payload(uint64_t features) override {
using ceph::encode;
header.version = HEAD_VERSION;
encode(epoch, payload);
assert(HAVE_FEATURE(features, SERVER_OCTOPUS));
encode(pg_list, payload);
}
void decode_payload() override {
auto p = payload.cbegin();
using ceph::decode;
decode(epoch, p);
decode(pg_list, p);
}
void print(std::ostream& out) const override {
out << "pg_notify(";
for (auto i = pg_list.begin();
i != pg_list.end();
++i) {
if (i != pg_list.begin())
out << " ";
out << *i;
}
out << " epoch " << epoch
<< ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,294 | 23.945652 | 71 | h |
null | ceph-main/src/messages/MOSDPGNotify2.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "messages/MOSDPeeringOp.h"
#include "osd/PGPeeringEvent.h"
class MOSDPGNotify2 final : public MOSDPeeringOp {
private:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
public:
spg_t spgid;
pg_notify_t notify;
spg_t get_spg() const override {
return spgid;
}
epoch_t get_map_epoch() const override {
return notify.epoch_sent;
}
epoch_t get_min_epoch() const override {
return notify.query_epoch;
}
PGPeeringEvent *get_event() override {
return new PGPeeringEvent(
notify.epoch_sent,
notify.query_epoch,
MNotifyRec(
spgid,
pg_shard_t(get_source().num(), notify.from),
notify,
#ifdef WITH_SEASTAR
features
#else
get_connection()->get_features()
#endif
),
true,
new PGCreateInfo(
spgid,
notify.epoch_sent,
notify.info.history,
notify.past_intervals,
false));
}
MOSDPGNotify2() : MOSDPeeringOp{MSG_OSD_PG_NOTIFY2,
HEAD_VERSION, COMPAT_VERSION} {
set_priority(CEPH_MSG_PRIO_HIGH);
}
MOSDPGNotify2(
spg_t s,
pg_notify_t n)
: MOSDPeeringOp{MSG_OSD_PG_NOTIFY2, HEAD_VERSION, COMPAT_VERSION},
spgid(s),
notify(n) {
set_priority(CEPH_MSG_PRIO_HIGH);
}
private:
~MOSDPGNotify2() final {}
public:
std::string_view get_type_name() const override {
return "pg_notify2";
}
void inner_print(std::ostream& out) const override {
out << spgid << " " << notify;
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(spgid, payload);
encode(notify, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(spgid, p);
decode(notify, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 1,949 | 20.666667 | 70 | h |
null | ceph-main/src/messages/MOSDPGPull.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Inktank Storage, 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 MOSDPGPULL_H
#define MOSDPGPULL_H
#include "MOSDFastDispatchOp.h"
class MOSDPGPull : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 2;
std::vector<PullOp> pulls;
public:
pg_shard_t from;
spg_t pgid;
epoch_t map_epoch = 0, min_epoch = 0;
uint64_t cost = 0;
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
std::vector<PullOp> take_pulls() {
return std::move(pulls);
}
void set_pulls(std::vector<PullOp>&& pull_ops) {
pulls = std::move(pull_ops);
}
MOSDPGPull()
: MOSDFastDispatchOp{MSG_OSD_PG_PULL, HEAD_VERSION, COMPAT_VERSION}
{}
void compute_cost(CephContext *cct) {
cost = 0;
for (auto i = pulls.begin(); i != pulls.end(); ++i) {
cost += i->cost(cct);
}
}
int get_cost() const override {
return cost;
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid.pgid, p);
decode(map_epoch, p);
decode(pulls, p);
decode(cost, p);
decode(pgid.shard, p);
decode(from, p);
if (header.version >= 3) {
decode(min_epoch, p);
} else {
min_epoch = map_epoch;
}
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid.pgid, payload);
encode(map_epoch, payload);
encode(pulls, payload, features);
encode(cost, payload);
encode(pgid.shard, payload);
encode(from, payload);
encode(min_epoch, payload);
}
std::string_view get_type_name() const override { return "MOSDPGPull"; }
void print(std::ostream& out) const override {
out << "MOSDPGPull(" << pgid
<< " e" << map_epoch << "/" << min_epoch
<< " cost " << cost
<< ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,426 | 21.682243 | 74 | h |
null | ceph-main/src/messages/MOSDPGPush.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Inktank Storage, 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 MOSDPGPUSH_H
#define MOSDPGPUSH_H
#include "MOSDFastDispatchOp.h"
class MOSDPGPush : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 4;
static constexpr int COMPAT_VERSION = 2;
public:
pg_shard_t from;
spg_t pgid;
epoch_t map_epoch = 0, min_epoch = 0;
std::vector<PushOp> pushes;
bool is_repair = false;
private:
uint64_t cost = 0;
public:
void compute_cost(CephContext *cct) {
cost = 0;
for (auto i = pushes.begin(); i != pushes.end(); ++i) {
cost += i->cost(cct);
}
}
int get_cost() const override {
return cost;
}
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
void set_cost(uint64_t c) {
cost = c;
}
MOSDPGPush()
: MOSDFastDispatchOp{MSG_OSD_PG_PUSH, HEAD_VERSION, COMPAT_VERSION}
{}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid.pgid, p);
decode(map_epoch, p);
decode(pushes, p);
decode(cost, p);
decode(pgid.shard, p);
decode(from, p);
if (header.version >= 3) {
decode(min_epoch, p);
} else {
min_epoch = map_epoch;
}
if (header.version >= 4) {
decode(is_repair, p);
} else {
is_repair = false;
}
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid.pgid, payload);
encode(map_epoch, payload);
encode(pushes, payload, features);
encode(cost, payload);
encode(pgid.shard, payload);
encode(from, payload);
encode(min_epoch, payload);
encode(is_repair, payload);
}
std::string_view get_type_name() const override { return "MOSDPGPush"; }
void print(std::ostream& out) const override {
out << "MOSDPGPush(" << pgid
<< " " << map_epoch << "/" << min_epoch
<< " " << pushes;
out << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,503 | 21.159292 | 74 | h |
null | ceph-main/src/messages/MOSDPGPushReply.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Inktank Storage, 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 MOSDPGPUSHREPLY_H
#define MOSDPGPUSHREPLY_H
#include "MOSDFastDispatchOp.h"
class MOSDPGPushReply : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 2;
public:
pg_shard_t from;
spg_t pgid;
epoch_t map_epoch = 0, min_epoch = 0;
std::vector<PushReplyOp> replies;
uint64_t cost = 0;
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDPGPushReply()
: MOSDFastDispatchOp{MSG_OSD_PG_PUSH_REPLY, HEAD_VERSION, COMPAT_VERSION}
{}
void compute_cost(CephContext *cct) {
cost = 0;
for (auto i = replies.begin(); i != replies.end(); ++i) {
cost += i->cost(cct);
}
}
int get_cost() const override {
return cost;
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid.pgid, p);
decode(map_epoch, p);
decode(replies, p);
decode(cost, p);
decode(pgid.shard, p);
decode(from, p);
if (header.version >= 3) {
decode(min_epoch, p);
} else {
min_epoch = map_epoch;
}
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid.pgid, payload);
encode(map_epoch, payload);
encode(replies, payload);
encode(cost, payload);
encode(pgid.shard, payload);
encode(from, payload);
encode(min_epoch, payload);
}
void print(std::ostream& out) const override {
out << "MOSDPGPushReply(" << pgid
<< " " << map_epoch << "/" << min_epoch
<< " " << replies;
out << ")";
}
std::string_view get_type_name() const override { return "MOSDPGPushReply"; }
};
#endif
| 2,197 | 22.136842 | 79 | h |
null | ceph-main/src/messages/MOSDPGQuery.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_MOSDPGQUERY_H
#define CEPH_MOSDPGQUERY_H
#include "common/hobject.h"
#include "msg/Message.h"
/*
* PGQuery - query another OSD as to the contents of their PGs
*/
class MOSDPGQuery final : public Message {
private:
static constexpr int HEAD_VERSION = 4;
static constexpr int COMPAT_VERSION = 4;
version_t epoch = 0;
public:
version_t get_epoch() const { return epoch; }
using pg_list_t = std::map<spg_t, pg_query_t>;
pg_list_t pg_list;
MOSDPGQuery() : Message{MSG_OSD_PG_QUERY,
HEAD_VERSION,
COMPAT_VERSION} {
set_priority(CEPH_MSG_PRIO_HIGH);
}
MOSDPGQuery(epoch_t e, pg_list_t&& ls) :
Message{MSG_OSD_PG_QUERY,
HEAD_VERSION,
COMPAT_VERSION},
epoch(e),
pg_list(std::move(ls)) {
set_priority(CEPH_MSG_PRIO_HIGH);
}
private:
~MOSDPGQuery() final {}
public:
std::string_view get_type_name() const override { return "pg_query"; }
void print(std::ostream& out) const override {
out << "pg_query(";
for (auto p = pg_list.begin(); p != pg_list.end(); ++p) {
if (p != pg_list.begin())
out << ",";
out << p->first;
}
out << " epoch " << epoch << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(epoch, payload);
encode(pg_list, payload, features);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(epoch, p);
decode(pg_list, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,012 | 23.253012 | 72 | h |
null | ceph-main/src/messages/MOSDPGQuery2.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "messages/MOSDPeeringOp.h"
#include "osd/PGPeeringEvent.h"
class MOSDPGQuery2 final : public MOSDPeeringOp {
private:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
public:
spg_t spgid;
pg_query_t query;
spg_t get_spg() const override {
return spgid;
}
epoch_t get_map_epoch() const override {
return query.epoch_sent;
}
epoch_t get_min_epoch() const override {
return query.epoch_sent;
}
PGPeeringEvent *get_event() override {
return new PGPeeringEvent(
query.epoch_sent,
query.epoch_sent,
MQuery(
spgid,
pg_shard_t(get_source().num(), query.from),
query,
query.epoch_sent),
false);
}
MOSDPGQuery2() : MOSDPeeringOp{MSG_OSD_PG_QUERY2,
HEAD_VERSION, COMPAT_VERSION} {
set_priority(CEPH_MSG_PRIO_HIGH);
}
MOSDPGQuery2(
spg_t s,
pg_query_t q)
: MOSDPeeringOp{MSG_OSD_PG_QUERY2, HEAD_VERSION, COMPAT_VERSION},
spgid(s),
query(q) {
set_priority(CEPH_MSG_PRIO_HIGH);
}
private:
~MOSDPGQuery2() final {}
public:
std::string_view get_type_name() const override {
return "pg_query2";
}
void inner_print(std::ostream& out) const override {
out << spgid << " " << query;
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(spgid, payload);
encode(query, payload, features);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(spgid, p);
decode(query, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 1,761 | 21.303797 | 70 | h |
null | ceph-main/src/messages/MOSDPGReadyToMerge.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
class MOSDPGReadyToMerge : public PaxosServiceMessage {
public:
pg_t pgid;
eversion_t source_version, target_version;
epoch_t last_epoch_started = 0;
epoch_t last_epoch_clean = 0;
bool ready = true;
MOSDPGReadyToMerge()
: PaxosServiceMessage{MSG_OSD_PG_READY_TO_MERGE, 0}
{}
MOSDPGReadyToMerge(pg_t p, eversion_t sv, eversion_t tv,
epoch_t les, epoch_t lec, bool r, epoch_t v)
: PaxosServiceMessage{MSG_OSD_PG_READY_TO_MERGE, v},
pgid(p),
source_version(sv),
target_version(tv),
last_epoch_started(les),
last_epoch_clean(lec),
ready(r)
{}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
encode(pgid, payload);
encode(source_version, payload);
encode(target_version, payload);
encode(last_epoch_started, payload);
encode(last_epoch_clean, payload);
encode(ready, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(pgid, p);
decode(source_version, p);
decode(target_version, p);
decode(last_epoch_started, p);
decode(last_epoch_clean, p);
decode(ready, p);
}
std::string_view get_type_name() const override { return "osd_pg_ready_to_merge"; }
void print(std::ostream &out) const {
out << get_type_name()
<< "(" << pgid
<< " sv " << source_version
<< " tv " << target_version
<< " les/c " << last_epoch_started << "/" << last_epoch_clean
<< (ready ? " ready" : " NOT READY")
<< " v" << version << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 1,812 | 28.241935 | 85 | h |
null | ceph-main/src/messages/MOSDPGRecoveryDelete.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_MOSDPGRECOVERYDELETE_H
#define CEPH_MOSDPGRECOVERYDELETE_H
#include "MOSDFastDispatchOp.h"
/*
* instruct non-primary to remove some objects during recovery
*/
class MOSDPGRecoveryDelete final : public MOSDFastDispatchOp {
public:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 1;
pg_shard_t from;
spg_t pgid; ///< target spg_t
epoch_t map_epoch, min_epoch;
std::list<std::pair<hobject_t, eversion_t>> objects; ///< objects to remove
private:
uint64_t cost = 0;
public:
int get_cost() const override {
return cost;
}
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
void set_cost(uint64_t c) {
cost = c;
}
MOSDPGRecoveryDelete()
: MOSDFastDispatchOp{MSG_OSD_PG_RECOVERY_DELETE, HEAD_VERSION,
COMPAT_VERSION}
{}
MOSDPGRecoveryDelete(pg_shard_t from, spg_t pgid, epoch_t map_epoch,
epoch_t min_epoch)
: MOSDFastDispatchOp{MSG_OSD_PG_RECOVERY_DELETE, HEAD_VERSION,
COMPAT_VERSION},
from(from),
pgid(pgid),
map_epoch(map_epoch),
min_epoch(min_epoch)
{}
private:
~MOSDPGRecoveryDelete() final {}
public:
std::string_view get_type_name() const { return "recovery_delete"; }
void print(std::ostream& out) const {
out << "MOSDPGRecoveryDelete(" << pgid << " e" << map_epoch << ","
<< min_epoch << " " << objects << ")";
}
void encode_payload(uint64_t features) {
using ceph::encode;
encode(from, payload);
encode(pgid, payload);
encode(map_epoch, payload);
encode(min_epoch, payload);
encode(cost, payload);
encode(objects, payload);
}
void decode_payload() {
using ceph::decode;
auto p = payload.cbegin();
decode(from, p);
decode(pgid, p);
decode(map_epoch, p);
decode(min_epoch, p);
decode(cost, p);
decode(objects, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,226 | 22.442105 | 80 | h |
null | ceph-main/src/messages/MOSDPGRecoveryDeleteReply.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef MOSDRECOVERYDELETEREPLY_H
#define MOSDRECOVERYDELETEREPLY_H
#include "MOSDFastDispatchOp.h"
class MOSDPGRecoveryDeleteReply : public MOSDFastDispatchOp {
public:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 1;
pg_shard_t from;
spg_t pgid;
epoch_t map_epoch = 0;
epoch_t min_epoch = 0;
std::list<std::pair<hobject_t, eversion_t> > objects;
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDPGRecoveryDeleteReply()
: MOSDFastDispatchOp{MSG_OSD_PG_RECOVERY_DELETE_REPLY, HEAD_VERSION, COMPAT_VERSION}
{}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid.pgid, p);
decode(map_epoch, p);
decode(min_epoch, p);
decode(objects, p);
decode(pgid.shard, p);
decode(from, p);
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid.pgid, payload);
encode(map_epoch, payload);
encode(min_epoch, payload);
encode(objects, payload);
encode(pgid.shard, payload);
encode(from, payload);
}
void print(std::ostream& out) const override {
out << "MOSDPGRecoveryDeleteReply(" << pgid
<< " e" << map_epoch << "," << min_epoch << " " << objects << ")";
}
std::string_view get_type_name() const override { return "recovery_delete_reply"; }
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 1,719 | 24.294118 | 88 | h |
null | ceph-main/src/messages/MOSDPGRemove.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_MOSDPGREMOVE_H
#define CEPH_MOSDPGREMOVE_H
#include "common/hobject.h"
#include "msg/Message.h"
class MOSDPGRemove final : public Message {
private:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 3;
epoch_t epoch = 0;
public:
std::vector<spg_t> pg_list;
epoch_t get_epoch() const { return epoch; }
MOSDPGRemove() :
Message{MSG_OSD_PG_REMOVE, HEAD_VERSION, COMPAT_VERSION} {}
MOSDPGRemove(epoch_t e, std::vector<spg_t>& l) :
Message{MSG_OSD_PG_REMOVE, HEAD_VERSION, COMPAT_VERSION} {
this->epoch = e;
pg_list.swap(l);
}
private:
~MOSDPGRemove() final {}
public:
std::string_view get_type_name() const override { return "PGrm"; }
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(epoch, payload);
encode(pg_list, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(epoch, p);
decode(pg_list, p);
}
void print(std::ostream& out) const override {
out << "osd pg remove(" << "epoch " << epoch << "; ";
for (auto i = pg_list.begin(); i != pg_list.end(); ++i) {
out << "pg" << *i << "; ";
}
out << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 1,780 | 23.736111 | 71 | h |
null | ceph-main/src/messages/MOSDPGScan.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_MOSDPGSCAN_H
#define CEPH_MOSDPGSCAN_H
#include "MOSDFastDispatchOp.h"
class MOSDPGScan final : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 2;
public:
enum {
OP_SCAN_GET_DIGEST = 1, // just objects and versions
OP_SCAN_DIGEST = 2, // result
};
const char *get_op_name(int o) const {
switch (o) {
case OP_SCAN_GET_DIGEST: return "get_digest";
case OP_SCAN_DIGEST: return "digest";
default: return "???";
}
}
__u32 op = 0;
epoch_t map_epoch = 0, query_epoch = 0;
pg_shard_t from;
spg_t pgid;
hobject_t begin, end;
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return query_epoch;
}
spg_t get_spg() const override {
return pgid;
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(op, p);
decode(map_epoch, p);
decode(query_epoch, p);
decode(pgid.pgid, p);
decode(begin, p);
decode(end, p);
// handle hobject_t format upgrade
if (!begin.is_max() && begin.pool == -1)
begin.pool = pgid.pool();
if (!end.is_max() && end.pool == -1)
end.pool = pgid.pool();
decode(from, p);
decode(pgid.shard, p);
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(op, payload);
encode(map_epoch, payload);
assert(HAVE_FEATURE(features, SERVER_NAUTILUS));
encode(query_epoch, payload);
encode(pgid.pgid, payload);
encode(begin, payload);
encode(end, payload);
encode(from, payload);
encode(pgid.shard, payload);
}
MOSDPGScan()
: MOSDFastDispatchOp{MSG_OSD_PG_SCAN, HEAD_VERSION, COMPAT_VERSION} {}
MOSDPGScan(__u32 o, pg_shard_t from,
epoch_t e, epoch_t qe, spg_t p, hobject_t be, hobject_t en)
: MOSDFastDispatchOp{MSG_OSD_PG_SCAN, HEAD_VERSION, COMPAT_VERSION},
op(o),
map_epoch(e), query_epoch(qe),
from(from),
pgid(p),
begin(be), end(en) {
}
private:
~MOSDPGScan() final {}
public:
std::string_view get_type_name() const override { return "pg_scan"; }
void print(std::ostream& out) const override {
out << "pg_scan(" << get_op_name(op)
<< " " << pgid
<< " " << begin << "-" << end
<< " e " << map_epoch << "/" << query_epoch
<< ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,953 | 24.465517 | 74 | h |
null | ceph-main/src/messages/MOSDPGTemp.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_MOSDPGTEMP_H
#define CEPH_MOSDPGTEMP_H
#include "messages/PaxosServiceMessage.h"
class MOSDPGTemp final : public PaxosServiceMessage {
public:
epoch_t map_epoch = 0;
std::map<pg_t, std::vector<int32_t> > pg_temp;
bool forced = false;
MOSDPGTemp(epoch_t e)
: PaxosServiceMessage{MSG_OSD_PGTEMP, e, HEAD_VERSION, COMPAT_VERSION},
map_epoch(e)
{}
MOSDPGTemp()
: MOSDPGTemp(0)
{}
private:
~MOSDPGTemp() final {}
public:
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
encode(map_epoch, payload);
encode(pg_temp, payload);
encode(forced, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(map_epoch, p);
decode(pg_temp, p);
if (header.version >= 2) {
decode(forced, p);
}
}
std::string_view get_type_name() const override { return "osd_pgtemp"; }
void print(std::ostream &out) const override {
out << "osd_pgtemp(e" << map_epoch << " " << pg_temp << " v" << version << ")";
}
private:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 1;
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 1,737 | 23.828571 | 83 | h |
null | ceph-main/src/messages/MOSDPGTrim.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_MOSDPGTRIM_H
#define CEPH_MOSDPGTRIM_H
#include "msg/Message.h"
#include "messages/MOSDPeeringOp.h"
#include "osd/PGPeeringEvent.h"
class MOSDPGTrim final : public MOSDPeeringOp {
private:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 2;
public:
epoch_t epoch = 0;
spg_t pgid;
eversion_t trim_to;
epoch_t get_epoch() const { return epoch; }
spg_t get_spg() const {
return pgid;
}
epoch_t get_map_epoch() const {
return epoch;
}
epoch_t get_min_epoch() const {
return epoch;
}
PGPeeringEvent *get_event() override {
return new PGPeeringEvent(
epoch,
epoch,
MTrim(epoch, get_source().num(), pgid.shard, trim_to));
}
MOSDPGTrim() : MOSDPeeringOp{MSG_OSD_PG_TRIM, HEAD_VERSION, COMPAT_VERSION} {}
MOSDPGTrim(version_t mv, spg_t p, eversion_t tt) :
MOSDPeeringOp{MSG_OSD_PG_TRIM, HEAD_VERSION, COMPAT_VERSION},
epoch(mv), pgid(p), trim_to(tt) { }
private:
~MOSDPGTrim() final {}
public:
std::string_view get_type_name() const override { return "pg_trim"; }
void inner_print(std::ostream& out) const override {
out << trim_to;
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(epoch, payload);
encode(pgid.pgid, payload);
encode(trim_to, payload);
encode(pgid.shard, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(epoch, p);
decode(pgid.pgid, p);
decode(trim_to, p);
decode(pgid.shard, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,112 | 24.457831 | 80 | h |
null | ceph-main/src/messages/MOSDPGUpdateLogMissing.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_MOSDPGUPDATELOGMISSING_H
#define CEPH_MOSDPGUPDATELOGMISSING_H
#include "MOSDFastDispatchOp.h"
class MOSDPGUpdateLogMissing final : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 1;
public:
epoch_t map_epoch = 0, min_epoch = 0;
spg_t pgid;
shard_id_t from;
ceph_tid_t rep_tid = 0;
mempool::osd_pglog::list<pg_log_entry_t> entries;
// piggybacked osd/pg state
eversion_t pg_trim_to; // primary->replica: trim to here
eversion_t pg_roll_forward_to; // primary->replica: trim rollback info to here
epoch_t get_epoch() const { return map_epoch; }
spg_t get_pgid() const { return pgid; }
epoch_t get_query_epoch() const { return map_epoch; }
ceph_tid_t get_tid() const { return rep_tid; }
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDPGUpdateLogMissing()
: MOSDFastDispatchOp{MSG_OSD_PG_UPDATE_LOG_MISSING, HEAD_VERSION,
COMPAT_VERSION} {}
MOSDPGUpdateLogMissing(
const mempool::osd_pglog::list<pg_log_entry_t> &entries,
spg_t pgid,
shard_id_t from,
epoch_t epoch,
epoch_t min_epoch,
ceph_tid_t rep_tid,
eversion_t pg_trim_to,
eversion_t pg_roll_forward_to)
: MOSDFastDispatchOp{MSG_OSD_PG_UPDATE_LOG_MISSING, HEAD_VERSION,
COMPAT_VERSION},
map_epoch(epoch),
min_epoch(min_epoch),
pgid(pgid),
from(from),
rep_tid(rep_tid),
entries(entries),
pg_trim_to(pg_trim_to),
pg_roll_forward_to(pg_roll_forward_to)
{}
private:
~MOSDPGUpdateLogMissing() final {}
public:
std::string_view get_type_name() const override { return "PGUpdateLogMissing"; }
void print(std::ostream& out) const override {
out << "pg_update_log_missing(" << pgid << " epoch " << map_epoch
<< "/" << min_epoch
<< " rep_tid " << rep_tid
<< " entries " << entries
<< " trim_to " << pg_trim_to
<< " roll_forward_to " << pg_roll_forward_to
<< ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(map_epoch, payload);
encode(pgid, payload);
encode(from, payload);
encode(rep_tid, payload);
encode(entries, payload);
encode(min_epoch, payload);
encode(pg_trim_to, payload);
encode(pg_roll_forward_to, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(map_epoch, p);
decode(pgid, p);
decode(from, p);
decode(rep_tid, p);
decode(entries, p);
if (header.version >= 2) {
decode(min_epoch, p);
} else {
min_epoch = map_epoch;
}
if (header.version >= 3) {
decode(pg_trim_to, p);
decode(pg_roll_forward_to, p);
}
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 3,400 | 26.208 | 82 | h |
null | ceph-main/src/messages/MOSDPGUpdateLogMissingReply.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_MOSDPGUPDATELOGMISSINGREPLY_H
#define CEPH_MOSDPGUPDATELOGMISSINGREPLY_H
#include "MOSDFastDispatchOp.h"
class MOSDPGUpdateLogMissingReply final : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 1;
public:
epoch_t map_epoch = 0, min_epoch = 0;
spg_t pgid;
shard_id_t from;
ceph_tid_t rep_tid = 0;
// piggybacked osd state
eversion_t last_complete_ondisk;
epoch_t get_epoch() const { return map_epoch; }
spg_t get_pgid() const { return pgid; }
epoch_t get_query_epoch() const { return map_epoch; }
ceph_tid_t get_tid() const { return rep_tid; }
pg_shard_t get_from() const {
return pg_shard_t(get_source().num(), from);
}
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDPGUpdateLogMissingReply()
: MOSDFastDispatchOp{MSG_OSD_PG_UPDATE_LOG_MISSING_REPLY, HEAD_VERSION,
COMPAT_VERSION}
{}
MOSDPGUpdateLogMissingReply(
spg_t pgid,
shard_id_t from,
epoch_t epoch,
epoch_t min_epoch,
ceph_tid_t rep_tid,
eversion_t last_complete_ondisk)
: MOSDFastDispatchOp{MSG_OSD_PG_UPDATE_LOG_MISSING_REPLY, HEAD_VERSION,
COMPAT_VERSION},
map_epoch(epoch),
min_epoch(min_epoch),
pgid(pgid),
from(from),
rep_tid(rep_tid),
last_complete_ondisk(last_complete_ondisk)
{}
private:
~MOSDPGUpdateLogMissingReply() final {}
public:
std::string_view get_type_name() const override { return "PGUpdateLogMissingReply"; }
void print(std::ostream& out) const override {
out << "pg_update_log_missing_reply(" << pgid << " epoch " << map_epoch
<< "/" << min_epoch
<< " rep_tid " << rep_tid
<< " lcod " << last_complete_ondisk << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(map_epoch, payload);
encode(pgid, payload);
encode(from, payload);
encode(rep_tid, payload);
encode(min_epoch, payload);
encode(last_complete_ondisk, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(map_epoch, p);
decode(pgid, p);
decode(from, p);
decode(rep_tid, p);
if (header.version >= 2) {
decode(min_epoch, p);
} else {
min_epoch = map_epoch;
}
if (header.version >= 3) {
decode(last_complete_ondisk, p);
}
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 3,067 | 25.448276 | 87 | h |
null | ceph-main/src/messages/MOSDPeeringOp.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "msg/Message.h"
#include "osd/osd_types.h"
class PGPeeringEvent;
class MOSDPeeringOp : public Message {
public:
MOSDPeeringOp(int t, int version, int compat_version)
: Message{t, version, compat_version} {}
void print(std::ostream& out) const override final {
out << get_type_name() << "("
<< get_spg() << " ";
inner_print(out);
out << " e" << get_map_epoch() << "/" << get_min_epoch() << ")";
}
virtual spg_t get_spg() const = 0;
virtual epoch_t get_map_epoch() const = 0;
virtual epoch_t get_min_epoch() const = 0;
virtual PGPeeringEvent *get_event() = 0;
virtual void inner_print(std::ostream& out) const = 0;
#ifdef WITH_SEASTAR
// In crimson, conn is independently maintained outside Message.
// Instead of get features from the connection later, set features at
// the start of the operation.
void set_features(uint64_t _features) {
features = _features;
}
protected:
uint64_t features;
#endif
};
| 1,080 | 25.365854 | 71 | h |
null | ceph-main/src/messages/MOSDPing.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.
*
*/
/**
* This is used to send pings between daemons (so far, the OSDs) for
* heartbeat purposes. We include a timestamp and distinguish between
* outgoing pings and responses to those. If you set the
* min_message in the constructor, the message will inflate itself
* to the specified size -- this is good for dealing with network
* issues with jumbo frames. See http://tracker.ceph.com/issues/20087
*
*/
#ifndef CEPH_MOSDPING_H
#define CEPH_MOSDPING_H
#include "common/Clock.h"
#include "msg/Message.h"
#include "osd/osd_types.h"
class MOSDPing final : public Message {
private:
static constexpr int HEAD_VERSION = 5;
static constexpr int COMPAT_VERSION = 4;
public:
enum {
HEARTBEAT = 0,
START_HEARTBEAT = 1,
YOU_DIED = 2,
STOP_HEARTBEAT = 3,
PING = 4,
PING_REPLY = 5,
};
const char *get_op_name(int op) const {
switch (op) {
case HEARTBEAT: return "heartbeat";
case START_HEARTBEAT: return "start_heartbeat";
case STOP_HEARTBEAT: return "stop_heartbeat";
case YOU_DIED: return "you_died";
case PING: return "ping";
case PING_REPLY: return "ping_reply";
default: return "???";
}
}
uuid_d fsid;
epoch_t map_epoch = 0;
__u8 op = 0;
utime_t ping_stamp; ///< when the PING was sent
ceph::signedspan mono_ping_stamp; ///< relative to sender's clock
ceph::signedspan mono_send_stamp; ///< replier's send stamp
std::optional<ceph::signedspan> delta_ub; ///< ping sender
epoch_t up_from = 0;
uint32_t min_message_size = 0;
MOSDPing(const uuid_d& f, epoch_t e, __u8 o,
utime_t s,
ceph::signedspan ms,
ceph::signedspan mss,
epoch_t upf,
uint32_t min_message,
std::optional<ceph::signedspan> delta_ub = {})
: Message{MSG_OSD_PING, HEAD_VERSION, COMPAT_VERSION},
fsid(f), map_epoch(e), op(o),
ping_stamp(s),
mono_ping_stamp(ms),
mono_send_stamp(mss),
delta_ub(delta_ub),
up_from(upf),
min_message_size(min_message)
{ }
MOSDPing()
: Message{MSG_OSD_PING, HEAD_VERSION, COMPAT_VERSION}
{}
private:
~MOSDPing() final {}
public:
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(fsid, p);
decode(map_epoch, p);
decode(op, p);
decode(ping_stamp, p);
int payload_mid_length = p.get_off();
uint32_t size;
decode(size, p);
if (header.version >= 5) {
decode(up_from, p);
decode(mono_ping_stamp, p);
decode(mono_send_stamp, p);
decode(delta_ub, p);
}
p += size;
min_message_size = size + payload_mid_length;
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(fsid, payload);
encode(map_epoch, payload);
encode(op, payload);
encode(ping_stamp, payload);
size_t s = 0;
if (min_message_size > payload.length()) {
s = min_message_size - payload.length();
}
encode((uint32_t)s, payload);
encode(up_from, payload);
encode(mono_ping_stamp, payload);
encode(mono_send_stamp, payload);
encode(delta_ub, payload);
if (s) {
// this should be big enough for normal min_message padding sizes. since
// we are targeting jumbo ethernet frames around 9000 bytes, 16k should
// be more than sufficient! the compiler will statically zero this so
// that at runtime we are only adding a bufferptr reference to it.
static char zeros[16384] = {};
while (s > sizeof(zeros)) {
payload.append(ceph::buffer::create_static(sizeof(zeros), zeros));
s -= sizeof(zeros);
}
if (s) {
payload.append(ceph::buffer::create_static(s, zeros));
}
}
}
std::string_view get_type_name() const override { return "osd_ping"; }
void print(std::ostream& out) const override {
out << "osd_ping(" << get_op_name(op)
<< " e" << map_epoch
<< " up_from " << up_from
<< " ping_stamp " << ping_stamp << "/" << mono_ping_stamp
<< " send_stamp " << mono_send_stamp;
if (delta_ub) {
out << " delta_ub " << *delta_ub;
}
out << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 4,653 | 26.538462 | 78 | h |
null | ceph-main/src/messages/MOSDRepOp.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_MOSDREPOP_H
#define CEPH_MOSDREPOP_H
#include "MOSDFastDispatchOp.h"
/*
* OSD sub op - for internal ops on pobjects between primary and replicas(/stripes/whatever)
*/
class MOSDRepOp final : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 1;
public:
epoch_t map_epoch, min_epoch;
// metadata from original request
osd_reqid_t reqid;
spg_t pgid;
ceph::buffer::list::const_iterator p;
// Decoding flags. Decoding is only needed for messages caught by pipe reader.
bool final_decode_needed;
// subop
pg_shard_t from;
hobject_t poid;
__u8 acks_wanted;
// transaction to exec
ceph::buffer::list logbl;
pg_stat_t pg_stats;
// subop metadata
eversion_t version;
// piggybacked osd/og state
eversion_t pg_trim_to; // primary->replica: trim to here
eversion_t min_last_complete_ondisk; // lower bound on committed version
hobject_t new_temp_oid; ///< new temp object that we must now start tracking
hobject_t discard_temp_oid; ///< previously used temp object that we can now stop tracking
/// non-empty if this transaction involves a hit_set history update
std::optional<pg_hit_set_history_t> updated_hit_set_history;
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
int get_cost() const override {
return data.length();
}
void decode_payload() override {
using ceph::decode;
p = payload.cbegin();
// split to partial and final
decode(map_epoch, p);
if (header.version >= 2) {
decode(min_epoch, p);
decode_trace(p);
} else {
min_epoch = map_epoch;
}
decode(reqid, p);
decode(pgid, p);
}
void finish_decode() {
using ceph::decode;
if (!final_decode_needed)
return; // Message is already final decoded
decode(poid, p);
decode(acks_wanted, p);
decode(version, p);
decode(logbl, p);
decode(pg_stats, p);
decode(pg_trim_to, p);
decode(new_temp_oid, p);
decode(discard_temp_oid, p);
decode(from, p);
decode(updated_hit_set_history, p);
if (header.version >= 3) {
decode(min_last_complete_ondisk, p);
} else {
/* This field used to mean pg_roll_foward_to, but ReplicatedBackend
* simply assumes that we're rolling foward to version. */
eversion_t pg_roll_forward_to;
decode(pg_roll_forward_to, p);
}
final_decode_needed = false;
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(map_epoch, payload);
assert(HAVE_FEATURE(features, SERVER_OCTOPUS));
header.version = HEAD_VERSION;
encode(min_epoch, payload);
encode_trace(payload, features);
encode(reqid, payload);
encode(pgid, payload);
encode(poid, payload);
encode(acks_wanted, payload);
encode(version, payload);
encode(logbl, payload);
encode(pg_stats, payload);
encode(pg_trim_to, payload);
encode(new_temp_oid, payload);
encode(discard_temp_oid, payload);
encode(from, payload);
encode(updated_hit_set_history, payload);
encode(min_last_complete_ondisk, payload);
}
MOSDRepOp()
: MOSDFastDispatchOp{MSG_OSD_REPOP, HEAD_VERSION, COMPAT_VERSION},
map_epoch(0),
final_decode_needed(true), acks_wanted (0) {}
MOSDRepOp(osd_reqid_t r, pg_shard_t from,
spg_t p, const hobject_t& po, int aw,
epoch_t mape, epoch_t min_epoch, ceph_tid_t rtid, eversion_t v)
: MOSDFastDispatchOp{MSG_OSD_REPOP, HEAD_VERSION, COMPAT_VERSION},
map_epoch(mape),
min_epoch(min_epoch),
reqid(r),
pgid(p),
final_decode_needed(false),
from(from),
poid(po),
acks_wanted(aw),
version(v) {
set_tid(rtid);
}
void set_rollback_to(const eversion_t &rollback_to) {
header.version = 2;
min_last_complete_ondisk = rollback_to;
}
private:
~MOSDRepOp() final {}
public:
std::string_view get_type_name() const override { return "osd_repop"; }
void print(std::ostream& out) const override {
out << "osd_repop(" << reqid
<< " " << pgid << " e" << map_epoch << "/" << min_epoch;
if (!final_decode_needed) {
out << " " << poid << " v " << version;
if (updated_hit_set_history)
out << ", has_updated_hit_set_history";
if (header.version < 3) {
out << ", rollback_to(legacy)=" << min_last_complete_ondisk;
} else {
out << ", mlcod=" << min_last_complete_ondisk;
}
}
out << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 5,187 | 25.335025 | 93 | h |
null | ceph-main/src/messages/MOSDRepOpReply.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_MOSDREPOPREPLY_H
#define CEPH_MOSDREPOPREPLY_H
#include "MOSDFastDispatchOp.h"
#include "MOSDRepOp.h"
/*
* OSD Client Subop reply
*
* oid - object id
* op - OSD_OP_DELETE, etc.
*
*/
class MOSDRepOpReply final : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 1;
public:
epoch_t map_epoch, min_epoch;
// subop metadata
osd_reqid_t reqid;
pg_shard_t from;
spg_t pgid;
// result
__u8 ack_type;
int32_t result;
// piggybacked osd state
eversion_t last_complete_ondisk;
ceph::buffer::list::const_iterator p;
// Decoding flags. Decoding is only needed for messages caught by pipe reader.
bool final_decode_needed;
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
void decode_payload() override {
using ceph::decode;
p = payload.cbegin();
decode(map_epoch, p);
if (header.version >= 2) {
decode(min_epoch, p);
decode_trace(p);
} else {
min_epoch = map_epoch;
}
decode(reqid, p);
decode(pgid, p);
}
void finish_decode() {
using ceph::decode;
if (!final_decode_needed)
return; // Message is already final decoded
decode(ack_type, p);
decode(result, p);
decode(last_complete_ondisk, p);
decode(from, p);
final_decode_needed = false;
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(map_epoch, payload);
header.version = HEAD_VERSION;
encode(min_epoch, payload);
encode_trace(payload, features);
encode(reqid, payload);
encode(pgid, payload);
encode(ack_type, payload);
encode(result, payload);
encode(last_complete_ondisk, payload);
encode(from, payload);
}
spg_t get_pg() { return pgid; }
int get_ack_type() { return ack_type; }
bool is_ondisk() { return ack_type & CEPH_OSD_FLAG_ONDISK; }
bool is_onnvram() { return ack_type & CEPH_OSD_FLAG_ONNVRAM; }
int get_result() { return result; }
void set_last_complete_ondisk(eversion_t v) { last_complete_ondisk = v; }
eversion_t get_last_complete_ondisk() const { return last_complete_ondisk; }
public:
MOSDRepOpReply(
const MOSDRepOp *req, pg_shard_t from, int result_, epoch_t e, epoch_t mine,
int at) :
MOSDFastDispatchOp{MSG_OSD_REPOPREPLY, HEAD_VERSION, COMPAT_VERSION},
map_epoch(e),
min_epoch(mine),
reqid(req->reqid),
from(from),
pgid(req->pgid.pgid, req->from.shard),
ack_type(at),
result(result_),
final_decode_needed(false) {
set_tid(req->get_tid());
}
MOSDRepOpReply()
: MOSDFastDispatchOp{MSG_OSD_REPOPREPLY, HEAD_VERSION, COMPAT_VERSION},
map_epoch(0),
min_epoch(0),
ack_type(0), result(0),
final_decode_needed(true) {}
private:
~MOSDRepOpReply() final {}
public:
std::string_view get_type_name() const override { return "osd_repop_reply"; }
void print(std::ostream& out) const override {
out << "osd_repop_reply(" << reqid
<< " " << pgid << " e" << map_epoch << "/" << min_epoch;
if (!final_decode_needed) {
if (ack_type & CEPH_OSD_FLAG_ONDISK)
out << " ondisk";
if (ack_type & CEPH_OSD_FLAG_ONNVRAM)
out << " onnvram";
if (ack_type & CEPH_OSD_FLAG_ACK)
out << " ack";
out << ", result = " << result;
}
out << ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 4,049 | 24.15528 | 80 | h |
null | ceph-main/src/messages/MOSDRepScrub.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_MOSDREPSCRUB_H
#define CEPH_MOSDREPSCRUB_H
#include "MOSDFastDispatchOp.h"
/*
* instruct an OSD initiate a replica scrub on a specific PG
*/
class MOSDRepScrub final : public MOSDFastDispatchOp {
public:
static constexpr int HEAD_VERSION = 9;
static constexpr int COMPAT_VERSION = 6;
spg_t pgid; // PG to scrub
eversion_t scrub_from; // only scrub log entries after scrub_from
eversion_t scrub_to; // last_update_applied when message sent (not used)
epoch_t map_epoch = 0, min_epoch = 0;
bool chunky; // true for chunky scrubs
hobject_t start; // lower bound of scrub, inclusive
hobject_t end; // upper bound of scrub, exclusive
bool deep; // true if scrub should be deep
bool allow_preemption = false;
int32_t priority = 0;
bool high_priority = false;
epoch_t get_map_epoch() const override {
return map_epoch;
}
epoch_t get_min_epoch() const override {
return min_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDRepScrub()
: MOSDFastDispatchOp{MSG_OSD_REP_SCRUB, HEAD_VERSION, COMPAT_VERSION},
chunky(false),
deep(false) { }
MOSDRepScrub(spg_t pgid, eversion_t scrub_to, epoch_t map_epoch, epoch_t min_epoch,
hobject_t start, hobject_t end, bool deep,
bool preemption, int prio, bool highprio)
: MOSDFastDispatchOp{MSG_OSD_REP_SCRUB, HEAD_VERSION, COMPAT_VERSION},
pgid(pgid),
scrub_to(scrub_to),
map_epoch(map_epoch),
min_epoch(min_epoch),
chunky(true),
start(start),
end(end),
deep(deep),
allow_preemption(preemption),
priority(prio),
high_priority(highprio) { }
private:
~MOSDRepScrub() final {}
public:
std::string_view get_type_name() const override { return "replica scrub"; }
void print(std::ostream& out) const override {
out << "replica_scrub(pg: " << pgid
<< ",from:" << scrub_from
<< ",to:" << scrub_to
<< ",epoch:" << map_epoch << "/" << min_epoch
<< ",start:" << start << ",end:" << end
<< ",chunky:" << chunky
<< ",deep:" << deep
<< ",version:" << header.version
<< ",allow_preemption:" << (int)allow_preemption
<< ",priority=" << priority
<< (high_priority ? " (high)":"")
<< ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid.pgid, payload);
encode(scrub_from, payload);
encode(scrub_to, payload);
encode(map_epoch, payload);
encode(chunky, payload);
encode(start, payload);
encode(end, payload);
encode(deep, payload);
encode(pgid.shard, payload);
encode((uint32_t)-1, payload); // seed
encode(min_epoch, payload);
encode(allow_preemption, payload);
encode(priority, payload);
encode(high_priority, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid.pgid, p);
decode(scrub_from, p);
decode(scrub_to, p);
decode(map_epoch, p);
decode(chunky, p);
decode(start, p);
decode(end, p);
decode(deep, p);
decode(pgid.shard, p);
{
uint32_t seed;
decode(seed, p);
}
if (header.version >= 7) {
decode(min_epoch, p);
} else {
min_epoch = map_epoch;
}
if (header.version >= 8) {
decode(allow_preemption, p);
}
if (header.version >= 9) {
decode(priority, p);
decode(high_priority, p);
}
}
};
#endif
| 3,918 | 26.405594 | 85 | h |
null | ceph-main/src/messages/MOSDRepScrubMap.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 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_MOSDREPSCRUBMAP_H
#define CEPH_MOSDREPSCRUBMAP_H
#include "MOSDFastDispatchOp.h"
/*
* pass a ScrubMap from a shard back to the primary
*/
class MOSDRepScrubMap final : public MOSDFastDispatchOp {
public:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 1;
spg_t pgid; // primary spg_t
epoch_t map_epoch = 0;
pg_shard_t from; // whose scrubmap this is
ceph::buffer::list scrub_map_bl;
bool preempted = false;
epoch_t get_map_epoch() const override {
return map_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDRepScrubMap()
: MOSDFastDispatchOp{MSG_OSD_REP_SCRUBMAP, HEAD_VERSION, COMPAT_VERSION} {}
MOSDRepScrubMap(spg_t pgid, epoch_t map_epoch, pg_shard_t from)
: MOSDFastDispatchOp{MSG_OSD_REP_SCRUBMAP, HEAD_VERSION, COMPAT_VERSION},
pgid(pgid),
map_epoch(map_epoch),
from(from) {}
private:
~MOSDRepScrubMap() final {}
public:
std::string_view get_type_name() const override { return "rep_scrubmap"; }
void print(std::ostream& out) const override {
out << "rep_scrubmap(" << pgid << " e" << map_epoch
<< " from shard " << from
<< (preempted ? " PREEMPTED":"") << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid, payload);
encode(map_epoch, payload);
encode(from, payload);
encode(preempted, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid, p);
decode(map_epoch, p);
decode(from, p);
if (header.version >= 2) {
decode(preempted, p);
}
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,196 | 24.847059 | 79 | h |
null | ceph-main/src/messages/MOSDScrub2.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "msg/Message.h"
/*
* instruct an OSD to scrub some or all pg(s)
*/
class MOSDScrub2 final : public Message {
public:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
uuid_d fsid;
epoch_t epoch;
std::vector<spg_t> scrub_pgs;
bool repair = false;
bool deep = false;
MOSDScrub2() : Message{MSG_OSD_SCRUB2, HEAD_VERSION, COMPAT_VERSION} {}
MOSDScrub2(const uuid_d& f, epoch_t e, std::vector<spg_t>& pgs, bool r, bool d) :
Message{MSG_OSD_SCRUB2, HEAD_VERSION, COMPAT_VERSION},
fsid(f), epoch(e), scrub_pgs(pgs), repair(r), deep(d) {}
private:
~MOSDScrub2() final {}
public:
std::string_view get_type_name() const override { return "scrub2"; }
void print(std::ostream& out) const override {
out << "scrub2(" << scrub_pgs;
if (repair)
out << " repair";
if (deep)
out << " deep";
out << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(fsid, payload);
encode(epoch, payload);
encode(scrub_pgs, payload);
encode(repair, payload);
encode(deep, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(fsid, p);
decode(epoch, p);
decode(scrub_pgs, p);
decode(repair, p);
decode(deep, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 1,559 | 24.16129 | 83 | h |
null | ceph-main/src/messages/MOSDScrubReserve.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_MOSDSCRUBRESERVE_H
#define CEPH_MOSDSCRUBRESERVE_H
#include "MOSDFastDispatchOp.h"
class MOSDScrubReserve : public MOSDFastDispatchOp {
private:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
public:
spg_t pgid;
epoch_t map_epoch;
enum {
REQUEST = 0,
GRANT = 1,
RELEASE = 2,
REJECT = 3,
};
int32_t type;
pg_shard_t from;
epoch_t get_map_epoch() const override {
return map_epoch;
}
spg_t get_spg() const override {
return pgid;
}
MOSDScrubReserve()
: MOSDFastDispatchOp{MSG_OSD_SCRUB_RESERVE, HEAD_VERSION, COMPAT_VERSION},
map_epoch(0), type(-1) {}
MOSDScrubReserve(spg_t pgid,
epoch_t map_epoch,
int type,
pg_shard_t from)
: MOSDFastDispatchOp{MSG_OSD_SCRUB_RESERVE, HEAD_VERSION, COMPAT_VERSION},
pgid(pgid), map_epoch(map_epoch),
type(type), from(from) {}
std::string_view get_type_name() const {
return "MOSDScrubReserve";
}
void print(std::ostream& out) const {
out << "MOSDScrubReserve(" << pgid << " ";
switch (type) {
case REQUEST:
out << "REQUEST ";
break;
case GRANT:
out << "GRANT ";
break;
case REJECT:
out << "REJECT ";
break;
case RELEASE:
out << "RELEASE ";
break;
}
out << "e" << map_epoch << ")";
return;
}
void decode_payload() {
using ceph::decode;
auto p = payload.cbegin();
decode(pgid, p);
decode(map_epoch, p);
decode(type, p);
decode(from, p);
}
void encode_payload(uint64_t features) {
using ceph::encode;
encode(pgid, payload);
encode(map_epoch, payload);
encode(type, payload);
encode(from, payload);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,279 | 21.8 | 78 | h |
null | ceph-main/src/messages/MPGStats.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_MPGSTATS_H
#define CEPH_MPGSTATS_H
#include "osd/osd_types.h"
#include "messages/PaxosServiceMessage.h"
class MPGStats final : public PaxosServiceMessage {
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 1;
public:
uuid_d fsid;
std::map<pg_t, pg_stat_t> pg_stat;
osd_stat_t osd_stat;
std::map<int64_t, store_statfs_t> pool_stat;
epoch_t epoch = 0;
MPGStats() : PaxosServiceMessage{MSG_PGSTATS, 0, HEAD_VERSION, COMPAT_VERSION} {}
MPGStats(const uuid_d& f, epoch_t e)
: PaxosServiceMessage{MSG_PGSTATS, 0, HEAD_VERSION, COMPAT_VERSION},
fsid(f),
epoch(e)
{}
private:
~MPGStats() final {}
public:
std::string_view get_type_name() const override { return "pg_stats"; }
void print(std::ostream& out) const override {
out << "pg_stats(" << pg_stat.size() << " pgs seq " << osd_stat.seq << " v " << version << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
encode(fsid, payload);
encode(osd_stat, payload, features);
encode(pg_stat, payload);
encode(epoch, payload);
encode(utime_t{}, payload);
encode(pool_stat, payload, features);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(fsid, p);
decode(osd_stat, p);
if (osd_stat.num_osds == 0) {
// for the benefit of legacy OSDs who don't set this field
osd_stat.num_osds = 1;
}
decode(pg_stat, p);
decode(epoch, p);
utime_t dummy;
decode(dummy, p);
if (header.version >= 2)
decode(pool_stat, p);
}
};
#endif
| 2,087 | 25.769231 | 99 | h |
null | ceph-main/src/messages/MPGStatsAck.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_MPGSTATSACK_H
#define CEPH_MPGSTATSACK_H
#include "osd/osd_types.h"
class MPGStatsAck final : public Message {
public:
std::map<pg_t,std::pair<version_t,epoch_t> > pg_stat;
MPGStatsAck() : Message{MSG_PGSTATSACK} {}
private:
~MPGStatsAck() final {}
public:
std::string_view get_type_name() const override { return "pg_stats_ack"; }
void print(std::ostream& out) const override {
out << "pg_stats_ack(" << pg_stat.size() << " pgs tid " << get_tid() << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pg_stat, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(pg_stat, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 1,277 | 24.56 | 80 | h |
null | ceph-main/src/messages/MPing.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_MPING_H
#define CEPH_MPING_H
#include "msg/Message.h"
class MPing final : public Message {
public:
MPing() : Message{CEPH_MSG_PING} {}
private:
~MPing() final {}
public:
void decode_payload() override { }
void encode_payload(uint64_t features) override { }
std::string_view get_type_name() const override { return "ping"; }
};
#endif
| 791 | 22.294118 | 71 | h |
null | ceph-main/src/messages/MPoolOp.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_MPOOLOP_H
#define CEPH_MPOOLOP_H
#include "messages/PaxosServiceMessage.h"
class MPoolOp final : public PaxosServiceMessage {
private:
static constexpr int HEAD_VERSION = 4;
static constexpr int COMPAT_VERSION = 2;
public:
uuid_d fsid;
__u32 pool = 0;
std::string name;
__u32 op = 0;
snapid_t snapid;
__s16 crush_rule = 0;
MPoolOp()
: PaxosServiceMessage{CEPH_MSG_POOLOP, 0, HEAD_VERSION, COMPAT_VERSION} {}
MPoolOp(const uuid_d& f, ceph_tid_t t, int p, std::string& n, int o, version_t v)
: PaxosServiceMessage{CEPH_MSG_POOLOP, v, HEAD_VERSION, COMPAT_VERSION},
fsid(f), pool(p), name(n), op(o),
snapid(0), crush_rule(0) {
set_tid(t);
}
private:
~MPoolOp() final {}
public:
std::string_view get_type_name() const override { return "poolop"; }
void print(std::ostream& out) const override {
out << "pool_op(" << ceph_pool_op_name(op) << " pool " << pool
<< " tid " << get_tid()
<< " name " << name
<< " v" << version << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
encode(fsid, payload);
encode(pool, payload);
encode(op, payload);
encode((uint64_t)0, payload);
encode(snapid, payload);
encode(name, payload);
__u8 pad = 0;
encode(pad, payload); /* for v3->v4 encoding change */
encode(crush_rule, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(fsid, p);
decode(pool, p);
if (header.version < 2)
decode(name, p);
decode(op, p);
uint64_t old_auid;
decode(old_auid, p);
decode(snapid, p);
if (header.version >= 2)
decode(name, p);
if (header.version >= 3) {
__u8 pad;
decode(pad, p);
if (header.version >= 4)
decode(crush_rule, p);
else
crush_rule = pad;
} else
crush_rule = -1;
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,484 | 24.10101 | 83 | h |
null | ceph-main/src/messages/MPoolOpReply.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_MPOOLOPREPLY_H
#define CEPH_MPOOLOPREPLY_H
#include "common/errno.h"
class MPoolOpReply : public PaxosServiceMessage {
public:
uuid_d fsid;
__u32 replyCode = 0;
epoch_t epoch = 0;
ceph::buffer::list response_data;
MPoolOpReply() : PaxosServiceMessage{CEPH_MSG_POOLOP_REPLY, 0}
{}
MPoolOpReply( uuid_d& f, ceph_tid_t t, int rc, int e, version_t v) :
PaxosServiceMessage{CEPH_MSG_POOLOP_REPLY, v},
fsid(f),
replyCode(rc),
epoch(e) {
set_tid(t);
}
MPoolOpReply(uuid_d& f, ceph_tid_t t, int rc, int e, version_t v,
ceph::buffer::list *blp) :
PaxosServiceMessage{CEPH_MSG_POOLOP_REPLY, v},
fsid(f),
replyCode(rc),
epoch(e) {
set_tid(t);
if (blp)
response_data = std::move(*blp);
}
std::string_view get_type_name() const override { return "poolopreply"; }
void print(std::ostream& out) const override {
out << "pool_op_reply(tid " << get_tid()
<< " " << cpp_strerror(-replyCode)
<< " v" << version << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
encode(fsid, payload);
encode(replyCode, payload);
encode(epoch, payload);
if (response_data.length()) {
encode(true, payload);
encode(response_data, payload);
} else
encode(false, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(fsid, p);
decode(replyCode, p);
decode(epoch, p);
bool has_response_data;
decode(has_response_data, p);
if (has_response_data) {
decode(response_data, p);
}
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,209 | 24.697674 | 75 | h |
null | ceph-main/src/messages/MRecoveryReserve.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_MRECOVERY_H
#define CEPH_MRECOVERY_H
#include "msg/Message.h"
#include "messages/MOSDPeeringOp.h"
#include "osd/PGPeeringEvent.h"
class MRecoveryReserve : public MOSDPeeringOp {
private:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 2;
public:
spg_t pgid;
epoch_t query_epoch;
enum {
REQUEST = 0, // primary->replica: please reserve slot
GRANT = 1, // replica->primary: ok, i reserved it
RELEASE = 2, // primary->replica: release the slot i reserved before
REVOKE = 3, // replica->primary: i'm taking back the slot i gave you
};
uint32_t type;
uint32_t priority = 0;
spg_t get_spg() const {
return pgid;
}
epoch_t get_map_epoch() const {
return query_epoch;
}
epoch_t get_min_epoch() const {
return query_epoch;
}
PGPeeringEvent *get_event() override {
switch (type) {
case REQUEST:
return new PGPeeringEvent(
query_epoch,
query_epoch,
RequestRecoveryPrio(priority));
case GRANT:
return new PGPeeringEvent(
query_epoch,
query_epoch,
RemoteRecoveryReserved());
case RELEASE:
return new PGPeeringEvent(
query_epoch,
query_epoch,
RecoveryDone());
case REVOKE:
return new PGPeeringEvent(
query_epoch,
query_epoch,
DeferRecovery(0.0));
default:
ceph_abort();
}
}
MRecoveryReserve()
: MOSDPeeringOp{MSG_OSD_RECOVERY_RESERVE, HEAD_VERSION, COMPAT_VERSION},
query_epoch(0), type(-1) {}
MRecoveryReserve(int type,
spg_t pgid,
epoch_t query_epoch,
unsigned prio = 0)
: MOSDPeeringOp{MSG_OSD_RECOVERY_RESERVE, HEAD_VERSION, COMPAT_VERSION},
pgid(pgid), query_epoch(query_epoch),
type(type), priority(prio) {}
std::string_view get_type_name() const override {
return "MRecoveryReserve";
}
void inner_print(std::ostream& out) const override {
switch (type) {
case REQUEST:
out << "REQUEST";
break;
case GRANT:
out << "GRANT";
break;
case RELEASE:
out << "RELEASE";
break;
case REVOKE:
out << "REVOKE";
break;
}
if (type == REQUEST) out << " prio: " << priority;
}
void decode_payload() override {
auto p = payload.cbegin();
using ceph::decode;
decode(pgid.pgid, p);
decode(query_epoch, p);
decode(type, p);
decode(pgid.shard, p);
if (header.version >= 3) {
decode(priority, p);
}
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(pgid.pgid, payload);
encode(query_epoch, payload);
encode(type, payload);
encode(pgid.shard, payload);
encode(priority, payload);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 3,228 | 23.097015 | 76 | h |
null | ceph-main/src/messages/MRemoveSnaps.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_MREMOVESNAPS_H
#define CEPH_MREMOVESNAPS_H
#include "messages/PaxosServiceMessage.h"
class MRemoveSnaps final : public PaxosServiceMessage {
public:
std::map<int32_t, std::vector<snapid_t>> snaps;
protected:
MRemoveSnaps() :
PaxosServiceMessage{MSG_REMOVE_SNAPS, 0} { }
MRemoveSnaps(std::map<int, std::vector<snapid_t>>& s) :
PaxosServiceMessage{MSG_REMOVE_SNAPS, 0} {
snaps.swap(s);
}
~MRemoveSnaps() final {}
public:
std::string_view get_type_name() const override { return "remove_snaps"; }
void print(std::ostream& out) const override {
out << "remove_snaps(" << snaps << " v" << version << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
encode(snaps, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(snaps, p);
ceph_assert(p.end());
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
template<class T, typename... Args>
friend MURef<T> crimson::make_message(Args&&... args);
};
#endif
| 1,595 | 26.050847 | 76 | h |
null | ceph-main/src/messages/MRoute.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_MROUTE_H
#define CEPH_MROUTE_H
#include "msg/Message.h"
#include "include/encoding.h"
class MRoute final : public Message {
public:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 3;
uint64_t session_mon_tid;
Message *msg;
epoch_t send_osdmap_first;
MRoute() : Message{MSG_ROUTE, HEAD_VERSION, COMPAT_VERSION},
session_mon_tid(0),
msg(NULL),
send_osdmap_first(0) {}
MRoute(uint64_t t, Message *m)
: Message{MSG_ROUTE, HEAD_VERSION, COMPAT_VERSION},
session_mon_tid(t),
msg(m),
send_osdmap_first(0) {}
private:
~MRoute() final {
if (msg)
msg->put();
}
public:
void decode_payload() override {
auto p = payload.cbegin();
using ceph::decode;
decode(session_mon_tid, p);
entity_inst_t dest_unused;
decode(dest_unused, p);
bool m;
decode(m, p);
if (m)
msg = decode_message(NULL, 0, p);
decode(send_osdmap_first, p);
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(session_mon_tid, payload);
entity_inst_t dest_unused;
encode(dest_unused, payload, features);
bool m = msg ? true : false;
encode(m, payload);
if (msg)
encode_message(msg, features, payload);
encode(send_osdmap_first, payload);
}
std::string_view get_type_name() const override { return "route"; }
void print(std::ostream& o) const override {
if (msg)
o << "route(" << *msg;
else
o << "route(no-reply";
if (send_osdmap_first)
o << " send_osdmap_first " << send_osdmap_first;
if (session_mon_tid)
o << " tid " << session_mon_tid << ")";
else
o << " tid (none)";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,273 | 23.989011 | 71 | h |
null | ceph-main/src/messages/MServiceMap.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "msg/Message.h"
#include "mgr/ServiceMap.h"
class MServiceMap final : public Message {
public:
ServiceMap service_map;
MServiceMap() : Message{MSG_SERVICE_MAP} { }
explicit MServiceMap(const ServiceMap& sm)
: Message{MSG_SERVICE_MAP},
service_map(sm) {
}
private:
~MServiceMap() final {}
public:
std::string_view get_type_name() const override { return "service_map"; }
void print(std::ostream& out) const override {
out << "service_map(e" << service_map.epoch << " "
<< service_map.services.size() << " svc)";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(service_map, payload, features);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(service_map, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 1,034 | 24.875 | 75 | h |
null | ceph-main/src/messages/MStatfs.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_MSTATFS_H
#define CEPH_MSTATFS_H
#include <optional>
#include <sys/statvfs.h> /* or <sys/statfs.h> */
#include "messages/PaxosServiceMessage.h"
class MStatfs final : public PaxosServiceMessage {
private:
static constexpr int HEAD_VERSION = 2;
static constexpr int COMPAT_VERSION = 1;
public:
uuid_d fsid;
std::optional<int64_t> data_pool;
MStatfs() : PaxosServiceMessage{CEPH_MSG_STATFS, 0, HEAD_VERSION, COMPAT_VERSION} {}
MStatfs(const uuid_d& f, ceph_tid_t t, std::optional<int64_t> _data_pool,
version_t v)
: PaxosServiceMessage{CEPH_MSG_STATFS, v, HEAD_VERSION, COMPAT_VERSION},
fsid(f), data_pool(_data_pool) {
set_tid(t);
}
private:
~MStatfs() final {}
public:
std::string_view get_type_name() const override { return "statfs"; }
void print(std::ostream& out) const override {
out << "statfs(" << get_tid() << " pool "
<< (data_pool ? *data_pool : -1) << " v" << version << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
paxos_encode();
encode(fsid, payload);
encode(data_pool, payload);
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
paxos_decode(p);
decode(fsid, p);
if (header.version >= 2) {
decode(data_pool, p);
} else {
data_pool = std::optional<int64_t> ();
}
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 1,937 | 25.547945 | 86 | h |
null | ceph-main/src/messages/MStatfsReply.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_MSTATFSREPLY_H
#define CEPH_MSTATFSREPLY_H
class MStatfsReply : public Message {
public:
struct ceph_mon_statfs_reply h{};
MStatfsReply() : Message{CEPH_MSG_STATFS_REPLY} {}
MStatfsReply(uuid_d &f, ceph_tid_t t, epoch_t epoch)
: Message{CEPH_MSG_STATFS_REPLY} {
memcpy(&h.fsid, f.bytes(), sizeof(h.fsid));
header.tid = t;
h.version = epoch;
}
std::string_view get_type_name() const override { return "statfs_reply"; }
void print(std::ostream& out) const override {
out << "statfs_reply(" << header.tid << ")";
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(h, payload);
}
void decode_payload() override {
auto p = payload.cbegin();
decode(h, p);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 1,312 | 25.26 | 76 | h |
null | ceph-main/src/messages/MTimeCheck.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_MTIMECHECK_H
#define CEPH_MTIMECHECK_H
class MTimeCheck final : public Message {
public:
static constexpr int HEAD_VERSION = 1;
enum {
OP_PING = 1,
OP_PONG = 2,
OP_REPORT = 3,
};
int op = 0;
version_t epoch = 0;
version_t round = 0;
utime_t timestamp;
map<entity_inst_t, double> skews;
map<entity_inst_t, double> latencies;
MTimeCheck() : Message{MSG_TIMECHECK, HEAD_VERSION} {}
MTimeCheck(int op) :
Message{MSG_TIMECHECK, HEAD_VERSION},
op(op)
{}
private:
~MTimeCheck() final {}
public:
std::string_view get_type_name() const override { return "time_check"; }
const char *get_op_name() const {
switch (op) {
case OP_PING: return "ping";
case OP_PONG: return "pong";
case OP_REPORT: return "report";
}
return "???";
}
void print(std::ostream &o) const override {
o << "time_check( " << get_op_name()
<< " e " << epoch << " r " << round;
if (op == OP_PONG) {
o << " ts " << timestamp;
} else if (op == OP_REPORT) {
o << " #skews " << skews.size()
<< " #latencies " << latencies.size();
}
o << " )";
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(op, p);
decode(epoch, p);
decode(round, p);
decode(timestamp, p);
decode(skews, p);
decode(latencies, p);
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(op, payload);
encode(epoch, payload);
encode(round, payload);
encode(timestamp, payload);
encode(skews, payload, features);
encode(latencies, payload, features);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif /* CEPH_MTIMECHECK_H */
| 2,211 | 22.784946 | 74 | h |
null | ceph-main/src/messages/MTimeCheck2.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2012 Inktank, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
class MTimeCheck2 final : public Message {
public:
static constexpr int HEAD_VERSION = 1;
static constexpr int COMPAT_VERSION = 1;
enum {
OP_PING = 1,
OP_PONG = 2,
OP_REPORT = 3,
};
int op = 0;
version_t epoch = 0;
version_t round = 0;
utime_t timestamp;
std::map<int, double> skews;
std::map<int, double> latencies;
MTimeCheck2() : Message{MSG_TIMECHECK2, HEAD_VERSION, COMPAT_VERSION} { }
MTimeCheck2(int op) :
Message{MSG_TIMECHECK2, HEAD_VERSION, COMPAT_VERSION},
op(op)
{ }
private:
~MTimeCheck2() final { }
public:
std::string_view get_type_name() const override { return "time_check2"; }
const char *get_op_name() const {
switch (op) {
case OP_PING: return "ping";
case OP_PONG: return "pong";
case OP_REPORT: return "report";
}
return "???";
}
void print(std::ostream &o) const override {
o << "time_check( " << get_op_name()
<< " e " << epoch << " r " << round;
if (op == OP_PONG) {
o << " ts " << timestamp;
} else if (op == OP_REPORT) {
o << " #skews " << skews.size()
<< " #latencies " << latencies.size();
}
o << " )";
}
void decode_payload() override {
using ceph::decode;
auto p = payload.cbegin();
decode(op, p);
decode(epoch, p);
decode(round, p);
decode(timestamp, p);
decode(skews, p);
decode(latencies, p);
}
void encode_payload(uint64_t features) override {
using ceph::encode;
encode(op, payload);
encode(epoch, payload);
encode(round, payload);
encode(timestamp, payload);
encode(skews, payload, features);
encode(latencies, payload, features);
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
| 2,212 | 23.318681 | 75 | h |
null | ceph-main/src/messages/MWatchNotify.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_MWATCHNOTIFY_H
#define CEPH_MWATCHNOTIFY_H
#include "msg/Message.h"
class MWatchNotify final : public Message {
private:
static constexpr int HEAD_VERSION = 3;
static constexpr int COMPAT_VERSION = 1;
public:
uint64_t cookie; ///< client unique id for this watch or notify
uint64_t ver; ///< unused
uint64_t notify_id; ///< osd unique id for a notify notification
uint8_t opcode; ///< CEPH_WATCH_EVENT_*
ceph::buffer::list bl; ///< notify payload (osd->client)
errorcode32_t return_code; ///< notify result (osd->client)
uint64_t notifier_gid; ///< who sent the notify
MWatchNotify()
: Message{CEPH_MSG_WATCH_NOTIFY, HEAD_VERSION, COMPAT_VERSION} { }
MWatchNotify(uint64_t c, uint64_t v, uint64_t i, uint8_t o, ceph::buffer::list b, uint64_t n=0)
: Message{CEPH_MSG_WATCH_NOTIFY, HEAD_VERSION, COMPAT_VERSION},
cookie(c),
ver(v),
notify_id(i),
opcode(o),
bl(b),
return_code(0),
notifier_gid(n) { }
private:
~MWatchNotify() final {}
public:
void decode_payload() override {
using ceph::decode;
uint8_t msg_ver;
auto p = payload.cbegin();
decode(msg_ver, p);
decode(opcode, p);
decode(cookie, p);
decode(ver, p);
decode(notify_id, p);
if (msg_ver >= 1)
decode(bl, p);
if (header.version >= 2)
decode(return_code, p);
else
return_code = 0;
if (header.version >= 3)
decode(notifier_gid, p);
else
notifier_gid = 0;
}
void encode_payload(uint64_t features) override {
using ceph::encode;
uint8_t msg_ver = 1;
encode(msg_ver, payload);
encode(opcode, payload);
encode(cookie, payload);
encode(ver, payload);
encode(notify_id, payload);
encode(bl, payload);
encode(return_code, payload);
encode(notifier_gid, payload);
}
std::string_view get_type_name() const override { return "watch-notify"; }
void print(std::ostream& out) const override {
out << "watch-notify("
<< ceph_watch_event_name(opcode) << " (" << (int)opcode << ")"
<< " cookie " << cookie
<< " notify " << notify_id
<< " ret " << return_code
<< ")";
}
private:
template<class T, typename... Args>
friend boost::intrusive_ptr<T> ceph::make_message(Args&&... args);
};
#endif
| 2,728 | 26.565657 | 97 | h |
null | ceph-main/src/messages/PaxosServiceMessage.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
#ifndef CEPH_PAXOSSERVICEMESSAGE_H
#define CEPH_PAXOSSERVICEMESSAGE_H
#include "msg/Message.h"
#include "mon/Session.h"
class PaxosServiceMessage : public Message {
public:
version_t version;
__s16 deprecated_session_mon;
uint64_t deprecated_session_mon_tid;
// track which epoch the leader received a forwarded request in, so we can
// discard forwarded requests appropriately on election boundaries.
epoch_t rx_election_epoch;
PaxosServiceMessage()
: Message{MSG_PAXOS},
version(0), deprecated_session_mon(-1), deprecated_session_mon_tid(0),
rx_election_epoch(0) { }
PaxosServiceMessage(int type, version_t v, int enc_version=1, int compat_enc_version=0)
: Message{type, enc_version, compat_enc_version},
version(v), deprecated_session_mon(-1), deprecated_session_mon_tid(0),
rx_election_epoch(0) { }
protected:
~PaxosServiceMessage() override {}
public:
void paxos_encode() {
using ceph::encode;
encode(version, payload);
encode(deprecated_session_mon, payload);
encode(deprecated_session_mon_tid, payload);
}
void paxos_decode(ceph::buffer::list::const_iterator& p ) {
using ceph::decode;
decode(version, p);
decode(deprecated_session_mon, p);
decode(deprecated_session_mon_tid, p);
}
void encode_payload(uint64_t features) override {
ceph_abort();
paxos_encode();
}
void decode_payload() override {
ceph_abort();
auto p = payload.cbegin();
paxos_decode(p);
}
std::string_view get_type_name() const override { return "PaxosServiceMessage"; }
};
#endif
| 1,661 | 26.7 | 89 | h |
null | ceph-main/src/mgr/ActivePyModule.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2016 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#include "PyFormatter.h"
#include "common/debug.h"
#include "mon/MonCommand.h"
#include "ActivePyModule.h"
#include "MgrSession.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_mgr
#undef dout_prefix
#define dout_prefix *_dout << "mgr " << __func__ << " "
using std::string;
using namespace std::literals;
int ActivePyModule::load(ActivePyModules *py_modules)
{
ceph_assert(py_modules);
Gil gil(py_module->pMyThreadState, true);
// We tell the module how we name it, so that it can be consistent
// with us in logging etc.
auto pThisPtr = PyCapsule_New(this, nullptr, nullptr);
auto pPyModules = PyCapsule_New(py_modules, nullptr, nullptr);
auto pModuleName = PyUnicode_FromString(get_name().c_str());
auto pArgs = PyTuple_Pack(3, pModuleName, pPyModules, pThisPtr);
pClassInstance = PyObject_CallObject(py_module->pClass, pArgs);
Py_DECREF(pModuleName);
Py_DECREF(pArgs);
if (pClassInstance == nullptr) {
derr << "Failed to construct class in '" << get_name() << "'" << dendl;
derr << handle_pyerror(true, get_name(), "ActivePyModule::load") << dendl;
return -EINVAL;
} else {
dout(1) << "Constructed class from module: " << get_name() << dendl;
}
return 0;
}
void ActivePyModule::notify(const std::string ¬ify_type, const std::string ¬ify_id)
{
if (is_dead()) {
dout(5) << "cancelling notify " << notify_type << " " << notify_id << dendl;
return;
}
ceph_assert(pClassInstance != nullptr);
Gil gil(py_module->pMyThreadState, true);
// Execute
auto pValue = PyObject_CallMethod(pClassInstance,
const_cast<char*>("notify"), const_cast<char*>("(ss)"),
notify_type.c_str(), notify_id.c_str());
if (pValue != NULL) {
Py_DECREF(pValue);
} else {
derr << get_name() << ".notify:" << dendl;
derr << handle_pyerror(true, get_name(), "ActivePyModule::notify") << dendl;
// FIXME: callers can't be expected to handle a python module
// that has spontaneously broken, but Mgr() should provide
// a hook to unload misbehaving modules when they have an
// error somewhere like this
}
}
void ActivePyModule::notify_clog(const LogEntry &log_entry)
{
if (is_dead()) {
dout(5) << "cancelling notify_clog" << dendl;
return;
}
ceph_assert(pClassInstance != nullptr);
Gil gil(py_module->pMyThreadState, true);
// Construct python-ized LogEntry
PyFormatter f;
log_entry.dump(&f);
auto py_log_entry = f.get();
// Execute
auto pValue = PyObject_CallMethod(pClassInstance,
const_cast<char*>("notify"), const_cast<char*>("(sN)"),
"clog", py_log_entry);
if (pValue != NULL) {
Py_DECREF(pValue);
} else {
derr << get_name() << ".notify_clog:" << dendl;
derr << handle_pyerror(true, get_name(), "ActivePyModule::notify_clog") << dendl;
// FIXME: callers can't be expected to handle a python module
// that has spontaneously broken, but Mgr() should provide
// a hook to unload misbehaving modules when they have an
// error somewhere like this
}
}
bool ActivePyModule::method_exists(const std::string &method) const
{
Gil gil(py_module->pMyThreadState, true);
auto boundMethod = PyObject_GetAttrString(pClassInstance, method.c_str());
if (boundMethod == nullptr) {
return false;
} else {
Py_DECREF(boundMethod);
return true;
}
}
PyObject *ActivePyModule::dispatch_remote(
const std::string &method,
PyObject *args,
PyObject *kwargs,
std::string *err)
{
ceph_assert(err != nullptr);
// Rather than serializing arguments, pass the CPython objects.
// Works because we happen to know that the subinterpreter
// implementation shares a GIL, allocator, deallocator and GC state, so
// it's okay to pass the objects between subinterpreters.
// But in future this might involve serialization to support a CSP-aware
// future Python interpreter a la PEP554
Gil gil(py_module->pMyThreadState, true);
// Fire the receiving method
auto boundMethod = PyObject_GetAttrString(pClassInstance, method.c_str());
// Caller should have done method_exists check first!
ceph_assert(boundMethod != nullptr);
dout(20) << "Calling " << py_module->get_name()
<< "." << method << "..." << dendl;
auto remoteResult = PyObject_Call(boundMethod,
args, kwargs);
Py_DECREF(boundMethod);
if (remoteResult == nullptr) {
// Because the caller is in a different context, we can't let this
// exception bubble up, need to re-raise it from the caller's
// context later.
std::string caller = "ActivePyModule::dispatch_remote "s + method;
*err = handle_pyerror(true, get_name(), caller);
} else {
dout(20) << "Success calling '" << method << "'" << dendl;
}
return remoteResult;
}
void ActivePyModule::config_notify()
{
if (is_dead()) {
dout(5) << "cancelling config_notify" << dendl;
return;
}
Gil gil(py_module->pMyThreadState, true);
dout(20) << "Calling " << py_module->get_name() << "._config_notify..."
<< dendl;
auto remoteResult = PyObject_CallMethod(pClassInstance,
const_cast<char*>("_config_notify"),
(char*)NULL);
if (remoteResult != nullptr) {
Py_DECREF(remoteResult);
}
}
int ActivePyModule::handle_command(
const ModuleCommand& module_command,
const MgrSession& session,
const cmdmap_t &cmdmap,
const bufferlist &inbuf,
std::stringstream *ds,
std::stringstream *ss)
{
ceph_assert(ss != nullptr);
ceph_assert(ds != nullptr);
if (pClassInstance == nullptr) {
// Not the friendliest error string, but we could only
// hit this in quite niche cases, if at all.
*ss << "Module not instantiated";
return -EINVAL;
}
Gil gil(py_module->pMyThreadState, true);
PyFormatter f;
TOPNSPC::common::cmdmap_dump(cmdmap, &f);
PyObject *py_cmd = f.get();
string instr;
inbuf.begin().copy(inbuf.length(), instr);
ceph_assert(m_session == nullptr);
m_command_perms = module_command.perm;
m_session = &session;
auto pResult = PyObject_CallMethod(pClassInstance,
const_cast<char*>("_handle_command"), const_cast<char*>("s#O"),
instr.c_str(), instr.length(), py_cmd);
m_command_perms.clear();
m_session = nullptr;
Py_DECREF(py_cmd);
int r = 0;
if (pResult != NULL) {
if (PyTuple_Size(pResult) != 3) {
derr << "module '" << py_module->get_name() << "' command handler "
"returned wrong type!" << dendl;
r = -EINVAL;
} else {
r = PyLong_AsLong(PyTuple_GetItem(pResult, 0));
*ds << PyUnicode_AsUTF8(PyTuple_GetItem(pResult, 1));
*ss << PyUnicode_AsUTF8(PyTuple_GetItem(pResult, 2));
}
Py_DECREF(pResult);
} else {
derr << "module '" << py_module->get_name() << "' command handler "
"threw exception: " << peek_pyerror() << dendl;
*ds << "";
*ss << handle_pyerror();
r = -EINVAL;
}
return r;
}
void ActivePyModule::get_health_checks(health_check_map_t *checks)
{
if (is_dead()) {
dout(5) << "cancelling get_health_checks" << dendl;
return;
}
checks->merge(health_checks);
}
bool ActivePyModule::is_authorized(
const std::map<std::string, std::string>& arguments) const {
if (m_session == nullptr) {
return false;
}
// No need to pass command prefix here since that would have already been
// tested before command invokation. Instead, only test for service/module
// arguments as defined by the module itself.
MonCommand mon_command {"", "", "", m_command_perms};
return m_session->caps.is_capable(nullptr, m_session->entity_name, "py",
py_module->get_name(), "", arguments,
mon_command.requires_perm('r'),
mon_command.requires_perm('w'),
mon_command.requires_perm('x'),
m_session->get_peer_addr());
}
| 8,359 | 28.857143 | 89 | cc |
null | ceph-main/src/mgr/ActivePyModule.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2016 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#pragma once
// Python.h comes first because otherwise it clobbers ceph's assert
#include "Python.h"
#include "common/cmdparse.h"
#include "common/LogEntry.h"
#include "common/Thread.h"
#include "common/Finisher.h"
#include "mon/health_check.h"
#include "mgr/Gil.h"
#include "PyModuleRunner.h"
#include "PyModule.h"
#include <vector>
#include <string>
class ActivePyModule;
class ActivePyModules;
class MgrSession;
class ModuleCommand;
class ActivePyModule : public PyModuleRunner
{
private:
health_check_map_t health_checks;
// Optional, URI exposed by plugins that implement serve()
std::string uri;
std::string m_command_perms;
const MgrSession* m_session = nullptr;
std::string fin_thread_name;
public:
Finisher finisher; // per active module finisher to execute commands
public:
ActivePyModule(const PyModuleRef &py_module_,
LogChannelRef clog_)
: PyModuleRunner(py_module_, clog_),
fin_thread_name(std::string("m-fin-" + py_module->get_name()).substr(0,15)),
finisher(g_ceph_context, thread_name, fin_thread_name)
{
}
int load(ActivePyModules *py_modules);
void notify(const std::string ¬ify_type, const std::string ¬ify_id);
void notify_clog(const LogEntry &le);
bool method_exists(const std::string &method) const;
PyObject *dispatch_remote(
const std::string &method,
PyObject *args,
PyObject *kwargs,
std::string *err);
int handle_command(
const ModuleCommand& module_command,
const MgrSession& session,
const cmdmap_t &cmdmap,
const bufferlist &inbuf,
std::stringstream *ds,
std::stringstream *ss);
bool set_health_checks(health_check_map_t&& c) {
// when health checks change a report is immediately sent to the monitors.
// currently modules have static health check details, but this equality
// test could be made smarter if too much noise shows up in the future.
bool changed = health_checks != c;
health_checks = std::move(c);
return changed;
}
void get_health_checks(health_check_map_t *checks);
void config_notify();
void set_uri(const std::string &str)
{
uri = str;
}
std::string get_uri() const
{
return uri;
}
std::string get_fin_thread_name() const
{
return fin_thread_name;
}
bool is_authorized(const std::map<std::string, std::string>& arguments) const;
};
| 2,802 | 23.373913 | 82 | h |
null | ceph-main/src/mgr/ActivePyModules.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
// Include this first to get python headers earlier
#include "Gil.h"
#include "ActivePyModules.h"
#include <rocksdb/version.h>
#include "common/errno.h"
#include "include/stringify.h"
#include "mon/MonMap.h"
#include "osd/OSDMap.h"
#include "osd/osd_types.h"
#include "mgr/MgrContext.h"
#include "mgr/TTLCache.h"
#include "mgr/mgr_perf_counters.h"
#include "DaemonKey.h"
#include "DaemonServer.h"
#include "mgr/MgrContext.h"
#include "PyFormatter.h"
// For ::mgr_store_prefix
#include "PyModule.h"
#include "PyModuleRegistry.h"
#include "PyUtil.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_mgr
#undef dout_prefix
#define dout_prefix *_dout << "mgr " << __func__ << " "
using std::pair;
using std::string;
using namespace std::literals;
ActivePyModules::ActivePyModules(
PyModuleConfig &module_config_,
std::map<std::string, std::string> store_data,
bool mon_provides_kv_sub,
DaemonStateIndex &ds, ClusterState &cs,
MonClient &mc, LogChannelRef clog_,
LogChannelRef audit_clog_, Objecter &objecter_,
Client &client_, Finisher &f, DaemonServer &server,
PyModuleRegistry &pmr)
: module_config(module_config_), daemon_state(ds), cluster_state(cs),
monc(mc), clog(clog_), audit_clog(audit_clog_), objecter(objecter_),
client(client_), finisher(f),
cmd_finisher(g_ceph_context, "cmd_finisher", "cmdfin"),
server(server), py_module_registry(pmr)
{
store_cache = std::move(store_data);
// we can only trust our ConfigMap if the mon cluster has provided
// kv sub since our startup.
have_local_config_map = mon_provides_kv_sub;
_refresh_config_map();
cmd_finisher.start();
}
ActivePyModules::~ActivePyModules() = default;
void ActivePyModules::dump_server(const std::string &hostname,
const DaemonStateCollection &dmc,
Formatter *f)
{
f->dump_string("hostname", hostname);
f->open_array_section("services");
std::string ceph_version;
for (const auto &[key, state] : dmc) {
std::string id;
without_gil([&ceph_version, &id, state=state] {
std::lock_guard l(state->lock);
// TODO: pick the highest version, and make sure that
// somewhere else (during health reporting?) we are
// indicating to the user if we see mixed versions
auto ver_iter = state->metadata.find("ceph_version");
if (ver_iter != state->metadata.end()) {
ceph_version = state->metadata.at("ceph_version");
}
if (state->metadata.find("id") != state->metadata.end()) {
id = state->metadata.at("id");
}
});
f->open_object_section("service");
f->dump_string("type", key.type);
f->dump_string("id", key.name);
f->dump_string("ceph_version", ceph_version);
if (!id.empty()) {
f->dump_string("name", id);
}
f->close_section();
}
f->close_section();
f->dump_string("ceph_version", ceph_version);
}
PyObject *ActivePyModules::get_server_python(const std::string &hostname)
{
const auto dmc = without_gil([&]{
std::lock_guard l(lock);
dout(10) << " (" << hostname << ")" << dendl;
return daemon_state.get_by_server(hostname);
});
PyFormatter f;
dump_server(hostname, dmc, &f);
return f.get();
}
PyObject *ActivePyModules::list_servers_python()
{
dout(10) << " >" << dendl;
without_gil_t no_gil;
return daemon_state.with_daemons_by_server([this, &no_gil]
(const std::map<std::string, DaemonStateCollection> &all) {
no_gil.acquire_gil();
PyFormatter f(false, true);
for (const auto &[hostname, daemon_state] : all) {
f.open_object_section("server");
dump_server(hostname, daemon_state, &f);
f.close_section();
}
return f.get();
});
}
PyObject *ActivePyModules::get_metadata_python(
const std::string &svc_type,
const std::string &svc_id)
{
auto metadata = daemon_state.get(DaemonKey{svc_type, svc_id});
if (metadata == nullptr) {
derr << "Requested missing service " << svc_type << "." << svc_id << dendl;
Py_RETURN_NONE;
}
auto l = without_gil([&] {
return std::lock_guard(lock);
});
PyFormatter f;
f.dump_string("hostname", metadata->hostname);
for (const auto &[key, val] : metadata->metadata) {
f.dump_string(key, val);
}
return f.get();
}
PyObject *ActivePyModules::get_daemon_status_python(
const std::string &svc_type,
const std::string &svc_id)
{
auto metadata = daemon_state.get(DaemonKey{svc_type, svc_id});
if (metadata == nullptr) {
derr << "Requested missing service " << svc_type << "." << svc_id << dendl;
Py_RETURN_NONE;
}
auto l = without_gil([&] {
return std::lock_guard(lock);
});
PyFormatter f;
for (const auto &[daemon, status] : metadata->service_status) {
f.dump_string(daemon, status);
}
return f.get();
}
void ActivePyModules::update_cache_metrics() {
auto hit_miss_ratio = ttl_cache.get_hit_miss_ratio();
perfcounter->set(l_mgr_cache_hit, hit_miss_ratio.first);
perfcounter->set(l_mgr_cache_miss, hit_miss_ratio.second);
}
PyObject *ActivePyModules::cacheable_get_python(const std::string &what)
{
uint64_t ttl_seconds = g_conf().get_val<uint64_t>("mgr_ttl_cache_expire_seconds");
if(ttl_seconds > 0) {
ttl_cache.set_ttl(ttl_seconds);
try{
PyObject* cached = ttl_cache.get(what);
update_cache_metrics();
return cached;
} catch (std::out_of_range& e) {}
}
PyObject *obj = get_python(what);
if(ttl_seconds && ttl_cache.is_cacheable(what)) {
ttl_cache.insert(what, obj);
Py_INCREF(obj);
}
update_cache_metrics();
return obj;
}
PyObject *ActivePyModules::get_python(const std::string &what)
{
uint64_t ttl_seconds = g_conf().get_val<uint64_t>("mgr_ttl_cache_expire_seconds");
PyFormatter pf;
PyJSONFormatter jf;
// Use PyJSONFormatter if TTL cache is enabled.
Formatter &f = ttl_seconds ? (Formatter&)jf : (Formatter&)pf;
if (what == "fs_map") {
without_gil_t no_gil;
cluster_state.with_fsmap([&](const FSMap &fsmap) {
no_gil.acquire_gil();
fsmap.dump(&f);
});
} else if (what == "osdmap_crush_map_text") {
without_gil_t no_gil;
bufferlist rdata;
cluster_state.with_osdmap([&](const OSDMap &osd_map){
osd_map.crush->encode(rdata, CEPH_FEATURES_SUPPORTED_DEFAULT);
});
std::string crush_text = rdata.to_str();
no_gil.acquire_gil();
return PyUnicode_FromString(crush_text.c_str());
} else if (what.substr(0, 7) == "osd_map") {
without_gil_t no_gil;
cluster_state.with_osdmap([&](const OSDMap &osd_map){
no_gil.acquire_gil();
if (what == "osd_map") {
osd_map.dump(&f, g_ceph_context);
} else if (what == "osd_map_tree") {
osd_map.print_tree(&f, nullptr);
} else if (what == "osd_map_crush") {
osd_map.crush->dump(&f);
}
});
} else if (what == "modified_config_options") {
without_gil_t no_gil;
auto all_daemons = daemon_state.get_all();
set<string> names;
for (auto& [key, daemon] : all_daemons) {
std::lock_guard l(daemon->lock);
for (auto& [name, valmap] : daemon->config) {
names.insert(name);
}
}
no_gil.acquire_gil();
f.open_array_section("options");
for (auto& name : names) {
f.dump_string("name", name);
}
f.close_section();
} else if (what.substr(0, 6) == "config") {
// We make a copy of the global config to avoid printing
// to py formater (which may drop-take GIL) while holding
// the global config lock, which might deadlock with other
// thread that is holding the GIL and acquiring the global
// config lock.
ConfigProxy config{g_conf()};
if (what == "config_options") {
config.config_options(&f);
} else if (what == "config") {
config.show_config(&f);
}
} else if (what == "mon_map") {
without_gil_t no_gil;
cluster_state.with_monmap([&](const MonMap &monmap) {
no_gil.acquire_gil();
monmap.dump(&f);
});
} else if (what == "service_map") {
without_gil_t no_gil;
cluster_state.with_servicemap([&](const ServiceMap &service_map) {
no_gil.acquire_gil();
service_map.dump(&f);
});
} else if (what == "osd_metadata") {
without_gil_t no_gil;
auto dmc = daemon_state.get_by_service("osd");
for (const auto &[key, state] : dmc) {
std::lock_guard l(state->lock);
with_gil(no_gil, [&f, &name=key.name, state=state] {
f.open_object_section(name.c_str());
f.dump_string("hostname", state->hostname);
for (const auto &[name, val] : state->metadata) {
f.dump_string(name.c_str(), val);
}
f.close_section();
});
}
} else if (what == "mds_metadata") {
without_gil_t no_gil;
auto dmc = daemon_state.get_by_service("mds");
for (const auto &[key, state] : dmc) {
std::lock_guard l(state->lock);
with_gil(no_gil, [&f, &name=key.name, state=state] {
f.open_object_section(name.c_str());
f.dump_string("hostname", state->hostname);
for (const auto &[name, val] : state->metadata) {
f.dump_string(name.c_str(), val);
}
f.close_section();
});
}
} else if (what == "pg_summary") {
without_gil_t no_gil;
cluster_state.with_pgmap(
[&f, &no_gil](const PGMap &pg_map) {
std::map<std::string, std::map<std::string, uint32_t> > osds;
std::map<std::string, std::map<std::string, uint32_t> > pools;
std::map<std::string, uint32_t> all;
for (const auto &i : pg_map.pg_stat) {
const auto pool = i.first.m_pool;
const std::string state = pg_state_string(i.second.state);
// Insert to per-pool map
pools[stringify(pool)][state]++;
for (const auto &osd_id : i.second.acting) {
osds[stringify(osd_id)][state]++;
}
all[state]++;
}
no_gil.acquire_gil();
f.open_object_section("by_osd");
for (const auto &i : osds) {
f.open_object_section(i.first.c_str());
for (const auto &j : i.second) {
f.dump_int(j.first.c_str(), j.second);
}
f.close_section();
}
f.close_section();
f.open_object_section("by_pool");
for (const auto &i : pools) {
f.open_object_section(i.first.c_str());
for (const auto &j : i.second) {
f.dump_int(j.first.c_str(), j.second);
}
f.close_section();
}
f.close_section();
f.open_object_section("all");
for (const auto &i : all) {
f.dump_int(i.first.c_str(), i.second);
}
f.close_section();
f.open_object_section("pg_stats_sum");
pg_map.pg_sum.dump(&f);
f.close_section();
}
);
} else if (what == "pg_status") {
without_gil_t no_gil;
cluster_state.with_pgmap(
[&](const PGMap &pg_map) {
no_gil.acquire_gil();
pg_map.print_summary(&f, nullptr);
}
);
} else if (what == "pg_dump") {
without_gil_t no_gil;
cluster_state.with_pgmap(
[&](const PGMap &pg_map) {
no_gil.acquire_gil();
pg_map.dump(&f, false);
}
);
} else if (what == "devices") {
without_gil_t no_gil;
daemon_state.with_devices2(
[&] {
with_gil(no_gil, [&] { f.open_array_section("devices"); });
},
[&](const DeviceState &dev) {
with_gil(no_gil, [&] { f.dump_object("device", dev); });
});
with_gil(no_gil, [&] {
f.close_section();
});
} else if (what.size() > 7 &&
what.substr(0, 7) == "device ") {
without_gil_t no_gil;
string devid = what.substr(7);
if (!daemon_state.with_device(devid,
[&] (const DeviceState& dev) {
with_gil_t with_gil{no_gil};
f.dump_object("device", dev);
})) {
// device not found
}
} else if (what == "io_rate") {
without_gil_t no_gil;
cluster_state.with_pgmap(
[&](const PGMap &pg_map) {
no_gil.acquire_gil();
pg_map.dump_delta(&f);
}
);
} else if (what == "df") {
without_gil_t no_gil;
cluster_state.with_osdmap_and_pgmap(
[&](
const OSDMap& osd_map,
const PGMap &pg_map) {
no_gil.acquire_gil();
pg_map.dump_cluster_stats(nullptr, &f, true);
pg_map.dump_pool_stats_full(osd_map, nullptr, &f, true);
});
} else if (what == "pg_stats") {
without_gil_t no_gil;
cluster_state.with_pgmap([&](const PGMap &pg_map) {
no_gil.acquire_gil();
pg_map.dump_pg_stats(&f, false);
});
} else if (what == "pool_stats") {
without_gil_t no_gil;
cluster_state.with_pgmap([&](const PGMap &pg_map) {
no_gil.acquire_gil();
pg_map.dump_pool_stats(&f);
});
} else if (what == "pg_ready") {
server.dump_pg_ready(&f);
} else if (what == "pg_progress") {
without_gil_t no_gil;
cluster_state.with_pgmap([&](const PGMap &pg_map) {
no_gil.acquire_gil();
pg_map.dump_pg_progress(&f);
server.dump_pg_ready(&f);
});
} else if (what == "osd_stats") {
without_gil_t no_gil;
cluster_state.with_pgmap([&](const PGMap &pg_map) {
no_gil.acquire_gil();
pg_map.dump_osd_stats(&f, false);
});
} else if (what == "osd_ping_times") {
without_gil_t no_gil;
cluster_state.with_pgmap([&](const PGMap &pg_map) {
no_gil.acquire_gil();
pg_map.dump_osd_ping_times(&f);
});
} else if (what == "osd_pool_stats") {
without_gil_t no_gil;
int64_t poolid = -ENOENT;
cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap,
const PGMap& pg_map) {
no_gil.acquire_gil();
f.open_array_section("pool_stats");
for (auto &p : osdmap.get_pools()) {
poolid = p.first;
pg_map.dump_pool_stats_and_io_rate(poolid, osdmap, &f, nullptr);
}
f.close_section();
});
} else if (what == "health") {
without_gil_t no_gil;
cluster_state.with_health([&](const ceph::bufferlist &health_json) {
no_gil.acquire_gil();
f.dump_string("json", health_json.to_str());
});
} else if (what == "mon_status") {
without_gil_t no_gil;
cluster_state.with_mon_status(
[&](const ceph::bufferlist &mon_status_json) {
no_gil.acquire_gil();
f.dump_string("json", mon_status_json.to_str());
});
} else if (what == "mgr_map") {
without_gil_t no_gil;
cluster_state.with_mgrmap([&](const MgrMap &mgr_map) {
no_gil.acquire_gil();
mgr_map.dump(&f);
});
} else if (what == "mgr_ips") {
entity_addrvec_t myaddrs = server.get_myaddrs();
f.open_array_section("ips");
std::set<std::string> did;
for (auto& i : myaddrs.v) {
std::string ip = i.ip_only_to_str();
if (auto [where, inserted] = did.insert(ip); inserted) {
f.dump_string("ip", ip);
}
}
f.close_section();
} else if (what == "have_local_config_map") {
f.dump_bool("have_local_config_map", have_local_config_map);
} else if (what == "active_clean_pgs"){
without_gil_t no_gil;
cluster_state.with_pgmap(
[&](const PGMap &pg_map) {
no_gil.acquire_gil();
f.open_array_section("pg_stats");
for (auto &i : pg_map.pg_stat) {
const auto state = i.second.state;
const auto pgid_raw = i.first;
const auto pgid = stringify(pgid_raw.m_pool) + "." + stringify(pgid_raw.m_seed);
const auto reported_epoch = i.second.reported_epoch;
if (state & PG_STATE_ACTIVE && state & PG_STATE_CLEAN) {
f.open_object_section("pg_stat");
f.dump_string("pgid", pgid);
f.dump_string("state", pg_state_string(state));
f.dump_unsigned("reported_epoch", reported_epoch);
f.close_section();
}
}
f.close_section();
const auto num_pg = pg_map.num_pg;
f.dump_unsigned("total_num_pgs", num_pg);
});
} else {
derr << "Python module requested unknown data '" << what << "'" << dendl;
Py_RETURN_NONE;
}
if(ttl_seconds) {
return jf.get();
} else {
return pf.get();
}
}
void ActivePyModules::start_one(PyModuleRef py_module)
{
std::lock_guard l(lock);
const auto name = py_module->get_name();
auto active_module = std::make_shared<ActivePyModule>(py_module, clog);
pending_modules.insert(name);
// Send all python calls down a Finisher to avoid blocking
// C++ code, and avoid any potential lock cycles.
finisher.queue(new LambdaContext([this, active_module, name](int) {
int r = active_module->load(this);
std::lock_guard l(lock);
pending_modules.erase(name);
if (r != 0) {
derr << "Failed to run module in active mode ('" << name << "')"
<< dendl;
} else {
auto em = modules.emplace(name, active_module);
ceph_assert(em.second); // actually inserted
dout(4) << "Starting thread for " << name << dendl;
active_module->thread.create(active_module->get_thread_name());
dout(4) << "Starting active module " << name <<" finisher thread "
<< active_module->get_fin_thread_name() << dendl;
active_module->finisher.start();
}
}));
}
void ActivePyModules::shutdown()
{
std::lock_guard locker(lock);
// Stop per active module finisher thread
for (auto& [name, module] : modules) {
dout(4) << "Stopping active module " << name << " finisher thread" << dendl;
module->finisher.wait_for_empty();
module->finisher.stop();
}
// Signal modules to drop out of serve() and/or tear down resources
for (auto& [name, module] : modules) {
lock.unlock();
dout(10) << "calling module " << name << " shutdown()" << dendl;
module->shutdown();
dout(10) << "module " << name << " shutdown() returned" << dendl;
lock.lock();
}
// For modules implementing serve(), finish the threads where we
// were running that.
for (auto& [name, module] : modules) {
lock.unlock();
dout(10) << "joining module " << name << dendl;
module->thread.join();
dout(10) << "joined module " << name << dendl;
lock.lock();
}
cmd_finisher.wait_for_empty();
cmd_finisher.stop();
modules.clear();
}
void ActivePyModules::notify_all(const std::string ¬ify_type,
const std::string ¬ify_id)
{
std::lock_guard l(lock);
dout(10) << __func__ << ": notify_all " << notify_type << dendl;
for (auto& [name, module] : modules) {
if (!py_module_registry.should_notify(name, notify_type)) {
continue;
}
// Send all python calls down a Finisher to avoid blocking
// C++ code, and avoid any potential lock cycles.
dout(15) << "queuing notify (" << notify_type << ") to " << name << dendl;
Finisher& mod_finisher = py_module_registry.get_active_module_finisher(name);
// workaround for https://bugs.llvm.org/show_bug.cgi?id=35984
mod_finisher.queue(new LambdaContext([module=module, notify_type, notify_id]
(int r){
module->notify(notify_type, notify_id);
}));
}
}
void ActivePyModules::notify_all(const LogEntry &log_entry)
{
std::lock_guard l(lock);
dout(10) << __func__ << ": notify_all (clog)" << dendl;
for (auto& [name, module] : modules) {
if (!py_module_registry.should_notify(name, "clog")) {
continue;
}
// Send all python calls down a Finisher to avoid blocking
// C++ code, and avoid any potential lock cycles.
//
// Note intentional use of non-reference lambda binding on
// log_entry: we take a copy because caller's instance is
// probably ephemeral.
dout(15) << "queuing notify (clog) to " << name << dendl;
Finisher& mod_finisher = py_module_registry.get_active_module_finisher(name);
// workaround for https://bugs.llvm.org/show_bug.cgi?id=35984
mod_finisher.queue(new LambdaContext([module=module, log_entry](int r){
module->notify_clog(log_entry);
}));
}
}
bool ActivePyModules::get_store(const std::string &module_name,
const std::string &key, std::string *val) const
{
without_gil_t no_gil;
std::lock_guard l(lock);
const std::string global_key = PyModule::mgr_store_prefix
+ module_name + "/" + key;
dout(4) << __func__ << " key: " << global_key << dendl;
auto i = store_cache.find(global_key);
if (i != store_cache.end()) {
*val = i->second;
return true;
} else {
return false;
}
}
PyObject *ActivePyModules::dispatch_remote(
const std::string &other_module,
const std::string &method,
PyObject *args,
PyObject *kwargs,
std::string *err)
{
auto mod_iter = modules.find(other_module);
ceph_assert(mod_iter != modules.end());
return mod_iter->second->dispatch_remote(method, args, kwargs, err);
}
bool ActivePyModules::get_config(const std::string &module_name,
const std::string &key, std::string *val) const
{
const std::string global_key = "mgr/" + module_name + "/" + key;
dout(20) << " key: " << global_key << dendl;
std::lock_guard lock(module_config.lock);
auto i = module_config.config.find(global_key);
if (i != module_config.config.end()) {
*val = i->second;
return true;
} else {
return false;
}
}
PyObject *ActivePyModules::get_typed_config(
const std::string &module_name,
const std::string &key,
const std::string &prefix) const
{
without_gil_t no_gil;
std::string value;
std::string final_key;
bool found = false;
if (prefix.size()) {
final_key = prefix + "/" + key;
found = get_config(module_name, final_key, &value);
}
if (!found) {
final_key = key;
found = get_config(module_name, final_key, &value);
}
if (found) {
PyModuleRef module = py_module_registry.get_module(module_name);
no_gil.acquire_gil();
if (!module) {
derr << "Module '" << module_name << "' is not available" << dendl;
Py_RETURN_NONE;
}
// removing value to hide sensitive data going into mgr logs
// leaving this for debugging purposes
// dout(10) << __func__ << " " << final_key << " found: " << value << dendl;
dout(10) << __func__ << " " << final_key << " found" << dendl;
return module->get_typed_option_value(key, value);
}
if (prefix.size()) {
dout(10) << " [" << prefix << "/]" << key << " not found "
<< dendl;
} else {
dout(10) << " " << key << " not found " << dendl;
}
Py_RETURN_NONE;
}
PyObject *ActivePyModules::get_store_prefix(const std::string &module_name,
const std::string &prefix) const
{
without_gil_t no_gil;
std::lock_guard l(lock);
std::lock_guard lock(module_config.lock);
no_gil.acquire_gil();
const std::string base_prefix = PyModule::mgr_store_prefix
+ module_name + "/";
const std::string global_prefix = base_prefix + prefix;
dout(4) << __func__ << " prefix: " << global_prefix << dendl;
PyFormatter f;
for (auto p = store_cache.lower_bound(global_prefix);
p != store_cache.end() && p->first.find(global_prefix) == 0; ++p) {
f.dump_string(p->first.c_str() + base_prefix.size(), p->second);
}
return f.get();
}
void ActivePyModules::set_store(const std::string &module_name,
const std::string &key, const std::optional<std::string>& val)
{
const std::string global_key = PyModule::mgr_store_prefix
+ module_name + "/" + key;
Command set_cmd;
{
std::lock_guard l(lock);
// NOTE: this isn't strictly necessary since we'll also get an MKVData
// update from the mon due to our subscription *before* our command is acked.
if (val) {
store_cache[global_key] = *val;
} else {
store_cache.erase(global_key);
}
std::ostringstream cmd_json;
JSONFormatter jf;
jf.open_object_section("cmd");
if (val) {
jf.dump_string("prefix", "config-key set");
jf.dump_string("key", global_key);
jf.dump_string("val", *val);
} else {
jf.dump_string("prefix", "config-key del");
jf.dump_string("key", global_key);
}
jf.close_section();
jf.flush(cmd_json);
set_cmd.run(&monc, cmd_json.str());
}
set_cmd.wait();
if (set_cmd.r != 0) {
// config-key set will fail if mgr's auth key has insufficient
// permission to set config keys
// FIXME: should this somehow raise an exception back into Python land?
dout(0) << "`config-key set " << global_key << " " << val << "` failed: "
<< cpp_strerror(set_cmd.r) << dendl;
dout(0) << "mon returned " << set_cmd.r << ": " << set_cmd.outs << dendl;
}
}
std::pair<int, std::string> ActivePyModules::set_config(
const std::string &module_name,
const std::string &key,
const std::optional<std::string>& val)
{
return module_config.set_config(&monc, module_name, key, val);
}
std::map<std::string, std::string> ActivePyModules::get_services() const
{
std::map<std::string, std::string> result;
std::lock_guard l(lock);
for (const auto& [name, module] : modules) {
std::string svc_str = module->get_uri();
if (!svc_str.empty()) {
result[name] = svc_str;
}
}
return result;
}
void ActivePyModules::update_kv_data(
const std::string prefix,
bool incremental,
const map<std::string, std::optional<bufferlist>, std::less<>>& data)
{
std::lock_guard l(lock);
bool do_config = false;
if (!incremental) {
dout(10) << "full update on " << prefix << dendl;
auto p = store_cache.lower_bound(prefix);
while (p != store_cache.end() && p->first.find(prefix) == 0) {
dout(20) << " rm prior " << p->first << dendl;
p = store_cache.erase(p);
}
} else {
dout(10) << "incremental update on " << prefix << dendl;
}
for (auto& i : data) {
if (i.second) {
dout(20) << " set " << i.first << " = " << i.second->to_str() << dendl;
store_cache[i.first] = i.second->to_str();
} else {
dout(20) << " rm " << i.first << dendl;
store_cache.erase(i.first);
}
if (i.first.find("config/") == 0) {
do_config = true;
}
}
if (do_config) {
_refresh_config_map();
}
}
void ActivePyModules::_refresh_config_map()
{
dout(10) << dendl;
config_map.clear();
for (auto p = store_cache.lower_bound("config/");
p != store_cache.end() && p->first.find("config/") == 0;
++p) {
string key = p->first.substr(7);
if (key.find("mgr/") == 0) {
// NOTE: for now, we ignore module options. see also ceph_foreign_option_get().
continue;
}
string value = p->second;
string name;
string who;
config_map.parse_key(key, &name, &who);
const Option *opt = g_conf().find_option(name);
if (!opt) {
config_map.stray_options.push_back(
std::unique_ptr<Option>(
new Option(name, Option::TYPE_STR, Option::LEVEL_UNKNOWN)));
opt = config_map.stray_options.back().get();
}
string err;
int r = opt->pre_validate(&value, &err);
if (r < 0) {
dout(10) << __func__ << " pre-validate failed on '" << name << "' = '"
<< value << "' for " << name << dendl;
}
MaskedOption mopt(opt);
mopt.raw_value = value;
string section_name;
if (who.size() &&
!ConfigMap::parse_mask(who, §ion_name, &mopt.mask)) {
derr << __func__ << " invalid mask for key " << key << dendl;
} else if (opt->has_flag(Option::FLAG_NO_MON_UPDATE)) {
dout(10) << __func__ << " NO_MON_UPDATE option '"
<< name << "' = '" << value << "' for " << name
<< dendl;
} else {
Section *section = &config_map.global;;
if (section_name.size() && section_name != "global") {
if (section_name.find('.') != std::string::npos) {
section = &config_map.by_id[section_name];
} else {
section = &config_map.by_type[section_name];
}
}
section->options.insert(make_pair(name, std::move(mopt)));
}
}
}
PyObject* ActivePyModules::with_perf_counters(
std::function<void(PerfCounterInstance& counter_instance, PerfCounterType& counter_type, PyFormatter& f)> fct,
const std::string &svc_name,
const std::string &svc_id,
const std::string &path) const
{
PyFormatter f;
f.open_array_section(path);
{
without_gil_t no_gil;
std::lock_guard l(lock);
auto metadata = daemon_state.get(DaemonKey{svc_name, svc_id});
if (metadata) {
std::lock_guard l2(metadata->lock);
if (metadata->perf_counters.instances.count(path)) {
auto counter_instance = metadata->perf_counters.instances.at(path);
auto counter_type = metadata->perf_counters.types.at(path);
with_gil(no_gil, [&] {
fct(counter_instance, counter_type, f);
});
} else {
dout(4) << "Missing counter: '" << path << "' ("
<< svc_name << "." << svc_id << ")" << dendl;
dout(20) << "Paths are:" << dendl;
for (const auto &i : metadata->perf_counters.instances) {
dout(20) << i.first << dendl;
}
}
} else {
dout(4) << "No daemon state for " << svc_name << "." << svc_id << ")"
<< dendl;
}
}
f.close_section();
return f.get();
}
PyObject* ActivePyModules::get_counter_python(
const std::string &svc_name,
const std::string &svc_id,
const std::string &path)
{
auto extract_counters = [](
PerfCounterInstance& counter_instance,
PerfCounterType& counter_type,
PyFormatter& f)
{
if (counter_type.type & PERFCOUNTER_LONGRUNAVG) {
const auto &avg_data = counter_instance.get_data_avg();
for (const auto &datapoint : avg_data) {
f.open_array_section("datapoint");
f.dump_float("t", datapoint.t);
f.dump_unsigned("s", datapoint.s);
f.dump_unsigned("c", datapoint.c);
f.close_section();
}
} else {
const auto &data = counter_instance.get_data();
for (const auto &datapoint : data) {
f.open_array_section("datapoint");
f.dump_float("t", datapoint.t);
f.dump_unsigned("v", datapoint.v);
f.close_section();
}
}
};
return with_perf_counters(extract_counters, svc_name, svc_id, path);
}
PyObject* ActivePyModules::get_latest_counter_python(
const std::string &svc_name,
const std::string &svc_id,
const std::string &path)
{
auto extract_latest_counters = [](
PerfCounterInstance& counter_instance,
PerfCounterType& counter_type,
PyFormatter& f)
{
if (counter_type.type & PERFCOUNTER_LONGRUNAVG) {
const auto &datapoint = counter_instance.get_latest_data_avg();
f.dump_float("t", datapoint.t);
f.dump_unsigned("s", datapoint.s);
f.dump_unsigned("c", datapoint.c);
} else {
const auto &datapoint = counter_instance.get_latest_data();
f.dump_float("t", datapoint.t);
f.dump_unsigned("v", datapoint.v);
}
};
return with_perf_counters(extract_latest_counters, svc_name, svc_id, path);
}
PyObject* ActivePyModules::get_perf_schema_python(
const std::string &svc_type,
const std::string &svc_id)
{
without_gil_t no_gil;
std::lock_guard l(lock);
DaemonStateCollection daemons;
if (svc_type == "") {
daemons = daemon_state.get_all();
} else if (svc_id.empty()) {
daemons = daemon_state.get_by_service(svc_type);
} else {
auto key = DaemonKey{svc_type, svc_id};
// so that the below can be a loop in all cases
auto got = daemon_state.get(key);
if (got != nullptr) {
daemons[key] = got;
}
}
auto f = with_gil(no_gil, [&] {
return PyFormatter();
});
if (!daemons.empty()) {
for (auto& [key, state] : daemons) {
std::lock_guard l(state->lock);
with_gil(no_gil, [&, key=ceph::to_string(key), state=state] {
f.open_object_section(key.c_str());
for (auto ctr_inst_iter : state->perf_counters.instances) {
const auto &counter_name = ctr_inst_iter.first;
f.open_object_section(counter_name.c_str());
auto type = state->perf_counters.types[counter_name];
f.dump_string("description", type.description);
if (!type.nick.empty()) {
f.dump_string("nick", type.nick);
}
f.dump_unsigned("type", type.type);
f.dump_unsigned("priority", type.priority);
f.dump_unsigned("units", type.unit);
f.close_section();
}
f.close_section();
});
}
} else {
dout(4) << __func__ << ": No daemon state found for "
<< svc_type << "." << svc_id << ")" << dendl;
}
return f.get();
}
PyObject* ActivePyModules::get_rocksdb_version()
{
std::string version = std::to_string(ROCKSDB_MAJOR) + "." +
std::to_string(ROCKSDB_MINOR) + "." +
std::to_string(ROCKSDB_PATCH);
return PyUnicode_FromString(version.c_str());
}
PyObject *ActivePyModules::get_context()
{
auto l = without_gil([&] {
return std::lock_guard(lock);
});
// Construct a capsule containing ceph context.
// Not incrementing/decrementing ref count on the context because
// it's the global one and it has process lifetime.
auto capsule = PyCapsule_New(g_ceph_context, nullptr, nullptr);
return capsule;
}
/**
* Helper for our wrapped types that take a capsule in their constructor.
*/
PyObject *construct_with_capsule(
const std::string &module_name,
const std::string &clsname,
void *wrapped)
{
// Look up the OSDMap type which we will construct
PyObject *module = PyImport_ImportModule(module_name.c_str());
if (!module) {
derr << "Failed to import python module:" << dendl;
derr << handle_pyerror(true, module_name,
"construct_with_capsule "s + module_name + " " + clsname) << dendl;
}
ceph_assert(module);
PyObject *wrapper_type = PyObject_GetAttrString(
module, (const char*)clsname.c_str());
if (!wrapper_type) {
derr << "Failed to get python type:" << dendl;
derr << handle_pyerror(true, module_name,
"construct_with_capsule "s + module_name + " " + clsname) << dendl;
}
ceph_assert(wrapper_type);
// Construct a capsule containing an OSDMap.
auto wrapped_capsule = PyCapsule_New(wrapped, nullptr, nullptr);
ceph_assert(wrapped_capsule);
// Construct the python OSDMap
auto pArgs = PyTuple_Pack(1, wrapped_capsule);
auto wrapper_instance = PyObject_CallObject(wrapper_type, pArgs);
if (wrapper_instance == nullptr) {
derr << "Failed to construct python OSDMap:" << dendl;
derr << handle_pyerror(true, module_name,
"construct_with_capsule "s + module_name + " " + clsname) << dendl;
}
ceph_assert(wrapper_instance != nullptr);
Py_DECREF(pArgs);
Py_DECREF(wrapped_capsule);
Py_DECREF(wrapper_type);
Py_DECREF(module);
return wrapper_instance;
}
PyObject *ActivePyModules::get_osdmap()
{
auto newmap = without_gil([&] {
OSDMap *newmap = new OSDMap;
cluster_state.with_osdmap([&](const OSDMap& o) {
newmap->deepish_copy_from(o);
});
return newmap;
});
return construct_with_capsule("mgr_module", "OSDMap", (void*)newmap);
}
PyObject *ActivePyModules::get_foreign_config(
const std::string& who,
const std::string& name)
{
dout(10) << "ceph_foreign_option_get " << who << " " << name << dendl;
// NOTE: for now this will only work with build-in options, not module options.
const Option *opt = g_conf().find_option(name);
if (!opt) {
dout(4) << "ceph_foreign_option_get " << name << " not found " << dendl;
PyErr_Format(PyExc_KeyError, "option not found: %s", name.c_str());
return nullptr;
}
// If the monitors are not yet running pacific, we cannot rely on our local
// ConfigMap
if (!have_local_config_map) {
dout(20) << "mon cluster wasn't pacific when we started: falling back to 'config get'"
<< dendl;
without_gil_t no_gil;
Command cmd;
{
std::lock_guard l(lock);
cmd.run(
&monc,
"{\"prefix\": \"config get\","s +
"\"who\": \""s + who + "\","s +
"\"key\": \""s + name + "\"}");
}
cmd.wait();
dout(10) << "ceph_foreign_option_get (mon command) " << who << " " << name << " = "
<< cmd.outbl.to_str() << dendl;
no_gil.acquire_gil();
return get_python_typed_option_value(opt->type, cmd.outbl.to_str());
}
// mimic the behavor of mon/ConfigMonitor's 'config get' command
EntityName entity;
if (!entity.from_str(who) &&
!entity.from_str(who + ".")) {
dout(5) << "unrecognized entity '" << who << "'" << dendl;
PyErr_Format(PyExc_KeyError, "invalid entity: %s", who.c_str());
return nullptr;
}
without_gil_t no_gil;
lock.lock();
// FIXME: this is super inefficient, since we generate the entire daemon
// config just to extract one value from it!
std::map<std::string,std::string,std::less<>> config;
cluster_state.with_osdmap([&](const OSDMap &osdmap) {
map<string,string> crush_location;
string device_class;
if (entity.is_osd()) {
osdmap.crush->get_full_location(who, &crush_location);
int id = atoi(entity.get_id().c_str());
const char *c = osdmap.crush->get_item_class(id);
if (c) {
device_class = c;
}
dout(10) << __func__ << " crush_location " << crush_location
<< " class " << device_class << dendl;
}
std::map<std::string,pair<std::string,const MaskedOption*>> src;
config = config_map.generate_entity_map(
entity,
crush_location,
osdmap.crush.get(),
device_class,
&src);
});
// get a single value
string value;
auto p = config.find(name);
if (p != config.end()) {
value = p->second;
} else {
if (!entity.is_client() &&
opt->daemon_value != Option::value_t{}) {
value = Option::to_str(opt->daemon_value);
} else {
value = Option::to_str(opt->value);
}
}
dout(10) << "ceph_foreign_option_get (configmap) " << who << " " << name << " = "
<< value << dendl;
lock.unlock();
no_gil.acquire_gil();
return get_python_typed_option_value(opt->type, value);
}
void ActivePyModules::set_health_checks(const std::string& module_name,
health_check_map_t&& checks)
{
bool changed = false;
lock.lock();
auto p = modules.find(module_name);
if (p != modules.end()) {
changed = p->second->set_health_checks(std::move(checks));
}
lock.unlock();
// immediately schedule a report to be sent to the monitors with the new
// health checks that have changed. This is done asynchronusly to avoid
// blocking python land. ActivePyModules::lock needs to be dropped to make
// lockdep happy:
//
// send_report callers: DaemonServer::lock -> PyModuleRegistery::lock
// active_start: PyModuleRegistry::lock -> ActivePyModules::lock
//
// if we don't release this->lock before calling schedule_tick a cycle is
// formed with the addition of ActivePyModules::lock -> DaemonServer::lock.
// This is still correct as send_report is run asynchronously under
// DaemonServer::lock.
if (changed)
server.schedule_tick(0);
}
int ActivePyModules::handle_command(
const ModuleCommand& module_command,
const MgrSession& session,
const cmdmap_t &cmdmap,
const bufferlist &inbuf,
std::stringstream *ds,
std::stringstream *ss)
{
lock.lock();
auto mod_iter = modules.find(module_command.module_name);
if (mod_iter == modules.end()) {
*ss << "Module '" << module_command.module_name << "' is not available";
lock.unlock();
return -ENOENT;
}
lock.unlock();
return mod_iter->second->handle_command(module_command, session, cmdmap,
inbuf, ds, ss);
}
void ActivePyModules::get_health_checks(health_check_map_t *checks)
{
std::lock_guard l(lock);
for (auto& [name, module] : modules) {
dout(15) << "getting health checks for " << name << dendl;
module->get_health_checks(checks);
}
}
void ActivePyModules::update_progress_event(
const std::string& evid,
const std::string& desc,
float progress,
bool add_to_ceph_s)
{
std::lock_guard l(lock);
auto& pe = progress_events[evid];
pe.message = desc;
pe.progress = progress;
pe.add_to_ceph_s = add_to_ceph_s;
}
void ActivePyModules::complete_progress_event(const std::string& evid)
{
std::lock_guard l(lock);
progress_events.erase(evid);
}
void ActivePyModules::clear_all_progress_events()
{
std::lock_guard l(lock);
progress_events.clear();
}
void ActivePyModules::get_progress_events(std::map<std::string,ProgressEvent> *events)
{
std::lock_guard l(lock);
*events = progress_events;
}
void ActivePyModules::config_notify()
{
std::lock_guard l(lock);
for (auto& [name, module] : modules) {
// Send all python calls down a Finisher to avoid blocking
// C++ code, and avoid any potential lock cycles.
dout(15) << "notify (config) " << name << dendl;
Finisher& mod_finisher = py_module_registry.get_active_module_finisher(name);
// workaround for https://bugs.llvm.org/show_bug.cgi?id=35984
mod_finisher.queue(new LambdaContext([module=module](int r){
module->config_notify();
}));
}
}
void ActivePyModules::set_uri(const std::string& module_name,
const std::string &uri)
{
std::lock_guard l(lock);
dout(4) << " module " << module_name << " set URI '" << uri << "'" << dendl;
modules.at(module_name)->set_uri(uri);
}
void ActivePyModules::set_device_wear_level(const std::string& devid,
float wear_level)
{
// update mgr state
map<string,string> meta;
daemon_state.with_device(
devid,
[wear_level, &meta] (DeviceState& dev) {
dev.set_wear_level(wear_level);
meta = dev.metadata;
});
// tell mon
json_spirit::Object json_object;
for (auto& i : meta) {
json_spirit::Config::add(json_object, i.first, i.second);
}
bufferlist json;
json.append(json_spirit::write(json_object));
const string cmd =
"{"
"\"prefix\": \"config-key set\", "
"\"key\": \"device/" + devid + "\""
"}";
Command set_cmd;
set_cmd.run(&monc, cmd, json);
set_cmd.wait();
}
MetricQueryID ActivePyModules::add_osd_perf_query(
const OSDPerfMetricQuery &query,
const std::optional<OSDPerfMetricLimit> &limit)
{
return server.add_osd_perf_query(query, limit);
}
void ActivePyModules::remove_osd_perf_query(MetricQueryID query_id)
{
int r = server.remove_osd_perf_query(query_id);
if (r < 0) {
dout(0) << "remove_osd_perf_query for query_id=" << query_id << " failed: "
<< cpp_strerror(r) << dendl;
}
}
PyObject *ActivePyModules::get_osd_perf_counters(MetricQueryID query_id)
{
OSDPerfCollector collector(query_id);
int r = server.get_osd_perf_counters(&collector);
if (r < 0) {
dout(0) << "get_osd_perf_counters for query_id=" << query_id << " failed: "
<< cpp_strerror(r) << dendl;
Py_RETURN_NONE;
}
PyFormatter f;
const std::map<OSDPerfMetricKey, PerformanceCounters> &counters = collector.counters;
f.open_array_section("counters");
for (auto &[key, instance_counters] : counters) {
f.open_object_section("i");
f.open_array_section("k");
for (auto &sub_key : key) {
f.open_array_section("s");
for (size_t i = 0; i < sub_key.size(); i++) {
f.dump_string(stringify(i).c_str(), sub_key[i]);
}
f.close_section(); // s
}
f.close_section(); // k
f.open_array_section("c");
for (auto &c : instance_counters) {
f.open_array_section("p");
f.dump_unsigned("0", c.first);
f.dump_unsigned("1", c.second);
f.close_section(); // p
}
f.close_section(); // c
f.close_section(); // i
}
f.close_section(); // counters
return f.get();
}
MetricQueryID ActivePyModules::add_mds_perf_query(
const MDSPerfMetricQuery &query,
const std::optional<MDSPerfMetricLimit> &limit)
{
return server.add_mds_perf_query(query, limit);
}
void ActivePyModules::remove_mds_perf_query(MetricQueryID query_id)
{
int r = server.remove_mds_perf_query(query_id);
if (r < 0) {
dout(0) << "remove_mds_perf_query for query_id=" << query_id << " failed: "
<< cpp_strerror(r) << dendl;
}
}
void ActivePyModules::reregister_mds_perf_queries()
{
server.reregister_mds_perf_queries();
}
PyObject *ActivePyModules::get_mds_perf_counters(MetricQueryID query_id)
{
MDSPerfCollector collector(query_id);
int r = server.get_mds_perf_counters(&collector);
if (r < 0) {
dout(0) << "get_mds_perf_counters for query_id=" << query_id << " failed: "
<< cpp_strerror(r) << dendl;
Py_RETURN_NONE;
}
PyFormatter f;
const std::map<MDSPerfMetricKey, PerformanceCounters> &counters = collector.counters;
f.open_array_section("metrics");
f.open_array_section("delayed_ranks");
f.dump_string("ranks", stringify(collector.delayed_ranks).c_str());
f.close_section(); // delayed_ranks
f.open_array_section("counters");
for (auto &[key, instance_counters] : counters) {
f.open_object_section("i");
f.open_array_section("k");
for (auto &sub_key : key) {
f.open_array_section("s");
for (size_t i = 0; i < sub_key.size(); i++) {
f.dump_string(stringify(i).c_str(), sub_key[i]);
}
f.close_section(); // s
}
f.close_section(); // k
f.open_array_section("c");
for (auto &c : instance_counters) {
f.open_array_section("p");
f.dump_unsigned("0", c.first);
f.dump_unsigned("1", c.second);
f.close_section(); // p
}
f.close_section(); // c
f.close_section(); // i
}
f.close_section(); // counters
f.open_array_section("last_updated");
f.dump_float("last_updated_mono", collector.last_updated_mono);
f.close_section(); // last_updated
f.close_section(); // metrics
return f.get();
}
void ActivePyModules::cluster_log(const std::string &channel, clog_type prio,
const std::string &message)
{
std::lock_guard l(lock);
auto cl = monc.get_log_client()->create_channel(channel);
cl->parse_client_options(g_ceph_context);
cl->do_log(prio, message);
}
void ActivePyModules::register_client(std::string_view name, std::string addrs, bool replace)
{
entity_addrvec_t addrv;
addrv.parse(addrs.data());
dout(7) << "registering msgr client handle " << addrv << " (replace=" << replace << ")" << dendl;
py_module_registry.register_client(name, std::move(addrv), replace);
}
void ActivePyModules::unregister_client(std::string_view name, std::string addrs)
{
entity_addrvec_t addrv;
addrv.parse(addrs.data());
dout(7) << "unregistering msgr client handle " << addrv << dendl;
py_module_registry.unregister_client(name, addrv);
}
PyObject* ActivePyModules::get_daemon_health_metrics()
{
without_gil_t no_gil;
return daemon_state.with_daemons_by_server([&no_gil]
(const std::map<std::string, DaemonStateCollection> &all) {
no_gil.acquire_gil();
PyFormatter f;
for (const auto &[hostname, daemon_state] : all) {
for (const auto &[key, state] : daemon_state) {
f.open_array_section(ceph::to_string(key));
for (const auto &metric : state->daemon_health_metrics) {
f.open_object_section(metric.get_type_name());
f.dump_int("value", metric.get_n1());
f.dump_string("type", metric.get_type_name());
f.close_section();
}
f.close_section();
}
}
return f.get();
});
}
| 47,637 | 29.655084 | 114 | cc |
null | ceph-main/src/mgr/ActivePyModules.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#pragma once
#include "ActivePyModule.h"
#include "common/Finisher.h"
#include "common/ceph_mutex.h"
#include "PyFormatter.h"
#include "osdc/Objecter.h"
#include "client/Client.h"
#include "common/LogClient.h"
#include "mon/MgrMap.h"
#include "mon/MonCommand.h"
#include "mon/mon_types.h"
#include "mon/ConfigMap.h"
#include "mgr/TTLCache.h"
#include "DaemonState.h"
#include "ClusterState.h"
#include "OSDPerfMetricTypes.h"
class health_check_map_t;
class DaemonServer;
class MgrSession;
class ModuleCommand;
class PyModuleRegistry;
class ActivePyModules
{
// module class instances not yet created
std::set<std::string, std::less<>> pending_modules;
// module class instances already created
std::map<std::string, std::shared_ptr<ActivePyModule>> modules;
PyModuleConfig &module_config;
bool have_local_config_map = false;
std::map<std::string, std::string> store_cache;
ConfigMap config_map; ///< derived from store_cache config/ keys
DaemonStateIndex &daemon_state;
ClusterState &cluster_state;
MonClient &monc;
LogChannelRef clog, audit_clog;
Objecter &objecter;
Client &client;
Finisher &finisher;
TTLCache<std::string, PyObject*> ttl_cache;
public:
Finisher cmd_finisher;
private:
DaemonServer &server;
PyModuleRegistry &py_module_registry;
std::map<std::string,ProgressEvent> progress_events;
mutable ceph::mutex lock = ceph::make_mutex("ActivePyModules::lock");
public:
ActivePyModules(
PyModuleConfig &module_config,
std::map<std::string, std::string> store_data,
bool mon_provides_kv_sub,
DaemonStateIndex &ds, ClusterState &cs, MonClient &mc,
LogChannelRef clog_, LogChannelRef audit_clog_, Objecter &objecter_, Client &client_,
Finisher &f, DaemonServer &server, PyModuleRegistry &pmr);
~ActivePyModules();
// FIXME: wrap for send_command?
MonClient &get_monc() {return monc;}
Objecter &get_objecter() {return objecter;}
Client &get_client() {return client;}
PyObject *cacheable_get_python(const std::string &what);
PyObject *get_python(const std::string &what);
PyObject *get_server_python(const std::string &hostname);
PyObject *list_servers_python();
PyObject *get_metadata_python(
const std::string &svc_type, const std::string &svc_id);
PyObject *get_daemon_status_python(
const std::string &svc_type, const std::string &svc_id);
PyObject *get_counter_python(
const std::string &svc_type,
const std::string &svc_id,
const std::string &path);
PyObject *get_latest_counter_python(
const std::string &svc_type,
const std::string &svc_id,
const std::string &path);
PyObject *get_perf_schema_python(
const std::string &svc_type,
const std::string &svc_id);
PyObject *get_rocksdb_version();
PyObject *get_context();
PyObject *get_osdmap();
/// @note @c fct is not allowed to acquire locks when holding GIL
PyObject *with_perf_counters(
std::function<void(
PerfCounterInstance& counter_instance,
PerfCounterType& counter_type,
PyFormatter& f)> fct,
const std::string &svc_name,
const std::string &svc_id,
const std::string &path) const;
MetricQueryID add_osd_perf_query(
const OSDPerfMetricQuery &query,
const std::optional<OSDPerfMetricLimit> &limit);
void remove_osd_perf_query(MetricQueryID query_id);
PyObject *get_osd_perf_counters(MetricQueryID query_id);
MetricQueryID add_mds_perf_query(
const MDSPerfMetricQuery &query,
const std::optional<MDSPerfMetricLimit> &limit);
void remove_mds_perf_query(MetricQueryID query_id);
void reregister_mds_perf_queries();
PyObject *get_mds_perf_counters(MetricQueryID query_id);
bool get_store(const std::string &module_name,
const std::string &key, std::string *val) const;
PyObject *get_store_prefix(const std::string &module_name,
const std::string &prefix) const;
void set_store(const std::string &module_name,
const std::string &key, const std::optional<std::string> &val);
bool get_config(const std::string &module_name,
const std::string &key, std::string *val) const;
std::pair<int, std::string> set_config(const std::string &module_name,
const std::string &key, const std::optional<std::string> &val);
PyObject *get_typed_config(const std::string &module_name,
const std::string &key,
const std::string &prefix = "") const;
PyObject *get_foreign_config(
const std::string& who,
const std::string& name);
void set_health_checks(const std::string& module_name,
health_check_map_t&& checks);
void get_health_checks(health_check_map_t *checks);
void update_progress_event(const std::string& evid,
const std::string& desc,
float progress,
bool add_to_ceph_s);
void complete_progress_event(const std::string& evid);
void clear_all_progress_events();
void get_progress_events(std::map<std::string,ProgressEvent>* events);
void register_client(std::string_view name, std::string addrs, bool replace);
void unregister_client(std::string_view name, std::string addrs);
void config_notify();
void set_uri(const std::string& module_name, const std::string &uri);
void set_device_wear_level(const std::string& devid, float wear_level);
int handle_command(
const ModuleCommand& module_command,
const MgrSession& session,
const cmdmap_t &cmdmap,
const bufferlist &inbuf,
std::stringstream *ds,
std::stringstream *ss);
std::map<std::string, std::string> get_services() const;
void update_kv_data(
const std::string prefix,
bool incremental,
const map<std::string, std::optional<bufferlist>, std::less<>>& data);
void _refresh_config_map();
// Public so that MonCommandCompletion can use it
// FIXME: for send_command completion notifications,
// send it to only the module that sent the command, not everyone
void notify_all(const std::string ¬ify_type,
const std::string ¬ify_id);
void notify_all(const LogEntry &log_entry);
auto& get_module_finisher(const std::string &name) {
return modules.at(name)->finisher;
}
bool is_pending(std::string_view name) const {
return pending_modules.count(name) > 0;
}
bool module_exists(const std::string &name) const
{
return modules.count(name) > 0;
}
bool method_exists(
const std::string &module_name,
const std::string &method_name) const
{
return modules.at(module_name)->method_exists(method_name);
}
PyObject *dispatch_remote(
const std::string &other_module,
const std::string &method,
PyObject *args,
PyObject *kwargs,
std::string *err);
int init();
void shutdown();
void start_one(PyModuleRef py_module);
void dump_server(const std::string &hostname,
const DaemonStateCollection &dmc,
Formatter *f);
void cluster_log(const std::string &channel, clog_type prio,
const std::string &message);
PyObject* get_daemon_health_metrics();
bool inject_python_on() const;
void update_cache_metrics();
};
| 7,526 | 31.029787 | 89 | h |
null | ceph-main/src/mgr/BaseMgrModule.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2016 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
/**
* The interface we present to python code that runs within
* ceph-mgr. This is implemented as a Python class from which
* all modules must inherit -- access to the Ceph state is then
* available as methods on that object.
*/
#include "Python.h"
#include "Mgr.h"
#include "mon/MonClient.h"
#include "common/errno.h"
#include "common/version.h"
#include "mgr/Types.h"
#include "PyUtil.h"
#include "BaseMgrModule.h"
#include "Gil.h"
#include <algorithm>
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_mgr
#define PLACEHOLDER ""
using std::list;
using std::string;
typedef struct {
PyObject_HEAD
ActivePyModules *py_modules;
ActivePyModule *this_module;
} BaseMgrModule;
class MonCommandCompletion : public Context
{
ActivePyModules *py_modules;
PyObject *python_completion;
const std::string tag;
SafeThreadState pThreadState;
public:
std::string outs;
bufferlist outbl;
MonCommandCompletion(
ActivePyModules *py_modules_, PyObject* ev,
const std::string &tag_, PyThreadState *ts_)
: py_modules(py_modules_), python_completion(ev),
tag(tag_), pThreadState(ts_)
{
ceph_assert(python_completion != nullptr);
Py_INCREF(python_completion);
}
~MonCommandCompletion() override
{
if (python_completion) {
// Usually do this in finish(): this path is only for if we're
// being destroyed without completing.
Gil gil(pThreadState, true);
Py_DECREF(python_completion);
python_completion = nullptr;
}
}
void finish(int r) override
{
ceph_assert(python_completion != nullptr);
dout(10) << "MonCommandCompletion::finish()" << dendl;
{
// Scoped so the Gil is released before calling notify_all()
// Create new thread state because this is called via the MonClient
// Finisher, not the PyModules finisher.
Gil gil(pThreadState, true);
auto set_fn = PyObject_GetAttrString(python_completion, "complete");
ceph_assert(set_fn != nullptr);
auto pyR = PyLong_FromLong(r);
auto pyOutBl = PyUnicode_FromString(outbl.to_str().c_str());
auto pyOutS = PyUnicode_FromString(outs.c_str());
auto args = PyTuple_Pack(3, pyR, pyOutBl, pyOutS);
Py_DECREF(pyR);
Py_DECREF(pyOutBl);
Py_DECREF(pyOutS);
auto rtn = PyObject_CallObject(set_fn, args);
if (rtn != nullptr) {
Py_DECREF(rtn);
}
Py_DECREF(args);
Py_DECREF(set_fn);
Py_DECREF(python_completion);
python_completion = nullptr;
}
py_modules->notify_all("command", tag);
}
};
static PyObject*
ceph_send_command(BaseMgrModule *self, PyObject *args)
{
// Like mon, osd, mds
char *type = nullptr;
// Like "23" for an OSD or "myid" for an MDS
char *name = nullptr;
char *cmd_json = nullptr;
char *tag = nullptr;
char *inbuf_ptr = nullptr;
Py_ssize_t inbuf_len = 0;
bufferlist inbuf = {};
PyObject *completion = nullptr;
if (!PyArg_ParseTuple(args, "Ossssz#:ceph_send_command",
&completion, &type, &name, &cmd_json, &tag, &inbuf_ptr, &inbuf_len)) {
return nullptr;
}
if (inbuf_ptr) {
inbuf.append(inbuf_ptr, (unsigned)inbuf_len);
}
auto set_fn = PyObject_GetAttrString(completion, "complete");
if (set_fn == nullptr) {
ceph_abort(); // TODO raise python exception instead
} else {
ceph_assert(PyCallable_Check(set_fn));
}
Py_DECREF(set_fn);
MonCommandCompletion *command_c = new MonCommandCompletion(self->py_modules,
completion, tag, PyThreadState_Get());
PyThreadState *tstate = PyEval_SaveThread();
if (std::string(type) == "mon") {
// Wait for the latest OSDMap after each command we send to
// the mons. This is a heavy-handed hack to make life simpler
// for python module authors, so that they know whenever they
// run a command they've gt a fresh OSDMap afterwards.
// TODO: enhance MCommand interface so that it returns
// latest cluster map versions on completion, and callers
// can wait for those.
auto c = new LambdaContext([command_c, self](int command_r){
self->py_modules->get_objecter().wait_for_latest_osdmap(
[command_c, command_r](boost::system::error_code) {
command_c->complete(command_r);
});
});
self->py_modules->get_monc().start_mon_command(
name,
{cmd_json},
inbuf,
&command_c->outbl,
&command_c->outs,
new C_OnFinisher(c, &self->py_modules->cmd_finisher));
} else if (std::string(type) == "osd") {
std::string err;
uint64_t osd_id = strict_strtoll(name, 10, &err);
if (!err.empty()) {
delete command_c;
string msg("invalid osd_id: ");
msg.append("\"").append(name).append("\"");
PyEval_RestoreThread(tstate);
PyErr_SetString(PyExc_ValueError, msg.c_str());
return nullptr;
}
ceph_tid_t tid;
self->py_modules->get_objecter().osd_command(
osd_id,
{cmd_json},
inbuf,
&tid,
[command_c, f = &self->py_modules->cmd_finisher]
(boost::system::error_code ec, std::string s, ceph::buffer::list bl) {
command_c->outs = std::move(s);
command_c->outbl = std::move(bl);
f->queue(command_c);
});
} else if (std::string(type) == "mds") {
int r = self->py_modules->get_client().mds_command(
name,
{cmd_json},
inbuf,
&command_c->outbl,
&command_c->outs,
new C_OnFinisher(command_c, &self->py_modules->cmd_finisher));
if (r != 0) {
string msg("failed to send command to mds: ");
msg.append(cpp_strerror(r));
PyEval_RestoreThread(tstate);
PyErr_SetString(PyExc_RuntimeError, msg.c_str());
return nullptr;
}
} else if (std::string(type) == "pg") {
pg_t pgid;
if (!pgid.parse(name)) {
delete command_c;
string msg("invalid pgid: ");
msg.append("\"").append(name).append("\"");
PyEval_RestoreThread(tstate);
PyErr_SetString(PyExc_ValueError, msg.c_str());
return nullptr;
}
ceph_tid_t tid;
self->py_modules->get_objecter().pg_command(
pgid,
{cmd_json},
inbuf,
&tid,
[command_c, f = &self->py_modules->cmd_finisher]
(boost::system::error_code ec, std::string s, ceph::buffer::list bl) {
command_c->outs = std::move(s);
command_c->outbl = std::move(bl);
f->queue(command_c);
});
PyEval_RestoreThread(tstate);
return nullptr;
} else {
delete command_c;
string msg("unknown service type: ");
msg.append(type);
PyEval_RestoreThread(tstate);
PyErr_SetString(PyExc_ValueError, msg.c_str());
return nullptr;
}
PyEval_RestoreThread(tstate);
Py_RETURN_NONE;
}
static PyObject*
ceph_set_health_checks(BaseMgrModule *self, PyObject *args)
{
PyObject *checks = NULL;
if (!PyArg_ParseTuple(args, "O:ceph_set_health_checks", &checks)) {
return NULL;
}
if (!PyDict_Check(checks)) {
derr << __func__ << " arg not a dict" << dendl;
Py_RETURN_NONE;
}
PyObject *checksls = PyDict_Items(checks);
health_check_map_t out_checks;
for (int i = 0; i < PyList_Size(checksls); ++i) {
PyObject *kv = PyList_GET_ITEM(checksls, i);
char *check_name = nullptr;
PyObject *check_info = nullptr;
if (!PyArg_ParseTuple(kv, "sO:pair", &check_name, &check_info)) {
derr << __func__ << " dict item " << i
<< " not a size 2 tuple" << dendl;
continue;
}
if (!PyDict_Check(check_info)) {
derr << __func__ << " item " << i << " " << check_name
<< " value not a dict" << dendl;
continue;
}
health_status_t severity = HEALTH_OK;
string summary;
list<string> detail;
int64_t count = 0;
PyObject *infols = PyDict_Items(check_info);
for (int j = 0; j < PyList_Size(infols); ++j) {
PyObject *pair = PyList_GET_ITEM(infols, j);
if (!PyTuple_Check(pair)) {
derr << __func__ << " item " << i << " pair " << j
<< " not a tuple" << dendl;
continue;
}
char *k = nullptr;
PyObject *v = nullptr;
if (!PyArg_ParseTuple(pair, "sO:pair", &k, &v)) {
derr << __func__ << " item " << i << " pair " << j
<< " not a size 2 tuple" << dendl;
continue;
}
string ks(k);
if (ks == "severity") {
if (!PyUnicode_Check(v)) {
derr << __func__ << " check " << check_name
<< " severity value not string" << dendl;
continue;
}
if (const string vs = PyUnicode_AsUTF8(v); vs == "warning") {
severity = HEALTH_WARN;
} else if (vs == "error") {
severity = HEALTH_ERR;
}
} else if (ks == "summary") {
if (!PyUnicode_Check(v)) {
derr << __func__ << " check " << check_name
<< " summary value not [unicode] string" << dendl;
continue;
} else {
summary = PyUnicode_AsUTF8(v);
}
} else if (ks == "count") {
if (PyLong_Check(v)) {
count = PyLong_AsLong(v);
} else {
derr << __func__ << " check " << check_name
<< " count value not int" << dendl;
continue;
}
} else if (ks == "detail") {
if (!PyList_Check(v)) {
derr << __func__ << " check " << check_name
<< " detail value not list" << dendl;
continue;
}
for (int k = 0; k < PyList_Size(v); ++k) {
PyObject *di = PyList_GET_ITEM(v, k);
if (!PyUnicode_Check(di)) {
derr << __func__ << " check " << check_name
<< " detail item " << k << " not a [unicode] string" << dendl;
continue;
} else {
detail.push_back(PyUnicode_AsUTF8(di));
}
}
} else {
derr << __func__ << " check " << check_name
<< " unexpected key " << k << dendl;
}
}
auto& d = out_checks.add(check_name, severity, summary, count);
d.detail.swap(detail);
}
JSONFormatter jf(true);
dout(10) << "module " << self->this_module->get_name()
<< " health checks:\n";
out_checks.dump(&jf);
jf.flush(*_dout);
*_dout << dendl;
without_gil([&] {
self->py_modules->set_health_checks(self->this_module->get_name(),
std::move(out_checks));
});
Py_RETURN_NONE;
}
static PyObject*
ceph_state_get(BaseMgrModule *self, PyObject *args)
{
char *what = NULL;
if (!PyArg_ParseTuple(args, "s:ceph_state_get", &what)) {
return NULL;
}
return self->py_modules->cacheable_get_python(what);
}
static PyObject*
ceph_get_server(BaseMgrModule *self, PyObject *args)
{
char *hostname = NULL;
if (!PyArg_ParseTuple(args, "z:ceph_get_server", &hostname)) {
return NULL;
}
if (hostname) {
return self->py_modules->get_server_python(hostname);
} else {
return self->py_modules->list_servers_python();
}
}
static PyObject*
ceph_get_mgr_id(BaseMgrModule *self, PyObject *args)
{
return PyUnicode_FromString(g_conf()->name.get_id().c_str());
}
static PyObject*
ceph_option_get(BaseMgrModule *self, PyObject *args)
{
char *what = nullptr;
if (!PyArg_ParseTuple(args, "s:ceph_option_get", &what)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
const Option *opt = g_conf().find_option(string(what));
if (opt) {
std::string value;
switch (int r = g_conf().get_val(string(what), &value); r) {
case -ENOMEM:
PyErr_NoMemory();
return nullptr;
case -ENAMETOOLONG:
PyErr_SetString(PyExc_ValueError, "value too long");
return nullptr;
default:
ceph_assert(r == 0);
break;
}
dout(10) << "ceph_option_get " << what << " found: " << value << dendl;
return get_python_typed_option_value(opt->type, value);
} else {
dout(4) << "ceph_option_get " << what << " not found " << dendl;
PyErr_Format(PyExc_KeyError, "option not found: %s", what);
return nullptr;
}
}
static PyObject*
ceph_foreign_option_get(BaseMgrModule *self, PyObject *args)
{
char *who = nullptr;
char *what = nullptr;
if (!PyArg_ParseTuple(args, "ss:ceph_foreign_option_get", &who, &what)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
return self->py_modules->get_foreign_config(who, what);
}
static PyObject*
ceph_get_module_option(BaseMgrModule *self, PyObject *args)
{
char *module = nullptr;
char *key = nullptr;
char *prefix = nullptr;
if (!PyArg_ParseTuple(args, "ss|s:ceph_get_module_option", &module, &key,
&prefix)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
std::string str_prefix;
if (prefix) {
str_prefix = prefix;
}
assert(self->this_module->py_module);
auto pResult = self->py_modules->get_typed_config(module, key, str_prefix);
return pResult;
}
static PyObject*
ceph_store_get_prefix(BaseMgrModule *self, PyObject *args)
{
char *prefix = nullptr;
if (!PyArg_ParseTuple(args, "s:ceph_store_get_prefix", &prefix)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
return self->py_modules->get_store_prefix(self->this_module->get_name(),
prefix);
}
static PyObject*
ceph_set_module_option(BaseMgrModule *self, PyObject *args)
{
char *module = nullptr;
char *key = nullptr;
char *value = nullptr;
if (!PyArg_ParseTuple(args, "ssz:ceph_set_module_option",
&module, &key, &value)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
std::optional<string> val;
if (value) {
val = value;
}
auto [ret, msg] = without_gil([&] {
return self->py_modules->set_config(module, key, val);
});
if (ret) {
PyErr_SetString(PyExc_ValueError, msg.c_str());
return nullptr;
}
Py_RETURN_NONE;
}
static PyObject*
ceph_store_get(BaseMgrModule *self, PyObject *args)
{
char *what = nullptr;
if (!PyArg_ParseTuple(args, "s:ceph_store_get", &what)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
std::string value;
bool found = self->py_modules->get_store(self->this_module->get_name(),
what, &value);
if (found) {
dout(10) << "ceph_store_get " << what << " found: " << value.c_str() << dendl;
return PyUnicode_FromString(value.c_str());
} else {
dout(4) << "ceph_store_get " << what << " not found " << dendl;
Py_RETURN_NONE;
}
}
static PyObject*
ceph_store_set(BaseMgrModule *self, PyObject *args)
{
char *key = nullptr;
char *value = nullptr;
if (!PyArg_ParseTuple(args, "sz:ceph_store_set", &key, &value)) {
return nullptr;
}
std::optional<string> val;
if (value) {
val = value;
}
without_gil([&] {
self->py_modules->set_store(self->this_module->get_name(), key, val);
});
Py_RETURN_NONE;
}
static PyObject*
get_metadata(BaseMgrModule *self, PyObject *args)
{
char *svc_name = NULL;
char *svc_id = NULL;
if (!PyArg_ParseTuple(args, "ss:get_metadata", &svc_name, &svc_id)) {
return nullptr;
}
return self->py_modules->get_metadata_python(svc_name, svc_id);
}
static PyObject*
get_daemon_status(BaseMgrModule *self, PyObject *args)
{
char *svc_name = NULL;
char *svc_id = NULL;
if (!PyArg_ParseTuple(args, "ss:get_daemon_status", &svc_name,
&svc_id)) {
return nullptr;
}
return self->py_modules->get_daemon_status_python(svc_name, svc_id);
}
static PyObject*
ceph_log(BaseMgrModule *self, PyObject *args)
{
char *record = nullptr;
if (!PyArg_ParseTuple(args, "s:log", &record)) {
return nullptr;
}
ceph_assert(self->this_module);
self->this_module->log(record);
Py_RETURN_NONE;
}
static PyObject*
ceph_cluster_log(BaseMgrModule *self, PyObject *args)
{
int prio = 0;
char *channel = nullptr;
char *message = nullptr;
if (!PyArg_ParseTuple(args, "sis:ceph_cluster_log", &channel, &prio, &message)) {
return nullptr;
}
without_gil([&] {
self->py_modules->cluster_log(channel, (clog_type)prio, message);
});
Py_RETURN_NONE;
}
static PyObject *
ceph_get_version(BaseMgrModule *self, PyObject *args)
{
return PyUnicode_FromString(pretty_version_to_str().c_str());
}
static PyObject *
ceph_get_ceph_conf_path(BaseMgrModule *self, PyObject *args)
{
return PyUnicode_FromString(g_conf().get_conf_path().c_str());
}
static PyObject *
ceph_get_release_name(BaseMgrModule *self, PyObject *args)
{
return PyUnicode_FromString(ceph_release_to_str());
}
static PyObject *
ceph_lookup_release_name(BaseMgrModule *self, PyObject *args)
{
int major = 0;
if (!PyArg_ParseTuple(args, "i:ceph_lookup_release_name", &major)) {
return nullptr;
}
return PyUnicode_FromString(ceph_release_name(major));
}
static PyObject *
ceph_get_context(BaseMgrModule *self)
{
return self->py_modules->get_context();
}
static PyObject*
get_counter(BaseMgrModule *self, PyObject *args)
{
char *svc_name = nullptr;
char *svc_id = nullptr;
char *counter_path = nullptr;
if (!PyArg_ParseTuple(args, "sss:get_counter", &svc_name,
&svc_id, &counter_path)) {
return nullptr;
}
return self->py_modules->get_counter_python(
svc_name, svc_id, counter_path);
}
static PyObject*
get_latest_counter(BaseMgrModule *self, PyObject *args)
{
char *svc_name = nullptr;
char *svc_id = nullptr;
char *counter_path = nullptr;
if (!PyArg_ParseTuple(args, "sss:get_counter", &svc_name,
&svc_id, &counter_path)) {
return nullptr;
}
return self->py_modules->get_latest_counter_python(
svc_name, svc_id, counter_path);
}
static PyObject*
get_perf_schema(BaseMgrModule *self, PyObject *args)
{
char *type_str = nullptr;
char *svc_id = nullptr;
if (!PyArg_ParseTuple(args, "ss:get_perf_schema", &type_str,
&svc_id)) {
return nullptr;
}
return self->py_modules->get_perf_schema_python(type_str, svc_id);
}
static PyObject*
ceph_get_rocksdb_version(BaseMgrModule *self)
{
return self->py_modules->get_rocksdb_version();
}
static PyObject *
ceph_get_osdmap(BaseMgrModule *self, PyObject *args)
{
return self->py_modules->get_osdmap();
}
static PyObject*
ceph_set_uri(BaseMgrModule *self, PyObject *args)
{
char *svc_str = nullptr;
if (!PyArg_ParseTuple(args, "s:ceph_advertize_service",
&svc_str)) {
return nullptr;
}
// We call down into PyModules even though we have a MgrPyModule
// reference here, because MgrPyModule's fields are protected
// by PyModules' lock.
without_gil([&] {
self->py_modules->set_uri(self->this_module->get_name(), svc_str);
});
Py_RETURN_NONE;
}
static PyObject*
ceph_set_wear_level(BaseMgrModule *self, PyObject *args)
{
char *devid = nullptr;
float wear_level;
if (!PyArg_ParseTuple(args, "sf:ceph_set_wear_level",
&devid, &wear_level)) {
return nullptr;
}
without_gil([&] {
self->py_modules->set_device_wear_level(devid, wear_level);
});
Py_RETURN_NONE;
}
static PyObject*
ceph_have_mon_connection(BaseMgrModule *self, PyObject *args)
{
if (self->py_modules->get_monc().is_connected()) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
}
static PyObject*
ceph_update_progress_event(BaseMgrModule *self, PyObject *args)
{
char *evid = nullptr;
char *desc = nullptr;
float progress = 0.0;
bool add_to_ceph_s = false;
if (!PyArg_ParseTuple(args, "ssfb:ceph_update_progress_event",
&evid, &desc, &progress, &add_to_ceph_s)) {
return nullptr;
}
without_gil([&] {
self->py_modules->update_progress_event(evid, desc, progress, add_to_ceph_s);
});
Py_RETURN_NONE;
}
static PyObject*
ceph_complete_progress_event(BaseMgrModule *self, PyObject *args)
{
char *evid = nullptr;
if (!PyArg_ParseTuple(args, "s:ceph_complete_progress_event",
&evid)) {
return nullptr;
}
without_gil([&] {
self->py_modules->complete_progress_event(evid);
});
Py_RETURN_NONE;
}
static PyObject*
ceph_clear_all_progress_events(BaseMgrModule *self, PyObject *args)
{
without_gil([&] {
self->py_modules->clear_all_progress_events();
});
Py_RETURN_NONE;
}
static PyObject *
ceph_dispatch_remote(BaseMgrModule *self, PyObject *args)
{
char *other_module = nullptr;
char *method = nullptr;
PyObject *remote_args = nullptr;
PyObject *remote_kwargs = nullptr;
if (!PyArg_ParseTuple(args, "ssOO:ceph_dispatch_remote",
&other_module, &method, &remote_args, &remote_kwargs)) {
return nullptr;
}
// Early error handling, because if the module doesn't exist then we
// won't be able to use its thread state to set python error state
// inside dispatch_remote().
if (!self->py_modules->module_exists(other_module)) {
derr << "no module '" << other_module << "'" << dendl;
PyErr_SetString(PyExc_ImportError, "Module not found");
return nullptr;
}
// Drop GIL from calling python thread state, it will be taken
// both for checking for method existence and for executing method.
PyThreadState *tstate = PyEval_SaveThread();
if (!self->py_modules->method_exists(other_module, method)) {
PyEval_RestoreThread(tstate);
PyErr_SetString(PyExc_NameError, "Method not found");
return nullptr;
}
std::string err;
auto result = self->py_modules->dispatch_remote(other_module, method,
remote_args, remote_kwargs, &err);
PyEval_RestoreThread(tstate);
if (result == nullptr) {
std::stringstream ss;
ss << "Remote method threw exception: " << err;
PyErr_SetString(PyExc_RuntimeError, ss.str().c_str());
derr << ss.str() << dendl;
}
return result;
}
static PyObject*
ceph_add_osd_perf_query(BaseMgrModule *self, PyObject *args)
{
static const std::string NAME_KEY_DESCRIPTOR = "key_descriptor";
static const std::string NAME_COUNTERS_DESCRIPTORS =
"performance_counter_descriptors";
static const std::string NAME_LIMIT = "limit";
static const std::string NAME_SUB_KEY_TYPE = "type";
static const std::string NAME_SUB_KEY_REGEX = "regex";
static const std::string NAME_LIMIT_ORDER_BY = "order_by";
static const std::string NAME_LIMIT_MAX_COUNT = "max_count";
static const std::map<std::string, OSDPerfMetricSubKeyType> sub_key_types = {
{"client_id", OSDPerfMetricSubKeyType::CLIENT_ID},
{"client_address", OSDPerfMetricSubKeyType::CLIENT_ADDRESS},
{"pool_id", OSDPerfMetricSubKeyType::POOL_ID},
{"namespace", OSDPerfMetricSubKeyType::NAMESPACE},
{"osd_id", OSDPerfMetricSubKeyType::OSD_ID},
{"pg_id", OSDPerfMetricSubKeyType::PG_ID},
{"object_name", OSDPerfMetricSubKeyType::OBJECT_NAME},
{"snap_id", OSDPerfMetricSubKeyType::SNAP_ID},
};
static const std::map<std::string, PerformanceCounterType> counter_types = {
{"ops", PerformanceCounterType::OPS},
{"write_ops", PerformanceCounterType::WRITE_OPS},
{"read_ops", PerformanceCounterType::READ_OPS},
{"bytes", PerformanceCounterType::BYTES},
{"write_bytes", PerformanceCounterType::WRITE_BYTES},
{"read_bytes", PerformanceCounterType::READ_BYTES},
{"latency", PerformanceCounterType::LATENCY},
{"write_latency", PerformanceCounterType::WRITE_LATENCY},
{"read_latency", PerformanceCounterType::READ_LATENCY},
};
PyObject *py_query = nullptr;
if (!PyArg_ParseTuple(args, "O:ceph_add_osd_perf_query", &py_query)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
if (!PyDict_Check(py_query)) {
derr << __func__ << " arg not a dict" << dendl;
Py_RETURN_NONE;
}
PyObject *query_params = PyDict_Items(py_query);
OSDPerfMetricQuery query;
std::optional<OSDPerfMetricLimit> limit;
// {
// 'key_descriptor': [
// {'type': subkey_type, 'regex': regex_pattern},
// ...
// ],
// 'performance_counter_descriptors': [
// list, of, descriptor, types
// ],
// 'limit': {'order_by': performance_counter_type, 'max_count': n},
// }
for (int i = 0; i < PyList_Size(query_params); ++i) {
PyObject *kv = PyList_GET_ITEM(query_params, i);
char *query_param_name = nullptr;
PyObject *query_param_val = nullptr;
if (!PyArg_ParseTuple(kv, "sO:pair", &query_param_name, &query_param_val)) {
derr << __func__ << " dict item " << i << " not a size 2 tuple" << dendl;
Py_RETURN_NONE;
}
if (query_param_name == NAME_KEY_DESCRIPTOR) {
if (!PyList_Check(query_param_val)) {
derr << __func__ << " " << query_param_name << " not a list" << dendl;
Py_RETURN_NONE;
}
for (int j = 0; j < PyList_Size(query_param_val); j++) {
PyObject *sub_key = PyList_GET_ITEM(query_param_val, j);
if (!PyDict_Check(sub_key)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " not a dict" << dendl;
Py_RETURN_NONE;
}
OSDPerfMetricSubKeyDescriptor d;
PyObject *sub_key_params = PyDict_Items(sub_key);
for (int k = 0; k < PyList_Size(sub_key_params); ++k) {
PyObject *pair = PyList_GET_ITEM(sub_key_params, k);
if (!PyTuple_Check(pair)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " pair " << k << " not a tuple" << dendl;
Py_RETURN_NONE;
}
char *param_name = nullptr;
PyObject *param_value = nullptr;
if (!PyArg_ParseTuple(pair, "sO:pair", ¶m_name, ¶m_value)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " pair " << k << " not a size 2 tuple" << dendl;
Py_RETURN_NONE;
}
if (param_name == NAME_SUB_KEY_TYPE) {
if (!PyUnicode_Check(param_value)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " contains invalid param " << param_name << dendl;
Py_RETURN_NONE;
}
auto type = PyUnicode_AsUTF8(param_value);
auto it = sub_key_types.find(type);
if (it == sub_key_types.end()) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " contains invalid type " << dendl;
Py_RETURN_NONE;
}
d.type = it->second;
} else if (param_name == NAME_SUB_KEY_REGEX) {
if (!PyUnicode_Check(param_value)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " contains invalid param " << param_name << dendl;
Py_RETURN_NONE;
}
d.regex_str = PyUnicode_AsUTF8(param_value);
try {
d.regex = d.regex_str.c_str();
} catch (const std::regex_error& e) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " contains invalid regex " << d.regex_str << dendl;
Py_RETURN_NONE;
}
if (d.regex.mark_count() == 0) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " regex " << d.regex_str << ": no capturing groups"
<< dendl;
Py_RETURN_NONE;
}
} else {
derr << __func__ << " query " << query_param_name << " item " << j
<< " contains invalid param " << param_name << dendl;
Py_RETURN_NONE;
}
}
if (d.type == static_cast<OSDPerfMetricSubKeyType>(-1) ||
d.regex_str.empty()) {
derr << __func__ << " query " << query_param_name << " item " << i
<< " invalid" << dendl;
Py_RETURN_NONE;
}
query.key_descriptor.push_back(d);
}
} else if (query_param_name == NAME_COUNTERS_DESCRIPTORS) {
if (!PyList_Check(query_param_val)) {
derr << __func__ << " " << query_param_name << " not a list" << dendl;
Py_RETURN_NONE;
}
for (int j = 0; j < PyList_Size(query_param_val); j++) {
PyObject *py_type = PyList_GET_ITEM(query_param_val, j);
if (!PyUnicode_Check(py_type)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " not a string" << dendl;
Py_RETURN_NONE;
}
auto type = PyUnicode_AsUTF8(py_type);
auto it = counter_types.find(type);
if (it == counter_types.end()) {
derr << __func__ << " query " << query_param_name << " item " << type
<< " is not valid type" << dendl;
Py_RETURN_NONE;
}
query.performance_counter_descriptors.push_back(it->second);
}
} else if (query_param_name == NAME_LIMIT) {
if (!PyDict_Check(query_param_val)) {
derr << __func__ << " query " << query_param_name << " not a dict"
<< dendl;
Py_RETURN_NONE;
}
limit = OSDPerfMetricLimit();
PyObject *limit_params = PyDict_Items(query_param_val);
for (int j = 0; j < PyList_Size(limit_params); ++j) {
PyObject *kv = PyList_GET_ITEM(limit_params, j);
char *limit_param_name = nullptr;
PyObject *limit_param_val = nullptr;
if (!PyArg_ParseTuple(kv, "sO:pair", &limit_param_name,
&limit_param_val)) {
derr << __func__ << " limit item " << j << " not a size 2 tuple"
<< dendl;
Py_RETURN_NONE;
}
if (limit_param_name == NAME_LIMIT_ORDER_BY) {
if (!PyUnicode_Check(limit_param_val)) {
derr << __func__ << " " << limit_param_name << " not a string"
<< dendl;
Py_RETURN_NONE;
}
auto order_by = PyUnicode_AsUTF8(limit_param_val);
auto it = counter_types.find(order_by);
if (it == counter_types.end()) {
derr << __func__ << " limit " << limit_param_name
<< " not a valid counter type" << dendl;
Py_RETURN_NONE;
}
limit->order_by = it->second;
} else if (limit_param_name == NAME_LIMIT_MAX_COUNT) {
if (!PyLong_Check(limit_param_val)) {
derr << __func__ << " " << limit_param_name << " not an int"
<< dendl;
Py_RETURN_NONE;
}
limit->max_count = PyLong_AsLong(limit_param_val);
} else {
derr << __func__ << " unknown limit param: " << limit_param_name
<< dendl;
Py_RETURN_NONE;
}
}
} else {
derr << __func__ << " unknown query param: " << query_param_name << dendl;
Py_RETURN_NONE;
}
}
if (query.key_descriptor.empty() ||
query.performance_counter_descriptors.empty()) {
derr << __func__ << " invalid query" << dendl;
Py_RETURN_NONE;
}
if (limit) {
auto &ds = query.performance_counter_descriptors;
if (std::find(ds.begin(), ds.end(), limit->order_by) == ds.end()) {
derr << __func__ << " limit order_by " << limit->order_by
<< " not in performance_counter_descriptors" << dendl;
Py_RETURN_NONE;
}
}
auto query_id = self->py_modules->add_osd_perf_query(query, limit);
return PyLong_FromLong(query_id);
}
static PyObject*
ceph_remove_osd_perf_query(BaseMgrModule *self, PyObject *args)
{
MetricQueryID query_id;
if (!PyArg_ParseTuple(args, "i:ceph_remove_osd_perf_query", &query_id)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
self->py_modules->remove_osd_perf_query(query_id);
Py_RETURN_NONE;
}
static PyObject*
ceph_get_osd_perf_counters(BaseMgrModule *self, PyObject *args)
{
MetricQueryID query_id;
if (!PyArg_ParseTuple(args, "i:ceph_get_osd_perf_counters", &query_id)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
return self->py_modules->get_osd_perf_counters(query_id);
}
// MDS perf query interface -- mostly follows ceph_add_osd_perf_query()
// style
static PyObject*
ceph_add_mds_perf_query(BaseMgrModule *self, PyObject *args)
{
static const std::string NAME_KEY_DESCRIPTOR = "key_descriptor";
static const std::string NAME_COUNTERS_DESCRIPTORS =
"performance_counter_descriptors";
static const std::string NAME_LIMIT = "limit";
static const std::string NAME_SUB_KEY_TYPE = "type";
static const std::string NAME_SUB_KEY_REGEX = "regex";
static const std::string NAME_LIMIT_ORDER_BY = "order_by";
static const std::string NAME_LIMIT_MAX_COUNT = "max_count";
static const std::map<std::string, MDSPerfMetricSubKeyType> sub_key_types = {
{"mds_rank", MDSPerfMetricSubKeyType::MDS_RANK},
{"client_id", MDSPerfMetricSubKeyType::CLIENT_ID},
};
static const std::map<std::string, MDSPerformanceCounterType> counter_types = {
{"cap_hit", MDSPerformanceCounterType::CAP_HIT_METRIC},
{"read_latency", MDSPerformanceCounterType::READ_LATENCY_METRIC},
{"write_latency", MDSPerformanceCounterType::WRITE_LATENCY_METRIC},
{"metadata_latency", MDSPerformanceCounterType::METADATA_LATENCY_METRIC},
{"dentry_lease", MDSPerformanceCounterType::DENTRY_LEASE_METRIC},
{"opened_files", MDSPerformanceCounterType::OPENED_FILES_METRIC},
{"pinned_icaps", MDSPerformanceCounterType::PINNED_ICAPS_METRIC},
{"opened_inodes", MDSPerformanceCounterType::OPENED_INODES_METRIC},
{"read_io_sizes", MDSPerformanceCounterType::READ_IO_SIZES_METRIC},
{"write_io_sizes", MDSPerformanceCounterType::WRITE_IO_SIZES_METRIC},
{"avg_read_latency", MDSPerformanceCounterType::AVG_READ_LATENCY_METRIC},
{"stdev_read_latency", MDSPerformanceCounterType::STDEV_READ_LATENCY_METRIC},
{"avg_write_latency", MDSPerformanceCounterType::AVG_WRITE_LATENCY_METRIC},
{"stdev_write_latency", MDSPerformanceCounterType::STDEV_WRITE_LATENCY_METRIC},
{"avg_metadata_latency", MDSPerformanceCounterType::AVG_METADATA_LATENCY_METRIC},
{"stdev_metadata_latency", MDSPerformanceCounterType::STDEV_METADATA_LATENCY_METRIC},
};
PyObject *py_query = nullptr;
if (!PyArg_ParseTuple(args, "O:ceph_add_mds_perf_query", &py_query)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
if (!PyDict_Check(py_query)) {
derr << __func__ << " arg not a dict" << dendl;
Py_RETURN_NONE;
}
PyObject *query_params = PyDict_Items(py_query);
MDSPerfMetricQuery query;
std::optional<MDSPerfMetricLimit> limit;
// {
// 'key_descriptor': [
// {'type': subkey_type, 'regex': regex_pattern},
// ...
// ],
// 'performance_counter_descriptors': [
// list, of, descriptor, types
// ],
// 'limit': {'order_by': performance_counter_type, 'max_count': n},
// }
for (int i = 0; i < PyList_Size(query_params); ++i) {
PyObject *kv = PyList_GET_ITEM(query_params, i);
char *query_param_name = nullptr;
PyObject *query_param_val = nullptr;
if (!PyArg_ParseTuple(kv, "sO:pair", &query_param_name, &query_param_val)) {
derr << __func__ << " dict item " << i << " not a size 2 tuple" << dendl;
Py_RETURN_NONE;
}
if (query_param_name == NAME_KEY_DESCRIPTOR) {
if (!PyList_Check(query_param_val)) {
derr << __func__ << " " << query_param_name << " not a list" << dendl;
Py_RETURN_NONE;
}
for (int j = 0; j < PyList_Size(query_param_val); j++) {
PyObject *sub_key = PyList_GET_ITEM(query_param_val, j);
if (!PyDict_Check(sub_key)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " not a dict" << dendl;
Py_RETURN_NONE;
}
MDSPerfMetricSubKeyDescriptor d;
PyObject *sub_key_params = PyDict_Items(sub_key);
for (int k = 0; k < PyList_Size(sub_key_params); ++k) {
PyObject *pair = PyList_GET_ITEM(sub_key_params, k);
if (!PyTuple_Check(pair)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " pair " << k << " not a tuple" << dendl;
Py_RETURN_NONE;
}
char *param_name = nullptr;
PyObject *param_value = nullptr;
if (!PyArg_ParseTuple(pair, "sO:pair", ¶m_name, ¶m_value)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " pair " << k << " not a size 2 tuple" << dendl;
Py_RETURN_NONE;
}
if (param_name == NAME_SUB_KEY_TYPE) {
if (!PyUnicode_Check(param_value)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " contains invalid param " << param_name << dendl;
Py_RETURN_NONE;
}
auto type = PyUnicode_AsUTF8(param_value);
auto it = sub_key_types.find(type);
if (it == sub_key_types.end()) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " contains invalid type " << dendl;
Py_RETURN_NONE;
}
d.type = it->second;
} else if (param_name == NAME_SUB_KEY_REGEX) {
if (!PyUnicode_Check(param_value)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " contains invalid param " << param_name << dendl;
Py_RETURN_NONE;
}
d.regex_str = PyUnicode_AsUTF8(param_value);
try {
d.regex = d.regex_str.c_str();
} catch (const std::regex_error& e) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " contains invalid regex " << d.regex_str << dendl;
Py_RETURN_NONE;
}
if (d.regex.mark_count() == 0) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " regex " << d.regex_str << ": no capturing groups"
<< dendl;
Py_RETURN_NONE;
}
} else {
derr << __func__ << " query " << query_param_name << " item " << j
<< " contains invalid param " << param_name << dendl;
Py_RETURN_NONE;
}
}
if (d.type == static_cast<MDSPerfMetricSubKeyType>(-1) ||
d.regex_str.empty()) {
derr << __func__ << " query " << query_param_name << " item " << i
<< " invalid" << dendl;
Py_RETURN_NONE;
}
query.key_descriptor.push_back(d);
}
} else if (query_param_name == NAME_COUNTERS_DESCRIPTORS) {
if (!PyList_Check(query_param_val)) {
derr << __func__ << " " << query_param_name << " not a list" << dendl;
Py_RETURN_NONE;
}
for (int j = 0; j < PyList_Size(query_param_val); j++) {
PyObject *py_type = PyList_GET_ITEM(query_param_val, j);
if (!PyUnicode_Check(py_type)) {
derr << __func__ << " query " << query_param_name << " item " << j
<< " not a string" << dendl;
Py_RETURN_NONE;
}
auto type = PyUnicode_AsUTF8(py_type);
auto it = counter_types.find(type);
if (it == counter_types.end()) {
derr << __func__ << " query " << query_param_name << " item " << type
<< " is not valid type" << dendl;
Py_RETURN_NONE;
}
query.performance_counter_descriptors.push_back(it->second);
}
} else if (query_param_name == NAME_LIMIT) {
if (!PyDict_Check(query_param_val)) {
derr << __func__ << " query " << query_param_name << " not a dict"
<< dendl;
Py_RETURN_NONE;
}
limit = MDSPerfMetricLimit();
PyObject *limit_params = PyDict_Items(query_param_val);
for (int j = 0; j < PyList_Size(limit_params); ++j) {
PyObject *kv = PyList_GET_ITEM(limit_params, j);
char *limit_param_name = nullptr;
PyObject *limit_param_val = nullptr;
if (!PyArg_ParseTuple(kv, "sO:pair", &limit_param_name,
&limit_param_val)) {
derr << __func__ << " limit item " << j << " not a size 2 tuple"
<< dendl;
Py_RETURN_NONE;
}
if (limit_param_name == NAME_LIMIT_ORDER_BY) {
if (!PyUnicode_Check(limit_param_val)) {
derr << __func__ << " " << limit_param_name << " not a string"
<< dendl;
Py_RETURN_NONE;
}
auto order_by = PyUnicode_AsUTF8(limit_param_val);
auto it = counter_types.find(order_by);
if (it == counter_types.end()) {
derr << __func__ << " limit " << limit_param_name
<< " not a valid counter type" << dendl;
Py_RETURN_NONE;
}
limit->order_by = it->second;
} else if (limit_param_name == NAME_LIMIT_MAX_COUNT) {
if (!PyLong_Check(limit_param_val)) {
derr << __func__ << " " << limit_param_name << " not an int"
<< dendl;
Py_RETURN_NONE;
}
limit->max_count = PyLong_AsLong(limit_param_val);
} else {
derr << __func__ << " unknown limit param: " << limit_param_name
<< dendl;
Py_RETURN_NONE;
}
}
} else {
derr << __func__ << " unknown query param: " << query_param_name << dendl;
Py_RETURN_NONE;
}
}
if (query.key_descriptor.empty()) {
derr << __func__ << " invalid query" << dendl;
Py_RETURN_NONE;
}
if (limit) {
auto &ds = query.performance_counter_descriptors;
if (std::find(ds.begin(), ds.end(), limit->order_by) == ds.end()) {
derr << __func__ << " limit order_by " << limit->order_by
<< " not in performance_counter_descriptors" << dendl;
Py_RETURN_NONE;
}
}
auto query_id = self->py_modules->add_mds_perf_query(query, limit);
return PyLong_FromLong(query_id);
}
static PyObject*
ceph_remove_mds_perf_query(BaseMgrModule *self, PyObject *args)
{
MetricQueryID query_id;
if (!PyArg_ParseTuple(args, "i:ceph_remove_mds_perf_query", &query_id)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
self->py_modules->remove_mds_perf_query(query_id);
Py_RETURN_NONE;
}
static PyObject*
ceph_reregister_mds_perf_queries(BaseMgrModule *self, PyObject *args)
{
self->py_modules->reregister_mds_perf_queries();
Py_RETURN_NONE;
}
static PyObject*
ceph_get_mds_perf_counters(BaseMgrModule *self, PyObject *args)
{
MetricQueryID query_id;
if (!PyArg_ParseTuple(args, "i:ceph_get_mds_perf_counters", &query_id)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
return self->py_modules->get_mds_perf_counters(query_id);
}
static PyObject*
ceph_is_authorized(BaseMgrModule *self, PyObject *args)
{
PyObject *args_dict = NULL;
if (!PyArg_ParseTuple(args, "O:ceph_is_authorized", &args_dict)) {
return nullptr;
}
if (!PyDict_Check(args_dict)) {
derr << __func__ << " arg not a dict" << dendl;
Py_RETURN_FALSE;
}
std::map<std::string, std::string> arguments;
PyObject *args_list = PyDict_Items(args_dict);
for (int i = 0; i < PyList_Size(args_list); ++i) {
PyObject *kv = PyList_GET_ITEM(args_list, i);
char *arg_key = nullptr;
char *arg_value = nullptr;
if (!PyArg_ParseTuple(kv, "ss:pair", &arg_key, &arg_value)) {
derr << __func__ << " dict item " << i << " not a size 2 tuple" << dendl;
continue;
}
arguments[arg_key] = arg_value;
}
bool r = without_gil([&] {
return self->this_module->is_authorized(arguments);
});
if (r) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyObject*
ceph_register_client(BaseMgrModule *self, PyObject *args)
{
const char* _name = nullptr;
char* addrs = nullptr;
int replace = 0;
if (!PyArg_ParseTuple(args, "zsp:ceph_register_client", &_name, &addrs, &replace)) {
return nullptr;
}
auto name = _name ? std::string(_name) : std::string(self->this_module->get_name());
without_gil([&] {
self->py_modules->register_client(name, addrs, replace);
});
Py_RETURN_NONE;
}
static PyObject*
ceph_unregister_client(BaseMgrModule *self, PyObject *args)
{
const char* _name = nullptr;
char* addrs = nullptr;
if (!PyArg_ParseTuple(args, "zs:ceph_unregister_client", &_name, &addrs)) {
return nullptr;
}
auto name = _name ? std::string(_name) : std::string(self->this_module->get_name());
without_gil([&] {
self->py_modules->unregister_client(name, addrs);
});
Py_RETURN_NONE;
}
static PyObject*
ceph_get_daemon_health_metrics(BaseMgrModule *self, PyObject *args)
{
return self->py_modules->get_daemon_health_metrics();
}
PyMethodDef BaseMgrModule_methods[] = {
{"_ceph_get", (PyCFunction)ceph_state_get, METH_VARARGS,
"Get a cluster object"},
{"_ceph_get_server", (PyCFunction)ceph_get_server, METH_VARARGS,
"Get a server object"},
{"_ceph_get_metadata", (PyCFunction)get_metadata, METH_VARARGS,
"Get a service's metadata"},
{"_ceph_get_daemon_status", (PyCFunction)get_daemon_status, METH_VARARGS,
"Get a service's status"},
{"_ceph_send_command", (PyCFunction)ceph_send_command, METH_VARARGS,
"Send a mon command"},
{"_ceph_set_health_checks", (PyCFunction)ceph_set_health_checks, METH_VARARGS,
"Set health checks for this module"},
{"_ceph_get_mgr_id", (PyCFunction)ceph_get_mgr_id, METH_NOARGS,
"Get the name of the Mgr daemon where we are running"},
{"_ceph_get_ceph_conf_path", (PyCFunction)ceph_get_ceph_conf_path, METH_NOARGS,
"Get path to ceph.conf"},
{"_ceph_get_option", (PyCFunction)ceph_option_get, METH_VARARGS,
"Get a native configuration option value"},
{"_ceph_get_foreign_option", (PyCFunction)ceph_foreign_option_get, METH_VARARGS,
"Get a native configuration option value for another entity"},
{"_ceph_get_module_option", (PyCFunction)ceph_get_module_option, METH_VARARGS,
"Get a module configuration option value"},
{"_ceph_get_store_prefix", (PyCFunction)ceph_store_get_prefix, METH_VARARGS,
"Get all KV store values with a given prefix"},
{"_ceph_set_module_option", (PyCFunction)ceph_set_module_option, METH_VARARGS,
"Set a module configuration option value"},
{"_ceph_get_store", (PyCFunction)ceph_store_get, METH_VARARGS,
"Get a stored field"},
{"_ceph_set_store", (PyCFunction)ceph_store_set, METH_VARARGS,
"Set a stored field"},
{"_ceph_get_counter", (PyCFunction)get_counter, METH_VARARGS,
"Get a performance counter"},
{"_ceph_get_latest_counter", (PyCFunction)get_latest_counter, METH_VARARGS,
"Get the latest performance counter"},
{"_ceph_get_perf_schema", (PyCFunction)get_perf_schema, METH_VARARGS,
"Get the performance counter schema"},
{"_ceph_get_rocksdb_version", (PyCFunction)ceph_get_rocksdb_version, METH_NOARGS,
"Get the current RocksDB version number"},
{"_ceph_log", (PyCFunction)ceph_log, METH_VARARGS,
"Emit a (local) log message"},
{"_ceph_cluster_log", (PyCFunction)ceph_cluster_log, METH_VARARGS,
"Emit a cluster log message"},
{"_ceph_get_version", (PyCFunction)ceph_get_version, METH_NOARGS,
"Get the ceph version of this process"},
{"_ceph_get_release_name", (PyCFunction)ceph_get_release_name, METH_NOARGS,
"Get the ceph release name of this process"},
{"_ceph_lookup_release_name", (PyCFunction)ceph_lookup_release_name, METH_VARARGS,
"Get the ceph release name for a given major number"},
{"_ceph_get_context", (PyCFunction)ceph_get_context, METH_NOARGS,
"Get a CephContext* in a python capsule"},
{"_ceph_get_osdmap", (PyCFunction)ceph_get_osdmap, METH_NOARGS,
"Get an OSDMap* in a python capsule"},
{"_ceph_set_uri", (PyCFunction)ceph_set_uri, METH_VARARGS,
"Advertize a service URI served by this module"},
{"_ceph_set_device_wear_level", (PyCFunction)ceph_set_wear_level, METH_VARARGS,
"Set device wear_level value"},
{"_ceph_have_mon_connection", (PyCFunction)ceph_have_mon_connection,
METH_NOARGS, "Find out whether this mgr daemon currently has "
"a connection to a monitor"},
{"_ceph_update_progress_event", (PyCFunction)ceph_update_progress_event,
METH_VARARGS, "Update status of a progress event"},
{"_ceph_complete_progress_event", (PyCFunction)ceph_complete_progress_event,
METH_VARARGS, "Complete a progress event"},
{"_ceph_clear_all_progress_events", (PyCFunction)ceph_clear_all_progress_events,
METH_NOARGS, "Clear all progress events"},
{"_ceph_dispatch_remote", (PyCFunction)ceph_dispatch_remote,
METH_VARARGS, "Dispatch a call to another module"},
{"_ceph_add_osd_perf_query", (PyCFunction)ceph_add_osd_perf_query,
METH_VARARGS, "Add an osd perf query"},
{"_ceph_remove_osd_perf_query", (PyCFunction)ceph_remove_osd_perf_query,
METH_VARARGS, "Remove an osd perf query"},
{"_ceph_get_osd_perf_counters", (PyCFunction)ceph_get_osd_perf_counters,
METH_VARARGS, "Get osd perf counters"},
{"_ceph_add_mds_perf_query", (PyCFunction)ceph_add_mds_perf_query,
METH_VARARGS, "Add an mds perf query"},
{"_ceph_remove_mds_perf_query", (PyCFunction)ceph_remove_mds_perf_query,
METH_VARARGS, "Remove an mds perf query"},
{"_ceph_reregister_mds_perf_queries", (PyCFunction)ceph_reregister_mds_perf_queries,
METH_NOARGS, "Re-register mds perf queries"},
{"_ceph_get_mds_perf_counters", (PyCFunction)ceph_get_mds_perf_counters,
METH_VARARGS, "Get mds perf counters"},
{"_ceph_is_authorized", (PyCFunction)ceph_is_authorized,
METH_VARARGS, "Verify the current session caps are valid"},
{"_ceph_register_client", (PyCFunction)ceph_register_client,
METH_VARARGS, "Register RADOS instance for potential blocklisting"},
{"_ceph_unregister_client", (PyCFunction)ceph_unregister_client,
METH_VARARGS, "Unregister RADOS instance for potential blocklisting"},
{"_ceph_get_daemon_health_metrics", (PyCFunction)ceph_get_daemon_health_metrics,
METH_VARARGS, "Get health metrics for all daemons"},
{NULL, NULL, 0, NULL}
};
static PyObject *
BaseMgrModule_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
BaseMgrModule *self;
self = (BaseMgrModule *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
static int
BaseMgrModule_init(BaseMgrModule *self, PyObject *args, PyObject *kwds)
{
PyObject *py_modules_capsule = nullptr;
PyObject *this_module_capsule = nullptr;
static const char *kwlist[] = {"py_modules", "this_module", NULL};
if (! PyArg_ParseTupleAndKeywords(args, kwds, "OO",
const_cast<char**>(kwlist),
&py_modules_capsule,
&this_module_capsule)) {
return -1;
}
self->py_modules = static_cast<ActivePyModules*>(PyCapsule_GetPointer(
py_modules_capsule, nullptr));
ceph_assert(self->py_modules);
self->this_module = static_cast<ActivePyModule*>(PyCapsule_GetPointer(
this_module_capsule, nullptr));
ceph_assert(self->this_module);
return 0;
}
PyTypeObject BaseMgrModuleType = {
PyVarObject_HEAD_INIT(NULL, 0)
"ceph_module.BaseMgrModule", /* tp_name */
sizeof(BaseMgrModule), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
"ceph-mgr Python Plugin", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
BaseMgrModule_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)BaseMgrModule_init, /* tp_init */
0, /* tp_alloc */
BaseMgrModule_new, /* tp_new */
};
| 52,834 | 31.314985 | 89 | cc |
null | ceph-main/src/mgr/BaseMgrModule.h |
#pragma once
#include "Python.h"
extern PyTypeObject BaseMgrModuleType;
| 76 | 8.625 | 38 | h |
null | ceph-main/src/mgr/BaseMgrStandbyModule.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2016 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#include "BaseMgrStandbyModule.h"
#include "StandbyPyModules.h"
#include "PyFormatter.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_mgr
using std::string;
typedef struct {
PyObject_HEAD
StandbyPyModule *this_module;
} BaseMgrStandbyModule;
static PyObject *
BaseMgrStandbyModule_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
BaseMgrStandbyModule *self;
self = (BaseMgrStandbyModule *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
static int
BaseMgrStandbyModule_init(BaseMgrStandbyModule *self, PyObject *args, PyObject *kwds)
{
PyObject *this_module_capsule = nullptr;
static const char *kwlist[] = {"this_module", NULL};
if (! PyArg_ParseTupleAndKeywords(args, kwds, "O",
const_cast<char**>(kwlist),
&this_module_capsule)) {
return -1;
}
self->this_module = static_cast<StandbyPyModule*>(PyCapsule_GetPointer(
this_module_capsule, nullptr));
ceph_assert(self->this_module);
return 0;
}
static PyObject*
ceph_get_mgr_id(BaseMgrStandbyModule *self, PyObject *args)
{
return PyUnicode_FromString(g_conf()->name.get_id().c_str());
}
static PyObject*
ceph_get_module_option(BaseMgrStandbyModule *self, PyObject *args)
{
char *what = nullptr;
char *prefix = nullptr;
if (!PyArg_ParseTuple(args, "s|s:ceph_get_module_option", &what, &prefix)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
PyThreadState *tstate = PyEval_SaveThread();
std::string final_key;
std::string value;
bool found = false;
if (prefix) {
final_key = std::string(prefix) + "/" + what;
found = self->this_module->get_config(final_key, &value);
}
if (!found) {
final_key = what;
found = self->this_module->get_config(final_key, &value);
}
PyEval_RestoreThread(tstate);
if (found) {
dout(10) << __func__ << " " << final_key << " found: " << value
<< dendl;
return self->this_module->py_module->get_typed_option_value(what, value);
} else {
if (prefix) {
dout(4) << __func__ << " [" << prefix << "/]" << what << " not found "
<< dendl;
} else {
dout(4) << __func__ << " " << what << " not found " << dendl;
}
Py_RETURN_NONE;
}
}
static PyObject*
ceph_option_get(BaseMgrStandbyModule *self, PyObject *args)
{
char *what = nullptr;
if (!PyArg_ParseTuple(args, "s:ceph_option_get", &what)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
std::string value;
int r = g_conf().get_val(string(what), &value);
if (r >= 0) {
dout(10) << "ceph_option_get " << what << " found: " << value << dendl;
return PyUnicode_FromString(value.c_str());
} else {
dout(4) << "ceph_option_get " << what << " not found " << dendl;
Py_RETURN_NONE;
}
}
static PyObject*
ceph_store_get(BaseMgrStandbyModule *self, PyObject *args)
{
char *what = nullptr;
if (!PyArg_ParseTuple(args, "s:ceph_store_get", &what)) {
derr << "Invalid args!" << dendl;
return nullptr;
}
// Drop GIL for blocking mon command execution
PyThreadState *tstate = PyEval_SaveThread();
std::string value;
bool found = self->this_module->get_store(what, &value);
PyEval_RestoreThread(tstate);
if (found) {
dout(10) << "ceph_store_get " << what << " found: " << value.c_str() << dendl;
return PyUnicode_FromString(value.c_str());
} else {
dout(4) << "ceph_store_get " << what << " not found " << dendl;
Py_RETURN_NONE;
}
}
static PyObject*
ceph_get_active_uri(BaseMgrStandbyModule *self, PyObject *args)
{
return PyUnicode_FromString(self->this_module->get_active_uri().c_str());
}
static PyObject*
ceph_log(BaseMgrStandbyModule *self, PyObject *args)
{
char *record = nullptr;
if (!PyArg_ParseTuple(args, "s:log", &record)) {
return nullptr;
}
ceph_assert(self->this_module);
self->this_module->log(record);
Py_RETURN_NONE;
}
static PyObject*
ceph_standby_state_get(BaseMgrStandbyModule *self, PyObject *args)
{
char *whatc = NULL;
if (!PyArg_ParseTuple(args, "s:ceph_state_get", &whatc)) {
return NULL;
}
std::string what(whatc);
PyFormatter f;
// Drop the GIL, as most of the following blocks will block on
// a mutex -- they are all responsible for re-taking the GIL before
// touching the PyFormatter instance or returning from the function.
without_gil_t no_gil;
if (what == "mgr_ips") {
entity_addrvec_t myaddrs = self->this_module->get_myaddrs();
with_gil_t with_gil{no_gil};
f.open_array_section("ips");
std::set<std::string> did;
for (auto& i : myaddrs.v) {
std::string ip = i.ip_only_to_str();
if (auto [where, inserted] = did.insert(ip); inserted) {
f.dump_string("ip", ip);
}
}
f.close_section();
return f.get();
} else {
derr << "Python module requested unknown data '" << what << "'" << dendl;
with_gil_t with_gil{no_gil};
Py_RETURN_NONE;
}
}
PyMethodDef BaseMgrStandbyModule_methods[] = {
{"_ceph_get", (PyCFunction)ceph_standby_state_get, METH_VARARGS,
"Get a cluster object (standby)"},
{"_ceph_get_mgr_id", (PyCFunction)ceph_get_mgr_id, METH_NOARGS,
"Get the name of the Mgr daemon where we are running"},
{"_ceph_get_module_option", (PyCFunction)ceph_get_module_option, METH_VARARGS,
"Get a module configuration option value"},
{"_ceph_get_option", (PyCFunction)ceph_option_get, METH_VARARGS,
"Get a native configuration option value"},
{"_ceph_get_store", (PyCFunction)ceph_store_get, METH_VARARGS,
"Get a KV store value"},
{"_ceph_get_active_uri", (PyCFunction)ceph_get_active_uri, METH_NOARGS,
"Get the URI of the active instance of this module, if any"},
{"_ceph_log", (PyCFunction)ceph_log, METH_VARARGS,
"Emit a log message"},
{NULL, NULL, 0, NULL}
};
PyTypeObject BaseMgrStandbyModuleType = {
PyVarObject_HEAD_INIT(NULL, 0)
"ceph_module.BaseMgrStandbyModule", /* tp_name */
sizeof(BaseMgrStandbyModule), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
"ceph-mgr Standby Python Plugin", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
BaseMgrStandbyModule_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)BaseMgrStandbyModule_init, /* tp_init */
0, /* tp_alloc */
BaseMgrStandbyModule_new, /* tp_new */
};
| 8,136 | 28.915441 | 85 | cc |
null | ceph-main/src/mgr/BaseMgrStandbyModule.h | #pragma once
#include <Python.h>
extern PyTypeObject BaseMgrStandbyModuleType;
| 82 | 10.857143 | 45 | h |
null | ceph-main/src/mgr/ClusterState.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#include "messages/MMgrDigest.h"
#include "messages/MMonMgrReport.h"
#include "messages/MPGStats.h"
#include "mgr/ClusterState.h"
#include <time.h>
#include <boost/range/adaptor/reversed.hpp>
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_mgr
#undef dout_prefix
#define dout_prefix *_dout << "mgr " << __func__ << " "
using std::ostream;
using std::set;
using std::string;
using std::stringstream;
ClusterState::ClusterState(
MonClient *monc_,
Objecter *objecter_,
const MgrMap& mgrmap)
: monc(monc_),
objecter(objecter_),
mgr_map(mgrmap),
asok_hook(NULL)
{}
void ClusterState::set_objecter(Objecter *objecter_)
{
std::lock_guard l(lock);
objecter = objecter_;
}
void ClusterState::set_fsmap(FSMap const &new_fsmap)
{
std::lock_guard l(lock);
fsmap = new_fsmap;
}
void ClusterState::set_mgr_map(MgrMap const &new_mgrmap)
{
std::lock_guard l(lock);
mgr_map = new_mgrmap;
}
void ClusterState::set_service_map(ServiceMap const &new_service_map)
{
std::lock_guard l(lock);
servicemap = new_service_map;
}
void ClusterState::load_digest(MMgrDigest *m)
{
std::lock_guard l(lock);
health_json = std::move(m->health_json);
mon_status_json = std::move(m->mon_status_json);
}
void ClusterState::ingest_pgstats(ref_t<MPGStats> stats)
{
std::lock_guard l(lock);
const int from = stats->get_orig_source().num();
bool is_in = with_osdmap([from](const OSDMap& osdmap) {
return osdmap.is_in(from);
});
if (is_in) {
pending_inc.update_stat(from, std::move(stats->osd_stat));
} else {
osd_stat_t empty_stat;
empty_stat.seq = stats->osd_stat.seq;
pending_inc.update_stat(from, std::move(empty_stat));
}
for (auto p : stats->pg_stat) {
pg_t pgid = p.first;
const auto &pg_stats = p.second;
// In case we're hearing about a PG that according to last
// OSDMap update should not exist
auto r = existing_pools.find(pgid.pool());
if (r == existing_pools.end()) {
dout(15) << " got " << pgid
<< " reported at " << pg_stats.reported_epoch << ":"
<< pg_stats.reported_seq
<< " state " << pg_state_string(pg_stats.state)
<< " but pool not in " << existing_pools
<< dendl;
continue;
}
if (pgid.ps() >= r->second) {
dout(15) << " got " << pgid
<< " reported at " << pg_stats.reported_epoch << ":"
<< pg_stats.reported_seq
<< " state " << pg_state_string(pg_stats.state)
<< " but > pg_num " << r->second
<< dendl;
continue;
}
// In case we already heard about more recent stats from this PG
// from another OSD
const auto q = pg_map.pg_stat.find(pgid);
if (q != pg_map.pg_stat.end() &&
q->second.get_version_pair() > pg_stats.get_version_pair()) {
dout(15) << " had " << pgid << " from "
<< q->second.reported_epoch << ":"
<< q->second.reported_seq << dendl;
continue;
}
pending_inc.pg_stat_updates[pgid] = pg_stats;
}
for (auto p : stats->pool_stat) {
pending_inc.pool_statfs_updates[std::make_pair(p.first, from)] = p.second;
}
}
void ClusterState::update_delta_stats()
{
pending_inc.stamp = ceph_clock_now();
pending_inc.version = pg_map.version + 1; // to make apply_incremental happy
dout(10) << " v" << pending_inc.version << dendl;
dout(30) << " pg_map before:\n";
JSONFormatter jf(true);
jf.dump_object("pg_map", pg_map);
jf.flush(*_dout);
*_dout << dendl;
dout(30) << " incremental:\n";
JSONFormatter jf(true);
jf.dump_object("pending_inc", pending_inc);
jf.flush(*_dout);
*_dout << dendl;
pg_map.apply_incremental(g_ceph_context, pending_inc);
pending_inc = PGMap::Incremental();
}
void ClusterState::notify_osdmap(const OSDMap &osd_map)
{
assert(ceph_mutex_is_locked(lock));
pending_inc.stamp = ceph_clock_now();
pending_inc.version = pg_map.version + 1; // to make apply_incremental happy
dout(10) << " v" << pending_inc.version << dendl;
PGMapUpdater::check_osd_map(g_ceph_context, osd_map, pg_map, &pending_inc);
// update our list of pools that exist, so that we can filter pg_map updates
// in synchrony with this OSDMap.
existing_pools.clear();
for (auto& p : osd_map.get_pools()) {
existing_pools[p.first] = p.second.get_pg_num();
}
// brute force this for now (don't bother being clever by only
// checking osds that went up/down)
set<int> need_check_down_pg_osds;
PGMapUpdater::check_down_pgs(osd_map, pg_map, true,
need_check_down_pg_osds, &pending_inc);
dout(30) << " pg_map before:\n";
JSONFormatter jf(true);
jf.dump_object("pg_map", pg_map);
jf.flush(*_dout);
*_dout << dendl;
dout(30) << " incremental:\n";
JSONFormatter jf(true);
jf.dump_object("pending_inc", pending_inc);
jf.flush(*_dout);
*_dout << dendl;
pg_map.apply_incremental(g_ceph_context, pending_inc);
pending_inc = PGMap::Incremental();
// TODO: Complete the separation of PG state handling so
// that a cut-down set of functionality remains in PGMonitor
// while the full-blown PGMap lives only here.
}
class ClusterSocketHook : public AdminSocketHook {
ClusterState *cluster_state;
public:
explicit ClusterSocketHook(ClusterState *o) : cluster_state(o) {}
int call(std::string_view admin_command, const cmdmap_t& cmdmap,
const bufferlist&,
Formatter *f,
std::ostream& errss,
bufferlist& out) override {
stringstream outss;
int r = 0;
try {
r = cluster_state->asok_command(admin_command, cmdmap, f, outss);
out.append(outss);
} catch (const TOPNSPC::common::bad_cmd_get& e) {
errss << e.what();
r = -EINVAL;
}
return r;
}
};
void ClusterState::final_init()
{
AdminSocket *admin_socket = g_ceph_context->get_admin_socket();
asok_hook = new ClusterSocketHook(this);
int r = admin_socket->register_command(
"dump_osd_network name=value,type=CephInt,req=false", asok_hook,
"Dump osd heartbeat network ping times");
ceph_assert(r == 0);
}
void ClusterState::shutdown()
{
// unregister commands
g_ceph_context->get_admin_socket()->unregister_commands(asok_hook);
delete asok_hook;
asok_hook = NULL;
}
bool ClusterState::asok_command(
std::string_view admin_command,
const cmdmap_t& cmdmap,
Formatter *f,
ostream& ss)
{
std::lock_guard l(lock);
if (admin_command == "dump_osd_network") {
int64_t value = 0;
// Default to health warning level if nothing specified
if (!(TOPNSPC::common::cmd_getval(cmdmap, "value", value))) {
// Convert milliseconds to microseconds
value = static_cast<int64_t>(g_ceph_context->_conf.get_val<double>("mon_warn_on_slow_ping_time")) * 1000;
if (value == 0) {
double ratio = g_conf().get_val<double>("mon_warn_on_slow_ping_ratio");
value = g_conf().get_val<int64_t>("osd_heartbeat_grace");
value *= 1000000 * ratio; // Seconds of grace to microseconds at ratio
}
} else {
// Convert user input to microseconds
value *= 1000;
}
if (value < 0)
value = 0;
struct mgr_ping_time_t {
uint32_t pingtime;
int from;
int to;
bool back;
std::array<uint32_t,3> times;
std::array<uint32_t,3> min;
std::array<uint32_t,3> max;
uint32_t last;
uint32_t last_update;
bool operator<(const mgr_ping_time_t& rhs) const {
if (pingtime < rhs.pingtime)
return true;
if (pingtime > rhs.pingtime)
return false;
if (from < rhs.from)
return true;
if (from > rhs.from)
return false;
if (to < rhs.to)
return true;
if (to > rhs.to)
return false;
return back;
}
};
set<mgr_ping_time_t> sorted;
utime_t now = ceph_clock_now();
for (auto i : pg_map.osd_stat) {
for (auto j : i.second.hb_pingtime) {
if (j.second.last_update == 0)
continue;
auto stale_time = g_ceph_context->_conf.get_val<int64_t>("osd_mon_heartbeat_stat_stale");
if (now.sec() - j.second.last_update > stale_time) {
dout(20) << __func__ << " time out heartbeat for osd " << i.first
<< " last_update " << j.second.last_update << dendl;
continue;
}
mgr_ping_time_t item;
item.pingtime = std::max(j.second.back_pingtime[0], j.second.back_pingtime[1]);
item.pingtime = std::max(item.pingtime, j.second.back_pingtime[2]);
if (!value || item.pingtime >= value) {
item.from = i.first;
item.to = j.first;
item.times[0] = j.second.back_pingtime[0];
item.times[1] = j.second.back_pingtime[1];
item.times[2] = j.second.back_pingtime[2];
item.min[0] = j.second.back_min[0];
item.min[1] = j.second.back_min[1];
item.min[2] = j.second.back_min[2];
item.max[0] = j.second.back_max[0];
item.max[1] = j.second.back_max[1];
item.max[2] = j.second.back_max[2];
item.last = j.second.back_last;
item.back = true;
item.last_update = j.second.last_update;
sorted.emplace(item);
}
if (j.second.front_last == 0)
continue;
item.pingtime = std::max(j.second.front_pingtime[0], j.second.front_pingtime[1]);
item.pingtime = std::max(item.pingtime, j.second.front_pingtime[2]);
if (!value || item.pingtime >= value) {
item.from = i.first;
item.to = j.first;
item.times[0] = j.second.front_pingtime[0];
item.times[1] = j.second.front_pingtime[1];
item.times[2] = j.second.front_pingtime[2];
item.min[0] = j.second.front_min[0];
item.min[1] = j.second.front_min[1];
item.min[2] = j.second.front_min[2];
item.max[0] = j.second.front_max[0];
item.max[1] = j.second.front_max[1];
item.max[2] = j.second.front_max[2];
item.last = j.second.front_last;
item.back = false;
item.last_update = j.second.last_update;
sorted.emplace(item);
}
}
}
// Network ping times (1min 5min 15min)
f->open_object_section("network_ping_times");
f->dump_int("threshold", value / 1000);
f->open_array_section("entries");
for (auto &sitem : boost::adaptors::reverse(sorted)) {
ceph_assert(!value || sitem.pingtime >= value);
f->open_object_section("entry");
const time_t lu(sitem.last_update);
char buffer[26];
string lustr(ctime_r(&lu, buffer));
lustr.pop_back(); // Remove trailing \n
auto stale = g_ceph_context->_conf.get_val<int64_t>("osd_heartbeat_stale");
f->dump_string("last update", lustr);
f->dump_bool("stale", ceph_clock_now().sec() - sitem.last_update > stale);
f->dump_int("from osd", sitem.from);
f->dump_int("to osd", sitem.to);
f->dump_string("interface", (sitem.back ? "back" : "front"));
f->open_object_section("average");
f->dump_format_unquoted("1min", "%s", fixed_u_to_string(sitem.times[0],3).c_str());
f->dump_format_unquoted("5min", "%s", fixed_u_to_string(sitem.times[1],3).c_str());
f->dump_format_unquoted("15min", "%s", fixed_u_to_string(sitem.times[2],3).c_str());
f->close_section(); // average
f->open_object_section("min");
f->dump_format_unquoted("1min", "%s", fixed_u_to_string(sitem.min[0],3).c_str());
f->dump_format_unquoted("5min", "%s", fixed_u_to_string(sitem.min[1],3).c_str());
f->dump_format_unquoted("15min", "%s", fixed_u_to_string(sitem.min[2],3).c_str());
f->close_section(); // min
f->open_object_section("max");
f->dump_format_unquoted("1min", "%s", fixed_u_to_string(sitem.max[0],3).c_str());
f->dump_format_unquoted("5min", "%s", fixed_u_to_string(sitem.max[1],3).c_str());
f->dump_format_unquoted("15min", "%s", fixed_u_to_string(sitem.max[2],3).c_str());
f->close_section(); // max
f->dump_format_unquoted("last", "%s", fixed_u_to_string(sitem.last,3).c_str());
f->close_section(); // entry
}
f->close_section(); // entries
f->close_section(); // network_ping_times
} else {
ceph_abort_msg("broken asok registration");
}
return true;
}
| 12,421 | 30.688776 | 111 | cc |
null | ceph-main/src/mgr/ClusterState.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#ifndef CLUSTER_STATE_H_
#define CLUSTER_STATE_H_
#include "mds/FSMap.h"
#include "mon/MgrMap.h"
#include "common/ceph_mutex.h"
#include "osdc/Objecter.h"
#include "mon/MonClient.h"
#include "mon/PGMap.h"
#include "mgr/ServiceMap.h"
class MMgrDigest;
class MMonMgrReport;
class MPGStats;
/**
* Cluster-scope state (things like cluster maps) as opposed
* to daemon-level state (things like perf counters and smart)
*/
class ClusterState
{
protected:
MonClient *monc;
Objecter *objecter;
FSMap fsmap;
ServiceMap servicemap;
mutable ceph::mutex lock = ceph::make_mutex("ClusterState");
MgrMap mgr_map;
std::map<int64_t,unsigned> existing_pools; ///< pools that exist, and pg_num, as of PGMap epoch
PGMap pg_map;
PGMap::Incremental pending_inc;
bufferlist health_json;
bufferlist mon_status_json;
class ClusterSocketHook *asok_hook;
public:
void load_digest(MMgrDigest *m);
void ingest_pgstats(ceph::ref_t<MPGStats> stats);
void update_delta_stats();
ClusterState(MonClient *monc_, Objecter *objecter_, const MgrMap& mgrmap);
void set_objecter(Objecter *objecter_);
void set_fsmap(FSMap const &new_fsmap);
void set_mgr_map(MgrMap const &new_mgrmap);
void set_service_map(ServiceMap const &new_service_map);
void notify_osdmap(const OSDMap &osd_map);
bool have_fsmap() const {
std::lock_guard l(lock);
return fsmap.get_epoch() > 0;
}
template<typename Callback, typename...Args>
auto with_servicemap(Callback&& cb, Args&&...args) const
{
std::lock_guard l(lock);
return std::forward<Callback>(cb)(servicemap, std::forward<Args>(args)...);
}
template<typename Callback, typename...Args>
auto with_fsmap(Callback&& cb, Args&&...args) const
{
std::lock_guard l(lock);
return std::forward<Callback>(cb)(fsmap, std::forward<Args>(args)...);
}
template<typename Callback, typename...Args>
auto with_mgrmap(Callback&& cb, Args&&...args) const
{
std::lock_guard l(lock);
return std::forward<Callback>(cb)(mgr_map, std::forward<Args>(args)...);
}
template<typename Callback, typename...Args>
auto with_pgmap(Callback&& cb, Args&&...args) const ->
decltype(cb(pg_map, std::forward<Args>(args)...))
{
std::lock_guard l(lock);
return std::forward<Callback>(cb)(pg_map, std::forward<Args>(args)...);
}
template<typename Callback, typename...Args>
auto with_mutable_pgmap(Callback&& cb, Args&&...args) ->
decltype(cb(pg_map, std::forward<Args>(args)...))
{
std::lock_guard l(lock);
return std::forward<Callback>(cb)(pg_map, std::forward<Args>(args)...);
}
template<typename... Args>
auto with_monmap(Args &&... args) const
{
std::lock_guard l(lock);
ceph_assert(monc != nullptr);
return monc->with_monmap(std::forward<Args>(args)...);
}
template<typename... Args>
auto with_osdmap(Args &&... args) const ->
decltype(objecter->with_osdmap(std::forward<Args>(args)...))
{
ceph_assert(objecter != nullptr);
return objecter->with_osdmap(std::forward<Args>(args)...);
}
// call cb(osdmap, pg_map, ...args) with the appropriate locks
template <typename Callback, typename ...Args>
auto with_osdmap_and_pgmap(Callback&& cb, Args&& ...args) const {
ceph_assert(objecter != nullptr);
std::lock_guard l(lock);
return objecter->with_osdmap(
std::forward<Callback>(cb),
pg_map,
std::forward<Args>(args)...);
}
template<typename Callback, typename...Args>
auto with_health(Callback&& cb, Args&&...args) const
{
std::lock_guard l(lock);
return std::forward<Callback>(cb)(health_json, std::forward<Args>(args)...);
}
template<typename Callback, typename...Args>
auto with_mon_status(Callback&& cb, Args&&...args) const
{
std::lock_guard l(lock);
return std::forward<Callback>(cb)(mon_status_json, std::forward<Args>(args)...);
}
void final_init();
void shutdown();
bool asok_command(std::string_view admin_command,
const cmdmap_t& cmdmap,
Formatter *f,
std::ostream& ss);
};
#endif
| 4,480 | 26.323171 | 97 | h |
null | ceph-main/src/mgr/DaemonHealthMetric.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <cstdint>
#include <ostream>
#include "include/denc.h"
enum class daemon_metric : uint8_t {
SLOW_OPS,
PENDING_CREATING_PGS,
NONE,
};
static inline const char *daemon_metric_name(daemon_metric t) {
switch (t) {
case daemon_metric::SLOW_OPS: return "SLOW_OPS";
case daemon_metric::PENDING_CREATING_PGS: return "PENDING_CREATING_PGS";
case daemon_metric::NONE: return "NONE";
default: return "???";
}
}
union daemon_metric_t {
struct {
uint32_t n1;
uint32_t n2;
};
uint64_t n;
daemon_metric_t(uint32_t x, uint32_t y)
: n1(x), n2(y)
{}
daemon_metric_t(uint64_t x = 0)
: n(x)
{}
};
class DaemonHealthMetric
{
public:
DaemonHealthMetric() = default;
DaemonHealthMetric(daemon_metric type_, uint64_t n)
: type(type_), value(n)
{}
DaemonHealthMetric(daemon_metric type_, uint32_t n1, uint32_t n2)
: type(type_), value(n1, n2)
{}
daemon_metric get_type() const {
return type;
}
uint64_t get_n() const {
return value.n;
}
uint32_t get_n1() const {
return value.n1;
}
uint32_t get_n2() const {
return value.n2;
}
DENC(DaemonHealthMetric, v, p) {
DENC_START(1, 1, p);
denc(v.type, p);
denc(v.value.n, p);
DENC_FINISH(p);
}
std::string get_type_name() const {
return daemon_metric_name(get_type());
}
friend std::ostream& operator<<(std::ostream& out, const DaemonHealthMetric& m) {
return out << daemon_metric_name(m.get_type()) << "("
<< m.get_n() << "|(" << m.get_n1() << "," << m.get_n2() << "))";
}
private:
daemon_metric type = daemon_metric::NONE;
daemon_metric_t value;
};
WRITE_CLASS_DENC(DaemonHealthMetric)
| 1,782 | 20.481928 | 83 | h |
null | ceph-main/src/mgr/DaemonHealthMetricCollector.cc | #include <fmt/format.h>
#include "include/health.h"
#include "include/types.h"
#include "DaemonHealthMetricCollector.h"
namespace {
using std::unique_ptr;
using std::vector;
using std::ostringstream;
class SlowOps final : public DaemonHealthMetricCollector {
bool _is_relevant(daemon_metric type) const override {
return type == daemon_metric::SLOW_OPS;
}
health_check_t& _get_check(health_check_map_t& cm) const override {
return cm.get_or_add("SLOW_OPS", HEALTH_WARN, "", 1);
}
bool _update(const DaemonKey& daemon,
const DaemonHealthMetric& metric) override {
auto num_slow = metric.get_n1();
auto blocked_time = metric.get_n2();
value.n1 += num_slow;
value.n2 = std::max(value.n2, blocked_time);
if (num_slow || blocked_time) {
daemons.push_back(daemon);
return true;
} else {
return false;
}
}
void _summarize(health_check_t& check) const override {
if (daemons.empty()) {
return;
}
// Note this message format is used in mgr/prometheus, so any change in format
// requires a corresponding change in the mgr/prometheus module.
ostringstream ss;
if (daemons.size() > 1) {
if (daemons.size() > 10) {
ss << "daemons " << vector<DaemonKey>(daemons.begin(), daemons.begin()+10)
<< "..." << " have slow ops.";
} else {
ss << "daemons " << daemons << " have slow ops.";
}
} else {
ss << daemons.front() << " has slow ops";
}
check.summary =
fmt::format("{} slow ops, oldest one blocked for {} sec, {}",
value.n1, value.n2, ss.str());
// No detail
}
vector<DaemonKey> daemons;
};
class PendingPGs final : public DaemonHealthMetricCollector {
bool _is_relevant(daemon_metric type) const override {
return type == daemon_metric::PENDING_CREATING_PGS;
}
health_check_t& _get_check(health_check_map_t& cm) const override {
return cm.get_or_add("PENDING_CREATING_PGS", HEALTH_WARN, "", 1);
}
bool _update(const DaemonKey& osd,
const DaemonHealthMetric& metric) override {
value.n += metric.get_n();
if (metric.get_n()) {
osds.push_back(osd);
return true;
} else {
return false;
}
}
void _summarize(health_check_t& check) const override {
if (osds.empty()) {
return;
}
check.summary = fmt::format("{} PGs pending on creation", value.n);
ostringstream ss;
if (osds.size() > 1) {
ss << "osds " << osds << " have pending PGs.";
} else {
ss << osds.front() << " has pending PGs";
}
check.detail.push_back(ss.str());
}
vector<DaemonKey> osds;
};
} // anonymous namespace
unique_ptr<DaemonHealthMetricCollector>
DaemonHealthMetricCollector::create(daemon_metric m)
{
switch (m) {
case daemon_metric::SLOW_OPS:
return std::make_unique<SlowOps>();
case daemon_metric::PENDING_CREATING_PGS:
return std::make_unique<PendingPGs>();
default:
return {};
}
}
| 3,003 | 27.339623 | 82 | cc |
null | ceph-main/src/mgr/DaemonHealthMetricCollector.h | #pragma once
#include <memory>
#include <string>
#include "DaemonHealthMetric.h"
#include "DaemonKey.h"
#include "mon/health_check.h"
class DaemonHealthMetricCollector {
public:
static std::unique_ptr<DaemonHealthMetricCollector> create(daemon_metric m);
void update(const DaemonKey& daemon, const DaemonHealthMetric& metric) {
if (_is_relevant(metric.get_type())) {
reported |= _update(daemon, metric);
}
}
void summarize(health_check_map_t& cm) {
if (reported) {
_summarize(_get_check(cm));
}
}
virtual ~DaemonHealthMetricCollector() {}
private:
virtual bool _is_relevant(daemon_metric type) const = 0;
virtual health_check_t& _get_check(health_check_map_t& cm) const = 0;
virtual bool _update(const DaemonKey& daemon, const DaemonHealthMetric& metric) = 0;
virtual void _summarize(health_check_t& check) const = 0;
protected:
daemon_metric_t value;
bool reported = false;
};
| 933 | 27.30303 | 86 | h |
null | ceph-main/src/mgr/DaemonKey.cc | #include "DaemonKey.h"
std::pair<DaemonKey, bool> DaemonKey::parse(const std::string& s)
{
auto p = s.find('.');
if (p == s.npos) {
return {{}, false};
} else {
return {DaemonKey{s.substr(0, p), s.substr(p + 1)}, true};
}
}
bool operator<(const DaemonKey& lhs, const DaemonKey& rhs)
{
if (int cmp = lhs.type.compare(rhs.type); cmp < 0) {
return true;
} else if (cmp > 0) {
return false;
} else {
return lhs.name < rhs.name;
}
}
std::ostream& operator<<(std::ostream& os, const DaemonKey& key)
{
return os << key.type << '.' << key.name;
}
namespace ceph {
std::string to_string(const DaemonKey& key)
{
return key.type + '.' + key.name;
}
}
| 685 | 18.055556 | 65 | cc |
null | ceph-main/src/mgr/DaemonKey.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <ostream>
#include <string>
#include <utility>
// Unique reference to a daemon within a cluster
struct DaemonKey
{
std::string type; // service type, like "osd", "mon"
std::string name; // service id / name, like "1", "a"
static std::pair<DaemonKey, bool> parse(const std::string& s);
};
bool operator<(const DaemonKey& lhs, const DaemonKey& rhs);
std::ostream& operator<<(std::ostream& os, const DaemonKey& key);
namespace ceph {
std::string to_string(const DaemonKey& key);
}
| 612 | 23.52 | 70 | h |
null | ceph-main/src/mgr/DaemonServer.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2016 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#include "DaemonServer.h"
#include <boost/algorithm/string.hpp>
#include "mgr/Mgr.h"
#include "include/stringify.h"
#include "include/str_list.h"
#include "auth/RotatingKeyRing.h"
#include "json_spirit/json_spirit_writer.h"
#include "mgr/mgr_commands.h"
#include "mgr/DaemonHealthMetricCollector.h"
#include "mgr/OSDPerfMetricCollector.h"
#include "mgr/MDSPerfMetricCollector.h"
#include "mon/MonCommand.h"
#include "messages/MMgrOpen.h"
#include "messages/MMgrUpdate.h"
#include "messages/MMgrClose.h"
#include "messages/MMgrConfigure.h"
#include "messages/MMonMgrReport.h"
#include "messages/MCommand.h"
#include "messages/MCommandReply.h"
#include "messages/MMgrCommand.h"
#include "messages/MMgrCommandReply.h"
#include "messages/MPGStats.h"
#include "messages/MOSDScrub2.h"
#include "messages/MOSDForceRecovery.h"
#include "common/errno.h"
#include "common/pick_address.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_mgr
#undef dout_prefix
#define dout_prefix *_dout << "mgr.server " << __func__ << " "
using namespace TOPNSPC::common;
using std::list;
using std::ostringstream;
using std::string;
using std::stringstream;
using std::vector;
using std::unique_ptr;
namespace {
template <typename Map>
bool map_compare(Map const &lhs, Map const &rhs) {
return lhs.size() == rhs.size()
&& std::equal(lhs.begin(), lhs.end(), rhs.begin(),
[] (auto a, auto b) { return a.first == b.first && a.second == b.second; });
}
}
DaemonServer::DaemonServer(MonClient *monc_,
Finisher &finisher_,
DaemonStateIndex &daemon_state_,
ClusterState &cluster_state_,
PyModuleRegistry &py_modules_,
LogChannelRef clog_,
LogChannelRef audit_clog_)
: Dispatcher(g_ceph_context),
client_byte_throttler(new Throttle(g_ceph_context, "mgr_client_bytes",
g_conf().get_val<Option::size_t>("mgr_client_bytes"))),
client_msg_throttler(new Throttle(g_ceph_context, "mgr_client_messages",
g_conf().get_val<uint64_t>("mgr_client_messages"))),
osd_byte_throttler(new Throttle(g_ceph_context, "mgr_osd_bytes",
g_conf().get_val<Option::size_t>("mgr_osd_bytes"))),
osd_msg_throttler(new Throttle(g_ceph_context, "mgr_osd_messsages",
g_conf().get_val<uint64_t>("mgr_osd_messages"))),
mds_byte_throttler(new Throttle(g_ceph_context, "mgr_mds_bytes",
g_conf().get_val<Option::size_t>("mgr_mds_bytes"))),
mds_msg_throttler(new Throttle(g_ceph_context, "mgr_mds_messsages",
g_conf().get_val<uint64_t>("mgr_mds_messages"))),
mon_byte_throttler(new Throttle(g_ceph_context, "mgr_mon_bytes",
g_conf().get_val<Option::size_t>("mgr_mon_bytes"))),
mon_msg_throttler(new Throttle(g_ceph_context, "mgr_mon_messsages",
g_conf().get_val<uint64_t>("mgr_mon_messages"))),
msgr(nullptr),
monc(monc_),
finisher(finisher_),
daemon_state(daemon_state_),
cluster_state(cluster_state_),
py_modules(py_modules_),
clog(clog_),
audit_clog(audit_clog_),
pgmap_ready(false),
timer(g_ceph_context, lock),
shutting_down(false),
tick_event(nullptr),
osd_perf_metric_collector_listener(this),
osd_perf_metric_collector(osd_perf_metric_collector_listener),
mds_perf_metric_collector_listener(this),
mds_perf_metric_collector(mds_perf_metric_collector_listener)
{
g_conf().add_observer(this);
}
DaemonServer::~DaemonServer() {
delete msgr;
g_conf().remove_observer(this);
}
int DaemonServer::init(uint64_t gid, entity_addrvec_t client_addrs)
{
// Initialize Messenger
std::string public_msgr_type = g_conf()->ms_public_type.empty() ?
g_conf().get_val<std::string>("ms_type") : g_conf()->ms_public_type;
msgr = Messenger::create(g_ceph_context, public_msgr_type,
entity_name_t::MGR(gid),
"mgr",
Messenger::get_random_nonce());
msgr->set_default_policy(Messenger::Policy::stateless_server(0));
msgr->set_auth_client(monc);
// throttle clients
msgr->set_policy_throttlers(entity_name_t::TYPE_CLIENT,
client_byte_throttler.get(),
client_msg_throttler.get());
// servers
msgr->set_policy_throttlers(entity_name_t::TYPE_OSD,
osd_byte_throttler.get(),
osd_msg_throttler.get());
msgr->set_policy_throttlers(entity_name_t::TYPE_MDS,
mds_byte_throttler.get(),
mds_msg_throttler.get());
msgr->set_policy_throttlers(entity_name_t::TYPE_MON,
mon_byte_throttler.get(),
mon_msg_throttler.get());
entity_addrvec_t addrs;
int r = pick_addresses(cct, CEPH_PICK_ADDRESS_PUBLIC, &addrs);
if (r < 0) {
return r;
}
dout(20) << __func__ << " will bind to " << addrs << dendl;
r = msgr->bindv(addrs);
if (r < 0) {
derr << "unable to bind mgr to " << addrs << dendl;
return r;
}
msgr->set_myname(entity_name_t::MGR(gid));
msgr->set_addr_unknowns(client_addrs);
msgr->start();
msgr->add_dispatcher_tail(this);
msgr->set_auth_server(monc);
monc->set_handle_authentication_dispatcher(this);
started_at = ceph_clock_now();
std::lock_guard l(lock);
timer.init();
schedule_tick_locked(
g_conf().get_val<std::chrono::seconds>("mgr_tick_period").count());
return 0;
}
entity_addrvec_t DaemonServer::get_myaddrs() const
{
return msgr->get_myaddrs();
}
int DaemonServer::ms_handle_authentication(Connection *con)
{
auto s = ceph::make_ref<MgrSession>(cct);
con->set_priv(s);
s->inst.addr = con->get_peer_addr();
s->entity_name = con->peer_name;
dout(10) << __func__ << " new session " << s << " con " << con
<< " entity " << con->peer_name
<< " addr " << con->get_peer_addrs()
<< dendl;
AuthCapsInfo &caps_info = con->get_peer_caps_info();
if (caps_info.allow_all) {
dout(10) << " session " << s << " " << s->entity_name
<< " allow_all" << dendl;
s->caps.set_allow_all();
} else if (caps_info.caps.length() > 0) {
auto p = caps_info.caps.cbegin();
string str;
try {
decode(str, p);
}
catch (buffer::error& e) {
dout(10) << " session " << s << " " << s->entity_name
<< " failed to decode caps" << dendl;
return -EACCES;
}
if (!s->caps.parse(str)) {
dout(10) << " session " << s << " " << s->entity_name
<< " failed to parse caps '" << str << "'" << dendl;
return -EACCES;
}
dout(10) << " session " << s << " " << s->entity_name
<< " has caps " << s->caps << " '" << str << "'" << dendl;
}
if (con->get_peer_type() == CEPH_ENTITY_TYPE_OSD) {
std::lock_guard l(lock);
s->osd_id = atoi(s->entity_name.get_id().c_str());
dout(10) << "registering osd." << s->osd_id << " session "
<< s << " con " << con << dendl;
osd_cons[s->osd_id].insert(con);
}
return 1;
}
bool DaemonServer::ms_handle_reset(Connection *con)
{
if (con->get_peer_type() == CEPH_ENTITY_TYPE_OSD) {
auto priv = con->get_priv();
auto session = static_cast<MgrSession*>(priv.get());
if (!session) {
return false;
}
std::lock_guard l(lock);
dout(10) << "unregistering osd." << session->osd_id
<< " session " << session << " con " << con << dendl;
osd_cons[session->osd_id].erase(con);
auto iter = daemon_connections.find(con);
if (iter != daemon_connections.end()) {
daemon_connections.erase(iter);
}
}
return false;
}
bool DaemonServer::ms_handle_refused(Connection *con)
{
// do nothing for now
return false;
}
bool DaemonServer::ms_dispatch2(const ref_t<Message>& m)
{
// Note that we do *not* take ::lock here, in order to avoid
// serializing all message handling. It's up to each handler
// to take whatever locks it needs.
switch (m->get_type()) {
case MSG_PGSTATS:
cluster_state.ingest_pgstats(ref_cast<MPGStats>(m));
maybe_ready(m->get_source().num());
return true;
case MSG_MGR_REPORT:
return handle_report(ref_cast<MMgrReport>(m));
case MSG_MGR_OPEN:
return handle_open(ref_cast<MMgrOpen>(m));
case MSG_MGR_UPDATE:
return handle_update(ref_cast<MMgrUpdate>(m));
case MSG_MGR_CLOSE:
return handle_close(ref_cast<MMgrClose>(m));
case MSG_COMMAND:
return handle_command(ref_cast<MCommand>(m));
case MSG_MGR_COMMAND:
return handle_command(ref_cast<MMgrCommand>(m));
default:
dout(1) << "Unhandled message type " << m->get_type() << dendl;
return false;
};
}
void DaemonServer::dump_pg_ready(ceph::Formatter *f)
{
f->dump_bool("pg_ready", pgmap_ready.load());
}
void DaemonServer::maybe_ready(int32_t osd_id)
{
if (pgmap_ready.load()) {
// Fast path: we don't need to take lock because pgmap_ready
// is already set
} else {
std::lock_guard l(lock);
if (reported_osds.find(osd_id) == reported_osds.end()) {
dout(4) << "initial report from osd " << osd_id << dendl;
reported_osds.insert(osd_id);
std::set<int32_t> up_osds;
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
osdmap.get_up_osds(up_osds);
});
std::set<int32_t> unreported_osds;
std::set_difference(up_osds.begin(), up_osds.end(),
reported_osds.begin(), reported_osds.end(),
std::inserter(unreported_osds, unreported_osds.begin()));
if (unreported_osds.size() == 0) {
dout(4) << "all osds have reported, sending PG state to mon" << dendl;
pgmap_ready = true;
reported_osds.clear();
// Avoid waiting for next tick
send_report();
} else {
dout(4) << "still waiting for " << unreported_osds.size() << " osds"
" to report in before PGMap is ready" << dendl;
}
}
}
}
void DaemonServer::tick()
{
dout(10) << dendl;
send_report();
adjust_pgs();
schedule_tick_locked(
g_conf().get_val<std::chrono::seconds>("mgr_tick_period").count());
}
// Currently modules do not set health checks in response to events delivered to
// all modules (e.g. notify) so we do not risk a thundering hurd situation here.
// if this pattern emerges in the future, this scheduler could be modified to
// fire after all modules have had a chance to set their health checks.
void DaemonServer::schedule_tick_locked(double delay_sec)
{
ceph_assert(ceph_mutex_is_locked_by_me(lock));
if (tick_event) {
timer.cancel_event(tick_event);
tick_event = nullptr;
}
// on shutdown start rejecting explicit requests to send reports that may
// originate from python land which may still be running.
if (shutting_down)
return;
tick_event = timer.add_event_after(delay_sec,
new LambdaContext([this](int r) {
tick();
}));
}
void DaemonServer::schedule_tick(double delay_sec)
{
std::lock_guard l(lock);
schedule_tick_locked(delay_sec);
}
void DaemonServer::handle_osd_perf_metric_query_updated()
{
dout(10) << dendl;
// Send a fresh MMgrConfigure to all clients, so that they can follow
// the new policy for transmitting stats
finisher.queue(new LambdaContext([this](int r) {
std::lock_guard l(lock);
for (auto &c : daemon_connections) {
if (c->peer_is_osd()) {
_send_configure(c);
}
}
}));
}
void DaemonServer::handle_mds_perf_metric_query_updated()
{
dout(10) << dendl;
// Send a fresh MMgrConfigure to all clients, so that they can follow
// the new policy for transmitting stats
finisher.queue(new LambdaContext([this](int r) {
std::lock_guard l(lock);
for (auto &c : daemon_connections) {
if (c->peer_is_mds()) {
_send_configure(c);
}
}
}));
}
void DaemonServer::shutdown()
{
dout(10) << "begin" << dendl;
msgr->shutdown();
msgr->wait();
cluster_state.shutdown();
dout(10) << "done" << dendl;
std::lock_guard l(lock);
shutting_down = true;
timer.shutdown();
}
static DaemonKey key_from_service(
const std::string& service_name,
int peer_type,
const std::string& daemon_name)
{
if (!service_name.empty()) {
return DaemonKey{service_name, daemon_name};
} else {
return DaemonKey{ceph_entity_type_name(peer_type), daemon_name};
}
}
void DaemonServer::fetch_missing_metadata(const DaemonKey& key,
const entity_addr_t& addr)
{
if (!daemon_state.is_updating(key) &&
(key.type == "osd" || key.type == "mds" || key.type == "mon")) {
std::ostringstream oss;
auto c = new MetadataUpdate(daemon_state, key);
if (key.type == "osd") {
oss << "{\"prefix\": \"osd metadata\", \"id\": "
<< key.name<< "}";
} else if (key.type == "mds") {
c->set_default("addr", stringify(addr));
oss << "{\"prefix\": \"mds metadata\", \"who\": \""
<< key.name << "\"}";
} else if (key.type == "mon") {
oss << "{\"prefix\": \"mon metadata\", \"id\": \""
<< key.name << "\"}";
} else {
ceph_abort();
}
monc->start_mon_command({oss.str()}, {}, &c->outbl, &c->outs, c);
}
}
bool DaemonServer::handle_open(const ref_t<MMgrOpen>& m)
{
std::unique_lock l(lock);
DaemonKey key = key_from_service(m->service_name,
m->get_connection()->get_peer_type(),
m->daemon_name);
auto con = m->get_connection();
dout(10) << "from " << key << " " << con->get_peer_addr() << dendl;
_send_configure(con);
DaemonStatePtr daemon;
if (daemon_state.exists(key)) {
dout(20) << "updating existing DaemonState for " << key << dendl;
daemon = daemon_state.get(key);
}
if (!daemon) {
if (m->service_daemon) {
dout(4) << "constructing new DaemonState for " << key << dendl;
daemon = std::make_shared<DaemonState>(daemon_state.types);
daemon->key = key;
daemon->service_daemon = true;
daemon_state.insert(daemon);
} else {
/* A normal Ceph daemon has connected but we are or should be waiting on
* metadata for it. Close the session so that it tries to reconnect.
*/
dout(2) << "ignoring open from " << key << " " << con->get_peer_addr()
<< "; not ready for session (expect reconnect)" << dendl;
con->mark_down();
l.unlock();
fetch_missing_metadata(key, m->get_source_addr());
return true;
}
}
if (daemon) {
if (m->service_daemon) {
// update the metadata through the daemon state index to
// ensure it's kept up-to-date
daemon_state.update_metadata(daemon, m->daemon_metadata);
}
std::lock_guard l(daemon->lock);
daemon->perf_counters.clear();
daemon->service_daemon = m->service_daemon;
if (m->service_daemon) {
daemon->service_status = m->daemon_status;
utime_t now = ceph_clock_now();
auto [d, added] = pending_service_map.get_daemon(m->service_name,
m->daemon_name);
if (added || d->gid != (uint64_t)m->get_source().num()) {
dout(10) << "registering " << key << " in pending_service_map" << dendl;
d->gid = m->get_source().num();
d->addr = m->get_source_addr();
d->start_epoch = pending_service_map.epoch;
d->start_stamp = now;
d->metadata = m->daemon_metadata;
pending_service_map_dirty = pending_service_map.epoch;
}
}
auto p = m->config_bl.cbegin();
if (p != m->config_bl.end()) {
decode(daemon->config, p);
decode(daemon->ignored_mon_config, p);
dout(20) << " got config " << daemon->config
<< " ignored " << daemon->ignored_mon_config << dendl;
}
daemon->config_defaults_bl = m->config_defaults_bl;
daemon->config_defaults.clear();
dout(20) << " got config_defaults_bl " << daemon->config_defaults_bl.length()
<< " bytes" << dendl;
}
if (con->get_peer_type() != entity_name_t::TYPE_CLIENT &&
m->service_name.empty())
{
// Store in set of the daemon/service connections, i.e. those
// connections that require an update in the event of stats
// configuration changes.
daemon_connections.insert(con);
}
return true;
}
bool DaemonServer::handle_update(const ref_t<MMgrUpdate>& m)
{
DaemonKey key;
if (!m->service_name.empty()) {
key.type = m->service_name;
} else {
key.type = ceph_entity_type_name(m->get_connection()->get_peer_type());
}
key.name = m->daemon_name;
dout(10) << "from " << m->get_connection() << " " << key << dendl;
if (m->get_connection()->get_peer_type() == entity_name_t::TYPE_CLIENT &&
m->service_name.empty()) {
// Clients should not be sending us update request
dout(10) << "rejecting update request from non-daemon client " << m->daemon_name
<< dendl;
clog->warn() << "rejecting report from non-daemon client " << m->daemon_name
<< " at " << m->get_connection()->get_peer_addrs();
m->get_connection()->mark_down();
return true;
}
{
std::unique_lock locker(lock);
DaemonStatePtr daemon;
// Look up the DaemonState
if (daemon_state.exists(key)) {
dout(20) << "updating existing DaemonState for " << key << dendl;
daemon = daemon_state.get(key);
if (m->need_metadata_update &&
!m->daemon_metadata.empty()) {
daemon_state.update_metadata(daemon, m->daemon_metadata);
}
}
}
return true;
}
bool DaemonServer::handle_close(const ref_t<MMgrClose>& m)
{
std::lock_guard l(lock);
DaemonKey key = key_from_service(m->service_name,
m->get_connection()->get_peer_type(),
m->daemon_name);
dout(4) << "from " << m->get_connection() << " " << key << dendl;
if (daemon_state.exists(key)) {
DaemonStatePtr daemon = daemon_state.get(key);
daemon_state.rm(key);
{
std::lock_guard l(daemon->lock);
if (daemon->service_daemon) {
pending_service_map.rm_daemon(m->service_name, m->daemon_name);
pending_service_map_dirty = pending_service_map.epoch;
}
}
}
// send same message back as a reply
m->get_connection()->send_message2(m);
return true;
}
void DaemonServer::update_task_status(
DaemonKey key,
const std::map<std::string,std::string>& task_status)
{
dout(10) << "got task status from " << key << dendl;
[[maybe_unused]] auto [daemon, added] =
pending_service_map.get_daemon(key.type, key.name);
if (daemon->task_status != task_status) {
daemon->task_status = task_status;
pending_service_map_dirty = pending_service_map.epoch;
}
}
bool DaemonServer::handle_report(const ref_t<MMgrReport>& m)
{
DaemonKey key;
if (!m->service_name.empty()) {
key.type = m->service_name;
} else {
key.type = ceph_entity_type_name(m->get_connection()->get_peer_type());
}
key.name = m->daemon_name;
dout(10) << "from " << m->get_connection() << " " << key << dendl;
if (m->get_connection()->get_peer_type() == entity_name_t::TYPE_CLIENT &&
m->service_name.empty()) {
// Clients should not be sending us stats unless they are declaring
// themselves to be a daemon for some service.
dout(10) << "rejecting report from non-daemon client " << m->daemon_name
<< dendl;
clog->warn() << "rejecting report from non-daemon client " << m->daemon_name
<< " at " << m->get_connection()->get_peer_addrs();
m->get_connection()->mark_down();
return true;
}
{
std::unique_lock locker(lock);
DaemonStatePtr daemon;
// Look up the DaemonState
if (daemon = daemon_state.get(key); daemon != nullptr) {
dout(20) << "updating existing DaemonState for " << key << dendl;
} else {
locker.unlock();
// we don't know the hostname at this stage, reject MMgrReport here.
dout(5) << "rejecting report from " << key << ", since we do not have its metadata now."
<< dendl;
// issue metadata request in background
fetch_missing_metadata(key, m->get_source_addr());
locker.lock();
// kill session
auto priv = m->get_connection()->get_priv();
auto session = static_cast<MgrSession*>(priv.get());
if (!session) {
return false;
}
m->get_connection()->mark_down();
dout(10) << "unregistering osd." << session->osd_id
<< " session " << session << " con " << m->get_connection() << dendl;
if (osd_cons.find(session->osd_id) != osd_cons.end()) {
osd_cons[session->osd_id].erase(m->get_connection());
}
auto iter = daemon_connections.find(m->get_connection());
if (iter != daemon_connections.end()) {
daemon_connections.erase(iter);
}
return false;
}
// Update the DaemonState
ceph_assert(daemon != nullptr);
{
std::lock_guard l(daemon->lock);
auto &daemon_counters = daemon->perf_counters;
daemon_counters.update(*m.get());
auto p = m->config_bl.cbegin();
if (p != m->config_bl.end()) {
decode(daemon->config, p);
decode(daemon->ignored_mon_config, p);
dout(20) << " got config " << daemon->config
<< " ignored " << daemon->ignored_mon_config << dendl;
}
utime_t now = ceph_clock_now();
if (daemon->service_daemon) {
if (m->daemon_status) {
daemon->service_status_stamp = now;
daemon->service_status = *m->daemon_status;
}
daemon->last_service_beacon = now;
} else if (m->daemon_status) {
derr << "got status from non-daemon " << key << dendl;
}
// update task status
if (m->task_status) {
update_task_status(key, *m->task_status);
daemon->last_service_beacon = now;
}
if (m->get_connection()->peer_is_osd() || m->get_connection()->peer_is_mon()) {
// only OSD and MON send health_checks to me now
daemon->daemon_health_metrics = std::move(m->daemon_health_metrics);
dout(10) << "daemon_health_metrics " << daemon->daemon_health_metrics
<< dendl;
}
}
}
// if there are any schema updates, notify the python modules
/* no users currently
if (!m->declare_types.empty() || !m->undeclare_types.empty()) {
py_modules.notify_all("perf_schema_update", ceph::to_string(key));
}
*/
if (m->get_connection()->peer_is_osd()) {
osd_perf_metric_collector.process_reports(m->osd_perf_metric_reports);
}
if (m->metric_report_message) {
const MetricReportMessage &message = *m->metric_report_message;
boost::apply_visitor(HandlePayloadVisitor(this), message.payload);
}
return true;
}
void DaemonServer::_generate_command_map(
cmdmap_t& cmdmap,
map<string,string> ¶m_str_map)
{
for (auto p = cmdmap.begin();
p != cmdmap.end(); ++p) {
if (p->first == "prefix")
continue;
if (p->first == "caps") {
vector<string> cv;
if (cmd_getval(cmdmap, "caps", cv) &&
cv.size() % 2 == 0) {
for (unsigned i = 0; i < cv.size(); i += 2) {
string k = string("caps_") + cv[i];
param_str_map[k] = cv[i + 1];
}
continue;
}
}
param_str_map[p->first] = cmd_vartype_stringify(p->second);
}
}
const MonCommand *DaemonServer::_get_mgrcommand(
const string &cmd_prefix,
const std::vector<MonCommand> &cmds)
{
const MonCommand *this_cmd = nullptr;
for (const auto &cmd : cmds) {
if (cmd.cmdstring.compare(0, cmd_prefix.size(), cmd_prefix) == 0) {
this_cmd = &cmd;
break;
}
}
return this_cmd;
}
bool DaemonServer::_allowed_command(
MgrSession *s,
const string &service,
const string &module,
const string &prefix,
const cmdmap_t& cmdmap,
const map<string,string>& param_str_map,
const MonCommand *this_cmd) {
if (s->entity_name.is_mon()) {
// mon is all-powerful. even when it is forwarding commands on behalf of
// old clients; we expect the mon is validating commands before proxying!
return true;
}
bool cmd_r = this_cmd->requires_perm('r');
bool cmd_w = this_cmd->requires_perm('w');
bool cmd_x = this_cmd->requires_perm('x');
bool capable = s->caps.is_capable(
g_ceph_context,
s->entity_name,
service, module, prefix, param_str_map,
cmd_r, cmd_w, cmd_x,
s->get_peer_addr());
dout(10) << " " << s->entity_name << " "
<< (capable ? "" : "not ") << "capable" << dendl;
return capable;
}
/**
* The working data for processing an MCommand. This lives in
* a class to enable passing it into other threads for processing
* outside of the thread/locks that called handle_command.
*/
class CommandContext {
public:
ceph::ref_t<MCommand> m_tell;
ceph::ref_t<MMgrCommand> m_mgr;
const std::vector<std::string>& cmd; ///< ref into m_tell or m_mgr
const bufferlist& data; ///< ref into m_tell or m_mgr
bufferlist odata;
cmdmap_t cmdmap;
explicit CommandContext(ceph::ref_t<MCommand> m)
: m_tell{std::move(m)},
cmd(m_tell->cmd),
data(m_tell->get_data()) {
}
explicit CommandContext(ceph::ref_t<MMgrCommand> m)
: m_mgr{std::move(m)},
cmd(m_mgr->cmd),
data(m_mgr->get_data()) {
}
void reply(int r, const std::stringstream &ss) {
reply(r, ss.str());
}
void reply(int r, const std::string &rs) {
// Let the connection drop as soon as we've sent our response
ConnectionRef con = m_tell ? m_tell->get_connection()
: m_mgr->get_connection();
if (con) {
con->mark_disposable();
}
if (r == 0) {
dout(20) << "success" << dendl;
} else {
derr << __func__ << " " << cpp_strerror(r) << " " << rs << dendl;
}
if (con) {
if (m_tell) {
MCommandReply *reply = new MCommandReply(r, rs);
reply->set_tid(m_tell->get_tid());
reply->set_data(odata);
con->send_message(reply);
} else {
MMgrCommandReply *reply = new MMgrCommandReply(r, rs);
reply->set_tid(m_mgr->get_tid());
reply->set_data(odata);
con->send_message(reply);
}
}
}
};
/**
* A context for receiving a bufferlist/error string from a background
* function and then calling back to a CommandContext when it's done
*/
class ReplyOnFinish : public Context {
std::shared_ptr<CommandContext> cmdctx;
public:
bufferlist from_mon;
string outs;
explicit ReplyOnFinish(const std::shared_ptr<CommandContext> &cmdctx_)
: cmdctx(cmdctx_)
{}
void finish(int r) override {
cmdctx->odata.claim_append(from_mon);
cmdctx->reply(r, outs);
}
};
bool DaemonServer::handle_command(const ref_t<MCommand>& m)
{
std::lock_guard l(lock);
auto cmdctx = std::make_shared<CommandContext>(m);
try {
return _handle_command(cmdctx);
} catch (const bad_cmd_get& e) {
cmdctx->reply(-EINVAL, e.what());
return true;
}
}
bool DaemonServer::handle_command(const ref_t<MMgrCommand>& m)
{
std::lock_guard l(lock);
auto cmdctx = std::make_shared<CommandContext>(m);
try {
return _handle_command(cmdctx);
} catch (const bad_cmd_get& e) {
cmdctx->reply(-EINVAL, e.what());
return true;
}
}
void DaemonServer::log_access_denied(
std::shared_ptr<CommandContext>& cmdctx,
MgrSession* session, std::stringstream& ss) {
dout(1) << " access denied" << dendl;
audit_clog->info() << "from='" << session->inst << "' "
<< "entity='" << session->entity_name << "' "
<< "cmd=" << cmdctx->cmd << ": access denied";
ss << "access denied: does your client key have mgr caps? "
"See http://docs.ceph.com/en/latest/mgr/administrator/"
"#client-authentication";
}
void DaemonServer::_check_offlines_pgs(
const set<int>& osds,
const OSDMap& osdmap,
const PGMap& pgmap,
offline_pg_report *report)
{
// reset output
*report = offline_pg_report();
report->osds = osds;
for (const auto& q : pgmap.pg_stat) {
set<int32_t> pg_acting; // net acting sets (with no missing if degraded)
bool found = false;
if (q.second.state == 0) {
report->unknown.insert(q.first);
continue;
}
if (q.second.state & PG_STATE_DEGRADED) {
for (auto& anm : q.second.avail_no_missing) {
if (osds.count(anm.osd)) {
found = true;
continue;
}
if (anm.osd != CRUSH_ITEM_NONE) {
pg_acting.insert(anm.osd);
}
}
} else {
for (auto& a : q.second.acting) {
if (osds.count(a)) {
found = true;
continue;
}
if (a != CRUSH_ITEM_NONE) {
pg_acting.insert(a);
}
}
}
if (!found) {
continue;
}
const pg_pool_t *pi = osdmap.get_pg_pool(q.first.pool());
bool dangerous = false;
if (!pi) {
report->bad_no_pool.insert(q.first); // pool is creating or deleting
dangerous = true;
}
if (!(q.second.state & PG_STATE_ACTIVE)) {
report->bad_already_inactive.insert(q.first);
dangerous = true;
}
if (pg_acting.size() < pi->min_size) {
report->bad_become_inactive.insert(q.first);
dangerous = true;
}
if (dangerous) {
report->not_ok.insert(q.first);
} else {
report->ok.insert(q.first);
if (q.second.state & PG_STATE_DEGRADED) {
report->ok_become_more_degraded.insert(q.first);
} else {
report->ok_become_degraded.insert(q.first);
}
}
}
dout(20) << osds << " -> " << report->ok.size() << " ok, "
<< report->not_ok.size() << " not ok, "
<< report->unknown.size() << " unknown"
<< dendl;
}
void DaemonServer::_maximize_ok_to_stop_set(
const set<int>& orig_osds,
unsigned max,
const OSDMap& osdmap,
const PGMap& pgmap,
offline_pg_report *out_report)
{
dout(20) << "orig_osds " << orig_osds << " max " << max << dendl;
_check_offlines_pgs(orig_osds, osdmap, pgmap, out_report);
if (!out_report->ok_to_stop()) {
return;
}
if (orig_osds.size() >= max) {
// already at max
return;
}
// semi-arbitrarily start with the first osd in the set
offline_pg_report report;
set<int> osds = orig_osds;
int parent = *osds.begin();
set<int> children;
while (true) {
// identify the next parent
int r = osdmap.crush->get_immediate_parent_id(parent, &parent);
if (r < 0) {
return; // just go with what we have so far!
}
// get candidate additions that are beneath this point in the tree
children.clear();
r = osdmap.crush->get_all_children(parent, &children);
if (r < 0) {
return; // just go with what we have so far!
}
dout(20) << " parent " << parent << " children " << children << dendl;
// try adding in more osds
int failed = 0; // how many children we failed to add to our set
for (auto o : children) {
if (o >= 0 && osdmap.is_up(o) && osds.count(o) == 0) {
osds.insert(o);
_check_offlines_pgs(osds, osdmap, pgmap, &report);
if (!report.ok_to_stop()) {
osds.erase(o);
++failed;
continue;
}
*out_report = report;
if (osds.size() == max) {
dout(20) << " hit max" << dendl;
return; // yay, we hit the max
}
}
}
if (failed) {
// we hit some failures; go with what we have
dout(20) << " hit some peer failures" << dendl;
return;
}
}
}
bool DaemonServer::_handle_command(
std::shared_ptr<CommandContext>& cmdctx)
{
MessageRef m;
bool admin_socket_cmd = false;
if (cmdctx->m_tell) {
m = cmdctx->m_tell;
// a blank fsid in MCommand signals a legacy client sending a "mon-mgr" CLI
// command.
admin_socket_cmd = (cmdctx->m_tell->fsid != uuid_d());
} else {
m = cmdctx->m_mgr;
}
auto priv = m->get_connection()->get_priv();
auto session = static_cast<MgrSession*>(priv.get());
if (!session) {
return true;
}
if (session->inst.name == entity_name_t()) {
session->inst.name = m->get_source();
}
map<string,string> param_str_map;
std::stringstream ss;
int r = 0;
if (!cmdmap_from_json(cmdctx->cmd, &(cmdctx->cmdmap), ss)) {
cmdctx->reply(-EINVAL, ss);
return true;
}
string prefix;
cmd_getval(cmdctx->cmdmap, "prefix", prefix);
dout(10) << "decoded-size=" << cmdctx->cmdmap.size() << " prefix=" << prefix << dendl;
boost::scoped_ptr<Formatter> f;
{
std::string format;
if (boost::algorithm::ends_with(prefix, "_json")) {
format = "json";
} else {
format = cmd_getval_or<string>(cmdctx->cmdmap, "format", "plain");
}
f.reset(Formatter::create(format));
}
// this is just for mgr commands - admin socket commands will fall
// through and use the admin socket version of
// get_command_descriptions
if (prefix == "get_command_descriptions" && !admin_socket_cmd) {
dout(10) << "reading commands from python modules" << dendl;
const auto py_commands = py_modules.get_commands();
int cmdnum = 0;
JSONFormatter f;
f.open_object_section("command_descriptions");
auto dump_cmd = [&cmdnum, &f, m](const MonCommand &mc){
ostringstream secname;
secname << "cmd" << std::setfill('0') << std::setw(3) << cmdnum;
dump_cmddesc_to_json(&f, m->get_connection()->get_features(),
secname.str(), mc.cmdstring, mc.helpstring,
mc.module, mc.req_perms, 0);
cmdnum++;
};
for (const auto &pyc : py_commands) {
dump_cmd(pyc);
}
for (const auto &mgr_cmd : mgr_commands) {
dump_cmd(mgr_cmd);
}
f.close_section(); // command_descriptions
f.flush(cmdctx->odata);
cmdctx->reply(0, ss);
return true;
}
// lookup command
const MonCommand *mgr_cmd = _get_mgrcommand(prefix, mgr_commands);
_generate_command_map(cmdctx->cmdmap, param_str_map);
bool is_allowed = false;
ModuleCommand py_command;
if (admin_socket_cmd) {
// admin socket commands require all capabilities
is_allowed = session->caps.is_allow_all();
} else if (!mgr_cmd) {
// Resolve the command to the name of the module that will
// handle it (if the command exists)
auto py_commands = py_modules.get_py_commands();
for (const auto &pyc : py_commands) {
auto pyc_prefix = cmddesc_get_prefix(pyc.cmdstring);
if (pyc_prefix == prefix) {
py_command = pyc;
break;
}
}
MonCommand pyc = {"", "", "py", py_command.perm};
is_allowed = _allowed_command(session, "py", py_command.module_name,
prefix, cmdctx->cmdmap, param_str_map,
&pyc);
} else {
// validate user's permissions for requested command
is_allowed = _allowed_command(session, mgr_cmd->module, "",
prefix, cmdctx->cmdmap, param_str_map, mgr_cmd);
}
if (!is_allowed) {
log_access_denied(cmdctx, session, ss);
cmdctx->reply(-EACCES, ss);
return true;
}
audit_clog->debug()
<< "from='" << session->inst << "' "
<< "entity='" << session->entity_name << "' "
<< "cmd=" << cmdctx->cmd << ": dispatch";
if (admin_socket_cmd) {
cct->get_admin_socket()->queue_tell_command(cmdctx->m_tell);
return true;
}
// ----------------
// service map commands
if (prefix == "service dump") {
if (!f)
f.reset(Formatter::create("json-pretty"));
cluster_state.with_servicemap([&](const ServiceMap &service_map) {
f->dump_object("service_map", service_map);
});
f->flush(cmdctx->odata);
cmdctx->reply(0, ss);
return true;
}
if (prefix == "service status") {
if (!f)
f.reset(Formatter::create("json-pretty"));
// only include state from services that are in the persisted service map
f->open_object_section("service_status");
for (auto& [type, service] : pending_service_map.services) {
if (ServiceMap::is_normal_ceph_entity(type)) {
continue;
}
f->open_object_section(type.c_str());
for (auto& q : service.daemons) {
f->open_object_section(q.first.c_str());
DaemonKey key{type, q.first};
ceph_assert(daemon_state.exists(key));
auto daemon = daemon_state.get(key);
std::lock_guard l(daemon->lock);
f->dump_stream("status_stamp") << daemon->service_status_stamp;
f->dump_stream("last_beacon") << daemon->last_service_beacon;
f->open_object_section("status");
for (auto& r : daemon->service_status) {
f->dump_string(r.first.c_str(), r.second);
}
f->close_section();
f->close_section();
}
f->close_section();
}
f->close_section();
f->flush(cmdctx->odata);
cmdctx->reply(0, ss);
return true;
}
if (prefix == "config set") {
std::string key;
std::string val;
cmd_getval(cmdctx->cmdmap, "key", key);
cmd_getval(cmdctx->cmdmap, "value", val);
r = cct->_conf.set_val(key, val, &ss);
if (r == 0) {
cct->_conf.apply_changes(nullptr);
}
cmdctx->reply(0, ss);
return true;
}
// -----------
// PG commands
if (prefix == "pg scrub" ||
prefix == "pg repair" ||
prefix == "pg deep-scrub") {
string scrubop = prefix.substr(3, string::npos);
pg_t pgid;
spg_t spgid;
string pgidstr;
cmd_getval(cmdctx->cmdmap, "pgid", pgidstr);
if (!pgid.parse(pgidstr.c_str())) {
ss << "invalid pgid '" << pgidstr << "'";
cmdctx->reply(-EINVAL, ss);
return true;
}
bool pg_exists = false;
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
pg_exists = osdmap.pg_exists(pgid);
});
if (!pg_exists) {
ss << "pg " << pgid << " does not exist";
cmdctx->reply(-ENOENT, ss);
return true;
}
int acting_primary = -1;
epoch_t epoch;
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
epoch = osdmap.get_epoch();
osdmap.get_primary_shard(pgid, &acting_primary, &spgid);
});
if (acting_primary == -1) {
ss << "pg " << pgid << " has no primary osd";
cmdctx->reply(-EAGAIN, ss);
return true;
}
auto p = osd_cons.find(acting_primary);
if (p == osd_cons.end()) {
ss << "pg " << pgid << " primary osd." << acting_primary
<< " is not currently connected";
cmdctx->reply(-EAGAIN, ss);
return true;
}
for (auto& con : p->second) {
assert(HAVE_FEATURE(con->get_features(), SERVER_OCTOPUS));
vector<spg_t> pgs = { spgid };
con->send_message(new MOSDScrub2(monc->get_fsid(),
epoch,
pgs,
scrubop == "repair",
scrubop == "deep-scrub"));
}
ss << "instructing pg " << spgid << " on osd." << acting_primary
<< " to " << scrubop;
cmdctx->reply(0, ss);
return true;
} else if (prefix == "osd scrub" ||
prefix == "osd deep-scrub" ||
prefix == "osd repair") {
string whostr;
cmd_getval(cmdctx->cmdmap, "who", whostr);
vector<string> pvec;
get_str_vec(prefix, pvec);
set<int> osds;
if (whostr == "*" || whostr == "all" || whostr == "any") {
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
for (int i = 0; i < osdmap.get_max_osd(); i++)
if (osdmap.is_up(i)) {
osds.insert(i);
}
});
} else {
long osd = parse_osd_id(whostr.c_str(), &ss);
if (osd < 0) {
ss << "invalid osd '" << whostr << "'";
cmdctx->reply(-EINVAL, ss);
return true;
}
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
if (osdmap.is_up(osd)) {
osds.insert(osd);
}
});
if (osds.empty()) {
ss << "osd." << osd << " is not up";
cmdctx->reply(-EAGAIN, ss);
return true;
}
}
set<int> sent_osds, failed_osds;
for (auto osd : osds) {
vector<spg_t> spgs;
epoch_t epoch;
cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pgmap) {
epoch = osdmap.get_epoch();
auto p = pgmap.pg_by_osd.find(osd);
if (p != pgmap.pg_by_osd.end()) {
for (auto pgid : p->second) {
int primary;
spg_t spg;
osdmap.get_primary_shard(pgid, &primary, &spg);
if (primary == osd) {
spgs.push_back(spg);
}
}
}
});
auto p = osd_cons.find(osd);
if (p == osd_cons.end()) {
failed_osds.insert(osd);
} else {
sent_osds.insert(osd);
for (auto& con : p->second) {
con->send_message(new MOSDScrub2(monc->get_fsid(),
epoch,
spgs,
pvec.back() == "repair",
pvec.back() == "deep-scrub"));
}
}
}
if (failed_osds.size() == osds.size()) {
ss << "failed to instruct osd(s) " << osds << " to " << pvec.back()
<< " (not connected)";
r = -EAGAIN;
} else {
ss << "instructed osd(s) " << sent_osds << " to " << pvec.back();
if (!failed_osds.empty()) {
ss << "; osd(s) " << failed_osds << " were not connected";
}
r = 0;
}
cmdctx->reply(0, ss);
return true;
} else if (prefix == "osd pool scrub" ||
prefix == "osd pool deep-scrub" ||
prefix == "osd pool repair") {
vector<string> pool_names;
cmd_getval(cmdctx->cmdmap, "who", pool_names);
if (pool_names.empty()) {
ss << "must specify one or more pool names";
cmdctx->reply(-EINVAL, ss);
return true;
}
epoch_t epoch;
map<int32_t, vector<pg_t>> pgs_by_primary; // legacy
map<int32_t, vector<spg_t>> spgs_by_primary;
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
epoch = osdmap.get_epoch();
for (auto& pool_name : pool_names) {
auto pool_id = osdmap.lookup_pg_pool_name(pool_name);
if (pool_id < 0) {
ss << "unrecognized pool '" << pool_name << "'";
r = -ENOENT;
return;
}
auto pool_pg_num = osdmap.get_pg_num(pool_id);
for (int i = 0; i < pool_pg_num; i++) {
pg_t pg(i, pool_id);
int primary;
spg_t spg;
auto got = osdmap.get_primary_shard(pg, &primary, &spg);
if (!got)
continue;
pgs_by_primary[primary].push_back(pg);
spgs_by_primary[primary].push_back(spg);
}
}
});
if (r < 0) {
cmdctx->reply(r, ss);
return true;
}
for (auto& it : spgs_by_primary) {
auto primary = it.first;
auto p = osd_cons.find(primary);
if (p == osd_cons.end()) {
ss << "osd." << primary << " is not currently connected";
cmdctx->reply(-EAGAIN, ss);
return true;
}
for (auto& con : p->second) {
con->send_message(new MOSDScrub2(monc->get_fsid(),
epoch,
it.second,
prefix == "osd pool repair",
prefix == "osd pool deep-scrub"));
}
}
cmdctx->reply(0, "");
return true;
} else if (prefix == "osd reweight-by-pg" ||
prefix == "osd reweight-by-utilization" ||
prefix == "osd test-reweight-by-pg" ||
prefix == "osd test-reweight-by-utilization") {
bool by_pg =
prefix == "osd reweight-by-pg" || prefix == "osd test-reweight-by-pg";
bool dry_run =
prefix == "osd test-reweight-by-pg" ||
prefix == "osd test-reweight-by-utilization";
int64_t oload = cmd_getval_or<int64_t>(cmdctx->cmdmap, "oload", 120);
set<int64_t> pools;
vector<string> poolnames;
cmd_getval(cmdctx->cmdmap, "pools", poolnames);
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
for (const auto& poolname : poolnames) {
int64_t pool = osdmap.lookup_pg_pool_name(poolname);
if (pool < 0) {
ss << "pool '" << poolname << "' does not exist";
r = -ENOENT;
}
pools.insert(pool);
}
});
if (r) {
cmdctx->reply(r, ss);
return true;
}
double max_change = g_conf().get_val<double>("mon_reweight_max_change");
cmd_getval(cmdctx->cmdmap, "max_change", max_change);
if (max_change <= 0.0) {
ss << "max_change " << max_change << " must be positive";
cmdctx->reply(-EINVAL, ss);
return true;
}
int64_t max_osds = g_conf().get_val<int64_t>("mon_reweight_max_osds");
cmd_getval(cmdctx->cmdmap, "max_osds", max_osds);
if (max_osds <= 0) {
ss << "max_osds " << max_osds << " must be positive";
cmdctx->reply(-EINVAL, ss);
return true;
}
bool no_increasing = false;
cmd_getval_compat_cephbool(cmdctx->cmdmap, "no_increasing", no_increasing);
string out_str;
mempool::osdmap::map<int32_t, uint32_t> new_weights;
r = cluster_state.with_osdmap_and_pgmap([&](const OSDMap &osdmap, const PGMap& pgmap) {
return reweight::by_utilization(osdmap, pgmap,
oload,
max_change,
max_osds,
by_pg,
pools.empty() ? NULL : &pools,
no_increasing,
&new_weights,
&ss, &out_str, f.get());
});
if (r >= 0) {
dout(10) << "reweight::by_utilization: finished with " << out_str << dendl;
}
if (f) {
f->flush(cmdctx->odata);
} else {
cmdctx->odata.append(out_str);
}
if (r < 0) {
ss << "FAILED reweight-by-pg";
cmdctx->reply(r, ss);
return true;
} else if (r == 0 || dry_run) {
ss << "no change";
cmdctx->reply(r, ss);
return true;
} else {
json_spirit::Object json_object;
for (const auto& osd_weight : new_weights) {
json_spirit::Config::add(json_object,
std::to_string(osd_weight.first),
std::to_string(osd_weight.second));
}
string s = json_spirit::write(json_object);
std::replace(begin(s), end(s), '\"', '\'');
const string cmd =
"{"
"\"prefix\": \"osd reweightn\", "
"\"weights\": \"" + s + "\""
"}";
auto on_finish = new ReplyOnFinish(cmdctx);
monc->start_mon_command({cmd}, {},
&on_finish->from_mon, &on_finish->outs, on_finish);
return true;
}
} else if (prefix == "osd df") {
string method, filter;
cmd_getval(cmdctx->cmdmap, "output_method", method);
cmd_getval(cmdctx->cmdmap, "filter", filter);
stringstream rs;
r = cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pgmap) {
// sanity check filter(s)
if (!filter.empty() &&
osdmap.lookup_pg_pool_name(filter) < 0 &&
!osdmap.crush->class_exists(filter) &&
!osdmap.crush->name_exists(filter)) {
rs << "'" << filter << "' not a pool, crush node or device class name";
return -EINVAL;
}
print_osd_utilization(osdmap, pgmap, ss,
f.get(), method == "tree", filter);
cmdctx->odata.append(ss);
return 0;
});
cmdctx->reply(r, rs);
return true;
} else if (prefix == "osd pool stats") {
string pool_name;
cmd_getval(cmdctx->cmdmap, "pool_name", pool_name);
int64_t poolid = -ENOENT;
bool one_pool = false;
r = cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pg_map) {
if (!pool_name.empty()) {
poolid = osdmap.lookup_pg_pool_name(pool_name);
if (poolid < 0) {
ceph_assert(poolid == -ENOENT);
ss << "unrecognized pool '" << pool_name << "'";
return -ENOENT;
}
one_pool = true;
}
stringstream rs;
if (f)
f->open_array_section("pool_stats");
else {
if (osdmap.get_pools().empty()) {
ss << "there are no pools!";
goto stats_out;
}
}
for (auto &p : osdmap.get_pools()) {
if (!one_pool) {
poolid = p.first;
}
pg_map.dump_pool_stats_and_io_rate(poolid, osdmap, f.get(), &rs);
if (one_pool) {
break;
}
}
stats_out:
if (f) {
f->close_section();
f->flush(cmdctx->odata);
} else {
cmdctx->odata.append(rs.str());
}
return 0;
});
if (r != -EOPNOTSUPP) {
cmdctx->reply(r, ss);
return true;
}
} else if (prefix == "osd safe-to-destroy" ||
prefix == "osd destroy" ||
prefix == "osd purge") {
set<int> osds;
int r = 0;
if (prefix == "osd safe-to-destroy") {
vector<string> ids;
cmd_getval(cmdctx->cmdmap, "ids", ids);
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
r = osdmap.parse_osd_id_list(ids, &osds, &ss);
});
if (!r && osds.empty()) {
ss << "must specify one or more OSDs";
r = -EINVAL;
}
} else {
int64_t id;
if (!cmd_getval(cmdctx->cmdmap, "id", id)) {
r = -EINVAL;
ss << "must specify OSD id";
} else {
osds.insert(id);
}
}
if (r < 0) {
cmdctx->reply(r, ss);
return true;
}
set<int> active_osds, missing_stats, stored_pgs, safe_to_destroy;
int affected_pgs = 0;
cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pg_map) {
if (pg_map.num_pg_unknown > 0) {
ss << pg_map.num_pg_unknown << " pgs have unknown state; cannot draw"
<< " any conclusions";
r = -EAGAIN;
return;
}
int num_active_clean = 0;
for (auto& p : pg_map.num_pg_by_state) {
unsigned want = PG_STATE_ACTIVE|PG_STATE_CLEAN;
if ((p.first & want) == want) {
num_active_clean += p.second;
}
}
for (auto osd : osds) {
if (!osdmap.exists(osd)) {
safe_to_destroy.insert(osd);
continue; // clearly safe to destroy
}
auto q = pg_map.num_pg_by_osd.find(osd);
if (q != pg_map.num_pg_by_osd.end()) {
if (q->second.acting > 0 || q->second.up_not_acting > 0) {
active_osds.insert(osd);
// XXX: For overlapping PGs, this counts them again
affected_pgs += q->second.acting + q->second.up_not_acting;
continue;
}
}
if (num_active_clean < pg_map.num_pg) {
// all pgs aren't active+clean; we need to be careful.
auto p = pg_map.osd_stat.find(osd);
if (p == pg_map.osd_stat.end() || !osdmap.is_up(osd)) {
missing_stats.insert(osd);
continue;
} else if (p->second.num_pgs > 0) {
stored_pgs.insert(osd);
continue;
}
}
safe_to_destroy.insert(osd);
}
});
if (r && prefix == "osd safe-to-destroy") {
cmdctx->reply(r, ss); // regardless of formatter
return true;
}
if (!r && (!active_osds.empty() ||
!missing_stats.empty() || !stored_pgs.empty())) {
if (!safe_to_destroy.empty()) {
ss << "OSD(s) " << safe_to_destroy
<< " are safe to destroy without reducing data durability. ";
}
if (!active_osds.empty()) {
ss << "OSD(s) " << active_osds << " have " << affected_pgs
<< " pgs currently mapped to them. ";
}
if (!missing_stats.empty()) {
ss << "OSD(s) " << missing_stats << " have no reported stats, and not all"
<< " PGs are active+clean; we cannot draw any conclusions. ";
}
if (!stored_pgs.empty()) {
ss << "OSD(s) " << stored_pgs << " last reported they still store some PG"
<< " data, and not all PGs are active+clean; we cannot be sure they"
<< " aren't still needed.";
}
if (!active_osds.empty() || !stored_pgs.empty()) {
r = -EBUSY;
} else {
r = -EAGAIN;
}
}
if (prefix == "osd safe-to-destroy") {
if (!r) {
ss << "OSD(s) " << osds << " are safe to destroy without reducing data"
<< " durability.";
}
if (f) {
f->open_object_section("osd_status");
f->open_array_section("safe_to_destroy");
for (auto i : safe_to_destroy)
f->dump_int("osd", i);
f->close_section();
f->open_array_section("active");
for (auto i : active_osds)
f->dump_int("osd", i);
f->close_section();
f->open_array_section("missing_stats");
for (auto i : missing_stats)
f->dump_int("osd", i);
f->close_section();
f->open_array_section("stored_pgs");
for (auto i : stored_pgs)
f->dump_int("osd", i);
f->close_section();
f->close_section(); // osd_status
f->flush(cmdctx->odata);
r = 0;
std::stringstream().swap(ss);
}
cmdctx->reply(r, ss);
return true;
}
if (r) {
bool force = false;
cmd_getval(cmdctx->cmdmap, "force", force);
if (!force) {
// Backward compat
cmd_getval(cmdctx->cmdmap, "yes_i_really_mean_it", force);
}
if (!force) {
ss << "\nYou can proceed by passing --force, but be warned that"
" this will likely mean real, permanent data loss.";
} else {
r = 0;
}
}
if (r) {
cmdctx->reply(r, ss);
return true;
}
const string cmd =
"{"
"\"prefix\": \"" + prefix + "-actual\", "
"\"id\": " + stringify(osds) + ", "
"\"yes_i_really_mean_it\": true"
"}";
auto on_finish = new ReplyOnFinish(cmdctx);
monc->start_mon_command({cmd}, {}, nullptr, &on_finish->outs, on_finish);
return true;
} else if (prefix == "osd ok-to-stop") {
vector<string> ids;
cmd_getval(cmdctx->cmdmap, "ids", ids);
set<int> osds;
int64_t max = 1;
cmd_getval(cmdctx->cmdmap, "max", max);
int r;
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
r = osdmap.parse_osd_id_list(ids, &osds, &ss);
});
if (!r && osds.empty()) {
ss << "must specify one or more OSDs";
r = -EINVAL;
}
if (max < (int)osds.size()) {
max = osds.size();
}
if (r < 0) {
cmdctx->reply(r, ss);
return true;
}
offline_pg_report out_report;
cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pg_map) {
_maximize_ok_to_stop_set(
osds, max, osdmap, pg_map,
&out_report);
});
if (!f) {
f.reset(Formatter::create("json"));
}
f->dump_object("ok_to_stop", out_report);
f->flush(cmdctx->odata);
cmdctx->odata.append("\n");
if (!out_report.unknown.empty()) {
ss << out_report.unknown.size() << " pgs have unknown state; "
<< "cannot draw any conclusions";
cmdctx->reply(-EAGAIN, ss);
}
if (!out_report.ok_to_stop()) {
ss << "unsafe to stop osd(s) at this time (" << out_report.not_ok.size() << " PGs are or would become offline)";
cmdctx->reply(-EBUSY, ss);
} else {
cmdctx->reply(0, ss);
}
return true;
} else if (prefix == "pg force-recovery" ||
prefix == "pg force-backfill" ||
prefix == "pg cancel-force-recovery" ||
prefix == "pg cancel-force-backfill" ||
prefix == "osd pool force-recovery" ||
prefix == "osd pool force-backfill" ||
prefix == "osd pool cancel-force-recovery" ||
prefix == "osd pool cancel-force-backfill") {
vector<string> vs;
get_str_vec(prefix, vs);
auto& granularity = vs.front();
auto& forceop = vs.back();
vector<pg_t> pgs;
// figure out actual op just once
int actual_op = 0;
if (forceop == "force-recovery") {
actual_op = OFR_RECOVERY;
} else if (forceop == "force-backfill") {
actual_op = OFR_BACKFILL;
} else if (forceop == "cancel-force-backfill") {
actual_op = OFR_BACKFILL | OFR_CANCEL;
} else if (forceop == "cancel-force-recovery") {
actual_op = OFR_RECOVERY | OFR_CANCEL;
}
set<pg_t> candidates; // deduped
if (granularity == "pg") {
// covnert pg names to pgs, discard any invalid ones while at it
vector<string> pgids;
cmd_getval(cmdctx->cmdmap, "pgid", pgids);
for (auto& i : pgids) {
pg_t pgid;
if (!pgid.parse(i.c_str())) {
ss << "invlaid pgid '" << i << "'; ";
r = -EINVAL;
continue;
}
candidates.insert(pgid);
}
} else {
// per pool
vector<string> pool_names;
cmd_getval(cmdctx->cmdmap, "who", pool_names);
if (pool_names.empty()) {
ss << "must specify one or more pool names";
cmdctx->reply(-EINVAL, ss);
return true;
}
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
for (auto& pool_name : pool_names) {
auto pool_id = osdmap.lookup_pg_pool_name(pool_name);
if (pool_id < 0) {
ss << "unrecognized pool '" << pool_name << "'";
r = -ENOENT;
return;
}
auto pool_pg_num = osdmap.get_pg_num(pool_id);
for (int i = 0; i < pool_pg_num; i++)
candidates.insert({(unsigned int)i, (uint64_t)pool_id});
}
});
if (r < 0) {
cmdctx->reply(r, ss);
return true;
}
}
cluster_state.with_pgmap([&](const PGMap& pg_map) {
for (auto& i : candidates) {
auto it = pg_map.pg_stat.find(i);
if (it == pg_map.pg_stat.end()) {
ss << "pg " << i << " does not exist; ";
r = -ENOENT;
continue;
}
auto state = it->second.state;
// discard pgs for which user requests are pointless
switch (actual_op) {
case OFR_RECOVERY:
if ((state & (PG_STATE_DEGRADED |
PG_STATE_RECOVERY_WAIT |
PG_STATE_RECOVERING)) == 0) {
// don't return error, user script may be racing with cluster.
// not fatal.
ss << "pg " << i << " doesn't require recovery; ";
continue;
} else if (state & PG_STATE_FORCED_RECOVERY) {
ss << "pg " << i << " recovery already forced; ";
// return error, as it may be a bug in user script
r = -EINVAL;
continue;
}
break;
case OFR_BACKFILL:
if ((state & (PG_STATE_DEGRADED |
PG_STATE_BACKFILL_WAIT |
PG_STATE_BACKFILLING)) == 0) {
ss << "pg " << i << " doesn't require backfilling; ";
continue;
} else if (state & PG_STATE_FORCED_BACKFILL) {
ss << "pg " << i << " backfill already forced; ";
r = -EINVAL;
continue;
}
break;
case OFR_BACKFILL | OFR_CANCEL:
if ((state & PG_STATE_FORCED_BACKFILL) == 0) {
ss << "pg " << i << " backfill not forced; ";
continue;
}
break;
case OFR_RECOVERY | OFR_CANCEL:
if ((state & PG_STATE_FORCED_RECOVERY) == 0) {
ss << "pg " << i << " recovery not forced; ";
continue;
}
break;
default:
ceph_abort_msg("actual_op value is not supported");
}
pgs.push_back(i);
} // for
});
// respond with error only when no pgs are correct
// yes, in case of mixed errors, only the last one will be emitted,
// but the message presented will be fine
if (pgs.size() != 0) {
// clear error to not confuse users/scripts
r = 0;
}
// optimize the command -> messages conversion, use only one
// message per distinct OSD
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
// group pgs to process by osd
map<int, vector<spg_t>> osdpgs;
for (auto& pgid : pgs) {
int primary;
spg_t spg;
if (osdmap.get_primary_shard(pgid, &primary, &spg)) {
osdpgs[primary].push_back(spg);
}
}
for (auto& i : osdpgs) {
if (osdmap.is_up(i.first)) {
auto p = osd_cons.find(i.first);
if (p == osd_cons.end()) {
ss << "osd." << i.first << " is not currently connected";
r = -EAGAIN;
continue;
}
for (auto& con : p->second) {
con->send_message(
new MOSDForceRecovery(monc->get_fsid(), i.second, actual_op));
}
ss << "instructing pg(s) " << i.second << " on osd." << i.first
<< " to " << forceop << "; ";
}
}
});
ss << std::endl;
cmdctx->reply(r, ss);
return true;
} else if (prefix == "config show" ||
prefix == "config show-with-defaults") {
string who;
cmd_getval(cmdctx->cmdmap, "who", who);
auto [key, valid] = DaemonKey::parse(who);
if (!valid) {
ss << "invalid daemon name: use <type>.<id>";
cmdctx->reply(-EINVAL, ss);
return true;
}
DaemonStatePtr daemon = daemon_state.get(key);
if (!daemon) {
ss << "no config state for daemon " << who;
cmdctx->reply(-ENOENT, ss);
return true;
}
std::lock_guard l(daemon->lock);
int r = 0;
string name;
if (cmd_getval(cmdctx->cmdmap, "key", name)) {
// handle special options
if (name == "fsid") {
cmdctx->odata.append(stringify(monc->get_fsid()) + "\n");
cmdctx->reply(r, ss);
return true;
}
auto p = daemon->config.find(name);
if (p != daemon->config.end() &&
!p->second.empty()) {
cmdctx->odata.append(p->second.rbegin()->second + "\n");
} else {
auto& defaults = daemon->_get_config_defaults();
auto q = defaults.find(name);
if (q != defaults.end()) {
cmdctx->odata.append(q->second + "\n");
} else {
r = -ENOENT;
}
}
} else if (daemon->config_defaults_bl.length() > 0) {
TextTable tbl;
if (f) {
f->open_array_section("config");
} else {
tbl.define_column("NAME", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("VALUE", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("SOURCE", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("OVERRIDES", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("IGNORES", TextTable::LEFT, TextTable::LEFT);
}
if (prefix == "config show") {
// show
for (auto& i : daemon->config) {
dout(20) << " " << i.first << " -> " << i.second << dendl;
if (i.second.empty()) {
continue;
}
if (f) {
f->open_object_section("value");
f->dump_string("name", i.first);
f->dump_string("value", i.second.rbegin()->second);
f->dump_string("source", ceph_conf_level_name(
i.second.rbegin()->first));
if (i.second.size() > 1) {
f->open_array_section("overrides");
auto j = i.second.rend();
for (--j; j != i.second.rbegin(); --j) {
f->open_object_section("value");
f->dump_string("source", ceph_conf_level_name(j->first));
f->dump_string("value", j->second);
f->close_section();
}
f->close_section();
}
if (daemon->ignored_mon_config.count(i.first)) {
f->dump_string("ignores", "mon");
}
f->close_section();
} else {
tbl << i.first;
tbl << i.second.rbegin()->second;
tbl << ceph_conf_level_name(i.second.rbegin()->first);
if (i.second.size() > 1) {
list<string> ov;
auto j = i.second.rend();
for (--j; j != i.second.rbegin(); --j) {
if (j->second == i.second.rbegin()->second) {
ov.push_front(string("(") + ceph_conf_level_name(j->first) +
string("[") + j->second + string("]") +
string(")"));
} else {
ov.push_front(ceph_conf_level_name(j->first) +
string("[") + j->second + string("]"));
}
}
tbl << ov;
} else {
tbl << "";
}
tbl << (daemon->ignored_mon_config.count(i.first) ? "mon" : "");
tbl << TextTable::endrow;
}
}
} else {
// show-with-defaults
auto& defaults = daemon->_get_config_defaults();
for (auto& i : defaults) {
if (f) {
f->open_object_section("value");
f->dump_string("name", i.first);
} else {
tbl << i.first;
}
auto j = daemon->config.find(i.first);
if (j != daemon->config.end() && !j->second.empty()) {
// have config
if (f) {
f->dump_string("value", j->second.rbegin()->second);
f->dump_string("source", ceph_conf_level_name(
j->second.rbegin()->first));
if (j->second.size() > 1) {
f->open_array_section("overrides");
auto k = j->second.rend();
for (--k; k != j->second.rbegin(); --k) {
f->open_object_section("value");
f->dump_string("source", ceph_conf_level_name(k->first));
f->dump_string("value", k->second);
f->close_section();
}
f->close_section();
}
if (daemon->ignored_mon_config.count(i.first)) {
f->dump_string("ignores", "mon");
}
f->close_section();
} else {
tbl << j->second.rbegin()->second;
tbl << ceph_conf_level_name(j->second.rbegin()->first);
if (j->second.size() > 1) {
list<string> ov;
auto k = j->second.rend();
for (--k; k != j->second.rbegin(); --k) {
if (k->second == j->second.rbegin()->second) {
ov.push_front(string("(") + ceph_conf_level_name(k->first) +
string("[") + k->second + string("]") +
string(")"));
} else {
ov.push_front(ceph_conf_level_name(k->first) +
string("[") + k->second + string("]"));
}
}
tbl << ov;
} else {
tbl << "";
}
tbl << (daemon->ignored_mon_config.count(i.first) ? "mon" : "");
tbl << TextTable::endrow;
}
} else {
// only have default
if (f) {
f->dump_string("value", i.second);
f->dump_string("source", ceph_conf_level_name(CONF_DEFAULT));
f->close_section();
} else {
tbl << i.second;
tbl << ceph_conf_level_name(CONF_DEFAULT);
tbl << "";
tbl << "";
tbl << TextTable::endrow;
}
}
}
}
if (f) {
f->close_section();
f->flush(cmdctx->odata);
} else {
cmdctx->odata.append(stringify(tbl));
}
}
cmdctx->reply(r, ss);
return true;
} else if (prefix == "device ls") {
set<string> devids;
TextTable tbl;
if (f) {
f->open_array_section("devices");
daemon_state.with_devices([&f](const DeviceState& dev) {
f->dump_object("device", dev);
});
f->close_section();
f->flush(cmdctx->odata);
} else {
tbl.define_column("DEVICE", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("HOST:DEV", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("DAEMONS", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("WEAR", TextTable::RIGHT, TextTable::RIGHT);
tbl.define_column("LIFE EXPECTANCY", TextTable::LEFT, TextTable::LEFT);
auto now = ceph_clock_now();
daemon_state.with_devices([&tbl, now](const DeviceState& dev) {
string h;
for (auto& i : dev.attachments) {
if (h.size()) {
h += " ";
}
h += std::get<0>(i) + ":" + std::get<1>(i);
}
string d;
for (auto& i : dev.daemons) {
if (d.size()) {
d += " ";
}
d += to_string(i);
}
char wear_level_str[16] = {0};
if (dev.wear_level >= 0) {
snprintf(wear_level_str, sizeof(wear_level_str)-1, "%d%%",
(int)(100.1 * dev.wear_level));
}
tbl << dev.devid
<< h
<< d
<< wear_level_str
<< dev.get_life_expectancy_str(now)
<< TextTable::endrow;
});
cmdctx->odata.append(stringify(tbl));
}
cmdctx->reply(0, ss);
return true;
} else if (prefix == "device ls-by-daemon") {
string who;
cmd_getval(cmdctx->cmdmap, "who", who);
if (auto [k, valid] = DaemonKey::parse(who); !valid) {
ss << who << " is not a valid daemon name";
r = -EINVAL;
} else {
auto dm = daemon_state.get(k);
if (dm) {
if (f) {
f->open_array_section("devices");
for (auto& i : dm->devices) {
daemon_state.with_device(i.first, [&f] (const DeviceState& dev) {
f->dump_object("device", dev);
});
}
f->close_section();
f->flush(cmdctx->odata);
} else {
TextTable tbl;
tbl.define_column("DEVICE", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("HOST:DEV", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("EXPECTED FAILURE", TextTable::LEFT,
TextTable::LEFT);
auto now = ceph_clock_now();
for (auto& i : dm->devices) {
daemon_state.with_device(
i.first, [&tbl, now] (const DeviceState& dev) {
string h;
for (auto& i : dev.attachments) {
if (h.size()) {
h += " ";
}
h += std::get<0>(i) + ":" + std::get<1>(i);
}
tbl << dev.devid
<< h
<< dev.get_life_expectancy_str(now)
<< TextTable::endrow;
});
}
cmdctx->odata.append(stringify(tbl));
}
} else {
r = -ENOENT;
ss << "daemon " << who << " not found";
}
cmdctx->reply(r, ss);
}
} else if (prefix == "device ls-by-host") {
string host;
cmd_getval(cmdctx->cmdmap, "host", host);
set<string> devids;
daemon_state.list_devids_by_server(host, &devids);
if (f) {
f->open_array_section("devices");
for (auto& devid : devids) {
daemon_state.with_device(
devid, [&f] (const DeviceState& dev) {
f->dump_object("device", dev);
});
}
f->close_section();
f->flush(cmdctx->odata);
} else {
TextTable tbl;
tbl.define_column("DEVICE", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("DEV", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("DAEMONS", TextTable::LEFT, TextTable::LEFT);
tbl.define_column("EXPECTED FAILURE", TextTable::LEFT, TextTable::LEFT);
auto now = ceph_clock_now();
for (auto& devid : devids) {
daemon_state.with_device(
devid, [&tbl, &host, now] (const DeviceState& dev) {
string n;
for (auto& j : dev.attachments) {
if (std::get<0>(j) == host) {
if (n.size()) {
n += " ";
}
n += std::get<1>(j);
}
}
string d;
for (auto& i : dev.daemons) {
if (d.size()) {
d += " ";
}
d += to_string(i);
}
tbl << dev.devid
<< n
<< d
<< dev.get_life_expectancy_str(now)
<< TextTable::endrow;
});
}
cmdctx->odata.append(stringify(tbl));
}
cmdctx->reply(0, ss);
return true;
} else if (prefix == "device info") {
string devid;
cmd_getval(cmdctx->cmdmap, "devid", devid);
int r = 0;
ostringstream rs;
if (!daemon_state.with_device(devid,
[&f, &rs] (const DeviceState& dev) {
if (f) {
f->dump_object("device", dev);
} else {
dev.print(rs);
}
})) {
ss << "device " << devid << " not found";
r = -ENOENT;
} else {
if (f) {
f->flush(cmdctx->odata);
} else {
cmdctx->odata.append(rs.str());
}
}
cmdctx->reply(r, ss);
return true;
} else if (prefix == "device set-life-expectancy") {
string devid;
cmd_getval(cmdctx->cmdmap, "devid", devid);
string from_str, to_str;
cmd_getval(cmdctx->cmdmap, "from", from_str);
cmd_getval(cmdctx->cmdmap, "to", to_str);
utime_t from, to;
if (!from.parse(from_str)) {
ss << "unable to parse datetime '" << from_str << "'";
r = -EINVAL;
cmdctx->reply(r, ss);
} else if (to_str.size() && !to.parse(to_str)) {
ss << "unable to parse datetime '" << to_str << "'";
r = -EINVAL;
cmdctx->reply(r, ss);
} else {
map<string,string> meta;
daemon_state.with_device_create(
devid,
[from, to, &meta] (DeviceState& dev) {
dev.set_life_expectancy(from, to, ceph_clock_now());
meta = dev.metadata;
});
json_spirit::Object json_object;
for (auto& i : meta) {
json_spirit::Config::add(json_object, i.first, i.second);
}
bufferlist json;
json.append(json_spirit::write(json_object));
const string cmd =
"{"
"\"prefix\": \"config-key set\", "
"\"key\": \"device/" + devid + "\""
"}";
auto on_finish = new ReplyOnFinish(cmdctx);
monc->start_mon_command({cmd}, json, nullptr, nullptr, on_finish);
}
return true;
} else if (prefix == "device rm-life-expectancy") {
string devid;
cmd_getval(cmdctx->cmdmap, "devid", devid);
map<string,string> meta;
if (daemon_state.with_device_write(devid, [&meta] (DeviceState& dev) {
dev.rm_life_expectancy();
meta = dev.metadata;
})) {
string cmd;
bufferlist json;
if (meta.empty()) {
cmd =
"{"
"\"prefix\": \"config-key rm\", "
"\"key\": \"device/" + devid + "\""
"}";
} else {
json_spirit::Object json_object;
for (auto& i : meta) {
json_spirit::Config::add(json_object, i.first, i.second);
}
json.append(json_spirit::write(json_object));
cmd =
"{"
"\"prefix\": \"config-key set\", "
"\"key\": \"device/" + devid + "\""
"}";
}
auto on_finish = new ReplyOnFinish(cmdctx);
monc->start_mon_command({cmd}, json, nullptr, nullptr, on_finish);
} else {
cmdctx->reply(0, ss);
}
return true;
} else {
if (!pgmap_ready) {
ss << "Warning: due to ceph-mgr restart, some PG states may not be up to date\n";
}
if (f) {
f->open_object_section("pg_info");
f->dump_bool("pg_ready", pgmap_ready);
}
// fall back to feeding command to PGMap
r = cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pg_map) {
return process_pg_map_command(prefix, cmdctx->cmdmap, pg_map, osdmap,
f.get(), &ss, &cmdctx->odata);
});
if (f) {
f->close_section();
}
if (r != -EOPNOTSUPP) {
if (f) {
f->flush(cmdctx->odata);
}
cmdctx->reply(r, ss);
return true;
}
}
// Was the command unfound?
if (py_command.cmdstring.empty()) {
ss << "No handler found for '" << prefix << "'";
dout(4) << "No handler found for '" << prefix << "'" << dendl;
cmdctx->reply(-EINVAL, ss);
return true;
}
// Validate that the module is active
auto& mod_name = py_command.module_name;
if (!py_modules.is_module_active(mod_name)) {
ss << "Module '" << mod_name << "' is not enabled/loaded (required by "
"command '" << prefix << "'): use `ceph mgr module enable "
<< mod_name << "` to enable it";
dout(4) << ss.str() << dendl;
cmdctx->reply(-EOPNOTSUPP, ss);
return true;
}
dout(10) << "passing through command '" << prefix << "' size " << cmdctx->cmdmap.size() << dendl;
Finisher& mod_finisher = py_modules.get_active_module_finisher(mod_name);
mod_finisher.queue(new LambdaContext([this, cmdctx, session, py_command, prefix]
(int r_) mutable {
std::stringstream ss;
dout(10) << "dispatching command '" << prefix << "' size " << cmdctx->cmdmap.size() << dendl;
// Validate that the module is enabled
auto& py_handler_name = py_command.module_name;
PyModuleRef module = py_modules.get_module(py_handler_name);
ceph_assert(module);
if (!module->is_enabled()) {
ss << "Module '" << py_handler_name << "' is not enabled (required by "
"command '" << prefix << "'): use `ceph mgr module enable "
<< py_handler_name << "` to enable it";
dout(4) << ss.str() << dendl;
cmdctx->reply(-EOPNOTSUPP, ss);
return;
}
// Hack: allow the self-test method to run on unhealthy modules.
// Fix this in future by creating a special path for self test rather
// than having the hook be a normal module command.
std::string self_test_prefix = py_handler_name + " " + "self-test";
// Validate that the module is healthy
bool accept_command;
if (module->is_loaded()) {
if (module->get_can_run() && !module->is_failed()) {
// Healthy module
accept_command = true;
} else if (self_test_prefix == prefix) {
// Unhealthy, but allow because it's a self test command
accept_command = true;
} else {
accept_command = false;
ss << "Module '" << py_handler_name << "' has experienced an error and "
"cannot handle commands: " << module->get_error_string();
}
} else {
// Module not loaded
accept_command = false;
ss << "Module '" << py_handler_name << "' failed to load and "
"cannot handle commands: " << module->get_error_string();
}
if (!accept_command) {
dout(4) << ss.str() << dendl;
cmdctx->reply(-EIO, ss);
return;
}
std::stringstream ds;
bufferlist inbl = cmdctx->data;
int r = py_modules.handle_command(py_command, *session, cmdctx->cmdmap,
inbl, &ds, &ss);
if (r == -EACCES) {
log_access_denied(cmdctx, session, ss);
}
cmdctx->odata.append(ds);
cmdctx->reply(r, ss);
dout(10) << " command returned " << r << dendl;
}));
return true;
}
void DaemonServer::_prune_pending_service_map()
{
utime_t cutoff = ceph_clock_now();
cutoff -= g_conf().get_val<double>("mgr_service_beacon_grace");
auto p = pending_service_map.services.begin();
while (p != pending_service_map.services.end()) {
auto q = p->second.daemons.begin();
while (q != p->second.daemons.end()) {
DaemonKey key{p->first, q->first};
if (!daemon_state.exists(key)) {
if (ServiceMap::is_normal_ceph_entity(p->first)) {
dout(10) << "daemon " << key << " in service map but not in daemon state "
<< "index -- force pruning" << dendl;
q = p->second.daemons.erase(q);
pending_service_map_dirty = pending_service_map.epoch;
} else {
derr << "missing key " << key << dendl;
++q;
}
continue;
}
auto daemon = daemon_state.get(key);
std::lock_guard l(daemon->lock);
if (daemon->last_service_beacon == utime_t()) {
// we must have just restarted; assume they are alive now.
daemon->last_service_beacon = ceph_clock_now();
++q;
continue;
}
if (daemon->last_service_beacon < cutoff) {
dout(10) << "pruning stale " << p->first << "." << q->first
<< " last_beacon " << daemon->last_service_beacon << dendl;
q = p->second.daemons.erase(q);
pending_service_map_dirty = pending_service_map.epoch;
} else {
++q;
}
}
if (p->second.daemons.empty()) {
p = pending_service_map.services.erase(p);
pending_service_map_dirty = pending_service_map.epoch;
} else {
++p;
}
}
}
void DaemonServer::send_report()
{
if (!pgmap_ready) {
if (ceph_clock_now() - started_at > g_conf().get_val<int64_t>("mgr_stats_period") * 4.0) {
pgmap_ready = true;
reported_osds.clear();
dout(1) << "Giving up on OSDs that haven't reported yet, sending "
<< "potentially incomplete PG state to mon" << dendl;
} else {
dout(1) << "Not sending PG status to monitor yet, waiting for OSDs"
<< dendl;
return;
}
}
auto m = ceph::make_message<MMonMgrReport>();
m->gid = monc->get_global_id();
py_modules.get_health_checks(&m->health_checks);
py_modules.get_progress_events(&m->progress_events);
cluster_state.with_mutable_pgmap([&](PGMap& pg_map) {
cluster_state.update_delta_stats();
if (pending_service_map.epoch) {
_prune_pending_service_map();
if (pending_service_map_dirty >= pending_service_map.epoch) {
pending_service_map.modified = ceph_clock_now();
encode(pending_service_map, m->service_map_bl, CEPH_FEATURES_ALL);
dout(10) << "sending service_map e" << pending_service_map.epoch
<< dendl;
pending_service_map.epoch++;
}
}
cluster_state.with_osdmap([&](const OSDMap& osdmap) {
// FIXME: no easy way to get mon features here. this will do for
// now, though, as long as we don't make a backward-incompat change.
pg_map.encode_digest(osdmap, m->get_data(), CEPH_FEATURES_ALL);
dout(10) << pg_map << dendl;
pg_map.get_health_checks(g_ceph_context, osdmap,
&m->health_checks);
dout(10) << m->health_checks.checks.size() << " health checks"
<< dendl;
dout(20) << "health checks:\n";
JSONFormatter jf(true);
jf.dump_object("health_checks", m->health_checks);
jf.flush(*_dout);
*_dout << dendl;
if (osdmap.require_osd_release >= ceph_release_t::luminous) {
clog->debug() << "pgmap v" << pg_map.version << ": " << pg_map;
}
});
});
map<daemon_metric, unique_ptr<DaemonHealthMetricCollector>> accumulated;
for (auto service : {"osd", "mon"} ) {
auto daemons = daemon_state.get_by_service(service);
for (const auto& [key,state] : daemons) {
std::lock_guard l{state->lock};
for (const auto& metric : state->daemon_health_metrics) {
auto acc = accumulated.find(metric.get_type());
if (acc == accumulated.end()) {
auto collector = DaemonHealthMetricCollector::create(metric.get_type());
if (!collector) {
derr << __func__ << " " << key
<< " sent me an unknown health metric: "
<< std::hex << static_cast<uint8_t>(metric.get_type())
<< std::dec << dendl;
continue;
}
tie(acc, std::ignore) = accumulated.emplace(metric.get_type(),
std::move(collector));
}
acc->second->update(key, metric);
}
}
}
for (const auto& acc : accumulated) {
acc.second->summarize(m->health_checks);
}
// TODO? We currently do not notify the PyModules
// TODO: respect needs_send, so we send the report only if we are asked to do
// so, or the state is updated.
monc->send_mon_message(std::move(m));
}
void DaemonServer::adjust_pgs()
{
dout(20) << dendl;
unsigned max = std::max<int64_t>(1, g_conf()->mon_osd_max_creating_pgs);
double max_misplaced = g_conf().get_val<double>("target_max_misplaced_ratio");
bool aggro = g_conf().get_val<bool>("mgr_debug_aggressive_pg_num_changes");
map<string,unsigned> pg_num_to_set;
map<string,unsigned> pgp_num_to_set;
set<pg_t> upmaps_to_clear;
cluster_state.with_osdmap_and_pgmap([&](const OSDMap& osdmap, const PGMap& pg_map) {
unsigned creating_or_unknown = 0;
for (auto& i : pg_map.num_pg_by_state) {
if ((i.first & (PG_STATE_CREATING)) ||
i.first == 0) {
creating_or_unknown += i.second;
}
}
unsigned left = max;
if (creating_or_unknown >= max) {
return;
}
left -= creating_or_unknown;
dout(10) << "creating_or_unknown " << creating_or_unknown
<< " max_creating " << max
<< " left " << left
<< dendl;
// FIXME: These checks are fundamentally racy given that adjust_pgs()
// can run more frequently than we get updated pg stats from OSDs. We
// may make multiple adjustments with stale informaiton.
double misplaced_ratio, degraded_ratio;
double inactive_pgs_ratio, unknown_pgs_ratio;
pg_map.get_recovery_stats(&misplaced_ratio, °raded_ratio,
&inactive_pgs_ratio, &unknown_pgs_ratio);
dout(20) << "misplaced_ratio " << misplaced_ratio
<< " degraded_ratio " << degraded_ratio
<< " inactive_pgs_ratio " << inactive_pgs_ratio
<< " unknown_pgs_ratio " << unknown_pgs_ratio
<< "; target_max_misplaced_ratio " << max_misplaced
<< dendl;
for (auto& i : osdmap.get_pools()) {
const pg_pool_t& p = i.second;
// adjust pg_num?
if (p.get_pg_num_target() != p.get_pg_num()) {
dout(20) << "pool " << i.first
<< " pg_num " << p.get_pg_num()
<< " target " << p.get_pg_num_target()
<< dendl;
if (p.has_flag(pg_pool_t::FLAG_CREATING)) {
dout(10) << "pool " << i.first
<< " pg_num_target " << p.get_pg_num_target()
<< " pg_num " << p.get_pg_num()
<< " - still creating initial pgs"
<< dendl;
} else if (p.get_pg_num_target() < p.get_pg_num()) {
// pg_num decrease (merge)
pg_t merge_source(p.get_pg_num() - 1, i.first);
pg_t merge_target = merge_source.get_parent();
bool ok = true;
if (p.get_pg_num() != p.get_pg_num_pending()) {
dout(10) << "pool " << i.first
<< " pg_num_target " << p.get_pg_num_target()
<< " pg_num " << p.get_pg_num()
<< " - decrease and pg_num_pending != pg_num, waiting"
<< dendl;
ok = false;
} else if (p.get_pg_num() == p.get_pgp_num()) {
dout(10) << "pool " << i.first
<< " pg_num_target " << p.get_pg_num_target()
<< " pg_num " << p.get_pg_num()
<< " - decrease blocked by pgp_num "
<< p.get_pgp_num()
<< dendl;
ok = false;
}
vector<int32_t> source_acting;
for (auto &merge_participant : {merge_source, merge_target}) {
bool is_merge_source = merge_participant == merge_source;
if (osdmap.have_pg_upmaps(merge_participant)) {
dout(10) << "pool " << i.first
<< " pg_num_target " << p.get_pg_num_target()
<< " pg_num " << p.get_pg_num()
<< (is_merge_source ? " - merge source " : " - merge target ")
<< merge_participant
<< " has upmap" << dendl;
upmaps_to_clear.insert(merge_participant);
ok = false;
}
auto q = pg_map.pg_stat.find(merge_participant);
if (q == pg_map.pg_stat.end()) {
dout(10) << "pool " << i.first
<< " pg_num_target " << p.get_pg_num_target()
<< " pg_num " << p.get_pg_num()
<< " - no state for " << merge_participant
<< (is_merge_source ? " (merge source)" : " (merge target)")
<< dendl;
ok = false;
} else if ((q->second.state & (PG_STATE_ACTIVE | PG_STATE_CLEAN)) !=
(PG_STATE_ACTIVE | PG_STATE_CLEAN)) {
dout(10) << "pool " << i.first
<< " pg_num_target " << p.get_pg_num_target()
<< " pg_num " << p.get_pg_num()
<< (is_merge_source ? " - merge source " : " - merge target ")
<< merge_participant
<< " not clean (" << pg_state_string(q->second.state)
<< ")" << dendl;
ok = false;
}
if (is_merge_source) {
source_acting = q->second.acting;
} else if (ok && q->second.acting != source_acting) {
dout(10) << "pool " << i.first
<< " pg_num_target " << p.get_pg_num_target()
<< " pg_num " << p.get_pg_num()
<< (is_merge_source ? " - merge source " : " - merge target ")
<< merge_participant
<< " acting does not match (source " << source_acting
<< " != target " << q->second.acting
<< ")" << dendl;
ok = false;
}
}
if (ok) {
unsigned target = p.get_pg_num() - 1;
dout(10) << "pool " << i.first
<< " pg_num_target " << p.get_pg_num_target()
<< " pg_num " << p.get_pg_num()
<< " -> " << target
<< " (merging " << merge_source
<< " and " << merge_target
<< ")" << dendl;
pg_num_to_set[osdmap.get_pool_name(i.first)] = target;
continue;
}
} else if (p.get_pg_num_target() > p.get_pg_num()) {
// pg_num increase (split)
bool active = true;
auto q = pg_map.num_pg_by_pool_state.find(i.first);
if (q != pg_map.num_pg_by_pool_state.end()) {
for (auto& j : q->second) {
if ((j.first & (PG_STATE_ACTIVE|PG_STATE_PEERED)) == 0) {
dout(20) << "pool " << i.first << " has " << j.second
<< " pgs in " << pg_state_string(j.first)
<< dendl;
active = false;
break;
}
}
} else {
active = false;
}
unsigned pg_gap = p.get_pg_num() - p.get_pgp_num();
unsigned max_jump = cct->_conf->mgr_max_pg_num_change;
if (!active) {
dout(10) << "pool " << i.first
<< " pg_num_target " << p.get_pg_num_target()
<< " pg_num " << p.get_pg_num()
<< " - not all pgs active"
<< dendl;
} else if (pg_gap >= max_jump) {
dout(10) << "pool " << i.first
<< " pg_num " << p.get_pg_num()
<< " - pgp_num " << p.get_pgp_num()
<< " gap >= max_pg_num_change " << max_jump
<< " - must scale pgp_num first"
<< dendl;
} else {
unsigned add = std::min(
std::min(left, max_jump - pg_gap),
p.get_pg_num_target() - p.get_pg_num());
unsigned target = p.get_pg_num() + add;
left -= add;
dout(10) << "pool " << i.first
<< " pg_num_target " << p.get_pg_num_target()
<< " pg_num " << p.get_pg_num()
<< " -> " << target << dendl;
pg_num_to_set[osdmap.get_pool_name(i.first)] = target;
}
}
}
// adjust pgp_num?
unsigned target = std::min(p.get_pg_num_pending(),
p.get_pgp_num_target());
if (target != p.get_pgp_num()) {
dout(20) << "pool " << i.first
<< " pgp_num_target " << p.get_pgp_num_target()
<< " pgp_num " << p.get_pgp_num()
<< " -> " << target << dendl;
if (target > p.get_pgp_num() &&
p.get_pgp_num() == p.get_pg_num()) {
dout(10) << "pool " << i.first
<< " pgp_num_target " << p.get_pgp_num_target()
<< " pgp_num " << p.get_pgp_num()
<< " - increase blocked by pg_num " << p.get_pg_num()
<< dendl;
} else if (!aggro && (inactive_pgs_ratio > 0 ||
degraded_ratio > 0 ||
unknown_pgs_ratio > 0)) {
dout(10) << "pool " << i.first
<< " pgp_num_target " << p.get_pgp_num_target()
<< " pgp_num " << p.get_pgp_num()
<< " - inactive|degraded|unknown pgs, deferring pgp_num"
<< " update" << dendl;
} else if (!aggro && (misplaced_ratio > max_misplaced)) {
dout(10) << "pool " << i.first
<< " pgp_num_target " << p.get_pgp_num_target()
<< " pgp_num " << p.get_pgp_num()
<< " - misplaced_ratio " << misplaced_ratio
<< " > max " << max_misplaced
<< ", deferring pgp_num update" << dendl;
} else {
// NOTE: this calculation assumes objects are
// basically uniformly distributed across all PGs
// (regardless of pool), which is probably not
// perfectly correct, but it's a start. make no
// single adjustment that's more than half of the
// max_misplaced, to somewhat limit the magnitude of
// our potential error here.
unsigned next;
static constexpr unsigned MAX_NUM_OBJECTS_PER_PG_FOR_LEAP = 1;
pool_stat_t s = pg_map.get_pg_pool_sum_stat(i.first);
if (aggro ||
// pool is (virtually) empty; just jump to final pgp_num?
(p.get_pgp_num_target() > p.get_pgp_num() &&
s.stats.sum.num_objects <= (MAX_NUM_OBJECTS_PER_PG_FOR_LEAP *
p.get_pgp_num_target()))) {
next = target;
} else {
double room =
std::min<double>(max_misplaced - misplaced_ratio,
max_misplaced / 2.0);
unsigned estmax = std::max<unsigned>(
(double)p.get_pg_num() * room, 1u);
unsigned next_min = 0;
if (p.get_pgp_num() > estmax) {
next_min = p.get_pgp_num() - estmax;
}
next = std::clamp(target,
next_min,
p.get_pgp_num() + estmax);
dout(20) << " room " << room << " estmax " << estmax
<< " delta " << (target-p.get_pgp_num())
<< " next " << next << dendl;
if (p.get_pgp_num_target() == p.get_pg_num_target() &&
p.get_pgp_num_target() < p.get_pg_num()) {
// since pgp_num is tracking pg_num, ceph is handling
// pgp_num. so, be responsible: don't let pgp_num get
// too far out ahead of merges (if we are merging).
// this avoids moving lots of unmerged pgs onto a
// small number of OSDs where we might blow out the
// per-osd pg max.
unsigned max_outpace_merges =
std::max<unsigned>(8, p.get_pg_num() * max_misplaced);
if (next + max_outpace_merges < p.get_pg_num()) {
next = p.get_pg_num() - max_outpace_merges;
dout(10) << " using next " << next
<< " to avoid outpacing merges (max_outpace_merges "
<< max_outpace_merges << ")" << dendl;
}
}
}
if (next != p.get_pgp_num()) {
dout(10) << "pool " << i.first
<< " pgp_num_target " << p.get_pgp_num_target()
<< " pgp_num " << p.get_pgp_num()
<< " -> " << next << dendl;
pgp_num_to_set[osdmap.get_pool_name(i.first)] = next;
}
}
}
if (left == 0) {
return;
}
}
});
for (auto i : pg_num_to_set) {
const string cmd =
"{"
"\"prefix\": \"osd pool set\", "
"\"pool\": \"" + i.first + "\", "
"\"var\": \"pg_num_actual\", "
"\"val\": \"" + stringify(i.second) + "\""
"}";
monc->start_mon_command({cmd}, {}, nullptr, nullptr, nullptr);
}
for (auto i : pgp_num_to_set) {
const string cmd =
"{"
"\"prefix\": \"osd pool set\", "
"\"pool\": \"" + i.first + "\", "
"\"var\": \"pgp_num_actual\", "
"\"val\": \"" + stringify(i.second) + "\""
"}";
monc->start_mon_command({cmd}, {}, nullptr, nullptr, nullptr);
}
for (auto pg : upmaps_to_clear) {
const string cmd =
"{"
"\"prefix\": \"osd rm-pg-upmap\", "
"\"pgid\": \"" + stringify(pg) + "\""
"}";
monc->start_mon_command({cmd}, {}, nullptr, nullptr, nullptr);
const string cmd2 =
"{"
"\"prefix\": \"osd rm-pg-upmap-items\", "
"\"pgid\": \"" + stringify(pg) + "\"" +
"}";
monc->start_mon_command({cmd2}, {}, nullptr, nullptr, nullptr);
}
}
void DaemonServer::got_service_map()
{
std::lock_guard l(lock);
cluster_state.with_servicemap([&](const ServiceMap& service_map) {
if (pending_service_map.epoch == 0) {
// we just started up
dout(10) << "got initial map e" << service_map.epoch << dendl;
ceph_assert(pending_service_map_dirty == 0);
pending_service_map = service_map;
pending_service_map.epoch = service_map.epoch + 1;
} else if (pending_service_map.epoch <= service_map.epoch) {
// we just started up but got one more not our own map
dout(10) << "got newer initial map e" << service_map.epoch << dendl;
ceph_assert(pending_service_map_dirty == 0);
pending_service_map = service_map;
pending_service_map.epoch = service_map.epoch + 1;
} else {
// we already active and therefore must have persisted it,
// which means ours is the same or newer.
dout(10) << "got updated map e" << service_map.epoch << dendl;
}
});
// cull missing daemons, populate new ones
std::set<std::string> types;
for (auto& [type, service] : pending_service_map.services) {
if (ServiceMap::is_normal_ceph_entity(type)) {
continue;
}
types.insert(type);
std::set<std::string> names;
for (auto& q : service.daemons) {
names.insert(q.first);
DaemonKey key{type, q.first};
if (!daemon_state.exists(key)) {
auto daemon = std::make_shared<DaemonState>(daemon_state.types);
daemon->key = key;
daemon->set_metadata(q.second.metadata);
daemon->service_daemon = true;
daemon_state.insert(daemon);
dout(10) << "added missing " << key << dendl;
}
}
daemon_state.cull(type, names);
}
daemon_state.cull_services(types);
}
void DaemonServer::got_mgr_map()
{
std::lock_guard l(lock);
set<std::string> have;
cluster_state.with_mgrmap([&](const MgrMap& mgrmap) {
auto md_update = [&] (DaemonKey key) {
std::ostringstream oss;
auto c = new MetadataUpdate(daemon_state, key);
// FIXME remove post-nautilus: include 'id' for luminous mons
oss << "{\"prefix\": \"mgr metadata\", \"who\": \""
<< key.name << "\", \"id\": \"" << key.name << "\"}";
monc->start_mon_command({oss.str()}, {}, &c->outbl, &c->outs, c);
};
if (mgrmap.active_name.size()) {
DaemonKey key{"mgr", mgrmap.active_name};
have.insert(mgrmap.active_name);
if (!daemon_state.exists(key) && !daemon_state.is_updating(key)) {
md_update(key);
dout(10) << "triggered addition of " << key << " via metadata update" << dendl;
}
}
for (auto& i : mgrmap.standbys) {
DaemonKey key{"mgr", i.second.name};
have.insert(i.second.name);
if (!daemon_state.exists(key) && !daemon_state.is_updating(key)) {
md_update(key);
dout(10) << "triggered addition of " << key << " via metadata update" << dendl;
}
}
});
daemon_state.cull("mgr", have);
}
const char** DaemonServer::get_tracked_conf_keys() const
{
static const char *KEYS[] = {
"mgr_stats_threshold",
"mgr_stats_period",
nullptr
};
return KEYS;
}
void DaemonServer::handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed)
{
if (changed.count("mgr_stats_threshold") || changed.count("mgr_stats_period")) {
dout(4) << "Updating stats threshold/period on "
<< daemon_connections.size() << " clients" << dendl;
// Send a fresh MMgrConfigure to all clients, so that they can follow
// the new policy for transmitting stats
finisher.queue(new LambdaContext([this](int r) {
std::lock_guard l(lock);
for (auto &c : daemon_connections) {
_send_configure(c);
}
}));
}
}
void DaemonServer::_send_configure(ConnectionRef c)
{
ceph_assert(ceph_mutex_is_locked_by_me(lock));
auto configure = make_message<MMgrConfigure>();
configure->stats_period = g_conf().get_val<int64_t>("mgr_stats_period");
configure->stats_threshold = g_conf().get_val<int64_t>("mgr_stats_threshold");
if (c->peer_is_osd()) {
configure->osd_perf_metric_queries =
osd_perf_metric_collector.get_queries();
} else if (c->peer_is_mds()) {
configure->metric_config_message =
MetricConfigMessage(MDSConfigPayload(mds_perf_metric_collector.get_queries()));
}
c->send_message2(configure);
}
MetricQueryID DaemonServer::add_osd_perf_query(
const OSDPerfMetricQuery &query,
const std::optional<OSDPerfMetricLimit> &limit)
{
return osd_perf_metric_collector.add_query(query, limit);
}
int DaemonServer::remove_osd_perf_query(MetricQueryID query_id)
{
return osd_perf_metric_collector.remove_query(query_id);
}
int DaemonServer::get_osd_perf_counters(OSDPerfCollector *collector)
{
return osd_perf_metric_collector.get_counters(collector);
}
MetricQueryID DaemonServer::add_mds_perf_query(
const MDSPerfMetricQuery &query,
const std::optional<MDSPerfMetricLimit> &limit)
{
return mds_perf_metric_collector.add_query(query, limit);
}
int DaemonServer::remove_mds_perf_query(MetricQueryID query_id)
{
return mds_perf_metric_collector.remove_query(query_id);
}
void DaemonServer::reregister_mds_perf_queries()
{
mds_perf_metric_collector.reregister_queries();
}
int DaemonServer::get_mds_perf_counters(MDSPerfCollector *collector)
{
return mds_perf_metric_collector.get_counters(collector);
}
| 98,453 | 30.354777 | 118 | cc |
null | ceph-main/src/mgr/DaemonServer.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2016 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#ifndef DAEMON_SERVER_H_
#define DAEMON_SERVER_H_
#include "PyModuleRegistry.h"
#include <set>
#include <string>
#include <boost/variant.hpp>
#include "common/ceph_mutex.h"
#include "common/LogClient.h"
#include "common/Timer.h"
#include <msg/Messenger.h>
#include <mon/MonClient.h>
#include "ServiceMap.h"
#include "MgrSession.h"
#include "DaemonState.h"
#include "MetricCollector.h"
#include "OSDPerfMetricCollector.h"
#include "MDSPerfMetricCollector.h"
class MMgrReport;
class MMgrOpen;
class MMgrUpdate;
class MMgrClose;
class MMonMgrReport;
class MCommand;
class MMgrCommand;
struct MonCommand;
class CommandContext;
struct OSDPerfMetricQuery;
struct MDSPerfMetricQuery;
struct offline_pg_report {
set<int> osds;
set<pg_t> ok, not_ok, unknown;
set<pg_t> ok_become_degraded, ok_become_more_degraded; // ok
set<pg_t> bad_no_pool, bad_already_inactive, bad_become_inactive; // not ok
bool ok_to_stop() const {
return not_ok.empty() && unknown.empty();
}
void dump(Formatter *f) const {
f->dump_bool("ok_to_stop", ok_to_stop());
f->open_array_section("osds");
for (auto o : osds) {
f->dump_int("osd", o);
}
f->close_section();
f->dump_unsigned("num_ok_pgs", ok.size());
f->dump_unsigned("num_not_ok_pgs", not_ok.size());
// ambiguous
if (!unknown.empty()) {
f->open_array_section("unknown_pgs");
for (auto pg : unknown) {
f->dump_stream("pg") << pg;
}
f->close_section();
}
// bad news
if (!bad_no_pool.empty()) {
f->open_array_section("bad_no_pool_pgs");
for (auto pg : bad_no_pool) {
f->dump_stream("pg") << pg;
}
f->close_section();
}
if (!bad_already_inactive.empty()) {
f->open_array_section("bad_already_inactive");
for (auto pg : bad_already_inactive) {
f->dump_stream("pg") << pg;
}
f->close_section();
}
if (!bad_become_inactive.empty()) {
f->open_array_section("bad_become_inactive");
for (auto pg : bad_become_inactive) {
f->dump_stream("pg") << pg;
}
f->close_section();
}
// informative
if (!ok_become_degraded.empty()) {
f->open_array_section("ok_become_degraded");
for (auto pg : ok_become_degraded) {
f->dump_stream("pg") << pg;
}
f->close_section();
}
if (!ok_become_more_degraded.empty()) {
f->open_array_section("ok_become_more_degraded");
for (auto pg : ok_become_more_degraded) {
f->dump_stream("pg") << pg;
}
f->close_section();
}
}
};
/**
* Server used in ceph-mgr to communicate with Ceph daemons like
* MDSs and OSDs.
*/
class DaemonServer : public Dispatcher, public md_config_obs_t
{
protected:
boost::scoped_ptr<Throttle> client_byte_throttler;
boost::scoped_ptr<Throttle> client_msg_throttler;
boost::scoped_ptr<Throttle> osd_byte_throttler;
boost::scoped_ptr<Throttle> osd_msg_throttler;
boost::scoped_ptr<Throttle> mds_byte_throttler;
boost::scoped_ptr<Throttle> mds_msg_throttler;
boost::scoped_ptr<Throttle> mon_byte_throttler;
boost::scoped_ptr<Throttle> mon_msg_throttler;
Messenger *msgr;
MonClient *monc;
Finisher &finisher;
DaemonStateIndex &daemon_state;
ClusterState &cluster_state;
PyModuleRegistry &py_modules;
LogChannelRef clog, audit_clog;
// Connections for daemons, and clients with service names set
// (i.e. those MgrClients that are allowed to send MMgrReports)
std::set<ConnectionRef> daemon_connections;
/// connections for osds
ceph::unordered_map<int,std::set<ConnectionRef>> osd_cons;
ServiceMap pending_service_map; // uncommitted
epoch_t pending_service_map_dirty = 0;
ceph::mutex lock = ceph::make_mutex("DaemonServer");
static void _generate_command_map(cmdmap_t& cmdmap,
std::map<std::string,std::string> ¶m_str_map);
static const MonCommand *_get_mgrcommand(const std::string &cmd_prefix,
const std::vector<MonCommand> &commands);
bool _allowed_command(
MgrSession *s, const std::string &service, const std::string &module,
const std::string &prefix, const cmdmap_t& cmdmap,
const std::map<std::string,std::string>& param_str_map,
const MonCommand *this_cmd);
private:
friend class ReplyOnFinish;
bool _reply(MCommand* m,
int ret, const std::string& s, const bufferlist& payload);
void _prune_pending_service_map();
void _check_offlines_pgs(
const std::set<int>& osds,
const OSDMap& osdmap,
const PGMap& pgmap,
offline_pg_report *report);
void _maximize_ok_to_stop_set(
const set<int>& orig_osds,
unsigned max,
const OSDMap& osdmap,
const PGMap& pgmap,
offline_pg_report *report);
utime_t started_at;
std::atomic<bool> pgmap_ready;
std::set<int32_t> reported_osds;
void maybe_ready(int32_t osd_id);
SafeTimer timer;
bool shutting_down;
Context *tick_event;
void tick();
void schedule_tick_locked(double delay_sec);
class OSDPerfMetricCollectorListener : public MetricListener {
public:
OSDPerfMetricCollectorListener(DaemonServer *server)
: server(server) {
}
void handle_query_updated() override {
server->handle_osd_perf_metric_query_updated();
}
private:
DaemonServer *server;
};
OSDPerfMetricCollectorListener osd_perf_metric_collector_listener;
OSDPerfMetricCollector osd_perf_metric_collector;
void handle_osd_perf_metric_query_updated();
class MDSPerfMetricCollectorListener : public MetricListener {
public:
MDSPerfMetricCollectorListener(DaemonServer *server)
: server(server) {
}
void handle_query_updated() override {
server->handle_mds_perf_metric_query_updated();
}
private:
DaemonServer *server;
};
MDSPerfMetricCollectorListener mds_perf_metric_collector_listener;
MDSPerfMetricCollector mds_perf_metric_collector;
void handle_mds_perf_metric_query_updated();
void handle_metric_payload(const OSDMetricPayload &payload) {
osd_perf_metric_collector.process_reports(payload);
}
void handle_metric_payload(const MDSMetricPayload &payload) {
mds_perf_metric_collector.process_reports(payload);
}
void handle_metric_payload(const UnknownMetricPayload &payload) {
ceph_abort();
}
struct HandlePayloadVisitor : public boost::static_visitor<void> {
DaemonServer *server;
HandlePayloadVisitor(DaemonServer *server)
: server(server) {
}
template <typename MetricPayload>
inline void operator()(const MetricPayload &payload) const {
server->handle_metric_payload(payload);
}
};
void update_task_status(DaemonKey key,
const std::map<std::string,std::string>& task_status);
public:
int init(uint64_t gid, entity_addrvec_t client_addrs);
void shutdown();
entity_addrvec_t get_myaddrs() const;
DaemonServer(MonClient *monc_,
Finisher &finisher_,
DaemonStateIndex &daemon_state_,
ClusterState &cluster_state_,
PyModuleRegistry &py_modules_,
LogChannelRef cl,
LogChannelRef auditcl);
~DaemonServer() override;
bool ms_dispatch2(const ceph::ref_t<Message>& m) override;
int ms_handle_authentication(Connection *con) override;
bool ms_handle_reset(Connection *con) override;
void ms_handle_remote_reset(Connection *con) override {}
bool ms_handle_refused(Connection *con) override;
void fetch_missing_metadata(const DaemonKey& key, const entity_addr_t& addr);
bool handle_open(const ceph::ref_t<MMgrOpen>& m);
bool handle_update(const ceph::ref_t<MMgrUpdate>& m);
bool handle_close(const ceph::ref_t<MMgrClose>& m);
bool handle_report(const ceph::ref_t<MMgrReport>& m);
bool handle_command(const ceph::ref_t<MCommand>& m);
bool handle_command(const ceph::ref_t<MMgrCommand>& m);
bool _handle_command(std::shared_ptr<CommandContext>& cmdctx);
void send_report();
void got_service_map();
void got_mgr_map();
void adjust_pgs();
void _send_configure(ConnectionRef c);
MetricQueryID add_osd_perf_query(
const OSDPerfMetricQuery &query,
const std::optional<OSDPerfMetricLimit> &limit);
int remove_osd_perf_query(MetricQueryID query_id);
int get_osd_perf_counters(OSDPerfCollector *collector);
MetricQueryID add_mds_perf_query(const MDSPerfMetricQuery &query,
const std::optional<MDSPerfMetricLimit> &limit);
int remove_mds_perf_query(MetricQueryID query_id);
void reregister_mds_perf_queries();
int get_mds_perf_counters(MDSPerfCollector *collector);
virtual const char** get_tracked_conf_keys() const override;
virtual void handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed) override;
void schedule_tick(double delay_sec);
void log_access_denied(std::shared_ptr<CommandContext>& cmdctx,
MgrSession* session, std::stringstream& ss);
void dump_pg_ready(ceph::Formatter *f);
};
#endif
| 9,430 | 28.750789 | 86 | h |
null | ceph-main/src/mgr/DaemonState.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2016 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#include "DaemonState.h"
#include <experimental/iterator>
#include "MgrSession.h"
#include "include/stringify.h"
#include "common/Formatter.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_mgr
#undef dout_prefix
#define dout_prefix *_dout << "mgr " << __func__ << " "
using std::list;
using std::make_pair;
using std::map;
using std::ostream;
using std::ostringstream;
using std::string;
using std::stringstream;
using std::unique_ptr;
void DeviceState::set_metadata(map<string,string>&& m)
{
metadata = std::move(m);
auto p = metadata.find("life_expectancy_min");
if (p != metadata.end()) {
life_expectancy.first.parse(p->second);
}
p = metadata.find("life_expectancy_max");
if (p != metadata.end()) {
life_expectancy.second.parse(p->second);
}
p = metadata.find("life_expectancy_stamp");
if (p != metadata.end()) {
life_expectancy_stamp.parse(p->second);
}
p = metadata.find("wear_level");
if (p != metadata.end()) {
wear_level = atof(p->second.c_str());
}
}
void DeviceState::set_life_expectancy(utime_t from, utime_t to, utime_t now)
{
life_expectancy = make_pair(from, to);
life_expectancy_stamp = now;
if (from != utime_t()) {
metadata["life_expectancy_min"] = stringify(from);
} else {
metadata["life_expectancy_min"] = "";
}
if (to != utime_t()) {
metadata["life_expectancy_max"] = stringify(to);
} else {
metadata["life_expectancy_max"] = "";
}
if (now != utime_t()) {
metadata["life_expectancy_stamp"] = stringify(now);
} else {
metadata["life_expectancy_stamp"] = "";
}
}
void DeviceState::rm_life_expectancy()
{
life_expectancy = make_pair(utime_t(), utime_t());
life_expectancy_stamp = utime_t();
metadata.erase("life_expectancy_min");
metadata.erase("life_expectancy_max");
metadata.erase("life_expectancy_stamp");
}
void DeviceState::set_wear_level(float wear)
{
wear_level = wear;
if (wear >= 0) {
metadata["wear_level"] = stringify(wear);
} else {
metadata.erase("wear_level");
}
}
string DeviceState::get_life_expectancy_str(utime_t now) const
{
if (life_expectancy.first == utime_t()) {
return string();
}
if (now >= life_expectancy.first) {
return "now";
}
utime_t min = life_expectancy.first - now;
utime_t max = life_expectancy.second - now;
if (life_expectancy.second == utime_t()) {
return string(">") + timespan_str(make_timespan(min));
}
string a = timespan_str(make_timespan(min));
string b = timespan_str(make_timespan(max));
if (a == b) {
return a;
}
return a + " to " + b;
}
void DeviceState::dump(Formatter *f) const
{
f->dump_string("devid", devid);
f->open_array_section("location");
for (auto& i : attachments) {
f->open_object_section("attachment");
f->dump_string("host", std::get<0>(i));
f->dump_string("dev", std::get<1>(i));
f->dump_string("path", std::get<2>(i));
f->close_section();
}
f->close_section();
f->open_array_section("daemons");
for (auto& i : daemons) {
f->dump_stream("daemon") << i;
}
f->close_section();
if (life_expectancy.first != utime_t()) {
f->dump_stream("life_expectancy_min") << life_expectancy.first;
f->dump_stream("life_expectancy_max") << life_expectancy.second;
f->dump_stream("life_expectancy_stamp")
<< life_expectancy_stamp;
}
if (wear_level >= 0) {
f->dump_float("wear_level", wear_level);
}
}
void DeviceState::print(ostream& out) const
{
out << "device " << devid << "\n";
for (auto& i : attachments) {
out << "attachment " << std::get<0>(i) << " " << std::get<1>(i) << " "
<< std::get<2>(i) << "\n";
out << "\n";
}
std::copy(std::begin(daemons), std::end(daemons),
std::experimental::make_ostream_joiner(out, ","));
out << '\n';
if (life_expectancy.first != utime_t()) {
out << "life_expectancy " << life_expectancy.first << " to "
<< life_expectancy.second
<< " (as of " << life_expectancy_stamp << ")\n";
}
if (wear_level >= 0) {
out << "wear_level " << wear_level << "\n";
}
}
void DaemonState::set_metadata(const std::map<std::string,std::string>& m)
{
devices.clear();
devices_bypath.clear();
metadata = m;
if (auto found = m.find("device_ids"); found != m.end()) {
auto& device_ids = found->second;
std::map<std::string,std::string> paths; // devname -> id or path
if (auto found = m.find("device_paths"); found != m.end()) {
get_str_map(found->second, &paths, ",; ");
}
for_each_pair(
device_ids, ",; ",
[&paths, this](std::string_view devname, std::string_view id) {
// skip blank ids
if (id.empty()) {
return;
}
// id -> devname
devices.emplace(id, devname);
if (auto path = paths.find(std::string(id)); path != paths.end()) {
// id -> path
devices_bypath.emplace(id, path->second);
}
});
}
if (auto found = m.find("hostname"); found != m.end()) {
hostname = found->second;
}
}
const std::map<std::string,std::string>& DaemonState::_get_config_defaults()
{
if (config_defaults.empty() &&
config_defaults_bl.length()) {
auto p = config_defaults_bl.cbegin();
try {
decode(config_defaults, p);
} catch (buffer::error& e) {
}
}
return config_defaults;
}
void DaemonStateIndex::insert(DaemonStatePtr dm)
{
std::unique_lock l{lock};
_insert(dm);
}
void DaemonStateIndex::_insert(DaemonStatePtr dm)
{
if (all.count(dm->key)) {
_erase(dm->key);
}
by_server[dm->hostname][dm->key] = dm;
all[dm->key] = dm;
for (auto& i : dm->devices) {
auto d = _get_or_create_device(i.first);
d->daemons.insert(dm->key);
auto p = dm->devices_bypath.find(i.first);
if (p != dm->devices_bypath.end()) {
d->attachments.insert(std::make_tuple(dm->hostname, i.second, p->second));
} else {
d->attachments.insert(std::make_tuple(dm->hostname, i.second,
std::string()));
}
}
}
void DaemonStateIndex::_erase(const DaemonKey& dmk)
{
ceph_assert(ceph_mutex_is_wlocked(lock));
const auto to_erase = all.find(dmk);
ceph_assert(to_erase != all.end());
const auto dm = to_erase->second;
for (auto& i : dm->devices) {
auto d = _get_or_create_device(i.first);
ceph_assert(d->daemons.count(dmk));
d->daemons.erase(dmk);
auto p = dm->devices_bypath.find(i.first);
if (p != dm->devices_bypath.end()) {
d->attachments.erase(make_tuple(dm->hostname, i.second, p->second));
} else {
d->attachments.erase(make_tuple(dm->hostname, i.second, std::string()));
}
if (d->empty()) {
_erase_device(d);
}
}
auto &server_collection = by_server[dm->hostname];
server_collection.erase(dm->key);
if (server_collection.empty()) {
by_server.erase(dm->hostname);
}
all.erase(to_erase);
}
DaemonStateCollection DaemonStateIndex::get_by_service(
const std::string& svc) const
{
std::shared_lock l{lock};
DaemonStateCollection result;
for (const auto& [key, state] : all) {
if (key.type == svc) {
result[key] = state;
}
}
return result;
}
DaemonStateCollection DaemonStateIndex::get_by_server(
const std::string &hostname) const
{
std::shared_lock l{lock};
if (auto found = by_server.find(hostname); found != by_server.end()) {
return found->second;
} else {
return {};
}
}
bool DaemonStateIndex::exists(const DaemonKey &key) const
{
std::shared_lock l{lock};
return all.count(key) > 0;
}
DaemonStatePtr DaemonStateIndex::get(const DaemonKey &key)
{
std::shared_lock l{lock};
auto iter = all.find(key);
if (iter != all.end()) {
return iter->second;
} else {
return nullptr;
}
}
void DaemonStateIndex::rm(const DaemonKey &key)
{
std::unique_lock l{lock};
_rm(key);
}
void DaemonStateIndex::_rm(const DaemonKey &key)
{
if (all.count(key)) {
_erase(key);
}
}
void DaemonStateIndex::cull(const std::string& svc_name,
const std::set<std::string>& names_exist)
{
std::vector<string> victims;
std::unique_lock l{lock};
auto begin = all.lower_bound({svc_name, ""});
auto end = all.end();
for (auto &i = begin; i != end; ++i) {
const auto& daemon_key = i->first;
if (daemon_key.type != svc_name)
break;
if (names_exist.count(daemon_key.name) == 0) {
victims.push_back(daemon_key.name);
}
}
for (auto &i : victims) {
DaemonKey daemon_key{svc_name, i};
dout(4) << "Removing data for " << daemon_key << dendl;
_erase(daemon_key);
}
}
void DaemonStateIndex::cull_services(const std::set<std::string>& types_exist)
{
std::set<DaemonKey> victims;
std::unique_lock l{lock};
for (auto it = all.begin(); it != all.end(); ++it) {
const auto& daemon_key = it->first;
if (it->second->service_daemon &&
types_exist.count(daemon_key.type) == 0) {
victims.insert(daemon_key);
}
}
for (auto &i : victims) {
dout(4) << "Removing data for " << i << dendl;
_erase(i);
}
}
void DaemonPerfCounters::update(const MMgrReport& report)
{
dout(20) << "loading " << report.declare_types.size() << " new types, "
<< report.undeclare_types.size() << " old types, had "
<< types.size() << " types, got "
<< report.packed.length() << " bytes of data" << dendl;
// Retrieve session state
auto priv = report.get_connection()->get_priv();
auto session = static_cast<MgrSession*>(priv.get());
// Load any newly declared types
for (const auto &t : report.declare_types) {
types.insert(std::make_pair(t.path, t));
session->declared_types.insert(t.path);
}
// Remove any old types
for (const auto &t : report.undeclare_types) {
session->declared_types.erase(t);
}
const auto now = ceph_clock_now();
// Parse packed data according to declared set of types
auto p = report.packed.cbegin();
DECODE_START(1, p);
for (const auto &t_path : session->declared_types) {
const auto &t = types.at(t_path);
auto instances_it = instances.find(t_path);
// Always check the instance exists, as we don't prevent yet
// multiple sessions from daemons with the same name, and one
// session clearing stats created by another on open.
if (instances_it == instances.end()) {
instances_it = instances.insert({t_path, t.type}).first;
}
uint64_t val = 0;
uint64_t avgcount = 0;
uint64_t avgcount2 = 0;
decode(val, p);
if (t.type & PERFCOUNTER_LONGRUNAVG) {
decode(avgcount, p);
decode(avgcount2, p);
instances_it->second.push_avg(now, val, avgcount);
} else {
instances_it->second.push(now, val);
}
}
DECODE_FINISH(p);
}
void PerfCounterInstance::push(utime_t t, uint64_t const &v)
{
buffer.push_back({t, v});
}
void PerfCounterInstance::push_avg(utime_t t, uint64_t const &s,
uint64_t const &c)
{
avg_buffer.push_back({t, s, c});
}
| 11,285 | 24.944828 | 80 | cc |
null | ceph-main/src/mgr/DaemonState.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2016 John Spray <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#ifndef DAEMON_STATE_H_
#define DAEMON_STATE_H_
#include <map>
#include <string>
#include <memory>
#include <set>
#include <boost/circular_buffer.hpp>
#include "include/str_map.h"
#include "msg/msg_types.h"
// For PerfCounterType
#include "messages/MMgrReport.h"
#include "DaemonKey.h"
namespace ceph {
class Formatter;
}
// An instance of a performance counter type, within
// a particular daemon.
class PerfCounterInstance
{
class DataPoint
{
public:
utime_t t;
uint64_t v;
DataPoint(utime_t t_, uint64_t v_)
: t(t_), v(v_)
{}
};
class AvgDataPoint
{
public:
utime_t t;
uint64_t s;
uint64_t c;
AvgDataPoint(utime_t t_, uint64_t s_, uint64_t c_)
: t(t_), s(s_), c(c_)
{}
};
boost::circular_buffer<DataPoint> buffer;
boost::circular_buffer<AvgDataPoint> avg_buffer;
uint64_t get_current() const;
public:
const boost::circular_buffer<DataPoint> & get_data() const
{
return buffer;
}
const DataPoint& get_latest_data() const
{
return buffer.back();
}
const boost::circular_buffer<AvgDataPoint> & get_data_avg() const
{
return avg_buffer;
}
const AvgDataPoint& get_latest_data_avg() const
{
return avg_buffer.back();
}
void push(utime_t t, uint64_t const &v);
void push_avg(utime_t t, uint64_t const &s, uint64_t const &c);
PerfCounterInstance(enum perfcounter_type_d type)
{
if (type & PERFCOUNTER_LONGRUNAVG)
avg_buffer = boost::circular_buffer<AvgDataPoint>(20);
else
buffer = boost::circular_buffer<DataPoint>(20);
};
};
typedef std::map<std::string, PerfCounterType> PerfCounterTypes;
// Performance counters for one daemon
class DaemonPerfCounters
{
public:
// The record of perf stat types, shared between daemons
PerfCounterTypes &types;
explicit DaemonPerfCounters(PerfCounterTypes &types_)
: types(types_)
{}
std::map<std::string, PerfCounterInstance> instances;
void update(const MMgrReport& report);
void clear()
{
instances.clear();
}
};
// The state that we store about one daemon
class DaemonState
{
public:
ceph::mutex lock = ceph::make_mutex("DaemonState::lock");
DaemonKey key;
// The hostname where daemon was last seen running (extracted
// from the metadata)
std::string hostname;
// The metadata (hostname, version, etc) sent from the daemon
std::map<std::string, std::string> metadata;
/// device ids -> devname, derived from metadata[device_ids]
std::map<std::string,std::string> devices;
/// device ids -> by-path, derived from metadata[device_ids]
std::map<std::string,std::string> devices_bypath;
// TODO: this can be generalized to other daemons
std::vector<DaemonHealthMetric> daemon_health_metrics;
// Ephemeral state
bool service_daemon = false;
utime_t service_status_stamp;
std::map<std::string, std::string> service_status;
utime_t last_service_beacon;
// running config
std::map<std::string,std::map<int32_t,std::string>> config;
// mon config values we failed to set
std::map<std::string,std::string> ignored_mon_config;
// compiled-in config defaults (rarely used, so we leave them encoded!)
bufferlist config_defaults_bl;
std::map<std::string,std::string> config_defaults;
// The perf counters received in MMgrReport messages
DaemonPerfCounters perf_counters;
explicit DaemonState(PerfCounterTypes &types_)
: perf_counters(types_)
{
}
void set_metadata(const std::map<std::string,std::string>& m);
const std::map<std::string,std::string>& _get_config_defaults();
};
typedef std::shared_ptr<DaemonState> DaemonStatePtr;
typedef std::map<DaemonKey, DaemonStatePtr> DaemonStateCollection;
struct DeviceState : public RefCountedObject
{
std::string devid;
/// (server,devname,path)
std::set<std::tuple<std::string,std::string,std::string>> attachments;
std::set<DaemonKey> daemons;
std::map<std::string,std::string> metadata; ///< persistent metadata
std::pair<utime_t,utime_t> life_expectancy; ///< when device failure is expected
utime_t life_expectancy_stamp; ///< when life expectency was recorded
float wear_level = -1; ///< SSD wear level (negative if unknown)
void set_metadata(std::map<std::string,std::string>&& m);
void set_life_expectancy(utime_t from, utime_t to, utime_t now);
void rm_life_expectancy();
void set_wear_level(float wear);
std::string get_life_expectancy_str(utime_t now) const;
/// true of we can be safely forgotten/removed from memory
bool empty() const {
return daemons.empty() && metadata.empty();
}
void dump(Formatter *f) const;
void print(std::ostream& out) const;
private:
FRIEND_MAKE_REF(DeviceState);
DeviceState(const std::string& n) : devid(n) {}
};
/**
* Fuse the collection of per-daemon metadata from Ceph into
* a view that can be queried by service type, ID or also
* by server (aka fqdn).
*/
class DaemonStateIndex
{
private:
mutable ceph::shared_mutex lock =
ceph::make_shared_mutex("DaemonStateIndex", true, true, true);
std::map<std::string, DaemonStateCollection> by_server;
DaemonStateCollection all;
std::set<DaemonKey> updating;
std::map<std::string,ceph::ref_t<DeviceState>> devices;
void _erase(const DaemonKey& dmk);
ceph::ref_t<DeviceState> _get_or_create_device(const std::string& dev) {
auto em = devices.try_emplace(dev, nullptr);
auto& d = em.first->second;
if (em.second) {
d = ceph::make_ref<DeviceState>(dev);
}
return d;
}
void _erase_device(const ceph::ref_t<DeviceState>& d) {
devices.erase(d->devid);
}
public:
DaemonStateIndex() {}
// FIXME: shouldn't really be public, maybe construct DaemonState
// objects internally to avoid this.
PerfCounterTypes types;
void insert(DaemonStatePtr dm);
void _insert(DaemonStatePtr dm);
bool exists(const DaemonKey &key) const;
DaemonStatePtr get(const DaemonKey &key);
void rm(const DaemonKey &key);
void _rm(const DaemonKey &key);
// Note that these return by value rather than reference to avoid
// callers needing to stay in lock while using result. Callers must
// still take the individual DaemonState::lock on each entry though.
DaemonStateCollection get_by_server(const std::string &hostname) const;
DaemonStateCollection get_by_service(const std::string &svc_name) const;
DaemonStateCollection get_all() const {return all;}
template<typename Callback, typename...Args>
auto with_daemons_by_server(Callback&& cb, Args&&... args) const ->
decltype(cb(by_server, std::forward<Args>(args)...)) {
std::shared_lock l{lock};
return std::forward<Callback>(cb)(by_server, std::forward<Args>(args)...);
}
template<typename Callback, typename...Args>
bool with_device(const std::string& dev,
Callback&& cb, Args&&... args) const {
std::shared_lock l{lock};
auto p = devices.find(dev);
if (p == devices.end()) {
return false;
}
std::forward<Callback>(cb)(*p->second, std::forward<Args>(args)...);
return true;
}
template<typename Callback, typename...Args>
bool with_device_write(const std::string& dev,
Callback&& cb, Args&&... args) {
std::unique_lock l{lock};
auto p = devices.find(dev);
if (p == devices.end()) {
return false;
}
std::forward<Callback>(cb)(*p->second, std::forward<Args>(args)...);
if (p->second->empty()) {
_erase_device(p->second);
}
return true;
}
template<typename Callback, typename...Args>
void with_device_create(const std::string& dev,
Callback&& cb, Args&&... args) {
std::unique_lock l{lock};
auto d = _get_or_create_device(dev);
std::forward<Callback>(cb)(*d, std::forward<Args>(args)...);
}
template<typename Callback, typename...Args>
void with_devices(Callback&& cb, Args&&... args) const {
std::shared_lock l{lock};
for (auto& i : devices) {
std::forward<Callback>(cb)(*i.second, std::forward<Args>(args)...);
}
}
template<typename CallbackInitial, typename Callback, typename...Args>
void with_devices2(CallbackInitial&& cbi, // with lock taken
Callback&& cb, // for each device
Args&&... args) const {
std::shared_lock l{lock};
cbi();
for (auto& i : devices) {
std::forward<Callback>(cb)(*i.second, std::forward<Args>(args)...);
}
}
void list_devids_by_server(const std::string& server,
std::set<std::string> *ls) {
auto m = get_by_server(server);
for (auto& i : m) {
std::lock_guard l(i.second->lock);
for (auto& j : i.second->devices) {
ls->insert(j.first);
}
}
}
void notify_updating(const DaemonKey &k) {
std::unique_lock l{lock};
updating.insert(k);
}
void clear_updating(const DaemonKey &k) {
std::unique_lock l{lock};
updating.erase(k);
}
bool is_updating(const DaemonKey &k) {
std::shared_lock l{lock};
return updating.count(k) > 0;
}
void update_metadata(DaemonStatePtr state,
const std::map<std::string,std::string>& meta) {
// remove and re-insert in case the device metadata changed
std::unique_lock l{lock};
_rm(state->key);
{
std::lock_guard l2{state->lock};
state->set_metadata(meta);
}
_insert(state);
}
/**
* Remove state for all daemons of this type whose names are
* not present in `names_exist`. Use this function when you have
* a cluster map and want to ensure that anything absent in the map
* is also absent in this class.
*/
void cull(const std::string& svc_name,
const std::set<std::string>& names_exist);
void cull_services(const std::set<std::string>& types_exist);
};
#endif
| 10,143 | 26.342318 | 83 | h |
null | ceph-main/src/mgr/Gil.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2017 SUSE LLC
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "Python.h"
#include "common/debug.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_mgr
#undef dout_prefix
#define dout_prefix *_dout << "mgr " << __func__ << " "
#include "Gil.h"
SafeThreadState::SafeThreadState(PyThreadState *ts_)
: ts(ts_)
{
ceph_assert(ts != nullptr);
thread = pthread_self();
}
Gil::Gil(SafeThreadState &ts, bool new_thread) : pThreadState(ts)
{
// Acquire the GIL, set the current thread state
PyEval_RestoreThread(pThreadState.ts);
dout(25) << "GIL acquired for thread state " << pThreadState.ts << dendl;
//
// If called from a separate OS thread (i.e. a thread not created
// by Python, that does't already have a python thread state that
// was created when that thread was active), we need to manually
// create and switch to a python thread state specifically for this
// OS thread.
//
// Note that instead of requring the caller to set new_thread == true
// when calling this from a separate OS thread, we could figure out
// if this was necessary automatically, as follows:
//
// if (pThreadState->thread_id != PyThread_get_thread_ident()) {
//
// However, this means we're accessing pThreadState->thread_id, but
// the Python C API docs say that "The only public data member is
// PyInterpreterState *interp", i.e. doing this would violate
// something that's meant to be a black box.
//
if (new_thread) {
pNewThreadState = PyThreadState_New(pThreadState.ts->interp);
PyThreadState_Swap(pNewThreadState);
dout(20) << "Switched to new thread state " << pNewThreadState << dendl;
} else {
ceph_assert(pthread_self() == pThreadState.thread);
}
}
Gil::~Gil()
{
if (pNewThreadState != nullptr) {
dout(20) << "Destroying new thread state " << pNewThreadState << dendl;
PyThreadState_Swap(pThreadState.ts);
PyThreadState_Clear(pNewThreadState);
PyThreadState_Delete(pNewThreadState);
}
// Release the GIL, reset the thread state to NULL
PyEval_SaveThread();
dout(25) << "GIL released for thread state " << pThreadState.ts << dendl;
}
without_gil_t::without_gil_t()
{
assert(PyGILState_Check());
release_gil();
}
without_gil_t::~without_gil_t()
{
if (save) {
acquire_gil();
}
}
void without_gil_t::release_gil()
{
save = PyEval_SaveThread();
}
void without_gil_t::acquire_gil()
{
assert(save);
PyEval_RestoreThread(save);
save = nullptr;
}
with_gil_t::with_gil_t(without_gil_t& allow_threads)
: allow_threads{allow_threads}
{
allow_threads.acquire_gil();
}
with_gil_t::~with_gil_t()
{
allow_threads.release_gil();
}
| 3,010 | 25.182609 | 76 | cc |
null | ceph-main/src/mgr/Gil.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2017 SUSE LLC
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <cassert>
#include <functional>
struct _ts;
typedef struct _ts PyThreadState;
#include <pthread.h>
/**
* Wrap PyThreadState to carry a record of which POSIX thread
* the thread state relates to. This allows the Gil class to
* validate that we're being used from the right thread.
*/
class SafeThreadState
{
public:
explicit SafeThreadState(PyThreadState *ts_);
SafeThreadState()
: ts(nullptr), thread(0)
{
}
PyThreadState *ts;
pthread_t thread;
void set(PyThreadState *ts_)
{
ts = ts_;
thread = pthread_self();
}
};
//
// Use one of these in any scope in which you need to hold Python's
// Global Interpreter Lock.
//
// Do *not* nest these, as a second GIL acquire will deadlock (see
// https://docs.python.org/2/c-api/init.html#c.PyEval_RestoreThread)
//
// If in doubt, explicitly put a scope around the block of code you
// know you need the GIL in.
//
// See the comment in Gil::Gil for when to set new_thread == true
//
class Gil {
public:
Gil(const Gil&) = delete;
Gil& operator=(const Gil&) = delete;
Gil(SafeThreadState &ts, bool new_thread = false);
~Gil();
private:
SafeThreadState &pThreadState;
PyThreadState *pNewThreadState = nullptr;
};
// because the Python runtime could relinquish the GIL when performing GC
// and re-acquire it afterwards, we should enforce following locking policy:
// 1. do not acquire locks when holding the GIL, use a without_gil or
// without_gil_t to guard the code which acquires non-gil locks.
// 2. always hold a GIL when calling python functions, for example, when
// constructing a PyFormatter instance.
//
// a wrapper that provides a convenient RAII-style mechinary for acquiring
// and releasing GIL, like the macros of Py_BEGIN_ALLOW_THREADS and
// Py_END_ALLOW_THREADS.
struct without_gil_t {
without_gil_t();
~without_gil_t();
void release_gil();
void acquire_gil();
private:
PyThreadState *save = nullptr;
friend struct with_gil_t;
};
struct with_gil_t {
with_gil_t(without_gil_t& allow_threads);
~with_gil_t();
private:
without_gil_t& allow_threads;
};
// invoke func with GIL acquired
template<typename Func>
auto with_gil(without_gil_t& no_gil, Func&& func) {
with_gil_t gil{no_gil};
return std::invoke(std::forward<Func>(func));
}
template<typename Func>
auto without_gil(Func&& func) {
without_gil_t no_gil;
return std::invoke(std::forward<Func>(func));
}
| 2,834 | 23.652174 | 76 | h |
null | ceph-main/src/mgr/MDSPerfMetricCollector.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "common/debug.h"
#include "common/errno.h"
#include "messages/MMgrReport.h"
#include "mgr/MDSPerfMetricTypes.h"
#include "mgr/MDSPerfMetricCollector.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_mgr
#undef dout_prefix
#define dout_prefix *_dout << "mgr.mds_perf_metric_collector " << __func__ << " "
MDSPerfMetricCollector::MDSPerfMetricCollector(MetricListener &listener)
: MetricCollector<MDSPerfMetricQuery,
MDSPerfMetricLimit,
MDSPerfMetricKey,
MDSPerfMetrics>(listener) {
}
void MDSPerfMetricCollector::process_reports(const MetricPayload &payload) {
const MDSPerfMetricReport &metric_report = boost::get<MDSMetricPayload>(payload).metric_report;
std::lock_guard locker(lock);
process_reports_generic(
metric_report.reports, [](PerformanceCounter *counter, const PerformanceCounter &update) {
counter->first = update.first;
counter->second = update.second;
});
// update delayed rank set
delayed_ranks = metric_report.rank_metrics_delayed;
dout(20) << ": delayed ranks=[" << delayed_ranks << "]" << dendl;
clock_gettime(CLOCK_MONOTONIC_COARSE, &last_updated_mono);
}
int MDSPerfMetricCollector::get_counters(PerfCollector *collector) {
MDSPerfCollector *c = static_cast<MDSPerfCollector *>(collector);
std::lock_guard locker(lock);
int r = get_counters_generic(c->query_id, &c->counters);
if (r != 0) {
return r;
}
get_delayed_ranks(&c->delayed_ranks);
get_last_updated(&c->last_updated_mono);
return r;
}
void MDSPerfMetricCollector::get_delayed_ranks(std::set<mds_rank_t> *ranks) {
ceph_assert(ceph_mutex_is_locked(lock));
*ranks = delayed_ranks;
}
void MDSPerfMetricCollector::get_last_updated(utime_t *ts) {
ceph_assert(ceph_mutex_is_locked(lock));
*ts = utime_t(last_updated_mono);
}
| 1,965 | 29.246154 | 97 | cc |
null | ceph-main/src/mgr/MDSPerfMetricCollector.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_MGR_MDS_PERF_COLLECTOR_H
#define CEPH_MGR_MDS_PERF_COLLECTOR_H
#include "mgr/MetricCollector.h"
#include "mgr/MDSPerfMetricTypes.h"
// MDS performance query class
class MDSPerfMetricCollector
: public MetricCollector<MDSPerfMetricQuery, MDSPerfMetricLimit, MDSPerfMetricKey,
MDSPerfMetrics> {
private:
std::set<mds_rank_t> delayed_ranks;
struct timespec last_updated_mono;
void get_delayed_ranks(std::set<mds_rank_t> *ranks);
void get_last_updated(utime_t *ts);
public:
MDSPerfMetricCollector(MetricListener &listener);
void process_reports(const MetricPayload &payload) override;
int get_counters(PerfCollector *collector) override;
};
#endif // CEPH_MGR_MDS_PERF_COLLECTOR_H
| 838 | 27.931034 | 84 | h |
null | ceph-main/src/mgr/MDSPerfMetricTypes.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include <ostream>
#include "mgr/MDSPerfMetricTypes.h"
std::ostream& operator<<(std::ostream& os, const MDSPerfMetricSubKeyDescriptor &d) {
switch (d.type) {
case MDSPerfMetricSubKeyType::MDS_RANK:
os << "mds_rank";
break;
case MDSPerfMetricSubKeyType::CLIENT_ID:
os << "client_id";
break;
default:
os << "unknown (" << static_cast<int>(d.type) << ")";
}
return os << "~/" << d.regex_str << "/";
}
void MDSPerformanceCounterDescriptor::pack_counter(
const PerformanceCounter &c, bufferlist *bl) const {
using ceph::encode;
encode(c.first, *bl);
encode(c.second, *bl);
switch(type) {
case MDSPerformanceCounterType::CAP_HIT_METRIC:
case MDSPerformanceCounterType::READ_LATENCY_METRIC:
case MDSPerformanceCounterType::WRITE_LATENCY_METRIC:
case MDSPerformanceCounterType::METADATA_LATENCY_METRIC:
case MDSPerformanceCounterType::DENTRY_LEASE_METRIC:
case MDSPerformanceCounterType::OPENED_FILES_METRIC:
case MDSPerformanceCounterType::PINNED_ICAPS_METRIC:
case MDSPerformanceCounterType::OPENED_INODES_METRIC:
case MDSPerformanceCounterType::READ_IO_SIZES_METRIC:
case MDSPerformanceCounterType::WRITE_IO_SIZES_METRIC:
case MDSPerformanceCounterType::AVG_READ_LATENCY_METRIC:
case MDSPerformanceCounterType::STDEV_READ_LATENCY_METRIC:
case MDSPerformanceCounterType::AVG_WRITE_LATENCY_METRIC:
case MDSPerformanceCounterType::STDEV_WRITE_LATENCY_METRIC:
case MDSPerformanceCounterType::AVG_METADATA_LATENCY_METRIC:
case MDSPerformanceCounterType::STDEV_METADATA_LATENCY_METRIC:
break;
default:
ceph_abort_msg("unknown counter type");
}
}
void MDSPerformanceCounterDescriptor::unpack_counter(
bufferlist::const_iterator& bl, PerformanceCounter *c) const {
using ceph::decode;
decode(c->first, bl);
decode(c->second, bl);
switch(type) {
case MDSPerformanceCounterType::CAP_HIT_METRIC:
case MDSPerformanceCounterType::READ_LATENCY_METRIC:
case MDSPerformanceCounterType::WRITE_LATENCY_METRIC:
case MDSPerformanceCounterType::METADATA_LATENCY_METRIC:
case MDSPerformanceCounterType::DENTRY_LEASE_METRIC:
case MDSPerformanceCounterType::OPENED_FILES_METRIC:
case MDSPerformanceCounterType::PINNED_ICAPS_METRIC:
case MDSPerformanceCounterType::OPENED_INODES_METRIC:
case MDSPerformanceCounterType::READ_IO_SIZES_METRIC:
case MDSPerformanceCounterType::WRITE_IO_SIZES_METRIC:
case MDSPerformanceCounterType::AVG_READ_LATENCY_METRIC:
case MDSPerformanceCounterType::STDEV_READ_LATENCY_METRIC:
case MDSPerformanceCounterType::AVG_WRITE_LATENCY_METRIC:
case MDSPerformanceCounterType::STDEV_WRITE_LATENCY_METRIC:
case MDSPerformanceCounterType::AVG_METADATA_LATENCY_METRIC:
case MDSPerformanceCounterType::STDEV_METADATA_LATENCY_METRIC:
break;
default:
ceph_abort_msg("unknown counter type");
}
}
std::ostream& operator<<(std::ostream &os, const MDSPerformanceCounterDescriptor &d) {
switch(d.type) {
case MDSPerformanceCounterType::CAP_HIT_METRIC:
os << "cap_hit_metric";
break;
case MDSPerformanceCounterType::READ_LATENCY_METRIC:
os << "read_latency_metric";
break;
case MDSPerformanceCounterType::WRITE_LATENCY_METRIC:
os << "write_latency_metric";
break;
case MDSPerformanceCounterType::METADATA_LATENCY_METRIC:
os << "metadata_latency_metric";
break;
case MDSPerformanceCounterType::DENTRY_LEASE_METRIC:
os << "dentry_lease_metric";
break;
case MDSPerformanceCounterType::OPENED_FILES_METRIC:
os << "opened_files_metric";
break;
case MDSPerformanceCounterType::PINNED_ICAPS_METRIC:
os << "pinned_icaps_metric";
break;
case MDSPerformanceCounterType::OPENED_INODES_METRIC:
os << "opened_inodes_metric";
break;
case MDSPerformanceCounterType::READ_IO_SIZES_METRIC:
os << "read_io_sizes_metric";
break;
case MDSPerformanceCounterType::WRITE_IO_SIZES_METRIC:
os << "write_io_sizes_metric";
break;
case MDSPerformanceCounterType::AVG_READ_LATENCY_METRIC:
os << "avg_read_latency";
break;
case MDSPerformanceCounterType::STDEV_READ_LATENCY_METRIC:
os << "stdev_read_latency";
break;
case MDSPerformanceCounterType::AVG_WRITE_LATENCY_METRIC:
os << "avg_write_latency";
break;
case MDSPerformanceCounterType::STDEV_WRITE_LATENCY_METRIC:
os << "stdev_write_latency";
break;
case MDSPerformanceCounterType::AVG_METADATA_LATENCY_METRIC:
os << "avg_metadata_latency";
break;
case MDSPerformanceCounterType::STDEV_METADATA_LATENCY_METRIC:
os << "stdev_metadata_latency";
break;
}
return os;
}
std::ostream &operator<<(std::ostream &os, const MDSPerfMetricLimit &limit) {
return os << "[order_by=" << limit.order_by << ", max_count=" << limit.max_count << "]";
}
void MDSPerfMetricQuery::pack_counters(const PerformanceCounters &counters,
bufferlist *bl) const {
auto it = counters.begin();
for (auto &descriptor : performance_counter_descriptors) {
if (it == counters.end()) {
descriptor.pack_counter(PerformanceCounter(), bl);
} else {
descriptor.pack_counter(*it, bl);
it++;
}
}
}
std::ostream &operator<<(std::ostream &os, const MDSPerfMetricQuery &query) {
return os << "[key=" << query.key_descriptor << ", counter="
<< query.performance_counter_descriptors << "]";
}
| 5,513 | 34.805195 | 90 | cc |
null | ceph-main/src/mgr/MDSPerfMetricTypes.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_MGR_MDS_PERF_METRIC_TYPES_H
#define CEPH_MGR_MDS_PERF_METRIC_TYPES_H
#include <regex>
#include <vector>
#include <iostream>
#include "include/denc.h"
#include "include/stringify.h"
#include "mds/mdstypes.h"
#include "mgr/Types.h"
typedef std::vector<std::string> MDSPerfMetricSubKey; // array of regex match
typedef std::vector<MDSPerfMetricSubKey> MDSPerfMetricKey;
enum class MDSPerfMetricSubKeyType : uint8_t {
MDS_RANK = 0,
CLIENT_ID = 1,
};
struct MDSPerfMetricSubKeyDescriptor {
MDSPerfMetricSubKeyType type = static_cast<MDSPerfMetricSubKeyType>(-1);
std::string regex_str;
std::regex regex;
bool is_supported() const {
switch (type) {
case MDSPerfMetricSubKeyType::MDS_RANK:
case MDSPerfMetricSubKeyType::CLIENT_ID:
return true;
default:
return false;
}
}
MDSPerfMetricSubKeyDescriptor() {
}
MDSPerfMetricSubKeyDescriptor(MDSPerfMetricSubKeyType type, const std::string ®ex_str)
: type(type), regex_str(regex_str) {
}
bool operator<(const MDSPerfMetricSubKeyDescriptor &other) const {
if (type < other.type) {
return true;
}
if (type > other.type) {
return false;
}
return regex_str < other.regex_str;
}
DENC(MDSPerfMetricSubKeyDescriptor, v, p) {
DENC_START(1, 1, p);
denc(v.type, p);
denc(v.regex_str, p);
DENC_FINISH(p);
}
};
WRITE_CLASS_DENC(MDSPerfMetricSubKeyDescriptor)
std::ostream& operator<<(std::ostream& os, const MDSPerfMetricSubKeyDescriptor &d);
typedef std::vector<MDSPerfMetricSubKeyDescriptor> MDSPerfMetricKeyDescriptor;
template<>
struct denc_traits<MDSPerfMetricKeyDescriptor> {
static constexpr bool supported = true;
static constexpr bool bounded = false;
static constexpr bool featured = false;
static constexpr bool need_contiguous = true;
static void bound_encode(const MDSPerfMetricKeyDescriptor& v, size_t& p) {
p += sizeof(uint32_t);
const auto size = v.size();
if (size) {
size_t per = 0;
denc(v.front(), per);
p += per * size;
}
}
static void encode(const MDSPerfMetricKeyDescriptor& v,
ceph::buffer::list::contiguous_appender& p) {
denc_varint(v.size(), p);
for (auto& i : v) {
denc(i, p);
}
}
static void decode(MDSPerfMetricKeyDescriptor& v,
ceph::buffer::ptr::const_iterator& p) {
unsigned num;
denc_varint(num, p);
v.clear();
v.reserve(num);
for (unsigned i=0; i < num; ++i) {
MDSPerfMetricSubKeyDescriptor d;
denc(d, p);
if (!d.is_supported()) {
v.clear();
return;
}
try {
d.regex = d.regex_str.c_str();
} catch (const std::regex_error& e) {
v.clear();
return;
}
if (d.regex.mark_count() == 0) {
v.clear();
return;
}
v.push_back(std::move(d));
}
}
};
enum class MDSPerformanceCounterType : uint8_t {
CAP_HIT_METRIC = 0,
READ_LATENCY_METRIC = 1,
WRITE_LATENCY_METRIC = 2,
METADATA_LATENCY_METRIC = 3,
DENTRY_LEASE_METRIC = 4,
OPENED_FILES_METRIC = 5,
PINNED_ICAPS_METRIC = 6,
OPENED_INODES_METRIC = 7,
READ_IO_SIZES_METRIC = 8,
WRITE_IO_SIZES_METRIC = 9,
AVG_READ_LATENCY_METRIC = 10,
STDEV_READ_LATENCY_METRIC = 11,
AVG_WRITE_LATENCY_METRIC = 12,
STDEV_WRITE_LATENCY_METRIC = 13,
AVG_METADATA_LATENCY_METRIC = 14,
STDEV_METADATA_LATENCY_METRIC = 15,
};
struct MDSPerformanceCounterDescriptor {
MDSPerformanceCounterType type = static_cast<MDSPerformanceCounterType>(-1);
bool is_supported() const {
switch(type) {
case MDSPerformanceCounterType::CAP_HIT_METRIC:
case MDSPerformanceCounterType::READ_LATENCY_METRIC:
case MDSPerformanceCounterType::WRITE_LATENCY_METRIC:
case MDSPerformanceCounterType::METADATA_LATENCY_METRIC:
case MDSPerformanceCounterType::DENTRY_LEASE_METRIC:
case MDSPerformanceCounterType::OPENED_FILES_METRIC:
case MDSPerformanceCounterType::PINNED_ICAPS_METRIC:
case MDSPerformanceCounterType::OPENED_INODES_METRIC:
case MDSPerformanceCounterType::READ_IO_SIZES_METRIC:
case MDSPerformanceCounterType::WRITE_IO_SIZES_METRIC:
case MDSPerformanceCounterType::AVG_READ_LATENCY_METRIC:
case MDSPerformanceCounterType::STDEV_READ_LATENCY_METRIC:
case MDSPerformanceCounterType::AVG_WRITE_LATENCY_METRIC:
case MDSPerformanceCounterType::STDEV_WRITE_LATENCY_METRIC:
case MDSPerformanceCounterType::AVG_METADATA_LATENCY_METRIC:
case MDSPerformanceCounterType::STDEV_METADATA_LATENCY_METRIC:
return true;
default:
return false;
}
}
MDSPerformanceCounterDescriptor() {
}
MDSPerformanceCounterDescriptor(MDSPerformanceCounterType type) : type(type) {
}
bool operator<(const MDSPerformanceCounterDescriptor &other) const {
return type < other.type;
}
bool operator==(const MDSPerformanceCounterDescriptor &other) const {
return type == other.type;
}
bool operator!=(const MDSPerformanceCounterDescriptor &other) const {
return type != other.type;
}
DENC(MDSPerformanceCounterDescriptor, v, p) {
DENC_START(1, 1, p);
denc(v.type, p);
DENC_FINISH(p);
}
void pack_counter(const PerformanceCounter &c, ceph::buffer::list *bl) const;
void unpack_counter(ceph::buffer::list::const_iterator& bl, PerformanceCounter *c) const;
};
WRITE_CLASS_DENC(MDSPerformanceCounterDescriptor)
std::ostream& operator<<(std::ostream &os, const MDSPerformanceCounterDescriptor &d);
typedef std::vector<MDSPerformanceCounterDescriptor> MDSPerformanceCounterDescriptors;
template<>
struct denc_traits<MDSPerformanceCounterDescriptors> {
static constexpr bool supported = true;
static constexpr bool bounded = false;
static constexpr bool featured = false;
static constexpr bool need_contiguous = true;
static void bound_encode(const MDSPerformanceCounterDescriptors& v, size_t& p) {
p += sizeof(uint32_t);
const auto size = v.size();
if (size) {
size_t per = 0;
denc(v.front(), per);
p += per * size;
}
}
static void encode(const MDSPerformanceCounterDescriptors& v,
ceph::buffer::list::contiguous_appender& p) {
denc_varint(v.size(), p);
for (auto& i : v) {
denc(i, p);
}
}
static void decode(MDSPerformanceCounterDescriptors& v,
ceph::buffer::ptr::const_iterator& p) {
unsigned num;
denc_varint(num, p);
v.clear();
v.reserve(num);
for (unsigned i=0; i < num; ++i) {
MDSPerformanceCounterDescriptor d;
denc(d, p);
if (d.is_supported()) {
v.push_back(std::move(d));
}
}
}
};
struct MDSPerfMetricLimit {
MDSPerformanceCounterDescriptor order_by;
uint64_t max_count;
MDSPerfMetricLimit() {
}
MDSPerfMetricLimit(const MDSPerformanceCounterDescriptor &order_by, uint64_t max_count)
: order_by(order_by), max_count(max_count) {
}
bool operator<(const MDSPerfMetricLimit &other) const {
if (order_by != other.order_by) {
return order_by < other.order_by;
}
return max_count < other.max_count;
}
DENC(MDSPerfMetricLimit, v, p) {
DENC_START(1, 1, p);
denc(v.order_by, p);
denc(v.max_count, p);
DENC_FINISH(p);
}
};
WRITE_CLASS_DENC(MDSPerfMetricLimit)
std::ostream &operator<<(std::ostream &os, const MDSPerfMetricLimit &limit);
typedef std::set<MDSPerfMetricLimit> MDSPerfMetricLimits;
struct MDSPerfMetricQuery {
MDSPerfMetricKeyDescriptor key_descriptor;
MDSPerformanceCounterDescriptors performance_counter_descriptors;
MDSPerfMetricQuery() {
}
MDSPerfMetricQuery(const MDSPerfMetricKeyDescriptor &key_descriptor,
const MDSPerformanceCounterDescriptors &performance_counter_descriptors)
: key_descriptor(key_descriptor),
performance_counter_descriptors(performance_counter_descriptors)
{
}
bool operator<(const MDSPerfMetricQuery &other) const {
if (key_descriptor < other.key_descriptor) {
return true;
}
if (key_descriptor > other.key_descriptor) {
return false;
}
return performance_counter_descriptors < other.performance_counter_descriptors;
}
template <typename L>
bool get_key(L&& get_sub_key, MDSPerfMetricKey *key) const {
for (auto &sub_key_descriptor : key_descriptor) {
MDSPerfMetricSubKey sub_key;
if (!get_sub_key(sub_key_descriptor, &sub_key)) {
return false;
}
key->push_back(sub_key);
}
return true;
}
void get_performance_counter_descriptors(MDSPerformanceCounterDescriptors *descriptors) const {
*descriptors = performance_counter_descriptors;
}
template <typename L>
void update_counters(L &&update_counter, PerformanceCounters *counters) const {
auto it = counters->begin();
for (auto &descriptor : performance_counter_descriptors) {
// TODO: optimize
if (it == counters->end()) {
counters->push_back(PerformanceCounter());
it = std::prev(counters->end());
}
update_counter(descriptor, &(*it));
it++;
}
}
DENC(MDSPerfMetricQuery, v, p) {
DENC_START(1, 1, p);
denc(v.key_descriptor, p);
denc(v.performance_counter_descriptors, p);
DENC_FINISH(p);
}
void pack_counters(const PerformanceCounters &counters, ceph::buffer::list *bl) const;
};
WRITE_CLASS_DENC(MDSPerfMetricQuery)
std::ostream &operator<<(std::ostream &os, const MDSPerfMetricQuery &query);
struct MDSPerfCollector : PerfCollector {
std::map<MDSPerfMetricKey, PerformanceCounters> counters;
std::set<mds_rank_t> delayed_ranks;
utime_t last_updated_mono;
MDSPerfCollector(MetricQueryID query_id)
: PerfCollector(query_id) {
}
};
struct MDSPerfMetrics {
MDSPerformanceCounterDescriptors performance_counter_descriptors;
std::map<MDSPerfMetricKey, ceph::buffer::list> group_packed_performance_counters;
DENC(MDSPerfMetrics, v, p) {
DENC_START(1, 1, p);
denc(v.performance_counter_descriptors, p);
denc(v.group_packed_performance_counters, p);
DENC_FINISH(p);
}
};
struct MDSPerfMetricReport {
std::map<MDSPerfMetricQuery, MDSPerfMetrics> reports;
// set of active ranks that have delayed (stale) metrics
std::set<mds_rank_t> rank_metrics_delayed;
DENC(MDSPerfMetricReport, v, p) {
DENC_START(1, 1, p);
denc(v.reports, p);
denc(v.rank_metrics_delayed, p);
DENC_FINISH(p);
}
};
WRITE_CLASS_DENC(MDSPerfMetrics)
WRITE_CLASS_DENC(MDSPerfMetricReport)
#endif // CEPH_MGR_MDS_PERF_METRIC_TYPES_H
| 10,607 | 27.826087 | 97 | h |
null | ceph-main/src/mgr/MetricCollector.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "common/debug.h"
#include "common/errno.h"
#include "mgr/MetricCollector.h"
#include "mgr/OSDPerfMetricTypes.h"
#include "mgr/MDSPerfMetricTypes.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_mgr
#undef dout_prefix
#define dout_prefix *_dout << "mgr.metric_collector " << __func__ << ": "
template <typename Query, typename Limit, typename Key, typename Report>
MetricCollector<Query, Limit, Key, Report>::MetricCollector(MetricListener &listener)
: listener(listener)
{
}
template <typename Query, typename Limit, typename Key, typename Report>
MetricQueryID MetricCollector<Query, Limit, Key, Report>::add_query(
const Query &query,
const std::optional<Limit> &limit) {
dout(20) << "query=" << query << ", limit=" << limit << dendl;
uint64_t query_id;
bool notify = false;
{
std::lock_guard locker(lock);
query_id = next_query_id++;
auto it = queries.find(query);
if (it == queries.end()) {
it = queries.emplace(query, std::map<MetricQueryID, OptionalLimit>{}).first;
notify = true;
} else if (is_limited(it->second)) {
notify = true;
}
it->second.emplace(query_id, limit);
counters.emplace(query_id, std::map<Key, PerformanceCounters>{});
}
dout(10) << query << " " << (limit ? stringify(*limit) : "unlimited")
<< " query_id=" << query_id << dendl;
if (notify) {
listener.handle_query_updated();
}
return query_id;
}
template <typename Query, typename Limit, typename Key, typename Report>
int MetricCollector<Query, Limit, Key, Report>::remove_query(MetricQueryID query_id) {
dout(20) << "query_id=" << query_id << dendl;
bool found = false;
bool notify = false;
{
std::lock_guard locker(lock);
for (auto it = queries.begin() ; it != queries.end();) {
auto iter = it->second.find(query_id);
if (iter == it->second.end()) {
++it;
continue;
}
it->second.erase(iter);
if (it->second.empty()) {
it = queries.erase(it);
notify = true;
} else if (is_limited(it->second)) {
++it;
notify = true;
}
found = true;
break;
}
counters.erase(query_id);
}
if (!found) {
dout(10) << query_id << " not found" << dendl;
return -ENOENT;
}
dout(10) << query_id << dendl;
if (notify) {
listener.handle_query_updated();
}
return 0;
}
template <typename Query, typename Limit, typename Key, typename Report>
void MetricCollector<Query, Limit, Key, Report>::remove_all_queries() {
dout(20) << dendl;
bool notify;
{
std::lock_guard locker(lock);
notify = !queries.empty();
queries.clear();
}
if (notify) {
listener.handle_query_updated();
}
}
template <typename Query, typename Limit, typename Key, typename Report>
void MetricCollector<Query, Limit, Key, Report>::reregister_queries() {
dout(20) << dendl;
listener.handle_query_updated();
}
template <typename Query, typename Limit, typename Key, typename Report>
int MetricCollector<Query, Limit, Key, Report>::get_counters_generic(
MetricQueryID query_id, std::map<Key, PerformanceCounters> *c) {
dout(20) << dendl;
ceph_assert(ceph_mutex_is_locked(lock));
auto it = counters.find(query_id);
if (it == counters.end()) {
dout(10) << "counters for " << query_id << " not found" << dendl;
return -ENOENT;
}
*c = std::move(it->second);
it->second.clear();
return 0;
}
template <typename Query, typename Limit, typename Key, typename Report>
void MetricCollector<Query, Limit, Key, Report>::process_reports_generic(
const std::map<Query, Report> &reports, UpdateCallback callback) {
ceph_assert(ceph_mutex_is_locked(lock));
if (reports.empty()) {
return;
}
for (auto& [query, report] : reports) {
dout(10) << "report for " << query << " query: "
<< report.group_packed_performance_counters.size() << " records"
<< dendl;
for (auto& [key, bl] : report.group_packed_performance_counters) {
auto bl_it = bl.cbegin();
for (auto& p : queries[query]) {
auto &key_counters = counters[p.first][key];
if (key_counters.empty()) {
key_counters.resize(query.performance_counter_descriptors.size(),
{0, 0});
}
}
auto desc_it = report.performance_counter_descriptors.begin();
for (size_t i = 0; i < query.performance_counter_descriptors.size(); i++) {
if (desc_it == report.performance_counter_descriptors.end()) {
break;
}
if (*desc_it != query.performance_counter_descriptors[i]) {
continue;
}
PerformanceCounter c;
desc_it->unpack_counter(bl_it, &c);
dout(20) << "counter " << key << " " << *desc_it << ": " << c << dendl;
for (auto& p : queries[query]) {
auto &key_counters = counters[p.first][key];
callback(&key_counters[i], c);
}
desc_it++;
}
}
}
}
template class
MetricCollector<OSDPerfMetricQuery, OSDPerfMetricLimit, OSDPerfMetricKey, OSDPerfMetricReport>;
template class
MetricCollector<MDSPerfMetricQuery, MDSPerfMetricLimit, MDSPerfMetricKey, MDSPerfMetrics>;
| 5,334 | 26.786458 | 95 | cc |
null | ceph-main/src/mgr/MetricCollector.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_MGR_METRIC_COLLECTOR_H
#define CEPH_MGR_METRIC_COLLECTOR_H
#include <map>
#include <set>
#include <tuple>
#include <vector>
#include <utility>
#include <algorithm>
#include "common/ceph_mutex.h"
#include "msg/Message.h"
#include "mgr/Types.h"
#include "mgr/MetricTypes.h"
class MMgrReport;
template <typename Query, typename Limit, typename Key, typename Report>
class MetricCollector {
public:
virtual ~MetricCollector() {
}
using Limits = std::set<Limit>;
MetricCollector(MetricListener &listener);
MetricQueryID add_query(const Query &query, const std::optional<Limit> &limit);
int remove_query(MetricQueryID query_id);
void remove_all_queries();
void reregister_queries();
std::map<Query, Limits> get_queries() const {
std::lock_guard locker(lock);
std::map<Query, Limits> result;
for (auto& [query, limits] : queries) {
auto result_it = result.insert({query, {}}).first;
if (is_limited(limits)) {
for (auto& limit : limits) {
if (limit.second) {
result_it->second.insert(*limit.second);
}
}
}
}
return result;
}
virtual void process_reports(const MetricPayload &payload) = 0;
virtual int get_counters(PerfCollector *collector) = 0;
protected:
typedef std::optional<Limit> OptionalLimit;
typedef std::map<MetricQueryID, OptionalLimit> QueryIDLimit;
typedef std::map<Query, QueryIDLimit> Queries;
typedef std::map<MetricQueryID, std::map<Key, PerformanceCounters>> Counters;
typedef std::function<void(PerformanceCounter *, const PerformanceCounter &)> UpdateCallback;
mutable ceph::mutex lock = ceph::make_mutex("mgr::metric::collector::lock");
Queries queries;
Counters counters;
void process_reports_generic(const std::map<Query, Report> &reports, UpdateCallback callback);
int get_counters_generic(MetricQueryID query_id, std::map<Key, PerformanceCounters> *counters);
private:
MetricListener &listener;
MetricQueryID next_query_id = 0;
bool is_limited(const std::map<MetricQueryID, OptionalLimit> &limits) const {
return std::any_of(begin(limits), end(limits),
[](auto &limits) { return limits.second.has_value(); });
}
};
#endif // CEPH_MGR_METRIC_COLLECTOR_H
| 2,367 | 26.534884 | 97 | h |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.