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/common/hex.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) 2008-2011 New Dream Network
*
* 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 "common/hex.h"
void hex2str(const char *s, int len, char *buf, int dest_len)
{
int pos = 0;
for (int i=0; i<len && pos<dest_len; i++) {
if (i && !(i%8))
pos += snprintf(&buf[pos], dest_len-pos, " ");
if (i && !(i%16))
pos += snprintf(&buf[pos], dest_len-pos, "\n");
pos += snprintf(&buf[pos], dest_len-pos, "%.2x ", (int)(unsigned char)s[i]);
}
}
std::string hexdump(const std::string &msg, const char *s, int len)
{
int buf_len = len*4;
char buf[buf_len];
hex2str(s, len, buf, buf_len);
return buf;
}
| 965 | 25.833333 | 80 | cc |
null | ceph-main/src/common/hex.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) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_COMMON_HEX_H
#define CEPH_COMMON_HEX_H
#include <string>
extern void hex2str(const char *s, int len, char *buf, int dest_len);
extern std::string hexdump(std::string msg, const char *s, int len);
#endif
| 630 | 23.269231 | 70 | h |
null | ceph-main/src/common/histogram.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) 2011 New Dream Network
*
* 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 "common/histogram.h"
#include "common/Formatter.h"
// -- pow2_hist_t --
void pow2_hist_t::dump(ceph::Formatter *f) const
{
f->open_array_section("histogram");
for (std::vector<int32_t>::const_iterator p = h.begin(); p != h.end(); ++p)
f->dump_int("count", *p);
f->close_section();
f->dump_int("upper_bound", upper_bound());
}
void pow2_hist_t::encode(ceph::buffer::list& bl) const
{
ENCODE_START(1, 1, bl);
encode(h, bl);
ENCODE_FINISH(bl);
}
void pow2_hist_t::decode(ceph::buffer::list::const_iterator& p)
{
DECODE_START(1, p);
decode(h, p);
DECODE_FINISH(p);
}
void pow2_hist_t::generate_test_instances(std::list<pow2_hist_t*>& ls)
{
ls.push_back(new pow2_hist_t);
ls.push_back(new pow2_hist_t);
ls.back()->h.push_back(1);
ls.back()->h.push_back(3);
ls.back()->h.push_back(0);
ls.back()->h.push_back(2);
}
void pow2_hist_t::decay(int bits)
{
for (std::vector<int32_t>::iterator p = h.begin(); p != h.end(); ++p) {
*p >>= bits;
}
_contract();
}
| 1,415 | 23 | 77 | cc |
null | ceph-main/src/common/histogram.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
* Copyright 2013 Inktank
*/
#ifndef CEPH_HISTOGRAM_H
#define CEPH_HISTOGRAM_H
#include <list>
#include "include/encoding.h"
#include "include/intarith.h"
namespace ceph {
class Formatter;
}
/**
* power of 2 histogram
*/
struct pow2_hist_t { //
/**
* histogram
*
* bin size is 2^index
* value is count of elements that are <= the current bin but > the previous bin.
*/
std::vector<int32_t> h;
private:
/// expand to at least another's size
void _expand_to(unsigned s) {
if (s > h.size())
h.resize(s, 0);
}
/// drop useless trailing 0's
void _contract() {
unsigned p = h.size();
while (p > 0 && h[p-1] == 0)
--p;
h.resize(p);
}
public:
void clear() {
h.clear();
}
bool empty() const {
return h.empty();
}
void set_bin(int bin, int32_t count) {
_expand_to(bin + 1);
h[bin] = count;
_contract();
}
void add(int32_t v) {
int bin = cbits(v);
_expand_to(bin + 1);
h[bin]++;
_contract();
}
bool operator==(const pow2_hist_t &r) const {
return h == r.h;
}
/// get a value's position in the histogram.
///
/// positions are represented as values in the range [0..1000000]
/// (millionths on the unit interval).
///
/// @param v [in] value (non-negative)
/// @param lower [out] pointer to lower-bound (0..1000000)
/// @param upper [out] pointer to the upper bound (0..1000000)
int get_position_micro(int32_t v, uint64_t *lower, uint64_t *upper) {
if (v < 0)
return -1;
unsigned bin = cbits(v);
uint64_t lower_sum = 0, upper_sum = 0, total = 0;
for (unsigned i=0; i<h.size(); ++i) {
if (i <= bin)
upper_sum += h[i];
if (i < bin)
lower_sum += h[i];
total += h[i];
}
if (total > 0) {
*lower = lower_sum * 1000000 / total;
*upper = upper_sum * 1000000 / total;
}
return 0;
}
void add(const pow2_hist_t& o) {
_expand_to(o.h.size());
for (unsigned p = 0; p < o.h.size(); ++p)
h[p] += o.h[p];
_contract();
}
void sub(const pow2_hist_t& o) {
_expand_to(o.h.size());
for (unsigned p = 0; p < o.h.size(); ++p)
h[p] -= o.h[p];
_contract();
}
int32_t upper_bound() const {
return 1 << h.size();
}
/// decay histogram by N bits (default 1, for a halflife)
void decay(int bits = 1);
void dump(ceph::Formatter *f) const;
void encode(ceph::buffer::list &bl) const;
void decode(ceph::buffer::list::const_iterator &bl);
static void generate_test_instances(std::list<pow2_hist_t*>& o);
};
WRITE_CLASS_ENCODER(pow2_hist_t)
#endif /* CEPH_HISTOGRAM_H */
| 2,973 | 22.054264 | 83 | h |
null | ceph-main/src/common/hobject.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include <charconv>
#include "hobject.h"
#include "common/Formatter.h"
using std::list;
using std::ostream;
using std::set;
using std::string;
using ceph::bufferlist;
using ceph::Formatter;
static void append_escaped(const string &in, string *out)
{
for (string::const_iterator i = in.begin(); i != in.end(); ++i) {
if (*i == '%') {
out->push_back('%');
out->push_back('p');
} else if (*i == '.') {
out->push_back('%');
out->push_back('e');
} else if (*i == '_') {
out->push_back('%');
out->push_back('u');
} else {
out->push_back(*i);
}
}
}
set<string> hobject_t::get_prefixes(
uint32_t bits,
uint32_t mask,
int64_t pool)
{
uint32_t len = bits;
while (len % 4 /* nibbles */) len++;
set<uint32_t> from;
if (bits < 32)
from.insert(mask & ~((uint32_t)(~0) << bits));
else if (bits == 32)
from.insert(mask);
else
ceph_abort();
set<uint32_t> to;
for (uint32_t i = bits; i < len; ++i) {
for (set<uint32_t>::iterator j = from.begin();
j != from.end();
++j) {
to.insert(*j | (1U << i));
to.insert(*j);
}
to.swap(from);
to.clear();
}
char buf[20];
char *t = buf;
uint64_t poolid(pool);
t += snprintf(t, sizeof(buf), "%.*llX", 16, (long long unsigned)poolid);
*(t++) = '.';
string poolstr(buf, t - buf);
set<string> ret;
for (set<uint32_t>::iterator i = from.begin();
i != from.end();
++i) {
uint32_t revhash(hobject_t::_reverse_nibbles(*i));
snprintf(buf, sizeof(buf), "%.*X", (int)(sizeof(revhash))*2, revhash);
ret.insert(poolstr + string(buf, len/4));
}
return ret;
}
string hobject_t::to_str() const
{
string out;
char snap_with_hash[1000];
char *t = snap_with_hash;
const char *end = t + sizeof(snap_with_hash);
uint64_t poolid(pool);
t += snprintf(t, end - t, "%.*llX", 16, (long long unsigned)poolid);
uint32_t revhash(get_nibblewise_key_u32());
t += snprintf(t, end - t, ".%.*X", 8, revhash);
if (snap == CEPH_NOSNAP)
t += snprintf(t, end - t, ".head");
else if (snap == CEPH_SNAPDIR)
t += snprintf(t, end - t, ".snapdir");
else
t += snprintf(t, end - t, ".%llx", (long long unsigned)snap);
out.append(snap_with_hash, t);
out.push_back('.');
append_escaped(oid.name, &out);
out.push_back('.');
append_escaped(get_key(), &out);
out.push_back('.');
append_escaped(nspace, &out);
return out;
}
void hobject_t::encode(bufferlist& bl) const
{
ENCODE_START(4, 3, bl);
encode(key, bl);
encode(oid, bl);
encode(snap, bl);
encode(hash, bl);
encode(max, bl);
encode(nspace, bl);
encode(pool, bl);
ceph_assert(!max || (*this == hobject_t(hobject_t::get_max())));
ENCODE_FINISH(bl);
}
void hobject_t::decode(bufferlist::const_iterator& bl)
{
DECODE_START_LEGACY_COMPAT_LEN(4, 3, 3, bl);
if (struct_v >= 1)
decode(key, bl);
decode(oid, bl);
decode(snap, bl);
decode(hash, bl);
if (struct_v >= 2)
decode(max, bl);
else
max = false;
if (struct_v >= 4) {
decode(nspace, bl);
decode(pool, bl);
// for compat with hammer, which did not handle the transition
// from pool -1 -> pool INT64_MIN for MIN properly. this object
// name looks a bit like a pgmeta object for the meta collection,
// but those do not ever exist (and is_pgmeta() pool >= 0).
if (pool == -1 &&
snap == 0 &&
hash == 0 &&
!max &&
oid.name.empty()) {
pool = INT64_MIN;
ceph_assert(is_min());
}
// for compatibility with some earlier verisons which might encoded
// a non-canonical max object
if (max) {
*this = hobject_t::get_max();
}
}
DECODE_FINISH(bl);
build_hash_cache();
}
void hobject_t::decode(json_spirit::Value& v)
{
using namespace json_spirit;
Object& o = v.get_obj();
for (Object::size_type i=0; i<o.size(); i++) {
Pair& p = o[i];
if (p.name_ == "oid")
oid.name = p.value_.get_str();
else if (p.name_ == "key")
key = p.value_.get_str();
else if (p.name_ == "snapid")
snap = p.value_.get_uint64();
else if (p.name_ == "hash")
hash = p.value_.get_int();
else if (p.name_ == "max")
max = p.value_.get_int();
else if (p.name_ == "pool")
pool = p.value_.get_int();
else if (p.name_ == "namespace")
nspace = p.value_.get_str();
}
build_hash_cache();
}
void hobject_t::dump(Formatter *f) const
{
f->dump_string("oid", oid.name);
f->dump_string("key", key);
f->dump_int("snapid", snap);
f->dump_int("hash", hash);
f->dump_int("max", (int)max);
f->dump_int("pool", pool);
f->dump_string("namespace", nspace);
}
void hobject_t::generate_test_instances(list<hobject_t*>& o)
{
o.push_back(new hobject_t);
o.push_back(new hobject_t);
o.back()->max = true;
o.push_back(new hobject_t(object_t("oname"), string(), 1, 234, -1, ""));
o.push_back(new hobject_t(object_t("oname2"), string("okey"), CEPH_NOSNAP,
67, 0, "n1"));
o.push_back(new hobject_t(object_t("oname3"), string("oname3"),
CEPH_SNAPDIR, 910, 1, "n2"));
}
static void append_out_escaped(const string &in, string *out)
{
for (auto c : in) {
int i = (int)(unsigned char)(c);
if (i <= 0x0f) {
char buf[4] = {'%', '0'};
std::to_chars(buf + 2, buf + 3, i, 16);
out->append(buf);
} else if (i < 32 || i >= 127 || i == '%' || i == ':' || i == '/') {
char buf[4] = {'%'};
std::to_chars(buf + 1, buf + 3, i, 16);
out->append(buf);
} else {
out->push_back(c);
}
}
}
static const char *decode_out_escaped(const char *in, string *out)
{
while (*in && *in != ':') {
if (*in == '%') {
++in;
char buf[3];
buf[0] = *in;
++in;
buf[1] = *in;
buf[2] = 0;
int v = strtol(buf, NULL, 16);
out->push_back(v);
} else {
out->push_back(*in);
}
++in;
}
return in;
}
ostream& operator<<(ostream& out, const hobject_t& o)
{
if (o == hobject_t())
return out << "MIN";
if (o.is_max())
return out << "MAX";
out << o.pool << ':';
out << std::hex;
out.width(8);
out.fill('0');
out << o.get_bitwise_key_u32(); // << '~' << o.get_hash();
out.width(0);
out.fill(' ');
out << std::dec;
out << ':';
string v;
append_out_escaped(o.nspace, &v);
v.push_back(':');
append_out_escaped(o.get_key(), &v);
v.push_back(':');
append_out_escaped(o.oid.name, &v);
out << v << ':' << o.snap;
return out;
}
bool hobject_t::parse(const string &s)
{
if (s == "MIN") {
*this = hobject_t();
return true;
}
if (s == "MAX") {
*this = hobject_t::get_max();
return true;
}
const char *start = s.c_str();
long long po;
unsigned h;
int r = sscanf(start, "%lld:%x:", &po, &h);
if (r != 2)
return false;
for (; *start && *start != ':'; ++start) ;
for (++start; *start && isxdigit(*start); ++start) ;
if (*start != ':')
return false;
string ns, k, name;
const char *p = decode_out_escaped(start + 1, &ns);
if (*p != ':')
return false;
p = decode_out_escaped(p + 1, &k);
if (*p != ':')
return false;
p = decode_out_escaped(p + 1, &name);
if (*p != ':')
return false;
start = p + 1;
unsigned long long sn;
if (strncmp(start, "head", 4) == 0) {
sn = CEPH_NOSNAP;
start += 4;
if (*start != 0)
return false;
} else {
r = sscanf(start, "%llx", &sn);
if (r != 1)
return false;
for (++start; *start && isxdigit(*start); ++start) ;
if (*start)
return false;
}
max = false;
pool = po;
set_hash(_reverse_bits(h));
nspace = ns;
oid.name = name;
set_key(k);
snap = sn;
return true;
}
int cmp(const hobject_t& l, const hobject_t& r)
{
if (l.max < r.max)
return -1;
if (l.max > r.max)
return 1;
if (l.pool < r.pool)
return -1;
if (l.pool > r.pool)
return 1;
if (l.get_bitwise_key() < r.get_bitwise_key())
return -1;
if (l.get_bitwise_key() > r.get_bitwise_key())
return 1;
if (l.nspace < r.nspace)
return -1;
if (l.nspace > r.nspace)
return 1;
if (!(l.get_key().empty() && r.get_key().empty())) {
if (l.get_effective_key() < r.get_effective_key()) {
return -1;
}
if (l.get_effective_key() > r.get_effective_key()) {
return 1;
}
}
if (l.oid < r.oid)
return -1;
if (l.oid > r.oid)
return 1;
if (l.snap < r.snap)
return -1;
if (l.snap > r.snap)
return 1;
return 0;
}
// This is compatible with decode for hobject_t prior to
// version 5.
void ghobject_t::encode(bufferlist& bl) const
{
// when changing this, remember to update encoded_size() too.
ENCODE_START(6, 3, bl);
encode(hobj.key, bl);
encode(hobj.oid, bl);
encode(hobj.snap, bl);
encode(hobj.hash, bl);
encode(hobj.max, bl);
encode(hobj.nspace, bl);
encode(hobj.pool, bl);
encode(generation, bl);
encode(shard_id, bl);
encode(max, bl);
ENCODE_FINISH(bl);
}
size_t ghobject_t::encoded_size() const
{
// this is not in order of encoding or appearance, but rather
// in order of known constants first, so it can be (mostly) computed
// at compile time.
// - encoding header + 3 string lengths
size_t r = sizeof(ceph_le32) + 2 * sizeof(__u8) + 3 * sizeof(__u32);
// hobj.snap
r += sizeof(uint64_t);
// hobj.hash
r += sizeof(uint32_t);
// hobj.max
r += sizeof(bool);
// hobj.pool
r += sizeof(uint64_t);
// hobj.generation
r += sizeof(uint64_t);
// hobj.shard_id
r += sizeof(int8_t);
// max
r += sizeof(bool);
// hobj.key
r += hobj.key.size();
// hobj.oid
r += hobj.oid.name.size();
// hobj.nspace
r += hobj.nspace.size();
return r;
}
void ghobject_t::decode(bufferlist::const_iterator& bl)
{
DECODE_START_LEGACY_COMPAT_LEN(6, 3, 3, bl);
if (struct_v >= 1)
decode(hobj.key, bl);
decode(hobj.oid, bl);
decode(hobj.snap, bl);
decode(hobj.hash, bl);
if (struct_v >= 2)
decode(hobj.max, bl);
else
hobj.max = false;
if (struct_v >= 4) {
decode(hobj.nspace, bl);
decode(hobj.pool, bl);
// for compat with hammer, which did not handle the transition from
// pool -1 -> pool INT64_MIN for MIN properly (see hobject_t::decode()).
if (hobj.pool == -1 &&
hobj.snap == 0 &&
hobj.hash == 0 &&
!hobj.max &&
hobj.oid.name.empty()) {
hobj.pool = INT64_MIN;
ceph_assert(hobj.is_min());
}
}
if (struct_v >= 5) {
decode(generation, bl);
decode(shard_id, bl);
} else {
generation = ghobject_t::NO_GEN;
shard_id = shard_id_t::NO_SHARD;
}
if (struct_v >= 6) {
decode(max, bl);
} else {
max = false;
}
DECODE_FINISH(bl);
hobj.build_hash_cache();
}
void ghobject_t::decode(json_spirit::Value& v)
{
hobj.decode(v);
using namespace json_spirit;
Object& o = v.get_obj();
for (Object::size_type i=0; i<o.size(); i++) {
Pair& p = o[i];
if (p.name_ == "generation")
generation = p.value_.get_uint64();
else if (p.name_ == "shard_id")
shard_id.id = p.value_.get_int();
else if (p.name_ == "max")
max = p.value_.get_int();
}
}
void ghobject_t::dump(Formatter *f) const
{
hobj.dump(f);
if (generation != NO_GEN)
f->dump_int("generation", generation);
if (shard_id != shard_id_t::NO_SHARD)
f->dump_int("shard_id", shard_id);
f->dump_int("max", (int)max);
}
void ghobject_t::generate_test_instances(list<ghobject_t*>& o)
{
o.push_back(new ghobject_t);
o.push_back(new ghobject_t);
o.back()->hobj.max = true;
o.push_back(new ghobject_t(hobject_t(object_t("oname"), string(), 1, 234, -1, "")));
o.push_back(new ghobject_t(hobject_t(object_t("oname2"), string("okey"), CEPH_NOSNAP,
67, 0, "n1"), 1, shard_id_t(0)));
o.push_back(new ghobject_t(hobject_t(object_t("oname2"), string("okey"), CEPH_NOSNAP,
67, 0, "n1"), 1, shard_id_t(1)));
o.push_back(new ghobject_t(hobject_t(object_t("oname2"), string("okey"), CEPH_NOSNAP,
67, 0, "n1"), 1, shard_id_t(2)));
o.push_back(new ghobject_t(hobject_t(object_t("oname3"), string("oname3"),
CEPH_SNAPDIR, 910, 1, "n2"), 1, shard_id_t(0)));
o.push_back(new ghobject_t(hobject_t(object_t("oname3"), string("oname3"),
CEPH_SNAPDIR, 910, 1, "n2"), 2, shard_id_t(0)));
o.push_back(new ghobject_t(hobject_t(object_t("oname3"), string("oname3"),
CEPH_SNAPDIR, 910, 1, "n2"), 3, shard_id_t(0)));
o.push_back(new ghobject_t(hobject_t(object_t("oname3"), string("oname3"),
CEPH_SNAPDIR, 910, 1, "n2"), 3, shard_id_t(1)));
o.push_back(new ghobject_t(hobject_t(object_t("oname3"), string("oname3"),
CEPH_SNAPDIR, 910, 1, "n2"), 3, shard_id_t(2)));
}
ostream& operator<<(ostream& out, const ghobject_t& o)
{
if (o == ghobject_t())
return out << "GHMIN";
if (o.is_max())
return out << "GHMAX";
if (o.shard_id != shard_id_t::NO_SHARD)
out << std::hex << o.shard_id << std::dec;
out << '#' << o.hobj << '#';
if (o.generation != ghobject_t::NO_GEN)
out << std::hex << (unsigned long long)(o.generation) << std::dec;
return out;
}
bool ghobject_t::parse(const string& s)
{
if (s == "GHMIN") {
*this = ghobject_t();
return true;
}
if (s == "GHMAX") {
*this = ghobject_t::get_max();
return true;
}
// look for shard# prefix
const char *start = s.c_str();
const char *p;
int sh = shard_id_t::NO_SHARD;
for (p = start; *p && isxdigit(*p); ++p) ;
if (!*p && *p != '#')
return false;
if (p > start) {
int r = sscanf(s.c_str(), "%x", &sh);
if (r < 1)
return false;
start = p + 1;
} else {
++start;
}
// look for #generation suffix
long long unsigned g = NO_GEN;
const char *last = start + strlen(start) - 1;
p = last;
while (isxdigit(*p))
p--;
if (*p != '#')
return false;
if (p < last) {
sscanf(p + 1, "%llx", &g);
}
string inner(start, p - start);
hobject_t h;
if (!h.parse(inner)) {
return false;
}
shard_id = shard_id_t(sh);
hobj = h;
generation = g;
max = false;
return true;
}
int cmp(const ghobject_t& l, const ghobject_t& r)
{
if (l.max < r.max)
return -1;
if (l.max > r.max)
return 1;
if (l.shard_id < r.shard_id)
return -1;
if (l.shard_id > r.shard_id)
return 1;
int ret = cmp(l.hobj, r.hobj);
if (ret != 0)
return ret;
if (l.generation < r.generation)
return -1;
if (l.generation > r.generation)
return 1;
return 0;
}
| 14,478 | 22.658497 | 87 | cc |
null | ceph-main/src/common/hobject.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_OS_HOBJECT_H
#define __CEPH_OS_HOBJECT_H
#if FMT_VERSION >= 90000
#include <fmt/ostream.h>
#endif
#include "include/types.h"
#include "json_spirit/json_spirit_value.h"
#include "include/ceph_assert.h" // spirit clobbers it!
#include "reverse.h"
namespace ceph {
class Formatter;
}
#ifndef UINT64_MAX
#define UINT64_MAX (18446744073709551615ULL)
#endif
#ifndef INT64_MIN
#define INT64_MIN ((int64_t)0x8000000000000000ll)
#endif
struct hobject_t {
public:
static const int64_t POOL_META = -1;
static const int64_t POOL_TEMP_START = -2; // and then negative
static bool is_temp_pool(int64_t pool) {
return pool <= POOL_TEMP_START;
}
static int64_t get_temp_pool(int64_t pool) {
return POOL_TEMP_START - pool;
}
static bool is_meta_pool(int64_t pool) {
return pool == POOL_META;
}
public:
object_t oid;
snapid_t snap;
private:
uint32_t hash;
bool max;
uint32_t nibblewise_key_cache;
uint32_t hash_reverse_bits;
public:
int64_t pool;
std::string nspace;
private:
std::string key;
class hobject_t_max {};
public:
const std::string& get_key() const {
return key;
}
void set_key(const std::string& key_) {
if (key_ == oid.name)
key.clear();
else
key = key_;
}
std::string to_str() const;
uint32_t get_hash() const {
return hash;
}
void set_hash(uint32_t value) {
hash = value;
build_hash_cache();
}
static bool match_hash(uint32_t to_check, uint32_t bits, uint32_t match) {
return (match & ~((~0)<<bits)) == (to_check & ~((~0)<<bits));
}
bool match(uint32_t bits, uint32_t match) const {
return match_hash(hash, bits, match);
}
bool is_temp() const {
return is_temp_pool(pool) && pool != INT64_MIN;
}
bool is_meta() const {
return is_meta_pool(pool);
}
int64_t get_logical_pool() const {
if (is_temp_pool(pool))
return get_temp_pool(pool); // it's reversible
else
return pool;
}
hobject_t() : snap(0), hash(0), max(false), pool(INT64_MIN) {
build_hash_cache();
}
hobject_t(const hobject_t &rhs) = default;
hobject_t(hobject_t &&rhs) = default;
hobject_t(hobject_t_max &&singleton) : hobject_t() {
max = true;
}
hobject_t &operator=(const hobject_t &rhs) = default;
hobject_t &operator=(hobject_t &&rhs) = default;
hobject_t &operator=(hobject_t_max &&singleton) {
*this = hobject_t();
max = true;
return *this;
}
// maximum sorted value.
static hobject_t_max get_max() {
return hobject_t_max();
}
hobject_t(const object_t& oid, const std::string& key, snapid_t snap,
uint32_t hash, int64_t pool, const std::string& nspace)
: oid(oid), snap(snap), hash(hash), max(false),
pool(pool), nspace(nspace),
key(oid.name == key ? std::string() : key) {
build_hash_cache();
}
hobject_t(const sobject_t &soid, const std::string &key, uint32_t hash,
int64_t pool, const std::string& nspace)
: oid(soid.oid), snap(soid.snap), hash(hash), max(false),
pool(pool), nspace(nspace),
key(soid.oid.name == key ? std::string() : key) {
build_hash_cache();
}
// used by Crimson
hobject_t(const std::string &key, snapid_t snap, uint32_t reversed_hash,
int64_t pool, const std::string& nspace)
: oid(key), snap(snap), max(false), pool(pool), nspace(nspace) {
set_bitwise_key_u32(reversed_hash);
}
/// @return min hobject_t ret s.t. ret.hash == this->hash
hobject_t get_boundary() const {
if (is_max())
return *this;
hobject_t ret;
ret.set_hash(hash);
ret.pool = pool;
return ret;
}
hobject_t get_object_boundary() const {
if (is_max())
return *this;
hobject_t ret = *this;
ret.snap = 0;
return ret;
}
/// @return head version of this hobject_t
hobject_t get_head() const {
hobject_t ret(*this);
ret.snap = CEPH_NOSNAP;
return ret;
}
/// @return snapdir version of this hobject_t
hobject_t get_snapdir() const {
hobject_t ret(*this);
ret.snap = CEPH_SNAPDIR;
return ret;
}
/// @return true if object is snapdir
bool is_snapdir() const {
return snap == CEPH_SNAPDIR;
}
/// @return true if object is head
bool is_head() const {
return snap == CEPH_NOSNAP;
}
/// @return true if object is neither head nor snapdir nor max
bool is_snap() const {
return !is_max() && !is_head() && !is_snapdir();
}
/// @return true iff the object should have a snapset in it's attrs
bool has_snapset() const {
return is_head() || is_snapdir();
}
/* Do not use when a particular hash function is needed */
explicit hobject_t(const sobject_t &o) :
oid(o.oid), snap(o.snap), max(false), pool(POOL_META) {
set_hash(std::hash<sobject_t>()(o));
}
bool is_max() const {
ceph_assert(!max || (*this == hobject_t(hobject_t::get_max())));
return max;
}
bool is_min() const {
// this needs to match how it's constructed
return snap == 0 &&
hash == 0 &&
!max &&
pool == INT64_MIN;
}
static uint32_t _reverse_bits(uint32_t v) {
return reverse_bits(v);
}
static uint32_t _reverse_nibbles(uint32_t retval) {
return reverse_nibbles(retval);
}
/**
* Returns set S of strings such that for any object
* h where h.match(bits, mask), there is some string
* s \f$\in\f$ S such that s is a prefix of h.to_str().
* Furthermore, for any s \f$\in\f$ S, s is a prefix of
* h.str() implies that h.match(bits, mask).
*/
static std::set<std::string> get_prefixes(
uint32_t bits,
uint32_t mask,
int64_t pool);
// filestore nibble-based key
uint32_t get_nibblewise_key_u32() const {
ceph_assert(!max);
return nibblewise_key_cache;
}
uint64_t get_nibblewise_key() const {
return max ? 0x100000000ull : nibblewise_key_cache;
}
// newer bit-reversed key
uint32_t get_bitwise_key_u32() const {
ceph_assert(!max);
return hash_reverse_bits;
}
uint64_t get_bitwise_key() const {
return max ? 0x100000000ull : hash_reverse_bits;
}
// please remember to update set_bitwise_key_u32() also
// once you change build_hash_cache()
void build_hash_cache() {
nibblewise_key_cache = _reverse_nibbles(hash);
hash_reverse_bits = _reverse_bits(hash);
}
void set_bitwise_key_u32(uint32_t value) {
hash = _reverse_bits(value);
// below is identical to build_hash_cache() and shall be
// updated correspondingly if you change build_hash_cache()
nibblewise_key_cache = _reverse_nibbles(hash);
hash_reverse_bits = value;
}
const std::string& get_effective_key() const {
if (key.length())
return key;
return oid.name;
}
hobject_t make_temp_hobject(const std::string& name) const {
return hobject_t(object_t(name), "", CEPH_NOSNAP,
hash,
get_temp_pool(pool),
"");
}
void swap(hobject_t &o) {
hobject_t temp(o);
o = (*this);
(*this) = temp;
}
const std::string &get_namespace() const {
return nspace;
}
bool parse(const std::string& s);
void encode(ceph::buffer::list& bl) const;
void decode(ceph::bufferlist::const_iterator& bl);
void decode(json_spirit::Value& v);
void dump(ceph::Formatter *f) const;
static void generate_test_instances(std::list<hobject_t*>& o);
friend int cmp(const hobject_t& l, const hobject_t& r);
auto operator<=>(const hobject_t &rhs) const noexcept {
auto cmp = max <=> rhs.max;
if (cmp != 0) return cmp;
cmp = pool <=> rhs.pool;
if (cmp != 0) return cmp;
cmp = get_bitwise_key() <=> rhs.get_bitwise_key();
if (cmp != 0) return cmp;
cmp = nspace <=> rhs.nspace;
if (cmp != 0) return cmp;
if (!(get_key().empty() && rhs.get_key().empty())) {
cmp = get_effective_key() <=> rhs.get_effective_key();
if (cmp != 0) return cmp;
}
cmp = oid <=> rhs.oid;
if (cmp != 0) return cmp;
return snap <=> rhs.snap;
}
bool operator==(const hobject_t& rhs) const noexcept {
return operator<=>(rhs) == 0;
}
friend struct ghobject_t;
};
WRITE_CLASS_ENCODER(hobject_t)
namespace std {
template<> struct hash<hobject_t> {
size_t operator()(const hobject_t &r) const {
static rjhash<uint64_t> RJ;
return RJ(r.get_hash() ^ r.snap);
}
};
} // namespace std
std::ostream& operator<<(std::ostream& out, const hobject_t& o);
template <typename T>
struct always_false {
using value = std::false_type;
};
template <typename T>
inline bool operator==(const hobject_t &lhs, const T&) {
static_assert(always_false<T>::value::value, "Do not compare to get_max()");
return lhs.is_max();
}
template <typename T>
inline bool operator==(const T&, const hobject_t &rhs) {
static_assert(always_false<T>::value::value, "Do not compare to get_max()");
return rhs.is_max();
}
template <typename T>
inline bool operator!=(const hobject_t &lhs, const T&) {
static_assert(always_false<T>::value::value, "Do not compare to get_max()");
return !lhs.is_max();
}
template <typename T>
inline bool operator!=(const T&, const hobject_t &rhs) {
static_assert(always_false<T>::value::value, "Do not compare to get_max()");
return !rhs.is_max();
}
extern int cmp(const hobject_t& l, const hobject_t& r);
template <typename T>
static inline int cmp(const hobject_t &l, const T&) {
static_assert(always_false<T>::value::value, "Do not compare to get_max()");
return l.is_max() ? 0 : -1;
}
template <typename T>
static inline int cmp(const T&, const hobject_t&r) {
static_assert(always_false<T>::value::value, "Do not compare to get_max()");
return r.is_max() ? 0 : 1;
}
typedef version_t gen_t;
struct ghobject_t {
static const gen_t NO_GEN = UINT64_MAX;
bool max = false;
shard_id_t shard_id = shard_id_t::NO_SHARD;
hobject_t hobj;
gen_t generation = NO_GEN;
ghobject_t() = default;
explicit ghobject_t(const hobject_t &obj)
: hobj(obj) {}
ghobject_t(const hobject_t &obj, gen_t gen, shard_id_t shard)
: shard_id(shard),
hobj(obj),
generation(gen) {}
// used by Crimson
ghobject_t(shard_id_t shard, int64_t pool, uint32_t reversed_hash,
const std::string& nspace, const std::string& oid,
snapid_t snap, gen_t gen)
: shard_id(shard),
hobj(oid, snap, reversed_hash, pool, nspace),
generation(gen) {}
static ghobject_t make_pgmeta(int64_t pool, uint32_t hash, shard_id_t shard) {
hobject_t h(object_t(), std::string(), CEPH_NOSNAP, hash, pool, std::string());
return ghobject_t(h, NO_GEN, shard);
}
bool is_pgmeta() const {
// make sure we are distinct from hobject_t(), which has pool INT64_MIN
return hobj.pool >= 0 && hobj.oid.name.empty();
}
bool match(uint32_t bits, uint32_t match) const {
return hobj.match_hash(hobj.hash, bits, match);
}
/// @return min ghobject_t ret s.t. ret.hash == this->hash
ghobject_t get_boundary() const {
if (hobj.is_max())
return *this;
ghobject_t ret;
ret.hobj.set_hash(hobj.hash);
ret.shard_id = shard_id;
ret.hobj.pool = hobj.pool;
return ret;
}
uint32_t get_nibblewise_key_u32() const {
return hobj.get_nibblewise_key_u32();
}
uint32_t get_nibblewise_key() const {
return hobj.get_nibblewise_key();
}
bool is_degenerate() const {
return generation == NO_GEN && shard_id == shard_id_t::NO_SHARD;
}
bool is_no_gen() const {
return generation == NO_GEN;
}
bool is_no_shard() const {
return shard_id == shard_id_t::NO_SHARD;
}
void set_shard(shard_id_t s) {
shard_id = s;
}
bool parse(const std::string& s);
// maximum sorted value.
static ghobject_t get_max() {
ghobject_t h;
h.max = true;
h.hobj = hobject_t::get_max(); // so that is_max() => hobj.is_max()
return h;
}
bool is_max() const {
return max;
}
bool is_min() const {
return *this == ghobject_t();
}
void swap(ghobject_t &o) {
ghobject_t temp(o);
o = (*this);
(*this) = temp;
}
void encode(ceph::buffer::list& bl) const;
void decode(ceph::buffer::list::const_iterator& bl);
void decode(json_spirit::Value& v);
size_t encoded_size() const;
void dump(ceph::Formatter *f) const;
static void generate_test_instances(std::list<ghobject_t*>& o);
friend int cmp(const ghobject_t& l, const ghobject_t& r);
auto operator<=>(const ghobject_t&) const = default;
bool operator==(const ghobject_t&) const = default;
};
WRITE_CLASS_ENCODER(ghobject_t)
namespace std {
template<> struct hash<ghobject_t> {
size_t operator()(const ghobject_t &r) const {
static rjhash<uint64_t> RJ;
static hash<hobject_t> HO;
size_t hash = HO(r.hobj);
hash = RJ(hash ^ r.generation);
hash = hash ^ r.shard_id.id;
return hash;
}
};
} // namespace std
std::ostream& operator<<(std::ostream& out, const ghobject_t& o);
#if FMT_VERSION >= 90000
template <> struct fmt::formatter<ghobject_t> : fmt::ostream_formatter {};
#endif
extern int cmp(const ghobject_t& l, const ghobject_t& r);
#endif
| 13,472 | 25.110465 | 83 | h |
null | ceph-main/src/common/hobject_fmt.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
/**
* \file fmtlib formatters for some hobject.h classes
*/
#include <fmt/format.h>
#include <fmt/ranges.h>
#include "common/hobject.h"
#include "include/object_fmt.h"
#include "msg/msg_fmt.h"
// \todo reimplement
static inline void append_out_escaped(const std::string& in, std::string* out)
{
for (auto i = in.cbegin(); i != in.cend(); ++i) {
if (*i == '%' || *i == ':' || *i == '/' || *i < 32 || *i >= 127) {
char buf[4];
snprintf(buf, sizeof(buf), "%%%02x", (int)(unsigned char)*i);
out->append(buf);
} else {
out->push_back(*i);
}
}
}
template <> struct fmt::formatter<hobject_t> {
constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
template <typename FormatContext> auto format(const hobject_t& ho, FormatContext& ctx)
{
if (ho == hobject_t{}) {
return fmt::format_to(ctx.out(), "MIN");
}
if (ho.is_max()) {
return fmt::format_to(ctx.out(), "MAX");
}
std::string v;
append_out_escaped(ho.nspace, &v);
v.push_back(':');
append_out_escaped(ho.get_key(), &v);
v.push_back(':');
append_out_escaped(ho.oid.name, &v);
return fmt::format_to(ctx.out(), "{}:{:08x}:{}:{}", static_cast<uint64_t>(ho.pool),
ho.get_bitwise_key_u32(), v, ho.snap);
}
};
| 1,398 | 24.907407 | 88 | h |
null | ceph-main/src/common/hostname.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "common/hostname.h"
#include <unistd.h>
#include "include/compat.h"
std::string ceph_get_hostname()
{
// are we in a container? if so we would prefer the *real* hostname.
const char *node_name = getenv("NODE_NAME");
if (node_name) {
return node_name;
}
char buf[1024];
gethostname(buf, 1024);
return std::string(buf);
}
std::string ceph_get_short_hostname()
{
std::string hostname = ceph_get_hostname();
size_t pos = hostname.find('.');
if (pos == std::string::npos)
{
return hostname;
}
else
{
return hostname.substr(0, pos);
}
}
| 1,014 | 20.595745 | 71 | cc |
null | ceph-main/src/common/hostname.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_COMMON_HOSTNAME_H
#define CEPH_COMMON_HOSTNAME_H
#include <string>
extern std::string ceph_get_hostname();
extern std::string ceph_get_short_hostname();
#endif
| 601 | 25.173913 | 70 | h |
null | ceph-main/src/common/inline_variant.h | // -*- mode:C++; tab-width:8; c-basic-offset:4; indent-tabs-mode:t -*-
// vim: ts=8 sw=4 smarttab
/*
* Copied from:
* https://github.com/exclipy/inline_variant_visitor/blob/master/inline_variant.hpp
*/
#ifndef INLINE_VARIANT_H
#define INLINE_VARIANT_H
#include <boost/function_types/function_arity.hpp>
#include <boost/fusion/algorithm/transformation/transform.hpp>
#include <boost/mpl/contains.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/range_c.hpp>
#include <boost/noncopyable.hpp>
#include "function_signature.h"
namespace detail {
// A metafunction class for getting the argument type from a unary function or functor type
struct function_arg_extractor
{
// Function is either a function type like void(int const&), or a functor - eg. a class with void operator(int)
// Sets type to the argument type with the constness and referenceness stripped (eg. int)
template <typename Function>
struct apply
{
private:
typedef typename boost::remove_const< typename boost::remove_reference<Function>::type >::type bare_type;
typedef typename signature_of<bare_type>::type normalized_function_type;
typedef typename boost::function_types::function_arity<normalized_function_type>::type arity;
typedef typename boost::function_types::parameter_types<normalized_function_type>::type parameter_types;
typedef typename boost::function_types::result_type<normalized_function_type>::type result_type;
BOOST_STATIC_ASSERT_MSG((arity::value == 1), "make_visitor called with a non-unary function");
typedef typename boost::mpl::front<parameter_types>::type parameter_type;
public:
typedef typename boost::remove_const< typename boost::remove_reference<parameter_type>::type >::type type;
};
};
struct make_pair
{
template <typename AType, typename Ind>
struct apply {
typedef boost::mpl::pair<AType, Ind> type;
};
};
// A metafunction class that asserts the second argument is in Allowed, and returns void
template<typename Allowed>
struct check_in
{
template <typename Type1, typename Type2>
struct apply
{
private:
BOOST_STATIC_ASSERT_MSG((boost::mpl::contains<Allowed, typename boost::mpl::first<Type2>::type>::value),
"make_visitor called with spurious handler functions");
public:
typedef void type;
};
};
template <typename Seq>
struct as_map
{
private:
struct insert_helper {
template <typename M, typename P>
struct apply
{
typedef typename boost::mpl::insert<
M,
P>::type type;
};
};
public:
typedef typename boost::mpl::fold<Seq, boost::mpl::map0<>, insert_helper>::type type;
};
// A functor template suitable for passing into apply_visitor. The constructor accepts the list of handler functions,
// which are then exposed through a set of operator()s
template <typename Result, typename Variant, typename... Functions>
struct generic_visitor : boost::static_visitor<Result>, boost::noncopyable
{
private:
typedef generic_visitor<Result, Variant, Functions...> type;
// Compute the function_map type
typedef boost::mpl::vector<Functions...> function_types;
typedef typename boost::mpl::transform<function_types, function_arg_extractor>::type arg_types;
typedef typename boost::mpl::transform<
arg_types,
boost::mpl::range_c<int, 0, boost::mpl::size<arg_types>::value>,
make_pair
>::type pair_list;
typedef typename as_map<pair_list>::type fmap;
// Check that the argument types are unique
BOOST_STATIC_ASSERT_MSG((boost::mpl::size<fmap>::value == boost::mpl::size<arg_types>::value),
"make_visitor called with non-unique argument types for handler functions");
// Check that there aren't any argument types not in the variant types
typedef typename boost::mpl::fold<fmap, void, check_in<typename Variant::types> >::type dummy;
boost::fusion::vector<Functions...> fvec;
template <typename T>
Result apply_helper(const T& object, boost::mpl::true_) const {
typedef typename boost::mpl::at<fmap, T>::type Ind;
return boost::fusion::at<Ind>(fvec)(object);
}
template <typename T>
Result apply_helper(const T& object, boost::mpl::false_) const {
return Result();
}
BOOST_MOVABLE_BUT_NOT_COPYABLE(generic_visitor)
public:
generic_visitor(BOOST_RV_REF(type) other)
:
fvec(boost::move(other.fvec))
{
}
generic_visitor(Functions&&... functions)
:
fvec(std::forward<Functions>(functions)...)
{
}
template <typename T>
Result operator()(const T& object) const {
typedef typename boost::mpl::has_key<fmap, T>::type correct_key;
BOOST_STATIC_ASSERT_MSG(correct_key::value,
"make_visitor called without specifying handlers for all required types");
return apply_helper(object, correct_key());
}
};
// A metafunction class for getting the return type of a function
struct function_return_extractor
{
template <typename Function>
struct apply : boost::function_types::result_type<typename signature_of<Function>::type>
{
};
};
// A metafunction class that asserts the two arguments are the same and returns the first one
struct check_same
{
template <typename Type1, typename Type2>
struct apply
{
private:
BOOST_STATIC_ASSERT_MSG((boost::is_same<Type1, Type2>::value),
"make_visitor called with functions of differing return types");
public:
typedef Type1 type;
};
};
// A metafunction for getting the required generic_visitor type for the set of Functions
template <typename Variant, typename... Functions>
struct get_generic_visitor
{
private:
typedef boost::mpl::vector<Functions...> function_types;
typedef typename boost::mpl::transform<
function_types,
boost::remove_const< boost::remove_reference<boost::mpl::_1> >
>::type bare_function_types;
typedef typename boost::mpl::transform<bare_function_types, function_return_extractor>::type return_types;
public:
// Set result_type to the return type of the first function
typedef typename boost::mpl::front<return_types>::type result_type;
typedef generic_visitor<result_type, Variant, Functions...> type;
private:
// Assert that every return type is the same as the first one
typedef typename boost::mpl::fold<return_types, result_type, check_same>::type dummy;
};
// Accepts a set of functions and returns an object suitable for apply_visitor
template <typename Variant, typename... Functions>
auto make_visitor(BOOST_RV_REF(Functions)... functions)
-> typename detail::get_generic_visitor<Variant, Functions...>::type
{
return typename detail::get_generic_visitor<Variant, Functions...>::type(boost::forward<Functions>(functions)...);
}
}
template <typename Variant, typename... Functions>
auto match(Variant const& variant, BOOST_RV_REF(Functions)... functions)
-> typename detail::get_generic_visitor<Variant, Functions...>::result_type
{
return boost::apply_visitor(detail::make_visitor<Variant>(
boost::forward<Functions>(functions)...), variant);
}
#endif
| 7,222 | 33.070755 | 118 | h |
null | ceph-main/src/common/interval_map.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 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 INTERVAL_MAP_H
#define INTERVAL_MAP_H
#include "include/interval_set.h"
#include <initializer_list>
template <typename K, typename V, typename S>
/**
* interval_map
*
* Maps intervals to values. Erasing or inserting over an existing
* range will use S::operator() to split any overlapping existing
* values.
*
* Surprisingly, boost/icl/interval_map doesn't seem to be appropriate
* for this use case. The aggregation concept seems to assume
* commutativity, which doesn't work if we want more recent insertions
* to overwrite previous ones.
*/
class interval_map {
S s;
using map = std::map<K, std::pair<K, V> >;
using mapiter = typename std::map<K, std::pair<K, V> >::iterator;
using cmapiter = typename std::map<K, std::pair<K, V> >::const_iterator;
map m;
std::pair<mapiter, mapiter> get_range(K off, K len) {
// fst is first iterator with end after off (may be end)
auto fst = m.upper_bound(off);
if (fst != m.begin())
--fst;
if (fst != m.end() && off >= (fst->first + fst->second.first))
++fst;
// lst is first iterator with start after off + len (may be end)
auto lst = m.lower_bound(off + len);
return std::make_pair(fst, lst);
}
std::pair<cmapiter, cmapiter> get_range(K off, K len) const {
// fst is first iterator with end after off (may be end)
auto fst = m.upper_bound(off);
if (fst != m.begin())
--fst;
if (fst != m.end() && off >= (fst->first + fst->second.first))
++fst;
// lst is first iterator with start after off + len (may be end)
auto lst = m.lower_bound(off + len);
return std::make_pair(fst, lst);
}
void try_merge(mapiter niter) {
if (niter != m.begin()) {
auto prev = niter;
prev--;
if (prev->first + prev->second.first == niter->first &&
s.can_merge(prev->second.second, niter->second.second)) {
V n = s.merge(
std::move(prev->second.second),
std::move(niter->second.second));
K off = prev->first;
K len = niter->first + niter->second.first - off;
niter++;
m.erase(prev, niter);
auto p = m.insert(
std::make_pair(
off,
std::make_pair(len, std::move(n))));
ceph_assert(p.second);
niter = p.first;
}
}
auto next = niter;
next++;
if (next != m.end() &&
niter->first + niter->second.first == next->first &&
s.can_merge(niter->second.second, next->second.second)) {
V n = s.merge(
std::move(niter->second.second),
std::move(next->second.second));
K off = niter->first;
K len = next->first + next->second.first - off;
next++;
m.erase(niter, next);
auto p = m.insert(
std::make_pair(
off,
std::make_pair(len, std::move(n))));
ceph_assert(p.second);
}
}
public:
interval_map() = default;
interval_map(std::initializer_list<typename map::value_type> l) {
for (auto& v : l) {
insert(v.first, v.second.first, v.second.second);
}
}
interval_map intersect(K off, K len) const {
interval_map ret;
auto limits = get_range(off, len);
for (auto i = limits.first; i != limits.second; ++i) {
K o = i->first;
K l = i->second.first;
V v = i->second.second;
if (o < off) {
V p = v;
l -= (off - o);
v = s.split(off - o, l, p);
o = off;
}
if ((o + l) > (off + len)) {
V p = v;
l -= (o + l) - (off + len);
v = s.split(0, l, p);
}
ret.insert(o, l, v);
}
return ret;
}
void clear() {
m.clear();
}
void erase(K off, K len) {
if (len == 0)
return;
auto range = get_range(off, len);
std::vector<
std::pair<
K,
std::pair<K, V>
>> to_insert;
for (auto i = range.first; i != range.second; ++i) {
if (i->first < off) {
to_insert.emplace_back(
std::make_pair(
i->first,
std::make_pair(
off - i->first,
s.split(0, off - i->first, i->second.second))));
}
if ((off + len) < (i->first + i->second.first)) {
K nlen = (i->first + i->second.first) - (off + len);
to_insert.emplace_back(
std::make_pair(
off + len,
std::make_pair(
nlen,
s.split(i->second.first - nlen, nlen, i->second.second))));
}
}
m.erase(range.first, range.second);
m.insert(to_insert.begin(), to_insert.end());
}
void insert(K off, K len, V &&v) {
ceph_assert(len > 0);
ceph_assert(len == s.length(v));
erase(off, len);
auto p = m.insert(make_pair(off, std::make_pair(len, std::forward<V>(v))));
ceph_assert(p.second);
try_merge(p.first);
}
void insert(interval_map &&other) {
for (auto i = other.m.begin();
i != other.m.end();
other.m.erase(i++)) {
insert(i->first, i->second.first, std::move(i->second.second));
}
}
void insert(K off, K len, const V &v) {
ceph_assert(len > 0);
ceph_assert(len == s.length(v));
erase(off, len);
auto p = m.insert(make_pair(off, std::make_pair(len, v)));
ceph_assert(p.second);
try_merge(p.first);
}
void insert(const interval_map &other) {
for (auto &&i: other) {
insert(i.get_off(), i.get_len(), i.get_val());
}
}
bool empty() const {
return m.empty();
}
interval_set<K> get_interval_set() const {
interval_set<K> ret;
for (auto &&i: *this) {
ret.insert(i.get_off(), i.get_len());
}
return ret;
}
class const_iterator {
cmapiter it;
const_iterator(cmapiter &&it) : it(std::move(it)) {}
const_iterator(const cmapiter &it) : it(it) {}
friend class interval_map;
public:
const_iterator(const const_iterator &) = default;
const_iterator &operator=(const const_iterator &) = default;
const_iterator &operator++() {
++it;
return *this;
}
const_iterator operator++(int) {
return const_iterator(it++);
}
const_iterator &operator--() {
--it;
return *this;
}
const_iterator operator--(int) {
return const_iterator(it--);
}
bool operator==(const const_iterator &rhs) const {
return it == rhs.it;
}
bool operator!=(const const_iterator &rhs) const {
return it != rhs.it;
}
K get_off() const {
return it->first;
}
K get_len() const {
return it->second.first;
}
const V &get_val() const {
return it->second.second;
}
const_iterator &operator*() {
return *this;
}
};
const_iterator begin() const {
return const_iterator(m.begin());
}
const_iterator end() const {
return const_iterator(m.end());
}
std::pair<const_iterator, const_iterator> get_containing_range(
K off,
K len) const {
auto rng = get_range(off, len);
return std::make_pair(const_iterator(rng.first), const_iterator(rng.second));
}
unsigned ext_count() const {
return m.size();
}
bool operator==(const interval_map &rhs) const {
return m == rhs.m;
}
std::ostream &print(std::ostream &out) const {
bool first = true;
out << "{";
for (auto &&i: *this) {
if (first) {
first = false;
} else {
out << ",";
}
out << i.get_off() << "~" << i.get_len() << "("
<< s.length(i.get_val()) << ")";
}
return out << "}";
}
};
template <typename K, typename V, typename S>
std::ostream &operator<<(std::ostream &out, const interval_map<K, V, S> &m) {
return m.print(out);
}
#endif
| 7,720 | 25.624138 | 81 | h |
null | ceph-main/src/common/intrusive_lru.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <boost/intrusive_ptr.hpp>
#include <boost/intrusive/set.hpp>
#include <boost/intrusive/list.hpp>
namespace ceph::common {
/**
* intrusive_lru: lru implementation with embedded map and list hook
*
* Elements will be stored in an intrusive set. Once an element is no longer
* referenced it will remain in the set. The unreferenced elements will be
* evicted from the set once the set size exceeds the `lru_target_size`.
* Referenced elements will not be evicted as this is a registery with
* extra caching capabilities.
*
* Note, this implementation currently is entirely thread-unsafe.
*/
template <typename K, typename V, typename VToK>
struct intrusive_lru_config {
using key_type = K;
using value_type = V;
using key_of_value = VToK;
};
template <typename Config>
class intrusive_lru;
template <typename Config>
class intrusive_lru_base;
template <typename Config>
void intrusive_ptr_add_ref(intrusive_lru_base<Config> *p);
template <typename Config>
void intrusive_ptr_release(intrusive_lru_base<Config> *p);
template <typename Config>
class intrusive_lru_base {
unsigned use_count = 0;
// lru points to the corresponding intrusive_lru
// which will be set to null if its use_count
// is zero (aka unreferenced).
intrusive_lru<Config> *lru = nullptr;
public:
bool is_referenced() const {
return static_cast<bool>(lru);
}
bool is_unreferenced() const {
return !is_referenced();
}
boost::intrusive::set_member_hook<> set_hook;
boost::intrusive::list_member_hook<> list_hook;
using Ref = boost::intrusive_ptr<typename Config::value_type>;
using lru_t = intrusive_lru<Config>;
friend intrusive_lru<Config>;
friend void intrusive_ptr_add_ref<>(intrusive_lru_base<Config> *);
friend void intrusive_ptr_release<>(intrusive_lru_base<Config> *);
virtual ~intrusive_lru_base() {}
};
template <typename Config>
class intrusive_lru {
using base_t = intrusive_lru_base<Config>;
using K = typename Config::key_type;
using T = typename Config::value_type;
using TRef = typename base_t::Ref;
using lru_set_option_t = boost::intrusive::member_hook<
base_t,
boost::intrusive::set_member_hook<>,
&base_t::set_hook>;
using VToK = typename Config::key_of_value;
struct VToKWrapped {
using type = typename VToK::type;
const type &operator()(const base_t &obc) {
return VToK()(static_cast<const T&>(obc));
}
};
using lru_set_t = boost::intrusive::set<
base_t,
lru_set_option_t,
boost::intrusive::key_of_value<VToKWrapped>
>;
lru_set_t lru_set;
using lru_list_t = boost::intrusive::list<
base_t,
boost::intrusive::member_hook<
base_t,
boost::intrusive::list_member_hook<>,
&base_t::list_hook>>;
lru_list_t unreferenced_list;
size_t lru_target_size = 0;
// when the lru_set exceeds its target size, evict
// only unreferenced elements from it (if any).
void evict() {
while (!unreferenced_list.empty() &&
lru_set.size() > lru_target_size) {
auto &evict_target = unreferenced_list.front();
assert(evict_target.is_unreferenced());
unreferenced_list.pop_front();
lru_set.erase_and_dispose(
lru_set.iterator_to(evict_target),
[](auto *p) { delete p; }
);
}
}
// access an existing element in the lru_set.
// mark as referenced if necessary.
void access(base_t &b) {
if (b.is_referenced())
return;
unreferenced_list.erase(lru_list_t::s_iterator_to(b));
b.lru = this;
}
// insert a new element to the lru_set.
// attempt to evict if possible.
void insert(base_t &b) {
assert(b.is_unreferenced());
lru_set.insert(b);
b.lru = this;
evict();
}
// an element in the lru_set has no users,
// mark it as unreferenced and try to evict.
void mark_as_unreferenced(base_t &b) {
assert(b.is_referenced());
unreferenced_list.push_back(b);
b.lru = nullptr;
evict();
}
public:
/**
* Returns the TRef corresponding to k if it exists or
* creates it otherwise. Return is:
* std::pair(reference_to_val, found)
*/
std::pair<TRef, bool> get_or_create(const K &k) {
typename lru_set_t::insert_commit_data icd;
auto [iter, missing] = lru_set.insert_check(
k,
icd);
if (missing) {
auto ret = new T(k);
lru_set.insert_commit(*ret, icd);
insert(*ret);
return {TRef(ret), false};
} else {
access(*iter);
return {TRef(static_cast<T*>(&*iter)), true};
}
}
/*
* Clears unreferenced elements from the lru set [from, to]
*/
void clear_range(
const K& from,
const K& to) {
auto from_iter = lru_set.lower_bound(from);
auto to_iter = lru_set.upper_bound(to);
for (auto i = from_iter; i != to_iter; ) {
if (!(*i).lru) {
unreferenced_list.erase(lru_list_t::s_iterator_to(*i));
i = lru_set.erase_and_dispose(i, [](auto *p)
{ delete p; } );
} else {
i++;
}
}
}
template <class F>
void for_each(F&& f) {
for (auto& v : lru_set) {
access(v);
f(TRef{static_cast<T*>(&v)});
}
}
/**
* Returns the TRef corresponding to k if it exists or
* nullptr otherwise.
*/
TRef get(const K &k) {
if (auto iter = lru_set.find(k); iter != std::end(lru_set)) {
access(*iter);
return TRef(static_cast<T*>(&*iter));
} else {
return nullptr;
}
}
void set_target_size(size_t target_size) {
lru_target_size = target_size;
evict();
}
~intrusive_lru() {
set_target_size(0);
}
friend void intrusive_ptr_add_ref<>(intrusive_lru_base<Config> *);
friend void intrusive_ptr_release<>(intrusive_lru_base<Config> *);
};
template <typename Config>
void intrusive_ptr_add_ref(intrusive_lru_base<Config> *p) {
assert(p);
assert(p->lru);
p->use_count++;
}
template <typename Config>
void intrusive_ptr_release(intrusive_lru_base<Config> *p) {
assert(p);
assert(p->use_count > 0);
--p->use_count;
if (p->use_count == 0) {
p->lru->mark_as_unreferenced(*p);
}
}
}
| 6,208 | 24.342857 | 76 | h |
null | ceph-main/src/common/ipaddr.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <stdlib.h>
#include <string.h>
#if defined(__FreeBSD__)
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#endif
#include "include/ipaddr.h"
#include "msg/msg_types.h"
#include "common/pick_address.h"
using std::string;
void netmask_ipv4(const struct in_addr *addr,
unsigned int prefix_len,
struct in_addr *out) {
uint32_t mask;
if (prefix_len >= 32) {
// also handle 32 in this branch, because >>32 is not defined by
// the C standards
mask = ~uint32_t(0);
} else {
mask = htonl(~(~uint32_t(0) >> prefix_len));
}
out->s_addr = addr->s_addr & mask;
}
bool matches_ipv4_in_subnet(const struct ifaddrs& addrs,
const struct sockaddr_in* net,
unsigned int prefix_len)
{
if (addrs.ifa_addr == nullptr)
return false;
if (addrs.ifa_addr->sa_family != net->sin_family)
return false;
struct in_addr want;
netmask_ipv4(&net->sin_addr, prefix_len, &want);
struct in_addr *cur = &((struct sockaddr_in*)addrs.ifa_addr)->sin_addr;
struct in_addr temp;
netmask_ipv4(cur, prefix_len, &temp);
return temp.s_addr == want.s_addr;
}
void netmask_ipv6(const struct in6_addr *addr,
unsigned int prefix_len,
struct in6_addr *out) {
if (prefix_len > 128)
prefix_len = 128;
memcpy(out->s6_addr, addr->s6_addr, prefix_len/8);
if (prefix_len < 128)
out->s6_addr[prefix_len/8] = addr->s6_addr[prefix_len/8] & ~( 0xFF >> (prefix_len % 8) );
if (prefix_len/8 < 15)
memset(out->s6_addr+prefix_len/8+1, 0, 16-prefix_len/8-1);
}
bool matches_ipv6_in_subnet(const struct ifaddrs& addrs,
const struct sockaddr_in6* net,
unsigned int prefix_len)
{
if (addrs.ifa_addr == nullptr)
return false;
if (addrs.ifa_addr->sa_family != net->sin6_family)
return false;
struct in6_addr want;
netmask_ipv6(&net->sin6_addr, prefix_len, &want);
struct in6_addr temp;
struct in6_addr *cur = &((struct sockaddr_in6*)addrs.ifa_addr)->sin6_addr;
if (IN6_IS_ADDR_LINKLOCAL(cur))
return false;
netmask_ipv6(cur, prefix_len, &temp);
return IN6_ARE_ADDR_EQUAL(&temp, &want);
}
bool parse_network(const char *s, struct sockaddr_storage *network, unsigned int *prefix_len) {
char *slash = strchr((char*)s, '/');
if (!slash) {
// no slash
return false;
}
if (*(slash+1) == '\0') {
// slash is the last character
return false;
}
char *end;
long int num = strtol(slash+1, &end, 10);
if (*end != '\0') {
// junk after the prefix_len
return false;
}
if (num < 0) {
return false;
}
*prefix_len = num;
// copy the part before slash to get nil termination
char *addr = (char*)alloca(slash-s + 1);
strncpy(addr, s, slash-s);
addr[slash-s] = '\0';
// caller expects ports etc to be zero
memset(network, 0, sizeof(*network));
// try parsing as ipv4
int ok;
ok = inet_pton(AF_INET, addr, &((struct sockaddr_in*)network)->sin_addr);
if (ok) {
network->ss_family = AF_INET;
return true;
}
// try parsing as ipv6
ok = inet_pton(AF_INET6, addr, &((struct sockaddr_in6*)network)->sin6_addr);
if (ok) {
network->ss_family = AF_INET6;
return true;
}
return false;
}
bool parse_network(const char *s,
entity_addr_t *network,
unsigned int *prefix_len)
{
sockaddr_storage ss;
bool ret = parse_network(s, &ss, prefix_len);
if (ret) {
network->set_type(entity_addr_t::TYPE_LEGACY);
network->set_sockaddr((sockaddr *)&ss);
}
return ret;
}
bool network_contains(
const struct entity_addr_t& network,
unsigned int prefix_len,
const struct entity_addr_t& addr)
{
if (addr.get_family() != network.get_family()) {
return false;
}
switch (network.get_family()) {
case AF_INET:
{
struct in_addr a, b;
netmask_ipv4(
&((const sockaddr_in*)network.get_sockaddr())->sin_addr, prefix_len, &a);
netmask_ipv4(
&((const sockaddr_in*)addr.get_sockaddr())->sin_addr, prefix_len, &b);
if (memcmp(&a, &b, sizeof(a)) == 0) {
return true;
}
}
break;
case AF_INET6:
{
struct in6_addr a, b;
netmask_ipv6(
&((const sockaddr_in6*)network.get_sockaddr())->sin6_addr, prefix_len, &a);
netmask_ipv6(
&((const sockaddr_in6*)addr.get_sockaddr())->sin6_addr, prefix_len, &b);
if (memcmp(&a, &b, sizeof(a)) == 0) {
return true;
}
}
break;
}
return false;
}
| 4,515 | 23.950276 | 95 | cc |
null | ceph-main/src/common/iso_8601.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include <iomanip>
#include <sstream>
#include "iso_8601.h"
#include "include/timegm.h"
#include "include/ceph_assert.h"
namespace ceph {
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
using std::chrono::seconds;
using std::setw;
using std::size_t;
using std::stringstream;
using std::string;
using std::uint16_t;
using boost::none;
using boost::optional;
using std::string_view;
using ceph::real_clock;
using ceph::real_time;
using sriter = string_view::const_iterator;
namespace {
// This assumes a contiguous block of numbers in the correct order.
uint16_t digit(char c) {
if (!(c >= '0' && c <= '9')) {
throw std::invalid_argument("Not a digit.");
}
return static_cast<uint16_t>(c - '0');
}
optional<real_time> calculate(const tm& t, uint32_t n = 0) {
ceph_assert(n < 1000000000);
time_t tt = internal_timegm(&t);
if (tt == static_cast<time_t>(-1)) {
return none;
}
return boost::make_optional<real_time>(real_clock::from_time_t(tt)
+ nanoseconds(n));
}
}
optional<real_time> from_iso_8601(const string_view s,
const bool ws_terminates) noexcept {
auto end = s.cend();
auto read_digit = [end](sriter& c) mutable {
if (c == end) {
throw std::invalid_argument("End of input.");
}
auto f = digit(*c);
++c;
return f;
};
auto read_digits = [&read_digit](sriter& c, std::size_t n) {
auto v = 0ULL;
for (auto i = 0U; i < n; ++i) {
auto d = read_digit(c);
v = (10ULL * v) + d;
}
return v;
};
auto partial_date = [end, ws_terminates](sriter& c) {
return (c == end || (ws_terminates && std::isspace(*c)));
};
auto time_end = [end, ws_terminates](sriter& c) {
return (c != end && *c == 'Z' &&
((c + 1) == end ||
(ws_terminates && std::isspace(*(c + 1)))));
};
auto consume_delimiter = [end](sriter& c, char q) {
if (c == end || *c != q) {
throw std::invalid_argument("Expected delimiter not found.");
} else {
++c;
}
};
tm t = { 0, // tm_sec
0, // tm_min
0, // tm_hour
1, // tm_mday
0, // tm_mon
70, // tm_year
0, // tm_wday
0, // tm_yday
0, // tm_isdst
};
try {
auto c = s.cbegin();
{
auto y = read_digits(c, 4);
if (y < 1970) {
return none;
}
t.tm_year = y - 1900;
}
if (partial_date(c)) {
return calculate(t, 0);
}
consume_delimiter(c, '-');
t.tm_mon = (read_digits(c, 2) - 1);
if (partial_date(c)) {
return calculate(t);
}
consume_delimiter(c, '-');
t.tm_mday = read_digits(c, 2);
if (partial_date(c)) {
return calculate(t);
}
consume_delimiter(c, 'T');
t.tm_hour = read_digits(c, 2);
if (time_end(c)) {
return calculate(t);
}
consume_delimiter(c, ':');
t.tm_min = read_digits(c, 2);
if (time_end(c)) {
return calculate(t);
}
consume_delimiter(c, ':');
t.tm_sec = read_digits(c, 2);
if (time_end(c)) {
return calculate(t);
}
consume_delimiter(c, '.');
auto n = 0UL;
auto multiplier = 100000000UL;
for (auto i = 0U; i < 9U; ++i) {
auto d = read_digit(c);
n += d * multiplier;
multiplier /= 10;
if (time_end(c)) {
return calculate(t, n);
}
}
} catch (std::invalid_argument& e) {
// fallthrough
}
return none;
}
string to_iso_8601(const real_time t,
const iso_8601_format f,
std::string_view date_separator,
std::string_view time_separator) noexcept {
ceph_assert(f >= iso_8601_format::Y &&
f <= iso_8601_format::YMDhmsn);
stringstream out(std::ios_base::out);
auto sec = real_clock::to_time_t(t);
auto nsec = duration_cast<nanoseconds>(t.time_since_epoch() %
seconds(1)).count();
struct tm bt;
gmtime_r(&sec, &bt);
out.fill('0');
out << 1900 + bt.tm_year;
if (f == iso_8601_format::Y) {
return out.str();
}
out << date_separator << setw(2) << bt.tm_mon + 1;
if (f == iso_8601_format::YM) {
return out.str();
}
out << date_separator << setw(2) << bt.tm_mday;
if (f == iso_8601_format::YMD) {
return out.str();
}
out << 'T' << setw(2) << bt.tm_hour;
if (f == iso_8601_format::YMDh) {
out << 'Z';
return out.str();
}
out << time_separator << setw(2) << bt.tm_min;
if (f == iso_8601_format::YMDhm) {
out << 'Z';
return out.str();
}
out << time_separator << setw(2) << bt.tm_sec;
if (f == iso_8601_format::YMDhms) {
out << 'Z';
return out.str();
}
out << '.' << setw(9) << nsec << 'Z';
return out.str();
}
}
| 4,735 | 21.990291 | 70 | cc |
null | ceph-main/src/common/iso_8601.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_COMMON_ISO_8601_H
#define CEPH_COMMON_ISO_8601_H
#include <string_view>
#include <boost/optional.hpp>
#include "common/ceph_time.h"
namespace ceph {
// Here, we support the W3C profile of ISO 8601 with the following
// restrictions:
// - Subsecond resolution is supported to nanosecond
// granularity. Any number of digits between 1 and 9 may be
// specified after the decimal point.
// - All times must be UTC.
// - All times must be representable as a sixty-four bit count of
// nanoseconds since the epoch.
// - Partial times are handled thus:
// * If there are no subseconds, they are assumed to be zero.
// * If there are no seconds, they are assumed to be zero.
// * If there are no minutes, they are assumed to be zero.
// * If there is no time, it is assumed to midnight.
// * If there is no day, it is assumed to be the first.
// * If there is no month, it is assumed to be January.
//
// If a date is invalid, boost::none is returned.
boost::optional<ceph::real_time> from_iso_8601(
std::string_view s, const bool ws_terminates = true) noexcept;
enum class iso_8601_format {
Y, YM, YMD, YMDh, YMDhm, YMDhms, YMDhmsn
};
std::string to_iso_8601(const ceph::real_time t,
const iso_8601_format f = iso_8601_format::YMDhmsn,
std::string_view date_separator = "-",
std::string_view time_separator = ":")
noexcept;
static inline std::string to_iso_8601_no_separators(const ceph::real_time t,
const iso_8601_format f = iso_8601_format::YMDhmsn)
noexcept {
return to_iso_8601(t, f, "", "");
}
}
#endif
| 1,803 | 33.037736 | 103 | h |
null | ceph-main/src/common/item_history.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <list>
#include <mutex>
/*
Keep a history of item values so that readers can dereference the pointer to
the latest value and continue using it as long as they want. This container
is only appropriate for values that are updated a handful of times over their
total lifetime.
*/
template<class T>
class safe_item_history {
private:
std::mutex lock;
std::list<T> history;
T *current = nullptr;
public:
safe_item_history() {
history.emplace_back(T());
current = &history.back();
}
// readers are lock-free
const T& operator*() const {
return *current;
}
const T *operator->() const {
return current;
}
// writes are serialized
const T& operator=(const T& other) {
std::lock_guard l(lock);
history.push_back(other);
current = &history.back();
return *current;
}
};
| 949 | 18.791667 | 77 | h |
null | ceph-main/src/common/likely.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) 2010 Dreamhost
*
* 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_LIKELY_DOT_H
#define CEPH_LIKELY_DOT_H
/*
* Likely / Unlikely macros
*/
#ifndef likely
#define likely(x) __builtin_expect((x),1)
#endif
#ifndef unlikely
#define unlikely(x) __builtin_expect((x),0)
#endif
#ifndef expect
#define expect(x, hint) __builtin_expect((x),(hint))
#endif
#endif
| 714 | 21.34375 | 70 | h |
null | ceph-main/src/common/linux_version.h | #ifndef CEPH_LINUX_VERSION_H
#define CEPH_LINUX_VERSION_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef HAVE_LINUX_VERSION_H
# include <linux/version.h>
#endif
#ifndef KERNEL_VERSION
# define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
#endif
int get_linux_version(void);
#ifdef __cplusplus
}
#endif
#endif /* CEPH_LINUX_VERSION_H */
| 351 | 14.304348 | 63 | h |
null | ceph-main/src/common/lockdep.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) 2008-2011 New Dream Network
*
* 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 "lockdep.h"
#include <bitset>
#include "common/ceph_context.h"
#include "common/dout.h"
#include "common/valgrind.h"
/******* Constants **********/
#define lockdep_dout(v) lsubdout(g_lockdep_ceph_ctx, lockdep, v)
#define BACKTRACE_SKIP 2
/******* Globals **********/
bool g_lockdep;
struct lockdep_stopper_t {
// disable lockdep when this module destructs.
~lockdep_stopper_t() {
g_lockdep = 0;
}
};
static pthread_mutex_t lockdep_mutex = PTHREAD_MUTEX_INITIALIZER;
static CephContext *g_lockdep_ceph_ctx = NULL;
static lockdep_stopper_t lockdep_stopper;
static ceph::unordered_map<std::string, int> lock_ids;
static std::map<int, std::string> lock_names;
static std::map<int, int> lock_refs;
static constexpr size_t MAX_LOCKS = 128 * 1024; // increase me as needed
static std::bitset<MAX_LOCKS> free_ids; // bit set = free
static ceph::unordered_map<pthread_t, std::map<int,ceph::BackTrace*> > held;
static constexpr size_t NR_LOCKS = 4096; // the initial number of locks
static std::vector<std::bitset<MAX_LOCKS>> follows(NR_LOCKS); // follows[a][b] means b taken after a
static std::vector<std::map<int,ceph::BackTrace *>> follows_bt(NR_LOCKS);
// upper bound of lock id
unsigned current_maxid;
int last_freed_id = -1;
static bool free_ids_inited;
static bool lockdep_force_backtrace()
{
return (g_lockdep_ceph_ctx != NULL &&
g_lockdep_ceph_ctx->_conf->lockdep_force_backtrace);
}
/******* Functions **********/
void lockdep_register_ceph_context(CephContext *cct)
{
static_assert((MAX_LOCKS > 0) && (MAX_LOCKS % 8 == 0),
"lockdep's MAX_LOCKS needs to be divisible by 8 to operate correctly.");
pthread_mutex_lock(&lockdep_mutex);
if (g_lockdep_ceph_ctx == NULL) {
ANNOTATE_BENIGN_RACE_SIZED(&g_lockdep_ceph_ctx, sizeof(g_lockdep_ceph_ctx),
"lockdep cct");
ANNOTATE_BENIGN_RACE_SIZED(&g_lockdep, sizeof(g_lockdep),
"lockdep enabled");
g_lockdep = true;
g_lockdep_ceph_ctx = cct;
lockdep_dout(1) << "lockdep start" << dendl;
if (!free_ids_inited) {
free_ids_inited = true;
// FIPS zeroization audit 20191115: this memset is not security related.
free_ids.set();
}
}
pthread_mutex_unlock(&lockdep_mutex);
}
void lockdep_unregister_ceph_context(CephContext *cct)
{
pthread_mutex_lock(&lockdep_mutex);
if (cct == g_lockdep_ceph_ctx) {
lockdep_dout(1) << "lockdep stop" << dendl;
// this cct is going away; shut it down!
g_lockdep = false;
g_lockdep_ceph_ctx = NULL;
// blow away all of our state, too, in case it starts up again.
for (unsigned i = 0; i < current_maxid; ++i) {
for (unsigned j = 0; j < current_maxid; ++j) {
delete follows_bt[i][j];
}
}
held.clear();
lock_names.clear();
lock_ids.clear();
std::for_each(follows.begin(), std::next(follows.begin(), current_maxid),
[](auto& follow) { follow.reset(); });
std::for_each(follows_bt.begin(), std::next(follows_bt.begin(), current_maxid),
[](auto& follow_bt) { follow_bt = {}; });
}
pthread_mutex_unlock(&lockdep_mutex);
}
int lockdep_dump_locks()
{
pthread_mutex_lock(&lockdep_mutex);
if (!g_lockdep)
goto out;
for (auto p = held.begin(); p != held.end(); ++p) {
lockdep_dout(0) << "--- thread " << p->first << " ---" << dendl;
for (auto q = p->second.begin();
q != p->second.end();
++q) {
lockdep_dout(0) << " * " << lock_names[q->first] << "\n";
if (q->second)
*_dout << *(q->second);
*_dout << dendl;
}
}
out:
pthread_mutex_unlock(&lockdep_mutex);
return 0;
}
int lockdep_get_free_id(void)
{
// if there's id known to be freed lately, reuse it
if (last_freed_id >= 0 &&
free_ids.test(last_freed_id)) {
int tmp = last_freed_id;
last_freed_id = -1;
free_ids.reset(tmp);
lockdep_dout(1) << "lockdep reusing last freed id " << tmp << dendl;
return tmp;
}
// walk through entire array and locate nonzero char, then find
// actual bit.
for (size_t i = 0; i < free_ids.size(); ++i) {
if (free_ids.test(i)) {
free_ids.reset(i);
return i;
}
}
// not found
lockdep_dout(0) << "failing miserably..." << dendl;
return -1;
}
static int _lockdep_register(const char *name)
{
int id = -1;
if (!g_lockdep)
return id;
ceph::unordered_map<std::string, int>::iterator p = lock_ids.find(name);
if (p == lock_ids.end()) {
id = lockdep_get_free_id();
if (id < 0) {
lockdep_dout(0) << "ERROR OUT OF IDS .. have 0"
<< " max " << MAX_LOCKS << dendl;
for (auto& p : lock_names) {
lockdep_dout(0) << " lock " << p.first << " " << p.second << dendl;
}
ceph_abort();
}
if (current_maxid <= (unsigned)id) {
current_maxid = (unsigned)id + 1;
if (current_maxid == follows.size()) {
follows.resize(current_maxid + 1);
follows_bt.resize(current_maxid + 1);
}
}
lock_ids[name] = id;
lock_names[id] = name;
lockdep_dout(10) << "registered '" << name << "' as " << id << dendl;
} else {
id = p->second;
lockdep_dout(20) << "had '" << name << "' as " << id << dendl;
}
++lock_refs[id];
return id;
}
int lockdep_register(const char *name)
{
int id;
pthread_mutex_lock(&lockdep_mutex);
id = _lockdep_register(name);
pthread_mutex_unlock(&lockdep_mutex);
return id;
}
void lockdep_unregister(int id)
{
if (id < 0) {
return;
}
pthread_mutex_lock(&lockdep_mutex);
std::string name;
auto p = lock_names.find(id);
if (p == lock_names.end())
name = "unknown" ;
else
name = p->second;
int &refs = lock_refs[id];
if (--refs == 0) {
if (p != lock_names.end()) {
// reset dependency ordering
follows[id].reset();
for (unsigned i=0; i<current_maxid; ++i) {
delete follows_bt[id][i];
follows_bt[id][i] = NULL;
delete follows_bt[i][id];
follows_bt[i][id] = NULL;
follows[i].reset(id);
}
lockdep_dout(10) << "unregistered '" << name << "' from " << id << dendl;
lock_ids.erase(p->second);
lock_names.erase(id);
}
lock_refs.erase(id);
free_ids.set(id);
last_freed_id = id;
} else if (g_lockdep) {
lockdep_dout(20) << "have " << refs << " of '" << name << "' " <<
"from " << id << dendl;
}
pthread_mutex_unlock(&lockdep_mutex);
}
// does b follow a?
static bool does_follow(int a, int b)
{
if (follows[a].test(b)) {
lockdep_dout(0) << "\n";
*_dout << "------------------------------------" << "\n";
*_dout << "existing dependency " << lock_names[a] << " (" << a << ") -> "
<< lock_names[b] << " (" << b << ") at:\n";
if (follows_bt[a][b]) {
follows_bt[a][b]->print(*_dout);
}
*_dout << dendl;
return true;
}
for (unsigned i=0; i<current_maxid; i++) {
if (follows[a].test(i) &&
does_follow(i, b)) {
lockdep_dout(0) << "existing intermediate dependency " << lock_names[a]
<< " (" << a << ") -> " << lock_names[i] << " (" << i << ") at:\n";
if (follows_bt[a][i]) {
follows_bt[a][i]->print(*_dout);
}
*_dout << dendl;
return true;
}
}
return false;
}
int lockdep_will_lock(const char *name, int id, bool force_backtrace,
bool recursive)
{
pthread_t p = pthread_self();
pthread_mutex_lock(&lockdep_mutex);
if (!g_lockdep) {
pthread_mutex_unlock(&lockdep_mutex);
return id;
}
if (id < 0)
id = _lockdep_register(name);
lockdep_dout(20) << "_will_lock " << name << " (" << id << ")" << dendl;
// check dependency graph
auto& m = held[p];
for (auto p = m.begin(); p != m.end(); ++p) {
if (p->first == id) {
if (!recursive) {
lockdep_dout(0) << "\n";
*_dout << "recursive lock of " << name << " (" << id << ")\n";
auto bt = new ceph::ClibBackTrace(BACKTRACE_SKIP);
bt->print(*_dout);
if (p->second) {
*_dout << "\npreviously locked at\n";
p->second->print(*_dout);
}
delete bt;
*_dout << dendl;
ceph_abort();
}
} else if (!follows[p->first].test(id)) {
// new dependency
// did we just create a cycle?
if (does_follow(id, p->first)) {
auto bt = new ceph::ClibBackTrace(BACKTRACE_SKIP);
lockdep_dout(0) << "new dependency " << lock_names[p->first]
<< " (" << p->first << ") -> " << name << " (" << id << ")"
<< " creates a cycle at\n";
bt->print(*_dout);
*_dout << dendl;
lockdep_dout(0) << "btw, i am holding these locks:" << dendl;
for (auto q = m.begin(); q != m.end(); ++q) {
lockdep_dout(0) << " " << lock_names[q->first] << " (" << q->first << ")" << dendl;
if (q->second) {
lockdep_dout(0) << " ";
q->second->print(*_dout);
*_dout << dendl;
}
}
lockdep_dout(0) << "\n" << dendl;
// don't add this dependency, or we'll get aMutex. cycle in the graph, and
// does_follow() won't terminate.
ceph_abort(); // actually, we should just die here.
} else {
ceph::BackTrace* bt = NULL;
if (force_backtrace || lockdep_force_backtrace()) {
bt = new ceph::ClibBackTrace(BACKTRACE_SKIP);
}
follows[p->first].set(id);
follows_bt[p->first][id] = bt;
lockdep_dout(10) << lock_names[p->first] << " -> " << name << " at" << dendl;
//bt->print(*_dout);
}
}
}
pthread_mutex_unlock(&lockdep_mutex);
return id;
}
int lockdep_locked(const char *name, int id, bool force_backtrace)
{
pthread_t p = pthread_self();
pthread_mutex_lock(&lockdep_mutex);
if (!g_lockdep)
goto out;
if (id < 0)
id = _lockdep_register(name);
lockdep_dout(20) << "_locked " << name << dendl;
if (force_backtrace || lockdep_force_backtrace())
held[p][id] = new ceph::ClibBackTrace(BACKTRACE_SKIP);
else
held[p][id] = 0;
out:
pthread_mutex_unlock(&lockdep_mutex);
return id;
}
int lockdep_will_unlock(const char *name, int id)
{
pthread_t p = pthread_self();
if (id < 0) {
//id = lockdep_register(name);
ceph_assert(id == -1);
return id;
}
pthread_mutex_lock(&lockdep_mutex);
if (!g_lockdep)
goto out;
lockdep_dout(20) << "_will_unlock " << name << dendl;
// don't assert.. lockdep may be enabled at any point in time
//assert(held.count(p));
//assert(held[p].count(id));
delete held[p][id];
held[p].erase(id);
out:
pthread_mutex_unlock(&lockdep_mutex);
return id;
}
| 10,866 | 26.099751 | 100 | cc |
null | ceph-main/src/common/lockdep.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) 2008-2011 New Dream Network
*
* 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_LOCKDEP_H
#define CEPH_LOCKDEP_H
#include "include/common_fwd.h"
#ifdef CEPH_DEBUG_MUTEX
extern bool g_lockdep;
extern void lockdep_register_ceph_context(CephContext *cct);
extern void lockdep_unregister_ceph_context(CephContext *cct);
// lockdep tracks dependencies between multiple and different instances
// of locks within a class denoted by `n`.
// Caller is obliged to guarantee name uniqueness.
extern int lockdep_register(const char *n);
extern void lockdep_unregister(int id);
extern int lockdep_will_lock(const char *n, int id, bool force_backtrace=false,
bool recursive=false);
extern int lockdep_locked(const char *n, int id, bool force_backtrace=false);
extern int lockdep_will_unlock(const char *n, int id);
extern int lockdep_dump_locks();
#else
static constexpr bool g_lockdep = false;
#define lockdep_register(...) 0
#define lockdep_unregister(...)
#define lockdep_will_lock(...) 0
#define lockdep_locked(...) 0
#define lockdep_will_unlock(...) 0
#endif // CEPH_DEBUG_MUTEX
#endif
| 1,442 | 27.86 | 79 | h |
null | ceph-main/src/common/lru_map.h | #ifndef CEPH_LRU_MAP_H
#define CEPH_LRU_MAP_H
#include "common/ceph_mutex.h"
template <class K, class V>
class lru_map {
struct entry {
V value;
typename std::list<K>::iterator lru_iter;
};
std::map<K, entry> entries;
std::list<K> entries_lru;
ceph::mutex lock = ceph::make_mutex("lru_map::lock");
size_t max;
public:
class UpdateContext {
public:
virtual ~UpdateContext() {}
/* update should return true if object is updated */
virtual bool update(V *v) = 0;
};
bool _find(const K& key, V *value, UpdateContext *ctx);
void _add(const K& key, V& value);
public:
lru_map(int _max) : max(_max) {}
virtual ~lru_map() {}
bool find(const K& key, V& value);
/*
* find_and_update()
*
* - will return true if object is found
* - if ctx is set will return true if object is found and updated
*/
bool find_and_update(const K& key, V *value, UpdateContext *ctx);
void add(const K& key, V& value);
void erase(const K& key);
};
template <class K, class V>
bool lru_map<K, V>::_find(const K& key, V *value, UpdateContext *ctx)
{
typename std::map<K, entry>::iterator iter = entries.find(key);
if (iter == entries.end()) {
return false;
}
entry& e = iter->second;
entries_lru.erase(e.lru_iter);
bool r = true;
if (ctx)
r = ctx->update(&e.value);
if (value)
*value = e.value;
entries_lru.push_front(key);
e.lru_iter = entries_lru.begin();
return r;
}
template <class K, class V>
bool lru_map<K, V>::find(const K& key, V& value)
{
std::lock_guard l(lock);
return _find(key, &value, NULL);
}
template <class K, class V>
bool lru_map<K, V>::find_and_update(const K& key, V *value, UpdateContext *ctx)
{
std::lock_guard l(lock);
return _find(key, value, ctx);
}
template <class K, class V>
void lru_map<K, V>::_add(const K& key, V& value)
{
typename std::map<K, entry>::iterator iter = entries.find(key);
if (iter != entries.end()) {
entry& e = iter->second;
entries_lru.erase(e.lru_iter);
}
entries_lru.push_front(key);
entry& e = entries[key];
e.value = value;
e.lru_iter = entries_lru.begin();
while (entries.size() > max) {
typename std::list<K>::reverse_iterator riter = entries_lru.rbegin();
iter = entries.find(*riter);
// ceph_assert(iter != entries.end());
entries.erase(iter);
entries_lru.pop_back();
}
}
template <class K, class V>
void lru_map<K, V>::add(const K& key, V& value)
{
std::lock_guard l(lock);
_add(key, value);
}
template <class K, class V>
void lru_map<K, V>::erase(const K& key)
{
std::lock_guard l(lock);
typename std::map<K, entry>::iterator iter = entries.find(key);
if (iter == entries.end())
return;
entry& e = iter->second;
entries_lru.erase(e.lru_iter);
entries.erase(iter);
}
#endif
| 2,813 | 20.157895 | 79 | h |
null | ceph-main/src/common/mClockPriorityQueue.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 Red Hat 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
#include <functional>
#include <map>
#include <list>
#include <cmath>
#include "common/Formatter.h"
#include "common/OpQueue.h"
#include "dmclock/src/dmclock_server.h"
// the following is done to unclobber _ASSERT_H so it returns to the
// way ceph likes it
#include "include/ceph_assert.h"
namespace ceph {
namespace dmc = crimson::dmclock;
template <typename T, typename K>
class mClockQueue : public OpQueue <T, K> {
using priority_t = unsigned;
using cost_t = unsigned;
typedef std::list<std::pair<cost_t, T> > ListPairs;
static void filter_list_pairs(ListPairs *l,
std::function<bool (T&&)> f) {
for (typename ListPairs::iterator i = l->end();
i != l->begin();
/* no inc */
) {
auto next = i;
--next;
if (f(std::move(next->second))) {
l->erase(next);
} else {
i = next;
}
}
}
struct SubQueue {
private:
typedef std::map<K, ListPairs> Classes;
// client-class to ordered queue
Classes q;
unsigned tokens, max_tokens;
typename Classes::iterator cur;
public:
SubQueue(const SubQueue &other)
: q(other.q),
tokens(other.tokens),
max_tokens(other.max_tokens),
cur(q.begin()) {}
SubQueue()
: tokens(0),
max_tokens(0),
cur(q.begin()) {}
void set_max_tokens(unsigned mt) {
max_tokens = mt;
}
unsigned get_max_tokens() const {
return max_tokens;
}
unsigned num_tokens() const {
return tokens;
}
void put_tokens(unsigned t) {
tokens += t;
if (tokens > max_tokens) {
tokens = max_tokens;
}
}
void take_tokens(unsigned t) {
if (tokens > t) {
tokens -= t;
} else {
tokens = 0;
}
}
void enqueue(K cl, cost_t cost, T&& item) {
q[cl].emplace_back(cost, std::move(item));
if (cur == q.end())
cur = q.begin();
}
void enqueue_front(K cl, cost_t cost, T&& item) {
q[cl].emplace_front(cost, std::move(item));
if (cur == q.end())
cur = q.begin();
}
const std::pair<cost_t, T>& front() const {
ceph_assert(!(q.empty()));
ceph_assert(cur != q.end());
return cur->second.front();
}
std::pair<cost_t, T>& front() {
ceph_assert(!(q.empty()));
ceph_assert(cur != q.end());
return cur->second.front();
}
void pop_front() {
ceph_assert(!(q.empty()));
ceph_assert(cur != q.end());
cur->second.pop_front();
if (cur->second.empty()) {
auto i = cur;
++cur;
q.erase(i);
} else {
++cur;
}
if (cur == q.end()) {
cur = q.begin();
}
}
unsigned get_size_slow() const {
unsigned count = 0;
for (const auto& cls : q) {
count += cls.second.size();
}
return count;
}
bool empty() const {
return q.empty();
}
void remove_by_filter(std::function<bool (T&&)> f) {
for (typename Classes::iterator i = q.begin();
i != q.end();
/* no-inc */) {
filter_list_pairs(&(i->second), f);
if (i->second.empty()) {
if (cur == i) {
++cur;
}
i = q.erase(i);
} else {
++i;
}
}
if (cur == q.end()) cur = q.begin();
}
void remove_by_class(K k, std::list<T> *out) {
typename Classes::iterator i = q.find(k);
if (i == q.end()) {
return;
}
if (i == cur) {
++cur;
}
if (out) {
for (auto j = i->second.rbegin(); j != i->second.rend(); ++j) {
out->push_front(std::move(j->second));
}
}
q.erase(i);
if (cur == q.end()) cur = q.begin();
}
void dump(ceph::Formatter *f) const {
f->dump_int("size", get_size_slow());
f->dump_int("num_keys", q.size());
}
};
using SubQueues = std::map<priority_t, SubQueue>;
SubQueues high_queue;
using Queue = dmc::PullPriorityQueue<K,T,false>;
Queue queue;
// when enqueue_front is called, rather than try to re-calc tags
// to put in mClock priority queue, we'll just keep a separate
// list from which we dequeue items first, and only when it's
// empty do we use queue.
std::list<std::pair<K,T>> queue_front;
public:
mClockQueue(
const typename Queue::ClientInfoFunc& info_func,
double anticipation_timeout = 0.0) :
queue(info_func, dmc::AtLimit::Allow, anticipation_timeout)
{
// empty
}
unsigned get_size_slow() const {
unsigned total = 0;
total += queue_front.size();
total += queue.request_count();
for (auto i = high_queue.cbegin(); i != high_queue.cend(); ++i) {
ceph_assert(i->second.get_size_slow());
total += i->second.get_size_slow();
}
return total;
}
// be sure to do things in reverse priority order and push_front
// to the list so items end up on list in front-to-back priority
// order
void remove_by_filter(std::function<bool (T&&)> filter_accum) {
queue.remove_by_req_filter([&] (std::unique_ptr<T>&& r) {
return filter_accum(std::move(*r));
}, true);
for (auto i = queue_front.rbegin(); i != queue_front.rend(); /* no-inc */) {
if (filter_accum(std::move(i->second))) {
i = decltype(i){ queue_front.erase(std::next(i).base()) };
} else {
++i;
}
}
for (typename SubQueues::iterator i = high_queue.begin();
i != high_queue.end();
/* no-inc */ ) {
i->second.remove_by_filter(filter_accum);
if (i->second.empty()) {
i = high_queue.erase(i);
} else {
++i;
}
}
}
void remove_by_class(K k, std::list<T> *out = nullptr) override final {
if (out) {
queue.remove_by_client(k,
true,
[&out] (std::unique_ptr<T>&& t) {
out->push_front(std::move(*t));
});
} else {
queue.remove_by_client(k, true);
}
for (auto i = queue_front.rbegin(); i != queue_front.rend(); /* no-inc */) {
if (k == i->first) {
if (nullptr != out) out->push_front(std::move(i->second));
i = decltype(i){ queue_front.erase(std::next(i).base()) };
} else {
++i;
}
}
for (auto i = high_queue.begin(); i != high_queue.end(); /* no-inc */) {
i->second.remove_by_class(k, out);
if (i->second.empty()) {
i = high_queue.erase(i);
} else {
++i;
}
}
}
void enqueue_strict(K cl, unsigned priority, T&& item) override final {
high_queue[priority].enqueue(cl, 1, std::move(item));
}
void enqueue_strict_front(K cl, unsigned priority, T&& item) override final {
high_queue[priority].enqueue_front(cl, 1, std::move(item));
}
void enqueue(K cl, unsigned priority, unsigned cost, T&& item) override final {
// priority is ignored
queue.add_request(std::move(item), cl, cost);
}
void enqueue_front(K cl,
unsigned priority,
unsigned cost,
T&& item) override final {
queue_front.emplace_front(std::pair<K,T>(cl, std::move(item)));
}
bool empty() const override final {
return queue.empty() && high_queue.empty() && queue_front.empty();
}
T dequeue() override final {
ceph_assert(!empty());
if (!high_queue.empty()) {
T ret = std::move(high_queue.rbegin()->second.front().second);
high_queue.rbegin()->second.pop_front();
if (high_queue.rbegin()->second.empty()) {
high_queue.erase(high_queue.rbegin()->first);
}
return ret;
}
if (!queue_front.empty()) {
T ret = std::move(queue_front.front().second);
queue_front.pop_front();
return ret;
}
auto pr = queue.pull_request();
ceph_assert(pr.is_retn());
auto& retn = pr.get_retn();
return std::move(*(retn.request));
}
void dump(ceph::Formatter *f) const override final {
f->open_array_section("high_queues");
for (typename SubQueues::const_iterator p = high_queue.begin();
p != high_queue.end();
++p) {
f->open_object_section("subqueue");
f->dump_int("priority", p->first);
p->second.dump(f);
f->close_section();
}
f->close_section();
f->open_object_section("queue_front");
f->dump_int("size", queue_front.size());
f->close_section();
f->open_object_section("queue");
f->dump_int("size", queue.request_count());
f->close_section();
} // dump
void print(std::ostream &os) const final {
os << "mClockPriorityQueue";
}
};
} // namespace ceph
| 8,645 | 22.367568 | 83 | h |
null | ceph-main/src/common/map_cacher.hpp | // -*- 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 MAPCACHER_H
#define MAPCACHER_H
#include "include/Context.h"
#include "common/sharedptr_registry.hpp"
namespace MapCacher {
/**
* Abstraction for ordering key updates
*/
template<typename K, typename V>
class Transaction {
public:
/// Std::set keys according to map
virtual void set_keys(
const std::map<K, V> &keys ///< [in] keys/values to std::set
) = 0;
/// Remove keys
virtual void remove_keys(
const std::set<K> &to_remove ///< [in] keys to remove
) = 0;
/// Add context to fire when data is readable
virtual void add_callback(
Context *c ///< [in] Context to fire on readable
) = 0;
virtual ~Transaction() {}
};
/**
* Abstraction for fetching keys
*/
template<typename K, typename V>
class StoreDriver {
public:
/// Returns requested key values
virtual int get_keys(
const std::set<K> &keys, ///< [in] keys requested
std::map<K, V> *got ///< [out] values for keys obtained
) = 0; ///< @return error value
/// Returns next key
virtual int get_next(
const K &key, ///< [in] key after which to get next
std::pair<K, V> *next ///< [out] first key after key
) = 0; ///< @return 0 on success, -ENOENT if there is no next
virtual int get_next_or_current(
const K &key, ///< [in] key at-which-or-after to get
std::pair<K, V> *next_or_current
) = 0; ///< @return 0 on success, -ENOENT if there is no next
virtual ~StoreDriver() {}
};
/**
* Uses SharedPtrRegistry to cache objects of in progress writes
* allowing the user to read/write a consistent view of the map
* without flushing writes.
*/
template<typename K, typename V>
class MapCacher {
private:
StoreDriver<K, V> *driver;
SharedPtrRegistry<K, boost::optional<V> > in_progress;
typedef typename SharedPtrRegistry<K, boost::optional<V> >::VPtr VPtr;
typedef ContainerContext<std::set<VPtr> > TransHolder;
public:
MapCacher(StoreDriver<K, V> *driver) : driver(driver) {}
/// Fetch first key/value std::pair after specified key
int get_next(
K key, ///< [in] key after which to get next
std::pair<K, V> *next ///< [out] next key
) {
while (true) {
std::pair<K, boost::optional<V> > cached;
std::pair<K, V> store;
bool got_cached = in_progress.get_next(key, &cached);
bool got_store = false;
int r = driver->get_next(key, &store);
if (r < 0 && r != -ENOENT) {
return r;
} else if (r == 0) {
got_store = true;
}
if (!got_cached && !got_store) {
return -ENOENT;
} else if (
got_cached &&
(!got_store || store.first >= cached.first)) {
if (cached.second) {
if (next)
*next = make_pair(cached.first, cached.second.get());
return 0;
} else {
key = cached.first;
continue; // value was cached as removed, recurse
}
} else {
if (next)
*next = store;
return 0;
}
}
ceph_abort(); // not reachable
return -EINVAL;
} ///< @return error value, 0 on success, -ENOENT if no more entries
/// Adds operation setting keys to Transaction
void set_keys(
const std::map<K, V> &keys, ///< [in] keys/values to std::set
Transaction<K, V> *t ///< [out] transaction to use
) {
std::set<VPtr> vptrs;
for (auto i = keys.begin(); i != keys.end(); ++i) {
VPtr ip = in_progress.lookup_or_create(i->first, i->second);
*ip = i->second;
vptrs.insert(ip);
}
t->set_keys(keys);
t->add_callback(new TransHolder(vptrs));
}
/// Adds operation removing keys to Transaction
void remove_keys(
const std::set<K> &keys, ///< [in]
Transaction<K, V> *t ///< [out] transaction to use
) {
std::set<VPtr> vptrs;
for (auto i = keys.begin(); i != keys.end(); ++i) {
boost::optional<V> empty;
VPtr ip = in_progress.lookup_or_create(*i, empty);
*ip = empty;
vptrs.insert(ip);
}
t->remove_keys(keys);
t->add_callback(new TransHolder(vptrs));
}
/// Gets keys, uses cached values for unstable keys
int get_keys(
const std::set<K> &keys_to_get, ///< [in] std::set of keys to fetch
std::map<K, V> *got ///< [out] keys gotten
) {
std::set<K> to_get;
std::map<K, V> _got;
for (auto i = keys_to_get.begin();
i != keys_to_get.end();
++i) {
VPtr val = in_progress.lookup(*i);
if (val) {
if (*val)
got->insert(make_pair(*i, val->get()));
//else: value cached is empty, key doesn't exist
} else {
to_get.insert(*i);
}
}
int r = driver->get_keys(to_get, &_got);
if (r < 0)
return r;
for (auto i = _got.begin(); i != _got.end(); ++i) {
got->insert(*i);
}
return 0;
} ///< @return error value, 0 on success
};
} // namespace
#endif
| 5,167 | 26.057592 | 72 | hpp |
null | ceph-main/src/common/mempool.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 Allen Samuels <[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 "include/mempool.h"
#include "include/demangle.h"
// Thread local variables should save index, not &shard[index],
// because shard[] is defined in the class
static thread_local size_t thread_shard_index = mempool::num_shards;
// default to debug_mode off
bool mempool::debug_mode = false;
// --------------------------------------------------------------
mempool::pool_t& mempool::get_pool(mempool::pool_index_t ix)
{
// We rely on this array being initialized before any invocation of
// this function, even if it is called by ctors in other compilation
// units that are being initialized before this compilation unit.
static mempool::pool_t table[num_pools];
return table[ix];
}
const char *mempool::get_pool_name(mempool::pool_index_t ix) {
#define P(x) #x,
static const char *names[num_pools] = {
DEFINE_MEMORY_POOLS_HELPER(P)
};
#undef P
return names[ix];
}
void mempool::dump(ceph::Formatter *f)
{
stats_t total;
f->open_object_section("mempool"); // we need (dummy?) topmost section for
// JSON Formatter to print pool names. It omits them otherwise.
f->open_object_section("by_pool");
for (size_t i = 0; i < num_pools; ++i) {
const pool_t &pool = mempool::get_pool((pool_index_t)i);
f->open_object_section(get_pool_name((pool_index_t)i));
pool.dump(f, &total);
f->close_section();
}
f->close_section();
f->dump_object("total", total);
f->close_section();
}
void mempool::set_debug_mode(bool d)
{
debug_mode = d;
}
// --------------------------------------------------------------
// pool_t
size_t mempool::pool_t::allocated_bytes() const
{
ssize_t result = 0;
for (size_t i = 0; i < num_shards; ++i) {
result += shard[i].bytes;
}
if (result < 0) {
// we raced with some unbalanced allocations/deallocations
result = 0;
}
return (size_t) result;
}
size_t mempool::pool_t::allocated_items() const
{
ssize_t result = 0;
for (size_t i = 0; i < num_shards; ++i) {
result += shard[i].items;
}
if (result < 0) {
// we raced with some unbalanced allocations/deallocations
result = 0;
}
return (size_t) result;
}
void mempool::pool_t::adjust_count(ssize_t items, ssize_t bytes)
{
thread_shard_index = (thread_shard_index == num_shards) ? pick_a_shard_int() : thread_shard_index;
shard[thread_shard_index].items += items;
shard[thread_shard_index].bytes += bytes;
}
void mempool::pool_t::get_stats(
stats_t *total,
std::map<std::string, stats_t> *by_type) const
{
for (size_t i = 0; i < num_shards; ++i) {
total->items += shard[i].items;
total->bytes += shard[i].bytes;
}
if (debug_mode) {
std::lock_guard shard_lock(lock);
for (auto &p : type_map) {
std::string n = ceph_demangle(p.second.type_name);
stats_t &s = (*by_type)[n];
s.bytes = p.second.items * p.second.item_size;
s.items = p.second.items;
}
}
}
void mempool::pool_t::dump(ceph::Formatter *f, stats_t *ptotal) const
{
stats_t total;
std::map<std::string, stats_t> by_type;
get_stats(&total, &by_type);
if (ptotal) {
*ptotal += total;
}
total.dump(f);
if (!by_type.empty()) {
f->open_object_section("by_type");
for (auto &i : by_type) {
f->open_object_section(i.first.c_str());
i.second.dump(f);
f->close_section();
}
f->close_section();
}
}
| 3,786 | 25.858156 | 100 | cc |
null | ceph-main/src/common/mime.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) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_COMMON_MIME_H
#define CEPH_COMMON_MIME_H
#ifdef __cplusplus
extern "C" {
#endif
/* Encode a buffer as quoted-printable.
*
* The input is a null-terminated string.
* The output is a null-terminated string representing the input encoded as
* a MIME quoted-printable.
*
* Returns the length of the buffer we would need to do the encoding.
* If we don't have enough buffer space, the output will be truncated.
*
* You may call mime_encode_as_qp(input, NULL, 0) to find the size of the
* buffer you will need.
*/
signed int mime_encode_as_qp(const char *input, char *output, int outlen);
/* Decode a quoted-printable buffer.
*
* The input is a null-terminated string encoded as a MIME quoted-printable.
* The output is a null-terminated string representing the input decoded.
*
* Returns a negative error code if the input is not a valid quoted-printable
* buffer.
* Returns the length of the buffer we would need to do the encoding.
* If we don't have enough buffer space, the output will be truncated.
*
* You may call mime_decode_as_qp(input, NULL, 0) to find the size of the
* buffer you will need. The output will never be longer than the input for
* this function.
*/
signed int mime_decode_from_qp(const char *input, char *output, int outlen);
#ifdef __cplusplus
}
#endif
#endif
| 1,732 | 29.403509 | 77 | h |
null | ceph-main/src/common/module.h | /*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 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_MODULE_H
#define CEPH_MODULE_H
#ifdef __cplusplus
extern "C" {
#endif
int module_has_param(const char *module, const char *param);
int module_load(const char *module, const char *options);
#ifdef __cplusplus
}
#endif
#endif /* CEPH_MODULE_H */
| 576 | 19.607143 | 61 | h |
null | ceph-main/src/common/mutex_debug.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "common/mutex_debug.h"
#include "common/perf_counters.h"
#include "common/ceph_context.h"
#include "common/config.h"
namespace ceph {
namespace mutex_debug_detail {
enum {
l_mutex_first = 999082,
l_mutex_wait,
l_mutex_last
};
mutex_debugging_base::mutex_debugging_base(std::string group, bool ld, bool bt)
: group(std::move(group)),
lockdep(ld),
backtrace(bt)
{
if (_enable_lockdep()) {
_register();
}
}
mutex_debugging_base::~mutex_debugging_base() {
ceph_assert(nlock == 0);
if (_enable_lockdep()) {
lockdep_unregister(id);
}
}
void mutex_debugging_base::_register() {
id = lockdep_register(group.c_str());
}
void mutex_debugging_base::_will_lock(bool recursive) { // about to lock
id = lockdep_will_lock(group.c_str(), id, backtrace, recursive);
}
void mutex_debugging_base::_locked() { // just locked
id = lockdep_locked(group.c_str(), id, backtrace);
}
void mutex_debugging_base::_will_unlock() { // about to unlock
id = lockdep_will_unlock(group.c_str(), id);
}
} // namespace mutex_debug_detail
} // namespace ceph
| 1,508 | 24.15 | 79 | cc |
null | ceph-main/src/common/mutex_debug.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_COMMON_MUTEX_DEBUG_H
#define CEPH_COMMON_MUTEX_DEBUG_H
#include <atomic>
#include <system_error>
#include <thread>
#include <pthread.h>
#include "include/ceph_assert.h"
#include "include/common_fwd.h"
#include "ceph_time.h"
#include "likely.h"
#include "lockdep.h"
namespace ceph {
namespace mutex_debug_detail {
class mutex_debugging_base
{
protected:
std::string group;
int id = -1;
bool lockdep; // track this mutex using lockdep_*
bool backtrace; // gather backtrace on lock acquisition
std::atomic<int> nlock = 0;
std::thread::id locked_by = {};
bool _enable_lockdep() const {
return lockdep && g_lockdep;
}
void _register();
void _will_lock(bool recursive=false); // about to lock
void _locked(); // just locked
void _will_unlock(); // about to unlock
mutex_debugging_base(std::string group, bool ld = true, bool bt = false);
~mutex_debugging_base();
public:
bool is_locked() const {
return (nlock > 0);
}
bool is_locked_by_me() const {
return nlock.load(std::memory_order_acquire) > 0 && locked_by == std::this_thread::get_id();
}
operator bool() const {
return is_locked_by_me();
}
};
// Since this is a /debugging/ mutex just define it in terms of the
// pthread error check mutex.
template<bool Recursive>
class mutex_debug_impl : public mutex_debugging_base
{
private:
pthread_mutex_t m;
void _init() {
pthread_mutexattr_t a;
pthread_mutexattr_init(&a);
int r;
if (recursive)
r = pthread_mutexattr_settype(&a, PTHREAD_MUTEX_RECURSIVE);
else
r = pthread_mutexattr_settype(&a, PTHREAD_MUTEX_ERRORCHECK);
ceph_assert(r == 0);
r = pthread_mutex_init(&m, &a);
ceph_assert(r == 0);
}
bool enable_lockdep(bool no_lockdep) const {
if (recursive) {
return false;
} else if (no_lockdep) {
return false;
} else {
return _enable_lockdep();
}
}
public:
static constexpr bool recursive = Recursive;
mutex_debug_impl(std::string group, bool ld = true, bool bt = false)
: mutex_debugging_base(group, ld, bt) {
_init();
}
// Mutex is Destructible
~mutex_debug_impl() {
int r = pthread_mutex_destroy(&m);
ceph_assert(r == 0);
}
// Mutex concept is non-Copyable
mutex_debug_impl(const mutex_debug_impl&) = delete;
mutex_debug_impl& operator =(const mutex_debug_impl&) = delete;
// Mutex concept is non-Movable
mutex_debug_impl(mutex_debug_impl&&) = delete;
mutex_debug_impl& operator =(mutex_debug_impl&&) = delete;
void lock_impl() {
int r = pthread_mutex_lock(&m);
// Allowed error codes for Mutex concept
if (unlikely(r == EPERM ||
r == EDEADLK ||
r == EBUSY)) {
throw std::system_error(r, std::generic_category());
}
ceph_assert(r == 0);
}
void unlock_impl() noexcept {
int r = pthread_mutex_unlock(&m);
ceph_assert(r == 0);
}
bool try_lock_impl() {
int r = pthread_mutex_trylock(&m);
switch (r) {
case 0:
return true;
case EBUSY:
return false;
default:
throw std::system_error(r, std::generic_category());
}
}
pthread_mutex_t* native_handle() {
return &m;
}
void _post_lock() {
if (!recursive)
ceph_assert(nlock == 0);
locked_by = std::this_thread::get_id();
nlock.fetch_add(1, std::memory_order_release);
}
void _pre_unlock() {
if (recursive) {
ceph_assert(nlock > 0);
} else {
ceph_assert(nlock == 1);
}
ceph_assert(locked_by == std::this_thread::get_id());
if (nlock == 1)
locked_by = std::thread::id();
nlock.fetch_sub(1, std::memory_order_release);
}
bool try_lock(bool no_lockdep = false) {
bool locked = try_lock_impl();
if (locked) {
if (enable_lockdep(no_lockdep))
_locked();
_post_lock();
}
return locked;
}
void lock(bool no_lockdep = false) {
if (enable_lockdep(no_lockdep))
_will_lock(recursive);
if (try_lock(no_lockdep))
return;
lock_impl();
if (enable_lockdep(no_lockdep))
_locked();
_post_lock();
}
void unlock(bool no_lockdep = false) {
_pre_unlock();
if (enable_lockdep(no_lockdep))
_will_unlock();
unlock_impl();
}
};
} // namespace mutex_debug_detail
typedef mutex_debug_detail::mutex_debug_impl<false> mutex_debug;
typedef mutex_debug_detail::mutex_debug_impl<true> mutex_recursive_debug;
} // namespace ceph
#endif
| 4,859 | 22.142857 | 96 | h |
null | ceph-main/src/common/numa.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "numa.h"
#include <cstring>
#include <errno.h>
#include <iostream>
#include "include/stringify.h"
#include "common/safe_io.h"
using namespace std::literals;
using std::set;
// list
#if defined(__linux__)
int parse_cpu_set_list(const char *s,
size_t *cpu_set_size,
cpu_set_t *cpu_set)
{
CPU_ZERO(cpu_set);
while (*s) {
char *end;
int a = strtol(s, &end, 10);
if (end == s) {
return -EINVAL;
}
if (*end == '-') {
s = end + 1;
int b = strtol(s, &end, 10);
if (end == s) {
return -EINVAL;
}
for (; a <= b; ++a) {
CPU_SET(a, cpu_set);
}
*cpu_set_size = a;
} else {
CPU_SET(a, cpu_set);
*cpu_set_size = a + 1;
}
if (*end == 0) {
break;
}
if (*end != ',') {
return -EINVAL;
}
s = end + 1;
}
return 0;
}
std::string cpu_set_to_str_list(size_t cpu_set_size,
const cpu_set_t *cpu_set)
{
std::string r;
unsigned a = 0;
while (true) {
while (a < cpu_set_size && !CPU_ISSET(a, cpu_set)) {
++a;
}
if (a >= cpu_set_size) {
break;
}
unsigned b = a + 1;
while (b < cpu_set_size && CPU_ISSET(b, cpu_set)) {
++b;
}
if (r.size()) {
r += ",";
}
if (b > a + 1) {
r += stringify(a) + "-" + stringify(b - 1);
} else {
r += stringify(a);
}
a = b;
}
return r;
}
std::set<int> cpu_set_to_set(size_t cpu_set_size,
const cpu_set_t *cpu_set)
{
set<int> r;
unsigned a = 0;
while (true) {
while (a < cpu_set_size && !CPU_ISSET(a, cpu_set)) {
++a;
}
if (a >= cpu_set_size) {
break;
}
unsigned b = a + 1;
while (b < cpu_set_size && CPU_ISSET(b, cpu_set)) {
++b;
}
while (a < b) {
r.insert(a);
++a;
}
}
return r;
}
int get_numa_node_cpu_set(
int node,
size_t *cpu_set_size,
cpu_set_t *cpu_set)
{
std::string fn = "/sys/devices/system/node/node";
fn += stringify(node);
fn += "/cpulist";
int fd = ::open(fn.c_str(), O_RDONLY);
if (fd < 0) {
return -errno;
}
char buf[1024];
int r = safe_read(fd, &buf, sizeof(buf));
if (r < 0) {
goto out;
}
buf[r] = 0;
while (r > 0 && ::isspace(buf[--r])) {
buf[r] = 0;
}
r = parse_cpu_set_list(buf, cpu_set_size, cpu_set);
if (r < 0) {
goto out;
}
r = 0;
out:
::close(fd);
return r;
}
static int easy_readdir(const std::string& dir, std::set<std::string> *out)
{
DIR *h = ::opendir(dir.c_str());
if (!h) {
return -errno;
}
struct dirent *de = nullptr;
while ((de = ::readdir(h))) {
if (strcmp(de->d_name, ".") == 0 ||
strcmp(de->d_name, "..") == 0) {
continue;
}
out->insert(de->d_name);
}
closedir(h);
return 0;
}
#ifdef HAVE_DPDK
static std::string get_task_comm(pid_t tid)
{
static const char* comm_fmt = "/proc/self/task/%d/comm";
char comm_name[strlen(comm_fmt) + 8];
snprintf(comm_name, sizeof(comm_name), comm_fmt, tid);
int fd = open(comm_name, O_CLOEXEC | O_RDONLY);
if (fd == -1) {
return "";
}
// see linux/sched.h
static constexpr int TASK_COMM_LEN = 16;
char name[TASK_COMM_LEN];
ssize_t n = safe_read(fd, name, sizeof(name));
close(fd);
if (n < 0) {
return "";
}
assert(static_cast<size_t>(n) <= sizeof(name));
if (name[n - 1] == '\n') {
name[n - 1] = '\0';
} else {
name[n] = '\0';
}
return name;
}
#endif
int set_cpu_affinity_all_threads(size_t cpu_set_size, cpu_set_t *cpu_set)
{
// first set my affinity
int r = sched_setaffinity(getpid(), cpu_set_size, cpu_set);
if (r < 0) {
return -errno;
}
// make 2 passes here so that we (hopefully) catch racing threads creating
// threads.
for (unsigned pass = 0; pass < 2; ++pass) {
// enumerate all child threads from /proc
std::set<std::string> ls;
std::string path = "/proc/"s + stringify(getpid()) + "/task";
r = easy_readdir(path, &ls);
if (r < 0) {
return r;
}
for (auto& i : ls) {
pid_t tid = atoll(i.c_str());
if (!tid) {
continue; // wtf
}
#ifdef HAVE_DPDK
std::string thread_name = get_task_comm(tid);
static const char *dpdk_worker_name = "lcore-worker";
if (!thread_name.compare(0, strlen(dpdk_worker_name), dpdk_worker_name)) {
// ignore dpdk reactor thread, as it takes case of numa by itself
continue;
}
#endif
r = sched_setaffinity(tid, cpu_set_size, cpu_set);
if (r < 0) {
return -errno;
}
}
}
return 0;
}
#else
int parse_cpu_set_list(const char *s,
size_t *cpu_set_size,
cpu_set_t *cpu_set)
{
return -ENOTSUP;
}
std::string cpu_set_to_str_list(size_t cpu_set_size,
const cpu_set_t *cpu_set)
{
return {};
}
std::set<int> cpu_set_to_set(size_t cpu_set_size,
const cpu_set_t *cpu_set)
{
return {};
}
int get_numa_node_cpu_set(int node,
size_t *cpu_set_size,
cpu_set_t *cpu_set)
{
return -ENOTSUP;
}
int set_cpu_affinity_all_threads(size_t cpu_set_size,
cpu_set_t *cpu_set)
{
return -ENOTSUP;
}
#endif
| 5,230 | 19.042146 | 80 | cc |
null | ceph-main/src/common/numa.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <include/compat.h>
#include <sched.h>
#include <ostream>
#include <set>
int parse_cpu_set_list(const char *s,
size_t *cpu_set_size,
cpu_set_t *cpu_set);
std::string cpu_set_to_str_list(size_t cpu_set_size,
const cpu_set_t *cpu_set);
std::set<int> cpu_set_to_set(size_t cpu_set_size,
const cpu_set_t *cpu_set);
int get_numa_node_cpu_set(int node,
size_t *cpu_set_size,
cpu_set_t *cpu_set);
int set_cpu_affinity_all_threads(size_t cpu_set_size,
cpu_set_t *cpu_set);
| 634 | 24.4 | 70 | h |
null | ceph-main/src/common/obj_bencher.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) 2009 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
* Series of functions to test your rados installation. Notice
* that this code is not terribly robust -- for instance, if you
* try and bench on a pool you don't have permission to access
* it will just loop forever.
*/
#include "include/compat.h"
#include <pthread.h>
#include "common/ceph_mutex.h"
#include "common/Clock.h"
#include "obj_bencher.h"
using std::ostream;
using std::cerr;
using std::cout;
using std::setfill;
using std::setprecision;
using std::setw;
using std::string;
using std::unique_lock;
using std::unique_ptr;
const std::string BENCH_LASTRUN_METADATA = "benchmark_last_metadata";
const std::string BENCH_PREFIX = "benchmark_data";
const std::string BENCH_OBJ_NAME = BENCH_PREFIX + "_%s_%d_object%d";
static char cached_hostname[30] = {0};
int cached_pid = 0;
static std::string generate_object_prefix_nopid() {
if (cached_hostname[0] == 0) {
gethostname(cached_hostname, sizeof(cached_hostname)-1);
cached_hostname[sizeof(cached_hostname)-1] = 0;
}
std::ostringstream oss;
oss << BENCH_PREFIX << "_" << cached_hostname;
return oss.str();
}
static std::string generate_object_prefix(int pid = 0) {
if (pid)
cached_pid = pid;
else if (!cached_pid)
cached_pid = getpid();
std::ostringstream oss;
oss << generate_object_prefix_nopid() << "_" << cached_pid;
return oss.str();
}
// this is 8x faster than previous impl based on chained, deduped functions call
static std::string generate_object_name_fast(int objnum, int pid = 0)
{
if (cached_hostname[0] == 0) {
gethostname(cached_hostname, sizeof(cached_hostname)-1);
cached_hostname[sizeof(cached_hostname)-1] = 0;
}
if (pid)
cached_pid = pid;
else if (!cached_pid)
cached_pid = getpid();
char name[512];
int n = snprintf(&name[0], sizeof(name), BENCH_OBJ_NAME.c_str(), cached_hostname, cached_pid, objnum);
ceph_assert(n > 0 && n < (int)sizeof(name));
return std::string(&name[0], (size_t)n);
}
static void sanitize_object_contents (bench_data *data, size_t length) {
// FIPS zeroization audit 20191115: this memset is not security related.
memset(data->object_contents, 'z', length);
}
ostream& ObjBencher::out(ostream& os, utime_t& t)
{
if (show_time)
return t.localtime(os) << " ";
else
return os;
}
ostream& ObjBencher::out(ostream& os)
{
utime_t cur_time = ceph_clock_now();
return out(os, cur_time);
}
void *ObjBencher::status_printer(void *_bencher) {
ObjBencher *bencher = static_cast<ObjBencher *>(_bencher);
bench_data& data = bencher->data;
Formatter *formatter = bencher->formatter;
ostream *outstream = bencher->outstream;
ceph::condition_variable cond;
int i = 0;
int previous_writes = 0;
int cycleSinceChange = 0;
double bandwidth;
int iops = 0;
mono_clock::duration ONE_SECOND = std::chrono::seconds(1);
std::unique_lock locker{bencher->lock};
if (formatter)
formatter->open_array_section("datas");
while(!data.done) {
mono_time cur_time = mono_clock::now();
utime_t t = ceph_clock_now();
if (i % 20 == 0 && !formatter) {
if (i > 0)
t.localtime(cout)
<< " min lat: " << data.min_latency
<< " max lat: " << data.max_latency
<< " avg lat: " << data.avg_latency << std::endl;
//I'm naughty and don't reset the fill
bencher->out(cout, t) << setfill(' ')
<< setw(5) << "sec"
<< setw(8) << "Cur ops"
<< setw(10) << "started"
<< setw(10) << "finished"
<< setw(10) << "avg MB/s"
<< setw(10) << "cur MB/s"
<< setw(12) << "last lat(s)"
<< setw(12) << "avg lat(s)" << std::endl;
}
if (cycleSinceChange)
bandwidth = (double)(data.finished - previous_writes)
* (data.op_size)
/ (1024*1024)
/ cycleSinceChange;
else
bandwidth = -1;
if (!std::isnan(bandwidth) && bandwidth > -1) {
if (bandwidth > data.idata.max_bandwidth)
data.idata.max_bandwidth = bandwidth;
if (bandwidth < data.idata.min_bandwidth)
data.idata.min_bandwidth = bandwidth;
++data.idata.bandwidth_cycles;
double delta = bandwidth - data.idata.avg_bandwidth;
data.idata.avg_bandwidth += delta / data.idata.bandwidth_cycles;
data.idata.bandwidth_diff_sum += delta * (bandwidth - data.idata.avg_bandwidth);
}
if (cycleSinceChange)
iops = (double)(data.finished - previous_writes)
/ cycleSinceChange;
else
iops = -1;
if (!std::isnan(iops) && iops > -1) {
if (iops > data.idata.max_iops)
data.idata.max_iops = iops;
if (iops < data.idata.min_iops)
data.idata.min_iops = iops;
++data.idata.iops_cycles;
double delta = iops - data.idata.avg_iops;
data.idata.avg_iops += delta / data.idata.iops_cycles;
data.idata.iops_diff_sum += delta * (iops - data.idata.avg_iops);
}
if (formatter)
formatter->open_object_section("data");
// elapsed will be in seconds, by default
std::chrono::duration<double> elapsed = cur_time - data.start_time;
double avg_bandwidth = (double) (data.op_size) * (data.finished)
/ elapsed.count() / (1024*1024);
if (previous_writes != data.finished) {
previous_writes = data.finished;
cycleSinceChange = 0;
if (!formatter) {
bencher->out(cout, t)
<< setfill(' ')
<< setw(5) << i
<< ' ' << setw(7) << data.in_flight
<< ' ' << setw(9) << data.started
<< ' ' << setw(9) << data.finished
<< ' ' << setw(9) << avg_bandwidth
<< ' ' << setw(9) << bandwidth
<< ' ' << setw(11) << (double)data.cur_latency.count()
<< ' ' << setw(11) << data.avg_latency << std::endl;
} else {
formatter->dump_format("sec", "%d", i);
formatter->dump_format("cur_ops", "%d", data.in_flight);
formatter->dump_format("started", "%d", data.started);
formatter->dump_format("finished", "%d", data.finished);
formatter->dump_format("avg_bw", "%f", avg_bandwidth);
formatter->dump_format("cur_bw", "%f", bandwidth);
formatter->dump_format("last_lat", "%f", (double)data.cur_latency.count());
formatter->dump_format("avg_lat", "%f", data.avg_latency);
}
}
else {
if (!formatter) {
bencher->out(cout, t)
<< setfill(' ')
<< setw(5) << i
<< ' ' << setw(7) << data.in_flight
<< ' ' << setw(9) << data.started
<< ' ' << setw(9) << data.finished
<< ' ' << setw(9) << avg_bandwidth
<< ' ' << setw(9) << '0'
<< ' ' << setw(11) << '-'
<< ' '<< setw(11) << data.avg_latency << std::endl;
} else {
formatter->dump_format("sec", "%d", i);
formatter->dump_format("cur_ops", "%d", data.in_flight);
formatter->dump_format("started", "%d", data.started);
formatter->dump_format("finished", "%d", data.finished);
formatter->dump_format("avg_bw", "%f", avg_bandwidth);
formatter->dump_format("cur_bw", "%f", 0);
formatter->dump_format("last_lat", "%f", 0);
formatter->dump_format("avg_lat", "%f", data.avg_latency);
}
}
if (formatter) {
formatter->close_section(); // data
formatter->flush(*outstream);
}
++i;
++cycleSinceChange;
cond.wait_for(locker, ONE_SECOND);
}
if (formatter)
formatter->close_section(); //datas
if (iops < 0) {
std::chrono::duration<double> runtime = mono_clock::now() - data.start_time;
data.idata.min_iops = data.idata.max_iops = data.finished / runtime.count();
}
return NULL;
}
int ObjBencher::aio_bench(
int operation, int secondsToRun,
int concurrentios,
uint64_t op_size, uint64_t object_size,
unsigned max_objects,
bool cleanup, bool hints,
const std::string& run_name, bool reuse_bench, bool no_verify) {
if (concurrentios <= 0)
return -EINVAL;
int num_ops = 0;
int num_objects = 0;
int r = 0;
int prev_pid = 0;
std::chrono::duration<double> timePassed;
// default metadata object is used if user does not specify one
const std::string run_name_meta = (run_name.empty() ? BENCH_LASTRUN_METADATA : run_name);
//get data from previous write run, if available
if (operation != OP_WRITE || reuse_bench) {
uint64_t prev_op_size, prev_object_size;
r = fetch_bench_metadata(run_name_meta, &prev_op_size, &prev_object_size,
&num_ops, &num_objects, &prev_pid);
if (r < 0) {
if (r == -ENOENT) {
if (reuse_bench)
cerr << "Must write data before using reuse_bench for a write benchmark!" << std::endl;
else
cerr << "Must write data before running a read benchmark!" << std::endl;
}
return r;
}
object_size = prev_object_size;
op_size = prev_op_size;
}
char* contentsChars = new char[op_size];
lock.lock();
data.done = false;
data.hints = hints;
data.object_size = object_size;
data.op_size = op_size;
data.in_flight = 0;
data.started = 0;
data.finished = 0;
data.min_latency = 9999.0; // this better be higher than initial latency!
data.max_latency = 0;
data.avg_latency = 0;
data.latency_diff_sum = 0;
data.object_contents = contentsChars;
lock.unlock();
//fill in contentsChars deterministically so we can check returns
sanitize_object_contents(&data, data.op_size);
if (formatter)
formatter->open_object_section("bench");
if (OP_WRITE == operation) {
r = write_bench(secondsToRun, concurrentios, run_name_meta, max_objects, prev_pid);
if (r != 0) goto out;
}
else if (OP_SEQ_READ == operation) {
r = seq_read_bench(secondsToRun, num_ops, num_objects, concurrentios, prev_pid, no_verify);
if (r != 0) goto out;
}
else if (OP_RAND_READ == operation) {
r = rand_read_bench(secondsToRun, num_ops, num_objects, concurrentios, prev_pid, no_verify);
if (r != 0) goto out;
}
if (OP_WRITE == operation && cleanup) {
r = fetch_bench_metadata(run_name_meta, &op_size, &object_size,
&num_ops, &num_objects, &prev_pid);
if (r < 0) {
if (r == -ENOENT)
cerr << "Should never happen: bench metadata missing for current run!" << std::endl;
goto out;
}
data.start_time = mono_clock::now();
out(cout) << "Cleaning up (deleting benchmark objects)" << std::endl;
r = clean_up(num_objects, prev_pid, concurrentios);
if (r != 0) goto out;
timePassed = mono_clock::now() - data.start_time;
out(cout) << "Clean up completed and total clean up time :" << timePassed.count() << std::endl;
// lastrun file
r = sync_remove(run_name_meta);
if (r != 0) goto out;
}
out:
if (formatter) {
formatter->close_section(); // bench
formatter->flush(*outstream);
*outstream << std::endl;
}
delete[] contentsChars;
return r;
}
struct lock_cond {
explicit lock_cond(ceph::mutex *_lock) : lock(_lock) {}
ceph::mutex *lock;
ceph::condition_variable cond;
};
void _aio_cb(void *cb, void *arg) {
struct lock_cond *lc = (struct lock_cond *)arg;
lc->lock->lock();
lc->cond.notify_all();
lc->lock->unlock();
}
int ObjBencher::fetch_bench_metadata(const std::string& metadata_file,
uint64_t *op_size, uint64_t* object_size,
int* num_ops, int* num_objects, int* prevPid) {
int r = 0;
bufferlist object_data;
r = sync_read(metadata_file, object_data,
sizeof(int) * 2 + sizeof(size_t) * 2);
if (r <= 0) {
// treat an empty file as a file that does not exist
if (r == 0) {
r = -ENOENT;
}
return r;
}
auto p = object_data.cbegin();
decode(*object_size, p);
decode(*num_ops, p);
decode(*prevPid, p);
if (!p.end()) {
decode(*op_size, p);
} else {
*op_size = *object_size;
}
unsigned ops_per_object = 1;
// make sure *op_size value is reasonable
if (*op_size > 0 && *object_size > *op_size) {
ops_per_object = *object_size / *op_size;
}
*num_objects = (*num_ops + ops_per_object - 1) / ops_per_object;
return 0;
}
int ObjBencher::write_bench(int secondsToRun,
int concurrentios, const string& run_name_meta,
unsigned max_objects, int prev_pid) {
if (concurrentios <= 0)
return -EINVAL;
if (!formatter) {
out(cout) << "Maintaining " << concurrentios << " concurrent writes of "
<< data.op_size << " bytes to objects of size "
<< data.object_size << " for up to "
<< secondsToRun << " seconds or "
<< max_objects << " objects"
<< std::endl;
} else {
formatter->dump_format("concurrent_ios", "%d", concurrentios);
formatter->dump_format("object_size", "%d", data.object_size);
formatter->dump_format("op_size", "%d", data.op_size);
formatter->dump_format("seconds_to_run", "%d", secondsToRun);
formatter->dump_format("max_objects", "%d", max_objects);
}
bufferlist* newContents = 0;
std::string prefix = prev_pid ? generate_object_prefix(prev_pid) : generate_object_prefix();
if (!formatter)
out(cout) << "Object prefix: " << prefix << std::endl;
else
formatter->dump_string("object_prefix", prefix);
std::vector<string> name(concurrentios);
std::string newName;
unique_ptr<bufferlist> contents[concurrentios];
int r = 0;
bufferlist b_write;
lock_cond lc(&lock);
double total_latency = 0;
std::vector<mono_time> start_times(concurrentios);
mono_time stopTime;
std::chrono::duration<double> timePassed;
unsigned writes_per_object = 1;
if (data.op_size)
writes_per_object = data.object_size / data.op_size;
r = completions_init(concurrentios);
//set up writes so I can start them together
for (int i = 0; i<concurrentios; ++i) {
name[i] = generate_object_name_fast(i / writes_per_object);
contents[i] = std::make_unique<bufferlist>();
snprintf(data.object_contents, data.op_size, "I'm the %16dth op!", i);
contents[i]->append(data.object_contents, data.op_size);
}
pthread_t print_thread;
pthread_create(&print_thread, NULL, ObjBencher::status_printer, (void *)this);
ceph_pthread_setname(print_thread, "write_stat");
std::unique_lock locker{lock};
data.finished = 0;
data.start_time = mono_clock::now();
locker.unlock();
for (int i = 0; i<concurrentios; ++i) {
start_times[i] = mono_clock::now();
r = create_completion(i, _aio_cb, (void *)&lc);
if (r < 0)
goto ERR;
r = aio_write(name[i], i, *contents[i], data.op_size,
data.op_size * (i % writes_per_object));
if (r < 0) {
goto ERR;
}
locker.lock();
++data.started;
++data.in_flight;
locker.unlock();
}
//keep on adding new writes as old ones complete until we've passed minimum time
int slot;
//don't need locking for reads because other thread doesn't write
stopTime = data.start_time + std::chrono::seconds(secondsToRun);
slot = 0;
locker.lock();
while (data.finished < data.started) {
bool found = false;
while (1) {
int old_slot = slot;
do {
if (completion_is_done(slot)) {
found = true;
break;
}
slot++;
if (slot == concurrentios) {
slot = 0;
}
} while (slot != old_slot);
if (found)
break;
lc.cond.wait(locker);
}
locker.unlock();
completion_wait(slot);
locker.lock();
r = completion_ret(slot);
if (r != 0) {
locker.unlock();
goto ERR;
}
data.cur_latency = mono_clock::now() - start_times[slot];
total_latency += data.cur_latency.count();
if( data.cur_latency.count() > data.max_latency)
data.max_latency = data.cur_latency.count();
if (data.cur_latency.count() < data.min_latency)
data.min_latency = data.cur_latency.count();
++data.finished;
double delta = data.cur_latency.count() - data.avg_latency;
data.avg_latency = total_latency / data.finished;
data.latency_diff_sum += delta * (data.cur_latency.count() - data.avg_latency);
--data.in_flight;
locker.unlock();
release_completion(slot);
if (!secondsToRun || mono_clock::now() >= stopTime) {
locker.lock();
continue;
}
if (data.op_size && max_objects &&
data.started >=
(int)((data.object_size * max_objects + data.op_size - 1) /
data.op_size)) {
locker.lock();
continue;
}
//write new stuff to backend
//create new contents and name on the heap, and fill them
newName = generate_object_name_fast(data.started / writes_per_object);
newContents = contents[slot].get();
snprintf(newContents->c_str(), data.op_size, "I'm the %16dth op!", data.started);
// we wrote to buffer, going around internal crc cache, so invalidate it now.
newContents->invalidate_crc();
start_times[slot] = mono_clock::now();
r = create_completion(slot, _aio_cb, &lc);
if (r < 0)
goto ERR;
r = aio_write(newName, slot, *newContents, data.op_size,
data.op_size * (data.started % writes_per_object));
if (r < 0) {
goto ERR;
}
name[slot] = newName;
locker.lock();
++data.started;
++data.in_flight;
}
locker.unlock();
timePassed = mono_clock::now() - data.start_time;
locker.lock();
data.done = true;
locker.unlock();
pthread_join(print_thread, NULL);
double bandwidth;
bandwidth = ((double)data.finished)*((double)data.op_size) /
timePassed.count();
bandwidth = bandwidth/(1024*1024); // we want it in MB/sec
double bandwidth_stddev;
double iops_stddev;
double latency_stddev;
if (data.idata.bandwidth_cycles > 1) {
bandwidth_stddev = std::sqrt(data.idata.bandwidth_diff_sum / (data.idata.bandwidth_cycles - 1));
} else {
bandwidth_stddev = 0;
}
if (data.idata.iops_cycles > 1) {
iops_stddev = std::sqrt(data.idata.iops_diff_sum / (data.idata.iops_cycles - 1));
} else {
iops_stddev = 0;
}
if (data.finished > 1) {
latency_stddev = std::sqrt(data.latency_diff_sum / (data.finished - 1));
} else {
latency_stddev = 0;
}
if (!formatter) {
out(cout) << "Total time run: " << timePassed.count() << std::endl
<< "Total writes made: " << data.finished << std::endl
<< "Write size: " << data.op_size << std::endl
<< "Object size: " << data.object_size << std::endl
<< "Bandwidth (MB/sec): " << setprecision(6) << bandwidth << std::endl
<< "Stddev Bandwidth: " << bandwidth_stddev << std::endl
<< "Max bandwidth (MB/sec): " << data.idata.max_bandwidth << std::endl
<< "Min bandwidth (MB/sec): " << data.idata.min_bandwidth << std::endl
<< "Average IOPS: " << (int)(data.finished/timePassed.count()) << std::endl
<< "Stddev IOPS: " << iops_stddev << std::endl
<< "Max IOPS: " << data.idata.max_iops << std::endl
<< "Min IOPS: " << data.idata.min_iops << std::endl
<< "Average Latency(s): " << data.avg_latency << std::endl
<< "Stddev Latency(s): " << latency_stddev << std::endl
<< "Max latency(s): " << data.max_latency << std::endl
<< "Min latency(s): " << data.min_latency << std::endl;
} else {
formatter->dump_format("total_time_run", "%f", timePassed.count());
formatter->dump_format("total_writes_made", "%d", data.finished);
formatter->dump_format("write_size", "%d", data.op_size);
formatter->dump_format("object_size", "%d", data.object_size);
formatter->dump_format("bandwidth", "%f", bandwidth);
formatter->dump_format("stddev_bandwidth", "%f", bandwidth_stddev);
formatter->dump_format("max_bandwidth", "%f", data.idata.max_bandwidth);
formatter->dump_format("min_bandwidth", "%f", data.idata.min_bandwidth);
formatter->dump_format("average_iops", "%d", (int)(data.finished/timePassed.count()));
formatter->dump_format("stddev_iops", "%d", iops_stddev);
formatter->dump_format("max_iops", "%d", data.idata.max_iops);
formatter->dump_format("min_iops", "%d", data.idata.min_iops);
formatter->dump_format("average_latency", "%f", data.avg_latency);
formatter->dump_format("stddev_latency", "%f", latency_stddev);
formatter->dump_format("max_latency", "%f", data.max_latency);
formatter->dump_format("min_latency", "%f", data.min_latency);
}
//write object size/number data for read benchmarks
encode(data.object_size, b_write);
encode(data.finished, b_write);
encode(prev_pid ? prev_pid : getpid(), b_write);
encode(data.op_size, b_write);
// persist meta-data for further cleanup or read
sync_write(run_name_meta, b_write, sizeof(int)*3);
completions_done();
return 0;
ERR:
locker.lock();
data.done = 1;
locker.unlock();
pthread_join(print_thread, NULL);
return r;
}
int ObjBencher::seq_read_bench(
int seconds_to_run, int num_ops, int num_objects,
int concurrentios, int pid, bool no_verify) {
lock_cond lc(&lock);
if (concurrentios <= 0)
return -EINVAL;
std::vector<string> name(concurrentios);
std::string newName;
unique_ptr<bufferlist> contents[concurrentios];
int index[concurrentios];
int errors = 0;
double total_latency = 0;
int r = 0;
std::vector<mono_time> start_times(concurrentios);
mono_clock::duration time_to_run = std::chrono::seconds(seconds_to_run);
std::chrono::duration<double> timePassed;
sanitize_object_contents(&data, data.op_size); //clean it up once; subsequent
//changes will be safe because string length should remain the same
unsigned reads_per_object = 1;
if (data.op_size)
reads_per_object = data.object_size / data.op_size;
r = completions_init(concurrentios);
if (r < 0)
return r;
//set up initial reads
for (int i = 0; i < concurrentios; ++i) {
name[i] = generate_object_name_fast(i / reads_per_object, pid);
contents[i] = std::make_unique<bufferlist>();
}
std::unique_lock locker{lock};
data.finished = 0;
data.start_time = mono_clock::now();
locker.unlock();
pthread_t print_thread;
pthread_create(&print_thread, NULL, status_printer, (void *)this);
ceph_pthread_setname(print_thread, "seq_read_stat");
mono_time finish_time = data.start_time + time_to_run;
//start initial reads
for (int i = 0; i < concurrentios; ++i) {
index[i] = i;
start_times[i] = mono_clock::now();
create_completion(i, _aio_cb, (void *)&lc);
r = aio_read(name[i], i, contents[i].get(), data.op_size,
data.op_size * (i % reads_per_object));
if (r < 0) {
cerr << "r = " << r << std::endl;
goto ERR;
}
locker.lock();
++data.started;
++data.in_flight;
locker.unlock();
}
//keep on adding new reads as old ones complete
int slot;
bufferlist *cur_contents;
slot = 0;
while (data.finished < data.started) {
locker.lock();
int old_slot = slot;
bool found = false;
while (1) {
do {
if (completion_is_done(slot)) {
found = true;
break;
}
slot++;
if (slot == concurrentios) {
slot = 0;
}
} while (slot != old_slot);
if (found) {
break;
}
lc.cond.wait(locker);
}
// calculate latency here, so memcmp doesn't inflate it
data.cur_latency = mono_clock::now() - start_times[slot];
cur_contents = contents[slot].get();
int current_index = index[slot];
// invalidate internal crc cache
cur_contents->invalidate_crc();
if (!no_verify) {
snprintf(data.object_contents, data.op_size, "I'm the %16dth op!", current_index);
if ( (cur_contents->length() != data.op_size) ||
(memcmp(data.object_contents, cur_contents->c_str(), data.op_size) != 0) ) {
cerr << name[slot] << " is not correct!" << std::endl;
++errors;
}
}
bool start_new_read = (seconds_to_run && mono_clock::now() < finish_time) &&
num_ops > data.started;
if (start_new_read) {
newName = generate_object_name_fast(data.started / reads_per_object, pid);
index[slot] = data.started;
}
locker.unlock();
completion_wait(slot);
locker.lock();
r = completion_ret(slot);
if (r < 0) {
cerr << "read got " << r << std::endl;
locker.unlock();
goto ERR;
}
total_latency += data.cur_latency.count();
if (data.cur_latency.count() > data.max_latency)
data.max_latency = data.cur_latency.count();
if (data.cur_latency.count() < data.min_latency)
data.min_latency = data.cur_latency.count();
++data.finished;
data.avg_latency = total_latency / data.finished;
--data.in_flight;
locker.unlock();
release_completion(slot);
if (!start_new_read)
continue;
//start new read and check data if requested
start_times[slot] = mono_clock::now();
create_completion(slot, _aio_cb, (void *)&lc);
r = aio_read(newName, slot, contents[slot].get(), data.op_size,
data.op_size * (data.started % reads_per_object));
if (r < 0) {
goto ERR;
}
locker.lock();
++data.started;
++data.in_flight;
locker.unlock();
name[slot] = newName;
}
timePassed = mono_clock::now() - data.start_time;
locker.lock();
data.done = true;
locker.unlock();
pthread_join(print_thread, NULL);
double bandwidth;
bandwidth = ((double)data.finished)*((double)data.op_size)/timePassed.count();
bandwidth = bandwidth/(1024*1024); // we want it in MB/sec
double iops_stddev;
if (data.idata.iops_cycles > 1) {
iops_stddev = std::sqrt(data.idata.iops_diff_sum / (data.idata.iops_cycles - 1));
} else {
iops_stddev = 0;
}
if (!formatter) {
out(cout) << "Total time run: " << timePassed.count() << std::endl
<< "Total reads made: " << data.finished << std::endl
<< "Read size: " << data.op_size << std::endl
<< "Object size: " << data.object_size << std::endl
<< "Bandwidth (MB/sec): " << setprecision(6) << bandwidth << std::endl
<< "Average IOPS: " << (int)(data.finished/timePassed.count()) << std::endl
<< "Stddev IOPS: " << iops_stddev << std::endl
<< "Max IOPS: " << data.idata.max_iops << std::endl
<< "Min IOPS: " << data.idata.min_iops << std::endl
<< "Average Latency(s): " << data.avg_latency << std::endl
<< "Max latency(s): " << data.max_latency << std::endl
<< "Min latency(s): " << data.min_latency << std::endl;
} else {
formatter->dump_format("total_time_run", "%f", timePassed.count());
formatter->dump_format("total_reads_made", "%d", data.finished);
formatter->dump_format("read_size", "%d", data.op_size);
formatter->dump_format("object_size", "%d", data.object_size);
formatter->dump_format("bandwidth", "%f", bandwidth);
formatter->dump_format("average_iops", "%d", (int)(data.finished/timePassed.count()));
formatter->dump_format("stddev_iops", "%f", iops_stddev);
formatter->dump_format("max_iops", "%d", data.idata.max_iops);
formatter->dump_format("min_iops", "%d", data.idata.min_iops);
formatter->dump_format("average_latency", "%f", data.avg_latency);
formatter->dump_format("max_latency", "%f", data.max_latency);
formatter->dump_format("min_latency", "%f", data.min_latency);
}
completions_done();
return (errors > 0 ? -EIO : 0);
ERR:
locker.lock();
data.done = 1;
locker.unlock();
pthread_join(print_thread, NULL);
return r;
}
int ObjBencher::rand_read_bench(
int seconds_to_run, int num_ops, int num_objects,
int concurrentios, int pid, bool no_verify) {
lock_cond lc(&lock);
if (concurrentios <= 0)
return -EINVAL;
std::vector<string> name(concurrentios);
std::string newName;
unique_ptr<bufferlist> contents[concurrentios];
int index[concurrentios];
int errors = 0;
int r = 0;
double total_latency = 0;
std::vector<mono_time> start_times(concurrentios);
mono_clock::duration time_to_run = std::chrono::seconds(seconds_to_run);
std::chrono::duration<double> timePassed;
sanitize_object_contents(&data, data.op_size); //clean it up once; subsequent
//changes will be safe because string length should remain the same
unsigned reads_per_object = 1;
if (data.op_size)
reads_per_object = data.object_size / data.op_size;
srand (time(NULL));
r = completions_init(concurrentios);
if (r < 0)
return r;
//set up initial reads
for (int i = 0; i < concurrentios; ++i) {
name[i] = generate_object_name_fast(i / reads_per_object, pid);
contents[i] = std::make_unique<bufferlist>();
}
unique_lock locker{lock};
data.finished = 0;
data.start_time = mono_clock::now();
locker.unlock();
pthread_t print_thread;
pthread_create(&print_thread, NULL, status_printer, (void *)this);
ceph_pthread_setname(print_thread, "rand_read_stat");
mono_time finish_time = data.start_time + time_to_run;
//start initial reads
for (int i = 0; i < concurrentios; ++i) {
index[i] = i;
start_times[i] = mono_clock::now();
create_completion(i, _aio_cb, (void *)&lc);
r = aio_read(name[i], i, contents[i].get(), data.op_size,
data.op_size * (i % reads_per_object));
if (r < 0) {
cerr << "r = " << r << std::endl;
goto ERR;
}
locker.lock();
++data.started;
++data.in_flight;
locker.unlock();
}
//keep on adding new reads as old ones complete
int slot;
bufferlist *cur_contents;
int rand_id;
slot = 0;
while (data.finished < data.started) {
locker.lock();
int old_slot = slot;
bool found = false;
while (1) {
do {
if (completion_is_done(slot)) {
found = true;
break;
}
slot++;
if (slot == concurrentios) {
slot = 0;
}
} while (slot != old_slot);
if (found) {
break;
}
lc.cond.wait(locker);
}
// calculate latency here, so memcmp doesn't inflate it
data.cur_latency = mono_clock::now() - start_times[slot];
locker.unlock();
int current_index = index[slot];
cur_contents = contents[slot].get();
completion_wait(slot);
locker.lock();
r = completion_ret(slot);
if (r < 0) {
cerr << "read got " << r << std::endl;
locker.unlock();
goto ERR;
}
total_latency += data.cur_latency.count();
if (data.cur_latency.count() > data.max_latency)
data.max_latency = data.cur_latency.count();
if (data.cur_latency.count() < data.min_latency)
data.min_latency = data.cur_latency.count();
++data.finished;
data.avg_latency = total_latency / data.finished;
--data.in_flight;
if (!no_verify) {
snprintf(data.object_contents, data.op_size, "I'm the %16dth op!", current_index);
if ((cur_contents->length() != data.op_size) ||
(memcmp(data.object_contents, cur_contents->c_str(), data.op_size) != 0)) {
cerr << name[slot] << " is not correct!" << std::endl;
++errors;
}
}
locker.unlock();
release_completion(slot);
if (!seconds_to_run || mono_clock::now() >= finish_time)
continue;
//start new read and check data if requested
rand_id = rand() % num_ops;
newName = generate_object_name_fast(rand_id / reads_per_object, pid);
index[slot] = rand_id;
// invalidate internal crc cache
cur_contents->invalidate_crc();
start_times[slot] = mono_clock::now();
create_completion(slot, _aio_cb, (void *)&lc);
r = aio_read(newName, slot, contents[slot].get(), data.op_size,
data.op_size * (rand_id % reads_per_object));
if (r < 0) {
goto ERR;
}
locker.lock();
++data.started;
++data.in_flight;
locker.unlock();
name[slot] = newName;
}
timePassed = mono_clock::now() - data.start_time;
locker.lock();
data.done = true;
locker.unlock();
pthread_join(print_thread, NULL);
double bandwidth;
bandwidth = ((double)data.finished)*((double)data.op_size)/timePassed.count();
bandwidth = bandwidth/(1024*1024); // we want it in MB/sec
double iops_stddev;
if (data.idata.iops_cycles > 1) {
iops_stddev = std::sqrt(data.idata.iops_diff_sum / (data.idata.iops_cycles - 1));
} else {
iops_stddev = 0;
}
if (!formatter) {
out(cout) << "Total time run: " << timePassed.count() << std::endl
<< "Total reads made: " << data.finished << std::endl
<< "Read size: " << data.op_size << std::endl
<< "Object size: " << data.object_size << std::endl
<< "Bandwidth (MB/sec): " << setprecision(6) << bandwidth << std::endl
<< "Average IOPS: " << (int)(data.finished/timePassed.count()) << std::endl
<< "Stddev IOPS: " << iops_stddev << std::endl
<< "Max IOPS: " << data.idata.max_iops << std::endl
<< "Min IOPS: " << data.idata.min_iops << std::endl
<< "Average Latency(s): " << data.avg_latency << std::endl
<< "Max latency(s): " << data.max_latency << std::endl
<< "Min latency(s): " << data.min_latency << std::endl;
} else {
formatter->dump_format("total_time_run", "%f", timePassed.count());
formatter->dump_format("total_reads_made", "%d", data.finished);
formatter->dump_format("read_size", "%d", data.op_size);
formatter->dump_format("object_size", "%d", data.object_size);
formatter->dump_format("bandwidth", "%f", bandwidth);
formatter->dump_format("average_iops", "%d", (int)(data.finished/timePassed.count()));
formatter->dump_format("stddev_iops", "%f", iops_stddev);
formatter->dump_format("max_iops", "%d", data.idata.max_iops);
formatter->dump_format("min_iops", "%d", data.idata.min_iops);
formatter->dump_format("average_latency", "%f", data.avg_latency);
formatter->dump_format("max_latency", "%f", data.max_latency);
formatter->dump_format("min_latency", "%f", data.min_latency);
}
completions_done();
return (errors > 0 ? -EIO : 0);
ERR:
locker.lock();
data.done = 1;
locker.unlock();
pthread_join(print_thread, NULL);
return r;
}
int ObjBencher::clean_up(const std::string& orig_prefix, int concurrentios, const std::string& run_name) {
int r = 0;
uint64_t op_size, object_size;
int num_ops, num_objects;
int prevPid;
// default meta object if user does not specify one
const std::string run_name_meta = (run_name.empty() ? BENCH_LASTRUN_METADATA : run_name);
const std::string prefix = (orig_prefix.empty() ? generate_object_prefix_nopid() : orig_prefix);
if (prefix.substr(0, BENCH_PREFIX.length()) != BENCH_PREFIX) {
cerr << "Specified --prefix invalid, it must begin with \"" << BENCH_PREFIX << "\"" << std::endl;
return -EINVAL;
}
std::list<Object> unfiltered_objects;
std::set<std::string> meta_namespaces, all_namespaces;
// If caller set all_nspaces this will be searching
// across multiple namespaces.
while (true) {
bool objects_remain = get_objects(&unfiltered_objects, 20);
if (!objects_remain)
break;
std::list<Object>::const_iterator i = unfiltered_objects.begin();
for ( ; i != unfiltered_objects.end(); ++i) {
if (i->first == run_name_meta) {
meta_namespaces.insert(i->second);
}
if (i->first.substr(0, prefix.length()) == prefix) {
all_namespaces.insert(i->second);
}
}
}
std::set<std::string>::const_iterator i = all_namespaces.begin();
for ( ; i != all_namespaces.end(); ++i) {
set_namespace(*i);
// if no metadata file found we should try to do a linear search on the prefix
if (meta_namespaces.find(*i) == meta_namespaces.end()) {
int r = clean_up_slow(prefix, concurrentios);
if (r < 0) {
cerr << "clean_up_slow error r= " << r << std::endl;
return r;
}
continue;
}
r = fetch_bench_metadata(run_name_meta, &op_size, &object_size, &num_ops, &num_objects, &prevPid);
if (r < 0) {
return r;
}
r = clean_up(num_objects, prevPid, concurrentios);
if (r != 0) return r;
r = sync_remove(run_name_meta);
if (r != 0) return r;
}
return 0;
}
int ObjBencher::clean_up(int num_objects, int prevPid, int concurrentios) {
lock_cond lc(&lock);
if (concurrentios <= 0)
return -EINVAL;
std::vector<string> name(concurrentios);
std::string newName;
int r = 0;
int slot = 0;
unique_lock locker{lock};
data.done = false;
data.in_flight = 0;
data.started = 0;
data.finished = 0;
locker.unlock();
// don't start more completions than files
if (num_objects == 0) {
return 0;
} else if (num_objects < concurrentios) {
concurrentios = num_objects;
}
r = completions_init(concurrentios);
if (r < 0)
return r;
//set up initial removes
for (int i = 0; i < concurrentios; ++i) {
name[i] = generate_object_name_fast(i, prevPid);
}
//start initial removes
for (int i = 0; i < concurrentios; ++i) {
create_completion(i, _aio_cb, (void *)&lc);
r = aio_remove(name[i], i);
if (r < 0) { //naughty, doesn't clean up heap
cerr << "r = " << r << std::endl;
goto ERR;
}
locker.lock();
++data.started;
++data.in_flight;
locker.unlock();
}
//keep on adding new removes as old ones complete
while (data.finished < data.started) {
locker.lock();
int old_slot = slot;
bool found = false;
while (1) {
do {
if (completion_is_done(slot)) {
found = true;
break;
}
slot++;
if (slot == concurrentios) {
slot = 0;
}
} while (slot != old_slot);
if (found) {
break;
}
lc.cond.wait(locker);
}
locker.unlock();
completion_wait(slot);
locker.lock();
r = completion_ret(slot);
if (r != 0 && r != -ENOENT) { // file does not exist
cerr << "remove got " << r << std::endl;
locker.unlock();
goto ERR;
}
++data.finished;
--data.in_flight;
locker.unlock();
release_completion(slot);
if (data.started >= num_objects)
continue;
//start new remove and check data if requested
newName = generate_object_name_fast(data.started, prevPid);
create_completion(slot, _aio_cb, (void *)&lc);
r = aio_remove(newName, slot);
if (r < 0) {
goto ERR;
}
locker.lock();
++data.started;
++data.in_flight;
locker.unlock();
name[slot] = newName;
}
locker.lock();
data.done = true;
locker.unlock();
completions_done();
out(cout) << "Removed " << data.finished << " object" << (data.finished != 1 ? "s" : "") << std::endl;
return 0;
ERR:
locker.lock();
data.done = 1;
locker.unlock();
return r;
}
/**
* Return objects from the datastore which match a prefix.
*
* Clears the list and populates it with any objects which match the
* prefix. The list is guaranteed to have at least one item when the
* function returns true.
*
* @param prefix the prefix to match against
* @param objects [out] return list of objects
* @returns true if there are any objects in the store which match
* the prefix, false if there are no more
*/
bool ObjBencher::more_objects_matching_prefix(const std::string& prefix, std::list<Object>* objects) {
std::list<Object> unfiltered_objects;
objects->clear();
while (objects->empty()) {
bool objects_remain = get_objects(&unfiltered_objects, 20);
if (!objects_remain)
return false;
std::list<Object>::const_iterator i = unfiltered_objects.begin();
for ( ; i != unfiltered_objects.end(); ++i) {
if (i->first.substr(0, prefix.length()) == prefix) {
objects->push_back(*i);
}
}
}
return true;
}
int ObjBencher::clean_up_slow(const std::string& prefix, int concurrentios) {
lock_cond lc(&lock);
if (concurrentios <= 0)
return -EINVAL;
std::vector<Object> name(concurrentios);
Object newName;
int r = 0;
int slot = 0;
std::list<Object> objects;
bool objects_remain = true;
std::unique_lock locker{lock};
data.done = false;
data.in_flight = 0;
data.started = 0;
data.finished = 0;
locker.unlock();
out(cout) << "Warning: using slow linear search" << std::endl;
r = completions_init(concurrentios);
if (r < 0)
return r;
//set up initial removes
for (int i = 0; i < concurrentios; ++i) {
if (objects.empty()) {
// if there are fewer objects than concurrent ios, don't generate extras
bool objects_found = more_objects_matching_prefix(prefix, &objects);
if (!objects_found) {
concurrentios = i;
objects_remain = false;
break;
}
}
name[i] = objects.front();
objects.pop_front();
}
//start initial removes
for (int i = 0; i < concurrentios; ++i) {
create_completion(i, _aio_cb, (void *)&lc);
set_namespace(name[i].second);
r = aio_remove(name[i].first, i);
if (r < 0) { //naughty, doesn't clean up heap
cerr << "r = " << r << std::endl;
goto ERR;
}
locker.lock();
++data.started;
++data.in_flight;
locker.unlock();
}
//keep on adding new removes as old ones complete
while (objects_remain) {
locker.lock();
int old_slot = slot;
bool found = false;
while (1) {
do {
if (completion_is_done(slot)) {
found = true;
break;
}
slot++;
if (slot == concurrentios) {
slot = 0;
}
} while (slot != old_slot);
if (found) {
break;
}
lc.cond.wait(locker);
}
locker.unlock();
// get more objects if necessary
if (objects.empty()) {
objects_remain = more_objects_matching_prefix(prefix, &objects);
// quit if there are no more
if (!objects_remain) {
break;
}
}
// get the next object
newName = objects.front();
objects.pop_front();
completion_wait(slot);
locker.lock();
r = completion_ret(slot);
if (r != 0 && r != -ENOENT) { // file does not exist
cerr << "remove got " << r << std::endl;
locker.unlock();
goto ERR;
}
++data.finished;
--data.in_flight;
locker.unlock();
release_completion(slot);
//start new remove and check data if requested
create_completion(slot, _aio_cb, (void *)&lc);
set_namespace(newName.second);
r = aio_remove(newName.first, slot);
if (r < 0) {
goto ERR;
}
locker.lock();
++data.started;
++data.in_flight;
locker.unlock();
name[slot] = newName;
}
//wait for final removes to complete
while (data.finished < data.started) {
slot = data.finished % concurrentios;
completion_wait(slot);
locker.lock();
r = completion_ret(slot);
if (r != 0 && r != -ENOENT) { // file does not exist
cerr << "remove got " << r << std::endl;
locker.unlock();
goto ERR;
}
++data.finished;
--data.in_flight;
release_completion(slot);
locker.unlock();
}
locker.lock();
data.done = true;
locker.unlock();
completions_done();
out(cout) << "Removed " << data.finished << " object" << (data.finished != 1 ? "s" : "") << std::endl;
return 0;
ERR:
locker.lock();
data.done = 1;
locker.unlock();
return -EIO;
}
| 43,800 | 29.396253 | 106 | cc |
null | ceph-main/src/common/obj_bencher.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2009 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_OBJ_BENCHER_H
#define CEPH_OBJ_BENCHER_H
#include "common/ceph_context.h"
#include "common/Formatter.h"
#include "ceph_time.h"
#include <cfloat>
using ceph::mono_clock;
struct bench_interval_data {
double min_bandwidth = DBL_MAX;
double max_bandwidth = 0;
double avg_bandwidth = 0;
int bandwidth_cycles = 0;
double bandwidth_diff_sum = 0;
int min_iops = INT_MAX;
int max_iops = 0;
double avg_iops = 0;
int iops_cycles = 0;
double iops_diff_sum = 0;
};
struct bench_data {
bool done; //is the benchmark is done
uint64_t object_size; //the size of the objects
uint64_t op_size; // the size of the read/write ops
bool hints;
// same as object_size for write tests
int in_flight; //number of reads/writes being waited on
int started;
int finished;
double min_latency;
double max_latency;
double avg_latency;
struct bench_interval_data idata; // data that is updated by time intervals and not by events
double latency_diff_sum;
std::chrono::duration<double> cur_latency; //latency of last completed transaction - in seconds by default
mono_time start_time; //start time for benchmark - use the monotonic clock as we'll measure the passage of time
char *object_contents; //pointer to the contents written to each object
};
const int OP_WRITE = 1;
const int OP_SEQ_READ = 2;
const int OP_RAND_READ = 3;
// Object is composed of <oid,namespace>
typedef std::pair<std::string, std::string> Object;
class ObjBencher {
bool show_time;
Formatter *formatter = NULL;
std::ostream *outstream = NULL;
public:
CephContext *cct;
protected:
ceph::mutex lock = ceph::make_mutex("ObjBencher::lock");
static void *status_printer(void *bencher);
struct bench_data data;
int fetch_bench_metadata(const std::string& metadata_file, uint64_t* op_size,
uint64_t* object_size, int* num_ops, int* num_objects, int* prev_pid);
int write_bench(int secondsToRun, int concurrentios, const std::string& run_name_meta, unsigned max_objects, int prev_pid);
int seq_read_bench(int secondsToRun, int num_ops, int num_objects, int concurrentios, int writePid, bool no_verify=false);
int rand_read_bench(int secondsToRun, int num_ops, int num_objects, int concurrentios, int writePid, bool no_verify=false);
int clean_up(int num_objects, int prevPid, int concurrentios);
bool more_objects_matching_prefix(const std::string& prefix, std::list<Object>* name);
virtual int completions_init(int concurrentios) = 0;
virtual void completions_done() = 0;
virtual int create_completion(int i, void (*cb)(void *, void*), void *arg) = 0;
virtual void release_completion(int slot) = 0;
virtual bool completion_is_done(int slot) = 0;
virtual int completion_wait(int slot) = 0;
virtual int completion_ret(int slot) = 0;
virtual int aio_read(const std::string& oid, int slot, bufferlist *pbl, size_t len, size_t offset) = 0;
virtual int aio_write(const std::string& oid, int slot, bufferlist& bl, size_t len, size_t offset) = 0;
virtual int aio_remove(const std::string& oid, int slot) = 0;
virtual int sync_read(const std::string& oid, bufferlist& bl, size_t len) = 0;
virtual int sync_write(const std::string& oid, bufferlist& bl, size_t len) = 0;
virtual int sync_remove(const std::string& oid) = 0;
virtual bool get_objects(std::list< std::pair<std::string, std::string> >* objects, int num) = 0;
virtual void set_namespace(const std::string&) {}
std::ostream& out(std::ostream& os);
std::ostream& out(std::ostream& os, utime_t& t);
public:
explicit ObjBencher(CephContext *cct_) : show_time(false), cct(cct_), data() {}
virtual ~ObjBencher() {}
int aio_bench(
int operation, int secondsToRun,
int concurrentios, uint64_t op_size, uint64_t object_size, unsigned max_objects,
bool cleanup, bool hints, const std::string& run_name, bool reuse_bench, bool no_verify=false);
int clean_up(const std::string& prefix, int concurrentios, const std::string& run_name);
void set_show_time(bool dt) {
show_time = dt;
}
void set_formatter(Formatter *f) {
formatter = f;
}
void set_outstream(std::ostream& os) {
outstream = &os;
}
int clean_up_slow(const std::string& prefix, int concurrentios);
};
#endif
| 4,670 | 34.386364 | 125 | h |
null | ceph-main/src/common/openssl_opts_handler.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) 2020 Huawei Technologies Co., Ltd.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
*/
#include "openssl_opts_handler.h"
#include <openssl/bio.h>
#include <openssl/conf.h>
#include <openssl/engine.h>
#include <mutex>
#include <vector>
#include <algorithm>
#include "common/debug.h"
#include "global/global_context.h"
#include "include/str_list.h"
#include "include/scope_guard.h"
using std::string;
using std::ostream;
using std::vector;
// -----------------------------------------------------------------------------
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_common
#undef dout_prefix
#define dout_prefix _prefix(_dout)
static ostream &_prefix(std::ostream *_dout)
{
return *_dout << "OpenSSLOptsHandler: ";
}
// -----------------------------------------------------------------------------
string construct_engine_conf(const string &opts)
{
const string conf_header = "openssl_conf=openssl_def\n[openssl_def]\n";
const string engine_header = "engines=engine_section\n[engine_section]\n";
string engine_id, engine_statement, engine_detail;
const string id_prefix = "engine";
const string suffix = "_section";
const char delimiter = '\n';
int index = 1;
vector<string> confs = get_str_vec(opts, ":");
for (auto conf : confs) {
// Construct engine section statement like "engine1=engine1_section"
engine_id = id_prefix + std::to_string(index++);
engine_statement += engine_id + "=" + engine_id + suffix + delimiter;
// Adapt to OpenSSL parser
// Replace ',' with '\n' and add section in front
std::replace(conf.begin(), conf.end(), ',', delimiter);
engine_detail += "[" + engine_id + suffix + "]" + delimiter;
engine_detail += conf + delimiter;
}
return conf_header + engine_header + engine_statement + engine_detail;
}
string get_openssl_error()
{
BIO *bio = BIO_new(BIO_s_mem());
if (bio == nullptr) {
return "failed to create BIO for more error printing";
}
ERR_print_errors(bio);
char* buf;
size_t len = BIO_get_mem_data(bio, &buf);
string ret(buf, len);
BIO_free(bio);
return ret;
}
void log_error(const string &err)
{
derr << "Intended OpenSSL engine acceleration failed.\n"
<< "set by openssl_engine_opts = "
<< g_ceph_context->_conf->openssl_engine_opts
<< "\ndetail error information:\n" << err << dendl;
}
void load_module(const string &engine_conf)
{
BIO *mem = BIO_new_mem_buf(engine_conf.c_str(), engine_conf.size());
if (mem == nullptr) {
log_error("failed to new BIO memory");
return;
}
auto sg_mem = make_scope_guard([&mem] { BIO_free(mem); });
CONF *conf = NCONF_new(nullptr);
if (conf == nullptr) {
log_error("failed to new OpenSSL CONF");
return;
}
auto sg_conf = make_scope_guard([&conf] { NCONF_free(conf); });
if (NCONF_load_bio(conf, mem, nullptr) <= 0) {
log_error("failed to load CONF from BIO:\n" + get_openssl_error());
return;
}
OPENSSL_load_builtin_modules();
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
ENGINE_load_builtin_engines();
#pragma clang diagnostic pop
#pragma GCC diagnostic pop
if (CONF_modules_load(
conf, nullptr,
CONF_MFLAGS_DEFAULT_SECTION | CONF_MFLAGS_IGNORE_MISSING_FILE) <= 0) {
log_error("failed to load modules from CONF:\n" + get_openssl_error());
}
}
void init_engine()
{
string opts = g_ceph_context->_conf->openssl_engine_opts;
if (opts.empty()) {
return;
}
string engine_conf = construct_engine_conf(opts);
load_module(engine_conf);
}
void ceph::crypto::init_openssl_engine_once()
{
static std::once_flag flag;
std::call_once(flag, init_engine);
}
| 4,164 | 27.333333 | 80 | cc |
null | ceph-main/src/common/openssl_opts_handler.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (c) 2020 Huawei Technologies Co., Ltd.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
*/
#ifndef CEPH_OPENSSL_OPTS_HANDLER_H
#define CEPH_OPENSSL_OPTS_HANDLER_H
namespace ceph {
namespace crypto {
void init_openssl_engine_once();
}
}
#endif
| 633 | 24.36 | 70 | h |
null | ceph-main/src/common/options.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "acconfig.h"
#include "options.h"
#include "common/Formatter.h"
#include "common/options/build_options.h"
// Helpers for validators
#include "include/stringify.h"
#include "include/common_fwd.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <regex>
// Definitions for enums
#include "common/perf_counters.h"
// rbd feature and io operation validation
#include "librbd/Features.h"
#include "librbd/io/IoOperations.h"
using std::ostream;
using std::ostringstream;
using ceph::Formatter;
using ceph::parse_timespan;
namespace {
class printer {
ostream& out;
public:
explicit printer(ostream& os)
: out(os) {}
template<typename T>
void operator()(const T& v) const {
out << v;
}
void operator()(std::monostate) const {
return;
}
void operator()(bool v) const {
out << (v ? "true" : "false");
}
void operator()(double v) const {
out << std::fixed << v << std::defaultfloat;
}
void operator()(const Option::size_t& v) const {
out << v.value;
}
void operator()(const std::chrono::seconds v) const {
out << v.count();
}
void operator()(const std::chrono::milliseconds v) const {
out << v.count();
}
};
}
ostream& operator<<(ostream& os, const Option::value_t& v) {
printer p{os};
std::visit(p, v);
return os;
}
void Option::dump_value(const char *field_name,
const Option::value_t &v, Formatter *f) const
{
if (v == value_t{}) {
// This should be nil but Formatter doesn't allow it.
f->dump_string(field_name, "");
return;
}
switch (type) {
case TYPE_INT:
f->dump_int(field_name, std::get<int64_t>(v)); break;
case TYPE_UINT:
f->dump_unsigned(field_name, std::get<uint64_t>(v)); break;
case TYPE_STR:
f->dump_string(field_name, std::get<std::string>(v)); break;
case TYPE_FLOAT:
f->dump_float(field_name, std::get<double>(v)); break;
case TYPE_BOOL:
f->dump_bool(field_name, std::get<bool>(v)); break;
default:
f->dump_stream(field_name) << v; break;
}
}
int Option::pre_validate(std::string *new_value, std::string *err) const
{
if (validator) {
return validator(new_value, err);
} else {
return 0;
}
}
int Option::validate(const Option::value_t &new_value, std::string *err) const
{
// Generic validation: min
if (min != value_t{}) {
if (new_value < min) {
std::ostringstream oss;
oss << "Value '" << new_value << "' is below minimum " << min;
*err = oss.str();
return -EINVAL;
}
}
// Generic validation: max
if (max != value_t{}) {
if (new_value > max) {
std::ostringstream oss;
oss << "Value '" << new_value << "' exceeds maximum " << max;
*err = oss.str();
return -EINVAL;
}
}
// Generic validation: enum
if (!enum_allowed.empty() && type == Option::TYPE_STR) {
auto found = std::find(enum_allowed.begin(), enum_allowed.end(),
std::get<std::string>(new_value));
if (found == enum_allowed.end()) {
std::ostringstream oss;
oss << "'" << new_value << "' is not one of the permitted "
"values: " << joinify(enum_allowed.begin(),
enum_allowed.end(),
std::string(", "));
*err = oss.str();
return -EINVAL;
}
}
return 0;
}
int Option::parse_value(
const std::string& raw_val,
value_t *out,
std::string *error_message,
std::string *normalized_value) const
{
std::string val = raw_val;
int r = pre_validate(&val, error_message);
if (r != 0) {
return r;
}
if (type == Option::TYPE_INT) {
int64_t f = strict_si_cast<int64_t>(val, error_message);
if (!error_message->empty()) {
return -EINVAL;
}
*out = f;
} else if (type == Option::TYPE_UINT) {
uint64_t f = strict_si_cast<uint64_t>(val, error_message);
if (!error_message->empty()) {
return -EINVAL;
}
*out = f;
} else if (type == Option::TYPE_STR) {
*out = val;
} else if (type == Option::TYPE_FLOAT) {
double f = strict_strtod(val.c_str(), error_message);
if (!error_message->empty()) {
return -EINVAL;
} else {
*out = f;
}
} else if (type == Option::TYPE_BOOL) {
bool b = strict_strtob(val.c_str(), error_message);
if (!error_message->empty()) {
return -EINVAL;
} else {
*out = b;
}
} else if (type == Option::TYPE_ADDR) {
entity_addr_t addr;
if (!addr.parse(val)){
return -EINVAL;
}
*out = addr;
} else if (type == Option::TYPE_ADDRVEC) {
entity_addrvec_t addr;
if (!addr.parse(val.c_str())){
return -EINVAL;
}
*out = addr;
} else if (type == Option::TYPE_UUID) {
uuid_d uuid;
if (!uuid.parse(val.c_str())) {
return -EINVAL;
}
*out = uuid;
} else if (type == Option::TYPE_SIZE) {
Option::size_t sz{strict_iecstrtoll(val, error_message)};
if (!error_message->empty()) {
return -EINVAL;
}
*out = sz;
} else if (type == Option::TYPE_SECS) {
try {
*out = parse_timespan(val);
} catch (const std::invalid_argument& e) {
*error_message = e.what();
return -EINVAL;
}
} else if (type == Option::TYPE_MILLISECS) {
try {
*out = std::chrono::milliseconds(std::stoull(val));
} catch (const std::logic_error& e) {
*error_message = e.what();
return -EINVAL;
}
} else {
ceph_abort();
}
r = validate(*out, error_message);
if (r != 0) {
return r;
}
if (normalized_value) {
*normalized_value = to_str(*out);
}
return 0;
}
void Option::dump(Formatter *f) const
{
f->dump_string("name", name);
f->dump_string("type", type_to_str(type));
f->dump_string("level", level_to_str(level));
f->dump_string("desc", desc);
f->dump_string("long_desc", long_desc);
dump_value("default", value, f);
dump_value("daemon_default", daemon_value, f);
f->open_array_section("tags");
for (const auto t : tags) {
f->dump_string("tag", t);
}
f->close_section();
f->open_array_section("services");
for (const auto s : services) {
f->dump_string("service", s);
}
f->close_section();
f->open_array_section("see_also");
for (const auto sa : see_also) {
f->dump_string("see_also", sa);
}
f->close_section();
if (type == TYPE_STR) {
f->open_array_section("enum_values");
for (const auto &ea : enum_allowed) {
f->dump_string("enum_value", ea);
}
f->close_section();
}
dump_value("min", min, f);
dump_value("max", max, f);
f->dump_bool("can_update_at_runtime", can_update_at_runtime());
f->open_array_section("flags");
if (has_flag(FLAG_RUNTIME)) {
f->dump_string("option", "runtime");
}
if (has_flag(FLAG_NO_MON_UPDATE)) {
f->dump_string("option", "no_mon_update");
}
if (has_flag(FLAG_STARTUP)) {
f->dump_string("option", "startup");
}
if (has_flag(FLAG_CLUSTER_CREATE)) {
f->dump_string("option", "cluster_create");
}
if (has_flag(FLAG_CREATE)) {
f->dump_string("option", "create");
}
f->close_section();
}
std::string Option::to_str(const Option::value_t& v)
{
return stringify(v);
}
void Option::print(ostream *out) const
{
*out << name << " - " << desc << "\n";
*out << " (" << type_to_str(type) << ", " << level_to_str(level) << ")\n";
if (daemon_value != value_t{}) {
*out << " Default (non-daemon): " << stringify(value) << "\n";
*out << " Default (daemon): " << stringify(daemon_value) << "\n";
} else {
*out << " Default: " << stringify(value) << "\n";
}
if (!enum_allowed.empty()) {
*out << " Possible values: ";
for (auto& i : enum_allowed) {
*out << " " << stringify(i);
}
*out << "\n";
}
if (min != value_t{}) {
*out << " Minimum: " << stringify(min) << "\n"
<< " Maximum: " << stringify(max) << "\n";
}
*out << " Can update at runtime: "
<< (can_update_at_runtime() ? "true" : "false") << "\n";
if (!services.empty()) {
*out << " Services: " << services << "\n";
}
if (!tags.empty()) {
*out << " Tags: " << tags << "\n";
}
if (!see_also.empty()) {
*out << " See also: " << see_also << "\n";
}
if (long_desc.size()) {
*out << "\n" << long_desc << "\n";
}
}
const std::vector<Option> ceph_options = build_options();
| 8,445 | 23.768328 | 78 | cc |
null | ceph-main/src/common/options.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <chrono>
#include <string>
#include <variant>
#include <vector>
#include "include/str_list.h"
#include "msg/msg_types.h"
#include "include/uuid.h"
struct Option {
enum type_t {
TYPE_UINT = 0,
TYPE_INT = 1,
TYPE_STR = 2,
TYPE_FLOAT = 3,
TYPE_BOOL = 4,
TYPE_ADDR = 5,
TYPE_ADDRVEC = 6,
TYPE_UUID = 7,
TYPE_SIZE = 8,
TYPE_SECS = 9,
TYPE_MILLISECS = 10,
};
static const char *type_to_c_type_str(type_t t) {
switch (t) {
case TYPE_UINT: return "uint64_t";
case TYPE_INT: return "int64_t";
case TYPE_STR: return "std::string";
case TYPE_FLOAT: return "double";
case TYPE_BOOL: return "bool";
case TYPE_ADDR: return "entity_addr_t";
case TYPE_ADDRVEC: return "entity_addrvec_t";
case TYPE_UUID: return "uuid_d";
case TYPE_SIZE: return "uint64_t";
case TYPE_SECS: return "secs";
case TYPE_MILLISECS: return "millisecs";
default: return "unknown";
}
}
static const char *type_to_str(type_t t) {
switch (t) {
case TYPE_UINT: return "uint";
case TYPE_INT: return "int";
case TYPE_STR: return "str";
case TYPE_FLOAT: return "float";
case TYPE_BOOL: return "bool";
case TYPE_ADDR: return "addr";
case TYPE_ADDRVEC: return "addrvec";
case TYPE_UUID: return "uuid";
case TYPE_SIZE: return "size";
case TYPE_SECS: return "secs";
case TYPE_MILLISECS: return "millisecs";
default: return "unknown";
}
}
static int str_to_type(const std::string& s) {
if (s == "uint") {
return TYPE_UINT;
}
if (s == "int") {
return TYPE_INT;
}
if (s == "str") {
return TYPE_STR;
}
if (s == "float") {
return TYPE_FLOAT;
}
if (s == "bool") {
return TYPE_BOOL;
}
if (s == "addr") {
return TYPE_ADDR;
}
if (s == "addrvec") {
return TYPE_ADDRVEC;
}
if (s == "uuid") {
return TYPE_UUID;
}
if (s == "size") {
return TYPE_SIZE;
}
if (s == "secs") {
return TYPE_SECS;
}
if (s == "millisecs") {
return TYPE_MILLISECS;
}
return -1;
}
/**
* Basic: for users, configures some externally visible functional aspect
* Advanced: for users, configures some internal behaviour
* Development: not for users. May be dangerous, may not be documented.
*/
enum level_t {
LEVEL_BASIC = 0,
LEVEL_ADVANCED = 1,
LEVEL_DEV = 2,
LEVEL_UNKNOWN = 3,
};
static const char *level_to_str(level_t l) {
switch (l) {
case LEVEL_BASIC: return "basic";
case LEVEL_ADVANCED: return "advanced";
case LEVEL_DEV: return "dev";
default: return "unknown";
}
}
enum flag_t {
FLAG_RUNTIME = 0x1, ///< option can be changed at runtime
FLAG_NO_MON_UPDATE = 0x2, ///< option cannot be changed via mon config
FLAG_STARTUP = 0x4, ///< option can only take effect at startup
FLAG_CLUSTER_CREATE = 0x8, ///< option only has effect at cluster creation
FLAG_CREATE = 0x10, ///< option only has effect at daemon creation
FLAG_MGR = 0x20, ///< option is a mgr module option
FLAG_MINIMAL_CONF = 0x40, ///< option should go in a minimal ceph.conf
};
struct size_t {
std::uint64_t value;
operator uint64_t() const {
return static_cast<uint64_t>(value);
}
bool operator==(const size_t& rhs) const {
return value == rhs.value;
}
};
using value_t = std::variant<
std::monostate,
std::string,
uint64_t,
int64_t,
double,
bool,
entity_addr_t,
entity_addrvec_t,
std::chrono::seconds,
std::chrono::milliseconds,
size_t,
uuid_d>;
const std::string name;
const type_t type;
const level_t level;
std::string desc;
std::string long_desc;
unsigned flags = 0;
int subsys = -1; // if >= 0, we are a subsys debug level
value_t value;
value_t daemon_value;
static std::string to_str(const value_t& v);
// Items like mon, osd, rgw, rbd, ceph-fuse. This is advisory metadata
// for presentation layers (like web dashboards, or generated docs), so that
// they know which options to display where.
// Additionally: "common" for settings that exist in any Ceph code. Do
// not use common for settings that are just shared some places: for those
// places, list them.
std::vector<const char*> services;
// Topics like:
// "service": a catchall for the boring stuff like log/asok paths.
// "network"
// "performance": a setting that may need adjustment depending on
// environment/workload to get best performance.
std::vector<const char*> tags;
std::vector<const char*> see_also;
value_t min, max;
std::vector<const char*> enum_allowed;
/**
* Return nonzero and set second argument to error string if the
* value is invalid.
*
* These callbacks are more than just validators, as they can also
* modify the value as it passes through.
*/
typedef std::function<int(std::string *, std::string *)> validator_fn_t;
validator_fn_t validator;
Option(std::string const &name, type_t t, level_t l)
: name(name), type(t), level(l)
{
// While value_t is nullable (via std::monostate), we don't ever
// want it set that way in an Option instance: within an instance,
// the type of ::value should always match the declared type.
switch (type) {
case TYPE_INT:
value = int64_t(0); break;
case TYPE_UINT:
value = uint64_t(0); break;
case TYPE_STR:
value = std::string(""); break;
case TYPE_FLOAT:
value = 0.0; break;
case TYPE_BOOL:
value = false; break;
case TYPE_ADDR:
value = entity_addr_t(); break;
case TYPE_ADDRVEC:
value = entity_addrvec_t(); break;
case TYPE_UUID:
value = uuid_d(); break;
case TYPE_SIZE:
value = size_t{0}; break;
case TYPE_SECS:
value = std::chrono::seconds{0}; break;
case TYPE_MILLISECS:
value = std::chrono::milliseconds{0}; break;
default:
ceph_abort();
}
}
void dump_value(const char *field_name, const value_t &v, ceph::Formatter *f) const;
// Validate and potentially modify incoming string value
int pre_validate(std::string *new_value, std::string *err) const;
// Validate properly typed value against bounds
int validate(const Option::value_t &new_value, std::string *err) const;
// const char * must be explicit to avoid it being treated as an int
Option& set_value(value_t& v, const char *new_value) {
v = std::string(new_value);
return *this;
}
// bool is an integer, but we don't think so. teach it the hard way.
template<typename T>
using is_not_integer_t =
std::enable_if_t<!std::is_integral_v<T> || std::is_same_v<T, bool>, int>;
template<typename T>
using is_integer_t =
std::enable_if_t<std::is_integral_v<T> && !std::is_same_v<T, bool>, int>;
template<typename T, typename = is_not_integer_t<T>>
Option& set_value(value_t& v, const T& new_value) {
v = new_value;
return *this;
}
// For potentially ambiguous types, inspect Option::type and
// do some casting. This is necessary to make sure that setting
// a float option to "0" actually sets the double part of variant.
template<typename T, typename = is_integer_t<T>>
Option& set_value(value_t& v, T new_value) {
switch (type) {
case TYPE_INT:
v = int64_t(new_value); break;
case TYPE_UINT:
v = uint64_t(new_value); break;
case TYPE_FLOAT:
v = double(new_value); break;
case TYPE_BOOL:
v = bool(new_value); break;
case TYPE_SIZE:
v = size_t{static_cast<std::uint64_t>(new_value)}; break;
case TYPE_SECS:
v = std::chrono::seconds{new_value}; break;
case TYPE_MILLISECS:
v = std::chrono::milliseconds{new_value}; break;
default:
std::cerr << "Bad type in set_value: " << name << ": "
<< typeid(T).name() << std::endl;
ceph_abort();
}
return *this;
}
/// parse and validate a string input
int parse_value(
const std::string& raw_val,
value_t *out,
std::string *error_message,
std::string *normalized_value=nullptr) const;
template<typename T>
Option& set_default(const T& v) {
return set_value(value, v);
}
template<typename T>
Option& set_daemon_default(const T& v) {
return set_value(daemon_value, v);
}
Option& add_tag(const char* tag) {
tags.push_back(tag);
return *this;
}
Option& add_tag(const std::initializer_list<const char*>& ts) {
tags.insert(tags.end(), ts);
return *this;
}
Option& add_service(const char* service) {
services.push_back(service);
return *this;
}
Option& add_service(const std::initializer_list<const char*>& ss) {
services.insert(services.end(), ss);
return *this;
}
Option& add_see_also(const char* t) {
see_also.push_back(t);
return *this;
}
Option& add_see_also(const std::initializer_list<const char*>& ts) {
see_also.insert(see_also.end(), ts);
return *this;
}
Option& set_description(const char* new_desc) {
desc = new_desc;
return *this;
}
Option& set_long_description(const char* new_desc) {
long_desc = new_desc;
return *this;
}
template<typename T>
Option& set_min(const T& mi) {
set_value(min, mi);
return *this;
}
template<typename T>
Option& set_min_max(const T& mi, const T& ma) {
set_value(min, mi);
set_value(max, ma);
return *this;
}
Option& set_enum_allowed(const std::vector<const char*>& allowed)
{
enum_allowed = allowed;
return *this;
}
Option &set_flag(flag_t f) {
flags |= f;
return *this;
}
Option &set_flags(flag_t f) {
flags |= f;
return *this;
}
Option &set_validator(const validator_fn_t &validator_)
{
validator = validator_;
return *this;
}
Option &set_subsys(int s) {
subsys = s;
return *this;
}
void dump(ceph::Formatter *f) const;
void print(std::ostream *out) const;
bool has_flag(flag_t f) const {
return flags & f;
}
/**
* A crude indicator of whether the value may be
* modified safely at runtime -- should be replaced
* with proper locking!
*/
bool can_update_at_runtime() const
{
return
(has_flag(FLAG_RUNTIME)
|| (!has_flag(FLAG_MGR)
&& (type == TYPE_BOOL || type == TYPE_INT
|| type == TYPE_UINT || type == TYPE_FLOAT
|| type == TYPE_SIZE || type == TYPE_SECS
|| type == TYPE_MILLISECS)))
&& !has_flag(FLAG_STARTUP)
&& !has_flag(FLAG_CLUSTER_CREATE)
&& !has_flag(FLAG_CREATE);
}
};
constexpr unsigned long long operator"" _min (unsigned long long min) {
return min * 60;
}
constexpr unsigned long long operator"" _hr (unsigned long long hr) {
return hr * 60 * 60;
}
constexpr unsigned long long operator"" _day (unsigned long long day) {
return day * 24 * 60 * 60;
}
constexpr unsigned long long operator"" _K (unsigned long long n) {
return n << 10;
}
constexpr unsigned long long operator"" _M (unsigned long long n) {
return n << 20;
}
constexpr unsigned long long operator"" _G (unsigned long long n) {
return n << 30;
}
constexpr unsigned long long operator"" _T (unsigned long long n) {
return n << 40;
}
extern const std::vector<Option> ceph_options;
| 11,502 | 26.065882 | 86 | h |
null | ceph-main/src/common/ostream_temp.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "common/ostream_temp.h"
OstreamTemp::OstreamTemp(clog_type type_, OstreamTempSink *parent_)
: type(type_), parent(parent_)
{
}
OstreamTemp::~OstreamTemp()
{
if (ss.peek() != EOF && parent)
parent->do_log(type, ss);
}
| 335 | 20 | 70 | cc |
null | ceph-main/src/common/ostream_temp.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <sstream>
typedef enum {
CLOG_DEBUG = 0,
CLOG_INFO = 1,
CLOG_SEC = 2,
CLOG_WARN = 3,
CLOG_ERROR = 4,
CLOG_UNKNOWN = -1,
} clog_type;
class OstreamTemp
{
public:
class OstreamTempSink {
public:
virtual void do_log(clog_type prio, std::stringstream& ss) = 0;
virtual ~OstreamTempSink() {}
};
OstreamTemp(clog_type type_, OstreamTempSink *parent_);
OstreamTemp(OstreamTemp &&rhs) = default;
~OstreamTemp();
template<typename T>
std::ostream& operator<<(const T& rhs)
{
return ss << rhs;
}
private:
clog_type type;
OstreamTempSink *parent;
std::stringstream ss;
};
class LoggerSinkSet : public OstreamTemp::OstreamTempSink {
public:
virtual void info(std::stringstream &s) = 0;
virtual void warn(std::stringstream &s) = 0;
virtual void error(std::stringstream &s) = 0;
virtual void sec(std::stringstream &s) = 0;
virtual void debug(std::stringstream &s) = 0;
virtual OstreamTemp info() = 0;
virtual OstreamTemp warn() = 0;
virtual OstreamTemp error() = 0;
virtual OstreamTemp sec() = 0;
virtual OstreamTemp debug() = 0;
virtual void do_log(clog_type prio, std::stringstream& ss) = 0;
virtual void do_log(clog_type prio, const std::string& ss) = 0;
virtual ~LoggerSinkSet() {};
};
| 1,379 | 23.210526 | 70 | h |
null | ceph-main/src/common/page.cc | #include <unistd.h>
#ifdef _WIN32
#include <windows.h>
#endif
namespace ceph {
// page size crap, see page.h
int _get_bits_of(int v) {
int n = 0;
while (v) {
n++;
v = v >> 1;
}
return n;
}
#ifdef _WIN32
unsigned _get_page_size() {
SYSTEM_INFO system_info;
GetSystemInfo(&system_info);
return system_info.dwPageSize;
}
unsigned _page_size = _get_page_size();
#else
unsigned _page_size = sysconf(_SC_PAGESIZE);
#endif
unsigned long _page_mask = ~(unsigned long)(_page_size - 1);
unsigned _page_shift = _get_bits_of(_page_size - 1);
}
| 602 | 16.735294 | 62 | cc |
null | ceph-main/src/common/perf_counters.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) 2011 New Dream Network
* 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.
*
*/
#include "common/perf_counters.h"
#include "common/perf_counters_key.h"
#include "common/dout.h"
#include "common/valgrind.h"
#include "include/common_fwd.h"
using std::ostringstream;
using std::make_pair;
using std::pair;
namespace TOPNSPC::common {
PerfCountersCollectionImpl::PerfCountersCollectionImpl()
{
}
PerfCountersCollectionImpl::~PerfCountersCollectionImpl()
{
clear();
}
void PerfCountersCollectionImpl::add(PerfCounters *l)
{
// make sure the name is unique
perf_counters_set_t::iterator i;
i = m_loggers.find(l);
while (i != m_loggers.end()) {
ostringstream ss;
ss << l->get_name() << "-" << (void*)l;
l->set_name(ss.str());
i = m_loggers.find(l);
}
m_loggers.insert(l);
for (unsigned int i = 0; i < l->m_data.size(); ++i) {
PerfCounters::perf_counter_data_any_d &data = l->m_data[i];
std::string path = l->get_name();
path += ".";
path += data.name;
by_path[path] = {&data, l};
}
}
void PerfCountersCollectionImpl::remove(PerfCounters *l)
{
for (unsigned int i = 0; i < l->m_data.size(); ++i) {
PerfCounters::perf_counter_data_any_d &data = l->m_data[i];
std::string path = l->get_name();
path += ".";
path += data.name;
by_path.erase(path);
}
perf_counters_set_t::iterator i = m_loggers.find(l);
ceph_assert(i != m_loggers.end());
m_loggers.erase(i);
}
void PerfCountersCollectionImpl::clear()
{
perf_counters_set_t::iterator i = m_loggers.begin();
perf_counters_set_t::iterator i_end = m_loggers.end();
for (; i != i_end; ) {
delete *i;
m_loggers.erase(i++);
}
by_path.clear();
}
bool PerfCountersCollectionImpl::reset(const std::string &name)
{
bool result = false;
perf_counters_set_t::iterator i = m_loggers.begin();
perf_counters_set_t::iterator i_end = m_loggers.end();
if (!strcmp(name.c_str(), "all")) {
while (i != i_end) {
(*i)->reset();
++i;
}
result = true;
} else {
while (i != i_end) {
if (!name.compare((*i)->get_name())) {
(*i)->reset();
result = true;
break;
}
++i;
}
}
return result;
}
/**
* Serialize current values of performance counters. Optionally
* output the schema instead, or filter output to a particular
* PerfCounters or particular named counter.
*
* @param logger name of subsystem logger, e.g. "mds_cache", may be empty
* @param counter name of counter within subsystem, e.g. "num_strays",
* may be empty.
* @param schema if true, output schema instead of current data.
* @param histograms if true, dump histogram values,
* if false dump all non-histogram counters
*/
void PerfCountersCollectionImpl::dump_formatted_generic(
Formatter *f,
bool schema,
bool histograms,
bool dump_labeled,
const std::string &logger,
const std::string &counter) const
{
f->open_object_section("perfcounter_collection");
if (dump_labeled) {
std::string prev_key_name;
for (auto l = m_loggers.begin(); l != m_loggers.end(); ++l) {
std::string_view key_name = ceph::perf_counters::key_name((*l)->get_name());
if (key_name != prev_key_name) {
// close previous set of counters before dumping new one
if (!prev_key_name.empty()) {
f->close_section(); // array section
}
prev_key_name = key_name;
f->open_array_section(key_name);
(*l)->dump_formatted_generic(f, schema, histograms, true, "");
} else {
(*l)->dump_formatted_generic(f, schema, histograms, true, "");
}
}
if (!m_loggers.empty()) {
f->close_section(); // final array section
}
} else {
for (auto l = m_loggers.begin(); l != m_loggers.end(); ++l) {
// Optionally filter on logger name, pass through counter filter
if (logger.empty() || (*l)->get_name() == logger) {
(*l)->dump_formatted_generic(f, schema, histograms, false, counter);
}
}
}
f->close_section();
}
void PerfCountersCollectionImpl::with_counters(std::function<void(
const PerfCountersCollectionImpl::CounterMap &)> fn) const
{
fn(by_path);
}
// ---------------------------
PerfCounters::~PerfCounters()
{
}
void PerfCounters::inc(int idx, uint64_t amt)
{
#ifndef WITH_SEASTAR
if (!m_cct->_conf->perf)
return;
#endif
ceph_assert(idx > m_lower_bound);
ceph_assert(idx < m_upper_bound);
perf_counter_data_any_d& data(m_data[idx - m_lower_bound - 1]);
if (!(data.type & PERFCOUNTER_U64))
return;
if (data.type & PERFCOUNTER_LONGRUNAVG) {
data.avgcount++;
data.u64 += amt;
data.avgcount2++;
} else {
data.u64 += amt;
}
}
void PerfCounters::dec(int idx, uint64_t amt)
{
#ifndef WITH_SEASTAR
if (!m_cct->_conf->perf)
return;
#endif
ceph_assert(idx > m_lower_bound);
ceph_assert(idx < m_upper_bound);
perf_counter_data_any_d& data(m_data[idx - m_lower_bound - 1]);
ceph_assert(!(data.type & PERFCOUNTER_LONGRUNAVG));
if (!(data.type & PERFCOUNTER_U64))
return;
data.u64 -= amt;
}
void PerfCounters::set(int idx, uint64_t amt)
{
#ifndef WITH_SEASTAR
if (!m_cct->_conf->perf)
return;
#endif
ceph_assert(idx > m_lower_bound);
ceph_assert(idx < m_upper_bound);
perf_counter_data_any_d& data(m_data[idx - m_lower_bound - 1]);
if (!(data.type & PERFCOUNTER_U64))
return;
ANNOTATE_BENIGN_RACE_SIZED(&data.u64, sizeof(data.u64),
"perf counter atomic");
if (data.type & PERFCOUNTER_LONGRUNAVG) {
data.avgcount++;
data.u64 = amt;
data.avgcount2++;
} else {
data.u64 = amt;
}
}
uint64_t PerfCounters::get(int idx) const
{
#ifndef WITH_SEASTAR
if (!m_cct->_conf->perf)
return 0;
#endif
ceph_assert(idx > m_lower_bound);
ceph_assert(idx < m_upper_bound);
const perf_counter_data_any_d& data(m_data[idx - m_lower_bound - 1]);
if (!(data.type & PERFCOUNTER_U64))
return 0;
return data.u64;
}
void PerfCounters::tinc(int idx, utime_t amt)
{
#ifndef WITH_SEASTAR
if (!m_cct->_conf->perf)
return;
#endif
ceph_assert(idx > m_lower_bound);
ceph_assert(idx < m_upper_bound);
perf_counter_data_any_d& data(m_data[idx - m_lower_bound - 1]);
if (!(data.type & PERFCOUNTER_TIME))
return;
if (data.type & PERFCOUNTER_LONGRUNAVG) {
data.avgcount++;
data.u64 += amt.to_nsec();
data.avgcount2++;
} else {
data.u64 += amt.to_nsec();
}
}
void PerfCounters::tinc(int idx, ceph::timespan amt)
{
#ifndef WITH_SEASTAR
if (!m_cct->_conf->perf)
return;
#endif
ceph_assert(idx > m_lower_bound);
ceph_assert(idx < m_upper_bound);
perf_counter_data_any_d& data(m_data[idx - m_lower_bound - 1]);
if (!(data.type & PERFCOUNTER_TIME))
return;
if (data.type & PERFCOUNTER_LONGRUNAVG) {
data.avgcount++;
data.u64 += amt.count();
data.avgcount2++;
} else {
data.u64 += amt.count();
}
}
void PerfCounters::tset(int idx, utime_t amt)
{
#ifndef WITH_SEASTAR
if (!m_cct->_conf->perf)
return;
#endif
ceph_assert(idx > m_lower_bound);
ceph_assert(idx < m_upper_bound);
perf_counter_data_any_d& data(m_data[idx - m_lower_bound - 1]);
if (!(data.type & PERFCOUNTER_TIME))
return;
data.u64 = amt.to_nsec();
if (data.type & PERFCOUNTER_LONGRUNAVG)
ceph_abort();
}
utime_t PerfCounters::tget(int idx) const
{
#ifndef WITH_SEASTAR
if (!m_cct->_conf->perf)
return utime_t();
#endif
ceph_assert(idx > m_lower_bound);
ceph_assert(idx < m_upper_bound);
const perf_counter_data_any_d& data(m_data[idx - m_lower_bound - 1]);
if (!(data.type & PERFCOUNTER_TIME))
return utime_t();
uint64_t v = data.u64;
return utime_t(v / 1000000000ull, v % 1000000000ull);
}
void PerfCounters::hinc(int idx, int64_t x, int64_t y)
{
#ifndef WITH_SEASTAR
if (!m_cct->_conf->perf)
return;
#endif
ceph_assert(idx > m_lower_bound);
ceph_assert(idx < m_upper_bound);
perf_counter_data_any_d& data(m_data[idx - m_lower_bound - 1]);
ceph_assert(data.type == (PERFCOUNTER_HISTOGRAM | PERFCOUNTER_COUNTER | PERFCOUNTER_U64));
ceph_assert(data.histogram);
data.histogram->inc(x, y);
}
pair<uint64_t, uint64_t> PerfCounters::get_tavg_ns(int idx) const
{
#ifndef WITH_SEASTAR
if (!m_cct->_conf->perf)
return make_pair(0, 0);
#endif
ceph_assert(idx > m_lower_bound);
ceph_assert(idx < m_upper_bound);
const perf_counter_data_any_d& data(m_data[idx - m_lower_bound - 1]);
if (!(data.type & PERFCOUNTER_TIME))
return make_pair(0, 0);
if (!(data.type & PERFCOUNTER_LONGRUNAVG))
return make_pair(0, 0);
pair<uint64_t,uint64_t> a = data.read_avg();
return make_pair(a.second, a.first);
}
void PerfCounters::reset()
{
perf_counter_data_vec_t::iterator d = m_data.begin();
perf_counter_data_vec_t::iterator d_end = m_data.end();
while (d != d_end) {
d->reset();
++d;
}
}
void PerfCounters::dump_formatted_generic(Formatter *f, bool schema,
bool histograms, bool dump_labeled, const std::string &counter) const
{
if (dump_labeled) {
f->open_object_section(""); // should be enclosed by array
f->open_object_section("labels");
for (auto label : ceph::perf_counters::key_labels(m_name)) {
// don't dump labels with empty label names
if (!label.first.empty()) {
f->dump_string(label.first, label.second);
}
}
f->close_section(); // labels
f->open_object_section("counters");
} else {
auto labels = ceph::perf_counters::key_labels(m_name);
// do not dump counters when counter instance is labeled and dump_labeled is not set
if (labels.begin() != labels.end()) {
return;
}
f->open_object_section(m_name.c_str());
}
for (perf_counter_data_vec_t::const_iterator d = m_data.begin();
d != m_data.end(); ++d) {
if (!counter.empty() && counter != d->name) {
// Optionally filter on counter name
continue;
}
// Switch between normal and histogram view
bool is_histogram = (d->type & PERFCOUNTER_HISTOGRAM) != 0;
if (is_histogram != histograms) {
continue;
}
if (schema) {
f->open_object_section(d->name);
// we probably should not have exposed this raw field (with bit
// values), but existing plugins rely on it so we're stuck with
// it.
f->dump_int("type", d->type);
if (d->type & PERFCOUNTER_COUNTER) {
f->dump_string("metric_type", "counter");
} else {
f->dump_string("metric_type", "gauge");
}
if (d->type & PERFCOUNTER_LONGRUNAVG) {
if (d->type & PERFCOUNTER_TIME) {
f->dump_string("value_type", "real-integer-pair");
} else {
f->dump_string("value_type", "integer-integer-pair");
}
} else if (d->type & PERFCOUNTER_HISTOGRAM) {
if (d->type & PERFCOUNTER_TIME) {
f->dump_string("value_type", "real-2d-histogram");
} else {
f->dump_string("value_type", "integer-2d-histogram");
}
} else {
if (d->type & PERFCOUNTER_TIME) {
f->dump_string("value_type", "real");
} else {
f->dump_string("value_type", "integer");
}
}
f->dump_string("description", d->description ? d->description : "");
if (d->nick != NULL) {
f->dump_string("nick", d->nick);
} else {
f->dump_string("nick", "");
}
f->dump_int("priority", get_adjusted_priority(d->prio));
if (d->unit == UNIT_NONE) {
f->dump_string("units", "none");
} else if (d->unit == UNIT_BYTES) {
f->dump_string("units", "bytes");
}
f->close_section();
} else {
if (d->type & PERFCOUNTER_LONGRUNAVG) {
f->open_object_section(d->name);
pair<uint64_t,uint64_t> a = d->read_avg();
if (d->type & PERFCOUNTER_U64) {
f->dump_unsigned("avgcount", a.second);
f->dump_unsigned("sum", a.first);
} else if (d->type & PERFCOUNTER_TIME) {
f->dump_unsigned("avgcount", a.second);
f->dump_format_unquoted("sum", "%" PRId64 ".%09" PRId64,
a.first / 1000000000ull,
a.first % 1000000000ull);
uint64_t count = a.second;
uint64_t sum_ns = a.first;
if (count) {
uint64_t avg_ns = sum_ns / count;
f->dump_format_unquoted("avgtime", "%" PRId64 ".%09" PRId64,
avg_ns / 1000000000ull,
avg_ns % 1000000000ull);
} else {
f->dump_format_unquoted("avgtime", "%" PRId64 ".%09" PRId64, 0, 0);
}
} else {
ceph_abort();
}
f->close_section();
} else if (d->type & PERFCOUNTER_HISTOGRAM) {
ceph_assert(d->type == (PERFCOUNTER_HISTOGRAM | PERFCOUNTER_COUNTER | PERFCOUNTER_U64));
ceph_assert(d->histogram);
f->open_object_section(d->name);
d->histogram->dump_formatted(f);
f->close_section();
} else {
uint64_t v = d->u64;
if (d->type & PERFCOUNTER_U64) {
f->dump_unsigned(d->name, v);
} else if (d->type & PERFCOUNTER_TIME) {
f->dump_format_unquoted(d->name, "%" PRId64 ".%09" PRId64,
v / 1000000000ull,
v % 1000000000ull);
} else {
ceph_abort();
}
}
}
}
if (dump_labeled) {
f->close_section(); // counters
}
f->close_section();
}
const std::string &PerfCounters::get_name() const
{
return m_name;
}
PerfCounters::PerfCounters(CephContext *cct, const std::string &name,
int lower_bound, int upper_bound)
: m_cct(cct),
m_lower_bound(lower_bound),
m_upper_bound(upper_bound),
m_name(name)
#if !defined(WITH_SEASTAR) || defined(WITH_ALIEN)
,
m_lock_name(std::string("PerfCounters::") + name.c_str()),
m_lock(ceph::make_mutex(m_lock_name))
#endif
{
m_data.resize(upper_bound - lower_bound - 1);
}
PerfCountersBuilder::PerfCountersBuilder(CephContext *cct, const std::string &name,
int first, int last)
: m_perf_counters(new PerfCounters(cct, name, first, last))
{
}
PerfCountersBuilder::~PerfCountersBuilder()
{
if (m_perf_counters)
delete m_perf_counters;
m_perf_counters = NULL;
}
void PerfCountersBuilder::add_u64_counter(
int idx, const char *name,
const char *description, const char *nick, int prio, int unit)
{
add_impl(idx, name, description, nick, prio,
PERFCOUNTER_U64 | PERFCOUNTER_COUNTER, unit);
}
void PerfCountersBuilder::add_u64(
int idx, const char *name,
const char *description, const char *nick, int prio, int unit)
{
add_impl(idx, name, description, nick, prio, PERFCOUNTER_U64, unit);
}
void PerfCountersBuilder::add_u64_avg(
int idx, const char *name,
const char *description, const char *nick, int prio, int unit)
{
add_impl(idx, name, description, nick, prio,
PERFCOUNTER_U64 | PERFCOUNTER_LONGRUNAVG, unit);
}
void PerfCountersBuilder::add_time(
int idx, const char *name,
const char *description, const char *nick, int prio)
{
add_impl(idx, name, description, nick, prio, PERFCOUNTER_TIME);
}
void PerfCountersBuilder::add_time_avg(
int idx, const char *name,
const char *description, const char *nick, int prio)
{
add_impl(idx, name, description, nick, prio,
PERFCOUNTER_TIME | PERFCOUNTER_LONGRUNAVG);
}
void PerfCountersBuilder::add_u64_counter_histogram(
int idx, const char *name,
PerfHistogramCommon::axis_config_d x_axis_config,
PerfHistogramCommon::axis_config_d y_axis_config,
const char *description, const char *nick, int prio, int unit)
{
add_impl(idx, name, description, nick, prio,
PERFCOUNTER_U64 | PERFCOUNTER_HISTOGRAM | PERFCOUNTER_COUNTER, unit,
std::unique_ptr<PerfHistogram<>>{new PerfHistogram<>{x_axis_config, y_axis_config}});
}
void PerfCountersBuilder::add_impl(
int idx, const char *name,
const char *description, const char *nick, int prio, int ty, int unit,
std::unique_ptr<PerfHistogram<>> histogram)
{
ceph_assert(idx > m_perf_counters->m_lower_bound);
ceph_assert(idx < m_perf_counters->m_upper_bound);
PerfCounters::perf_counter_data_vec_t &vec(m_perf_counters->m_data);
PerfCounters::perf_counter_data_any_d
&data(vec[idx - m_perf_counters->m_lower_bound - 1]);
ceph_assert(data.type == PERFCOUNTER_NONE);
data.name = name;
data.description = description;
// nick must be <= 4 chars
if (nick) {
ceph_assert(strlen(nick) <= 4);
}
data.nick = nick;
data.prio = prio ? prio : prio_default;
data.type = (enum perfcounter_type_d)ty;
data.unit = (enum unit_t) unit;
data.histogram = std::move(histogram);
}
PerfCounters *PerfCountersBuilder::create_perf_counters()
{
PerfCounters::perf_counter_data_vec_t::const_iterator d = m_perf_counters->m_data.begin();
PerfCounters::perf_counter_data_vec_t::const_iterator d_end = m_perf_counters->m_data.end();
for (; d != d_end; ++d) {
ceph_assert(d->type != PERFCOUNTER_NONE);
ceph_assert(d->type & (PERFCOUNTER_U64 | PERFCOUNTER_TIME));
}
PerfCounters *ret = m_perf_counters;
m_perf_counters = NULL;
return ret;
}
}
| 17,224 | 26.083333 | 96 | cc |
null | ceph-main/src/common/perf_counters.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) 2011 New Dream Network
* 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_COMMON_PERF_COUNTERS_H
#define CEPH_COMMON_PERF_COUNTERS_H
#include <string>
#include <vector>
#include <memory>
#include <atomic>
#include <cstdint>
#include "common/perf_histogram.h"
#include "include/utime.h"
#include "include/common_fwd.h"
#include "common/ceph_mutex.h"
#include "common/ceph_time.h"
namespace TOPNSPC::common {
class CephContext;
class PerfCountersBuilder;
class PerfCounters;
}
enum perfcounter_type_d : uint8_t
{
PERFCOUNTER_NONE = 0,
PERFCOUNTER_TIME = 0x1, // float (measuring seconds)
PERFCOUNTER_U64 = 0x2, // integer (note: either TIME or U64 *must* be set)
PERFCOUNTER_LONGRUNAVG = 0x4, // paired counter + sum (time)
PERFCOUNTER_COUNTER = 0x8, // counter (vs gauge)
PERFCOUNTER_HISTOGRAM = 0x10, // histogram (vector) of values
};
enum unit_t : uint8_t
{
UNIT_BYTES,
UNIT_NONE
};
/* Class for constructing a PerfCounters object.
*
* This class performs some validation that the parameters we have supplied are
* correct in create_perf_counters().
*
* In the future, we will probably get rid of the first/last arguments, since
* PerfCountersBuilder can deduce them itself.
*/
namespace TOPNSPC::common {
class PerfCountersBuilder
{
public:
PerfCountersBuilder(CephContext *cct, const std::string &name,
int first, int last);
~PerfCountersBuilder();
// prio values: higher is better, and higher values get included in
// 'ceph daemonperf' (and similar) results.
// Use of priorities enables us to add large numbers of counters
// internally without necessarily overwhelming consumers.
enum {
PRIO_CRITICAL = 10,
// 'interesting' is the default threshold for `daemonperf` output
PRIO_INTERESTING = 8,
// `useful` is the default threshold for transmission to ceph-mgr
// and inclusion in prometheus/influxdb plugin output
PRIO_USEFUL = 5,
PRIO_UNINTERESTING = 2,
PRIO_DEBUGONLY = 0,
};
void add_u64(int key, const char *name,
const char *description=NULL, const char *nick = NULL,
int prio=0, int unit=UNIT_NONE);
void add_u64_counter(int key, const char *name,
const char *description=NULL,
const char *nick = NULL,
int prio=0, int unit=UNIT_NONE);
void add_u64_avg(int key, const char *name,
const char *description=NULL,
const char *nick = NULL,
int prio=0, int unit=UNIT_NONE);
void add_time(int key, const char *name,
const char *description=NULL,
const char *nick = NULL,
int prio=0);
void add_time_avg(int key, const char *name,
const char *description=NULL,
const char *nick = NULL,
int prio=0);
void add_u64_counter_histogram(
int key, const char* name,
PerfHistogramCommon::axis_config_d x_axis_config,
PerfHistogramCommon::axis_config_d y_axis_config,
const char *description=NULL,
const char* nick = NULL,
int prio=0, int unit=UNIT_NONE);
void set_prio_default(int prio_)
{
prio_default = prio_;
}
PerfCounters* create_perf_counters();
private:
PerfCountersBuilder(const PerfCountersBuilder &rhs);
PerfCountersBuilder& operator=(const PerfCountersBuilder &rhs);
void add_impl(int idx, const char *name,
const char *description, const char *nick, int prio, int ty, int unit=UNIT_NONE,
std::unique_ptr<PerfHistogram<>> histogram = nullptr);
PerfCounters *m_perf_counters;
int prio_default = 0;
};
/*
* A PerfCounters object is usually associated with a single subsystem.
* It contains counters which we modify to track performance and throughput
* over time.
*
* PerfCounters can track several different types of values:
* 1) integer values & counters
* 2) floating-point values & counters
* 3) floating-point averages
* 4) 2D histograms of quantized value pairs
*
* The difference between values, counters and histograms is in how they are initialized
* and accessed. For a counter, use the inc(counter, amount) function (note
* that amount defaults to 1 if you don't set it). For a value, use the
* set(index, value) function. For histogram use the hinc(value1, value2) function.
* (For time, use the tinc and tset variants.)
*
* If for some reason you would like to reset your counters, you can do so using
* the set functions even if they are counters, and you can also
* increment your values if for some reason you wish to.
*
* For the time average, it returns the current value and
* the "avgcount" member when read off. avgcount is incremented when you call
* tinc. Calling tset on an average is an error and will assert out.
*/
class PerfCounters
{
public:
/** Represents a PerfCounters data element. */
struct perf_counter_data_any_d {
perf_counter_data_any_d()
: name(NULL),
description(NULL),
nick(NULL),
type(PERFCOUNTER_NONE),
unit(UNIT_NONE)
{}
perf_counter_data_any_d(const perf_counter_data_any_d& other)
: name(other.name),
description(other.description),
nick(other.nick),
type(other.type),
unit(other.unit),
u64(other.u64.load()) {
auto a = other.read_avg();
u64 = a.first;
avgcount = a.second;
avgcount2 = a.second;
if (other.histogram) {
histogram.reset(new PerfHistogram<>(*other.histogram));
}
}
const char *name;
const char *description;
const char *nick;
uint8_t prio = 0;
enum perfcounter_type_d type;
enum unit_t unit;
std::atomic<uint64_t> u64 = { 0 };
std::atomic<uint64_t> avgcount = { 0 };
std::atomic<uint64_t> avgcount2 = { 0 };
std::unique_ptr<PerfHistogram<>> histogram;
void reset()
{
if (type != PERFCOUNTER_U64) {
u64 = 0;
avgcount = 0;
avgcount2 = 0;
}
if (histogram) {
histogram->reset();
}
}
// read <sum, count> safely by making sure the post- and pre-count
// are identical; in other words the whole loop needs to be run
// without any intervening calls to inc, set, or tinc.
std::pair<uint64_t,uint64_t> read_avg() const {
uint64_t sum, count;
do {
count = avgcount2;
sum = u64;
} while (avgcount != count);
return { sum, count };
}
};
template <typename T>
struct avg_tracker {
std::pair<uint64_t, T> last;
std::pair<uint64_t, T> cur;
avg_tracker() : last(0, 0), cur(0, 0) {}
T current_avg() const {
if (cur.first == last.first)
return 0;
return (cur.second - last.second) / (cur.first - last.first);
}
void consume_next(const std::pair<uint64_t, T> &next) {
last = cur;
cur = next;
}
};
~PerfCounters();
void inc(int idx, uint64_t v = 1);
void dec(int idx, uint64_t v = 1);
void set(int idx, uint64_t v);
uint64_t get(int idx) const;
void tset(int idx, utime_t v);
void tinc(int idx, utime_t v);
void tinc(int idx, ceph::timespan v);
utime_t tget(int idx) const;
void hinc(int idx, int64_t x, int64_t y);
void reset();
void dump_formatted(ceph::Formatter *f, bool schema, bool dump_labeled,
const std::string &counter = "") const {
dump_formatted_generic(f, schema, false, dump_labeled, counter);
}
void dump_formatted_histograms(ceph::Formatter *f, bool schema,
const std::string &counter = "") const {
dump_formatted_generic(f, schema, true, false, counter);
}
std::pair<uint64_t, uint64_t> get_tavg_ns(int idx) const;
const std::string& get_name() const;
void set_name(std::string s) {
m_name = s;
}
/// adjust priority values by some value
void set_prio_adjust(int p) {
prio_adjust = p;
}
int get_adjusted_priority(int p) const {
return std::max(std::min(p + prio_adjust,
(int)PerfCountersBuilder::PRIO_CRITICAL),
0);
}
private:
PerfCounters(CephContext *cct, const std::string &name,
int lower_bound, int upper_bound);
PerfCounters(const PerfCounters &rhs);
PerfCounters& operator=(const PerfCounters &rhs);
void dump_formatted_generic(ceph::Formatter *f, bool schema, bool histograms,
bool dump_labeled,
const std::string &counter = "") const;
typedef std::vector<perf_counter_data_any_d> perf_counter_data_vec_t;
CephContext *m_cct;
int m_lower_bound;
int m_upper_bound;
std::string m_name;
int prio_adjust = 0;
#if !defined(WITH_SEASTAR) || defined(WITH_ALIEN)
const std::string m_lock_name;
/** Protects m_data */
ceph::mutex m_lock;
#endif
perf_counter_data_vec_t m_data;
friend class PerfCountersBuilder;
friend class PerfCountersCollectionImpl;
};
class SortPerfCountersByName {
public:
bool operator()(const PerfCounters* lhs, const PerfCounters* rhs) const {
return (lhs->get_name() < rhs->get_name());
}
};
typedef std::set <PerfCounters*, SortPerfCountersByName> perf_counters_set_t;
/*
* PerfCountersCollectionImp manages PerfCounters objects for a Ceph process.
*/
class PerfCountersCollectionImpl
{
public:
PerfCountersCollectionImpl();
~PerfCountersCollectionImpl();
void add(PerfCounters *l);
void remove(PerfCounters *l);
void clear();
bool reset(const std::string &name);
void dump_formatted(ceph::Formatter *f, bool schema, bool dump_labeled,
const std::string &logger = "",
const std::string &counter = "") const {
dump_formatted_generic(f, schema, false, dump_labeled, logger, counter);
}
void dump_formatted_histograms(ceph::Formatter *f, bool schema,
const std::string &logger = "",
const std::string &counter = "") const {
dump_formatted_generic(f, schema, true, false, logger, counter);
}
// A reference to a perf_counter_data_any_d, with an accompanying
// pointer to the enclosing PerfCounters, in order that the consumer
// can see the prio_adjust
class PerfCounterRef
{
public:
PerfCounters::perf_counter_data_any_d *data;
PerfCounters *perf_counters;
};
typedef std::map<std::string,
PerfCounterRef> CounterMap;
void with_counters(std::function<void(const CounterMap &)>) const;
private:
void dump_formatted_generic(ceph::Formatter *f, bool schema, bool histograms,
bool dump_labeled,
const std::string &logger = "",
const std::string &counter = "") const;
perf_counters_set_t m_loggers;
CounterMap by_path;
};
class PerfGuard {
const ceph::real_clock::time_point start;
PerfCounters* const counters;
const int event;
public:
PerfGuard(PerfCounters* const counters,
const int event)
: start(ceph::real_clock::now()),
counters(counters),
event(event) {
}
~PerfGuard() {
counters->tinc(event, ceph::real_clock::now() - start);
}
};
}
#endif
| 11,376 | 28.550649 | 96 | h |
null | ceph-main/src/common/perf_counters_collection.cc | #include "common/perf_counters_collection.h"
#include "common/ceph_mutex.h"
#include "common/ceph_context.h"
namespace ceph::common {
/* PerfcounterCollection hold the lock for PerfCounterCollectionImp */
PerfCountersCollection::PerfCountersCollection(CephContext *cct)
: m_cct(cct),
m_lock(ceph::make_mutex("PerfCountersCollection"))
{
}
PerfCountersCollection::~PerfCountersCollection()
{
clear();
}
void PerfCountersCollection::add(PerfCounters *l)
{
std::lock_guard lck(m_lock);
perf_impl.add(l);
}
void PerfCountersCollection::remove(PerfCounters *l)
{
std::lock_guard lck(m_lock);
perf_impl.remove(l);
}
void PerfCountersCollection::clear()
{
std::lock_guard lck(m_lock);
perf_impl.clear();
}
bool PerfCountersCollection::reset(const std::string &name)
{
std::lock_guard lck(m_lock);
return perf_impl.reset(name);
}
void PerfCountersCollection::dump_formatted(ceph::Formatter *f, bool schema,
bool dump_labeled,
const std::string &logger,
const std::string &counter)
{
std::lock_guard lck(m_lock);
perf_impl.dump_formatted(f, schema, dump_labeled, logger, counter);
}
void PerfCountersCollection::dump_formatted_histograms(ceph::Formatter *f, bool schema,
const std::string &logger,
const std::string &counter)
{
std::lock_guard lck(m_lock);
perf_impl.dump_formatted_histograms(f,schema,logger,counter);
}
void PerfCountersCollection::with_counters(std::function<void(const PerfCountersCollectionImpl::CounterMap &)> fn) const
{
std::lock_guard lck(m_lock);
perf_impl.with_counters(fn);
}
void PerfCountersDeleter::operator()(PerfCounters* p) noexcept
{
if (cct)
cct->get_perfcounters_collection()->remove(p);
delete p;
}
}
| 1,808 | 27.265625 | 120 | cc |
null | ceph-main/src/common/perf_counters_collection.h | #pragma once
#include "common/perf_counters.h"
#include "common/ceph_mutex.h"
#include "include/common_fwd.h"
namespace ceph::common {
class PerfCountersCollection
{
CephContext *m_cct;
/** Protects perf_impl->m_loggers */
mutable ceph::mutex m_lock;
PerfCountersCollectionImpl perf_impl;
public:
PerfCountersCollection(CephContext *cct);
~PerfCountersCollection();
void add(PerfCounters *l);
void remove(PerfCounters *l);
void clear();
bool reset(const std::string &name);
void dump_formatted(ceph::Formatter *f, bool schema, bool dump_labeled,
const std::string &logger = "",
const std::string &counter = "");
void dump_formatted_histograms(ceph::Formatter *f, bool schema,
const std::string &logger = "",
const std::string &counter = "");
void with_counters(std::function<void(const PerfCountersCollectionImpl::CounterMap &)>) const;
friend class PerfCountersCollectionTest;
};
class PerfCountersDeleter {
CephContext* cct;
public:
PerfCountersDeleter() noexcept : cct(nullptr) {}
PerfCountersDeleter(CephContext* cct) noexcept : cct(cct) {}
void operator()(PerfCounters* p) noexcept;
};
}
using PerfCountersRef = std::unique_ptr<ceph::common::PerfCounters, ceph::common::PerfCountersDeleter>;
| 1,351 | 29.044444 | 103 | h |
null | ceph-main/src/common/perf_counters_key.cc | #include "common/perf_counters_key.h"
#include <algorithm>
#include <iterator>
#include <numeric>
namespace ceph::perf_counters {
namespace detail {
// use a null character to delimit strings
constexpr char DELIMITER = '\0';
// write a delimited string to the output
auto write(std::string_view str, std::output_iterator<char> auto out)
{
out = std::copy(str.begin(), str.end(), out);
*(out++) = DELIMITER;
return out;
}
// return the encoded size of a label
inline std::size_t label_size(const label_pair& l)
{
return l.first.size() + sizeof(DELIMITER)
+ l.second.size() + sizeof(DELIMITER);
}
// an output iterator that writes label_pairs to a flat buffer
template <std::contiguous_iterator Iterator>
class label_insert_iterator {
using base_iterator = Iterator;
struct label_writer {
base_iterator pos; // write position
label_writer& operator=(const label_pair& l) {
pos = write(l.first, pos);
pos = write(l.second, pos);
return *this;
}
};
label_writer label;
public:
using difference_type = std::ptrdiff_t;
using value_type = label_writer;
using reference = value_type&;
label_insert_iterator() = default;
label_insert_iterator(base_iterator begin) : label{begin} {
static_assert(std::output_iterator<label_insert_iterator, label_pair>);
}
// increments are noops
label_insert_iterator& operator++() { return *this; }
label_insert_iterator operator++(int) { return *this; }
// can only dereference to assign
reference operator*() { return label; }
// return the wrapped iterator position
base_iterator base() { return label.pos; }
};
// compare label_pairs by their key only
bool label_key_less(const label_pair& lhs, const label_pair& rhs)
{
return lhs.first < rhs.first;
}
bool label_key_equal(const label_pair& lhs, const label_pair& rhs)
{
return lhs.first == rhs.first;
}
std::string create(std::string_view counter_name,
label_pair* begin, label_pair* end)
{
// sort the input labels and remove duplicate keys
std::sort(begin, end, label_key_less);
end = std::unique(begin, end, label_key_equal);
// calculate the total size and preallocate the buffer
auto size = std::accumulate(begin, end,
counter_name.size() + sizeof(DELIMITER),
[] (std::size_t sum, const label_pair& l) {
return sum + label_size(l);
});
std::string result;
result.resize(size);
// copy out the counter name and labels
auto out = result.begin();
out = write(counter_name, out);
std::copy(begin, end, label_insert_iterator{out});
return result;
}
std::string insert(const char* begin1, const char* end1,
label_pair* begin2, label_pair* end2)
{
// sort the input labels and remove duplicate keys
std::sort(begin2, end2, label_key_less);
end2 = std::unique(begin2, end2, label_key_equal);
// find the first delimiter that marks the end of the counter name
auto pos = std::find(begin1, end1, DELIMITER);
// calculate the total size and preallocate the buffer
auto size = std::distance(begin1, end1);
if (pos == end1) { // add a delimiter if the key doesn't have one
size += sizeof(DELIMITER);
}
size = std::accumulate(begin2, end2, size,
[] (std::size_t sum, const label_pair& l) {
return sum + label_size(l);
});
std::string result;
result.resize(size);
// copy the counter name without the delimiter
auto out = std::copy(begin1, pos, result.begin());
if (pos != end1) {
++pos; // advance past the delimiter
}
*(out++) = DELIMITER;
// merge the two sorted input ranges, drop any duplicate keys, and write
// them to output. the begin2 range is first so that new input labels can
// replace existing duplicates
auto end = std::set_union(begin2, end2,
label_iterator{pos, end1},
label_iterator{end1, end1},
label_insert_iterator{out},
label_key_less);
// fix up the size in case set_union() removed any duplicates
result.resize(std::distance(result.begin(), end.base()));
return result;
}
std::string_view name(const char* begin, const char* end)
{
auto pos = std::find(begin, end, DELIMITER);
return {begin, pos};
}
std::string_view labels(const char* begin, const char* end)
{
auto pos = std::find(begin, end, DELIMITER);
if (pos == end) {
return {};
}
return {std::next(pos), end};
}
} // namespace detail
std::string key_create(std::string_view counter_name)
{
label_pair* end = nullptr;
return detail::create(counter_name, end, end);
}
std::string_view key_name(std::string_view key)
{
return detail::name(key.begin(), key.end());
}
label_range key_labels(std::string_view key)
{
return detail::labels(key.begin(), key.end());
}
label_iterator::label_iterator(base_iterator begin, base_iterator end)
: state(make_state(begin, end))
{
static_assert(std::forward_iterator<label_iterator>);
}
void label_iterator::advance(std::optional<iterator_state>& s)
{
auto d = std::find(s->pos, s->end, detail::DELIMITER);
if (d == s->end) { // no delimiter for label key
s = std::nullopt;
return;
}
s->label.first = std::string_view{s->pos, d};
s->pos = std::next(d);
d = std::find(s->pos, s->end, detail::DELIMITER);
if (d == s->end) { // no delimiter for label name
s = std::nullopt;
return;
}
s->label.second = std::string_view{s->pos, d};
s->pos = std::next(d);
}
auto label_iterator::make_state(base_iterator begin, base_iterator end)
-> std::optional<iterator_state>
{
std::optional state = iterator_state{begin, end};
advance(state);
return state;
}
label_iterator& label_iterator::operator++()
{
advance(state);
return *this;
}
label_iterator label_iterator::operator++(int)
{
label_iterator tmp = *this;
advance(state);
return tmp;
}
} // namespace ceph::perf_counters
| 6,091 | 26.075556 | 75 | cc |
null | ceph-main/src/common/perf_counters_key.h | #pragma once
#include <optional>
#include <string>
#include <utility>
namespace ceph::perf_counters {
/// A key/value pair representing a perf counter label
using label_pair = std::pair<std::string_view, std::string_view>;
/// \brief Construct a key for a perf counter and set of labels.
///
/// Returns a string of the form "counter_name\0key1\0val1\0key2\0val2\0",
/// where label pairs are sorted by key with duplicates removed.
///
/// This string representation avoids extra memory allocations associated
/// with map<string, string>. It also supports the hashing and comparison
/// operators required for use as a key in unordered and ordered containers.
///
/// Example:
/// \code
/// std::string key = key_create("counter_name", {
/// {"key1", "val1"}, {"key2", "val2"}
/// });
/// \endcode
template <std::size_t Count>
std::string key_create(std::string_view counter_name,
label_pair (&&labels)[Count]);
/// \brief Construct a key for a perf counter without labels.
/// \overload
std::string key_create(std::string_view counter_name);
/// \brief Insert additional labels into an existing key.
///
/// This returns a new string without modifying the input. The returned
/// string has labels in sorted order and no duplicate keys.
template <std::size_t Count>
std::string key_insert(std::string_view key,
label_pair (&&labels)[Count]);
/// \brief Return the counter name for a given key.
std::string_view key_name(std::string_view key);
/// A forward iterator over label_pairs encoded in a key
class label_iterator {
public:
using base_iterator = const char*;
using difference_type = std::ptrdiff_t;
using value_type = label_pair;
using pointer = const value_type*;
using reference = const value_type&;
label_iterator() = default;
label_iterator(base_iterator begin, base_iterator end);
label_iterator& operator++();
label_iterator operator++(int);
reference operator*() const { return state->label; }
pointer operator->() const { return &state->label; }
auto operator<=>(const label_iterator& rhs) const = default;
private:
struct iterator_state {
base_iterator pos; // end of current label
base_iterator end; // end of buffer
label_pair label; // current label
auto operator<=>(const iterator_state& rhs) const = default;
};
// an empty state represents a past-the-end iterator
std::optional<iterator_state> state;
// find the next two delimiters and construct the label string views
static void advance(std::optional<iterator_state>& s);
// try to parse the first label pair
static auto make_state(base_iterator begin, base_iterator end)
-> std::optional<iterator_state>;
};
/// A sorted range of label_pairs
class label_range {
std::string_view buffer;
public:
using iterator = label_iterator;
using const_iterator = label_iterator;
label_range(std::string_view buffer) : buffer(buffer) {}
const_iterator begin() const { return {buffer.begin(), buffer.end()}; }
const_iterator cbegin() const { return {buffer.begin(), buffer.end()}; }
const_iterator end() const { return {}; }
const_iterator cend() const { return {}; }
};
/// \brief Return the sorted range of label_pairs for a given key.
///
/// Example:
/// \code
/// for (label_pair label : key_labels(key)) {
/// std::cout << label.first << ":" << label.second << std::endl;
/// }
/// \endcode
label_range key_labels(std::string_view key);
namespace detail {
std::string create(std::string_view counter_name,
label_pair* begin, label_pair* end);
std::string insert(const char* begin1, const char* end1,
label_pair* begin2, label_pair* end2);
} // namespace detail
template <std::size_t Count>
std::string key_create(std::string_view counter_name,
label_pair (&&labels)[Count])
{
return detail::create(counter_name, std::begin(labels), std::end(labels));
}
template <std::size_t Count>
std::string key_insert(std::string_view key,
label_pair (&&labels)[Count])
{
return detail::insert(key.begin(), key.end(),
std::begin(labels), std::end(labels));
}
} // namespace ceph::perf_counters
| 4,245 | 29.328571 | 76 | h |
null | ceph-main/src/common/perf_histogram.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 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.
*
*/
#include "common/perf_histogram.h"
#include <limits>
void PerfHistogramCommon::dump_formatted_axis(
ceph::Formatter *f, const PerfHistogramCommon::axis_config_d &ac) {
f->open_object_section("axis");
// Dump axis configuration
f->dump_string("name", ac.m_name);
f->dump_int("min", ac.m_min);
f->dump_int("quant_size", ac.m_quant_size);
f->dump_int("buckets", ac.m_buckets);
switch (ac.m_scale_type) {
case SCALE_LINEAR:
f->dump_string("scale_type", "linear");
break;
case SCALE_LOG2:
f->dump_string("scale_type", "log2");
break;
default:
ceph_assert(false && "Invalid scale type");
}
{
// Dump concrete ranges for axis buckets
f->open_array_section("ranges");
auto ranges = get_axis_bucket_ranges(ac);
for (int i = 0; i < ac.m_buckets; ++i) {
f->open_object_section("bucket");
if (i > 0) {
f->dump_int("min", ranges[i].first);
}
if (i < ac.m_buckets - 1) {
f->dump_int("max", ranges[i].second);
}
f->close_section();
}
f->close_section();
}
f->close_section();
}
int64_t get_quants(int64_t i, PerfHistogramCommon::scale_type_d st) {
switch (st) {
case PerfHistogramCommon::SCALE_LINEAR:
return i;
case PerfHistogramCommon::SCALE_LOG2:
return int64_t(1) << (i - 1);
}
ceph_assert(false && "Invalid scale type");
}
int64_t PerfHistogramCommon::get_bucket_for_axis(
int64_t value, const PerfHistogramCommon::axis_config_d &ac) {
if (value < ac.m_min) {
return 0;
}
value -= ac.m_min;
value /= ac.m_quant_size;
switch (ac.m_scale_type) {
case SCALE_LINEAR:
return std::min<int64_t>(value + 1, ac.m_buckets - 1);
case SCALE_LOG2:
for (int64_t i = 1; i < ac.m_buckets; ++i) {
if (value < get_quants(i, SCALE_LOG2)) {
return i;
}
}
return ac.m_buckets - 1;
}
ceph_assert(false && "Invalid scale type");
}
std::vector<std::pair<int64_t, int64_t>>
PerfHistogramCommon::get_axis_bucket_ranges(
const PerfHistogramCommon::axis_config_d &ac) {
std::vector<std::pair<int64_t, int64_t>> ret;
ret.resize(ac.m_buckets);
// First bucket is for value < min
int64_t min = ac.m_min;
for (int64_t i = 1; i < ac.m_buckets - 1; i++) {
int64_t max_exclusive =
ac.m_min + get_quants(i, ac.m_scale_type) * ac.m_quant_size;
// Dump bucket range
ret[i].first = min;
ret[i].second = max_exclusive - 1;
// Shift min to next bucket
min = max_exclusive;
}
// Fill up first and last element, note that in case m_buckets == 1
// those will point to the same element, the order is important here
ret.front().second = ac.m_min - 1;
ret.back().first = min;
ret.front().first = std::numeric_limits<int64_t>::min();
ret.back().second = std::numeric_limits<int64_t>::max();
return ret;
}
| 3,271 | 25.819672 | 71 | cc |
null | ceph-main/src/common/perf_histogram.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_COMMON_PERF_HISTOGRAM_H
#define CEPH_COMMON_PERF_HISTOGRAM_H
#include <array>
#include <atomic>
#include <memory>
#include "common/Formatter.h"
#include "include/int_types.h"
#include "include/ceph_assert.h"
class PerfHistogramCommon {
public:
enum scale_type_d : uint8_t {
SCALE_LINEAR = 1,
SCALE_LOG2 = 2,
};
struct axis_config_d {
const char *m_name = nullptr;
scale_type_d m_scale_type = SCALE_LINEAR;
int64_t m_min = 0;
int64_t m_quant_size = 0;
int32_t m_buckets = 0;
axis_config_d() = default;
axis_config_d(const char* name,
scale_type_d scale_type,
int64_t min,
int64_t quant_size,
int32_t buckets)
: m_name(name),
m_scale_type(scale_type),
m_min(min),
m_quant_size(quant_size),
m_buckets(buckets)
{}
};
protected:
/// Dump configuration of one axis to a formatter
static void dump_formatted_axis(ceph::Formatter *f, const axis_config_d &ac);
/// Quantize given value and convert to bucket number on given axis
static int64_t get_bucket_for_axis(int64_t value, const axis_config_d &ac);
/// Calculate inclusive ranges of axis values for each bucket on that axis
static std::vector<std::pair<int64_t, int64_t>> get_axis_bucket_ranges(
const axis_config_d &ac);
};
/// PerfHistogram does trace a histogram of input values. It's an extended
/// version of a standard histogram which does trace characteristics of a single
/// one value only. In this implementation, values can be traced in multiple
/// dimensions - i.e. we can create a histogram of input request size (first
/// dimension) and processing latency (second dimension). Creating standard
/// histogram out of such multidimensional one is trivial and requires summing
/// values across dimensions we're not interested in.
template <int DIM = 2>
class PerfHistogram : public PerfHistogramCommon {
public:
/// Initialize new histogram object
PerfHistogram(std::initializer_list<axis_config_d> axes_config) {
ceph_assert(axes_config.size() == DIM &&
"Invalid number of axis configuration objects");
int i = 0;
for (const auto &ac : axes_config) {
ceph_assertf(ac.m_buckets > 0, "Must have at least one bucket on axis");
ceph_assertf(ac.m_quant_size > 0,
"Quantization unit must be non-zero positive integer value");
m_axes_config[i++] = ac;
}
m_rawData.reset(new std::atomic<uint64_t>[get_raw_size()] {});
}
/// Copy from other histogram object
PerfHistogram(const PerfHistogram &other)
: m_axes_config(other.m_axes_config) {
int64_t size = get_raw_size();
m_rawData.reset(new std::atomic<uint64_t>[size] {});
for (int64_t i = 0; i < size; i++) {
m_rawData[i] = other.m_rawData[i].load();
}
}
/// Set all histogram values to 0
void reset() {
auto size = get_raw_size();
for (auto i = size; --i >= 0;) {
m_rawData[i] = 0;
}
}
/// Increase counter for given axis values by one
template <typename... T>
void inc(T... axis) {
auto index = get_raw_index_for_value(axis...);
m_rawData[index]++;
}
/// Increase counter for given axis buckets by one
template <typename... T>
void inc_bucket(T... bucket) {
auto index = get_raw_index_for_bucket(bucket...);
m_rawData[index]++;
}
/// Read value from given bucket
template <typename... T>
uint64_t read_bucket(T... bucket) const {
auto index = get_raw_index_for_bucket(bucket...);
return m_rawData[index];
}
/// Dump data to a Formatter object
void dump_formatted(ceph::Formatter *f) const {
// Dump axes configuration
f->open_array_section("axes");
for (auto &ac : m_axes_config) {
dump_formatted_axis(f, ac);
}
f->close_section();
// Dump histogram values
dump_formatted_values(f);
}
protected:
/// Raw data stored as linear space, internal indexes are calculated on
/// demand.
std::unique_ptr<std::atomic<uint64_t>[]> m_rawData;
/// Configuration of axes
std::array<axis_config_d, DIM> m_axes_config;
/// Dump histogram counters to a formatter
void dump_formatted_values(ceph::Formatter *f) const {
visit_values([f](int) { f->open_array_section("values"); },
[f](int64_t value) { f->dump_unsigned("value", value); },
[f](int) { f->close_section(); });
}
/// Get number of all histogram counters
int64_t get_raw_size() {
int64_t ret = 1;
for (const auto &ac : m_axes_config) {
ret *= ac.m_buckets;
}
return ret;
}
/// Calculate m_rawData index from axis values
template <typename... T>
int64_t get_raw_index_for_value(T... axes) const {
static_assert(sizeof...(T) == DIM, "Incorrect number of arguments");
return get_raw_index_internal<0>(get_bucket_for_axis, 0, axes...);
}
/// Calculate m_rawData index from axis bucket numbers
template <typename... T>
int64_t get_raw_index_for_bucket(T... buckets) const {
static_assert(sizeof...(T) == DIM, "Incorrect number of arguments");
return get_raw_index_internal<0>(
[](int64_t bucket, const axis_config_d &ac) {
ceph_assertf(bucket >= 0, "Bucket index can not be negative");
ceph_assertf(bucket < ac.m_buckets, "Bucket index too large");
return bucket;
},
0, buckets...);
}
template <int level = 0, typename F, typename... T>
int64_t get_raw_index_internal(F bucket_evaluator, int64_t startIndex,
int64_t value, T... tail) const {
static_assert(level + 1 + sizeof...(T) == DIM,
"Internal consistency check");
auto &ac = m_axes_config[level];
auto bucket = bucket_evaluator(value, ac);
return get_raw_index_internal<level + 1>(
bucket_evaluator, ac.m_buckets * startIndex + bucket, tail...);
}
template <int level, typename F>
int64_t get_raw_index_internal(F, int64_t startIndex) const {
static_assert(level == DIM, "Internal consistency check");
return startIndex;
}
/// Visit all histogram counters, call onDimensionEnter / onDimensionLeave
/// when starting / finishing traversal
/// on given axis, call onValue when dumping raw histogram counter value.
template <typename FDE, typename FV, typename FDL>
void visit_values(FDE onDimensionEnter, FV onValue, FDL onDimensionLeave,
int level = 0, int startIndex = 0) const {
if (level == DIM) {
onValue(m_rawData[startIndex]);
return;
}
onDimensionEnter(level);
auto &ac = m_axes_config[level];
startIndex *= ac.m_buckets;
for (int32_t i = 0; i < ac.m_buckets; ++i, ++startIndex) {
visit_values(onDimensionEnter, onValue, onDimensionLeave, level + 1,
startIndex);
}
onDimensionLeave(level);
}
};
#endif
| 7,206 | 30.609649 | 80 | h |
null | ceph-main/src/common/pick_address.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2012 Inktank
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "common/pick_address.h"
#include <bitset>
#include <netdb.h>
#include <netinet/in.h>
#include <string>
#include <string.h>
#include <vector>
#include <boost/algorithm/string/predicate.hpp>
#include <fmt/format.h>
#include "include/ipaddr.h"
#include "include/str_list.h"
#include "common/ceph_context.h"
#ifndef WITH_SEASTAR
#include "common/config.h"
#include "common/config_obs.h"
#endif
#include "common/debug.h"
#include "common/errno.h"
#include "common/numa.h"
#ifndef HAVE_IN_ADDR_T
typedef uint32_t in_addr_t;
#endif
#ifndef IN_LOOPBACKNET
#define IN_LOOPBACKNET 127
#endif
#define dout_subsys ceph_subsys_
using std::string;
using std::vector;
namespace {
bool matches_with_name(const ifaddrs& ifa, const std::string& if_name)
{
return if_name.compare(ifa.ifa_name) == 0;
}
static int is_loopback_addr(sockaddr* addr)
{
if (addr->sa_family == AF_INET) {
const sockaddr_in* sin = (struct sockaddr_in *)(addr);
const in_addr_t net = ntohl(sin->sin_addr.s_addr) >> IN_CLASSA_NSHIFT;
return net == IN_LOOPBACKNET ? 1 : 0;
} else if (addr->sa_family == AF_INET6) {
sockaddr_in6* sin6 = (struct sockaddr_in6 *)(addr);
return IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr) ? 1 : 0;
} else {
return -1;
}
}
static int grade_addr(const ifaddrs& ifa)
{
if (ifa.ifa_addr == nullptr) {
return -1;
}
int score = 0;
if (ifa.ifa_flags & IFF_UP) {
score += 4;
}
switch (is_loopback_addr(ifa.ifa_addr)) {
case 0:
// prefer non-loopback addresses
score += 2;
break;
case 1:
score += 0;
break;
default:
score = -1;
break;
}
return score;
}
bool matches_with_net(const ifaddrs& ifa,
const sockaddr* net,
unsigned int prefix_len,
unsigned ipv)
{
switch (net->sa_family) {
case AF_INET:
if (ipv & CEPH_PICK_ADDRESS_IPV4) {
return matches_ipv4_in_subnet(ifa, (struct sockaddr_in*)net, prefix_len);
}
break;
case AF_INET6:
if (ipv & CEPH_PICK_ADDRESS_IPV6) {
return matches_ipv6_in_subnet(ifa, (struct sockaddr_in6*)net, prefix_len);
}
break;
}
return false;
}
bool matches_with_net(CephContext *cct,
const ifaddrs& ifa,
const std::string& s,
unsigned ipv)
{
struct sockaddr_storage net;
unsigned int prefix_len;
if (!parse_network(s.c_str(), &net, &prefix_len)) {
lderr(cct) << "unable to parse network: " << s << dendl;
exit(1);
}
return matches_with_net(ifa, (sockaddr*)&net, prefix_len, ipv);
}
int grade_with_numa_node(const ifaddrs& ifa, int numa_node)
{
#if defined(WITH_SEASTAR) || defined(_WIN32)
return 0;
#else
if (numa_node < 0) {
return 0;
}
int if_node = -1;
int r = get_iface_numa_node(ifa.ifa_name, &if_node);
if (r < 0) {
return 0;
}
return if_node == numa_node ? 1 : 0;
#endif
}
}
const struct sockaddr *find_ip_in_subnet_list(
CephContext *cct,
const struct ifaddrs *ifa,
unsigned ipv,
const std::string &networks,
const std::string &interfaces,
int numa_node)
{
const auto ifs = get_str_list(interfaces);
const auto nets = get_str_list(networks);
if (!ifs.empty() && nets.empty()) {
lderr(cct) << "interface names specified but not network names" << dendl;
exit(1);
}
int best_score = 0;
const sockaddr* best_addr = nullptr;
for (const auto* addr = ifa; addr != nullptr; addr = addr->ifa_next) {
if (!ifs.empty() &&
std::none_of(std::begin(ifs), std::end(ifs),
[&](const auto& if_name) {
return matches_with_name(*addr, if_name);
})) {
continue;
}
if (!nets.empty() &&
std::none_of(std::begin(nets), std::end(nets),
[&](const auto& net) {
return matches_with_net(cct, *addr, net, ipv);
})) {
continue;
}
int score = grade_addr(*addr);
if (score < 0) {
continue;
}
score += grade_with_numa_node(*addr, numa_node);
if (score > best_score) {
best_score = score;
best_addr = addr->ifa_addr;
}
}
return best_addr;
}
#ifndef WITH_SEASTAR
// observe this change
struct Observer : public md_config_obs_t {
const char *keys[2];
explicit Observer(const char *c) {
keys[0] = c;
keys[1] = NULL;
}
const char** get_tracked_conf_keys() const override {
return (const char **)keys;
}
void handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed) override {
// do nothing.
}
};
static void fill_in_one_address(CephContext *cct,
const struct ifaddrs *ifa,
const string &networks,
const string &interfaces,
const char *conf_var,
int numa_node = -1)
{
const struct sockaddr *found = find_ip_in_subnet_list(
cct,
ifa,
CEPH_PICK_ADDRESS_IPV4|CEPH_PICK_ADDRESS_IPV6,
networks,
interfaces,
numa_node);
if (!found) {
lderr(cct) << "unable to find any IP address in networks '" << networks
<< "' interfaces '" << interfaces << "'" << dendl;
exit(1);
}
char buf[INET6_ADDRSTRLEN];
int err;
err = getnameinfo(found,
(found->sa_family == AF_INET)
? sizeof(struct sockaddr_in)
: sizeof(struct sockaddr_in6),
buf, sizeof(buf),
nullptr, 0,
NI_NUMERICHOST);
if (err != 0) {
lderr(cct) << "unable to convert chosen address to string: " << gai_strerror(err) << dendl;
exit(1);
}
Observer obs(conf_var);
cct->_conf.add_observer(&obs);
cct->_conf.set_val_or_die(conf_var, buf);
cct->_conf.apply_changes(nullptr);
cct->_conf.remove_observer(&obs);
}
void pick_addresses(CephContext *cct, int needs)
{
auto public_addr = cct->_conf.get_val<entity_addr_t>("public_addr");
auto public_network = cct->_conf.get_val<std::string>("public_network");
auto public_network_interface =
cct->_conf.get_val<std::string>("public_network_interface");
auto cluster_addr = cct->_conf.get_val<entity_addr_t>("cluster_addr");
auto cluster_network = cct->_conf.get_val<std::string>("cluster_network");
auto cluster_network_interface =
cct->_conf.get_val<std::string>("cluster_network_interface");
struct ifaddrs *ifa;
int r = getifaddrs(&ifa);
if (r < 0) {
string err = cpp_strerror(errno);
lderr(cct) << "unable to fetch interfaces and addresses: " << err << dendl;
exit(1);
}
auto free_ifa = make_scope_guard([ifa] { freeifaddrs(ifa); });
if ((needs & CEPH_PICK_ADDRESS_PUBLIC) &&
public_addr.is_blank_ip() && !public_network.empty()) {
fill_in_one_address(cct, ifa, public_network, public_network_interface,
"public_addr");
}
if ((needs & CEPH_PICK_ADDRESS_CLUSTER) && cluster_addr.is_blank_ip()) {
if (!cluster_network.empty()) {
fill_in_one_address(cct, ifa, cluster_network, cluster_network_interface,
"cluster_addr");
} else {
if (!public_network.empty()) {
lderr(cct) << "Public network was set, but cluster network was not set " << dendl;
lderr(cct) << " Using public network also for cluster network" << dendl;
fill_in_one_address(cct, ifa, public_network, public_network_interface,
"cluster_addr");
}
}
}
}
#endif // !WITH_SEASTAR
static std::optional<entity_addr_t> get_one_address(
CephContext *cct,
const struct ifaddrs *ifa,
unsigned ipv,
const string &networks,
const string &interfaces,
int numa_node = -1)
{
const struct sockaddr *found = find_ip_in_subnet_list(cct, ifa, ipv,
networks,
interfaces,
numa_node);
if (!found) {
std::string_view ip_type;
if ((ipv & CEPH_PICK_ADDRESS_IPV4) && (ipv & CEPH_PICK_ADDRESS_IPV6)) {
ip_type = "IPv4 or IPv6";
} else if (ipv & CEPH_PICK_ADDRESS_IPV4) {
ip_type = "IPv4";
} else {
ip_type = "IPv6";
}
lderr(cct) << "unable to find any " << ip_type << " address in networks '"
<< networks << "' interfaces '" << interfaces << "'" << dendl;
return {};
}
char buf[INET6_ADDRSTRLEN];
int err;
err = getnameinfo(found,
(found->sa_family == AF_INET)
? sizeof(struct sockaddr_in)
: sizeof(struct sockaddr_in6),
buf, sizeof(buf),
nullptr, 0,
NI_NUMERICHOST);
if (err != 0) {
lderr(cct) << "unable to convert chosen address to string: " << gai_strerror(err) << dendl;
return {};
}
entity_addr_t addr;
if (addr.parse(buf)) {
return addr;
} else {
return {};
}
}
int pick_addresses(
CephContext *cct,
unsigned flags,
struct ifaddrs *ifa,
entity_addrvec_t *addrs,
int preferred_numa_node)
{
addrs->v.clear();
unsigned addrt = (flags & (CEPH_PICK_ADDRESS_PUBLIC |
CEPH_PICK_ADDRESS_PUBLIC_BIND |
CEPH_PICK_ADDRESS_CLUSTER));
// TODO: move to std::popcount when it's available for all release lines
// we are interested in (quincy was a blocker at the time of writing)
if (std::bitset<sizeof(addrt)*CHAR_BIT>(addrt).count() != 1) {
// these flags are mutually exclusive and one of them must be
// always set (in other words: it's mode selection).
return -EINVAL;
}
unsigned msgrv = flags & (CEPH_PICK_ADDRESS_MSGR1 |
CEPH_PICK_ADDRESS_MSGR2);
if (msgrv == 0) {
if (cct->_conf.get_val<bool>("ms_bind_msgr1")) {
msgrv |= CEPH_PICK_ADDRESS_MSGR1;
}
if (cct->_conf.get_val<bool>("ms_bind_msgr2")) {
msgrv |= CEPH_PICK_ADDRESS_MSGR2;
}
if (msgrv == 0) {
return -EINVAL;
}
}
unsigned ipv = flags & (CEPH_PICK_ADDRESS_IPV4 |
CEPH_PICK_ADDRESS_IPV6);
if (ipv == 0) {
if (cct->_conf.get_val<bool>("ms_bind_ipv4")) {
ipv |= CEPH_PICK_ADDRESS_IPV4;
}
if (cct->_conf.get_val<bool>("ms_bind_ipv6")) {
ipv |= CEPH_PICK_ADDRESS_IPV6;
}
if (ipv == 0) {
return -EINVAL;
}
if (cct->_conf.get_val<bool>("ms_bind_prefer_ipv4")) {
flags |= CEPH_PICK_ADDRESS_PREFER_IPV4;
} else {
flags &= ~CEPH_PICK_ADDRESS_PREFER_IPV4;
}
}
entity_addr_t addr;
string networks;
string interfaces;
if (addrt & CEPH_PICK_ADDRESS_PUBLIC) {
addr = cct->_conf.get_val<entity_addr_t>("public_addr");
networks = cct->_conf.get_val<std::string>("public_network");
interfaces =
cct->_conf.get_val<std::string>("public_network_interface");
} else if (addrt & CEPH_PICK_ADDRESS_PUBLIC_BIND) {
addr = cct->_conf.get_val<entity_addr_t>("public_bind_addr");
// XXX: we don't support _network nor _network_interface for
// the public_bind addrs yet.
if (addr.is_blank_ip()) {
return -ENOENT;
}
} else {
addr = cct->_conf.get_val<entity_addr_t>("cluster_addr");
networks = cct->_conf.get_val<std::string>("cluster_network");
interfaces =
cct->_conf.get_val<std::string>("cluster_network_interface");
if (networks.empty()) {
lderr(cct) << "Falling back to public interface" << dendl;
// fall back to public_ network and interface if cluster is not set
networks = cct->_conf.get_val<std::string>("public_network");
interfaces =
cct->_conf.get_val<std::string>("public_network_interface");
}
}
if (addr.is_blank_ip() &&
!networks.empty()) {
// note: pass in ipv to filter the matching addresses
for (auto pick_mask : {CEPH_PICK_ADDRESS_IPV4, CEPH_PICK_ADDRESS_IPV6}) {
if (ipv & pick_mask) {
auto ip_addr = get_one_address(cct, ifa, pick_mask,
networks, interfaces,
preferred_numa_node);
if (ip_addr) {
addrs->v.push_back(*ip_addr);
} else {
// picked but not found
return -1;
}
}
}
}
// note: we may have a blank addr here
// ipv4 and/or ipv6?
if (addrs->v.empty()) {
addr.set_type(entity_addr_t::TYPE_MSGR2);
for (auto pick_mask : {CEPH_PICK_ADDRESS_IPV4, CEPH_PICK_ADDRESS_IPV6}) {
if (ipv & pick_mask) {
addr.set_family(pick_mask == CEPH_PICK_ADDRESS_IPV4 ? AF_INET : AF_INET6);
addrs->v.push_back(addr);
}
}
}
std::sort(addrs->v.begin(), addrs->v.end(),
[flags] (entity_addr_t& lhs, entity_addr_t& rhs) {
if (flags & CEPH_PICK_ADDRESS_PREFER_IPV4) {
return lhs.is_ipv4() && rhs.is_ipv6();
} else {
return lhs.is_ipv6() && rhs.is_ipv4();
}
});
// msgr2 or legacy or both?
if (msgrv == (CEPH_PICK_ADDRESS_MSGR1 | CEPH_PICK_ADDRESS_MSGR2)) {
vector<entity_addr_t> v;
v.swap(addrs->v);
for (auto a : v) {
a.set_type(entity_addr_t::TYPE_MSGR2);
if (flags & CEPH_PICK_ADDRESS_DEFAULT_MON_PORTS) {
a.set_port(CEPH_MON_PORT_IANA);
}
addrs->v.push_back(a);
a.set_type(entity_addr_t::TYPE_LEGACY);
if (flags & CEPH_PICK_ADDRESS_DEFAULT_MON_PORTS) {
a.set_port(CEPH_MON_PORT_LEGACY);
}
addrs->v.push_back(a);
}
} else if (msgrv == CEPH_PICK_ADDRESS_MSGR1) {
for (auto& a : addrs->v) {
a.set_type(entity_addr_t::TYPE_LEGACY);
}
} else {
for (auto& a : addrs->v) {
a.set_type(entity_addr_t::TYPE_MSGR2);
}
}
return 0;
}
int pick_addresses(
CephContext *cct,
unsigned flags,
entity_addrvec_t *addrs,
int preferred_numa_node)
{
struct ifaddrs *ifa;
int r = getifaddrs(&ifa);
if (r < 0) {
r = -errno;
string err = cpp_strerror(r);
lderr(cct) << "unable to fetch interfaces and addresses: "
<< cpp_strerror(r) << dendl;
return r;
}
r = pick_addresses(cct, flags, ifa, addrs, preferred_numa_node);
freeifaddrs(ifa);
return r;
}
std::string pick_iface(CephContext *cct, const struct sockaddr_storage &network)
{
struct ifaddrs *ifa;
int r = getifaddrs(&ifa);
if (r < 0) {
string err = cpp_strerror(errno);
lderr(cct) << "unable to fetch interfaces and addresses: " << err << dendl;
return {};
}
auto free_ifa = make_scope_guard([ifa] { freeifaddrs(ifa); });
const unsigned int prefix_len = std::max(sizeof(in_addr::s_addr), sizeof(in6_addr::s6_addr)) * CHAR_BIT;
for (auto addr = ifa; addr != nullptr; addr = addr->ifa_next) {
if (matches_with_net(*ifa, (const struct sockaddr *) &network, prefix_len,
CEPH_PICK_ADDRESS_IPV4 | CEPH_PICK_ADDRESS_IPV6)) {
return addr->ifa_name;
}
}
return {};
}
bool have_local_addr(CephContext *cct, const std::list<entity_addr_t>& ls, entity_addr_t *match)
{
struct ifaddrs *ifa;
int r = getifaddrs(&ifa);
if (r < 0) {
lderr(cct) << "unable to fetch interfaces and addresses: " << cpp_strerror(errno) << dendl;
exit(1);
}
auto free_ifa = make_scope_guard([ifa] { freeifaddrs(ifa); });
for (struct ifaddrs *addrs = ifa; addrs != nullptr; addrs = addrs->ifa_next) {
if (addrs->ifa_addr) {
entity_addr_t a;
a.set_sockaddr(addrs->ifa_addr);
for (auto& p : ls) {
if (a.is_same_host(p)) {
*match = p;
return true;
}
}
}
}
return false;
}
int get_iface_numa_node(
const std::string& iface,
int *node)
{
enum class iface_t {
PHY_PORT,
BOND_PORT
} ifatype = iface_t::PHY_PORT;
std::string_view ifa{iface};
if (auto pos = ifa.find(":"); pos != ifa.npos) {
ifa.remove_suffix(ifa.size() - pos);
}
string fn = fmt::format("/sys/class/net/{}/device/numa_node", ifa);
int fd = ::open(fn.c_str(), O_RDONLY);
if (fd < 0) {
fn = fmt::format("/sys/class/net/{}/bonding/slaves", ifa);
fd = ::open(fn.c_str(), O_RDONLY);
if (fd < 0) {
return -errno;
}
ifatype = iface_t::BOND_PORT;
}
int r = 0;
char buf[1024];
char *endptr = 0;
r = safe_read(fd, &buf, sizeof(buf));
if (r < 0) {
goto out;
}
buf[r] = 0;
while (r > 0 && ::isspace(buf[--r])) {
buf[r] = 0;
}
switch (ifatype) {
case iface_t::PHY_PORT:
*node = strtoll(buf, &endptr, 10);
if (endptr != buf + strlen(buf)) {
r = -EINVAL;
goto out;
}
r = 0;
break;
case iface_t::BOND_PORT:
int bond_node = -1;
std::vector<std::string> sv;
std::string ifacestr = buf;
get_str_vec(ifacestr, " ", sv);
for (auto& iter : sv) {
int bn = -1;
r = get_iface_numa_node(iter, &bn);
if (r >= 0) {
if (bond_node == -1 || bn == bond_node) {
bond_node = bn;
} else {
*node = -2;
goto out;
}
} else {
goto out;
}
}
*node = bond_node;
break;
}
out:
::close(fd);
return r;
}
| 16,939 | 25.719243 | 106 | cc |
null | ceph-main/src/common/pick_address.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_PICK_ADDRESS_H
#define CEPH_PICK_ADDRESS_H
#include <string>
#include <list>
#include "include/common_fwd.h"
struct entity_addr_t;
class entity_addrvec_t;
#define CEPH_PICK_ADDRESS_PUBLIC 0x01
#define CEPH_PICK_ADDRESS_CLUSTER 0x02
#define CEPH_PICK_ADDRESS_MSGR1 0x04
#define CEPH_PICK_ADDRESS_MSGR2 0x08
#define CEPH_PICK_ADDRESS_IPV4 0x10
#define CEPH_PICK_ADDRESS_IPV6 0x20
#define CEPH_PICK_ADDRESS_PREFER_IPV4 0x40
#define CEPH_PICK_ADDRESS_DEFAULT_MON_PORTS 0x80
#define CEPH_PICK_ADDRESS_PUBLIC_BIND 0x100
#ifndef WITH_SEASTAR
/*
Pick addresses based on subnets if needed.
If an address is not explicitly given, and a list of subnets is
given, find an assigned IP address in the subnets and set that.
cluster_addr is set based on cluster_network, public_addr is set
based on public_network.
cluster_network and public_network are a list of ip/prefix pairs.
All IP addresses assigned to all local network interfaces are
potential matches.
If multiple IP addresses match the subnet, one of them will be
picked, effectively randomly.
This function will exit on error.
*/
void pick_addresses(CephContext *cct, int needs);
#endif // !WITH_SEASTAR
int pick_addresses(CephContext *cct, unsigned flags, entity_addrvec_t *addrs,
int preferred_numa_node = -1);
int pick_addresses(CephContext *cct, unsigned flags, struct ifaddrs *ifa,
entity_addrvec_t *addrs,
int preferred_numa_node = -1);
/**
* Find a network interface whose address matches the address/netmask
* in `network`.
*/
std::string pick_iface(CephContext *cct, const struct sockaddr_storage &network);
/**
* check for a locally configured address
*
* check if any of the listed addresses is configured on the local host.
*
* @param cct context
* @param ls list of addresses
* @param match [out] pointer to match, if an item in @a ls is found configured locally.
*/
bool have_local_addr(CephContext *cct, const std::list<entity_addr_t>& ls, entity_addr_t *match);
/**
* filter the addresses in @c ifa with specified interfaces, networks and IPv
*
* @param cct
* @param ifa a list of network interface addresses to be filtered
* @param ipv bitmask of CEPH_PICK_ADDRESS_IPV4 and CEPH_PICK_ADDRESS_IPV6.
* it is used to filter the @c networks
* @param networks a comma separated list of networks as the allow list. only
* the addresses in the specified networks are allowed. all addresses
* are accepted if it is empty.
* @param interfaces a comma separated list of interfaces for the allow list.
* all addresses are accepted if it is empty
* @param exclude_lo_iface filter out network interface named "lo"
*/
const struct sockaddr *find_ip_in_subnet_list(
CephContext *cct,
const struct ifaddrs *ifa,
unsigned ipv,
const std::string &networks,
const std::string &interfaces,
int numa_node=-1);
int get_iface_numa_node(
const std::string& iface,
int *node);
#endif
| 3,094 | 30.262626 | 97 | h |
null | ceph-main/src/common/ppc-asm.h | /* PowerPC asm definitions for GNU C.
Copyright (C) 2002-2017 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
/* Under winnt, 1) gas supports the following as names and 2) in particular
defining "toc" breaks the FUNC_START macro as ".toc" becomes ".2" */
#define r0 0
#define sp 1
#define toc 2
#define r3 3
#define r4 4
#define r5 5
#define r6 6
#define r7 7
#define r8 8
#define r9 9
#define r10 10
#define r11 11
#define r12 12
#define r13 13
#define r14 14
#define r15 15
#define r16 16
#define r17 17
#define r18 18
#define r19 19
#define r20 20
#define r21 21
#define r22 22
#define r23 23
#define r24 24
#define r25 25
#define r26 26
#define r27 27
#define r28 28
#define r29 29
#define r30 30
#define r31 31
#define cr0 0
#define cr1 1
#define cr2 2
#define cr3 3
#define cr4 4
#define cr5 5
#define cr6 6
#define cr7 7
#define f0 0
#define f1 1
#define f2 2
#define f3 3
#define f4 4
#define f5 5
#define f6 6
#define f7 7
#define f8 8
#define f9 9
#define f10 10
#define f11 11
#define f12 12
#define f13 13
#define f14 14
#define f15 15
#define f16 16
#define f17 17
#define f18 18
#define f19 19
#define f20 20
#define f21 21
#define f22 22
#define f23 23
#define f24 24
#define f25 25
#define f26 26
#define f27 27
#define f28 28
#define f29 29
#define f30 30
#define f31 31
#ifdef __VSX__
#define f32 32
#define f33 33
#define f34 34
#define f35 35
#define f36 36
#define f37 37
#define f38 38
#define f39 39
#define f40 40
#define f41 41
#define f42 42
#define f43 43
#define f44 44
#define f45 45
#define f46 46
#define f47 47
#define f48 48
#define f49 49
#define f50 30
#define f51 51
#define f52 52
#define f53 53
#define f54 54
#define f55 55
#define f56 56
#define f57 57
#define f58 58
#define f59 59
#define f60 60
#define f61 61
#define f62 62
#define f63 63
#endif
#ifdef __ALTIVEC__
#define v0 0
#define v1 1
#define v2 2
#define v3 3
#define v4 4
#define v5 5
#define v6 6
#define v7 7
#define v8 8
#define v9 9
#define v10 10
#define v11 11
#define v12 12
#define v13 13
#define v14 14
#define v15 15
#define v16 16
#define v17 17
#define v18 18
#define v19 19
#define v20 20
#define v21 21
#define v22 22
#define v23 23
#define v24 24
#define v25 25
#define v26 26
#define v27 27
#define v28 28
#define v29 29
#define v30 30
#define v31 31
#endif
#ifdef __VSX__
#define vs0 0
#define vs1 1
#define vs2 2
#define vs3 3
#define vs4 4
#define vs5 5
#define vs6 6
#define vs7 7
#define vs8 8
#define vs9 9
#define vs10 10
#define vs11 11
#define vs12 12
#define vs13 13
#define vs14 14
#define vs15 15
#define vs16 16
#define vs17 17
#define vs18 18
#define vs19 19
#define vs20 20
#define vs21 21
#define vs22 22
#define vs23 23
#define vs24 24
#define vs25 25
#define vs26 26
#define vs27 27
#define vs28 28
#define vs29 29
#define vs30 30
#define vs31 31
#define vs32 32
#define vs33 33
#define vs34 34
#define vs35 35
#define vs36 36
#define vs37 37
#define vs38 38
#define vs39 39
#define vs40 40
#define vs41 41
#define vs42 42
#define vs43 43
#define vs44 44
#define vs45 45
#define vs46 46
#define vs47 47
#define vs48 48
#define vs49 49
#define vs50 30
#define vs51 51
#define vs52 52
#define vs53 53
#define vs54 54
#define vs55 55
#define vs56 56
#define vs57 57
#define vs58 58
#define vs59 59
#define vs60 60
#define vs61 61
#define vs62 62
#define vs63 63
#endif
/*
* Macros to glue together two tokens.
*/
#ifdef __STDC__
#define XGLUE(a,b) a##b
#else
#define XGLUE(a,b) a/**/b
#endif
#define GLUE(a,b) XGLUE(a,b)
/*
* Macros to begin and end a function written in assembler. If -mcall-aixdesc
* or -mcall-nt, create a function descriptor with the given name, and create
* the real function with one or two leading periods respectively.
*/
#if defined(__powerpc64__) && _CALL_ELF == 2
/* Defining "toc" above breaks @toc in assembler code. */
#undef toc
#define FUNC_NAME(name) GLUE(__USER_LABEL_PREFIX__,name)
#define JUMP_TARGET(name) FUNC_NAME(name)
#define FUNC_START(name) \
.type FUNC_NAME(name),@function; \
.globl FUNC_NAME(name); \
FUNC_NAME(name): \
0: addis 2,12,(.TOC.-0b)@ha; \
addi 2,2,(.TOC.-0b)@l; \
.localentry FUNC_NAME(name),.-FUNC_NAME(name)
#define HIDDEN_FUNC(name) \
FUNC_START(name) \
.hidden FUNC_NAME(name);
#define FUNC_END(name) \
.size FUNC_NAME(name),.-FUNC_NAME(name)
#elif defined (__powerpc64__)
#define FUNC_NAME(name) GLUE(.,name)
#define JUMP_TARGET(name) FUNC_NAME(name)
#define FUNC_START(name) \
.section ".opd","aw"; \
name: \
.quad GLUE(.,name); \
.quad .TOC.@tocbase; \
.quad 0; \
.previous; \
.type GLUE(.,name),@function; \
.globl name; \
.globl GLUE(.,name); \
GLUE(.,name):
#define HIDDEN_FUNC(name) \
FUNC_START(name) \
.hidden name; \
.hidden GLUE(.,name);
#define FUNC_END(name) \
GLUE(.L,name): \
.size GLUE(.,name),GLUE(.L,name)-GLUE(.,name)
#elif defined(_CALL_AIXDESC)
#ifdef _RELOCATABLE
#define DESC_SECTION ".got2"
#else
#define DESC_SECTION ".got1"
#endif
#define FUNC_NAME(name) GLUE(.,name)
#define JUMP_TARGET(name) FUNC_NAME(name)
#define FUNC_START(name) \
.section DESC_SECTION,"aw"; \
name: \
.long GLUE(.,name); \
.long _GLOBAL_OFFSET_TABLE_; \
.long 0; \
.previous; \
.type GLUE(.,name),@function; \
.globl name; \
.globl GLUE(.,name); \
GLUE(.,name):
#define HIDDEN_FUNC(name) \
FUNC_START(name) \
.hidden name; \
.hidden GLUE(.,name);
#define FUNC_END(name) \
GLUE(.L,name): \
.size GLUE(.,name),GLUE(.L,name)-GLUE(.,name)
#else
#define FUNC_NAME(name) GLUE(__USER_LABEL_PREFIX__,name)
#if defined __PIC__ || defined __pic__
#define JUMP_TARGET(name) FUNC_NAME(name@plt)
#else
#define JUMP_TARGET(name) FUNC_NAME(name)
#endif
#define FUNC_START(name) \
.type FUNC_NAME(name),@function; \
.globl FUNC_NAME(name); \
FUNC_NAME(name):
#define HIDDEN_FUNC(name) \
FUNC_START(name) \
.hidden FUNC_NAME(name);
#define FUNC_END(name) \
GLUE(.L,name): \
.size FUNC_NAME(name),GLUE(.L,name)-FUNC_NAME(name)
#endif
#ifdef IN_GCC
/* For HAVE_GAS_CFI_DIRECTIVE. */
#include "auto-host.h"
#ifdef HAVE_GAS_CFI_DIRECTIVE
# define CFI_STARTPROC .cfi_startproc
# define CFI_ENDPROC .cfi_endproc
# define CFI_OFFSET(reg, off) .cfi_offset reg, off
# define CFI_DEF_CFA_REGISTER(reg) .cfi_def_cfa_register reg
# define CFI_RESTORE(reg) .cfi_restore reg
#else
# define CFI_STARTPROC
# define CFI_ENDPROC
# define CFI_OFFSET(reg, off)
# define CFI_DEF_CFA_REGISTER(reg)
# define CFI_RESTORE(reg)
#endif
#endif
#if defined __linux__
.section .note.GNU-stack
.previous
#endif
| 7,342 | 18.222513 | 78 | h |
null | ceph-main/src/common/ppc-opcode.h | /*
* Copyright (C) 2015 Anton Blanchard <[email protected]>, IBM
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of either:
*
* a) the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version, or
* b) the Apache License, Version 2.0
*/
#ifndef __OPCODES_H
#define __OPCODES_H
#define __PPC_RA(a) (((a) & 0x1f) << 16)
#define __PPC_RB(b) (((b) & 0x1f) << 11)
#define __PPC_XA(a) ((((a) & 0x1f) << 16) | (((a) & 0x20) >> 3))
#define __PPC_XB(b) ((((b) & 0x1f) << 11) | (((b) & 0x20) >> 4))
#define __PPC_XS(s) ((((s) & 0x1f) << 21) | (((s) & 0x20) >> 5))
#define __PPC_XT(s) __PPC_XS(s)
#define VSX_XX3(t, a, b) (__PPC_XT(t) | __PPC_XA(a) | __PPC_XB(b))
#define VSX_XX1(s, a, b) (__PPC_XS(s) | __PPC_RA(a) | __PPC_RB(b))
#define PPC_INST_VPMSUMW 0x10000488
#define PPC_INST_VPMSUMD 0x100004c8
#define PPC_INST_MFVSRD 0x7c000066
#define PPC_INST_MTVSRD 0x7c000166
#define VPMSUMW(t, a, b) .long PPC_INST_VPMSUMW | VSX_XX3((t), a, b)
#define VPMSUMD(t, a, b) .long PPC_INST_VPMSUMD | VSX_XX3((t), a, b)
#define MFVRD(a, t) .long PPC_INST_MFVSRD | VSX_XX1((t)+32, a, 0)
#define MTVRD(t, a) .long PPC_INST_MTVSRD | VSX_XX1((t)+32, a, 0)
#endif
/* Copyright (C) 2017 International Business Machines Corp.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#ifndef __OPCODES_H
#define __OPCODES_H
#define __PPC_RA(a) (((a) & 0x1f) << 16)
#define __PPC_RB(b) (((b) & 0x1f) << 11)
#define __PPC_XA(a) ((((a) & 0x1f) << 16) | (((a) & 0x20) >> 3))
#define __PPC_XB(b) ((((b) & 0x1f) << 11) | (((b) & 0x20) >> 4))
#define __PPC_XS(s) ((((s) & 0x1f) << 21) | (((s) & 0x20) >> 5))
#define __PPC_XT(s) __PPC_XS(s)
#define VSX_XX3(t, a, b) (__PPC_XT(t) | __PPC_XA(a) | __PPC_XB(b))
#define VSX_XX1(s, a, b) (__PPC_XS(s) | __PPC_RA(a) | __PPC_RB(b))
#define PPC_INST_VPMSUMW 0x10000488
#define PPC_INST_VPMSUMD 0x100004c8
#define PPC_INST_MFVSRD 0x7c000066
#define PPC_INST_MTVSRD 0x7c000166
#define VPMSUMW(t, a, b) .long PPC_INST_VPMSUMW | VSX_XX3((t), a, b)
#define VPMSUMD(t, a, b) .long PPC_INST_VPMSUMD | VSX_XX3((t), a, b)
#define MFVRD(a, t) .long PPC_INST_MFVSRD | VSX_XX1((t)+32, a, 0)
#define MTVRD(t, a) .long PPC_INST_MTVSRD | VSX_XX1((t)+32, a, 0)
#endif
| 2,567 | 37.909091 | 71 | h |
null | ceph-main/src/common/pretty_binary.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "pretty_binary.h"
#include <stdexcept>
#include <sstream>
std::string pretty_binary_string_reverse(const std::string& pretty)
{
size_t i = 0;
auto raise = [&](size_t failpos) {
std::ostringstream ss;
ss << "invalid char at pos " << failpos << " of " << pretty;
throw std::invalid_argument(ss.str());
};
auto hexdigit = [&](unsigned char c) -> int32_t {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
auto require = [&](unsigned char c) {
if (i >= pretty.length() || pretty[i] != c) {
raise(i);
}
++i;
};
std::string bin;
if (pretty.empty())
return bin;
bin.reserve(pretty.length());
bool strmode;
switch (pretty[0]) {
case '\'':
++i;
strmode = true;
break;
case '0':
++i;
require('x');
if (i == pretty.length()) {
raise(i);
}
strmode = false;
break;
default:
raise(0);
}
for (; i < pretty.length();) {
if (strmode) {
if (pretty[i] == '\'') {
if (i + 1 < pretty.length() && pretty[i + 1] == '\'') {
bin.push_back('\'');
i += 2;
} else {
++i;
strmode = false;
if (i + 1 < pretty.length()) {
require('0');
require('x');
if (i == pretty.length()) {
raise(i);
}
}
}
} else {
bin.push_back(pretty[i]);
++i;
}
} else {
if (pretty[i] != '\'') {
int32_t hex0 = hexdigit(pretty[i]);
if (hex0 < 0) {
raise(i);
}
++i;
if (i >= pretty.length()) {
raise(i);
}
int32_t hex1 = hexdigit(pretty[i]);
if (hex1 < 0) {
raise(i);
}
bin.push_back(hex0 * 0x10 + hex1);
++i;
} else {
strmode = true;
++i;
}
}
}
if (strmode)
raise(i);
return bin;
}
| 1,916 | 18.96875 | 70 | cc |
null | ceph-main/src/common/pretty_binary.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <string>
template<typename S>
static std::string pretty_binary_string(const S& bin)
{
std::string pretty;
if (bin.empty())
return pretty;
pretty.reserve(bin.length() * 3);
auto printable = [](unsigned char c) -> bool {
return (c >= 32) && (c <= 126);
};
auto append_hex = [&](unsigned char c) {
static const char hex[16] = {'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'A', 'B',
'C', 'D', 'E', 'F'};
pretty.push_back(hex[c / 16]);
pretty.push_back(hex[c % 16]);
};
// prologue
bool strmode = printable(bin[0]);
if (strmode) {
pretty.push_back('\'');
} else {
pretty.push_back('0');
pretty.push_back('x');
}
for (size_t i = 0; i < bin.length(); ++i) {
// change mode from hex to str if following 3 characters are printable
if (strmode) {
if (!printable(bin[i])) {
pretty.push_back('\'');
pretty.push_back('0');
pretty.push_back('x');
strmode = false;
}
} else {
if (i + 2 < bin.length() &&
printable(bin[i]) &&
printable(bin[i + 1]) &&
printable(bin[i + 2])) {
pretty.push_back('\'');
strmode = true;
}
}
if (strmode) {
if (bin[i] == '\'')
pretty.push_back('\'');
pretty.push_back(bin[i]);
} else {
append_hex(bin[i]);
}
}
// epilog
if (strmode) {
pretty.push_back('\'');
}
return pretty;
}
std::string pretty_binary_string_reverse(const std::string& pretty);
| 1,561 | 21.970588 | 74 | h |
null | ceph-main/src/common/ptr_wrapper.h |
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, 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
template <typename T, int id>
struct ptr_wrapper
{
T *_p;
ptr_wrapper(T *v) : _p(v) {}
ptr_wrapper() : _p(nullptr) {}
T *operator=(T *p) {
_p = p;
return p;
}
T& operator*() {
return *_p;
}
T* operator->() {
return _p;
}
T *get() {
return _p;
}
};
| 717 | 14.608696 | 70 | h |
null | ceph-main/src/common/random_string.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <string_view>
#include "auth/Crypto.h"
#include "common/armor.h"
#include "common/ceph_context.h"
#include "common/dout.h"
#include "random_string.h"
int gen_rand_base64(CephContext *cct, char *dest, size_t size) /* size should be the required string size + 1 */
{
char buf[size];
char tmp_dest[size + 4]; /* so that there's space for the extra '=' characters, and some */
int ret;
cct->random()->get_bytes(buf, sizeof(buf));
ret = ceph_armor(tmp_dest, &tmp_dest[sizeof(tmp_dest)],
(const char *)buf, ((const char *)buf) + ((size - 1) * 3 + 4 - 1) / 4);
if (ret < 0) {
lderr(cct) << "ceph_armor failed" << dendl;
return ret;
}
tmp_dest[ret] = '\0';
memcpy(dest, tmp_dest, size);
dest[size-1] = '\0';
return 0;
}
// choose 'size' random characters from the given string table
static void choose_from(CryptoRandom* random, std::string_view table,
char *dest, size_t size)
{
random->get_bytes(dest, size);
for (size_t i = 0; i < size; i++) {
auto pos = static_cast<unsigned>(dest[i]);
dest[i] = table[pos % table.size()];
}
}
void gen_rand_alphanumeric(CephContext *cct, char *dest, size_t size) /* size should be the required string size + 1 */
{
// this is basically a modified base64 charset, url friendly
static constexpr char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
choose_from(cct->random(), table, dest, size-1);
dest[size-1] = 0;
}
std::string gen_rand_alphanumeric(CephContext *cct, size_t size)
{
std::string str;
str.resize(size + 1);
gen_rand_alphanumeric(cct, str.data(), str.size());
str.pop_back(); // pop the extra \0
return str;
}
void gen_rand_alphanumeric_lower(CephContext *cct, char *dest, size_t size) /* size should be the required string size + 1 */
{
static constexpr char table[] = "0123456789abcdefghijklmnopqrstuvwxyz";
choose_from(cct->random(), table, dest, size-1);
dest[size-1] = 0;
}
std::string gen_rand_alphanumeric_lower(CephContext *cct, size_t size)
{
std::string str;
str.resize(size + 1);
gen_rand_alphanumeric_lower(cct, str.data(), str.size());
str.pop_back(); // pop the extra \0
return str;
}
void gen_rand_alphanumeric_upper(CephContext *cct, char *dest, size_t size) /* size should be the required string size + 1 */
{
static constexpr char table[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
choose_from(cct->random(), table, dest, size-1);
dest[size-1] = 0;
}
std::string gen_rand_alphanumeric_upper(CephContext *cct, size_t size)
{
std::string str;
str.resize(size + 1);
gen_rand_alphanumeric_upper(cct, str.data(), str.size());
str.pop_back(); // pop the extra \0
return str;
}
void gen_rand_alphanumeric_no_underscore(CephContext *cct, char *dest, size_t size) /* size should be the required string size + 1 */
{
static constexpr char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";
choose_from(cct->random(), table, dest, size-1);
dest[size-1] = 0;
}
std::string gen_rand_alphanumeric_no_underscore(CephContext *cct, size_t size)
{
std::string str;
str.resize(size + 1);
gen_rand_alphanumeric_no_underscore(cct, str.data(), str.size());
str.pop_back(); // pop the extra \0
return str;
}
void gen_rand_alphanumeric_plain(CephContext *cct, char *dest, size_t size) /* size should be the required string size + 1 */
{
static constexpr char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
choose_from(cct->random(), table, dest, size-1);
dest[size-1] = 0;
}
std::string gen_rand_alphanumeric_plain(CephContext *cct, size_t size)
{
std::string str;
str.resize(size + 1);
gen_rand_alphanumeric_plain(cct, str.data(), str.size());
str.pop_back(); // pop the extra \0
return str;
}
| 3,907 | 29.53125 | 133 | cc |
null | ceph-main/src/common/random_string.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2009 Sage Weil <[email protected]>
* Copyright (C) 2015 Yehuda Sadeh <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <string>
#include "include/common_fwd.h"
/* size should be the required string size + 1 */
int gen_rand_base64(CephContext *cct, char *dest, size_t size);
void gen_rand_alphanumeric(CephContext *cct, char *dest, size_t size);
void gen_rand_alphanumeric_lower(CephContext *cct, char *dest, size_t size);
void gen_rand_alphanumeric_upper(CephContext *cct, char *dest, size_t size);
void gen_rand_alphanumeric_no_underscore(CephContext *cct, char *dest, size_t size);
void gen_rand_alphanumeric_plain(CephContext *cct, char *dest, size_t size);
// returns a std::string with 'size' random characters
std::string gen_rand_alphanumeric(CephContext *cct, size_t size);
std::string gen_rand_alphanumeric_lower(CephContext *cct, size_t size);
std::string gen_rand_alphanumeric_upper(CephContext *cct, size_t size);
std::string gen_rand_alphanumeric_no_underscore(CephContext *cct, size_t size);
std::string gen_rand_alphanumeric_plain(CephContext *cct, size_t size);
| 1,473 | 39.944444 | 84 | h |
null | ceph-main/src/common/ref.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef COMMON_REF_H
#define COMMON_REF_H
#include <boost/intrusive_ptr.hpp>
namespace ceph {
template<typename T> using ref_t = boost::intrusive_ptr<T>;
template<typename T> using cref_t = boost::intrusive_ptr<const T>;
template<class T, class U>
ref_t<T> ref_cast(const ref_t<U>& r) noexcept {
return static_cast<T*>(r.get());
}
template<class T, class U>
ref_t<T> ref_cast(ref_t<U>&& r) noexcept {
return {static_cast<T*>(r.detach()), false};
}
template<class T, class U>
cref_t<T> ref_cast(const cref_t<U>& r) noexcept {
return static_cast<const T*>(r.get());
}
template<class T, typename... Args>
ceph::ref_t<T> make_ref(Args&&... args) {
return {new T(std::forward<Args>(args)...), false};
}
}
// Friends cannot be partial specializations: https://en.cppreference.com/w/cpp/language/friend
#define FRIEND_MAKE_REF(C) \
template<class T, typename... Args> friend ceph::ref_t<T> ceph::make_ref(Args&&... args)
#endif
| 1,032 | 28.514286 | 95 | h |
null | ceph-main/src/common/reverse.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_OS_REVERSE_H
#define __CEPH_OS_REVERSE_H
#include "include/int_types.h"
#ifdef __cplusplus
extern "C" {
#endif
extern uint32_t reverse_bits(uint32_t v);
extern uint32_t reverse_nibbles(uint32_t retval);
#ifdef __cplusplus
}
#endif
#endif
| 691 | 20.625 | 71 | h |
null | ceph-main/src/common/run_cmd.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) 2011 New Dream Network
*
* 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 "common/errno.h"
#ifndef _WIN32
#include <sstream>
#include <stdarg.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
#else
#include "common/SubProcess.h"
#endif /* _WIN32 */
using std::ostringstream;
#ifndef _WIN32
std::string run_cmd(const char *cmd, ...)
{
std::vector <const char *> arr;
va_list ap;
va_start(ap, cmd);
const char *c = cmd;
do {
arr.push_back(c);
c = va_arg(ap, const char*);
} while (c != NULL);
va_end(ap);
arr.push_back(NULL);
int fret = fork();
if (fret == -1) {
int err = errno;
ostringstream oss;
oss << "run_cmd(" << cmd << "): unable to fork(): " << cpp_strerror(err);
return oss.str();
}
else if (fret == 0) {
// execvp doesn't modify its arguments, so the const-cast here is safe.
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
execvp(cmd, (char * const*)&arr[0]);
_exit(127);
}
int status;
while (waitpid(fret, &status, 0) == -1) {
int err = errno;
if (err == EINTR)
continue;
ostringstream oss;
oss << "run_cmd(" << cmd << "): waitpid error: "
<< cpp_strerror(err);
return oss.str();
}
if (WIFEXITED(status)) {
int wexitstatus = WEXITSTATUS(status);
if (wexitstatus != 0) {
ostringstream oss;
oss << "run_cmd(" << cmd << "): exited with status " << wexitstatus;
return oss.str();
}
return "";
}
else if (WIFSIGNALED(status)) {
ostringstream oss;
oss << "run_cmd(" << cmd << "): terminated by signal";
return oss.str();
}
ostringstream oss;
oss << "run_cmd(" << cmd << "): terminated by unknown mechanism";
return oss.str();
}
#else
std::string run_cmd(const char *cmd, ...)
{
SubProcess p(cmd, SubProcess::CLOSE, SubProcess::PIPE, SubProcess::CLOSE);
va_list ap;
va_start(ap, cmd);
const char *c = cmd;
c = va_arg(ap, const char*);
while (c != NULL) {
p.add_cmd_arg(c);
c = va_arg(ap, const char*);
}
va_end(ap);
if (p.spawn() == 0) {
p.join();
}
return p.err();
}
#endif /* _WIN32 */
| 2,475 | 21.925926 | 77 | cc |
null | ceph-main/src/common/run_cmd.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) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_COMMON_RUN_CMD_H
#define CEPH_COMMON_RUN_CMD_H
#include <string>
//
// Fork a command and run it. The shell will not be invoked and shell
// expansions will not be done.
// This function takes a variable number of arguments. The last argument must
// be NULL.
//
// Example:
// run_cmd("rm", "-rf", "foo", NULL)
//
// Returns an empty string on success, and an error string otherwise.
//
std::string run_cmd(const char *cmd, ...);
#endif
| 865 | 24.470588 | 77 | h |
null | ceph-main/src/common/safe_io.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) 2011 New Dream Network
*
* 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_SAFE_IO
#define CEPH_SAFE_IO
#include "common/compiler_extensions.h"
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Safe functions wrapping the raw read() and write() libc functions.
* These retry on EINTR, and on error return -errno instead of returning
* -1 and setting errno).
*
* On Windows, only recv/send work with sockets.
*/
ssize_t safe_read(int fd, void *buf, size_t count)
WARN_UNUSED_RESULT;
ssize_t safe_write(int fd, const void *buf, size_t count)
WARN_UNUSED_RESULT;
ssize_t safe_recv(int fd, void *buf, size_t count)
WARN_UNUSED_RESULT;
ssize_t safe_send(int fd, const void *buf, size_t count)
WARN_UNUSED_RESULT;
ssize_t safe_pread(int fd, void *buf, size_t count, off_t offset)
WARN_UNUSED_RESULT;
ssize_t safe_pwrite(int fd, const void *buf, size_t count, off_t offset)
WARN_UNUSED_RESULT;
#ifdef CEPH_HAVE_SPLICE
/*
* Similar to the above (non-exact version) and below (exact version).
* See splice(2) for parameter descriptions.
*/
ssize_t safe_splice(int fd_in, off_t *off_in, int fd_out, off_t *off_out,
size_t len, unsigned int flags)
WARN_UNUSED_RESULT;
ssize_t safe_splice_exact(int fd_in, off_t *off_in, int fd_out,
off_t *off_out, size_t len, unsigned int flags)
WARN_UNUSED_RESULT;
#endif
/*
* Same as the above functions, but return -EDOM unless exactly the requested
* number of bytes can be read.
*/
ssize_t safe_read_exact(int fd, void *buf, size_t count)
WARN_UNUSED_RESULT;
ssize_t safe_recv_exact(int fd, void *buf, size_t count)
WARN_UNUSED_RESULT;
ssize_t safe_pread_exact(int fd, void *buf, size_t count, off_t offset)
WARN_UNUSED_RESULT;
/*
* Safe functions to read and write an entire file.
*/
int safe_write_file(const char *base, const char *file,
const char *val, size_t vallen,
unsigned mode);
int safe_read_file(const char *base, const char *file,
char *val, size_t vallen);
#ifdef __cplusplus
}
#endif
#endif
| 2,482 | 28.915663 | 79 | h |
null | ceph-main/src/common/scrub_types.cc | #include "scrub_types.h"
using std::map;
using namespace librados;
void object_id_wrapper::encode(bufferlist& bl) const
{
ENCODE_START(1, 1, bl);
encode(name, bl);
encode(nspace, bl);
encode(locator, bl);
encode(snap, bl);
ENCODE_FINISH(bl);
}
void object_id_wrapper::decode(bufferlist::const_iterator& bp)
{
DECODE_START(1, bp);
decode(name, bp);
decode(nspace, bp);
decode(locator, bp);
decode(snap, bp);
DECODE_FINISH(bp);
}
namespace librados {
static void encode(const object_id_t& obj, bufferlist& bl)
{
reinterpret_cast<const object_id_wrapper&>(obj).encode(bl);
}
}
void osd_shard_wrapper::encode(bufferlist& bl) const
{
ENCODE_START(1, 1, bl);
encode(osd, bl);
encode(shard, bl);
ENCODE_FINISH(bl);
}
void osd_shard_wrapper::decode(bufferlist::const_iterator& bp)
{
DECODE_START(1, bp);
decode(osd, bp);
decode(shard, bp);
DECODE_FINISH(bp);
}
namespace librados {
static void encode(const osd_shard_t& shard, bufferlist& bl) {
reinterpret_cast<const osd_shard_wrapper&>(shard).encode(bl);
}
}
void shard_info_wrapper::set_object(const ScrubMap::object& object)
{
for (auto attr : object.attrs) {
bufferlist bl;
bl.push_back(attr.second);
attrs.insert(std::make_pair(attr.first, std::move(bl)));
}
size = object.size;
if (object.omap_digest_present) {
omap_digest_present = true;
omap_digest = object.omap_digest;
}
if (object.digest_present) {
data_digest_present = true;
data_digest = object.digest;
}
}
void shard_info_wrapper::encode(bufferlist& bl) const
{
ENCODE_START(3, 3, bl);
encode(errors, bl);
encode(primary, bl);
if (!has_shard_missing()) {
encode(attrs, bl);
encode(size, bl);
encode(omap_digest_present, bl);
encode(omap_digest, bl);
encode(data_digest_present, bl);
encode(data_digest, bl);
encode(selected_oi, bl);
}
ENCODE_FINISH(bl);
}
void shard_info_wrapper::decode(bufferlist::const_iterator& bp)
{
DECODE_START(3, bp);
decode(errors, bp);
decode(primary, bp);
if (!has_shard_missing()) {
decode(attrs, bp);
decode(size, bp);
decode(omap_digest_present, bp);
decode(omap_digest, bp);
decode(data_digest_present, bp);
decode(data_digest, bp);
decode(selected_oi, bp);
}
DECODE_FINISH(bp);
}
inconsistent_obj_wrapper::inconsistent_obj_wrapper(const hobject_t& hoid)
: inconsistent_obj_t{librados::object_id_t{hoid.oid.name,
hoid.nspace,
hoid.get_key(), hoid.snap}}
{}
void inconsistent_obj_wrapper::add_shard(const pg_shard_t& pgs,
const shard_info_wrapper& shard)
{
union_shards.errors |= shard.errors;
shards.emplace(osd_shard_t{pgs.osd, int8_t(pgs.shard)}, shard);
}
void
inconsistent_obj_wrapper::set_auth_missing(const hobject_t& hoid,
const map<pg_shard_t, ScrubMap>& maps,
map<pg_shard_t, shard_info_wrapper> &shard_map,
int &shallow_errors, int &deep_errors,
const pg_shard_t &primary)
{
for (auto pg_map : maps) {
auto oid_object = pg_map.second.objects.find(hoid);
shard_map[pg_map.first].primary = (pg_map.first == primary);
if (oid_object == pg_map.second.objects.end())
shard_map[pg_map.first].set_missing();
else
shard_map[pg_map.first].set_object(oid_object->second);
if (shard_map[pg_map.first].has_deep_errors())
++deep_errors;
else if (shard_map[pg_map.first].has_shallow_errors())
++shallow_errors;
union_shards.errors |= shard_map[pg_map.first].errors;
shards.emplace(osd_shard_t{pg_map.first.osd, pg_map.first.shard}, shard_map[pg_map.first]);
}
}
namespace librados {
static void encode(const shard_info_t& shard, bufferlist& bl)
{
reinterpret_cast<const shard_info_wrapper&>(shard).encode(bl);
}
}
void inconsistent_obj_wrapper::encode(bufferlist& bl) const
{
ENCODE_START(2, 2, bl);
encode(errors, bl);
encode(object, bl);
encode(version, bl);
encode(shards, bl);
encode(union_shards.errors, bl);
ENCODE_FINISH(bl);
}
void inconsistent_obj_wrapper::decode(bufferlist::const_iterator& bp)
{
DECODE_START(2, bp);
DECODE_OLDEST(2);
decode(errors, bp);
decode(object, bp);
decode(version, bp);
decode(shards, bp);
decode(union_shards.errors, bp);
DECODE_FINISH(bp);
}
inconsistent_snapset_wrapper::inconsistent_snapset_wrapper(const hobject_t& hoid)
: inconsistent_snapset_t{object_id_t{hoid.oid.name,
hoid.nspace,
hoid.get_key(),
hoid.snap}}
{}
using inc_snapset_t = inconsistent_snapset_t;
void inconsistent_snapset_wrapper::set_headless()
{
errors |= inc_snapset_t::HEADLESS_CLONE;
}
void inconsistent_snapset_wrapper::set_snapset_missing()
{
errors |= inc_snapset_t::SNAPSET_MISSING;
}
void inconsistent_snapset_wrapper::set_info_missing()
{
errors |= inc_snapset_t::INFO_MISSING;
}
void inconsistent_snapset_wrapper::set_snapset_corrupted()
{
errors |= inc_snapset_t::SNAPSET_CORRUPTED;
}
void inconsistent_snapset_wrapper::set_info_corrupted()
{
errors |= inc_snapset_t::INFO_CORRUPTED;
}
void inconsistent_snapset_wrapper::set_clone_missing(snapid_t snap)
{
errors |= inc_snapset_t::CLONE_MISSING;
missing.push_back(snap);
}
void inconsistent_snapset_wrapper::set_clone(snapid_t snap)
{
errors |= inc_snapset_t::EXTRA_CLONES;
clones.push_back(snap);
}
void inconsistent_snapset_wrapper::set_snapset_error()
{
errors |= inc_snapset_t::SNAP_ERROR;
}
void inconsistent_snapset_wrapper::set_size_mismatch()
{
errors |= inc_snapset_t::SIZE_MISMATCH;
}
void inconsistent_snapset_wrapper::encode(bufferlist& bl) const
{
ENCODE_START(2, 1, bl);
encode(errors, bl);
encode(object, bl);
encode(clones, bl);
encode(missing, bl);
encode(ss_bl, bl);
ENCODE_FINISH(bl);
}
void inconsistent_snapset_wrapper::decode(bufferlist::const_iterator& bp)
{
DECODE_START(2, bp);
decode(errors, bp);
decode(object, bp);
decode(clones, bp);
decode(missing, bp);
if (struct_v >= 2) {
decode(ss_bl, bp);
}
DECODE_FINISH(bp);
}
void scrub_ls_arg_t::encode(bufferlist& bl) const
{
ENCODE_START(1, 1, bl);
encode(interval, bl);
encode(get_snapsets, bl);
encode(start_after.name, bl);
encode(start_after.nspace, bl);
encode(start_after.snap, bl);
encode(max_return, bl);
ENCODE_FINISH(bl);
}
void scrub_ls_arg_t::decode(bufferlist::const_iterator& bp)
{
DECODE_START(1, bp);
decode(interval, bp);
decode(get_snapsets, bp);
decode(start_after.name, bp);
decode(start_after.nspace, bp);
decode(start_after.snap, bp);
decode(max_return, bp);
DECODE_FINISH(bp);
}
void scrub_ls_result_t::encode(bufferlist& bl) const
{
ENCODE_START(1, 1, bl);
encode(interval, bl);
encode(vals, bl);
ENCODE_FINISH(bl);
}
void scrub_ls_result_t::decode(bufferlist::const_iterator& bp)
{
DECODE_START(1, bp);
decode(interval, bp);
decode(vals, bp);
DECODE_FINISH(bp);
}
| 7,075 | 23.150171 | 95 | cc |
null | ceph-main/src/common/scrub_types.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_SCRUB_TYPES_H
#define CEPH_SCRUB_TYPES_H
#include "osd/osd_types.h"
// wrappers around scrub types to offer the necessary bits other than
// the minimal set that the lirados requires
struct object_id_wrapper : public librados::object_id_t {
explicit object_id_wrapper(const hobject_t& hoid)
: object_id_t{hoid.oid.name, hoid.nspace, hoid.get_key(), hoid.snap}
{}
void encode(ceph::buffer::list& bl) const;
void decode(ceph::buffer::list::const_iterator& bl);
};
WRITE_CLASS_ENCODER(object_id_wrapper)
namespace librados {
inline void decode(object_id_t& obj, ceph::buffer::list::const_iterator& bp) {
reinterpret_cast<object_id_wrapper&>(obj).decode(bp);
}
}
struct osd_shard_wrapper : public librados::osd_shard_t {
void encode(ceph::buffer::list& bl) const;
void decode(ceph::buffer::list::const_iterator& bp);
};
WRITE_CLASS_ENCODER(osd_shard_wrapper)
namespace librados {
inline void decode(librados::osd_shard_t& shard, ceph::buffer::list::const_iterator& bp) {
reinterpret_cast<osd_shard_wrapper&>(shard).decode(bp);
}
}
struct shard_info_wrapper : public librados::shard_info_t {
public:
shard_info_wrapper() = default;
explicit shard_info_wrapper(const ScrubMap::object& object) {
set_object(object);
}
void set_object(const ScrubMap::object& object);
void set_missing() {
errors |= err_t::SHARD_MISSING;
}
void set_omap_digest_mismatch_info() {
errors |= err_t::OMAP_DIGEST_MISMATCH_INFO;
}
void set_size_mismatch_info() {
errors |= err_t::SIZE_MISMATCH_INFO;
}
void set_data_digest_mismatch_info() {
errors |= err_t::DATA_DIGEST_MISMATCH_INFO;
}
void set_read_error() {
errors |= err_t::SHARD_READ_ERR;
}
void set_stat_error() {
errors |= err_t::SHARD_STAT_ERR;
}
void set_ec_hash_mismatch() {
errors |= err_t::SHARD_EC_HASH_MISMATCH;
}
void set_ec_size_mismatch() {
errors |= err_t::SHARD_EC_SIZE_MISMATCH;
}
void set_info_missing() {
errors |= err_t::INFO_MISSING;
}
void set_info_corrupted() {
errors |= err_t::INFO_CORRUPTED;
}
void set_snapset_missing() {
errors |= err_t::SNAPSET_MISSING;
}
void set_snapset_corrupted() {
errors |= err_t::SNAPSET_CORRUPTED;
}
void set_obj_size_info_mismatch() {
errors |= err_t::OBJ_SIZE_INFO_MISMATCH;
}
void set_hinfo_missing() {
errors |= err_t::HINFO_MISSING;
}
void set_hinfo_corrupted() {
errors |= err_t::HINFO_CORRUPTED;
}
bool only_data_digest_mismatch_info() const {
return errors == err_t::DATA_DIGEST_MISMATCH_INFO;
}
void clear_data_digest_mismatch_info() {
errors &= ~err_t::DATA_DIGEST_MISMATCH_INFO;
}
void encode(ceph::buffer::list& bl) const;
void decode(ceph::buffer::list::const_iterator& bp);
};
WRITE_CLASS_ENCODER(shard_info_wrapper)
namespace librados {
inline void decode(librados::shard_info_t& shard,
ceph::buffer::list::const_iterator& bp) {
reinterpret_cast<shard_info_wrapper&>(shard).decode(bp);
}
}
struct inconsistent_obj_wrapper : librados::inconsistent_obj_t {
explicit inconsistent_obj_wrapper(const hobject_t& hoid);
void set_object_info_inconsistency() {
errors |= obj_err_t::OBJECT_INFO_INCONSISTENCY;
}
void set_omap_digest_mismatch() {
errors |= obj_err_t::OMAP_DIGEST_MISMATCH;
}
void set_data_digest_mismatch() {
errors |= obj_err_t::DATA_DIGEST_MISMATCH;
}
void set_size_mismatch() {
errors |= obj_err_t::SIZE_MISMATCH;
}
void set_attr_value_mismatch() {
errors |= obj_err_t::ATTR_VALUE_MISMATCH;
}
void set_attr_name_mismatch() {
errors |= obj_err_t::ATTR_NAME_MISMATCH;
}
void set_snapset_inconsistency() {
errors |= obj_err_t::SNAPSET_INCONSISTENCY;
}
void set_hinfo_inconsistency() {
errors |= obj_err_t::HINFO_INCONSISTENCY;
}
void set_size_too_large() {
errors |= obj_err_t::SIZE_TOO_LARGE;
}
void add_shard(const pg_shard_t& pgs, const shard_info_wrapper& shard);
void set_auth_missing(const hobject_t& hoid,
const std::map<pg_shard_t, ScrubMap>&,
std::map<pg_shard_t, shard_info_wrapper>&,
int &shallow_errors, int &deep_errors,
const pg_shard_t &primary);
void set_version(uint64_t ver) { version = ver; }
void encode(ceph::buffer::list& bl) const;
void decode(ceph::buffer::list::const_iterator& bp);
};
WRITE_CLASS_ENCODER(inconsistent_obj_wrapper)
inline void decode(librados::inconsistent_obj_t& obj,
ceph::buffer::list::const_iterator& bp) {
reinterpret_cast<inconsistent_obj_wrapper&>(obj).decode(bp);
}
struct inconsistent_snapset_wrapper : public librados::inconsistent_snapset_t {
inconsistent_snapset_wrapper() = default;
explicit inconsistent_snapset_wrapper(const hobject_t& head);
void set_headless();
// soid claims that it is a head or a snapdir, but its SS_ATTR
// is missing.
void set_snapset_missing();
void set_info_missing();
void set_snapset_corrupted();
void set_info_corrupted();
// snapset with missing clone
void set_clone_missing(snapid_t);
// Clones that are there
void set_clone(snapid_t);
// the snapset is not consistent with itself
void set_snapset_error();
void set_size_mismatch();
void encode(ceph::buffer::list& bl) const;
void decode(ceph::buffer::list::const_iterator& bp);
};
WRITE_CLASS_ENCODER(inconsistent_snapset_wrapper)
namespace librados {
inline void decode(librados::inconsistent_snapset_t& snapset,
ceph::buffer::list::const_iterator& bp) {
reinterpret_cast<inconsistent_snapset_wrapper&>(snapset).decode(bp);
}
}
struct scrub_ls_arg_t {
uint32_t interval;
uint32_t get_snapsets;
librados::object_id_t start_after;
uint64_t max_return;
void encode(ceph::buffer::list& bl) const;
void decode(ceph::buffer::list::const_iterator& bl);
};
WRITE_CLASS_ENCODER(scrub_ls_arg_t);
struct scrub_ls_result_t {
epoch_t interval;
std::vector<ceph::buffer::list> vals;
void encode(ceph::buffer::list& bl) const;
void decode(ceph::buffer::list::const_iterator& bl);
};
WRITE_CLASS_ENCODER(scrub_ls_result_t);
#endif
| 6,175 | 28.270142 | 92 | h |
null | ceph-main/src/common/sctp_crc32.h | #ifndef CEPH_COMMON_SCTP_CRC32_H
#define CEPH_COMMON_SCTP_CRC32_H
#ifdef __cplusplus
extern "C" {
#endif
extern uint32_t ceph_crc32c_sctp(uint32_t crc, unsigned char const *data, unsigned length);
#ifdef __cplusplus
}
#endif
#endif
| 236 | 14.8 | 91 | h |
null | ceph-main/src/common/secret.h | #ifndef CEPH_SECRET_H
#define CEPH_SECRET_H
#ifdef __cplusplus
extern "C" {
#endif
int read_secret_from_file(const char *filename, char *secret, size_t max_len);
int set_kernel_secret(const char *secret, const char *key_name);
int is_kernel_secret(const char *key_name);
#ifdef __cplusplus
}
#endif
#endif
| 312 | 15.473684 | 78 | h |
null | ceph-main/src/common/shared_cache.hpp | // -*- 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_SHAREDCACHE_H
#define CEPH_SHAREDCACHE_H
#include <map>
#include <list>
#ifdef WITH_SEASTAR
#include <boost/smart_ptr/local_shared_ptr.hpp>
#else
#include <memory>
#endif
#include "common/ceph_mutex.h"
#include "common/ceph_context.h"
#include "common/dout.h"
#include "include/unordered_map.h"
template <class K, class V>
class SharedLRU {
CephContext *cct;
#ifdef WITH_SEASTAR
using VPtr = boost::local_shared_ptr<V>;
using WeakVPtr = boost::weak_ptr<V>;
#else
using VPtr = std::shared_ptr<V>;
using WeakVPtr = std::weak_ptr<V>;
#endif
ceph::mutex lock;
size_t max_size;
ceph::condition_variable cond;
unsigned size;
public:
int waiting;
private:
using C = std::less<K>;
using H = std::hash<K>;
ceph::unordered_map<K, typename std::list<std::pair<K, VPtr> >::iterator, H> contents;
std::list<std::pair<K, VPtr> > lru;
std::map<K, std::pair<WeakVPtr, V*>, C> weak_refs;
void trim_cache(std::list<VPtr> *to_release) {
while (size > max_size) {
to_release->push_back(lru.back().second);
lru_remove(lru.back().first);
}
}
void lru_remove(const K& key) {
auto i = contents.find(key);
if (i == contents.end())
return;
lru.erase(i->second);
--size;
contents.erase(i);
}
void lru_add(const K& key, const VPtr& val, std::list<VPtr> *to_release) {
auto i = contents.find(key);
if (i != contents.end()) {
lru.splice(lru.begin(), lru, i->second);
} else {
++size;
lru.push_front(make_pair(key, val));
contents[key] = lru.begin();
trim_cache(to_release);
}
}
void remove(const K& key, V *valptr) {
std::lock_guard l{lock};
auto i = weak_refs.find(key);
if (i != weak_refs.end() && i->second.second == valptr) {
weak_refs.erase(i);
}
cond.notify_all();
}
class Cleanup {
public:
SharedLRU<K, V> *cache;
K key;
Cleanup(SharedLRU<K, V> *cache, K key) : cache(cache), key(key) {}
void operator()(V *ptr) {
cache->remove(key, ptr);
delete ptr;
}
};
public:
SharedLRU(CephContext *cct = NULL, size_t max_size = 20)
: cct(cct),
lock{ceph::make_mutex("SharedLRU::lock")},
max_size(max_size),
size(0), waiting(0) {
contents.rehash(max_size);
}
~SharedLRU() {
contents.clear();
lru.clear();
if (!weak_refs.empty()) {
lderr(cct) << "leaked refs:\n";
dump_weak_refs(*_dout);
*_dout << dendl;
if (cct->_conf.get_val<bool>("debug_asserts_on_shutdown")) {
ceph_assert(weak_refs.empty());
}
}
}
int get_count() {
std::lock_guard locker{lock};
return size;
}
void set_cct(CephContext *c) {
cct = c;
}
void dump_weak_refs() {
lderr(cct) << "leaked refs:\n";
dump_weak_refs(*_dout);
*_dout << dendl;
}
void dump_weak_refs(std::ostream& out) {
for (const auto& [key, ref] : weak_refs) {
out << __func__ << " " << this << " weak_refs: "
<< key << " = " << ref.second
<< " with " << ref.first.use_count() << " refs"
<< std::endl;
}
}
//clear all strong reference from the lru.
void clear() {
while (true) {
VPtr val; // release any ref we have after we drop the lock
std::lock_guard locker{lock};
if (size == 0)
break;
val = lru.back().second;
lru_remove(lru.back().first);
}
}
void clear(const K& key) {
VPtr val; // release any ref we have after we drop the lock
{
std::lock_guard l{lock};
auto i = weak_refs.find(key);
if (i != weak_refs.end()) {
val = i->second.first.lock();
}
lru_remove(key);
}
}
/* Clears weakrefs in the interval [from, to] -- note that to is inclusive */
void clear_range(
const K& from,
const K& to) {
std::list<VPtr> vals; // release any refs we have after we drop the lock
{
std::lock_guard l{lock};
auto from_iter = weak_refs.lower_bound(from);
auto to_iter = weak_refs.upper_bound(to);
for (auto i = from_iter; i != to_iter; ) {
vals.push_back(i->second.first.lock());
lru_remove((i++)->first);
}
}
}
void purge(const K &key) {
VPtr val; // release any ref we have after we drop the lock
{
std::lock_guard l{lock};
auto i = weak_refs.find(key);
if (i != weak_refs.end()) {
val = i->second.first.lock();
weak_refs.erase(i);
}
lru_remove(key);
}
}
void set_size(size_t new_size) {
std::list<VPtr> to_release;
{
std::lock_guard l{lock};
max_size = new_size;
trim_cache(&to_release);
}
}
// Returns K key s.t. key <= k for all currently cached k,v
K cached_key_lower_bound() {
std::lock_guard l{lock};
return weak_refs.begin()->first;
}
VPtr lower_bound(const K& key) {
VPtr val;
std::list<VPtr> to_release;
{
std::unique_lock l{lock};
++waiting;
cond.wait(l, [this, &key, &val, &to_release] {
if (weak_refs.empty()) {
return true;
}
auto i = weak_refs.lower_bound(key);
if (i == weak_refs.end()) {
--i;
}
if (val = i->second.first.lock(); val) {
lru_add(i->first, val, &to_release);
return true;
} else {
return false;
}
});
--waiting;
}
return val;
}
bool get_next(const K &key, std::pair<K, VPtr> *next) {
std::pair<K, VPtr> r;
{
std::lock_guard l{lock};
VPtr next_val;
typename std::map<K, std::pair<WeakVPtr, V*>, C>::iterator i = weak_refs.upper_bound(key);
while (i != weak_refs.end() &&
!(next_val = i->second.first.lock()))
++i;
if (i == weak_refs.end())
return false;
if (next)
r = make_pair(i->first, next_val);
}
if (next)
*next = r;
return true;
}
bool get_next(const K &key, std::pair<K, V> *next) {
std::pair<K, VPtr> r;
bool found = get_next(key, &r);
if (!found || !next)
return found;
next->first = r.first;
ceph_assert(r.second);
next->second = *(r.second);
return found;
}
VPtr lookup(const K& key) {
VPtr val;
std::list<VPtr> to_release;
{
std::unique_lock l{lock};
++waiting;
cond.wait(l, [this, &key, &val, &to_release] {
if (auto i = weak_refs.find(key); i != weak_refs.end()) {
if (val = i->second.first.lock(); val) {
lru_add(key, val, &to_release);
return true;
} else {
return false;
}
} else {
return true;
}
});
--waiting;
}
return val;
}
VPtr lookup_or_create(const K &key) {
VPtr val;
std::list<VPtr> to_release;
{
std::unique_lock l{lock};
cond.wait(l, [this, &key, &val] {
if (auto i = weak_refs.find(key); i != weak_refs.end()) {
if (val = i->second.first.lock(); val) {
return true;
} else {
return false;
}
} else {
return true;
}
});
if (!val) {
val = VPtr{new V{}, Cleanup{this, key}};
weak_refs.insert(make_pair(key, make_pair(val, val.get())));
}
lru_add(key, val, &to_release);
}
return val;
}
/**
* empty()
*
* Returns true iff there are no live references left to anything that has been
* in the cache.
*/
bool empty() {
std::lock_guard l{lock};
return weak_refs.empty();
}
/***
* Inserts a key if not present, or bumps it to the front of the LRU if
* it is, and then gives you a reference to the value. If the key already
* existed, you are responsible for deleting the new value you tried to
* insert.
*
* @param key The key to insert
* @param value The value that goes with the key
* @param existed Set to true if the value was already in the
* map, false otherwise
* @return A reference to the map's value for the given key
*/
VPtr add(const K& key, V *value, bool *existed = NULL) {
VPtr val;
std::list<VPtr> to_release;
{
typename std::map<K, std::pair<WeakVPtr, V*>, C>::iterator actual;
std::unique_lock l{lock};
cond.wait(l, [this, &key, &actual, &val] {
actual = weak_refs.lower_bound(key);
if (actual != weak_refs.end() && actual->first == key) {
val = actual->second.first.lock();
if (val) {
return true;
} else {
return false;
}
} else {
return true;
}
});
if (val) {
if (existed) {
*existed = true;
}
} else {
if (existed) {
*existed = false;
}
val = VPtr(value, Cleanup(this, key));
weak_refs.insert(actual, make_pair(key, make_pair(val, value)));
}
lru_add(key, val, &to_release);
}
return val;
}
friend class SharedLRUTest;
};
#endif
| 9,272 | 23.085714 | 96 | hpp |
null | ceph-main/src/common/shared_mutex_debug.cc | #include "shared_mutex_debug.h"
#include <system_error>
#include "acconfig.h"
#include "common/valgrind.h"
namespace ceph {
shared_mutex_debug::shared_mutex_debug(std::string group,
bool track_lock,
bool enable_lock_dep,
bool prioritize_write)
: mutex_debugging_base{std::move(group),
enable_lock_dep,
false /* backtrace */},
track(track_lock)
{
#ifdef HAVE_PTHREAD_RWLOCKATTR_SETKIND_NP
if (prioritize_write) {
pthread_rwlockattr_t attr;
pthread_rwlockattr_init(&attr);
// PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP
// Setting the lock kind to this avoids writer starvation as long as
// long as any read locking is not done in a recursive fashion.
pthread_rwlockattr_setkind_np(&attr,
PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
pthread_rwlock_init(&rwlock, &attr);
pthread_rwlockattr_destroy(&attr);
} else
#endif
// Next block is in {} to possibly connect to the above if when code is used.
{
pthread_rwlock_init(&rwlock, NULL);
}
ANNOTATE_BENIGN_RACE_SIZED(&id, sizeof(id), "shared_mutex_debug lockdep id");
ANNOTATE_BENIGN_RACE_SIZED(&nlock, sizeof(nlock), "shared_mutex_debug nwlock");
ANNOTATE_BENIGN_RACE_SIZED(&nrlock, sizeof(nrlock), "shared_mutex_debug nrlock");
}
// exclusive
void shared_mutex_debug::lock()
{
if (_enable_lockdep()) {
_will_lock();
}
if (int r = pthread_rwlock_wrlock(&rwlock); r != 0) {
throw std::system_error(r, std::generic_category());
}
if (_enable_lockdep()) {
_locked();
}
_post_lock();
}
bool shared_mutex_debug::try_lock()
{
int r = pthread_rwlock_trywrlock(&rwlock);
switch (r) {
case 0:
if (_enable_lockdep()) {
_locked();
}
_post_lock();
return true;
case EBUSY:
return false;
default:
throw std::system_error(r, std::generic_category());
}
}
void shared_mutex_debug::unlock()
{
_pre_unlock();
if (_enable_lockdep()) {
_will_unlock();
}
if (int r = pthread_rwlock_unlock(&rwlock); r != 0) {
throw std::system_error(r, std::generic_category());
}
}
// shared locking
void shared_mutex_debug::lock_shared()
{
if (_enable_lockdep()) {
_will_lock();
}
if (int r = pthread_rwlock_rdlock(&rwlock); r != 0) {
throw std::system_error(r, std::generic_category());
}
if (_enable_lockdep()) {
_locked();
}
_post_lock_shared();
}
bool shared_mutex_debug::try_lock_shared()
{
if (_enable_lockdep()) {
_will_unlock();
}
switch (int r = pthread_rwlock_rdlock(&rwlock); r) {
case 0:
if (_enable_lockdep()) {
_locked();
}
_post_lock_shared();
return true;
case EBUSY:
return false;
default:
throw std::system_error(r, std::generic_category());
}
}
void shared_mutex_debug::unlock_shared()
{
_pre_unlock_shared();
if (_enable_lockdep()) {
_will_unlock();
}
if (int r = pthread_rwlock_unlock(&rwlock); r != 0) {
throw std::system_error(r, std::generic_category());
}
}
// exclusive locking
void shared_mutex_debug::_pre_unlock()
{
if (track) {
ceph_assert(nlock > 0);
--nlock;
ceph_assert(locked_by == std::this_thread::get_id());
ceph_assert(nlock == 0);
locked_by = std::thread::id();
}
}
void shared_mutex_debug::_post_lock()
{
if (track) {
ceph_assert(nlock == 0);
locked_by = std::this_thread::get_id();
++nlock;
}
}
// shared locking
void shared_mutex_debug::_pre_unlock_shared()
{
if (track) {
ceph_assert(nrlock > 0);
nrlock--;
}
}
void shared_mutex_debug::_post_lock_shared()
{
if (track) {
++nrlock;
}
}
} // namespace ceph
| 3,780 | 21.640719 | 83 | cc |
null | ceph-main/src/common/shared_mutex_debug.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <pthread.h>
#include <atomic>
#include "common/mutex_debug.h"
namespace ceph {
class shared_mutex_debug :
public ceph::mutex_debug_detail::mutex_debugging_base
{
pthread_rwlock_t rwlock;
const bool track;
std::atomic<unsigned> nrlock{0};
public:
shared_mutex_debug(std::string group,
bool track_lock=true,
bool enable_lock_dep=true,
bool prioritize_write=false);
// exclusive locking
void lock();
bool try_lock();
void unlock();
bool is_wlocked() const {
return nlock > 0;
}
// shared locking
void lock_shared();
bool try_lock_shared();
void unlock_shared();
bool is_rlocked() const {
return nrlock > 0;
}
// either of them
bool is_locked() const {
return nlock > 0 || nrlock > 0;
}
private:
// exclusive locking
void _pre_unlock();
void _post_lock();
// shared locking
void _pre_unlock_shared();
void _post_lock_shared();
};
} // namespace ceph
| 1,060 | 19.018868 | 70 | h |
null | ceph-main/src/common/sharedptr_registry.hpp | // -*- 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_SHAREDPTR_REGISTRY_H
#define CEPH_SHAREDPTR_REGISTRY_H
#include <map>
#include <memory>
#include "common/ceph_mutex.h"
/**
* Provides a registry of shared_ptr<V> indexed by K while
* the references are alive.
*/
template <class K, class V, class C = std::less<K> >
class SharedPtrRegistry {
public:
typedef std::shared_ptr<V> VPtr;
typedef std::weak_ptr<V> WeakVPtr;
int waiting;
private:
ceph::mutex lock = ceph::make_mutex("SharedPtrRegistry::lock");
ceph::condition_variable cond;
std::map<K, std::pair<WeakVPtr, V*>, C> contents;
class OnRemoval {
SharedPtrRegistry<K,V,C> *parent;
K key;
public:
OnRemoval(SharedPtrRegistry<K,V,C> *parent, K key) :
parent(parent), key(key) {}
void operator()(V *to_remove) {
{
std::lock_guard l(parent->lock);
typename std::map<K, std::pair<WeakVPtr, V*>, C>::iterator i =
parent->contents.find(key);
if (i != parent->contents.end() &&
i->second.second == to_remove) {
parent->contents.erase(i);
parent->cond.notify_all();
}
}
delete to_remove;
}
};
friend class OnRemoval;
public:
SharedPtrRegistry() :
waiting(0)
{}
bool empty() {
std::lock_guard l(lock);
return contents.empty();
}
bool get_next(const K &key, std::pair<K, VPtr> *next) {
std::pair<K, VPtr> r;
{
std::lock_guard l(lock);
VPtr next_val;
typename std::map<K, std::pair<WeakVPtr, V*>, C>::iterator i =
contents.upper_bound(key);
while (i != contents.end() &&
!(next_val = i->second.first.lock()))
++i;
if (i == contents.end())
return false;
if (next)
r = std::make_pair(i->first, next_val);
}
if (next)
*next = r;
return true;
}
bool get_next(const K &key, std::pair<K, V> *next) {
VPtr next_val;
std::lock_guard l(lock);
typename std::map<K, std::pair<WeakVPtr, V*>, C>::iterator i =
contents.upper_bound(key);
while (i != contents.end() &&
!(next_val = i->second.first.lock()))
++i;
if (i == contents.end())
return false;
if (next)
*next = std::make_pair(i->first, *next_val);
return true;
}
VPtr lookup(const K &key) {
std::unique_lock l(lock);
waiting++;
while (1) {
typename std::map<K, std::pair<WeakVPtr, V*>, C>::iterator i =
contents.find(key);
if (i != contents.end()) {
VPtr retval = i->second.first.lock();
if (retval) {
waiting--;
return retval;
}
} else {
break;
}
cond.wait(l);
}
waiting--;
return VPtr();
}
VPtr lookup_or_create(const K &key) {
std::unique_lock l(lock);
waiting++;
while (1) {
typename std::map<K, std::pair<WeakVPtr, V*>, C>::iterator i =
contents.find(key);
if (i != contents.end()) {
VPtr retval = i->second.first.lock();
if (retval) {
waiting--;
return retval;
}
} else {
break;
}
cond.wait(l);
}
V *ptr = new V();
VPtr retval(ptr, OnRemoval(this, key));
contents.insert(std::make_pair(key, make_pair(retval, ptr)));
waiting--;
return retval;
}
unsigned size() {
std::lock_guard l(lock);
return contents.size();
}
void remove(const K &key) {
std::lock_guard l(lock);
contents.erase(key);
cond.notify_all();
}
template<class A>
VPtr lookup_or_create(const K &key, const A &arg) {
std::unique_lock l(lock);
waiting++;
while (1) {
typename std::map<K, std::pair<WeakVPtr, V*>, C>::iterator i =
contents.find(key);
if (i != contents.end()) {
VPtr retval = i->second.first.lock();
if (retval) {
waiting--;
return retval;
}
} else {
break;
}
cond.wait(l);
}
V *ptr = new V(arg);
VPtr retval(ptr, OnRemoval(this, key));
contents.insert(std::make_pair(key, make_pair(retval, ptr)));
waiting--;
return retval;
}
friend class SharedPtrRegistryTest;
};
#endif
| 4,351 | 21.905263 | 70 | hpp |
null | ceph-main/src/common/shunique_lock.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_COMMON_SHUNIQUE_LOCK_H
#define CEPH_COMMON_SHUNIQUE_LOCK_H
#include <mutex>
#include <shared_mutex>
#include <system_error>
namespace ceph {
// This is a 'lock' class in the style of shared_lock and
// unique_lock. Like shared_mutex it implements both Lockable and
// SharedLockable.
// My rationale is thus: one of the advantages of unique_lock is that
// I can pass a thread of execution's control of a lock around as a
// parameter. So that methods further down the call stack can unlock
// it, do something, relock it, and have the lock state be known by
// the caller afterward, explicitly. The shared_lock class offers a
// similar advantage to shared_lock, but each class is one or the
// other. In Objecter we have calls that in most cases need /a/ lock
// on the shared mutex, and whether it's shared or exclusive doesn't
// matter. In some circumstances they may drop the shared lock and
// reacquire an exclusive one. This could be handled by passing both a
// shared and unique lock down the call stack. This is vexacious and
// shameful.
// Wanting to avoid heaping shame and vexation upon myself, I threw
// this class together.
// This class makes no attempt to support atomic upgrade or
// downgrade. I don't want either. Matt has convinced me that if you
// think you want them you've usually made a mistake somewhere. It is
// exactly and only a reification of the state held on a shared mutex.
/// Acquire unique ownership of the mutex.
struct acquire_unique_t { };
/// Acquire shared ownership of the mutex.
struct acquire_shared_t { };
constexpr acquire_unique_t acquire_unique { };
constexpr acquire_shared_t acquire_shared { };
template<typename Mutex>
class shunique_lock {
public:
typedef Mutex mutex_type;
typedef std::unique_lock<Mutex> unique_lock_type;
typedef std::shared_lock<Mutex> shared_lock_type;
shunique_lock() noexcept : m(nullptr), o(ownership::none) { }
// We do not provide a default locking/try_locking constructor that
// takes only the mutex, since it is not clear whether to take it
// shared or unique. We explicitly require the use of lock_deferred
// to prevent Nasty Surprises.
shunique_lock(mutex_type& m, std::defer_lock_t) noexcept
: m(&m), o(ownership::none) { }
shunique_lock(mutex_type& m, acquire_unique_t)
: m(&m), o(ownership::none) {
lock();
}
shunique_lock(mutex_type& m, acquire_shared_t)
: m(&m), o(ownership::none) {
lock_shared();
}
template<typename AcquireType>
shunique_lock(mutex_type& m, AcquireType at, std::try_to_lock_t)
: m(&m), o(ownership::none) {
try_lock(at);
}
shunique_lock(mutex_type& m, acquire_unique_t, std::adopt_lock_t)
: m(&m), o(ownership::unique) {
// You'd better actually have a lock, or I will find you and I
// will hunt you down.
}
shunique_lock(mutex_type& m, acquire_shared_t, std::adopt_lock_t)
: m(&m), o(ownership::shared) {
}
template<typename AcquireType, typename Clock, typename Duration>
shunique_lock(mutex_type& m, AcquireType at,
const std::chrono::time_point<Clock, Duration>& t)
: m(&m), o(ownership::none) {
try_lock_until(at, t);
}
template<typename AcquireType, typename Rep, typename Period>
shunique_lock(mutex_type& m, AcquireType at,
const std::chrono::duration<Rep, Period>& dur)
: m(&m), o(ownership::none) {
try_lock_for(at, dur);
}
~shunique_lock() {
switch (o) {
case ownership::none:
return;
case ownership::unique:
m->unlock();
break;
case ownership::shared:
m->unlock_shared();
break;
}
}
shunique_lock(shunique_lock const&) = delete;
shunique_lock& operator=(shunique_lock const&) = delete;
shunique_lock(shunique_lock&& l) noexcept : shunique_lock() {
swap(l);
}
shunique_lock(unique_lock_type&& l) noexcept {
if (l.owns_lock())
o = ownership::unique;
else
o = ownership::none;
m = l.release();
}
shunique_lock(shared_lock_type&& l) noexcept {
if (l.owns_lock())
o = ownership::shared;
else
o = ownership::none;
m = l.release();
}
shunique_lock& operator=(shunique_lock&& l) noexcept {
shunique_lock(std::move(l)).swap(*this);
return *this;
}
shunique_lock& operator=(unique_lock_type&& l) noexcept {
shunique_lock(std::move(l)).swap(*this);
return *this;
}
shunique_lock& operator=(shared_lock_type&& l) noexcept {
shunique_lock(std::move(l)).swap(*this);
return *this;
}
void lock() {
lockable();
m->lock();
o = ownership::unique;
}
void lock_shared() {
lockable();
m->lock_shared();
o = ownership::shared;
}
void lock(ceph::acquire_unique_t) {
lock();
}
void lock(ceph::acquire_shared_t) {
lock_shared();
}
bool try_lock() {
lockable();
if (m->try_lock()) {
o = ownership::unique;
return true;
}
return false;
}
bool try_lock_shared() {
lockable();
if (m->try_lock_shared()) {
o = ownership::shared;
return true;
}
return false;
}
bool try_lock(ceph::acquire_unique_t) {
return try_lock();
}
bool try_lock(ceph::acquire_shared_t) {
return try_lock_shared();
}
template<typename Rep, typename Period>
bool try_lock_for(const std::chrono::duration<Rep, Period>& dur) {
lockable();
if (m->try_lock_for(dur)) {
o = ownership::unique;
return true;
}
return false;
}
template<typename Rep, typename Period>
bool try_lock_shared_for(const std::chrono::duration<Rep, Period>& dur) {
lockable();
if (m->try_lock_shared_for(dur)) {
o = ownership::shared;
return true;
}
return false;
}
template<typename Rep, typename Period>
bool try_lock_for(ceph::acquire_unique_t,
const std::chrono::duration<Rep, Period>& dur) {
return try_lock_for(dur);
}
template<typename Rep, typename Period>
bool try_lock_for(ceph::acquire_shared_t,
const std::chrono::duration<Rep, Period>& dur) {
return try_lock_shared_for(dur);
}
template<typename Clock, typename Duration>
bool try_lock_until(const std::chrono::time_point<Clock, Duration>& time) {
lockable();
if (m->try_lock_until(time)) {
o = ownership::unique;
return true;
}
return false;
}
template<typename Clock, typename Duration>
bool try_lock_shared_until(const std::chrono::time_point<Clock,
Duration>& time) {
lockable();
if (m->try_lock_shared_until(time)) {
o = ownership::shared;
return true;
}
return false;
}
template<typename Clock, typename Duration>
bool try_lock_until(ceph::acquire_unique_t,
const std::chrono::time_point<Clock, Duration>& time) {
return try_lock_until(time);
}
template<typename Clock, typename Duration>
bool try_lock_until(ceph::acquire_shared_t,
const std::chrono::time_point<Clock, Duration>& time) {
return try_lock_shared_until(time);
}
// Only have a single unlock method. Otherwise we'd be building an
// Acme lock class suitable only for ravenous coyotes desparate to
// devour a road runner. It would be bad. It would be disgusting. It
// would be infelicitous as heck. It would leave our developers in a
// state of seeming safety unaware of the yawning chasm of failure
// that had opened beneath their feet that would soon transition
// into a sickening realization of the error they made and a brief
// moment of blinking self pity before their program hurled itself
// into undefined behaviour and plummeted up the stack with core
// dumps trailing behind it.
void unlock() {
switch (o) {
case ownership::none:
throw std::system_error((int)std::errc::resource_deadlock_would_occur,
std::generic_category());
break;
case ownership::unique:
m->unlock();
break;
case ownership::shared:
m->unlock_shared();
break;
}
o = ownership::none;
}
// Setters
void swap(shunique_lock& u) noexcept {
std::swap(m, u.m);
std::swap(o, u.o);
}
mutex_type* release() noexcept {
o = ownership::none;
mutex_type* tm = m;
m = nullptr;
return tm;
}
// Ideally I'd rather make a move constructor for std::unique_lock
// that took a shunique_lock, but obviously I can't.
unique_lock_type release_to_unique() {
if (o == ownership::unique) {
o = ownership::none;
unique_lock_type tu(*m, std::adopt_lock);
m = nullptr;
return tu;
} else if (o == ownership::none) {
unique_lock_type tu(*m, std::defer_lock);
m = nullptr;
return tu;
} else if (m == nullptr) {
return unique_lock_type();
}
throw std::system_error((int)std::errc::operation_not_permitted,
std::generic_category());
}
shared_lock_type release_to_shared() {
if (o == ownership::shared) {
o = ownership::none;
shared_lock_type ts(*m, std::adopt_lock);
m = nullptr;
return ts;
} else if (o == ownership::none) {
shared_lock_type ts(*m, std::defer_lock);
m = nullptr;
return ts;
} else if (m == nullptr) {
return shared_lock_type();
}
throw std::system_error((int)std::errc::operation_not_permitted,
std::generic_category());
return shared_lock_type();
}
// Getters
// Note that this returns true if the lock UNIQUE, it will return
// false for shared
bool owns_lock() const noexcept {
return o == ownership::unique;
}
bool owns_lock_shared() const noexcept {
return o == ownership::shared;
}
// If you want to make sure you have a lock of some sort on the
// mutex, just treat as a bool.
explicit operator bool() const noexcept {
return o != ownership::none;
}
mutex_type* mutex() const noexcept {
return m;
}
private:
void lockable() const {
if (m == nullptr)
throw std::system_error((int)std::errc::operation_not_permitted,
std::generic_category());
if (o != ownership::none)
throw std::system_error((int)std::errc::resource_deadlock_would_occur,
std::generic_category());
}
mutex_type* m;
enum struct ownership : uint8_t {
none, unique, shared
};
ownership o;
};
} // namespace ceph
namespace std {
template<typename Mutex>
void swap(ceph::shunique_lock<Mutex> sh1,
ceph::shunique_lock<Mutex> sha) {
sh1.swap(sha);
}
} // namespace std
#endif // CEPH_COMMON_SHUNIQUE_LOCK_H
| 10,608 | 25.926396 | 77 | h |
null | ceph-main/src/common/signal.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) 2011 New Dream Network
*
* 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 <cstdlib>
#include <sstream>
#include <sys/stat.h>
#include <sys/types.h>
#include <signal.h>
#include "common/BackTrace.h"
#include "common/config.h"
#include "common/debug.h"
#include "common/signal.h"
#include "common/perf_counters.h"
#include "global/pidfile.h"
using namespace std::literals;
#ifndef _WIN32
std::string signal_mask_to_str()
{
sigset_t old_sigset;
if (pthread_sigmask(SIG_SETMASK, NULL, &old_sigset)) {
return "(pthread_signmask failed)";
}
std::ostringstream oss;
oss << "show_signal_mask: { ";
auto sep = ""s;
for (int signum = 0; signum < NSIG; ++signum) {
if (sigismember(&old_sigset, signum) == 1) {
oss << sep << signum;
sep = ", ";
}
}
oss << " }";
return oss.str();
}
/* Block the signals in 'siglist'. If siglist == NULL, block all signals. */
void block_signals(const int *siglist, sigset_t *old_sigset)
{
sigset_t sigset;
if (!siglist) {
sigfillset(&sigset);
}
else {
int i = 0;
sigemptyset(&sigset);
while (siglist[i]) {
sigaddset(&sigset, siglist[i]);
++i;
}
}
int ret = pthread_sigmask(SIG_BLOCK, &sigset, old_sigset);
ceph_assert(ret == 0);
}
void restore_sigset(const sigset_t *old_sigset)
{
int ret = pthread_sigmask(SIG_SETMASK, old_sigset, NULL);
ceph_assert(ret == 0);
}
void unblock_all_signals(sigset_t *old_sigset)
{
sigset_t sigset;
sigfillset(&sigset);
sigdelset(&sigset, SIGKILL);
int ret = pthread_sigmask(SIG_UNBLOCK, &sigset, old_sigset);
ceph_assert(ret == 0);
}
#else
std::string signal_mask_to_str()
{
return "(unsupported signal)";
}
// Windows provides limited signal functionality.
void block_signals(const int *siglist, sigset_t *old_sigset) {}
void restore_sigset(const sigset_t *old_sigset) {}
void unblock_all_signals(sigset_t *old_sigset) {}
#endif /* _WIN32 */
| 2,257 | 22.040816 | 76 | cc |
null | ceph-main/src/common/signal.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) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_COMMON_SIGNAL_H
#define CEPH_COMMON_SIGNAL_H
#include <signal.h>
#include <string>
// Returns a string showing the set of blocked signals for the calling thread.
// Other threads may have a different set (this is per-thread thing).
extern std::string signal_mask_to_str();
// Block a list of signals. If siglist == NULL, blocks all signals.
// If not, the list is terminated with a 0 element.
//
// On success, stores the old set of blocked signals in
// old_sigset. On failure, stores an invalid set of blocked signals in
// old_sigset.
extern void block_signals(const int *siglist, sigset_t *old_sigset);
// Restore the set of blocked signals. Will not restore an invalid set of
// blocked signals.
extern void restore_sigset(const sigset_t *old_sigset);
// Unblock all signals. On success, stores the old set of blocked signals in
// old_sigset. On failure, stores an invalid set of blocked signals in
// old_sigset.
extern void unblock_all_signals(sigset_t *old_sigset);
#endif
| 1,410 | 31.813953 | 78 | h |
null | ceph-main/src/common/simple_cache.hpp | // -*- 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_SIMPLECACHE_H
#define CEPH_SIMPLECACHE_H
#include <list>
#include <map>
#include <unordered_map>
#include <utility>
#include "common/ceph_mutex.h"
template <class K, class V, class C = std::less<K>, class H = std::hash<K> >
class SimpleLRU {
ceph::mutex lock = ceph::make_mutex("SimpleLRU::lock");
size_t max_size;
size_t max_bytes = 0;
size_t total_bytes = 0;
std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator, H> contents;
std::list<std::pair<K, V> > lru;
std::map<K, V, C> pinned;
void trim_cache() {
while (contents.size() > max_size) {
contents.erase(lru.back().first);
lru.pop_back();
}
}
void trim_cache_bytes() {
while(total_bytes > max_bytes) {
total_bytes -= lru.back().second.length();
contents.erase(lru.back().first);
lru.pop_back();
}
}
void _add(K key, V&& value) {
lru.emplace_front(key, std::move(value)); // can't move key because we access it below
contents[key] = lru.begin();
trim_cache();
}
void _add_bytes(K key, V&& value) {
lru.emplace_front(key, std::move(value)); // can't move key because we access it below
contents[key] = lru.begin();
trim_cache_bytes();
}
public:
SimpleLRU(size_t max_size) : max_size(max_size) {
contents.rehash(max_size);
}
void pin(K key, V val) {
std::lock_guard l(lock);
pinned.emplace(std::move(key), std::move(val));
}
void clear_pinned(K e) {
std::lock_guard l(lock);
for (auto i = pinned.begin();
i != pinned.end() && i->first <= e;
pinned.erase(i++)) {
auto iter = contents.find(i->first);
if (iter == contents.end())
_add(i->first, std::move(i->second));
else
lru.splice(lru.begin(), lru, iter->second);
}
}
void clear(K key) {
std::lock_guard l(lock);
auto i = contents.find(key);
if (i == contents.end())
return;
total_bytes -= i->second->second.length();
lru.erase(i->second);
contents.erase(i);
}
void set_size(size_t new_size) {
std::lock_guard l(lock);
max_size = new_size;
trim_cache();
}
size_t get_size() {
std::lock_guard l(lock);
return contents.size();
}
void set_bytes(size_t num_bytes) {
std::lock_guard l(lock);
max_bytes = num_bytes;
trim_cache_bytes();
}
size_t get_bytes() {
std::lock_guard l(lock);
return total_bytes;
}
bool lookup(K key, V *out) {
std::lock_guard l(lock);
auto i = contents.find(key);
if (i != contents.end()) {
*out = i->second->second;
lru.splice(lru.begin(), lru, i->second);
return true;
}
auto i_pinned = pinned.find(key);
if (i_pinned != pinned.end()) {
*out = i_pinned->second;
return true;
}
return false;
}
void add(K key, V value) {
std::lock_guard l(lock);
_add(std::move(key), std::move(value));
}
void add_bytes(K key, V value) {
std::lock_guard l(lock);
total_bytes += value.length();
_add_bytes(std::move(key), std::move(value));
}
};
#endif
| 3,477 | 22.821918 | 90 | hpp |
null | ceph-main/src/common/snap_types.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "snap_types.h"
#include "common/Formatter.h"
void SnapRealmInfo::encode(ceph::buffer::list& bl) const
{
h.num_snaps = my_snaps.size();
h.num_prior_parent_snaps = prior_parent_snaps.size();
using ceph::encode;
encode(h, bl);
ceph::encode_nohead(my_snaps, bl);
ceph::encode_nohead(prior_parent_snaps, bl);
}
void SnapRealmInfo::decode(ceph::buffer::list::const_iterator& bl)
{
using ceph::decode;
decode(h, bl);
ceph::decode_nohead(h.num_snaps, my_snaps, bl);
ceph::decode_nohead(h.num_prior_parent_snaps, prior_parent_snaps, bl);
}
void SnapRealmInfo::dump(ceph::Formatter *f) const
{
f->dump_unsigned("ino", ino());
f->dump_unsigned("parent", parent());
f->dump_unsigned("seq", seq());
f->dump_unsigned("parent_since", parent_since());
f->dump_unsigned("created", created());
f->open_array_section("snaps");
for (auto p = my_snaps.begin(); p != my_snaps.end(); ++p)
f->dump_unsigned("snap", *p);
f->close_section();
f->open_array_section("prior_parent_snaps");
for (auto p = prior_parent_snaps.begin(); p != prior_parent_snaps.end(); ++p)
f->dump_unsigned("snap", *p);
f->close_section();
}
void SnapRealmInfo::generate_test_instances(std::list<SnapRealmInfo*>& o)
{
o.push_back(new SnapRealmInfo);
o.push_back(new SnapRealmInfo(1, 10, 10, 0));
o.push_back(new SnapRealmInfo(1, 10, 10, 0));
o.back()->my_snaps.push_back(10);
o.push_back(new SnapRealmInfo(1, 10, 10, 5));
o.back()->my_snaps.push_back(10);
o.back()->prior_parent_snaps.push_back(3);
o.back()->prior_parent_snaps.push_back(5);
}
// -- "new" SnapRealmInfo --
void SnapRealmInfoNew::encode(ceph::buffer::list& bl) const
{
using ceph::encode;
ENCODE_START(1, 1, bl);
encode(info, bl);
encode(last_modified, bl);
encode(change_attr, bl);
ENCODE_FINISH(bl);
}
void SnapRealmInfoNew::decode(ceph::buffer::list::const_iterator& bl)
{
using ceph::decode;
DECODE_START(1, bl);
decode(info, bl);
decode(last_modified, bl);
decode(change_attr, bl);
DECODE_FINISH(bl);
}
void SnapRealmInfoNew::dump(ceph::Formatter *f) const
{
info.dump(f);
f->dump_stream("last_modified") << last_modified;
f->dump_unsigned("change_attr", change_attr);
}
void SnapRealmInfoNew::generate_test_instances(std::list<SnapRealmInfoNew*>& o)
{
o.push_back(new SnapRealmInfoNew);
o.push_back(new SnapRealmInfoNew(SnapRealmInfo(1, 10, 10, 0), utime_t(), 0));
o.push_back(new SnapRealmInfoNew(SnapRealmInfo(1, 10, 10, 0), utime_t(), 1));
o.back()->info.my_snaps.push_back(10);
o.push_back(new SnapRealmInfoNew(SnapRealmInfo(1, 10, 10, 5), utime_t(), 2));
o.back()->info.my_snaps.push_back(10);
o.back()->info.prior_parent_snaps.push_back(3);
o.back()->info.prior_parent_snaps.push_back(5);
}
// -----
bool SnapContext::is_valid() const
{
// seq is a valid snapid
if (seq > CEPH_MAXSNAP)
return false;
if (!snaps.empty()) {
// seq >= snaps[0]
if (snaps[0] > seq)
return false;
// snaps[] is descending
snapid_t t = snaps[0];
for (unsigned i=1; i<snaps.size(); i++) {
if (snaps[i] >= t || t == 0)
return false;
t = snaps[i];
}
}
return true;
}
void SnapContext::dump(ceph::Formatter *f) const
{
f->dump_unsigned("seq", seq);
f->open_array_section("snaps");
for (auto p = snaps.cbegin(); p != snaps.cend(); ++p)
f->dump_unsigned("snap", *p);
f->close_section();
}
void SnapContext::generate_test_instances(std::list<SnapContext*>& o)
{
o.push_back(new SnapContext);
std::vector<snapid_t> v;
o.push_back(new SnapContext(10, v));
v.push_back(18);
v.push_back(3);
v.push_back(1);
o.push_back(new SnapContext(20, v));
}
| 3,757 | 26.231884 | 79 | cc |
null | ceph-main/src/common/snap_types.h | #ifndef __CEPH_SNAP_TYPES_H
#define __CEPH_SNAP_TYPES_H
#include "include/types.h"
#include "include/utime.h"
#include "include/fs_types.h"
namespace ceph {
class Formatter;
}
struct SnapRealmInfo {
mutable ceph_mds_snap_realm h;
std::vector<snapid_t> my_snaps;
std::vector<snapid_t> prior_parent_snaps; // before parent_since
SnapRealmInfo() {
// FIPS zeroization audit 20191115: this memset is not security related.
memset(&h, 0, sizeof(h));
}
SnapRealmInfo(inodeno_t ino_, snapid_t created_, snapid_t seq_, snapid_t current_parent_since_) {
// FIPS zeroization audit 20191115: this memset is not security related.
memset(&h, 0, sizeof(h));
h.ino = ino_;
h.created = created_;
h.seq = seq_;
h.parent_since = current_parent_since_;
}
inodeno_t ino() const { return inodeno_t(h.ino); }
inodeno_t parent() const { return inodeno_t(h.parent); }
snapid_t seq() const { return snapid_t(h.seq); }
snapid_t parent_since() const { return snapid_t(h.parent_since); }
snapid_t created() const { return snapid_t(h.created); }
void encode(ceph::buffer::list& bl) const;
void decode(ceph::buffer::list::const_iterator& bl);
void dump(ceph::Formatter *f) const;
static void generate_test_instances(std::list<SnapRealmInfo*>& o);
};
WRITE_CLASS_ENCODER(SnapRealmInfo)
// "new* snap realm info - carries additional metadata (last modified,
// change_attr) and is version encoded.
struct SnapRealmInfoNew {
SnapRealmInfo info;
utime_t last_modified;
uint64_t change_attr;
SnapRealmInfoNew() {
}
SnapRealmInfoNew(const SnapRealmInfo &info_, utime_t last_modified_, uint64_t change_attr_) {
// FIPS zeroization audit 20191115: this memset is not security related.
info = info_;
last_modified = last_modified_;
change_attr = change_attr_;
}
inodeno_t ino() const { return inodeno_t(info.h.ino); }
inodeno_t parent() const { return inodeno_t(info.h.parent); }
snapid_t seq() const { return snapid_t(info.h.seq); }
snapid_t parent_since() const { return snapid_t(info.h.parent_since); }
snapid_t created() const { return snapid_t(info.h.created); }
void encode(ceph::buffer::list& bl) const;
void decode(ceph::buffer::list::const_iterator& bl);
void dump(ceph::Formatter *f) const;
static void generate_test_instances(std::list<SnapRealmInfoNew*>& o);
};
WRITE_CLASS_ENCODER(SnapRealmInfoNew)
struct SnapContext {
snapid_t seq; // 'time' stamp
std::vector<snapid_t> snaps; // existent snaps, in descending order
SnapContext() {}
SnapContext(snapid_t s, const std::vector<snapid_t>& v) : seq(s), snaps(v) {}
bool is_valid() const;
void clear() {
seq = 0;
snaps.clear();
}
bool empty() const { return seq == 0; }
void encode(ceph::buffer::list& bl) const {
using ceph::encode;
encode(seq, bl);
encode(snaps, bl);
}
void decode(ceph::buffer::list::const_iterator& bl) {
using ceph::decode;
decode(seq, bl);
decode(snaps, bl);
}
void dump(ceph::Formatter *f) const;
static void generate_test_instances(std::list<SnapContext*>& o);
};
WRITE_CLASS_ENCODER(SnapContext)
inline std::ostream& operator<<(std::ostream& out, const SnapContext& snapc) {
return out << snapc.seq << "=" << snapc.snaps;
}
#if FMT_VERSION >= 90000
template <> struct fmt::formatter<SnapContext> : fmt::ostream_formatter {};
#endif
#endif
| 3,395 | 29.321429 | 99 | h |
null | ceph-main/src/common/solaris_errno.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) 2011 New Dream Network
*
* 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 "include/types.h"
// converts from linux errno values to host values
__s32 ceph_to_hostos_errno(__s32 r)
{
if (r < -34) {
switch (r) {
case -35:
return -EDEADLK;
case -36:
return -ENAMETOOLONG;
case -37:
return -ENOLCK;
case -38:
return -ENOSYS;
case -39:
return -ENOTEMPTY;
case -40:
return -ELOOP;
case -42:
return -ENOMSG;
case -43:
return -EIDRM;
case -44:
return -ECHRNG;
case -45:
return -EL2NSYNC;
case -46:
return -EL3HLT;
case -47:
return -EL3RST;
case -48:
return -ELNRNG;
case -49:
return -EUNATCH;
case -50:
return -ENOCSI;
case -51:
return -EL2HLT;
case -52:
return -EBADE;
case -53:
return -EBADR;
case -54:
return -EXFULL;
case -55:
return -ENOANO;
case -56:
return -EBADRQC;
case -57:
return -EBADSLT;
case -59:
return -EBFONT;
case -60:
return -ENOSTR;
case -61:
return -ENODATA;
case -62:
return -ETIME;
case -63:
return -ENOSR;
//case -64:
// return -EPERM; //TODO ENONET
//case -65:
// return -EPERM; //TODO ENOPKG
//case -66:
// return -EREMOTE;
//case -67:
// return -ENOLINK;
//case -68:
// return -EPERM; //TODO EADV
//case -69:
// return -EPERM; //TODO ESRMNT
//case -70:
// return -EPERM; //TODO ECOMM
case -71:
return -EPROTO;
case -72:
return -EMULTIHOP;
case -73:
return -EPERM; //TODO EDOTDOT
case -74:
return -EBADMSG;
case -75:
return -EOVERFLOW;
case -76:
return -ENOTUNIQ;
case -77:
return -EBADFD;
case -78:
return -EREMCHG;
case -79:
return -ELIBACC;
case -80:
return -ELIBBAD;
case -81:
return -ELIBSCN;
case -82:
return -ELIBMAX;
case -83:
return -ELIBEXEC;
case -84:
return -EILSEQ;
case -85:
return -ERESTART;
case -86:
return -ESTRPIPE;
case -87:
return -EUSERS;
case -88:
return -ENOTSOCK;
case -89:
return -EDESTADDRREQ;
case -90:
return -EMSGSIZE;
case -91:
return -EPROTOTYPE;
case -92:
return -ENOPROTOOPT;
case -93:
return -EPROTONOSUPPORT;
case -94:
return -ESOCKTNOSUPPORT;
case -95:
return -EOPNOTSUPP;
case -96:
return -EPFNOSUPPORT;
case -97:
return -EAFNOSUPPORT;
case -98:
return -EADDRINUSE;
case -99:
return -EADDRNOTAVAIL;
case -100:
return -ENETDOWN;
case -101:
return -ENETUNREACH;
case -102:
return -ENETRESET;
case -103:
return -ECONNABORTED;
case -104:
return -ECONNRESET;
case -105:
return -ENOBUFS;
case -106:
return -EISCONN;
case -107:
return -ENOTCONN;
case -108:
return -ESHUTDOWN;
case -109:
return -ETOOMANYREFS;
case -110:
return -ETIMEDOUT;
case -111:
return -ECONNREFUSED;
case -112:
return -EHOSTDOWN;
case -113:
return -EHOSTUNREACH;
case -114:
return -EALREADY;
case -115:
return -EINPROGRESS;
case -116:
return -ESTALE;
case -117:
return -EPERM; //TODO EUCLEAN
case -118:
return -EPERM; //TODO ENOTNAM
case -119:
return -EPERM; //TODO ENAVAIL
case -120:
return -EPERM; //TODO EISNAM
case -121:
return -EPERM; //TODO EREMOTEIO
case -122:
return -EDQUOT;
case -123:
return -EPERM; //TODO ENOMEDIUM
case -124:
return -EPERM; //TODO EMEDIUMTYPE - not used
case -125:
return -ECANCELED;
case -126:
return -EPERM; //TODO ENOKEY
case -127:
return -EPERM; //TODO EKEYEXPIRED
case -128:
return -EPERM; //TODO EKEYREVOKED
case -129:
return -EPERM; //TODO EKEYREJECTED
case -130:
return -EOWNERDEAD;
case -131:
return -ENOTRECOVERABLE;
case -132:
return -EPERM; //TODO ERFKILL
case -133:
return -EPERM; //TODO EHWPOISON
default: {
break;
}
}
}
return r; // otherwise return original value
}
// converts Host OS errno values to linux/Ceph values
// XXX Currently not worked out
__s32 hostos_to_ceph_errno(__s32 r)
{
return r;
}
| 5,205 | 21.247863 | 70 | cc |
null | ceph-main/src/common/split.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, 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
#include <string_view>
namespace ceph {
// a forward iterator over the parts of a split string
class spliterator {
std::string_view str; // full string
std::string_view delims; // delimiters
using size_type = std::string_view::size_type;
size_type pos = 0; // start position of current part
std::string_view part; // view of current part
// return the next part after the given position
std::string_view next(size_type end) {
pos = str.find_first_not_of(delims, end);
if (pos == str.npos) {
return {};
}
return str.substr(pos, str.find_first_of(delims, pos) - pos);
}
public:
// types required by std::iterator_traits
using difference_type = int;
using value_type = std::string_view;
using pointer = const value_type*;
using reference = const value_type&;
using iterator_category = std::forward_iterator_tag;
spliterator() = default;
spliterator(std::string_view str, std::string_view delims)
: str(str), delims(delims), pos(0), part(next(0))
{}
spliterator& operator++() {
part = next(pos + part.size());
return *this;
}
spliterator operator++(int) {
spliterator tmp = *this;
part = next(pos + part.size());
return tmp;
}
reference operator*() const { return part; }
pointer operator->() const { return ∂ }
friend bool operator==(const spliterator& lhs, const spliterator& rhs) {
return lhs.part.data() == rhs.part.data()
&& lhs.part.size() == rhs.part.size();
}
friend bool operator!=(const spliterator& lhs, const spliterator& rhs) {
return lhs.part.data() != rhs.part.data()
|| lhs.part.size() != rhs.part.size();
}
};
// represents an immutable range of split string parts
//
// ranged-for loop example:
//
// for (std::string_view s : split(input)) {
// ...
//
// container initialization example:
//
// auto parts = split(input);
//
// std::vector<std::string> strings;
// strings.assign(parts.begin(), parts.end());
//
class split {
std::string_view str; // full string
std::string_view delims; // delimiters
public:
split(std::string_view str, std::string_view delims = ";,= \t\n")
: str(str), delims(delims) {}
using iterator = spliterator;
using const_iterator = spliterator;
iterator begin() const { return {str, delims}; }
const_iterator cbegin() const { return {str, delims}; }
iterator end() const { return {}; }
const_iterator cend() const { return {}; }
};
} // namespace ceph
| 2,899 | 25.851852 | 74 | h |
null | ceph-main/src/common/static_ptr.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, 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
#include <cstddef>
#include <utility>
#include <type_traits>
namespace ceph {
// `static_ptr`
// ===========
//
// It would be really nice if polymorphism didn't require a bunch of
// mucking about with the heap. So let's build something where we
// don't have to do that.
//
namespace _mem {
// This, an operator function, is one of the canonical ways to do type
// erasure in C++ so long as all operations can be done with subsets
// of the same arguments (which is not true for function type erasure)
// it's a pretty good one.
enum class op {
move, destroy, size
};
template<typename T>
static std::size_t op_fun(op oper, void* p1, void* p2)
{
auto me = static_cast<T*>(p1);
switch (oper) {
case op::move:
new (p2) T(std::move(*me));
break;
case op::destroy:
me->~T();
break;
case op::size:
return sizeof(T);
}
return 0;
}
}
// The thing itself!
//
// The default value for Size may be wrong in almost all cases. You
// can change it to your heart's content. The upside is that you'll
// just get a compile error and you can bump it up.
//
// I *recommend* having a size constant in header files (or perhaps a
// using declaration, e.g.
// ```
// using StaticFoo = static_ptr<Foo, sizeof(Blah)>`
// ```
// in some header file that can be used multiple places) so that when
// you create a new derived class with a larger size, you only have to
// change it in one place.
//
template<typename Base, std::size_t Size = sizeof(Base)>
class static_ptr {
template<typename U, std::size_t S>
friend class static_ptr;
// Refuse to be set to anything with whose type we are
// incompatible. Also never try to eat anything bigger than you are.
//
template<typename T, std::size_t S>
constexpr static int create_ward() noexcept {
static_assert(std::is_void_v<Base> ||
std::is_base_of_v<Base, std::decay_t<T>>,
"Value to store must be a derivative of the base.");
static_assert(S <= Size, "Value too large.");
static_assert(std::is_void_v<Base> || !std::is_const<Base>{} ||
std::is_const_v<T>,
"Cannot assign const pointer to non-const pointer.");
return 0;
}
// Here we can store anything that has the same signature, which is
// relevant to the multiple-versions for move/copy support that I
// mentioned above.
//
size_t (*operate)(_mem::op, void*, void*);
// This is mutable so that get and the dereference operators can be
// const. Since we're modeling a pointer, we should preserve the
// difference in semantics between a pointer-to-const and a const
// pointer.
//
mutable typename std::aligned_storage<Size>::type buf;
public:
using element_type = Base;
using pointer = Base*;
// Empty
static_ptr() noexcept : operate(nullptr) {}
static_ptr(std::nullptr_t) noexcept : operate(nullptr) {}
static_ptr& operator =(std::nullptr_t) noexcept {
reset();
return *this;
}
~static_ptr() noexcept {
reset();
}
// Since other pointer-ish types have it
void reset() noexcept {
if (operate) {
operate(_mem::op::destroy, &buf, nullptr);
operate = nullptr;
}
}
// Set from another static pointer.
//
// Since the templated versions don't count for overriding the defaults
static_ptr(static_ptr&& rhs)
noexcept(std::is_nothrow_move_constructible_v<Base>) : operate(rhs.operate) {
if (operate) {
operate(_mem::op::move, &rhs.buf, &buf);
}
}
template<typename U, std::size_t S>
static_ptr(static_ptr<U, S>&& rhs)
noexcept(std::is_nothrow_move_constructible_v<U>) : operate(rhs.operate) {
create_ward<U, S>();
if (operate) {
operate(_mem::op::move, &rhs.buf, &buf);
}
}
static_ptr& operator =(static_ptr&& rhs)
noexcept(std::is_nothrow_move_constructible_v<Base>) {
reset();
if (rhs) {
operate = rhs.operate;
operate(_mem::op::move, &rhs.buf, &buf);
}
return *this;
}
template<typename U, std::size_t S>
static_ptr& operator =(static_ptr<U, S>&& rhs)
noexcept(std::is_nothrow_move_constructible_v<U>) {
create_ward<U, S>();
reset();
if (rhs) {
operate = rhs.operate;
operate(_mem::op::move, &rhs.buf, &buf);
}
return *this;
}
bool operator ==(std::nullptr_t) const {
return !operate;
}
// In-place construction!
//
// This is basically what you want, and I didn't include value
// construction because in-place construction renders it
// unnecessary. Also it doesn't fit the pointer idiom as well.
//
template<typename T, typename... Args>
static_ptr(std::in_place_type_t<T>, Args&& ...args)
noexcept(std::is_nothrow_constructible_v<T, Args...>)
: operate(&_mem::op_fun<T>){
static_assert((!std::is_nothrow_copy_constructible_v<Base> ||
std::is_nothrow_copy_constructible_v<T>) &&
(!std::is_nothrow_move_constructible_v<Base> ||
std::is_nothrow_move_constructible_v<T>),
"If declared type of static_ptr is nothrow "
"move/copy constructible, then any "
"type assigned to it must be as well. "
"You can use reinterpret_pointer_cast "
"to get around this limit, but don't "
"come crying to me when the C++ "
"runtime calls terminate().");
create_ward<T, sizeof(T)>();
new (&buf) T(std::forward<Args>(args)...);
}
// I occasionally get tempted to make an overload of the assignment
// operator that takes a tuple as its right-hand side to provide
// arguments.
//
template<typename T, typename... Args>
void emplace(Args&& ...args)
noexcept(std::is_nothrow_constructible_v<T, Args...>) {
create_ward<T, sizeof(T)>();
reset();
operate = &_mem::op_fun<T>;
new (&buf) T(std::forward<Args>(args)...);
}
// Access!
Base* get() const noexcept {
return operate ? reinterpret_cast<Base*>(&buf) : nullptr;
}
template<typename U = Base>
std::enable_if_t<!std::is_void_v<U>, Base*> operator->() const noexcept {
return get();
}
template<typename U = Base>
std::enable_if_t<!std::is_void_v<U>, Base&> operator *() const noexcept {
return *get();
}
operator bool() const noexcept {
return !!operate;
}
// Big wall of friendship
//
template<typename U, std::size_t Z, typename T, std::size_t S>
friend static_ptr<U, Z> static_pointer_cast(const static_ptr<T, S>& p);
template<typename U, std::size_t Z, typename T, std::size_t S>
friend static_ptr<U, Z> static_pointer_cast(static_ptr<T, S>&& p);
template<typename U, std::size_t Z, typename T, std::size_t S>
friend static_ptr<U, Z> dynamic_pointer_cast(const static_ptr<T, S>& p);
template<typename U, std::size_t Z, typename T, std::size_t S>
friend static_ptr<U, Z> dynamic_pointer_cast(static_ptr<T, S>&& p);
template<typename U, std::size_t Z, typename T, std::size_t S>
friend static_ptr<U, Z> const_pointer_cast(const static_ptr<T, S>& p);
template<typename U, std::size_t Z, typename T, std::size_t S>
friend static_ptr<U, Z> const_pointer_cast(static_ptr<T, S>&& p);
template<typename U, std::size_t Z, typename T, std::size_t S>
friend static_ptr<U, Z> reinterpret_pointer_cast(const static_ptr<T, S>& p);
template<typename U, std::size_t Z, typename T, std::size_t S>
friend static_ptr<U, Z> reinterpret_pointer_cast(static_ptr<T, S>&& p);
template<typename U, std::size_t Z, typename T, std::size_t S>
friend static_ptr<U, Z> resize_pointer_cast(const static_ptr<T, S>& p);
template<typename U, std::size_t Z, typename T, std::size_t S>
friend static_ptr<U, Z> resize_pointer_cast(static_ptr<T, S>&& p);
};
// These are all modeled after the same ones for shared pointer.
//
// Also I'm annoyed that the standard library doesn't have
// *_pointer_cast overloads for a move-only unique pointer. It's a
// nice idiom. Having to release and reconstruct is obnoxious.
//
template<typename U, std::size_t Z, typename T, std::size_t S>
static_ptr<U, Z> static_pointer_cast(static_ptr<T, S>&& p) {
static_assert(Z >= S,
"Value too large.");
static_ptr<U, Z> r;
if (static_cast<U*>(p.get())) {
p.operate(_mem::op::move, &p.buf, &r.buf);
r.operate = p.operate;
}
return r;
}
// Here the conditional is actually important and ensures we have the
// same behavior as dynamic_cast.
//
template<typename U, std::size_t Z, typename T, std::size_t S>
static_ptr<U, Z> dynamic_pointer_cast(static_ptr<T, S>&& p) {
static_assert(Z >= S,
"Value too large.");
static_ptr<U, Z> r;
if (dynamic_cast<U*>(p.get())) {
p.operate(_mem::op::move, &p.buf, &r.buf);
r.operate = p.operate;
}
return r;
}
template<typename U, std::size_t Z, typename T, std::size_t S>
static_ptr<U, Z> const_pointer_cast(static_ptr<T, S>&& p) {
static_assert(Z >= S,
"Value too large.");
static_ptr<U, Z> r;
if (const_cast<U*>(p.get())) {
p.operate(_mem::op::move, &p.buf, &r.buf);
r.operate = p.operate;
}
return r;
}
// I'm not sure if anyone will ever use this. I can imagine situations
// where they might. It works, though!
//
template<typename U, std::size_t Z, typename T, std::size_t S>
static_ptr<U, Z> reinterpret_pointer_cast(static_ptr<T, S>&& p) {
static_assert(Z >= S,
"Value too large.");
static_ptr<U, Z> r;
p.operate(_mem::op::move, &p.buf, &r.buf);
r.operate = p.operate;
return r;
}
// This is the only way to move from a bigger static pointer into a
// smaller static pointer. The size of the total data stored in the
// pointer is checked at runtime and if the destination size is large
// enough, we copy it over.
//
// I follow cast semantics. Since this is a pointer-like type, it
// returns a null value rather than throwing.
template<typename U, std::size_t Z, typename T, std::size_t S>
static_ptr<U, Z> resize_pointer_cast(static_ptr<T, S>&& p) {
static_assert(std::is_same_v<U, T>,
"resize_pointer_cast only changes size, not type.");
static_ptr<U, Z> r;
if (Z >= p.operate(_mem::op::size, &p.buf, nullptr)) {
p.operate(_mem::op::move, &p.buf, &r.buf);
r.operate = p.operate;
}
return r;
}
// Since `make_unique` and `make_shared` exist, we should follow their
// lead.
//
template<typename Base, typename Derived = Base,
std::size_t Size = sizeof(Derived), typename... Args>
static_ptr<Base, Size> make_static(Args&& ...args) {
return { std::in_place_type<Derived>, std::forward<Args>(args)... };
}
}
| 10,890 | 30.845029 | 81 | h |
null | ceph-main/src/common/str_list.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) 2009-2010 Dreamhost
*
* 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 "include/str_list.h"
using std::string;
using std::vector;
using std::list;
using ceph::for_each_substr;
void get_str_list(const string& str, const char *delims, list<string>& str_list)
{
str_list.clear();
for_each_substr(str, delims, [&str_list] (auto token) {
str_list.emplace_back(token.begin(), token.end());
});
}
void get_str_list(const string& str, list<string>& str_list)
{
const char *delims = ";,= \t";
get_str_list(str, delims, str_list);
}
list<string> get_str_list(const string& str, const char *delims)
{
list<string> result;
get_str_list(str, delims, result);
return result;
}
void get_str_vec(std::string_view str, const char *delims, vector<string>& str_vec)
{
str_vec.clear();
for_each_substr(str, delims, [&str_vec] (auto token) {
str_vec.emplace_back(token.begin(), token.end());
});
}
void get_str_vec(std::string_view str, vector<string>& str_vec)
{
const char *delims = ";,= \t";
get_str_vec(str, delims, str_vec);
}
vector<string> get_str_vec(std::string_view str, const char *delims)
{
vector<string> result;
for_each_substr(str, delims, [&result] (auto token) {
result.emplace_back(token.begin(), token.end());
});
return result;
}
| 1,638 | 24.215385 | 83 | cc |
null | ceph-main/src/common/str_map.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2013 Cloudwatt <[email protected]>
*
* Author: Loic Dachary <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
*/
#include "include/str_map.h"
#include "include/str_list.h"
#include <boost/algorithm/string.hpp>
#include "json_spirit/json_spirit.h"
using namespace std;
int get_json_str_map(
const string &str,
ostream &ss,
str_map_t *str_map,
bool fallback_to_plain)
{
json_spirit::mValue json;
try {
// try json parsing first
json_spirit::read_or_throw(str, json);
if (json.type() != json_spirit::obj_type) {
ss << str << " must be a JSON object but is of type "
<< json.type() << " instead";
return -EINVAL;
}
json_spirit::mObject o = json.get_obj();
for (map<string, json_spirit::mValue>::iterator i = o.begin();
i != o.end();
++i) {
(*str_map)[i->first] = i->second.get_str();
}
} catch (json_spirit::Error_position &e) {
if (fallback_to_plain) {
// fallback to key=value format
get_str_map(str, str_map, "\t\n ");
} else {
return -EINVAL;
}
}
return 0;
}
static std::string_view trim(std::string_view str)
{
static const char* whitespaces = "\t\n ";
auto beg = str.find_first_not_of(whitespaces);
if (beg == str.npos) {
return {};
}
auto end = str.find_last_not_of(whitespaces);
return str.substr(beg, end - beg + 1);
}
int get_str_map(
const string &str,
str_map_t* str_map,
const char *delims)
{
for_each_pair(str, delims, [str_map](std::string_view key,
std::string_view val) {
// is the format 'K=V' or just 'K'?
if (val.empty()) {
str_map->emplace(std::string(key), "");
} else {
str_map->emplace(std::string(trim(key)), std::string(trim(val)));
}
});
return 0;
}
str_map_t get_str_map(
const string& str,
const char* delim)
{
str_map_t str_map;
get_str_map(str, &str_map, delim);
return str_map;
}
string get_str_map_value(
const str_map_t &str_map,
const string &key,
const string *def_val)
{
auto p = str_map.find(key);
// key exists in str_map
if (p != str_map.end()) {
// but value is empty
if (p->second.empty())
return p->first;
// and value is not empty
return p->second;
}
// key DNE in str_map and def_val was specified
if (def_val != nullptr)
return *def_val;
// key DNE in str_map, no def_val was specified
return string();
}
string get_str_map_key(
const str_map_t &str_map,
const string &key,
const string *fallback_key)
{
auto p = str_map.find(key);
if (p != str_map.end())
return p->second;
if (fallback_key != nullptr) {
p = str_map.find(*fallback_key);
if (p != str_map.end())
return p->second;
}
return string();
}
// This function's only purpose is to check whether a given map has only
// ONE key with an empty value (which would mean that 'get_str_map()' read
// a map in the form of 'VALUE', without any KEY/VALUE pairs) and, in such
// event, to assign said 'VALUE' to a given 'def_key', such that we end up
// with a map of the form "m = { 'def_key' : 'VALUE' }" instead of the
// original "m = { 'VALUE' : '' }".
int get_conf_str_map_helper(
const string &str,
ostringstream &oss,
str_map_t* str_map,
const string &default_key)
{
get_str_map(str, str_map);
if (str_map->size() == 1) {
auto p = str_map->begin();
if (p->second.empty()) {
string s = p->first;
str_map->erase(s);
(*str_map)[default_key] = s;
}
}
return 0;
}
std::string get_value_via_strmap(
const string& conf_string,
std::string_view default_key)
{
auto mp = get_str_map(conf_string);
if (mp.size() != 1) {
return "";
}
// if the one-elem "map" is of the form { 'value' : '' }
// replace it with { 'default_key' : 'value' }
const auto& [k, v] = *(mp.begin());
if (v.empty()) {
return k;
}
return v;
}
std::string get_value_via_strmap(
const string& conf_string,
const string& key,
std::string_view default_key)
{
auto mp = get_str_map(conf_string);
if (mp.size() != 1) {
return std::string{};
}
// if the one-elem "map" is of the form { 'value' : '' }
// replace it with { 'default_key' : 'value' }
const auto& [k, v] = *(mp.begin());
if (v.empty()) {
return k;
}
if (k == key) {
return k;
}
if (k == default_key) {
return v;
}
return string{};
}
| 4,811 | 22.134615 | 74 | cc |
null | ceph-main/src/common/strescape.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) 2021 Red Hat, 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_STRESCAPE_H
#define CEPH_STRESCAPE_H
#include <algorithm>
#include <ostream>
#include <string_view>
#include <ctype.h>
inline std::string binstrprint(std::string_view sv, size_t maxlen=0)
{
std::string s;
if (maxlen == 0 || sv.size() < maxlen) {
s = std::string(sv);
} else {
maxlen = std::max<size_t>(8, maxlen);
s = std::string(sv.substr(0, maxlen-3)) + "...";
}
std::replace_if(s.begin(), s.end(), [](char c){ return !(isalnum(c) || ispunct(c)); }, '.');
return s;
}
#endif
| 923 | 23.315789 | 94 | h |
null | ceph-main/src/common/strtol.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) 2011 New Dream Network
*
* 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 "strtol.h"
#include <algorithm>
#include <climits>
#include <limits>
#include <cmath>
#include <sstream>
#include <strings.h>
#include <string_view>
using std::ostringstream;
bool strict_strtob(const char* str, std::string *err)
{
if (strcasecmp(str, "false") == 0) {
return false;
} else if (strcasecmp(str, "true") == 0) {
return true;
} else {
int b = strict_strtol(str, 10, err);
return (bool)!!b;
}
}
long long strict_strtoll(std::string_view str, int base, std::string *err)
{
char *endptr;
errno = 0; /* To distinguish success/failure after call (see man page) */
long long ret = strtoll(str.data(), &endptr, base);
if (endptr == str.data() || endptr != str.data() + str.size()) {
*err = (std::string{"Expected option value to be integer, got '"} +
std::string{str} + "'");
return 0;
}
if (errno) {
*err = (std::string{"The option value '"} + std::string{str} +
"' seems to be invalid");
return 0;
}
*err = "";
return ret;
}
int strict_strtol(std::string_view str, int base, std::string *err)
{
long long ret = strict_strtoll(str, base, err);
if (!err->empty())
return 0;
if ((ret < INT_MIN) || (ret > INT_MAX)) {
ostringstream errStr;
errStr << "The option value '" << str << "' seems to be invalid";
*err = errStr.str();
return 0;
}
return static_cast<int>(ret);
}
int strict_strtol(const char *str, int base, std::string *err)
{
return strict_strtol(std::string_view(str), base, err);
}
double strict_strtod(std::string_view str, std::string *err)
{
char *endptr;
errno = 0; /* To distinguish success/failure after call (see man page) */
double ret = strtod(str.data(), &endptr);
if (errno == ERANGE) {
ostringstream oss;
oss << "strict_strtod: floating point overflow or underflow parsing '"
<< str << "'";
*err = oss.str();
return 0.0;
}
if (endptr == str) {
ostringstream oss;
oss << "strict_strtod: expected double, got: '" << str << "'";
*err = oss.str();
return 0;
}
if (*endptr != '\0') {
ostringstream oss;
oss << "strict_strtod: garbage at end of string. got: '" << str << "'";
*err = oss.str();
return 0;
}
*err = "";
return ret;
}
float strict_strtof(std::string_view str, std::string *err)
{
char *endptr;
errno = 0; /* To distinguish success/failure after call (see man page) */
float ret = strtof(str.data(), &endptr);
if (errno == ERANGE) {
ostringstream oss;
oss << "strict_strtof: floating point overflow or underflow parsing '"
<< str << "'";
*err = oss.str();
return 0.0;
}
if (endptr == str) {
ostringstream oss;
oss << "strict_strtof: expected float, got: '" << str << "'";
*err = oss.str();
return 0;
}
if (*endptr != '\0') {
ostringstream oss;
oss << "strict_strtof: garbage at end of string. got: '" << str << "'";
*err = oss.str();
return 0;
}
*err = "";
return ret;
}
template<typename T>
T strict_iec_cast(std::string_view str, std::string *err)
{
if (str.empty()) {
*err = "strict_iecstrtoll: value not specified";
return 0;
}
// get a view of the unit and of the value
std::string_view unit;
std::string_view n = str;
size_t u = str.find_first_not_of("0123456789-+");
int m = 0;
// deal with unit prefix if there is one
if (u != std::string_view::npos) {
n = str.substr(0, u);
unit = str.substr(u, str.length() - u);
// we accept both old si prefixes as well as the proper iec prefixes
// i.e. K, M, ... and Ki, Mi, ...
if (unit.back() == 'i') {
if (unit.front() == 'B') {
*err = "strict_iecstrtoll: illegal prefix \"Bi\"";
return 0;
}
}
if (unit.length() > 2) {
*err = "strict_iecstrtoll: illegal prefix (length > 2)";
return 0;
}
switch(unit.front()) {
case 'K':
m = 10;
break;
case 'M':
m = 20;
break;
case 'G':
m = 30;
break;
case 'T':
m = 40;
break;
case 'P':
m = 50;
break;
case 'E':
m = 60;
break;
case 'B':
break;
default:
*err = "strict_iecstrtoll: unit prefix not recognized";
return 0;
}
}
long long ll = strict_strtoll(n, 10, err);
if (ll < 0 && !std::numeric_limits<T>::is_signed) {
*err = "strict_iecstrtoll: value should not be negative";
return 0;
}
if (static_cast<unsigned>(m) >= sizeof(T) * CHAR_BIT) {
*err = ("strict_iecstrtoll: the IEC prefix is too large for the designated "
"type");
return 0;
}
using promoted_t = typename std::common_type<decltype(ll), T>::type;
if (static_cast<promoted_t>(ll) <
static_cast<promoted_t>(std::numeric_limits<T>::min()) >> m) {
*err = "strict_iecstrtoll: value seems to be too small";
return 0;
}
if (static_cast<promoted_t>(ll) >
static_cast<promoted_t>(std::numeric_limits<T>::max()) >> m) {
*err = "strict_iecstrtoll: value seems to be too large";
return 0;
}
return (ll << m);
}
template int strict_iec_cast<int>(std::string_view str, std::string *err);
template long strict_iec_cast<long>(std::string_view str, std::string *err);
template long long strict_iec_cast<long long>(std::string_view str, std::string *err);
template uint64_t strict_iec_cast<uint64_t>(std::string_view str, std::string *err);
template uint32_t strict_iec_cast<uint32_t>(std::string_view str, std::string *err);
uint64_t strict_iecstrtoll(std::string_view str, std::string *err)
{
return strict_iec_cast<uint64_t>(str, err);
}
template<typename T>
T strict_si_cast(std::string_view str, std::string *err)
{
if (str.empty()) {
*err = "strict_sistrtoll: value not specified";
return 0;
}
std::string_view n = str;
int m = 0;
// deal with unit prefix is there is one
if (str.find_first_not_of("0123456789+-") != std::string_view::npos) {
const char &u = str.back();
if (u == 'K')
m = 3;
else if (u == 'M')
m = 6;
else if (u == 'G')
m = 9;
else if (u == 'T')
m = 12;
else if (u == 'P')
m = 15;
else if (u == 'E')
m = 18;
else if (u != 'B') {
*err = "strict_si_cast: unit prefix not recognized";
return 0;
}
if (m >= 3)
n = str.substr(0, str.length() -1);
}
long long ll = strict_strtoll(n, 10, err);
if (ll < 0 && !std::numeric_limits<T>::is_signed) {
*err = "strict_sistrtoll: value should not be negative";
return 0;
}
using promoted_t = typename std::common_type<decltype(ll), T>::type;
auto v = static_cast<promoted_t>(ll);
auto coefficient = static_cast<promoted_t>(powl(10, m));
if (v != std::clamp(v,
(static_cast<promoted_t>(std::numeric_limits<T>::min()) /
coefficient),
(static_cast<promoted_t>(std::numeric_limits<T>::max()) /
coefficient))) {
*err = "strict_sistrtoll: value out of range";
return 0;
}
return v * coefficient;
}
template int strict_si_cast<int>(std::string_view str, std::string *err);
template long strict_si_cast<long>(std::string_view str, std::string *err);
template long long strict_si_cast<long long>(std::string_view str, std::string *err);
template uint64_t strict_si_cast<uint64_t>(std::string_view str, std::string *err);
template uint32_t strict_si_cast<uint32_t>(std::string_view str, std::string *err);
| 7,829 | 26.964286 | 86 | cc |
null | ceph-main/src/common/strtol.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) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_COMMON_STRTOL_H
#define CEPH_COMMON_STRTOL_H
#include <charconv>
#include <cinttypes>
#include <cstdlib>
#include <optional>
#include <string>
#include <string_view>
#include <system_error>
#include <type_traits>
namespace ceph {
// Wrappers around std::from_chars.
//
// Why do we want this instead of strtol and friends? Because the
// string doesn't have to be NUL-terminated! (Also, for a lot of
// purposes, just putting a string_view in and getting an optional out
// is friendly.)
//
// Returns the found number on success. Returns an empty optional on
// failure OR on trailing characters.
// Sadly GCC < 11 is missing the floating point versions.
template<typename T>
auto parse(std::string_view s, int base = 10)
-> std::enable_if_t<std::is_integral_v<T>, std::optional<T>>
{
T t;
auto r = std::from_chars(s.data(), s.data() + s.size(), t, base);
if ((r.ec != std::errc{}) || (r.ptr != s.data() + s.size())) {
return std::nullopt;
}
return t;
}
// As above, but succeed on trailing characters and trim the supplied
// string_view to remove the parsed number. Set the supplied
// string_view to empty if it ends with the number.
template<typename T>
auto consume(std::string_view& s, int base = 10)
-> std::enable_if_t<std::is_integral_v<T>, std::optional<T>>
{
T t;
auto r = std::from_chars(s.data(), s.data() + s.size(), t, base);
if (r.ec != std::errc{})
return std::nullopt;
if (r.ptr == s.data() + s.size()) {
s = std::string_view{};
} else {
s.remove_prefix(r.ptr - s.data());
}
return t;
}
} // namespace ceph
bool strict_strtob(const char* str, std::string *err);
long long strict_strtoll(std::string_view str, int base, std::string *err);
int strict_strtol(std::string_view str, int base, std::string *err);
double strict_strtod(std::string_view str, std::string *err);
float strict_strtof(std::string_view str, std::string *err);
uint64_t strict_iecstrtoll(std::string_view str, std::string *err);
template<typename T>
T strict_iec_cast(std::string_view str, std::string *err);
template<typename T>
T strict_si_cast(std::string_view str, std::string *err);
/* On enter buf points to the end of the buffer, e.g. where the least
* significant digit of the input number will be printed. Returns pointer to
* where the most significant digit were printed, including zero padding.
* Does NOT add zero at the end of buffer, this is responsibility of the caller.
*/
template<typename T, const unsigned base = 10, const unsigned width = 1>
static inline
char* ritoa(T u, char *buf)
{
static_assert(std::is_unsigned_v<T>, "signed types are not supported");
static_assert(base <= 16, "extend character map below to support higher bases");
unsigned digits = 0;
while (u) {
*--buf = "0123456789abcdef"[u % base];
u /= base;
digits++;
}
while (digits++ < width)
*--buf = '0';
return buf;
}
#endif
| 3,318 | 28.371681 | 82 | h |
null | ceph-main/src/common/subsys.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 header describes the subsystems (each one gets a "--debug-<subsystem>"
* log verbosity setting), along with their default verbosities.
*/
DEFAULT_SUBSYS(0, 5)
SUBSYS(lockdep, 0, 1)
SUBSYS(context, 0, 1)
SUBSYS(crush, 1, 1)
SUBSYS(mds, 1, 5)
SUBSYS(mds_balancer, 1, 5)
SUBSYS(mds_locker, 1, 5)
SUBSYS(mds_log, 1, 5)
SUBSYS(mds_log_expire, 1, 5)
SUBSYS(mds_migrator, 1, 5)
SUBSYS(buffer, 0, 1)
SUBSYS(timer, 0, 1)
SUBSYS(filer, 0, 1)
SUBSYS(striper, 0, 1)
SUBSYS(objecter, 0, 1)
SUBSYS(rados, 0, 5)
SUBSYS(rbd, 0, 5)
SUBSYS(rbd_mirror, 0, 5)
SUBSYS(rbd_replay, 0, 5)
SUBSYS(rbd_pwl, 0, 5)
SUBSYS(journaler, 0, 5)
SUBSYS(objectcacher, 0, 5)
SUBSYS(immutable_obj_cache, 0, 5)
SUBSYS(client, 0, 5)
SUBSYS(osd, 1, 5)
SUBSYS(optracker, 0, 5)
SUBSYS(objclass, 0, 5)
SUBSYS(filestore, 1, 3)
SUBSYS(journal, 1, 3)
SUBSYS(ms, 0, 0)
SUBSYS(mon, 1, 5)
SUBSYS(monc, 0, 10)
SUBSYS(paxos, 1, 5)
SUBSYS(tp, 0, 5)
SUBSYS(auth, 1, 5)
SUBSYS(crypto, 1, 5)
SUBSYS(finisher, 1, 1)
SUBSYS(reserver, 1, 1)
SUBSYS(heartbeatmap, 1, 5)
SUBSYS(perfcounter, 1, 5)
SUBSYS(rgw, 1, 5) // log level for the Rados gateway
SUBSYS(rgw_sync, 1, 5)
SUBSYS(rgw_datacache, 1, 5)
SUBSYS(rgw_access, 1, 5)
SUBSYS(rgw_dbstore, 1, 5)
SUBSYS(rgw_flight, 1, 5)
SUBSYS(javaclient, 1, 5)
SUBSYS(asok, 1, 5)
SUBSYS(throttle, 1, 1)
SUBSYS(refs, 0, 0)
SUBSYS(compressor, 1, 5)
SUBSYS(bluestore, 1, 5)
SUBSYS(bluefs, 1, 5)
SUBSYS(bdev, 1, 3)
SUBSYS(kstore, 1, 5)
SUBSYS(rocksdb, 4, 5)
SUBSYS(fuse, 1, 5)
SUBSYS(mgr, 2, 5)
SUBSYS(mgrc, 1, 5)
SUBSYS(dpdk, 1, 5)
SUBSYS(eventtrace, 1, 5)
SUBSYS(prioritycache, 1, 5)
SUBSYS(test, 0, 5)
SUBSYS(cephfs_mirror, 0, 5)
SUBSYS(cephsqlite, 0, 5)
SUBSYS(seastore, 0, 5) // logs above seastore tm
SUBSYS(seastore_onode, 0, 5)
SUBSYS(seastore_odata, 0, 5)
SUBSYS(seastore_omap, 0, 5)
SUBSYS(seastore_tm, 0, 5) // logs below seastore tm
SUBSYS(seastore_t, 0, 5)
SUBSYS(seastore_cleaner, 0, 5)
SUBSYS(seastore_epm, 0, 5)
SUBSYS(seastore_lba, 0, 5)
SUBSYS(seastore_fixedkv_tree, 0, 5)
SUBSYS(seastore_cache, 0, 5)
SUBSYS(seastore_journal, 0, 5)
SUBSYS(seastore_device, 0, 5)
SUBSYS(seastore_backref, 0, 5)
SUBSYS(alienstore, 0, 5)
SUBSYS(mclock, 1, 5)
SUBSYS(cyanstore, 0, 5)
SUBSYS(ceph_exporter, 1, 5)
SUBSYS(memstore, 1, 5)
// *********************************************************************
// Developers should update /doc/rados/troubleshooting/log-and-debug.rst
// when adding or removing a subsystem accordingly.
// *********************************************************************
| 2,947 | 25.8 | 78 | h |
null | ceph-main/src/common/subsys_types.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2018 Red Hat 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_SUBSYS_TYPES_H
#define CEPH_SUBSYS_TYPES_H
#include <algorithm>
#include <array>
#include <cstdint>
enum ceph_subsys_id_t {
ceph_subsys_, // default
#define SUBSYS(name, log, gather) \
ceph_subsys_##name,
#define DEFAULT_SUBSYS(log, gather)
#include "common/subsys.h"
#undef SUBSYS
#undef DEFAULT_SUBSYS
ceph_subsys_max
};
constexpr static std::size_t ceph_subsys_get_num() {
return static_cast<std::size_t>(ceph_subsys_max);
}
struct ceph_subsys_item_t {
const char* name;
uint8_t log_level;
uint8_t gather_level;
};
constexpr static std::array<ceph_subsys_item_t, ceph_subsys_get_num()>
ceph_subsys_get_as_array() {
#define SUBSYS(name, log, gather) \
ceph_subsys_item_t{ #name, log, gather },
#define DEFAULT_SUBSYS(log, gather) \
ceph_subsys_item_t{ "none", log, gather },
return {
#include "common/subsys.h"
};
#undef SUBSYS
#undef DEFAULT_SUBSYS
}
constexpr static std::uint8_t
ceph_subsys_get_max_default_level(const std::size_t subidx) {
const auto item = ceph_subsys_get_as_array()[subidx];
return std::max(item.log_level, item.gather_level);
}
// Compile time-capable version of std::strlen. Resorting to own
// implementation only because C++17 doesn't mandate constexpr
// on the standard one.
constexpr static std::size_t strlen_ct(const char* const s) {
std::size_t l = 0;
while (s[l] != '\0') {
++l;
}
return l;
}
constexpr static std::size_t ceph_subsys_max_name_length() {
return std::max({
#define SUBSYS(name, log, gather) \
strlen_ct(#name),
#define DEFAULT_SUBSYS(log, gather) \
strlen_ct("none"),
#include "common/subsys.h"
#undef SUBSYS
#undef DEFAULT_SUBSYS
});
}
#endif // CEPH_SUBSYS_TYPES_H
| 2,094 | 22.806818 | 70 | h |
null | ceph-main/src/common/sync_filesystem.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) 2011 New Dream Network
*
* 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_SYNC_FILESYSTEM_H
#define CEPH_SYNC_FILESYSTEM_H
#include <unistd.h>
#if defined(__linux__)
#include <sys/ioctl.h>
#include <syscall.h>
#include "os/fs/btrfs_ioctl.h"
#endif
inline int sync_filesystem(int fd)
{
/* On Linux, newer versions of glibc have a function called syncfs that
* performs a sync on only one filesystem. If we don't have this call, we
* have to fall back on sync(), which synchronizes every filesystem on the
* computer. */
#ifdef HAVE_SYS_SYNCFS
if (syncfs(fd) == 0)
return 0;
#elif defined(SYS_syncfs)
if (syscall(SYS_syncfs, fd) == 0)
return 0;
#elif defined(__NR_syncfs)
if (syscall(__NR_syncfs, fd) == 0)
return 0;
#endif
#if defined(HAVE_SYS_SYNCFS) || defined(SYS_syncfs) || defined(__NR_syncfs)
else if (errno == ENOSYS) {
sync();
return 0;
} else {
return -errno;
}
#else
sync();
return 0;
#endif
}
#endif
| 1,314 | 22.070175 | 76 | h |
null | ceph-main/src/common/tracer.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "common/ceph_context.h"
#include "global/global_context.h"
#include "tracer.h"
#ifdef HAVE_JAEGER
#include "opentelemetry/sdk/trace/batch_span_processor.h"
#include "opentelemetry/sdk/trace/tracer_provider.h"
#include "opentelemetry/exporters/jaeger/jaeger_exporter.h"
namespace tracing {
const opentelemetry::nostd::shared_ptr<opentelemetry::trace::Tracer> Tracer::noop_tracer = opentelemetry::trace::Provider::GetTracerProvider()->GetTracer("no-op", OPENTELEMETRY_SDK_VERSION);
const jspan Tracer::noop_span = noop_tracer->StartSpan("noop");
using bufferlist = ceph::buffer::list;
Tracer::Tracer(opentelemetry::nostd::string_view service_name) {
init(service_name);
}
void Tracer::init(opentelemetry::nostd::string_view service_name) {
if (!tracer) {
opentelemetry::exporter::jaeger::JaegerExporterOptions exporter_options;
if (g_ceph_context) {
exporter_options.server_port = g_ceph_context->_conf.get_val<int64_t>("jaeger_agent_port");
}
const opentelemetry::sdk::trace::BatchSpanProcessorOptions processor_options;
const auto jaeger_resource = opentelemetry::sdk::resource::Resource::Create(std::move(opentelemetry::sdk::resource::ResourceAttributes{{"service.name", service_name}}));
auto jaeger_exporter = std::unique_ptr<opentelemetry::sdk::trace::SpanExporter>(new opentelemetry::exporter::jaeger::JaegerExporter(exporter_options));
auto processor = std::unique_ptr<opentelemetry::sdk::trace::SpanProcessor>(new opentelemetry::sdk::trace::BatchSpanProcessor(std::move(jaeger_exporter), processor_options));
const auto provider = opentelemetry::nostd::shared_ptr<opentelemetry::trace::TracerProvider>(new opentelemetry::sdk::trace::TracerProvider(std::move(processor), jaeger_resource));
opentelemetry::trace::Provider::SetTracerProvider(provider);
tracer = provider->GetTracer(service_name, OPENTELEMETRY_SDK_VERSION);
}
}
jspan Tracer::start_trace(opentelemetry::nostd::string_view trace_name) {
if (is_enabled()) {
return tracer->StartSpan(trace_name);
}
return noop_span;
}
jspan Tracer::start_trace(opentelemetry::nostd::string_view trace_name, bool trace_is_enabled) {
if (trace_is_enabled) {
return tracer->StartSpan(trace_name);
}
return noop_tracer->StartSpan(trace_name);
}
jspan Tracer::add_span(opentelemetry::nostd::string_view span_name, const jspan& parent_span) {
if (is_enabled() && parent_span->IsRecording()) {
opentelemetry::trace::StartSpanOptions span_opts;
span_opts.parent = parent_span->GetContext();
return tracer->StartSpan(span_name, span_opts);
}
return noop_span;
}
jspan Tracer::add_span(opentelemetry::nostd::string_view span_name, const jspan_context& parent_ctx) {
if (is_enabled() && parent_ctx.IsValid()) {
opentelemetry::trace::StartSpanOptions span_opts;
span_opts.parent = parent_ctx;
return tracer->StartSpan(span_name, span_opts);
}
return noop_span;
}
bool Tracer::is_enabled() const {
return g_ceph_context->_conf->jaeger_tracing_enable;
}
void encode(const jspan_context& span_ctx, bufferlist& bl, uint64_t f) {
ENCODE_START(1, 1, bl);
using namespace opentelemetry;
using namespace trace;
auto is_valid = span_ctx.IsValid();
encode(is_valid, bl);
if (is_valid) {
encode_nohead(std::string_view(reinterpret_cast<const char*>(span_ctx.trace_id().Id().data()), TraceId::kSize), bl);
encode_nohead(std::string_view(reinterpret_cast<const char*>(span_ctx.span_id().Id().data()), SpanId::kSize), bl);
encode(span_ctx.trace_flags().flags(), bl);
}
ENCODE_FINISH(bl);
}
void decode(jspan_context& span_ctx, bufferlist::const_iterator& bl) {
using namespace opentelemetry;
using namespace trace;
DECODE_START(1, bl);
bool is_valid;
decode(is_valid, bl);
if (is_valid) {
std::array<uint8_t, TraceId::kSize> trace_id;
std::array<uint8_t, SpanId::kSize> span_id;
uint8_t flags;
decode(trace_id, bl);
decode(span_id, bl);
decode(flags, bl);
span_ctx = SpanContext(
TraceId(nostd::span<uint8_t, TraceId::kSize>(trace_id)),
SpanId(nostd::span<uint8_t, SpanId::kSize>(span_id)),
TraceFlags(flags),
true);
}
DECODE_FINISH(bl);
}
} // namespace tracing
#endif // HAVE_JAEGER
| 4,338 | 37.061404 | 190 | cc |
null | ceph-main/src/common/tracer.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include "acconfig.h"
#include "include/buffer.h"
#ifdef HAVE_JAEGER
#include "opentelemetry/trace/provider.h"
using jspan = opentelemetry::nostd::shared_ptr<opentelemetry::trace::Span>;
using jspan_context = opentelemetry::trace::SpanContext;
using jspan_attribute = opentelemetry::common::AttributeValue;
namespace tracing {
class Tracer {
private:
const static opentelemetry::nostd::shared_ptr<opentelemetry::trace::Tracer> noop_tracer;
const static jspan noop_span;
opentelemetry::nostd::shared_ptr<opentelemetry::trace::Tracer> tracer;
public:
Tracer() = default;
Tracer(opentelemetry::nostd::string_view service_name);
void init(opentelemetry::nostd::string_view service_name);
bool is_enabled() const;
// creates and returns a new span with `trace_name`
// this span represents a trace, since it has no parent.
jspan start_trace(opentelemetry::nostd::string_view trace_name);
// creates and returns a new span with `trace_name`
// if false is given to `trace_is_enabled` param, noop span will be returned
jspan start_trace(opentelemetry::nostd::string_view trace_name, bool trace_is_enabled);
// creates and returns a new span with `span_name` which parent span is `parent_span'
jspan add_span(opentelemetry::nostd::string_view span_name, const jspan& parent_span);
// creates and return a new span with `span_name`
// the span is added to the trace which it's context is `parent_ctx`.
// parent_ctx contains the required information of the trace.
jspan add_span(opentelemetry::nostd::string_view span_name, const jspan_context& parent_ctx);
};
void encode(const jspan_context& span, ceph::buffer::list& bl, uint64_t f = 0);
void decode(jspan_context& span_ctx, ceph::buffer::list::const_iterator& bl);
} // namespace tracing
#else // !HAVE_JAEGER
#include <string_view>
class Value {
public:
template <typename T> Value(T val) {}
};
using jspan_attribute = Value;
struct jspan_context {
jspan_context() {}
jspan_context(bool sampled_flag, bool is_remote) {}
};
struct span_stub {
jspan_context _ctx;
template <typename T>
void SetAttribute(std::string_view key, const T& value) const noexcept {}
void AddEvent(std::string_view) {}
void AddEvent(std::string_view, std::initializer_list<std::pair<std::string_view, jspan_attribute>> fields) {}
template <typename T> void AddEvent(std::string_view name, const T& fields = {}) {}
const jspan_context& GetContext() { return _ctx; }
void UpdateName(std::string_view) {}
bool IsRecording() { return false; }
};
class jspan {
span_stub span;
public:
span_stub& operator*() { return span; }
const span_stub& operator*() const { return span; }
span_stub* operator->() { return &span; }
const span_stub* operator->() const { return &span; }
operator bool() const { return false; }
};
namespace tracing {
struct Tracer {
bool is_enabled() const { return false; }
jspan start_trace(std::string_view, bool enabled = true) { return {}; }
jspan add_span(std::string_view, const jspan&) { return {}; }
jspan add_span(std::string_view span_name, const jspan_context& parent_ctx) { return {}; }
void init(std::string_view service_name) {}
};
inline void encode(const jspan_context& span, bufferlist& bl, uint64_t f=0) {}
inline void decode(jspan_context& span_ctx, ceph::buffer::list::const_iterator& bl) {}
}
#endif // !HAVE_JAEGER
| 3,503 | 31.444444 | 112 | h |
null | ceph-main/src/common/tracked_int_ptr.hpp | // -*- 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_TRACKEDINTPTR_H
#define CEPH_TRACKEDINTPTR_H
template <class T>
class TrackedIntPtr {
T *ptr;
uint64_t id;
public:
TrackedIntPtr() : ptr(NULL), id(0) {}
TrackedIntPtr(T *ptr) : ptr(ptr), id(ptr ? get_with_id(ptr) : 0) {}
~TrackedIntPtr() {
if (ptr)
put_with_id(ptr, id);
else
ceph_assert(id == 0);
}
void swap(TrackedIntPtr &other) {
T *optr = other.ptr;
uint64_t oid = other.id;
other.ptr = ptr;
other.id = id;
ptr = optr;
id = oid;
}
TrackedIntPtr(const TrackedIntPtr &rhs) :
ptr(rhs.ptr), id(ptr ? get_with_id(ptr) : 0) {}
TrackedIntPtr& operator=(const TrackedIntPtr &rhs) {
TrackedIntPtr o(rhs.ptr);
swap(o);
return *this;
}
T &operator*() const {
return *ptr;
}
T *operator->() const {
return ptr;
}
T *get() const { return ptr; }
operator bool() const {
return ptr != NULL;
}
bool operator<(const TrackedIntPtr &lhs) const {
return ptr < lhs.ptr;
}
bool operator==(const TrackedIntPtr &lhs) const {
return ptr == lhs.ptr;
}
void reset() {
if (ptr)
put_with_id(ptr, id);
ptr = nullptr;
id = 0;
}
};
#endif
| 1,591 | 20.226667 | 70 | hpp |
null | ceph-main/src/common/types.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 Cloudwatt <[email protected]>
*
* Author: Loic Dachary <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
*/
#ifndef __CEPH_TYPES_H
#define __CEPH_TYPES_H
#include <include/types.h>
#ifndef UINT8_MAX
#define UINT8_MAX (255)
#endif
const shard_id_t shard_id_t::NO_SHARD(-1);
std::ostream& operator<<(std::ostream& lhs, const shard_id_t& rhs)
{
return lhs << (unsigned)(uint8_t)rhs.id;
}
#endif
| 825 | 24.030303 | 71 | cc |
null | ceph-main/src/common/url_escape.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "url_escape.h"
#include <stdexcept>
#include <sstream>
std::string url_escape(const std::string& s)
{
std::string out;
for (auto c : s) {
if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~' ||
c == '/') {
out.push_back(c);
} else {
char t[4];
snprintf(t, sizeof(t), "%%%02x", (int)(unsigned char)c);
out.append(t);
}
}
return out;
}
std::string url_unescape(const std::string& s)
{
std::string out;
const char *end = s.c_str() + s.size();
for (const char *c = s.c_str(); c < end; ++c) {
switch (*c) {
case '%':
{
unsigned char v = 0;
for (unsigned i=0; i<2; ++i) {
++c;
if (c >= end) {
std::ostringstream ss;
ss << "invalid escaped string at pos " << (c - s.c_str()) << " of '"
<< s << "'";
throw std::runtime_error(ss.str());
}
v <<= 4;
if (*c >= '0' && *c <= '9') {
v += *c - '0';
} else if (*c >= 'a' && *c <= 'f') {
v += *c - 'a' + 10;
} else if (*c >= 'A' && *c <= 'F') {
v += *c - 'A' + 10;
} else {
std::ostringstream ss;
ss << "invalid escaped string at pos " << (c - s.c_str()) << " of '"
<< s << "'";
throw std::runtime_error(ss.str());
}
}
out.push_back(v);
}
break;
default:
out.push_back(*c);
}
}
return out;
}
| 1,438 | 21.138462 | 74 | cc |
null | ceph-main/src/common/url_escape.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <string>
extern std::string url_escape(const std::string& s);
extern std::string url_unescape(const std::string& s);
| 240 | 23.1 | 70 | h |
null | ceph-main/src/common/utf8.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) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_COMMON_UTF8_H
#define CEPH_COMMON_UTF8_H
#define MAX_UTF8_SZ 6
#define INVALID_UTF8_CHAR 0xfffffffful
#ifdef __cplusplus
extern "C" {
#endif
/* Checks if a buffer is valid UTF-8.
* Returns 0 if it is, and one plus the offset of the first invalid byte
* if it is not.
*/
int check_utf8(const char *buf, int len);
/* Checks if a null-terminated string is valid UTF-8.
* Returns 0 if it is, and one plus the offset of the first invalid byte
* if it is not.
*/
int check_utf8_cstr(const char *buf);
/* Returns true if 'ch' is a control character.
* We do count newline as a control character, but not NULL.
*/
int is_control_character(int ch);
/* Checks if a buffer contains control characters.
*/
int check_for_control_characters(const char *buf, int len);
/* Checks if a null-terminated string contains control characters.
*/
int check_for_control_characters_cstr(const char *buf);
/* Encode a 31-bit UTF8 code point to 'buf'.
* Assumes buf is of size MAX_UTF8_SZ
* Returns -1 on failure; number of bytes in the encoded value otherwise.
*/
int encode_utf8(unsigned long u, unsigned char *buf);
/*
* Decode a UTF8 character from an array of bytes. Return character code.
* Upon error, return INVALID_UTF8_CHAR.
*/
unsigned long decode_utf8(unsigned char *buf, int nbytes);
#ifdef __cplusplus
}
#endif
#endif
| 1,754 | 25.19403 | 73 | h |
null | ceph-main/src/common/util.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) 2012 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 _WIN32
#include <sys/utsname.h>
#endif
#include <fstream>
#include <boost/algorithm/string.hpp>
#include "include/compat.h"
#include "include/util.h"
#include "common/debug.h"
#include "common/errno.h"
#include "common/version.h"
#ifdef HAVE_SYS_VFS_H
#include <sys/vfs.h>
#endif
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <sys/param.h>
#include <sys/mount.h>
#if defined(__APPLE__)
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#endif
#include <string>
#include <stdio.h>
using std::list;
using std::map;
using std::string;
using ceph::bufferlist;
using ceph::Formatter;
#ifndef _WIN32
int get_fs_stats(ceph_data_stats_t &stats, const char *path)
{
if (!path)
return -EINVAL;
struct statfs stbuf;
int err = ::statfs(path, &stbuf);
if (err < 0) {
return -errno;
}
stats.byte_total = stbuf.f_blocks * stbuf.f_bsize;
stats.byte_used = (stbuf.f_blocks - stbuf.f_bfree) * stbuf.f_bsize;
stats.byte_avail = stbuf.f_bavail * stbuf.f_bsize;
stats.avail_percent = (((float)stats.byte_avail/stats.byte_total)*100);
return 0;
}
#else
int get_fs_stats(ceph_data_stats_t &stats, const char *path)
{
ULARGE_INTEGER avail_bytes, total_bytes, total_free_bytes;
if (!GetDiskFreeSpaceExA(path, &avail_bytes,
&total_bytes, &total_free_bytes)) {
return -EINVAL;
}
stats.byte_total = total_bytes.QuadPart;
stats.byte_used = total_bytes.QuadPart - total_free_bytes.QuadPart;
// may not be equal to total_free_bytes due to quotas
stats.byte_avail = avail_bytes.QuadPart;
stats.avail_percent = ((float)stats.byte_avail / stats.byte_total) * 100;
return 0;
}
#endif
static char* value_sanitize(char *value)
{
while (isspace(*value) || *value == '"')
value++;
char* end = value + strlen(value) - 1;
while (end > value && (isspace(*end) || *end == '"'))
end--;
*(end + 1) = '\0';
return value;
}
static bool value_set(char *buf, const char *prefix,
map<string, string> *pm, const char *key)
{
if (strncmp(buf, prefix, strlen(prefix))) {
return false;
}
(*pm)[key] = value_sanitize(buf + strlen(prefix));
return true;
}
static void file_values_parse(const map<string, string>& kvm, FILE *fp, map<string, string> *m, CephContext *cct) {
char buf[512];
while (fgets(buf, sizeof(buf) - 1, fp) != NULL) {
for (auto& kv : kvm) {
if (value_set(buf, kv.second.c_str(), m, kv.first.c_str()))
continue;
}
}
}
static bool os_release_parse(map<string, string> *m, CephContext *cct)
{
#if defined(__linux__)
static const map<string, string> kvm = {
{ "distro", "ID=" },
{ "distro_description", "PRETTY_NAME=" },
{ "distro_version", "VERSION_ID=" }
};
FILE *fp = fopen("/etc/os-release", "r");
if (!fp) {
int ret = -errno;
lderr(cct) << "os_release_parse - failed to open /etc/os-release: " << cpp_strerror(ret) << dendl;
return false;
}
file_values_parse(kvm, fp, m, cct);
fclose(fp);
#elif defined(__FreeBSD__)
struct utsname u;
int r = uname(&u);
if (!r) {
m->insert(std::make_pair("distro", u.sysname));
m->insert(std::make_pair("distro_description", u.version));
m->insert(std::make_pair("distro_version", u.release));
}
#endif
return true;
}
static void distro_detect(map<string, string> *m, CephContext *cct)
{
if (!os_release_parse(m, cct)) {
lderr(cct) << "distro_detect - /etc/os-release is required" << dendl;
}
for (const char* rk: {"distro", "distro_description"}) {
if (m->find(rk) == m->end())
lderr(cct) << "distro_detect - can't detect " << rk << dendl;
}
}
int get_cgroup_memory_limit(uint64_t *limit)
{
#if defined(__linux__)
// /sys/fs/cgroup/memory/memory.limit_in_bytes
// the magic value 9223372036854771712 or 0x7ffffffffffff000
// appears to mean no limit.
FILE *f = fopen(PROCPREFIX "/sys/fs/cgroup/memory/memory.limit_in_bytes", "r");
if (!f) {
return -errno;
}
char buf[100];
int ret = 0;
long long value;
char *line = fgets(buf, sizeof(buf), f);
if (!line) {
ret = -EINVAL;
goto out;
}
if (sscanf(line, "%lld", &value) != 1) {
ret = -EINVAL;
}
if (value == 0x7ffffffffffff000) {
*limit = 0; // no limit
} else {
*limit = value;
}
out:
fclose(f);
return ret;
#else
return 0;
#endif
}
#ifdef _WIN32
int get_windows_version(POSVERSIONINFOEXW ver) {
using get_version_func_t = DWORD (WINAPI *)(OSVERSIONINFOEXW*);
// We'll load the library directly to avoid depending on the NTDDK.
HMODULE ntdll_lib = LoadLibraryW(L"Ntdll.dll");
if (!ntdll_lib) {
return -EINVAL;
}
// The standard "GetVersion" returned values depend on the application
// manifest. We'll get the "real" version by using the Rtl* version.
auto get_version_func = (
get_version_func_t)GetProcAddress(ntdll_lib, "RtlGetVersion");
int ret = 0;
if (!get_version_func || get_version_func(ver)) {
// RtlGetVersion returns non-zero values in case of errors.
ret = -EINVAL;
}
FreeLibrary(ntdll_lib);
return ret;
}
#endif
void collect_sys_info(map<string, string> *m, CephContext *cct)
{
// version
(*m)["ceph_version"] = pretty_version_to_str();
(*m)["ceph_version_short"] = ceph_version_to_str();
(*m)["ceph_release"] = ceph_release_to_str();
#ifndef _WIN32
// kernel info
struct utsname u;
int r = uname(&u);
if (r >= 0) {
(*m)["os"] = u.sysname;
(*m)["kernel_version"] = u.release;
(*m)["kernel_description"] = u.version;
(*m)["hostname"] = u.nodename;
(*m)["arch"] = u.machine;
}
#else
OSVERSIONINFOEXW ver = {0};
ver.dwOSVersionInfoSize = sizeof(ver);
get_windows_version(&ver);
char version_str[64];
snprintf(version_str, 64, "%lu.%lu (%lu)",
ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber);
char hostname[64];
DWORD hostname_sz = sizeof(hostname);
GetComputerNameA(hostname, &hostname_sz);
SYSTEM_INFO sys_info;
const char* arch_str;
GetNativeSystemInfo(&sys_info);
switch (sys_info.wProcessorArchitecture) {
case PROCESSOR_ARCHITECTURE_AMD64:
arch_str = "x86_64";
break;
case PROCESSOR_ARCHITECTURE_INTEL:
arch_str = "x86";
break;
case PROCESSOR_ARCHITECTURE_ARM:
arch_str = "arm";
break;
default:
arch_str = "unknown";
break;
}
(*m)["os"] = "Windows";
(*m)["kernel_version"] = version_str;
(*m)["kernel_description"] = version_str;
(*m)["hostname"] = hostname;
(*m)["arch"] = arch_str;
#endif
// but wait, am i in a container?
bool in_container = false;
if (const char *pod_name = getenv("POD_NAME")) {
(*m)["pod_name"] = pod_name;
in_container = true;
}
if (const char *container_name = getenv("CONTAINER_NAME")) {
(*m)["container_name"] = container_name;
in_container = true;
}
if (const char *container_image = getenv("CONTAINER_IMAGE")) {
(*m)["container_image"] = container_image;
in_container = true;
}
if (in_container) {
if (const char *node_name = getenv("NODE_NAME")) {
(*m)["container_hostname"] = (*m)["hostname"];
(*m)["hostname"] = node_name;
}
if (const char *ns = getenv("POD_NAMESPACE")) {
(*m)["pod_namespace"] = ns;
}
}
#ifdef __APPLE__
// memory
{
uint64_t size;
size_t len = sizeof(size);
r = sysctlbyname("hw.memsize", &size, &len, NULL, 0);
if (r == 0) {
(*m)["mem_total_kb"] = std::to_string(size);
}
}
{
xsw_usage vmusage;
size_t len = sizeof(vmusage);
r = sysctlbyname("vm.swapusage", &vmusage, &len, NULL, 0);
if (r == 0) {
(*m)["mem_swap_kb"] = std::to_string(vmusage.xsu_total);
}
}
// processor
{
char buf[100];
size_t len = sizeof(buf);
r = sysctlbyname("machdep.cpu.brand_string", buf, &len, NULL, 0);
if (r == 0) {
buf[len - 1] = '\0';
(*m)["cpu"] = buf;
}
}
#elif !defined(_WIN32)
// memory
if (std::ifstream f{PROCPREFIX "/proc/meminfo"}; !f.fail()) {
for (std::string line; std::getline(f, line); ) {
std::vector<string> parts;
boost::split(parts, line, boost::is_any_of(":\t "), boost::token_compress_on);
if (parts.size() != 3) {
continue;
}
if (parts[0] == "MemTotal") {
(*m)["mem_total_kb"] = parts[1];
} else if (parts[0] == "SwapTotal") {
(*m)["mem_swap_kb"] = parts[1];
}
}
}
uint64_t cgroup_limit;
if (get_cgroup_memory_limit(&cgroup_limit) == 0 &&
cgroup_limit > 0) {
(*m)["mem_cgroup_limit"] = std::to_string(cgroup_limit);
}
// processor
if (std::ifstream f{PROCPREFIX "/proc/cpuinfo"}; !f.fail()) {
for (std::string line; std::getline(f, line); ) {
std::vector<string> parts;
boost::split(parts, line, boost::is_any_of(":"));
if (parts.size() != 2) {
continue;
}
boost::trim(parts[0]);
boost::trim(parts[1]);
if (parts[0] == "model name") {
(*m)["cpu"] = parts[1];
break;
}
}
}
#endif
// distro info
distro_detect(m, cct);
}
void dump_services(Formatter* f, const map<string, list<int> >& services, const char* type)
{
ceph_assert(f);
f->open_object_section(type);
for (auto host = services.begin();
host != services.end(); ++host) {
f->open_array_section(host->first.c_str());
const list<int>& hosted = host->second;
for (auto s = hosted.cbegin();
s != hosted.cend(); ++s) {
f->dump_int(type, *s);
}
f->close_section();
}
f->close_section();
}
void dump_services(Formatter* f, const map<string, list<string> >& services, const char* type)
{
ceph_assert(f);
f->open_object_section(type);
for (const auto& host : services) {
f->open_array_section(host.first.c_str());
const auto& hosted = host.second;
for (const auto& s : hosted) {
f->dump_string(type, s);
}
f->close_section();
}
f->close_section();
}
// If non-printable characters found then convert bufferlist to
// base64 encoded string indicating whether it did.
string cleanbin(bufferlist &bl, bool &base64, bool show)
{
bufferlist::iterator it;
for (it = bl.begin(); it != bl.end(); ++it) {
if (iscntrl(*it))
break;
}
if (it == bl.end()) {
base64 = false;
string result(bl.c_str(), bl.length());
return result;
}
bufferlist b64;
bl.encode_base64(b64);
string encoded(b64.c_str(), b64.length());
if (show)
encoded = "Base64:" + encoded;
base64 = true;
return encoded;
}
// If non-printable characters found then convert to "Base64:" followed by
// base64 encoding
string cleanbin(string &str)
{
bool base64;
bufferlist bl;
bl.append(str);
string result = cleanbin(bl, base64, true);
return result;
}
std::string bytes2str(uint64_t count) {
static char s[][2] = {"\0", "k", "M", "G", "T", "P", "E", "\0"};
int i = 0;
while (count >= 1024 && *s[i+1]) {
count >>= 10;
i++;
}
char str[128];
snprintf(str, sizeof str, "%" PRIu64 "%sB", count, s[i]);
return std::string(str);
}
| 11,412 | 23.75705 | 115 | cc |
null | ceph-main/src/common/valgrind.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_VALGRIND_H
#define CEPH_VALGRIND_H
#include "acconfig.h"
#if defined(HAVE_VALGRIND_HELGRIND_H) && !defined(NDEBUG)
#include <valgrind/helgrind.h>
#else
#define ANNOTATE_HAPPENS_AFTER(x) (void)0
#define ANNOTATE_HAPPENS_BEFORE_FORGET_ALL(x) (void)0
#define ANNOTATE_HAPPENS_BEFORE(x) (void)0
#define ANNOTATE_BENIGN_RACE_SIZED(address, size, description) (void)0
#endif
#endif // CEPH_VALGRIND_H
| 544 | 26.25 | 72 | h |
null | ceph-main/src/common/version.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) 2011 New Dream Network
*
* 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 "common/version.h"
#include <stdlib.h>
#include <sstream>
#include "ceph_ver.h"
#include "common/ceph_strings.h"
#define _STR(x) #x
#define STRINGIFY(x) _STR(x)
const char *ceph_version_to_str()
{
char* debug_version_for_testing = getenv("ceph_debug_version_for_testing");
if (debug_version_for_testing) {
return debug_version_for_testing;
} else {
return CEPH_GIT_NICE_VER;
}
}
const char *ceph_release_to_str(void)
{
return ceph_release_name(CEPH_RELEASE);
}
const char *git_version_to_str(void)
{
return STRINGIFY(CEPH_GIT_VER);
}
std::string const pretty_version_to_str(void)
{
std::ostringstream oss;
oss << "ceph version " << CEPH_GIT_NICE_VER
<< " (" << STRINGIFY(CEPH_GIT_VER) << ") "
<< ceph_release_name(CEPH_RELEASE)
<< " (" << CEPH_RELEASE_TYPE << ")";
return oss.str();
}
const char *ceph_release_type(void)
{
return CEPH_RELEASE_TYPE;
}
| 1,323 | 21.066667 | 77 | cc |
null | ceph-main/src/common/version.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) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_COMMON_VERSION_H
#define CEPH_COMMON_VERSION_H
#include <string>
// Return a string describing the Ceph version
const char *ceph_version_to_str();
// Return a string with the Ceph release
const char *ceph_release_to_str(void);
// Return a string describing the git version
const char *git_version_to_str(void);
// Return a formatted string describing the ceph and git versions
std::string const pretty_version_to_str(void);
// Release type ("dev", "rc", or "stable")
const char *ceph_release_type(void);
#endif
| 940 | 25.138889 | 70 | h |
null | ceph-main/src/common/weighted_shuffle.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <algorithm>
#include <iterator>
#include <random>
template <class RandomIt, class DistIt, class URBG>
void weighted_shuffle(RandomIt first, RandomIt last,
DistIt weight_first, DistIt weight_last,
URBG &&g)
{
if (first == last) {
return;
} else {
std::discrete_distribution d{weight_first, weight_last};
if (auto n = d(g); n > 0) {
std::iter_swap(first, std::next(first, n));
std::iter_swap(weight_first, std::next(weight_first, n));
}
weighted_shuffle(++first, last, ++weight_first, weight_last, std::move(g));
}
}
| 692 | 25.653846 | 79 | h |
null | ceph-main/src/common/zipkin_trace.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef COMMON_ZIPKIN_TRACE_H
#define COMMON_ZIPKIN_TRACE_H
#include "acconfig.h"
#include "include/encoding.h"
#ifdef WITH_BLKIN
#include <ztracer.hpp>
#else // !WITH_BLKIN
// add stubs for noop Trace and Endpoint
// match the "real" struct
struct blkin_trace_info {
int64_t trace_id;
int64_t span_id;
int64_t parent_span_id;
};
namespace ZTracer
{
static inline int ztrace_init() { return 0; }
class Endpoint {
public:
Endpoint(const char *name) {}
Endpoint(const char *ip, int port, const char *name) {}
void copy_ip(const std::string &newip) {}
void copy_name(const std::string &newname) {}
void copy_address_from(const Endpoint *endpoint) {}
void share_address_from(const Endpoint *endpoint) {}
void set_port(int p) {}
};
class Trace {
public:
Trace() {}
Trace(const char *name, const Endpoint *ep, const Trace *parent = NULL) {}
Trace(const char *name, const Endpoint *ep,
const blkin_trace_info *i, bool child=false) {}
bool valid() const { return false; }
operator bool() const { return false; }
int init(const char *name, const Endpoint *ep, const Trace *parent = NULL) {
return 0;
}
int init(const char *name, const Endpoint *ep,
const blkin_trace_info *i, bool child=false) {
return 0;
}
void copy_name(const std::string &newname) {}
const blkin_trace_info* get_info() const { return NULL; }
void set_info(const blkin_trace_info *i) {}
void keyval(const char *key, const char *val) const {}
void keyval(const char *key, int64_t val) const {}
void keyval(const char *key, const char *val, const Endpoint *ep) const {}
void keyval(const char *key, int64_t val, const Endpoint *ep) const {}
void event(const char *event) const {}
void event(const char *event, const Endpoint *ep) const {}
};
} // namespace ZTrace
#endif // !WITH_BLKIN
static inline void encode(const blkin_trace_info& b, ceph::buffer::list& bl)
{
using ceph::encode;
encode(b.trace_id, bl);
encode(b.span_id, bl);
encode(b.parent_span_id, bl);
}
static inline void decode(blkin_trace_info& b, ceph::buffer::list::const_iterator& p)
{
using ceph::decode;
decode(b.trace_id, p);
decode(b.span_id, p);
decode(b.parent_span_id, p);
}
#endif // COMMON_ZIPKIN_TRACE_H
| 2,365 | 24.170213 | 85 | h |
null | ceph-main/src/common/async/bind_handler.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2018 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_ASYNC_BIND_HANDLER_H
#define CEPH_ASYNC_BIND_HANDLER_H
#include <tuple>
#include <boost/asio.hpp>
namespace ceph::async {
/**
* A bound completion handler for use with boost::asio.
*
* A completion handler wrapper that allows a tuple of arguments to be forwarded
* to the original Handler. This is intended for use with boost::asio functions
* like defer(), dispatch() and post() which expect handlers which are callable
* with no arguments.
*
* The original Handler's associated allocator and executor are maintained.
*
* @see bind_handler
*/
template <typename Handler, typename Tuple>
struct CompletionHandler {
Handler handler;
Tuple args;
CompletionHandler(Handler&& handler, Tuple&& args)
: handler(std::move(handler)),
args(std::move(args))
{}
void operator()() & {
std::apply(handler, args);
}
void operator()() const & {
std::apply(handler, args);
}
void operator()() && {
std::apply(std::move(handler), std::move(args));
}
using allocator_type = boost::asio::associated_allocator_t<Handler>;
allocator_type get_allocator() const noexcept {
return boost::asio::get_associated_allocator(handler);
}
};
} // namespace ceph::async
namespace boost::asio {
// specialize boost::asio::associated_executor<> for CompletionHandler
template <typename Handler, typename Tuple, typename Executor>
struct associated_executor<ceph::async::CompletionHandler<Handler, Tuple>, Executor> {
using type = boost::asio::associated_executor_t<Handler, Executor>;
static type get(const ceph::async::CompletionHandler<Handler, Tuple>& handler,
const Executor& ex = Executor()) noexcept {
return boost::asio::get_associated_executor(handler.handler, ex);
}
};
} // namespace boost::asio
namespace ceph::async {
/**
* Returns a wrapped completion handler with bound arguments.
*
* Binds the given arguments to a handler, and returns a CompletionHandler that
* is callable with no arguments. This is similar to std::bind(), except that
* all arguments must be provided. Move-only argument types are supported as
* long as the CompletionHandler's 'operator() &&' overload is used, i.e.
* std::move(handler)().
*
* Example use:
*
* // bind the arguments (5, "hello") to a callback lambda:
* auto callback = [] (int a, std::string b) {};
* auto handler = bind_handler(callback, 5, "hello");
*
* // execute the bound handler on an io_context:
* boost::asio::io_context context;
* boost::asio::post(context, std::move(handler));
* context.run();
*
* @see CompletionHandler
*/
template <typename Handler, typename ...Args>
auto bind_handler(Handler&& h, Args&& ...args)
{
return CompletionHandler{std::forward<Handler>(h),
std::make_tuple(std::forward<Args>(args)...)};
}
} // namespace ceph::async
#endif // CEPH_ASYNC_BIND_HANDLER_H
| 3,292 | 28.401786 | 86 | h |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.